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-requirements.md export-ignore
renovate.json export-ignore
.gitleaks.toml export-ignore
internal/server/release_gate_test.go export-ignore
internal/server/release_version_test.go export-ignore
.gitattributes export-ignore
+22 -15
View File
@@ -122,7 +122,7 @@ jobs:
go:
runs-on: go-ci
container:
image: git.fabledsword.com/bvandeusen/ci-go:1.26
image: git.fabledsword.com/bvandeusen/ci-go:1.27
steps:
- name: Checkout
@@ -176,10 +176,10 @@ jobs:
integration:
runs-on: go-ci
container:
image: git.fabledsword.com/bvandeusen/ci-go:1.26
image: git.fabledsword.com/bvandeusen/ci-go:1.27
services:
postgres:
image: postgres:16-alpine
image: postgres:19-alpine
env:
POSTGRES_USER: minstrel
POSTGRES_PASSWORD: minstrel
@@ -211,7 +211,7 @@ jobs:
echo "self ($SELF) networks: $SELF_NETS"
PG_ID=""
PG_NAME=""
for cid in $(docker ps --filter "ancestor=postgres:16-alpine" -q); do
for cid in $(docker ps --filter "ancestor=postgres:19-alpine" -q); do
nm=$(docker inspect -f '{{.Name}}' "$cid" | sed 's#^/##')
case "$nm" in *minstrel-postgres*|*_postgres_*) continue ;; esac
for net in $(docker inspect -f '{{range $k,$v := .NetworkSettings.Networks}}{{$k}} {{end}}' "$cid"); do
@@ -223,6 +223,9 @@ jobs:
PG_IP=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$PG_ID")
test -n "$PG_IP"
export MINSTREL_TEST_DATABASE_URL="postgres://minstrel:minstrel@${PG_IP}:5432/minstrel_test?sslmode=disable"
# A database test that finds no database fails here instead of
# skipping, so this lane can't pass with nothing run.
export MINSTREL_TEST_DATABASE_REQUIRED=1
# Wait for Postgres to accept connections. Asked of the service
# container itself: the run: shell is dash, where a `/dev/tcp`
@@ -303,7 +306,7 @@ jobs:
web:
runs-on: go-ci
container:
image: git.fabledsword.com/bvandeusen/ci-go:1.26
image: git.fabledsword.com/bvandeusen/ci-go:1.27
defaults:
run:
@@ -332,7 +335,7 @@ jobs:
# docker that can pull our container.image.
runs-on: flutter-ci
container:
image: git.fabledsword.com/bvandeusen/ci-android:36
image: git.fabledsword.com/bvandeusen/ci-android:37
defaults:
run:
@@ -410,7 +413,7 @@ jobs:
govulncheck:
runs-on: go-ci
container:
image: golang:1.26-bookworm
image: golang:1.27-trixie
steps:
# Plain git, not actions/checkout: that action runs on node, which the
@@ -443,7 +446,7 @@ jobs:
|| github.ref == 'refs/heads/main'
runs-on: flutter-ci
container:
image: git.fabledsword.com/bvandeusen/ci-android:36
image: git.fabledsword.com/bvandeusen/ci-android:37
defaults:
run:
@@ -557,10 +560,14 @@ jobs:
signer="$(ls "$sdk"/build-tools/*/apksigner 2>/dev/null | sort -V | tail -1 || true)"
test -n "$signer" || { echo "::error::no apksigner under '$sdk/build-tools'"; exit 1; }
certs="$("$signer" verify --print-certs app/build/outputs/apk/release/app-release.apk)"
printf '%s\n' "$certs" | grep -E '^Signer #[0-9]+ certificate (DN|SHA-256 digest)'
# One signer, and it is ours. A second signer would be a lineage or
# apksigner's signer label varies between versions: "Signer #1
# certificate ..." before build-tools 37, "V3.0 Signer: certificate
# ..." from 37 on. So the digests are read without relying on it.
printf '%s\n' "$certs" | grep -E 'certificate (DN|SHA-256 digest):' || true
# One signer, and it is ours: exactly one distinct SHA-256 across
# every scheme apksigner reports. A second key would be a lineage or
# 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 printf '%s' "$certs" | grep -q 'CN=Android Debug'; then
echo "::error::the release APK is signed with a debug key"
@@ -615,7 +622,7 @@ jobs:
&& needs.android-release.result == 'success' }}
runs-on: go-ci
container:
image: git.fabledsword.com/bvandeusen/ci-go:1.26
image: git.fabledsword.com/bvandeusen/ci-go:1.27
env:
IMAGE: git.fabledsword.com/bvandeusen/minstrel
@@ -700,7 +707,7 @@ jobs:
rm -rf "${EXPORT}"
mkdir -p "${EXPORT}"
git archive HEAD | tar -x -C "${EXPORT}"
for private in .gitea .forgejo .github ci ci-requirements.md .gitattributes renovate.json; do
for private in .gitea .forgejo .github ci ci-requirements.md .gitattributes renovate.json .gitleaks.toml; do
if [ -e "${EXPORT}/${private}" ]; then
echo "::error::the export carries ${private}; .gitattributes export-ignore no longer covers it"
exit 1
@@ -783,8 +790,8 @@ jobs:
- name: Build and push
shell: bash
# --pull: the Dockerfile's base images are floating tags (golang:1.26,
# debian:bookworm-slim). Without it the runner's daemon reuses
# --pull: the Dockerfile's base images are floating tags (golang:1.27,
# debian:trixie-slim). Without it the runner's daemon reuses
# whatever it cached, and the shipped binary can sit on a Go patch
# release govulncheck already flagged while the lane, which pulls
# fresh, reports clean.
+22
View File
@@ -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
COPY web/package.json web/package-lock.json ./
RUN npm ci
COPY web/ ./
RUN npm run build
FROM golang:1.26-bookworm AS builder
FROM golang:1.27-trixie AS builder
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
@@ -31,7 +31,7 @@ RUN go build -trimpath \
-X 'github.com/Fabled-Sword/minstrel/internal/buildinfo.Channel=${MINSTREL_CHANNEL}'" \
-o /out/minstrel ./cmd/minstrel
FROM debian:bookworm-slim
FROM debian:trixie-slim
# ffmpeg: duration probes and the exact-tier audio hash (a SHA-256 of the
# encoded audio packets, so no decode). libchromaprint-tools: fpcalc, the
# acoustic fingerprint that tells the same recording at two bitrates apart
+3 -1
View File
@@ -32,7 +32,7 @@ services:
depends_on: [db]
db:
image: postgres:17
image: postgres:19
environment:
POSTGRES_USER: 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.
**Keep the Postgres image on the major version your database was created with.** The quick start uses `postgres:19`. Postgres can't open a data folder made by another major version, so moving an existing database to a newer one takes a `pg_dump`, a fresh volume and a restore.
## Features
**Listening**
+11
View File
@@ -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 {
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 {
applicationId = "com.fabledsword.minstrel"
@@ -30,8 +30,8 @@ import com.fabledsword.minstrel.auth.AuthStore
import com.fabledsword.minstrel.auth.ui.AuthGateViewModel
import com.fabledsword.minstrel.cache.CachedTrackIds
import com.fabledsword.minstrel.connectivity.LocalServerHealth
import com.fabledsword.minstrel.connectivity.ServerHealth
import com.fabledsword.minstrel.connectivity.NetworkStatusController
import com.fabledsword.minstrel.connectivity.ServerHealth
import com.fabledsword.minstrel.nav.DetailSeedCache
import com.fabledsword.minstrel.nav.LocalDetailSeedCache
import com.fabledsword.minstrel.nav.Login
@@ -56,8 +56,11 @@ import javax.inject.Inject
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
@Inject lateinit var seedCache: DetailSeedCache
@Inject lateinit var cachedTrackIds: CachedTrackIds
@Inject lateinit var serverHealth: NetworkStatusController
@Inject lateinit var authStore: AuthStore
// Set when the user taps a notification: the media one asks for the full
@@ -120,7 +123,8 @@ class MainActivity : ComponentActivity() {
val signedIn = authStore.sessionCookie.map { !it.isNullOrEmpty() }
combine(signedIn, authStore.backgroundDelivery, ::deliveryWanted).first { it }
val permission = Manifest.permission.POST_NOTIFICATIONS
val granted = ContextCompat.checkSelfPermission(this@MainActivity, permission) ==
val granted =
ContextCompat.checkSelfPermission(this@MainActivity, permission) ==
PackageManager.PERMISSION_GRANTED
if (!granted) askToNotify.launch(permission)
}
@@ -196,7 +200,10 @@ private fun App(
* request fails.
*/
@Composable
private fun SignInWhenSessionRejected(gate: AuthGateViewModel, navController: NavHostController) {
private fun SignInWhenSessionRejected(
gate: AuthGateViewModel,
navController: NavHostController,
) {
val sessionRejected by gate.sessionRejected.collectAsStateWithLifecycle()
LaunchedEffect(sessionRejected, navController) {
if (!sessionRejected) return@LaunchedEffect
@@ -11,6 +11,7 @@ import com.fabledsword.minstrel.cache.CacheIndexer
import com.fabledsword.minstrel.cache.audiocache.CacheBudgetSync
import com.fabledsword.minstrel.cache.mutations.MutationReplayer
import com.fabledsword.minstrel.cache.sync.SyncController
import com.fabledsword.minstrel.connectivity.NetworkStatusController
import com.fabledsword.minstrel.di.ApplicationScope
import com.fabledsword.minstrel.diagnostics.DiagnosticsReporter
import com.fabledsword.minstrel.diagnostics.DiagnosticsUploader
@@ -24,7 +25,6 @@ import com.fabledsword.minstrel.player.LikedAudioPinner
import com.fabledsword.minstrel.player.PlayEventsReporter
import com.fabledsword.minstrel.player.PlaybackErrorReporter
import com.fabledsword.minstrel.player.ResumeController
import com.fabledsword.minstrel.connectivity.NetworkStatusController
import dagger.hilt.android.HiltAndroidApp
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
@@ -41,7 +41,6 @@ class MinstrelApplication :
Application(),
Configuration.Provider,
SingletonImageLoader.Factory {
@Inject lateinit var workerFactory: HiltWorkerFactory
/**
@@ -66,7 +65,9 @@ class MinstrelApplication :
* cold start with persisted cookie). Without this @Inject the
* singleton would never instantiate.
*/
@Suppress("unused") @Inject lateinit var syncController: SyncController
@Suppress("unused")
@Inject
lateinit var syncController: SyncController
/**
* Same construct-the-singleton trick — MutationReplayer's init
@@ -75,7 +76,9 @@ class MinstrelApplication :
* cold start with persisted cookie). Without this @Inject the
* queue would only enqueue, never replay.
*/
@Suppress("unused") @Inject lateinit var mutationReplayer: MutationReplayer
@Suppress("unused")
@Inject
lateinit var mutationReplayer: MutationReplayer
/**
* Same construct-the-singleton trick — DeliveryLauncher starts and stops
@@ -83,7 +86,9 @@ class MinstrelApplication :
* every nudge and reconnect. Without this @Inject no phone
* notification would ever be posted.
*/
@Suppress("unused") @Inject lateinit var deliveryLauncher: DeliveryLauncher
@Suppress("unused")
@Inject
lateinit var deliveryLauncher: DeliveryLauncher
/**
* Same construct-the-singleton trick — PlayEventsReporter's init
@@ -92,7 +97,9 @@ class MinstrelApplication :
* server. Without this @Inject the singleton would never
* instantiate and Android plays would never reach the server.
*/
@Suppress("unused") @Inject lateinit var playEventsReporter: PlayEventsReporter
@Suppress("unused")
@Inject
lateinit var playEventsReporter: PlayEventsReporter
/**
* Same construct-the-singleton trick — PlaybackErrorReporter
@@ -102,7 +109,9 @@ class MinstrelApplication :
* snackbar. Without this construct ExoPlayer skip-on-error is
* invisible to the user.
*/
@Suppress("unused") @Inject lateinit var playbackErrorReporter: PlaybackErrorReporter
@Suppress("unused")
@Inject
lateinit var playbackErrorReporter: PlaybackErrorReporter
/**
* Same construct-the-singleton trick — CoverPrefetcher's init
@@ -110,7 +119,9 @@ class MinstrelApplication :
* cache with the next track's cover so track changes don't flash
* a loading state.
*/
@Suppress("unused") @Inject lateinit var coverPrefetcher: CoverPrefetcher
@Suppress("unused")
@Inject
lateinit var coverPrefetcher: CoverPrefetcher
/**
* Same construct-the-singleton trick — CacheIndexer's init block
@@ -119,7 +130,9 @@ class MinstrelApplication :
* and the cached indicator their data source. Without this @Inject
* the index would stay empty and the offline pools would be inert.
*/
@Suppress("unused") @Inject lateinit var cacheIndexer: CacheIndexer
@Suppress("unused")
@Inject
lateinit var cacheIndexer: CacheIndexer
/**
* Same construct-the-singleton trick — CacheBudgetSync's init block
@@ -127,14 +140,18 @@ class MinstrelApplication :
* Without this @Inject the evictor would never arm, and the cache
* would grow without a limit.
*/
@Suppress("unused") @Inject lateinit var cacheBudgetSync: CacheBudgetSync
@Suppress("unused")
@Inject
lateinit var cacheBudgetSync: CacheBudgetSync
/**
* Same construct-the-singleton trick — LikedAudioPinner's init block
* downloads liked tracks into the Liked songs budget. Without this
* @Inject, liking a track would not keep it offline.
*/
@Suppress("unused") @Inject lateinit var likedAudioPinner: LikedAudioPinner
@Suppress("unused")
@Inject
lateinit var likedAudioPinner: LikedAudioPinner
/**
* Same construct-the-singleton trick — AudioPrefetcher's init
@@ -143,7 +160,9 @@ class MinstrelApplication :
* SimpleCache via CacheWriter. Without this @Inject the
* prefetchWindow setting would be inert and skips would re-fetch.
*/
@Suppress("unused") @Inject lateinit var audioPrefetcher: AudioPrefetcher
@Suppress("unused")
@Inject
lateinit var audioPrefetcher: AudioPrefetcher
/**
* Same construct-the-singleton trick — NetworkStatusController owns the
@@ -152,7 +171,9 @@ class MinstrelApplication :
* signal (plus the VersionTooOld byproduct). It must exist from launch so
* the poll loop runs and the StateFlow stays warm for every consumer.
*/
@Suppress("unused") @Inject lateinit var networkStatusController: NetworkStatusController
@Suppress("unused")
@Inject
lateinit var networkStatusController: NetworkStatusController
/**
* Same construct-the-singleton trick — FreshnessSweeper's init
@@ -161,7 +182,9 @@ class MinstrelApplication :
* via MetadataProvider, so the cache stays warm without
* user-driven pull-to-refresh.
*/
@Suppress("unused") @Inject lateinit var freshnessSweeper: FreshnessSweeper
@Suppress("unused")
@Inject
lateinit var freshnessSweeper: FreshnessSweeper
/**
* Same construct-the-singleton trick — EventsStream's init block
@@ -170,21 +193,31 @@ class MinstrelApplication :
* Without this @Inject the events SharedFlow would have no
* upstream and consumers would never see anything.
*/
@Suppress("unused") @Inject lateinit var eventsStream: EventsStream
@Suppress("unused")
@Inject
lateinit var eventsStream: EventsStream
/**
* Same construct-the-singleton trick — LiveEventsDispatcher's
* init block subscribes to EventsStream.events + the process
* lifecycle and routes cross-screen state refreshes.
*/
@Suppress("unused") @Inject lateinit var liveEventsDispatcher: LiveEventsDispatcher
@Suppress("unused")
@Inject
lateinit var liveEventsDispatcher: LiveEventsDispatcher
// Device diagnostics. The reporter gates itself on the account's
// debug flag; the uploader drains its buffer on a tick / recovery.
@Suppress("unused") @Inject lateinit var diagnosticsReporter: DiagnosticsReporter
@Suppress("unused") @Inject lateinit var diagnosticsUploader: DiagnosticsUploader
@Suppress("unused")
@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() {
super.onCreate()
@@ -208,10 +241,17 @@ class MinstrelApplication :
* to the package-stack-trace tag DebugTree produces.
*/
private class ReleaseTree : Timber.Tree() {
override fun isLoggable(tag: String?, priority: Int): Boolean =
priority >= android.util.Log.WARN
override fun isLoggable(
tag: String?,
priority: Int,
): Boolean = priority >= android.util.Log.WARN
override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
override fun log(
priority: Int,
tag: String?,
message: String,
t: Throwable?,
) {
val resolvedTag = tag ?: "Minstrel"
if (t == null) {
android.util.Log.println(priority, resolvedTag, message)
@@ -226,7 +266,9 @@ class MinstrelApplication :
}
override val workManagerConfiguration: Configuration
get() = Configuration.Builder()
get() =
Configuration
.Builder()
.setWorkerFactory(workerFactory)
.build()
@@ -242,10 +284,10 @@ class MinstrelApplication :
* two read as one cross-dissolve.
*/
override fun newImageLoader(context: android.content.Context): ImageLoader =
ImageLoader.Builder(context)
ImageLoader
.Builder(context)
.components {
add(OkHttpNetworkFetcherFactory(callFactory = { okHttpClient }))
}
.crossfade(ART_CROSSFADE_MS)
}.crossfade(ART_CROSSFADE_MS)
.build()
}
@@ -14,20 +14,33 @@ import javax.inject.Singleton
* admin repos — direct REST, no caching.
*/
@Singleton
class AdminInvitesRepository @Inject constructor(retrofit: Retrofit) {
class AdminInvitesRepository
@Inject
constructor(
retrofit: Retrofit,
) {
private val api: AdminInvitesApi = retrofit.create()
suspend fun list(): List<Invite> = api.list().invites.map { it.toDomain() }
suspend fun 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) {
api.revoke(token)
}
}
private fun InviteWire.toDomain(): Invite = Invite(
private fun InviteWire.toDomain(): Invite =
Invite(
token = token,
invitedBy = invitedBy,
note = note,
@@ -17,7 +17,9 @@ import javax.inject.Singleton
* Each action takes the row off the queue once the server accepts it.
*/
@Singleton
class AdminQuarantineRepository @Inject constructor(
class AdminQuarantineRepository
@Inject
constructor(
retrofit: Retrofit,
) {
private val api: AdminQuarantineApi = retrofit.create()
@@ -18,23 +18,30 @@ import javax.inject.Singleton
* Exceptions propagate to the ViewModel (which maps them via ErrorCopy).
*/
@Singleton
class AdminTagSourcesRepository @Inject constructor(
class AdminTagSourcesRepository
@Inject
constructor(
retrofit: Retrofit,
) {
private val api: AdminTagSourcesApi = retrofit.create()
suspend fun list(): List<AdminTagSourceRef> = api.list().providers.map { it.toDomain() }
suspend fun setEnabled(id: String, enabled: Boolean): AdminTagSourceRef =
api.update(id, UpdateTagSourceBody(enabled = enabled)).toDomain()
suspend fun setEnabled(
id: String,
enabled: Boolean,
): AdminTagSourceRef = api.update(id, UpdateTagSourceBody(enabled = enabled)).toDomain()
suspend fun setApiKey(id: String, apiKey: String): AdminTagSourceRef =
api.update(id, UpdateTagSourceBody(apiKey = apiKey)).toDomain()
suspend fun setApiKey(
id: String,
apiKey: String,
): AdminTagSourceRef = api.update(id, UpdateTagSourceBody(apiKey = apiKey)).toDomain()
suspend fun test(id: String): TagSourceTestResult = api.test(id).toResult()
}
private fun AdminTagSourceWire.toDomain(): AdminTagSourceRef = AdminTagSourceRef(
private fun AdminTagSourceWire.toDomain(): AdminTagSourceRef =
AdminTagSourceRef(
id = id,
displayName = displayName,
requiresApiKey = requiresApiKey,
@@ -16,23 +16,30 @@ import javax.inject.Singleton
* admin repositories.
*/
@Singleton
class AdminUsersRepository @Inject constructor(
class AdminUsersRepository
@Inject
constructor(
retrofit: Retrofit,
) {
private val api: AdminUsersApi = retrofit.create()
suspend fun list(): List<AdminUserRef> = api.list().users.map { it.toDomain() }
suspend fun setAdmin(id: String, isAdmin: Boolean) =
api.setAdmin(id, SetAdminBody(isAdmin))
suspend fun setAdmin(
id: String,
isAdmin: Boolean,
) = api.setAdmin(id, SetAdminBody(isAdmin))
suspend fun resetPassword(id: String, newPassword: String) =
api.resetPassword(id, ResetPasswordBody(newPassword))
suspend fun resetPassword(
id: String,
newPassword: String,
) = api.resetPassword(id, ResetPasswordBody(newPassword))
suspend fun delete(id: String) = api.delete(id)
}
private fun AdminUserWire.toDomain(): AdminUserRef = AdminUserRef(
private fun AdminUserWire.toDomain(): AdminUserRef =
AdminUserRef(
id = id,
username = username,
displayName = displayName,
@@ -25,11 +25,12 @@ data class AdminInvitesUiState(
)
@HiltViewModel
class AdminInvitesViewModel @Inject constructor(
class AdminInvitesViewModel
@Inject
constructor(
private val repository: AdminInvitesRepository,
networkStatus: NetworkStatusController,
) : ViewModel() {
private val internal = MutableStateFlow(AdminInvitesUiState())
val state: StateFlow<AdminInvitesUiState> = internal.asStateFlow()
@@ -39,11 +39,11 @@ import com.fabledsword.minstrel.nav.AdminTagSources
import com.fabledsword.minstrel.nav.AdminUsers
import com.fabledsword.minstrel.shared.UiState
import com.fabledsword.minstrel.shared.loadUiState
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.EmptyState
import com.fabledsword.minstrel.shared.widgets.LoadingCentered
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
@@ -56,7 +56,11 @@ import javax.inject.Inject
// ─── State ───────────────────────────────────────────────────────────
data class AdminCounts(val quarantine: Int, val users: Int, val tagSources: Int)
data class AdminCounts(
val quarantine: Int,
val users: Int,
val tagSources: Int,
)
/** The admin landing's counts, as the shared [UiState] (never Empty: it always has counts). */
typealias AdminLandingUiState = UiState<AdminCounts>
@@ -64,12 +68,13 @@ typealias AdminLandingUiState = UiState<AdminCounts>
// ─── ViewModel ───────────────────────────────────────────────────────
@HiltViewModel
class AdminLandingViewModel @Inject constructor(
class AdminLandingViewModel
@Inject
constructor(
private val quarantineRepo: AdminQuarantineRepository,
private val usersRepo: AdminUsersRepository,
private val tagSourcesRepo: AdminTagSourcesRepository,
) : ViewModel() {
private val internal = MutableStateFlow<AdminLandingUiState>(UiState.Loading)
val uiState: StateFlow<AdminLandingUiState> = internal.asStateFlow()
@@ -77,9 +82,11 @@ class AdminLandingViewModel @Inject constructor(
refresh()
}
fun refresh(): Job = viewModelScope.launch {
fun refresh(): Job =
viewModelScope.launch {
internal.value = UiState.Loading
internal.value = loadUiState {
internal.value =
loadUiState {
coroutineScope {
val qua = async { quarantineRepo.list().size }
val usr = async { usersRepo.list().size }
@@ -116,11 +123,13 @@ fun AdminLandingScreen(
) {
when (val s = state) {
UiState.Loading, UiState.Empty -> LoadingCentered()
is UiState.Error -> EmptyState(
is UiState.Error ->
EmptyState(
title = "Couldn't load admin counts",
body = s.message,
)
is UiState.Success -> SectionList(
is UiState.Success ->
SectionList(
counts = s.data,
navController = navController,
)
@@ -130,7 +139,10 @@ fun AdminLandingScreen(
}
@Composable
private fun SectionList(counts: AdminCounts, navController: NavHostController) {
private fun SectionList(
counts: AdminCounts,
navController: NavHostController,
) {
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(16.dp),
@@ -175,7 +187,8 @@ private fun SectionCard(
onClick: () -> Unit,
) {
ElevatedCard(
modifier = Modifier
modifier =
Modifier
.fillMaxWidth()
.clickable(onClick = onClick),
) {
@@ -35,12 +35,12 @@ import com.fabledsword.minstrel.models.AdminQuarantineItemRef
import com.fabledsword.minstrel.nav.AdminQuarantine
import com.fabledsword.minstrel.shared.UiState
import com.fabledsword.minstrel.shared.widgets.ConfirmDestructiveDialog
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.EmptyState
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
import com.fabledsword.minstrel.shared.widgets.LoadingCentered
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@@ -74,17 +74,21 @@ fun AdminQuarantineScreen(
) {
when (val s = state) {
UiState.Loading -> LoadingCentered()
UiState.Empty -> EmptyState(
UiState.Empty ->
EmptyState(
title = "No reports",
body = "When listeners flag a track as a bad rip, wrong tags or " +
body =
"When listeners flag a track as a bad rip, wrong tags or " +
"a duplicate, their reports gather here.",
)
is UiState.Error -> ErrorRetry(
is UiState.Error ->
ErrorRetry(
title = "Couldn't load queue",
message = s.message,
onRetry = { viewModel.refresh() },
)
is UiState.Success -> QueueList(
is UiState.Success ->
QueueList(
rows = s.data,
onResolve = viewModel::resolve,
onRemoveFile = viewModel::removeFile,
@@ -98,7 +102,10 @@ fun AdminQuarantineScreen(
/** A confirm asked of the admin before a removal: which one, and of which track. */
private enum class Removal { File, Library }
private data class PendingRemoval(val row: AdminQuarantineItemRef, val kind: Removal)
private data class PendingRemoval(
val row: AdminQuarantineItemRef,
val kind: Removal,
)
@Composable
private fun QueueList(
@@ -146,14 +153,17 @@ private fun RemovalConfirm(
onDismiss: () -> Unit,
) {
val title = pending.row.trackTitle
val (heading, body, action) = when (pending.kind) {
Removal.File -> Triple(
val (heading, body, action) =
when (pending.kind) {
Removal.File ->
Triple(
"Remove the file?",
"Delete the file of \u201c$title\u201d and keep the track. It waits, with its likes " +
"and plays, and takes over a good copy when one is in the library. Its reports are cleared.",
"Remove the file",
)
Removal.Library -> Triple(
Removal.Library ->
Triple(
"Remove from library?",
"Remove \u201c$title\u201d and its file for good, with its likes, plays and playlist " +
"places. To keep the track for a good copy, remove the file instead.",
@@ -177,7 +187,8 @@ private fun QuarantineRow(
onDeleteFile: () -> Unit,
) {
Column(
modifier = Modifier
modifier =
Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
@@ -27,12 +27,13 @@ import javax.inject.Inject
typealias AdminQuarantineUiState = UiState<List<AdminQuarantineItemRef>>
@HiltViewModel
class AdminQuarantineViewModel @Inject constructor(
class AdminQuarantineViewModel
@Inject
constructor(
private val repository: AdminQuarantineRepository,
private val eventsStream: EventsStream,
networkStatus: NetworkStatusController,
) : ViewModel() {
private val internal = MutableStateFlow<AdminQuarantineUiState>(UiState.Loading)
val uiState: StateFlow<AdminQuarantineUiState> = internal.asStateFlow()
@@ -60,16 +61,22 @@ class AdminQuarantineViewModel @Inject constructor(
}
}
fun refresh(): Job = viewModelScope.launch {
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) {
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()
@@ -36,12 +36,12 @@ import com.fabledsword.minstrel.models.AdminTagSourceRef
import com.fabledsword.minstrel.models.TagSourceTestResult
import com.fabledsword.minstrel.nav.AdminTagSources
import com.fabledsword.minstrel.shared.UiState
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.EmptyState
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
import com.fabledsword.minstrel.shared.widgets.LoadingCentered
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@@ -68,16 +68,19 @@ fun AdminTagSourcesScreen(
) {
when (val s = state) {
UiState.Loading -> LoadingCentered()
UiState.Empty -> EmptyState(
UiState.Empty ->
EmptyState(
title = "No tag sources",
body = "Tag-enrichment providers register on the server; none are available.",
)
is UiState.Error -> ErrorRetry(
is UiState.Error ->
ErrorRetry(
title = "Couldn't load tag sources",
message = s.message,
onRetry = { viewModel.refresh() },
)
is UiState.Success -> TagSourceList(
is UiState.Success ->
TagSourceList(
providers = s.data.providers,
testResults = s.data.testResults,
onToggle = viewModel::setEnabled,
@@ -156,7 +159,10 @@ private fun TagSourceCard(
}
@Composable
private fun ApiKeyRow(provider: AdminTagSourceRef, onSaveKey: (String, String) -> Unit) {
private fun ApiKeyRow(
provider: AdminTagSourceRef,
onSaveKey: (String, String) -> Unit,
) {
var key by remember(provider.id) { mutableStateOf("") }
OutlinedTextField(
value = key,
@@ -28,11 +28,12 @@ data class AdminTagSources(
typealias AdminTagSourcesUiState = UiState<AdminTagSources>
@HiltViewModel
class AdminTagSourcesViewModel @Inject constructor(
class AdminTagSourcesViewModel
@Inject
constructor(
private val repository: AdminTagSourcesRepository,
networkStatus: NetworkStatusController,
) : ViewModel() {
private val internal = MutableStateFlow<AdminTagSourcesUiState>(UiState.Loading)
val uiState: StateFlow<AdminTagSourcesUiState> = internal.asStateFlow()
@@ -47,20 +48,27 @@ class AdminTagSourcesViewModel @Inject constructor(
}
}
fun refresh(): Job = viewModelScope.launch {
fun refresh(): Job =
viewModelScope.launch {
internal.value = UiState.Loading
internal.value = loadUiState {
internal.value =
loadUiState {
val providers = repository.list()
if (providers.isEmpty()) UiState.Empty else UiState.Success(AdminTagSources(providers))
}
}
fun setEnabled(id: String, enabled: Boolean) {
fun setEnabled(
id: String,
enabled: Boolean,
) {
val before = (internal.value as? UiState.Success<AdminTagSources>)?.data ?: return
// Optimistic toggle; reconcile via refresh() if the server rejects.
internal.value = UiState.Success(
internal.value =
UiState.Success(
before.copy(
providers = before.providers.map {
providers =
before.providers.map {
if (it.id == id) it.copy(enabled = enabled) else it
},
),
@@ -76,7 +84,10 @@ class AdminTagSourcesViewModel @Inject constructor(
}
}
fun saveApiKey(id: String, apiKey: String) {
fun saveApiKey(
id: String,
apiKey: String,
) {
viewModelScope.launch {
try {
replaceProvider(repository.setApiKey(id, apiKey))
@@ -90,7 +101,8 @@ class AdminTagSourcesViewModel @Inject constructor(
fun test(id: String) {
viewModelScope.launch {
val result = try {
val result =
try {
repository.test(id)
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
@@ -104,7 +116,8 @@ class AdminTagSourcesViewModel @Inject constructor(
private fun replaceProvider(updated: AdminTagSourceRef) {
val current = (internal.value as? UiState.Success<AdminTagSources>)?.data ?: return
internal.value = UiState.Success(
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
import android.content.ClipData
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.layout.size
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import com.composables.icons.lucide.Lucide
import com.composables.icons.lucide.Copy
import com.composables.icons.lucide.KeyRound
import com.composables.icons.lucide.Plus
import com.composables.icons.lucide.Trash2
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import android.content.ClipData
import androidx.compose.ui.platform.ClipEntry
import androidx.compose.ui.platform.LocalClipboard
import com.fabledsword.minstrel.auth.PasswordRules
import com.fabledsword.minstrel.models.Invite
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
@@ -42,19 +32,28 @@ import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.ClipEntry
import androidx.compose.ui.platform.LocalClipboard
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavHostController
import com.composables.icons.lucide.Copy
import com.composables.icons.lucide.KeyRound
import com.composables.icons.lucide.Lucide
import com.composables.icons.lucide.Plus
import com.composables.icons.lucide.Trash2
import com.fabledsword.minstrel.auth.PasswordRules
import com.fabledsword.minstrel.models.AdminUserRef
import com.fabledsword.minstrel.models.Invite
import com.fabledsword.minstrel.nav.AdminUsers
import com.fabledsword.minstrel.shared.UiState
import com.fabledsword.minstrel.shared.widgets.ConfirmDestructiveDialog
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import kotlinx.coroutines.launch
@Composable
@@ -175,9 +174,13 @@ private fun AdminUsersScaffold(
}
@Composable
private fun SectionHeader(label: String, trailing: (@Composable () -> Unit)? = null) {
private fun SectionHeader(
label: String,
trailing: (@Composable () -> Unit)? = null,
) {
Row(
modifier = Modifier
modifier =
Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
@@ -202,7 +205,8 @@ private fun androidx.compose.foundation.lazy.LazyListScope.usersSection(
UiState.Loading -> item { CenteredHint("Loading users…") }
UiState.Empty -> item { CenteredHint("No registered users.") }
is UiState.Error -> item { CenteredHint(state.message) }
is UiState.Success -> items(items = state.data, key = { it.id }) { user ->
is UiState.Success ->
items(items = state.data, key = { it.id }) { user ->
UserRow(
user = user,
onSetAdmin = { onSetAdmin(user.id, it) },
@@ -220,10 +224,12 @@ private fun androidx.compose.foundation.lazy.LazyListScope.invitesSection(
) {
when {
state.isLoading -> item { CenteredHint("Loading invites…") }
state.invites.isEmpty() -> item {
state.invites.isEmpty() ->
item {
CenteredHint("No active invites. Use Generate to create one.")
}
else -> items(items = state.invites, key = { it.token }) { invite ->
else ->
items(items = state.invites, key = { it.token }) { invite ->
InviteRow(invite = invite, onRevoke = { onRevoke(invite.token) })
HorizontalDivider()
}
@@ -241,9 +247,13 @@ private fun CenteredHint(text: String) {
}
@Composable
private fun InviteRow(invite: Invite, onRevoke: () -> Unit) {
private fun InviteRow(
invite: Invite,
onRevoke: () -> Unit,
) {
Row(
modifier = Modifier
modifier =
Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
@@ -256,7 +266,8 @@ private fun InviteRow(invite: Invite, onRevoke: () -> Unit) {
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
val subtitle = buildString {
val subtitle =
buildString {
if (!invite.note.isNullOrEmpty()) {
append(invite.note)
append(" · ")
@@ -284,7 +295,10 @@ private fun InviteRow(invite: Invite, onRevoke: () -> Unit) {
}
@Composable
private fun GenerateInviteDialog(onDismiss: () -> Unit, onConfirm: (String?) -> Unit) {
private fun GenerateInviteDialog(
onDismiss: () -> Unit,
onConfirm: (String?) -> Unit,
) {
var note by remember { mutableStateOf("") }
AlertDialog(
onDismissRequest = onDismiss,
@@ -317,7 +331,10 @@ private fun GenerateInviteDialog(onDismiss: () -> Unit, onConfirm: (String?) ->
}
@Composable
private fun GeneratedInviteDialog(invite: Invite, onDismiss: () -> Unit) {
private fun GeneratedInviteDialog(
invite: Invite,
onDismiss: () -> Unit,
) {
val clipboard = LocalClipboard.current
val scope = rememberCoroutineScope()
AlertDialog(
@@ -399,7 +416,8 @@ private fun UserRow(
onDelete: () -> Unit,
) {
Column(
modifier = Modifier
modifier =
Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
@@ -444,7 +462,11 @@ private fun UserRow(
}
@Composable
private fun ToggleRow(label: String, checked: Boolean, onChange: (Boolean) -> Unit) {
private fun ToggleRow(
label: String,
checked: Boolean,
onChange: (Boolean) -> Unit,
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
@@ -496,7 +518,8 @@ private fun DeleteConfirmDialog(
) {
ConfirmDestructiveDialog(
title = "Delete user?",
text = "Delete @${user.username}? This removes the account and all " +
text =
"Delete @${user.username}? This removes the account and all " +
"their data. Type $DELETE_CONFIRM_WORD to confirm.",
confirmLabel = "Delete",
onConfirm = onConfirm,
@@ -506,4 +529,3 @@ private fun DeleteConfirmDialog(
}
private const val DELETE_CONFIRM_WORD = "DELETE"
@@ -21,11 +21,12 @@ import javax.inject.Inject
typealias AdminUsersUiState = UiState<List<AdminUserRef>>
@HiltViewModel
class AdminUsersViewModel @Inject constructor(
class AdminUsersViewModel
@Inject
constructor(
private val repository: AdminUsersRepository,
networkStatus: NetworkStatusController,
) : ViewModel() {
private val internal = MutableStateFlow<AdminUsersUiState>(UiState.Loading)
val uiState: StateFlow<AdminUsersUiState> = internal.asStateFlow()
@@ -40,16 +41,23 @@ class AdminUsersViewModel @Inject constructor(
}
}
fun refresh(): Job = viewModelScope.launch {
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) }) {
fun setAdmin(
id: String,
isAdmin: Boolean,
) = patch(id, { it.copy(isAdmin = isAdmin) }) {
repository.setAdmin(it, isAdmin)
}
fun resetPassword(id: String, newPassword: String) {
fun resetPassword(
id: String,
newPassword: String,
) {
viewModelScope.launch {
runCatching { repository.resetPassword(id, newPassword) }
}
@@ -78,7 +86,8 @@ class AdminUsersViewModel @Inject constructor(
) {
val before = internal.value
if (before is UiState.Success) {
internal.value = UiState.Success(
internal.value =
UiState.Success(
before.data.map { if (it.id == id) mutate(it) else it },
)
}
@@ -20,10 +20,11 @@ import javax.inject.Singleton
* from any of those hosts would sign the user out of Minstrel.
*/
@Singleton
class AuthCookieInterceptor @Inject constructor(
class AuthCookieInterceptor
@Inject
constructor(
private val authStore: AuthStore,
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val original = chain.request()
if (original.url.host != BaseUrlInterceptor.PLACEHOLDER_HOST) {
@@ -33,7 +34,10 @@ class AuthCookieInterceptor @Inject constructor(
return chain.proceed(original)
}
val cookie = authStore.sessionCookieForRequest()
val request = original.newBuilder().apply {
val request =
original
.newBuilder()
.apply {
if (!cookie.isNullOrEmpty()) header("Cookie", cookie)
}.build()
@@ -31,10 +31,11 @@ import javax.inject.Singleton
* error in the caller's normal error path.
*/
@Singleton
class BaseUrlInterceptor @Inject constructor(
class BaseUrlInterceptor
@Inject
constructor(
private val authStore: AuthStore,
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val original = chain.request()
// Early-bail keeps the no-op path for external URLs cheap
@@ -42,15 +43,18 @@ class BaseUrlInterceptor @Inject constructor(
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()
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()
original
.newBuilder()
.url(rewritten)
// Lets CleartextGuardInterceptor tell server requests from
// external fetches once the placeholder host is gone.
@@ -39,7 +39,12 @@ class CleartextGuardInterceptor(
if (request.isHttps || request.tag(MinstrelServerRequest::class.java) == null) {
return chain.proceed(request)
}
val address = chain.connection()?.route()?.socketAddress?.address
val address =
chain
.connection()
?.route()
?.socketAddress
?.address
if (address != null && !allows(address)) {
throw CleartextToPublicHostException(request.url.host)
}
@@ -48,8 +53,9 @@ class CleartextGuardInterceptor(
}
/** The server was reached over plain HTTP at a public address, and refused. */
class CleartextToPublicHostException(host: String) :
IOException("refusing plain http:// to $host: it is a public address")
class CleartextToPublicHostException(
host: String,
) : IOException("refusing plain http:// to $host: it is a public address")
/** Which addresses plain HTTP may reach: the home network, never the internet. */
object CleartextPolicy {
@@ -62,8 +68,10 @@ object CleartextPolicy {
fun allows(address: InetAddress): Boolean =
address.isLoopbackAddress ||
address.isSiteLocalAddress || // 10/8, 172.16/12, 192.168/16
address.isLinkLocalAddress || // 169.254/16, fe80::/10
address.isSiteLocalAddress ||
// 10/8, 172.16/12, 192.168/16
address.isLinkLocalAddress ||
// 169.254/16, fe80::/10
address.isAnyLocalAddress ||
isCarrierGradeNat(address) ||
isUniqueLocal(address)
@@ -1,6 +1,5 @@
package com.fabledsword.minstrel.api
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import retrofit2.HttpException
@@ -23,10 +22,15 @@ object ErrorCopy {
private val json = Json { ignoreUnknownKeys = true }
@Serializable
private data class Envelope(val error: Body? = null)
private data class Envelope(
val error: Body? = null,
)
@Serializable
private data class Body(val code: String = "", val message: String = "")
private data class Body(
val code: String = "",
val message: String = "",
)
/** Friendly copy for a known error [code], or the `unknown` fallback. */
fun messageFor(code: String): String = TABLE[code] ?: TABLE.getValue("unknown")
@@ -36,7 +40,8 @@ object ErrorCopy {
* HttpException bodies for the server code; treats IOExceptions
* as connection failures.
*/
fun fromThrowable(t: Throwable): String = when (t) {
fun fromThrowable(t: Throwable): String =
when (t) {
is HttpException -> fromHttp(t)
is CleartextToPublicHostException -> messageFor("cleartext_public")
is IOException -> messageFor("connection_refused")
@@ -65,7 +70,8 @@ object ErrorCopy {
}
private fun bodyFromHttp(e: HttpException): Body {
val raw = runCatching { e.response()?.errorBody()?.string() }.getOrNull()
val raw =
runCatching { e.response()?.errorBody()?.string() }.getOrNull()
?: return Body()
return runCatching { json.decodeFromString<Envelope>(raw).error }
.getOrNull() ?: Body()
@@ -28,7 +28,6 @@ import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Provides
@Singleton
fun provideHttpLogging(): HttpLoggingInterceptor =
@@ -49,7 +48,8 @@ object NetworkModule {
reachability: ReachabilityReportingInterceptor,
logging: HttpLoggingInterceptor,
): OkHttpClient =
OkHttpClient.Builder()
OkHttpClient
.Builder()
// ReachabilityReportingInterceptor MUST run first: it identifies
// Minstrel-bound requests by the still-unrewritten PLACEHOLDER_HOST
// (so external artwork fetches don't read as server reachability)
@@ -82,7 +82,8 @@ object NetworkModule {
okHttp: OkHttpClient,
json: Json,
): Retrofit =
Retrofit.Builder()
Retrofit
.Builder()
// Placeholder base URL — BaseUrlInterceptor rewrites every
// outgoing request to the live AuthStore value, so this
// string only has to satisfy Retrofit's parser and is
@@ -6,4 +6,6 @@ package com.fabledsword.minstrel.api
* the graph.
*/
@JvmInline
value class ServerBaseUrl(val value: String)
value class ServerBaseUrl(
val value: String,
)
@@ -20,10 +20,14 @@ interface AdminInvitesApi {
suspend fun list(): AdminInvitesListWire
@POST("api/admin/invites")
suspend fun create(@Body body: CreateInviteBody): InviteWire
suspend fun create(
@Body body: CreateInviteBody,
): InviteWire
@DELETE("api/admin/invites/{token}")
suspend fun revoke(@Path("token") token: String)
suspend fun revoke(
@Path("token") token: String,
)
}
/**
@@ -31,4 +35,6 @@ interface AdminInvitesApi {
* which the server treats the same as an absent field.
*/
@Serializable
data class CreateInviteBody(val note: String? = null)
data class CreateInviteBody(
val note: String? = null,
)
@@ -19,11 +19,17 @@ interface AdminQuarantineApi {
suspend fun list(): List<AdminQuarantineItemWire>
@POST("api/admin/quarantine/{trackId}/resolve")
suspend fun resolve(@Path("trackId") trackId: String)
suspend fun resolve(
@Path("trackId") trackId: String,
)
@POST("api/admin/quarantine/{trackId}/remove-file")
suspend fun removeFile(@Path("trackId") trackId: String)
suspend fun removeFile(
@Path("trackId") trackId: String,
)
@POST("api/admin/quarantine/{trackId}/delete-file")
suspend fun deleteFile(@Path("trackId") trackId: String)
suspend fun deleteFile(
@Path("trackId") trackId: String,
)
}
@@ -23,10 +23,15 @@ interface AdminTagSourcesApi {
suspend fun list(): AdminTagSourcesListWire
@PATCH("api/admin/tag-sources/{id}")
suspend fun update(@Path("id") id: String, @Body body: UpdateTagSourceBody): AdminTagSourceWire
suspend fun update(
@Path("id") id: String,
@Body body: UpdateTagSourceBody,
): AdminTagSourceWire
@POST("api/admin/tag-sources/{id}/test")
suspend fun test(@Path("id") id: String): TestTagSourceWire
suspend fun test(
@Path("id") id: String,
): TestTagSourceWire
}
/**
@@ -15,13 +15,21 @@ interface AdminUsersApi {
suspend fun list(): AdminUsersListWire
@PUT("api/admin/users/{id}/admin")
suspend fun setAdmin(@Path("id") id: String, @Body body: SetAdminBody)
suspend fun setAdmin(
@Path("id") id: String,
@Body body: SetAdminBody,
)
@POST("api/admin/users/{id}/reset-password")
suspend fun resetPassword(@Path("id") id: String, @Body body: ResetPasswordBody)
suspend fun resetPassword(
@Path("id") id: String,
@Body body: ResetPasswordBody,
)
@DELETE("api/admin/users/{id}")
suspend fun delete(@Path("id") id: String)
suspend fun delete(
@Path("id") id: String,
)
}
@Serializable
@@ -30,4 +38,6 @@ data class SetAdminBody(
)
@Serializable
data class ResetPasswordBody(val password: String)
data class ResetPasswordBody(
val password: String,
)
@@ -14,7 +14,9 @@ import retrofit2.http.POST
*/
interface AuthApi {
@POST("api/auth/login")
suspend fun login(@Body body: LoginRequestBody): LoginResponseWire
suspend fun login(
@Body body: LoginRequestBody,
): LoginResponseWire
@POST("api/auth/logout")
suspend fun logout()
@@ -22,7 +22,9 @@ import retrofit2.http.POST
*/
interface CastApi {
@POST("api/cast/stream-token")
suspend fun streamToken(@Body req: StreamTokenRequest): StreamTokenResponse
suspend fun streamToken(
@Body req: StreamTokenRequest,
): StreamTokenResponse
}
/**
@@ -14,7 +14,9 @@ import retrofit2.http.POST
*/
interface DiagnosticsApi {
@POST("api/diagnostics")
suspend fun report(@Body body: DiagnosticsReportRequest)
suspend fun report(
@Body body: DiagnosticsReportRequest,
)
}
@Serializable
@@ -17,14 +17,22 @@ import retrofit2.http.POST
*/
interface EventsApi {
@POST("api/events")
suspend fun playStarted(@Body body: PlayStartedRequest): PlayStartedResponse
suspend fun playStarted(
@Body body: PlayStartedRequest,
): PlayStartedResponse
@POST("api/events")
suspend fun playEnded(@Body body: PlayEndedRequest)
suspend fun playEnded(
@Body body: PlayEndedRequest,
)
@POST("api/events")
suspend fun playSkipped(@Body body: PlaySkippedRequest)
suspend fun playSkipped(
@Body body: PlaySkippedRequest,
)
@POST("api/events")
suspend fun playOffline(@Body body: PlayOfflineRequest)
suspend fun playOffline(
@Body body: PlayOfflineRequest,
)
}
@@ -30,13 +30,19 @@ import retrofit2.http.Query
*/
interface LibraryApi {
@GET("api/tracks/{id}")
suspend fun getTrack(@Path("id") id: String): TrackWire
suspend fun getTrack(
@Path("id") id: String,
): TrackWire
@GET("api/artists/{id}")
suspend fun getArtistDetail(@Path("id") id: String): ArtistDetailWire
suspend fun getArtistDetail(
@Path("id") id: String,
): ArtistDetailWire
@GET("api/artists/{id}/tracks")
suspend fun getArtistTracks(@Path("id") id: String): List<TrackWire>
suspend fun getArtistTracks(
@Path("id") id: String,
): List<TrackWire>
@GET("api/artists/{id}/similar")
suspend fun getSimilarArtists(
@@ -51,10 +57,14 @@ interface LibraryApi {
): List<TrackWire>
@GET("api/albums/{id}")
suspend fun getAlbumDetail(@Path("id") id: String): AlbumDetailWire
suspend fun getAlbumDetail(
@Path("id") id: String,
): AlbumDetailWire
@GET("api/library/shuffle")
suspend fun shuffleLibrary(@Query("limit") limit: Int = 100): List<TrackWire>
suspend fun shuffleLibrary(
@Query("limit") limit: Int = 100,
): List<TrackWire>
// Browse axes. Both indexes are unpaged by design: the client needs
// the whole set to render a browsable picker, and even a messy library
@@ -20,10 +20,16 @@ import retrofit2.http.Path
*/
interface LikesApi {
@POST("api/likes/{kind}/{id}")
suspend fun like(@Path("kind") kind: String, @Path("id") id: String)
suspend fun like(
@Path("kind") kind: String,
@Path("id") id: String,
)
@DELETE("api/likes/{kind}/{id}")
suspend fun unlike(@Path("kind") kind: String, @Path("id") id: String)
suspend fun unlike(
@Path("kind") kind: String,
@Path("id") id: String,
)
@GET("api/likes/ids")
suspend fun ids(): LikedIdsWire
@@ -27,14 +27,18 @@ interface MeApi {
* state without an extra GET.
*/
@PUT("api/me/profile")
suspend fun updateProfile(@Body body: UpdateProfileRequest): MyProfileWire
suspend fun updateProfile(
@Body body: UpdateProfileRequest,
): MyProfileWire
/**
* Change the caller's password. Server validates `current_password`
* before accepting `new_password`. No body on success (204).
*/
@PUT("api/me/password")
suspend fun changePassword(@Body body: ChangePasswordRequest)
suspend fun changePassword(
@Body body: ChangePasswordRequest,
)
/**
* Caller's ListenBrainz state — never returns the token itself,
@@ -59,7 +63,9 @@ interface MeApi {
* post-write status so callers refresh without a separate GET.
*/
@PUT("api/me/listenbrainz")
suspend fun setListenBrainz(@Body body: ListenBrainzPutBody): ListenBrainzStatusWire
suspend fun setListenBrainz(
@Body body: ListenBrainzPutBody,
): ListenBrainzStatusWire
/** The caller's loudness-normalization preference, or the defaults if never set. */
@GET("api/me/normalization")
@@ -67,7 +73,9 @@ interface MeApi {
/** Replaces the whole preference; returns what the server stored. */
@PUT("api/me/normalization")
suspend fun putNormalization(@Body body: NormalizationPrefs): NormalizationPrefs
suspend fun putNormalization(
@Body body: NormalizationPrefs,
): NormalizationPrefs
}
/**
@@ -15,20 +15,28 @@ import retrofit2.http.Query
*/
interface NotificationsApi {
@GET("api/me/notifications")
suspend fun list(@Query("limit") limit: Int): NotificationsPageWire
suspend fun list(
@Query("limit") limit: Int,
): NotificationsPageWire
/** 204; 404 when the notice is gone, which a replay treats as done. */
@POST("api/me/notifications/{id}/read")
suspend fun markRead(@Path("id") id: String)
suspend fun markRead(
@Path("id") id: String,
)
@POST("api/me/notifications/read-all")
suspend fun readAll(@Body body: ReadAllBody)
suspend fun readAll(
@Body body: ReadAllBody,
)
@GET("api/me/notification-settings")
suspend fun getSettings(): NotificationSettingsWire
@PUT("api/me/notification-settings")
suspend fun putSettings(@Body body: PutNotificationSettingsBody): NotificationSettingsWire
suspend fun putSettings(
@Body body: PutNotificationSettingsBody,
): NotificationSettingsWire
}
@Serializable
@@ -55,7 +63,9 @@ data class NotificationsPageWire(
* the app's Json drops default-valued fields.
*/
@Serializable
data class ReadAllBody(@SerialName("up_to") val upTo: String?)
data class ReadAllBody(
@SerialName("up_to") val upTo: String?,
)
@Serializable
data class NotificationKindSettingWire(
@@ -87,4 +97,6 @@ data class NotificationSettingChangeWire(
)
@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 {
@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).
*/
@GET("api/playlists")
suspend fun list(@Query("kind") kind: String = "all"): PlaylistsListWire
suspend fun list(
@Query("kind") kind: String = "all",
): PlaylistsListWire
@GET("api/playlists/{id}")
suspend fun get(@Path("id") id: String): PlaylistDetailWire
suspend fun get(
@Path("id") id: String,
): PlaylistDetailWire
/**
* POST /api/playlists — make a playlist under the id the app chose,
* so a create queued offline and sent again finds the same list.
*/
@POST("api/playlists")
suspend fun create(@Body body: CreatePlaylistRequest)
suspend fun create(
@Body body: CreatePlaylistRequest,
)
/** PATCH /api/playlists/{id} — rename, or make public or private. Null fields stay as they are. */
@PATCH("api/playlists/{id}")
suspend fun update(@Path("id") id: String, @Body body: UpdatePlaylistRequest)
suspend fun update(
@Path("id") id: String,
@Body body: UpdatePlaylistRequest,
)
@DELETE("api/playlists/{id}")
suspend fun delete(@Path("id") id: String)
suspend fun delete(
@Path("id") id: String,
)
/**
* DELETE /api/playlists/{id}/tracks/{position}. [trackId] is the song
@@ -62,7 +73,10 @@ interface PlaylistsApi {
* changes nothing the second time.
*/
@PUT("api/playlists/{id}/tracks")
suspend fun reorder(@Path("id") id: String, @Body body: ReorderTracksRequest)
suspend fun reorder(
@Path("id") id: String,
@Body body: ReorderTracksRequest,
)
/** POST /api/playlists/{id}/tracks — append the given track IDs to the owner's playlist. */
@POST("api/playlists/{id}/tracks")
@@ -79,7 +93,9 @@ interface PlaylistsApi {
* pick seed tracks. The kind is the raw system_variant.
*/
@POST("api/playlists/system/{kind}/refresh")
suspend fun refreshSystem(@Path("kind") variant: String): RefreshSystemResponse
suspend fun refreshSystem(
@Path("kind") variant: String,
): RefreshSystemResponse
/**
* GET /api/playlists/system/{kind}/shuffle. Returns
@@ -89,7 +105,9 @@ interface PlaylistsApi {
* the stored order.
*/
@GET("api/playlists/system/{kind}/shuffle")
suspend fun systemShuffle(@Path("kind") variant: String): PlaylistDetailWire
suspend fun systemShuffle(
@Path("kind") variant: String,
): PlaylistDetailWire
}
/**
@@ -20,10 +20,14 @@ interface QuarantineApi {
suspend fun listMine(): List<QuarantineMineWire>
@POST("api/quarantine")
suspend fun flag(@Body body: FlagRequest)
suspend fun flag(
@Body body: FlagRequest,
)
@DELETE("api/quarantine/{trackId}")
suspend fun unflag(@Path("trackId") trackId: String)
suspend fun unflag(
@Path("trackId") trackId: String,
)
}
/**
@@ -11,5 +11,7 @@ interface ReplayGainApi {
* missing from `items` has not been measured yet.
*/
@GET("api/tracks/replay-gain")
suspend fun getReplayGain(@Query("ids") ids: String): ReplayGainResponseWire
suspend fun getReplayGain(
@Query("ids") ids: String,
): ReplayGainResponseWire
}
@@ -19,5 +19,7 @@ import retrofit2.http.Query
*/
interface SyncApi {
@GET("api/library/sync")
suspend fun sync(@Query("since") since: Long): Response<SyncResponseWire>
suspend fun sync(
@Query("since") since: Long,
): Response<SyncResponseWire>
}
@@ -29,7 +29,9 @@ import javax.inject.Singleton
* username after a fresh app launch without re-prompting.
*/
@Singleton
class AuthController @Inject constructor(
class AuthController
@Inject
constructor(
private val authStore: AuthStore,
private val json: Json,
@ApplicationScope private val scope: CoroutineScope,
@@ -69,9 +71,13 @@ class AuthController @Inject constructor(
* caller can safely navigate to the in-shell graph. Throws on
* any non-2xx response (caller surfaces in UI).
*/
suspend fun signIn(username: String, password: String): UserRef {
suspend fun signIn(
username: String,
password: String,
): UserRef {
val response = api.login(LoginRequestBody(username = username, password = password))
val user = UserRef(
val user =
UserRef(
id = response.user.id,
username = response.user.username,
isAdmin = response.user.isAdmin,
@@ -97,7 +103,8 @@ class AuthController @Inject constructor(
authStore.awaitSessionHydrated()
if (!isSignedIn) return
val p = runCatching { meApi.getProfile() }.getOrNull() ?: return
val user = UserRef(
val user =
UserRef(
id = p.id,
username = p.username,
isAdmin = p.isAdmin,
@@ -122,7 +129,8 @@ class AuthController @Inject constructor(
suspend fun signOut() {
currentUserState.value = null
authStore.setUserJson(null)
scope.launch {
scope
.launch {
try {
withTimeoutOrNull(LOGOUT_TIMEOUT_MS) { runCatching { api.logout() } }
} finally {
@@ -132,7 +140,9 @@ class AuthController @Inject constructor(
}
private fun decodeUser(raw: String): UserRef? =
runCatching { json.decodeFromString(UserRef.serializer(), raw) }.getOrNull()
runCatching {
json.decodeFromString(UserRef.serializer(), raw)
}.getOrNull()
private companion object {
// Long enough for a logout on a slow connection, short enough that
@@ -21,6 +21,14 @@ import timber.log.Timber
import javax.inject.Inject
import javax.inject.Singleton
// AuthStore is the single-row facade over auth_session (de-facto
// app_preferences — see entity comment). It legitimately owns one
// getter + one setter + one persist helper per pref column; the
// function count scales with the pref count, not with feature
// complexity. Splitting into per-pref stores would scatter the
// shared dao + scope + json plumbing for no real gain. Suppress
// the cap rather than fragment.
/**
* Holds the user's session cookie and configured server base URL.
*
@@ -44,16 +52,11 @@ import javax.inject.Singleton
* [awaitSessionHydrated] lets a caller that needs a definitive answer
* (the auth gate) wait for this.
*/
// AuthStore is the single-row facade over auth_session (de-facto
// app_preferences — see entity comment). It legitimately owns one
// getter + one setter + one persist helper per pref column; the
// function count scales with the pref count, not with feature
// complexity. Splitting into per-pref stores would scatter the
// shared dao + scope + json plumbing for no real gain. Suppress
// the cap rather than fragment.
@Suppress("TooManyFunctions")
@Singleton
class AuthStore @Inject constructor(
class AuthStore
@Inject
constructor(
private val dao: AuthSessionDao,
private val vault: SessionVault,
@ApplicationScope private val scope: CoroutineScope,
@@ -205,7 +208,8 @@ class AuthStore @Inject constructor(
sessionRejectedState.value = true
}
private suspend fun hydrateSessionCookie() = cookieLock.withLock {
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
@@ -363,7 +367,8 @@ class AuthStore @Inject constructor(
}
}
private fun currentEntity(): AuthSessionEntity = AuthSessionEntity(
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.
@@ -372,12 +377,14 @@ class AuthStore @Inject constructor(
userJson = userJsonState.value,
themeMode = themeModeState.value,
clientId = clientIdState.value,
cacheSettingsJson = json.encodeToString(
cacheSettingsJson =
json.encodeToString(
CacheSettings.serializer(),
cacheSettingsState.value,
),
diagnosticsOptOut = diagnosticsOptOutState.value,
normalizationJson = json.encodeToString(
normalizationJson =
json.encodeToString(
NormalizationPrefs.serializer(),
normalizationState.value,
),
@@ -35,21 +35,30 @@ import kotlin.coroutines.resumeWithException
* Plain http still passes through [com.fabledsword.minstrel.api.CleartextGuardInterceptor]
* on [client], so the fallback can only succeed on a home-network address.
*/
class ServerProbe internal constructor(client: OkHttpClient, callTimeoutMillis: Long) {
class ServerProbe internal constructor(
client: OkHttpClient,
callTimeoutMillis: Long,
) {
// Each attempt is short: a probe that stalls holds the sign-in screen.
@Inject constructor(client: OkHttpClient) : this(client, CALL_TIMEOUT_MILLIS)
@Inject
constructor(client: OkHttpClient) : this(client, CALL_TIMEOUT_MILLIS)
private val client: OkHttpClient = client.newBuilder()
private val client: OkHttpClient =
client
.newBuilder()
.connectTimeout(callTimeoutMillis, TimeUnit.MILLISECONDS)
.callTimeout(callTimeoutMillis, TimeUnit.MILLISECONDS)
.build()
sealed interface Result {
/** Minstrel answered at [baseUrl], which includes its scheme. */
data class Found(val baseUrl: String) : Result
data class Found(
val baseUrl: String,
) : Result
data class Failed(val message: String) : Result
data class Failed(
val message: String,
) : Result
}
suspend fun find(input: String): Result {
@@ -100,16 +109,23 @@ class ServerProbe internal constructor(client: OkHttpClient, callTimeoutMillis:
data object Minstrel : Outcome
/** Nothing answered: the next scheme may be tried. */
data class Unreachable(val publicCleartext: Boolean = false) : Outcome
data class Unreachable(
val publicCleartext: Boolean = false,
) : Outcome
/** Something answered, or TLS failed to verify: stop here. */
data class Stop(val message: String) : Outcome
data class Stop(
val message: String,
) : Outcome
}
private suspend fun attempt(baseUrl: String): Outcome {
val url = "$baseUrl$SETUP_STATUS_PATH".toHttpUrlOrNull()
val url =
"$baseUrl$SETUP_STATUS_PATH".toHttpUrlOrNull()
?: return Outcome.Stop("That doesn't look like a server address.")
val request = Request.Builder()
val request =
Request
.Builder()
.url(url)
// Lets CleartextGuardInterceptor treat the probe as a Minstrel
// server request, as it treats sign-in.
@@ -123,9 +139,13 @@ class ServerProbe internal constructor(client: OkHttpClient, callTimeoutMillis:
Outcome.Stop("A server answered at $baseUrl, but it isn't Minstrel.")
}
}
} catch (@Suppress("SwallowedException") e: CleartextToPublicHostException) {
} catch (
@Suppress("SwallowedException") e: CleartextToPublicHostException,
) {
Outcome.Unreachable(publicCleartext = true)
} catch (@Suppress("SwallowedException") e: UnknownHostException) {
} catch (
@Suppress("SwallowedException") e: UnknownHostException,
) {
Outcome.Stop("Couldn't find a server named ${url.host}.")
} catch (e: IOException) {
if (isCertificateFailure(e)) {
@@ -151,21 +171,43 @@ class ServerProbe internal constructor(client: OkHttpClient, callTimeoutMillis:
// (hostname) or as an SSLHandshakeException caused by a
// CertificateException or CertPathValidatorException (trust). A port
// with no TLS fails the handshake too, but with no such cause.
private fun isCertificateFailure(e: IOException): Boolean =
generateSequence<Throwable>(e) { it.cause }
.take(MAX_CAUSE_DEPTH)
.any { it is SSLPeerUnverifiedException || it is GeneralSecurityException }
//
// OkHttp tries a host's addresses in parallel (fast fallback). When
// all of them fail it throws one failure and attaches the rest as
// suppressed, so the certificate error can sit behind a refused
// connection to the host's other address. Both causes and suppressed
// exceptions are searched.
private fun isCertificateFailure(e: IOException): Boolean {
val seen = mutableSetOf<Throwable>()
val pending = ArrayDeque<Throwable>().apply { add(e) }
var found = false
while (!found && pending.isNotEmpty() && seen.size < MAX_EXCEPTIONS_SEARCHED) {
val t = pending.removeFirst()
if (seen.add(t)) {
found = t is SSLPeerUnverifiedException || t is GeneralSecurityException
t.cause?.let { pending.addLast(it) }
pending.addAll(t.suppressed)
}
}
return found
}
private suspend fun Call.await(): Response =
suspendCancellableCoroutine { continuation ->
continuation.invokeOnCancellation { cancel() }
enqueue(
object : Callback {
override fun onResponse(call: Call, response: Response) {
override fun onResponse(
call: Call,
response: Response,
) {
if (continuation.isActive) continuation.resume(response) else response.close()
}
override fun onFailure(call: Call, e: IOException) {
override fun onFailure(
call: Call,
e: IOException,
) {
if (continuation.isActive) continuation.resumeWithException(e)
}
},
@@ -175,6 +217,6 @@ class ServerProbe internal constructor(client: OkHttpClient, callTimeoutMillis:
private companion object {
const val SETUP_STATUS_PATH = "/api/auth/setup-status"
const val CALL_TIMEOUT_MILLIS = 8_000L
const val MAX_CAUSE_DEPTH = 8
const val MAX_EXCEPTIONS_SEARCHED = 16
}
}
@@ -54,7 +54,10 @@ internal object SealedBox {
// under the same key will not open as a session cookie.
private val AAD = "minstrel-session-cookie-v1".toByteArray(Charsets.UTF_8)
fun seal(key: SecretKey, plaintext: String): String {
fun seal(
key: SecretKey,
plaintext: String,
): String {
val cipher = Cipher.getInstance(TRANSFORMATION)
// No IV passed: the provider generates a fresh random one. Keystore
// keys refuse a caller-chosen IV for encryption by default.
@@ -64,7 +67,10 @@ internal object SealedBox {
return Base64.getEncoder().encodeToString(sealed)
}
fun open(key: SecretKey, sealed: String): String {
fun open(
key: SecretKey,
sealed: String,
): String {
val bytes = Base64.getDecoder().decode(sealed)
require(bytes.size > IV_BYTES) { "sealed value too short" }
val cipher = Cipher.getInstance(TRANSFORMATION)
@@ -85,7 +91,9 @@ internal object SealedBox {
* credential that no longer verifies.
*/
@Singleton
class KeystoreSessionVault @Inject constructor(
class KeystoreSessionVault
@Inject
constructor(
@ApplicationContext context: Context,
) : SessionVault {
private val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
@@ -96,11 +104,11 @@ class KeystoreSessionVault @Inject constructor(
.onFailure {
Timber.w(it, "session vault: stored cookie would not decrypt; discarding it")
prefs.edit().remove(KEY_COOKIE).commit()
}
.getOrNull()
}.getOrNull()
}
override fun write(value: String?): Boolean = runCatching {
override fun write(value: String?): Boolean =
runCatching {
val editor = prefs.edit()
if (value == null) {
editor.remove(KEY_COOKIE)
@@ -117,11 +125,11 @@ class KeystoreSessionVault @Inject constructor(
(keyStore.getKey(KEY_ALIAS, null) as? SecretKey)?.let { return it }
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE)
generator.init(
KeyGenParameterSpec.Builder(
KeyGenParameterSpec
.Builder(
KEY_ALIAS,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
).setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(KEY_BITS)
.build(),
@@ -30,11 +30,12 @@ import javax.inject.Inject
* and then exactly one resolved value.
*/
@HiltViewModel
class AuthGateViewModel @Inject constructor(
class AuthGateViewModel
@Inject
constructor(
private val dao: AuthSessionDao,
private val authStore: AuthStore,
) : ViewModel() {
private val internal = MutableStateFlow<Any?>(null)
val startDestination: StateFlow<Any?> = internal.asStateFlow()
@@ -52,7 +53,8 @@ class AuthGateViewModel @Inject constructor(
authStore.awaitSessionHydrated()
val signedIn = !authStore.sessionCookie.value.isNullOrEmpty()
val row = dao.get()
internal.value = when {
internal.value =
when {
row == null -> ServerUrl
row.baseUrl == AuthStore.DEFAULT_BASE_URL && !signedIn -> ServerUrl
!signedIn -> Login
@@ -71,7 +71,8 @@ private fun LoginForm(
onChangeServerUrl: () -> Unit,
) {
Column(
modifier = Modifier
modifier =
Modifier
.fillMaxSize()
.padding(24.dp),
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
@@ -89,7 +90,8 @@ private fun LoginForm(
label = { Text("Username") },
singleLine = true,
enabled = !state.isSubmitting,
keyboardOptions = KeyboardOptions(
keyboardOptions =
KeyboardOptions(
keyboardType = KeyboardType.Email,
imeAction = ImeAction.Next,
),
@@ -102,7 +104,8 @@ private fun LoginForm(
singleLine = true,
enabled = !state.isSubmitting,
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(
keyboardOptions =
KeyboardOptions(
keyboardType = KeyboardType.Password,
imeAction = ImeAction.Done,
),
@@ -126,10 +129,14 @@ private fun LoginForm(
}
@Composable
private fun SubmitButton(state: LoginFormState, onSubmit: () -> Unit) {
private fun SubmitButton(
state: LoginFormState,
onSubmit: () -> Unit,
) {
Button(
onClick = onSubmit,
enabled = !state.isSubmitting &&
enabled =
!state.isSubmitting &&
state.username.isNotBlank() &&
state.password.isNotBlank(),
modifier = Modifier.fillMaxWidth(),
@@ -21,10 +21,11 @@ data class LoginFormState(
)
@HiltViewModel
class LoginViewModel @Inject constructor(
class LoginViewModel
@Inject
constructor(
private val auth: AuthController,
) : ViewModel() {
private val internal = MutableStateFlow(LoginFormState())
val state: StateFlow<LoginFormState> = internal.asStateFlow()
@@ -51,12 +51,14 @@ data class ServerUrlFormState(
)
@HiltViewModel
class ServerUrlViewModel @Inject constructor(
class ServerUrlViewModel
@Inject
constructor(
private val authStore: AuthStore,
private val probe: ServerProbe,
) : ViewModel() {
private val internal = MutableStateFlow(
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
@@ -64,7 +66,8 @@ class ServerUrlViewModel @Inject constructor(
// placeholder ("minstrel.example.com") show through so the user
// can just type without first having to clear.
ServerUrlFormState(
url = authStore.baseUrl.value
url =
authStore.baseUrl.value
.takeIf { it != AuthStore.DEFAULT_BASE_URL }
.orEmpty(),
),
@@ -85,7 +88,8 @@ class ServerUrlViewModel @Inject constructor(
fun submit() {
if (internal.value.probing) return
val typed = internal.value.url
probeJob = viewModelScope.launch {
probeJob =
viewModelScope.launch {
internal.update { it.copy(probing = true, errorMessage = null) }
when (val result = probe.find(typed)) {
is ServerProbe.Result.Found -> {
@@ -149,7 +153,8 @@ private fun ServerUrlForm(
onCancel: () -> Unit,
) {
Column(
modifier = Modifier
modifier =
Modifier
.fillMaxSize()
.padding(24.dp),
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
@@ -176,7 +181,8 @@ private fun ServerUrlForm(
},
singleLine = true,
enabled = !state.probing,
keyboardOptions = KeyboardOptions(
keyboardOptions =
KeyboardOptions(
keyboardType = KeyboardType.Uri,
imeAction = ImeAction.Done,
),
@@ -31,7 +31,9 @@ import javax.inject.Singleton
* the construct-the-singleton trick in `MinstrelApplication`.
*/
@Singleton
class CacheIndexer @Inject constructor(
class CacheIndexer
@Inject
constructor(
playerController: PlayerController,
private val dao: AudioCacheIndexDao,
@ApplicationScope private val scope: CoroutineScope,
@@ -33,7 +33,9 @@ import javax.inject.Singleton
* library is opened offline with no active playback.
*/
@Singleton
class CachedTrackIds @Inject constructor(
class CachedTrackIds
@Inject
constructor(
playerController: PlayerController,
private val playerFactory: PlayerFactory,
@ApplicationScope scope: CoroutineScope,
@@ -28,7 +28,9 @@ private const val POOL_LIMIT = 100
* plays the pool from the cache.
*/
@Singleton
class ShuffleSource @Inject constructor(
class ShuffleSource
@Inject
constructor(
private val cacheIndexDao: AudioCacheIndexDao,
private val trackDao: CachedTrackDao,
private val likes: LikesRepository,
@@ -47,7 +49,8 @@ class ShuffleSource @Inject constructor(
/** Recency-ordered ids whose audio is actually resident in the cache. */
private suspend fun residentIdsByRecency(): List<String> {
val resident = runCatching { playerFactory.simpleCache.keys.toSet() }
val resident =
runCatching { playerFactory.simpleCache.keys.toSet() }
.getOrDefault(emptySet())
return cacheIndexDao.trackIdsByRecency().filter { it in resident }
}
@@ -34,7 +34,12 @@ internal enum class OwnerStep {
OWNED,
}
internal fun ownerStep(loaded: Boolean, signedInUserId: String?, ownerUserId: String?): OwnerStep = when {
internal fun ownerStep(
loaded: Boolean,
signedInUserId: String?,
ownerUserId: String?,
): OwnerStep =
when {
!loaded || signedInUserId == null -> OwnerStep.WAIT
ownerUserId == null -> OwnerStep.ADOPT
ownerUserId != signedInUserId -> OwnerStep.SWITCH
@@ -62,7 +67,9 @@ internal fun ownerStep(loaded: Boolean, signedInUserId: String?, ownerUserId: St
* out under another account's session.
*/
@Singleton
class AccountCache @Inject constructor(
class AccountCache
@Inject
constructor(
private val authStore: AuthStore,
authController: AuthController,
private val tables: AccountTables,
@@ -86,7 +93,10 @@ class AccountCache @Inject constructor(
}
}
private suspend fun step(step: OwnerStep, userId: String?) {
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.
@@ -12,7 +12,11 @@ import javax.inject.Singleton
* (likes, playlists) or shared by every account (the library) does not.
*/
@Singleton
class AccountTables @Inject constructor(private val db: AppDatabase) {
class AccountTables
@Inject
constructor(
private val db: AppDatabase,
) {
/** Clears them in one transaction, so a crash can't leave half of them. */
suspend fun clear() {
db.withTransaction {
@@ -27,7 +27,8 @@ class BucketLedger<S : Any>(
private val lengthOf: (S) -> Long,
lruOrder: Comparator<S>,
) {
private val spans = mapOf(
private val spans =
mapOf(
CacheBucket.LIKED to TreeSet(lruOrder),
CacheBucket.RECENT to TreeSet(lruOrder),
)
@@ -43,13 +44,13 @@ class BucketLedger<S : Any>(
/** Cap on Recently played bytes; 0 means unlimited. */
var recentCapBytes: Long = 0L
fun bucketOf(key: String): CacheBucket =
if (key in liked) CacheBucket.LIKED else CacheBucket.RECENT
fun bucketOf(key: String): CacheBucket = if (key in liked) CacheBucket.LIKED else CacheBucket.RECENT
fun bytesIn(bucket: CacheBucket): Long = bytes.getValue(bucket)
/** Bytes the Liked budget can still take; [Long.MAX_VALUE] when unlimited. */
fun likedRoomBytes(): Long = when {
fun likedRoomBytes(): Long =
when {
likedCapBytes <= 0L -> Long.MAX_VALUE
else -> (likedCapBytes - bytesIn(CacheBucket.LIKED)).coerceAtLeast(0L)
}
@@ -105,7 +106,10 @@ class BucketLedger<S : Any>(
* [pendingBytes] describe a write about to start, so room is made for it
* in its own bucket first. Recently played is trimmed before Liked.
*/
fun nextEviction(pendingKey: String? = null, pendingBytes: Long = 0L): S? {
fun nextEviction(
pendingKey: String? = null,
pendingBytes: Long = 0L,
): S? {
if (!armed) return null
val pendingBucket = pendingKey?.let(::bucketOf)
return listOf(CacheBucket.RECENT, CacheBucket.LIKED).firstNotNullOfOrNull { bucket ->
@@ -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 over = cap > 0L && bytesIn(bucket) + incoming > cap
return if (over) spans.getValue(bucket).firstOrNull() else null
@@ -23,7 +23,9 @@ import javax.inject.Singleton
* `MinstrelApplication`.
*/
@Singleton
class CacheBudgetSync @Inject constructor(
class CacheBudgetSync
@Inject
constructor(
likes: LikesRepository,
authStore: AuthStore,
evictor: TwoBucketCacheEvictor,
@@ -11,7 +11,11 @@ import javax.inject.Singleton
* Bytes held against each audio-cache budget, and how much more the Liked
* budget can take ([Long.MAX_VALUE] when it is unlimited).
*/
data class CacheUsage(val likedBytes: Long, val recentBytes: Long, val likedRoomBytes: Long)
data class CacheUsage(
val likedBytes: Long,
val recentBytes: Long,
val likedRoomBytes: Long,
)
/**
* The audio cache's eviction policy: two budgets, Liked songs and Recently
@@ -29,8 +33,11 @@ data class CacheUsage(val likedBytes: Long, val recentBytes: Long, val likedRoom
* deadlock.
*/
@Singleton
class TwoBucketCacheEvictor @Inject constructor() : CacheEvictor {
private val ledger = BucketLedger<CacheSpan>(
class TwoBucketCacheEvictor
@Inject
constructor() : CacheEvictor {
private val ledger =
BucketLedger<CacheSpan>(
keyOf = { it.key },
lengthOf = { it.length },
lruOrder = compareBy<CacheSpan> { it.lastTouchTimestamp }.then(naturalOrder()),
@@ -44,7 +51,11 @@ class TwoBucketCacheEvictor @Inject constructor() : CacheEvictor {
}
/** Apply a new liked set and caps, then trim whatever no longer fits. */
fun update(likedIds: Set<String>, likedCapBytes: Long, recentCapBytes: Long) {
fun update(
likedIds: Set<String>,
likedCapBytes: Long,
recentCapBytes: Long,
) {
val c = cache
val apply = {
ledger.likedCapBytes = likedCapBytes
@@ -63,7 +74,8 @@ class TwoBucketCacheEvictor @Inject constructor() : CacheEvictor {
}
}
fun usage(): CacheUsage = synchronized(ledger) {
fun usage(): CacheUsage =
synchronized(ledger) {
CacheUsage(
likedBytes = ledger.bytesIn(CacheBucket.LIKED),
recentBytes = ledger.bytesIn(CacheBucket.RECENT),
@@ -75,24 +87,39 @@ class TwoBucketCacheEvictor @Inject constructor() : CacheEvictor {
override fun onCacheInitialized() = Unit
override fun onStartFile(cache: Cache, key: String, position: Long, length: Long) {
override fun onStartFile(
cache: Cache,
key: String,
position: Long,
length: Long,
) {
synchronized(ledger) {
evict(cache, key, if (length == C.LENGTH_UNSET.toLong()) 0L else length)
}
}
override fun onSpanAdded(cache: Cache, span: CacheSpan) {
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) {
override fun onSpanRemoved(
cache: Cache,
span: CacheSpan,
) {
synchronized(ledger) { ledger.remove(span) }
}
override fun onSpanTouched(cache: Cache, oldSpan: CacheSpan, newSpan: CacheSpan) {
override fun onSpanTouched(
cache: Cache,
oldSpan: CacheSpan,
newSpan: CacheSpan,
) {
synchronized(ledger) {
ledger.remove(oldSpan)
ledger.add(newSpan)
@@ -100,7 +127,11 @@ class TwoBucketCacheEvictor @Inject constructor() : CacheEvictor {
}
}
private fun evict(cache: Cache, pendingKey: String?, pendingBytes: Long) {
private fun evict(
cache: Cache,
pendingKey: String?,
pendingBytes: Long,
) {
while (true) {
val span = ledger.nextEviction(pendingKey, pendingBytes) ?: return
cache.removeSpan(span)
@@ -15,9 +15,9 @@ import com.fabledsword.minstrel.cache.db.dao.CachedLikeDao
import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao
import com.fabledsword.minstrel.cache.db.dao.CachedNotificationDao
import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistDao
import com.fabledsword.minstrel.cache.db.dao.CachedResumeStateDao
import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistTrackDao
import com.fabledsword.minstrel.cache.db.dao.CachedQuarantineDao
import com.fabledsword.minstrel.cache.db.dao.CachedResumeStateDao
import com.fabledsword.minstrel.cache.db.dao.CachedTrackDao
import com.fabledsword.minstrel.cache.db.dao.DiagnosticEventDao
import com.fabledsword.minstrel.cache.db.dao.SyncMetadataDao
@@ -32,9 +32,9 @@ import com.fabledsword.minstrel.cache.db.entities.CachedMutationEntity
import com.fabledsword.minstrel.cache.db.entities.CachedNotificationEntity
import com.fabledsword.minstrel.cache.db.entities.CachedNotificationSettingsEntity
import com.fabledsword.minstrel.cache.db.entities.CachedPlaylistEntity
import com.fabledsword.minstrel.cache.db.entities.CachedResumeStateEntity
import com.fabledsword.minstrel.cache.db.entities.CachedPlaylistTrackEntity
import com.fabledsword.minstrel.cache.db.entities.CachedQuarantineEntity
import com.fabledsword.minstrel.cache.db.entities.CachedResumeStateEntity
import com.fabledsword.minstrel.cache.db.entities.CachedTrackEntity
import com.fabledsword.minstrel.cache.db.entities.DiagnosticEventEntity
import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity
@@ -101,25 +101,41 @@ import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity
@TypeConverters(MinstrelTypeConverters::class)
abstract class AppDatabase : RoomDatabase() {
abstract fun syncMetadataDao(): SyncMetadataDao
abstract fun cachedArtistDao(): CachedArtistDao
abstract fun cachedAlbumDao(): CachedAlbumDao
abstract fun cachedTrackDao(): CachedTrackDao
abstract fun cachedLikeDao(): CachedLikeDao
abstract fun cachedPlaylistDao(): CachedPlaylistDao
abstract fun cachedPlaylistTrackDao(): CachedPlaylistTrackDao
abstract fun cachedQuarantineDao(): CachedQuarantineDao
abstract fun audioCacheIndexDao(): AudioCacheIndexDao
abstract fun cachedMutationDao(): CachedMutationDao
abstract fun cachedResumeStateDao(): CachedResumeStateDao
abstract fun cachedHomeIndexDao(): CachedHomeIndexDao
abstract fun cachedHistorySnapshotDao(): CachedHistorySnapshotDao
abstract fun authSessionDao(): AuthSessionDao
abstract fun diagnosticEventDao(): DiagnosticEventDao
abstract fun cachedNotificationDao(): CachedNotificationDao
}
/** v8 → v9: add the nullable normalization preference column. */
val MIGRATION_8_9: Migration = object : Migration(8, 9) {
val MIGRATION_8_9: Migration =
object : Migration(8, 9) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE auth_session ADD COLUMN normalizationJson TEXT")
}
@@ -130,7 +146,8 @@ val MIGRATION_8_9: Migration = object : Migration(8, 9) {
* and the sync is incremental, so it would never re-send them: the cursor goes
* back to 0 and the next sync is a full one, upserting every row in place.
*/
val MIGRATION_9_10: Migration = object : Migration(9, 10) {
val MIGRATION_9_10: Migration =
object : Migration(9, 10) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE cached_tracks ADD COLUMN trackGain REAL")
db.execSQL("ALTER TABLE cached_tracks ADD COLUMN trackPeak REAL")
@@ -144,7 +161,8 @@ val MIGRATION_9_10: Migration = object : Migration(9, 10) {
* v10 → v11: the notifications inbox cache and its settings. The SQL
* matches what Room generates for the two entities; Room checks it on open.
*/
val MIGRATION_10_11: Migration = object : Migration(10, 11) {
val MIGRATION_10_11: Migration =
object : Migration(10, 11) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL(
"CREATE TABLE IF NOT EXISTS `cached_notifications` (" +
@@ -164,7 +182,8 @@ val MIGRATION_10_11: Migration = object : Migration(10, 11) {
* as the entity's column default says; the high-water mark starts empty, so
* the first catch-up sets it without announcing anything.
*/
val MIGRATION_11_12: Migration = object : Migration(11, 12) {
val MIGRATION_11_12: Migration =
object : Migration(11, 12) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE auth_session ADD COLUMN backgroundDelivery INTEGER NOT NULL DEFAULT 1")
db.execSQL("ALTER TABLE auth_session ADD COLUMN notifiedUpTo INTEGER")
@@ -175,7 +194,8 @@ val MIGRATION_11_12: Migration = object : Migration(11, 12) {
* v12 → v13: a playlist's cover albums and creation time. Both start empty;
* Home refreshes the playlist list on open, which fills them.
*/
val MIGRATION_12_13: Migration = object : Migration(12, 13) {
val MIGRATION_12_13: Migration =
object : Migration(12, 13) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE cached_playlists ADD COLUMN coverAlbumIds TEXT NOT NULL DEFAULT ''")
db.execSQL("ALTER TABLE cached_playlists ADD COLUMN createdAt TEXT NOT NULL DEFAULT ''")
@@ -186,7 +206,8 @@ val MIGRATION_12_13: Migration = object : Migration(12, 13) {
* v13 → v14: a playlist's place on its Home shelf. Starts at 0 (unranked);
* Home refreshes the playlist list on open, which fills it.
*/
val MIGRATION_13_14: Migration = object : Migration(13, 14) {
val MIGRATION_13_14: Migration =
object : Migration(13, 14) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE cached_playlists ADD COLUMN shelfRank INTEGER NOT NULL DEFAULT 0")
}
@@ -197,7 +218,8 @@ val MIGRATION_13_14: Migration = object : Migration(13, 14) {
* AccountCache adopts whoever is signed in without clearing anything, so
* an update keeps the signed-in person's queued writes and cache.
*/
val MIGRATION_14_15: Migration = object : Migration(14, 15) {
val MIGRATION_14_15: Migration =
object : Migration(14, 15) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE auth_session ADD COLUMN cacheOwnerUserId TEXT")
}
@@ -11,12 +11,12 @@ import com.fabledsword.minstrel.cache.db.dao.CachedHomeIndexDao
import com.fabledsword.minstrel.cache.db.dao.CachedLikeDao
import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao
import com.fabledsword.minstrel.cache.db.dao.CachedNotificationDao
import com.fabledsword.minstrel.cache.db.dao.DiagnosticEventDao
import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistDao
import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistTrackDao
import com.fabledsword.minstrel.cache.db.dao.CachedQuarantineDao
import com.fabledsword.minstrel.cache.db.dao.CachedResumeStateDao
import com.fabledsword.minstrel.cache.db.dao.CachedTrackDao
import com.fabledsword.minstrel.cache.db.dao.DiagnosticEventDao
import com.fabledsword.minstrel.cache.db.dao.SyncMetadataDao
import dagger.Module
import dagger.Provides
@@ -31,8 +31,11 @@ import javax.inject.Singleton
object DatabaseModule {
@Provides
@Singleton
fun provideDatabase(@ApplicationContext context: Context): AppDatabase =
Room.databaseBuilder(context, AppDatabase::class.java, DATABASE_NAME)
fun provideDatabase(
@ApplicationContext context: Context,
): AppDatabase =
Room
.databaseBuilder(context, AppDatabase::class.java, DATABASE_NAME)
// Explicit migrations from v8 onward; an older schema has no path
// and rebuilds. The sync controller refills the cache from the
// server on first launch, so a rebuild loses only the unsynced
@@ -45,8 +48,7 @@ object DatabaseModule {
MIGRATION_12_13,
MIGRATION_13_14,
MIGRATION_14_15,
)
.fallbackToDestructiveMigration(dropAllTables = true)
).fallbackToDestructiveMigration(dropAllTables = true)
.build()
// DAO @Provides — Hilt can't inject AppDatabase abstract accessors
@@ -69,33 +71,27 @@ object DatabaseModule {
@Provides
@Singleton
fun provideCachedResumeStateDao(db: AppDatabase): CachedResumeStateDao =
db.cachedResumeStateDao()
fun provideCachedResumeStateDao(db: AppDatabase): CachedResumeStateDao = db.cachedResumeStateDao()
@Provides
@Singleton
fun provideCachedHomeIndexDao(db: AppDatabase): CachedHomeIndexDao =
db.cachedHomeIndexDao()
fun provideCachedHomeIndexDao(db: AppDatabase): CachedHomeIndexDao = db.cachedHomeIndexDao()
@Provides
@Singleton
fun provideCachedHistorySnapshotDao(db: AppDatabase): CachedHistorySnapshotDao =
db.cachedHistorySnapshotDao()
fun provideCachedHistorySnapshotDao(db: AppDatabase): CachedHistorySnapshotDao = db.cachedHistorySnapshotDao()
@Provides
@Singleton
fun provideCachedQuarantineDao(db: AppDatabase): CachedQuarantineDao =
db.cachedQuarantineDao()
fun provideCachedQuarantineDao(db: AppDatabase): CachedQuarantineDao = db.cachedQuarantineDao()
@Provides
@Singleton
fun provideCachedPlaylistDao(db: AppDatabase): CachedPlaylistDao =
db.cachedPlaylistDao()
fun provideCachedPlaylistDao(db: AppDatabase): CachedPlaylistDao = db.cachedPlaylistDao()
@Provides
@Singleton
fun provideCachedPlaylistTrackDao(db: AppDatabase): CachedPlaylistTrackDao =
db.cachedPlaylistTrackDao()
fun provideCachedPlaylistTrackDao(db: AppDatabase): CachedPlaylistTrackDao = db.cachedPlaylistTrackDao()
@Provides
@Singleton
@@ -103,8 +99,7 @@ object DatabaseModule {
@Provides
@Singleton
fun provideCachedMutationDao(db: AppDatabase): CachedMutationDao =
db.cachedMutationDao()
fun provideCachedMutationDao(db: AppDatabase): CachedMutationDao = db.cachedMutationDao()
@Provides
@Singleton
@@ -112,18 +107,15 @@ object DatabaseModule {
@Provides
@Singleton
fun provideAudioCacheIndexDao(db: AppDatabase): AudioCacheIndexDao =
db.audioCacheIndexDao()
fun provideAudioCacheIndexDao(db: AppDatabase): AudioCacheIndexDao = db.audioCacheIndexDao()
@Provides
@Singleton
fun provideDiagnosticEventDao(db: AppDatabase): DiagnosticEventDao =
db.diagnosticEventDao()
fun provideDiagnosticEventDao(db: AppDatabase): DiagnosticEventDao = db.diagnosticEventDao()
@Provides
@Singleton
fun provideCachedNotificationDao(db: AppDatabase): CachedNotificationDao =
db.cachedNotificationDao()
fun provideCachedNotificationDao(db: AppDatabase): CachedNotificationDao = db.cachedNotificationDao()
private const val DATABASE_NAME = "minstrel.db"
}
@@ -21,11 +21,9 @@ enum class CacheSource { MANUAL, AUTO_LIKED, AUTO_PLAYLIST, AUTO_PREFETCH, INCID
class MinstrelTypeConverters {
@TypeConverter fun instantToLong(i: Instant?): Long? = i?.toEpochMilliseconds()
@TypeConverter fun longToInstant(l: Long?): Instant? =
l?.let { Instant.fromEpochMilliseconds(it) }
@TypeConverter fun longToInstant(l: Long?): Instant? = l?.let { Instant.fromEpochMilliseconds(it) }
@TypeConverter fun sourceToName(s: CacheSource?): String? = s?.name
@TypeConverter fun nameToSource(n: String?): CacheSource? =
n?.let { CacheSource.valueOf(it) }
@TypeConverter fun nameToSource(n: String?): CacheSource? = n?.let { CacheSource.valueOf(it) }
}
@@ -37,7 +37,10 @@ interface AudioCacheIndexDao {
@Query(
"UPDATE audio_cache_index SET lastPlayedAt = :at WHERE trackId = :trackId",
)
suspend fun touchLastPlayed(trackId: String, at: kotlinx.datetime.Instant)
suspend fun touchLastPlayed(
trackId: String,
at: kotlinx.datetime.Instant,
)
@Query("DELETE FROM audio_cache_index WHERE trackId = :trackId")
suspend fun deleteByTrackId(trackId: String)
@@ -30,10 +30,16 @@ interface CachedAlbumDao {
"ORDER BY sortTitle COLLATE NOCASE ASC " +
"LIMIT :limit",
)
suspend fun searchByTitle(q: String, limit: Int): List<CachedAlbumEntity>
suspend fun searchByTitle(
q: String,
limit: Int,
): List<CachedAlbumEntity>
@Query("SELECT id FROM cached_albums WHERE fetchedAt < :before LIMIT :limit")
suspend fun idsStaleBefore(before: Long, limit: Int): List<String>
suspend fun idsStaleBefore(
before: Long,
limit: Int,
): List<String>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertAll(rows: List<CachedAlbumEntity>)
@@ -24,10 +24,16 @@ interface CachedArtistDao {
"ORDER BY sortName COLLATE NOCASE ASC " +
"LIMIT :limit",
)
suspend fun searchByName(q: String, limit: Int): List<CachedArtistEntity>
suspend fun searchByName(
q: String,
limit: Int,
): List<CachedArtistEntity>
@Query("SELECT id FROM cached_artists WHERE fetchedAt < :before LIMIT :limit")
suspend fun idsStaleBefore(before: Long, limit: Int): List<String>
suspend fun idsStaleBefore(
before: Long,
limit: Int,
): List<String>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertAll(rows: List<CachedArtistEntity>)
@@ -44,7 +44,10 @@ interface CachedHomeIndexDao {
* sequence rather than as a single content swap.
*/
@Transaction
suspend fun replaceSections(sections: List<String>, rows: List<CachedHomeIndexEntity>) {
suspend fun replaceSections(
sections: List<String>,
rows: List<CachedHomeIndexEntity>,
) {
deleteSections(sections)
if (rows.isNotEmpty()) upsertAll(rows)
}
@@ -25,13 +25,20 @@ interface CachedLikeDao {
"SELECT entityId FROM cached_likes " +
"WHERE userId = :userId AND entityType = :entityType",
)
fun observeLikedIdsOfType(userId: String, entityType: String): Flow<List<String>>
fun observeLikedIdsOfType(
userId: String,
entityType: String,
): Flow<List<String>>
@Query(
"SELECT EXISTS(SELECT 1 FROM cached_likes " +
"WHERE userId = :userId AND entityType = :entityType AND entityId = :entityId)",
)
fun observeIsLiked(userId: String, entityType: String, entityId: String): Flow<Boolean>
fun observeIsLiked(
userId: String,
entityType: String,
entityId: String,
): Flow<Boolean>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertAll(rows: List<CachedLikeEntity>)
@@ -40,7 +47,11 @@ interface CachedLikeDao {
"DELETE FROM cached_likes " +
"WHERE userId = :userId AND entityType = :entityType AND entityId = :entityId",
)
suspend fun delete(userId: String, entityType: String, entityId: String)
suspend fun delete(
userId: String,
entityType: String,
entityId: String,
)
@Query("DELETE FROM cached_likes WHERE userId = :userId")
suspend fun clearForUser(userId: String)
@@ -53,7 +64,10 @@ interface CachedLikeDao {
* stale Liked tab entry forever.
*/
@Transaction
suspend fun replaceAllForUser(userId: String, rows: List<CachedLikeEntity>) {
suspend fun replaceAllForUser(
userId: String,
rows: List<CachedLikeEntity>,
) {
clearForUser(userId)
upsertAll(rows)
}
@@ -24,7 +24,10 @@ interface CachedMutationDao {
"UPDATE cached_mutations SET attempts = attempts + 1, lastAttemptAt = :at " +
"WHERE id = :id",
)
suspend fun recordAttempt(id: Long, at: Instant)
suspend fun recordAttempt(
id: Long,
at: Instant,
)
@Query("DELETE FROM cached_mutations WHERE id = :id")
suspend fun delete(id: Long)
@@ -35,7 +35,10 @@ interface CachedNotificationDao {
}
@Query("UPDATE cached_notifications SET readAt = :at WHERE id = :id AND readAt IS NULL")
suspend fun markRead(id: String, at: Instant)
suspend fun markRead(
id: String,
at: Instant,
)
@Query("UPDATE cached_notifications SET readAt = :at WHERE readAt IS NULL")
suspend fun markAllRead(at: Instant)
@@ -55,7 +55,10 @@ interface CachedPlaylistDao {
suspend fun deleteAllOwned(userId: String)
@Query("DELETE FROM cached_playlists WHERE userId = :userId AND id NOT IN (:keepIds)")
suspend fun deleteOwnedNotIn(userId: String, keepIds: List<String>)
suspend fun deleteOwnedNotIn(
userId: String,
keepIds: List<String>,
)
/**
* Atomically reconciles the cache against the fresh list response.
@@ -67,5 +67,8 @@ interface CachedPlaylistTrackDao {
"DELETE FROM cached_playlist_tracks " +
"WHERE playlistId = :playlistId AND trackId IN (:trackIds)",
)
suspend fun deleteTracksFromPlaylist(playlistId: String, trackIds: List<String>)
suspend fun deleteTracksFromPlaylist(
playlistId: String,
trackIds: List<String>,
)
}
@@ -30,10 +30,16 @@ interface CachedTrackDao {
"ORDER BY title COLLATE NOCASE ASC " +
"LIMIT :limit",
)
suspend fun searchByTitle(q: String, limit: Int): List<CachedTrackEntity>
suspend fun searchByTitle(
q: String,
limit: Int,
): List<CachedTrackEntity>
@Query("SELECT id FROM cached_tracks WHERE fetchedAt < :before LIMIT :limit")
suspend fun idsStaleBefore(before: Long, limit: Int): List<String>
suspend fun idsStaleBefore(
before: Long,
limit: Int,
): List<String>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertAll(rows: List<CachedTrackEntity>)
@@ -87,7 +87,9 @@ data class LikeTogglePayload(
*/
@Suppress("TooManyFunctions") // one enqueue per mutation kind, like the replayer's dispatchers
@Singleton
class MutationQueue @Inject constructor(
class MutationQueue
@Inject
constructor(
private val dao: CachedMutationDao,
private val json: Json,
) {
@@ -95,7 +97,8 @@ class MutationQueue @Inject constructor(
// tracks while offline) surfaces as one snackbar rather than queueing
// N. replay=0 because a hint observed at enqueue time isn't useful
// to a screen that mounts later.
private val _userEnqueueHints = MutableSharedFlow<String>(
private val _userEnqueueHints =
MutableSharedFlow<String>(
replay = 0,
extraBufferCapacity = 1,
onBufferOverflow = BufferOverflow.DROP_OLDEST,
@@ -115,7 +118,8 @@ class MutationQueue @Inject constructor(
entityType: String,
entityId: String,
desiredState: Boolean,
): Long = insertUserDriven(
): Long =
insertUserDriven(
MutationKind.LIKE_TOGGLE,
json.encodeToString(
LikeTogglePayload.serializer(),
@@ -123,7 +127,8 @@ class MutationQueue @Inject constructor(
),
)
suspend fun enqueueQuarantineUnflag(trackId: String): Long = insertUserDriven(
suspend fun enqueueQuarantineUnflag(trackId: String): Long =
insertUserDriven(
MutationKind.QUARANTINE_UNFLAG,
json.encodeToString(
QuarantineUnflagPayload.serializer(),
@@ -131,32 +136,38 @@ class MutationQueue @Inject constructor(
),
)
suspend fun enqueuePlaylistAppend(payload: PlaylistAppendPayload): Long = insertUserDriven(
suspend fun enqueuePlaylistAppend(payload: PlaylistAppendPayload): Long =
insertUserDriven(
MutationKind.PLAYLIST_APPEND,
json.encodeToString(PlaylistAppendPayload.serializer(), payload),
)
suspend fun enqueuePlaylistCreate(payload: PlaylistCreatePayload): Long = insertUserDriven(
suspend fun enqueuePlaylistCreate(payload: PlaylistCreatePayload): Long =
insertUserDriven(
MutationKind.PLAYLIST_CREATE,
json.encodeToString(PlaylistCreatePayload.serializer(), payload),
)
suspend fun enqueuePlaylistUpdate(payload: PlaylistUpdatePayload): Long = insertUserDriven(
suspend fun enqueuePlaylistUpdate(payload: PlaylistUpdatePayload): Long =
insertUserDriven(
MutationKind.PLAYLIST_UPDATE,
json.encodeToString(PlaylistUpdatePayload.serializer(), payload),
)
suspend fun enqueuePlaylistDelete(playlistId: String): Long = insertUserDriven(
suspend fun enqueuePlaylistDelete(playlistId: String): Long =
insertUserDriven(
MutationKind.PLAYLIST_DELETE,
json.encodeToString(PlaylistDeletePayload.serializer(), PlaylistDeletePayload(playlistId)),
)
suspend fun enqueuePlaylistRemoveTrack(payload: PlaylistRemoveTrackPayload): Long = insertUserDriven(
suspend fun enqueuePlaylistRemoveTrack(payload: PlaylistRemoveTrackPayload): Long =
insertUserDriven(
MutationKind.PLAYLIST_REMOVE_TRACK,
json.encodeToString(PlaylistRemoveTrackPayload.serializer(), payload),
)
suspend fun enqueuePlaylistReorder(payload: PlaylistReorderPayload): Long = insertUserDriven(
suspend fun enqueuePlaylistReorder(payload: PlaylistReorderPayload): Long =
insertUserDriven(
MutationKind.PLAYLIST_REORDER,
json.encodeToString(PlaylistReorderPayload.serializer(), payload),
)
@@ -166,14 +177,16 @@ class MutationQueue @Inject constructor(
* sent yet. A list refresh keeps them, so a playlist made offline
* doesn't vanish before its create goes out.
*/
suspend fun pendingPlaylistCreateIds(): Set<String> = dao.getAll()
suspend fun pendingPlaylistCreateIds(): Set<String> =
dao
.getAll()
.asSequence()
.filter { it.kind == MutationKind.PLAYLIST_CREATE }
.mapNotNull { row ->
runCatching { json.decodeFromString(PlaylistCreatePayload.serializer(), row.payload) }
.getOrNull()?.id
}
.toSet()
.getOrNull()
?.id
}.toSet()
/**
* The like state each still-queued like toggle sets, by
@@ -182,7 +195,8 @@ class MutationQueue @Inject constructor(
* one replays after it and undoes it; and a refresh keeps these states
* over the server's, which hasn't seen them yet.
*/
suspend fun pendingLikeStates(): Map<String, Boolean> = buildMap {
suspend fun pendingLikeStates(): Map<String, Boolean> =
buildMap {
dao.getAll().filter { it.kind == MutationKind.LIKE_TOGGLE }.forEach { row ->
runCatching { json.decodeFromString(LikeTogglePayload.serializer(), row.payload) }
.getOrNull()
@@ -195,13 +209,16 @@ class MutationQueue @Inject constructor(
* up flagged (true) or not, the newest winning. Read for the same two
* reasons as [pendingLikeStates].
*/
suspend fun pendingQuarantineStates(): Map<String, Boolean> = buildMap {
suspend fun pendingQuarantineStates(): Map<String, Boolean> =
buildMap {
dao.getAll().forEach { row ->
when (row.kind) {
MutationKind.QUARANTINE_FLAG -> runCatching {
MutationKind.QUARANTINE_FLAG ->
runCatching {
json.decodeFromString(QuarantineFlagPayload.serializer(), row.payload)
}.getOrNull()?.let { put(it.trackId, true) }
MutationKind.QUARANTINE_UNFLAG -> runCatching {
MutationKind.QUARANTINE_UNFLAG ->
runCatching {
json.decodeFromString(QuarantineUnflagPayload.serializer(), row.payload)
}.getOrNull()?.let { put(it.trackId, false) }
}
@@ -212,7 +229,8 @@ class MutationQueue @Inject constructor(
trackId: String,
reason: String,
notes: String,
): Long = insertUserDriven(
): Long =
insertUserDriven(
MutationKind.QUARANTINE_FLAG,
json.encodeToString(
QuarantineFlagPayload.serializer(),
@@ -221,17 +239,20 @@ class MutationQueue @Inject constructor(
)
/** Queues the user's whole normalization preference for replay. */
suspend fun enqueueNormalizationSet(prefs: NormalizationPrefs): Long = insertUserDriven(
suspend fun enqueueNormalizationSet(prefs: NormalizationPrefs): Long =
insertUserDriven(
MutationKind.NORMALIZATION_SET,
json.encodeToString(NormalizationPrefs.serializer(), prefs),
)
suspend fun enqueueNotificationRead(id: String): Long = insertUserDriven(
suspend fun enqueueNotificationRead(id: String): Long =
insertUserDriven(
MutationKind.NOTIFICATION_READ,
json.encodeToString(NotificationReadPayload.serializer(), NotificationReadPayload(id)),
)
suspend fun enqueueNotificationsReadAll(upToIso: String?): Long = insertUserDriven(
suspend fun enqueueNotificationsReadAll(upToIso: String?): Long =
insertUserDriven(
MutationKind.NOTIFICATIONS_READ_ALL,
json.encodeToString(
NotificationsReadAllPayload.serializer(),
@@ -245,14 +266,16 @@ class MutationQueue @Inject constructor(
json.encodeToString(NotificationSettingPayload.serializer(), payload),
)
suspend fun enqueuePlayOffline(payload: PlayOfflinePayload): Long = dao.insert(
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(
suspend fun enqueuePlaybackErrorReport(payload: PlaybackErrorReportPayload): Long =
dao.insert(
CachedMutationEntity(
kind = MutationKind.PLAYBACK_ERROR_REPORT,
payload = json.encodeToString(PlaybackErrorReportPayload.serializer(), payload),
@@ -263,14 +286,18 @@ class MutationQueue @Inject constructor(
* 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(
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 {
private suspend fun insertUserDriven(
kind: String,
payload: String,
): Long {
val id = dao.insert(CachedMutationEntity(kind = kind, payload = payload))
_userEnqueueHints.tryEmit(QUEUED_MESSAGE)
return id
@@ -283,10 +310,15 @@ class MutationQueue @Inject constructor(
* hiccup. The replayer just re-fires the DELETE; idempotent server-side.
*/
@Serializable
data class QuarantineUnflagPayload(val trackId: String)
data class QuarantineUnflagPayload(
val trackId: String,
)
/** The key [MutationQueue.pendingLikeStates] files a like toggle under. */
fun likeToggleKey(entityType: String, entityId: String): String = "$entityType:$entityId"
fun likeToggleKey(
entityType: String,
entityId: String,
): String = "$entityType:$entityId"
/**
* Persisted payload for `MutationKind.PLAYLIST_APPEND`: the track IDs to
@@ -320,7 +352,9 @@ data class PlaylistUpdatePayload(
/** Persisted payload for `MutationKind.PLAYLIST_DELETE`. */
@Serializable
data class PlaylistDeletePayload(val playlistId: String)
data class PlaylistDeletePayload(
val playlistId: String,
)
/**
* Persisted payload for `MutationKind.PLAYLIST_REMOVE_TRACK`. [trackId] is
@@ -405,7 +439,9 @@ data class PlaybackErrorReportPayload(
/** Persisted payload for `MutationKind.NOTIFICATION_READ`. */
@Serializable
data class NotificationReadPayload(val id: String)
data class NotificationReadPayload(
val id: String,
)
/**
* Persisted payload for `MutationKind.NOTIFICATIONS_READ_ALL`.
@@ -413,7 +449,9 @@ data class NotificationReadPayload(val id: String)
* when the inbox was empty on the device, which marks everything.
*/
@Serializable
data class NotificationsReadAllPayload(val upToIso: String?)
data class NotificationsReadAllPayload(
val upToIso: String?,
)
/**
* Persisted payload for `MutationKind.NOTIFICATION_SETTING_SET`: one
@@ -9,24 +9,24 @@ import com.fabledsword.minstrel.api.endpoints.FlagRequest
import com.fabledsword.minstrel.api.endpoints.LikesApi
import com.fabledsword.minstrel.api.endpoints.MeApi
import com.fabledsword.minstrel.api.endpoints.NotificationsApi
import com.fabledsword.minstrel.api.endpoints.PutNotificationSettingsBody
import com.fabledsword.minstrel.api.endpoints.ReadAllBody
import com.fabledsword.minstrel.api.endpoints.PlaybackErrorReportRequest
import com.fabledsword.minstrel.api.endpoints.PlaybackErrorsApi
import com.fabledsword.minstrel.api.endpoints.PlaylistsApi
import com.fabledsword.minstrel.api.endpoints.PutNotificationSettingsBody
import com.fabledsword.minstrel.api.endpoints.QuarantineApi
import com.fabledsword.minstrel.api.endpoints.ReadAllBody
import com.fabledsword.minstrel.api.endpoints.ReorderTracksRequest
import com.fabledsword.minstrel.api.endpoints.UpdatePlaylistRequest
import com.fabledsword.minstrel.connectivity.NetworkStatusController
import com.fabledsword.minstrel.connectivity.ServerHealth
import com.fabledsword.minstrel.models.wire.PlayEndedRequest
import com.fabledsword.minstrel.models.wire.PlayOfflineRequest
import com.fabledsword.minstrel.auth.AuthStore
import com.fabledsword.minstrel.cache.account.AccountCache
import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao
import com.fabledsword.minstrel.cache.db.entities.CachedMutationEntity
import com.fabledsword.minstrel.connectivity.NetworkStatusController
import com.fabledsword.minstrel.connectivity.ServerHealth
import com.fabledsword.minstrel.di.ApplicationScope
import com.fabledsword.minstrel.likes.data.LikesRepository
import com.fabledsword.minstrel.models.wire.PlayEndedRequest
import com.fabledsword.minstrel.models.wire.PlayOfflineRequest
import com.fabledsword.minstrel.settings.data.NormalizationPrefs
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.distinctUntilChanged
@@ -35,7 +35,6 @@ import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.datetime.Clock
import kotlinx.serialization.SerializationException
import kotlinx.serialization.json.Json
@@ -75,7 +74,9 @@ import javax.inject.Singleton
* forever.
*/
@Singleton
class MutationReplayer @Inject constructor(
class MutationReplayer
@Inject
constructor(
private val dao: CachedMutationDao,
private val authStore: AuthStore,
private val accountCache: AccountCache,
@@ -154,12 +155,17 @@ class MutationReplayer @Inject constructor(
* leaves it queued when an earlier change to the same playlist is still
* waiting. A row that has to retry makes its playlist wait in [waiting].
*/
private suspend fun replayRow(row: CachedMutationEntity, superseded: Boolean, waiting: MutableSet<String>) {
private suspend fun replayRow(
row: CachedMutationEntity,
superseded: Boolean,
waiting: MutableSet<String>,
) {
val playlistId = playlistIdOf(row, json)
when {
superseded -> dao.delete(row.id)
playlistId != null && playlistId in waiting -> Unit
else -> when (outcomeFor(row)) {
else ->
when (outcomeFor(row)) {
Outcome.SENT, Outcome.DROP -> dao.delete(row.id)
Outcome.RETRY -> {
dao.recordAttempt(row.id, Clock.System.now())
@@ -169,14 +175,19 @@ class MutationReplayer @Inject constructor(
}
}
private suspend fun outcomeFor(row: CachedMutationEntity): Outcome = try {
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) {
} catch (
@Suppress("SwallowedException") e: SerializationException,
) {
// Corrupt / schema-incompatible payload — permanent, drop it.
Outcome.DROP
} catch (@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable) {
} catch (
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
) {
// Transport / unknown — leave queued for the next pass.
Outcome.RETRY
}
@@ -189,7 +200,8 @@ class MutationReplayer @Inject constructor(
* 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) {
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,
@@ -213,7 +225,8 @@ class MutationReplayer @Inject constructor(
}
/** The notifications inbox's kinds, split out to keep [dispatch] simple. */
private suspend fun dispatchNotification(row: CachedMutationEntity): Outcome = when (row.kind) {
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)
@@ -222,7 +235,8 @@ class MutationReplayer @Inject constructor(
private suspend fun dispatchLikeToggle(payload: String): Outcome {
val decoded = json.decodeFromString(LikeTogglePayload.serializer(), payload)
val kindPath = when (decoded.entityType) {
val kindPath =
when (decoded.entityType) {
LikesRepository.ENTITY_ARTIST -> "artists"
LikesRepository.ENTITY_ALBUM -> "albums"
LikesRepository.ENTITY_TRACK -> "tracks"
@@ -376,10 +390,14 @@ class MutationReplayer @Inject constructor(
* instance. [rows] must be ascending by id (FIFO), which is what
* `CachedMutationDao.getAll()` returns.
*/
internal fun supersededToggleIds(rows: List<CachedMutationEntity>, json: Json): Set<Long> {
internal fun supersededToggleIds(
rows: List<CachedMutationEntity>,
json: Json,
): Set<Long> {
val latestByEntity = HashMap<String, Long>()
val superseded = HashSet<Long>()
rows.asSequence()
rows
.asSequence()
.mapNotNull { row -> toggleKeyOf(row, json)?.let { key -> key to row.id } }
.forEach { (key, id) ->
// Ascending ids mean a prior entry for this key is always older.
@@ -397,22 +415,30 @@ internal fun supersededToggleIds(rows: List<CachedMutationEntity>, json: Json):
* The kind is part of the key so two toggle kinds can never collide on the
* same entity id.
*/
private fun toggleKeyOf(row: CachedMutationEntity, json: Json): String? = when (row.kind) {
MutationKind.LIKE_TOGGLE -> runCatching {
private fun toggleKeyOf(
row: CachedMutationEntity,
json: Json,
): String? =
when (row.kind) {
MutationKind.LIKE_TOGGLE ->
runCatching {
json.decodeFromString(LikeTogglePayload.serializer(), row.payload)
}.getOrNull()?.let { "${row.kind}:${it.entityType}:${it.entityId}" }
MutationKind.NOTIFICATION_SETTING_SET -> runCatching {
MutationKind.NOTIFICATION_SETTING_SET ->
runCatching {
json.decodeFromString(NotificationSettingPayload.serializer(), row.payload)
}.getOrNull()?.let { "${row.kind}:${it.kind}:${it.channel}" }
// A reorder is the list's whole new order, so only the last one counts.
MutationKind.PLAYLIST_REORDER -> runCatching {
MutationKind.PLAYLIST_REORDER ->
runCatching {
json.decodeFromString(PlaylistReorderPayload.serializer(), row.payload)
}.getOrNull()?.let { "${row.kind}:${it.playlistId}" }
// One preference per user, so every normalization row shares one key.
MutationKind.NORMALIZATION_SET -> runCatching {
MutationKind.NORMALIZATION_SET ->
runCatching {
json.decodeFromString(NormalizationPrefs.serializer(), row.payload)
}.getOrNull()?.let { row.kind }
@@ -423,7 +449,11 @@ private fun toggleKeyOf(row: CachedMutationEntity, json: Json): String? = when (
* The playlist a queued row changes, or null for a row that isn't a
* playlist change (or won't decode, which its dispatcher then DROPs).
*/
internal fun playlistIdOf(row: CachedMutationEntity, json: Json): String? = runCatching {
internal fun playlistIdOf(
row: CachedMutationEntity,
json: Json,
): String? =
runCatching {
when (row.kind) {
MutationKind.PLAYLIST_APPEND ->
json.decodeFromString(PlaylistAppendPayload.serializer(), row.payload).playlistId
@@ -13,7 +13,9 @@ import javax.inject.Inject
* accessor. Mirrors PlaybackErrorViewModel.
*/
@HiltViewModel
class OfflineWriteHintViewModel @Inject constructor(
class OfflineWriteHintViewModel
@Inject
constructor(
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.endpoints.SyncApi
import com.fabledsword.minstrel.auth.AuthStore
import com.fabledsword.minstrel.connectivity.NetworkStatusController
import com.fabledsword.minstrel.connectivity.ServerHealth
import com.fabledsword.minstrel.cache.db.dao.CachedAlbumDao
import com.fabledsword.minstrel.cache.db.dao.CachedArtistDao
import com.fabledsword.minstrel.cache.db.dao.CachedTrackDao
@@ -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.CachedTrackEntity
import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity
import com.fabledsword.minstrel.connectivity.NetworkStatusController
import com.fabledsword.minstrel.connectivity.ServerHealth
import com.fabledsword.minstrel.di.ApplicationScope
import com.fabledsword.minstrel.models.wire.SyncAlbumWire
import com.fabledsword.minstrel.models.wire.SyncArtistWire
@@ -50,7 +50,9 @@ import javax.inject.Singleton
* cursor to 0 and pulls the full entity set again (see [resetCursor]).
*/
@Singleton
class SyncController @Inject constructor(
class SyncController
@Inject
constructor(
private val syncMetadataDao: SyncMetadataDao,
private val artistDao: CachedArtistDao,
private val albumDao: CachedAlbumDao,
@@ -210,7 +212,8 @@ class SyncController @Inject constructor(
// ── Mappers (file-internal — sync wire types stay out of UI) ──
private fun SyncArtistWire.toEntity(): CachedArtistEntity = CachedArtistEntity(
private fun SyncArtistWire.toEntity(): CachedArtistEntity =
CachedArtistEntity(
id = id,
name = name,
sortName = sortName,
@@ -219,7 +222,8 @@ private fun SyncArtistWire.toEntity(): CachedArtistEntity = CachedArtistEntity(
artistFanartPath = artistFanartPath,
)
private fun SyncAlbumWire.toEntity(): CachedAlbumEntity = CachedAlbumEntity(
private fun SyncAlbumWire.toEntity(): CachedAlbumEntity =
CachedAlbumEntity(
id = id,
artistId = artistId,
title = title,
@@ -231,7 +235,8 @@ private fun SyncAlbumWire.toEntity(): CachedAlbumEntity = CachedAlbumEntity(
albumPeak = albumPeak,
)
private fun SyncTrackWire.toEntity(): CachedTrackEntity = CachedTrackEntity(
private fun SyncTrackWire.toEntity(): CachedTrackEntity =
CachedTrackEntity(
id = id,
albumId = albumId,
artistId = artistId,
@@ -36,22 +36,30 @@ import javax.inject.Singleton
* repositories can also collect this to gate retry loops.
*/
@Singleton
class ConnectivityObserver @Inject constructor(
class ConnectivityObserver
@Inject
constructor(
@ApplicationContext context: Context,
) {
private val cm = context.getSystemService(ConnectivityManager::class.java)
val online: Flow<Boolean> = callbackFlow {
val request = NetworkRequest.Builder()
val online: Flow<Boolean> =
callbackFlow {
val request =
NetworkRequest
.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.build()
val callback = object : ConnectivityManager.NetworkCallback() {
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,
@@ -80,14 +88,17 @@ class ConnectivityObserver @Inject constructor(
* Downloads the user did not start (the liked-song downloads) wait for
* this.
*/
val unmetered: Flow<Boolean> = callbackFlow {
val callback = object : ConnectivityManager.NetworkCallback() {
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)
}
@@ -55,7 +55,9 @@ private const val ARBITRATE_MIN_GAP_MS = 2_000L
* [com.fabledsword.minstrel.MinstrelApplication].
*/
@Singleton
class NetworkStatusController @Inject constructor(
class NetworkStatusController
@Inject
constructor(
@ApplicationScope private val scope: CoroutineScope,
connectivity: ConnectivityObserver,
private val authStore: AuthStore,
@@ -72,9 +74,16 @@ class NetworkStatusController @Inject constructor(
val versionResult: StateFlow<VersionResult> = versionInternal.asStateFlow()
private sealed interface Intent {
data class Link(val up: Boolean) : Intent
data class Probe(val resp: HealthzResponse?) : Intent
data class Link(
val up: Boolean,
) : Intent
data class Probe(
val resp: HealthzResponse?,
) : Intent
object OpSuccess : Intent
object OpFailure : Intent
}
@@ -141,7 +150,10 @@ class NetworkStatusController @Inject constructor(
}
}
private fun applyProbe(resp: HealthzResponse?, now: Long) {
private fun applyProbe(
resp: HealthzResponse?,
now: Long,
) {
if (resp == null) {
machine.onProbeFailure(now)
} else {
@@ -161,8 +173,11 @@ class NetworkStatusController @Inject constructor(
probeOnce()
while (true) {
val interval =
if (stateInternal.value == ServerHealth.Healthy) POLL_HEALTHY_MS
else POLL_DEGRADED_MS
if (stateInternal.value == ServerHealth.Healthy) {
POLL_HEALTHY_MS
} else {
POLL_DEGRADED_MS
}
delay(interval)
probeOnce()
}
@@ -41,7 +41,6 @@ internal const val CORROBORATION_MIN_SPACING_MS = 3_000L
* sustained-time backstop.
*/
class ReachabilityMachine {
private enum class Reachability { Reachable, Unstable, Unreachable }
private var linkUp = true
@@ -89,7 +88,8 @@ class ReachabilityMachine {
}
}
fun health(): ServerHealth = when {
fun health(): ServerHealth =
when {
!linkUp -> ServerHealth.Offline
reachability == Reachability.Reachable -> ServerHealth.Healthy
reachability == Reachability.Unstable -> ServerHealth.Unstable
@@ -29,7 +29,9 @@ private const val HEALTHZ_PATH = "/healthz"
* already constructed (construct-the-singleton trick in MinstrelApplication).
*/
@Singleton
class ReachabilityReportingInterceptor @Inject constructor(
class ReachabilityReportingInterceptor
@Inject
constructor(
private val networkStatus: Lazy<NetworkStatusController>,
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
@@ -19,7 +19,8 @@ import kotlinx.coroutines.flow.map
* heals itself the moment connectivity returns instead of sitting in the
* failed state until a manual pull-to-refresh.
*/
fun NetworkStatusController.recoveries(): Flow<Unit> = state
fun NetworkStatusController.recoveries(): Flow<Unit> =
state
.map { it == ServerHealth.Healthy }
.distinctUntilChanged()
.drop(1)
@@ -43,7 +43,9 @@ private const val BACK_ONLINE_FLASH_MS = 2_000L
* re-wrapping StateFlow — the controller's is already app-scoped and warm.
*/
@HiltViewModel
class ConnectivityBannerViewModel @Inject constructor(
class ConnectivityBannerViewModel
@Inject
constructor(
networkStatus: NetworkStatusController,
@Suppress("UnusedPrivateProperty") savedStateHandle: SavedStateHandle,
) : ViewModel() {
@@ -57,9 +59,7 @@ class ConnectivityBannerViewModel @Inject constructor(
* recovery is unmistakable. Sentence case, understated voice (design system).
*/
@Composable
fun ConnectionErrorBanner(
viewModel: ConnectivityBannerViewModel = hiltViewModel(),
) {
fun ConnectionErrorBanner(viewModel: ConnectivityBannerViewModel = hiltViewModel()) {
val health by viewModel.health.collectAsStateWithLifecycle()
var showBackOnline by remember { mutableStateOf(false) }
var wasDown by remember { mutableStateOf(false) }
@@ -89,7 +89,10 @@ fun ConnectionErrorBanner(
}
@Composable
private fun BannerContent(health: ServerHealth, backOnline: Boolean) {
private fun BannerContent(
health: ServerHealth,
backOnline: Boolean,
) {
val scheme = MaterialTheme.colorScheme
val background: Color
val foreground: Color
@@ -108,7 +111,8 @@ private fun BannerContent(health: ServerHealth, backOnline: Boolean) {
}
}
Row(
modifier = Modifier
modifier =
Modifier
.fillMaxWidth()
.background(background)
.padding(horizontal = 16.dp, vertical = 10.dp),
@@ -124,7 +128,11 @@ private fun BannerContent(health: ServerHealth, backOnline: Boolean) {
}
}
private fun bannerText(health: ServerHealth, backOnline: Boolean): String = when {
private fun bannerText(
health: ServerHealth,
backOnline: Boolean,
): String =
when {
backOnline -> "Back online."
health == ServerHealth.Offline -> "No connection — check Wi-Fi or mobile data."
health == ServerHealth.ServerDown ->
@@ -20,7 +20,8 @@ annotation class ApplicationScope
object AppModule {
@Provides
@Singleton
fun provideJson(): Json = Json {
fun provideJson(): Json =
Json {
ignoreUnknownKeys = true
explicitNulls = false
coerceInputValues = true
@@ -5,9 +5,9 @@ import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.PowerManager
import androidx.core.content.ContextCompat
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.core.content.ContextCompat
import androidx.lifecycle.ProcessLifecycleOwner
import com.fabledsword.minstrel.auth.AuthController
import com.fabledsword.minstrel.auth.AuthStore
@@ -52,7 +52,9 @@ import javax.inject.Singleton
*/
@Suppress("TooManyFunctions") // one collector + one (un)register pair per signal; cohesive
@Singleton
class DiagnosticsReporter @Inject constructor(
class DiagnosticsReporter
@Inject
constructor(
@ApplicationContext private val context: Context,
@ApplicationScope private val scope: CoroutineScope,
private val dao: DiagnosticEventDao,
@@ -97,7 +99,8 @@ class DiagnosticsReporter @Inject constructor(
private fun start() {
registerPowerReceiver()
registerLifecycleObserver()
collectorJob = scope.launch {
collectorJob =
scope.launch {
record("lifecycle", buildJsonObject { put("event", "reporting_started") })
launch { collectConnectivity() }
launch { collectServerHealth() }
@@ -122,10 +125,13 @@ class DiagnosticsReporter @Inject constructor(
private suspend fun collectConnectivity() {
connectivity.online.distinctUntilChanged().collect { online ->
record("connectivity", buildJsonObject {
record(
"connectivity",
buildJsonObject {
put("event", "online_changed")
put("online", online)
})
},
)
}
}
@@ -133,19 +139,25 @@ class DiagnosticsReporter @Inject constructor(
// state is a StateFlow — already conflated/distinct, so no
// distinctUntilChanged (it's a deprecation warning = build error).
networkStatus.state.collect { s ->
record("connectivity", buildJsonObject {
record(
"connectivity",
buildJsonObject {
put("event", "server_health")
put("state", s.name)
})
},
)
}
}
private suspend fun collectUpnpDrops() {
playerController.dropEvents.collect { msg ->
record("upnp_sync", buildJsonObject {
record(
"upnp_sync",
buildJsonObject {
put("event", "drop")
put("message", msg)
})
},
)
}
}
@@ -156,12 +168,15 @@ class DiagnosticsReporter @Inject constructor(
.map { Triple(it.currentSource, it.isUpnpLoading, it.playbackError) }
.distinctUntilChanged()
.collect { (source, upnpLoading, err) ->
record("playback", buildJsonObject {
record(
"playback",
buildJsonObject {
put("event", "player_state")
put("source", source ?: "")
put("upnp_loading", upnpLoading)
if (err != null) put("error", err)
})
},
)
}
}
@@ -176,9 +191,12 @@ class DiagnosticsReporter @Inject constructor(
.distinctUntilChanged()
.collect { (index, _) ->
val ui = playerController.uiState.value
val casting = outputPicker.routesState.value.current.protocol !=
val casting =
outputPicker.routesState.value.current.protocol !=
OutputRoute.Protocol.SYSTEM
record("playback", buildJsonObject {
record(
"playback",
buildJsonObject {
put("event", "track_change")
put("local_index", index)
// Track IDENTITY, not just index — indices wobble across
@@ -189,7 +207,8 @@ class DiagnosticsReporter @Inject constructor(
put("upnp_loading", ui.isUpnpLoading)
put("server_health", networkStatus.state.value.name)
put("route", outputPicker.routesState.value.current.name)
})
},
)
}
}
@@ -214,24 +233,30 @@ class DiagnosticsReporter @Inject constructor(
private suspend fun collectTransportFlap() {
val detector = TransportFlapDetector()
playerController.transportEvents.collect { obs ->
record("upnp_sync", buildJsonObject {
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 !=
val casting =
outputPicker.routesState.value.current.protocol !=
OutputRoute.Protocol.SYSTEM
val spanMs = recent.last().atElapsedMs - recent.first().atElapsedMs
record("upnp_sync", buildJsonObject {
record(
"upnp_sync",
buildJsonObject {
put("event", "transport_flap")
put("changes", recent.size)
put("window_ms", spanMs)
@@ -249,20 +274,24 @@ class DiagnosticsReporter @Inject constructor(
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 {
record(
"playback",
buildJsonObject {
put("event", "route")
put("id", r.id)
put("name", r.name)
put("kind", r.kind.name)
put("protocol", r.protocol.name)
})
},
)
}
}
@@ -274,7 +303,9 @@ class DiagnosticsReporter @Inject constructor(
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 {
record(
"heartbeat",
buildJsonObject {
put("server_health", networkStatus.state.value.name)
put("is_playing", ui.isPlaying)
put("source", ui.currentSource ?: "")
@@ -285,7 +316,8 @@ class DiagnosticsReporter @Inject constructor(
put("route_protocol", route.protocol.name)
putSonos(this, routeActive)
addPowerFields(this)
})
},
)
}
}
@@ -293,14 +325,19 @@ class DiagnosticsReporter @Inject constructor(
private fun registerPowerReceiver() {
if (powerReceiver != null) return
val receiver = object : BroadcastReceiver() {
override fun onReceive(c: Context?, intent: Intent?) {
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 {
val filter =
IntentFilter().apply {
addAction(Intent.ACTION_SCREEN_ON)
addAction(Intent.ACTION_SCREEN_OFF)
addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED)
@@ -308,7 +345,10 @@ class DiagnosticsReporter @Inject constructor(
// 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,
context,
receiver,
filter,
ContextCompat.RECEIVER_NOT_EXPORTED,
)
powerReceiver = receiver
}
@@ -320,8 +360,10 @@ class DiagnosticsReporter @Inject constructor(
private fun registerLifecycleObserver() {
if (lifecycleObserver != null) return
val obs = object : DefaultLifecycleObserver {
val obs =
object : DefaultLifecycleObserver {
override fun onStart(owner: LifecycleOwner) = logLifecycle("app_foreground")
override fun onStop(owner: LifecycleOwner) = logLifecycle("app_background")
}
lifecycleObserver = obs
@@ -343,7 +385,8 @@ class DiagnosticsReporter @Inject constructor(
scope.launch { record("lifecycle", buildJsonObject { put("event", event) }) }
}
private fun powerEvent(action: String): JsonObject = buildJsonObject {
private fun powerEvent(action: String): JsonObject =
buildJsonObject {
put("event", action.substringAfterLast('.'))
addPowerFields(this)
}
@@ -353,7 +396,10 @@ class DiagnosticsReporter @Inject constructor(
// 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) {
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)
@@ -367,9 +413,13 @@ class DiagnosticsReporter @Inject constructor(
builder.put("battery_opt_ignored", pm.isIgnoringBatteryOptimizations(context.packageName))
}
private suspend fun record(kind: String, payload: JsonObject) {
private suspend fun record(
kind: String,
payload: JsonObject,
) {
runCatching {
val id = dao.insert(
val id =
dao.insert(
DiagnosticEventEntity(
kind = kind,
occurredAtMillis = System.currentTimeMillis(),
@@ -38,7 +38,9 @@ import javax.inject.Singleton
* uploader treats as success so the buffer drains either way.
*/
@Singleton
class DiagnosticsUploader @Inject constructor(
class DiagnosticsUploader
@Inject
constructor(
private val dao: DiagnosticEventDao,
private val authStore: AuthStore,
private val json: Json,
@@ -57,7 +59,10 @@ class DiagnosticsUploader @Inject constructor(
}
}
scope.launch {
authStore.sessionCookie.filterNotNull().distinctUntilChanged().collect { drainSafe() }
authStore.sessionCookie
.filterNotNull()
.distinctUntilChanged()
.collect { drainSafe() }
}
scope.launch {
networkStatus.state
@@ -97,13 +102,17 @@ class DiagnosticsUploader @Inject constructor(
}
}
private suspend fun upload(clientId: String, batch: List<DiagnosticEventEntity>) {
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 ->
events =
batch.map { row ->
DiagnosticEventWire(
kind = row.kind,
occurredAt = row.occurredAtMillis,
@@ -63,7 +63,9 @@ private const val EVENTS_BUFFER_CAPACITY = 64
* needing a separate path through here.
*/
@Singleton
class EventsStream @Inject constructor(
class EventsStream
@Inject
constructor(
private val authStore: AuthStore,
@ApplicationScope private val scope: CoroutineScope,
private val okHttpClient: OkHttpClient,
@@ -72,7 +74,8 @@ class EventsStream @Inject constructor(
) {
private val factory = EventSources.createFactory(okHttpClient)
private val emitter = MutableSharedFlow<LiveEvent>(
private val emitter =
MutableSharedFlow<LiveEvent>(
replay = 0,
extraBufferCapacity = EVENTS_BUFFER_CAPACITY,
onBufferOverflow = BufferOverflow.DROP_OLDEST,
@@ -83,6 +86,7 @@ class EventsStream @Inject constructor(
val connected: StateFlow<Boolean> = connectedState.asStateFlow()
private var currentSource: EventSource? = null
@Volatile private var signedIn = false
private var reconnectJob: Job? = null
private var backoffMs = ReconnectBackoff.BASE_MS
@@ -149,14 +153,17 @@ class EventsStream @Inject constructor(
reconnectJob?.cancel()
val waitMs = ReconnectBackoff.jittered(backoffMs)
backoffMs = ReconnectBackoff.next(backoffMs)
reconnectJob = scope.launch {
reconnectJob =
scope.launch {
delay(waitMs)
if (signedIn) connect()
}
}
private fun openSubscription(): EventSource {
val request = Request.Builder()
val request =
Request
.Builder()
.url("http://placeholder.invalid$SSE_PATH")
.header("Accept", "text/event-stream")
.build()
@@ -164,7 +171,10 @@ class EventsStream @Inject constructor(
}
private inner class Listener : EventSourceListener() {
override fun onOpen(eventSource: EventSource, response: Response) {
override fun onOpen(
eventSource: EventSource,
response: Response,
) {
backoffMs = ReconnectBackoff.BASE_MS
connectedState.value = true
}
@@ -199,7 +209,11 @@ class EventsStream @Inject constructor(
* 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 {
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()) {
@@ -28,13 +28,14 @@ import javax.inject.Singleton
* stream reconnects and the re-refresh avoids stale data flashing.
*/
@Singleton
class LiveEventsDispatcher @Inject constructor(
class LiveEventsDispatcher
@Inject
constructor(
private val eventsStream: EventsStream,
private val likes: LikesRepository,
private val notifications: NotificationsRepository,
@ApplicationScope private val scope: CoroutineScope,
) : DefaultLifecycleObserver {
init {
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
scope.launch {
@@ -24,7 +24,10 @@ internal object ReconnectBackoff {
fun next(currentMs: Long): Long = (currentMs * 2).coerceAtMost(MAX_MS)
/** [ms] moved by up to a quarter either way. */
fun jittered(ms: Long, random: Random = Random.Default): Long {
fun jittered(
ms: Long,
random: Random = Random.Default,
): Long {
val spread = ms * JITTER
return (ms + random.nextDouble(-spread, spread)).toLong()
}
@@ -49,7 +49,9 @@ data class HistoryPage(
* ordering/paging bookkeeping for no UX gain.
*/
@Singleton
class HistoryRepository @Inject constructor(
class HistoryRepository
@Inject
constructor(
private val snapshotDao: CachedHistorySnapshotDao,
private val json: Json,
retrofit: Retrofit,
@@ -69,8 +71,10 @@ class HistoryRepository @Inject constructor(
}
}
private fun HistoryPageWire.toDomain(): HistoryPage = HistoryPage(
entries = events.map {
private fun HistoryPageWire.toDomain(): HistoryPage =
HistoryPage(
entries =
events.map {
HistoryEntry(id = it.id, playedAt = it.playedAt, track = it.track.toDomain())
},
hasMore = hasMore,
@@ -1,10 +1,7 @@
package com.fabledsword.minstrel.history.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.HorizontalDivider
@@ -26,12 +23,12 @@ import com.fabledsword.minstrel.history.data.HistoryRepository
import com.fabledsword.minstrel.models.TrackRef
import com.fabledsword.minstrel.player.PlayerController
import com.fabledsword.minstrel.shared.UiState
import com.fabledsword.minstrel.shared.widgets.TrackRow
import com.fabledsword.minstrel.shared.widgets.EmptyState
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
import com.fabledsword.minstrel.shared.widgets.LoadingCentered
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
import com.fabledsword.minstrel.shared.widgets.TrackCoverThumb
import com.fabledsword.minstrel.shared.widgets.TrackRow
import com.fabledsword.minstrel.shared.widgets.trackactions.TrackActionsButton
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
@@ -56,12 +53,13 @@ private const val SHARE_STOP_TIMEOUT_MS = 5_000L
// ─── ViewModel ───────────────────────────────────────────────────────
@HiltViewModel
class HistoryTabViewModel @Inject constructor(
class HistoryTabViewModel
@Inject
constructor(
private val repository: HistoryRepository,
private val player: PlayerController,
networkStatus: NetworkStatusController,
) : ViewModel() {
private val refreshError = MutableStateFlow<String?>(null)
/**
@@ -93,7 +91,8 @@ class HistoryTabViewModel @Inject constructor(
}
}
fun refresh(): Job = viewModelScope.launch {
fun refresh(): Job =
viewModelScope.launch {
refreshError.value = null
runCatching { repository.refresh() }
.onFailure { refreshError.value = ErrorCopy.fromThrowable(it) }
@@ -121,16 +120,19 @@ fun HistoryTab(
PullToRefreshScaffold(onRefresh = { viewModel.refresh().join() }) {
when (val s = state) {
UiState.Loading -> LoadingCentered()
UiState.Empty -> EmptyState(
UiState.Empty ->
EmptyState(
title = "No listening history yet",
body = "Play something — your recent plays will show up here.",
)
is UiState.Error -> ErrorRetry(
is UiState.Error ->
ErrorRetry(
title = "Couldn't load history",
message = s.message,
onRetry = { viewModel.refresh() },
)
is UiState.Success -> HistoryList(
is UiState.Success ->
HistoryList(
entries = s.data,
playingTrackId = playingTrackId,
onPlay = viewModel::playTrack,
@@ -215,7 +217,8 @@ private const val DAYS_PER_WEEK = 7L
* up the row over malformed timestamps.
*/
private fun relativeTime(iso: String): String {
val parsed = runCatching { OffsetDateTime.parse(iso) }.getOrNull()
val parsed =
runCatching { OffsetDateTime.parse(iso) }.getOrNull()
?: return iso
val local = parsed.atZoneSameInstant(ZoneId.systemDefault())
val now = OffsetDateTime.now(ZoneId.systemDefault())
@@ -44,7 +44,9 @@ import javax.inject.Singleton
// Per-section observe accessors (one per Home row) inflate the function
// count past detekt's 11 default — accessor density, not complexity.
@Suppress("TooManyFunctions")
class HomeRepository @Inject constructor(
class HomeRepository
@Inject
constructor(
private val homeIndexDao: CachedHomeIndexDao,
private val metadataProvider: MetadataProvider,
private val prewarmer: HomeArtistPrewarmer,
@@ -69,14 +71,12 @@ class HomeRepository @Inject constructor(
fun observeRecentlyAddedAlbums(): Flow<List<HomeTile<AlbumRef>>> =
observeAlbumSection(SECTION_RECENTLY_ADDED_ALBUMS)
fun observeRediscoverAlbums(): Flow<List<HomeTile<AlbumRef>>> =
observeAlbumSection(SECTION_REDISCOVER_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 observeMostPlayedTracks(): Flow<List<HomeTile<TrackRef>>> = observeTrackSection(SECTION_MOST_PLAYED_TRACKS)
fun observeLastPlayedArtists(): Flow<List<HomeTile<ArtistRef>>> =
observeArtistSection(SECTION_LAST_PLAYED_ARTISTS)
@@ -105,7 +105,8 @@ class HomeRepository @Inject constructor(
val wire = api.getHomeIndex()
homeIndexDao.replaceSections(
sections = ALL_SECTIONS,
rows = rowsFor(SECTION_RECENTLY_ADDED_ALBUMS, "album", wire.recentlyAddedAlbums) +
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) +
@@ -122,7 +123,8 @@ class HomeRepository @Inject constructor(
section: String,
entityType: String,
ids: List<String>,
): List<CachedHomeIndexEntity> = ids.mapIndexed { index, id ->
): List<CachedHomeIndexEntity> =
ids.mapIndexed { index, id ->
CachedHomeIndexEntity(
section = section,
position = index,
@@ -143,7 +145,8 @@ class HomeRepository @Inject constructor(
* and flicker unchanged tiles.
*/
private fun observeSectionIds(section: String): Flow<List<String>> =
homeIndexDao.observeBySection(section)
homeIndexDao
.observeBySection(section)
.map { rows -> rows.map { it.entityId } }
.distinctUntilChanged()
@@ -193,7 +196,8 @@ class HomeRepository @Inject constructor(
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(
val ALL_SECTIONS =
listOf(
SECTION_RECENTLY_ADDED_ALBUMS,
SECTION_REDISCOVER_ALBUMS,
SECTION_REDISCOVER_ARTISTS,
@@ -31,7 +31,6 @@ import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyHorizontalGrid
import androidx.compose.foundation.lazy.grid.items as gridItems
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
@@ -49,14 +48,14 @@ import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.platform.LocalConfiguration
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.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewModelScope
import androidx.navigation.NavHostController
import com.composables.icons.lucide.Heart
import com.composables.icons.lucide.History
@@ -85,8 +84,8 @@ import com.fabledsword.minstrel.playlists.byShelfRank
import com.fabledsword.minstrel.playlists.data.PlaylistsRepository
import com.fabledsword.minstrel.playlists.data.playPlaylistShuffled
import com.fabledsword.minstrel.playlists.shelfMeta
import com.fabledsword.minstrel.playlists.widgets.OfflinePoolCard
import com.fabledsword.minstrel.playlists.widgets.GenreBandCard
import com.fabledsword.minstrel.playlists.widgets.OfflinePoolCard
import com.fabledsword.minstrel.playlists.widgets.PlaceholderShape
import com.fabledsword.minstrel.playlists.widgets.PlaylistPlaceholderCard
import com.fabledsword.minstrel.playlists.widgets.SongsLikeCard
@@ -98,7 +97,6 @@ import com.fabledsword.minstrel.shared.VeilOutcome
import com.fabledsword.minstrel.shared.VeilSessionResult
import com.fabledsword.minstrel.shared.VeilSettleState
import com.fabledsword.minstrel.shared.asCacheFirstStateFlow
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.ArtSettleTracker
import com.fabledsword.minstrel.shared.widgets.EmptyState
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
@@ -106,6 +104,7 @@ import com.fabledsword.minstrel.shared.widgets.HorizontalScrollRow
import com.fabledsword.minstrel.shared.widgets.LocalArtSettleTracker
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.SkeletonAlbumTile
import com.fabledsword.minstrel.shared.widgets.SkeletonArtistTile
import com.fabledsword.minstrel.shared.widgets.SkeletonSectionHeader
@@ -122,17 +121,19 @@ import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
import javax.inject.Inject
import androidx.compose.foundation.lazy.grid.items as gridItems
private const val SHARE_STOP_TIMEOUT_MS = 5_000L
private const val BOTTOM_PADDING_FOR_MINIPLAYER_DP = 140
// Recently Added is laid out in a multi-row LazyHorizontalGrid that
// scrolls as one panel (same pattern as Most Played). Two rows trades
// a tall block for fewer columns to scroll past — a 200dp tile × 2 =
@@ -169,7 +170,8 @@ data class HomeSections(
val youMightLikeArtists: List<HomeTile<ArtistRef>> = emptyList(),
) {
val isAllEmpty: Boolean
get() = playlists.isEmpty() &&
get() =
playlists.isEmpty() &&
recentlyAddedAlbums.isEmpty() &&
rediscoverAlbums.isEmpty() &&
rediscoverArtists.isEmpty() &&
@@ -182,7 +184,9 @@ data class HomeSections(
// ─── ViewModel ───────────────────────────────────────────────────────
@HiltViewModel
class HomeViewModel @Inject constructor(
class HomeViewModel
@Inject
constructor(
private val homeRepository: HomeRepository,
private val playlistsRepository: PlaylistsRepository,
private val libraryRepository: LibraryRepository,
@@ -191,7 +195,6 @@ class HomeViewModel @Inject constructor(
private val eventsStream: com.fabledsword.minstrel.events.EventsStream,
networkStatus: com.fabledsword.minstrel.connectivity.NetworkStatusController,
) : ViewModel() {
private val systemStatusInternal = MutableStateFlow(SystemPlaylistsStatus())
/** System-playlist build status for the Home placeholder cards. */
@@ -202,7 +205,8 @@ class HomeViewModel @Inject constructor(
* unified [NetworkStatusController] (not the raw device link) so Home reacts
* to ServerDown too; the transient Unstable state stays calm (not offline).
*/
val offline: StateFlow<Boolean> = networkStatus.state
val offline: StateFlow<Boolean> =
networkStatus.state
.map { it == ServerHealth.Offline || it == ServerHealth.ServerDown }
.stateIn(
scope = viewModelScope,
@@ -240,7 +244,8 @@ class HomeViewModel @Inject constructor(
*/
fun playPool(kind: OfflinePoolKind) {
viewModelScope.launch {
val tracks = when (kind) {
val tracks =
when (kind) {
OfflinePoolKind.RECENTLY_PLAYED -> shuffleSource.recentlyPlayed()
OfflinePoolKind.LIKED -> shuffleSource.liked()
}.shuffled()
@@ -257,7 +262,10 @@ class HomeViewModel @Inject constructor(
* tracks and start at the tapped index. Home's section is itself the
* playable unit, not a list of album-detail links.
*/
fun playMostPlayed(tracks: List<com.fabledsword.minstrel.models.TrackRef>, startIndex: Int) {
fun playMostPlayed(
tracks: List<com.fabledsword.minstrel.models.TrackRef>,
startIndex: Int,
) {
if (tracks.isEmpty()) return
player.setQueue(
tracks = tracks,
@@ -275,7 +283,8 @@ class HomeViewModel @Inject constructor(
* like the ArtistDetail play handler.
*/
suspend fun playAlbum(albumId: String) {
viewModelScope.launch {
viewModelScope
.launch {
playAlbumFromStart(albumId, libraryRepository, player) { snackbarMessages.trySend(it) }
}.join()
}
@@ -286,7 +295,8 @@ class HomeViewModel @Inject constructor(
* the Artist page's Play does).
*/
suspend fun playArtistShuffled(artistId: String) {
viewModelScope.launch {
viewModelScope
.launch {
shufflePlayArtist(artistId, libraryRepository, player) { snackbarMessages.trySend(it) }
}.join()
}
@@ -299,7 +309,8 @@ class HomeViewModel @Inject constructor(
* fall through to [ErrorCopy.fromThrowable].
*/
suspend fun playPlaylist(playlist: PlaylistRef) {
viewModelScope.launch {
viewModelScope
.launch {
playPlaylistShuffled(playlist, playlistsRepository, player) {
snackbarMessages.trySend(it)
}
@@ -312,7 +323,8 @@ class HomeViewModel @Inject constructor(
* succeeded — the veil controller retries on false and reports the
* outcome, so this must report failure rather than swallow it.
*/
private suspend fun runRefresh(): Boolean = coroutineScope {
private suspend fun runRefresh(): Boolean =
coroutineScope {
// /home/index is the load-bearing pull: its failure drives the
// empty-cache Error state. A failure over a populated cache
// stays silent — cached sections beat a full-screen error.
@@ -321,14 +333,16 @@ class HomeViewModel @Inject constructor(
// veil's retries, clearing up front made a failing cold start
// flash the "Welcome to Minstrel" empty state (empty cache + no
// error reads as Empty) between one attempt and the next.
val home = async {
val home =
async {
runCatching { homeRepository.refreshIndex() }
.onSuccess { refreshError.value = null }
.onFailure { refreshError.value = ErrorCopy.fromThrowable(it) }
.isSuccess
}
val lists = launch { runCatching { playlistsRepository.refreshList() } }
val status = launch {
val status =
launch {
runCatching { homeRepository.getSystemPlaylistsStatus() }
.onSuccess { systemStatusInternal.value = it }
}
@@ -375,7 +389,8 @@ class HomeViewModel @Inject constructor(
* folds in the two you-might-like flows, and [combineHomeFlows] the
* playlists flow.
*/
private fun observeCoreSections() = combine(
private fun observeCoreSections() =
combine(
homeRepository.observeRecentlyAddedAlbums(),
homeRepository.observeRediscoverAlbums(),
homeRepository.observeRediscoverArtists(),
@@ -391,7 +406,8 @@ class HomeViewModel @Inject constructor(
)
}
private fun observeHomeSections() = combine(
private fun observeHomeSections() =
combine(
observeCoreSections(),
homeRepository.observeYouMightLikeAlbums(),
homeRepository.observeYouMightLikeArtists(),
@@ -442,7 +458,8 @@ class HomeViewModel @Inject constructor(
)
}
private val veil = UpdateVeilController(
private val veil =
UpdateVeilController(
scope = viewModelScope,
settleSignal = settleSignal,
shouldVeil = {
@@ -520,7 +537,8 @@ class HomeViewModel @Inject constructor(
* the Playlists and Songs-like rows; `scan.run_finished` changes
* Recently added (and Home never reacted to it at all before).
*/
private val VEILED_EVENT_KINDS = setOf(
private val VEILED_EVENT_KINDS =
setOf(
"playlist.system_rebuilt",
"playlist.created",
"playlist.updated",
@@ -607,18 +625,22 @@ private fun HomeStateCrossfade(
Crossfade(targetState = state::class, label = "home-state") { _ ->
when (val s = state) {
UiState.Loading -> HomeSkeletonContent()
UiState.Empty -> EmptyState(
UiState.Empty ->
EmptyState(
title = "Welcome to Minstrel",
body = "Nothing to show yet — scan a folder in your server " +
body =
"Nothing to show yet — scan a folder in your server " +
"settings, then come back here for system playlists " +
"and recommendations.",
)
is UiState.Error -> ErrorRetry(
is UiState.Error ->
ErrorRetry(
title = "Couldn't load home",
message = s.message,
onRetry = { viewModel.retry() },
)
is UiState.Success -> HomeSuccessContent(
is UiState.Success ->
HomeSuccessContent(
sections = s.data,
systemStatus = systemStatus,
offline = offline,
@@ -650,7 +672,8 @@ private fun BoxScope.UpdatingVeil(visible: Boolean) {
modifier = Modifier.matchParentSize(),
) {
Box(
modifier = Modifier
modifier =
Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.background.copy(alpha = VEIL_ALPHA))
.clickable(
@@ -901,7 +924,8 @@ private fun RecentlyAddedGrid(
val perRow = (albums.size + RECENTLY_ADDED_GRID_ROWS - 1) / RECENTLY_ADDED_GRID_ROWS
val rows = albums.chunked(perRow.coerceAtLeast(1))
val cols = rows.maxOfOrNull { it.size } ?: 0
val ordered = buildList {
val ordered =
buildList {
for (c in 0 until cols) {
for (r in 0 until RECENTLY_ADDED_GRID_ROWS) {
rows.getOrNull(r)?.getOrNull(c)?.let { add(it) }
@@ -913,7 +937,8 @@ private fun RecentlyAddedGrid(
contentPadding = PaddingValues(horizontal = 16.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier
modifier =
Modifier
.fillMaxWidth()
.height(RECENTLY_ADDED_GRID_HEIGHT_DP.dp),
) {
@@ -994,9 +1019,13 @@ private fun LazyListScope.lastPlayedSection(
}
@Composable
private fun EmptySection(title: String, body: String) {
private fun EmptySection(
title: String,
body: String,
) {
Column(
modifier = Modifier
modifier =
Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp),
) {
@@ -1067,7 +1096,8 @@ private fun LazyListScope.youMightLikeSection(
} else {
EmptySection(
title = "You might like",
body = "We're still learning your taste — keep listening and " +
body =
"We're still learning your taste — keep listening and " +
"picks you might like will show up here.",
)
}
@@ -1134,7 +1164,8 @@ private fun PlaylistsRow(
onPlayPlaylist: suspend (PlaylistRef) -> Unit,
) {
val reals = rowItems.filterIsInstance<PlaylistRowItem.Real>().map { it.playlist }
val covers = remember(reals, shape) {
val covers =
remember(reals, shape) {
reals.map { it.id }.zip(assignShelfCovers(reals, shape.coversPerTile)).toMap()
}
val meta = remember(reals) { shelfMeta(reals) }
@@ -1142,12 +1173,14 @@ private fun PlaylistsRow(
HorizontalScrollRow(title = title, meta = meta) {
itemsIndexed(items = rowItems) { _, item ->
when (item) {
is PlaylistRowItem.OfflinePool -> OfflinePoolCard(
is PlaylistRowItem.OfflinePool ->
OfflinePoolCard(
label = item.kind.label,
icon = iconForPool(item.kind),
onClick = { onPlayPool(item.kind) },
)
is PlaylistRowItem.Real -> ShelfTile(
is PlaylistRowItem.Real ->
ShelfTile(
shape = shape,
tallWidth = tallWidth,
playlist = item.playlist,
@@ -1159,7 +1192,8 @@ private fun PlaylistsRow(
onClick = { onPlaylistClick(item.playlist.id) },
onPlay = { onPlayPlaylist(item.playlist) },
)
is PlaylistRowItem.Placeholder -> PlaylistPlaceholderCard(
is PlaylistRowItem.Placeholder ->
PlaylistPlaceholderCard(
label = item.label,
variant = item.variant,
shape = if (tallWidth != null) PlaceholderShape.TALL else shape.placeholder,
@@ -1213,26 +1247,41 @@ private fun ShelfTile(
* covers for genres. [coversPerTile] is how many distinct covers a tile
* shows; [placeholder] is the shape a not-yet-built mix takes on the shelf.
*/
internal enum class ShelfShape(val coversPerTile: Int, val placeholder: PlaceholderShape) {
internal enum class ShelfShape(
val coversPerTile: Int,
val placeholder: PlaceholderShape,
) {
WIDE(coversPerTile = 1, placeholder = PlaceholderShape.WIDE),
ROUND(coversPerTile = 1, placeholder = PlaceholderShape.ROUND),
BAND(coversPerTile = 3, placeholder = PlaceholderShape.SQUARE),
}
private fun iconForPool(kind: OfflinePoolKind) = when (kind) {
private fun iconForPool(kind: OfflinePoolKind) =
when (kind) {
OfflinePoolKind.RECENTLY_PLAYED -> Lucide.History
OfflinePoolKind.LIKED -> Lucide.Heart
}
/** A cache-backed offline pool, a real playlist tile, or a not-yet-generated slot. */
internal sealed interface PlaylistRowItem {
data class OfflinePool(val kind: OfflinePoolKind) : PlaylistRowItem
data class Real(val playlist: PlaylistRef) : PlaylistRowItem
data class Placeholder(val label: String, val variant: String) : PlaylistRowItem
data class OfflinePool(
val kind: OfflinePoolKind,
) : PlaylistRowItem
data class Real(
val playlist: PlaylistRef,
) : PlaylistRowItem
data class Placeholder(
val label: String,
val variant: String,
) : PlaylistRowItem
}
/** The two offline cache pools surfaced on Home when offline. */
enum class OfflinePoolKind(val label: String) {
enum class OfflinePoolKind(
val label: String,
) {
RECENTLY_PLAYED("Recently played"),
LIKED("Liked"),
}
@@ -1257,7 +1306,8 @@ internal fun buildPlaylistsRow(
offline: Boolean,
): List<PlaylistRowItem> {
if (!offline) return buildOnlineRow(owned, status)
val out = mutableListOf<PlaylistRowItem>(
val out =
mutableListOf<PlaylistRowItem>(
PlaylistRowItem.OfflinePool(OfflinePoolKind.RECENTLY_PLAYED),
PlaylistRowItem.OfflinePool(OfflinePoolKind.LIKED),
)
@@ -1272,10 +1322,12 @@ private fun buildOnlineRow(
status: SystemPlaylistsStatus,
): List<PlaylistRowItem> {
val out = mutableListOf<PlaylistRowItem>()
out += owned.firstOrNull { it.systemVariant == "for_you" }
out += owned
.firstOrNull { it.systemVariant == "for_you" }
?.let { PlaylistRowItem.Real(it) }
?: PlaylistRowItem.Placeholder("For You", variantFor("for-you", status))
out += owned.firstOrNull { it.systemVariant == "discover" }
out += owned
.firstOrNull { it.systemVariant == "discover" }
?.let { PlaylistRowItem.Real(it) }
?: PlaylistRowItem.Placeholder("Discover", variantFor("discover", status))
// Songs-like is not here: it has its own row.
@@ -1307,7 +1359,8 @@ internal fun buildSongsLikeRow(
(available + greyed).map { PlaylistRowItem.Real(it) }
}
mixes.isNotEmpty() -> mixes.map { PlaylistRowItem.Real(it) }
else -> List(SONGS_LIKE_PLACEHOLDER_SLOTS) {
else ->
List(SONGS_LIKE_PLACEHOLDER_SLOTS) {
PlaylistRowItem.Placeholder("Songs like…", variantFor("songs-like", status))
}
}
@@ -1324,7 +1377,8 @@ internal fun buildGenreMixRow(
owned: List<PlaylistRef>,
offline: Boolean,
): List<PlaylistRowItem> {
val mixes = owned
val mixes =
owned
.filter { it.systemVariant == "genre_mix" }
.sortedWith(byShelfRank)
if (!offline) return mixes.map { PlaylistRowItem.Real(it) }
@@ -1350,7 +1404,11 @@ private fun orderedRealPlaylists(owned: List<PlaylistRef>): List<PlaylistRef> {
return out
}
private fun variantFor(slot: String, s: SystemPlaylistsStatus): String = when {
private fun variantFor(
slot: String,
s: SystemPlaylistsStatus,
): String =
when {
s.inFlight -> "building"
s.lastError != null -> "failed"
slot == "songs-like" && s.lastRunAt != null -> "seed-needed"
@@ -1381,7 +1439,8 @@ private val ARTIST_ART = 104.dp
* to Home's primary slots. Order matches `systemPlaylistRegistry` in
* `internal/playlists/system.go`.
*/
private val SECONDARY_SYSTEM_VARIANTS = listOf(
private val SECONDARY_SYSTEM_VARIANTS =
listOf(
"deep_cuts",
"rediscover",
"new_for_you",
@@ -1440,7 +1499,8 @@ private fun MostPlayedRow(
val perRow = (tracks.size + MOST_PLAYED_ROWS - 1) / MOST_PLAYED_ROWS
val rows = tracks.chunked(perRow.coerceAtLeast(1))
val cols = rows.maxOfOrNull { it.size } ?: 0
val ordered = buildList {
val ordered =
buildList {
for (c in 0 until cols) {
for (r in 0 until MOST_PLAYED_ROWS) {
rows.getOrNull(r)?.getOrNull(c)?.let { add(it) }
@@ -1452,7 +1512,8 @@ private fun MostPlayedRow(
contentPadding = PaddingValues(horizontal = 16.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier
modifier =
Modifier
.fillMaxWidth()
.height(MOST_PLAYED_GRID_HEIGHT_DP.dp),
) {
@@ -1487,14 +1548,16 @@ private const val MOST_PLAYED_GRID_HEIGHT_DP = 200
@Composable
private fun SkeletonCompactTrackTile() {
Row(
modifier = Modifier
modifier =
Modifier
.width(MOST_PLAYED_TILE_WIDTH_DP.dp)
.height(MOST_PLAYED_TILE_HEIGHT_DP.dp)
.padding(horizontal = 8.dp, vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Box(
modifier = Modifier
modifier =
Modifier
.size(MOST_PLAYED_COVER_DP.dp)
.clip(RoundedCornerShape(4.dp))
.background(MaterialTheme.colorScheme.surfaceVariant),
@@ -1508,7 +1571,8 @@ private fun CompactTrackTile(
onClick: () -> Unit,
) {
Row(
modifier = Modifier
modifier =
Modifier
.width(MOST_PLAYED_TILE_WIDTH_DP.dp)
.height(MOST_PLAYED_TILE_HEIGHT_DP.dp)
.clickable(onClick = onClick)
@@ -1522,7 +1586,8 @@ private fun CompactTrackTile(
)
Spacer(Modifier.width(8.dp))
Column(
modifier = Modifier
modifier =
Modifier
.weight(1f)
.fillMaxHeight(),
verticalArrangement = Arrangement.Center,
@@ -1544,4 +1609,3 @@ private fun CompactTrackTile(
}
}
}
@@ -17,6 +17,11 @@ import retrofit2.create
import javax.inject.Inject
import javax.inject.Singleton
// LibraryRepository owns reads + refreshes for three entity families
// (artists / albums / tracks) plus shuffle. Function count scales with
// entity-family count; splitting into per-family repos would
// scatter the shared dao + retrofit plumbing for no real gain.
/**
* Cache-first reads of artists/albums/tracks. The Room DAOs are the
* source of truth ViewModels observe; refresh* methods pull from the
@@ -27,13 +32,11 @@ import javax.inject.Singleton
* own their interfaces (see NetworkModule), so there is no @Provides
* per endpoint — fewer Hilt bindings, locality of reference.
*/
// LibraryRepository owns reads + refreshes for three entity families
// (artists / albums / tracks) plus shuffle. Function count scales with
// entity-family count; splitting into per-family repos would
// scatter the shared dao + retrofit plumbing for no real gain.
@Suppress("TooManyFunctions")
@Singleton
class LibraryRepository @Inject constructor(
class LibraryRepository
@Inject
constructor(
private val artistDao: CachedArtistDao,
private val albumDao: CachedAlbumDao,
private val trackDao: CachedTrackDao,
@@ -48,14 +51,14 @@ class LibraryRepository @Inject constructor(
// stores no cover and sync carries none.
fun observeArtists(): Flow<List<ArtistRef>> =
combine(artistDao.observeAll(), albumDao.observeAll()) { artists, albums ->
val firstAlbumByArtist = albums
val firstAlbumByArtist =
albums
.groupBy { it.artistId }
.mapValues { (_, list) -> list.minByOrNull { it.sortTitle }?.id ?: "" }
artists.map { it.toDomain(coverAlbumId = firstAlbumByArtist[it.id] ?: "") }
}
fun observeAlbums(): Flow<List<AlbumRef>> =
albumDao.observeAll().map { rows -> rows.map { it.toDomain() } }
fun 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() } }
@@ -83,7 +86,8 @@ class LibraryRepository @Inject constructor(
artistDao.upsertAll(listOf(wire.toArtistEntity()))
albumDao.upsertAll(wire.albums.map { it.toEntity() })
return ArtistDetailRef(
artist = ArtistRef(
artist =
ArtistRef(
id = wire.id,
name = wire.name,
sortName = wire.sortName,
@@ -100,24 +104,21 @@ class LibraryRepository @Inject constructor(
* persistence — the response is consumed straight into a player
* queue.
*/
suspend fun fetchArtistTracks(id: String): List<TrackRef> =
api.getArtistTracks(id).map { it.toDomain() }
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() }
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() }
suspend fun fetchArtistTopTracks(id: String): List<TrackRef> = api.getArtistTopTracks(id).map { it.toDomain() }
/**
* Pulls the album detail (AlbumRef + tracks), persists both, and
@@ -130,7 +131,8 @@ class LibraryRepository @Inject constructor(
albumDao.upsertAll(listOf(wire.toAlbumEntity()))
trackDao.upsertAll(wire.tracks.map { it.toEntity() })
return AlbumDetailRef(
album = AlbumRef(
album =
AlbumRef(
id = wire.id,
title = wire.title,
artistId = wire.artistId,
@@ -168,21 +170,34 @@ class LibraryRepository @Inject constructor(
/** 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) }
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) }
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 {
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(
suspend fun albumsByYear(
year: Int,
limit: Int,
offset: Int,
): AlbumPage {
val page =
api.getAlbumsByYear(
yearFrom = year,
yearTo = year,
limit = limit,
@@ -197,13 +212,22 @@ class LibraryRepository @Inject constructor(
}
/** One row of the genre index. */
data class GenreCount(val genre: String, val trackCount: Int)
data class GenreCount(
val genre: String,
val trackCount: Int,
)
/** One row of the year index. */
data class YearCount(val year: Int, val albumCount: Int)
data class YearCount(
val year: Int,
val albumCount: Int,
)
/**
* A page of albums plus the server's total for the whole filter, which is
* what lets the UI say how many are left rather than just offering "more".
*/
data class AlbumPage(val items: List<AlbumRef>, val total: Int)
data class AlbumPage(
val items: List<AlbumRef>,
val total: Int,
)
@@ -2,6 +2,7 @@
package com.fabledsword.minstrel.library.ui
import androidx.compose.animation.Crossfade
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
@@ -12,7 +13,6 @@ import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.animation.Crossfade
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
@@ -29,7 +29,6 @@ import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
@@ -51,12 +50,12 @@ import com.fabledsword.minstrel.shared.formatDuration
import com.fabledsword.minstrel.shared.plural
import com.fabledsword.minstrel.shared.widgets.CoverFallbackIcon
import com.fabledsword.minstrel.shared.widgets.CoverTile
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.TrackRow
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
import com.fabledsword.minstrel.shared.widgets.LikeButton
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.SkeletonTrackRow
import com.fabledsword.minstrel.shared.widgets.TrackRow
import com.fabledsword.minstrel.shared.widgets.trackactions.TrackActionsButton
@OptIn(ExperimentalMaterial3Api::class)
@@ -95,7 +94,8 @@ fun AlbumDetailScreen(
}
}
private fun titleFor(state: AlbumDetailUiState): String = when (state) {
private fun titleFor(state: AlbumDetailUiState): String =
when (state) {
is AlbumDetailUiState.Success -> state.detail.album.title
is AlbumDetailUiState.Loading -> state.seed?.title ?: "Album"
is AlbumDetailUiState.Error -> "Album"
@@ -115,7 +115,8 @@ private fun AlbumDetailStateContent(
when (val s = state) {
is AlbumDetailUiState.Loading ->
if (s.seed != null) SeededAlbumLoading(s.seed) else SkeletonTrackList()
is AlbumDetailUiState.Error -> ErrorRetry(
is AlbumDetailUiState.Error ->
ErrorRetry(
title = "Couldn't load album",
message = s.message,
onRetry = { viewModel.refresh() },
@@ -209,7 +210,8 @@ private fun AlbumHeader(
onToggleAlbumLike: () -> Unit,
) {
Column(
modifier = Modifier
modifier =
Modifier
.fillMaxWidth()
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
@@ -28,13 +28,23 @@ import javax.inject.Inject
private const val SHARE_STOP_TIMEOUT_MS = 5_000L
sealed interface AlbumDetailUiState {
data class Loading(val seed: AlbumRef? = null) : AlbumDetailUiState
data class Success(val detail: AlbumDetailRef) : AlbumDetailUiState
data class Error(val message: String) : AlbumDetailUiState
data class Loading(
val seed: AlbumRef? = null,
) : AlbumDetailUiState
data class Success(
val detail: AlbumDetailRef,
) : AlbumDetailUiState
data class Error(
val message: String,
) : AlbumDetailUiState
}
@HiltViewModel
class AlbumDetailViewModel @Inject constructor(
class AlbumDetailViewModel
@Inject
constructor(
private val repository: LibraryRepository,
private val likes: LikesRepository,
private val player: PlayerController,
@@ -42,7 +52,6 @@ class AlbumDetailViewModel @Inject constructor(
networkStatus: NetworkStatusController,
savedStateHandle: SavedStateHandle,
) : ViewModel() {
private val route: AlbumDetail = savedStateHandle.toRoute()
val albumId: String = route.id
@@ -51,7 +60,8 @@ class AlbumDetailViewModel @Inject constructor(
val uiState: StateFlow<AlbumDetailUiState> = internal.asStateFlow()
val albumLiked: StateFlow<Boolean> =
likes.observeIsLiked(LikesRepository.ENTITY_ALBUM, albumId)
likes
.observeIsLiked(LikesRepository.ENTITY_ALBUM, albumId)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS),
@@ -59,7 +69,8 @@ class AlbumDetailViewModel @Inject constructor(
)
val likedTrackIds: StateFlow<Set<String>> =
likes.observeLikedTrackIds()
likes
.observeLikedTrackIds()
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS),
@@ -78,8 +89,10 @@ class AlbumDetailViewModel @Inject constructor(
}
}
fun refresh(): Job = viewModelScope.launch {
val carried = when (val cur = internal.value) {
fun refresh(): Job =
viewModelScope.launch {
val carried =
when (val cur = internal.value) {
is AlbumDetailUiState.Loading -> cur.seed
is AlbumDetailUiState.Success -> cur.detail.album
is AlbumDetailUiState.Error -> null
@@ -99,7 +112,8 @@ class AlbumDetailViewModel @Inject constructor(
fun play(startTrackId: String?) {
val detail = (internal.value as? AlbumDetailUiState.Success)?.detail ?: return
if (detail.tracks.isEmpty()) return
val startIndex = detail.tracks
val startIndex =
detail.tracks
.indexOfFirst { it.id == startTrackId }
.coerceAtLeast(0)
player.setQueue(
@@ -20,16 +20,15 @@ import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.items as lazyItems
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
@@ -58,14 +57,15 @@ import com.fabledsword.minstrel.nav.ArtistDetail
import com.fabledsword.minstrel.shared.formatDuration
import com.fabledsword.minstrel.shared.plural
import com.fabledsword.minstrel.shared.widgets.CoverFallbackIcon
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
import com.fabledsword.minstrel.shared.widgets.HorizontalScrollRow
import com.fabledsword.minstrel.shared.widgets.LikeButton
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
import com.fabledsword.minstrel.shared.widgets.ServerImage
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.SkeletonAlbumTile
import com.fabledsword.minstrel.shared.widgets.TrackRow
import androidx.compose.foundation.lazy.items as lazyItems
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@@ -111,7 +111,8 @@ fun ArtistDetailScreen(
} else {
SkeletonArtistAlbumsGrid()
}
is ArtistDetailUiState.Error -> ErrorRetry(
is ArtistDetailUiState.Error ->
ErrorRetry(
title = "Couldn't load artist",
message = s.message,
onRetry = { viewModel.refresh() },
@@ -145,7 +146,8 @@ private fun ArtistSuccessBody(
)
}
private fun titleFor(state: ArtistDetailUiState): String = when (state) {
private fun titleFor(state: ArtistDetailUiState): String =
when (state) {
is ArtistDetailUiState.Success -> state.detail.artist.name
is ArtistDetailUiState.Loading -> state.seed?.name ?: "Artist"
is ArtistDetailUiState.Error -> "Artist"
@@ -278,7 +280,8 @@ private fun ArtistHeader(
onToggleLike: () -> Unit,
) {
Row(
modifier = Modifier
modifier =
Modifier
.fillMaxWidth()
.padding(16.dp),
verticalAlignment = Alignment.CenterVertically,
@@ -311,17 +314,22 @@ private fun ArtistHeader(
}
@Composable
private fun ArtistAvatar(artist: ArtistRef, fallbackAlbumId: String? = null) {
private fun ArtistAvatar(
artist: ArtistRef,
fallbackAlbumId: String? = null,
) {
// Server coverUrl wins; otherwise use the first loaded album's
// cover, the same rule the server applies. Bare Lucide.User only
// when neither exists.
val model = when {
val model =
when {
artist.coverUrl.isNotEmpty() -> artist.coverUrl
fallbackAlbumId != null -> albumCoverPath(fallbackAlbumId)
else -> null
}
Box(
modifier = Modifier
modifier =
Modifier
.size(96.dp)
.clip(CircleShape)
.background(MaterialTheme.colorScheme.surfaceVariant),
@@ -335,13 +343,13 @@ private fun ArtistAvatar(artist: ArtistRef, fallbackAlbumId: String? = null) {
}
}
private fun albumCountLine(artist: ArtistRef): String =
plural(artist.albumCount, "album", "albums")
private fun albumCountLine(artist: ArtistRef): String = plural(artist.albumCount, "album", "albums")
@Composable
private fun EmptyAlbumsHint() {
Column(
modifier = Modifier
modifier =
Modifier
.fillMaxWidth()
.padding(24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
@@ -33,17 +33,25 @@ import javax.inject.Inject
private const val SHARE_STOP_TIMEOUT_MS = 5_000L
sealed interface ArtistDetailUiState {
data class Loading(val seed: ArtistRef? = null) : ArtistDetailUiState
data class Loading(
val seed: ArtistRef? = null,
) : ArtistDetailUiState
data class Success(
val detail: ArtistDetailRef,
val similarArtists: List<ArtistRef> = emptyList(),
val topTracks: List<TrackRef> = emptyList(),
) : ArtistDetailUiState
data class Error(val message: String) : ArtistDetailUiState
data class Error(
val message: String,
) : ArtistDetailUiState
}
@HiltViewModel
class ArtistDetailViewModel @Inject constructor(
class ArtistDetailViewModel
@Inject
constructor(
private val repository: LibraryRepository,
private val likes: LikesRepository,
private val player: PlayerController,
@@ -51,7 +59,6 @@ class ArtistDetailViewModel @Inject constructor(
networkStatus: NetworkStatusController,
savedStateHandle: SavedStateHandle,
) : ViewModel() {
private val route: ArtistDetail = savedStateHandle.toRoute()
val artistId: String = route.id
@@ -64,7 +71,8 @@ class ArtistDetailViewModel @Inject constructor(
val transientMessages: Flow<String> = transientMessagesChannel.receiveAsFlow()
val artistLiked: StateFlow<Boolean> =
likes.observeIsLiked(LikesRepository.ENTITY_ARTIST, artistId)
likes
.observeIsLiked(LikesRepository.ENTITY_ARTIST, artistId)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS),
@@ -95,8 +103,10 @@ class ArtistDetailViewModel @Inject constructor(
}
}
fun refresh(): Job = viewModelScope.launch {
val carried = when (val cur = internal.value) {
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
@@ -41,6 +41,11 @@ data class AlbumBrowseState(
val remaining: Int get() = (total - albums.size).coerceAtLeast(0)
}
// Two browse axes, each with an index, a filter/sort or grouping, a
// drill-down and a pager. The function count is two axes' worth of a
// cohesive surface; splitting into GenresViewModel + YearsViewModel would
// duplicate the shared paging body for no gain.
/**
* Backs the Genres and Years tabs, the same browse axes the web client has.
*
@@ -49,16 +54,13 @@ data class AlbumBrowseState(
* missing and matches the web client's. These two tabs therefore need a
* connection; the empty states say so rather than looking broken.
*/
// Two browse axes, each with an index, a filter/sort or grouping, a
// drill-down and a pager. The function count is two axes' worth of a
// cohesive surface; splitting into GenresViewModel + YearsViewModel would
// duplicate the shared paging body for no gain.
@Suppress("TooManyFunctions")
@HiltViewModel
class BrowseViewModel @Inject constructor(
class BrowseViewModel
@Inject
constructor(
private val repository: LibraryRepository,
) : ViewModel() {
private val genresInternal = MutableStateFlow<UiState<List<GenreCount>>>(UiState.Loading)
val genres: StateFlow<UiState<List<GenreCount>>> = genresInternal.asStateFlow()
@@ -97,7 +99,8 @@ class BrowseViewModel @Inject constructor(
fun loadGenres() {
viewModelScope.launch {
genresInternal.value = UiState.Loading
genresInternal.value = runCatching { repository.genres() }.fold(
genresInternal.value =
runCatching { repository.genres() }.fold(
onSuccess = { if (it.isEmpty()) UiState.Empty else UiState.Success(it) },
onFailure = { UiState.Error(ErrorCopy.fromThrowable(it)) },
)
@@ -107,16 +110,21 @@ class BrowseViewModel @Inject constructor(
fun loadYears() {
viewModelScope.launch {
yearsInternal.value = UiState.Loading
yearsInternal.value = runCatching { repository.albumYears() }.fold(
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 setGenreFilter(value: String) {
genreFilterInternal.value = value
}
fun setGenreSort(sort: GenreSort) { genreSortInternal.value = sort }
fun setGenreSort(sort: GenreSort) {
genreSortInternal.value = sort
}
/** Drill into [genre], or pass null to go back to the index. */
fun selectGenre(genre: String?) {
@@ -158,7 +166,11 @@ class BrowseViewModel @Inject constructor(
selectedYearInternal.value?.let { selectYear(it) }
}
private fun fetchGenrePage(genre: String, offset: Int, token: Int) {
private fun fetchGenrePage(
genre: String,
offset: Int,
token: Int,
) {
fetchPage(
state = genreAlbumsInternal,
offset = offset,
@@ -167,7 +179,11 @@ class BrowseViewModel @Inject constructor(
)
}
private fun fetchYearPage(year: Int, offset: Int, token: Int) {
private fun fetchYearPage(
year: Int,
offset: Int,
token: Int,
) {
fetchPage(
state = yearAlbumsInternal,
offset = offset,
@@ -193,7 +209,8 @@ class BrowseViewModel @Inject constructor(
if (!isCurrent()) return@launch
val merged =
if (offset == 0) page.items else state.value.albums + page.items
state.value = AlbumBrowseState(
state.value =
AlbumBrowseState(
albums = merged,
total = page.total,
loading = false,
@@ -257,12 +274,12 @@ data class DecadeGroup(
* same reason as [visibleGenres].
*/
fun groupByDecade(years: List<YearCount>): List<DecadeGroup> =
years.groupBy { (it.year / YEARS_PER_DECADE) * YEARS_PER_DECADE }
years
.groupBy { (it.year / YEARS_PER_DECADE) * YEARS_PER_DECADE }
.map { (decade, entries) ->
DecadeGroup(
decade = decade,
years = entries.sortedByDescending { it.year },
albumCount = entries.sumOf { it.albumCount },
)
}
.sortedByDescending { it.decade }
}.sortedByDescending { it.decade }
@@ -10,11 +10,11 @@ import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.FilterChip
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
@@ -32,8 +32,8 @@ import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.composables.icons.lucide.ArrowLeft
import com.composables.icons.lucide.Lucide
import com.composables.icons.lucide.LibraryBig
import com.composables.icons.lucide.Lucide
import com.fabledsword.minstrel.library.widgets.AlbumCard
import com.fabledsword.minstrel.models.AlbumRef
import com.fabledsword.minstrel.shared.UiState
@@ -74,19 +74,23 @@ private fun GenreIndex(viewModel: BrowseViewModel) {
val sort by viewModel.genreSort.collectAsStateWithLifecycle()
when (val s = state) {
UiState.Loading -> EmptyState(
UiState.Loading ->
EmptyState(
title = "Reading your genres…",
body = "",
icon = Lucide.LibraryBig,
)
UiState.Empty -> EmptyState(
UiState.Empty ->
EmptyState(
title = "No genres found",
body = "Genres come from the genre tag on your audio files. If your " +
body =
"Genres come from the genre tag on your audio files. If your " +
"library is tagged but this is empty, try a rescan from the admin " +
"screen.",
icon = Lucide.LibraryBig,
)
is UiState.Error -> ErrorRetry(
is UiState.Error ->
ErrorRetry(
message = s.message,
onRetry = viewModel::loadGenres,
)
@@ -161,7 +165,8 @@ private fun GenreIndexControls(
label = { Text("A–Z") },
)
Text(
text = if (filter.isBlank()) {
text =
if (filter.isBlank()) {
"$total genres"
} else {
"$shown of $total"
@@ -174,9 +179,14 @@ private fun GenreIndexControls(
}
@Composable
private fun GenreRow(genre: String, trackCount: Int, onClick: () -> Unit) {
private fun GenreRow(
genre: String,
trackCount: Int,
onClick: () -> Unit,
) {
Row(
modifier = Modifier
modifier =
Modifier
.fillMaxWidth()
.clickable(onClick = onClick)
.padding(horizontal = 16.dp, vertical = 14.dp),
@@ -263,16 +273,19 @@ fun BrowseAlbumResults(
}
when {
state.failed && state.albums.isEmpty() -> ErrorRetry(
state.failed && state.albums.isEmpty() ->
ErrorRetry(
message = "Couldn't load albums.",
onRetry = onRetry,
)
state.loading && state.albums.isEmpty() -> EmptyState(
state.loading && state.albums.isEmpty() ->
EmptyState(
title = "Loading…",
body = "",
)
state.albums.isEmpty() -> EmptyState(title = emptyTitle, body = emptyBody)
else -> BrowseAlbumGrid(
else ->
BrowseAlbumGrid(
state = state,
onLoadMore = onLoadMore,
onAlbumClick = onAlbumClick,
@@ -334,7 +347,12 @@ private fun BrowseAlbumGrid(
* is still in flight — a count that appears as 0 and then corrects itself reads
* as a bug.
*/
internal fun albumCountLabel(total: Int, loading: Boolean, loaded: Int): String = when {
internal fun albumCountLabel(
total: Int,
loading: Boolean,
loaded: Int,
): String =
when {
loading && loaded == 0 -> ""
total == 1 -> "1 album"
else -> "$total albums"

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