Compare commits

...
Author SHA1 Message Date
renovate-bot c69122188f Merge pull request 'chore(deps): update dependency dev.detekt to v2.0.0-alpha.7' (#160) from renovate/android-gradle into dev
release / web (push) Successful in 1m25s
release / govulncheck (push) Successful in 18s
release / integration (push) Successful in 2m41s
release / go (push) Successful in 1m52s
release / android (push) Failing after 1m4s
release / Build signed APK (push) Successful in 4m33s
release / Build + push container image (push) Skipped
2026-12-04 23:02:17 -05:00
Renovate Bot 419c67bf8a chore(deps): update dependency dev.detekt to v2.0.0-alpha.7
renovate/stability-days Updates have met minimum release age requirement
2026-12-05 04:02:15 +00:00
bvandeusenandClaude Opus 5.5 2551d1e11f deps: Go 1.27 for CI, the builder and govulncheck (ci-go:1.27)
release / go (push) Successful in 1m50s
release / integration (push) Successful in 2m25s
release / web (push) Successful in 1m9s
release / govulncheck (push) Successful in 17s
release / android (push) Successful in 2m19s
release / Build signed APK (push) Successful in 2m14s
release / Build + push container image (push) Successful in 20s
ci-go:1.27 (CI-runner PR #19) carries Go 1.27 and golangci-lint v2.15.0.
Five places now name the same Go minor:
- go.mod;
- the ci-go lanes;
- the Dockerfile's golang:1.27-trixie builder;
- the govulncheck lane;
- the requirements sheet.

The sheet's toolchain note no longer points at the x/crypto floor. It now
says to move all of these together.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 16:11:21 -05:00
bvandeusenandClaude Opus 5.5 f32fe95179 android: certificate failures found behind OkHttp 5's fast fallback; release-key check reads apksigner 37 (#8533)
release / go (push) Successful in 1m46s
release / integration (push) Successful in 2m33s
release / web (push) Successful in 1m11s
release / govulncheck (push) Successful in 18s
release / android (push) Successful in 4m52s
release / Build signed APK (push) Successful in 5m4s
release / Build + push container image (push) Successful in 17s
Run 11511 failed in two places.

ServerProbe: OkHttp 5 tries a host's addresses in parallel. When all of
them fail it throws one failure and attaches the others as suppressed
exceptions. For localhost, the refused ::1 connection was thrown, and the
certificate error from 127.0.0.1 was only attached, so the probe said
"Couldn't reach" instead of naming the certificate. A real server with
both IPv4 and IPv6 addresses would hit the same. isCertificateFailure now
searches suppressed exceptions as well as causes, up to 16 in all.

Release-key check: apksigner from build-tools 37 labels signers by
signature scheme ("V3.0 Signer: certificate SHA-256 digest: ...") instead
of "Signer #1 certificate ...". The step's grep matched nothing, and
pipefail ended it with no message. The step now collects every
certificate SHA-256 digest whatever the label, and still requires exactly
one distinct digest, equal to the release key's. I checked the parsing on
both label formats, on two keys and on no output: it passes our key in
either format and fails the other two cases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 15:28:20 -05:00
bvandeusenandClaude Opus 5.5 3a7bd2b04d android: the Now Playing scrubber uses the SliderState overload (material3 1.5) (#8533)
release / go (push) Successful in 2m5s
release / Build signed APK (push) Failing after 3m26s
release / Build + push container image (push) Skipped
release / web (push) Successful in 1m20s
release / govulncheck (push) Successful in 17s
release / integration (push) Successful in 2m37s
release / android (push) Failing after 2m59s
material3 1.5 takes a custom thumb and track only on the SliderState
overloads of Slider, so the value-based call no longer compiled (run
11508). The scrubber now passes a remembered SliderState that mirrors the
playback fraction. Dragging still seeks through onValueChange, and the
thumb and track are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 15:18:01 -05:00
bvandeusenandClaude Opus 5.5 dc9edb4fc4 android: compileSdk 37.1 for Compose 1.13; ktlint wraps at detekt's 120 (#8533)
release / web (push) Successful in 1m29s
release / govulncheck (push) Successful in 19s
release / Build signed APK (push) Failing after 2m26s
release / Build + push container image (push) Skipped
release / go (push) Successful in 1m47s
release / integration (push) Successful in 2m41s
release / android (push) Failing after 2m19s
Run 11504 failed in two places:
- checkReleaseAarMetadata: Compose 1.13 requires compiling against
  Android 37.1, and compileSdk 37 resolves to 37.0. It is now
  release(37) { minorApiLevel = 1 }.
- detekt:
  - 25 MaxLineLength findings, because ktlint_official wraps at 140 and
    detekt allows 120. .editorconfig now sets max_line_length = 120, so
    the two checks agree, and the sources are reformatted to it.
  - The reformat's extra line breaks pushed MinstrelForwardingPlayer past
    LargeClass. Its file-level suppression already explains that the
    class mirrors the Media3 Player surface, and it now covers size too.
  - The extra line breaks also pushed MiniRow past LongMethod. Its cover
    and title moved into MiniTrackInfo.

ktlint 1.5 and detekt 2.0.0-alpha.6 both pass locally on these sources.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 15:00:38 -05:00
bvandeusenandClaude Opus 5.5 924b4537c3 android: compileSdk 37 on ci-android:37; current AndroidX, Compose, Coil, OkHttp 5; ktlint-gradle 14 (#8533)
release / web (push) Successful in 1m16s
release / go (push) Successful in 1m50s
release / govulncheck (push) Successful in 17s
release / android (push) Failing after 1m5s
release / integration (push) Successful in 2m36s
release / Build signed APK (push) Failing after 1m13s
release / Build + push container image (push) Skipped
ci-android:37 (CI-runner PR #17) carries Android SDK 37. That lets the app
compile against 37 and take the libraries that require it:
- compose-bom 2026.11.01
- androidx.hilt 1.4.0
- navigation 2.10.2
- lifecycle 2.11.1
- core-ktx 1.19.1
- mediarouter 1.9.0
- coil 3.6.3
- OkHttp 5.5.1

targetSdk stays 36, so runtime behaviour on phones is unchanged.

ktlint-gradle 14.2 runs ktlint 1.5, which turns on rules that 1.0 left
experimental, so the sources are reformatted to them. Ignoring whitespace
that is about 4.7k lines across 312 files, and none of it changes
behaviour.

android/.editorconfig keeps ktlint's default style but exempts
@Composable functions from the lowercase function-naming rule, which
Compose's own convention breaks.

A few spots ktlint 1.5 cannot fix by itself were rewritten:
- EOL comments moved above the KDoc they followed;
- DeliveryPlan's file-level doc became plain comments;
- three /* name = */ argument labels on Java calls became trailing
  comments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 14:53:14 -05:00
bvandeusenandClaude Opus 5.5 feef626ba5 web: Vitest after svelte-query 6; spaces that Svelte trimmed out of four labels (#8532)
release / go (push) Successful in 1m55s
release / govulncheck (push) Successful in 17s
release / android (push) Successful in 2m6s
release / Build signed APK (push) Successful in 2m0s
release / web (push) Successful in 1m25s
release / integration (push) Successful in 2m40s
release / Build + push container image (push) Successful in 37s
Run 11484 failed 18 Vitest tests in 7 files:
- Two tests still mocked a query as a hand-written store ({ subscribe }).
  They now mock a plain query object.
- TrackMenu now creates its hidden-tracks query when it mounts, not lazily
  as the old $derived store did, so page tests that render track rows mock
  #lib/api/quarantine like the component tests already did.
- The tuning trends headers read "Plays(window)". Svelte drops the
  leading space inside <span> (window)</span>, and jsdom 31 no longer
  hides that. The same gluing showed in:
  - "Title· File missing" on track rows;
  - the track position on Suspect sources;
  - the screen-reader "(new)" on notifications.
  Each space now sits outside the span, or is an expression Svelte keeps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 14:09:20 -05:00
bvandeusenandClaude Opus 5.5 72e8702e53 fix CI: errcheck in the migration test, Svelte 5 icon and props types, hold Android's SDK-37 libraries (#8532, #8533)
release / go (push) Successful in 1m48s
release / govulncheck (push) Successful in 16s
release / Build + push container image (push) Skipped
release / web (push) Failing after 1m23s
release / integration (push) Successful in 2m36s
release / android (push) Successful in 4m36s
release / Build signed APK (push) Successful in 4m59s
Run 11469 failed in three places:
- golangci-lint (errcheck) flagged three unchecked Close calls in
  migrations_roundtrip_test.go. Their errors are now discarded
  explicitly.
- svelte-check found two kinds of error:
  - IconProp was typed for class-based lucide-svelte components.
    @lucide/svelte's are Svelte 5 components, so it is now LucideIcon.
  - Svelte 5.60 no longer accepts $props<T>(). Eight components now
    type the destructuring instead.
- Android: compose-bom 2026.11, androidx.hilt 1.4, navigation 2.10,
  lifecycle 2.11, core-ktx 1.19, mediarouter 1.9, coil 3.6 and
  OkHttp 5 all require compileSdk 37. ci-android:36 carries SDK 36, so
  they are held at their previous versions until an SDK 37 image
  exists. OkHttp takes 4.12.1.
- ktlint-gradle 14's newer ktlint rules flag 751 lines in the test
  sources, so it stays on 12 until those sources are reformatted.

The rest of the Android update stays: Kotlin 2.4, AGP 9.5, Gradle 9.9,
Retrofit 3, JUnit 6 and the others.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 14:00:23 -05:00
bvandeusenandClaude Opus 5.5 be384c8efe web: svelte-query 6 — queries are reactive objects read directly, not stores (#8532)
release / go (push) Failing after 1m10s
release / web (push) Failing after 10s
release / android (push) Failing after 1m2s
release / govulncheck (push) Successful in 17s
release / integration (push) Successful in 2m31s
release / Build signed APK (push) Failing after 1m43s
release / Build + push container image (push) Skipped
@tanstack/svelte-query 6 is built on runes:
- createQuery and createInfiniteQuery take their options as a function
  and return a reactive object that components read as query.data.
- createMutation takes its options the same way.

What this commit changes:
- Every query creator in src/lib/api now takes its arguments as getters
  and reads them inside the options, so a query follows the values it
  depends on. Before, each component rebuilt it in a $derived.
- Constant arguments are passed as getters too, so the rule has no
  exceptions.
- Components call a creator once at init: const query =
  createArtistQuery(() => id). The $derived(create…) and $store pairs
  are gone.
- A query that loads only on demand (a chosen genre or year, the
  Handled view) has an enabled getter. The page keeps its `cond ? q :
  null` alias, because a switched-off query reports isPending and the
  page expects null when nothing is chosen.
- Tests: the query mocks return plain objects. liveQuery
  (test-utils/liveQuery.svelte.ts) gives a test a result it can change
  mid-test. Argument checks call the getter the page passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 10:55:05 -05:00
bvandeusenandClaude Opus 5.5 936c0cd3ec android deps: OkHttp 5, Retrofit 3, JUnit 6, ktlint-gradle 14, Kotlin 2.4, AGP 9.5, Gradle 9.9; tools: sharp 0.35 (#8533)
Android, majors:
- OkHttp 5.5.1 (okhttp, logging, sse, mockwebserver, tls);
- Retrofit 3.0.0;
- JUnit Jupiter and Platform Launcher 6.1.3;
- ktlint-gradle 14.2.0.

Android, the rest of the dashboard's group:
- Kotlin 2.4.21, AGP 9.5.3, KSP 2.3.14, Gradle 9.9.3;
- Hilt 2.60.1, androidx.hilt 1.4.0, compose-bom 2026.11.01,
  navigation 2.10.2, Room 2.8.5;
- lifecycle 2.11.1, work 2.12.0, core-ktx 1.19.1, activity-compose
  1.13.0, media3 1.11.1, mediarouter 1.9.0, palette 1.1.0;
- coil 3.6.3, kotlinx serialization 1.13, coroutines 1.11, datetime
  0.8.0-0.6.x-compat (keeps the kotlinx.datetime.Instant API);
- turbine 1.2.1, mockk 1.14.12, detekt 2.0.0-alpha.6.

The catalog's header comment no longer names versions that go stale.

tools/: sharp ^0.35.0, the fix for the advisory on the Security
Dashboard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 10:50:30 -05:00
bvandeusenandClaude Opus 5.5 b36801b5a4 web deps: jsdom 31, jest-dom 8, @types/node 26, @lucide/svelte, current non-majors (#8532)
- lucide-svelte is replaced by its successor @lucide/svelte. The
  component names are the same, so only the import path changes (44
  files).
- jsdom 31, @testing-library/jest-dom 8, @types/node 26.
- The lockfile is refreshed within every range: svelte 5.60, vite 8.4,
  vitest 5.1, @sveltejs/kit 3.5, adapter-static 4.0.1. sharp is no
  longer in the tree.

TypeScript stays on 6: svelte-check 4.7.9, the web lane's type check,
accepts typescript ^5 || ^6 only. svelte-query 6 follows in its own
commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 10:49:30 -05:00
bvandeusenandClaude Opus 5.5 4e5cb298ef web: every Copy button works over plain http; saved keys and passwords can be removed (#8508, #8511)
copyText (family idea "copyText"):
- web/src/lib/utils/clipboard.ts tries the Clipboard API first.
- Where the API is missing (plain http on a home network) or refuses,
  it copies through the copy command on a hidden textarea instead.
- If that fails too, it selects the shown value.
- All six Copy buttons go through it: an invite token, the needs-a-file
  list, diagnostics, connection details, a playlist link, and report
  details. Before, five of them only showed an error over http.

SecretField (family idea "SecretField"):
- One component for a write-only credential: a password box for a new
  value, which the card's own Save sends, and a Remove button while one
  is saved.
- Used for the provider API keys, the SMTP password, the backup secret
  key and the AcoustID key. Only AcoustID had Remove before.
- The server gains clear_password (SMTP) and clear_secret_key (backup).
  An empty value still keeps the stored one. Provider keys already clear
  when sent empty.
- Remove sends the saved settings back with only the credential cleared,
  so unsaved edits elsewhere on the card stay unsaved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 10:48:00 -05:00
bvandeusenandClaude Opus 5.5 7491a7b60f test: migrations round-trip down and up; dbtest fails when the lane has no database (#8509, #8510)
Migration round trip (family idea "Migration CI lane"):
- TestMigrationsRoundTrip, in the integration lane, migrates a scratch
  database to the baseline, then all the way up, then every migration
  after the baseline down, then up again.
- The schema after the down pass must match a database migrated to the
  baseline alone: columns, indexes, constraints, sequences, enums,
  functions and triggers. So a down file that leaves something behind
  fails, as well as one that errors.
- The baseline's own down file refuses to run by design, so the round
  trip stops there.
- The test uses golang-migrate as a library, with no migrator binary.
- The scratch database is dropped afterwards, and the shared test
  database is never migrated down.

dbtest (family idea "dbtest Pool and Fixtures"):
- dbtest.URL skips without a database. It fails instead when
  MINSTREL_TEST_DATABASE_REQUIRED is set, and the integration lane sets
  it.
- dbtest.On(t, db) gives One/Exec/Count fixtures. The local copies are
  repointed to them: exec in api, mustExec/mustID in backup,
  countQueueRows in scrobble, and countTrackSim/countArtistSim in
  similarity.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 10:44:18 -05:00
bvandeusenandClaude Opus 5.5 d1c63acf78 deps: Debian 13 image, Postgres 19, current Go modules (#8529, #8530, #8531)
release / go (push) Successful in 1m45s
release / web (push) Successful in 1m16s
release / govulncheck (push) Successful in 19s
release / android (push) Successful in 1m59s
release / integration (push) Successful in 2m49s
release / Build signed APK (push) Successful in 1m49s
release / Build + push container image (push) Successful in 1m22s
- Every image stage moves to Debian 13 (trixie): node:26-trixie-slim,
  golang:1.26-trixie, debian:trixie-slim. The govulncheck lane follows
  the builder. Most of the Security Dashboard's image findings are
  bookworm packages with no fix.
- Dockerfile syntax 1.29.
- Postgres 19 in the CI integration lane, the dev compose, the demo
  compose and the README quick start. The README says a major-version
  move needs a dump and restore.
- Go modules: chi 5.5, gocron 2.23, migrate 4.20, pgx 5.13,
  testify 1.12, x/crypto 0.59, x/sync 0.25. go 1.26.0.

Go itself stays on 1.26: ci-go:1.27 is not published yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 10:41:00 -05:00
bvandeusenandClaude Opus 5.5 94f7bab191 security: allowlist the three test values the sweep reads as secrets (#8507)
release / go (push) Successful in 1m47s
release / web (push) Successful in 1m14s
release / govulncheck (push) Successful in 19s
release / android (push) Successful in 1m55s
release / integration (push) Successful in 2m42s
release / Build signed APK (push) Successful in 1m45s
release / Build + push container image (push) Successful in 16s
The weekly security sweep flagged AWS's published SigV4 example keys in
internal/backup/s3_test.go and a test invite token in
internal/api/auth_register_test.go. None is a credential. A repo-level
.gitleaks.toml extends the family config and allowlists each value with
its reason. It is export-ignored like renovate.json, and the export
check names it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 09:24:54 -05:00
466 changed files with 18467 additions and 16528 deletions
+1
View File
@@ -5,6 +5,7 @@
ci/ export-ignore ci/ export-ignore
ci-requirements.md export-ignore ci-requirements.md export-ignore
renovate.json export-ignore renovate.json export-ignore
.gitleaks.toml export-ignore
internal/server/release_gate_test.go export-ignore internal/server/release_gate_test.go export-ignore
internal/server/release_version_test.go export-ignore internal/server/release_version_test.go export-ignore
.gitattributes export-ignore .gitattributes export-ignore
+22 -15
View File
@@ -122,7 +122,7 @@ jobs:
go: go:
runs-on: go-ci runs-on: go-ci
container: container:
image: git.fabledsword.com/bvandeusen/ci-go:1.26 image: git.fabledsword.com/bvandeusen/ci-go:1.27
steps: steps:
- name: Checkout - name: Checkout
@@ -176,10 +176,10 @@ jobs:
integration: integration:
runs-on: go-ci runs-on: go-ci
container: container:
image: git.fabledsword.com/bvandeusen/ci-go:1.26 image: git.fabledsword.com/bvandeusen/ci-go:1.27
services: services:
postgres: postgres:
image: postgres:16-alpine image: postgres:19-alpine
env: env:
POSTGRES_USER: minstrel POSTGRES_USER: minstrel
POSTGRES_PASSWORD: minstrel POSTGRES_PASSWORD: minstrel
@@ -211,7 +211,7 @@ jobs:
echo "self ($SELF) networks: $SELF_NETS" echo "self ($SELF) networks: $SELF_NETS"
PG_ID="" PG_ID=""
PG_NAME="" PG_NAME=""
for cid in $(docker ps --filter "ancestor=postgres:16-alpine" -q); do for cid in $(docker ps --filter "ancestor=postgres:19-alpine" -q); do
nm=$(docker inspect -f '{{.Name}}' "$cid" | sed 's#^/##') nm=$(docker inspect -f '{{.Name}}' "$cid" | sed 's#^/##')
case "$nm" in *minstrel-postgres*|*_postgres_*) continue ;; esac case "$nm" in *minstrel-postgres*|*_postgres_*) continue ;; esac
for net in $(docker inspect -f '{{range $k,$v := .NetworkSettings.Networks}}{{$k}} {{end}}' "$cid"); do for net in $(docker inspect -f '{{range $k,$v := .NetworkSettings.Networks}}{{$k}} {{end}}' "$cid"); do
@@ -223,6 +223,9 @@ jobs:
PG_IP=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$PG_ID") PG_IP=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$PG_ID")
test -n "$PG_IP" test -n "$PG_IP"
export MINSTREL_TEST_DATABASE_URL="postgres://minstrel:minstrel@${PG_IP}:5432/minstrel_test?sslmode=disable" 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 # Wait for Postgres to accept connections. Asked of the service
# container itself: the run: shell is dash, where a `/dev/tcp` # container itself: the run: shell is dash, where a `/dev/tcp`
@@ -303,7 +306,7 @@ jobs:
web: web:
runs-on: go-ci runs-on: go-ci
container: container:
image: git.fabledsword.com/bvandeusen/ci-go:1.26 image: git.fabledsword.com/bvandeusen/ci-go:1.27
defaults: defaults:
run: run:
@@ -332,7 +335,7 @@ jobs:
# docker that can pull our container.image. # docker that can pull our container.image.
runs-on: flutter-ci runs-on: flutter-ci
container: container:
image: git.fabledsword.com/bvandeusen/ci-android:36 image: git.fabledsword.com/bvandeusen/ci-android:37
defaults: defaults:
run: run:
@@ -410,7 +413,7 @@ jobs:
govulncheck: govulncheck:
runs-on: go-ci runs-on: go-ci
container: container:
image: golang:1.26-bookworm image: golang:1.27-trixie
steps: steps:
# Plain git, not actions/checkout: that action runs on node, which the # Plain git, not actions/checkout: that action runs on node, which the
@@ -443,7 +446,7 @@ jobs:
|| github.ref == 'refs/heads/main' || github.ref == 'refs/heads/main'
runs-on: flutter-ci runs-on: flutter-ci
container: container:
image: git.fabledsword.com/bvandeusen/ci-android:36 image: git.fabledsword.com/bvandeusen/ci-android:37
defaults: defaults:
run: run:
@@ -557,10 +560,14 @@ jobs:
signer="$(ls "$sdk"/build-tools/*/apksigner 2>/dev/null | sort -V | tail -1 || true)" 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; } 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)" certs="$("$signer" verify --print-certs app/build/outputs/apk/release/app-release.apk)"
printf '%s\n' "$certs" | grep -E '^Signer #[0-9]+ certificate (DN|SHA-256 digest)' # apksigner's signer label varies between versions: "Signer #1
# One signer, and it is ours. A second signer would be a lineage or # 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
# a mistake; either way not something to ship unexamined. # a mistake; either way not something to ship unexamined.
digests="$(printf '%s\n' "$certs" | sed -n 's/^Signer #[0-9]* certificate SHA-256 digest: //p')" digests="$(printf '%s\n' "$certs" | sed -n 's/^.*certificate SHA-256 digest: //p' | sort -u)"
if [ "$digests" != "$RELEASE_CERT_SHA256" ]; then if [ "$digests" != "$RELEASE_CERT_SHA256" ]; then
if printf '%s' "$certs" | grep -q 'CN=Android Debug'; then if printf '%s' "$certs" | grep -q 'CN=Android Debug'; then
echo "::error::the release APK is signed with a debug key" echo "::error::the release APK is signed with a debug key"
@@ -615,7 +622,7 @@ jobs:
&& needs.android-release.result == 'success' }} && needs.android-release.result == 'success' }}
runs-on: go-ci runs-on: go-ci
container: container:
image: git.fabledsword.com/bvandeusen/ci-go:1.26 image: git.fabledsword.com/bvandeusen/ci-go:1.27
env: env:
IMAGE: git.fabledsword.com/bvandeusen/minstrel IMAGE: git.fabledsword.com/bvandeusen/minstrel
@@ -700,7 +707,7 @@ jobs:
rm -rf "${EXPORT}" rm -rf "${EXPORT}"
mkdir -p "${EXPORT}" mkdir -p "${EXPORT}"
git archive HEAD | tar -x -C "${EXPORT}" git archive HEAD | tar -x -C "${EXPORT}"
for private in .gitea .forgejo .github ci ci-requirements.md .gitattributes renovate.json; do for private in .gitea .forgejo .github ci ci-requirements.md .gitattributes renovate.json .gitleaks.toml; do
if [ -e "${EXPORT}/${private}" ]; then if [ -e "${EXPORT}/${private}" ]; then
echo "::error::the export carries ${private}; .gitattributes export-ignore no longer covers it" echo "::error::the export carries ${private}; .gitattributes export-ignore no longer covers it"
exit 1 exit 1
@@ -783,8 +790,8 @@ jobs:
- name: Build and push - name: Build and push
shell: bash shell: bash
# --pull: the Dockerfile's base images are floating tags (golang:1.26, # --pull: the Dockerfile's base images are floating tags (golang:1.27,
# debian:bookworm-slim). Without it the runner's daemon reuses # debian:trixie-slim). Without it the runner's daemon reuses
# whatever it cached, and the shipped binary can sit on a Go patch # whatever it cached, and the shipped binary can sit on a Go patch
# release govulncheck already flagged while the lane, which pulls # release govulncheck already flagged while the lane, which pulls
# fresh, reports clean. # fresh, reports clean.
+22
View File
@@ -0,0 +1,22 @@
# 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.6 # syntax=docker/dockerfile:1.29
FROM node:22-bookworm-slim AS web FROM node:26-trixie-slim AS web
WORKDIR /web WORKDIR /web
COPY web/package.json web/package-lock.json ./ COPY web/package.json web/package-lock.json ./
RUN npm ci RUN npm ci
COPY web/ ./ COPY web/ ./
RUN npm run build RUN npm run build
FROM golang:1.26-bookworm AS builder FROM golang:1.27-trixie AS builder
WORKDIR /src WORKDIR /src
COPY go.mod go.sum ./ COPY go.mod go.sum ./
RUN go mod download RUN go mod download
@@ -31,7 +31,7 @@ RUN go build -trimpath \
-X 'github.com/Fabled-Sword/minstrel/internal/buildinfo.Channel=${MINSTREL_CHANNEL}'" \ -X 'github.com/Fabled-Sword/minstrel/internal/buildinfo.Channel=${MINSTREL_CHANNEL}'" \
-o /out/minstrel ./cmd/minstrel -o /out/minstrel ./cmd/minstrel
FROM debian:bookworm-slim FROM debian:trixie-slim
# ffmpeg: duration probes and the exact-tier audio hash (a SHA-256 of the # ffmpeg: duration probes and the exact-tier audio hash (a SHA-256 of the
# encoded audio packets, so no decode). libchromaprint-tools: fpcalc, the # encoded audio packets, so no decode). libchromaprint-tools: fpcalc, the
# acoustic fingerprint that tells the same recording at two bitrates apart # acoustic fingerprint that tells the same recording at two bitrates apart
+3 -1
View File
@@ -32,7 +32,7 @@ services:
depends_on: [db] depends_on: [db]
db: db:
image: postgres:17 image: postgres:19
environment: environment:
POSTGRES_USER: minstrel POSTGRES_USER: minstrel
POSTGRES_PASSWORD: minstrel POSTGRES_PASSWORD: minstrel
@@ -94,6 +94,8 @@ 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. **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 ## Features
**Listening** **Listening**
+11
View File
@@ -0,0 +1,11 @@
# 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
+4 -1
View File
@@ -15,7 +15,10 @@ plugins {
android { android {
namespace = "com.fabledsword.minstrel" namespace = "com.fabledsword.minstrel"
compileSdk = 36 // 37.1: Compose 1.13 requires compiling against Android 37.1 or later.
compileSdk {
version = release(37) { minorApiLevel = 1 }
}
defaultConfig { defaultConfig {
applicationId = "com.fabledsword.minstrel" 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.auth.ui.AuthGateViewModel
import com.fabledsword.minstrel.cache.CachedTrackIds import com.fabledsword.minstrel.cache.CachedTrackIds
import com.fabledsword.minstrel.connectivity.LocalServerHealth import com.fabledsword.minstrel.connectivity.LocalServerHealth
import com.fabledsword.minstrel.connectivity.ServerHealth
import com.fabledsword.minstrel.connectivity.NetworkStatusController import com.fabledsword.minstrel.connectivity.NetworkStatusController
import com.fabledsword.minstrel.connectivity.ServerHealth
import com.fabledsword.minstrel.nav.DetailSeedCache import com.fabledsword.minstrel.nav.DetailSeedCache
import com.fabledsword.minstrel.nav.LocalDetailSeedCache import com.fabledsword.minstrel.nav.LocalDetailSeedCache
import com.fabledsword.minstrel.nav.Login import com.fabledsword.minstrel.nav.Login
@@ -56,8 +56,11 @@ import javax.inject.Inject
@AndroidEntryPoint @AndroidEntryPoint
class MainActivity : ComponentActivity() { class MainActivity : ComponentActivity() {
@Inject lateinit var seedCache: DetailSeedCache @Inject lateinit var seedCache: DetailSeedCache
@Inject lateinit var cachedTrackIds: CachedTrackIds @Inject lateinit var cachedTrackIds: CachedTrackIds
@Inject lateinit var serverHealth: NetworkStatusController @Inject lateinit var serverHealth: NetworkStatusController
@Inject lateinit var authStore: AuthStore @Inject lateinit var authStore: AuthStore
// Set when the user taps a notification: the media one asks for the full // Set when the user taps a notification: the media one asks for the full
@@ -120,8 +123,9 @@ class MainActivity : ComponentActivity() {
val signedIn = authStore.sessionCookie.map { !it.isNullOrEmpty() } val signedIn = authStore.sessionCookie.map { !it.isNullOrEmpty() }
combine(signedIn, authStore.backgroundDelivery, ::deliveryWanted).first { it } combine(signedIn, authStore.backgroundDelivery, ::deliveryWanted).first { it }
val permission = Manifest.permission.POST_NOTIFICATIONS val permission = Manifest.permission.POST_NOTIFICATIONS
val granted = ContextCompat.checkSelfPermission(this@MainActivity, permission) == val granted =
PackageManager.PERMISSION_GRANTED ContextCompat.checkSelfPermission(this@MainActivity, permission) ==
PackageManager.PERMISSION_GRANTED
if (!granted) askToNotify.launch(permission) if (!granted) askToNotify.launch(permission)
} }
} }
@@ -196,7 +200,10 @@ private fun App(
* request fails. * request fails.
*/ */
@Composable @Composable
private fun SignInWhenSessionRejected(gate: AuthGateViewModel, navController: NavHostController) { private fun SignInWhenSessionRejected(
gate: AuthGateViewModel,
navController: NavHostController,
) {
val sessionRejected by gate.sessionRejected.collectAsStateWithLifecycle() val sessionRejected by gate.sessionRejected.collectAsStateWithLifecycle()
LaunchedEffect(sessionRejected, navController) { LaunchedEffect(sessionRejected, navController) {
if (!sessionRejected) return@LaunchedEffect if (!sessionRejected) return@LaunchedEffect
@@ -11,6 +11,7 @@ import com.fabledsword.minstrel.cache.CacheIndexer
import com.fabledsword.minstrel.cache.audiocache.CacheBudgetSync import com.fabledsword.minstrel.cache.audiocache.CacheBudgetSync
import com.fabledsword.minstrel.cache.mutations.MutationReplayer import com.fabledsword.minstrel.cache.mutations.MutationReplayer
import com.fabledsword.minstrel.cache.sync.SyncController import com.fabledsword.minstrel.cache.sync.SyncController
import com.fabledsword.minstrel.connectivity.NetworkStatusController
import com.fabledsword.minstrel.di.ApplicationScope import com.fabledsword.minstrel.di.ApplicationScope
import com.fabledsword.minstrel.diagnostics.DiagnosticsReporter import com.fabledsword.minstrel.diagnostics.DiagnosticsReporter
import com.fabledsword.minstrel.diagnostics.DiagnosticsUploader import com.fabledsword.minstrel.diagnostics.DiagnosticsUploader
@@ -24,7 +25,6 @@ import com.fabledsword.minstrel.player.LikedAudioPinner
import com.fabledsword.minstrel.player.PlayEventsReporter import com.fabledsword.minstrel.player.PlayEventsReporter
import com.fabledsword.minstrel.player.PlaybackErrorReporter import com.fabledsword.minstrel.player.PlaybackErrorReporter
import com.fabledsword.minstrel.player.ResumeController import com.fabledsword.minstrel.player.ResumeController
import com.fabledsword.minstrel.connectivity.NetworkStatusController
import dagger.hilt.android.HiltAndroidApp import dagger.hilt.android.HiltAndroidApp
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
@@ -41,7 +41,6 @@ class MinstrelApplication :
Application(), Application(),
Configuration.Provider, Configuration.Provider,
SingletonImageLoader.Factory { SingletonImageLoader.Factory {
@Inject lateinit var workerFactory: HiltWorkerFactory @Inject lateinit var workerFactory: HiltWorkerFactory
/** /**
@@ -66,7 +65,9 @@ class MinstrelApplication :
* cold start with persisted cookie). Without this @Inject the * cold start with persisted cookie). Without this @Inject the
* singleton would never instantiate. * 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 * Same construct-the-singleton trick — MutationReplayer's init
@@ -75,7 +76,9 @@ class MinstrelApplication :
* cold start with persisted cookie). Without this @Inject the * cold start with persisted cookie). Without this @Inject the
* queue would only enqueue, never replay. * 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 * Same construct-the-singleton trick — DeliveryLauncher starts and stops
@@ -83,7 +86,9 @@ class MinstrelApplication :
* every nudge and reconnect. Without this @Inject no phone * every nudge and reconnect. Without this @Inject no phone
* notification would ever be posted. * 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 * Same construct-the-singleton trick — PlayEventsReporter's init
@@ -92,7 +97,9 @@ class MinstrelApplication :
* server. Without this @Inject the singleton would never * server. Without this @Inject the singleton would never
* instantiate and Android plays would never reach the server. * 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 * Same construct-the-singleton trick — PlaybackErrorReporter
@@ -102,7 +109,9 @@ class MinstrelApplication :
* snackbar. Without this construct ExoPlayer skip-on-error is * snackbar. Without this construct ExoPlayer skip-on-error is
* invisible to the user. * 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 * Same construct-the-singleton trick — CoverPrefetcher's init
@@ -110,7 +119,9 @@ class MinstrelApplication :
* cache with the next track's cover so track changes don't flash * cache with the next track's cover so track changes don't flash
* a loading state. * 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 * Same construct-the-singleton trick — CacheIndexer's init block
@@ -119,7 +130,9 @@ class MinstrelApplication :
* and the cached indicator their data source. Without this @Inject * and the cached indicator their data source. Without this @Inject
* the index would stay empty and the offline pools would be inert. * 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 * Same construct-the-singleton trick — CacheBudgetSync's init block
@@ -127,14 +140,18 @@ class MinstrelApplication :
* Without this @Inject the evictor would never arm, and the cache * Without this @Inject the evictor would never arm, and the cache
* would grow without a limit. * 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 * Same construct-the-singleton trick — LikedAudioPinner's init block
* downloads liked tracks into the Liked songs budget. Without this * downloads liked tracks into the Liked songs budget. Without this
* @Inject, liking a track would not keep it offline. * @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 * Same construct-the-singleton trick — AudioPrefetcher's init
@@ -143,7 +160,9 @@ class MinstrelApplication :
* SimpleCache via CacheWriter. Without this @Inject the * SimpleCache via CacheWriter. Without this @Inject the
* prefetchWindow setting would be inert and skips would re-fetch. * 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 * Same construct-the-singleton trick — NetworkStatusController owns the
@@ -152,7 +171,9 @@ class MinstrelApplication :
* signal (plus the VersionTooOld byproduct). It must exist from launch so * signal (plus the VersionTooOld byproduct). It must exist from launch so
* the poll loop runs and the StateFlow stays warm for every consumer. * 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 * Same construct-the-singleton trick — FreshnessSweeper's init
@@ -161,7 +182,9 @@ class MinstrelApplication :
* via MetadataProvider, so the cache stays warm without * via MetadataProvider, so the cache stays warm without
* user-driven pull-to-refresh. * 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 * Same construct-the-singleton trick — EventsStream's init block
@@ -170,21 +193,31 @@ class MinstrelApplication :
* Without this @Inject the events SharedFlow would have no * Without this @Inject the events SharedFlow would have no
* upstream and consumers would never see anything. * 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 * Same construct-the-singleton trick — LiveEventsDispatcher's
* init block subscribes to EventsStream.events + the process * init block subscribes to EventsStream.events + the process
* lifecycle and routes cross-screen state refreshes. * 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 // Device diagnostics. The reporter gates itself on the account's
// debug flag; the uploader drains its buffer on a tick / recovery. // debug flag; the uploader drains its buffer on a tick / recovery.
@Suppress("unused") @Inject lateinit var diagnosticsReporter: DiagnosticsReporter @Suppress("unused")
@Suppress("unused") @Inject lateinit var diagnosticsUploader: DiagnosticsUploader @Inject
lateinit var diagnosticsReporter: DiagnosticsReporter
@Inject @ApplicationScope lateinit var appScope: CoroutineScope @Suppress("unused")
@Inject
lateinit var diagnosticsUploader: DiagnosticsUploader
@Inject @ApplicationScope
lateinit var appScope: CoroutineScope
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
@@ -208,10 +241,17 @@ class MinstrelApplication :
* to the package-stack-trace tag DebugTree produces. * to the package-stack-trace tag DebugTree produces.
*/ */
private class ReleaseTree : Timber.Tree() { private class ReleaseTree : Timber.Tree() {
override fun isLoggable(tag: String?, priority: Int): Boolean = override fun isLoggable(
priority >= android.util.Log.WARN 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" val resolvedTag = tag ?: "Minstrel"
if (t == null) { if (t == null) {
android.util.Log.println(priority, resolvedTag, message) android.util.Log.println(priority, resolvedTag, message)
@@ -226,9 +266,11 @@ class MinstrelApplication :
} }
override val workManagerConfiguration: Configuration override val workManagerConfiguration: Configuration
get() = Configuration.Builder() get() =
.setWorkerFactory(workerFactory) Configuration
.build() .Builder()
.setWorkerFactory(workerFactory)
.build()
/** /**
* Builds the process-singleton Coil ImageLoader with our shared * Builds the process-singleton Coil ImageLoader with our shared
@@ -242,10 +284,10 @@ class MinstrelApplication :
* two read as one cross-dissolve. * two read as one cross-dissolve.
*/ */
override fun newImageLoader(context: android.content.Context): ImageLoader = override fun newImageLoader(context: android.content.Context): ImageLoader =
ImageLoader.Builder(context) ImageLoader
.Builder(context)
.components { .components {
add(OkHttpNetworkFetcherFactory(callFactory = { okHttpClient })) add(OkHttpNetworkFetcherFactory(callFactory = { okHttpClient }))
} }.crossfade(ART_CROSSFADE_MS)
.crossfade(ART_CROSSFADE_MS)
.build() .build()
} }
@@ -14,25 +14,38 @@ import javax.inject.Singleton
* admin repos — direct REST, no caching. * admin repos — direct REST, no caching.
*/ */
@Singleton @Singleton
class AdminInvitesRepository @Inject constructor(retrofit: Retrofit) { class AdminInvitesRepository
private val api: AdminInvitesApi = retrofit.create() @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 = suspend fun create(note: String?): Invite =
api.create(CreateInviteBody(note = note?.takeIf { it.isNotEmpty() })).toDomain() api
.create(
CreateInviteBody(
note =
note?.takeIf {
it.isNotEmpty()
},
),
).toDomain()
suspend fun revoke(token: String) { suspend fun revoke(token: String) {
api.revoke(token) api.revoke(token)
}
} }
}
private fun InviteWire.toDomain(): Invite = Invite( private fun InviteWire.toDomain(): Invite =
token = token, Invite(
invitedBy = invitedBy, token = token,
note = note, invitedBy = invitedBy,
createdAt = createdAt, note = note,
expiresAt = expiresAt, createdAt = createdAt,
redeemedAt = redeemedAt, expiresAt = expiresAt,
redeemedBy = redeemedBy, redeemedAt = redeemedAt,
) redeemedBy = redeemedBy,
)
@@ -17,19 +17,21 @@ import javax.inject.Singleton
* Each action takes the row off the queue once the server accepts it. * Each action takes the row off the queue once the server accepts it.
*/ */
@Singleton @Singleton
class AdminQuarantineRepository @Inject constructor( class AdminQuarantineRepository
retrofit: Retrofit, @Inject
) { constructor(
private val api: AdminQuarantineApi = retrofit.create() 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 ── // ── Mappers ──
@@ -18,31 +18,38 @@ import javax.inject.Singleton
* Exceptions propagate to the ViewModel (which maps them via ErrorCopy). * Exceptions propagate to the ViewModel (which maps them via ErrorCopy).
*/ */
@Singleton @Singleton
class AdminTagSourcesRepository @Inject constructor( class AdminTagSourcesRepository
retrofit: Retrofit, @Inject
) { constructor(
private val api: AdminTagSourcesApi = retrofit.create() 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 = suspend fun setEnabled(
api.update(id, UpdateTagSourceBody(enabled = enabled)).toDomain() id: String,
enabled: Boolean,
): AdminTagSourceRef = api.update(id, UpdateTagSourceBody(enabled = enabled)).toDomain()
suspend fun setApiKey(id: String, apiKey: String): AdminTagSourceRef = suspend fun setApiKey(
api.update(id, UpdateTagSourceBody(apiKey = apiKey)).toDomain() 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( private fun AdminTagSourceWire.toDomain(): AdminTagSourceRef =
id = id, AdminTagSourceRef(
displayName = displayName, id = id,
requiresApiKey = requiresApiKey, displayName = displayName,
supports = supports, requiresApiKey = requiresApiKey,
enabled = enabled, supports = supports,
apiKeySet = apiKeySet, enabled = enabled,
testable = testable, apiKeySet = apiKeySet,
) testable = testable,
)
private fun TestTagSourceWire.toResult(): TagSourceTestResult = private fun TestTagSourceWire.toResult(): TagSourceTestResult =
TagSourceTestResult(ok = ok, durationMs = durationMs, error = error) TagSourceTestResult(ok = ok, durationMs = durationMs, error = error)
@@ -16,26 +16,33 @@ import javax.inject.Singleton
* admin repositories. * admin repositories.
*/ */
@Singleton @Singleton
class AdminUsersRepository @Inject constructor( class AdminUsersRepository
retrofit: Retrofit, @Inject
) { constructor(
private val api: AdminUsersApi = retrofit.create() 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) = suspend fun setAdmin(
api.setAdmin(id, SetAdminBody(isAdmin)) id: String,
isAdmin: Boolean,
) = api.setAdmin(id, SetAdminBody(isAdmin))
suspend fun resetPassword(id: String, newPassword: String) = suspend fun resetPassword(
api.resetPassword(id, ResetPasswordBody(newPassword)) 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( private fun AdminUserWire.toDomain(): AdminUserRef =
id = id, AdminUserRef(
username = username, id = id,
displayName = displayName, username = username,
isAdmin = isAdmin, displayName = displayName,
createdAt = createdAt, isAdmin = isAdmin,
) createdAt = createdAt,
)
@@ -25,72 +25,73 @@ data class AdminInvitesUiState(
) )
@HiltViewModel @HiltViewModel
class AdminInvitesViewModel @Inject constructor( class AdminInvitesViewModel
private val repository: AdminInvitesRepository, @Inject
networkStatus: NetworkStatusController, constructor(
) : ViewModel() { private val repository: AdminInvitesRepository,
networkStatus: NetworkStatusController,
) : ViewModel() {
private val internal = MutableStateFlow(AdminInvitesUiState())
val state: StateFlow<AdminInvitesUiState> = internal.asStateFlow()
private val internal = MutableStateFlow(AdminInvitesUiState()) /** One-shot signal for screens to show the generated token + copy UI. */
val state: StateFlow<AdminInvitesUiState> = internal.asStateFlow() private val createdChannel = Channel<Invite>(Channel.BUFFERED)
val created: Flow<Invite> = createdChannel.receiveAsFlow()
/** One-shot signal for screens to show the generated token + copy UI. */ init {
private val createdChannel = Channel<Invite>(Channel.BUFFERED) refresh()
val created: Flow<Invite> = createdChannel.receiveAsFlow() // Screen-level auto-recovery: reload a failed list
// when server health returns instead of waiting for a manual pull.
init { viewModelScope.launch {
refresh() networkStatus.recoveries().collect {
// Screen-level auto-recovery: reload a failed list if (internal.value.message != null) refresh()
// 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?) { fun refresh() {
viewModelScope.launch { viewModelScope.launch {
try { internal.update { it.copy(isLoading = true, message = null) }
val invite = repository.create(note) try {
createdChannel.trySend(invite) val rows = repository.list()
// Optimistically prepend; next refresh reconciles. internal.update { it.copy(isLoading = false, invites = rows) }
internal.update { it.copy(invites = listOf(invite) + it.invites) } } catch (
} catch ( @Suppress("TooGenericExceptionCaught") e: Throwable,
@Suppress("TooGenericExceptionCaught") e: Throwable, ) {
) { internal.update {
internal.update { it.copy(
it.copy(message = ErrorCopy.fromThrowable(e)) isLoading = false,
message = ErrorCopy.fromThrowable(e),
)
}
} }
} }
} }
}
fun revoke(token: String) { fun generate(note: String?) {
val before = internal.value.invites viewModelScope.launch {
// Optimistic removal. try {
internal.update { it.copy(invites = before.filterNot { i -> i.token == token }) } val invite = repository.create(note)
viewModelScope.launch { createdChannel.trySend(invite)
runCatching { repository.revoke(token) } // Optimistically prepend; next refresh reconciles.
.onFailure { refresh() } 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.nav.AdminUsers
import com.fabledsword.minstrel.shared.UiState import com.fabledsword.minstrel.shared.UiState
import com.fabledsword.minstrel.shared.loadUiState 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.EmptyState
import com.fabledsword.minstrel.shared.widgets.LoadingCentered import com.fabledsword.minstrel.shared.widgets.LoadingCentered
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job import kotlinx.coroutines.Job
import kotlinx.coroutines.async import kotlinx.coroutines.async
@@ -56,7 +56,11 @@ import javax.inject.Inject
// ─── State ─────────────────────────────────────────────────────────── // ─── 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). */ /** The admin landing's counts, as the shared [UiState] (never Empty: it always has counts). */
typealias AdminLandingUiState = UiState<AdminCounts> typealias AdminLandingUiState = UiState<AdminCounts>
@@ -64,31 +68,34 @@ typealias AdminLandingUiState = UiState<AdminCounts>
// ─── ViewModel ─────────────────────────────────────────────────────── // ─── ViewModel ───────────────────────────────────────────────────────
@HiltViewModel @HiltViewModel
class AdminLandingViewModel @Inject constructor( class AdminLandingViewModel
private val quarantineRepo: AdminQuarantineRepository, @Inject
private val usersRepo: AdminUsersRepository, constructor(
private val tagSourcesRepo: AdminTagSourcesRepository, private val quarantineRepo: AdminQuarantineRepository,
) : ViewModel() { private val usersRepo: AdminUsersRepository,
private val tagSourcesRepo: AdminTagSourcesRepository,
) : ViewModel() {
private val internal = MutableStateFlow<AdminLandingUiState>(UiState.Loading)
val uiState: StateFlow<AdminLandingUiState> = internal.asStateFlow()
private val internal = MutableStateFlow<AdminLandingUiState>(UiState.Loading) init {
val uiState: StateFlow<AdminLandingUiState> = internal.asStateFlow() refresh()
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()))
}
} }
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 ────────────────────────────────────────────────────────── // ─── Screen ──────────────────────────────────────────────────────────
@@ -116,21 +123,26 @@ fun AdminLandingScreen(
) { ) {
when (val s = state) { when (val s = state) {
UiState.Loading, UiState.Empty -> LoadingCentered() UiState.Loading, UiState.Empty -> LoadingCentered()
is UiState.Error -> EmptyState( is UiState.Error ->
title = "Couldn't load admin counts", EmptyState(
body = s.message, title = "Couldn't load admin counts",
) body = s.message,
is UiState.Success -> SectionList( )
counts = s.data, is UiState.Success ->
navController = navController, SectionList(
) counts = s.data,
navController = navController,
)
} }
} }
} }
} }
@Composable @Composable
private fun SectionList(counts: AdminCounts, navController: NavHostController) { private fun SectionList(
counts: AdminCounts,
navController: NavHostController,
) {
LazyColumn( LazyColumn(
modifier = Modifier.fillMaxSize(), modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(16.dp), contentPadding = PaddingValues(16.dp),
@@ -175,9 +187,10 @@ private fun SectionCard(
onClick: () -> Unit, onClick: () -> Unit,
) { ) {
ElevatedCard( ElevatedCard(
modifier = Modifier modifier =
.fillMaxWidth() Modifier
.clickable(onClick = onClick), .fillMaxWidth()
.clickable(onClick = onClick),
) { ) {
Row( Row(
modifier = Modifier.padding(16.dp), 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.nav.AdminQuarantine
import com.fabledsword.minstrel.shared.UiState import com.fabledsword.minstrel.shared.UiState
import com.fabledsword.minstrel.shared.widgets.ConfirmDestructiveDialog 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.EmptyState
import com.fabledsword.minstrel.shared.widgets.ErrorRetry import com.fabledsword.minstrel.shared.widgets.ErrorRetry
import com.fabledsword.minstrel.shared.widgets.LoadingCentered import com.fabledsword.minstrel.shared.widgets.LoadingCentered
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
@@ -74,22 +74,26 @@ fun AdminQuarantineScreen(
) { ) {
when (val s = state) { when (val s = state) {
UiState.Loading -> LoadingCentered() UiState.Loading -> LoadingCentered()
UiState.Empty -> EmptyState( UiState.Empty ->
title = "No reports", EmptyState(
body = "When listeners flag a track as a bad rip, wrong tags or " + title = "No reports",
"a duplicate, their reports gather here.", body =
) "When listeners flag a track as a bad rip, wrong tags or " +
is UiState.Error -> ErrorRetry( "a duplicate, their reports gather here.",
title = "Couldn't load queue", )
message = s.message, is UiState.Error ->
onRetry = { viewModel.refresh() }, ErrorRetry(
) title = "Couldn't load queue",
is UiState.Success -> QueueList( message = s.message,
rows = s.data, onRetry = { viewModel.refresh() },
onResolve = viewModel::resolve, )
onRemoveFile = viewModel::removeFile, is UiState.Success ->
onDeleteFile = viewModel::deleteFile, QueueList(
) rows = s.data,
onResolve = viewModel::resolve,
onRemoveFile = viewModel::removeFile,
onDeleteFile = viewModel::deleteFile,
)
} }
} }
} }
@@ -98,7 +102,10 @@ fun AdminQuarantineScreen(
/** A confirm asked of the admin before a removal: which one, and of which track. */ /** A confirm asked of the admin before a removal: which one, and of which track. */
private enum class Removal { File, Library } 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 @Composable
private fun QueueList( private fun QueueList(
@@ -146,20 +153,23 @@ private fun RemovalConfirm(
onDismiss: () -> Unit, onDismiss: () -> Unit,
) { ) {
val title = pending.row.trackTitle val title = pending.row.trackTitle
val (heading, body, action) = when (pending.kind) { val (heading, body, action) =
Removal.File -> Triple( when (pending.kind) {
"Remove the file?", Removal.File ->
"Delete the file of \u201c$title\u201d and keep the track. It waits, with its likes " + Triple(
"and plays, and takes over a good copy when one is in the library. Its reports are cleared.", "Remove the file?",
"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.",
Removal.Library -> Triple( "Remove the file",
"Remove from library?", )
"Remove \u201c$title\u201d and its file for good, with its likes, plays and playlist " + Removal.Library ->
"places. To keep the track for a good copy, remove the file instead.", Triple(
"Remove from library", "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( ConfirmDestructiveDialog(
title = heading, title = heading,
text = body, text = body,
@@ -177,9 +187,10 @@ private fun QuarantineRow(
onDeleteFile: () -> Unit, onDeleteFile: () -> Unit,
) { ) {
Column( Column(
modifier = Modifier modifier =
.fillMaxWidth() Modifier
.padding(horizontal = 16.dp, vertical = 12.dp), .fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp),
) { ) {
Text( Text(
@@ -27,62 +27,69 @@ import javax.inject.Inject
typealias AdminQuarantineUiState = UiState<List<AdminQuarantineItemRef>> typealias AdminQuarantineUiState = UiState<List<AdminQuarantineItemRef>>
@HiltViewModel @HiltViewModel
class AdminQuarantineViewModel @Inject constructor( class AdminQuarantineViewModel
private val repository: AdminQuarantineRepository, @Inject
private val eventsStream: EventsStream, constructor(
networkStatus: NetworkStatusController, private val repository: AdminQuarantineRepository,
) : ViewModel() { private val eventsStream: EventsStream,
networkStatus: NetworkStatusController,
) : ViewModel() {
private val internal = MutableStateFlow<AdminQuarantineUiState>(UiState.Loading)
val uiState: StateFlow<AdminQuarantineUiState> = internal.asStateFlow()
private val internal = MutableStateFlow<AdminQuarantineUiState>(UiState.Loading) /**
val uiState: StateFlow<AdminQuarantineUiState> = internal.asStateFlow() * 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 {
* One-shot messages for the screen's snackbar. A failed action has to say refresh()
* why: the row quietly reappearing reads as a glitch, and for a removal viewModelScope.launch {
* refused by a read-only library it hides the one thing an admin can fix. eventsStream.events
*/ .filter { it.kind.startsWith("quarantine.") }
private val transientMessagesChannel = Channel<String>(Channel.BUFFERED) .collect { refresh() }
val transientMessages: Flow<String> = transientMessagesChannel.receiveAsFlow() }
// Screen-level auto-recovery: reload a failed list
init { // when server health returns instead of waiting for a manual pull.
refresh() viewModelScope.launch {
viewModelScope.launch { networkStatus.recoveries().collect {
eventsStream.events if (internal.value is UiState.Error) refresh()
.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. fun refresh(): Job =
viewModelScope.launch { viewModelScope.launch {
networkStatus.recoveries().collect { internal.value = UiState.Loading
if (internal.value is UiState.Error) refresh() 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()
}
} }
} }
} }
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.models.TagSourceTestResult
import com.fabledsword.minstrel.nav.AdminTagSources import com.fabledsword.minstrel.nav.AdminTagSources
import com.fabledsword.minstrel.shared.UiState import com.fabledsword.minstrel.shared.UiState
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.EmptyState import com.fabledsword.minstrel.shared.widgets.EmptyState
import com.fabledsword.minstrel.shared.widgets.ErrorRetry import com.fabledsword.minstrel.shared.widgets.ErrorRetry
import com.fabledsword.minstrel.shared.widgets.LoadingCentered import com.fabledsword.minstrel.shared.widgets.LoadingCentered
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
@@ -68,22 +68,25 @@ fun AdminTagSourcesScreen(
) { ) {
when (val s = state) { when (val s = state) {
UiState.Loading -> LoadingCentered() UiState.Loading -> LoadingCentered()
UiState.Empty -> EmptyState( UiState.Empty ->
title = "No tag sources", EmptyState(
body = "Tag-enrichment providers register on the server; none are available.", 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", is UiState.Error ->
message = s.message, ErrorRetry(
onRetry = { viewModel.refresh() }, title = "Couldn't load tag sources",
) message = s.message,
is UiState.Success -> TagSourceList( onRetry = { viewModel.refresh() },
providers = s.data.providers, )
testResults = s.data.testResults, is UiState.Success ->
onToggle = viewModel::setEnabled, TagSourceList(
onSaveKey = viewModel::saveApiKey, providers = s.data.providers,
onTest = viewModel::test, testResults = s.data.testResults,
) onToggle = viewModel::setEnabled,
onSaveKey = viewModel::saveApiKey,
onTest = viewModel::test,
)
} }
} }
} }
@@ -156,7 +159,10 @@ private fun TagSourceCard(
} }
@Composable @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("") } var key by remember(provider.id) { mutableStateOf("") }
OutlinedTextField( OutlinedTextField(
value = key, value = key,
@@ -28,86 +28,99 @@ data class AdminTagSources(
typealias AdminTagSourcesUiState = UiState<AdminTagSources> typealias AdminTagSourcesUiState = UiState<AdminTagSources>
@HiltViewModel @HiltViewModel
class AdminTagSourcesViewModel @Inject constructor( class AdminTagSourcesViewModel
private val repository: AdminTagSourcesRepository, @Inject
networkStatus: NetworkStatusController, constructor(
) : ViewModel() { private val repository: AdminTagSourcesRepository,
networkStatus: NetworkStatusController,
) : ViewModel() {
private val internal = MutableStateFlow<AdminTagSourcesUiState>(UiState.Loading)
val uiState: StateFlow<AdminTagSourcesUiState> = internal.asStateFlow()
private val internal = MutableStateFlow<AdminTagSourcesUiState>(UiState.Loading) init {
val uiState: StateFlow<AdminTagSourcesUiState> = internal.asStateFlow() refresh()
// Screen-level auto-recovery: reload a failed list when server
init { // health returns instead of waiting for a manual pull.
refresh() viewModelScope.launch {
// Screen-level auto-recovery: reload a failed list when server networkStatus.recoveries().collect {
// health returns instead of waiting for a manual pull. if (internal.value is UiState.Error) refresh()
viewModelScope.launch { }
networkStatus.recoveries().collect {
if (internal.value is UiState.Error) refresh()
} }
} }
}
fun refresh(): Job = viewModelScope.launch { fun refresh(): Job =
internal.value = UiState.Loading viewModelScope.launch {
internal.value = loadUiState { internal.value = UiState.Loading
val providers = repository.list() internal.value =
if (providers.isEmpty()) UiState.Empty else UiState.Success(AdminTagSources(providers)) loadUiState {
} val providers = repository.list()
} if (providers.isEmpty()) UiState.Empty else UiState.Success(AdminTagSources(providers))
}
}
fun setEnabled(id: String, enabled: Boolean) { fun setEnabled(
val before = (internal.value as? UiState.Success<AdminTagSources>)?.data ?: return id: String,
// Optimistic toggle; reconcile via refresh() if the server rejects. enabled: Boolean,
internal.value = UiState.Success( ) {
before.copy( val before = (internal.value as? UiState.Success<AdminTagSources>)?.data ?: return
providers = before.providers.map { // Optimistic toggle; reconcile via refresh() if the server rejects.
if (it.id == id) it.copy(enabled = enabled) else it internal.value =
}, UiState.Success(
), before.copy(
) providers =
viewModelScope.launch { before.providers.map {
try { if (it.id == id) it.copy(enabled = enabled) else it
repository.setEnabled(id, enabled) },
} catch ( ),
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, )
) { viewModelScope.launch {
refresh() try {
repository.setEnabled(id, enabled)
} catch (
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
) {
refresh()
}
} }
} }
}
fun saveApiKey(id: String, apiKey: String) { fun saveApiKey(
viewModelScope.launch { id: String,
try { apiKey: String,
replaceProvider(repository.setApiKey(id, apiKey)) ) {
} catch ( viewModelScope.launch {
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, try {
) { replaceProvider(repository.setApiKey(id, apiKey))
refresh() } catch (
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
) {
refresh()
}
} }
} }
}
fun test(id: String) { fun test(id: String) {
viewModelScope.launch { viewModelScope.launch {
val result = try { val result =
repository.test(id) try {
} catch ( repository.test(id)
@Suppress("TooGenericExceptionCaught") e: Throwable, } catch (
) { @Suppress("TooGenericExceptionCaught") e: Throwable,
TagSourceTestResult(ok = false, error = ErrorCopy.fromThrowable(e)) ) {
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)))
} }
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 },
),
)
} }
} }
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,37 +2,27 @@
package com.fabledsword.minstrel.admin.ui package com.fabledsword.minstrel.admin.ui
import android.content.ClipData
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.layout.size
import androidx.compose.material3.AlertDialog import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button 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.HorizontalDivider
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch import androidx.compose.material3.Switch
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton 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.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
@@ -42,19 +32,28 @@ import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.ClipEntry
import androidx.compose.ui.platform.LocalClipboard
import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavHostController 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.AdminUserRef
import com.fabledsword.minstrel.models.Invite
import com.fabledsword.minstrel.nav.AdminUsers import com.fabledsword.minstrel.nav.AdminUsers
import com.fabledsword.minstrel.shared.UiState import com.fabledsword.minstrel.shared.UiState
import com.fabledsword.minstrel.shared.widgets.ConfirmDestructiveDialog 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.MinstrelTopAppBar
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
@Composable @Composable
@@ -175,11 +174,15 @@ private fun AdminUsersScaffold(
} }
@Composable @Composable
private fun SectionHeader(label: String, trailing: (@Composable () -> Unit)? = null) { private fun SectionHeader(
label: String,
trailing: (@Composable () -> Unit)? = null,
) {
Row( Row(
modifier = Modifier modifier =
.fillMaxWidth() Modifier
.padding(horizontal = 16.dp, vertical = 8.dp), .fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
) { ) {
Text( Text(
@@ -202,15 +205,16 @@ private fun androidx.compose.foundation.lazy.LazyListScope.usersSection(
UiState.Loading -> item { CenteredHint("Loading users…") } UiState.Loading -> item { CenteredHint("Loading users…") }
UiState.Empty -> item { CenteredHint("No registered users.") } UiState.Empty -> item { CenteredHint("No registered users.") }
is UiState.Error -> item { CenteredHint(state.message) } is UiState.Error -> item { CenteredHint(state.message) }
is UiState.Success -> items(items = state.data, key = { it.id }) { user -> is UiState.Success ->
UserRow( items(items = state.data, key = { it.id }) { user ->
user = user, UserRow(
onSetAdmin = { onSetAdmin(user.id, it) }, user = user,
onResetPassword = { onAskResetPassword(user) }, onSetAdmin = { onSetAdmin(user.id, it) },
onDelete = { onAskDelete(user) }, onResetPassword = { onAskResetPassword(user) },
) onDelete = { onAskDelete(user) },
HorizontalDivider() )
} HorizontalDivider()
}
} }
} }
@@ -220,13 +224,15 @@ private fun androidx.compose.foundation.lazy.LazyListScope.invitesSection(
) { ) {
when { when {
state.isLoading -> item { CenteredHint("Loading invites…") } state.isLoading -> item { CenteredHint("Loading invites…") }
state.invites.isEmpty() -> item { state.invites.isEmpty() ->
CenteredHint("No active invites. Use Generate to create one.") 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) }) else ->
HorizontalDivider() items(items = state.invites, key = { it.token }) { invite ->
} InviteRow(invite = invite, onRevoke = { onRevoke(invite.token) })
HorizontalDivider()
}
} }
} }
@@ -241,11 +247,15 @@ private fun CenteredHint(text: String) {
} }
@Composable @Composable
private fun InviteRow(invite: Invite, onRevoke: () -> Unit) { private fun InviteRow(
invite: Invite,
onRevoke: () -> Unit,
) {
Row( Row(
modifier = Modifier modifier =
.fillMaxWidth() Modifier
.padding(horizontal = 16.dp, vertical = 12.dp), .fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
) { ) {
Column(modifier = Modifier.weight(1f)) { Column(modifier = Modifier.weight(1f)) {
@@ -256,13 +266,14 @@ private fun InviteRow(invite: Invite, onRevoke: () -> Unit) {
maxLines = 1, maxLines = 1,
overflow = TextOverflow.Ellipsis, overflow = TextOverflow.Ellipsis,
) )
val subtitle = buildString { val subtitle =
if (!invite.note.isNullOrEmpty()) { buildString {
append(invite.note) if (!invite.note.isNullOrEmpty()) {
append(" · ") append(invite.note)
append(" · ")
}
append(if (invite.isRedeemed) "redeemed" else "expires ${invite.expiresAt}")
} }
append(if (invite.isRedeemed) "redeemed" else "expires ${invite.expiresAt}")
}
Text( Text(
text = subtitle, text = subtitle,
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
@@ -284,7 +295,10 @@ private fun InviteRow(invite: Invite, onRevoke: () -> Unit) {
} }
@Composable @Composable
private fun GenerateInviteDialog(onDismiss: () -> Unit, onConfirm: (String?) -> Unit) { private fun GenerateInviteDialog(
onDismiss: () -> Unit,
onConfirm: (String?) -> Unit,
) {
var note by remember { mutableStateOf("") } var note by remember { mutableStateOf("") }
AlertDialog( AlertDialog(
onDismissRequest = onDismiss, onDismissRequest = onDismiss,
@@ -317,7 +331,10 @@ private fun GenerateInviteDialog(onDismiss: () -> Unit, onConfirm: (String?) ->
} }
@Composable @Composable
private fun GeneratedInviteDialog(invite: Invite, onDismiss: () -> Unit) { private fun GeneratedInviteDialog(
invite: Invite,
onDismiss: () -> Unit,
) {
val clipboard = LocalClipboard.current val clipboard = LocalClipboard.current
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()
AlertDialog( AlertDialog(
@@ -399,9 +416,10 @@ private fun UserRow(
onDelete: () -> Unit, onDelete: () -> Unit,
) { ) {
Column( Column(
modifier = Modifier modifier =
.fillMaxWidth() Modifier
.padding(horizontal = 16.dp, vertical = 12.dp), .fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp),
) { ) {
Text( Text(
@@ -444,7 +462,11 @@ private fun UserRow(
} }
@Composable @Composable
private fun ToggleRow(label: String, checked: Boolean, onChange: (Boolean) -> Unit) { private fun ToggleRow(
label: String,
checked: Boolean,
onChange: (Boolean) -> Unit,
) {
Row( Row(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
@@ -496,8 +518,9 @@ private fun DeleteConfirmDialog(
) { ) {
ConfirmDestructiveDialog( ConfirmDestructiveDialog(
title = "Delete user?", title = "Delete user?",
text = "Delete @${user.username}? This removes the account and all " + text =
"their data. Type $DELETE_CONFIRM_WORD to confirm.", "Delete @${user.username}? This removes the account and all " +
"their data. Type $DELETE_CONFIRM_WORD to confirm.",
confirmLabel = "Delete", confirmLabel = "Delete",
onConfirm = onConfirm, onConfirm = onConfirm,
onDismiss = onDismiss, onDismiss = onDismiss,
@@ -506,4 +529,3 @@ private fun DeleteConfirmDialog(
} }
private const val DELETE_CONFIRM_WORD = "DELETE" private const val DELETE_CONFIRM_WORD = "DELETE"
@@ -21,77 +21,86 @@ import javax.inject.Inject
typealias AdminUsersUiState = UiState<List<AdminUserRef>> typealias AdminUsersUiState = UiState<List<AdminUserRef>>
@HiltViewModel @HiltViewModel
class AdminUsersViewModel @Inject constructor( class AdminUsersViewModel
private val repository: AdminUsersRepository, @Inject
networkStatus: NetworkStatusController, constructor(
) : ViewModel() { private val repository: AdminUsersRepository,
networkStatus: NetworkStatusController,
) : ViewModel() {
private val internal = MutableStateFlow<AdminUsersUiState>(UiState.Loading)
val uiState: StateFlow<AdminUsersUiState> = internal.asStateFlow()
private val internal = MutableStateFlow<AdminUsersUiState>(UiState.Loading) init {
val uiState: StateFlow<AdminUsersUiState> = internal.asStateFlow() 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()
}
}
}
init { fun refresh(): Job =
refresh() viewModelScope.launch {
// Screen-level auto-recovery: reload a failed list internal.value = UiState.Loading
// when server health returns instead of waiting for a manual pull. internal.value = loadUiState { repository.list().toListState() }
viewModelScope.launch { }
networkStatus.recoveries().collect {
if (internal.value is UiState.Error) refresh() 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()
}
} }
} }
} }
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,43 +20,47 @@ import javax.inject.Singleton
* from any of those hosts would sign the user out of Minstrel. * from any of those hosts would sign the user out of Minstrel.
*/ */
@Singleton @Singleton
class AuthCookieInterceptor @Inject constructor( class AuthCookieInterceptor
private val authStore: AuthStore, @Inject
) : Interceptor { constructor(
private val authStore: AuthStore,
override fun intercept(chain: Interceptor.Chain): Response { ) : Interceptor {
val original = chain.request() override fun intercept(chain: Interceptor.Chain): Response {
if (original.url.host != BaseUrlInterceptor.PLACEHOLDER_HOST) { val original = chain.request()
// External request — no Minstrel session cookie attached, if (original.url.host != BaseUrlInterceptor.PLACEHOLDER_HOST) {
// and a 401 from this host does NOT clear the user's // External request — no Minstrel session cookie attached,
// session. Pass through untouched. // and a 401 from this host does NOT clear the user's
return chain.proceed(original) // session. Pass through untouched.
} return chain.proceed(original)
val cookie = authStore.sessionCookieForRequest()
val request = original.newBuilder().apply {
if (!cookie.isNullOrEmpty()) header("Cookie", cookie)
}.build()
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)
} }
} val cookie = authStore.sessionCookieForRequest()
return response val request =
} original
.newBuilder()
.apply {
if (!cookie.isNullOrEmpty()) header("Cookie", cookie)
}.build()
private companion object { val response = chain.proceed(request)
const val HTTP_UNAUTHORIZED = 401
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,39 +31,43 @@ import javax.inject.Singleton
* error in the caller's normal error path. * error in the caller's normal error path.
*/ */
@Singleton @Singleton
class BaseUrlInterceptor @Inject constructor( class BaseUrlInterceptor
private val authStore: AuthStore, @Inject
) : Interceptor { 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(),
)
}
override fun intercept(chain: Interceptor.Chain): Response { companion object {
val original = chain.request() /** Sentinel host used by Retrofit + every code path that builds
// Early-bail keeps the no-op path for external URLs cheap * a Minstrel-server URL via the `http://placeholder.invalid/...`
// (no AuthStore read, no URL parse). * form (see [com.fabledsword.minstrel.shared.resolveServerUrl],
if (original.url.host != PLACEHOLDER_HOST) return chain.proceed(original) * CoverUrls.kt, AlbumRef/TrackRef cover getters). */
// Unparseable baseUrl folds into the same proceed path — keeps const val PLACEHOLDER_HOST = "placeholder.invalid"
// 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,7 +39,12 @@ class CleartextGuardInterceptor(
if (request.isHttps || request.tag(MinstrelServerRequest::class.java) == null) { if (request.isHttps || request.tag(MinstrelServerRequest::class.java) == null) {
return chain.proceed(request) return chain.proceed(request)
} }
val address = chain.connection()?.route()?.socketAddress?.address val address =
chain
.connection()
?.route()
?.socketAddress
?.address
if (address != null && !allows(address)) { if (address != null && !allows(address)) {
throw CleartextToPublicHostException(request.url.host) throw CleartextToPublicHostException(request.url.host)
} }
@@ -48,8 +53,9 @@ class CleartextGuardInterceptor(
} }
/** The server was reached over plain HTTP at a public address, and refused. */ /** The server was reached over plain HTTP at a public address, and refused. */
class CleartextToPublicHostException(host: String) : class CleartextToPublicHostException(
IOException("refusing plain http:// to $host: it is a public address") 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. */ /** Which addresses plain HTTP may reach: the home network, never the internet. */
object CleartextPolicy { object CleartextPolicy {
@@ -62,8 +68,10 @@ object CleartextPolicy {
fun allows(address: InetAddress): Boolean = fun allows(address: InetAddress): Boolean =
address.isLoopbackAddress || address.isLoopbackAddress ||
address.isSiteLocalAddress || // 10/8, 172.16/12, 192.168/16 address.isSiteLocalAddress ||
address.isLinkLocalAddress || // 169.254/16, fe80::/10 // 10/8, 172.16/12, 192.168/16
address.isLinkLocalAddress ||
// 169.254/16, fe80::/10
address.isAnyLocalAddress || address.isAnyLocalAddress ||
isCarrierGradeNat(address) || isCarrierGradeNat(address) ||
isUniqueLocal(address) isUniqueLocal(address)
@@ -1,6 +1,5 @@
package com.fabledsword.minstrel.api package com.fabledsword.minstrel.api
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json import kotlinx.serialization.json.Json
import retrofit2.HttpException import retrofit2.HttpException
@@ -23,10 +22,15 @@ object ErrorCopy {
private val json = Json { ignoreUnknownKeys = true } private val json = Json { ignoreUnknownKeys = true }
@Serializable @Serializable
private data class Envelope(val error: Body? = null) private data class Envelope(
val error: Body? = null,
)
@Serializable @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. */ /** Friendly copy for a known error [code], or the `unknown` fallback. */
fun messageFor(code: String): String = TABLE[code] ?: TABLE.getValue("unknown") fun messageFor(code: String): String = TABLE[code] ?: TABLE.getValue("unknown")
@@ -36,12 +40,13 @@ object ErrorCopy {
* HttpException bodies for the server code; treats IOExceptions * HttpException bodies for the server code; treats IOExceptions
* as connection failures. * as connection failures.
*/ */
fun fromThrowable(t: Throwable): String = when (t) { fun fromThrowable(t: Throwable): String =
is HttpException -> fromHttp(t) when (t) {
is CleartextToPublicHostException -> messageFor("cleartext_public") is HttpException -> fromHttp(t)
is IOException -> messageFor("connection_refused") is CleartextToPublicHostException -> messageFor("cleartext_public")
else -> TABLE.getValue("unknown") is IOException -> messageFor("connection_refused")
} else -> TABLE.getValue("unknown")
}
/** /**
* Codes whose server message carries specifics an admin needs in order * Codes whose server message carries specifics an admin needs in order
@@ -65,8 +70,9 @@ object ErrorCopy {
} }
private fun bodyFromHttp(e: HttpException): Body { private fun bodyFromHttp(e: HttpException): Body {
val raw = runCatching { e.response()?.errorBody()?.string() }.getOrNull() val raw =
?: return Body() runCatching { e.response()?.errorBody()?.string() }.getOrNull()
?: return Body()
return runCatching { json.decodeFromString<Envelope>(raw).error } return runCatching { json.decodeFromString<Envelope>(raw).error }
.getOrNull() ?: Body() .getOrNull() ?: Body()
} }
@@ -28,7 +28,6 @@ import javax.inject.Singleton
@Module @Module
@InstallIn(SingletonComponent::class) @InstallIn(SingletonComponent::class)
object NetworkModule { object NetworkModule {
@Provides @Provides
@Singleton @Singleton
fun provideHttpLogging(): HttpLoggingInterceptor = fun provideHttpLogging(): HttpLoggingInterceptor =
@@ -49,7 +48,8 @@ object NetworkModule {
reachability: ReachabilityReportingInterceptor, reachability: ReachabilityReportingInterceptor,
logging: HttpLoggingInterceptor, logging: HttpLoggingInterceptor,
): OkHttpClient = ): OkHttpClient =
OkHttpClient.Builder() OkHttpClient
.Builder()
// ReachabilityReportingInterceptor MUST run first: it identifies // ReachabilityReportingInterceptor MUST run first: it identifies
// Minstrel-bound requests by the still-unrewritten PLACEHOLDER_HOST // Minstrel-bound requests by the still-unrewritten PLACEHOLDER_HOST
// (so external artwork fetches don't read as server reachability) // (so external artwork fetches don't read as server reachability)
@@ -82,7 +82,8 @@ object NetworkModule {
okHttp: OkHttpClient, okHttp: OkHttpClient,
json: Json, json: Json,
): Retrofit = ): Retrofit =
Retrofit.Builder() Retrofit
.Builder()
// Placeholder base URL — BaseUrlInterceptor rewrites every // Placeholder base URL — BaseUrlInterceptor rewrites every
// outgoing request to the live AuthStore value, so this // outgoing request to the live AuthStore value, so this
// string only has to satisfy Retrofit's parser and is // string only has to satisfy Retrofit's parser and is
@@ -6,4 +6,6 @@ package com.fabledsword.minstrel.api
* the graph. * the graph.
*/ */
@JvmInline @JvmInline
value class ServerBaseUrl(val value: String) value class ServerBaseUrl(
val value: String,
)
@@ -20,10 +20,14 @@ interface AdminInvitesApi {
suspend fun list(): AdminInvitesListWire suspend fun list(): AdminInvitesListWire
@POST("api/admin/invites") @POST("api/admin/invites")
suspend fun create(@Body body: CreateInviteBody): InviteWire suspend fun create(
@Body body: CreateInviteBody,
): InviteWire
@DELETE("api/admin/invites/{token}") @DELETE("api/admin/invites/{token}")
suspend fun revoke(@Path("token") token: String) suspend fun revoke(
@Path("token") token: String,
)
} }
/** /**
@@ -31,4 +35,6 @@ interface AdminInvitesApi {
* which the server treats the same as an absent field. * which the server treats the same as an absent field.
*/ */
@Serializable @Serializable
data class CreateInviteBody(val note: String? = null) data class CreateInviteBody(
val note: String? = null,
)
@@ -19,11 +19,17 @@ interface AdminQuarantineApi {
suspend fun list(): List<AdminQuarantineItemWire> suspend fun list(): List<AdminQuarantineItemWire>
@POST("api/admin/quarantine/{trackId}/resolve") @POST("api/admin/quarantine/{trackId}/resolve")
suspend fun resolve(@Path("trackId") trackId: String) suspend fun resolve(
@Path("trackId") trackId: String,
)
@POST("api/admin/quarantine/{trackId}/remove-file") @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") @POST("api/admin/quarantine/{trackId}/delete-file")
suspend fun deleteFile(@Path("trackId") trackId: String) suspend fun deleteFile(
@Path("trackId") trackId: String,
)
} }
@@ -23,10 +23,15 @@ interface AdminTagSourcesApi {
suspend fun list(): AdminTagSourcesListWire suspend fun list(): AdminTagSourcesListWire
@PATCH("api/admin/tag-sources/{id}") @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") @POST("api/admin/tag-sources/{id}/test")
suspend fun test(@Path("id") id: String): TestTagSourceWire suspend fun test(
@Path("id") id: String,
): TestTagSourceWire
} }
/** /**
@@ -15,13 +15,21 @@ interface AdminUsersApi {
suspend fun list(): AdminUsersListWire suspend fun list(): AdminUsersListWire
@PUT("api/admin/users/{id}/admin") @PUT("api/admin/users/{id}/admin")
suspend fun setAdmin(@Path("id") id: String, @Body body: SetAdminBody) suspend fun setAdmin(
@Path("id") id: String,
@Body body: SetAdminBody,
)
@POST("api/admin/users/{id}/reset-password") @POST("api/admin/users/{id}/reset-password")
suspend fun resetPassword(@Path("id") id: String, @Body body: ResetPasswordBody) suspend fun resetPassword(
@Path("id") id: String,
@Body body: ResetPasswordBody,
)
@DELETE("api/admin/users/{id}") @DELETE("api/admin/users/{id}")
suspend fun delete(@Path("id") id: String) suspend fun delete(
@Path("id") id: String,
)
} }
@Serializable @Serializable
@@ -30,4 +38,6 @@ data class SetAdminBody(
) )
@Serializable @Serializable
data class ResetPasswordBody(val password: String) data class ResetPasswordBody(
val password: String,
)
@@ -14,7 +14,9 @@ import retrofit2.http.POST
*/ */
interface AuthApi { interface AuthApi {
@POST("api/auth/login") @POST("api/auth/login")
suspend fun login(@Body body: LoginRequestBody): LoginResponseWire suspend fun login(
@Body body: LoginRequestBody,
): LoginResponseWire
@POST("api/auth/logout") @POST("api/auth/logout")
suspend fun logout() suspend fun logout()
@@ -22,7 +22,9 @@ import retrofit2.http.POST
*/ */
interface CastApi { interface CastApi {
@POST("api/cast/stream-token") @POST("api/cast/stream-token")
suspend fun streamToken(@Body req: StreamTokenRequest): StreamTokenResponse suspend fun streamToken(
@Body req: StreamTokenRequest,
): StreamTokenResponse
} }
/** /**
@@ -14,7 +14,9 @@ import retrofit2.http.POST
*/ */
interface DiagnosticsApi { interface DiagnosticsApi {
@POST("api/diagnostics") @POST("api/diagnostics")
suspend fun report(@Body body: DiagnosticsReportRequest) suspend fun report(
@Body body: DiagnosticsReportRequest,
)
} }
@Serializable @Serializable
@@ -17,14 +17,22 @@ import retrofit2.http.POST
*/ */
interface EventsApi { interface EventsApi {
@POST("api/events") @POST("api/events")
suspend fun playStarted(@Body body: PlayStartedRequest): PlayStartedResponse suspend fun playStarted(
@Body body: PlayStartedRequest,
): PlayStartedResponse
@POST("api/events") @POST("api/events")
suspend fun playEnded(@Body body: PlayEndedRequest) suspend fun playEnded(
@Body body: PlayEndedRequest,
)
@POST("api/events") @POST("api/events")
suspend fun playSkipped(@Body body: PlaySkippedRequest) suspend fun playSkipped(
@Body body: PlaySkippedRequest,
)
@POST("api/events") @POST("api/events")
suspend fun playOffline(@Body body: PlayOfflineRequest) suspend fun playOffline(
@Body body: PlayOfflineRequest,
)
} }
@@ -30,13 +30,19 @@ import retrofit2.http.Query
*/ */
interface LibraryApi { interface LibraryApi {
@GET("api/tracks/{id}") @GET("api/tracks/{id}")
suspend fun getTrack(@Path("id") id: String): TrackWire suspend fun getTrack(
@Path("id") id: String,
): TrackWire
@GET("api/artists/{id}") @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") @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") @GET("api/artists/{id}/similar")
suspend fun getSimilarArtists( suspend fun getSimilarArtists(
@@ -51,10 +57,14 @@ interface LibraryApi {
): List<TrackWire> ): List<TrackWire>
@GET("api/albums/{id}") @GET("api/albums/{id}")
suspend fun getAlbumDetail(@Path("id") id: String): AlbumDetailWire suspend fun getAlbumDetail(
@Path("id") id: String,
): AlbumDetailWire
@GET("api/library/shuffle") @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 // Browse axes. Both indexes are unpaged by design: the client needs
// the whole set to render a browsable picker, and even a messy library // the whole set to render a browsable picker, and even a messy library
@@ -20,10 +20,16 @@ import retrofit2.http.Path
*/ */
interface LikesApi { interface LikesApi {
@POST("api/likes/{kind}/{id}") @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}") @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") @GET("api/likes/ids")
suspend fun ids(): LikedIdsWire suspend fun ids(): LikedIdsWire
@@ -27,14 +27,18 @@ interface MeApi {
* state without an extra GET. * state without an extra GET.
*/ */
@PUT("api/me/profile") @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` * Change the caller's password. Server validates `current_password`
* before accepting `new_password`. No body on success (204). * before accepting `new_password`. No body on success (204).
*/ */
@PUT("api/me/password") @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, * Caller's ListenBrainz state — never returns the token itself,
@@ -59,7 +63,9 @@ interface MeApi {
* post-write status so callers refresh without a separate GET. * post-write status so callers refresh without a separate GET.
*/ */
@PUT("api/me/listenbrainz") @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. */ /** The caller's loudness-normalization preference, or the defaults if never set. */
@GET("api/me/normalization") @GET("api/me/normalization")
@@ -67,7 +73,9 @@ interface MeApi {
/** Replaces the whole preference; returns what the server stored. */ /** Replaces the whole preference; returns what the server stored. */
@PUT("api/me/normalization") @PUT("api/me/normalization")
suspend fun putNormalization(@Body body: NormalizationPrefs): NormalizationPrefs suspend fun putNormalization(
@Body body: NormalizationPrefs,
): NormalizationPrefs
} }
/** /**
@@ -15,20 +15,28 @@ import retrofit2.http.Query
*/ */
interface NotificationsApi { interface NotificationsApi {
@GET("api/me/notifications") @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. */ /** 204; 404 when the notice is gone, which a replay treats as done. */
@POST("api/me/notifications/{id}/read") @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") @POST("api/me/notifications/read-all")
suspend fun readAll(@Body body: ReadAllBody) suspend fun readAll(
@Body body: ReadAllBody,
)
@GET("api/me/notification-settings") @GET("api/me/notification-settings")
suspend fun getSettings(): NotificationSettingsWire suspend fun getSettings(): NotificationSettingsWire
@PUT("api/me/notification-settings") @PUT("api/me/notification-settings")
suspend fun putSettings(@Body body: PutNotificationSettingsBody): NotificationSettingsWire suspend fun putSettings(
@Body body: PutNotificationSettingsBody,
): NotificationSettingsWire
} }
@Serializable @Serializable
@@ -55,7 +63,9 @@ data class NotificationsPageWire(
* the app's Json drops default-valued fields. * the app's Json drops default-valued fields.
*/ */
@Serializable @Serializable
data class ReadAllBody(@SerialName("up_to") val upTo: String?) data class ReadAllBody(
@SerialName("up_to") val upTo: String?,
)
@Serializable @Serializable
data class NotificationKindSettingWire( data class NotificationKindSettingWire(
@@ -87,4 +97,6 @@ data class NotificationSettingChangeWire(
) )
@Serializable @Serializable
data class PutNotificationSettingsBody(val kinds: List<NotificationSettingChangeWire>) data class PutNotificationSettingsBody(
val kinds: List<NotificationSettingChangeWire>,
)
@@ -13,7 +13,9 @@ import retrofit2.http.POST
*/ */
interface PlaybackErrorsApi { interface PlaybackErrorsApi {
@POST("api/playback-errors") @POST("api/playback-errors")
suspend fun report(@Body body: PlaybackErrorReportRequest) suspend fun report(
@Body body: PlaybackErrorReportRequest,
)
} }
/** /**
@@ -24,24 +24,35 @@ interface PlaylistsApi {
* playlists (not kind-filtered). * playlists (not kind-filtered).
*/ */
@GET("api/playlists") @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}") @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, * POST /api/playlists — make a playlist under the id the app chose,
* so a create queued offline and sent again finds the same list. * so a create queued offline and sent again finds the same list.
*/ */
@POST("api/playlists") @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} — rename, or make public or private. Null fields stay as they are. */
@PATCH("api/playlists/{id}") @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}") @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 * DELETE /api/playlists/{id}/tracks/{position}. [trackId] is the song
@@ -62,7 +73,10 @@ interface PlaylistsApi {
* changes nothing the second time. * changes nothing the second time.
*/ */
@PUT("api/playlists/{id}/tracks") @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 — append the given track IDs to the owner's playlist. */
@POST("api/playlists/{id}/tracks") @POST("api/playlists/{id}/tracks")
@@ -79,7 +93,9 @@ interface PlaylistsApi {
* pick seed tracks. The kind is the raw system_variant. * pick seed tracks. The kind is the raw system_variant.
*/ */
@POST("api/playlists/system/{kind}/refresh") @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 * GET /api/playlists/system/{kind}/shuffle. Returns
@@ -89,7 +105,9 @@ interface PlaylistsApi {
* the stored order. * the stored order.
*/ */
@GET("api/playlists/system/{kind}/shuffle") @GET("api/playlists/system/{kind}/shuffle")
suspend fun systemShuffle(@Path("kind") variant: String): PlaylistDetailWire suspend fun systemShuffle(
@Path("kind") variant: String,
): PlaylistDetailWire
} }
/** /**
@@ -20,10 +20,14 @@ interface QuarantineApi {
suspend fun listMine(): List<QuarantineMineWire> suspend fun listMine(): List<QuarantineMineWire>
@POST("api/quarantine") @POST("api/quarantine")
suspend fun flag(@Body body: FlagRequest) suspend fun flag(
@Body body: FlagRequest,
)
@DELETE("api/quarantine/{trackId}") @DELETE("api/quarantine/{trackId}")
suspend fun unflag(@Path("trackId") trackId: String) suspend fun unflag(
@Path("trackId") trackId: String,
)
} }
/** /**
@@ -11,5 +11,7 @@ interface ReplayGainApi {
* missing from `items` has not been measured yet. * missing from `items` has not been measured yet.
*/ */
@GET("api/tracks/replay-gain") @GET("api/tracks/replay-gain")
suspend fun getReplayGain(@Query("ids") ids: String): ReplayGainResponseWire suspend fun getReplayGain(
@Query("ids") ids: String,
): ReplayGainResponseWire
} }
@@ -19,5 +19,7 @@ import retrofit2.http.Query
*/ */
interface SyncApi { interface SyncApi {
@GET("api/library/sync") @GET("api/library/sync")
suspend fun sync(@Query("since") since: Long): Response<SyncResponseWire> suspend fun sync(
@Query("since") since: Long,
): Response<SyncResponseWire>
} }
@@ -29,114 +29,124 @@ import javax.inject.Singleton
* username after a fresh app launch without re-prompting. * username after a fresh app launch without re-prompting.
*/ */
@Singleton @Singleton
class AuthController @Inject constructor( class AuthController
private val authStore: AuthStore, @Inject
private val json: Json, constructor(
@ApplicationScope private val scope: CoroutineScope, private val authStore: AuthStore,
retrofit: Retrofit, private val json: Json,
) { @ApplicationScope private val scope: CoroutineScope,
private val api: AuthApi = retrofit.create() retrofit: Retrofit,
private val meApi: MeApi = retrofit.create() ) {
private val api: AuthApi = retrofit.create()
private val meApi: MeApi = retrofit.create()
private val currentUserState = MutableStateFlow<UserRef?>(null) private val currentUserState = MutableStateFlow<UserRef?>(null)
val currentUser: StateFlow<UserRef?> = currentUserState.asStateFlow() val currentUser: StateFlow<UserRef?> = currentUserState.asStateFlow()
val sessionCookie: StateFlow<String?> get() = authStore.sessionCookie val sessionCookie: StateFlow<String?> get() = authStore.sessionCookie
val isSignedIn: Boolean val isSignedIn: Boolean
get() = !authStore.sessionCookie.value.isNullOrEmpty() get() = !authStore.sessionCookie.value.isNullOrEmpty()
init { init {
// Rehydrate currentUser whenever the persisted userJson emits // Rehydrate currentUser whenever the persisted userJson emits
// (cold start with a saved cookie OR explicit sign-in/out // (cold start with a saved cookie OR explicit sign-in/out
// writing through AuthStore). Decode failures collapse to null // writing through AuthStore). Decode failures collapse to null
// so a malformed row can't crash the app — worst case is a // so a malformed row can't crash the app — worst case is a
// blank username until the next sign-in writes a valid value. // blank username until the next sign-in writes a valid value.
scope.launch { scope.launch {
authStore.userJson.collect { raw -> authStore.userJson.collect { raw ->
currentUserState.value = raw?.let { decodeUser(it) } 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() }
} }
// 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 * Submit credentials. On success the AuthCookieInterceptor will
* have captured the Set-Cookie before this method returns; the * have captured the Set-Cookie before this method returns; the
* caller can safely navigate to the in-shell graph. Throws on * caller can safely navigate to the in-shell graph. Throws on
* any non-2xx response (caller surfaces in UI). * any non-2xx response (caller surfaces in UI).
*/ */
suspend fun signIn(username: String, password: String): UserRef { suspend fun signIn(
val response = api.login(LoginRequestBody(username = username, password = password)) username: String,
val user = UserRef( password: String,
id = response.user.id, ): UserRef {
username = response.user.username, val response = api.login(LoginRequestBody(username = username, password = password))
isAdmin = response.user.isAdmin, val user =
) UserRef(
currentUserState.value = user id = response.user.id,
authStore.setUserJson(json.encodeToString(UserRef.serializer(), user)) username = response.user.username,
// Pull the fuller /me shape (carries debug_mode_enabled) right isAdmin = response.user.isAdmin,
// after login so the diagnostics gate is correct without waiting )
// for the next startup refresh. currentUserState.value = user
scope.launch { refreshProfile() } authStore.setUserJson(json.encodeToString(UserRef.serializer(), user))
return 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 * Re-fetch the caller's profile from /api/me and update currentUser
* + persisted userJson. Carries account-level flags (debug mode) * + persisted userJson. Carries account-level flags (debug mode)
* that aren't in the login response. Best-effort: a network failure * that aren't in the login response. Best-effort: a network failure
* leaves the cached identity untouched. No-op when signed out. * leaves the cached identity untouched. No-op when signed out.
* Waits for the stored login to load first: at launch this runs before * 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. * it has, and would otherwise read the user as signed out and skip.
*/ */
suspend fun refreshProfile() { suspend fun refreshProfile() {
authStore.awaitSessionHydrated() authStore.awaitSessionHydrated()
if (!isSignedIn) return if (!isSignedIn) return
val p = runCatching { meApi.getProfile() }.getOrNull() ?: return val p = runCatching { meApi.getProfile() }.getOrNull() ?: return
val user = UserRef( val user =
id = p.id, UserRef(
username = p.username, id = p.id,
isAdmin = p.isAdmin, username = p.username,
debugModeEnabled = p.debugModeEnabled, isAdmin = p.isAdmin,
) debugModeEnabled = p.debugModeEnabled,
currentUserState.value = user )
authStore.setUserJson(json.encodeToString(UserRef.serializer(), user)) currentUserState.value = user
} authStore.setUserJson(json.encodeToString(UserRef.serializer(), user))
}
/** /**
* Signs out here at once and ends the session on the server too. * Signs out here at once and ends the session on the server too.
* *
* The app shows signed-out straight away, then calls * The app shows signed-out straight away, then calls
* `/api/auth/logout` while the session cookie is still set: the cookie * `/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 * 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 * before the cookie is cleared. The call waits at most
* [LOGOUT_TIMEOUT_MS]; offline, or on an error, the cookie is cleared * [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 * 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 * application scope, so the screen that asked closing as the app shows
* signed-out can't cancel it halfway. * signed-out can't cancel it halfway.
*/ */
suspend fun signOut() { suspend fun signOut() {
currentUserState.value = null currentUserState.value = null
authStore.setUserJson(null) authStore.setUserJson(null)
scope.launch { scope
try { .launch {
withTimeoutOrNull(LOGOUT_TIMEOUT_MS) { runCatching { api.logout() } } try {
} finally { withTimeoutOrNull(LOGOUT_TIMEOUT_MS) { runCatching { api.logout() } }
authStore.setSessionCookie(null) } finally {
} authStore.setSessionCookie(null)
}.join() }
} }.join()
}
private fun decodeUser(raw: String): UserRef? = private fun decodeUser(raw: String): UserRef? =
runCatching { json.decodeFromString(UserRef.serializer(), raw) }.getOrNull() runCatching {
json.decodeFromString(UserRef.serializer(), raw)
}.getOrNull()
private companion object { private companion object {
// Long enough for a logout on a slow connection, short enough that // Long enough for a logout on a slow connection, short enough that
// signing out offline doesn't seem to hang. // signing out offline doesn't seem to hang.
const val LOGOUT_TIMEOUT_MS = 5_000L const val LOGOUT_TIMEOUT_MS = 5_000L
}
} }
}
@@ -21,6 +21,14 @@ import timber.log.Timber
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton 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. * Holds the user's session cookie and configured server base URL.
* *
@@ -44,353 +52,352 @@ import javax.inject.Singleton
* [awaitSessionHydrated] lets a caller that needs a definitive answer * [awaitSessionHydrated] lets a caller that needs a definitive answer
* (the auth gate) wait for this. * (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") @Suppress("TooManyFunctions")
@Singleton @Singleton
class AuthStore @Inject constructor( class AuthStore
private val dao: AuthSessionDao, @Inject
private val vault: SessionVault, constructor(
@ApplicationScope private val scope: CoroutineScope, private val dao: AuthSessionDao,
) { private val vault: SessionVault,
private val sessionCookieState = MutableStateFlow<String?>(null) @ApplicationScope private val scope: CoroutineScope,
val sessionCookie: StateFlow<String?> = sessionCookieState.asStateFlow() ) {
private val sessionCookieState = MutableStateFlow<String?>(null)
val sessionCookie: StateFlow<String?> = sessionCookieState.asStateFlow()
private val baseUrlState = MutableStateFlow(DEFAULT_BASE_URL) private val baseUrlState = MutableStateFlow(DEFAULT_BASE_URL)
val baseUrl: StateFlow<String> = baseUrlState.asStateFlow() val baseUrl: StateFlow<String> = baseUrlState.asStateFlow()
private val userJsonState = MutableStateFlow<String?>(null) private val userJsonState = MutableStateFlow<String?>(null)
val userJson: StateFlow<String?> = userJsonState.asStateFlow() val userJson: StateFlow<String?> = userJsonState.asStateFlow()
private val themeModeState = MutableStateFlow<String?>(null) private val themeModeState = MutableStateFlow<String?>(null)
val themeMode: StateFlow<String?> = themeModeState.asStateFlow() val themeMode: StateFlow<String?> = themeModeState.asStateFlow()
private val clientIdState = MutableStateFlow<String?>(null) private val clientIdState = MutableStateFlow<String?>(null)
val clientId: StateFlow<String?> = clientIdState.asStateFlow() val clientId: StateFlow<String?> = clientIdState.asStateFlow()
private val cacheSettingsState = MutableStateFlow(CacheSettings.DEFAULT) private val cacheSettingsState = MutableStateFlow(CacheSettings.DEFAULT)
val cacheSettings: StateFlow<CacheSettings> = cacheSettingsState.asStateFlow() val cacheSettings: StateFlow<CacheSettings> = cacheSettingsState.asStateFlow()
private val diagnosticsOptOutState = MutableStateFlow(false) private val diagnosticsOptOutState = MutableStateFlow(false)
val diagnosticsOptOut: StateFlow<Boolean> = diagnosticsOptOutState.asStateFlow() val diagnosticsOptOut: StateFlow<Boolean> = diagnosticsOptOutState.asStateFlow()
private val normalizationState = MutableStateFlow(NormalizationPrefs.DEFAULT) private val normalizationState = MutableStateFlow(NormalizationPrefs.DEFAULT)
val normalization: StateFlow<NormalizationPrefs> = normalizationState.asStateFlow() val normalization: StateFlow<NormalizationPrefs> = normalizationState.asStateFlow()
// Background delivery: the device's choice, on by default. // Background delivery: the device's choice, on by default.
// The shade's high-water mark lives in the same row but is read and // 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. // written through the DAO by NotificationSync, awaited, never cached here.
private val backgroundDeliveryState = MutableStateFlow(true) private val backgroundDeliveryState = MutableStateFlow(true)
val backgroundDelivery: StateFlow<Boolean> = backgroundDeliveryState.asStateFlow() val backgroundDelivery: StateFlow<Boolean> = backgroundDeliveryState.asStateFlow()
// The account the cached data belongs to (AuthSessionEntity.cacheOwnerUserId). // The account the cached data belongs to (AuthSessionEntity.cacheOwnerUserId).
// Null while the stored row is still loading, and before any account // Null while the stored row is still loading, and before any account
// has been adopted; [settingsLoaded] tells the two apart. // has been adopted; [settingsLoaded] tells the two apart.
private val cacheOwnerState = MutableStateFlow<String?>(null) private val cacheOwnerState = MutableStateFlow<String?>(null)
val cacheOwnerUserId: StateFlow<String?> = cacheOwnerState.asStateFlow() 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. */ /** True once the stored settings row has been read at least once. */
val settingsLoaded: StateFlow<Boolean> = settingsLoadedState.asStateFlow() val settingsLoaded: StateFlow<Boolean> = settingsLoadedState.asStateFlow()
private val json = Json { ignoreUnknownKeys = true } private val json = Json { ignoreUnknownKeys = true }
// Serialises every cookie persist with the one-time hydration, so a // Serialises every cookie persist with the one-time hydration, so a
// sign-in or a 401 that lands while hydration runs is never overwritten // sign-in or a 401 that lands while hydration runs is never overwritten
// by the stale value hydration read. // by the stale value hydration read.
private val cookieLock = Mutex() private val cookieLock = Mutex()
// Set by setSessionCookie. Once something has written the cookie this // Set by setSessionCookie. Once something has written the cookie this
// process, that value wins over whatever hydration finds on disk. // process, that value wins over whatever hydration finds on disk.
@Volatile private var cookieTouched = false @Volatile private var cookieTouched = false
private val cookieHydration: Deferred<Unit> = scope.async { hydrateSessionCookie() } private val cookieHydration: Deferred<Unit> = scope.async { hydrateSessionCookie() }
init { init {
scope.launch { scope.launch {
dao.observe().collect { row -> dao.observe().collect { row ->
baseUrlState.value = row?.baseUrl ?: DEFAULT_BASE_URL baseUrlState.value = row?.baseUrl ?: DEFAULT_BASE_URL
userJsonState.value = row?.userJson userJsonState.value = row?.userJson
themeModeState.value = row?.themeMode themeModeState.value = row?.themeMode
clientIdState.value = row?.clientId clientIdState.value = row?.clientId
cacheSettingsState.value = decodeCacheSettings(row?.cacheSettingsJson) cacheSettingsState.value = decodeCacheSettings(row?.cacheSettingsJson)
diagnosticsOptOutState.value = row?.diagnosticsOptOut ?: false diagnosticsOptOutState.value = row?.diagnosticsOptOut ?: false
normalizationState.value = decodeNormalization(row?.normalizationJson) normalizationState.value = decodeNormalization(row?.normalizationJson)
backgroundDeliveryState.value = row?.backgroundDelivery ?: true backgroundDeliveryState.value = row?.backgroundDelivery ?: true
cacheOwnerState.value = row?.cacheOwnerUserId cacheOwnerState.value = row?.cacheOwnerUserId
settingsLoadedState.value = true settingsLoadedState.value = true
}
} }
} }
}
private fun decodeCacheSettings(raw: String?): CacheSettings { private fun decodeCacheSettings(raw: String?): CacheSettings {
if (raw.isNullOrEmpty()) return CacheSettings.DEFAULT if (raw.isNullOrEmpty()) return CacheSettings.DEFAULT
return runCatching { return runCatching {
json.decodeFromString(CacheSettings.serializer(), raw) json.decodeFromString(CacheSettings.serializer(), raw)
}.getOrDefault(CacheSettings.DEFAULT) }.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
}
/** private fun decodeNormalization(raw: String?): NormalizationPrefs {
* True once the server has refused the current session (see if (raw.isNullOrEmpty()) return NormalizationPrefs.DEFAULT
* [dropRejectedSessionCookie]) and the UI has not yet sent the user to return runCatching {
* sign in. Held rather than fired, so a refusal that lands while the app json.decodeFromString(NormalizationPrefs.serializer(), raw)
* is in the background is still acted on when it comes back. A sign-out }.getOrDefault(NormalizationPrefs.DEFAULT)
* 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. * Suspends until the stored session cookie has been loaded into
private suspend fun storeCookie(value: String?) { * [sessionCookie], or [HYDRATION_DEADLINE_MS] passes, so a wedged
if (vault.write(value)) { * Keystore cannot leave the start screen spinning. Returns false on
if (dao.get()?.sessionCookie != null) dao.setSessionCookie(null) * the deadline; the caller then decides from whatever has loaded, and a
} else { * late hydration still lands in [sessionCookie].
persistLegacyCookie(value) */
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 setBaseUrl(value: String) { fun setSessionCookie(value: String?) {
baseUrlState.value = value cookieTouched = true
scope.launch { persistBaseUrl(value) } sessionCookieState.value = value
} scope.launch { cookieLock.withLock { storeCookie(value) } }
}
fun setUserJson(value: String?) { /**
userJsonState.value = value * The cookie to attach to an outgoing request. Blocks the calling
scope.launch { persistUserJson(value) } * (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
}
fun setThemeMode(value: String?) { /**
themeModeState.value = value * True once the server has refused the current session (see
scope.launch { persistThemeMode(value) } * [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()
fun setClientId(value: String?) { /** The UI has opened the sign-in screen for a refused session. */
clientIdState.value = value fun consumeSessionRejected() {
scope.launch { persistClientId(value) } sessionRejectedState.value = false
} }
fun setCacheSettings(value: CacheSettings) { /**
cacheSettingsState.value = value * Signs out because the server answered 401 to a request that carried
val encoded = json.encodeToString(CacheSettings.serializer(), value) * [rejected]. Does nothing when the store has since moved on to another
scope.launch { persistCacheSettings(encoded) } * 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
}
fun setDiagnosticsOptOut(value: Boolean) { private suspend fun hydrateSessionCookie() =
diagnosticsOptOutState.value = value cookieLock.withLock {
scope.launch { persistDiagnosticsOptOut(value) } 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
}
fun setNormalization(value: NormalizationPrefs) { // Vault first; the Room row only when the Keystore is unusable, so a
normalizationState.value = value // broken Keystore degrades to the old storage rather than a sign-out.
val encoded = json.encodeToString(NormalizationPrefs.serializer(), value) private suspend fun storeCookie(value: String?) {
scope.launch { persistNormalization(encoded) } if (vault.write(value)) {
} if (dao.get()?.sessionCookie != null) dao.setSessionCookie(null)
fun setBackgroundDelivery(value: Boolean) {
backgroundDeliveryState.value = value
scope.launch {
if (dao.get() == null) {
dao.upsert(currentEntity().copy(backgroundDelivery = value))
} else { } else {
dao.setBackgroundDelivery(value) persistLegacyCookie(value)
} }
} }
}
/** fun setBaseUrl(value: String) {
* Records which account the cached data now belongs to. Suspends until baseUrlState.value = value
* it is stored, so a caller that has just cleared the old account's scope.launch { persistBaseUrl(value) }
* data can't have the adoption lost to a crash in between. }
*/
suspend fun setCacheOwnerUserId(value: String?) { fun setUserJson(value: String?) {
cacheOwnerState.value = value userJsonState.value = value
if (dao.get() == null) { scope.launch { persistUserJson(value) }
dao.upsert(currentEntity().copy(cacheOwnerUserId = value)) }
} else {
dao.setCacheOwnerUserId(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
} }
} }
/** 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,21 +35,30 @@ import kotlin.coroutines.resumeWithException
* Plain http still passes through [com.fabledsword.minstrel.api.CleartextGuardInterceptor] * Plain http still passes through [com.fabledsword.minstrel.api.CleartextGuardInterceptor]
* on [client], so the fallback can only succeed on a home-network address. * on [client], so the fallback can only succeed on a home-network address.
*/ */
class ServerProbe internal constructor(client: OkHttpClient, callTimeoutMillis: Long) { class ServerProbe internal constructor(
client: OkHttpClient,
callTimeoutMillis: Long,
) {
// Each attempt is short: a probe that stalls holds the sign-in screen. // Each attempt is short: a probe that stalls holds the sign-in screen.
@Inject constructor(client: OkHttpClient) : this(client, CALL_TIMEOUT_MILLIS) @Inject
constructor(client: OkHttpClient) : this(client, CALL_TIMEOUT_MILLIS)
private val client: OkHttpClient = client.newBuilder() private val client: OkHttpClient =
.connectTimeout(callTimeoutMillis, TimeUnit.MILLISECONDS) client
.callTimeout(callTimeoutMillis, TimeUnit.MILLISECONDS) .newBuilder()
.build() .connectTimeout(callTimeoutMillis, TimeUnit.MILLISECONDS)
.callTimeout(callTimeoutMillis, TimeUnit.MILLISECONDS)
.build()
sealed interface Result { sealed interface Result {
/** Minstrel answered at [baseUrl], which includes its scheme. */ /** 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 { suspend fun find(input: String): Result {
@@ -100,21 +109,28 @@ class ServerProbe internal constructor(client: OkHttpClient, callTimeoutMillis:
data object Minstrel : Outcome data object Minstrel : Outcome
/** Nothing answered: the next scheme may be tried. */ /** 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. */ /** 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 { private suspend fun attempt(baseUrl: String): Outcome {
val url = "$baseUrl$SETUP_STATUS_PATH".toHttpUrlOrNull() val url =
?: return Outcome.Stop("That doesn't look like a server address.") "$baseUrl$SETUP_STATUS_PATH".toHttpUrlOrNull()
val request = Request.Builder() ?: return Outcome.Stop("That doesn't look like a server address.")
.url(url) val request =
// Lets CleartextGuardInterceptor treat the probe as a Minstrel Request
// server request, as it treats sign-in. .Builder()
.tag(MinstrelServerRequest::class.java, MinstrelServerRequest) .url(url)
.build() // Lets CleartextGuardInterceptor treat the probe as a Minstrel
// server request, as it treats sign-in.
.tag(MinstrelServerRequest::class.java, MinstrelServerRequest)
.build()
return try { return try {
client.newCall(request).await().use { response -> client.newCall(request).await().use { response ->
if (isMinstrel(response)) { if (isMinstrel(response)) {
@@ -123,9 +139,13 @@ class ServerProbe internal constructor(client: OkHttpClient, callTimeoutMillis:
Outcome.Stop("A server answered at $baseUrl, but it isn't Minstrel.") 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) Outcome.Unreachable(publicCleartext = true)
} catch (@Suppress("SwallowedException") e: UnknownHostException) { } catch (
@Suppress("SwallowedException") e: UnknownHostException,
) {
Outcome.Stop("Couldn't find a server named ${url.host}.") Outcome.Stop("Couldn't find a server named ${url.host}.")
} catch (e: IOException) { } catch (e: IOException) {
if (isCertificateFailure(e)) { if (isCertificateFailure(e)) {
@@ -151,21 +171,43 @@ class ServerProbe internal constructor(client: OkHttpClient, callTimeoutMillis:
// (hostname) or as an SSLHandshakeException caused by a // (hostname) or as an SSLHandshakeException caused by a
// CertificateException or CertPathValidatorException (trust). A port // CertificateException or CertPathValidatorException (trust). A port
// with no TLS fails the handshake too, but with no such cause. // with no TLS fails the handshake too, but with no such cause.
private fun isCertificateFailure(e: IOException): Boolean = //
generateSequence<Throwable>(e) { it.cause } // OkHttp tries a host's addresses in parallel (fast fallback). When
.take(MAX_CAUSE_DEPTH) // all of them fail it throws one failure and attaches the rest as
.any { it is SSLPeerUnverifiedException || it is GeneralSecurityException } // 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 suspend fun Call.await(): Response = private suspend fun Call.await(): Response =
suspendCancellableCoroutine { continuation -> suspendCancellableCoroutine { continuation ->
continuation.invokeOnCancellation { cancel() } continuation.invokeOnCancellation { cancel() }
enqueue( enqueue(
object : Callback { 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() 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) if (continuation.isActive) continuation.resumeWithException(e)
} }
}, },
@@ -175,6 +217,6 @@ class ServerProbe internal constructor(client: OkHttpClient, callTimeoutMillis:
private companion object { private companion object {
const val SETUP_STATUS_PATH = "/api/auth/setup-status" const val SETUP_STATUS_PATH = "/api/auth/setup-status"
const val CALL_TIMEOUT_MILLIS = 8_000L const val CALL_TIMEOUT_MILLIS = 8_000L
const val MAX_CAUSE_DEPTH = 8 const val MAX_EXCEPTIONS_SEARCHED = 16
} }
} }
@@ -54,7 +54,10 @@ internal object SealedBox {
// under the same key will not open as a session cookie. // under the same key will not open as a session cookie.
private val AAD = "minstrel-session-cookie-v1".toByteArray(Charsets.UTF_8) 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) val cipher = Cipher.getInstance(TRANSFORMATION)
// No IV passed: the provider generates a fresh random one. Keystore // No IV passed: the provider generates a fresh random one. Keystore
// keys refuse a caller-chosen IV for encryption by default. // keys refuse a caller-chosen IV for encryption by default.
@@ -64,7 +67,10 @@ internal object SealedBox {
return Base64.getEncoder().encodeToString(sealed) 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) val bytes = Base64.getDecoder().decode(sealed)
require(bytes.size > IV_BYTES) { "sealed value too short" } require(bytes.size > IV_BYTES) { "sealed value too short" }
val cipher = Cipher.getInstance(TRANSFORMATION) val cipher = Cipher.getInstance(TRANSFORMATION)
@@ -85,58 +91,60 @@ internal object SealedBox {
* credential that no longer verifies. * credential that no longer verifies.
*/ */
@Singleton @Singleton
class KeystoreSessionVault @Inject constructor( class KeystoreSessionVault
@ApplicationContext context: Context, @Inject
) : SessionVault { constructor(
private val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) @ApplicationContext context: Context,
) : SessionVault {
private val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
override fun read(): String? { override fun read(): String? {
val sealed = prefs.getString(KEY_COOKIE, null) ?: return null val sealed = prefs.getString(KEY_COOKIE, null) ?: return null
return runCatching { SealedBox.open(key(), sealed) } return runCatching { SealedBox.open(key(), sealed) }
.onFailure { .onFailure {
Timber.w(it, "session vault: stored cookie would not decrypt; discarding it") Timber.w(it, "session vault: stored cookie would not decrypt; discarding it")
prefs.edit().remove(KEY_COOKIE).commit() prefs.edit().remove(KEY_COOKIE).commit()
} }.getOrNull()
.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 { override fun write(value: String?): Boolean =
val keyStore = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) } runCatching {
(keyStore.getKey(KEY_ALIAS, null) as? SecretKey)?.let { return it } val editor = prefs.edit()
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE) if (value == null) {
generator.init( editor.remove(KEY_COOKIE)
KeyGenParameterSpec.Builder( } else {
KEY_ALIAS, editor.putString(KEY_COOKIE, SealedBox.seal(key(), value))
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT, }
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(),
) )
.setBlockModes(KeyProperties.BLOCK_MODE_GCM) return generator.generateKey()
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) }
.setKeySize(KEY_BITS)
.build(),
)
return generator.generateKey()
}
private companion object { private companion object {
const val ANDROID_KEYSTORE = "AndroidKeyStore" const val ANDROID_KEYSTORE = "AndroidKeyStore"
const val KEY_ALIAS = "minstrel_session_cookie" const val KEY_ALIAS = "minstrel_session_cookie"
const val KEY_BITS = 256 const val KEY_BITS = 256
const val PREFS_NAME = "session_vault" const val PREFS_NAME = "session_vault"
const val KEY_COOKIE = "sealed_cookie" const val KEY_COOKIE = "sealed_cookie"
}
} }
}
@Module @Module
@InstallIn(SingletonComponent::class) @InstallIn(SingletonComponent::class)
@@ -30,34 +30,36 @@ import javax.inject.Inject
* and then exactly one resolved value. * and then exactly one resolved value.
*/ */
@HiltViewModel @HiltViewModel
class AuthGateViewModel @Inject constructor( class AuthGateViewModel
private val dao: AuthSessionDao, @Inject
private val authStore: AuthStore, constructor(
) : ViewModel() { private val dao: AuthSessionDao,
private val authStore: AuthStore,
) : ViewModel() {
private val internal = MutableStateFlow<Any?>(null)
val startDestination: StateFlow<Any?> = internal.asStateFlow()
private val internal = MutableStateFlow<Any?>(null) /**
val startDestination: StateFlow<Any?> = internal.asStateFlow() * True when the server has ended the session while the app was in use;
* the root NavHost answers by opening the sign-in screen, then calls
* [consumeSessionRejected].
*/
val sessionRejected: StateFlow<Boolean> = authStore.sessionRejected
/** fun consumeSessionRejected() = authStore.consumeSessionRejected()
* True when the server has ended the session while the app was in use;
* the root NavHost answers by opening the sign-in screen, then calls
* [consumeSessionRejected].
*/
val sessionRejected: StateFlow<Boolean> = authStore.sessionRejected
fun consumeSessionRejected() = authStore.consumeSessionRejected() init {
viewModelScope.launch {
init { authStore.awaitSessionHydrated()
viewModelScope.launch { val signedIn = !authStore.sessionCookie.value.isNullOrEmpty()
authStore.awaitSessionHydrated() val row = dao.get()
val signedIn = !authStore.sessionCookie.value.isNullOrEmpty() internal.value =
val row = dao.get() when {
internal.value = when { row == null -> ServerUrl
row == null -> ServerUrl row.baseUrl == AuthStore.DEFAULT_BASE_URL && !signedIn -> ServerUrl
row.baseUrl == AuthStore.DEFAULT_BASE_URL && !signedIn -> ServerUrl !signedIn -> Login
!signedIn -> Login else -> Home
else -> Home }
} }
} }
} }
}
@@ -71,9 +71,10 @@ private fun LoginForm(
onChangeServerUrl: () -> Unit, onChangeServerUrl: () -> Unit,
) { ) {
Column( Column(
modifier = Modifier modifier =
.fillMaxSize() Modifier
.padding(24.dp), .fillMaxSize()
.padding(24.dp),
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically), verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
horizontalAlignment = Alignment.CenterHorizontally, horizontalAlignment = Alignment.CenterHorizontally,
) { ) {
@@ -89,10 +90,11 @@ private fun LoginForm(
label = { Text("Username") }, label = { Text("Username") },
singleLine = true, singleLine = true,
enabled = !state.isSubmitting, enabled = !state.isSubmitting,
keyboardOptions = KeyboardOptions( keyboardOptions =
keyboardType = KeyboardType.Email, KeyboardOptions(
imeAction = ImeAction.Next, keyboardType = KeyboardType.Email,
), imeAction = ImeAction.Next,
),
) )
OutlinedTextField( OutlinedTextField(
value = state.password, value = state.password,
@@ -102,10 +104,11 @@ private fun LoginForm(
singleLine = true, singleLine = true,
enabled = !state.isSubmitting, enabled = !state.isSubmitting,
visualTransformation = PasswordVisualTransformation(), visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions( keyboardOptions =
keyboardType = KeyboardType.Password, KeyboardOptions(
imeAction = ImeAction.Done, keyboardType = KeyboardType.Password,
), imeAction = ImeAction.Done,
),
keyboardActions = KeyboardActions(onDone = { onSubmit() }), keyboardActions = KeyboardActions(onDone = { onSubmit() }),
) )
if (state.errorMessage != null) { if (state.errorMessage != null) {
@@ -126,12 +129,16 @@ private fun LoginForm(
} }
@Composable @Composable
private fun SubmitButton(state: LoginFormState, onSubmit: () -> Unit) { private fun SubmitButton(
state: LoginFormState,
onSubmit: () -> Unit,
) {
Button( Button(
onClick = onSubmit, onClick = onSubmit,
enabled = !state.isSubmitting && enabled =
state.username.isNotBlank() && !state.isSubmitting &&
state.password.isNotBlank(), state.username.isNotBlank() &&
state.password.isNotBlank(),
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
) { ) {
if (state.isSubmitting) { if (state.isSubmitting) {
@@ -21,44 +21,45 @@ data class LoginFormState(
) )
@HiltViewModel @HiltViewModel
class LoginViewModel @Inject constructor( class LoginViewModel
private val auth: AuthController, @Inject
) : ViewModel() { constructor(
private val auth: AuthController,
) : ViewModel() {
private val internal = MutableStateFlow(LoginFormState())
val state: StateFlow<LoginFormState> = internal.asStateFlow()
private val internal = MutableStateFlow(LoginFormState()) fun setUsername(value: String) {
val state: StateFlow<LoginFormState> = internal.asStateFlow() internal.update { it.copy(username = value, errorMessage = null) }
}
fun setUsername(value: String) { fun setPassword(value: String) {
internal.update { it.copy(username = value, errorMessage = null) } internal.update { it.copy(password = value, errorMessage = null) }
} }
fun setPassword(value: String) { fun submit() {
internal.update { it.copy(password = value, errorMessage = null) } val s = internal.value
} if (s.username.isBlank() || s.password.isBlank() || s.isSubmitting) return
viewModelScope.launch {
fun submit() { internal.update { it.copy(isSubmitting = true, errorMessage = null) }
val s = internal.value try {
if (s.username.isBlank() || s.password.isBlank() || s.isSubmitting) return auth.signIn(s.username, s.password)
viewModelScope.launch { internal.update { it.copy(isSubmitting = false, signedIn = true) }
internal.update { it.copy(isSubmitting = true, errorMessage = null) } } catch (
try { @Suppress("TooGenericExceptionCaught") e: Throwable,
auth.signIn(s.username, s.password) ) {
internal.update { it.copy(isSubmitting = false, signedIn = true) } internal.update {
} catch ( it.copy(
@Suppress("TooGenericExceptionCaught") e: Throwable, isSubmitting = false,
) { errorMessage = ErrorCopy.fromThrowable(e),
internal.update { )
it.copy( }
isSubmitting = false,
errorMessage = ErrorCopy.fromThrowable(e),
)
} }
} }
} }
}
/** Called after the navigation away from /login completes. */ /** Called after the navigation away from /login completes. */
fun consumeSignedIn() { fun consumeSignedIn() {
internal.update { it.copy(signedIn = false) } internal.update { it.copy(signedIn = false) }
}
} }
}
@@ -51,64 +51,68 @@ data class ServerUrlFormState(
) )
@HiltViewModel @HiltViewModel
class ServerUrlViewModel @Inject constructor( class ServerUrlViewModel
private val authStore: AuthStore, @Inject
private val probe: ServerProbe, constructor(
) : ViewModel() { 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()
private val internal = MutableStateFlow( private var probeJob: Job? = null
// 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()
private var probeJob: Job? = null fun setUrl(value: String) {
internal.update { it.copy(url = value, errorMessage = null) }
}
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.
/** */
* Looks for Minstrel at the typed address ([ServerProbe]) and saves the fun submit() {
* full URL that answered, scheme included, so every caller of if (internal.value.probing) return
* [AuthStore.baseUrl] still receives a complete URL. val typed = internal.value.url
*/ probeJob =
fun submit() { viewModelScope.launch {
if (internal.value.probing) return internal.update { it.copy(probing = true, errorMessage = null) }
val typed = internal.value.url when (val result = probe.find(typed)) {
probeJob = viewModelScope.launch { is ServerProbe.Result.Found -> {
internal.update { it.copy(probing = true, errorMessage = null) } authStore.setBaseUrl(result.baseUrl)
when (val result = probe.find(typed)) { internal.update { it.copy(probing = false, saved = true) }
is ServerProbe.Result.Found -> { }
authStore.setBaseUrl(result.baseUrl) is ServerProbe.Result.Failed ->
internal.update { it.copy(probing = false, saved = true) } internal.update { it.copy(probing = false, errorMessage = result.message) }
}
} }
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) }
} }
} }
fun cancelProbe() {
probeJob?.cancel()
probeJob = null
internal.update { it.copy(probing = false) }
}
fun consumeSaved() {
internal.update { it.copy(saved = false) }
}
}
// ─── Screen ─────────────────────────────────────────────────────────── // ─── Screen ───────────────────────────────────────────────────────────
@Composable @Composable
@@ -149,9 +153,10 @@ private fun ServerUrlForm(
onCancel: () -> Unit, onCancel: () -> Unit,
) { ) {
Column( Column(
modifier = Modifier modifier =
.fillMaxSize() Modifier
.padding(24.dp), .fillMaxSize()
.padding(24.dp),
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically), verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
horizontalAlignment = Alignment.CenterHorizontally, horizontalAlignment = Alignment.CenterHorizontally,
) { ) {
@@ -176,10 +181,11 @@ private fun ServerUrlForm(
}, },
singleLine = true, singleLine = true,
enabled = !state.probing, enabled = !state.probing,
keyboardOptions = KeyboardOptions( keyboardOptions =
keyboardType = KeyboardType.Uri, KeyboardOptions(
imeAction = ImeAction.Done, keyboardType = KeyboardType.Uri,
), imeAction = ImeAction.Done,
),
keyboardActions = KeyboardActions(onDone = { onSubmit() }), keyboardActions = KeyboardActions(onDone = { onSubmit() }),
) )
if (state.errorMessage != null) { if (state.errorMessage != null) {
@@ -31,34 +31,36 @@ import javax.inject.Singleton
* the construct-the-singleton trick in `MinstrelApplication`. * the construct-the-singleton trick in `MinstrelApplication`.
*/ */
@Singleton @Singleton
class CacheIndexer @Inject constructor( class CacheIndexer
playerController: PlayerController, @Inject
private val dao: AudioCacheIndexDao, constructor(
@ApplicationScope private val scope: CoroutineScope, playerController: PlayerController,
) { private val dao: AudioCacheIndexDao,
init { @ApplicationScope private val scope: CoroutineScope,
scope.launch { ) {
playerController.uiState init {
.map { it.currentTrack } scope.launch {
.distinctUntilChanged { a, b -> a?.id == b?.id } playerController.uiState
.collect { track -> if (track != null) record(track) } .map { it.currentTrack }
.distinctUntilChanged { a, b -> a?.id == b?.id }
.collect { track -> if (track != null) record(track) }
}
} }
}
private suspend fun record(track: TrackRef) { private suspend fun record(track: TrackRef) {
val now = Clock.System.now() val now = Clock.System.now()
if (dao.get(track.id) != null) { if (dao.get(track.id) != null) {
dao.touchLastPlayed(track.id, now) dao.touchLastPlayed(track.id, now)
} else { } else {
dao.upsert( dao.upsert(
AudioCacheIndexEntity( AudioCacheIndexEntity(
trackId = track.id, trackId = track.id,
path = track.streamUrl, path = track.streamUrl,
sizeBytes = 0, sizeBytes = 0,
lastPlayedAt = now, lastPlayedAt = now,
source = CacheSource.INCIDENTAL, source = CacheSource.INCIDENTAL,
), ),
) )
}
} }
} }
}
@@ -33,28 +33,30 @@ import javax.inject.Singleton
* library is opened offline with no active playback. * library is opened offline with no active playback.
*/ */
@Singleton @Singleton
class CachedTrackIds @Inject constructor( class CachedTrackIds
playerController: PlayerController, @Inject
private val playerFactory: PlayerFactory, constructor(
@ApplicationScope scope: CoroutineScope, playerController: PlayerController,
) { private val playerFactory: PlayerFactory,
private val refresh = MutableStateFlow(0L) @ApplicationScope scope: CoroutineScope,
) {
private val refresh = MutableStateFlow(0L)
val ids: StateFlow<Set<String>> = val ids: StateFlow<Set<String>> =
refresh refresh
.map { readKeys() } .map { readKeys() }
.flowOn(Dispatchers.IO) .flowOn(Dispatchers.IO)
.stateIn(scope, SharingStarted.Eagerly, emptySet()) .stateIn(scope, SharingStarted.Eagerly, emptySet())
init { init {
scope.launch { scope.launch {
playerController.uiState playerController.uiState
.map { it.currentTrack?.id } .map { it.currentTrack?.id }
.distinctUntilChanged() .distinctUntilChanged()
.collect { refresh.value += 1 } .collect { refresh.value += 1 }
}
} }
}
private fun readKeys(): Set<String> = private fun readKeys(): Set<String> =
runCatching { playerFactory.simpleCache.keys.toSet() }.getOrDefault(emptySet()) runCatching { playerFactory.simpleCache.keys.toSet() }.getOrDefault(emptySet())
} }
@@ -28,42 +28,45 @@ private const val POOL_LIMIT = 100
* plays the pool from the cache. * plays the pool from the cache.
*/ */
@Singleton @Singleton
class ShuffleSource @Inject constructor( class ShuffleSource
private val cacheIndexDao: AudioCacheIndexDao, @Inject
private val trackDao: CachedTrackDao, constructor(
private val likes: LikesRepository, private val cacheIndexDao: AudioCacheIndexDao,
private val playerFactory: PlayerFactory, private val trackDao: CachedTrackDao,
) { private val likes: LikesRepository,
/** Cached tracks, most-recently-played first (liked included). */ private val playerFactory: PlayerFactory,
suspend fun recentlyPlayed(limit: Int = POOL_LIMIT): List<TrackRef> = ) {
materialize(residentIdsByRecency()).take(limit) /** 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. */ /** Cached tracks that are in the user's liked set, recency-ordered. */
suspend fun liked(limit: Int = POOL_LIMIT): List<TrackRef> { suspend fun liked(limit: Int = POOL_LIMIT): List<TrackRef> {
val likedSet = likes.likedTrackIds() val likedSet = likes.likedTrackIds()
val ids = residentIdsByRecency().filter { it in likedSet } val ids = residentIdsByRecency().filter { it in likedSet }
return materialize(ids).take(limit) return materialize(ids).take(limit)
} }
/** Recency-ordered ids whose audio is actually resident in the cache. */ /** Recency-ordered ids whose audio is actually resident in the cache. */
private suspend fun residentIdsByRecency(): List<String> { private suspend fun residentIdsByRecency(): List<String> {
val resident = runCatching { playerFactory.simpleCache.keys.toSet() } val resident =
.getOrDefault(emptySet()) runCatching { playerFactory.simpleCache.keys.toSet() }
return cacheIndexDao.trackIdsByRecency().filter { it in resident } .getOrDefault(emptySet())
} return cacheIndexDao.trackIdsByRecency().filter { it in resident }
}
/** Materialize ordered ids into TrackRefs from cached metadata, preserving order. */ /** Materialize ordered ids into TrackRefs from cached metadata, preserving order. */
private suspend fun materialize(orderedIds: List<String>): List<TrackRef> { private suspend fun materialize(orderedIds: List<String>): List<TrackRef> {
if (orderedIds.isEmpty()) return emptyList() if (orderedIds.isEmpty()) return emptyList()
val byId = trackDao.getByIds(orderedIds).associateBy { it.id } val byId = trackDao.getByIds(orderedIds).associateBy { it.id }
return orderedIds.mapNotNull { id -> return orderedIds.mapNotNull { id ->
// Clear the server's missing mark. Every id reaching here // Clear the server's missing mark. Every id reaching here
// came through residentIdsByRecency, which already proved the // came through residentIdsByRecency, which already proved the
// AUDIO is in the local cache — so these play regardless of what // AUDIO is in the local cache — so these play regardless of what
// the server has lost, and the queue filter in PlayerController // the server has lost, and the queue filter in PlayerController
// would otherwise throw away tracks that work perfectly. Missing // would otherwise throw away tracks that work perfectly. Missing
// means "cannot stream", not "cannot play". // means "cannot stream", not "cannot play".
byId[id]?.toDomain()?.copy(unavailable = false) byId[id]?.toDomain()?.copy(unavailable = false)
}
} }
} }
}
@@ -34,12 +34,17 @@ internal enum class OwnerStep {
OWNED, OWNED,
} }
internal fun ownerStep(loaded: Boolean, signedInUserId: String?, ownerUserId: String?): OwnerStep = when { internal fun ownerStep(
!loaded || signedInUserId == null -> OwnerStep.WAIT loaded: Boolean,
ownerUserId == null -> OwnerStep.ADOPT signedInUserId: String?,
ownerUserId != signedInUserId -> OwnerStep.SWITCH ownerUserId: String?,
else -> OwnerStep.OWNED ): 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 * Keeps one account's cached data from reaching another account on a
@@ -62,48 +67,53 @@ internal fun ownerStep(loaded: Boolean, signedInUserId: String?, ownerUserId: St
* out under another account's session. * out under another account's session.
*/ */
@Singleton @Singleton
class AccountCache @Inject constructor( class AccountCache
private val authStore: AuthStore, @Inject
authController: AuthController, constructor(
private val tables: AccountTables, private val authStore: AuthStore,
private val player: Lazy<PlayerController>, authController: AuthController,
@ApplicationScope scope: CoroutineScope, private val tables: AccountTables,
) { private val player: Lazy<PlayerController>,
private val ownedState = MutableStateFlow(false) @ApplicationScope scope: CoroutineScope,
) {
private val ownedState = MutableStateFlow(false)
/** True while the signed-in account is the one the cached data belongs to. */ /** True while the signed-in account is the one the cached data belongs to. */
val ownedBySignedInUser: StateFlow<Boolean> = ownedState.asStateFlow() val ownedBySignedInUser: StateFlow<Boolean> = ownedState.asStateFlow()
init { init {
scope.launch { scope.launch {
combine( combine(
authStore.settingsLoaded, authStore.settingsLoaded,
authController.currentUser, authController.currentUser,
authStore.cacheOwnerUserId, authStore.cacheOwnerUserId,
) { loaded, user, owner -> Triple(loaded, user?.id, owner) } ) { loaded, user, owner -> Triple(loaded, user?.id, owner) }
.distinctUntilChanged() .distinctUntilChanged()
.collect { (loaded, userId, owner) -> step(ownerStep(loaded, userId, owner), userId) } .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 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()
} }
} }
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,17 +12,21 @@ import javax.inject.Singleton
* (likes, playlists) or shared by every account (the library) does not. * (likes, playlists) or shared by every account (the library) does not.
*/ */
@Singleton @Singleton
class AccountTables @Inject constructor(private val db: AppDatabase) { class AccountTables
/** Clears them in one transaction, so a crash can't leave half of them. */ @Inject
suspend fun clear() { constructor(
db.withTransaction { private val db: AppDatabase,
db.cachedMutationDao().clear() ) {
db.cachedHomeIndexDao().clear() /** Clears them in one transaction, so a crash can't leave half of them. */
db.cachedHistorySnapshotDao().clear() suspend fun clear() {
db.cachedQuarantineDao().clear() db.withTransaction {
db.cachedResumeStateDao().clear() db.cachedMutationDao().clear()
db.cachedNotificationDao().clear() db.cachedHomeIndexDao().clear()
db.cachedNotificationDao().clearSettings() db.cachedHistorySnapshotDao().clear()
db.cachedQuarantineDao().clear()
db.cachedResumeStateDao().clear()
db.cachedNotificationDao().clear()
db.cachedNotificationDao().clearSettings()
}
} }
} }
}
@@ -27,10 +27,11 @@ class BucketLedger<S : Any>(
private val lengthOf: (S) -> Long, private val lengthOf: (S) -> Long,
lruOrder: Comparator<S>, lruOrder: Comparator<S>,
) { ) {
private val spans = mapOf( private val spans =
CacheBucket.LIKED to TreeSet(lruOrder), mapOf(
CacheBucket.RECENT to TreeSet(lruOrder), CacheBucket.LIKED to TreeSet(lruOrder),
) CacheBucket.RECENT to TreeSet(lruOrder),
)
private val bytes = mutableMapOf(CacheBucket.LIKED to 0L, CacheBucket.RECENT to 0L) private val bytes = mutableMapOf(CacheBucket.LIKED to 0L, CacheBucket.RECENT to 0L)
private val spansByKey = HashMap<String, MutableSet<S>>() private val spansByKey = HashMap<String, MutableSet<S>>()
private val bucketByKey = HashMap<String, CacheBucket>() private val bucketByKey = HashMap<String, CacheBucket>()
@@ -43,16 +44,16 @@ class BucketLedger<S : Any>(
/** Cap on Recently played bytes; 0 means unlimited. */ /** Cap on Recently played bytes; 0 means unlimited. */
var recentCapBytes: Long = 0L var recentCapBytes: Long = 0L
fun bucketOf(key: String): CacheBucket = fun bucketOf(key: String): CacheBucket = if (key in liked) CacheBucket.LIKED else CacheBucket.RECENT
if (key in liked) CacheBucket.LIKED else CacheBucket.RECENT
fun bytesIn(bucket: CacheBucket): Long = bytes.getValue(bucket) fun bytesIn(bucket: CacheBucket): Long = bytes.getValue(bucket)
/** Bytes the Liked budget can still take; [Long.MAX_VALUE] when unlimited. */ /** Bytes the Liked budget can still take; [Long.MAX_VALUE] when unlimited. */
fun likedRoomBytes(): Long = when { fun likedRoomBytes(): Long =
likedCapBytes <= 0L -> Long.MAX_VALUE when {
else -> (likedCapBytes - bytesIn(CacheBucket.LIKED)).coerceAtLeast(0L) likedCapBytes <= 0L -> Long.MAX_VALUE
} else -> (likedCapBytes - bytesIn(CacheBucket.LIKED)).coerceAtLeast(0L)
}
fun add(span: S) { fun add(span: S) {
val key = keyOf(span) val key = keyOf(span)
@@ -105,7 +106,10 @@ class BucketLedger<S : Any>(
* [pendingBytes] describe a write about to start, so room is made for it * [pendingBytes] describe a write about to start, so room is made for it
* in its own bucket first. Recently played is trimmed before Liked. * 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 if (!armed) return null
val pendingBucket = pendingKey?.let(::bucketOf) val pendingBucket = pendingKey?.let(::bucketOf)
return listOf(CacheBucket.RECENT, CacheBucket.LIKED).firstNotNullOfOrNull { bucket -> return listOf(CacheBucket.RECENT, CacheBucket.LIKED).firstNotNullOfOrNull { bucket ->
@@ -114,7 +118,10 @@ 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 cap = if (bucket == CacheBucket.LIKED) likedCapBytes else recentCapBytes
val over = cap > 0L && bytesIn(bucket) + incoming > cap val over = cap > 0L && bytesIn(bucket) + incoming > cap
return if (over) spans.getValue(bucket).firstOrNull() else null return if (over) spans.getValue(bucket).firstOrNull() else null
@@ -23,18 +23,20 @@ import javax.inject.Singleton
* `MinstrelApplication`. * `MinstrelApplication`.
*/ */
@Singleton @Singleton
class CacheBudgetSync @Inject constructor( class CacheBudgetSync
likes: LikesRepository, @Inject
authStore: AuthStore, constructor(
evictor: TwoBucketCacheEvictor, likes: LikesRepository,
@ApplicationScope scope: CoroutineScope, authStore: AuthStore,
) { evictor: TwoBucketCacheEvictor,
init { @ApplicationScope scope: CoroutineScope,
scope.launch(Dispatchers.IO) { ) {
combine(likes.observeSignedInLikedTrackIds(), authStore.cacheSettings, ::Pair) init {
.collect { (ids, settings) -> scope.launch(Dispatchers.IO) {
evictor.update(ids, settings.likedCapBytes, settings.rollingCapBytes) combine(likes.observeSignedInLikedTrackIds(), authStore.cacheSettings, ::Pair)
} .collect { (ids, settings) ->
evictor.update(ids, settings.likedCapBytes, settings.rollingCapBytes)
}
}
} }
} }
}
@@ -11,7 +11,11 @@ import javax.inject.Singleton
* Bytes held against each audio-cache budget, and how much more the Liked * Bytes held against each audio-cache budget, and how much more the Liked
* budget can take ([Long.MAX_VALUE] when it is unlimited). * 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 * The audio cache's eviction policy: two budgets, Liked songs and Recently
@@ -29,84 +33,111 @@ data class CacheUsage(val likedBytes: Long, val recentBytes: Long, val likedRoom
* deadlock. * deadlock.
*/ */
@Singleton @Singleton
class TwoBucketCacheEvictor @Inject constructor() : CacheEvictor { class TwoBucketCacheEvictor
private val ledger = BucketLedger<CacheSpan>( @Inject
keyOf = { it.key }, constructor() : CacheEvictor {
lengthOf = { it.length }, private val ledger =
lruOrder = compareBy<CacheSpan> { it.lastTouchTimestamp }.then(naturalOrder()), 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. */ /** Called once the SimpleCache exists, so updates can trim it. */
fun attach(cache: Cache) { fun attach(cache: Cache) {
this.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)
} }
if (c == null) {
synchronized(ledger) { apply() } /** Apply a new liked set and caps, then trim whatever no longer fits. */
} else { fun update(
synchronized(c) { likedIds: Set<String>,
synchronized(ledger) { likedCapBytes: Long,
apply() recentCapBytes: Long,
evict(c, pendingKey = null, pendingBytes = 0L) ) {
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)
}
} }
} }
} }
}
fun usage(): CacheUsage = synchronized(ledger) { fun usage(): CacheUsage =
CacheUsage( synchronized(ledger) {
likedBytes = ledger.bytesIn(CacheBucket.LIKED), CacheUsage(
recentBytes = ledger.bytesIn(CacheBucket.RECENT), likedBytes = ledger.bytesIn(CacheBucket.LIKED),
likedRoomBytes = ledger.likedRoomBytes(), 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) { override fun onStartFile(
synchronized(ledger) { cache: Cache,
evict(cache, key, if (length == C.LENGTH_UNSET.toLong()) 0L else length) 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 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.CachedMutationDao
import com.fabledsword.minstrel.cache.db.dao.CachedNotificationDao import com.fabledsword.minstrel.cache.db.dao.CachedNotificationDao
import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistDao 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.CachedPlaylistTrackDao
import com.fabledsword.minstrel.cache.db.dao.CachedQuarantineDao 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.CachedTrackDao
import com.fabledsword.minstrel.cache.db.dao.DiagnosticEventDao import com.fabledsword.minstrel.cache.db.dao.DiagnosticEventDao
import com.fabledsword.minstrel.cache.db.dao.SyncMetadataDao 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.CachedNotificationEntity
import com.fabledsword.minstrel.cache.db.entities.CachedNotificationSettingsEntity import com.fabledsword.minstrel.cache.db.entities.CachedNotificationSettingsEntity
import com.fabledsword.minstrel.cache.db.entities.CachedPlaylistEntity 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.CachedPlaylistTrackEntity
import com.fabledsword.minstrel.cache.db.entities.CachedQuarantineEntity 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.CachedTrackEntity
import com.fabledsword.minstrel.cache.db.entities.DiagnosticEventEntity import com.fabledsword.minstrel.cache.db.entities.DiagnosticEventEntity
import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity
@@ -101,104 +101,126 @@ import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity
@TypeConverters(MinstrelTypeConverters::class) @TypeConverters(MinstrelTypeConverters::class)
abstract class AppDatabase : RoomDatabase() { abstract class AppDatabase : RoomDatabase() {
abstract fun syncMetadataDao(): SyncMetadataDao abstract fun syncMetadataDao(): SyncMetadataDao
abstract fun cachedArtistDao(): CachedArtistDao abstract fun cachedArtistDao(): CachedArtistDao
abstract fun cachedAlbumDao(): CachedAlbumDao abstract fun cachedAlbumDao(): CachedAlbumDao
abstract fun cachedTrackDao(): CachedTrackDao abstract fun cachedTrackDao(): CachedTrackDao
abstract fun cachedLikeDao(): CachedLikeDao abstract fun cachedLikeDao(): CachedLikeDao
abstract fun cachedPlaylistDao(): CachedPlaylistDao abstract fun cachedPlaylistDao(): CachedPlaylistDao
abstract fun cachedPlaylistTrackDao(): CachedPlaylistTrackDao abstract fun cachedPlaylistTrackDao(): CachedPlaylistTrackDao
abstract fun cachedQuarantineDao(): CachedQuarantineDao abstract fun cachedQuarantineDao(): CachedQuarantineDao
abstract fun audioCacheIndexDao(): AudioCacheIndexDao abstract fun audioCacheIndexDao(): AudioCacheIndexDao
abstract fun cachedMutationDao(): CachedMutationDao abstract fun cachedMutationDao(): CachedMutationDao
abstract fun cachedResumeStateDao(): CachedResumeStateDao abstract fun cachedResumeStateDao(): CachedResumeStateDao
abstract fun cachedHomeIndexDao(): CachedHomeIndexDao abstract fun cachedHomeIndexDao(): CachedHomeIndexDao
abstract fun cachedHistorySnapshotDao(): CachedHistorySnapshotDao abstract fun cachedHistorySnapshotDao(): CachedHistorySnapshotDao
abstract fun authSessionDao(): AuthSessionDao abstract fun authSessionDao(): AuthSessionDao
abstract fun diagnosticEventDao(): DiagnosticEventDao abstract fun diagnosticEventDao(): DiagnosticEventDao
abstract fun cachedNotificationDao(): CachedNotificationDao abstract fun cachedNotificationDao(): CachedNotificationDao
} }
/** v8 → v9: add the nullable normalization preference column. */ /** v8 → v9: add the nullable normalization preference column. */
val MIGRATION_8_9: Migration = object : Migration(8, 9) { val MIGRATION_8_9: Migration =
override fun migrate(db: SupportSQLiteDatabase) { object : Migration(8, 9) {
db.execSQL("ALTER TABLE auth_session ADD COLUMN normalizationJson TEXT") 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, * 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 * 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. * 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) { val MIGRATION_9_10: Migration =
override fun migrate(db: SupportSQLiteDatabase) { object : Migration(9, 10) {
db.execSQL("ALTER TABLE cached_tracks ADD COLUMN trackGain REAL") override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE cached_tracks ADD COLUMN trackPeak REAL") db.execSQL("ALTER TABLE cached_tracks ADD COLUMN trackGain REAL")
db.execSQL("ALTER TABLE cached_albums ADD COLUMN albumGain REAL") db.execSQL("ALTER TABLE cached_tracks ADD COLUMN trackPeak REAL")
db.execSQL("ALTER TABLE cached_albums ADD COLUMN albumPeak REAL") db.execSQL("ALTER TABLE cached_albums ADD COLUMN albumGain REAL")
db.execSQL("UPDATE sync_metadata SET cursor = 0") 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 * v10 → v11: the notifications inbox cache and its settings. The SQL
* matches what Room generates for the two entities; Room checks it on open. * matches what Room generates for the two entities; Room checks it on open.
*/ */
val MIGRATION_10_11: Migration = object : Migration(10, 11) { val MIGRATION_10_11: Migration =
override fun migrate(db: SupportSQLiteDatabase) { object : Migration(10, 11) {
db.execSQL( override fun migrate(db: SupportSQLiteDatabase) {
"CREATE TABLE IF NOT EXISTS `cached_notifications` (" + db.execSQL(
"`id` TEXT NOT NULL, `kind` TEXT NOT NULL, `title` TEXT NOT NULL, " + "CREATE TABLE IF NOT EXISTS `cached_notifications` (" +
"`body` TEXT NOT NULL, `link` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, " + "`id` TEXT NOT NULL, `kind` TEXT NOT NULL, `title` TEXT NOT NULL, " +
"`readAt` INTEGER, PRIMARY KEY(`id`))", "`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` (" + db.execSQL(
"`id` INTEGER NOT NULL, `json` TEXT NOT NULL, PRIMARY KEY(`id`))", "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, * v11 → v12: background delivery. The device choice defaults on,
* as the entity's column default says; the high-water mark starts empty, so * as the entity's column default says; the high-water mark starts empty, so
* the first catch-up sets it without announcing anything. * the first catch-up sets it without announcing anything.
*/ */
val MIGRATION_11_12: Migration = object : Migration(11, 12) { val MIGRATION_11_12: Migration =
override fun migrate(db: SupportSQLiteDatabase) { object : Migration(11, 12) {
db.execSQL("ALTER TABLE auth_session ADD COLUMN backgroundDelivery INTEGER NOT NULL DEFAULT 1") override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE auth_session ADD COLUMN notifiedUpTo INTEGER") 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; * v12 → v13: a playlist's cover albums and creation time. Both start empty;
* Home refreshes the playlist list on open, which fills them. * Home refreshes the playlist list on open, which fills them.
*/ */
val MIGRATION_12_13: Migration = object : Migration(12, 13) { val MIGRATION_12_13: Migration =
override fun migrate(db: SupportSQLiteDatabase) { object : Migration(12, 13) {
db.execSQL("ALTER TABLE cached_playlists ADD COLUMN coverAlbumIds TEXT NOT NULL DEFAULT ''") override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE cached_playlists ADD COLUMN createdAt TEXT NOT NULL DEFAULT ''") 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); * v13 → v14: a playlist's place on its Home shelf. Starts at 0 (unranked);
* Home refreshes the playlist list on open, which fills it. * Home refreshes the playlist list on open, which fills it.
*/ */
val MIGRATION_13_14: Migration = object : Migration(13, 14) { val MIGRATION_13_14: Migration =
override fun migrate(db: SupportSQLiteDatabase) { object : Migration(13, 14) {
db.execSQL("ALTER TABLE cached_playlists ADD COLUMN shelfRank INTEGER NOT NULL DEFAULT 0") 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 * v14 → v15: the account the cached data belongs to. Starts empty, and
* AccountCache adopts whoever is signed in without clearing anything, so * AccountCache adopts whoever is signed in without clearing anything, so
* an update keeps the signed-in person's queued writes and cache. * an update keeps the signed-in person's queued writes and cache.
*/ */
val MIGRATION_14_15: Migration = object : Migration(14, 15) { val MIGRATION_14_15: Migration =
override fun migrate(db: SupportSQLiteDatabase) { object : Migration(14, 15) {
db.execSQL("ALTER TABLE auth_session ADD COLUMN cacheOwnerUserId TEXT") 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.CachedLikeDao
import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao
import com.fabledsword.minstrel.cache.db.dao.CachedNotificationDao 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.CachedPlaylistDao
import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistTrackDao import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistTrackDao
import com.fabledsword.minstrel.cache.db.dao.CachedQuarantineDao import com.fabledsword.minstrel.cache.db.dao.CachedQuarantineDao
import com.fabledsword.minstrel.cache.db.dao.CachedResumeStateDao import com.fabledsword.minstrel.cache.db.dao.CachedResumeStateDao
import com.fabledsword.minstrel.cache.db.dao.CachedTrackDao 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 com.fabledsword.minstrel.cache.db.dao.SyncMetadataDao
import dagger.Module import dagger.Module
import dagger.Provides import dagger.Provides
@@ -31,8 +31,11 @@ import javax.inject.Singleton
object DatabaseModule { object DatabaseModule {
@Provides @Provides
@Singleton @Singleton
fun provideDatabase(@ApplicationContext context: Context): AppDatabase = fun provideDatabase(
Room.databaseBuilder(context, AppDatabase::class.java, DATABASE_NAME) @ApplicationContext context: Context,
): AppDatabase =
Room
.databaseBuilder(context, AppDatabase::class.java, DATABASE_NAME)
// Explicit migrations from v8 onward; an older schema has no path // Explicit migrations from v8 onward; an older schema has no path
// and rebuilds. The sync controller refills the cache from the // and rebuilds. The sync controller refills the cache from the
// server on first launch, so a rebuild loses only the unsynced // server on first launch, so a rebuild loses only the unsynced
@@ -45,8 +48,7 @@ object DatabaseModule {
MIGRATION_12_13, MIGRATION_12_13,
MIGRATION_13_14, MIGRATION_13_14,
MIGRATION_14_15, MIGRATION_14_15,
) ).fallbackToDestructiveMigration(dropAllTables = true)
.fallbackToDestructiveMigration(dropAllTables = true)
.build() .build()
// DAO @Provides — Hilt can't inject AppDatabase abstract accessors // DAO @Provides — Hilt can't inject AppDatabase abstract accessors
@@ -69,33 +71,27 @@ object DatabaseModule {
@Provides @Provides
@Singleton @Singleton
fun provideCachedResumeStateDao(db: AppDatabase): CachedResumeStateDao = fun provideCachedResumeStateDao(db: AppDatabase): CachedResumeStateDao = db.cachedResumeStateDao()
db.cachedResumeStateDao()
@Provides @Provides
@Singleton @Singleton
fun provideCachedHomeIndexDao(db: AppDatabase): CachedHomeIndexDao = fun provideCachedHomeIndexDao(db: AppDatabase): CachedHomeIndexDao = db.cachedHomeIndexDao()
db.cachedHomeIndexDao()
@Provides @Provides
@Singleton @Singleton
fun provideCachedHistorySnapshotDao(db: AppDatabase): CachedHistorySnapshotDao = fun provideCachedHistorySnapshotDao(db: AppDatabase): CachedHistorySnapshotDao = db.cachedHistorySnapshotDao()
db.cachedHistorySnapshotDao()
@Provides @Provides
@Singleton @Singleton
fun provideCachedQuarantineDao(db: AppDatabase): CachedQuarantineDao = fun provideCachedQuarantineDao(db: AppDatabase): CachedQuarantineDao = db.cachedQuarantineDao()
db.cachedQuarantineDao()
@Provides @Provides
@Singleton @Singleton
fun provideCachedPlaylistDao(db: AppDatabase): CachedPlaylistDao = fun provideCachedPlaylistDao(db: AppDatabase): CachedPlaylistDao = db.cachedPlaylistDao()
db.cachedPlaylistDao()
@Provides @Provides
@Singleton @Singleton
fun provideCachedPlaylistTrackDao(db: AppDatabase): CachedPlaylistTrackDao = fun provideCachedPlaylistTrackDao(db: AppDatabase): CachedPlaylistTrackDao = db.cachedPlaylistTrackDao()
db.cachedPlaylistTrackDao()
@Provides @Provides
@Singleton @Singleton
@@ -103,8 +99,7 @@ object DatabaseModule {
@Provides @Provides
@Singleton @Singleton
fun provideCachedMutationDao(db: AppDatabase): CachedMutationDao = fun provideCachedMutationDao(db: AppDatabase): CachedMutationDao = db.cachedMutationDao()
db.cachedMutationDao()
@Provides @Provides
@Singleton @Singleton
@@ -112,18 +107,15 @@ object DatabaseModule {
@Provides @Provides
@Singleton @Singleton
fun provideAudioCacheIndexDao(db: AppDatabase): AudioCacheIndexDao = fun provideAudioCacheIndexDao(db: AppDatabase): AudioCacheIndexDao = db.audioCacheIndexDao()
db.audioCacheIndexDao()
@Provides @Provides
@Singleton @Singleton
fun provideDiagnosticEventDao(db: AppDatabase): DiagnosticEventDao = fun provideDiagnosticEventDao(db: AppDatabase): DiagnosticEventDao = db.diagnosticEventDao()
db.diagnosticEventDao()
@Provides @Provides
@Singleton @Singleton
fun provideCachedNotificationDao(db: AppDatabase): CachedNotificationDao = fun provideCachedNotificationDao(db: AppDatabase): CachedNotificationDao = db.cachedNotificationDao()
db.cachedNotificationDao()
private const val DATABASE_NAME = "minstrel.db" private const val DATABASE_NAME = "minstrel.db"
} }
@@ -21,11 +21,9 @@ enum class CacheSource { MANUAL, AUTO_LIKED, AUTO_PLAYLIST, AUTO_PREFETCH, INCID
class MinstrelTypeConverters { class MinstrelTypeConverters {
@TypeConverter fun instantToLong(i: Instant?): Long? = i?.toEpochMilliseconds() @TypeConverter fun instantToLong(i: Instant?): Long? = i?.toEpochMilliseconds()
@TypeConverter fun longToInstant(l: Long?): Instant? = @TypeConverter fun longToInstant(l: Long?): Instant? = l?.let { Instant.fromEpochMilliseconds(it) }
l?.let { Instant.fromEpochMilliseconds(it) }
@TypeConverter fun sourceToName(s: CacheSource?): String? = s?.name @TypeConverter fun sourceToName(s: CacheSource?): String? = s?.name
@TypeConverter fun nameToSource(n: String?): CacheSource? = @TypeConverter fun nameToSource(n: String?): CacheSource? = n?.let { CacheSource.valueOf(it) }
n?.let { CacheSource.valueOf(it) }
} }
@@ -37,7 +37,10 @@ interface AudioCacheIndexDao {
@Query( @Query(
"UPDATE audio_cache_index SET lastPlayedAt = :at WHERE trackId = :trackId", "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") @Query("DELETE FROM audio_cache_index WHERE trackId = :trackId")
suspend fun deleteByTrackId(trackId: String) suspend fun deleteByTrackId(trackId: String)
@@ -30,10 +30,16 @@ interface CachedAlbumDao {
"ORDER BY sortTitle COLLATE NOCASE ASC " + "ORDER BY sortTitle COLLATE NOCASE ASC " +
"LIMIT :limit", "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") @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) @Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertAll(rows: List<CachedAlbumEntity>) suspend fun upsertAll(rows: List<CachedAlbumEntity>)
@@ -24,10 +24,16 @@ interface CachedArtistDao {
"ORDER BY sortName COLLATE NOCASE ASC " + "ORDER BY sortName COLLATE NOCASE ASC " +
"LIMIT :limit", "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") @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) @Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertAll(rows: List<CachedArtistEntity>) suspend fun upsertAll(rows: List<CachedArtistEntity>)
@@ -44,7 +44,10 @@ interface CachedHomeIndexDao {
* sequence rather than as a single content swap. * sequence rather than as a single content swap.
*/ */
@Transaction @Transaction
suspend fun replaceSections(sections: List<String>, rows: List<CachedHomeIndexEntity>) { suspend fun replaceSections(
sections: List<String>,
rows: List<CachedHomeIndexEntity>,
) {
deleteSections(sections) deleteSections(sections)
if (rows.isNotEmpty()) upsertAll(rows) if (rows.isNotEmpty()) upsertAll(rows)
} }
@@ -25,13 +25,20 @@ interface CachedLikeDao {
"SELECT entityId FROM cached_likes " + "SELECT entityId FROM cached_likes " +
"WHERE userId = :userId AND entityType = :entityType", "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( @Query(
"SELECT EXISTS(SELECT 1 FROM cached_likes " + "SELECT EXISTS(SELECT 1 FROM cached_likes " +
"WHERE userId = :userId AND entityType = :entityType AND entityId = :entityId)", "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) @Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertAll(rows: List<CachedLikeEntity>) suspend fun upsertAll(rows: List<CachedLikeEntity>)
@@ -40,7 +47,11 @@ interface CachedLikeDao {
"DELETE FROM cached_likes " + "DELETE FROM cached_likes " +
"WHERE userId = :userId AND entityType = :entityType AND entityId = :entityId", "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") @Query("DELETE FROM cached_likes WHERE userId = :userId")
suspend fun clearForUser(userId: String) suspend fun clearForUser(userId: String)
@@ -53,7 +64,10 @@ interface CachedLikeDao {
* stale Liked tab entry forever. * stale Liked tab entry forever.
*/ */
@Transaction @Transaction
suspend fun replaceAllForUser(userId: String, rows: List<CachedLikeEntity>) { suspend fun replaceAllForUser(
userId: String,
rows: List<CachedLikeEntity>,
) {
clearForUser(userId) clearForUser(userId)
upsertAll(rows) upsertAll(rows)
} }
@@ -24,7 +24,10 @@ interface CachedMutationDao {
"UPDATE cached_mutations SET attempts = attempts + 1, lastAttemptAt = :at " + "UPDATE cached_mutations SET attempts = attempts + 1, lastAttemptAt = :at " +
"WHERE id = :id", "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") @Query("DELETE FROM cached_mutations WHERE id = :id")
suspend fun delete(id: Long) suspend fun delete(id: Long)
@@ -35,7 +35,10 @@ interface CachedNotificationDao {
} }
@Query("UPDATE cached_notifications SET readAt = :at WHERE id = :id AND readAt IS NULL") @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") @Query("UPDATE cached_notifications SET readAt = :at WHERE readAt IS NULL")
suspend fun markAllRead(at: Instant) suspend fun markAllRead(at: Instant)
@@ -55,7 +55,10 @@ interface CachedPlaylistDao {
suspend fun deleteAllOwned(userId: String) suspend fun deleteAllOwned(userId: String)
@Query("DELETE FROM cached_playlists WHERE userId = :userId AND id NOT IN (:keepIds)") @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. * Atomically reconciles the cache against the fresh list response.
@@ -67,5 +67,8 @@ interface CachedPlaylistTrackDao {
"DELETE FROM cached_playlist_tracks " + "DELETE FROM cached_playlist_tracks " +
"WHERE playlistId = :playlistId AND trackId IN (:trackIds)", "WHERE playlistId = :playlistId AND trackId IN (:trackIds)",
) )
suspend fun deleteTracksFromPlaylist(playlistId: String, trackIds: List<String>) suspend fun deleteTracksFromPlaylist(
playlistId: String,
trackIds: List<String>,
)
} }
@@ -30,10 +30,16 @@ interface CachedTrackDao {
"ORDER BY title COLLATE NOCASE ASC " + "ORDER BY title COLLATE NOCASE ASC " +
"LIMIT :limit", "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") @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) @Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertAll(rows: List<CachedTrackEntity>) suspend fun upsertAll(rows: List<CachedTrackEntity>)
@@ -87,206 +87,238 @@ data class LikeTogglePayload(
*/ */
@Suppress("TooManyFunctions") // one enqueue per mutation kind, like the replayer's dispatchers @Suppress("TooManyFunctions") // one enqueue per mutation kind, like the replayer's dispatchers
@Singleton @Singleton
class MutationQueue @Inject constructor( class MutationQueue
private val dao: CachedMutationDao, @Inject
private val json: Json, constructor(
) { private val dao: CachedMutationDao,
// capacity=1 DROP_OLDEST so a burst of user enqueues (e.g. liking N private val json: Json,
// tracks while offline) surfaces as one snackbar rather than queueing ) {
// N. replay=0 because a hint observed at enqueue time isn't useful // capacity=1 DROP_OLDEST so a burst of user enqueues (e.g. liking N
// to a screen that mounts later. // tracks while offline) surfaces as one snackbar rather than queueing
private val _userEnqueueHints = MutableSharedFlow<String>( // N. replay=0 because a hint observed at enqueue time isn't useful
replay = 0, // to a screen that mounts later.
extraBufferCapacity = 1, private val _userEnqueueHints =
onBufferOverflow = BufferOverflow.DROP_OLDEST, MutableSharedFlow<String>(
) replay = 0,
extraBufferCapacity = 1,
onBufferOverflow = BufferOverflow.DROP_OLDEST,
)
/** /**
* Hint stream consumed by [com.fabledsword.minstrel.shared.widgets.ShellScaffold] * Hint stream consumed by [com.fabledsword.minstrel.shared.widgets.ShellScaffold]
* to surface "Saved — will sync when online" as a snackbar whenever a * to surface "Saved — will sync when online" as a snackbar whenever a
* user-driven write hits the offline-fallback path. Background-only * user-driven write hits the offline-fallback path. Background-only
* enqueues (play-events, playback-error reports) do not emit — those * enqueues (play-events, playback-error reports) do not emit — those
* fire from non-foreground paths where a snackbar would be either * fire from non-foreground paths where a snackbar would be either
* dropped (no shell mounted) or jarring (lock-screen toggle). * dropped (no shell mounted) or jarring (lock-screen toggle).
*/ */
val userEnqueueHints: SharedFlow<String> = _userEnqueueHints.asSharedFlow() val userEnqueueHints: SharedFlow<String> = _userEnqueueHints.asSharedFlow()
suspend fun enqueueLikeToggle( suspend fun enqueueLikeToggle(
entityType: String, entityType: String,
entityId: String, entityId: String,
desiredState: Boolean, desiredState: Boolean,
): Long = insertUserDriven( ): Long =
MutationKind.LIKE_TOGGLE, insertUserDriven(
json.encodeToString( MutationKind.LIKE_TOGGLE,
LikeTogglePayload.serializer(), json.encodeToString(
LikeTogglePayload(entityType, entityId, desiredState), LikeTogglePayload.serializer(),
), LikeTogglePayload(entityType, entityId, desiredState),
) ),
)
suspend fun enqueueQuarantineUnflag(trackId: String): Long = insertUserDriven( suspend fun enqueueQuarantineUnflag(trackId: String): Long =
MutationKind.QUARANTINE_UNFLAG, insertUserDriven(
json.encodeToString( MutationKind.QUARANTINE_UNFLAG,
QuarantineUnflagPayload.serializer(), json.encodeToString(
QuarantineUnflagPayload(trackId), QuarantineUnflagPayload.serializer(),
), QuarantineUnflagPayload(trackId),
) ),
)
suspend fun enqueuePlaylistAppend(payload: PlaylistAppendPayload): Long = insertUserDriven( suspend fun enqueuePlaylistAppend(payload: PlaylistAppendPayload): Long =
MutationKind.PLAYLIST_APPEND, insertUserDriven(
json.encodeToString(PlaylistAppendPayload.serializer(), payload), MutationKind.PLAYLIST_APPEND,
) json.encodeToString(PlaylistAppendPayload.serializer(), payload),
)
suspend fun enqueuePlaylistCreate(payload: PlaylistCreatePayload): Long = insertUserDriven( suspend fun enqueuePlaylistCreate(payload: PlaylistCreatePayload): Long =
MutationKind.PLAYLIST_CREATE, insertUserDriven(
json.encodeToString(PlaylistCreatePayload.serializer(), payload), MutationKind.PLAYLIST_CREATE,
) json.encodeToString(PlaylistCreatePayload.serializer(), payload),
)
suspend fun enqueuePlaylistUpdate(payload: PlaylistUpdatePayload): Long = insertUserDriven( suspend fun enqueuePlaylistUpdate(payload: PlaylistUpdatePayload): Long =
MutationKind.PLAYLIST_UPDATE, insertUserDriven(
json.encodeToString(PlaylistUpdatePayload.serializer(), payload), MutationKind.PLAYLIST_UPDATE,
) json.encodeToString(PlaylistUpdatePayload.serializer(), payload),
)
suspend fun enqueuePlaylistDelete(playlistId: String): Long = insertUserDriven( suspend fun enqueuePlaylistDelete(playlistId: String): Long =
MutationKind.PLAYLIST_DELETE, insertUserDriven(
json.encodeToString(PlaylistDeletePayload.serializer(), PlaylistDeletePayload(playlistId)), MutationKind.PLAYLIST_DELETE,
) json.encodeToString(PlaylistDeletePayload.serializer(), PlaylistDeletePayload(playlistId)),
)
suspend fun enqueuePlaylistRemoveTrack(payload: PlaylistRemoveTrackPayload): Long = insertUserDriven( suspend fun enqueuePlaylistRemoveTrack(payload: PlaylistRemoveTrackPayload): Long =
MutationKind.PLAYLIST_REMOVE_TRACK, insertUserDriven(
json.encodeToString(PlaylistRemoveTrackPayload.serializer(), payload), MutationKind.PLAYLIST_REMOVE_TRACK,
) json.encodeToString(PlaylistRemoveTrackPayload.serializer(), payload),
)
suspend fun enqueuePlaylistReorder(payload: PlaylistReorderPayload): Long = insertUserDriven( suspend fun enqueuePlaylistReorder(payload: PlaylistReorderPayload): Long =
MutationKind.PLAYLIST_REORDER, insertUserDriven(
json.encodeToString(PlaylistReorderPayload.serializer(), payload), MutationKind.PLAYLIST_REORDER,
) json.encodeToString(PlaylistReorderPayload.serializer(), payload),
)
/** /**
* Ids of playlists made on this device that the server hasn't been * 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 * sent yet. A list refresh keeps them, so a playlist made offline
* doesn't vanish before its create goes out. * doesn't vanish before its create goes out.
*/ */
suspend fun pendingPlaylistCreateIds(): Set<String> = dao.getAll() suspend fun pendingPlaylistCreateIds(): Set<String> =
.asSequence() dao
.filter { it.kind == MutationKind.PLAYLIST_CREATE } .getAll()
.mapNotNull { row -> .asSequence()
runCatching { json.decodeFromString(PlaylistCreatePayload.serializer(), row.payload) } .filter { it.kind == MutationKind.PLAYLIST_CREATE }
.getOrNull()?.id .mapNotNull { row ->
} runCatching { json.decodeFromString(PlaylistCreatePayload.serializer(), row.payload) }
.toSet() .getOrNull()
?.id
}.toSet()
/** /**
* The like state each still-queued like toggle sets, by * The like state each still-queued like toggle sets, by
* [likeToggleKey], the newest toggle winning. A toggle for an entity * [likeToggleKey], the newest toggle winning. A toggle for an entity
* found here must queue behind it rather than go live, or the older * 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 * one replays after it and undoes it; and a refresh keeps these states
* over the server's, which hasn't seen them yet. * over the server's, which hasn't seen them yet.
*/ */
suspend fun pendingLikeStates(): Map<String, Boolean> = buildMap { suspend fun pendingLikeStates(): Map<String, Boolean> =
dao.getAll().filter { it.kind == MutationKind.LIKE_TOGGLE }.forEach { row -> buildMap {
runCatching { json.decodeFromString(LikeTogglePayload.serializer(), row.payload) } dao.getAll().filter { it.kind == MutationKind.LIKE_TOGGLE }.forEach { row ->
.getOrNull() runCatching { json.decodeFromString(LikeTogglePayload.serializer(), row.payload) }
?.let { put(likeToggleKey(it.entityType, it.entityId), it.desiredState) } .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) }
} }
/**
* 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
} }
} }
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 * Persisted payload for `MutationKind.QUARANTINE_UNFLAG` — the
* `DELETE /api/quarantine/{trackId}` call lost during a connectivity * `DELETE /api/quarantine/{trackId}` call lost during a connectivity
* hiccup. The replayer just re-fires the DELETE; idempotent server-side. * hiccup. The replayer just re-fires the DELETE; idempotent server-side.
*/ */
@Serializable @Serializable
data class QuarantineUnflagPayload(val trackId: String) data class QuarantineUnflagPayload(
val trackId: String,
)
/** The key [MutationQueue.pendingLikeStates] files a like toggle under. */ /** 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 * Persisted payload for `MutationKind.PLAYLIST_APPEND`: the track IDs to
@@ -320,7 +352,9 @@ data class PlaylistUpdatePayload(
/** Persisted payload for `MutationKind.PLAYLIST_DELETE`. */ /** Persisted payload for `MutationKind.PLAYLIST_DELETE`. */
@Serializable @Serializable
data class PlaylistDeletePayload(val playlistId: String) data class PlaylistDeletePayload(
val playlistId: String,
)
/** /**
* Persisted payload for `MutationKind.PLAYLIST_REMOVE_TRACK`. [trackId] is * Persisted payload for `MutationKind.PLAYLIST_REMOVE_TRACK`. [trackId] is
@@ -405,7 +439,9 @@ data class PlaybackErrorReportPayload(
/** Persisted payload for `MutationKind.NOTIFICATION_READ`. */ /** Persisted payload for `MutationKind.NOTIFICATION_READ`. */
@Serializable @Serializable
data class NotificationReadPayload(val id: String) data class NotificationReadPayload(
val id: String,
)
/** /**
* Persisted payload for `MutationKind.NOTIFICATIONS_READ_ALL`. * Persisted payload for `MutationKind.NOTIFICATIONS_READ_ALL`.
@@ -413,7 +449,9 @@ data class NotificationReadPayload(val id: String)
* when the inbox was empty on the device, which marks everything. * when the inbox was empty on the device, which marks everything.
*/ */
@Serializable @Serializable
data class NotificationsReadAllPayload(val upToIso: String?) data class NotificationsReadAllPayload(
val upToIso: String?,
)
/** /**
* Persisted payload for `MutationKind.NOTIFICATION_SETTING_SET`: one * 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.LikesApi
import com.fabledsword.minstrel.api.endpoints.MeApi import com.fabledsword.minstrel.api.endpoints.MeApi
import com.fabledsword.minstrel.api.endpoints.NotificationsApi 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.PlaybackErrorReportRequest
import com.fabledsword.minstrel.api.endpoints.PlaybackErrorsApi import com.fabledsword.minstrel.api.endpoints.PlaybackErrorsApi
import com.fabledsword.minstrel.api.endpoints.PlaylistsApi import com.fabledsword.minstrel.api.endpoints.PlaylistsApi
import com.fabledsword.minstrel.api.endpoints.PutNotificationSettingsBody
import com.fabledsword.minstrel.api.endpoints.QuarantineApi 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.ReorderTracksRequest
import com.fabledsword.minstrel.api.endpoints.UpdatePlaylistRequest 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.auth.AuthStore
import com.fabledsword.minstrel.cache.account.AccountCache import com.fabledsword.minstrel.cache.account.AccountCache
import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao
import com.fabledsword.minstrel.cache.db.entities.CachedMutationEntity import com.fabledsword.minstrel.cache.db.entities.CachedMutationEntity
import com.fabledsword.minstrel.connectivity.NetworkStatusController
import com.fabledsword.minstrel.connectivity.ServerHealth
import com.fabledsword.minstrel.di.ApplicationScope import com.fabledsword.minstrel.di.ApplicationScope
import com.fabledsword.minstrel.likes.data.LikesRepository import com.fabledsword.minstrel.likes.data.LikesRepository
import com.fabledsword.minstrel.models.wire.PlayEndedRequest
import com.fabledsword.minstrel.models.wire.PlayOfflineRequest
import com.fabledsword.minstrel.settings.data.NormalizationPrefs import com.fabledsword.minstrel.settings.data.NormalizationPrefs
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.distinctUntilChanged
@@ -35,7 +35,6 @@ import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.datetime.Clock import kotlinx.datetime.Clock
import kotlinx.serialization.SerializationException import kotlinx.serialization.SerializationException
import kotlinx.serialization.json.Json import kotlinx.serialization.json.Json
@@ -75,296 +74,311 @@ import javax.inject.Singleton
* forever. * forever.
*/ */
@Singleton @Singleton
class MutationReplayer @Inject constructor( class MutationReplayer
private val dao: CachedMutationDao, @Inject
private val authStore: AuthStore, constructor(
private val accountCache: AccountCache, private val dao: CachedMutationDao,
private val json: Json, private val authStore: AuthStore,
@ApplicationScope private val scope: CoroutineScope, private val accountCache: AccountCache,
networkStatus: NetworkStatusController, private val json: Json,
retrofit: Retrofit, @ApplicationScope private val scope: CoroutineScope,
) { networkStatus: NetworkStatusController,
private val likesApi: LikesApi = retrofit.create() retrofit: Retrofit,
private val quarantineApi: QuarantineApi = retrofit.create() ) {
private val playlistsApi: PlaylistsApi = retrofit.create() private val likesApi: LikesApi = retrofit.create()
private val eventsApi: EventsApi = retrofit.create() private val quarantineApi: QuarantineApi = retrofit.create()
private val playbackErrorsApi: PlaybackErrorsApi = retrofit.create() private val playlistsApi: PlaylistsApi = retrofit.create()
private val meApi: MeApi = retrofit.create() private val eventsApi: EventsApi = retrofit.create()
private val notificationsApi: NotificationsApi = 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 { init {
scope.launch { scope.launch {
authStore.sessionCookie authStore.sessionCookie
.filterNotNull() .filterNotNull()
.distinctUntilChanged() .distinctUntilChanged()
.collect { drainSafe() } .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() }
}
} }
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() }
}
}
/** Public entry-point; coalesces concurrent triggers via a Mutex. */ /** Public entry-point; coalesces concurrent triggers via a Mutex. */
suspend fun drainSafe() { suspend fun drainSafe() {
if (!mutex.tryLock()) return if (!mutex.tryLock()) return
try { try {
drain() drain()
} finally { } finally {
mutex.unlock() mutex.unlock()
}
} }
}
private suspend fun drain() { private suspend fun drain() {
// Another account's writes must not go out under this session. // Another account's writes must not go out under this session.
if (!accountCache.ownedBySignedInUser.value) return if (!accountCache.ownedBySignedInUser.value) return
val rows = dao.getAll() val rows = dao.getAll()
// Collapse superseded toggles (likes, settings): only the latest // Collapse superseded toggles (likes, settings): only the latest
// desired state per entity is replayed; older toggles for the same // desired state per entity is replayed; older toggles for the same
// entity are dropped unsent. Without this, partial-failure + // entity are dropped unsent. Without this, partial-failure +
// differential retry could replay an older toggle last and invert the // differential retry could replay an older toggle last and invert the
// final state — an unlike the user already made would be undone. // final state — an unlike the user already made would be undone.
val superseded = supersededToggleIds(rows, json) val superseded = supersededToggleIds(rows, json)
// A playlist's changes go out in the order they were made: once one // 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 // has to wait, the rest for that list wait behind it, so an add
// never reaches the server before the create of its list. // never reaches the server before the create of its list.
val waiting = HashSet<String>() val waiting = HashSet<String>()
for (row in rows) { for (row in rows) {
replayRow(row, superseded = row.id in superseded, waiting = waiting) replayRow(row, superseded = row.id in superseded, waiting = waiting)
}
} }
}
/** /**
* Sends one row, or drops it when a later row has superseded it, or * 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 * 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]. * waiting. A row that has to retry makes its playlist wait in [waiting].
*/ */
private suspend fun replayRow(row: CachedMutationEntity, superseded: Boolean, waiting: MutableSet<String>) { private suspend fun replayRow(
val playlistId = playlistIdOf(row, json) row: CachedMutationEntity,
when { superseded: Boolean,
superseded -> dao.delete(row.id) waiting: MutableSet<String>,
playlistId != null && playlistId in waiting -> Unit ) {
else -> when (outcomeFor(row)) { val playlistId = playlistIdOf(row, json)
Outcome.SENT, Outcome.DROP -> dao.delete(row.id) when {
Outcome.RETRY -> { superseded -> dao.delete(row.id)
dao.recordAttempt(row.id, Clock.System.now()) playlistId != null && playlistId in waiting -> Unit
playlistId?.let(waiting::add) 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
} }
} }
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 * Row ids of desired-state toggles superseded by a later toggle for the same
* entity. Applies to every kind whose payload encodes a TARGET state rather * entity. Applies to every kind whose payload encodes a TARGET state rather
@@ -376,10 +390,14 @@ class MutationReplayer @Inject constructor(
* instance. [rows] must be ascending by id (FIFO), which is what * instance. [rows] must be ascending by id (FIFO), which is what
* `CachedMutationDao.getAll()` returns. * `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 latestByEntity = HashMap<String, Long>()
val superseded = HashSet<Long>() val superseded = HashSet<Long>()
rows.asSequence() rows
.asSequence()
.mapNotNull { row -> toggleKeyOf(row, json)?.let { key -> key to row.id } } .mapNotNull { row -> toggleKeyOf(row, json)?.let { key -> key to row.id } }
.forEach { (key, id) -> .forEach { (key, id) ->
// Ascending ids mean a prior entry for this key is always older. // Ascending ids mean a prior entry for this key is always older.
@@ -397,46 +415,58 @@ internal fun supersededToggleIds(rows: List<CachedMutationEntity>, json: Json):
* The kind is part of the key so two toggle kinds can never collide on the * The kind is part of the key so two toggle kinds can never collide on the
* same entity id. * same entity id.
*/ */
private fun toggleKeyOf(row: CachedMutationEntity, json: Json): String? = when (row.kind) { private fun toggleKeyOf(
MutationKind.LIKE_TOGGLE -> runCatching { row: CachedMutationEntity,
json.decodeFromString(LikeTogglePayload.serializer(), row.payload) json: Json,
}.getOrNull()?.let { "${row.kind}:${it.entityType}:${it.entityId}" } ): 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 { MutationKind.NOTIFICATION_SETTING_SET ->
json.decodeFromString(NotificationSettingPayload.serializer(), row.payload) runCatching {
}.getOrNull()?.let { "${row.kind}:${it.kind}:${it.channel}" } 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. // A reorder is the list's whole new order, so only the last one counts.
MutationKind.PLAYLIST_REORDER -> runCatching { MutationKind.PLAYLIST_REORDER ->
json.decodeFromString(PlaylistReorderPayload.serializer(), row.payload) runCatching {
}.getOrNull()?.let { "${row.kind}:${it.playlistId}" } json.decodeFromString(PlaylistReorderPayload.serializer(), row.payload)
}.getOrNull()?.let { "${row.kind}:${it.playlistId}" }
// One preference per user, so every normalization row shares one key. // One preference per user, so every normalization row shares one key.
MutationKind.NORMALIZATION_SET -> runCatching { MutationKind.NORMALIZATION_SET ->
json.decodeFromString(NormalizationPrefs.serializer(), row.payload) runCatching {
}.getOrNull()?.let { row.kind } 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 * 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). * playlist change (or won't decode, which its dispatcher then DROPs).
*/ */
internal fun playlistIdOf(row: CachedMutationEntity, json: Json): String? = runCatching { internal fun playlistIdOf(
when (row.kind) { row: CachedMutationEntity,
MutationKind.PLAYLIST_APPEND -> json: Json,
json.decodeFromString(PlaylistAppendPayload.serializer(), row.payload).playlistId ): String? =
MutationKind.PLAYLIST_CREATE -> runCatching {
json.decodeFromString(PlaylistCreatePayload.serializer(), row.payload).id when (row.kind) {
MutationKind.PLAYLIST_UPDATE -> MutationKind.PLAYLIST_APPEND ->
json.decodeFromString(PlaylistUpdatePayload.serializer(), row.payload).playlistId json.decodeFromString(PlaylistAppendPayload.serializer(), row.payload).playlistId
MutationKind.PLAYLIST_DELETE -> MutationKind.PLAYLIST_CREATE ->
json.decodeFromString(PlaylistDeletePayload.serializer(), row.payload).playlistId json.decodeFromString(PlaylistCreatePayload.serializer(), row.payload).id
MutationKind.PLAYLIST_REMOVE_TRACK -> MutationKind.PLAYLIST_UPDATE ->
json.decodeFromString(PlaylistRemoveTrackPayload.serializer(), row.payload).playlistId json.decodeFromString(PlaylistUpdatePayload.serializer(), row.payload).playlistId
MutationKind.PLAYLIST_REORDER -> MutationKind.PLAYLIST_DELETE ->
json.decodeFromString(PlaylistReorderPayload.serializer(), row.payload).playlistId json.decodeFromString(PlaylistDeletePayload.serializer(), row.payload).playlistId
else -> null MutationKind.PLAYLIST_REMOVE_TRACK ->
} json.decodeFromString(PlaylistRemoveTrackPayload.serializer(), row.payload).playlistId
}.getOrNull() MutationKind.PLAYLIST_REORDER ->
json.decodeFromString(PlaylistReorderPayload.serializer(), row.payload).playlistId
else -> null
}
}.getOrNull()
@@ -13,8 +13,10 @@ import javax.inject.Inject
* accessor. Mirrors PlaybackErrorViewModel. * accessor. Mirrors PlaybackErrorViewModel.
*/ */
@HiltViewModel @HiltViewModel
class OfflineWriteHintViewModel @Inject constructor( class OfflineWriteHintViewModel
mutationQueue: MutationQueue, @Inject
) : ViewModel() { constructor(
val messages: Flow<String> = mutationQueue.userEnqueueHints mutationQueue: MutationQueue,
} ) : ViewModel() {
val messages: Flow<String> = mutationQueue.userEnqueueHints
}
@@ -3,8 +3,6 @@ package com.fabledsword.minstrel.cache.sync
import com.fabledsword.minstrel.api.ErrorCopy import com.fabledsword.minstrel.api.ErrorCopy
import com.fabledsword.minstrel.api.endpoints.SyncApi import com.fabledsword.minstrel.api.endpoints.SyncApi
import com.fabledsword.minstrel.auth.AuthStore 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.CachedAlbumDao
import com.fabledsword.minstrel.cache.db.dao.CachedArtistDao import com.fabledsword.minstrel.cache.db.dao.CachedArtistDao
import com.fabledsword.minstrel.cache.db.dao.CachedTrackDao import com.fabledsword.minstrel.cache.db.dao.CachedTrackDao
@@ -13,6 +11,8 @@ import com.fabledsword.minstrel.cache.db.entities.CachedAlbumEntity
import com.fabledsword.minstrel.cache.db.entities.CachedArtistEntity import com.fabledsword.minstrel.cache.db.entities.CachedArtistEntity
import com.fabledsword.minstrel.cache.db.entities.CachedTrackEntity import com.fabledsword.minstrel.cache.db.entities.CachedTrackEntity
import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity 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.di.ApplicationScope
import com.fabledsword.minstrel.models.wire.SyncAlbumWire import com.fabledsword.minstrel.models.wire.SyncAlbumWire
import com.fabledsword.minstrel.models.wire.SyncArtistWire import com.fabledsword.minstrel.models.wire.SyncArtistWire
@@ -50,199 +50,204 @@ import javax.inject.Singleton
* cursor to 0 and pulls the full entity set again (see [resetCursor]). * cursor to 0 and pulls the full entity set again (see [resetCursor]).
*/ */
@Singleton @Singleton
class SyncController @Inject constructor( class SyncController
private val syncMetadataDao: SyncMetadataDao, @Inject
private val artistDao: CachedArtistDao, constructor(
private val albumDao: CachedAlbumDao, private val syncMetadataDao: SyncMetadataDao,
private val trackDao: CachedTrackDao, private val artistDao: CachedArtistDao,
private val authStore: AuthStore, private val albumDao: CachedAlbumDao,
@ApplicationScope private val scope: CoroutineScope, private val trackDao: CachedTrackDao,
networkStatus: NetworkStatusController, private val authStore: AuthStore,
retrofit: Retrofit, @ApplicationScope private val scope: CoroutineScope,
) { networkStatus: NetworkStatusController,
private val api: SyncApi = retrofit.create() retrofit: Retrofit,
// 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)
/**
* 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() }
}
}
/** 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() }) private val api: SyncApi = retrofit.create()
if (albums.isNotEmpty()) albumDao.upsertAll(albums.map { it.toEntity() })
if (tracks.isNotEmpty()) trackDao.upsertAll(tracks.map { it.toEntity() })
}
private suspend fun applyDeletes( // Single in-flight guard: the cookie + health-recovery triggers (and a
artistIds: List<String>, // pull-to-refresh) can fire concurrently; coalesce them into one pass.
albumIds: List<String>, private val mutex = Mutex()
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) { private val lastSyncErrorInternal = MutableStateFlow<String?>(null)
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 * Human copy for the most recent sync failure; null after any clean
// path the next page is requested with cursor=0 after * pass. Lets the Library screen distinguish "empty because the first
// resetting our cursor. The following pages carry the full * sync failed" (show error + retry) from "genuinely empty library"
// entity set, which upsertAll overwrites the existing rows * (show welcome copy) — a failed sync over a populated cache stays
// with — old rows for entities the server no longer knows * silent, since the cached content is still the better surface.
// about linger until MetadataProvider's refresh meets their */
// 404 and drops them. val lastSyncError: StateFlow<String?> = lastSyncErrorInternal.asStateFlow()
syncMetadataDao.upsert(
SyncMetadataEntity(id = 0, cursor = 0, lastSyncAt = null),
)
}
private companion object { init {
const val HTTP_OK = 200 scope.launch {
const val HTTP_NO_CONTENT = 204 authStore.sessionCookie
const val HTTP_GONE = 410 .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() }
}
}
// A guard, not a budget: 1000 pages is a million changes, far past /** Public entry-point for "Sync now" affordances. Swallows errors into [lastSyncError]. */
// anything a library writes between two app starts. suspend fun syncSafe() {
const val MAX_PAGES_PER_PASS = 1000 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) ── // ── Mappers (file-internal — sync wire types stay out of UI) ──
private fun SyncArtistWire.toEntity(): CachedArtistEntity = CachedArtistEntity( private fun SyncArtistWire.toEntity(): CachedArtistEntity =
id = id, CachedArtistEntity(
name = name, id = id,
sortName = sortName, name = name,
mbid = mbid, sortName = sortName,
artistThumbPath = artistThumbPath, mbid = mbid,
artistFanartPath = artistFanartPath, artistThumbPath = artistThumbPath,
) artistFanartPath = artistFanartPath,
)
private fun SyncAlbumWire.toEntity(): CachedAlbumEntity = CachedAlbumEntity( private fun SyncAlbumWire.toEntity(): CachedAlbumEntity =
id = id, CachedAlbumEntity(
artistId = artistId, id = id,
title = title, artistId = artistId,
sortTitle = sortTitle, title = title,
releaseDate = releaseDate, sortTitle = sortTitle,
coverPath = coverArtPath, releaseDate = releaseDate,
mbid = mbid, coverPath = coverArtPath,
albumGain = albumGain, mbid = mbid,
albumPeak = albumPeak, albumGain = albumGain,
) albumPeak = albumPeak,
)
private fun SyncTrackWire.toEntity(): CachedTrackEntity = CachedTrackEntity( private fun SyncTrackWire.toEntity(): CachedTrackEntity =
id = id, CachedTrackEntity(
albumId = albumId, id = id,
artistId = artistId, albumId = albumId,
title = title, artistId = artistId,
durationMs = durationMs, title = title,
trackNumber = trackNumber, durationMs = durationMs,
discNumber = discNumber, trackNumber = trackNumber,
filePath = filePath, discNumber = discNumber,
fileFormat = fileFormat, filePath = filePath,
genre = genre, fileFormat = fileFormat,
missing = missing, genre = genre,
trackGain = trackGain, missing = missing,
trackPeak = trackPeak, trackGain = trackGain,
) trackPeak = trackPeak,
)
@@ -36,76 +36,87 @@ import javax.inject.Singleton
* repositories can also collect this to gate retry loops. * repositories can also collect this to gate retry loops.
*/ */
@Singleton @Singleton
class ConnectivityObserver @Inject constructor( class ConnectivityObserver
@ApplicationContext context: Context, @Inject
) { constructor(
private val cm = context.getSystemService(ConnectivityManager::class.java) @ApplicationContext context: Context,
) {
private val cm = context.getSystemService(ConnectivityManager::class.java)
val online: Flow<Boolean> = callbackFlow { val online: Flow<Boolean> =
val request = NetworkRequest.Builder() callbackFlow {
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) val request =
.build() NetworkRequest
val callback = object : ConnectivityManager.NetworkCallback() { .Builder()
override fun onAvailable(network: Network) { .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.
trySend(hasActiveNetwork()) trySend(hasActiveNetwork())
} awaitClose { cm.unregisterNetworkCallback(callback) }
override fun onLost(network: Network) { }.distinctUntilChanged()
trySend(hasActiveNetwork())
} /**
override fun onCapabilitiesChanged( * Whether the network the device is using now is unmetered: Wi-Fi or
network: Network, * Ethernet, but not mobile data or a hotspot Android marks metered.
capabilities: NetworkCapabilities, * Downloads the user did not start (the liked-song downloads) wait for
) { * this.
// INTERNET only -- NOT VALIDATED. A WAN/validation flicker */
// must not read as "device offline" when the LAN (and the val unmetered: Flow<Boolean> =
// Minstrel server on it) is still reachable. /healthz is the callbackFlow {
// authority on server reachability. val callback =
trySend( object : ConnectivityManager.NetworkCallback() {
capabilities.hasCapability( override fun onCapabilitiesChanged(
NetworkCapabilities.NET_CAPABILITY_INTERNET, 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)
} }
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 {
* Whether the network the device is using now is unmetered: Wi-Fi or val caps = cm.activeNetwork?.let { cm.getNetworkCapabilities(it) }
* Ethernet, but not mobile data or a hotspot Android marks metered. return caps != null &&
* Downloads the user did not start (the liked-song downloads) wait for caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
* 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,140 +55,155 @@ private const val ARBITRATE_MIN_GAP_MS = 2_000L
* [com.fabledsword.minstrel.MinstrelApplication]. * [com.fabledsword.minstrel.MinstrelApplication].
*/ */
@Singleton @Singleton
class NetworkStatusController @Inject constructor( class NetworkStatusController
@ApplicationScope private val scope: CoroutineScope, @Inject
connectivity: ConnectivityObserver, constructor(
private val authStore: AuthStore, @ApplicationScope private val scope: CoroutineScope,
retrofit: Retrofit, connectivity: ConnectivityObserver,
) : DefaultLifecycleObserver { private val authStore: AuthStore,
private val api: HealthzApi = retrofit.create(HealthzApi::class.java) retrofit: Retrofit,
private val machine = ReachabilityMachine() ) : DefaultLifecycleObserver {
private val lastProbeAtMs = AtomicLong(0) private val api: HealthzApi = retrofit.create(HealthzApi::class.java)
private val machine = ReachabilityMachine()
private val lastProbeAtMs = AtomicLong(0)
private val stateInternal = MutableStateFlow(ServerHealth.Healthy) private val stateInternal = MutableStateFlow(ServerHealth.Healthy)
val state: StateFlow<ServerHealth> = stateInternal.asStateFlow() val state: StateFlow<ServerHealth> = stateInternal.asStateFlow()
private val versionInternal = MutableStateFlow(VersionResult.SKIPPED) private val versionInternal = MutableStateFlow(VersionResult.SKIPPED)
val versionResult: StateFlow<VersionResult> = versionInternal.asStateFlow() val versionResult: StateFlow<VersionResult> = versionInternal.asStateFlow()
private sealed interface Intent { private sealed interface Intent {
data class Link(val up: Boolean) : Intent data class Link(
data class Probe(val resp: HealthzResponse?) : Intent val up: Boolean,
object OpSuccess : Intent ) : Intent
object OpFailure : Intent
}
private val intents = Channel<Intent>(Channel.UNLIMITED) data class Probe(
val resp: HealthzResponse?,
) : Intent
init { object OpSuccess : Intent
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
scope.launch { reduceLoop() } object OpFailure : Intent
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. */ private val intents = Channel<Intent>(Channel.UNLIMITED)
fun reportSuccess() {
if (stateInternal.value != ServerHealth.Healthy) intents.trySend(Intent.OpSuccess)
}
/** A real network op failed — triggers /healthz arbitration. No-op when already Offline. */ init {
fun reportFailure() { ProcessLifecycleOwner.get().lifecycle.addObserver(this)
if (stateInternal.value == ServerHealth.Offline) return scope.launch { reduceLoop() }
intents.trySend(Intent.OpFailure) scope.launch {
} connectivity.online.collect { up ->
intents.trySend(Intent.Link(up))
/** One-shot recheck for pull-to-refresh and the banner. */ if (up) probeOnce()
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()) scope.launch { pollLoop() }
} }
}
private fun applyProbe(resp: HealthzResponse?, now: Long) { /** A real server op verifiably succeeded — self-proving recovery. Cheap; safe on hot paths. */
if (resp == null) { fun reportSuccess() {
machine.onProbeFailure(now) if (stateInternal.value != ServerHealth.Healthy) intents.trySend(Intent.OpSuccess)
} else {
machine.onSuccess()
versionInternal.value = versionResultFor(resp)
} }
}
private fun emit(next: ServerHealth) { /** A real network op failed — triggers /healthz arbitration. No-op when already Offline. */
if (stateInternal.value != next) { fun reportFailure() {
Timber.w("NetworkStatus -> %s", next) if (stateInternal.value == ServerHealth.Offline) return
stateInternal.value = next intents.trySend(Intent.OpFailure)
} }
}
private suspend fun pollLoop() { /** One-shot recheck for pull-to-refresh and the banner. */
probeOnce() fun recheck() {
while (true) { scope.launch { probeOnce(force = true) }
val interval = }
if (stateInternal.value == ServerHealth.Healthy) POLL_HEALTHY_MS
else POLL_DEGRADED_MS /**
delay(interval) * 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())
}
}
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() 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
}
} }
} }
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 * Reactive [ServerHealth] snapshot provided once at the app root. Lets leaf
* composables (TrackRow gating, write-affordance disabling) branch on health * composables (TrackRow gating, write-affordance disabling) branch on health
@@ -41,7 +41,6 @@ internal const val CORROBORATION_MIN_SPACING_MS = 3_000L
* sustained-time backstop. * sustained-time backstop.
*/ */
class ReachabilityMachine { class ReachabilityMachine {
private enum class Reachability { Reachable, Unstable, Unreachable } private enum class Reachability { Reachable, Unstable, Unreachable }
private var linkUp = true private var linkUp = true
@@ -89,12 +88,13 @@ class ReachabilityMachine {
} }
} }
fun health(): ServerHealth = when { fun health(): ServerHealth =
!linkUp -> ServerHealth.Offline when {
reachability == Reachability.Reachable -> ServerHealth.Healthy !linkUp -> ServerHealth.Offline
reachability == Reachability.Unstable -> ServerHealth.Unstable reachability == Reachability.Reachable -> ServerHealth.Healthy
else -> ServerHealth.ServerDown reachability == Reachability.Unstable -> ServerHealth.Unstable
} else -> ServerHealth.ServerDown
}
private fun shouldEscalate(nowMs: Long): Boolean { private fun shouldEscalate(nowMs: Long): Boolean {
val corroborated = recentOpFailures.size >= CORROBORATION_OP_THRESHOLD val corroborated = recentOpFailures.size >= CORROBORATION_OP_THRESHOLD
@@ -29,21 +29,23 @@ private const val HEALTHZ_PATH = "/healthz"
* already constructed (construct-the-singleton trick in MinstrelApplication). * already constructed (construct-the-singleton trick in MinstrelApplication).
*/ */
@Singleton @Singleton
class ReachabilityReportingInterceptor @Inject constructor( class ReachabilityReportingInterceptor
private val networkStatus: Lazy<NetworkStatusController>, @Inject
) : Interceptor { constructor(
override fun intercept(chain: Interceptor.Chain): Response { private val networkStatus: Lazy<NetworkStatusController>,
val request = chain.request() ) : Interceptor {
val isMinstrel = request.url.host == PLACEHOLDER_HOST override fun intercept(chain: Interceptor.Chain): Response {
val isHealthz = request.url.encodedPath.endsWith(HEALTHZ_PATH) val request = chain.request()
if (!isMinstrel || isHealthz) return chain.proceed(request) val isMinstrel = request.url.host == PLACEHOLDER_HOST
return try { val isHealthz = request.url.encodedPath.endsWith(HEALTHZ_PATH)
val response = chain.proceed(request) if (!isMinstrel || isHealthz) return chain.proceed(request)
if (response.isSuccessful) networkStatus.get().reportSuccess() return try {
response val response = chain.proceed(request)
} catch (e: IOException) { if (response.isSuccessful) networkStatus.get().reportSuccess()
networkStatus.get().reportFailure() response
throw e } catch (e: IOException) {
networkStatus.get().reportFailure()
throw e
}
} }
} }
}
@@ -19,9 +19,10 @@ import kotlinx.coroutines.flow.map
* heals itself the moment connectivity returns instead of sitting in the * heals itself the moment connectivity returns instead of sitting in the
* failed state until a manual pull-to-refresh. * failed state until a manual pull-to-refresh.
*/ */
fun NetworkStatusController.recoveries(): Flow<Unit> = state fun NetworkStatusController.recoveries(): Flow<Unit> =
.map { it == ServerHealth.Healthy } state
.distinctUntilChanged() .map { it == ServerHealth.Healthy }
.drop(1) .distinctUntilChanged()
.filter { it } .drop(1)
.map { } .filter { it }
.map { }
@@ -43,12 +43,14 @@ private const val BACK_ONLINE_FLASH_MS = 2_000L
* re-wrapping StateFlow — the controller's is already app-scoped and warm. * re-wrapping StateFlow — the controller's is already app-scoped and warm.
*/ */
@HiltViewModel @HiltViewModel
class ConnectivityBannerViewModel @Inject constructor( class ConnectivityBannerViewModel
networkStatus: NetworkStatusController, @Inject
@Suppress("UnusedPrivateProperty") savedStateHandle: SavedStateHandle, constructor(
) : ViewModel() { networkStatus: NetworkStatusController,
val health: StateFlow<ServerHealth> = networkStatus.state @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 * Shell banner. Tells the user *why* they're degraded — no link vs server-down
@@ -57,9 +59,7 @@ class ConnectivityBannerViewModel @Inject constructor(
* recovery is unmistakable. Sentence case, understated voice (design system). * recovery is unmistakable. Sentence case, understated voice (design system).
*/ */
@Composable @Composable
fun ConnectionErrorBanner( fun ConnectionErrorBanner(viewModel: ConnectivityBannerViewModel = hiltViewModel()) {
viewModel: ConnectivityBannerViewModel = hiltViewModel(),
) {
val health by viewModel.health.collectAsStateWithLifecycle() val health by viewModel.health.collectAsStateWithLifecycle()
var showBackOnline by remember { mutableStateOf(false) } var showBackOnline by remember { mutableStateOf(false) }
var wasDown by remember { mutableStateOf(false) } var wasDown by remember { mutableStateOf(false) }
@@ -89,7 +89,10 @@ fun ConnectionErrorBanner(
} }
@Composable @Composable
private fun BannerContent(health: ServerHealth, backOnline: Boolean) { private fun BannerContent(
health: ServerHealth,
backOnline: Boolean,
) {
val scheme = MaterialTheme.colorScheme val scheme = MaterialTheme.colorScheme
val background: Color val background: Color
val foreground: Color val foreground: Color
@@ -108,10 +111,11 @@ private fun BannerContent(health: ServerHealth, backOnline: Boolean) {
} }
} }
Row( Row(
modifier = Modifier modifier =
.fillMaxWidth() Modifier
.background(background) .fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 10.dp), .background(background)
.padding(horizontal = 16.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp), horizontalArrangement = Arrangement.spacedBy(12.dp),
) { ) {
@@ -124,11 +128,15 @@ private fun BannerContent(health: ServerHealth, backOnline: Boolean) {
} }
} }
private fun bannerText(health: ServerHealth, backOnline: Boolean): String = when { private fun bannerText(
backOnline -> "Back online." health: ServerHealth,
health == ServerHealth.Offline -> "No connection — check Wi-Fi or mobile data." backOnline: Boolean,
health == ServerHealth.ServerDown -> ): String =
"Server unreachable — your cached content is still available." when {
health == ServerHealth.Unstable -> "Reconnecting…" backOnline -> "Back online."
else -> "" 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,11 +20,12 @@ annotation class ApplicationScope
object AppModule { object AppModule {
@Provides @Provides
@Singleton @Singleton
fun provideJson(): Json = Json { fun provideJson(): Json =
ignoreUnknownKeys = true Json {
explicitNulls = false ignoreUnknownKeys = true
coerceInputValues = true explicitNulls = false
} coerceInputValues = true
}
@Provides @Provides
@Singleton @Singleton
@@ -5,9 +5,9 @@ import android.content.Context
import android.content.Intent import android.content.Intent
import android.content.IntentFilter import android.content.IntentFilter
import android.os.PowerManager import android.os.PowerManager
import androidx.core.content.ContextCompat
import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleOwner
import androidx.core.content.ContextCompat
import androidx.lifecycle.ProcessLifecycleOwner import androidx.lifecycle.ProcessLifecycleOwner
import com.fabledsword.minstrel.auth.AuthController import com.fabledsword.minstrel.auth.AuthController
import com.fabledsword.minstrel.auth.AuthStore import com.fabledsword.minstrel.auth.AuthStore
@@ -52,338 +52,388 @@ import javax.inject.Singleton
*/ */
@Suppress("TooManyFunctions") // one collector + one (un)register pair per signal; cohesive @Suppress("TooManyFunctions") // one collector + one (un)register pair per signal; cohesive
@Singleton @Singleton
class DiagnosticsReporter @Inject constructor( class DiagnosticsReporter
@ApplicationContext private val context: Context, @Inject
@ApplicationScope private val scope: CoroutineScope, constructor(
private val dao: DiagnosticEventDao, @ApplicationContext private val context: Context,
private val authController: AuthController, @ApplicationScope private val scope: CoroutineScope,
private val authStore: AuthStore, private val dao: DiagnosticEventDao,
private val connectivity: ConnectivityObserver, private val authController: AuthController,
private val networkStatus: NetworkStatusController, private val authStore: AuthStore,
private val playerController: PlayerController, private val connectivity: ConnectivityObserver,
private val outputPicker: OutputPickerController, private val networkStatus: NetworkStatusController,
private val remoteState: RemotePlayerState, private val playerController: PlayerController,
private val json: Json, private val outputPicker: OutputPickerController,
) { private val remoteState: RemotePlayerState,
@Volatile private var enabled = false private val json: Json,
private var collectorJob: Job? = null ) {
private var powerReceiver: BroadcastReceiver? = null @Volatile private var enabled = false
private var lifecycleObserver: DefaultLifecycleObserver? = null private var collectorJob: Job? = null
private var powerReceiver: BroadcastReceiver? = null
private var lifecycleObserver: DefaultLifecycleObserver? = null
init { init {
// Gate = account flag (currentUser.debugModeEnabled) AND not the // Gate = account flag (currentUser.debugModeEnabled) AND not the
// per-device local opt-out. // per-device local opt-out.
scope.launch { scope.launch {
combine(authController.currentUser, authStore.diagnosticsOptOut) { user, optOut -> combine(authController.currentUser, authStore.diagnosticsOptOut) { user, optOut ->
(user?.debugModeEnabled == true) && !optOut (user?.debugModeEnabled == true) && !optOut
}.distinctUntilChanged().collect { setEnabled(it) } }.distinctUntilChanged().collect { setEnabled(it) }
} }
// Periodically re-pull /me so a remote admin flip propagates // Periodically re-pull /me so a remote admin flip propagates
// without a re-login or app restart. // without a re-login or app restart.
scope.launch { scope.launch {
while (true) { while (true) {
delay(GATE_REFRESH_MS) delay(GATE_REFRESH_MS)
authController.refreshProfile() authController.refreshProfile()
}
} }
} }
}
private fun setEnabled(value: Boolean) { private fun setEnabled(value: Boolean) {
if (value == enabled) return if (value == enabled) return
enabled = value enabled = value
if (value) start() else stop() 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 stop() { private fun start() {
collectorJob?.cancel() registerPowerReceiver()
collectorJob = null registerLifecycleObserver()
unregisterPowerReceiver() collectorJob =
unregisterLifecycleObserver() scope.launch {
// Off means off: drop any unsent buffer (honors the user OFF record("lifecycle", buildJsonObject { put("event", "reporting_started") })
// intent and avoids leaking data captured before disable). launch { collectConnectivity() }
scope.launch { runCatching { dao.clear() } } launch { collectServerHealth() }
} launch { collectUpnpDrops() }
launch { collectPlayerState() }
private suspend fun collectConnectivity() { launch { collectTrackChanges() }
connectivity.online.distinctUntilChanged().collect { online -> launch { collectTransportFlap() }
record("connectivity", buildJsonObject { launch { collectRoutes() }
put("event", "online_changed") launch { heartbeatLoop() }
put("online", online) }
})
} }
}
private suspend fun collectServerHealth() { private fun stop() {
// state is a StateFlow — already conflated/distinct, so no collectorJob?.cancel()
// distinctUntilChanged (it's a deprecation warning = build error). collectorJob = null
networkStatus.state.collect { s -> unregisterPowerReceiver()
record("connectivity", buildJsonObject { unregisterLifecycleObserver()
put("event", "server_health") // Off means off: drop any unsent buffer (honors the user OFF
put("state", s.name) // intent and avoids leaking data captured before disable).
}) scope.launch { runCatching { dao.clear() } }
} }
}
private suspend fun collectUpnpDrops() { private suspend fun collectConnectivity() {
playerController.dropEvents.collect { msg -> connectivity.online.distinctUntilChanged().collect { online ->
record("upnp_sync", buildJsonObject { record(
put("event", "drop") "connectivity",
put("message", msg) buildJsonObject {
}) put("event", "online_changed")
} put("online", online)
} },
)
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 private suspend fun collectServerHealth() {
// skip-induced local↔Sonos desync at the INSTANT it happens, which the // state is a StateFlow — already conflated/distinct, so no
// 45s heartbeat misses. Note: uiState is a conflated StateFlow, so a // distinctUntilChanged (it's a deprecation warning = build error).
// very rapid skip burst may coalesce intermediate indices (we still get networkStatus.state.collect { s ->
// the boundaries + the local-vs-Sonos snapshot). record(
private suspend fun collectTrackChanges() { "connectivity",
playerController.uiState buildJsonObject {
.map { it.queueIndex to it.currentTrack?.id } put("event", "server_health")
.distinctUntilChanged() put("state", s.name)
.collect { (index, _) -> },
val ui = playerController.uiState.value )
val casting = outputPicker.routesState.value.current.protocol != }
}
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 !=
OutputRoute.Protocol.SYSTEM OutputRoute.Protocol.SYSTEM
record("playback", buildJsonObject { val spanMs = recent.last().atElapsedMs - recent.first().atElapsedMs
put("event", "track_change") record(
put("local_index", index) "upnp_sync",
// Track IDENTITY, not just index — indices wobble across buildJsonObject {
// re-casts, so the id + Sonos URI make a desync unambiguous. 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_track_id", ui.currentTrack?.id ?: "")
put("local_pos_ms", ui.positionMs) put("local_pos_ms", ui.positionMs)
putSonos(this, casting) putSonos(this, casting)
put("upnp_loading", ui.isUpnpLoading) put("upnp_loading", ui.isUpnpLoading)
put("server_health", networkStatus.state.value.name) put("server_health", networkStatus.state.value.name)
put("route", outputPicker.routesState.value.current.name) put("route", outputPicker.routesState.value.current.name)
}) addPowerFields(this)
} },
}
/**
* 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 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
} }
} }
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,84 +38,93 @@ import javax.inject.Singleton
* uploader treats as success so the buffer drains either way. * uploader treats as success so the buffer drains either way.
*/ */
@Singleton @Singleton
class DiagnosticsUploader @Inject constructor( class DiagnosticsUploader
private val dao: DiagnosticEventDao, @Inject
private val authStore: AuthStore, constructor(
private val json: Json, private val dao: DiagnosticEventDao,
@ApplicationScope private val scope: CoroutineScope, private val authStore: AuthStore,
networkStatus: NetworkStatusController, private val json: Json,
retrofit: Retrofit, @ApplicationScope private val scope: CoroutineScope,
) { networkStatus: NetworkStatusController,
private val api: DiagnosticsApi = retrofit.create() retrofit: Retrofit,
private val mutex = Mutex() ) {
private val api: DiagnosticsApi = retrofit.create()
private val mutex = Mutex()
init { init {
scope.launch { scope.launch {
while (true) { while (true) {
delay(UPLOAD_INTERVAL_MS) delay(UPLOAD_INTERVAL_MS)
drainSafe() drainSafe()
}
}
scope.launch {
authStore.sessionCookie
.filterNotNull()
.distinctUntilChanged()
.collect { drainSafe() }
}
scope.launch {
networkStatus.state
.map { it == ServerHealth.Healthy }
.distinctUntilChanged()
.filter { it }
.collect { drainSafe() }
} }
} }
scope.launch {
authStore.sessionCookie.filterNotNull().distinctUntilChanged().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()
}
} }
scope.launch {
networkStatus.state private suspend fun drain(clientId: String) {
.map { it == ServerHealth.Healthy } var more = true
.distinctUntilChanged() while (more) {
.filter { it } val batch = runCatching { dao.takeBatch(BATCH_SIZE) }.getOrNull().orEmpty()
.collect { drainSafe() } 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
} }
} }
/** 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,157 +63,171 @@ private const val EVENTS_BUFFER_CAPACITY = 64
* needing a separate path through here. * needing a separate path through here.
*/ */
@Singleton @Singleton
class EventsStream @Inject constructor( class EventsStream
private val authStore: AuthStore, @Inject
@ApplicationScope private val scope: CoroutineScope, constructor(
private val okHttpClient: OkHttpClient, private val authStore: AuthStore,
private val json: Json, @ApplicationScope private val scope: CoroutineScope,
private val connectivity: ConnectivityObserver, private val okHttpClient: OkHttpClient,
) { private val json: Json,
private val factory = EventSources.createFactory(okHttpClient) private val connectivity: ConnectivityObserver,
) {
private val factory = EventSources.createFactory(okHttpClient)
private val emitter = MutableSharedFlow<LiveEvent>( private val emitter =
replay = 0, MutableSharedFlow<LiveEvent>(
extraBufferCapacity = EVENTS_BUFFER_CAPACITY, replay = 0,
onBufferOverflow = BufferOverflow.DROP_OLDEST, extraBufferCapacity = EVENTS_BUFFER_CAPACITY,
) onBufferOverflow = BufferOverflow.DROP_OLDEST,
val events: SharedFlow<LiveEvent> = emitter.asSharedFlow() )
val events: SharedFlow<LiveEvent> = emitter.asSharedFlow()
private val connectedState = MutableStateFlow(false) private val connectedState = MutableStateFlow(false)
val connected: StateFlow<Boolean> = connectedState.asStateFlow() 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
init { @Volatile private var signedIn = false
scope.launch { private var reconnectJob: Job? = null
authStore.sessionCookie private var backoffMs = ReconnectBackoff.BASE_MS
.map { !it.isNullOrEmpty() }
.distinctUntilChanged() init {
.collect { isSignedIn -> scope.launch {
signedIn = isSignedIn authStore.sessionCookie
if (isSignedIn) { .map { !it.isNullOrEmpty() }
backoffMs = ReconnectBackoff.BASE_MS .distinctUntilChanged()
connect() .collect { isSignedIn ->
} else { signedIn = isSignedIn
disconnect() 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()
} }
} }
scope.launch {
connectivity.online.collect { up -> if (up) reconnectNow() }
}
}
/** private fun openSubscription(): EventSource {
* Cuts a pending backoff short: reconnects at once and starts the ladder val request =
* over. For a network that has just come up, or the app coming to the Request
* foreground, where waiting out a five-minute backoff would leave the .Builder()
* server unheard from for nothing. Does nothing while a stream is open or .url("http://placeholder.invalid$SSE_PATH")
* opening. .header("Accept", "text/event-stream")
*/ .build()
@Synchronized return factory.newEventSource(request, Listener())
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( private inner class Listener : EventSourceListener() {
eventSource: EventSource, override fun onOpen(
id: String?, eventSource: EventSource,
type: String?, 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, data: String,
) { ): LiveEvent? =
parseFrame(kind = type, data = data)?.let(emitter::tryEmit) try {
} val payload = json.parseToJsonElement(data).jsonObject
val resolvedKind = kind ?: payload["kind"]?.jsonPrimitive?.contentOrNull
override fun onClosed(eventSource: EventSource) { if (resolvedKind.isNullOrEmpty()) {
scheduleReconnect() null
} } else {
LiveEvent(
override fun onFailure( kind = resolvedKind,
eventSource: EventSource, userId = payload["user_id"]?.jsonPrimitive?.contentOrNull.orEmpty(),
t: Throwable?, data = (payload["data"] as? JsonObject) ?: JsonObject(emptyMap()),
response: Response?, )
) { }
scheduleReconnect() } catch (
} @Suppress("TooGenericExceptionCaught") _: Throwable,
) {
null
}
} }
/**
* 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,57 +28,58 @@ import javax.inject.Singleton
* stream reconnects and the re-refresh avoids stale data flashing. * stream reconnects and the re-refresh avoids stale data flashing.
*/ */
@Singleton @Singleton
class LiveEventsDispatcher @Inject constructor( class LiveEventsDispatcher
private val eventsStream: EventsStream, @Inject
private val likes: LikesRepository, constructor(
private val notifications: NotificationsRepository, private val eventsStream: EventsStream,
@ApplicationScope private val scope: CoroutineScope, private val likes: LikesRepository,
) : DefaultLifecycleObserver { private val notifications: NotificationsRepository,
@ApplicationScope private val scope: CoroutineScope,
) : DefaultLifecycleObserver {
init {
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
scope.launch {
eventsStream.events.collect { e -> handle(e) }
}
}
init { private fun handle(event: LiveEvent) {
ProcessLifecycleOwner.get().lifecycle.addObserver(this) when (event.kind) {
scope.launch { "track.liked",
eventsStream.events.collect { e -> handle(e) } "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() }
}
} }
} }
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,7 +24,10 @@ internal object ReconnectBackoff {
fun next(currentMs: Long): Long = (currentMs * 2).coerceAtMost(MAX_MS) fun next(currentMs: Long): Long = (currentMs * 2).coerceAtMost(MAX_MS)
/** [ms] moved by up to a quarter either way. */ /** [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 val spread = ms * JITTER
return (ms + random.nextDouble(-spread, spread)).toLong() return (ms + random.nextDouble(-spread, spread)).toLong()
} }
@@ -49,29 +49,33 @@ data class HistoryPage(
* ordering/paging bookkeeping for no UX gain. * ordering/paging bookkeeping for no UX gain.
*/ */
@Singleton @Singleton
class HistoryRepository @Inject constructor( class HistoryRepository
private val snapshotDao: CachedHistorySnapshotDao, @Inject
private val json: Json, constructor(
retrofit: Retrofit, private val snapshotDao: CachedHistorySnapshotDao,
) { private val json: Json,
private val api: HistoryApi = retrofit.create() retrofit: Retrofit,
) {
private val api: HistoryApi = retrofit.create()
fun observeHistory(): Flow<HistoryPage?> = fun observeHistory(): Flow<HistoryPage?> =
snapshotDao.observe().map { row -> snapshotDao.observe().map { row ->
row?.let { json.decodeFromString<HistoryPageWire>(it.json).toDomain() } 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))
} }
/** 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( private fun HistoryPageWire.toDomain(): HistoryPage =
entries = events.map { HistoryPage(
HistoryEntry(id = it.id, playedAt = it.playedAt, track = it.track.toDomain()) entries =
}, events.map {
hasMore = hasMore, HistoryEntry(id = it.id, playedAt = it.playedAt, track = it.track.toDomain())
) },
hasMore = hasMore,
)
@@ -1,10 +1,7 @@
package com.fabledsword.minstrel.history.ui package com.fabledsword.minstrel.history.ui
import androidx.compose.foundation.layout.Arrangement 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.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.items
import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.HorizontalDivider
@@ -26,12 +23,12 @@ import com.fabledsword.minstrel.history.data.HistoryRepository
import com.fabledsword.minstrel.models.TrackRef import com.fabledsword.minstrel.models.TrackRef
import com.fabledsword.minstrel.player.PlayerController import com.fabledsword.minstrel.player.PlayerController
import com.fabledsword.minstrel.shared.UiState 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.EmptyState
import com.fabledsword.minstrel.shared.widgets.ErrorRetry import com.fabledsword.minstrel.shared.widgets.ErrorRetry
import com.fabledsword.minstrel.shared.widgets.LoadingCentered import com.fabledsword.minstrel.shared.widgets.LoadingCentered
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
import com.fabledsword.minstrel.shared.widgets.TrackCoverThumb import com.fabledsword.minstrel.shared.widgets.TrackCoverThumb
import com.fabledsword.minstrel.shared.widgets.TrackRow
import com.fabledsword.minstrel.shared.widgets.trackactions.TrackActionsButton import com.fabledsword.minstrel.shared.widgets.trackactions.TrackActionsButton
import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job import kotlinx.coroutines.Job
@@ -56,56 +53,58 @@ private const val SHARE_STOP_TIMEOUT_MS = 5_000L
// ─── ViewModel ─────────────────────────────────────────────────────── // ─── ViewModel ───────────────────────────────────────────────────────
@HiltViewModel @HiltViewModel
class HistoryTabViewModel @Inject constructor( class HistoryTabViewModel
private val repository: HistoryRepository, @Inject
private val player: PlayerController, constructor(
networkStatus: NetworkStatusController, private val repository: HistoryRepository,
) : ViewModel() { private val player: PlayerController,
networkStatus: NetworkStatusController,
) : ViewModel() {
private val refreshError = MutableStateFlow<String?>(null)
private val refreshError = MutableStateFlow<String?>(null) /**
* 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,
)
/** init {
* Cache-first: emits the cached snapshot instantly (paints from refresh()
* disk on cold open), then SWR-refreshes underneath. Shows Error // Screen-level auto-recovery: re-pull when server
* only when there's nothing cached AND the refresh failed — a // health returns, so a load that failed offline heals unprompted.
* failed refresh over a populated cache stays silent. viewModelScope.launch {
*/ networkStatus.recoveries().collect { refresh() }
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,
)
init { fun refresh(): Job =
refresh() viewModelScope.launch {
// Screen-level auto-recovery: re-pull when server refreshError.value = null
// health returns, so a load that failed offline heals unprompted. runCatching { repository.refresh() }
viewModelScope.launch { .onFailure { refreshError.value = ErrorCopy.fromThrowable(it) }
networkStatus.recoveries().collect { refresh() } }
/** Plays the tapped track on its own. */
fun playTrack(track: TrackRef) {
if (track.streamUrl.isEmpty()) return
player.setQueue(listOf(track), initialIndex = 0, source = "history")
} }
} }
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 ──────────────────────────────────────────────────────
@Composable @Composable
@@ -121,22 +120,25 @@ fun HistoryTab(
PullToRefreshScaffold(onRefresh = { viewModel.refresh().join() }) { PullToRefreshScaffold(onRefresh = { viewModel.refresh().join() }) {
when (val s = state) { when (val s = state) {
UiState.Loading -> LoadingCentered() UiState.Loading -> LoadingCentered()
UiState.Empty -> EmptyState( UiState.Empty ->
title = "No listening history yet", EmptyState(
body = "Play something — your recent plays will show up here.", title = "No listening history yet",
) body = "Play something — your recent plays will show up here.",
is UiState.Error -> ErrorRetry( )
title = "Couldn't load history", is UiState.Error ->
message = s.message, ErrorRetry(
onRetry = { viewModel.refresh() }, title = "Couldn't load history",
) message = s.message,
is UiState.Success -> HistoryList( onRetry = { viewModel.refresh() },
entries = s.data, )
playingTrackId = playingTrackId, is UiState.Success ->
onPlay = viewModel::playTrack, HistoryList(
onNavigateToAlbum = onNavigateToAlbum, entries = s.data,
onNavigateToArtist = onNavigateToArtist, playingTrackId = playingTrackId,
) onPlay = viewModel::playTrack,
onNavigateToAlbum = onNavigateToAlbum,
onNavigateToArtist = onNavigateToArtist,
)
} }
} }
} }
@@ -215,8 +217,9 @@ private const val DAYS_PER_WEEK = 7L
* up the row over malformed timestamps. * up the row over malformed timestamps.
*/ */
private fun relativeTime(iso: String): String { private fun relativeTime(iso: String): String {
val parsed = runCatching { OffsetDateTime.parse(iso) }.getOrNull() val parsed =
?: return iso runCatching { OffsetDateTime.parse(iso) }.getOrNull()
?: return iso
val local = parsed.atZoneSameInstant(ZoneId.systemDefault()) val local = parsed.atZoneSameInstant(ZoneId.systemDefault())
val now = OffsetDateTime.now(ZoneId.systemDefault()) val now = OffsetDateTime.now(ZoneId.systemDefault())
val minutes = ChronoUnit.MINUTES.between(local, now) val minutes = ChronoUnit.MINUTES.between(local, now)
@@ -44,163 +44,167 @@ import javax.inject.Singleton
// Per-section observe accessors (one per Home row) inflate the function // Per-section observe accessors (one per Home row) inflate the function
// count past detekt's 11 default — accessor density, not complexity. // count past detekt's 11 default — accessor density, not complexity.
@Suppress("TooManyFunctions") @Suppress("TooManyFunctions")
class HomeRepository @Inject constructor( class HomeRepository
private val homeIndexDao: CachedHomeIndexDao, @Inject
private val metadataProvider: MetadataProvider, constructor(
private val prewarmer: HomeArtistPrewarmer, private val homeIndexDao: CachedHomeIndexDao,
retrofit: Retrofit, private val metadataProvider: MetadataProvider,
) { private val prewarmer: HomeArtistPrewarmer,
private val api: HomeApi = retrofit.create() retrofit: Retrofit,
private val meApi: MeApi = retrofit.create() ) {
private val api: HomeApi = retrofit.create()
private val meApi: MeApi = retrofit.create()
/** /**
* Caller's system-playlist build state for the Home placeholder * Caller's system-playlist build state for the Home placeholder
* cards. One-shot GET; the caller refreshes alongside the index. * cards. One-shot GET; the caller refreshes alongside the index.
*/ */
suspend fun getSystemPlaylistsStatus(): SystemPlaylistsStatus = suspend fun getSystemPlaylistsStatus(): SystemPlaylistsStatus =
meApi.getSystemPlaylistsStatus().let { meApi.getSystemPlaylistsStatus().let {
SystemPlaylistsStatus( SystemPlaylistsStatus(
inFlight = it.inFlight, inFlight = it.inFlight,
lastRunAt = it.lastRunAt, lastRunAt = it.lastRunAt,
lastError = it.lastError, 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,
) )
} }
fun observeRecentlyAddedAlbums(): Flow<List<HomeTile<AlbumRef>>> = private fun rowsFor(
observeAlbumSection(SECTION_RECENTLY_ADDED_ALBUMS) section: String,
entityType: String,
ids: List<String>,
): List<CachedHomeIndexEntity> =
ids.mapIndexed { index, id ->
CachedHomeIndexEntity(
section = section,
position = index,
entityType = entityType,
entityId = id,
)
}
fun observeRediscoverAlbums(): Flow<List<HomeTile<AlbumRef>>> = /**
observeAlbumSection(SECTION_REDISCOVER_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 observeRediscoverArtists(): Flow<List<HomeTile<ArtistRef>>> = @OptIn(ExperimentalCoroutinesApi::class)
observeArtistSection(SECTION_REDISCOVER_ARTISTS) private fun observeAlbumSection(section: String): Flow<List<HomeTile<AlbumRef>>> =
observeSectionIds(section).flatMapLatest { ids ->
fun observeMostPlayedTracks(): Flow<List<HomeTile<TrackRef>>> = if (ids.isEmpty()) {
observeTrackSection(SECTION_MOST_PLAYED_TRACKS) flowOf(emptyList())
} else {
fun observeLastPlayedArtists(): Flow<List<HomeTile<ArtistRef>>> = combine(ids.map { metadataProvider.observeAlbum(it) }) { refs ->
observeArtistSection(SECTION_LAST_PLAYED_ARTISTS) ids.mapIndexed { i, id -> HomeTile(id, refs[i]) }
}
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,
)
}
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) @OptIn(ExperimentalCoroutinesApi::class)
private fun observeArtistSection(section: String): Flow<List<HomeTile<ArtistRef>>> = private fun observeArtistSection(section: String): Flow<List<HomeTile<ArtistRef>>> =
observeSectionIds(section).flatMapLatest { ids -> observeSectionIds(section).flatMapLatest { ids ->
if (ids.isEmpty()) { if (ids.isEmpty()) {
flowOf(emptyList()) flowOf(emptyList())
} else { } else {
combine(ids.map { metadataProvider.observeArtist(it) }) { refs -> combine(ids.map { metadataProvider.observeArtist(it) }) { refs ->
ids.mapIndexed { i, id -> HomeTile(id, refs[i]) } ids.mapIndexed { i, id -> HomeTile(id, refs[i]) }
}
} }
} }
}
@OptIn(ExperimentalCoroutinesApi::class) @OptIn(ExperimentalCoroutinesApi::class)
private fun observeTrackSection(section: String): Flow<List<HomeTile<TrackRef>>> = private fun observeTrackSection(section: String): Flow<List<HomeTile<TrackRef>>> =
observeSectionIds(section).flatMapLatest { ids -> observeSectionIds(section).flatMapLatest { ids ->
if (ids.isEmpty()) { if (ids.isEmpty()) {
flowOf(emptyList()) flowOf(emptyList())
} else { } else {
combine(ids.map { metadataProvider.observeTrack(it) }) { refs -> combine(ids.map { metadataProvider.observeTrack(it) }) { refs ->
ids.mapIndexed { i, id -> HomeTile(id, refs[i]) } 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,
)
} }
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,6 +17,11 @@ import retrofit2.create
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton 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 * Cache-first reads of artists/albums/tracks. The Room DAOs are the
* source of truth ViewModels observe; refresh* methods pull from the * source of truth ViewModels observe; refresh* methods pull from the
@@ -27,183 +32,202 @@ import javax.inject.Singleton
* own their interfaces (see NetworkModule), so there is no @Provides * own their interfaces (see NetworkModule), so there is no @Provides
* per endpoint — fewer Hilt bindings, locality of reference. * 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") @Suppress("TooManyFunctions")
@Singleton @Singleton
class LibraryRepository @Inject constructor( class LibraryRepository
private val artistDao: CachedArtistDao, @Inject
private val albumDao: CachedAlbumDao, constructor(
private val trackDao: CachedTrackDao, private val artistDao: CachedArtistDao,
retrofit: Retrofit, private val albumDao: CachedAlbumDao,
) { private val trackDao: CachedTrackDao,
private val api: LibraryApi = retrofit.create() 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 // Joins each artist to its first cached album (by sort title) so the
// tile cover derives from /api/albums/{id}/cover — cached_artists // tile cover derives from /api/albums/{id}/cover — cached_artists
// stores no cover and sync carries none. // stores no cover and sync carries none.
fun observeArtists(): Flow<List<ArtistRef>> = fun observeArtists(): Flow<List<ArtistRef>> =
combine(artistDao.observeAll(), albumDao.observeAll()) { artists, albums -> combine(artistDao.observeAll(), albumDao.observeAll()) { artists, albums ->
val firstAlbumByArtist = albums val firstAlbumByArtist =
.groupBy { it.artistId } albums
.mapValues { (_, list) -> list.minByOrNull { it.sortTitle }?.id ?: "" } .groupBy { it.artistId }
artists.map { it.toDomain(coverAlbumId = firstAlbumByArtist[it.id] ?: "") } .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() },
)
} }
fun observeAlbums(): Flow<List<AlbumRef>> = /**
albumDao.observeAll().map { rows -> rows.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() }
fun observeAlbumsForArtist(artistId: String): Flow<List<AlbumRef>> = /**
albumDao.observeByArtist(artistId).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 observeTracksForAlbum(albumId: String): Flow<List<TrackRef>> = /**
trackDao.observeByAlbum(albumId).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() }
// ---- Single-shot lookups ---- /**
* 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() },
)
}
suspend fun getArtist(id: String): ArtistRef? = artistDao.getById(id)?.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()))
}
suspend fun getAlbum(id: String): AlbumRef? = albumDao.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 getTrack(id: String): TrackRef? = trackDao.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.
// ---- Server refreshes (sync-style writes; errors propagate) ---- /** 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. */
* Pulls the full artist detail (ArtistRef + albums), persists both, suspend fun albumYears(): List<YearCount> =
* and returns the in-memory snapshot. Lets the ArtistDetail screen api.getAlbumYears().map {
* render from the wire response without the Room round-trip. YearCount(year = it.year, albumCount = it.albumCount)
*/ }
suspend fun refreshArtistDetail(id: String): ArtistDetailRef {
val wire = api.getArtistDetail(id) /** One page of albums carrying [genre] on any track. */
artistDao.upsertAll(listOf(wire.toArtistEntity())) suspend fun albumsByGenre(
albumDao.upsertAll(wire.albums.map { it.toEntity() }) genre: String,
return ArtistDetailRef( limit: Int,
artist = ArtistRef( offset: Int,
id = wire.id, ): AlbumPage {
name = wire.name, val page = api.getAlbumsByGenre(genre = genre, limit = limit, offset = offset)
sortName = wire.sortName, return AlbumPage(items = page.items.map { it.toDomain() }, total = page.total)
albumCount = wire.albumCount, }
coverUrl = wire.coverUrl,
), /** One page of albums released in [year]. */
albums = wire.albums.map { it.toDomain() }, 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 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. */ /** 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. */ /** 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 * 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". * 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,6 +2,7 @@
package com.fabledsword.minstrel.library.ui package com.fabledsword.minstrel.library.ui
import androidx.compose.animation.Crossfade
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
@@ -12,7 +13,6 @@ import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.animation.Crossfade
import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.items
@@ -29,7 +29,6 @@ import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
@@ -51,12 +50,12 @@ import com.fabledsword.minstrel.shared.formatDuration
import com.fabledsword.minstrel.shared.plural import com.fabledsword.minstrel.shared.plural
import com.fabledsword.minstrel.shared.widgets.CoverFallbackIcon import com.fabledsword.minstrel.shared.widgets.CoverFallbackIcon
import com.fabledsword.minstrel.shared.widgets.CoverTile import com.fabledsword.minstrel.shared.widgets.CoverTile
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.TrackRow
import com.fabledsword.minstrel.shared.widgets.ErrorRetry import com.fabledsword.minstrel.shared.widgets.ErrorRetry
import com.fabledsword.minstrel.shared.widgets.LikeButton import com.fabledsword.minstrel.shared.widgets.LikeButton
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.SkeletonTrackRow import com.fabledsword.minstrel.shared.widgets.SkeletonTrackRow
import com.fabledsword.minstrel.shared.widgets.TrackRow
import com.fabledsword.minstrel.shared.widgets.trackactions.TrackActionsButton import com.fabledsword.minstrel.shared.widgets.trackactions.TrackActionsButton
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@@ -95,11 +94,12 @@ fun AlbumDetailScreen(
} }
} }
private fun titleFor(state: AlbumDetailUiState): String = when (state) { private fun titleFor(state: AlbumDetailUiState): String =
is AlbumDetailUiState.Success -> state.detail.album.title when (state) {
is AlbumDetailUiState.Loading -> state.seed?.title ?: "Album" is AlbumDetailUiState.Success -> state.detail.album.title
is AlbumDetailUiState.Error -> "Album" is AlbumDetailUiState.Loading -> state.seed?.title ?: "Album"
} is AlbumDetailUiState.Error -> "Album"
}
@Composable @Composable
private fun AlbumDetailStateContent( private fun AlbumDetailStateContent(
@@ -115,11 +115,12 @@ private fun AlbumDetailStateContent(
when (val s = state) { when (val s = state) {
is AlbumDetailUiState.Loading -> is AlbumDetailUiState.Loading ->
if (s.seed != null) SeededAlbumLoading(s.seed) else SkeletonTrackList() if (s.seed != null) SeededAlbumLoading(s.seed) else SkeletonTrackList()
is AlbumDetailUiState.Error -> ErrorRetry( is AlbumDetailUiState.Error ->
title = "Couldn't load album", ErrorRetry(
message = s.message, title = "Couldn't load album",
onRetry = { viewModel.refresh() }, message = s.message,
) onRetry = { viewModel.refresh() },
)
is AlbumDetailUiState.Success -> { is AlbumDetailUiState.Success -> {
val albumLiked by viewModel.albumLiked.collectAsStateWithLifecycle() val albumLiked by viewModel.albumLiked.collectAsStateWithLifecycle()
val likedTrackIds by viewModel.likedTrackIds val likedTrackIds by viewModel.likedTrackIds
@@ -209,9 +210,10 @@ private fun AlbumHeader(
onToggleAlbumLike: () -> Unit, onToggleAlbumLike: () -> Unit,
) { ) {
Column( Column(
modifier = Modifier modifier =
.fillMaxWidth() Modifier
.padding(16.dp), .fillMaxWidth()
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp), verticalArrangement = Arrangement.spacedBy(12.dp),
) { ) {
Row( Row(
@@ -28,112 +28,126 @@ import javax.inject.Inject
private const val SHARE_STOP_TIMEOUT_MS = 5_000L private const val SHARE_STOP_TIMEOUT_MS = 5_000L
sealed interface AlbumDetailUiState { sealed interface AlbumDetailUiState {
data class Loading(val seed: AlbumRef? = null) : AlbumDetailUiState data class Loading(
data class Success(val detail: AlbumDetailRef) : AlbumDetailUiState val seed: AlbumRef? = null,
data class Error(val message: String) : AlbumDetailUiState ) : AlbumDetailUiState
data class Success(
val detail: AlbumDetailRef,
) : AlbumDetailUiState
data class Error(
val message: String,
) : AlbumDetailUiState
} }
@HiltViewModel @HiltViewModel
class AlbumDetailViewModel @Inject constructor( class AlbumDetailViewModel
private val repository: LibraryRepository, @Inject
private val likes: LikesRepository, constructor(
private val player: PlayerController, private val repository: LibraryRepository,
private val seedCache: DetailSeedCache, private val likes: LikesRepository,
networkStatus: NetworkStatusController, private val player: PlayerController,
savedStateHandle: SavedStateHandle, private val seedCache: DetailSeedCache,
) : ViewModel() { networkStatus: NetworkStatusController,
savedStateHandle: SavedStateHandle,
) : ViewModel() {
private val route: AlbumDetail = savedStateHandle.toRoute()
val albumId: String = route.id
private val route: AlbumDetail = savedStateHandle.toRoute() private val internal =
val albumId: String = route.id MutableStateFlow<AlbumDetailUiState>(AlbumDetailUiState.Loading())
val uiState: StateFlow<AlbumDetailUiState> = internal.asStateFlow()
private val internal = val albumLiked: StateFlow<Boolean> =
MutableStateFlow<AlbumDetailUiState>(AlbumDetailUiState.Loading()) likes
val uiState: StateFlow<AlbumDetailUiState> = internal.asStateFlow() .observeIsLiked(LikesRepository.ENTITY_ALBUM, albumId)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS),
initialValue = false,
)
val albumLiked: StateFlow<Boolean> = val likedTrackIds: StateFlow<Set<String>> =
likes.observeIsLiked(LikesRepository.ENTITY_ALBUM, albumId) likes
.stateIn( .observeLikedTrackIds()
scope = viewModelScope, .stateIn(
started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), scope = viewModelScope,
initialValue = false, started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS),
) initialValue = emptySet(),
)
val likedTrackIds: StateFlow<Set<String>> = init {
likes.observeLikedTrackIds() refresh()
.stateIn( // Screen-level auto-recovery: a detail that failed to
scope = viewModelScope, // load while the server was unreachable re-fetches when health
started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), // returns, so coming back to the screen shows content, not an error.
initialValue = emptySet(), viewModelScope.launch {
) networkStatus.recoveries().collect {
if (internal.value is AlbumDetailUiState.Error) refresh()
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 { fun refresh(): Job =
val carried = when (val cur = internal.value) { viewModelScope.launch {
is AlbumDetailUiState.Loading -> cur.seed val carried =
is AlbumDetailUiState.Success -> cur.detail.album when (val cur = internal.value) {
is AlbumDetailUiState.Error -> null 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}",
)
} }
internal.value = AlbumDetailUiState.Loading(carried ?: seedCache.peekAlbum(albumId))
try { /**
val detail = repository.refreshAlbumDetail(albumId) * Play the album in shuffled order. Pre-shuffles the list and hands
internal.value = AlbumDetailUiState.Success(detail) * the result to the player — matches the PlaylistDetail shuffle
} catch ( * pattern. A future refinement could use Media3's
@Suppress("TooGenericExceptionCaught") e: Throwable, * `setShuffleModeEnabled` for play-then-shuffle without disturbing
) { * the original queue ordering.
internal.value = AlbumDetailUiState.Error(ErrorCopy.fromThrowable(e)) */
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) }
} }
} }
/** 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,16 +20,15 @@ import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.items as lazyItems
import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
@@ -58,14 +57,15 @@ import com.fabledsword.minstrel.nav.ArtistDetail
import com.fabledsword.minstrel.shared.formatDuration import com.fabledsword.minstrel.shared.formatDuration
import com.fabledsword.minstrel.shared.plural import com.fabledsword.minstrel.shared.plural
import com.fabledsword.minstrel.shared.widgets.CoverFallbackIcon 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.ErrorRetry
import com.fabledsword.minstrel.shared.widgets.HorizontalScrollRow import com.fabledsword.minstrel.shared.widgets.HorizontalScrollRow
import com.fabledsword.minstrel.shared.widgets.LikeButton import com.fabledsword.minstrel.shared.widgets.LikeButton
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
import com.fabledsword.minstrel.shared.widgets.ServerImage import com.fabledsword.minstrel.shared.widgets.ServerImage
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.SkeletonAlbumTile import com.fabledsword.minstrel.shared.widgets.SkeletonAlbumTile
import com.fabledsword.minstrel.shared.widgets.TrackRow import com.fabledsword.minstrel.shared.widgets.TrackRow
import androidx.compose.foundation.lazy.items as lazyItems
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
@@ -111,11 +111,12 @@ fun ArtistDetailScreen(
} else { } else {
SkeletonArtistAlbumsGrid() SkeletonArtistAlbumsGrid()
} }
is ArtistDetailUiState.Error -> ErrorRetry( is ArtistDetailUiState.Error ->
title = "Couldn't load artist", ErrorRetry(
message = s.message, title = "Couldn't load artist",
onRetry = { viewModel.refresh() }, message = s.message,
) onRetry = { viewModel.refresh() },
)
is ArtistDetailUiState.Success -> is ArtistDetailUiState.Success ->
ArtistSuccessBody(s, viewModel, playerViewModel, navController) ArtistSuccessBody(s, viewModel, playerViewModel, navController)
} }
@@ -145,11 +146,12 @@ private fun ArtistSuccessBody(
) )
} }
private fun titleFor(state: ArtistDetailUiState): String = when (state) { private fun titleFor(state: ArtistDetailUiState): String =
is ArtistDetailUiState.Success -> state.detail.artist.name when (state) {
is ArtistDetailUiState.Loading -> state.seed?.name ?: "Artist" is ArtistDetailUiState.Success -> state.detail.artist.name
is ArtistDetailUiState.Error -> "Artist" is ArtistDetailUiState.Loading -> state.seed?.name ?: "Artist"
} is ArtistDetailUiState.Error -> "Artist"
}
@Composable @Composable
private fun ArtistBody( private fun ArtistBody(
@@ -278,9 +280,10 @@ private fun ArtistHeader(
onToggleLike: () -> Unit, onToggleLike: () -> Unit,
) { ) {
Row( Row(
modifier = Modifier modifier =
.fillMaxWidth() Modifier
.padding(16.dp), .fillMaxWidth()
.padding(16.dp),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp), horizontalArrangement = Arrangement.spacedBy(12.dp),
) { ) {
@@ -311,20 +314,25 @@ private fun ArtistHeader(
} }
@Composable @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 // Server coverUrl wins; otherwise use the first loaded album's
// cover, the same rule the server applies. Bare Lucide.User only // cover, the same rule the server applies. Bare Lucide.User only
// when neither exists. // when neither exists.
val model = when { val model =
artist.coverUrl.isNotEmpty() -> artist.coverUrl when {
fallbackAlbumId != null -> albumCoverPath(fallbackAlbumId) artist.coverUrl.isNotEmpty() -> artist.coverUrl
else -> null fallbackAlbumId != null -> albumCoverPath(fallbackAlbumId)
} else -> null
}
Box( Box(
modifier = Modifier modifier =
.size(96.dp) Modifier
.clip(CircleShape) .size(96.dp)
.background(MaterialTheme.colorScheme.surfaceVariant), .clip(CircleShape)
.background(MaterialTheme.colorScheme.surfaceVariant),
contentAlignment = Alignment.Center, contentAlignment = Alignment.Center,
) { ) {
ServerImage( ServerImage(
@@ -335,15 +343,15 @@ private fun ArtistAvatar(artist: ArtistRef, fallbackAlbumId: String? = null) {
} }
} }
private fun albumCountLine(artist: ArtistRef): String = private fun albumCountLine(artist: ArtistRef): String = plural(artist.albumCount, "album", "albums")
plural(artist.albumCount, "album", "albums")
@Composable @Composable
private fun EmptyAlbumsHint() { private fun EmptyAlbumsHint() {
Column( Column(
modifier = Modifier modifier =
.fillMaxWidth() Modifier
.padding(24.dp), .fillMaxWidth()
.padding(24.dp),
horizontalAlignment = Alignment.CenterHorizontally, horizontalAlignment = Alignment.CenterHorizontally,
) { ) {
Text( Text(
@@ -33,136 +33,146 @@ import javax.inject.Inject
private const val SHARE_STOP_TIMEOUT_MS = 5_000L private const val SHARE_STOP_TIMEOUT_MS = 5_000L
sealed interface ArtistDetailUiState { sealed interface ArtistDetailUiState {
data class Loading(val seed: ArtistRef? = null) : ArtistDetailUiState data class Loading(
val seed: ArtistRef? = null,
) : ArtistDetailUiState
data class Success( data class Success(
val detail: ArtistDetailRef, val detail: ArtistDetailRef,
val similarArtists: List<ArtistRef> = emptyList(), val similarArtists: List<ArtistRef> = emptyList(),
val topTracks: List<TrackRef> = emptyList(), val topTracks: List<TrackRef> = emptyList(),
) : ArtistDetailUiState ) : ArtistDetailUiState
data class Error(val message: String) : ArtistDetailUiState
data class Error(
val message: String,
) : ArtistDetailUiState
} }
@HiltViewModel @HiltViewModel
class ArtistDetailViewModel @Inject constructor( class ArtistDetailViewModel
private val repository: LibraryRepository, @Inject
private val likes: LikesRepository, constructor(
private val player: PlayerController, private val repository: LibraryRepository,
private val seedCache: DetailSeedCache, private val likes: LikesRepository,
networkStatus: NetworkStatusController, private val player: PlayerController,
savedStateHandle: SavedStateHandle, private val seedCache: DetailSeedCache,
) : ViewModel() { networkStatus: NetworkStatusController,
savedStateHandle: SavedStateHandle,
) : ViewModel() {
private val route: ArtistDetail = savedStateHandle.toRoute()
val artistId: String = route.id
private val route: ArtistDetail = savedStateHandle.toRoute() private val internal =
val artistId: String = route.id MutableStateFlow<ArtistDetailUiState>(ArtistDetailUiState.Loading())
val uiState: StateFlow<ArtistDetailUiState> = internal.asStateFlow()
private val internal = /** Transient one-shot messages for the screen-level snackbar (e.g. Play-button failure). */
MutableStateFlow<ArtistDetailUiState>(ArtistDetailUiState.Loading()) private val transientMessagesChannel = Channel<String>(Channel.BUFFERED)
val uiState: StateFlow<ArtistDetailUiState> = internal.asStateFlow() val transientMessages: Flow<String> = transientMessagesChannel.receiveAsFlow()
/** Transient one-shot messages for the screen-level snackbar (e.g. Play-button failure). */ val artistLiked: StateFlow<Boolean> =
private val transientMessagesChannel = Channel<String>(Channel.BUFFERED) likes
val transientMessages: Flow<String> = transientMessagesChannel.receiveAsFlow() .observeIsLiked(LikesRepository.ENTITY_ARTIST, artistId)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS),
initialValue = false,
)
val artistLiked: StateFlow<Boolean> = init {
likes.observeIsLiked(LikesRepository.ENTITY_ARTIST, artistId) refresh()
.stateIn( // Screen-level auto-recovery. From Error, redo the
scope = viewModelScope, // whole load; from Success, re-pull just the secondary sections —
started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), // their fetch failures are swallowed to emptyList, so a dead zone
initialValue = false, // during the first load leaves them permanently absent otherwise.
) viewModelScope.launch {
networkStatus.recoveries().collect {
init { when (internal.value) {
refresh() is ArtistDetailUiState.Error -> refresh()
// Screen-level auto-recovery. From Error, redo the is ArtistDetailUiState.Success -> loadSecondarySections()
// whole load; from Success, re-pull just the secondary sections — is ArtistDetailUiState.Loading -> Unit
// 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() { fun toggleLikeArtist() {
val desired = !artistLiked.value val desired = !artistLiked.value
viewModelScope.launch { viewModelScope.launch {
likes.toggleLike(LikesRepository.ENTITY_ARTIST, artistId, desired) 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()
} }
/** fun refresh(): Job =
* Pull every track across the artist's albums, shuffle, and start viewModelScope.launch {
* playing. Pressing Play on an artist means "shuffle this artist", val carried =
* not "play album by album in tracklist order". One network when (val cur = internal.value) {
* round-trip per click; fine because the user explicitly tapped Play. is ArtistDetailUiState.Loading -> cur.seed
*/ is ArtistDetailUiState.Success -> cur.detail.artist
fun playArtist() { is ArtistDetailUiState.Error -> null
viewModelScope.launch { }
shufflePlayArtist(artistId, repository, player) { transientMessagesChannel.trySend(it) } 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",
)
} }
} }
/**
* 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,6 +41,11 @@ data class AlbumBrowseState(
val remaining: Int get() = (total - albums.size).coerceAtLeast(0) 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. * Backs the Genres and Years tabs, the same browse axes the web client has.
* *
@@ -49,171 +54,183 @@ data class AlbumBrowseState(
* missing and matches the web client's. These two tabs therefore need a * missing and matches the web client's. These two tabs therefore need a
* connection; the empty states say so rather than looking broken. * 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") @Suppress("TooManyFunctions")
@HiltViewModel @HiltViewModel
class BrowseViewModel @Inject constructor( class BrowseViewModel
private val repository: LibraryRepository, @Inject
) : ViewModel() { constructor(
private val repository: LibraryRepository,
) : ViewModel() {
private val genresInternal = MutableStateFlow<UiState<List<GenreCount>>>(UiState.Loading)
val genres: StateFlow<UiState<List<GenreCount>>> = genresInternal.asStateFlow()
private val genresInternal = MutableStateFlow<UiState<List<GenreCount>>>(UiState.Loading) private val yearsInternal = MutableStateFlow<UiState<List<YearCount>>>(UiState.Loading)
val genres: StateFlow<UiState<List<GenreCount>>> = genresInternal.asStateFlow() val years: StateFlow<UiState<List<YearCount>>> = yearsInternal.asStateFlow()
private val yearsInternal = MutableStateFlow<UiState<List<YearCount>>>(UiState.Loading) private val genreFilterInternal = MutableStateFlow("")
val years: StateFlow<UiState<List<YearCount>>> = yearsInternal.asStateFlow() val genreFilter: StateFlow<String> = genreFilterInternal.asStateFlow()
private val genreFilterInternal = MutableStateFlow("") private val genreSortInternal = MutableStateFlow(GenreSort.COUNT)
val genreFilter: StateFlow<String> = genreFilterInternal.asStateFlow() val genreSort: StateFlow<GenreSort> = genreSortInternal.asStateFlow()
private val genreSortInternal = MutableStateFlow(GenreSort.COUNT) private val selectedGenreInternal = MutableStateFlow<String?>(null)
val genreSort: StateFlow<GenreSort> = genreSortInternal.asStateFlow() val selectedGenre: StateFlow<String?> = selectedGenreInternal.asStateFlow()
private val selectedGenreInternal = MutableStateFlow<String?>(null) private val selectedYearInternal = MutableStateFlow<Int?>(null)
val selectedGenre: StateFlow<String?> = selectedGenreInternal.asStateFlow() val selectedYear: StateFlow<Int?> = selectedYearInternal.asStateFlow()
private val selectedYearInternal = MutableStateFlow<Int?>(null) private val genreAlbumsInternal = MutableStateFlow(AlbumBrowseState())
val selectedYear: StateFlow<Int?> = selectedYearInternal.asStateFlow() val genreAlbums: StateFlow<AlbumBrowseState> = genreAlbumsInternal.asStateFlow()
private val genreAlbumsInternal = MutableStateFlow(AlbumBrowseState()) private val yearAlbumsInternal = MutableStateFlow(AlbumBrowseState())
val genreAlbums: StateFlow<AlbumBrowseState> = genreAlbumsInternal.asStateFlow() val yearAlbums: StateFlow<AlbumBrowseState> = yearAlbumsInternal.asStateFlow()
private val yearAlbumsInternal = MutableStateFlow(AlbumBrowseState()) // Guards against a slow response for a previously-selected genre/year
val yearAlbums: StateFlow<AlbumBrowseState> = yearAlbumsInternal.asStateFlow() // 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
// Guards against a slow response for a previously-selected genre/year init {
// landing after the user has moved on and painting over the new list. loadGenres()
// One counter per axis, since the two drill-downs are independent. loadYears()
private var genreRequestToken = 0
private var yearRequestToken = 0
init {
loadGenres()
loadYears()
}
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)) },
)
} }
}
fun loadYears() { fun loadGenres() {
viewModelScope.launch { viewModelScope.launch {
yearsInternal.value = UiState.Loading genresInternal.value = UiState.Loading
yearsInternal.value = runCatching { repository.albumYears() }.fold( genresInternal.value =
onSuccess = { if (it.isEmpty()) UiState.Empty else UiState.Success(it) }, runCatching { repository.genres() }.fold(
onFailure = { UiState.Error(ErrorCopy.fromThrowable(it)) }, 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) 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 companion object { private fun fetchYearPage(
// Matches the web client's BROWSE_PAGE_SIZE so "Load more (N left)" year: Int,
// steps at the same rate on both clients. offset: Int,
const val PAGE_SIZE = 50 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. * Apply the current filter and sort to a genre index.
@@ -257,12 +274,12 @@ data class DecadeGroup(
* same reason as [visibleGenres]. * same reason as [visibleGenres].
*/ */
fun groupByDecade(years: List<YearCount>): List<DecadeGroup> = 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) -> .map { (decade, entries) ->
DecadeGroup( DecadeGroup(
decade = decade, decade = decade,
years = entries.sortedByDescending { it.year }, years = entries.sortedByDescending { it.year },
albumCount = entries.sumOf { it.albumCount }, 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.fillMaxWidth
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn 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.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.FilterChip import androidx.compose.material3.FilterChip
import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
@@ -32,8 +32,8 @@ import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.composables.icons.lucide.ArrowLeft import com.composables.icons.lucide.ArrowLeft
import com.composables.icons.lucide.Lucide
import com.composables.icons.lucide.LibraryBig import com.composables.icons.lucide.LibraryBig
import com.composables.icons.lucide.Lucide
import com.fabledsword.minstrel.library.widgets.AlbumCard import com.fabledsword.minstrel.library.widgets.AlbumCard
import com.fabledsword.minstrel.models.AlbumRef import com.fabledsword.minstrel.models.AlbumRef
import com.fabledsword.minstrel.shared.UiState import com.fabledsword.minstrel.shared.UiState
@@ -74,22 +74,26 @@ private fun GenreIndex(viewModel: BrowseViewModel) {
val sort by viewModel.genreSort.collectAsStateWithLifecycle() val sort by viewModel.genreSort.collectAsStateWithLifecycle()
when (val s = state) { when (val s = state) {
UiState.Loading -> EmptyState( UiState.Loading ->
title = "Reading your genres…", EmptyState(
body = "", title = "Reading your genres…",
icon = Lucide.LibraryBig, body = "",
) icon = Lucide.LibraryBig,
UiState.Empty -> EmptyState( )
title = "No genres found", UiState.Empty ->
body = "Genres come from the genre tag on your audio files. If your " + EmptyState(
"library is tagged but this is empty, try a rescan from the admin " + title = "No genres found",
"screen.", body =
icon = Lucide.LibraryBig, "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 " +
is UiState.Error -> ErrorRetry( "screen.",
message = s.message, icon = Lucide.LibraryBig,
onRetry = viewModel::loadGenres, )
) is UiState.Error ->
ErrorRetry(
message = s.message,
onRetry = viewModel::loadGenres,
)
is UiState.Success -> { is UiState.Success -> {
val visible = visibleGenres(s.data, filter, sort) val visible = visibleGenres(s.data, filter, sort)
Column(modifier = Modifier.fillMaxSize()) { Column(modifier = Modifier.fillMaxSize()) {
@@ -161,11 +165,12 @@ private fun GenreIndexControls(
label = { Text("A–Z") }, label = { Text("A–Z") },
) )
Text( Text(
text = if (filter.isBlank()) { text =
"$total genres" if (filter.isBlank()) {
} else { "$total genres"
"$shown of $total" } else {
}, "$shown of $total"
},
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
@@ -174,12 +179,17 @@ private fun GenreIndexControls(
} }
@Composable @Composable
private fun GenreRow(genre: String, trackCount: Int, onClick: () -> Unit) { private fun GenreRow(
genre: String,
trackCount: Int,
onClick: () -> Unit,
) {
Row( Row(
modifier = Modifier modifier =
.fillMaxWidth() Modifier
.clickable(onClick = onClick) .fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 14.dp), .clickable(onClick = onClick)
.padding(horizontal = 16.dp, vertical = 14.dp),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
) { ) {
Text( Text(
@@ -263,20 +273,23 @@ fun BrowseAlbumResults(
} }
when { when {
state.failed && state.albums.isEmpty() -> ErrorRetry( state.failed && state.albums.isEmpty() ->
message = "Couldn't load albums.", ErrorRetry(
onRetry = onRetry, message = "Couldn't load albums.",
) onRetry = onRetry,
state.loading && state.albums.isEmpty() -> EmptyState( )
title = "Loading…", state.loading && state.albums.isEmpty() ->
body = "", EmptyState(
) title = "Loading…",
body = "",
)
state.albums.isEmpty() -> EmptyState(title = emptyTitle, body = emptyBody) state.albums.isEmpty() -> EmptyState(title = emptyTitle, body = emptyBody)
else -> BrowseAlbumGrid( else ->
state = state, BrowseAlbumGrid(
onLoadMore = onLoadMore, state = state,
onAlbumClick = onAlbumClick, onLoadMore = onLoadMore,
) onAlbumClick = onAlbumClick,
)
} }
} }
} }
@@ -334,8 +347,13 @@ private fun BrowseAlbumGrid(
* is still in flight — a count that appears as 0 and then corrects itself reads * is still in flight — a count that appears as 0 and then corrects itself reads
* as a bug. * as a bug.
*/ */
internal fun albumCountLabel(total: Int, loading: Boolean, loaded: Int): String = when { internal fun albumCountLabel(
loading && loaded == 0 -> "" total: Int,
total == 1 -> "1 album" loading: Boolean,
else -> "$total albums" 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