Compare commits
81
Commits
ae7e05c579
..
dev
+2
-6
@@ -9,12 +9,8 @@ web/build
|
||||
# The Android client — built by its own job, never from this context. The APK
|
||||
# reaches the image through client/, downloaded as a CI artifact, so nothing
|
||||
# here reads android/ sources.
|
||||
#
|
||||
# This block named `flutter_client/` until 2026-09-10 and lost its PATTERN when
|
||||
# that tree was deleted, leaving a comment describing an exclusion that was no
|
||||
# longer happening. android/ never took its place, so 4.1 MB of Gradle project
|
||||
# has been entering the context and busting the `COPY . .` layer on every
|
||||
# Android-only change.
|
||||
# Excluded so the Gradle project neither bloats the context nor busts the
|
||||
# `COPY . .` layer on every Android-only change.
|
||||
android/
|
||||
|
||||
# Local `make build` output — an 18 MB binary the image never uses, since the
|
||||
|
||||
+148
-248
@@ -3,49 +3,49 @@ name: release
|
||||
# Builds and pushes the minstrel container image to the Gitea registry.
|
||||
#
|
||||
# push to dev → :dev (freshly-built dev APK bundled)
|
||||
# push to main → :latest + :<sha> (latest-release APK bundled)
|
||||
# push tag vYYYY.MM.DD.HHMM → :latest (fresh APK bundled)
|
||||
# push to main → :latest + :<sha> (freshly-built stable APK bundled)
|
||||
# push tag vYYYY.MM.DD.HHMM → :latest (fresh APK bundled, and attached to the Release)
|
||||
# workflow_dispatch → manual trigger (same rules based on the ref)
|
||||
#
|
||||
# That is the whole tag map, and it is family rule 145 + 147 as written.
|
||||
# That is the whole tag map.
|
||||
#
|
||||
# :<sha> on main is the ROLLBACK UNIT — every production commit addressable
|
||||
# without a release ceremony. It is minted only on main, where rollback is
|
||||
# actually worth having: merges are gated (rule 2) so they number in the dozens
|
||||
# per year, while on dev they would be one per push, forever, for a channel
|
||||
# whose entire contract is that it moves.
|
||||
# actually worth having: merges to main are deliberate, so they number in the
|
||||
# dozens per year, while on dev they would be one per push, forever, for a
|
||||
# channel whose entire contract is that it moves.
|
||||
#
|
||||
# There are NO :<version> image tags. This repo published :vYYYY.MM.DD.HHMM
|
||||
# until 2026-09-10 and it was the inverse of the rule on both counts — minting
|
||||
# a version tag nobody pinned while the rollback unit the rule names did not
|
||||
# exist here at all. Git and the build's own self-reported version answer
|
||||
# "which build is this"; a third name for the same thing is upkeep for a model
|
||||
# we do not run. Operator, 2026-09-10: "only things like the APK need that kind
|
||||
# of versioning for their update process."
|
||||
# There are NO :<version> image tags. Git and the build's own self-reported
|
||||
# version answer "which build is this"; a third name for the same thing is
|
||||
# upkeep for a model we do not run. Only the APK needs version numbers, for
|
||||
# its update process.
|
||||
#
|
||||
# There is no :main either. :latest tracks main's tip with no gate between them
|
||||
# (rule 147), so a second name for the same image sends readers looking for a
|
||||
# There is no :main either. :latest tracks main's tip with no gate between
|
||||
# them, so a second name for the same image sends readers looking for a
|
||||
# distinction that does not exist.
|
||||
#
|
||||
# The dev channel exists so testing a build does not require shipping one.
|
||||
# Before it, the only way to get an APK onto a phone was to cut a release,
|
||||
# which made `main` the staging area by default. `:dev` carries its own
|
||||
# freshly-built APK, signed with the SAME key as release builds — a different
|
||||
# key cannot install over the stable app, so anyone crossing channels would
|
||||
# have to uninstall and lose their data.
|
||||
# The dev channel exists so testing a build does not require shipping one:
|
||||
# without it the only way to get an APK onto a phone is to cut a release,
|
||||
# which makes `main` the staging area. `:dev` carries its own freshly-built
|
||||
# APK, signed with the SAME key as release builds — a different key cannot
|
||||
# install over the stable app, so anyone crossing channels would have to
|
||||
# uninstall and lose their data.
|
||||
#
|
||||
# :dev is published ALONE, with no per-commit tag. A rolling channel is
|
||||
# rolling by definition; a commit-addressable image for it would be a
|
||||
# rollback target nobody ever pulls, kept forever. Recovery on dev is to fix
|
||||
# forward.
|
||||
#
|
||||
# Note what this repo does NOT need: a cross-repo dispatch to refresh the
|
||||
# channel when its bundled APK is rebuilt. That mechanism exists elsewhere in
|
||||
# the family because the app and the server live in separate repos. Minstrel
|
||||
# is a monorepo — one push builds the APK and the image in the same run from
|
||||
# the same commit, so the channel cannot go stale against its own artifact.
|
||||
# The requirement is satisfied structurally; copying the mechanism would add
|
||||
# a moving part to fix a problem that does not exist here.
|
||||
# No cross-repo dispatch is needed to refresh a channel when its bundled APK
|
||||
# is rebuilt: Minstrel is a monorepo, so one push builds the APK and the
|
||||
# image in the same run from the same commit, and the channel cannot go
|
||||
# stale against its own artifact.
|
||||
#
|
||||
# Every branch build carries the app built from its own commit, so a merge to
|
||||
# main is all it takes to put a new app in front of stable phones: `:latest`
|
||||
# serves it from /api/client/apk and the in-app update offers it. A release
|
||||
# is an optional bookmark — a named point in history with the APK attached
|
||||
# for download — never a step the app has to wait for.
|
||||
#
|
||||
# Release model: the tag IS the artifact's version name with a `v` in front.
|
||||
# `v2026.09.10.1432` and `2026.09.10.1432` are the same string, derived from
|
||||
@@ -55,43 +55,30 @@ name: release
|
||||
#
|
||||
# TAGS ARE IMMUTABLE. Never move, retarget or delete a published tag. A
|
||||
# same-day second release is not a collision — HHMM makes every tag unique
|
||||
# by construction, so the answer is simply another tag.
|
||||
#
|
||||
# This block used to say the opposite: that the per-day tag was
|
||||
# "intentionally mutable" and that a same-day re-cut should
|
||||
# `git push -f origin vYYYY.MM.DD`. That instruction is what the family
|
||||
# rulebook now forbids outright, and it has incidents behind it — moving a
|
||||
# same-day tag forward once took a published release down with it. Anyone
|
||||
# installing from a tag is holding something the tag no longer points at,
|
||||
# which is a worse failure than an extra row in the tag list.
|
||||
# by construction, so the answer is simply another tag. Anyone installing
|
||||
# from a moved tag would hold something the tag no longer points at, which
|
||||
# is a worse failure than an extra row in the tag list.
|
||||
#
|
||||
# :latest is updated by every main push AND every tag push, so it always
|
||||
# reflects the newest blessed image.
|
||||
#
|
||||
# APK pipeline: on tag pushes the android-release job builds + signs the
|
||||
# Android APK and uploads it as a workflow artifact. The image-release
|
||||
# job declares `needs: android-release`, so the docker image cannot
|
||||
# start building until the APK is guaranteed-ready — no polling, no
|
||||
# race, no silent-failure mode. Attaching the APK to the gitea Release is
|
||||
# its own job (release-assets), behind the test gate below.
|
||||
# APK pipeline: on every push — dev, main and tags alike — the
|
||||
# android-release job builds + signs the Android APK and uploads it as a
|
||||
# workflow artifact. The image-release job declares `needs: android-release`
|
||||
# and requires its success, so the docker image cannot start building until
|
||||
# the APK is guaranteed-ready — no polling, no race, no silent-failure mode,
|
||||
# and no image that moves a channel without an app inside it. Attaching the
|
||||
# APK to the gitea Release is its own job (release-assets), tags only, behind
|
||||
# the test gate below.
|
||||
#
|
||||
# :latest always carries an APK. Because every main push also moves
|
||||
# :latest (not just tags), a main build with no APK would silently strip
|
||||
# the in-app update channel off :latest until the next release. So on
|
||||
# non-tag builds image-release pulls the MOST RECENT release's signed APK
|
||||
# AND the version sidecar published beside it — the recorded values, not
|
||||
# recomputed ones — so no rebuild is needed, just a rebundle. Tag builds
|
||||
# keep bundling their own freshly-built APK.
|
||||
#
|
||||
# THE GATE (rule 177, M462 #4984). Every verifying lane lives in this file —
|
||||
# THE GATE. Every verifying lane lives in this file —
|
||||
# Go (vet, lint, short tests), the Postgres integration suite, the web app
|
||||
# (npm audit, svelte-check, vitest), Android (ktlint, detekt, unit tests) and
|
||||
# govulncheck — and every job that publishes something names each of them in
|
||||
# `needs:` and requires `success` from each, by name. Nothing publishes on red.
|
||||
#
|
||||
# They used to be three separate workflows (test-go, test-web, android) on the
|
||||
# same push trigger as this one. Separate workflows cannot see each other's
|
||||
# verdict, so :dev meant "it built", never "it passed": a red test run and a
|
||||
# One workflow, because separate workflows cannot see each other's verdict:
|
||||
# :dev would mean "it built", never "it passed", and a red test run and a
|
||||
# fresh :dev could carry the same timestamp. One graph is the only place the
|
||||
# edge can be written.
|
||||
#
|
||||
@@ -125,10 +112,9 @@ on:
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
# A rapid re-push to main should supersede the in-flight build — the
|
||||
# operator explicitly wants the later commit to win. Tags no longer enter
|
||||
# into this: they are immutable and unique, so no tag build can ever be
|
||||
# superseded by another run on the same ref.
|
||||
# A rapid re-push to main supersedes the in-flight build: the later commit
|
||||
# wins. Tags are immutable and unique, so no tag build can be superseded by
|
||||
# another run on the same ref.
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
@@ -173,14 +159,14 @@ jobs:
|
||||
# Full `go test -race` against an ephemeral Postgres.
|
||||
#
|
||||
# DB wiring follows the act_runner shared-daemon pattern: the runner's Docker
|
||||
# daemon also runs the operator's dev compose stack, so service containers
|
||||
# get NO published ports (collision) and no service-name DNS. We discover the
|
||||
# daemon also runs a dev compose stack, so service containers get NO
|
||||
# published ports (collision) and no service-name DNS. We discover the
|
||||
# service container through the mounted docker socket and reach it by bridge
|
||||
# IP. The exactly-one assertion is a hard guard — pointing tests at the dev
|
||||
# Postgres would truncate it (the disaster Fable #339 exists to prevent).
|
||||
# Postgres would truncate it.
|
||||
#
|
||||
# The key stays `integration` with no `name:` (rule 80): act_runner derives
|
||||
# the service container's name from the job's display name.
|
||||
# The key stays `integration` with no `name:`: act_runner derives the
|
||||
# service container's name from the job's display name.
|
||||
#
|
||||
# `web/build/` has a committed placeholder index.html so go:embed succeeds
|
||||
# without the SPA being built first.
|
||||
@@ -195,7 +181,7 @@ jobs:
|
||||
POSTGRES_USER: minstrel
|
||||
POSTGRES_PASSWORD: minstrel
|
||||
POSTGRES_DB: minstrel_test
|
||||
# No `ports:` — the runner shares the operator's dev compose
|
||||
# No `ports:` — the runner shares the dev compose
|
||||
# Docker daemon; publishing a fixed host port collides.
|
||||
|
||||
steps:
|
||||
@@ -209,13 +195,13 @@ jobs:
|
||||
# mounted docker socket. act_runner attaches the job
|
||||
# container and its service container(s) to a shared per-job
|
||||
# network, so scope discovery to a postgres that sits on a
|
||||
# network THIS job container is also on. The old
|
||||
# `--filter name=integration` matched EVERY concurrent
|
||||
# integration run's postgres (a dev push + the main-merge run
|
||||
# overlap → 2 candidates → false "expected exactly 1" abort).
|
||||
# The operator's dev compose `minstrel-postgres-*` is never on
|
||||
# this job's network; skip it explicitly as belt-and-suspenders
|
||||
# (a wrong target would truncate real data).
|
||||
# network THIS job container is also on. A name filter alone
|
||||
# would match EVERY concurrent integration run's postgres (a dev
|
||||
# push and a main-merge run overlapping give 2 candidates and a
|
||||
# false "expected exactly 1" abort). The dev compose
|
||||
# `minstrel-postgres-*` is never on this job's network; skip it
|
||||
# explicitly as belt-and-suspenders (a wrong target would
|
||||
# truncate real data).
|
||||
SELF=$(cat /etc/hostname)
|
||||
SELF_NETS=$(docker inspect -f '{{range $k,$v := .NetworkSettings.Networks}}{{$k}} {{end}}' "$SELF")
|
||||
test -n "$SELF_NETS"
|
||||
@@ -236,11 +222,11 @@ jobs:
|
||||
export MINSTREL_TEST_DATABASE_URL="postgres://minstrel:minstrel@${PG_IP}:5432/minstrel_test?sslmode=disable"
|
||||
|
||||
# Wait for Postgres to accept connections. Asked of the service
|
||||
# container itself: the run: shell is dash (rule 81), where the
|
||||
# old `/dev/tcp` probe never connects and the loop silently
|
||||
# burned its full two minutes on every run.
|
||||
# container itself: the run: shell is dash, where a `/dev/tcp`
|
||||
# probe never connects and the loop would silently burn its full
|
||||
# two minutes.
|
||||
#
|
||||
# Over TCP (-h 127.0.0.1), not the unix socket (#5426). On first
|
||||
# Over TCP (-h 127.0.0.1), not the unix socket. On first
|
||||
# boot the image's entrypoint runs initdb under a temporary server
|
||||
# that listens on the socket only, then stops it and starts the
|
||||
# real one. A socket probe can catch the temporary server, and the
|
||||
@@ -267,7 +253,7 @@ jobs:
|
||||
# synchronous_commit is user-context, so pg_reload_conf() picks
|
||||
# all three up with no restart.
|
||||
# Non-fatal: a failure degrades to "slower", never red CI. But
|
||||
# slower is ~15x on internal/api (#5426), so retry a few times and
|
||||
# slower is ~15x on internal/api, so retry a few times and
|
||||
# print what took effect.
|
||||
relaxed=""
|
||||
for i in 1 2 3 4 5; do
|
||||
@@ -291,10 +277,10 @@ jobs:
|
||||
# every integration package TRUNCATEs the one shared test DB;
|
||||
# concurrent package binaries → TRUNCATE deadlocks. Serialize
|
||||
# package execution (the documented local invocation too).
|
||||
# -timeout 20m: internal/api alone takes ~6.5 min under -race on
|
||||
# an idle runner, and a dev and a main run sharing the runner
|
||||
# pushed it past go test's default 10m (run 8368, 600.016s, the
|
||||
# running test 2s old — nothing hung).
|
||||
# -timeout 20m: internal/api alone takes several minutes under
|
||||
# -race on an idle runner, and a dev and a main run sharing the
|
||||
# runner can push it past go test's default 10m with nothing
|
||||
# hung.
|
||||
MINSTREL_DATABASE_URL="$MINSTREL_TEST_DATABASE_URL" go run ./cmd/minstrel migrate
|
||||
go test -p 1 -race -timeout 20m ./...
|
||||
|
||||
@@ -314,11 +300,8 @@ jobs:
|
||||
- name: Install deps
|
||||
run: npm ci
|
||||
|
||||
# The whole tree, build and test tooling included. Until #5021 this
|
||||
# audited only what ships to browsers (`--omit=dev`), because vite,
|
||||
# vitest, tailwind and kit carried advisories that needed major
|
||||
# upgrades. Those upgrades landed and the full tree audits clean, so
|
||||
# the tooling that builds the shipped bundle is held to the same bar.
|
||||
# The whole tree, build and test tooling included: the tooling that
|
||||
# builds the shipped bundle is held to the same bar as the bundle.
|
||||
- name: npm audit (all dependencies)
|
||||
run: npm audit --audit-level=moderate
|
||||
|
||||
@@ -329,8 +312,8 @@ jobs:
|
||||
run: npm test
|
||||
|
||||
android:
|
||||
# Using flutter-ci runner label because it's the only proven-working
|
||||
# label with docker that can pull our container.image.
|
||||
# The flutter-ci runner label is the only proven-working label with
|
||||
# docker that can pull our container.image.
|
||||
runs-on: flutter-ci
|
||||
container:
|
||||
image: git.fabledsword.com/bvandeusen/ci-android:36
|
||||
@@ -376,11 +359,10 @@ jobs:
|
||||
- name: Unit tests
|
||||
run: ./gradlew testDebugUnitTest
|
||||
|
||||
# No debug APK is built or uploaded here. Main used to upload a
|
||||
# debug-signed app-debug.apk: a build signed by a key regenerated in
|
||||
# every container, which no install can update (family idea #5103,
|
||||
# practice 2). Phones get builds from android-release, signed with
|
||||
# the one release key, on dev and on tags.
|
||||
# No debug APK is built or uploaded here: a debug build is signed by a
|
||||
# key regenerated in every container, which no install can update.
|
||||
# Phones get builds from android-release, signed with the one release
|
||||
# key, on dev and on tags.
|
||||
|
||||
# Known vulnerabilities in the Go code and the standard library it is built
|
||||
# with. Runs in the SAME image the Dockerfile's builder stage uses, so the
|
||||
@@ -388,7 +370,7 @@ jobs:
|
||||
# the ci-go image carries its own Go and would be checking a different
|
||||
# toolchain. Keep this image and the Dockerfile's builder in step.
|
||||
#
|
||||
# govulncheck is fetched at CI time, unpinned (rule 154): the vulnerability
|
||||
# govulncheck is fetched at CI time, unpinned: the vulnerability
|
||||
# database and the tool that reads it should both be current.
|
||||
govulncheck:
|
||||
runs-on: go-ci
|
||||
@@ -397,7 +379,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
# Plain git, not actions/checkout: that action runs on node, which the
|
||||
# golang image does not carry. This step is dash (rule 81).
|
||||
# golang image does not carry. This step is dash.
|
||||
- name: Checkout
|
||||
env:
|
||||
TOKEN: ${{ github.token }}
|
||||
@@ -418,11 +400,14 @@ jobs:
|
||||
# ------------------------------------------------------------ artifacts --
|
||||
|
||||
android-release:
|
||||
name: Build signed APK (releases and dev)
|
||||
# Also builds on `dev`, which is what makes a test channel possible at
|
||||
# all. Without it the only way to get a build onto a phone was to cut a
|
||||
# release, which quietly turns `main` into the staging area.
|
||||
if: startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/dev'
|
||||
name: Build signed APK
|
||||
# Builds on every ref, so each channel's image carries the app from its
|
||||
# own commit: `dev` for the test channel, `main` for stable phones, and a
|
||||
# tag for the copy attached to its Release.
|
||||
if: >-
|
||||
startsWith(github.ref, 'refs/tags/v')
|
||||
|| github.ref == 'refs/heads/dev'
|
||||
|| github.ref == 'refs/heads/main'
|
||||
runs-on: flutter-ci
|
||||
container:
|
||||
image: git.fabledsword.com/bvandeusen/ci-android:36
|
||||
@@ -453,7 +438,7 @@ jobs:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
# Full history. The version name now reads only the tip commit's
|
||||
# Full history. The version name reads only the tip commit's
|
||||
# timestamp, so a shallow clone would technically serve — but this
|
||||
# job derives a value that ships to devices, and a shallow checkout
|
||||
# changes what git-derived values resolve to WITHOUT failing. The
|
||||
@@ -470,7 +455,7 @@ jobs:
|
||||
# The derivation lives in ci/version.sh, not here, so it can be
|
||||
# executed by a test on every push. Anything inline in this file is
|
||||
# unverifiable until a release is already running.
|
||||
out="$(ci/version.sh HEAD)"
|
||||
out="$(ci/version.sh --apk HEAD)"
|
||||
printf '%s\n' "${out}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# The channel is a property of the LANE, not of the commit, which is
|
||||
@@ -487,9 +472,9 @@ jobs:
|
||||
|
||||
# Checked BEFORE the expensive work, not after it. "Attach APK to gitea
|
||||
# Release" below resolves the release by tag and fails if it is absent —
|
||||
# but that is the final step, so a tag pushed without a release built an
|
||||
# APK for several minutes first and only then discovered it had nowhere to
|
||||
# put it. Same check, seconds in instead of minutes.
|
||||
# but that is the final step, so a tag pushed without a release would
|
||||
# build an APK for several minutes first and only then find it has
|
||||
# nowhere to put it. Same check, seconds in instead of minutes.
|
||||
#
|
||||
# Releases are normally created through the API (which creates the tag and
|
||||
# the release together, so this passes). A bare `git push origin vX` is the
|
||||
@@ -549,16 +534,15 @@ jobs:
|
||||
# secret) reaches no installed phone. The certificate's digest is
|
||||
# pinned below; it is public, not a secret. Gradle signs with the
|
||||
# release key or leaves the APK unsigned, and an unsigned build fails
|
||||
# here too, as there is no app-release.apk to verify (family idea
|
||||
# #5103, practice 3). apksigner, not keytool: keytool prints nothing
|
||||
# for a v2-only APK.
|
||||
# here too, as there is no app-release.apk to verify. apksigner, not
|
||||
# keytool: keytool prints nothing for a v2-only APK.
|
||||
#
|
||||
# Rotating the key on purpose means every install must be removed and
|
||||
# reinstalled; change the digest here in the same commit.
|
||||
- name: The APK carries the release key
|
||||
shell: bash
|
||||
env:
|
||||
# CN=Minstrel, O=FabledSword. Read from run 8446 (#5116).
|
||||
# CN=Minstrel, O=FabledSword.
|
||||
RELEASE_CERT_SHA256: 43d183307bc46b821789d90444a960b137f78f2166ff431efb2406d0fceaf612
|
||||
run: |
|
||||
set -euo pipefail
|
||||
@@ -580,11 +564,10 @@ jobs:
|
||||
fi
|
||||
|
||||
- name: Upload APK as workflow artifact
|
||||
# Stock action (snippet #2271) — never @v3, which uploads something Gitea
|
||||
# will never serve back. This is the producing half of a pair:
|
||||
# image-release downloads `minstrel-apk` below. Any upload v4+ pairs with
|
||||
# any download v4+ on this forge (every combination tested 2026-09-10,
|
||||
# Scribe spike #3843), so the two pins need not move together.
|
||||
# Stock action — never @v3, which uploads something Gitea will never
|
||||
# serve back. This is the producing half of a pair: image-release
|
||||
# downloads `minstrel-apk` below. Any upload v4+ pairs with any
|
||||
# download v4+ on this forge, so the two pins need not move together.
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: minstrel-apk
|
||||
@@ -621,9 +604,9 @@ jobs:
|
||||
path: release-apk/
|
||||
|
||||
- name: Attach APK to gitea Release
|
||||
# Tag releases only. A dev build has no Release to hang assets on and
|
||||
# does not need one — the :dev image bundles the APK, and the server
|
||||
# serves it from /api/client/apk like any other.
|
||||
# Tag releases only. A branch build has no Release to hang assets on
|
||||
# and does not need one — its image bundles the APK, and the server
|
||||
# serves it from /api/client/apk.
|
||||
shell: bash
|
||||
env:
|
||||
CI_TOKEN: ${{ secrets.CI_TOKEN }}
|
||||
@@ -687,10 +670,9 @@ jobs:
|
||||
|
||||
image-release:
|
||||
name: Build + push container image
|
||||
# Every lane must have SUCCEEDED, each named here (rule 177). Then the
|
||||
# APK: tag and dev pushes build one and it must have succeeded; main
|
||||
# pushes skip android-release and bundle the latest release's APK
|
||||
# instead, so for main alone a skipped android-release is expected.
|
||||
# Every lane must have SUCCEEDED, each named here, and so must the APK
|
||||
# build: every ref bundles the APK built from its own commit, so an
|
||||
# image without one would move a channel with no app for phones to take.
|
||||
needs: [go, integration, web, android, govulncheck, android-release]
|
||||
if: >-
|
||||
${{
|
||||
@@ -700,8 +682,7 @@ jobs:
|
||||
&& needs.web.result == 'success'
|
||||
&& needs.android.result == 'success'
|
||||
&& needs.govulncheck.result == 'success'
|
||||
&& (needs.android-release.result == 'success'
|
||||
|| (needs.android-release.result == 'skipped' && github.ref == 'refs/heads/main')) }}
|
||||
&& needs.android-release.result == 'success' }}
|
||||
runs-on: go-ci
|
||||
container:
|
||||
image: git.fabledsword.com/bvandeusen/ci-go:1.26
|
||||
@@ -713,15 +694,13 @@ jobs:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
# Full history, and rule 149 names this specifically: any job that
|
||||
# DERIVES the version name needs it, because a shallow clone changes
|
||||
# what git-derived values resolve to WITHOUT failing — a too-low
|
||||
# value, silently, with every lane green.
|
||||
# Full history: any job that DERIVES the version name needs it,
|
||||
# because a shallow clone changes what git-derived values resolve to
|
||||
# WITHOUT failing — a too-low value, silently, with every lane green.
|
||||
#
|
||||
# This job was depth-1 while it took the version from GITHUB_REF. It
|
||||
# now runs ci/version.sh itself, because with :<version> image tags
|
||||
# gone the server's self-reported version is the only thing that says
|
||||
# which build an image is.
|
||||
# This job runs ci/version.sh itself: with no :<version> image tags,
|
||||
# the server's self-reported version is the only thing that says which
|
||||
# build an image is.
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Detect buildable project
|
||||
@@ -743,21 +722,16 @@ jobs:
|
||||
set -euo pipefail
|
||||
|
||||
# THE VERSION, and it is derived the same way on every ref — the
|
||||
# branch decides the CHANNEL, never the version (family rule 149).
|
||||
# branch decides the CHANNEL, never the version.
|
||||
#
|
||||
# This used to be three different things: the literal string "main"
|
||||
# on main, "dev" on dev, and the tag name on a tag. None of them
|
||||
# ordered, and the first two were the same string forever — two dev
|
||||
# images eight weeks apart were indistinguishable in the UI. That
|
||||
# mattered little while :vYYYY.MM.DD.HHMM existed to identify a
|
||||
# build; with version image tags gone, this IS how an operator tells
|
||||
# which build a container is running.
|
||||
# A per-ref string ("main", "dev", the tag name) would not order, and
|
||||
# "dev" would be the same string forever — two dev images eight weeks
|
||||
# apart indistinguishable in the UI. With no version image tags, this
|
||||
# is how an admin tells which build a container is running.
|
||||
#
|
||||
# `sed -n s///p` rather than `grep`: it exits 0 when nothing matches,
|
||||
# so the empty check below is actually reachable. A grep here would
|
||||
# kill the step at the assignment under the runner's pipefail — the
|
||||
# exact bug that took down the first main build after the version
|
||||
# rework.
|
||||
# kill the step at the assignment under the runner's pipefail.
|
||||
VERSION="$(ci/version.sh HEAD | sed -n 's/^name=//p')"
|
||||
if [ -z "${VERSION}" ]; then
|
||||
echo "::error::could not derive a build version from ci/version.sh"
|
||||
@@ -770,13 +744,14 @@ jobs:
|
||||
# The tag build exists to produce the signed APK and attach it to
|
||||
# the release; the image it rebuilds is the SAME SOURCE as the main
|
||||
# build minutes earlier, differing only in which APK is baked in.
|
||||
# Rule 145 is explicit about that case: when the same source is
|
||||
# rebuilt with different contents, publish the moving channel tag
|
||||
# and never a commit-addressable one.
|
||||
# When the same source is rebuilt with different contents,
|
||||
# publish the moving channel tag and never a commit-addressable
|
||||
# one.
|
||||
#
|
||||
# :latest must move here rather than waiting for the next main
|
||||
# push, or the channel would carry the PREVIOUS release's APK
|
||||
# indefinitely — a channel that cannot refresh itself (rule 146).
|
||||
# :latest moves here so the server hands out the same APK build
|
||||
# that is attached to the Release: a phone that installed from the
|
||||
# Release page and one that updated in-app hold one build, with one
|
||||
# ordering key. Cut a release on main's tip, as :latest follows it.
|
||||
CHANNEL=stable
|
||||
echo "args=-t ${IMAGE}:latest" >> "$GITHUB_OUTPUT"
|
||||
echo "::notice::Release build ${VERSION}: refreshing :latest around the new APK"
|
||||
@@ -790,10 +765,9 @@ jobs:
|
||||
echo "args=-t ${IMAGE}:dev" >> "$GITHUB_OUTPUT"
|
||||
echo "::notice::Dev-branch build ${VERSION}: :dev"
|
||||
else
|
||||
# The production line: :latest tracks main's tip (rule 147) and
|
||||
# :<sha> is the rollback unit (rule 145). Full 40-char SHA, matching
|
||||
# the family's other repos, so a rollback target is addressable
|
||||
# straight from the commit anyone is reading.
|
||||
# The production line: :latest tracks main's tip and :<sha> is
|
||||
# the rollback unit. Full 40-char SHA, so a rollback target is
|
||||
# addressable straight from the commit anyone is reading.
|
||||
CHANNEL=stable
|
||||
echo "args=-t ${IMAGE}:latest -t ${IMAGE}:${GITHUB_SHA}" >> "$GITHUB_OUTPUT"
|
||||
echo "::notice::Main-branch build ${VERSION}: :latest + :${GITHUB_SHA}"
|
||||
@@ -810,25 +784,19 @@ jobs:
|
||||
| docker login git.fabledsword.com -u "${{ github.actor }}" --password-stdin
|
||||
|
||||
- name: Download signed APK artifact
|
||||
# Tag and dev pushes — android-release just produced this. Only `main`
|
||||
# takes the "Bundle latest release APK" path below, because it is the
|
||||
# one ref that moves a channel without building an APK of its own.
|
||||
if: >-
|
||||
steps.guard.outputs.ready == 'true' &&
|
||||
(startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/dev')
|
||||
# android-release just produced this, on every ref.
|
||||
if: steps.guard.outputs.ready == 'true'
|
||||
# Consuming half of the pair: stock download-artifact, which works here for
|
||||
# the same reason as the upload (gitea/runner 3.x edits the GHES refusal
|
||||
# out of the bundle; snippet #2271). v8 runs on node24, which every
|
||||
# CI-runner image carries — the runner uses the image's own node.
|
||||
# out of the bundle). v8 runs on node24, which every CI-runner image
|
||||
# carries — the runner uses the image's own node.
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: minstrel-apk
|
||||
path: client/
|
||||
|
||||
- name: Stage bundled APK + version sidecar
|
||||
if: >-
|
||||
steps.guard.outputs.ready == 'true' &&
|
||||
(startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/dev')
|
||||
if: steps.guard.outputs.ready == 'true'
|
||||
shell: bash
|
||||
env:
|
||||
# All three pulled from android-release's outputs so the sidecar the
|
||||
@@ -849,65 +817,6 @@ jobs:
|
||||
cat client/minstrel.apk.version
|
||||
ls -lh client/
|
||||
|
||||
- name: Bundle latest release APK (non-tag :latest builds)
|
||||
# Main pushes don't build an APK, but they DO move :latest — so
|
||||
# without this the in-app update channel would vanish from :latest
|
||||
# until the next tag. Pull the most-recent release's signed APK and
|
||||
# the sidecar published beside it, so what the server reports is what
|
||||
# that build actually recorded rather than something re-derived here.
|
||||
# Degrades to an empty client/ (404 update channel) — never a wrong
|
||||
# version — if no release or APK asset can be resolved. That
|
||||
# degradation only actually works because the greps below carry
|
||||
# `|| true`; under the runner's default pipefail a non-matching grep
|
||||
# kills the step instead of falling through to the empty-case branch.
|
||||
if: steps.guard.outputs.ready == 'true' && github.ref == 'refs/heads/main'
|
||||
shell: bash
|
||||
env:
|
||||
CI_TOKEN: ${{ secrets.CI_TOKEN }}
|
||||
run: |
|
||||
set -eu
|
||||
REPO="${GITHUB_REPOSITORY}"
|
||||
REL_JSON="$(curl -fsSL -H "Authorization: token ${CI_TOKEN}" \
|
||||
"https://git.fabledsword.com/api/v1/repos/${REPO}/releases/latest" || true)"
|
||||
if [ -z "${REL_JSON}" ]; then
|
||||
echo "::notice::no published release — image ships without bundled APK"; exit 0
|
||||
fi
|
||||
# `|| true` on every one of these, and it is load-bearing rather
|
||||
# than defensive habit. The runner already invokes this shell as
|
||||
# `bash -e -o pipefail`, so a pipeline whose grep matches NOTHING
|
||||
# exits non-zero even though `head` succeeded — and the step dies at
|
||||
# the assignment, before ever reaching the `if` written to handle the
|
||||
# empty case. Every "degrades gracefully" branch below is unreachable
|
||||
# without this.
|
||||
TAG="$(printf '%s' "${REL_JSON}" | grep -oP '"tag_name":\s*"\K[^"]+' | head -1)" || true
|
||||
APK_URL="$(printf '%s' "${REL_JSON}" | grep -oP '"browser_download_url":\s*"\K[^"]+' | grep -E '\.apk$' | head -1)" || true
|
||||
if [ -z "${TAG}" ] || [ -z "${APK_URL}" ]; then
|
||||
echo "::notice::latest release '${TAG:-?}' has no APK asset — image ships without bundled APK"; exit 0
|
||||
fi
|
||||
curl -fsSL -H "Authorization: token ${CI_TOKEN}" -o client/minstrel.apk "${APK_URL}"
|
||||
|
||||
# Take the version the release RECORDED rather than recomputing it.
|
||||
# This used to re-derive the name from the tagged commit, which meant
|
||||
# the formula lived in two files that had to be kept in step, and it
|
||||
# could only ever recover the name — the ordering key is build-time
|
||||
# minutes and does not exist anywhere after that build ends.
|
||||
SIDECAR_URL="$(printf '%s' "${REL_JSON}" | grep -oP '"browser_download_url":\s*"\K[^"]+' | grep -E '\.apk\.version$' | head -1)" || true
|
||||
if [ -n "${SIDECAR_URL}" ]; then
|
||||
curl -fsSL -H "Authorization: token ${CI_TOKEN}" -o client/minstrel.apk.version "${SIDECAR_URL}"
|
||||
cat client/minstrel.apk.version
|
||||
else
|
||||
# Releases published before sidecars were attached. Their name is
|
||||
# still recoverable from the tag, but their ordering key genuinely
|
||||
# is not — so it is reported ABSENT rather than guessed. A wrong
|
||||
# key is an install the platform refuses; an absent one just tells
|
||||
# the client to fall back to comparing names, which is exactly
|
||||
# what those builds already do.
|
||||
echo "::notice::release ${TAG} predates the version sidecar — bundling with name only, no ordering key"
|
||||
printf '{"name":"%s","code":null,"channel":"stable"}\n' "${TAG#v}" > client/minstrel.apk.version
|
||||
fi
|
||||
echo "::notice::bundled release APK from ${TAG}"
|
||||
ls -lh client/
|
||||
|
||||
- name: Build and push
|
||||
if: steps.guard.outputs.ready == 'true'
|
||||
# --pull: the Dockerfile's base images are floating tags (golang:1.26,
|
||||
@@ -924,18 +833,15 @@ jobs:
|
||||
# Verifies a tag release actually ended up complete, and names the specific
|
||||
# thing that's missing if not.
|
||||
#
|
||||
# Added 2026-08-07 after v2026.08.07 was re-cut. The android-release job never
|
||||
# started — no log was written at all — so all eight of its steps reported
|
||||
# `failure` with none executed and image-release showed `skipped`. The run was
|
||||
# red, but the *release page rendered fine*, and `main`'s own push build had
|
||||
# already moved `:latest`, so the code was deployable and nothing looked
|
||||
# obviously wrong. The release was simply missing its APK and its image,
|
||||
# which is easy to skim past.
|
||||
# A release can be incomplete while looking fine. If android-release never
|
||||
# starts (a runner failing to launch), its steps all report `failure` with
|
||||
# none executed and image-release shows `skipped`. The run is red, but the
|
||||
# release page renders and main's own push build has already moved
|
||||
# `:latest`, so a release missing its APK and its image is easy to skim
|
||||
# past.
|
||||
#
|
||||
# This job cannot prevent that (the cause was a runner failing to launch, not
|
||||
# anything in this file). What it does is turn an incomplete release into an
|
||||
# explicit, named error instead of eight mystery step failures — so the
|
||||
# consequence is legible without having to infer it.
|
||||
# This job cannot prevent that; it turns an incomplete release into an
|
||||
# explicit, named error instead of a row of mystery step failures.
|
||||
#
|
||||
# `if: always()` is the whole point: it has to report precisely when the jobs
|
||||
# above did NOT succeed.
|
||||
@@ -977,22 +883,16 @@ jobs:
|
||||
echo "::notice::APK attached: ${APK}"
|
||||
|
||||
# The other half. Checking only the APK would report success on a release
|
||||
# whose image push failed — which is precisely the second thing that was
|
||||
# missing when v2026.08.07 had to be re-cut. `always()` on this job means
|
||||
# it runs even when image-release failed, so without this the guard would
|
||||
# cheerfully verify an incomplete release.
|
||||
# whose image push failed. `always()` on this job means it runs even when
|
||||
# image-release failed, so without this the guard would cheerfully verify
|
||||
# an incomplete release.
|
||||
#
|
||||
# This asserted `:${TAG}` — the :vYYYY.MM.DD.HHMM image — until
|
||||
# 2026-09-10. Version image tags are no longer published (rule 145), so
|
||||
# that assertion would now fail every release for a tag nothing mints.
|
||||
# The rollback target it was really protecting is the :<sha> image, which
|
||||
# main's own build published for this same commit before the tag was cut.
|
||||
#
|
||||
# Checking it here earns its keep twice over: it still catches an image
|
||||
# push that silently did not happen, and it additionally proves the
|
||||
# ORDERING — a tag cut on a commit whose main build never completed has
|
||||
# no rollback target, and that is worth failing on rather than
|
||||
# discovering during an incident.
|
||||
# The image checked is the :<sha> rollback target, which main's own build
|
||||
# published for this same commit before the tag was cut (there are no
|
||||
# version image tags). It catches an image push that silently did not
|
||||
# happen, and it proves the ORDERING — a tag cut on a commit whose main
|
||||
# build never completed has no rollback target, and that is worth failing
|
||||
# on rather than discovering during an incident.
|
||||
- name: Rollback image must exist for the tagged commit
|
||||
shell: bash
|
||||
run: |
|
||||
|
||||
+6
-9
@@ -12,13 +12,11 @@
|
||||
# Test binary, built with `go test -c`
|
||||
*.test
|
||||
|
||||
# `make build` output. bin/minstrel was tracked until 2026-09-10 — an 18 MB
|
||||
# binary committed by accident, last refreshed by a commit about web test
|
||||
# mocks, and re-dirtied by every local build since.
|
||||
# `make build` output — an 18 MB binary that is never committed.
|
||||
bin/
|
||||
|
||||
# Bundled Android APK + version sidecar (#397). Populated by CI for
|
||||
# tag releases; never committed. README in client/ explains the flow.
|
||||
# Bundled Android APK + version sidecar. Populated by CI on every image
|
||||
# build; never committed. README in client/ explains the flow.
|
||||
client/minstrel.apk
|
||||
client/minstrel.apk.version
|
||||
|
||||
@@ -44,10 +42,9 @@ go.work.sum
|
||||
docs/superpowers/
|
||||
|
||||
# Per-machine Claude Code settings + remember-skill memory artifacts +
|
||||
# project-level Claude/AI instruction files. All operator-scoped; the
|
||||
# canonical project memory lives under ~/.claude/projects/ outside the
|
||||
# repo. CLAUDE.md/AGENTS.md/GEMINI.md stay on the operator's machine
|
||||
# only — they're tool-specific working notes, not project artifacts.
|
||||
# project-level Claude/AI instruction files. All per-machine;
|
||||
# CLAUDE.md/AGENTS.md/GEMINI.md are tool-specific working notes, not
|
||||
# project artifacts.
|
||||
.claude/
|
||||
.remember/
|
||||
CLAUDE.md
|
||||
|
||||
+12
-11
@@ -19,11 +19,10 @@ ENV CGO_ENABLED=0
|
||||
# (YYYY.MM.DD.HHMM) and the lane's channel; a local `docker build` falls back
|
||||
# to "dev"/"local". Both are surfaced at /healthz.
|
||||
#
|
||||
# These are two values on purpose (family rule 149): the same commit built on
|
||||
# dev and on main reports the same NAME and differs only in CHANNEL. Folding
|
||||
# the channel into the version string is what the rule forbids — the version
|
||||
# used to BE the channel word here ("main"/"dev"), which meant two dev images
|
||||
# eight weeks apart were indistinguishable.
|
||||
# These are two values on purpose: the same commit built on dev and on main
|
||||
# reports the same NAME and differs only in CHANNEL. Folding the channel
|
||||
# into the version string would make two dev images eight weeks apart
|
||||
# indistinguishable.
|
||||
ARG MINSTREL_VERSION=dev
|
||||
ARG MINSTREL_CHANNEL=local
|
||||
RUN go build -trimpath \
|
||||
@@ -36,8 +35,8 @@ FROM debian:bookworm-slim
|
||||
# ffmpeg: duration probes and the exact-tier audio hash (a SHA-256 of the
|
||||
# encoded audio packets, so no decode). libchromaprint-tools: fpcalc, the
|
||||
# acoustic fingerprint that tells the same recording at two bitrates apart
|
||||
# from two different recordings (M400). Both are baked in at build time so a
|
||||
# deployed instance never fetches either (rule 164); fpcalc is shelled out
|
||||
# from two different recordings. Both are baked in at build time so a
|
||||
# deployed instance never fetches either; fpcalc is shelled out
|
||||
# rather than bound because CGO_ENABLED=0 above rules out cgo.
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates ffmpeg libchromaprint-tools \
|
||||
@@ -57,10 +56,12 @@ COPY config.example.yaml /etc/smartmusic/config.yaml
|
||||
RUN mkdir -p /app/data /app/client && chown -R minstrel:minstrel /app
|
||||
WORKDIR /app
|
||||
|
||||
# In-app update channel (#397). client/ in the build context holds
|
||||
# minstrel.apk + minstrel.apk.version (populated by release.yml on tag
|
||||
# pushes; .gitkeep + README otherwise). Endpoints return 404 when the
|
||||
# APK files aren't present, so non-tag images degrade gracefully.
|
||||
# In-app update channel. client/ in the build context holds
|
||||
# minstrel.apk + minstrel.apk.version, which release.yml fills on every
|
||||
# build (dev and tag pushes bundle their own APK, main bundles the latest
|
||||
# release's); a local build has only .gitkeep + README. Endpoints return
|
||||
# 404 when the APK files aren't present, so such an image degrades
|
||||
# gracefully.
|
||||
COPY --chown=minstrel:minstrel client/ /app/client/
|
||||
|
||||
USER minstrel
|
||||
|
||||
@@ -1,9 +1,661 @@
|
||||
MIT License
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (c) 2026 bvandeusen
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
Preamble
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
<p align="center">A self-hosted music server that picks what to play next.</p>
|
||||
|
||||
Minstrel serves your music library to the web, to its own Android app, and to any Subsonic client. Shuffle, radio, likes and play history are worked out on the server, so every device gets the same mixes and the same history. It can also find, download and file the albums you want, through a search service and a download client you run yourself. It is for anyone who keeps their own music collection and wants it to sound like more than a random shuffle.
|
||||
Minstrel serves your music library to the web, to its own Android app, and to any Subsonic client. Shuffle, radio, likes and play history are worked out on the server, so every device gets the same mixes and the same history. It is for anyone who keeps their own music collection and wants it to sound like more than a random shuffle.
|
||||
|
||||
<a href="docs/screenshots/home.png"><img src="docs/screenshots/home.png" width="820" alt="Minstrel home — your library at a glance"></a>
|
||||
|
||||
@@ -49,9 +49,7 @@ Open `http://<host>:4533/register` and create the first account with that setup
|
||||
1. **Let the first scan finish.** Minstrel scans the library on startup. Watch it, or scan again, on the **Admin** page (`/admin`). Later scans only pick up what changed.
|
||||
2. **Install the Android app.** In **Settings** (`/settings`), the *Install the Android app* card downloads the app this server ships. It updates itself from your server after that.
|
||||
3. **Invite the household.** In **Admin › Users** (`/admin/users`), make an invite token or turn on open registration. Each person gets their own likes, history and recommendations.
|
||||
4. **Optional: connect services.** Add a search service and a download client in **Admin › Acquisition** (`/admin/acquisition`). Each person adds their own ListenBrainz token in **Settings › Connections**.
|
||||
|
||||
<a href="docs/screenshots/library-scan.png"><img src="docs/screenshots/library-scan.png" width="820" alt="The Admin page, where the library scan runs and reports progress"></a>
|
||||
4. **Optional: connect ListenBrainz.** Each person adds their own ListenBrainz token in **Settings › Connections**.
|
||||
|
||||
## Configuration
|
||||
|
||||
@@ -64,11 +62,11 @@ The quick start sets everything that's required. These are the settings people m
|
||||
| `MINSTREL_BRANDING_APP_NAME` | The name shown in the header, the browser tab and link previews. |
|
||||
| `MINSTREL_LOG_LEVEL` | `debug`, `info`, `warn` or `error`. |
|
||||
|
||||
Search services, download clients, ListenBrainz, email and recommendation tuning are set in the web UI and take effect without a restart. The full file-based surface is in [`config.example.yaml`](./config.example.yaml); to use it, mount your copy at `/etc/smartmusic/config.yaml`.
|
||||
ListenBrainz, email, metadata sources and recommendation tuning are set in the web UI and take effect without a restart. The full file-based surface is in [`config.example.yaml`](./config.example.yaml); to use it, mount your copy at `/etc/smartmusic/config.yaml`.
|
||||
|
||||
## Setup pitfalls
|
||||
|
||||
- **The library mount has to be writable by uid 1000.** Minstrel files the albums it downloads into the library, and it deletes a file when an admin asks it to. It never moves, renames or retags files that were already there. Mount the library `:ro` to forbid writes: those actions then refuse and say why.
|
||||
- **The library mount has to be writable by uid 1000.** Minstrel deletes a file when an admin asks it to, and when the duplicate resolver removes a copy. It never moves, renames or retags your files. Mount the library `:ro` to forbid writes: those actions then refuse and say why.
|
||||
- **`MINSTREL_LIBRARY_SCAN_PATHS` names the path inside the container** (`/music`), not the folder on your host.
|
||||
- **On the internet, put it behind HTTPS.** Plain `http://` is fine on a network you trust. For a public server, bind the port to `127.0.0.1` and put a reverse proxy in front: see [docs/hosting.md](docs/hosting.md).
|
||||
|
||||
@@ -103,11 +101,6 @@ Every image carries a signed Android app, all with the same key, so a phone can
|
||||
- Duplicates, missing files and suspect copies are found and listed under **Collection** for an admin to fix.
|
||||
- Missing album art and MusicBrainz ids are filled in automatically.
|
||||
|
||||
**Getting music**
|
||||
- A wanted list: requests from the household, artists you follow, and albums whose files went missing.
|
||||
- Minstrel searches the indexers you configure, hands the best release to your download client, checks what arrives against MusicBrainz, tags it, and files it. A better copy replaces a poor one.
|
||||
- Off until you add a search service and a download client.
|
||||
|
||||
**Clients and accounts**
|
||||
- A full web app, built into the server.
|
||||
- A native Android app that ships inside the server image, keeps playing what it has cached when the server is out of reach, and updates itself from your server.
|
||||
@@ -116,13 +109,11 @@ Every image carries a signed Android app, all with the same key, so a phone can
|
||||
|
||||
## Scope and responsible use
|
||||
|
||||
Minstrel indexes the files you point it at and streams them to your own clients. It ships no indexers, no trackers, no torrent, Usenet or NZB engine of its own, and no DRM circumvention.
|
||||
Minstrel indexes the files you point it at and streams them to your own clients. It does not find or download music, and it does no DRM circumvention.
|
||||
|
||||
Getting music is optional and does nothing until you configure it. It searches only the search service (Prowlarr or a Torznab indexer) and the download client (qBittorrent) you add yourself.
|
||||
What you put in your library is your responsibility. Copyright law applies to your collection as it does to any other software that plays a file; please respect it, and the terms of any service you connect.
|
||||
|
||||
What you put in your library, and the sources you configure, are your responsibility. Copyright law applies to your collection as it does to any other software that plays a file; please respect it, and the terms of any service you connect.
|
||||
|
||||
Minstrel is not affiliated with or endorsed by ListenBrainz, MusicBrainz, Prowlarr, qBittorrent or Subsonic.
|
||||
Minstrel is not affiliated with or endorsed by ListenBrainz, MusicBrainz or Subsonic.
|
||||
|
||||
## Development
|
||||
|
||||
@@ -136,4 +127,6 @@ How accounts and sessions are protected: [docs/security.md](docs/security.md).
|
||||
|
||||
## License
|
||||
|
||||
MIT. See [LICENSE](./LICENSE).
|
||||
GNU Affero General Public License v3.0. See [LICENSE](./LICENSE).
|
||||
|
||||
You can run, change and share Minstrel freely. If you run a changed copy that other people use over a network, you must offer those people the source of your changes.
|
||||
|
||||
@@ -24,6 +24,7 @@ import androidx.core.content.ContextCompat
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.navigation.NavHostController
|
||||
import androidx.navigation.compose.rememberNavController
|
||||
import com.fabledsword.minstrel.auth.AuthStore
|
||||
import com.fabledsword.minstrel.auth.ui.AuthGateViewModel
|
||||
@@ -33,6 +34,7 @@ import com.fabledsword.minstrel.connectivity.ServerHealth
|
||||
import com.fabledsword.minstrel.connectivity.NetworkStatusController
|
||||
import com.fabledsword.minstrel.nav.DetailSeedCache
|
||||
import com.fabledsword.minstrel.nav.LocalDetailSeedCache
|
||||
import com.fabledsword.minstrel.nav.Login
|
||||
import com.fabledsword.minstrel.nav.MinstrelNavGraph
|
||||
import com.fabledsword.minstrel.nav.Notifications
|
||||
import com.fabledsword.minstrel.nav.NowPlaying
|
||||
@@ -177,6 +179,7 @@ private fun App(
|
||||
navController.navigate(route) { launchSingleTop = true }
|
||||
onOpenedRoute()
|
||||
}
|
||||
SignInWhenSessionRejected(gate, navController)
|
||||
MinstrelNavGraph(
|
||||
navController = navController,
|
||||
startDestination = resolved,
|
||||
@@ -187,6 +190,24 @@ private fun App(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* When the server ends the session while the app is in use, opens the
|
||||
* sign-in screen rather than leaving the user on screens whose every
|
||||
* request fails.
|
||||
*/
|
||||
@Composable
|
||||
private fun SignInWhenSessionRejected(gate: AuthGateViewModel, navController: NavHostController) {
|
||||
val sessionRejected by gate.sessionRejected.collectAsStateWithLifecycle()
|
||||
LaunchedEffect(sessionRejected, navController) {
|
||||
if (!sessionRejected) return@LaunchedEffect
|
||||
navController.navigate(Login) {
|
||||
popUpTo(0) { inclusive = true }
|
||||
launchSingleTop = true
|
||||
}
|
||||
gate.consumeSessionRejected()
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun BootSplash() {
|
||||
Surface(
|
||||
|
||||
@@ -8,6 +8,7 @@ import coil3.SingletonImageLoader
|
||||
import coil3.network.okhttp.OkHttpNetworkFetcherFactory
|
||||
import coil3.request.crossfade
|
||||
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.di.ApplicationScope
|
||||
@@ -19,10 +20,10 @@ import com.fabledsword.minstrel.metadata.FreshnessSweeper
|
||||
import com.fabledsword.minstrel.notifications.delivery.DeliveryLauncher
|
||||
import com.fabledsword.minstrel.player.AudioPrefetcher
|
||||
import com.fabledsword.minstrel.player.CoverPrefetcher
|
||||
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.update.data.UpdateBannerController
|
||||
import com.fabledsword.minstrel.connectivity.NetworkStatusController
|
||||
import dagger.hilt.android.HiltAndroidApp
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
@@ -120,6 +121,21 @@ class MinstrelApplication :
|
||||
*/
|
||||
@Suppress("unused") @Inject lateinit var cacheIndexer: CacheIndexer
|
||||
|
||||
/**
|
||||
* Same construct-the-singleton trick — CacheBudgetSync's init block
|
||||
* feeds the audio cache's evictor the liked set and the Storage caps.
|
||||
* Without this @Inject the evictor would never arm, and the cache
|
||||
* would grow without a limit.
|
||||
*/
|
||||
@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
|
||||
|
||||
/**
|
||||
* Same construct-the-singleton trick — AudioPrefetcher's init
|
||||
* block subscribes to PlayerController.uiState +
|
||||
@@ -138,14 +154,6 @@ class MinstrelApplication :
|
||||
*/
|
||||
@Suppress("unused") @Inject lateinit var networkStatusController: NetworkStatusController
|
||||
|
||||
/**
|
||||
* Same construct-the-singleton trick — UpdateBannerController polls
|
||||
* /api/client/version at launch + every 24h and drives the shell's
|
||||
* soft "update available" banner. Without this @Inject the poll
|
||||
* loop would never start and the banner would never surface.
|
||||
*/
|
||||
@Suppress("unused") @Inject lateinit var updateBannerController: UpdateBannerController
|
||||
|
||||
/**
|
||||
* Same construct-the-singleton trick — FreshnessSweeper's init
|
||||
* block starts a 30-min sweep loop that re-fetches cached
|
||||
|
||||
+6
-3
@@ -11,9 +11,10 @@ import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Read-through accessor for the admin quarantine queue. No Room cache —
|
||||
* same rationale as AdminRequests. Three resolution actions all delete
|
||||
* the row from the queue once the server accepts them.
|
||||
* Read-through accessor for the admin Reports queue. No Room cache: it is an
|
||||
* admin's live work list, read fresh each time, and its actions go straight
|
||||
* to the server, so offline they fail with the reason rather than queueing.
|
||||
* Each action takes the row off the queue once the server accepts it.
|
||||
*/
|
||||
@Singleton
|
||||
class AdminQuarantineRepository @Inject constructor(
|
||||
@@ -25,6 +26,8 @@ class AdminQuarantineRepository @Inject constructor(
|
||||
|
||||
suspend fun resolve(trackId: String) = api.resolve(trackId)
|
||||
|
||||
suspend fun removeFile(trackId: String) = api.removeFile(trackId)
|
||||
|
||||
suspend fun deleteFile(trackId: String) = api.deleteFile(trackId)
|
||||
}
|
||||
|
||||
|
||||
-50
@@ -1,50 +0,0 @@
|
||||
package com.fabledsword.minstrel.admin.data
|
||||
|
||||
import com.fabledsword.minstrel.api.endpoints.AdminRequestsApi
|
||||
import com.fabledsword.minstrel.models.RequestRef
|
||||
import com.fabledsword.minstrel.models.RequestStatus
|
||||
import com.fabledsword.minstrel.models.wire.RequestWire
|
||||
import retrofit2.Retrofit
|
||||
import retrofit2.create
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Read-through accessor for the admin cross-user requests queue.
|
||||
*
|
||||
* No Room caching — admin actions are infrequent and don't benefit
|
||||
* from offline scrollback. `approve` and `reject` fire direct REST
|
||||
* (no mutation queue) because admin confirmation is point-and-shoot;
|
||||
* if the request fails the UI surfaces the error and rolls back.
|
||||
*/
|
||||
@Singleton
|
||||
class AdminRequestsRepository @Inject constructor(
|
||||
retrofit: Retrofit,
|
||||
) {
|
||||
private val api: AdminRequestsApi = retrofit.create()
|
||||
|
||||
suspend fun list(): List<RequestRef> = api.list().map { it.toDomain() }
|
||||
|
||||
suspend fun approve(id: String) = api.approve(id)
|
||||
|
||||
suspend fun reject(id: String) = api.reject(id)
|
||||
}
|
||||
|
||||
private fun RequestWire.toDomain(): RequestRef = RequestRef(
|
||||
id = id,
|
||||
userId = userId,
|
||||
username = username,
|
||||
status = RequestStatus.fromWire(status),
|
||||
kind = kind,
|
||||
artistName = artistName,
|
||||
albumTitle = albumTitle,
|
||||
trackTitle = trackTitle,
|
||||
requestedAt = requestedAt,
|
||||
decidedAt = decidedAt,
|
||||
notes = notes,
|
||||
importedAlbumCount = importedAlbumCount,
|
||||
importedTrackCount = importedTrackCount,
|
||||
matchedTrackId = matchedTrackId,
|
||||
matchedAlbumId = matchedAlbumId,
|
||||
matchedArtistId = matchedArtistId,
|
||||
)
|
||||
@@ -3,7 +3,6 @@ package com.fabledsword.minstrel.admin.data
|
||||
import com.fabledsword.minstrel.api.endpoints.AdminUsersApi
|
||||
import com.fabledsword.minstrel.api.endpoints.ResetPasswordBody
|
||||
import com.fabledsword.minstrel.api.endpoints.SetAdminBody
|
||||
import com.fabledsword.minstrel.api.endpoints.SetAutoApproveBody
|
||||
import com.fabledsword.minstrel.models.AdminUserRef
|
||||
import com.fabledsword.minstrel.models.wire.AdminUserWire
|
||||
import retrofit2.Retrofit
|
||||
@@ -27,9 +26,6 @@ class AdminUsersRepository @Inject constructor(
|
||||
suspend fun setAdmin(id: String, isAdmin: Boolean) =
|
||||
api.setAdmin(id, SetAdminBody(isAdmin))
|
||||
|
||||
suspend fun setAutoApprove(id: String, autoApprove: Boolean) =
|
||||
api.setAutoApprove(id, SetAutoApproveBody(autoApprove))
|
||||
|
||||
suspend fun resetPassword(id: String, newPassword: String) =
|
||||
api.resetPassword(id, ResetPasswordBody(newPassword))
|
||||
|
||||
@@ -41,6 +37,5 @@ private fun AdminUserWire.toDomain(): AdminUserRef = AdminUserRef(
|
||||
username = username,
|
||||
displayName = displayName,
|
||||
isAdmin = isAdmin,
|
||||
autoApproveRequests = autoApproveRequests,
|
||||
createdAt = createdAt,
|
||||
)
|
||||
|
||||
@@ -26,19 +26,16 @@ import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.navigation.NavHostController
|
||||
import com.composables.icons.lucide.Inbox
|
||||
import com.composables.icons.lucide.Lucide
|
||||
import com.composables.icons.lucide.Music
|
||||
import com.composables.icons.lucide.TriangleAlert
|
||||
import com.composables.icons.lucide.Users
|
||||
import com.fabledsword.minstrel.admin.data.AdminQuarantineRepository
|
||||
import com.fabledsword.minstrel.admin.data.AdminRequestsRepository
|
||||
import com.fabledsword.minstrel.admin.data.AdminTagSourcesRepository
|
||||
import com.fabledsword.minstrel.admin.data.AdminUsersRepository
|
||||
import com.fabledsword.minstrel.api.ErrorCopy
|
||||
import com.fabledsword.minstrel.nav.Admin
|
||||
import com.fabledsword.minstrel.nav.AdminQuarantine
|
||||
import com.fabledsword.minstrel.nav.AdminRequests
|
||||
import com.fabledsword.minstrel.nav.AdminTagSources
|
||||
import com.fabledsword.minstrel.nav.AdminUsers
|
||||
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
|
||||
@@ -58,7 +55,7 @@ import javax.inject.Inject
|
||||
|
||||
// ─── State ───────────────────────────────────────────────────────────
|
||||
|
||||
data class AdminCounts(val requests: Int, val quarantine: Int, val users: Int, val tagSources: Int)
|
||||
data class AdminCounts(val quarantine: Int, val users: Int, val tagSources: Int)
|
||||
|
||||
sealed interface AdminLandingUiState {
|
||||
data object Loading : AdminLandingUiState
|
||||
@@ -70,7 +67,6 @@ sealed interface AdminLandingUiState {
|
||||
|
||||
@HiltViewModel
|
||||
class AdminLandingViewModel @Inject constructor(
|
||||
private val requestsRepo: AdminRequestsRepository,
|
||||
private val quarantineRepo: AdminQuarantineRepository,
|
||||
private val usersRepo: AdminUsersRepository,
|
||||
private val tagSourcesRepo: AdminTagSourcesRepository,
|
||||
@@ -87,11 +83,10 @@ class AdminLandingViewModel @Inject constructor(
|
||||
internal.value = AdminLandingUiState.Loading
|
||||
try {
|
||||
val counts = coroutineScope {
|
||||
val req = async { requestsRepo.list().size }
|
||||
val qua = async { quarantineRepo.list().size }
|
||||
val usr = async { usersRepo.list().size }
|
||||
val tag = async { tagSourcesRepo.list().count { it.enabled } }
|
||||
AdminCounts(req.await(), qua.await(), usr.await(), tag.await())
|
||||
AdminCounts(qua.await(), usr.await(), tag.await())
|
||||
}
|
||||
internal.value = AdminLandingUiState.Success(counts)
|
||||
} catch (
|
||||
@@ -150,20 +145,11 @@ private fun SectionList(counts: AdminCounts, navController: NavHostController) {
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
item {
|
||||
SectionCard(
|
||||
icon = Lucide.Inbox,
|
||||
title = "Requests",
|
||||
subtitle = "Approve or reject requests for new music",
|
||||
count = counts.requests,
|
||||
onClick = { navController.navigate(AdminRequests) },
|
||||
)
|
||||
}
|
||||
item {
|
||||
SectionCard(
|
||||
icon = Lucide.TriangleAlert,
|
||||
title = "Quarantine",
|
||||
subtitle = "Resolve scan failures",
|
||||
title = "Reports",
|
||||
subtitle = "Tracks listeners flagged",
|
||||
count = counts.quarantine,
|
||||
onClick = { navController.navigate(AdminQuarantine) },
|
||||
)
|
||||
|
||||
+76
-6
@@ -8,6 +8,7 @@ import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.AssistChip
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
@@ -21,7 +22,9 @@ import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
@@ -56,7 +59,7 @@ fun AdminQuarantineScreen(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
topBar = {
|
||||
MinstrelTopAppBar(
|
||||
title = "Admin · Quarantine",
|
||||
title = "Admin · Reports",
|
||||
navController = navController,
|
||||
currentRouteName = AdminQuarantine::class.qualifiedName,
|
||||
onBack = { navController.popBackStack() },
|
||||
@@ -71,9 +74,9 @@ fun AdminQuarantineScreen(
|
||||
when (val s = state) {
|
||||
AdminQuarantineUiState.Loading -> LoadingCentered()
|
||||
AdminQuarantineUiState.Empty -> EmptyState(
|
||||
title = "Queue is empty",
|
||||
body = "When users flag tracks as bad rips, wrong tags, or " +
|
||||
"duplicates, their reports get aggregated and surfaced here.",
|
||||
title = "No reports",
|
||||
body = "When listeners flag a track as a bad rip, wrong tags or " +
|
||||
"a duplicate, their reports gather here.",
|
||||
)
|
||||
is AdminQuarantineUiState.Error -> ErrorRetry(
|
||||
title = "Couldn't load queue",
|
||||
@@ -83,6 +86,7 @@ fun AdminQuarantineScreen(
|
||||
is AdminQuarantineUiState.Success -> QueueList(
|
||||
rows = s.rows,
|
||||
onResolve = viewModel::resolve,
|
||||
onRemoveFile = viewModel::removeFile,
|
||||
onDeleteFile = viewModel::deleteFile,
|
||||
)
|
||||
}
|
||||
@@ -90,28 +94,91 @@ fun AdminQuarantineScreen(
|
||||
}
|
||||
}
|
||||
|
||||
/** A confirm asked of the admin before a removal: which one, and of which track. */
|
||||
private enum class Removal { File, Library }
|
||||
|
||||
private data class PendingRemoval(val row: AdminQuarantineItemRef, val kind: Removal)
|
||||
|
||||
@Composable
|
||||
private fun QueueList(
|
||||
rows: List<AdminQuarantineItemRef>,
|
||||
onResolve: (String) -> Unit,
|
||||
onRemoveFile: (String) -> Unit,
|
||||
onDeleteFile: (String) -> Unit,
|
||||
) {
|
||||
var pending by remember { mutableStateOf<PendingRemoval?>(null) }
|
||||
LazyColumn(modifier = Modifier.fillMaxSize()) {
|
||||
items(items = rows, key = { it.trackId }) { row ->
|
||||
QuarantineRow(
|
||||
row = row,
|
||||
onResolve = { onResolve(row.trackId) },
|
||||
onDeleteFile = { onDeleteFile(row.trackId) },
|
||||
onRemoveFile = { pending = PendingRemoval(row, Removal.File) },
|
||||
onDeleteFile = { pending = PendingRemoval(row, Removal.Library) },
|
||||
)
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
pending?.let { p ->
|
||||
RemovalConfirm(
|
||||
pending = p,
|
||||
onConfirm = {
|
||||
pending = null
|
||||
when (p.kind) {
|
||||
Removal.File -> onRemoveFile(p.row.trackId)
|
||||
Removal.Library -> onDeleteFile(p.row.trackId)
|
||||
}
|
||||
},
|
||||
onDismiss = { pending = null },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Both removals delete the file, so each asks first. Remove the file keeps the
|
||||
* track waiting for a good copy, with its likes and plays; Remove from library
|
||||
* takes the track and its history too.
|
||||
*/
|
||||
@Composable
|
||||
private fun RemovalConfirm(
|
||||
pending: PendingRemoval,
|
||||
onConfirm: () -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
val title = pending.row.trackTitle
|
||||
val (heading, body, action) = when (pending.kind) {
|
||||
Removal.File -> Triple(
|
||||
"Remove the file?",
|
||||
"Delete the file of \u201c$title\u201d and keep the track. It waits, with its likes " +
|
||||
"and plays, and takes over a good copy when one is in the library. Its reports are cleared.",
|
||||
"Remove the file",
|
||||
)
|
||||
Removal.Library -> Triple(
|
||||
"Remove from library?",
|
||||
"Remove \u201c$title\u201d and its file for good, with its likes, plays and playlist " +
|
||||
"places. To keep the track for a good copy, remove the file instead.",
|
||||
"Remove from library",
|
||||
)
|
||||
}
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(heading) },
|
||||
text = {
|
||||
Text(
|
||||
text = body,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
},
|
||||
confirmButton = { TextButton(onClick = onConfirm) { Text(action) } },
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun QuarantineRow(
|
||||
row: AdminQuarantineItemRef,
|
||||
onResolve: () -> Unit,
|
||||
onRemoveFile: () -> Unit,
|
||||
onDeleteFile: () -> Unit,
|
||||
) {
|
||||
Column(
|
||||
@@ -160,6 +227,7 @@ private fun QuarantineRow(
|
||||
}
|
||||
ActionButtons(
|
||||
onResolve = onResolve,
|
||||
onRemoveFile = onRemoveFile,
|
||||
onDeleteFile = onDeleteFile,
|
||||
)
|
||||
}
|
||||
@@ -168,6 +236,7 @@ private fun QuarantineRow(
|
||||
@Composable
|
||||
private fun ActionButtons(
|
||||
onResolve: () -> Unit,
|
||||
onRemoveFile: () -> Unit,
|
||||
onDeleteFile: () -> Unit,
|
||||
) {
|
||||
Row(
|
||||
@@ -175,6 +244,7 @@ private fun ActionButtons(
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End),
|
||||
) {
|
||||
TextButton(onClick = onResolve) { Text("Resolve") }
|
||||
OutlinedButton(onClick = onDeleteFile) { Text("Delete file") }
|
||||
TextButton(onClick = onDeleteFile) { Text("Remove from library") }
|
||||
OutlinedButton(onClick = onRemoveFile) { Text("Remove the file") }
|
||||
}
|
||||
}
|
||||
|
||||
+3
-3
@@ -39,9 +39,8 @@ class AdminQuarantineViewModel @Inject constructor(
|
||||
|
||||
/**
|
||||
* One-shot messages for the screen's snackbar. A failed action has to say
|
||||
* why: the row quietly reappearing reads as a glitch, and for a Delete
|
||||
* file refused by a read-only library it hides the one thing an
|
||||
* admin can fix.
|
||||
* why: the row quietly reappearing reads as a glitch, and for a removal
|
||||
* refused by a read-only library it hides the one thing an admin can fix.
|
||||
*/
|
||||
private val transientMessagesChannel = Channel<String>(Channel.BUFFERED)
|
||||
val transientMessages: Flow<String> = transientMessagesChannel.receiveAsFlow()
|
||||
@@ -81,6 +80,7 @@ class AdminQuarantineViewModel @Inject constructor(
|
||||
}
|
||||
|
||||
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) {
|
||||
|
||||
@@ -1,163 +0,0 @@
|
||||
package com.fabledsword.minstrel.admin.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material3.AssistChip
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.navigation.NavHostController
|
||||
import com.fabledsword.minstrel.models.RequestRef
|
||||
import com.fabledsword.minstrel.nav.AdminRequests
|
||||
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
|
||||
import com.fabledsword.minstrel.shared.widgets.EmptyState
|
||||
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
|
||||
import com.fabledsword.minstrel.shared.widgets.LoadingCentered
|
||||
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
|
||||
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun AdminRequestsScreen(
|
||||
navController: NavHostController,
|
||||
viewModel: AdminRequestsViewModel = hiltViewModel(),
|
||||
) {
|
||||
val state by viewModel.uiState.collectAsStateWithLifecycle()
|
||||
Scaffold(
|
||||
contentWindowInsets = ShellContentWindowInsets,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
topBar = {
|
||||
MinstrelTopAppBar(
|
||||
title = "Admin · Requests",
|
||||
navController = navController,
|
||||
currentRouteName = AdminRequests::class.qualifiedName,
|
||||
onBack = { navController.popBackStack() },
|
||||
)
|
||||
},
|
||||
) { inner ->
|
||||
PullToRefreshScaffold(
|
||||
onRefresh = { viewModel.refresh().join() },
|
||||
modifier = Modifier.fillMaxSize().padding(inner),
|
||||
) {
|
||||
when (val s = state) {
|
||||
AdminRequestsUiState.Loading -> LoadingCentered()
|
||||
AdminRequestsUiState.Empty -> EmptyState(
|
||||
title = "No requests waiting",
|
||||
body = "When users ask for new music, their pending " +
|
||||
"requests show up here for approval.",
|
||||
)
|
||||
is AdminRequestsUiState.Error -> ErrorRetry(
|
||||
title = "Couldn't load requests",
|
||||
message = s.message,
|
||||
onRetry = { viewModel.refresh() },
|
||||
)
|
||||
is AdminRequestsUiState.Success -> RequestList(
|
||||
rows = s.rows,
|
||||
onApprove = viewModel::approve,
|
||||
onReject = viewModel::reject,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RequestList(
|
||||
rows: List<RequestRef>,
|
||||
onApprove: (String) -> Unit,
|
||||
onReject: (String) -> Unit,
|
||||
) {
|
||||
LazyColumn(modifier = Modifier.fillMaxSize()) {
|
||||
items(items = rows, key = { it.id }) { req ->
|
||||
AdminRequestRow(
|
||||
req = req,
|
||||
requester = req.username.ifEmpty {
|
||||
req.userId.take(USER_ID_PREFIX_LEN).ifEmpty { "unknown" }
|
||||
},
|
||||
onApprove = { onApprove(req.id) },
|
||||
onReject = { onReject(req.id) },
|
||||
)
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AdminRequestRow(
|
||||
req: RequestRef,
|
||||
requester: String,
|
||||
onApprove: () -> Unit,
|
||||
onReject: () -> Unit,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Text(
|
||||
text = req.displayName,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(
|
||||
text = "Requested by $requester",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
AssistChip(
|
||||
onClick = {},
|
||||
enabled = false,
|
||||
label = { Text(req.kind, style = MaterialTheme.typography.labelSmall) },
|
||||
)
|
||||
AssistChip(
|
||||
onClick = {},
|
||||
enabled = false,
|
||||
label = { Text(req.status.wire, style = MaterialTheme.typography.labelSmall) },
|
||||
)
|
||||
}
|
||||
if (req.artistName.isNotEmpty() && req.artistName != req.displayName) {
|
||||
Text(
|
||||
text = "Artist: ${req.artistName}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End),
|
||||
) {
|
||||
OutlinedButton(onClick = onReject) { Text("Reject") }
|
||||
Button(onClick = onApprove) { Text("Approve") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// UUID prefix length used as a friendlier-than-raw-UUID fallback when a
|
||||
// row comes back without the requester's username.
|
||||
private const val USER_ID_PREFIX_LEN = 8
|
||||
-105
@@ -1,105 +0,0 @@
|
||||
package com.fabledsword.minstrel.admin.ui
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.fabledsword.minstrel.admin.data.AdminRequestsRepository
|
||||
import com.fabledsword.minstrel.api.ErrorCopy
|
||||
import com.fabledsword.minstrel.connectivity.NetworkStatusController
|
||||
import com.fabledsword.minstrel.connectivity.recoveries
|
||||
import com.fabledsword.minstrel.events.EventsStream
|
||||
import com.fabledsword.minstrel.models.RequestRef
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.filter
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
|
||||
private val RELEVANT_EVENT_KINDS = setOf("request.status_changed")
|
||||
|
||||
sealed interface AdminRequestsUiState {
|
||||
data object Loading : AdminRequestsUiState
|
||||
data object Empty : AdminRequestsUiState
|
||||
data class Success(val rows: List<RequestRef>) : AdminRequestsUiState
|
||||
data class Error(val message: String) : AdminRequestsUiState
|
||||
}
|
||||
|
||||
@HiltViewModel
|
||||
class AdminRequestsViewModel @Inject constructor(
|
||||
private val repository: AdminRequestsRepository,
|
||||
private val eventsStream: EventsStream,
|
||||
networkStatus: NetworkStatusController,
|
||||
) : ViewModel() {
|
||||
|
||||
private val internal = MutableStateFlow<AdminRequestsUiState>(AdminRequestsUiState.Loading)
|
||||
val uiState: StateFlow<AdminRequestsUiState> = internal.asStateFlow()
|
||||
|
||||
init {
|
||||
refresh()
|
||||
viewModelScope.launch {
|
||||
eventsStream.events
|
||||
.filter { it.kind in RELEVANT_EVENT_KINDS }
|
||||
.collect { refresh() }
|
||||
}
|
||||
// Screen-level auto-recovery: reload a failed list
|
||||
// when server health returns instead of waiting for a manual pull.
|
||||
viewModelScope.launch {
|
||||
networkStatus.recoveries().collect {
|
||||
if (internal.value is AdminRequestsUiState.Error) refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun refresh(): Job = viewModelScope.launch {
|
||||
internal.value = AdminRequestsUiState.Loading
|
||||
try {
|
||||
val rows = repository.list()
|
||||
internal.value = if (rows.isEmpty()) {
|
||||
AdminRequestsUiState.Empty
|
||||
} else {
|
||||
AdminRequestsUiState.Success(rows = rows)
|
||||
}
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
||||
) {
|
||||
internal.value = AdminRequestsUiState.Error(
|
||||
ErrorCopy.fromThrowable(e),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun approve(id: String) = decide(id) { repository.approve(it) }
|
||||
|
||||
fun reject(id: String) = decide(id) { repository.reject(it) }
|
||||
|
||||
/**
|
||||
* Optimistically removes the decided row from the visible list and
|
||||
* fires the REST call. On failure, refetches so the UI matches the
|
||||
* server's view rather than leaving a phantom hole.
|
||||
*/
|
||||
private fun decide(id: String, action: suspend (String) -> Unit) {
|
||||
val before = internal.value
|
||||
if (before is AdminRequestsUiState.Success) {
|
||||
val filtered = before.rows.filterNot { it.id == id }
|
||||
internal.value = if (filtered.isEmpty()) {
|
||||
AdminRequestsUiState.Empty
|
||||
} else {
|
||||
AdminRequestsUiState.Success(rows = filtered)
|
||||
}
|
||||
}
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
action(id)
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
|
||||
) {
|
||||
// Refetch reconciles whatever the server now says about
|
||||
// this request; the error is intentionally swallowed
|
||||
// because the refresh result IS the user-facing signal.
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -81,7 +81,6 @@ fun AdminUsersScreen(
|
||||
invitesViewModel.refresh()
|
||||
},
|
||||
onSetAdmin = viewModel::setAdmin,
|
||||
onSetAutoApprove = viewModel::setAutoApprove,
|
||||
onAskResetPassword = { resetPasswordFor = it },
|
||||
onAskDelete = { deleteCandidate = it },
|
||||
onAskGenerateInvite = { showGenerateInvite = true },
|
||||
@@ -121,7 +120,6 @@ private fun AdminUsersScaffold(
|
||||
invitesState: AdminInvitesUiState,
|
||||
onRefresh: suspend () -> Unit,
|
||||
onSetAdmin: (String, Boolean) -> Unit,
|
||||
onSetAutoApprove: (String, Boolean) -> Unit,
|
||||
onAskResetPassword: (AdminUserRef) -> Unit,
|
||||
onAskDelete: (AdminUserRef) -> Unit,
|
||||
onAskGenerateInvite: () -> Unit,
|
||||
@@ -148,7 +146,6 @@ private fun AdminUsersScaffold(
|
||||
usersSection(
|
||||
state = usersState,
|
||||
onSetAdmin = onSetAdmin,
|
||||
onSetAutoApprove = onSetAutoApprove,
|
||||
onAskResetPassword = onAskResetPassword,
|
||||
onAskDelete = onAskDelete,
|
||||
)
|
||||
@@ -195,7 +192,6 @@ private fun SectionHeader(label: String, trailing: (@Composable () -> Unit)? = n
|
||||
private fun androidx.compose.foundation.lazy.LazyListScope.usersSection(
|
||||
state: AdminUsersUiState,
|
||||
onSetAdmin: (String, Boolean) -> Unit,
|
||||
onSetAutoApprove: (String, Boolean) -> Unit,
|
||||
onAskResetPassword: (AdminUserRef) -> Unit,
|
||||
onAskDelete: (AdminUserRef) -> Unit,
|
||||
) {
|
||||
@@ -207,7 +203,6 @@ private fun androidx.compose.foundation.lazy.LazyListScope.usersSection(
|
||||
UserRow(
|
||||
user = user,
|
||||
onSetAdmin = { onSetAdmin(user.id, it) },
|
||||
onSetAutoApprove = { onSetAutoApprove(user.id, it) },
|
||||
onResetPassword = { onAskResetPassword(user) },
|
||||
onDelete = { onAskDelete(user) },
|
||||
)
|
||||
@@ -397,7 +392,6 @@ private fun PendingDialogs(
|
||||
private fun UserRow(
|
||||
user: AdminUserRef,
|
||||
onSetAdmin: (Boolean) -> Unit,
|
||||
onSetAutoApprove: (Boolean) -> Unit,
|
||||
onResetPassword: () -> Unit,
|
||||
onDelete: () -> Unit,
|
||||
) {
|
||||
@@ -420,11 +414,6 @@ private fun UserRow(
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
ToggleRow(label = "Admin", checked = user.isAdmin, onChange = onSetAdmin)
|
||||
ToggleRow(
|
||||
label = "Auto-approve requests",
|
||||
checked = user.autoApproveRequests,
|
||||
onChange = onSetAutoApprove,
|
||||
)
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp, Alignment.End),
|
||||
|
||||
@@ -62,11 +62,6 @@ class AdminUsersViewModel @Inject constructor(
|
||||
repository.setAdmin(it, isAdmin)
|
||||
}
|
||||
|
||||
fun setAutoApprove(id: String, autoApprove: Boolean) =
|
||||
patch(id, { it.copy(autoApproveRequests = autoApprove) }) {
|
||||
repository.setAutoApprove(it, autoApprove)
|
||||
}
|
||||
|
||||
fun resetPassword(id: String, newPassword: String) {
|
||||
viewModelScope.launch {
|
||||
runCatching { repository.resetPassword(id, newPassword) }
|
||||
|
||||
@@ -8,9 +8,9 @@ import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Attaches the session cookie from [AuthStore] to Minstrel-server
|
||||
* requests, captures Set-Cookie from successful responses (login
|
||||
* flow), and clears the store on 401 so downstream code can react
|
||||
* to logout.
|
||||
* requests (waiting for the stored one to load at launch), captures
|
||||
* Set-Cookie from successful responses (login flow), and signs out when
|
||||
* the server refuses the cookie a request carried.
|
||||
*
|
||||
* Scoped to the [BaseUrlInterceptor.PLACEHOLDER_HOST] sentinel host
|
||||
* the same way BaseUrlInterceptor is. The shared OkHttpClient also
|
||||
@@ -32,7 +32,7 @@ class AuthCookieInterceptor @Inject constructor(
|
||||
// session. Pass through untouched.
|
||||
return chain.proceed(original)
|
||||
}
|
||||
val cookie = authStore.sessionCookie.value
|
||||
val cookie = authStore.sessionCookieForRequest()
|
||||
val request = original.newBuilder().apply {
|
||||
if (!cookie.isNullOrEmpty()) header("Cookie", cookie)
|
||||
}.build()
|
||||
@@ -40,7 +40,11 @@ class AuthCookieInterceptor @Inject constructor(
|
||||
val response = chain.proceed(request)
|
||||
|
||||
if (response.code == HTTP_UNAUTHORIZED) {
|
||||
authStore.setSessionCookie(null)
|
||||
// Only a refusal of the cookie this request carried ends the
|
||||
// session. A request sent without one says nothing about the
|
||||
// stored login, and a refusal of an older cookie must not
|
||||
// discard one a sign-in has stored since.
|
||||
if (!cookie.isNullOrEmpty()) authStore.dropRejectedSessionCookie(cookie)
|
||||
} else if (response.isSuccessful) {
|
||||
// Capture the first Set-Cookie pair on login; subsequent
|
||||
// responses that include Set-Cookie keep the store fresh.
|
||||
|
||||
@@ -24,7 +24,7 @@ import javax.inject.Singleton
|
||||
* rewritten. Absolute external URLs — artwork from
|
||||
* artwork.musicbrainz.org / coverartarchive.org, for example — must
|
||||
* reach their authored host unchanged: rewritten to the Minstrel host
|
||||
* they 404, and Discover suggestions show no covers.
|
||||
* they 404, and the art never shows.
|
||||
*
|
||||
* No-op when the stored base URL is unparseable (falls through to
|
||||
* whatever Retrofit had) — that case shows up as a transport-level
|
||||
|
||||
@@ -99,16 +99,11 @@ object ErrorCopy {
|
||||
"bad_kind" to "Invalid request type.",
|
||||
"bad_paging" to "Invalid page size or offset.",
|
||||
"bad_reason" to "Invalid quarantine reason.",
|
||||
"mbid_required" to "An MBID is required for this lookup.",
|
||||
"system_playlist_readonly" to "System playlists can't be edited directly.",
|
||||
"connection_refused" to "Couldn't reach the server. Check the URL and try again.",
|
||||
"cleartext_public" to
|
||||
"This server is on the internet, so its URL must start with https://. " +
|
||||
"Plain http:// only works on your home network.",
|
||||
"request_not_pending" to "This request is no longer pending.",
|
||||
"request_not_found" to "That request no longer exists.",
|
||||
"not_followable" to "Various Artists and MusicBrainz placeholders can't be followed.",
|
||||
"profile_not_found" to "That release-type profile no longer exists.",
|
||||
"track_not_found" to "That track no longer exists.",
|
||||
"library_not_writable" to "The music library isn't writable by the server.",
|
||||
"file_delete_failed" to "The file couldn't be deleted.",
|
||||
|
||||
+8
-3
@@ -8,9 +8,11 @@ import retrofit2.http.Path
|
||||
/**
|
||||
* Retrofit interface for `/api/admin/quarantine`.
|
||||
*
|
||||
* Two resolution endpoints:
|
||||
* - `resolve` → admin reviewed, no action taken (clears flags).
|
||||
* - `delete-file` → delete the track's file and row.
|
||||
* Three resolution endpoints:
|
||||
* - `resolve` → admin reviewed, no action taken (clears the reports).
|
||||
* - `remove-file` → delete the track's file and keep the track, which waits
|
||||
* for a good copy with its likes and plays.
|
||||
* - `delete-file` → remove the track from the library, file and history.
|
||||
*/
|
||||
interface AdminQuarantineApi {
|
||||
@GET("api/admin/quarantine")
|
||||
@@ -19,6 +21,9 @@ interface AdminQuarantineApi {
|
||||
@POST("api/admin/quarantine/{trackId}/resolve")
|
||||
suspend fun resolve(@Path("trackId") trackId: String)
|
||||
|
||||
@POST("api/admin/quarantine/{trackId}/remove-file")
|
||||
suspend fun removeFile(@Path("trackId") trackId: String)
|
||||
|
||||
@POST("api/admin/quarantine/{trackId}/delete-file")
|
||||
suspend fun deleteFile(@Path("trackId") trackId: String)
|
||||
}
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
package com.fabledsword.minstrel.api.endpoints
|
||||
|
||||
import com.fabledsword.minstrel.models.wire.RequestWire
|
||||
import retrofit2.http.GET
|
||||
import retrofit2.http.POST
|
||||
import retrofit2.http.Path
|
||||
|
||||
/**
|
||||
* Retrofit interface for `/api/admin/requests`.
|
||||
*
|
||||
* Server returns the same `requestView` shape as the user-side
|
||||
* `/api/requests`, so RequestWire is reused. Different listing scope —
|
||||
* admin sees all users' requests, not just the caller's.
|
||||
*/
|
||||
interface AdminRequestsApi {
|
||||
@GET("api/admin/requests")
|
||||
suspend fun list(): List<RequestWire>
|
||||
|
||||
@POST("api/admin/requests/{id}/approve")
|
||||
suspend fun approve(@Path("id") id: String)
|
||||
|
||||
@POST("api/admin/requests/{id}/reject")
|
||||
suspend fun reject(@Path("id") id: String)
|
||||
}
|
||||
@@ -9,14 +9,7 @@ import retrofit2.http.POST
|
||||
import retrofit2.http.PUT
|
||||
import retrofit2.http.Path
|
||||
|
||||
/**
|
||||
* Retrofit interface for `/api/admin/users`.
|
||||
*
|
||||
* Note: the PUT-auto-approve body field is `auto_approve`, NOT
|
||||
* `auto_approve_requests` — the request shape differs from the
|
||||
* response field name. Verified against `internal/api/admin_users.go
|
||||
* adminAutoApproveReq` (May 2026).
|
||||
*/
|
||||
/** Retrofit interface for `/api/admin/users`. */
|
||||
interface AdminUsersApi {
|
||||
@GET("api/admin/users")
|
||||
suspend fun list(): AdminUsersListWire
|
||||
@@ -24,9 +17,6 @@ interface AdminUsersApi {
|
||||
@PUT("api/admin/users/{id}/admin")
|
||||
suspend fun setAdmin(@Path("id") id: String, @Body body: SetAdminBody)
|
||||
|
||||
@PUT("api/admin/users/{id}/auto-approve")
|
||||
suspend fun setAutoApprove(@Path("id") id: String, @Body body: SetAutoApproveBody)
|
||||
|
||||
@POST("api/admin/users/{id}/reset-password")
|
||||
suspend fun resetPassword(@Path("id") id: String, @Body body: ResetPasswordBody)
|
||||
|
||||
@@ -39,10 +29,5 @@ data class SetAdminBody(
|
||||
@kotlinx.serialization.SerialName("is_admin") val isAdmin: Boolean,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class SetAutoApproveBody(
|
||||
@kotlinx.serialization.SerialName("auto_approve") val autoApprove: Boolean,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ResetPasswordBody(val password: String)
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
package com.fabledsword.minstrel.api.endpoints
|
||||
|
||||
import com.fabledsword.minstrel.models.wire.ArtistSuggestionWire
|
||||
import com.fabledsword.minstrel.models.wire.CreateRequestBody
|
||||
import com.fabledsword.minstrel.models.wire.CatalogueSearchResultWire
|
||||
import com.fabledsword.minstrel.models.wire.SnoozeSuggestionBody
|
||||
import com.fabledsword.minstrel.models.wire.SuggestionSnoozeWire
|
||||
import retrofit2.http.Body
|
||||
import retrofit2.http.DELETE
|
||||
import retrofit2.http.GET
|
||||
import retrofit2.http.POST
|
||||
import retrofit2.http.Path
|
||||
import retrofit2.http.Query
|
||||
|
||||
/**
|
||||
* Retrofit interface for Discover / catalogue search / request creation.
|
||||
*
|
||||
* `/api/catalogue/search` asks MusicBrainz, which allows one request a
|
||||
* second, so the Discover screen searches when the query is submitted,
|
||||
* not on every keystroke.
|
||||
*
|
||||
* Cancel + my-requests-list endpoints live on RequestsApi, not here.
|
||||
*/
|
||||
interface DiscoverApi {
|
||||
@GET("api/discover/suggestions")
|
||||
suspend fun listSuggestions(): List<ArtistSuggestionWire>
|
||||
|
||||
@GET("api/catalogue/search")
|
||||
suspend fun search(
|
||||
@Query("q") query: String,
|
||||
@Query("kind") kind: String,
|
||||
): List<CatalogueSearchResultWire>
|
||||
|
||||
@POST("api/requests")
|
||||
suspend fun createRequest(@Body body: CreateRequestBody)
|
||||
|
||||
/**
|
||||
* Parks a suggestion — "not right now", NOT a dislike. Time-boxed
|
||||
* server-side (90 days) and never fed into the taste profile.
|
||||
*
|
||||
* [body] must carry the artist's name: candidates are out-of-library, so
|
||||
* the server has no local row to resolve a display name from and returns
|
||||
* 400 without it.
|
||||
*/
|
||||
@POST("api/discover/suggestions/{mbid}/snooze")
|
||||
suspend fun snoozeSuggestion(
|
||||
@Path("mbid") mbid: String,
|
||||
@Body body: SnoozeSuggestionBody,
|
||||
)
|
||||
|
||||
/** Brings a parked suggestion back. 404 when it wasn't snoozed. */
|
||||
@DELETE("api/discover/suggestions/{mbid}/snooze")
|
||||
suspend fun unsnoozeSuggestion(@Path("mbid") mbid: String)
|
||||
|
||||
/**
|
||||
* Currently-parked suggestions. Server filters expired rows, so every
|
||||
* row returned is still snoozed. This is the only route back to an
|
||||
* un-snooze once the card has left the deck.
|
||||
*/
|
||||
@GET("api/discover/snoozes")
|
||||
suspend fun listSnoozes(): List<SuggestionSnoozeWire>
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package com.fabledsword.minstrel.api.endpoints
|
||||
|
||||
import com.fabledsword.minstrel.models.wire.RequestWire
|
||||
import retrofit2.http.DELETE
|
||||
import retrofit2.http.GET
|
||||
import retrofit2.http.Path
|
||||
|
||||
/**
|
||||
* Retrofit interface for the user-side `/api/requests`.
|
||||
*
|
||||
* Server scopes results to the caller — admins see only their own
|
||||
* requests through this endpoint. The cross-user admin view lives on
|
||||
* a separate `/api/admin/requests` route.
|
||||
*
|
||||
* The DELETE endpoint returns the cancelled row (not 204) so the UI
|
||||
* can patch local state without a refetch.
|
||||
*/
|
||||
interface RequestsApi {
|
||||
@GET("api/requests")
|
||||
suspend fun listMine(): List<RequestWire>
|
||||
|
||||
@DELETE("api/requests/{id}")
|
||||
suspend fun cancel(@Path("id") id: String): RequestWire
|
||||
}
|
||||
@@ -89,8 +89,11 @@ class AuthController @Inject constructor(
|
||||
* + persisted userJson. Carries account-level flags (debug mode)
|
||||
* that aren't in the login response. Best-effort: a network failure
|
||||
* leaves the cached identity untouched. No-op when signed out.
|
||||
* Waits for the stored login to load first: at launch this runs before
|
||||
* it has, and would otherwise read the user as signed out and skip.
|
||||
*/
|
||||
suspend fun refreshProfile() {
|
||||
authStore.awaitSessionHydrated()
|
||||
if (!isSignedIn) return
|
||||
val p = runCatching { meApi.getProfile() }.getOrNull() ?: return
|
||||
val user = UserRef(
|
||||
|
||||
@@ -12,6 +12,7 @@ import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
@@ -148,6 +149,49 @@ class AuthStore @Inject constructor(
|
||||
scope.launch { cookieLock.withLock { storeCookie(value) } }
|
||||
}
|
||||
|
||||
/**
|
||||
* The cookie to attach to an outgoing request. Blocks the calling
|
||||
* (OkHttp) thread until the stored cookie has loaded, up to
|
||||
* [HYDRATION_DEADLINE_MS], so a request made in the first moment after
|
||||
* launch carries the login instead of going out without it. Once
|
||||
* hydration has finished this is a plain read.
|
||||
*/
|
||||
fun sessionCookieForRequest(): String? {
|
||||
if (!cookieHydration.isCompleted) {
|
||||
runBlocking { withTimeoutOrNull(HYDRATION_DEADLINE_MS) { cookieHydration.await() } }
|
||||
}
|
||||
return sessionCookieState.value
|
||||
}
|
||||
|
||||
/**
|
||||
* True once the server has refused the current session (see
|
||||
* [dropRejectedSessionCookie]) and the UI has not yet sent the user to
|
||||
* sign in. Held rather than fired, so a refusal that lands while the app
|
||||
* is in the background is still acted on when it comes back. A sign-out
|
||||
* the user asked for does not set it.
|
||||
*/
|
||||
private val sessionRejectedState = MutableStateFlow(false)
|
||||
val sessionRejected: StateFlow<Boolean> = sessionRejectedState.asStateFlow()
|
||||
|
||||
/** The UI has opened the sign-in screen for a refused session. */
|
||||
fun consumeSessionRejected() {
|
||||
sessionRejectedState.value = false
|
||||
}
|
||||
|
||||
/**
|
||||
* Signs out because the server answered 401 to a request that carried
|
||||
* [rejected]. Does nothing when the store has since moved on to another
|
||||
* cookie (a sign-in landed meanwhile), so a refusal of an old session
|
||||
* never discards a new one. What is persisted is read inside the lock,
|
||||
* so a sign-in racing this call is the value that ends up stored.
|
||||
*/
|
||||
fun dropRejectedSessionCookie(rejected: String) {
|
||||
if (!sessionCookieState.compareAndSet(rejected, null)) return
|
||||
cookieTouched = true
|
||||
scope.launch { cookieLock.withLock { storeCookie(sessionCookieState.value) } }
|
||||
sessionRejectedState.value = true
|
||||
}
|
||||
|
||||
private suspend fun hydrateSessionCookie() = cookieLock.withLock {
|
||||
val legacy = runCatching { dao.get()?.sessionCookie }.getOrNull()
|
||||
if (cookieTouched) return@withLock
|
||||
|
||||
@@ -38,6 +38,15 @@ class AuthGateViewModel @Inject constructor(
|
||||
private val internal = MutableStateFlow<Any?>(null)
|
||||
val startDestination: StateFlow<Any?> = internal.asStateFlow()
|
||||
|
||||
/**
|
||||
* True when the server has ended the session while the app was in use;
|
||||
* the root NavHost answers by opening the sign-in screen, then calls
|
||||
* [consumeSessionRejected].
|
||||
*/
|
||||
val sessionRejected: StateFlow<Boolean> = authStore.sessionRejected
|
||||
|
||||
fun consumeSessionRejected() = authStore.consumeSessionRejected()
|
||||
|
||||
init {
|
||||
viewModelScope.launch {
|
||||
authStore.awaitSessionHydrated()
|
||||
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
package com.fabledsword.minstrel.cache.audiocache
|
||||
|
||||
import java.util.TreeSet
|
||||
|
||||
/** Which budget a cached track's bytes count against. */
|
||||
enum class CacheBucket { LIKED, RECENT }
|
||||
|
||||
/**
|
||||
* The bookkeeping behind [TwoBucketCacheEvictor]: which budget each cached
|
||||
* span counts against, how full each budget is, and which span to drop
|
||||
* next. It knows nothing of Media3, so it is tested directly.
|
||||
*
|
||||
* A span belongs to [CacheBucket.LIKED] when its key (the track id) is in
|
||||
* the liked set, and to [CacheBucket.RECENT] otherwise. A track that is
|
||||
* liked and also recently played is therefore charged to Liked only; the
|
||||
* two budgets never count the same bytes. Each bucket drops its own
|
||||
* least-recently-used span first, so filling one never evicts the other.
|
||||
*
|
||||
* Nothing is evicted until [setLiked] has been called once. Before then
|
||||
* every span would read as Recently played, and trimming at the Recently
|
||||
* played cap would throw away liked audio at startup.
|
||||
*
|
||||
* Not thread-safe; the evictor serialises every call.
|
||||
*/
|
||||
class BucketLedger<S : Any>(
|
||||
private val keyOf: (S) -> String,
|
||||
private val lengthOf: (S) -> Long,
|
||||
lruOrder: Comparator<S>,
|
||||
) {
|
||||
private val spans = mapOf(
|
||||
CacheBucket.LIKED to TreeSet(lruOrder),
|
||||
CacheBucket.RECENT to TreeSet(lruOrder),
|
||||
)
|
||||
private val bytes = mutableMapOf(CacheBucket.LIKED to 0L, CacheBucket.RECENT to 0L)
|
||||
private val spansByKey = HashMap<String, MutableSet<S>>()
|
||||
private val bucketByKey = HashMap<String, CacheBucket>()
|
||||
private var liked: Set<String> = emptySet()
|
||||
private var armed = false
|
||||
|
||||
/** Cap on Liked bytes; 0 means unlimited. */
|
||||
var likedCapBytes: Long = 0L
|
||||
|
||||
/** 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 bytesIn(bucket: CacheBucket): Long = bytes.getValue(bucket)
|
||||
|
||||
/** Bytes the Liked budget can still take; [Long.MAX_VALUE] when unlimited. */
|
||||
fun likedRoomBytes(): Long = when {
|
||||
likedCapBytes <= 0L -> Long.MAX_VALUE
|
||||
else -> (likedCapBytes - bytesIn(CacheBucket.LIKED)).coerceAtLeast(0L)
|
||||
}
|
||||
|
||||
fun add(span: S) {
|
||||
val key = keyOf(span)
|
||||
val bucket = bucketByKey[key] ?: bucketOf(key).also { bucketByKey[key] = it }
|
||||
if (spans.getValue(bucket).add(span)) {
|
||||
bytes[bucket] = bytesIn(bucket) + lengthOf(span)
|
||||
spansByKey.getOrPut(key) { HashSet() }.add(span)
|
||||
}
|
||||
}
|
||||
|
||||
fun remove(span: S) {
|
||||
val key = keyOf(span)
|
||||
val bucket = bucketByKey[key] ?: return
|
||||
if (spans.getValue(bucket).remove(span)) {
|
||||
bytes[bucket] = bytesIn(bucket) - lengthOf(span)
|
||||
}
|
||||
val forKey = spansByKey[key] ?: return
|
||||
forKey.remove(span)
|
||||
if (forKey.isEmpty()) {
|
||||
spansByKey.remove(key)
|
||||
bucketByKey.remove(key)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the liked set and move every cached track whose bucket
|
||||
* changed: a newly liked track's bytes leave Recently played for Liked,
|
||||
* an unliked track's go the other way. Arms eviction.
|
||||
*/
|
||||
fun setLiked(ids: Set<String>) {
|
||||
liked = ids
|
||||
armed = true
|
||||
val moves = bucketByKey.filter { (key, bucket) -> bucketOf(key) != bucket }.keys.toList()
|
||||
for (key in moves) {
|
||||
val from = bucketByKey.getValue(key)
|
||||
val to = bucketOf(key)
|
||||
for (span in spansByKey[key].orEmpty()) {
|
||||
if (spans.getValue(from).remove(span)) {
|
||||
bytes[from] = bytesIn(from) - lengthOf(span)
|
||||
spans.getValue(to).add(span)
|
||||
bytes[to] = bytesIn(to) + lengthOf(span)
|
||||
}
|
||||
}
|
||||
bucketByKey[key] = to
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The span to drop next, or null when both budgets fit. [pendingKey] and
|
||||
* [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? {
|
||||
if (!armed) return null
|
||||
val pendingBucket = pendingKey?.let(::bucketOf)
|
||||
return listOf(CacheBucket.RECENT, CacheBucket.LIKED).firstNotNullOfOrNull { bucket ->
|
||||
val incoming = if (bucket == pendingBucket) pendingBytes.coerceAtLeast(0L) else 0L
|
||||
oldestIfOver(bucket, incoming)
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.fabledsword.minstrel.cache.audiocache
|
||||
|
||||
import com.fabledsword.minstrel.auth.AuthStore
|
||||
import com.fabledsword.minstrel.di.ApplicationScope
|
||||
import com.fabledsword.minstrel.likes.data.LikesRepository
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Keeps [TwoBucketCacheEvictor] in step with the signed-in user's liked
|
||||
* tracks and the Storage caps. A like moves that track's cached audio into
|
||||
* the Liked budget, an unlike moves it out, and a cap change trims at once.
|
||||
*
|
||||
* The liked set only flows once a user is signed in, and the evictor drops
|
||||
* nothing until it has one, so liked audio is never trimmed as Recently
|
||||
* played while the session is still loading.
|
||||
*
|
||||
* Eager-constructed via the construct-the-singleton trick in
|
||||
* `MinstrelApplication`.
|
||||
*/
|
||||
@Singleton
|
||||
class CacheBudgetSync @Inject constructor(
|
||||
likes: LikesRepository,
|
||||
authStore: AuthStore,
|
||||
evictor: TwoBucketCacheEvictor,
|
||||
@ApplicationScope scope: CoroutineScope,
|
||||
) {
|
||||
init {
|
||||
scope.launch(Dispatchers.IO) {
|
||||
combine(likes.observeSignedInLikedTrackIds(), authStore.cacheSettings, ::Pair)
|
||||
.collect { (ids, settings) ->
|
||||
evictor.update(ids, settings.likedCapBytes, settings.rollingCapBytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
package com.fabledsword.minstrel.cache.audiocache
|
||||
|
||||
/**
|
||||
* Defaults for the audio cache; the user's Storage settings override them.
|
||||
*
|
||||
* - `likedCapBytes`: cap meant for a protected bucket of liked tracks'
|
||||
* files. Nothing enforces it yet; SimpleCache evicts by the rolling
|
||||
* cap alone.
|
||||
* - `rollingCapBytes`: cap for incidental / auto-prefetch downloads,
|
||||
* evicted least-recently-used first.
|
||||
*
|
||||
* The values are generous so first-time installs work well without
|
||||
* configuration.
|
||||
*/
|
||||
data class CacheConfig(
|
||||
val likedCapBytes: Long = DEFAULT_LIKED_CAP_BYTES,
|
||||
val rollingCapBytes: Long = DEFAULT_ROLLING_CAP_BYTES,
|
||||
) {
|
||||
companion object {
|
||||
const val DEFAULT_LIKED_CAP_BYTES: Long = 200L * 1024 * 1024 // 200 MiB
|
||||
const val DEFAULT_ROLLING_CAP_BYTES: Long = 150L * 1024 * 1024 // 150 MiB
|
||||
}
|
||||
}
|
||||
+9
-9
@@ -9,17 +9,17 @@ private const val DEFAULT_PREFETCH_WINDOW = 5
|
||||
* User-tunable audio cache settings. Persisted as a JSON
|
||||
* blob on the auth_session single-row table via [AuthStore].
|
||||
*
|
||||
* - [likedCapBytes]: budget for cached files of liked tracks. 0 means
|
||||
* unlimited. Nothing enforces it yet: SimpleCache evicts by
|
||||
* [rollingCapBytes] alone, and the Storage card hides this control.
|
||||
* - [rollingCapBytes]: budget for incidental / auto-prefetch downloads.
|
||||
* 0 means unlimited. Effective at next app start (SimpleCache is
|
||||
* built once per process).
|
||||
* - [likedCapBytes]: the Liked songs budget, for the cached audio of
|
||||
* liked tracks. 0 means unlimited.
|
||||
* - [rollingCapBytes]: the Recently played budget, for everything else
|
||||
* streamed or prefetched. 0 means unlimited.
|
||||
* A track that is liked and also recently played counts against Liked
|
||||
* only. Both caps apply as soon as they change ([TwoBucketCacheEvictor]).
|
||||
* - [prefetchWindow]: 1..10. Number of next-tracks `AudioPrefetcher`
|
||||
* pre-downloads.
|
||||
* - [cacheLikedTracks]: when true, liking a track should also pin its
|
||||
* audio to the liked-cache bucket. Nothing reads it yet, and the
|
||||
* Storage card hides this control.
|
||||
* - [cacheLikedTracks]: "Keep liked songs offline". When true,
|
||||
* `LikedAudioPinner` downloads liked tracks into the Liked budget on
|
||||
* Wi-Fi, most recently liked first, while the budget has room.
|
||||
*
|
||||
* Defaults: 5 GiB per bucket, prefetch=5, cache-liked=true.
|
||||
*/
|
||||
|
||||
Vendored
+112
@@ -0,0 +1,112 @@
|
||||
package com.fabledsword.minstrel.cache.audiocache
|
||||
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.datasource.cache.Cache
|
||||
import androidx.media3.datasource.cache.CacheEvictor
|
||||
import androidx.media3.datasource.cache.CacheSpan
|
||||
import javax.inject.Inject
|
||||
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)
|
||||
|
||||
/**
|
||||
* The audio cache's eviction policy: two budgets, Liked songs and Recently
|
||||
* played, each with its own cap and its own least-recently-used order (see
|
||||
* [BucketLedger]). SimpleCache takes exactly one evictor, so this one
|
||||
* carries both budgets.
|
||||
*
|
||||
* [CacheBudgetSync] feeds it the signed-in user's liked set and the caps
|
||||
* from Storage settings, so a like, an unlike or a cap change applies at
|
||||
* once, without restarting the app.
|
||||
*
|
||||
* Locking: SimpleCache calls every [CacheEvictor] method while holding its
|
||||
* own monitor. Outside calls take the cache's monitor first and the
|
||||
* ledger's second, the same order as those callbacks, so the two never
|
||||
* deadlock.
|
||||
*/
|
||||
@Singleton
|
||||
class TwoBucketCacheEvictor @Inject constructor() : CacheEvictor {
|
||||
private val ledger = BucketLedger<CacheSpan>(
|
||||
keyOf = { it.key },
|
||||
lengthOf = { it.length },
|
||||
lruOrder = compareBy<CacheSpan> { it.lastTouchTimestamp }.then(naturalOrder()),
|
||||
)
|
||||
|
||||
@Volatile private var cache: Cache? = null
|
||||
|
||||
/** Called once the SimpleCache exists, so updates can trim it. */
|
||||
fun attach(cache: Cache) {
|
||||
this.cache = cache
|
||||
}
|
||||
|
||||
/** Apply a new liked set and caps, then trim whatever no longer fits. */
|
||||
fun update(likedIds: Set<String>, likedCapBytes: Long, recentCapBytes: Long) {
|
||||
val c = cache
|
||||
val apply = {
|
||||
ledger.likedCapBytes = likedCapBytes
|
||||
ledger.recentCapBytes = recentCapBytes
|
||||
ledger.setLiked(likedIds)
|
||||
}
|
||||
if (c == null) {
|
||||
synchronized(ledger) { apply() }
|
||||
} else {
|
||||
synchronized(c) {
|
||||
synchronized(ledger) {
|
||||
apply()
|
||||
evict(c, pendingKey = null, pendingBytes = 0L)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun usage(): CacheUsage = synchronized(ledger) {
|
||||
CacheUsage(
|
||||
likedBytes = ledger.bytesIn(CacheBucket.LIKED),
|
||||
recentBytes = ledger.bytesIn(CacheBucket.RECENT),
|
||||
likedRoomBytes = ledger.likedRoomBytes(),
|
||||
)
|
||||
}
|
||||
|
||||
override fun requiresCacheSpanTouches(): Boolean = true
|
||||
|
||||
override fun onCacheInitialized() = Unit
|
||||
|
||||
override fun onStartFile(cache: Cache, key: String, position: Long, length: Long) {
|
||||
synchronized(ledger) {
|
||||
evict(cache, key, if (length == C.LENGTH_UNSET.toLong()) 0L else length)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onSpanAdded(cache: Cache, span: CacheSpan) {
|
||||
synchronized(ledger) {
|
||||
ledger.add(span)
|
||||
evict(cache, pendingKey = null, pendingBytes = 0L)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onSpanRemoved(cache: Cache, span: CacheSpan) {
|
||||
synchronized(ledger) { ledger.remove(span) }
|
||||
}
|
||||
|
||||
override fun onSpanTouched(cache: Cache, oldSpan: CacheSpan, newSpan: CacheSpan) {
|
||||
synchronized(ledger) {
|
||||
ledger.remove(oldSpan)
|
||||
ledger.add(newSpan)
|
||||
evict(cache, pendingKey = null, pendingBytes = 0L)
|
||||
}
|
||||
}
|
||||
|
||||
private fun evict(cache: Cache, pendingKey: String?, pendingBytes: Long) {
|
||||
while (true) {
|
||||
val span = ledger.nextEviction(pendingKey, pendingBytes) ?: return
|
||||
cache.removeSpan(span)
|
||||
// removeSpan reports back through onSpanRemoved; removing here as
|
||||
// well guarantees the loop advances even if it did not.
|
||||
ledger.remove(span)
|
||||
}
|
||||
}
|
||||
}
|
||||
+15
-1
@@ -67,6 +67,9 @@ import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity
|
||||
CachedNotificationEntity::class,
|
||||
CachedNotificationSettingsEntity::class,
|
||||
],
|
||||
// v13: + cached_playlists.coverAlbumIds and createdAt, the albums Home's
|
||||
// shelves draw each playlist tile's picture from and when a mix was
|
||||
// rebuilt. MIGRATION_12_13 adds both empty; the next list refresh fills them.
|
||||
// v12: + auth_session.backgroundDelivery and notifiedUpTo, the device's
|
||||
// background-delivery choice and its shade high-water mark.
|
||||
// v11: + cached_notifications and cached_notification_settings, the
|
||||
@@ -87,7 +90,7 @@ import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity
|
||||
// on auth_session. Versions before v8 rebuild destructively, which is
|
||||
// right for them: the next sync refills every row with the new
|
||||
// columns populated, so there is nothing to migrate by hand.
|
||||
version = 12,
|
||||
version = 13,
|
||||
exportSchema = true,
|
||||
)
|
||||
@TypeConverters(MinstrelTypeConverters::class)
|
||||
@@ -162,3 +165,14 @@ val MIGRATION_11_12: Migration = object : Migration(11, 12) {
|
||||
db.execSQL("ALTER TABLE auth_session ADD COLUMN notifiedUpTo INTEGER")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* v12 → v13: a playlist's cover albums and creation time. Both start empty;
|
||||
* Home refreshes the playlist list on open, which fills them.
|
||||
*/
|
||||
val MIGRATION_12_13: Migration = object : Migration(12, 13) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL("ALTER TABLE cached_playlists ADD COLUMN coverAlbumIds TEXT NOT NULL DEFAULT ''")
|
||||
db.execSQL("ALTER TABLE cached_playlists ADD COLUMN createdAt TEXT NOT NULL DEFAULT ''")
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -37,7 +37,7 @@ object DatabaseModule {
|
||||
// and rebuilds. The sync controller refills the cache from the
|
||||
// server on first launch, so a rebuild loses only the unsynced
|
||||
// mutation queue.
|
||||
.addMigrations(MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12)
|
||||
.addMigrations(MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12, MIGRATION_12_13)
|
||||
.fallbackToDestructiveMigration(dropAllTables = true)
|
||||
.build()
|
||||
|
||||
|
||||
+4
-12
@@ -4,18 +4,10 @@ import androidx.room.TypeConverter
|
||||
import kotlinx.datetime.Instant
|
||||
|
||||
/**
|
||||
* Source category for a cached audio file in `audio_cache_index`.
|
||||
*
|
||||
* - `MANUAL`: user explicitly pinned (e.g. "save for offline")
|
||||
* - `AUTO_LIKED`: auto-cached because the track is liked
|
||||
* - `AUTO_PLAYLIST`: auto-cached because it's in a pinned playlist
|
||||
* - `AUTO_PREFETCH`: pre-warmed by background prefetch heuristics
|
||||
* - `INCIDENTAL`: cached as a side effect of playback streaming
|
||||
*
|
||||
* Eviction priority (first to evict): INCIDENTAL → AUTO_PREFETCH
|
||||
* → AUTO_PLAYLIST → AUTO_LIKED → MANUAL. Only INCIDENTAL is written
|
||||
* today, and SimpleCache evicts by plain LRU, so nothing applies the
|
||||
* order yet.
|
||||
* How a row reached `audio_cache_index`. `CacheIndexer` writes
|
||||
* `INCIDENTAL` (the track was played); the other values are stored names
|
||||
* no writer uses. Eviction does not read this: the audio cache's two
|
||||
* budgets follow the liked set (see `TwoBucketCacheEvictor`).
|
||||
*/
|
||||
enum class CacheSource { MANUAL, AUTO_LIKED, AUTO_PLAYLIST, AUTO_PREFETCH, INCIDENTAL }
|
||||
|
||||
|
||||
-18
@@ -4,7 +4,6 @@ import androidx.room.Dao
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import com.fabledsword.minstrel.cache.db.CacheSource
|
||||
import com.fabledsword.minstrel.cache.db.entities.AudioCacheIndexEntity
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
@@ -32,23 +31,6 @@ interface AudioCacheIndexDao {
|
||||
@Query("SELECT trackId FROM audio_cache_index ORDER BY lastPlayedAt DESC NULLS LAST")
|
||||
suspend fun trackIdsByRecency(): List<String>
|
||||
|
||||
/** Eviction-candidate ordering — oldest lastPlayedAt first within a source. */
|
||||
@Query(
|
||||
"SELECT * FROM audio_cache_index " +
|
||||
"WHERE source = :source " +
|
||||
"ORDER BY lastPlayedAt ASC NULLS FIRST, cachedAt ASC",
|
||||
)
|
||||
suspend fun evictionCandidates(source: CacheSource): List<AudioCacheIndexEntity>
|
||||
|
||||
/** Sum of bytes across rows; the rolling/liked bucket caps compare against this. */
|
||||
@Query("SELECT COALESCE(SUM(sizeBytes), 0) FROM audio_cache_index")
|
||||
suspend fun totalBytes(): Long
|
||||
|
||||
@Query(
|
||||
"SELECT COALESCE(SUM(sizeBytes), 0) FROM audio_cache_index WHERE source = :source",
|
||||
)
|
||||
suspend fun bytesBySource(source: CacheSource): Long
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun upsert(row: AudioCacheIndexEntity)
|
||||
|
||||
|
||||
+7
-3
@@ -10,12 +10,16 @@ import kotlinx.coroutines.flow.Flow
|
||||
|
||||
@Dao
|
||||
interface CachedLikeDao {
|
||||
/** All track IDs the user has liked. Audio-cache eviction uses this set. */
|
||||
/**
|
||||
* The user's liked track IDs, most recently liked first. The audio
|
||||
* cache's Liked budget and the liked-audio downloads read this.
|
||||
*/
|
||||
@Query(
|
||||
"SELECT entityId FROM cached_likes " +
|
||||
"WHERE userId = :userId AND entityType = 'track'",
|
||||
"WHERE userId = :userId AND entityType = 'track' " +
|
||||
"ORDER BY likedAt DESC",
|
||||
)
|
||||
fun observeLikedTrackIds(userId: String): Flow<List<String>>
|
||||
fun observeLikedTrackIdsNewestFirst(userId: String): Flow<List<String>>
|
||||
|
||||
@Query(
|
||||
"SELECT entityId FROM cached_likes " +
|
||||
|
||||
Vendored
+5
-7
@@ -10,13 +10,11 @@ import kotlinx.datetime.Instant
|
||||
* One row per track that has played through the audio cache (see
|
||||
* `CacheIndexer`); SimpleCache, not this table, says what is on disk.
|
||||
*
|
||||
* The `source` column is meant to drive a 2-bucket eviction
|
||||
* (incidental first, then auto-prefetch, manual last). Nothing evicts
|
||||
* by it yet: SimpleCache evicts by plain LRU over the rolling cap.
|
||||
* `cachedAt` = when we downloaded. `lastPlayedAt` = when the user last
|
||||
* played it; drives the offline "recently played" ordering and is the
|
||||
* tiebreaker for LRU eviction within a source bucket. Nullable on
|
||||
* brand-new rows until the first post-cache play touches them.
|
||||
* `source` says how the row arrived (see [CacheSource]); eviction does
|
||||
* not read it. `cachedAt` = when the row was written. `lastPlayedAt` =
|
||||
* when the user last played the track, which orders the offline
|
||||
* "recently played" pool. Nullable on brand-new rows until the first
|
||||
* post-cache play touches them.
|
||||
*/
|
||||
@Entity(tableName = "audio_cache_index")
|
||||
data class AudioCacheIndexEntity(
|
||||
|
||||
+1
-1
@@ -9,7 +9,7 @@ import kotlinx.datetime.Instant
|
||||
* Cache row for one artist.
|
||||
*
|
||||
* Column names follow Kotlin idiom (camelCase) — the schema is purely
|
||||
* internal to the app; the sync controller exchanges snake_case JSON
|
||||
* internal to the app; the sync controller trades snake_case JSON
|
||||
* with the server and our mappers translate at the boundary.
|
||||
*/
|
||||
@Entity(tableName = "cached_artists")
|
||||
|
||||
Vendored
+10
@@ -1,5 +1,6 @@
|
||||
package com.fabledsword.minstrel.cache.db.entities
|
||||
|
||||
import androidx.room.ColumnInfo
|
||||
import androidx.room.Entity
|
||||
import androidx.room.PrimaryKey
|
||||
import kotlinx.datetime.Clock
|
||||
@@ -25,4 +26,13 @@ data class CachedPlaylistEntity(
|
||||
val durationSec: Int = 0,
|
||||
val systemVariant: String? = null,
|
||||
val fetchedAt: Instant = Clock.System.now(),
|
||||
/**
|
||||
* The playlist's cover albums, comma-joined (album ids are UUIDs and
|
||||
* carry no commas). Empty until the list is next refreshed.
|
||||
*/
|
||||
@ColumnInfo(defaultValue = "''")
|
||||
val coverAlbumIds: String = "",
|
||||
/** ISO-8601 creation time; for a system mix, when it was last rebuilt. */
|
||||
@ColumnInfo(defaultValue = "''")
|
||||
val createdAt: String = "",
|
||||
)
|
||||
|
||||
+2
-82
@@ -19,16 +19,15 @@ private const val QUEUED_MESSAGE = "Saved — will sync when online"
|
||||
/**
|
||||
* Stable mutation kinds the queue knows how to replay. Strings are
|
||||
* persisted in `cached_mutations.kind` so renaming a variant breaks
|
||||
* the on-disk queue — only ever add new kinds, never rename.
|
||||
* the on-disk queue — never rename one. A kind can be removed: the
|
||||
* replayer drops rows of a kind it doesn't know.
|
||||
*/
|
||||
object MutationKind {
|
||||
const val LIKE_TOGGLE: String = "like_toggle"
|
||||
const val REQUEST_CREATE: String = "request_create"
|
||||
const val QUARANTINE_UNFLAG: String = "quarantine_unflag"
|
||||
const val PLAYLIST_APPEND: String = "playlist_append"
|
||||
const val QUARANTINE_FLAG: String = "quarantine_flag"
|
||||
const val PLAY_OFFLINE: String = "play_offline"
|
||||
const val REQUEST_CANCEL: String = "request_cancel"
|
||||
const val PLAYBACK_ERROR_REPORT: String = "playback_error_report"
|
||||
|
||||
// Durable close-by-id for a play whose server row is already open
|
||||
@@ -37,12 +36,6 @@ object MutationKind {
|
||||
// background would duplicate the open row and leave it orphaned.
|
||||
const val PLAY_ENDED: String = "play_ended"
|
||||
|
||||
// Suggestion snooze. ONE toggle kind rather than separate
|
||||
// snooze/unsnooze kinds, mirroring LIKE_TOGGLE, so a snooze followed by
|
||||
// an undo collapses to the latest intent instead of replaying as two
|
||||
// opposed calls whose order decides the outcome.
|
||||
const val SUGGESTION_SNOOZE_TOGGLE: String = "suggestion_snooze_toggle"
|
||||
|
||||
// Loudness-normalization preference. The payload is the whole
|
||||
// preference, a target state like the toggles above, so queued changes
|
||||
// collapse to the last one and an older one can never be replayed last.
|
||||
@@ -73,23 +66,6 @@ data class LikeTogglePayload(
|
||||
val desiredState: Boolean,
|
||||
)
|
||||
|
||||
/**
|
||||
* Persisted payload for `MutationKind.REQUEST_CREATE` (a Discover
|
||||
* request that landed during a connectivity hiccup). Optional
|
||||
* fields stay null when not applicable; the replayer rebuilds the
|
||||
* `CreateRequestBody` from these.
|
||||
*/
|
||||
@Serializable
|
||||
data class RequestCreatePayload(
|
||||
val kind: String,
|
||||
val artistMbid: String,
|
||||
val artistName: String,
|
||||
val albumMbid: String? = null,
|
||||
val albumTitle: String? = null,
|
||||
val trackMbid: String? = null,
|
||||
val trackTitle: String? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* Write side of the offline mutation queue; [MutationReplayer] drains it.
|
||||
*
|
||||
@@ -137,11 +113,6 @@ class MutationQueue @Inject constructor(
|
||||
),
|
||||
)
|
||||
|
||||
suspend fun enqueueRequestCreate(payload: RequestCreatePayload): Long = insertUserDriven(
|
||||
MutationKind.REQUEST_CREATE,
|
||||
json.encodeToString(RequestCreatePayload.serializer(), payload),
|
||||
)
|
||||
|
||||
suspend fun enqueueQuarantineUnflag(trackId: String): Long = insertUserDriven(
|
||||
MutationKind.QUARANTINE_UNFLAG,
|
||||
json.encodeToString(
|
||||
@@ -173,25 +144,6 @@ class MutationQueue @Inject constructor(
|
||||
),
|
||||
)
|
||||
|
||||
/**
|
||||
* Queues a suggestion snooze (or its undo) for replay. [desiredSnoozed]
|
||||
* is the TARGET state, so repeated taps collapse to one replay.
|
||||
*
|
||||
* [name] is carried even for an un-snooze, where the server ignores it,
|
||||
* so a single payload shape serves both directions.
|
||||
*/
|
||||
suspend fun enqueueSuggestionSnoozeToggle(
|
||||
mbid: String,
|
||||
name: String,
|
||||
desiredSnoozed: Boolean,
|
||||
): Long = insertUserDriven(
|
||||
MutationKind.SUGGESTION_SNOOZE_TOGGLE,
|
||||
json.encodeToString(
|
||||
SuggestionSnoozeTogglePayload.serializer(),
|
||||
SuggestionSnoozeTogglePayload(mbid, name, desiredSnoozed),
|
||||
),
|
||||
)
|
||||
|
||||
/** Queues the user's whole normalization preference for replay. */
|
||||
suspend fun enqueueNormalizationSet(prefs: NormalizationPrefs): Long = insertUserDriven(
|
||||
MutationKind.NORMALIZATION_SET,
|
||||
@@ -217,14 +169,6 @@ class MutationQueue @Inject constructor(
|
||||
json.encodeToString(NotificationSettingPayload.serializer(), payload),
|
||||
)
|
||||
|
||||
suspend fun enqueueRequestCancel(requestId: String): Long = insertUserDriven(
|
||||
MutationKind.REQUEST_CANCEL,
|
||||
json.encodeToString(
|
||||
RequestCancelPayload.serializer(),
|
||||
RequestCancelPayload(requestId),
|
||||
),
|
||||
)
|
||||
|
||||
suspend fun enqueuePlayOffline(payload: PlayOfflinePayload): Long = dao.insert(
|
||||
CachedMutationEntity(
|
||||
kind = MutationKind.PLAY_OFFLINE,
|
||||
@@ -257,21 +201,6 @@ class MutationQueue @Inject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Persisted payload for `MutationKind.SUGGESTION_SNOOZE_TOGGLE`.
|
||||
* `desiredSnoozed` is the *target* state, matching [LikeTogglePayload], so
|
||||
* the replayer can collapse repeated toggles for one candidate down to the
|
||||
* last intent. Both directions are idempotent server-side: re-snoozing
|
||||
* extends the window, and un-snoozing something already back is a 404 the
|
||||
* replayer treats as permanent (nothing left to do).
|
||||
*/
|
||||
@Serializable
|
||||
data class SuggestionSnoozeTogglePayload(
|
||||
val mbid: String,
|
||||
val name: String,
|
||||
val desiredSnoozed: Boolean,
|
||||
)
|
||||
|
||||
/**
|
||||
* Persisted payload for `MutationKind.QUARANTINE_UNFLAG` — the
|
||||
* `DELETE /api/quarantine/{trackId}` call lost during a connectivity
|
||||
@@ -337,15 +266,6 @@ data class PlayEndedPayload(
|
||||
val durationPlayedMs: Long,
|
||||
)
|
||||
|
||||
/**
|
||||
* Persisted payload for `MutationKind.REQUEST_CANCEL` — the
|
||||
* `POST /api/requests/{id}/cancel` call lost during a connectivity
|
||||
* hiccup. Server is idempotent on re-cancel (already-cancelled
|
||||
* request stays cancelled).
|
||||
*/
|
||||
@Serializable
|
||||
data class RequestCancelPayload(val requestId: String)
|
||||
|
||||
/**
|
||||
* Persisted payload for `MutationKind.PLAYBACK_ERROR_REPORT` — the
|
||||
* `POST /api/playback-errors` call lost during a connectivity hiccup.
|
||||
|
||||
+5
-58
@@ -3,7 +3,6 @@
|
||||
package com.fabledsword.minstrel.cache.mutations
|
||||
|
||||
import com.fabledsword.minstrel.api.endpoints.AppendTracksRequest
|
||||
import com.fabledsword.minstrel.api.endpoints.DiscoverApi
|
||||
import com.fabledsword.minstrel.api.endpoints.EventsApi
|
||||
import com.fabledsword.minstrel.api.endpoints.FlagRequest
|
||||
import com.fabledsword.minstrel.api.endpoints.LikesApi
|
||||
@@ -15,19 +14,16 @@ import com.fabledsword.minstrel.api.endpoints.PlaybackErrorReportRequest
|
||||
import com.fabledsword.minstrel.api.endpoints.PlaybackErrorsApi
|
||||
import com.fabledsword.minstrel.api.endpoints.PlaylistsApi
|
||||
import com.fabledsword.minstrel.api.endpoints.QuarantineApi
|
||||
import com.fabledsword.minstrel.api.endpoints.RequestsApi
|
||||
import com.fabledsword.minstrel.connectivity.NetworkStatusController
|
||||
import com.fabledsword.minstrel.connectivity.ServerHealth
|
||||
import com.fabledsword.minstrel.models.wire.PlayEndedRequest
|
||||
import com.fabledsword.minstrel.models.wire.PlayOfflineRequest
|
||||
import com.fabledsword.minstrel.models.wire.SnoozeSuggestionBody
|
||||
import com.fabledsword.minstrel.auth.AuthStore
|
||||
import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao
|
||||
import com.fabledsword.minstrel.cache.db.entities.CachedMutationEntity
|
||||
import com.fabledsword.minstrel.di.ApplicationScope
|
||||
import com.fabledsword.minstrel.likes.data.LikesRepository
|
||||
import com.fabledsword.minstrel.settings.data.NormalizationPrefs
|
||||
import com.fabledsword.minstrel.models.wire.CreateRequestBody
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.filter
|
||||
@@ -78,11 +74,9 @@ class MutationReplayer @Inject constructor(
|
||||
retrofit: Retrofit,
|
||||
) {
|
||||
private val likesApi: LikesApi = retrofit.create()
|
||||
private val discoverApi: DiscoverApi = retrofit.create()
|
||||
private val quarantineApi: QuarantineApi = retrofit.create()
|
||||
private val playlistsApi: PlaylistsApi = retrofit.create()
|
||||
private val eventsApi: EventsApi = retrofit.create()
|
||||
private val requestsApi: RequestsApi = retrofit.create()
|
||||
private val playbackErrorsApi: PlaybackErrorsApi = retrofit.create()
|
||||
private val meApi: MeApi = retrofit.create()
|
||||
private val notificationsApi: NotificationsApi = retrofit.create()
|
||||
@@ -122,11 +116,11 @@ class MutationReplayer @Inject constructor(
|
||||
|
||||
private suspend fun drain() {
|
||||
val rows = dao.getAll()
|
||||
// Collapse superseded toggles (likes, suggestion snoozes): only the
|
||||
// latest desired state per entity is replayed; older toggles for the
|
||||
// same entity are dropped unsent. Without this, partial-failure +
|
||||
// Collapse superseded toggles (likes, settings): only the latest
|
||||
// desired state per entity is replayed; older toggles for the same
|
||||
// entity are dropped unsent. Without this, partial-failure +
|
||||
// differential retry could replay an older toggle last and invert the
|
||||
// final state — a snooze the user already undid would come back.
|
||||
// final state — an unlike the user already made would be undone.
|
||||
val superseded = supersededToggleIds(rows, json)
|
||||
for (row in rows) {
|
||||
if (row.id in superseded) {
|
||||
@@ -164,15 +158,12 @@ class MutationReplayer @Inject constructor(
|
||||
*/
|
||||
private suspend fun dispatch(row: CachedMutationEntity): Outcome = when (row.kind) {
|
||||
MutationKind.LIKE_TOGGLE -> dispatchLikeToggle(row.payload)
|
||||
MutationKind.REQUEST_CREATE -> dispatchRequestCreate(row.payload)
|
||||
MutationKind.QUARANTINE_UNFLAG -> dispatchQuarantineUnflag(row.payload)
|
||||
MutationKind.PLAYLIST_APPEND -> dispatchPlaylistAppend(row.payload)
|
||||
MutationKind.QUARANTINE_FLAG -> dispatchQuarantineFlag(row.payload)
|
||||
MutationKind.PLAY_OFFLINE -> dispatchPlayOffline(row.payload)
|
||||
MutationKind.PLAY_ENDED -> dispatchPlayEnded(row.payload)
|
||||
MutationKind.REQUEST_CANCEL -> dispatchRequestCancel(row.payload)
|
||||
MutationKind.PLAYBACK_ERROR_REPORT -> dispatchPlaybackErrorReport(row.payload)
|
||||
MutationKind.SUGGESTION_SNOOZE_TOGGLE -> dispatchSuggestionSnoozeToggle(row.payload)
|
||||
MutationKind.NORMALIZATION_SET -> dispatchNormalizationSet(row.payload)
|
||||
MutationKind.NOTIFICATION_READ,
|
||||
MutationKind.NOTIFICATIONS_READ_ALL,
|
||||
@@ -206,22 +197,6 @@ class MutationReplayer @Inject constructor(
|
||||
return Outcome.SENT
|
||||
}
|
||||
|
||||
private suspend fun dispatchRequestCreate(payload: String): Outcome {
|
||||
val decoded = json.decodeFromString(RequestCreatePayload.serializer(), payload)
|
||||
discoverApi.createRequest(
|
||||
CreateRequestBody(
|
||||
kind = decoded.kind,
|
||||
artistMbid = decoded.artistMbid,
|
||||
artistName = decoded.artistName,
|
||||
albumMbid = decoded.albumMbid,
|
||||
albumTitle = decoded.albumTitle,
|
||||
trackMbid = decoded.trackMbid,
|
||||
trackTitle = decoded.trackTitle,
|
||||
),
|
||||
)
|
||||
return Outcome.SENT
|
||||
}
|
||||
|
||||
private suspend fun dispatchQuarantineUnflag(payload: String): Outcome {
|
||||
val decoded = json.decodeFromString(QuarantineUnflagPayload.serializer(), payload)
|
||||
quarantineApi.unflag(decoded.trackId)
|
||||
@@ -275,30 +250,6 @@ class MutationReplayer @Inject constructor(
|
||||
return Outcome.SENT
|
||||
}
|
||||
|
||||
private suspend fun dispatchRequestCancel(payload: String): Outcome {
|
||||
val decoded = json.decodeFromString(RequestCancelPayload.serializer(), payload)
|
||||
requestsApi.cancel(decoded.requestId)
|
||||
return Outcome.SENT
|
||||
}
|
||||
|
||||
/**
|
||||
* Replays a suggestion snooze in whichever direction the payload asks for.
|
||||
*
|
||||
* The un-snooze branch can legitimately 404 (the row already lapsed, or a
|
||||
* previous attempt landed and the response was lost). [outcomeFor] classes
|
||||
* 404 as permanent → DROP, which is right: the user's intended end state
|
||||
* already holds, so there is nothing left to send.
|
||||
*/
|
||||
private suspend fun dispatchSuggestionSnoozeToggle(payload: String): Outcome {
|
||||
val decoded = json.decodeFromString(SuggestionSnoozeTogglePayload.serializer(), payload)
|
||||
if (decoded.desiredSnoozed) {
|
||||
discoverApi.snoozeSuggestion(decoded.mbid, SnoozeSuggestionBody(name = decoded.name))
|
||||
} else {
|
||||
discoverApi.unsnoozeSuggestion(decoded.mbid)
|
||||
}
|
||||
return Outcome.SENT
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends the queued normalization preference. The device already shows
|
||||
* it, so the server's echo is not written back: a change made since the
|
||||
@@ -354,7 +305,7 @@ class MutationReplayer @Inject constructor(
|
||||
/**
|
||||
* Row ids of desired-state toggles superseded by a later toggle for the same
|
||||
* entity. Applies to every kind whose payload encodes a TARGET state rather
|
||||
* than an action — like-toggles, suggestion snoozes and the
|
||||
* than an action — like-toggles, notification settings and the
|
||||
* normalization preference — because
|
||||
* replaying a stale one last would invert the final state.
|
||||
*
|
||||
@@ -388,10 +339,6 @@ private fun toggleKeyOf(row: CachedMutationEntity, json: Json): String? = when (
|
||||
json.decodeFromString(LikeTogglePayload.serializer(), row.payload)
|
||||
}.getOrNull()?.let { "${row.kind}:${it.entityType}:${it.entityId}" }
|
||||
|
||||
MutationKind.SUGGESTION_SNOOZE_TOGGLE -> runCatching {
|
||||
json.decodeFromString(SuggestionSnoozeTogglePayload.serializer(), row.payload)
|
||||
}.getOrNull()?.let { "${row.kind}:${it.mbid}" }
|
||||
|
||||
MutationKind.NOTIFICATION_SETTING_SET -> runCatching {
|
||||
json.decodeFromString(NotificationSettingPayload.serializer(), row.payload)
|
||||
}.getOrNull()?.let { "${row.kind}:${it.kind}:${it.channel}" }
|
||||
|
||||
+29
@@ -74,6 +74,35 @@ class ConnectivityObserver @Inject constructor(
|
||||
awaitClose { cm.unregisterNetworkCallback(callback) }
|
||||
}.distinctUntilChanged()
|
||||
|
||||
/**
|
||||
* Whether the network the device is using now is unmetered: Wi-Fi or
|
||||
* Ethernet, but not mobile data or a hotspot Android marks metered.
|
||||
* Downloads the user did not start (the liked-song downloads) wait for
|
||||
* this.
|
||||
*/
|
||||
val unmetered: Flow<Boolean> = callbackFlow {
|
||||
val callback = object : ConnectivityManager.NetworkCallback() {
|
||||
override fun onCapabilitiesChanged(
|
||||
network: Network,
|
||||
capabilities: NetworkCapabilities,
|
||||
) {
|
||||
trySend(capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED))
|
||||
}
|
||||
override fun onLost(network: Network) {
|
||||
trySend(false)
|
||||
}
|
||||
}
|
||||
cm.registerDefaultNetworkCallback(callback)
|
||||
trySend(isActiveNetworkUnmetered())
|
||||
awaitClose { cm.unregisterNetworkCallback(callback) }
|
||||
}.distinctUntilChanged()
|
||||
|
||||
private fun isActiveNetworkUnmetered(): Boolean {
|
||||
val caps = cm.activeNetwork?.let { cm.getNetworkCapabilities(it) }
|
||||
return caps != null &&
|
||||
caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
|
||||
}
|
||||
|
||||
private fun hasActiveNetwork(): Boolean {
|
||||
val caps = cm.activeNetwork?.let { cm.getNetworkCapabilities(it) }
|
||||
return caps != null &&
|
||||
|
||||
@@ -70,6 +70,9 @@ class DiagnosticsUploader @Inject constructor(
|
||||
|
||||
/** Coalesces concurrent triggers via tryLock — a drain in flight wins. */
|
||||
private suspend fun drainSafe() {
|
||||
// A trigger at launch can fire before the stored login has loaded;
|
||||
// wait for it, so a signed-in user is not read as signed out.
|
||||
authStore.awaitSessionHydrated()
|
||||
val clientId = authStore.clientId.value
|
||||
// Signed out / no client id yet → nothing to do. Single guard keeps
|
||||
// the return count within the detekt gate.
|
||||
|
||||
-199
@@ -1,199 +0,0 @@
|
||||
package com.fabledsword.minstrel.discover.data
|
||||
|
||||
import com.fabledsword.minstrel.api.endpoints.DiscoverApi
|
||||
import com.fabledsword.minstrel.cache.mutations.MutationQueue
|
||||
import com.fabledsword.minstrel.cache.mutations.RequestCreatePayload
|
||||
import com.fabledsword.minstrel.models.ArtistSuggestionRef
|
||||
import com.fabledsword.minstrel.models.RequestKind
|
||||
import com.fabledsword.minstrel.models.CatalogueResultRef
|
||||
import com.fabledsword.minstrel.models.SeedContributionRef
|
||||
import com.fabledsword.minstrel.models.SuggestionSnoozeRef
|
||||
import com.fabledsword.minstrel.models.wire.ArtistSuggestionWire
|
||||
import com.fabledsword.minstrel.models.wire.CreateRequestBody
|
||||
import com.fabledsword.minstrel.models.wire.CatalogueSearchResultWire
|
||||
import com.fabledsword.minstrel.models.wire.SeedContributionWire
|
||||
import com.fabledsword.minstrel.models.wire.SnoozeSuggestionBody
|
||||
import com.fabledsword.minstrel.models.wire.SuggestionSnoozeWire
|
||||
import retrofit2.HttpException
|
||||
import retrofit2.Retrofit
|
||||
import retrofit2.create
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Outcome of a `createRequest` call — discriminates "server accepted"
|
||||
* from "network down, queued for later replay". The UI uses this to
|
||||
* pick between "Requested" and "Queued" snackbars.
|
||||
*/
|
||||
enum class RequestOutcome { ACCEPTED, QUEUED }
|
||||
|
||||
/**
|
||||
* Read-through Discover surface: catalogue search, suggestion feed, and
|
||||
* the request-creation write path. Writes never go fire-and-forget, so
|
||||
* `createRequest` falls back to the MutationQueue on transport failure.
|
||||
*
|
||||
* Reads are not cached locally — discovery results are inherently
|
||||
* transient (60s server-side LRU), so a local cache would win little.
|
||||
*/
|
||||
@Singleton
|
||||
class DiscoverRepository @Inject constructor(
|
||||
private val mutationQueue: MutationQueue,
|
||||
retrofit: Retrofit,
|
||||
) {
|
||||
private val api: DiscoverApi = retrofit.create()
|
||||
|
||||
suspend fun listSuggestions(): List<ArtistSuggestionRef> =
|
||||
api.listSuggestions().map { it.toDomain() }
|
||||
|
||||
suspend fun listSnoozes(): List<SuggestionSnoozeRef> =
|
||||
api.listSnoozes().map { it.toDomain() }
|
||||
|
||||
/**
|
||||
* Parks a suggestion ("not right now"). Offline-first: on
|
||||
* transport failure the target state is queued for the replayer rather
|
||||
* than dropped.
|
||||
*
|
||||
* Always reports success to the caller. Unlike a request, a snooze has no
|
||||
* meaningful failed state to show — the user asked for a card to go away,
|
||||
* and it will, either now or when the queue drains.
|
||||
*/
|
||||
suspend fun snoozeSuggestion(mbid: String, name: String): Unit = toggleSnooze(
|
||||
mbid = mbid,
|
||||
name = name,
|
||||
desiredSnoozed = true,
|
||||
) { api.snoozeSuggestion(mbid, SnoozeSuggestionBody(name = name)) }
|
||||
|
||||
/** Brings a parked suggestion back. Same offline-first contract. */
|
||||
suspend fun unsnoozeSuggestion(mbid: String, name: String): Unit = toggleSnooze(
|
||||
mbid = mbid,
|
||||
name = name,
|
||||
desiredSnoozed = false,
|
||||
) { api.unsnoozeSuggestion(mbid) }
|
||||
|
||||
private suspend fun toggleSnooze(
|
||||
mbid: String,
|
||||
name: String,
|
||||
desiredSnoozed: Boolean,
|
||||
call: suspend () -> Unit,
|
||||
) {
|
||||
try {
|
||||
call()
|
||||
} catch (e: HttpException) {
|
||||
// A 4xx is the server's considered answer, not a lost call, so
|
||||
// queueing it would be wrong twice over: the replay is guaranteed
|
||||
// to fail again, and the enqueue would raise a "will sync when
|
||||
// online" snackbar for something already settled. The common case
|
||||
// is a 404 from un-snoozing a row that already lapsed — which is
|
||||
// the end state the user wanted anyway.
|
||||
if (!isPermanent(e.code())) {
|
||||
mutationQueue.enqueueSuggestionSnoozeToggle(mbid, name, desiredSnoozed)
|
||||
}
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
|
||||
) {
|
||||
// Transport failure — intentional swallow, same offline-first
|
||||
// rationale as createRequest above. The queue carries the desired
|
||||
// STATE, so a later undo supersedes this rather than fighting it
|
||||
// on replay.
|
||||
mutationQueue.enqueueSuggestionSnoozeToggle(mbid, name, desiredSnoozed)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirrors MutationReplayer's classification so the enqueue decision here
|
||||
* and the drop decision there can't disagree: 4xx is permanent except the
|
||||
* two "retry me" statuses.
|
||||
*/
|
||||
private fun isPermanent(code: Int): Boolean =
|
||||
code in HTTP_CLIENT_ERR_MIN..HTTP_CLIENT_ERR_MAX &&
|
||||
code != HTTP_TIMEOUT && code != HTTP_TOO_MANY
|
||||
|
||||
suspend fun search(query: String, kind: RequestKind): List<CatalogueResultRef> =
|
||||
api.search(query = query, kind = kind.wire).map { it.toDomain() }
|
||||
|
||||
/**
|
||||
* Fires `POST /api/requests`; on transport failure enqueues a
|
||||
* `RequestCreatePayload` for the Phase-12.2 replayer to drain.
|
||||
* Returns [RequestOutcome.ACCEPTED] when the server responded
|
||||
* 2xx, [RequestOutcome.QUEUED] when the call was buffered.
|
||||
*/
|
||||
suspend fun createRequest(
|
||||
kind: RequestKind,
|
||||
artistMbid: String,
|
||||
artistName: String,
|
||||
albumMbid: String? = null,
|
||||
albumTitle: String? = null,
|
||||
trackMbid: String? = null,
|
||||
trackTitle: String? = null,
|
||||
): RequestOutcome {
|
||||
val payload = RequestCreatePayload(
|
||||
kind = kind.wire,
|
||||
artistMbid = artistMbid,
|
||||
artistName = artistName,
|
||||
albumMbid = albumMbid?.ifEmpty { null },
|
||||
albumTitle = albumTitle?.ifEmpty { null },
|
||||
trackMbid = trackMbid?.ifEmpty { null },
|
||||
trackTitle = trackTitle?.ifEmpty { null },
|
||||
)
|
||||
return try {
|
||||
api.createRequest(payload.toBody())
|
||||
RequestOutcome.ACCEPTED
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
|
||||
) {
|
||||
// Intentional swallow — see LikesRepository.toggleLike for
|
||||
// the same offline-first rationale.
|
||||
mutationQueue.enqueueRequestCreate(payload)
|
||||
RequestOutcome.QUEUED
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val HTTP_CLIENT_ERR_MIN = 400
|
||||
const val HTTP_CLIENT_ERR_MAX = 499
|
||||
const val HTTP_TIMEOUT = 408
|
||||
const val HTTP_TOO_MANY = 429
|
||||
}
|
||||
}
|
||||
|
||||
// ── Mappers (internal — wire types stay out of UI) ──
|
||||
|
||||
private fun CatalogueSearchResultWire.toDomain(): CatalogueResultRef = CatalogueResultRef(
|
||||
mbid = mbid,
|
||||
name = name,
|
||||
secondaryText = secondaryText,
|
||||
imageUrl = imageUrl,
|
||||
artistMbid = artistMbid,
|
||||
albumMbid = albumMbid,
|
||||
inLibrary = inLibrary,
|
||||
requested = requested,
|
||||
)
|
||||
|
||||
private fun ArtistSuggestionWire.toDomain(): ArtistSuggestionRef = ArtistSuggestionRef(
|
||||
mbid = mbid,
|
||||
name = name,
|
||||
imageUrl = imageUrl,
|
||||
attribution = attribution.map { it.toDomain() },
|
||||
matchedTags = matchedTags,
|
||||
)
|
||||
|
||||
private fun SeedContributionWire.toDomain(): SeedContributionRef = SeedContributionRef(
|
||||
name = name,
|
||||
isLiked = isLiked,
|
||||
)
|
||||
|
||||
private fun SuggestionSnoozeWire.toDomain(): SuggestionSnoozeRef = SuggestionSnoozeRef(
|
||||
mbid = mbid,
|
||||
name = name,
|
||||
snoozedUntil = snoozedUntil,
|
||||
)
|
||||
|
||||
private fun RequestCreatePayload.toBody(): CreateRequestBody = CreateRequestBody(
|
||||
kind = kind,
|
||||
artistMbid = artistMbid,
|
||||
artistName = artistName,
|
||||
albumMbid = albumMbid,
|
||||
albumTitle = albumTitle,
|
||||
trackMbid = trackMbid,
|
||||
trackTitle = trackTitle,
|
||||
)
|
||||
@@ -1,353 +0,0 @@
|
||||
package com.fabledsword.minstrel.discover.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.FilterChip
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.navigation.NavHostController
|
||||
import com.composables.icons.lucide.Lucide
|
||||
import com.composables.icons.lucide.Search as LucideSearch
|
||||
import com.fabledsword.minstrel.discover.data.RequestOutcome
|
||||
import com.fabledsword.minstrel.models.ArtistSuggestionRef
|
||||
import com.fabledsword.minstrel.models.RequestKind
|
||||
import com.fabledsword.minstrel.models.CatalogueResultRef
|
||||
import com.fabledsword.minstrel.models.SuggestionSnoozeRef
|
||||
import com.fabledsword.minstrel.nav.Discover
|
||||
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
|
||||
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
|
||||
import com.fabledsword.minstrel.shared.widgets.LoadingCentered
|
||||
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
|
||||
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
// ─── Screen ──────────────────────────────────────────────────────────
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun DiscoverScreen(
|
||||
navController: NavHostController,
|
||||
viewModel: DiscoverViewModel = hiltViewModel(),
|
||||
) {
|
||||
val state by viewModel.state.collectAsStateWithLifecycle()
|
||||
val snackbar = remember { SnackbarHostState() }
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
Scaffold(
|
||||
contentWindowInsets = ShellContentWindowInsets,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
topBar = {
|
||||
MinstrelTopAppBar(
|
||||
title = "Discover",
|
||||
navController = navController,
|
||||
currentRouteName = Discover::class.qualifiedName,
|
||||
onBack = { navController.popBackStack() },
|
||||
)
|
||||
},
|
||||
snackbarHost = { SnackbarHost(snackbar) },
|
||||
) { inner ->
|
||||
DiscoverBody(
|
||||
inner = inner,
|
||||
state = state,
|
||||
viewModel = viewModel,
|
||||
snackbar = snackbar,
|
||||
scope = scope,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DiscoverBody(
|
||||
inner: androidx.compose.foundation.layout.PaddingValues,
|
||||
state: DiscoverState,
|
||||
viewModel: DiscoverViewModel,
|
||||
snackbar: SnackbarHostState,
|
||||
scope: kotlinx.coroutines.CoroutineScope,
|
||||
) {
|
||||
Column(modifier = Modifier.fillMaxSize().padding(inner)) {
|
||||
SearchBar(
|
||||
query = state.query,
|
||||
onQueryChange = viewModel::setQuery,
|
||||
onSubmit = viewModel::runSearch,
|
||||
)
|
||||
KindChips(kind = state.kind, onChange = viewModel::setKind)
|
||||
PullToRefreshScaffold(
|
||||
onRefresh = { viewModel.loadSuggestions().join() },
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
) {
|
||||
when (val r = state.results) {
|
||||
ResultsState.Idle -> SuggestionsPane(
|
||||
state = state.suggestions,
|
||||
locallyRequestedMbids = state.locallyRequestedMbids,
|
||||
snoozeUi = SnoozeUi(
|
||||
locallySnoozedMbids = state.locallySnoozedMbids,
|
||||
snoozes = state.snoozes,
|
||||
// No snackbar on snooze: the row itself flips to "Not
|
||||
// right now" with an Undo, so a snackbar would only
|
||||
// repeat what the user can already see — and cover the
|
||||
// next row while doing it.
|
||||
onSnooze = { s -> scope.launch { viewModel.snoozeSuggestion(s) } },
|
||||
onUnsnooze = { mbid, name ->
|
||||
scope.launch { viewModel.unsnoozeSuggestion(mbid, name) }
|
||||
},
|
||||
),
|
||||
onRequest = { s ->
|
||||
scope.launch {
|
||||
val outcome = viewModel.requestSuggestion(s)
|
||||
snackbar.showSnackbar(snackbarFor(outcome, s.name))
|
||||
}
|
||||
},
|
||||
onRetry = { viewModel.loadSuggestions() },
|
||||
)
|
||||
ResultsState.Loading -> LoadingCentered()
|
||||
is ResultsState.Loaded -> ResultsList(
|
||||
rows = r.items,
|
||||
locallyRequestedMbids = state.locallyRequestedMbids,
|
||||
onRequest = { row ->
|
||||
scope.launch {
|
||||
val outcome = viewModel.requestRow(row)
|
||||
snackbar.showSnackbar(snackbarFor(outcome, row.name))
|
||||
}
|
||||
},
|
||||
)
|
||||
is ResultsState.Error -> ErrorRetry(
|
||||
title = "Search failed",
|
||||
message = r.message,
|
||||
onRetry = viewModel::runSearch,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SearchBar(
|
||||
query: String,
|
||||
onQueryChange: (String) -> Unit,
|
||||
onSubmit: () -> Unit,
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = query,
|
||||
onValueChange = onQueryChange,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
singleLine = true,
|
||||
placeholder = { Text("Search MusicBrainz for new music") },
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
|
||||
keyboardActions = KeyboardActions(onSearch = { onSubmit() }),
|
||||
trailingIcon = {
|
||||
IconButton(onClick = onSubmit) {
|
||||
Icon(Lucide.LucideSearch, contentDescription = "Search")
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun KindChips(kind: RequestKind, onChange: (RequestKind) -> Unit) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 4.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
FilterChip(
|
||||
selected = kind == RequestKind.ARTIST,
|
||||
onClick = { onChange(RequestKind.ARTIST) },
|
||||
label = { Text("Artists") },
|
||||
)
|
||||
FilterChip(
|
||||
selected = kind == RequestKind.ALBUM,
|
||||
onClick = { onChange(RequestKind.ALBUM) },
|
||||
label = { Text("Albums") },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The snooze surface's data and callbacks, bundled rather than threaded
|
||||
* through as separate parameters: the pane carries three actions, and the
|
||||
* signatures stop being readable otherwise.
|
||||
*/
|
||||
private data class SnoozeUi(
|
||||
val locallySnoozedMbids: Set<String>,
|
||||
val snoozes: List<SuggestionSnoozeRef>,
|
||||
val onSnooze: (ArtistSuggestionRef) -> Unit,
|
||||
val onUnsnooze: (String, String) -> Unit,
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun SuggestionsPane(
|
||||
state: SuggestionState,
|
||||
locallyRequestedMbids: Set<String>,
|
||||
snoozeUi: SnoozeUi,
|
||||
onRequest: (ArtistSuggestionRef) -> Unit,
|
||||
onRetry: () -> Unit,
|
||||
) {
|
||||
when (state) {
|
||||
SuggestionState.Loading -> LoadingCentered()
|
||||
is SuggestionState.Error -> ErrorRetry(
|
||||
title = "Couldn't load suggestions",
|
||||
message = state.message,
|
||||
onRetry = onRetry,
|
||||
)
|
||||
is SuggestionState.Loaded -> SuggestionsList(
|
||||
items = state.items.filter { it.mbid !in locallyRequestedMbids },
|
||||
snoozeUi = snoozeUi,
|
||||
onRequest = onRequest,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SuggestionsList(
|
||||
items: List<ArtistSuggestionRef>,
|
||||
snoozeUi: SnoozeUi,
|
||||
onRequest: (ArtistSuggestionRef) -> Unit,
|
||||
) {
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(bottom = 16.dp),
|
||||
) {
|
||||
item { SuggestionsHeader() }
|
||||
if (items.isEmpty()) {
|
||||
// An empty deck means one of two things — no listening signal yet,
|
||||
// or "you parked them all" — and telling the second user to go
|
||||
// listen to something would be wrong advice.
|
||||
item {
|
||||
CenteredMessage(
|
||||
if (snoozeUi.snoozes.isEmpty()) {
|
||||
"Listen to or like an artist to fill this in."
|
||||
} else {
|
||||
"Nothing new right now — the artists you've parked are below."
|
||||
},
|
||||
)
|
||||
}
|
||||
} else {
|
||||
items(items = items, key = { it.mbid }) { s ->
|
||||
SuggestionTile(
|
||||
s = s,
|
||||
snoozed = s.mbid in snoozeUi.locallySnoozedMbids,
|
||||
onRequest = { onRequest(s) },
|
||||
onSnooze = { snoozeUi.onSnooze(s) },
|
||||
onUnsnooze = { snoozeUi.onUnsnooze(s.mbid, s.name) },
|
||||
)
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
// Parked candidates live at the bottom of the same scroll, not behind a
|
||||
// separate screen: it's a short list the user rarely needs, but it must
|
||||
// be reachable — a snoozed candidate is gone from the deck above, so
|
||||
// this is the only way back to it.
|
||||
if (snoozeUi.snoozes.isNotEmpty()) {
|
||||
item { SnoozedHeader() }
|
||||
items(items = snoozeUi.snoozes, key = { "snoozed-${it.mbid}" }) { row ->
|
||||
SnoozedTile(
|
||||
row = row,
|
||||
onUnsnooze = { snoozeUi.onUnsnooze(row.mbid, row.name) },
|
||||
)
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SnoozedHeader() {
|
||||
Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp)) {
|
||||
HorizontalDivider(modifier = Modifier.padding(bottom = 12.dp))
|
||||
Text(
|
||||
text = "Not right now",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onBackground,
|
||||
)
|
||||
Text(
|
||||
text = "These come back on their own. Nothing here counts against your taste profile.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SuggestionsHeader() {
|
||||
Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp)) {
|
||||
Text(
|
||||
text = "Suggested for you",
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
color = MaterialTheme.colorScheme.onBackground,
|
||||
)
|
||||
Text(
|
||||
text = "Out-of-library artists drawn from what you've liked and played.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ResultsList(
|
||||
rows: List<CatalogueResultRef>,
|
||||
locallyRequestedMbids: Set<String>,
|
||||
onRequest: (CatalogueResultRef) -> Unit,
|
||||
) {
|
||||
if (rows.isEmpty()) {
|
||||
CenteredMessage("Nothing to add for that search yet.")
|
||||
return
|
||||
}
|
||||
LazyColumn(modifier = Modifier.fillMaxSize()) {
|
||||
items(items = rows, key = { it.mbid }) { row ->
|
||||
ResultTile(
|
||||
row = row,
|
||||
locallyRequested = row.mbid in locallyRequestedMbids,
|
||||
onRequest = { onRequest(row) },
|
||||
)
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CenteredMessage(text: String) {
|
||||
Box(modifier = Modifier.fillMaxSize().padding(24.dp), contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
text = text,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun snackbarFor(outcome: RequestOutcome, name: String): String = when (outcome) {
|
||||
RequestOutcome.ACCEPTED -> "Requested: $name"
|
||||
RequestOutcome.QUEUED -> "Request queued: $name"
|
||||
}
|
||||
@@ -1,191 +0,0 @@
|
||||
package com.fabledsword.minstrel.discover.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.AssistChip
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.composables.icons.lucide.Clock
|
||||
import com.composables.icons.lucide.Disc3
|
||||
import com.composables.icons.lucide.Lucide
|
||||
import com.composables.icons.lucide.User
|
||||
import com.fabledsword.minstrel.models.ArtistSuggestionRef
|
||||
import com.fabledsword.minstrel.models.CatalogueResultRef
|
||||
import com.fabledsword.minstrel.models.SuggestionSnoozeRef
|
||||
import com.fabledsword.minstrel.shared.widgets.ServerImage
|
||||
|
||||
@Composable
|
||||
internal fun SuggestionTile(
|
||||
s: ArtistSuggestionRef,
|
||||
snoozed: Boolean,
|
||||
onRequest: () -> Unit,
|
||||
onSnooze: () -> Unit,
|
||||
onUnsnooze: () -> Unit,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Avatar(imageUrl = s.imageUrl, fallback = Lucide.User, circular = true)
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = s.name,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
// Once parked, the "because you liked X" line is no longer the
|
||||
// useful thing to say — confirming what just happened is.
|
||||
val secondary =
|
||||
if (snoozed) "Not right now — hidden for a while" else s.reasonText
|
||||
if (secondary.isNotEmpty()) {
|
||||
Text(
|
||||
text = secondary,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (snoozed) {
|
||||
TextButton(onClick = onUnsnooze) { Text("Undo") }
|
||||
} else {
|
||||
Button(onClick = onRequest) { Text("Request") }
|
||||
IconButton(onClick = onSnooze) {
|
||||
Icon(
|
||||
imageVector = Lucide.Clock,
|
||||
// The label states what happens and passes no judgement on the
|
||||
// music: never "not for me".
|
||||
contentDescription = "Not right now — hide ${s.name} for a while",
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One row of the parked list. This exists because a snoozed candidate is by
|
||||
* definition absent from the deck above, so without it there is no route back
|
||||
* to an un-snooze once the card has gone.
|
||||
*/
|
||||
@Composable
|
||||
internal fun SnoozedTile(row: SuggestionSnoozeRef, onUnsnooze: () -> Unit) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = row.name,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(
|
||||
text = "Back ${row.returnsIn()}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
TextButton(onClick = onUnsnooze) { Text("Bring back") }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun ResultTile(
|
||||
row: CatalogueResultRef,
|
||||
locallyRequested: Boolean,
|
||||
onRequest: () -> Unit,
|
||||
) {
|
||||
val effectivelyRequested = row.requested || locallyRequested
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Avatar(imageUrl = row.imageUrl, fallback = Lucide.Disc3, circular = false)
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = row.name,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (row.secondaryText.isNotEmpty()) {
|
||||
Text(
|
||||
text = row.secondaryText,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
when {
|
||||
row.inLibrary -> AssistChip(onClick = {}, enabled = false, label = { Text("In library") })
|
||||
effectivelyRequested ->
|
||||
AssistChip(onClick = {}, enabled = false, label = { Text("Requested") })
|
||||
else -> Button(onClick = onRequest) { Text("Request") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Avatar(imageUrl: String, fallback: ImageVector, circular: Boolean) {
|
||||
val clip = if (circular) CircleShape else RoundedCornerShape(6.dp)
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(56.dp)
|
||||
.clip(clip)
|
||||
.background(MaterialTheme.colorScheme.surfaceVariant),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
// The server hands back its own art endpoint (relative),
|
||||
// which answers 404 when no source has an image: ServerImage resolves
|
||||
// the path and shows the icon while loading and on a miss.
|
||||
ServerImage(
|
||||
url = imageUrl,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = fallback,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,206 +0,0 @@
|
||||
package com.fabledsword.minstrel.discover.ui
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.fabledsword.minstrel.api.ErrorCopy
|
||||
import com.fabledsword.minstrel.connectivity.NetworkStatusController
|
||||
import com.fabledsword.minstrel.connectivity.recoveries
|
||||
import com.fabledsword.minstrel.discover.data.DiscoverRepository
|
||||
import com.fabledsword.minstrel.discover.data.RequestOutcome
|
||||
import com.fabledsword.minstrel.models.ArtistSuggestionRef
|
||||
import com.fabledsword.minstrel.models.RequestKind
|
||||
import com.fabledsword.minstrel.models.CatalogueResultRef
|
||||
import com.fabledsword.minstrel.models.SuggestionSnoozeRef
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
|
||||
// ─── State ───────────────────────────────────────────────────────────
|
||||
|
||||
data class DiscoverState(
|
||||
val query: String = "",
|
||||
val kind: RequestKind = RequestKind.ARTIST,
|
||||
val suggestions: SuggestionState = SuggestionState.Loading,
|
||||
val results: ResultsState = ResultsState.Idle,
|
||||
val locallyRequestedMbids: Set<String> = emptySet(),
|
||||
/**
|
||||
* Parked candidates, for the manage list under the feed. Empty is the
|
||||
* normal case and hides the section entirely.
|
||||
*/
|
||||
val snoozes: List<SuggestionSnoozeRef> = emptyList(),
|
||||
/**
|
||||
* Just-snoozed MBIDs. These keep their row visible showing an Undo rather
|
||||
* than yanking it out from under the user's finger; the row is gone on the
|
||||
* next load, and [snoozes] is the way back after that.
|
||||
*/
|
||||
val locallySnoozedMbids: Set<String> = emptySet(),
|
||||
)
|
||||
|
||||
sealed interface SuggestionState {
|
||||
data object Loading : SuggestionState
|
||||
data class Loaded(val items: List<ArtistSuggestionRef>) : SuggestionState
|
||||
data class Error(val message: String) : SuggestionState
|
||||
}
|
||||
|
||||
sealed interface ResultsState {
|
||||
/** No active search — the screen shows the suggestion feed. */
|
||||
data object Idle : ResultsState
|
||||
data object Loading : ResultsState
|
||||
data class Loaded(val items: List<CatalogueResultRef>) : ResultsState
|
||||
data class Error(val message: String) : ResultsState
|
||||
}
|
||||
|
||||
// ─── ViewModel ───────────────────────────────────────────────────────
|
||||
|
||||
@HiltViewModel
|
||||
class DiscoverViewModel @Inject constructor(
|
||||
private val repository: DiscoverRepository,
|
||||
networkStatus: NetworkStatusController,
|
||||
) : ViewModel() {
|
||||
|
||||
private val internal = MutableStateFlow(DiscoverState())
|
||||
val state: StateFlow<DiscoverState> = internal.asStateFlow()
|
||||
|
||||
init {
|
||||
loadSuggestions()
|
||||
// Screen-level auto-recovery: re-run whichever pane
|
||||
// failed while the server was unreachable once health returns.
|
||||
viewModelScope.launch {
|
||||
networkStatus.recoveries().collect {
|
||||
val s = internal.value
|
||||
if (s.suggestions is SuggestionState.Error) loadSuggestions()
|
||||
if (s.results is ResultsState.Error) runSearch()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun setQuery(value: String) {
|
||||
internal.update {
|
||||
// Clearing the box returns to the suggestion feed.
|
||||
val newResults = if (value.isBlank()) ResultsState.Idle else it.results
|
||||
it.copy(query = value, results = newResults)
|
||||
}
|
||||
}
|
||||
|
||||
fun setKind(kind: RequestKind) {
|
||||
internal.update { it.copy(kind = kind) }
|
||||
if (internal.value.query.isNotBlank()) runSearch()
|
||||
}
|
||||
|
||||
fun loadSuggestions(): Job = viewModelScope.launch {
|
||||
internal.update { it.copy(suggestions = SuggestionState.Loading) }
|
||||
try {
|
||||
val items = repository.listSuggestions()
|
||||
internal.update { it.copy(suggestions = SuggestionState.Loaded(items)) }
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
||||
) {
|
||||
internal.update {
|
||||
it.copy(
|
||||
suggestions = SuggestionState.Error(
|
||||
ErrorCopy.fromThrowable(e),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
// Refresh the parked list alongside the deck: a snooze made on another
|
||||
// client should show up here, and one whose window lapsed should drop
|
||||
// off. Sequenced after the deck load rather than raced with it so the
|
||||
// two panes can't disagree about a candidate mid-refresh.
|
||||
loadSnoozes()
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the parked list. Failure is deliberately silent: this is a
|
||||
* secondary pane, and an error banner for it would sit above the suggestion
|
||||
* feed the user actually came for. The list stays as-is and the next
|
||||
* refresh retries.
|
||||
*/
|
||||
private suspend fun loadSnoozes() {
|
||||
try {
|
||||
val rows = repository.listSnoozes()
|
||||
internal.update { it.copy(snoozes = rows) }
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
|
||||
) {
|
||||
// Keep whatever we last showed rather than blanking the section.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parks a suggestion. Flips the row locally first so the tap registers
|
||||
* immediately; the repository handles the offline case, so there is no
|
||||
* failure branch to revert here — unlike the web client, where the fetch
|
||||
* either lands or doesn't.
|
||||
*/
|
||||
suspend fun snoozeSuggestion(s: ArtistSuggestionRef) {
|
||||
internal.update { it.copy(locallySnoozedMbids = it.locallySnoozedMbids + s.mbid) }
|
||||
repository.snoozeSuggestion(s.mbid, s.name)
|
||||
loadSnoozes()
|
||||
}
|
||||
|
||||
/** Brings a parked suggestion back, from either the card or the list. */
|
||||
suspend fun unsnoozeSuggestion(mbid: String, name: String) {
|
||||
internal.update { it.copy(locallySnoozedMbids = it.locallySnoozedMbids - mbid) }
|
||||
repository.unsnoozeSuggestion(mbid, name)
|
||||
loadSnoozes()
|
||||
}
|
||||
|
||||
fun runSearch() {
|
||||
val q = internal.value.query.trim()
|
||||
if (q.isEmpty()) {
|
||||
internal.update { it.copy(results = ResultsState.Idle) }
|
||||
return
|
||||
}
|
||||
viewModelScope.launch {
|
||||
internal.update { it.copy(results = ResultsState.Loading) }
|
||||
try {
|
||||
val rows = repository.search(q, internal.value.kind)
|
||||
internal.update { it.copy(results = ResultsState.Loaded(rows)) }
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
||||
) {
|
||||
internal.update {
|
||||
it.copy(results = ResultsState.Error(ErrorCopy.fromThrowable(e)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Request a search-result row. Returns the outcome (ACCEPTED vs
|
||||
* QUEUED) so the screen can pick the snackbar wording and update
|
||||
* the local "requested" overlay.
|
||||
*/
|
||||
suspend fun requestRow(row: CatalogueResultRef): RequestOutcome {
|
||||
val kind = internal.value.kind
|
||||
val outcome = repository.createRequest(
|
||||
kind = kind,
|
||||
artistMbid = if (kind == RequestKind.ARTIST) row.mbid else row.artistMbid,
|
||||
artistName = if (kind == RequestKind.ARTIST) row.name else row.secondaryText,
|
||||
albumMbid = if (kind == RequestKind.ALBUM) row.mbid else null,
|
||||
albumTitle = if (kind == RequestKind.ALBUM) row.name else null,
|
||||
)
|
||||
markRequested(row.mbid)
|
||||
return outcome
|
||||
}
|
||||
|
||||
suspend fun requestSuggestion(s: ArtistSuggestionRef): RequestOutcome {
|
||||
val outcome = repository.createRequest(
|
||||
kind = RequestKind.ARTIST,
|
||||
artistMbid = s.mbid,
|
||||
artistName = s.name,
|
||||
)
|
||||
markRequested(s.mbid)
|
||||
return outcome
|
||||
}
|
||||
|
||||
private fun markRequested(mbid: String) {
|
||||
internal.update { it.copy(locallyRequestedMbids = it.locallyRequestedMbids + mbid) }
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,8 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.ViewModel
|
||||
@@ -80,11 +82,17 @@ import com.fabledsword.minstrel.nav.AlbumDetail
|
||||
import com.fabledsword.minstrel.nav.ArtistDetail
|
||||
import com.fabledsword.minstrel.nav.Home
|
||||
import com.fabledsword.minstrel.nav.PlaylistDetail
|
||||
import com.fabledsword.minstrel.playlists.assignShelfCovers
|
||||
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.PlaylistCard
|
||||
import com.fabledsword.minstrel.playlists.widgets.GenreBandCard
|
||||
import com.fabledsword.minstrel.playlists.widgets.PlaceholderShape
|
||||
import com.fabledsword.minstrel.playlists.widgets.PlaylistPlaceholderCard
|
||||
import com.fabledsword.minstrel.playlists.widgets.SongsLikeCard
|
||||
import com.fabledsword.minstrel.playlists.widgets.TallPlaylistCard
|
||||
import com.fabledsword.minstrel.playlists.widgets.WidePlaylistCard
|
||||
import com.fabledsword.minstrel.shared.UiState
|
||||
import com.fabledsword.minstrel.shared.UpdateVeilController
|
||||
import com.fabledsword.minstrel.shared.VeilOutcome
|
||||
@@ -102,6 +110,8 @@ import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
|
||||
import com.fabledsword.minstrel.shared.widgets.SkeletonAlbumTile
|
||||
import com.fabledsword.minstrel.shared.widgets.SkeletonArtistTile
|
||||
import com.fabledsword.minstrel.shared.widgets.SkeletonSectionHeader
|
||||
import com.fabledsword.minstrel.update.ui.UpdateNotices
|
||||
import com.fabledsword.minstrel.update.ui.UpdateViewModel
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
@@ -553,6 +563,7 @@ class HomeViewModel @Inject constructor(
|
||||
fun HomeScreen(
|
||||
navController: NavHostController,
|
||||
viewModel: HomeViewModel = hiltViewModel(),
|
||||
updates: UpdateViewModel = hiltViewModel(),
|
||||
) {
|
||||
val snackbarHostState = remember { SnackbarHostState() }
|
||||
LaunchedEffect(Unit) {
|
||||
@@ -575,7 +586,11 @@ fun HomeScreen(
|
||||
val offline by viewModel.offline.collectAsStateWithLifecycle()
|
||||
val updating by viewModel.isUpdating.collectAsStateWithLifecycle()
|
||||
PullToRefreshScaffold(
|
||||
onRefresh = { viewModel.refreshFromPull() },
|
||||
onRefresh = {
|
||||
// A pull asks about a newer app too, so one shows up at once.
|
||||
updates.check()
|
||||
viewModel.refreshFromPull()
|
||||
},
|
||||
modifier = Modifier.fillMaxSize().padding(inner),
|
||||
) {
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
@@ -590,6 +605,7 @@ fun HomeScreen(
|
||||
// hide behind an "Updating your mixes…" wipe that stays up
|
||||
// until the screen has actually stopped moving.
|
||||
UpdatingVeil(visible = updating)
|
||||
UpdateNotices(updates)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -755,6 +771,7 @@ private fun HomeSuccessContent(
|
||||
// pool cards lead the row. Songs-like has its own row below.
|
||||
PlaylistsRow(
|
||||
title = "Playlists",
|
||||
shape = ShelfShape.WIDE,
|
||||
rowItems = buildPlaylistsRow(sections.playlists, systemStatus, offline),
|
||||
offline = offline,
|
||||
onPlaylistClick = onPlaylistClick,
|
||||
@@ -773,6 +790,13 @@ private fun HomeSuccessContent(
|
||||
onPlayPool = onPlayPool,
|
||||
onPlayPlaylist = onPlayPlaylist,
|
||||
)
|
||||
genreMixSection(
|
||||
playlists = sections.playlists,
|
||||
offline = offline,
|
||||
onPlaylistClick = onPlaylistClick,
|
||||
onPlayPool = onPlayPool,
|
||||
onPlayPlaylist = onPlayPlaylist,
|
||||
)
|
||||
youMightLikeSection(
|
||||
albums = sections.youMightLikeAlbums,
|
||||
artists = sections.youMightLikeArtists,
|
||||
@@ -816,6 +840,33 @@ private fun LazyListScope.songsLikeSection(
|
||||
item {
|
||||
PlaylistsRow(
|
||||
title = "Songs like…",
|
||||
shape = ShelfShape.ROUND,
|
||||
rowItems = rowItems,
|
||||
offline = offline,
|
||||
onPlaylistClick = onPlaylistClick,
|
||||
onPlayPool = onPlayPool,
|
||||
onPlayPlaylist = onPlayPlaylist,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The "Your genres" row: one mix per genre the user listens to. Hidden
|
||||
* when there is nothing to show, built or cached.
|
||||
*/
|
||||
private fun LazyListScope.genreMixSection(
|
||||
playlists: List<PlaylistRef>,
|
||||
offline: Boolean,
|
||||
onPlaylistClick: (String) -> Unit,
|
||||
onPlayPool: (OfflinePoolKind) -> Unit,
|
||||
onPlayPlaylist: suspend (PlaylistRef) -> Unit,
|
||||
) {
|
||||
val rowItems = buildGenreMixRow(playlists, offline)
|
||||
if (rowItems.isEmpty()) return
|
||||
item {
|
||||
PlaylistsRow(
|
||||
title = "Your genres",
|
||||
shape = ShelfShape.BAND,
|
||||
rowItems = rowItems,
|
||||
offline = offline,
|
||||
onPlaylistClick = onPlaylistClick,
|
||||
@@ -1080,28 +1131,41 @@ private fun AlbumsRow(
|
||||
items(items = albums, key = { it.id }) { tile ->
|
||||
val album = tile.value
|
||||
if (album == null) {
|
||||
SkeletonAlbumTile()
|
||||
SkeletonAlbumTile(artSize = SECONDARY_ALBUM_ART)
|
||||
} else {
|
||||
AlbumCard(
|
||||
album = album,
|
||||
onClick = { onAlbumClick(album.id) },
|
||||
onPlay = { onPlayAlbum(album.id) },
|
||||
artSize = SECONDARY_ALBUM_ART,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A shelf of playlist tiles in one [shape]. Each tile gets cover albums no
|
||||
* tile before it already shows (assignShelfCovers), and the size and refresh
|
||||
* time the shelf's mixes share go beside the title once (shelfMeta).
|
||||
*/
|
||||
@Composable
|
||||
private fun PlaylistsRow(
|
||||
title: String,
|
||||
shape: ShelfShape,
|
||||
rowItems: List<PlaylistRowItem>,
|
||||
offline: Boolean,
|
||||
onPlaylistClick: (String) -> Unit,
|
||||
onPlayPool: (OfflinePoolKind) -> Unit,
|
||||
onPlayPlaylist: suspend (PlaylistRef) -> Unit,
|
||||
) {
|
||||
HorizontalScrollRow(title = title) {
|
||||
val reals = rowItems.filterIsInstance<PlaylistRowItem.Real>().map { it.playlist }
|
||||
val covers = remember(reals, shape) {
|
||||
reals.map { it.id }.zip(assignShelfCovers(reals, shape.coversPerTile)).toMap()
|
||||
}
|
||||
val meta = remember(reals) { shelfMeta(reals) }
|
||||
val tallWidth = tallCardWidth(shape)
|
||||
HorizontalScrollRow(title = title, meta = meta) {
|
||||
itemsIndexed(items = rowItems) { _, item ->
|
||||
when (item) {
|
||||
is PlaylistRowItem.OfflinePool -> OfflinePoolCard(
|
||||
@@ -1109,28 +1173,78 @@ private fun PlaylistsRow(
|
||||
icon = iconForPool(item.kind),
|
||||
onClick = { onPlayPool(item.kind) },
|
||||
)
|
||||
is PlaylistRowItem.Real -> {
|
||||
is PlaylistRowItem.Real -> ShelfTile(
|
||||
shape = shape,
|
||||
tallWidth = tallWidth,
|
||||
playlist = item.playlist,
|
||||
covers = covers[item.playlist.id].orEmpty(),
|
||||
// Greyed offline when the tile needs the live server or
|
||||
// isn't fully cached — dimmed but still tappable into the
|
||||
// detail to shuffle whatever subset is cached.
|
||||
val greyed = offline && item.playlist.unavailableOffline
|
||||
PlaylistCard(
|
||||
playlist = item.playlist,
|
||||
greyed = offline && item.playlist.unavailableOffline,
|
||||
onClick = { onPlaylistClick(item.playlist.id) },
|
||||
onPlay = { onPlayPlaylist(item.playlist) },
|
||||
playEnabled = item.playlist.trackCount > 0 && !greyed,
|
||||
greyed = greyed,
|
||||
)
|
||||
}
|
||||
is PlaylistRowItem.Placeholder -> PlaylistPlaceholderCard(
|
||||
label = item.label,
|
||||
variant = item.variant,
|
||||
shape = if (tallWidth != null) PlaceholderShape.TALL else shape.placeholder,
|
||||
modifier = if (tallWidth != null) Modifier.width(tallWidth) else Modifier,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* On a narrow screen (a phone held upright) the wide shelf would leave one
|
||||
* playlist in view, so it switches to tall cards sized for two whole cards
|
||||
* and a glimpse of the third. Null keeps the shelf's own shape.
|
||||
*/
|
||||
@Composable
|
||||
private fun tallCardWidth(shape: ShelfShape): Dp? {
|
||||
val screen = LocalConfiguration.current.screenWidthDp.dp
|
||||
return if (shape == ShelfShape.WIDE && screen < COMPACT_WIDTH) {
|
||||
// Row padding at the start, two gaps between cards, the third's glimpse.
|
||||
(screen - ROW_EDGE - ROW_GAP * 2 - NEXT_CARD_GLIMPSE) / 2
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/** One playlist tile in its shelf's shape; a wide one turns tall at [tallWidth]. */
|
||||
@Composable
|
||||
private fun ShelfTile(
|
||||
shape: ShelfShape,
|
||||
tallWidth: Dp?,
|
||||
playlist: PlaylistRef,
|
||||
covers: List<String>,
|
||||
greyed: Boolean,
|
||||
onClick: () -> Unit,
|
||||
onPlay: suspend () -> Unit,
|
||||
) {
|
||||
val playEnabled = playlist.trackCount > 0
|
||||
when {
|
||||
tallWidth != null -> TallPlaylistCard(playlist, covers, tallWidth, onClick, onPlay, playEnabled, greyed)
|
||||
shape == ShelfShape.WIDE -> WidePlaylistCard(playlist, covers, onClick, onPlay, playEnabled, greyed)
|
||||
shape == ShelfShape.ROUND -> SongsLikeCard(playlist, covers, onClick, onPlay, playEnabled, greyed)
|
||||
else -> GenreBandCard(playlist, covers, onClick, onPlay, playEnabled, greyed)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The tile shape a Home playlist shelf uses, so shelves read apart at a
|
||||
* glance: wide cards for the main mixes and playlists, circles for Songs
|
||||
* like (the shape artists have everywhere), colour bands with a fan of
|
||||
* covers for genres. [coversPerTile] is how many distinct covers a tile
|
||||
* shows; [placeholder] is the shape a not-yet-built mix takes on the shelf.
|
||||
*/
|
||||
internal enum class ShelfShape(val coversPerTile: Int, val placeholder: PlaceholderShape) {
|
||||
WIDE(coversPerTile = 1, placeholder = PlaceholderShape.WIDE),
|
||||
ROUND(coversPerTile = 1, placeholder = PlaceholderShape.ROUND),
|
||||
BAND(coversPerTile = 3, placeholder = PlaceholderShape.SQUARE),
|
||||
}
|
||||
|
||||
private fun iconForPool(kind: OfflinePoolKind) = when (kind) {
|
||||
OfflinePoolKind.RECENTLY_PLAYED -> Lucide.History
|
||||
OfflinePoolKind.LIKED -> Lucide.Heart
|
||||
@@ -1225,6 +1339,25 @@ internal fun buildSongsLikeRow(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the "Your genres" row: every genre mix, in name order so the
|
||||
* shelf reads like a stable channel list. No placeholders — a genre mix
|
||||
* needs listening history or a genre-tagged library, so none built means
|
||||
* nothing to show. Offline, fully-cached mixes come first and the rest are
|
||||
* greyed. Mirrors the web Home's genreMixPlaylists.
|
||||
*/
|
||||
internal fun buildGenreMixRow(
|
||||
owned: List<PlaylistRef>,
|
||||
offline: Boolean,
|
||||
): List<PlaylistRowItem> {
|
||||
val mixes = owned
|
||||
.filter { it.systemVariant == "genre_mix" }
|
||||
.sortedBy { it.name.lowercase() }
|
||||
if (!offline) return mixes.map { PlaylistRowItem.Real(it) }
|
||||
val (available, greyed) = mixes.partition { !it.unavailableOffline }
|
||||
return (available + greyed).map { PlaylistRowItem.Real(it) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Curated real-playlist order (system primaries, then secondary, then user).
|
||||
* Must mirror [buildOnlineRow]'s slot order — the offline row reuses this and
|
||||
@@ -1255,6 +1388,20 @@ private fun variantFor(slot: String, s: SystemPlaylistsStatus): String = when {
|
||||
// once generated, are shown in full, uncapped.
|
||||
private const val SONGS_LIKE_PLACEHOLDER_SLOTS = 3
|
||||
|
||||
// Below this width (a phone held upright) the Playlists shelf uses tall
|
||||
// cards; the 600dp line is Material's compact width class.
|
||||
private val COMPACT_WIDTH = 600.dp
|
||||
private val ROW_EDGE = 16.dp
|
||||
private val ROW_GAP = 8.dp
|
||||
private val NEXT_CARD_GLIMPSE = 20.dp
|
||||
|
||||
// Home's shelves step down in size below the playlists, as on web: Recently
|
||||
// added keeps the full 144dp album cover, the You might like and Rediscover
|
||||
// album shelves are smaller, and artist shelves smaller again. The ratios
|
||||
// follow web's 176 / 144 / 128px minimum tile widths.
|
||||
private val SECONDARY_ALBUM_ART = 120.dp
|
||||
private val ARTIST_ART = 104.dp
|
||||
|
||||
/**
|
||||
* The 5 system playlist kinds the server generates that aren't pinned
|
||||
* to Home's primary slots. Order matches `systemPlaylistRegistry` in
|
||||
@@ -1279,12 +1426,13 @@ private fun ArtistsRow(
|
||||
items(items = artists, key = { it.id }) { tile ->
|
||||
val artist = tile.value
|
||||
if (artist == null) {
|
||||
SkeletonArtistTile()
|
||||
SkeletonArtistTile(artSize = ARTIST_ART)
|
||||
} else {
|
||||
ArtistCard(
|
||||
artist = artist,
|
||||
onClick = { onArtistClick(artist.id) },
|
||||
onPlay = { onPlayArtist(artist.id) },
|
||||
artSize = ARTIST_ART,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.composables.icons.lucide.Disc3
|
||||
import com.composables.icons.lucide.Lucide
|
||||
@@ -34,6 +35,9 @@ import androidx.compose.ui.Alignment
|
||||
* circular play button is overlaid at the bottom-right of the cover.
|
||||
* Only Home wires it currently; Library / Discover / detail surfaces
|
||||
* leave it null.
|
||||
*
|
||||
* [artSize] is the cover's side; the tile is 32dp wider for its padding.
|
||||
* Home shrinks it on shelves that rank below Recently added.
|
||||
*/
|
||||
@Composable
|
||||
fun AlbumCard(
|
||||
@@ -41,11 +45,12 @@ fun AlbumCard(
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
onPlay: (suspend () -> Unit)? = null,
|
||||
artSize: Dp = 144.dp,
|
||||
) {
|
||||
val seedCache = LocalDetailSeedCache.current
|
||||
Surface(
|
||||
modifier = modifier
|
||||
.width(176.dp)
|
||||
.width(artSize + 32.dp)
|
||||
.clickable {
|
||||
seedCache.stashAlbum(album)
|
||||
onClick()
|
||||
@@ -56,7 +61,7 @@ fun AlbumCard(
|
||||
CoverTile(
|
||||
url = album.displayCoverUrl,
|
||||
contentDescription = album.title,
|
||||
size = 144.dp,
|
||||
size = artSize,
|
||||
background = MaterialTheme.colorScheme.surfaceVariant,
|
||||
fallback = {
|
||||
Icon(
|
||||
|
||||
@@ -18,6 +18,7 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.composables.icons.lucide.Lucide
|
||||
import com.composables.icons.lucide.User
|
||||
@@ -35,6 +36,9 @@ import com.fabledsword.minstrel.shared.widgets.PlayCircleButton
|
||||
* circular play button is overlaid at the bottom-right of the avatar.
|
||||
* Only Home wires it currently. Padding is 4dp instead of 6dp because
|
||||
* the circular avatar pulls the button visually inward at the corner.
|
||||
*
|
||||
* [artSize] is the avatar's diameter; the tile is 16dp wider for its
|
||||
* padding. Home shrinks it on shelves that rank below the album shelves.
|
||||
*/
|
||||
@Composable
|
||||
fun ArtistCard(
|
||||
@@ -42,11 +46,12 @@ fun ArtistCard(
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
onPlay: (suspend () -> Unit)? = null,
|
||||
artSize: Dp = 128.dp,
|
||||
) {
|
||||
val seedCache = LocalDetailSeedCache.current
|
||||
Surface(
|
||||
modifier = modifier
|
||||
.width(144.dp)
|
||||
.width(artSize + 16.dp)
|
||||
.clickable {
|
||||
seedCache.stashArtist(artist)
|
||||
onClick()
|
||||
@@ -60,7 +65,7 @@ fun ArtistCard(
|
||||
CoverTile(
|
||||
url = artist.displayCoverUrl,
|
||||
contentDescription = artist.name,
|
||||
size = 128.dp,
|
||||
size = artSize,
|
||||
shape = CircleShape,
|
||||
fallback = {
|
||||
Icon(
|
||||
|
||||
@@ -14,14 +14,20 @@ import com.fabledsword.minstrel.models.AlbumRef
|
||||
import com.fabledsword.minstrel.models.ArtistRef
|
||||
import com.fabledsword.minstrel.models.TrackRef
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.filterNotNull
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.flatMapLatest
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.datetime.Clock
|
||||
import retrofit2.Retrofit
|
||||
import retrofit2.create
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
import kotlin.time.Duration.Companion.milliseconds
|
||||
|
||||
/**
|
||||
* Cache-first reads + offline-first writes for likes.
|
||||
@@ -117,6 +123,24 @@ class LikesRepository @Inject constructor(
|
||||
fun observeLikedTrackIds(): Flow<Set<String>> =
|
||||
likeDao.observeLikedIdsOfType(currentUserId(), ENTITY_TRACK).map { it.toSet() }
|
||||
|
||||
/**
|
||||
* The liked track ids of whoever is signed in, most recently liked
|
||||
* first, following sign-in and account changes. Emits nothing while
|
||||
* signed out, so a long-lived collector never mistakes the anonymous
|
||||
* empty set for "no likes".
|
||||
*/
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
fun observeSignedInLikedTrackIdsNewestFirst(): Flow<List<String>> =
|
||||
authController.currentUser
|
||||
.map { it?.id }
|
||||
.distinctUntilChanged()
|
||||
.filterNotNull()
|
||||
.flatMapLatest { userId -> likeDao.observeLikedTrackIdsNewestFirst(userId) }
|
||||
|
||||
/** [observeSignedInLikedTrackIdsNewestFirst] as a set. */
|
||||
fun observeSignedInLikedTrackIds(): Flow<Set<String>> =
|
||||
observeSignedInLikedTrackIdsNewestFirst().map { it.toSet() }
|
||||
|
||||
/** One-shot snapshot of the liked track-id set — for the offline pool filter. */
|
||||
suspend fun likedTrackIds(): Set<String> =
|
||||
likeDao.observeLikedIdsOfType(currentUserId(), ENTITY_TRACK).first().toSet()
|
||||
@@ -166,14 +190,21 @@ class LikesRepository @Inject constructor(
|
||||
* device would stay on the Liked tab forever. The replaceAllForUser
|
||||
* DAO method runs a transactional delete-then-insert so the local
|
||||
* set is exactly what the server reports.
|
||||
*
|
||||
* The server lists each kind most recently liked first but sends no
|
||||
* times, so the rows are stamped a millisecond apart in that order;
|
||||
* `likedAt` then sorts the way the server does.
|
||||
*/
|
||||
suspend fun refreshIds() {
|
||||
val uid = currentUserId()
|
||||
val wire = api.ids()
|
||||
val now = Clock.System.now()
|
||||
fun rowsOf(type: String, ids: List<String>) =
|
||||
ids.mapIndexed { i, id -> CachedLikeEntity(uid, type, id, likedAt = now - i.milliseconds) }
|
||||
val rows = mutableListOf<CachedLikeEntity>()
|
||||
rows += wire.artistIds.map { CachedLikeEntity(uid, ENTITY_ARTIST, it) }
|
||||
rows += wire.albumIds.map { CachedLikeEntity(uid, ENTITY_ALBUM, it) }
|
||||
rows += wire.trackIds.map { CachedLikeEntity(uid, ENTITY_TRACK, it) }
|
||||
rows += rowsOf(ENTITY_ARTIST, wire.artistIds)
|
||||
rows += rowsOf(ENTITY_ALBUM, wire.albumIds)
|
||||
rows += rowsOf(ENTITY_TRACK, wire.trackIds)
|
||||
likeDao.replaceAllForUser(uid, rows)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
package com.fabledsword.minstrel.models
|
||||
|
||||
/**
|
||||
* One admin-side user row. The
|
||||
* admin-scoped variant exposes `autoApproveRequests` and the
|
||||
* One admin-side user row. The admin-scoped variant carries the
|
||||
* canonical `createdAt` that the user-scoped /me response omits.
|
||||
*/
|
||||
data class AdminUserRef(
|
||||
@@ -10,6 +9,5 @@ data class AdminUserRef(
|
||||
val username: String,
|
||||
val displayName: String? = null,
|
||||
val isAdmin: Boolean = false,
|
||||
val autoApproveRequests: Boolean = false,
|
||||
val createdAt: String = "",
|
||||
)
|
||||
|
||||
@@ -1,157 +0,0 @@
|
||||
package com.fabledsword.minstrel.models
|
||||
|
||||
import kotlinx.datetime.Instant
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
* Kind of request being created. Wire form is the lowercase
|
||||
* enum name; the helper [wire] keeps that mapping in one place.
|
||||
*/
|
||||
enum class RequestKind {
|
||||
ARTIST, ALBUM, TRACK;
|
||||
|
||||
val wire: String get() = name.lowercase()
|
||||
}
|
||||
|
||||
/**
|
||||
* Catalogue search hit — `mbid` is the result's own MBID; `artistMbid`
|
||||
* and `albumMbid` are filled when the row is an album/track and the
|
||||
* UI needs the parent IDs to build the request.
|
||||
*
|
||||
* `inLibrary` and `requested` together cover the "already-handled"
|
||||
* cases — UI greys the row + swaps the Request button for a pill.
|
||||
*/
|
||||
data class CatalogueResultRef(
|
||||
val mbid: String,
|
||||
val name: String,
|
||||
val secondaryText: String = "",
|
||||
val imageUrl: String = "",
|
||||
val artistMbid: String = "",
|
||||
val albumMbid: String = "",
|
||||
val inLibrary: Boolean = false,
|
||||
val requested: Boolean = false,
|
||||
)
|
||||
|
||||
/**
|
||||
* Per-seed attribution string for a suggestion — "you liked X" /
|
||||
* "you played Y". `isLiked = true` discriminates the verb.
|
||||
*/
|
||||
data class SeedContributionRef(
|
||||
val name: String,
|
||||
val isLiked: Boolean,
|
||||
)
|
||||
|
||||
/**
|
||||
* Out-of-library artist suggestion from `GET /api/discover/suggestions`.
|
||||
* `attributionText` names up to 3 seeds with an Oxford comma so the
|
||||
* subtitle reads naturally.
|
||||
*/
|
||||
data class ArtistSuggestionRef(
|
||||
val mbid: String,
|
||||
val name: String,
|
||||
val imageUrl: String = "",
|
||||
val attribution: List<SeedContributionRef> = emptyList(),
|
||||
/** Taste-profile tags this candidate matches, strongest first. */
|
||||
val matchedTags: List<String> = emptyList(),
|
||||
) {
|
||||
val attributionText: String
|
||||
get() {
|
||||
if (attribution.isEmpty()) return ""
|
||||
val phrases = attribution
|
||||
.take(MAX_ATTRIBUTION_PHRASES)
|
||||
.map { "${if (it.isLiked) "liked" else "played"} ${it.name}" }
|
||||
return when (phrases.size) {
|
||||
1 -> "Because you ${phrases[0]}."
|
||||
2 -> "Because you ${phrases[0]} and ${phrases[1]}."
|
||||
else -> "Because you ${phrases[0]}, ${phrases[1]}, and ${phrases[2]}."
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The subtitle line for the card.
|
||||
*
|
||||
* Prefers the taste-tag reason over seed attribution when we have one,
|
||||
* because it describes the MUSIC ("sounds like what you like") rather than
|
||||
* the graph ("adjacent to something you played"). Falls back to
|
||||
* attribution, which is the common case: tag coverage for out-of-library
|
||||
* artists is partial by nature, so most candidates have no matched tags.
|
||||
*
|
||||
* Kept in lockstep with the web client's reasonText() in
|
||||
* SuggestionFeed.svelte — same wording, same Oxford comma.
|
||||
*/
|
||||
val reasonText: String
|
||||
get() {
|
||||
val tags = matchedTags.take(MAX_ATTRIBUTION_PHRASES)
|
||||
return when (tags.size) {
|
||||
0 -> attributionText
|
||||
1 -> "Matches your taste in ${tags[0]}."
|
||||
2 -> "Matches your taste in ${tags[0]} and ${tags[1]}."
|
||||
else -> "Matches your taste in ${tags[0]}, ${tags[1]}, and ${tags[2]}."
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val MAX_ATTRIBUTION_PHRASES = 3
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A suggestion the user parked with "not right now".
|
||||
*
|
||||
* Deliberately NOT a dislike: it carries no verdict on the artist, expires on
|
||||
* its own, and never reaches the taste profile. Anything that treats this as
|
||||
* negative preference signal is a bug.
|
||||
*
|
||||
* [snoozedUntil] is the raw RFC3339 string from the wire. Only the server
|
||||
* decides whether a snooze is still in effect — every row the client receives
|
||||
* already is — so this is read purely to phrase "back in about 3 months".
|
||||
*/
|
||||
data class SuggestionSnoozeRef(
|
||||
val mbid: String,
|
||||
val name: String,
|
||||
val snoozedUntil: String,
|
||||
) {
|
||||
/**
|
||||
* Relative return phrase for the manage list. Relative rather than a
|
||||
* calendar date because the exact day a 90-day snooze lapses is noise the
|
||||
* user never asked for.
|
||||
*
|
||||
* [nowMs] is injectable so this is testable without freezing the clock.
|
||||
* Returns "shortly" for an unparseable or already-past timestamp: the row
|
||||
* is on screen, so the server still considers it snoozed, and guessing is
|
||||
* better than rendering an empty line.
|
||||
*/
|
||||
fun returnsIn(nowMs: Long = System.currentTimeMillis()): String {
|
||||
val remainingMs = runCatching { Instant.parse(snoozedUntil).toEpochMilliseconds() }
|
||||
.getOrNull()?.minus(nowMs)
|
||||
// Two ways to have nothing to state: an unparseable timestamp, or one
|
||||
// already lapsed by our clock though the server still returned the row
|
||||
// (the two disagree). Neither is "today", which would read as a real
|
||||
// prediction.
|
||||
if (remainingMs == null || remainingMs <= 0) return "shortly"
|
||||
val days = (remainingMs.toDouble() / MILLIS_PER_DAY).roundToInt()
|
||||
return when {
|
||||
days < 1 -> "today"
|
||||
days == 1 -> "tomorrow"
|
||||
days < DAYS_BEFORE_MONTHS -> "in $days days"
|
||||
else -> {
|
||||
val months = (days.toDouble() / DAYS_PER_MONTH).roundToInt()
|
||||
if (months == 1) "in about a month" else "in about $months months"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val MILLIS_PER_DAY = 86_400_000.0
|
||||
|
||||
// Below this, days read more naturally than a rounded month count.
|
||||
//
|
||||
// Must be <= DAYS_PER_MONTH, or the singular "in about a month" is
|
||||
// unreachable: a rounded month count of 1 needs 15..44 days, and any
|
||||
// threshold above 30 sends all of those down the days branch instead.
|
||||
// This was 45 and the singular branch was dead code — the unit test
|
||||
// for it is what surfaced that.
|
||||
const val DAYS_BEFORE_MONTHS = 30
|
||||
const val DAYS_PER_MONTH = 30.0
|
||||
}
|
||||
}
|
||||
@@ -21,15 +21,23 @@ data class PlaylistRef(
|
||||
val ownerUsername: String = "",
|
||||
/** All member tracks resident in the audio cache — playable fully offline. */
|
||||
val fullyCached: Boolean = false,
|
||||
/**
|
||||
* Albums whose covers can stand for this playlist, in playlist order. Home
|
||||
* gives each tile one the tiles before it do not already show.
|
||||
*/
|
||||
val coverAlbumIds: List<String> = emptyList(),
|
||||
/** ISO-8601. A system mix is rebuilt in place, so this is when it was last refreshed. */
|
||||
val createdAt: String = "",
|
||||
) {
|
||||
val isSystem: Boolean get() = systemVariant != null
|
||||
|
||||
/**
|
||||
* Whether the "Regenerate" affordance applies: every system playlist
|
||||
* EXCEPT songs_like_artist (the server's songs-like family exposes no
|
||||
* refresh trigger; rebuilds are scheduler-driven).
|
||||
* EXCEPT the kinds with several playlists per user (songs_like_artist,
|
||||
* genre_mix), which the server can't address by kind; those rebuild on
|
||||
* the daily schedule and play by playlist id.
|
||||
*/
|
||||
val refreshable: Boolean get() = isSystem && systemVariant != "songs_like_artist"
|
||||
val refreshable: Boolean get() = isSystem && systemVariant !in PER_PLAYLIST_SYSTEM_VARIANTS
|
||||
|
||||
/**
|
||||
* Can't be relied on while offline — either it needs the live server to
|
||||
@@ -39,6 +47,9 @@ data class PlaylistRef(
|
||||
val unavailableOffline: Boolean get() = refreshable || !fullyCached
|
||||
}
|
||||
|
||||
/** System kinds with several playlists per user, played by playlist id. */
|
||||
private val PER_PLAYLIST_SYSTEM_VARIANTS = setOf("songs_like_artist", "genre_mix")
|
||||
|
||||
/**
|
||||
* One row of a playlist's tracks.
|
||||
*
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
package com.fabledsword.minstrel.models
|
||||
|
||||
/**
|
||||
* Status of a request. Stored on the wire as a plain string;
|
||||
* the typed enum keeps switch / when blocks exhaustive and lets the
|
||||
* UI map directly to a status pill color without raw-string matches.
|
||||
*/
|
||||
enum class RequestStatus {
|
||||
PENDING, APPROVED, REJECTED, COMPLETED, FAILED, UNKNOWN;
|
||||
|
||||
companion object {
|
||||
fun fromWire(s: String): RequestStatus = when (s) {
|
||||
"pending" -> PENDING
|
||||
"approved" -> APPROVED
|
||||
"rejected" -> REJECTED
|
||||
"completed" -> COMPLETED
|
||||
"failed" -> FAILED
|
||||
else -> UNKNOWN
|
||||
}
|
||||
}
|
||||
|
||||
val wire: String get() = name.lowercase()
|
||||
}
|
||||
|
||||
/**
|
||||
* One request the user has submitted, shared between the user-side
|
||||
* `/api/requests` view and the admin cross-user view since the wire
|
||||
* shape is identical.
|
||||
*
|
||||
* `displayName` picks the right field based on kind:
|
||||
* - album → albumTitle (fallback artistName)
|
||||
* - track → trackTitle (fallback artistName)
|
||||
* - artist → artistName
|
||||
*
|
||||
* `listenHrefId` returns the most-specific matched library ID once the
|
||||
* request completes (track → album → artist) so the "Listen" CTA can
|
||||
* navigate to the right detail screen. Returns null until the
|
||||
* server's ingest job populates the matched_* fields.
|
||||
*/
|
||||
data class RequestRef(
|
||||
val id: String,
|
||||
val userId: String,
|
||||
val username: String = "",
|
||||
val status: RequestStatus,
|
||||
val kind: String,
|
||||
val artistName: String,
|
||||
val albumTitle: String? = null,
|
||||
val trackTitle: String? = null,
|
||||
val requestedAt: String,
|
||||
val decidedAt: String? = null,
|
||||
val notes: String? = null,
|
||||
val importedAlbumCount: Int = 0,
|
||||
val importedTrackCount: Int = 0,
|
||||
val matchedTrackId: String? = null,
|
||||
val matchedAlbumId: String? = null,
|
||||
val matchedArtistId: String? = null,
|
||||
) {
|
||||
val displayName: String
|
||||
get() = when (kind) {
|
||||
"album" -> albumTitle ?: artistName
|
||||
"track" -> trackTitle ?: artistName
|
||||
else -> artistName
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,9 @@ package com.fabledsword.minstrel.models
|
||||
* verbatim rather than validated, so an unexpected value is shown rather
|
||||
* than dropped.
|
||||
*
|
||||
* [apkUrl] is server-relative (e.g. `/api/client/apk`).
|
||||
* [apkUrl] is server-relative (e.g. `/api/client/apk`). [sha256] is the
|
||||
* served file's digest, in hex; empty from a server that predates it, and
|
||||
* then a download is judged whole by its size alone.
|
||||
*/
|
||||
data class UpdateInfo(
|
||||
val version: String,
|
||||
@@ -23,4 +25,5 @@ data class UpdateInfo(
|
||||
val channel: String?,
|
||||
val apkUrl: String,
|
||||
val sizeBytes: Long,
|
||||
val sha256: String,
|
||||
)
|
||||
|
||||
@@ -6,8 +6,8 @@ import kotlinx.serialization.Serializable
|
||||
/**
|
||||
* One admin-side user row. Mirrors `adminUserView` from
|
||||
* `internal/api/admin_users.go`. Distinct from the user-scoped /me
|
||||
* profile shape because admin endpoints expose `auto_approve_requests`
|
||||
* and the canonical `created_at`.
|
||||
* profile shape because admin endpoints expose the canonical
|
||||
* `created_at`.
|
||||
*/
|
||||
@Serializable
|
||||
data class AdminUserWire(
|
||||
@@ -15,7 +15,6 @@ data class AdminUserWire(
|
||||
val username: String = "",
|
||||
@SerialName("display_name") val displayName: String? = null,
|
||||
@SerialName("is_admin") val isAdmin: Boolean = false,
|
||||
@SerialName("auto_approve_requests") val autoApproveRequests: Boolean = false,
|
||||
@SerialName("created_at") val createdAt: String = "",
|
||||
)
|
||||
|
||||
|
||||
@@ -1,100 +0,0 @@
|
||||
package com.fabledsword.minstrel.models.wire
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
/**
|
||||
* One row of `GET /api/catalogue/search` (the MusicBrainz search). Mirrors
|
||||
* `web/src/lib/api/types.ts` CatalogueSearchResult. `imageUrl` is the
|
||||
* server's own art endpoint, relative, so it goes through ServerImage.
|
||||
*
|
||||
* `inLibrary` and `requested` let the UI greyout rows the user can't
|
||||
* act on (already imported / already awaiting review). All defaults
|
||||
* empty so missing keys don't throw on decode.
|
||||
*/
|
||||
@Serializable
|
||||
data class CatalogueSearchResultWire(
|
||||
val mbid: String = "",
|
||||
val name: String = "",
|
||||
@SerialName("secondary_text") val secondaryText: String = "",
|
||||
@SerialName("image_url") val imageUrl: String = "",
|
||||
@SerialName("artist_mbid") val artistMbid: String = "",
|
||||
@SerialName("album_mbid") val albumMbid: String = "",
|
||||
@SerialName("in_library") val inLibrary: Boolean = false,
|
||||
val requested: Boolean = false,
|
||||
)
|
||||
|
||||
/**
|
||||
* `GET /api/discover/suggestions` row — an out-of-library artist
|
||||
* surfaced from ListenBrainz-derived seeds. `imageUrl` may be empty.
|
||||
*/
|
||||
@Serializable
|
||||
data class ArtistSuggestionWire(
|
||||
val mbid: String = "",
|
||||
val name: String = "",
|
||||
@SerialName("image_url") val imageUrl: String = "",
|
||||
val attribution: List<SeedContributionWire> = emptyList(),
|
||||
/**
|
||||
* Tags this candidate shares with the user's taste profile, strongest
|
||||
* first (max 3). Absent for most candidates — tag coverage for
|
||||
* out-of-library artists is partial by nature — so the default
|
||||
* empty list is the common case, not an error.
|
||||
*/
|
||||
@SerialName("matched_tags") val matchedTags: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
/**
|
||||
* Per-seed attribution for an ArtistSuggestion — "because you liked X"
|
||||
* / "because you played Y". `isLiked = true` means the seed came from
|
||||
* the user's likes; false means a played-but-not-liked play.
|
||||
*/
|
||||
@Serializable
|
||||
data class SeedContributionWire(
|
||||
val name: String = "",
|
||||
@SerialName("is_liked") val isLiked: Boolean = false,
|
||||
)
|
||||
|
||||
/**
|
||||
* One row of `GET /api/discover/snoozes` — a suggestion the user parked
|
||||
* with "not right now". The server only returns rows that are still in
|
||||
* effect, so the client never compares [snoozedUntil] against the clock to
|
||||
* decide whether to show it; it reads it only to say when the artist comes
|
||||
* back.
|
||||
*/
|
||||
@Serializable
|
||||
data class SuggestionSnoozeWire(
|
||||
val mbid: String = "",
|
||||
val name: String = "",
|
||||
@SerialName("snoozed_until") val snoozedUntil: String = "",
|
||||
@SerialName("created_at") val createdAt: String = "",
|
||||
)
|
||||
|
||||
/**
|
||||
* Body for `POST /api/discover/suggestions/{mbid}/snooze`.
|
||||
*
|
||||
* [name] is required by the server, not decorative: suggestions are
|
||||
* out-of-library, so there is no artists row to resolve a display name from
|
||||
* and the snooze list would have nothing to render. Omitting it is a 400.
|
||||
*
|
||||
* No `days` field. The duration is the server's to own (90 days); pinning it
|
||||
* client-side would freeze the default at whatever this build shipped.
|
||||
*/
|
||||
@Serializable
|
||||
data class SnoozeSuggestionBody(
|
||||
val name: String,
|
||||
)
|
||||
|
||||
/**
|
||||
* Body posted to `POST /api/requests`. Optional fields are emitted only
|
||||
* when non-null server-side; matching that here keeps the wire identical.
|
||||
*/
|
||||
@Serializable
|
||||
data class CreateRequestBody(
|
||||
val kind: String,
|
||||
@SerialName("artist_mbid") val artistMbid: String,
|
||||
@SerialName("artist_name") val artistName: String,
|
||||
@SerialName("album_mbid") val albumMbid: String? = null,
|
||||
@SerialName("album_title") val albumTitle: String? = null,
|
||||
@SerialName("track_mbid") val trackMbid: String? = null,
|
||||
@SerialName("track_title") val trackTitle: String? = null,
|
||||
)
|
||||
@@ -23,6 +23,11 @@ data class PlaylistWire(
|
||||
@SerialName("owner_username") val ownerUsername: String = "",
|
||||
@SerialName("created_at") val createdAt: String = "",
|
||||
@SerialName("updated_at") val updatedAt: String = "",
|
||||
/**
|
||||
* Up to six distinct albums with art, in the order they first appear in
|
||||
* the playlist. Home's shelves pick each tile's picture from these.
|
||||
*/
|
||||
@SerialName("cover_album_ids") val coverAlbumIds: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -79,5 +84,7 @@ data class PlaylistDetailWire(
|
||||
@SerialName("track_count") val trackCount: Int = 0,
|
||||
@SerialName("cover_url") val coverUrl: String = "",
|
||||
@SerialName("owner_username") val ownerUsername: String = "",
|
||||
@SerialName("created_at") val createdAt: String = "",
|
||||
@SerialName("cover_album_ids") val coverAlbumIds: List<String> = emptyList(),
|
||||
val tracks: List<PlaylistTrackWire> = emptyList(),
|
||||
)
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
package com.fabledsword.minstrel.models.wire
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
/**
|
||||
* Wire shape of `requestView` from `internal/api/requests.go` — the
|
||||
* row returned by both `GET /api/requests` (caller's own requests) and
|
||||
* `GET /api/admin/requests` (cross-user admin view).
|
||||
*
|
||||
* Status values: `pending` / `approved` / `rejected` / `completed` /
|
||||
* `failed`. Kind values: `artist` / `album` / `track`.
|
||||
*
|
||||
* `matched_*_id` are set after a completed request ingests into the
|
||||
* local library; the user-side "Listen" affordance picks the most
|
||||
* specific one (track → album → artist).
|
||||
*/
|
||||
@Serializable
|
||||
data class RequestWire(
|
||||
val id: String,
|
||||
@SerialName("user_id") val userId: String = "",
|
||||
// The requester's username. Only `GET /api/admin/requests` sends it.
|
||||
val username: String = "",
|
||||
val status: String = "pending",
|
||||
val kind: String = "artist",
|
||||
@SerialName("artist_name") val artistName: String = "",
|
||||
@SerialName("album_title") val albumTitle: String? = null,
|
||||
@SerialName("track_title") val trackTitle: String? = null,
|
||||
@SerialName("requested_at") val requestedAt: String = "",
|
||||
@SerialName("decided_at") val decidedAt: String? = null,
|
||||
val notes: String? = null,
|
||||
@SerialName("imported_album_count") val importedAlbumCount: Int = 0,
|
||||
@SerialName("imported_track_count") val importedTrackCount: Int = 0,
|
||||
@SerialName("matched_track_id") val matchedTrackId: String? = null,
|
||||
@SerialName("matched_album_id") val matchedAlbumId: String? = null,
|
||||
@SerialName("matched_artist_id") val matchedArtistId: String? = null,
|
||||
)
|
||||
@@ -26,4 +26,5 @@ data class UpdateInfoWire(
|
||||
val channel: String? = null,
|
||||
@SerialName("apk_url") val apkUrl: String = "/api/client/apk",
|
||||
@SerialName("size_bytes") val sizeBytes: Long = 0,
|
||||
val sha256: String = "",
|
||||
)
|
||||
|
||||
@@ -15,12 +15,10 @@ import androidx.navigation.compose.NavHost
|
||||
import androidx.navigation.compose.composable
|
||||
import com.fabledsword.minstrel.admin.ui.AdminLandingScreen
|
||||
import com.fabledsword.minstrel.admin.ui.AdminQuarantineScreen
|
||||
import com.fabledsword.minstrel.admin.ui.AdminRequestsScreen
|
||||
import com.fabledsword.minstrel.admin.ui.AdminTagSourcesScreen
|
||||
import com.fabledsword.minstrel.admin.ui.AdminUsersScreen
|
||||
import com.fabledsword.minstrel.auth.ui.LoginScreen
|
||||
import com.fabledsword.minstrel.auth.ui.ServerUrlScreen
|
||||
import com.fabledsword.minstrel.discover.ui.DiscoverScreen
|
||||
import com.fabledsword.minstrel.home.ui.HomeScreen
|
||||
import com.fabledsword.minstrel.library.ui.AlbumDetailScreen
|
||||
import com.fabledsword.minstrel.library.ui.ArtistDetailScreen
|
||||
@@ -31,7 +29,6 @@ import com.fabledsword.minstrel.player.ui.NowPlayingScreen
|
||||
import com.fabledsword.minstrel.player.ui.QueueScreen
|
||||
import com.fabledsword.minstrel.playlists.ui.PlaylistDetailScreen
|
||||
import com.fabledsword.minstrel.playlists.ui.PlaylistsListScreen
|
||||
import com.fabledsword.minstrel.requests.ui.RequestsScreen
|
||||
import com.fabledsword.minstrel.search.ui.SearchScreen
|
||||
import com.fabledsword.minstrel.settings.ui.SettingsScreen
|
||||
import com.fabledsword.minstrel.shared.widgets.ShellScaffold
|
||||
@@ -92,13 +89,6 @@ private fun NavGraphBuilder.inShellTopLevel(
|
||||
}
|
||||
}
|
||||
}
|
||||
composable<Discover> {
|
||||
WithAnimatedScope {
|
||||
ShellScaffold(onExpandPlayer = expandPlayer) {
|
||||
DiscoverScreen(navController = navController)
|
||||
}
|
||||
}
|
||||
}
|
||||
composable<Playlists> {
|
||||
WithAnimatedScope {
|
||||
ShellScaffold(onExpandPlayer = expandPlayer) {
|
||||
@@ -120,13 +110,6 @@ private fun NavGraphBuilder.inShellTopLevel(
|
||||
}
|
||||
}
|
||||
}
|
||||
composable<Requests> {
|
||||
WithAnimatedScope {
|
||||
ShellScaffold(onExpandPlayer = expandPlayer) {
|
||||
RequestsScreen(navController = navController)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -172,13 +155,6 @@ private fun NavGraphBuilder.inShellDetail(
|
||||
}
|
||||
}
|
||||
}
|
||||
composable<AdminRequests> {
|
||||
WithAnimatedScope {
|
||||
ShellScaffold(onExpandPlayer = expandPlayer) {
|
||||
AdminRequestsScreen(navController = navController)
|
||||
}
|
||||
}
|
||||
}
|
||||
composable<AdminQuarantine> {
|
||||
WithAnimatedScope {
|
||||
ShellScaffold(onExpandPlayer = expandPlayer) {
|
||||
|
||||
@@ -8,11 +8,9 @@ import kotlinx.serialization.Serializable
|
||||
@Serializable data object Home
|
||||
@Serializable data object Library
|
||||
@Serializable data object Search
|
||||
@Serializable data object Discover
|
||||
@Serializable data object Playlists
|
||||
@Serializable data object Settings
|
||||
@Serializable data object Admin
|
||||
@Serializable data object Requests
|
||||
@Serializable data object Notifications
|
||||
@Serializable data object NotificationSettings
|
||||
|
||||
@@ -21,7 +19,6 @@ import kotlinx.serialization.Serializable
|
||||
@Serializable data class AlbumDetail(val id: String)
|
||||
@Serializable data class ArtistDetail(val id: String)
|
||||
@Serializable data class PlaylistDetail(val id: String)
|
||||
@Serializable data object AdminRequests
|
||||
@Serializable data object AdminQuarantine
|
||||
@Serializable data object AdminUsers
|
||||
@Serializable data object AdminTagSources
|
||||
|
||||
+8
-5
@@ -76,7 +76,7 @@ internal fun announcementFor(fresh: List<CachedNotificationEntity>): Announcemen
|
||||
channel = if (fresh.all { shadeChannelFor(it.kind) == ShadeChannel.LIBRARY_HEALTH }) {
|
||||
ShadeChannel.LIBRARY_HEALTH
|
||||
} else {
|
||||
ShadeChannel.YOUR_REQUESTS
|
||||
ShadeChannel.NEW_MUSIC
|
||||
},
|
||||
lines = fresh.sortedByDescending { it.createdAt }.take(PILE_LINES).map { it.title },
|
||||
)
|
||||
@@ -94,15 +94,18 @@ internal fun phoneOnFor(settings: NotificationSettingsWire?): (String) -> Boolea
|
||||
* user's system-level choice for it.
|
||||
*/
|
||||
internal enum class ShadeChannel(val id: String, val title: String, val description: String) {
|
||||
YOUR_REQUESTS("your_requests", "Your requests", "Approved, declined, and new music arriving"),
|
||||
LIBRARY_HEALTH("library_health", "Library health", "For admins: requests to review and library problems"),
|
||||
NEW_MUSIC("new_music", "New music", "Albums arriving in the library"),
|
||||
LIBRARY_HEALTH("library_health", "Library health", "For admins: flagged tracks and library problems"),
|
||||
}
|
||||
|
||||
private val requesterKinds = setOf("request_approved", "request_rejected", "request_completed")
|
||||
/** Channel ids the app does not post to; deleted at startup so system settings lists only live ones. */
|
||||
internal val retiredShadeChannelIds = listOf("your_requests")
|
||||
|
||||
private val listenerKinds = setOf("new_music")
|
||||
|
||||
/** Everything a listener can receive is theirs; the rest is admin work. */
|
||||
internal fun shadeChannelFor(kind: String): ShadeChannel =
|
||||
if (kind in requesterKinds) ShadeChannel.YOUR_REQUESTS else ShadeChannel.LIBRARY_HEALTH
|
||||
if (kind in listenerKinds) ShadeChannel.NEW_MUSIC else ShadeChannel.LIBRARY_HEALTH
|
||||
|
||||
/** The delivery service runs exactly while signed in with background delivery on. */
|
||||
internal fun deliveryWanted(signedIn: Boolean, enabled: Boolean): Boolean = signedIn && enabled
|
||||
|
||||
+1
@@ -79,6 +79,7 @@ class NotificationPoster @Inject constructor(
|
||||
|
||||
private fun ensureChannels() {
|
||||
val manager = context.getSystemService(NotificationManager::class.java) ?: return
|
||||
retiredShadeChannelIds.forEach { manager.deleteNotificationChannel(it) }
|
||||
ShadeChannel.entries.forEach { c ->
|
||||
manager.createNotificationChannel(
|
||||
NotificationChannel(c.id, c.title, NotificationManager.IMPORTANCE_DEFAULT)
|
||||
|
||||
+5
-5
@@ -2,14 +2,14 @@ package com.fabledsword.minstrel.notifications.ui
|
||||
|
||||
import com.fabledsword.minstrel.nav.Admin
|
||||
import com.fabledsword.minstrel.nav.AdminQuarantine
|
||||
import com.fabledsword.minstrel.nav.AdminRequests
|
||||
import com.fabledsword.minstrel.nav.AlbumDetail
|
||||
import com.fabledsword.minstrel.nav.ArtistDetail
|
||||
import com.fabledsword.minstrel.nav.Requests
|
||||
import com.fabledsword.minstrel.nav.Home
|
||||
|
||||
/**
|
||||
* The app screen for a notice's link. The server writes web paths, the same
|
||||
* for every client; this maps them onto the app's routes. The library's
|
||||
* for every client; this maps them onto the app's routes. "/" is Home,
|
||||
* where several new albums at once are found under Recently added. The library's
|
||||
* health pages sit under Collection on the web: Reports opens the
|
||||
* app's report screen, and the ones the app has no screen for (duplicates,
|
||||
* suspect sources, missing files) open the Admin landing, as do other Admin
|
||||
@@ -20,10 +20,10 @@ private val ADMIN_COLLECTION_PAGES = setOf("duplicates", "suspect-sources", "mis
|
||||
internal fun routeForLink(link: String): Any? {
|
||||
val parts = link.substringBefore('?').trim('/').split('/').filter { it.isNotEmpty() }
|
||||
return when {
|
||||
link.isBlank() -> null
|
||||
parts.isEmpty() -> Home
|
||||
parts.size == 2 && parts[0] == "albums" -> AlbumDetail(parts[1])
|
||||
parts.size == 2 && parts[0] == "artists" -> ArtistDetail(parts[1])
|
||||
parts == listOf("requests") -> Requests
|
||||
parts == listOf("admin", "requests") -> AdminRequests
|
||||
parts == listOf("collection", "reports") -> AdminQuarantine
|
||||
parts.firstOrNull() == "collection" && parts.getOrNull(1) in ADMIN_COLLECTION_PAGES -> Admin
|
||||
parts.firstOrNull() == "admin" -> Admin
|
||||
|
||||
+39
-87
@@ -9,23 +9,17 @@ import android.os.Build
|
||||
import android.provider.Settings
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.selection.toggleable
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
@@ -35,7 +29,6 @@ import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
@@ -45,8 +38,6 @@ import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.LifecycleResumeEffect
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.navigation.NavHostController
|
||||
import com.composables.icons.lucide.ChevronRight
|
||||
import com.composables.icons.lucide.Lucide
|
||||
import com.fabledsword.minstrel.api.endpoints.NotificationKindSettingWire
|
||||
import com.fabledsword.minstrel.api.endpoints.NotificationSettingsWire
|
||||
import com.fabledsword.minstrel.nav.NotificationSettings
|
||||
@@ -54,13 +45,19 @@ import com.fabledsword.minstrel.notifications.data.NotificationChannel
|
||||
import com.fabledsword.minstrel.shared.widgets.LoadingCentered
|
||||
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
|
||||
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
|
||||
import com.fabledsword.minstrel.theme.Muted
|
||||
import com.fabledsword.minstrel.theme.RowChevron
|
||||
import com.fabledsword.minstrel.theme.Section
|
||||
import com.fabledsword.minstrel.theme.SectionEdge
|
||||
import com.fabledsword.minstrel.theme.SectionGap
|
||||
import com.fabledsword.minstrel.theme.SettingRow
|
||||
import com.fabledsword.minstrel.theme.SwitchRow
|
||||
|
||||
private val CELL_WIDTH = 56.dp
|
||||
private val CELL_WIDTH = 48.dp
|
||||
|
||||
/**
|
||||
* Per-user notification settings: a row per kind with a box for each
|
||||
* channel. Rows read as a menu; anything that needs explaining
|
||||
* is one short line.
|
||||
* Per-user notification settings: what this device does, then a row per
|
||||
* kind with a box for each channel.
|
||||
*/
|
||||
@Composable
|
||||
fun NotificationSettingsScreen(
|
||||
@@ -109,29 +106,28 @@ private fun SettingsBody(
|
||||
modifier = modifier
|
||||
.fillMaxSize()
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(vertical = 8.dp),
|
||||
.padding(horizontal = SectionEdge, vertical = SectionEdge),
|
||||
verticalArrangement = Arrangement.spacedBy(SectionGap),
|
||||
) {
|
||||
deviceRows()
|
||||
HeaderRow()
|
||||
Section("This device") { deviceRows() }
|
||||
Section("New music", trailing = { ChannelHeaders() }) {
|
||||
settings.kinds.filter { !it.adminOnly }.forEach { KindRow(it, settings.emailAvailable, onSet) }
|
||||
val adminKinds = settings.kinds.filter { it.adminOnly }
|
||||
if (adminKinds.isNotEmpty()) {
|
||||
SectionLabel("Library health")
|
||||
adminKinds.forEach { KindRow(it, settings.emailAvailable, onSet) }
|
||||
}
|
||||
if (!settings.emailAvailable) {
|
||||
Muted(emailUnavailableLine(settings.emailUnavailableReason, isAdmin))
|
||||
}
|
||||
}
|
||||
val adminKinds = settings.kinds.filter { it.adminOnly }
|
||||
if (adminKinds.isNotEmpty()) {
|
||||
Section("Library health", trailing = { ChannelHeaders() }) {
|
||||
adminKinds.forEach { KindRow(it, settings.emailAvailable, onSet) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The channel names over the boxes, in the section's title line. */
|
||||
@Composable
|
||||
private fun HeaderRow() {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Box(Modifier.weight(1f))
|
||||
private fun ChannelHeaders() {
|
||||
NotificationChannel.entries.forEach { c ->
|
||||
Text(
|
||||
text = channelLabel(c),
|
||||
@@ -142,7 +138,6 @@ private fun HeaderRow() {
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun KindRow(
|
||||
@@ -151,11 +146,7 @@ private fun KindRow(
|
||||
onSet: (String, NotificationChannel, Boolean) -> Unit,
|
||||
) {
|
||||
val label = kindLabel(row.kind)
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(label, modifier = Modifier.weight(1f), style = MaterialTheme.typography.bodyLarge)
|
||||
SettingRow(title = label) {
|
||||
NotificationChannel.entries.forEach { c ->
|
||||
val enabled = channelEnabled(row, c, emailAvailable)
|
||||
Box(Modifier.width(CELL_WIDTH), contentAlignment = Alignment.Center) {
|
||||
@@ -204,60 +195,24 @@ private fun DeviceRows(backgroundDelivery: Boolean, onBackgroundDelivery: (Boole
|
||||
|
||||
@Composable
|
||||
private fun BackgroundDeliveryRow(checked: Boolean, onChange: (Boolean) -> Unit) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.toggleable(value = checked, role = Role.Switch, onValueChange = onChange)
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text("Notifications when the app is closed", style = MaterialTheme.typography.bodyLarge)
|
||||
// The ongoing notice is the price of not using Google's push;
|
||||
// said plainly rather than left to be discovered.
|
||||
Muted("Keeps a quiet notice in the shade, in place of Google's push", padded = false)
|
||||
}
|
||||
Switch(checked = checked, onCheckedChange = null)
|
||||
}
|
||||
// The ongoing notice is the price of not using Google's push; said
|
||||
// plainly rather than left to be discovered.
|
||||
SwitchRow(
|
||||
title = "Notifications when the app is closed",
|
||||
summary = "Keeps a quiet notice in the shade, in place of Google's push",
|
||||
checked = checked,
|
||||
onCheckedChange = onChange,
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PhoneBlockedRow(onClick: () -> Unit) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable(onClick = onClick)
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text("Phone alerts are off", style = MaterialTheme.typography.bodyLarge)
|
||||
Muted("Allow notifications for Minstrel in system settings", padded = false)
|
||||
}
|
||||
Icon(Lucide.ChevronRight, contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SectionLabel(text: String) {
|
||||
Text(
|
||||
text = text,
|
||||
modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 16.dp, bottom = 4.dp),
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Muted(text: String, padded: Boolean = true) {
|
||||
Text(
|
||||
text = text,
|
||||
modifier = if (padded) Modifier.padding(horizontal = 16.dp, vertical = 12.dp) else Modifier,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
SettingRow(
|
||||
title = "Phone alerts are off",
|
||||
summary = "Allow notifications for Minstrel in system settings",
|
||||
tone = MaterialTheme.colorScheme.error,
|
||||
onClick = onClick,
|
||||
) { RowChevron() }
|
||||
}
|
||||
|
||||
private fun openAppNotificationSettings(context: Context) {
|
||||
@@ -293,10 +248,7 @@ internal fun channelLabel(c: NotificationChannel): String = when (c) {
|
||||
|
||||
/** Short row labels, the same as the web's. Unknown kinds show their key. */
|
||||
internal fun kindLabel(kind: String): String = when (kind) {
|
||||
"request_approved" -> "Request approved"
|
||||
"request_rejected" -> "Request declined"
|
||||
"request_completed" -> "New music arrived"
|
||||
"request_pending" -> "Requests to review"
|
||||
"new_music" -> "New music arrived"
|
||||
"quarantine_flagged" -> "Tracks flagged"
|
||||
"scan_failed" -> "Library scan failed"
|
||||
"tracks_missing" -> "Tracks gone missing"
|
||||
|
||||
+1
-1
@@ -80,7 +80,7 @@ fun NotificationsScreen(
|
||||
list == null -> LoadingCentered()
|
||||
list.isEmpty() -> EmptyState(
|
||||
title = "Nothing waiting for you",
|
||||
body = "Requests, new music and anything needing a look will gather here.",
|
||||
body = "Library problems and anything needing a look will gather here.",
|
||||
icon = Lucide.Bell,
|
||||
)
|
||||
else -> LazyColumn(modifier = Modifier.fillMaxSize()) {
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
package com.fabledsword.minstrel.player
|
||||
|
||||
import android.net.Uri
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.datasource.DataSpec
|
||||
import androidx.media3.datasource.cache.CacheDataSource
|
||||
import androidx.media3.datasource.cache.CacheWriter
|
||||
import androidx.media3.datasource.cache.ContentMetadata
|
||||
import androidx.media3.datasource.okhttp.OkHttpDataSource
|
||||
import com.fabledsword.minstrel.auth.AuthStore
|
||||
import com.fabledsword.minstrel.cache.audiocache.TwoBucketCacheEvictor
|
||||
import com.fabledsword.minstrel.cache.db.dao.CachedTrackDao
|
||||
import com.fabledsword.minstrel.connectivity.ConnectivityObserver
|
||||
import com.fabledsword.minstrel.connectivity.NetworkStatusController
|
||||
import com.fabledsword.minstrel.connectivity.ServerHealth
|
||||
import com.fabledsword.minstrel.di.ApplicationScope
|
||||
import com.fabledsword.minstrel.library.data.toDomain
|
||||
import com.fabledsword.minstrel.likes.data.LikesRepository
|
||||
import com.fabledsword.minstrel.models.TrackRef
|
||||
import com.fabledsword.minstrel.shared.resolveServerUrl
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.collectLatest
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.runInterruptible
|
||||
import okhttp3.OkHttpClient
|
||||
import timber.log.Timber
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
// The Liked budget must have room for a track at CD bitrate (1411 kbps)
|
||||
// before one is downloaded, so a download never pushes out liked audio that
|
||||
// is already on the phone. A track of unknown length is assumed to be ten
|
||||
// minutes.
|
||||
private const val CD_BYTES_PER_SECOND = 176_400L
|
||||
private const val UNKNOWN_DURATION_SEC = 600
|
||||
|
||||
/**
|
||||
* Keeps liked songs on the phone: when "Keep liked songs offline" is on,
|
||||
* every liked track's whole audio is downloaded into the cache, where
|
||||
* [TwoBucketCacheEvictor] counts it against the Liked songs budget.
|
||||
*
|
||||
* - Most recently liked first, one track at a time, so the newest likes get
|
||||
* the room and the server is never asked for more than one file at once.
|
||||
* - Only on an unmetered network (Wi-Fi or Ethernet) while the server is
|
||||
* reachable. A like made on mobile data downloads once the phone is back
|
||||
* on Wi-Fi.
|
||||
* - Stops when the Liked budget cannot fit another track. Liked tracks
|
||||
* played after that are still cached as they stream.
|
||||
* - Any change (a like, an unlike, the switch, the network) restarts the
|
||||
* pass, cancelling a download in flight. Tracks already fully on the
|
||||
* phone are skipped without touching the network, and a track whose
|
||||
* download failed is tried again on the next pass.
|
||||
*
|
||||
* Downloads are keyed by track id exactly like playback and
|
||||
* [AudioPrefetcher], so the player reads what this writes.
|
||||
*
|
||||
* Eager-constructed via the construct-the-singleton trick in
|
||||
* `MinstrelApplication`.
|
||||
*/
|
||||
@Singleton
|
||||
class LikedAudioPinner @Inject constructor(
|
||||
@ApplicationScope scope: CoroutineScope,
|
||||
likes: LikesRepository,
|
||||
authStore: AuthStore,
|
||||
connectivity: ConnectivityObserver,
|
||||
serverHealth: NetworkStatusController,
|
||||
private val playerFactory: PlayerFactory,
|
||||
private val evictor: TwoBucketCacheEvictor,
|
||||
private val trackDao: CachedTrackDao,
|
||||
okHttpClient: OkHttpClient,
|
||||
) {
|
||||
private val cacheDataSourceFactory: CacheDataSource.Factory =
|
||||
CacheDataSource.Factory()
|
||||
.setCache(playerFactory.simpleCache)
|
||||
.setUpstreamDataSourceFactory(OkHttpDataSource.Factory(okHttpClient))
|
||||
|
||||
private data class Pass(val likedNewestFirst: List<String>, val enabled: Boolean, val canDownload: Boolean)
|
||||
|
||||
init {
|
||||
scope.launch(Dispatchers.IO) {
|
||||
combine(
|
||||
likes.observeSignedInLikedTrackIdsNewestFirst(),
|
||||
authStore.cacheSettings.map { it.cacheLikedTracks },
|
||||
connectivity.unmetered,
|
||||
serverHealth.state.map { it == ServerHealth.Healthy || it == ServerHealth.Unstable },
|
||||
) { liked, enabled, unmetered, reachable ->
|
||||
Pass(liked, enabled, unmetered && reachable)
|
||||
}
|
||||
.distinctUntilChanged()
|
||||
.collectLatest { pass ->
|
||||
if (pass.enabled && pass.canDownload) pinAll(pass.likedNewestFirst)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun pinAll(likedNewestFirst: List<String>) {
|
||||
for (trackId in likedNewestFirst) {
|
||||
val track = downloadable(trackId)
|
||||
if (track != null) {
|
||||
val durationSec = track.durationSec.takeIf { it > 0 } ?: UNKNOWN_DURATION_SEC
|
||||
if (evictor.usage().likedRoomBytes < durationSec * CD_BYTES_PER_SECOND) return
|
||||
runCatching { runInterruptible { download(track.id, track.streamUrl) } }
|
||||
.onFailure { Timber.d(it, "liked audio: download of %s failed; next pass retries", track.id) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The track, when it still needs downloading and the server can serve it. */
|
||||
private suspend fun downloadable(trackId: String): TrackRef? {
|
||||
if (isFullyCached(trackId)) return null
|
||||
val track = trackDao.getById(trackId)?.toDomain()
|
||||
return track?.takeIf { !it.unavailable && it.streamUrl.isNotBlank() }
|
||||
}
|
||||
|
||||
private fun isFullyCached(trackId: String): Boolean {
|
||||
val cache = playerFactory.simpleCache
|
||||
val length = ContentMetadata.getContentLength(cache.getContentMetadata(trackId))
|
||||
return length != C.LENGTH_UNSET.toLong() && cache.isCached(trackId, 0, length)
|
||||
}
|
||||
|
||||
private fun download(trackId: String, streamUrl: String) {
|
||||
val dataSpec = DataSpec.Builder()
|
||||
.setUri(Uri.parse(resolveServerUrl(streamUrl) ?: streamUrl))
|
||||
.setKey(trackId)
|
||||
.build()
|
||||
CacheWriter(cacheDataSourceFactory.createDataSource(), dataSpec, null, null).cache()
|
||||
}
|
||||
}
|
||||
+180
-55
@@ -14,6 +14,9 @@ import com.fabledsword.minstrel.connectivity.NetworkStatusController
|
||||
import com.fabledsword.minstrel.connectivity.ServerHealth
|
||||
import com.fabledsword.minstrel.player.output.ActiveUpnp
|
||||
import com.fabledsword.minstrel.player.output.ActiveUpnpHolder
|
||||
import com.fabledsword.minstrel.player.output.QueueMode
|
||||
import com.fabledsword.minstrel.player.output.SingleTrackLoader
|
||||
import com.fabledsword.minstrel.player.output.streamUriTrackId
|
||||
import com.fabledsword.minstrel.player.output.upnp.PositionInfo
|
||||
import com.fabledsword.minstrel.player.output.upnp.SoapFaultException
|
||||
import com.fabledsword.minstrel.player.output.upnp.TransportInfo
|
||||
@@ -57,14 +60,21 @@ import timber.log.Timber
|
||||
* wraps that callback into a SharedFlow consumed by the NowPlaying
|
||||
* surface as a snackbar.
|
||||
*
|
||||
* Queue mode: OutputPickerController loads the full queue into Sonos's
|
||||
* native queue via ClearQueue + AddURIToQueue, then points the
|
||||
* transport at x-rincon-queue:<udn>#0. Skip/prev/seekTo delegate to
|
||||
* Queue mode ([ActiveUpnp.queueMode]):
|
||||
* - NATIVE_QUEUE (Sonos): OutputPickerController loads the full queue
|
||||
* into Sonos's native queue via ClearQueue + AddURIToQueue, then points
|
||||
* the transport at x-rincon-queue:<udn>#0. Skip/prev/seekTo delegate to
|
||||
* AVTransport Next/Previous/SeekToTrack so Sonos manages gap-free
|
||||
* advance natively. PollLoop keeps the local cursor aligned to the
|
||||
* track the renderer is actually playing, matched by track identity
|
||||
* (the id in GetPositionInfo's TrackURI) so it survives queue-reload
|
||||
* index drift -- see [syncLocalCursorToRemote].
|
||||
* advance natively.
|
||||
* - SINGLE_TRACK (any other UPnP / DLNA renderer): the renderer holds one
|
||||
* track. Skip/prev/seekTo point it at the track the local cursor moved
|
||||
* to, and each poll lets [SingleTrackLoader] follow or drive the advance
|
||||
* to the next track and supply the queue position the renderer cannot.
|
||||
*
|
||||
* PollLoop keeps the local cursor aligned to the track the renderer is
|
||||
* actually playing, matched by track identity (the id in
|
||||
* GetPositionInfo's TrackURI) so it survives queue-reload index drift --
|
||||
* see [syncLocalCursorToRemote].
|
||||
*/
|
||||
class MinstrelForwardingPlayer(
|
||||
private val delegate: Player,
|
||||
@@ -72,6 +82,7 @@ class MinstrelForwardingPlayer(
|
||||
private val remoteState: RemotePlayerState,
|
||||
private val castNetworkLock: CastNetworkLock,
|
||||
private val networkStatus: NetworkStatusController,
|
||||
private val singleTrack: SingleTrackLoader,
|
||||
private val events: RemoteEvents = RemoteEvents(),
|
||||
) : ForwardingPlayer(delegate) {
|
||||
|
||||
@@ -205,24 +216,56 @@ class MinstrelForwardingPlayer(
|
||||
// drops via isLoadingUpnp() = true; the OutputPickerController
|
||||
// observes the uiState.queue change and runs the resync (re-clears
|
||||
// Sonos's native queue + AddURIToQueue the new tracks + Play).
|
||||
//
|
||||
// The SAME tracks set again (play on the album already queued, from
|
||||
// another track) is not a new queue: the renderer already holds it, and
|
||||
// the uiState collector -- which keys on the track ids -- would never see
|
||||
// a change to resync on, leaving the cast stuck "loading". It is a move
|
||||
// within the queue, so the renderer is pointed at the new track and the
|
||||
// play() that follows goes through.
|
||||
|
||||
override fun setMediaItems(mediaItems: List<MediaItem>) {
|
||||
val sameQueue = holdsSameItems(mediaItems)
|
||||
super.setMediaItems(mediaItems)
|
||||
markPendingResyncIfRemote()
|
||||
afterQueueSet(sameQueue)
|
||||
}
|
||||
|
||||
override fun setMediaItems(mediaItems: List<MediaItem>, resetPosition: Boolean) {
|
||||
val sameQueue = holdsSameItems(mediaItems)
|
||||
super.setMediaItems(mediaItems, resetPosition)
|
||||
markPendingResyncIfRemote()
|
||||
afterQueueSet(sameQueue)
|
||||
}
|
||||
|
||||
override fun setMediaItems(mediaItems: List<MediaItem>, startIndex: Int, startPositionMs: Long) {
|
||||
val sameQueue = holdsSameItems(mediaItems)
|
||||
super.setMediaItems(mediaItems, startIndex, startPositionMs)
|
||||
markPendingResyncIfRemote()
|
||||
afterQueueSet(sameQueue)
|
||||
}
|
||||
|
||||
private fun markPendingResyncIfRemote() {
|
||||
val wasActive = holder.active.value ?: return
|
||||
private fun holdsSameItems(mediaItems: List<MediaItem>): Boolean =
|
||||
mediaItems.size == delegate.mediaItemCount &&
|
||||
mediaItems.indices.all { mediaItems[it].mediaId == delegate.getMediaItemAt(it).mediaId }
|
||||
|
||||
private fun afterQueueSet(sameQueue: Boolean) {
|
||||
val active = holder.active.value ?: return
|
||||
if (!sameQueue) {
|
||||
markPendingResync(active)
|
||||
return
|
||||
}
|
||||
val index = delegate.currentMediaItemIndex
|
||||
val positionMs = delegate.currentPosition.coerceAtLeast(0L)
|
||||
Timber.w(
|
||||
"setMediaItems with the queue %s already holds -- moving to track %d",
|
||||
active.routeName,
|
||||
index + 1,
|
||||
)
|
||||
when (active.queueMode) {
|
||||
QueueMode.SINGLE_TRACK -> startSingleTrack(active, index, positionMs)
|
||||
QueueMode.NATIVE_QUEUE -> seekNativeQueue(active, index, positionMs)
|
||||
}
|
||||
}
|
||||
|
||||
private fun markPendingResync(wasActive: ActiveUpnp) {
|
||||
Timber.w(
|
||||
"setMediaItems while UPnP active (%s) -- marking pending resync",
|
||||
wasActive.routeName,
|
||||
@@ -319,19 +362,19 @@ class MinstrelForwardingPlayer(
|
||||
return
|
||||
}
|
||||
super.seekTo(mediaItemIndex, positionMs)
|
||||
remoteState.beginPendingTransport(
|
||||
SystemClock.elapsedRealtime() + PENDING_TRANSPORT_SAFETY_TIMEOUT_MS,
|
||||
)
|
||||
scope.launch {
|
||||
runCatching {
|
||||
retryTransport {
|
||||
active.avTransport.seekToTrack(mediaItemIndex + 1)
|
||||
when (active.queueMode) {
|
||||
QueueMode.SINGLE_TRACK -> playSingleTrackAt(active, mediaItemIndex, positionMs)
|
||||
QueueMode.NATIVE_QUEUE -> seekNativeQueue(active, mediaItemIndex, positionMs)
|
||||
}
|
||||
}
|
||||
|
||||
private fun seekNativeQueue(active: ActiveUpnp, index: Int, positionMs: Long) {
|
||||
sendNativeQueueCommand(active) {
|
||||
active.avTransport.seekToTrack(index + 1)
|
||||
if (positionMs > 0L) {
|
||||
active.avTransport.seek(positionMs)
|
||||
}
|
||||
}
|
||||
}.onFailure { handleTransportFailure(active, it) }
|
||||
}
|
||||
}
|
||||
|
||||
override fun seekToNextMediaItem() {
|
||||
@@ -349,12 +392,9 @@ class MinstrelForwardingPlayer(
|
||||
// then delegate to Sonos Next. PollLoop reconciles cursor via
|
||||
// Track index if they diverge.
|
||||
super.seekToNextMediaItem()
|
||||
remoteState.beginPendingTransport(
|
||||
SystemClock.elapsedRealtime() + PENDING_TRANSPORT_SAFETY_TIMEOUT_MS,
|
||||
)
|
||||
scope.launch {
|
||||
runCatching { retryTransport { active.avTransport.next() } }
|
||||
.onFailure { handleTransportFailure(active, it) }
|
||||
when (active.queueMode) {
|
||||
QueueMode.SINGLE_TRACK -> playSingleTrackAt(active, delegate.currentMediaItemIndex)
|
||||
QueueMode.NATIVE_QUEUE -> sendNativeQueueCommand(active) { active.avTransport.next() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -372,11 +412,56 @@ class MinstrelForwardingPlayer(
|
||||
// Super first for immediate local cursor advance (UI feedback);
|
||||
// then delegate to Sonos Previous. PollLoop reconciles.
|
||||
super.seekToPreviousMediaItem()
|
||||
when (active.queueMode) {
|
||||
QueueMode.SINGLE_TRACK -> playSingleTrackAt(active, delegate.currentMediaItemIndex)
|
||||
QueueMode.NATIVE_QUEUE -> sendNativeQueueCommand(active) { active.avTransport.previous() }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a track change to a Sonos native queue. The local cursor has
|
||||
* already moved; the pending window holds the poll's cursor sync off
|
||||
* until Sonos reports the new track, so it can't undo the press.
|
||||
*/
|
||||
private fun sendNativeQueueCommand(active: ActiveUpnp, command: suspend () -> Unit) {
|
||||
remoteState.beginPendingTransport(
|
||||
SystemClock.elapsedRealtime() + PENDING_TRANSPORT_SAFETY_TIMEOUT_MS,
|
||||
)
|
||||
scope.launch {
|
||||
runCatching { retryTransport { active.avTransport.previous() } }
|
||||
runCatching { retryTransport { command() } }
|
||||
.onFailure { handleTransportFailure(active, it) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Point a one-track renderer at [index] of the queue, the track the local
|
||||
* cursor was just moved to. The same track as the renderer's is a seek
|
||||
* within it, so next on the last track (the cursor cannot move) sends
|
||||
* nothing rather than restarting the track. The seek after a new track is
|
||||
* best-effort: a renderer still loading the URI may refuse it, and the
|
||||
* track playing from the start beats it not playing.
|
||||
*/
|
||||
private fun playSingleTrackAt(active: ActiveUpnp, index: Int, positionMs: Long = 0L) {
|
||||
if (index == singleTrack.currentIndex) {
|
||||
if (positionMs > 0L) seekTo(positionMs)
|
||||
} else {
|
||||
startSingleTrack(active, index, positionMs)
|
||||
}
|
||||
}
|
||||
|
||||
private fun startSingleTrack(active: ActiveUpnp, index: Int, positionMs: Long) {
|
||||
remoteState.beginPendingTransport(
|
||||
SystemClock.elapsedRealtime() + PENDING_TRANSPORT_SAFETY_TIMEOUT_MS,
|
||||
)
|
||||
scope.launch {
|
||||
runCatching { retryTransport { singleTrack.playIndex(active.avTransport, index) } }
|
||||
.onSuccess {
|
||||
if (positionMs > 0L) {
|
||||
runCatching { active.avTransport.seek(positionMs) }
|
||||
.onFailure { Timber.w(it, "UPnP seek after track change refused") }
|
||||
}
|
||||
pollTrigger.trySend(Unit)
|
||||
}
|
||||
.onFailure { handleTransportFailure(active, it) }
|
||||
}
|
||||
}
|
||||
@@ -611,6 +696,14 @@ class MinstrelForwardingPlayer(
|
||||
*/
|
||||
private suspend fun pollOnce(active: ActiveUpnp) {
|
||||
val info = active.avTransport.getPositionInfo()
|
||||
val transport = active.avTransport.getTransportInfo()
|
||||
val single = pollSingleTrack(active, info, transport)
|
||||
// The loader just started the next track, so this reading describes
|
||||
// the one that ended. Report the new track from its start and leave
|
||||
// the cursor to the new index; the next poll reads it for real.
|
||||
val advanced = single?.advanced == true
|
||||
val rendererTrack = single?.trackNumber ?: info.track
|
||||
val trackUri = if (advanced) "" else info.trackUri
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
val inSeekAckWindow = lastSeekIssuedAtMs > 0L &&
|
||||
(now - lastSeekIssuedAtMs) < SEEK_ACK_WINDOW_MS
|
||||
@@ -618,15 +711,52 @@ class MinstrelForwardingPlayer(
|
||||
// seekTo -- the poll's reported position is stale until Sonos finishes
|
||||
// processing the Seek SOAP. Other fields still refresh from the poll.
|
||||
remoteState.applyPositionInfo(
|
||||
positionMs = if (inSeekAckWindow) remoteState.positionMs else info.relTimeMs,
|
||||
durationMs = info.trackDurationMs,
|
||||
trackUri = info.trackUri,
|
||||
trackNumber = info.track,
|
||||
positionMs = when {
|
||||
advanced -> 0L
|
||||
inSeekAckWindow -> remoteState.positionMs
|
||||
else -> info.relTimeMs
|
||||
},
|
||||
durationMs = durationFor(info, single),
|
||||
trackUri = trackUri,
|
||||
trackNumber = rendererTrack,
|
||||
)
|
||||
syncLocalCursorToRemote(sonosTrack = info.track, trackUri = info.trackUri)
|
||||
events.onRendererTrack(info.track)
|
||||
val transport = active.avTransport.getTransportInfo()
|
||||
when (transport.state) {
|
||||
syncLocalCursorToRemote(sonosTrack = rendererTrack, trackUri = trackUri)
|
||||
if (single == null) events.onRendererTrack(info.track)
|
||||
if (advanced) {
|
||||
applyTransportState(TransportState.PLAYING)
|
||||
} else {
|
||||
applyTransportState(transport.state)
|
||||
observeTransport(transport, info)
|
||||
checkForStall(active, info.trackUri, transport)
|
||||
}
|
||||
notifyRemoteStateChanged()
|
||||
}
|
||||
|
||||
/**
|
||||
* A one-track renderer reports Track=1 whatever it plays; the loader
|
||||
* knows the queue position, and may start the next track from here.
|
||||
* Null for a Sonos, whose native queue answers for itself.
|
||||
*/
|
||||
private suspend fun pollSingleTrack(
|
||||
active: ActiveUpnp,
|
||||
info: PositionInfo,
|
||||
transport: TransportInfo,
|
||||
): SingleTrackLoader.PollOutcome? =
|
||||
if (active.queueMode == QueueMode.SINGLE_TRACK) {
|
||||
singleTrack.onPoll(
|
||||
transport = active.avTransport,
|
||||
trackUri = info.trackUri,
|
||||
state = transport.state,
|
||||
positionMs = info.relTimeMs,
|
||||
durationMs = info.trackDurationMs,
|
||||
playIntent = remoteState.lastPlayIntent,
|
||||
)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
|
||||
private fun applyTransportState(state: TransportState) {
|
||||
when (state) {
|
||||
TransportState.PLAYING -> {
|
||||
nonPlayingPollStreak = 0
|
||||
remoteState.applyTransportPlaying()
|
||||
@@ -643,13 +773,18 @@ class MinstrelForwardingPlayer(
|
||||
remoteState.applyTransportStopped()
|
||||
}
|
||||
}
|
||||
TransportState.TRANSITIONING, TransportState.UNKNOWN -> Unit
|
||||
TransportState.TRANSITIONING, TransportState.NO_MEDIA, TransportState.UNKNOWN -> Unit
|
||||
}
|
||||
observeTransport(transport, info)
|
||||
checkForStall(active, info.trackUri, transport)
|
||||
notifyRemoteStateChanged()
|
||||
}
|
||||
|
||||
/**
|
||||
* The track's duration as the renderer reports it. A one-track renderer
|
||||
* that reports none (some leave TrackDuration at 0:00:00) falls back to
|
||||
* the library's duration, so the scrubber has an end to run to.
|
||||
*/
|
||||
private fun durationFor(info: PositionInfo, single: SingleTrackLoader.PollOutcome?): Long =
|
||||
if (single != null && info.trackDurationMs <= 0L) single.knownDurationMs else info.trackDurationMs
|
||||
|
||||
/**
|
||||
* Ask the watchdog what to make of this poll, and act on its answer.
|
||||
*
|
||||
@@ -711,7 +846,7 @@ class MinstrelForwardingPlayer(
|
||||
)
|
||||
// Tell the user and the admin inbox. Silence here would be the
|
||||
// original bug: playback simply ends and nobody finds out.
|
||||
trackIdFromStreamUri(trackUri)?.let { handler.post { events.onStalled(it) } }
|
||||
streamUriTrackId(trackUri)?.let { handler.post { events.onStalled(it) } }
|
||||
}
|
||||
RemoteStallWatchdog.Decision.None -> Unit
|
||||
}
|
||||
@@ -763,6 +898,9 @@ class MinstrelForwardingPlayer(
|
||||
): RemoteStallWatchdog.QueueState {
|
||||
val stalled = transport.state == TransportState.STOPPED || !transport.statusOk
|
||||
if (!stalled) return RemoteStallWatchdog.QueueState.UNKNOWN
|
||||
// A one-track renderer has no queue length to ask for; the loader
|
||||
// knows whether it just played out the queue's last track.
|
||||
if (active.queueMode == QueueMode.SINGLE_TRACK) return singleTrack.queueState()
|
||||
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
if (now - lastMediaInfoAtMs > MEDIA_INFO_TTL_MS) {
|
||||
@@ -834,7 +972,7 @@ class MinstrelForwardingPlayer(
|
||||
* Must run on the application looper -- reads the delegate timeline.
|
||||
*/
|
||||
private fun resolveRemoteCursorIndex(sonosTrack: Int, trackUri: String): Int? {
|
||||
val byId = trackIdFromStreamUri(trackUri)?.let { id ->
|
||||
val byId = streamUriTrackId(trackUri)?.let { id ->
|
||||
nearestIndexWithMediaId(id, preferNear = sonosTrack - 1)
|
||||
}
|
||||
return byId ?: (sonosTrack - 1).takeIf { it in 0 until delegate.mediaItemCount }
|
||||
@@ -860,20 +998,7 @@ class MinstrelForwardingPlayer(
|
||||
return best
|
||||
}
|
||||
|
||||
/** Extract `{id}` from a `.../api/tracks/{id}/stream...` stream URI. */
|
||||
private fun trackIdFromStreamUri(uri: String): String? {
|
||||
val start = uri.indexOf(TRACKS_PATH_MARKER)
|
||||
if (start < 0) return null
|
||||
val idStart = start + TRACKS_PATH_MARKER.length
|
||||
val idEnd = uri.indexOf('/', idStart)
|
||||
return if (idEnd > idStart) uri.substring(idStart, idEnd) else null
|
||||
}
|
||||
|
||||
private companion object {
|
||||
// Path segment that precedes the track-id in a stream URI
|
||||
// (…/api/tracks/{id}/stream…) — used to map the renderer's current URI
|
||||
// back to a delegate MediaItem by identity.
|
||||
const val TRACKS_PATH_MARKER = "/api/tracks/"
|
||||
const val POLL_INTERVAL_MS = 1_000L
|
||||
const val NON_PLAYING_CONFIRM = 2
|
||||
const val SEEK_ACK_WINDOW_MS = 2_000L
|
||||
|
||||
@@ -10,7 +10,6 @@ import androidx.media3.database.StandaloneDatabaseProvider
|
||||
import androidx.media3.datasource.DataSourceBitmapLoader
|
||||
import androidx.media3.datasource.cache.CacheDataSink
|
||||
import androidx.media3.datasource.cache.CacheDataSource
|
||||
import androidx.media3.datasource.cache.LeastRecentlyUsedCacheEvictor
|
||||
import androidx.media3.datasource.cache.SimpleCache
|
||||
import androidx.media3.datasource.okhttp.OkHttpDataSource
|
||||
import androidx.media3.exoplayer.DefaultRenderersFactory
|
||||
@@ -20,10 +19,11 @@ import androidx.media3.exoplayer.audio.DefaultAudioSink
|
||||
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
|
||||
import androidx.media3.session.CacheBitmapLoader
|
||||
import com.fabledsword.minstrel.auth.AuthStore
|
||||
import com.fabledsword.minstrel.cache.audiocache.CacheConfig
|
||||
import com.fabledsword.minstrel.cache.audiocache.TwoBucketCacheEvictor
|
||||
import com.fabledsword.minstrel.player.gain.GainAudioProcessor
|
||||
import com.fabledsword.minstrel.player.gain.ReplayGainStore
|
||||
import com.fabledsword.minstrel.player.output.ActiveUpnpHolder
|
||||
import com.fabledsword.minstrel.player.output.SingleTrackLoader
|
||||
import com.fabledsword.minstrel.player.output.SonosQueueLoader
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import kotlinx.coroutines.channels.BufferOverflow
|
||||
@@ -42,8 +42,8 @@ import javax.inject.Singleton
|
||||
*
|
||||
* `simpleCache` is exposed as a val for what needs the on-disk bytes:
|
||||
* the cached-track ids, the offline pools, the prefetcher and the
|
||||
* Storage card. The `LeastRecentlyUsedCacheEvictor` bounds it at the
|
||||
* rolling cap; there is no separate liked-track bucket yet.
|
||||
* Storage card. [TwoBucketCacheEvictor] bounds it by two budgets, Liked
|
||||
* songs and Recently played.
|
||||
*
|
||||
* `build()` returns a [MinstrelForwardingPlayer] wrapping the internal
|
||||
* ExoPlayer. When the UPnP route drops (the poll loop's consecutive-
|
||||
@@ -56,21 +56,22 @@ import javax.inject.Singleton
|
||||
class PlayerFactory @Inject constructor(
|
||||
@ApplicationContext private val context: Context,
|
||||
private val okHttpClient: OkHttpClient,
|
||||
private val cacheConfig: CacheConfig,
|
||||
private val cacheEvictor: TwoBucketCacheEvictor,
|
||||
private val activeUpnpHolder: ActiveUpnpHolder,
|
||||
private val remoteState: RemotePlayerState,
|
||||
private val serverHealth: com.fabledsword.minstrel.connectivity.NetworkStatusController,
|
||||
private val authStore: AuthStore,
|
||||
private val replayGains: ReplayGainStore,
|
||||
private val sonosQueue: SonosQueueLoader,
|
||||
private val singleTrack: SingleTrackLoader,
|
||||
) {
|
||||
private val cacheDir: File = File(context.cacheDir, "audio_cache").apply { mkdirs() }
|
||||
|
||||
val simpleCache: SimpleCache = SimpleCache(
|
||||
cacheDir,
|
||||
LeastRecentlyUsedCacheEvictor(cacheConfig.rollingCapBytes),
|
||||
cacheEvictor,
|
||||
StandaloneDatabaseProvider(context),
|
||||
)
|
||||
).also(cacheEvictor::attach)
|
||||
|
||||
// MutableSharedFlow with extraBufferCapacity=1 + DROP_OLDEST so a burst
|
||||
// of drop events (rapid SOAP failures during a single tear-down) surfaces
|
||||
@@ -122,6 +123,7 @@ class PlayerFactory @Inject constructor(
|
||||
remoteState = remoteState,
|
||||
castNetworkLock = CastNetworkLock(context),
|
||||
networkStatus = serverHealth,
|
||||
singleTrack = singleTrack,
|
||||
events = MinstrelForwardingPlayer.RemoteEvents(
|
||||
onDrop = { name -> emitDrop(name) },
|
||||
onStalled = { trackId -> stallEventsInternal.tryEmit(trackId) },
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
package com.fabledsword.minstrel.player
|
||||
|
||||
import com.fabledsword.minstrel.auth.AuthStore
|
||||
import com.fabledsword.minstrel.cache.audiocache.CacheConfig
|
||||
import dagger.Module
|
||||
import dagger.Provides
|
||||
import dagger.hilt.InstallIn
|
||||
import dagger.hilt.components.SingletonComponent
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Player + audio-cache wiring. PlayerFactory has @Inject so it doesn't
|
||||
* need a @Provides here; this module provides the configuration values
|
||||
* (CacheConfig) it depends on, and any player-related singletons that
|
||||
* aren't @Inject-constructible.
|
||||
*
|
||||
* MinstrelPlayerService injects PlayerFactory and calls `build()` from
|
||||
* `onCreate`.
|
||||
*/
|
||||
@Module
|
||||
@InstallIn(SingletonComponent::class)
|
||||
object PlayerModule {
|
||||
|
||||
/**
|
||||
* CacheConfig snapshot from the user's persisted CacheSettings.
|
||||
* SimpleCache is constructed once per process, so changes via the
|
||||
* Settings UI take effect on next app launch (not mid-flight).
|
||||
* AuthStore's StateFlow hydrates async from Room — when the
|
||||
* factory @Provides runs, the value is either the persisted
|
||||
* setting (if Room finished first) or CacheSettings.DEFAULT.
|
||||
* Worst case the user's tuning lands on next-next launch, which
|
||||
* is acceptable for a single-user device pref.
|
||||
*/
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideCacheConfig(authStore: AuthStore): CacheConfig {
|
||||
val s = authStore.cacheSettings.value
|
||||
return CacheConfig(
|
||||
likedCapBytes = s.likedCapBytes,
|
||||
rollingCapBytes = s.rollingCapBytes,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -13,14 +13,31 @@ import javax.inject.Singleton
|
||||
* + rendering clients. Decouples [com.fabledsword.minstrel.player.MinstrelForwardingPlayer]
|
||||
* from [OutputPickerController] -- the picker writes; the forwarding
|
||||
* player reads. Null = no UPnP active (local ExoPlayer path).
|
||||
*
|
||||
* [queueMode] says how the renderer is fed tracks, which decides what a
|
||||
* skip sends and where the poll reads the queue position from.
|
||||
*/
|
||||
data class ActiveUpnp(
|
||||
val routeId: String,
|
||||
val routeName: String,
|
||||
val avTransport: AVTransportClient,
|
||||
val rendering: RenderingControlClient?,
|
||||
val queueMode: QueueMode,
|
||||
)
|
||||
|
||||
enum class QueueMode {
|
||||
/** A Sonos holds the whole queue: [SonosQueueLoader]. */
|
||||
NATIVE_QUEUE,
|
||||
|
||||
/** Any other renderer holds one track at a time: [SingleTrackLoader]. */
|
||||
SINGLE_TRACK,
|
||||
;
|
||||
|
||||
companion object {
|
||||
fun forRoute(isSonos: Boolean): QueueMode = if (isSonos) NATIVE_QUEUE else SINGLE_TRACK
|
||||
}
|
||||
}
|
||||
|
||||
@Singleton
|
||||
class ActiveUpnpHolder @Inject constructor() {
|
||||
|
||||
|
||||
+145
-49
@@ -15,6 +15,7 @@ import com.fabledsword.minstrel.player.output.upnp.RenderingControlClient
|
||||
import com.fabledsword.minstrel.player.output.upnp.SoapClient
|
||||
import com.fabledsword.minstrel.player.output.upnp.TransportState
|
||||
import com.fabledsword.minstrel.player.output.upnp.UpnpDiscoveryController
|
||||
import com.fabledsword.minstrel.player.output.upnp.UpnpRoute
|
||||
import com.fabledsword.minstrel.player.output.upnp.bareUdn
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
@@ -28,7 +29,6 @@ import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
||||
import okhttp3.OkHttpClient
|
||||
import timber.log.Timber
|
||||
import javax.inject.Inject
|
||||
@@ -58,10 +58,11 @@ data class RouteSnapshot(
|
||||
* Selection branches on [OutputRoute.Protocol]:
|
||||
* - [OutputRoute.Protocol.SYSTEM] — MediaRouter.selectRoute (built-in,
|
||||
* wired, Bluetooth)
|
||||
* - [OutputRoute.Protocol.UPNP] — mint a signed stream token via
|
||||
* [SonosQueueLoader], drive the discovered renderer with
|
||||
* AVTransport.SetAVTransportURI + Play, pause local playback so
|
||||
* audio yields to the network speaker
|
||||
* - [OutputRoute.Protocol.UPNP] — pause local playback so audio yields
|
||||
* to the network speaker, then hand the renderer the queue: a Sonos
|
||||
* takes all of it through [SonosQueueLoader]; any other UPnP / DLNA
|
||||
* renderer takes one track at a time through [SingleTrackLoader]
|
||||
* (see [QueueMode])
|
||||
* - [OutputRoute.Protocol.CAST] / [OutputRoute.Protocol.SONOS] —
|
||||
* not implemented; selecting one does nothing.
|
||||
*/
|
||||
@@ -73,6 +74,7 @@ class OutputPickerController @Inject constructor(
|
||||
private val playerController: PlayerController,
|
||||
private val playerFactory: PlayerFactory,
|
||||
private val sonosQueue: SonosQueueLoader,
|
||||
private val singleTrack: SingleTrackLoader,
|
||||
private val activeUpnpHolder: ActiveUpnpHolder,
|
||||
private val remoteState: RemotePlayerState,
|
||||
private val okHttp: OkHttpClient,
|
||||
@@ -330,6 +332,12 @@ class OutputPickerController @Inject constructor(
|
||||
Timber.w("Sonos queue repair: route or transport gone for %s", routeId)
|
||||
return@withLock
|
||||
}
|
||||
if (!upnpRoute.isSonos) {
|
||||
// Only a native queue can be truncated; a one-track renderer
|
||||
// never asks for this.
|
||||
Timber.w("Sonos queue repair skipped: %s holds no queue", upnpRoute.name)
|
||||
return@withLock
|
||||
}
|
||||
val outputRoute = OutputRoute.fromUpnpRoute(upnpRoute)
|
||||
Timber.w(
|
||||
"Sonos queue repair: reloading %d tracks on %s (resuming at index %d)",
|
||||
@@ -371,23 +379,31 @@ class OutputPickerController @Inject constructor(
|
||||
selectedUpnpRouteIdInternal.value = null
|
||||
return@withLock
|
||||
}
|
||||
val handledIncrementally = runCatching {
|
||||
if (!upnpRoute.isSonos) {
|
||||
resyncSingleTrack(upnpRoute, transport, newQueue, newCurrentIndex)
|
||||
return@withLock
|
||||
}
|
||||
// The incremental diff is for a queue changed under a cast that kept
|
||||
// running (play next, an append, a removal): it leaves the playing
|
||||
// track alone. A queue REPLACED through setMediaItems has already
|
||||
// cleared active, and the listener asked for its start track and for
|
||||
// it to play -- both of which the diff would ignore, and with active
|
||||
// never restored the app would think it had gone back to the phone
|
||||
// while the speaker played on. That case reloads in full below.
|
||||
val stillActive = activeUpnpHolder.active.value?.routeId == routeId
|
||||
val handledIncrementally = stillActive && runCatching {
|
||||
sonosQueue.tryIncrementalResync(transport, oldIds, newQueue)
|
||||
}.getOrElse { e ->
|
||||
Timber.w(e, "Sonos incremental resync errored; falling back to full reload")
|
||||
false
|
||||
}
|
||||
if (handledIncrementally) {
|
||||
// Active was never cleared on the incremental path; clear any
|
||||
// target that markPendingResyncIfRemote set (it didn't, for
|
||||
// incremental cases that don't go through setMediaItems, but
|
||||
// belt-and-suspenders).
|
||||
activeUpnpHolder.setTarget(null)
|
||||
return@withLock
|
||||
}
|
||||
// Full rebuild: ensure active is cleared so transport calls drop
|
||||
// (markPendingResyncIfRemote may already have done this on the
|
||||
// setMediaItems path).
|
||||
// (the forwarding player has already done this on the setMediaItems
|
||||
// path).
|
||||
if (activeUpnpHolder.active.value != null) {
|
||||
activeUpnpHolder.set(null)
|
||||
activeUpnpHolder.setTarget(routeId)
|
||||
@@ -403,6 +419,7 @@ class OutputPickerController @Inject constructor(
|
||||
routeName = outputRoute.name,
|
||||
avTransport = transport,
|
||||
rendering = rendering,
|
||||
queueMode = QueueMode.NATIVE_QUEUE,
|
||||
),
|
||||
)
|
||||
activeUpnpHolder.setTarget(null)
|
||||
@@ -413,6 +430,57 @@ class OutputPickerController @Inject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The one-track counterpart of the Sonos resync. A mutation that left the
|
||||
* cast running (play next, radio append, a removal) keeps the current
|
||||
* track playing and only re-arms what follows it. A queue replaced
|
||||
* through setMediaItems -- the forwarding player has already cleared
|
||||
* active, and dropped the play() that came with it -- starts the new
|
||||
* queue at its current index, as the listener asked. So does a mutation
|
||||
* that removed the playing track.
|
||||
*/
|
||||
private suspend fun resyncSingleTrack(
|
||||
upnpRoute: UpnpRoute,
|
||||
transport: AVTransportClient,
|
||||
newQueue: List<TrackRef>,
|
||||
newCurrentIndex: Int,
|
||||
) {
|
||||
val stillActive = activeUpnpHolder.active.value?.routeId == upnpRoute.id
|
||||
if (stillActive && requeueKeepsTrack(transport, newQueue)) {
|
||||
activeUpnpHolder.setTarget(null)
|
||||
return
|
||||
}
|
||||
if (activeUpnpHolder.active.value != null) {
|
||||
activeUpnpHolder.set(null)
|
||||
activeUpnpHolder.setTarget(upnpRoute.id)
|
||||
}
|
||||
Timber.w("UPnP single-track resync: starting track %d on %s", newCurrentIndex + 1, upnpRoute.name)
|
||||
runCatching {
|
||||
singleTrack.load(transport, newQueue, newCurrentIndex)
|
||||
activeUpnpHolder.set(
|
||||
ActiveUpnp(
|
||||
routeId = upnpRoute.id,
|
||||
routeName = upnpRoute.name,
|
||||
avTransport = transport,
|
||||
rendering = renderingClientFor(upnpRoute.id),
|
||||
queueMode = QueueMode.SINGLE_TRACK,
|
||||
),
|
||||
)
|
||||
activeUpnpHolder.setTarget(null)
|
||||
remoteState.setPlayIntent(true)
|
||||
}.onFailure { e ->
|
||||
Timber.w(e, "UPnP single-track resync failed -- dropping to local")
|
||||
activeUpnpHolder.setTarget(null)
|
||||
selectedUpnpRouteIdInternal.value = null
|
||||
}
|
||||
}
|
||||
|
||||
/** True when the playing track survived the change and was kept playing. */
|
||||
private suspend fun requeueKeepsTrack(transport: AVTransportClient, newQueue: List<TrackRef>): Boolean =
|
||||
runCatching { singleTrack.requeue(transport, newQueue) }
|
||||
.onFailure { Timber.w(it, "UPnP single-track requeue failed; restarting the queue") }
|
||||
.getOrDefault(false)
|
||||
|
||||
|
||||
/**
|
||||
* Called when the active UPnP route drops unexpectedly (the poll loop's
|
||||
@@ -496,11 +564,10 @@ class OutputPickerController @Inject constructor(
|
||||
}
|
||||
|
||||
/**
|
||||
* Drive the UPnP renderer using Sonos native queue mode:
|
||||
* clear the device's queue, load every track from our local queue
|
||||
* via AddURIToQueue, point the transport at the queue URI, seek to
|
||||
* the current index, and play. Wrapped in `runCatching` — SOAP
|
||||
* failure abandons the selection cleanly.
|
||||
* Hand the renderer the local queue and play it. A Sonos gets its native
|
||||
* queue loaded ([SonosQueueLoader]); any other renderer is started on the
|
||||
* current track with the next one armed ([SingleTrackLoader]). Wrapped in
|
||||
* `runCatching` — SOAP failure abandons the selection cleanly.
|
||||
*
|
||||
* Order of operations is deliberate:
|
||||
* 1. Pause local so the user doesn't keep hearing local audio.
|
||||
@@ -531,6 +598,7 @@ class OutputPickerController @Inject constructor(
|
||||
return@withLock
|
||||
}
|
||||
val rendering = renderingClientFor(effectiveRoute.id)
|
||||
val queueMode = queueModeFor(effectiveRoute.id)
|
||||
// Pause local before flipping UI state -- user shouldn't keep hearing
|
||||
// local audio while we queue up Sonos.
|
||||
playerController.pause()
|
||||
@@ -539,7 +607,12 @@ class OutputPickerController @Inject constructor(
|
||||
// session we got disconnected from), attach to it in place instead of
|
||||
// wiping + reloading -- no jarring restart, and skip/seek land on its
|
||||
// live queue. Falls through to the clear+reload path when it isn't ours.
|
||||
if (tryAdoptRunningSession(transport, rendering, effectiveRoute, uiState.queue)) {
|
||||
val adopted = tryAdoptRunningSession(
|
||||
AdoptTarget(transport, rendering, effectiveRoute, queueMode),
|
||||
uiState.queue,
|
||||
uiState.queueIndex,
|
||||
)
|
||||
if (adopted) {
|
||||
return@withLock
|
||||
}
|
||||
// Mark UPnP loading. ForwardingPlayer overrides drop transport commands
|
||||
@@ -547,7 +620,12 @@ class OutputPickerController @Inject constructor(
|
||||
// taps don't hit Sonos's stale state from a prior session.
|
||||
activeUpnpHolder.setTarget(effectiveRoute.id)
|
||||
runCatching {
|
||||
when (queueMode) {
|
||||
QueueMode.NATIVE_QUEUE ->
|
||||
sonosQueue.load(transport, effectiveRoute, uiState.queue, uiState.queueIndex)
|
||||
QueueMode.SINGLE_TRACK ->
|
||||
singleTrack.load(transport, uiState.queue, uiState.queueIndex)
|
||||
}
|
||||
// Wire active LAST -- SOAP path is now safe to use.
|
||||
activeUpnpHolder.set(
|
||||
ActiveUpnp(
|
||||
@@ -555,6 +633,7 @@ class OutputPickerController @Inject constructor(
|
||||
routeName = effectiveRoute.name,
|
||||
avTransport = transport,
|
||||
rendering = rendering,
|
||||
queueMode = queueMode,
|
||||
),
|
||||
)
|
||||
// Selecting a route loads the queue and Plays on the renderer, so
|
||||
@@ -570,38 +649,49 @@ class OutputPickerController @Inject constructor(
|
||||
|
||||
/**
|
||||
* The renderer's current position + transport state, validated as an
|
||||
* adoptable continuation of our local queue: same track id at the same
|
||||
* 1-based index. Null means "not ours / not playing" -> caller reloads.
|
||||
* adoptable continuation of our local queue. Null means "not ours / not
|
||||
* playing" -> caller reloads.
|
||||
*/
|
||||
private data class AdoptPlan(
|
||||
val localIndex: Int,
|
||||
val positionMs: Long,
|
||||
val durationMs: Long,
|
||||
val trackUri: String,
|
||||
val trackNumber: Int,
|
||||
val playing: Boolean,
|
||||
)
|
||||
|
||||
/** The renderer a select is about to drive, and how. */
|
||||
private data class AdoptTarget(
|
||||
val transport: AVTransportClient,
|
||||
val rendering: RenderingControlClient?,
|
||||
val route: OutputRoute,
|
||||
val queueMode: QueueMode,
|
||||
)
|
||||
|
||||
/**
|
||||
* Attach to a renderer that is *already* playing our queue (a session the
|
||||
* phone got disconnected from but the speaker kept streaming) instead of
|
||||
* clearing + reloading it. Probes the renderer's live state, and if it's
|
||||
* mid-playback on the same track id at the same queue index, syncs the
|
||||
* mid-playback on one of our tracks where our queue has it, syncs the
|
||||
* local cursor to match and wires [ActiveUpnpHolder] -- the speaker never
|
||||
* skips a beat, and skip/seek now drive its live queue. Returns false (and
|
||||
* the caller does the full clear+reload) when the renderer isn't playing
|
||||
* our queue. The local player is already paused by the caller.
|
||||
* skips a beat, and skip/seek now drive it. Returns false (and the caller
|
||||
* does the full load) when the renderer isn't playing our queue. The
|
||||
* local player is already paused by the caller.
|
||||
*/
|
||||
private suspend fun tryAdoptRunningSession(
|
||||
transport: AVTransportClient,
|
||||
rendering: RenderingControlClient?,
|
||||
route: OutputRoute,
|
||||
target: AdoptTarget,
|
||||
localQueue: List<TrackRef>,
|
||||
localIndex: Int,
|
||||
): Boolean {
|
||||
val plan = probeAdoptable(transport, route, localQueue) ?: return false
|
||||
val route = target.route
|
||||
val plan = probeAdoptable(target, localQueue, localIndex) ?: return false
|
||||
if (target.queueMode == QueueMode.SINGLE_TRACK) {
|
||||
// The renderer holds only this track; arm the one after it.
|
||||
singleTrack.adopt(target.transport, localQueue, plan.localIndex, plan.trackUri)
|
||||
}
|
||||
Timber.w(
|
||||
"UPnP adopt: attaching to live session on %s at track %d (%dms)",
|
||||
route.name, plan.trackNumber, plan.positionMs,
|
||||
route.name, plan.localIndex + 1, plan.positionMs,
|
||||
)
|
||||
// active is still null here, so this aligns the *local* cursor without
|
||||
// emitting SOAP; the holder.set below then starts the poll loop, which
|
||||
@@ -611,45 +701,54 @@ class OutputPickerController @Inject constructor(
|
||||
positionMs = plan.positionMs,
|
||||
durationMs = plan.durationMs,
|
||||
trackUri = plan.trackUri,
|
||||
trackNumber = plan.trackNumber,
|
||||
trackNumber = plan.localIndex + 1,
|
||||
)
|
||||
remoteState.setPlayIntent(plan.playing)
|
||||
activeUpnpHolder.set(
|
||||
ActiveUpnp(
|
||||
routeId = route.id,
|
||||
routeName = route.name,
|
||||
avTransport = transport,
|
||||
rendering = rendering,
|
||||
avTransport = target.transport,
|
||||
rendering = target.rendering,
|
||||
queueMode = target.queueMode,
|
||||
),
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* A Sonos must be on our track at the same 1-based index of its native
|
||||
* queue, since skips drive that queue. A one-track renderer has no index
|
||||
* to agree on: it is ours if it is playing one of our tracks, taken
|
||||
* nearest the local cursor.
|
||||
*/
|
||||
private suspend fun probeAdoptable(
|
||||
transport: AVTransportClient,
|
||||
route: OutputRoute,
|
||||
target: AdoptTarget,
|
||||
localQueue: List<TrackRef>,
|
||||
localIndex: Int,
|
||||
): AdoptPlan? {
|
||||
val probe = runCatching {
|
||||
transport.getTransportInfo() to transport.getPositionInfo()
|
||||
target.transport.getTransportInfo() to target.transport.getPositionInfo()
|
||||
}.getOrElse {
|
||||
Timber.w(it, "UPnP adopt: probe failed for %s; will reload", route.name)
|
||||
Timber.w(it, "UPnP adopt: probe failed for %s; will reload", target.route.name)
|
||||
return null
|
||||
}
|
||||
val (info, pos) = probe
|
||||
val idx0 = pos.track - 1
|
||||
val playingId = trackIdFromStreamUrl(pos.trackUri)
|
||||
val playingId = streamUriTrackId(pos.trackUri)
|
||||
val midPlayback =
|
||||
info.state == TransportState.PLAYING || info.state == TransportState.PAUSED
|
||||
val aligned = midPlayback && playingId != null &&
|
||||
idx0 in localQueue.indices && localQueue[idx0].id == playingId
|
||||
return if (aligned) {
|
||||
val idx0 = when {
|
||||
playingId == null -> null
|
||||
target.queueMode == QueueMode.SINGLE_TRACK ->
|
||||
nearestIndexOf(localQueue, playingId, localIndex)
|
||||
else -> (pos.track - 1).takeIf { it in localQueue.indices && localQueue[it].id == playingId }
|
||||
}
|
||||
return if (midPlayback && idx0 != null) {
|
||||
AdoptPlan(
|
||||
localIndex = idx0,
|
||||
positionMs = pos.relTimeMs,
|
||||
durationMs = pos.trackDurationMs,
|
||||
trackUri = pos.trackUri,
|
||||
trackNumber = pos.track,
|
||||
playing = info.state == TransportState.PLAYING,
|
||||
)
|
||||
} else {
|
||||
@@ -657,12 +756,9 @@ class OutputPickerController @Inject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
/** Extract our track id from a stream URL `.../api/tracks/<id>/stream...`. */
|
||||
private fun trackIdFromStreamUrl(url: String): String? {
|
||||
val segments = url.toHttpUrlOrNull()?.pathSegments ?: return null
|
||||
val i = segments.indexOf("tracks")
|
||||
return if (i >= 0) segments.getOrNull(i + 1) else null
|
||||
}
|
||||
/** How the route is fed tracks; a route gone from discovery reads as not-Sonos. */
|
||||
private fun queueModeFor(routeId: String): QueueMode =
|
||||
QueueMode.forRoute(upnpDiscovery.routes.value.firstOrNull { it.id == routeId }?.isSonos == true)
|
||||
|
||||
|
||||
private fun renderingClientFor(routeId: String): RenderingControlClient? {
|
||||
|
||||
+266
@@ -0,0 +1,266 @@
|
||||
package com.fabledsword.minstrel.player.output
|
||||
|
||||
import com.fabledsword.minstrel.models.TrackRef
|
||||
import com.fabledsword.minstrel.player.RemoteStallWatchdog
|
||||
import com.fabledsword.minstrel.player.StreamTokenProvider
|
||||
import com.fabledsword.minstrel.player.output.upnp.AVTransportClient
|
||||
import com.fabledsword.minstrel.player.output.upnp.SoapFaultException
|
||||
import com.fabledsword.minstrel.player.output.upnp.TransportState
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import timber.log.Timber
|
||||
import javax.inject.Inject
|
||||
import kotlin.math.abs
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Drives a UPnP / DLNA renderer that has no queue of its own — anything that
|
||||
* isn't a Sonos. [SonosQueueLoader] hands a Sonos the whole queue; the queue
|
||||
* verbs it uses are Sonos extensions a generic renderer faults on. Here the
|
||||
* app holds the queue and the renderer holds one track at a time:
|
||||
*
|
||||
* - SetAVTransportURI + Play starts a track.
|
||||
* - SetNextAVTransportURI hands over the one after it, so a renderer that
|
||||
* supports it moves on by itself, without a gap. The poll sees the
|
||||
* renderer's URI change to that one and arms the next.
|
||||
* - A renderer without SetNext (it faults) or one that accepts it and
|
||||
* ignores it stops at the end of the track; [TrackEndDetector] tells that
|
||||
* from a stop partway, and the app starts the next track itself.
|
||||
*
|
||||
* The renderer reports Track=1 for whatever it is playing, so the 1-based
|
||||
* queue position everything else keys on comes from here ([PollOutcome]).
|
||||
*
|
||||
* One mutex covers every write, because the poll's auto-advance and the
|
||||
* listener's skip both point the renderer somewhere and must not interleave.
|
||||
*/
|
||||
@Singleton
|
||||
class SingleTrackLoader @Inject constructor(
|
||||
private val streamTokens: StreamTokenProvider,
|
||||
) {
|
||||
private val mutex = Mutex()
|
||||
|
||||
@Volatile private var queue: List<TrackRef> = emptyList()
|
||||
|
||||
/** 0-based index of the track the renderer was last pointed at; -1 when none. */
|
||||
@Volatile var currentIndex: Int = -1
|
||||
private set
|
||||
|
||||
private var currentUri: String = ""
|
||||
private var armedNextIndex: Int = -1
|
||||
private var armedNextUri: String = ""
|
||||
|
||||
// Set when the renderer faults SetNextAVTransportURI: it does not have the
|
||||
// action, and asking again per track would only collect the same fault.
|
||||
// Cleared on every load, since a load may be a different renderer.
|
||||
private var nextUnsupported = false
|
||||
|
||||
// Polls to wait before re-trying a SetNext that failed in transit. Each
|
||||
// try mints a URL from the server, so a failure is not retried every
|
||||
// second.
|
||||
private var armRetryPolls = 0
|
||||
|
||||
// Whether the last poll found the current track played to its end. Read
|
||||
// by [queueState] for the stall watchdog.
|
||||
private var endedOnLastPoll = false
|
||||
|
||||
private val endDetector = TrackEndDetector()
|
||||
|
||||
/**
|
||||
* What a poll learned. [trackNumber] is the 1-based queue position the
|
||||
* renderer is playing (0 when nothing is loaded). [advanced] is true when
|
||||
* this poll started the next track itself, so the reading it was given is
|
||||
* already stale and the caller should not judge a stall from it.
|
||||
* [knownDurationMs] is the library's duration for that track, for a
|
||||
* renderer that reports none.
|
||||
*/
|
||||
data class PollOutcome(val trackNumber: Int, val advanced: Boolean, val knownDurationMs: Long = 0L)
|
||||
|
||||
/** Take [queue] as the one to play, and start [index] on the renderer. */
|
||||
suspend fun load(transport: AVTransportClient, queue: List<TrackRef>, index: Int) =
|
||||
mutex.withLock {
|
||||
this.queue = queue
|
||||
nextUnsupported = false
|
||||
start(transport, index)
|
||||
}
|
||||
|
||||
/**
|
||||
* Start [index] of the queue already held — a skip, a previous, or a tap
|
||||
* on a queue row. Returns false when [index] is outside the queue.
|
||||
*/
|
||||
suspend fun playIndex(transport: AVTransportClient, index: Int): Boolean =
|
||||
mutex.withLock { start(transport, index) }
|
||||
|
||||
/**
|
||||
* Attach to a renderer already playing [index] of [queue] at [uri] — a
|
||||
* session the phone lost touch with and the renderer carried on with —
|
||||
* without restarting it. Only arms the next track.
|
||||
*/
|
||||
suspend fun adopt(transport: AVTransportClient, queue: List<TrackRef>, index: Int, uri: String) =
|
||||
mutex.withLock {
|
||||
this.queue = queue
|
||||
nextUnsupported = false
|
||||
pointedAt(index, uri)
|
||||
armNext(transport)
|
||||
}
|
||||
|
||||
/**
|
||||
* The local queue changed under a playing track (play next, radio
|
||||
* append, a removal). Keep playing the current track and re-arm what
|
||||
* follows it. Returns false when the current track is gone from
|
||||
* [newQueue]; the caller then starts the new queue with [load].
|
||||
*/
|
||||
suspend fun requeue(transport: AVTransportClient, newQueue: List<TrackRef>): Boolean =
|
||||
mutex.withLock {
|
||||
val playingId = queue.getOrNull(currentIndex)?.id
|
||||
val idx = playingId?.let { nearestIndexOf(newQueue, it, currentIndex) }
|
||||
queue = newQueue
|
||||
if (idx == null) return@withLock false
|
||||
currentIndex = idx
|
||||
// What was armed was chosen from the old queue; SetNext replaces it.
|
||||
armedNextIndex = -1
|
||||
armedNextUri = ""
|
||||
armNext(transport)
|
||||
true
|
||||
}
|
||||
|
||||
/**
|
||||
* One poll's reading of the renderer. Follows a renderer that moved on by
|
||||
* itself, re-tries arming the next track, and starts the next track when
|
||||
* the current one has played to its end.
|
||||
*/
|
||||
suspend fun onPoll(
|
||||
transport: AVTransportClient,
|
||||
trackUri: String,
|
||||
state: TransportState,
|
||||
positionMs: Long,
|
||||
durationMs: Long,
|
||||
playIntent: Boolean,
|
||||
): PollOutcome = mutex.withLock {
|
||||
if (currentIndex !in queue.indices) return@withLock PollOutcome(0, advanced = false)
|
||||
val moved = followRenderer(trackUri)
|
||||
armNext(transport)
|
||||
if (moved) return@withLock PollOutcome(currentIndex + 1, advanced = false, knownDurationMs(queue, currentIndex))
|
||||
endedOnLastPoll = endDetector.onPoll(state, positionMs, durationMs, knownDurationMs(queue, currentIndex))
|
||||
val next = currentIndex + 1
|
||||
val advance = endedOnLastPoll && playIntent && next in queue.indices
|
||||
if (advance) {
|
||||
Timber.w("UPnP single-track: track %d ended; starting %d", currentIndex + 1, next + 1)
|
||||
runCatching { start(transport, next) }
|
||||
.onFailure { Timber.w(it, "UPnP single-track: could not start track %d", next + 1) }
|
||||
}
|
||||
PollOutcome(currentIndex + 1, advanced = advance, knownDurationMs(queue, currentIndex))
|
||||
}
|
||||
|
||||
/**
|
||||
* For the stall watchdog: a renderer stopped at the end of the queue's
|
||||
* last track has simply finished. Anything else is left for the watchdog
|
||||
* to judge, as it would for a renderer that says nothing.
|
||||
*/
|
||||
fun queueState(): RemoteStallWatchdog.QueueState =
|
||||
if (endedOnLastPoll && currentIndex == queue.lastIndex) {
|
||||
RemoteStallWatchdog.QueueState.COMPLETE
|
||||
} else {
|
||||
RemoteStallWatchdog.QueueState.UNKNOWN
|
||||
}
|
||||
|
||||
private suspend fun start(transport: AVTransportClient, index: Int): Boolean {
|
||||
if (index !in queue.indices) return false
|
||||
val token = mint(index)
|
||||
transport.setAVTransportURIWithMetadata(token.url, token.mime, token.title)
|
||||
transport.play()
|
||||
pointedAt(index, token.url)
|
||||
armNext(transport)
|
||||
return true
|
||||
}
|
||||
|
||||
private fun pointedAt(index: Int, uri: String) {
|
||||
currentIndex = index
|
||||
currentUri = uri
|
||||
armedNextIndex = -1
|
||||
armedNextUri = ""
|
||||
armRetryPolls = 0
|
||||
endedOnLastPoll = false
|
||||
endDetector.reset()
|
||||
}
|
||||
|
||||
/**
|
||||
* Update [currentIndex] when the renderer's URI says it is playing
|
||||
* something other than the track we started. The armed next URI is the
|
||||
* common case (it advanced by itself); otherwise the track id in the URI
|
||||
* is looked up, for a renderer that was re-pointed some other way.
|
||||
* Returns true when the index moved.
|
||||
*/
|
||||
private fun followRenderer(trackUri: String): Boolean {
|
||||
val idx = when {
|
||||
trackUri.isEmpty() || trackUri == currentUri -> null
|
||||
trackUri == armedNextUri -> armedNextIndex
|
||||
else -> streamUriTrackId(trackUri)?.let { nearestIndexOf(queue, it, currentIndex + 1) }
|
||||
}
|
||||
if (idx == null || idx == currentIndex) return false
|
||||
Timber.w("UPnP single-track: renderer moved on to track %d", idx + 1)
|
||||
pointedAt(idx, trackUri)
|
||||
return true
|
||||
}
|
||||
|
||||
private suspend fun armNext(transport: AVTransportClient) {
|
||||
val next = currentIndex + 1
|
||||
if (nextUnsupported || next !in queue.indices || next == armedNextIndex) return
|
||||
if (armRetryPolls > 0) {
|
||||
armRetryPolls -= 1
|
||||
return
|
||||
}
|
||||
runCatching {
|
||||
val token = mint(next)
|
||||
transport.setNextAVTransportURI(token.url, token.mime, token.title)
|
||||
token.url
|
||||
}.onSuccess { url ->
|
||||
armedNextIndex = next
|
||||
armedNextUri = url
|
||||
}.onFailure { e ->
|
||||
if (e is SoapFaultException) {
|
||||
// The renderer answered: it has no SetNext. The app advances it.
|
||||
Timber.w("UPnP single-track: SetNext refused (%s); advancing from the app", e.code)
|
||||
nextUnsupported = true
|
||||
} else {
|
||||
Timber.w(e, "UPnP single-track: SetNext failed; retrying later")
|
||||
armRetryPolls = ARM_RETRY_POLLS
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Prerender both: the current track is about to be fetched, and the next
|
||||
// one is fetched the moment the renderer moves on.
|
||||
private suspend fun mint(index: Int) = streamTokens.mint(
|
||||
queue[index].id,
|
||||
asAlbum = SonosQueueLoader.playingAsAlbum(queue, index),
|
||||
prerender = true,
|
||||
)
|
||||
|
||||
private companion object {
|
||||
const val ARM_RETRY_POLLS = 10
|
||||
}
|
||||
}
|
||||
|
||||
/** The library's duration of [queue]'s track at [index], or 0 when there is none. */
|
||||
private fun knownDurationMs(queue: List<TrackRef>, index: Int): Long =
|
||||
queue.getOrNull(index)?.durationSec?.times(MILLIS_PER_SECOND) ?: 0L
|
||||
|
||||
/**
|
||||
* Index in [queue] of the track with [id], taking the occurrence nearest
|
||||
* [preferNear] so a track queued twice does not send the cursor across the
|
||||
* queue. Null when [id] is not queued.
|
||||
*/
|
||||
internal fun nearestIndexOf(queue: List<TrackRef>, id: String, preferNear: Int): Int? =
|
||||
queue.indices.filter { queue[it].id == id }.minByOrNull { abs(it - preferNear) }
|
||||
|
||||
/** The track id in a `.../api/tracks/{id}/stream...` URL, or null for any other URL. */
|
||||
internal fun streamUriTrackId(uri: String): String? {
|
||||
val start = uri.indexOf(TRACKS_PATH_MARKER)
|
||||
if (start < 0) return null
|
||||
val idStart = start + TRACKS_PATH_MARKER.length
|
||||
val idEnd = uri.indexOf('/', idStart)
|
||||
return if (idEnd > idStart) uri.substring(idStart, idEnd) else null
|
||||
}
|
||||
|
||||
private const val TRACKS_PATH_MARKER = "/api/tracks/"
|
||||
private const val MILLIS_PER_SECOND = 1_000L
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.fabledsword.minstrel.player.output
|
||||
|
||||
import com.fabledsword.minstrel.player.output.upnp.TransportState
|
||||
|
||||
/**
|
||||
* Tells a renderer that finished its track from one that stopped partway.
|
||||
*
|
||||
* A renderer with no queue of its own reports the same STOPPED either way.
|
||||
* Finishing means the app should start the next track; stopping partway is
|
||||
* the stall watchdog's business (the stream died, or someone pressed stop on
|
||||
* the device), and starting the next track then would skip music.
|
||||
*
|
||||
* The test is where the renderer was last seen playing: within [END_SLACK_MS]
|
||||
* of the end counts as finished. The slack covers the 1 s poll cadence plus a
|
||||
* renderer that stops a little short of the duration it reported. A track is
|
||||
* only judged once it has been seen playing, so the brief STOPPED a renderer
|
||||
* passes through while it loads a new URI never reads as an ending.
|
||||
*
|
||||
* Pure state, no SOAP: [SingleTrackLoader] feeds it each poll.
|
||||
*/
|
||||
internal class TrackEndDetector {
|
||||
|
||||
private var sawPlaying = false
|
||||
private var lastPlayingPositionMs = 0L
|
||||
private var durationMs = 0L
|
||||
|
||||
/**
|
||||
* Feed one poll, learn whether the current track has ended.
|
||||
* [reportedDurationMs] is the renderer's TrackDuration, which some
|
||||
* renderers leave at zero; [knownDurationMs] is the library's duration
|
||||
* for the same track, used when the renderer says nothing.
|
||||
*/
|
||||
fun onPoll(
|
||||
state: TransportState,
|
||||
positionMs: Long,
|
||||
reportedDurationMs: Long,
|
||||
knownDurationMs: Long,
|
||||
): Boolean {
|
||||
val duration = reportedDurationMs.takeIf { it > 0L } ?: knownDurationMs
|
||||
if (duration > 0L) durationMs = duration
|
||||
if (state == TransportState.PLAYING) {
|
||||
sawPlaying = true
|
||||
lastPlayingPositionMs = positionMs
|
||||
return false
|
||||
}
|
||||
val stopped = state == TransportState.STOPPED || state == TransportState.NO_MEDIA
|
||||
return stopped &&
|
||||
sawPlaying &&
|
||||
durationMs > 0L &&
|
||||
lastPlayingPositionMs >= durationMs - END_SLACK_MS
|
||||
}
|
||||
|
||||
/** A new track was handed to the renderer: judge it from scratch. */
|
||||
fun reset() {
|
||||
sawPlaying = false
|
||||
lastPlayingPositionMs = 0L
|
||||
durationMs = 0L
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val END_SLACK_MS = 5_000L
|
||||
}
|
||||
}
|
||||
+50
-9
@@ -4,15 +4,21 @@ import okhttp3.HttpUrl
|
||||
|
||||
/**
|
||||
* High-level wrapper for the UPnP AVTransport service.
|
||||
* Covers SetAVTransportURI / Play / Pause / Stop / Seek /
|
||||
* GetPositionInfo / GetTransportInfo / queue management
|
||||
* (RemoveAllTracksFromQueue, AddURIToQueue, Next, Previous, SeekToTrack).
|
||||
* Covers SetAVTransportURI / SetNextAVTransportURI / Play / Pause / Stop /
|
||||
* Seek / GetPositionInfo / GetTransportInfo, plus the Sonos queue
|
||||
* extensions (RemoveAllTracksFromQueue, AddURIToQueue, Next, Previous,
|
||||
* SeekToTrack).
|
||||
*
|
||||
* [sonos] says which kind of renderer is on the other end. It shapes the
|
||||
* DIDL-Lite every track is described with, so it is fixed at construction
|
||||
* rather than chosen per call.
|
||||
*/
|
||||
// One method per AVTransport SOAP verb; splitting would obscure the 1:1 protocol mapping.
|
||||
@Suppress("TooManyFunctions")
|
||||
class AVTransportClient(
|
||||
private val soap: SoapClient,
|
||||
private val controlUrl: HttpUrl,
|
||||
private val sonos: Boolean,
|
||||
) {
|
||||
suspend fun setAVTransportURI(uri: String, metadata: String = "") {
|
||||
soap.call(
|
||||
@@ -39,15 +45,34 @@ class AVTransportClient(
|
||||
* <res protocolInfo="http-get:*:<mime>:*">...</res>
|
||||
* </item>
|
||||
* </DIDL-Lite>
|
||||
* Generic UPnP renderers tolerate this shape too — there's no
|
||||
* downside to always sending it. Title falls back to "Minstrel"
|
||||
* when the caller doesn't supply one.
|
||||
* The Sonos-only parts are left out for other renderers; see
|
||||
* [buildDidlLite]. Title falls back to "Minstrel" when the caller
|
||||
* doesn't supply one.
|
||||
*/
|
||||
suspend fun setAVTransportURIWithMetadata(uri: String, mime: String, title: String) {
|
||||
val safeTitle = title.ifBlank { "Minstrel" }
|
||||
setAVTransportURI(uri, buildDidlLite(uri, mime, safeTitle))
|
||||
}
|
||||
|
||||
/**
|
||||
* Hand the renderer the track to play once the current one ends, so it
|
||||
* can move on without a gap and without waiting for us. Optional in the
|
||||
* UPnP spec: a renderer without it faults (401 Invalid Action, or 602
|
||||
* Not Implemented), and the caller then advances the renderer itself.
|
||||
*/
|
||||
suspend fun setNextAVTransportURI(uri: String, mime: String, title: String) {
|
||||
soap.call(
|
||||
controlUrl = controlUrl,
|
||||
serviceType = SERVICE_TYPE,
|
||||
action = "SetNextAVTransportURI",
|
||||
args = mapOf(
|
||||
"InstanceID" to "0",
|
||||
"NextURI" to uri,
|
||||
"NextURIMetaData" to buildDidlLite(uri, mime, title),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove all tracks from the renderer's queue. UPnP action name is
|
||||
* `RemoveAllTracksFromQueue`. Used at activation time to clear out any
|
||||
@@ -247,6 +272,7 @@ class AVTransportClient(
|
||||
"PAUSED_PLAYBACK" -> TransportState.PAUSED
|
||||
"STOPPED" -> TransportState.STOPPED
|
||||
"TRANSITIONING" -> TransportState.TRANSITIONING
|
||||
"NO_MEDIA_PRESENT" -> TransportState.NO_MEDIA
|
||||
else -> TransportState.UNKNOWN
|
||||
}
|
||||
// CurrentTransportStatus is the renderer's own verdict on whether it is
|
||||
@@ -267,22 +293,31 @@ class AVTransportClient(
|
||||
// discards our metadata content and regenerates its own with
|
||||
// class=object.item and the URL query string as the title
|
||||
// instead. Match SoCo's pattern.
|
||||
//
|
||||
// Other renderers get plain DIDL with DLNA.ORG_OP=01 in the
|
||||
// protocolInfo, which declares that the stream takes byte-range
|
||||
// requests. Several DLNA renderers (TVs, AV receivers) refuse to
|
||||
// seek without it; the server's streams all serve Range.
|
||||
val safeTitle = title.ifBlank { "Minstrel" }
|
||||
val fourthField = if (sonos) "*" else DLNA_SEEKABLE
|
||||
return buildString {
|
||||
append("<DIDL-Lite ")
|
||||
append("xmlns=\"urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/\" ")
|
||||
append("xmlns:dc=\"http://purl.org/dc/elements/1.1/\" ")
|
||||
append("xmlns:upnp=\"urn:schemas-upnp-org:metadata-1-0/upnp/\"")
|
||||
append("xmlns:r=\"urn:schemas-rinconnetworks-com:metadata-1-0/\">")
|
||||
if (sonos) append(" xmlns:r=\"urn:schemas-rinconnetworks-com:metadata-1-0/\"")
|
||||
append(">")
|
||||
append("<item id=\"-1\" parentID=\"-1\" restricted=\"true\">")
|
||||
append("<dc:title>").append(xmlEscape(safeTitle)).append("</dc:title>")
|
||||
append("<upnp:class>object.item.audioItem.musicTrack</upnp:class>")
|
||||
append("<res protocolInfo=\"http-get:*:").append(xmlEscape(mime))
|
||||
append(":*\">").append(xmlEscape(uri)).append("</res>")
|
||||
append(":").append(fourthField).append("\">").append(xmlEscape(uri)).append("</res>")
|
||||
if (sonos) {
|
||||
append("<desc id=\"cdudn\" ")
|
||||
append("nameSpace=\"urn:schemas-rinconnetworks-com:metadata-1-0/\">")
|
||||
append("RINCON_AssociatedZPUDN")
|
||||
append("</desc>")
|
||||
}
|
||||
append("</item>")
|
||||
append("</DIDL-Lite>")
|
||||
}
|
||||
@@ -308,6 +343,7 @@ class AVTransportClient(
|
||||
|
||||
private companion object {
|
||||
const val SERVICE_TYPE = "urn:schemas-upnp-org:service:AVTransport:1"
|
||||
const val DLNA_SEEKABLE = "DLNA.ORG_OP=01"
|
||||
const val MILLIS_PER_SECOND = 1000L
|
||||
const val SECONDS_PER_MINUTE = 60L
|
||||
const val SECONDS_PER_HOUR = 3600L
|
||||
@@ -330,7 +366,12 @@ data class PositionInfo(
|
||||
*/
|
||||
data class MediaInfo(val nrTracks: Int, val currentUri: String)
|
||||
|
||||
enum class TransportState { PLAYING, PAUSED, STOPPED, TRANSITIONING, UNKNOWN }
|
||||
/**
|
||||
* [NO_MEDIA] is NO_MEDIA_PRESENT: nothing loaded. Several DLNA renderers land
|
||||
* there instead of STOPPED when a track plays out, so a one-track renderer's
|
||||
* ending reads it as a stop; it is not treated as a stall.
|
||||
*/
|
||||
enum class TransportState { PLAYING, PAUSED, STOPPED, TRANSITIONING, NO_MEDIA, UNKNOWN }
|
||||
|
||||
/**
|
||||
* [statusOk] is CurrentTransportStatus, defaulted true so the many call sites
|
||||
|
||||
+2
-1
@@ -135,13 +135,14 @@ class UpnpDiscoveryController @Inject constructor(
|
||||
return AVTransportClient(
|
||||
loggingSoapClient(controlHttp, route.name),
|
||||
route.avTransportControlUrl,
|
||||
sonos = route.isSonos,
|
||||
)
|
||||
}
|
||||
|
||||
private suspend fun handleDiscovery(locationUrl: String) {
|
||||
val route = fetchRoute(locationUrl) ?: return
|
||||
upsertRoute(route)
|
||||
if (route.manufacturer.contains("Sonos", ignoreCase = true)) {
|
||||
if (route.isSonos) {
|
||||
refreshSonosTopology(route)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,4 +25,13 @@ data class UpnpRoute(
|
||||
val avTransportControlUrl: HttpUrl,
|
||||
val renderingControlUrl: HttpUrl?,
|
||||
val zoneGroupTopologyControlUrl: HttpUrl? = null,
|
||||
)
|
||||
) {
|
||||
/**
|
||||
* Whether this renderer is a Sonos, which is driven through its native
|
||||
* queue. Anything else gets one track at a time — the Sonos queue verbs
|
||||
* are vendor extensions a generic renderer faults on.
|
||||
*/
|
||||
val isSonos: Boolean
|
||||
get() = zoneGroupTopologyControlUrl != null ||
|
||||
manufacturer.contains("Sonos", ignoreCase = true)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
package com.fabledsword.minstrel.playlists
|
||||
|
||||
import com.fabledsword.minstrel.models.PlaylistRef
|
||||
import java.time.Instant
|
||||
import java.time.ZoneId
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.time.temporal.ChronoUnit
|
||||
import java.util.Locale
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
// What a Home shelf of playlist tiles shows: which album covers each tile
|
||||
// gets, the one line of facts the shelf's tiles share, and the colour a
|
||||
// wide card or genre band is washed in. Mirrors the web client's
|
||||
// lib/playlists/shelf.ts so both Homes read the same.
|
||||
|
||||
/**
|
||||
* Each tile takes the first of its playlist's cover albums that no tile
|
||||
* before it on the shelf already shows, so a shelf never repeats a cover
|
||||
* while a tile still has an unused one. A tile whose albums are all taken
|
||||
* reuses its own first albums rather than showing nothing. [perTile] is
|
||||
* how many covers a tile shows (one for a card, three for a genre band).
|
||||
*/
|
||||
fun assignShelfCovers(playlists: List<PlaylistRef>, perTile: Int): List<List<String>> {
|
||||
val used = mutableSetOf<String>()
|
||||
return playlists.map { p ->
|
||||
val fresh = p.coverAlbumIds.filter { it !in used }.take(perTile)
|
||||
val picked = fresh.ifEmpty { p.coverAlbumIds.take(perTile) }
|
||||
used += picked
|
||||
picked
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* System playlists are rebuilt in place, so created_at is when the mix was
|
||||
* last refreshed. Worded for a person ("Refreshed today"), not as "3h ago".
|
||||
* Empty when [iso] does not parse.
|
||||
*/
|
||||
fun refreshedLabel(
|
||||
iso: String,
|
||||
now: Instant = Instant.now(),
|
||||
zone: ZoneId = ZoneId.systemDefault(),
|
||||
): String {
|
||||
val t = runCatching { Instant.parse(iso) }.getOrNull() ?: return ""
|
||||
val days = ChronoUnit.DAYS.between(t.atZone(zone).toLocalDate(), now.atZone(zone).toLocalDate())
|
||||
return when {
|
||||
ChronoUnit.MINUTES.between(t, now) < JUST_NOW_MINUTES -> "Refreshed just now"
|
||||
days <= 0 -> "Refreshed today"
|
||||
days == 1L -> "Refreshed yesterday"
|
||||
days < WEEK_DAYS -> "Refreshed $days days ago"
|
||||
else -> "Refreshed " + t.atZone(zone).format(DateTimeFormatter.ofPattern("MMM d", Locale.getDefault()))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The facts every system mix on a shelf has in common, said once beside the
|
||||
* shelf's title instead of under each tile: their size when it is about the
|
||||
* same, and when they were refreshed when that is the same. Empty when the
|
||||
* mixes share nothing worth saying. User playlists are left out: their sizes
|
||||
* and ages are their own.
|
||||
*/
|
||||
fun shelfMeta(
|
||||
playlists: List<PlaylistRef>,
|
||||
now: Instant = Instant.now(),
|
||||
zone: ZoneId = ZoneId.systemDefault(),
|
||||
): String {
|
||||
val mixes = playlists.filter { it.isSystem }
|
||||
if (mixes.isEmpty()) return ""
|
||||
val parts = mutableListOf<String>()
|
||||
|
||||
val counts = mixes.map { it.trackCount }.sorted()
|
||||
val lo = counts.first()
|
||||
val hi = counts.last()
|
||||
if (lo == hi) {
|
||||
parts += "${plural(lo, "song", "songs")} each"
|
||||
} else if (hi - lo <= hi * SAME_SIZE_TOLERANCE) {
|
||||
// Close enough to read as one size: round the middle to a friendly 5.
|
||||
val mid = counts[counts.size / 2]
|
||||
val rounded = max(ROUND_TO, (mid.toDouble() / ROUND_TO).roundToInt() * ROUND_TO)
|
||||
parts += "about ${plural(rounded, "song", "songs")} each"
|
||||
}
|
||||
|
||||
val labels = mixes.map { refreshedLabel(it.createdAt, now, zone) }.toSet()
|
||||
val label = labels.singleOrNull()
|
||||
if (!label.isNullOrEmpty()) parts += label.lowercase(Locale.getDefault())
|
||||
|
||||
return parts.joinToString(" · ").replaceFirstChar { it.uppercase() }
|
||||
}
|
||||
|
||||
/**
|
||||
* "Songs like Low Tide Choir" → "Low Tide Choir": a Songs like tile labels
|
||||
* the artist under its circle, so the prefix would only repeat the shelf.
|
||||
*/
|
||||
fun songsLikeArtist(p: PlaylistRef): String = p.name.replace(SONGS_LIKE_PREFIX, "")
|
||||
|
||||
/** "{n} song" / "{n} songs". */
|
||||
fun plural(n: Int, one: String, many: String): String = "$n ${if (n == 1) one else many}"
|
||||
|
||||
/** An sRGB colour as 0–255 channels; kept free of Compose so it unit-tests. */
|
||||
data class Rgb(val r: Int, val g: Int, val b: Int)
|
||||
|
||||
/**
|
||||
* The colour a wide card or genre band is washed in, from its lead cover's
|
||||
* main colour. A light or loud cover would wash the card too light for the
|
||||
* light text on it, so the tone keeps the cover's hue but caps its
|
||||
* lightness and saturation. The card's gradient then darkens it further,
|
||||
* and its text clears 4.5:1 on any cover (ShelfTest checks it).
|
||||
*/
|
||||
fun washTone(c: Rgb): Rgb {
|
||||
val (h, s, l) = toHsl(c.r / CHANNEL_MAX, c.g / CHANNEL_MAX, c.b / CHANNEL_MAX)
|
||||
return fromHsl(h, min(s, MAX_WASH_SATURATION), min(l, MAX_WASH_LIGHTNESS))
|
||||
}
|
||||
|
||||
private fun toHsl(r: Double, g: Double, b: Double): Triple<Double, Double, Double> {
|
||||
val mx = maxOf(r, g, b)
|
||||
val mn = minOf(r, g, b)
|
||||
val l = (mx + mn) / 2
|
||||
if (mx == mn) return Triple(0.0, 0.0, l)
|
||||
val d = mx - mn
|
||||
val s = if (l > HALF) d / (2 - mx - mn) else d / (mx + mn)
|
||||
val h = when (mx) {
|
||||
r -> (g - b) / d + (if (g < b) HUE_SECTORS else 0.0)
|
||||
g -> (b - r) / d + 2
|
||||
else -> (r - g) / d + 4
|
||||
}
|
||||
return Triple(h / HUE_SECTORS, s, l)
|
||||
}
|
||||
|
||||
private fun fromHsl(h: Double, s: Double, l: Double): Rgb {
|
||||
val q = if (l < HALF) l * (1 + s) else l + s - l * s
|
||||
val p = 2 * l - q
|
||||
fun channel(t0: Double): Double {
|
||||
var t = t0
|
||||
if (t < 0) t += 1
|
||||
if (t > 1) t -= 1
|
||||
return when {
|
||||
t < 1.0 / HUE_SECTORS -> p + (q - p) * HUE_SECTORS * t
|
||||
t < HALF -> q
|
||||
t < TWO_THIRDS -> p + (q - p) * (TWO_THIRDS - t) * HUE_SECTORS
|
||||
else -> p
|
||||
}
|
||||
}
|
||||
return Rgb(
|
||||
r = (channel(h + ONE_THIRD) * CHANNEL_MAX).roundToInt(),
|
||||
g = (channel(h) * CHANNEL_MAX).roundToInt(),
|
||||
b = (channel(h - ONE_THIRD) * CHANNEL_MAX).roundToInt(),
|
||||
)
|
||||
}
|
||||
|
||||
private val SONGS_LIKE_PREFIX = Regex("^Songs like\\s+", RegexOption.IGNORE_CASE)
|
||||
private const val JUST_NOW_MINUTES = 5
|
||||
private const val WEEK_DAYS = 7
|
||||
private const val SAME_SIZE_TOLERANCE = 0.1
|
||||
private const val ROUND_TO = 5
|
||||
private const val CHANNEL_MAX = 255.0
|
||||
private const val HUE_SECTORS = 6.0
|
||||
private const val HALF = 0.5
|
||||
private const val ONE_THIRD = 1.0 / 3
|
||||
private const val TWO_THIRDS = 2.0 / 3
|
||||
private const val MAX_WASH_SATURATION = 0.6
|
||||
private const val MAX_WASH_LIGHTNESS = 0.3
|
||||
+8
@@ -263,6 +263,8 @@ private fun CachedPlaylistEntity.toDomain(): PlaylistRef =
|
||||
isPublic = isPublic,
|
||||
systemVariant = systemVariant,
|
||||
trackCount = trackCount,
|
||||
coverAlbumIds = coverAlbumIds.split(',').filter { it.isNotEmpty() },
|
||||
createdAt = createdAt,
|
||||
// Server returns a relative cover path like "/api/playlists/<id>/cover";
|
||||
// wrap through the placeholder host so BaseUrlInterceptor + the shared
|
||||
// Coil/OkHttpClient resolve it against the live server. Without this
|
||||
@@ -280,6 +282,8 @@ private fun PlaylistWire.toEntity(): CachedPlaylistEntity =
|
||||
coverPath = coverUrl.ifEmpty { null },
|
||||
trackCount = trackCount,
|
||||
systemVariant = systemVariant,
|
||||
coverAlbumIds = coverAlbumIds.joinToString(","),
|
||||
createdAt = createdAt,
|
||||
)
|
||||
|
||||
private fun PlaylistDetailWire.toPlaylistEntity(): CachedPlaylistEntity =
|
||||
@@ -292,6 +296,8 @@ private fun PlaylistDetailWire.toPlaylistEntity(): CachedPlaylistEntity =
|
||||
coverPath = coverUrl.ifEmpty { null },
|
||||
trackCount = trackCount,
|
||||
systemVariant = systemVariant,
|
||||
coverAlbumIds = coverAlbumIds.joinToString(","),
|
||||
createdAt = createdAt,
|
||||
)
|
||||
|
||||
private fun PlaylistDetailWire.toPlaylistRef(): PlaylistRef =
|
||||
@@ -308,6 +314,8 @@ private fun PlaylistDetailWire.toPlaylistRef(): PlaylistRef =
|
||||
// host for BaseUrlInterceptor to rewrite to the live server.
|
||||
coverUrl = resolveServerUrl(coverUrl) ?: "",
|
||||
ownerUsername = ownerUsername,
|
||||
coverAlbumIds = coverAlbumIds,
|
||||
createdAt = createdAt,
|
||||
)
|
||||
|
||||
private fun PlaylistTrackWire.toDomain(): PlaylistTrackRef =
|
||||
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.fabledsword.minstrel.playlists.widgets
|
||||
|
||||
/**
|
||||
* Which shelf a placeholder stands in for; it takes that shelf's tile shape.
|
||||
* TALL fills the width its caller gives it, like [TallPlaylistCard].
|
||||
*/
|
||||
enum class PlaceholderShape { SQUARE, WIDE, TALL, ROUND }
|
||||
+1
-1
@@ -154,7 +154,6 @@ private fun VariantPill(label: String, modifier: Modifier = Modifier) {
|
||||
}
|
||||
|
||||
private const val PILL_BG_ALPHA = 0.85f
|
||||
private const val GREYED_ALPHA = 0.45f
|
||||
|
||||
private fun subtitleFor(playlist: PlaylistRef): String = when {
|
||||
playlist.trackCount > 0 -> "${playlist.trackCount} tracks"
|
||||
@@ -171,6 +170,7 @@ private fun systemLabelFor(variant: String?): String = when (variant) {
|
||||
"new_for_you" -> "New for you"
|
||||
"on_this_day" -> "On this day"
|
||||
"first_listens" -> "First listens"
|
||||
"genre_mix" -> "Genre mix"
|
||||
null -> ""
|
||||
else -> variant.replace('_', ' ').replaceFirstChar { it.uppercase() }
|
||||
}
|
||||
|
||||
+73
-8
@@ -3,12 +3,15 @@ package com.fabledsword.minstrel.playlists.widgets
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
@@ -18,6 +21,7 @@ import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.composables.icons.lucide.ListMusic
|
||||
@@ -43,12 +47,32 @@ fun PlaylistPlaceholderCard(
|
||||
label: String,
|
||||
variant: String,
|
||||
modifier: Modifier = Modifier,
|
||||
shape: PlaceholderShape = PlaceholderShape.SQUARE,
|
||||
) {
|
||||
if (shape == PlaceholderShape.WIDE) {
|
||||
WidePlaceholder(label = label, variant = variant, modifier = modifier)
|
||||
return
|
||||
}
|
||||
val round = shape == PlaceholderShape.ROUND
|
||||
val tall = shape == PlaceholderShape.TALL
|
||||
Column(
|
||||
modifier = if (tall) {
|
||||
modifier
|
||||
} else {
|
||||
modifier.width(if (round) 136.dp else 176.dp).padding(horizontal = 8.dp)
|
||||
},
|
||||
horizontalAlignment = if (round) Alignment.CenterHorizontally else Alignment.Start,
|
||||
) {
|
||||
Column(modifier = modifier.width(176.dp).padding(horizontal = 8.dp)) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(144.dp)
|
||||
.clip(RoundedCornerShape(FabledSwordFlatTokens.radiusSm))
|
||||
.then(
|
||||
if (tall) {
|
||||
Modifier.fillMaxWidth().aspectRatio(1f)
|
||||
} else {
|
||||
Modifier.size(if (round) 120.dp else 144.dp)
|
||||
},
|
||||
)
|
||||
.clip(if (round) CircleShape else RoundedCornerShape(FabledSwordFlatTokens.radiusSm))
|
||||
.background(MaterialTheme.colorScheme.surfaceVariant),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
@@ -58,10 +82,47 @@ fun PlaylistPlaceholderCard(
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(40.dp),
|
||||
)
|
||||
Surface(
|
||||
StatusPill(
|
||||
variant = variant,
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomStart)
|
||||
.align(if (round) Alignment.BottomCenter else Alignment.BottomStart)
|
||||
.padding(6.dp),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
PlaceholderText(label = label, variant = variant, centered = round)
|
||||
}
|
||||
}
|
||||
|
||||
/** The wide placeholder, the same size as Home's wide playlist card. */
|
||||
@Composable
|
||||
private fun WidePlaceholder(label: String, variant: String, modifier: Modifier) {
|
||||
Row(
|
||||
modifier = modifier
|
||||
.width(296.dp)
|
||||
.height(125.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(MaterialTheme.colorScheme.surfaceVariant),
|
||||
) {
|
||||
Box(modifier = Modifier.size(125.dp), contentAlignment = Alignment.Center) {
|
||||
Icon(
|
||||
imageVector = iconFor(variant),
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(40.dp),
|
||||
)
|
||||
StatusPill(variant = variant, modifier = Modifier.align(Alignment.BottomStart).padding(6.dp))
|
||||
}
|
||||
Column(modifier = Modifier.padding(12.dp)) {
|
||||
PlaceholderText(label = label, variant = variant, centered = false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StatusPill(variant: String, modifier: Modifier) {
|
||||
Surface(
|
||||
modifier = modifier,
|
||||
shape = RoundedCornerShape(FabledSwordFlatTokens.radiusSm),
|
||||
color = MaterialTheme.colorScheme.surface.copy(alpha = STATUS_BG_ALPHA),
|
||||
) {
|
||||
@@ -73,13 +134,17 @@ fun PlaylistPlaceholderCard(
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
|
||||
@Composable
|
||||
private fun PlaceholderText(label: String, variant: String, centered: Boolean) {
|
||||
val align = if (centered) TextAlign.Center else TextAlign.Start
|
||||
Text(
|
||||
text = label,
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
textAlign = align,
|
||||
)
|
||||
Text(
|
||||
text = subtitleFor(variant),
|
||||
@@ -87,9 +152,9 @@ fun PlaylistPlaceholderCard(
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
textAlign = align,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private const val STATUS_BG_ALPHA = 0.85f
|
||||
|
||||
|
||||
+369
@@ -0,0 +1,369 @@
|
||||
package com.fabledsword.minstrel.playlists.widgets
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.offset
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.rotate
|
||||
import androidx.compose.ui.draw.shadow
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Shadow
|
||||
import androidx.compose.ui.graphics.lerp
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.zIndex
|
||||
import com.composables.icons.lucide.ListMusic
|
||||
import com.composables.icons.lucide.Lucide
|
||||
import com.fabledsword.minstrel.models.PlaylistRef
|
||||
import com.fabledsword.minstrel.models.albumCoverPath
|
||||
import com.fabledsword.minstrel.nav.LocalDetailSeedCache
|
||||
import com.fabledsword.minstrel.player.ui.rememberDominantColor
|
||||
import com.fabledsword.minstrel.playlists.Rgb
|
||||
import com.fabledsword.minstrel.playlists.plural
|
||||
import com.fabledsword.minstrel.playlists.songsLikeArtist
|
||||
import com.fabledsword.minstrel.playlists.washTone
|
||||
import com.fabledsword.minstrel.shared.widgets.CoverTile
|
||||
import com.fabledsword.minstrel.shared.widgets.PlayCircleButton
|
||||
import com.fabledsword.minstrel.shared.widgets.ServerImage
|
||||
import com.fabledsword.minstrel.theme.FabledSwordDarkTokens
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
// Home's three playlist tile shapes, one per kind of shelf, so the shelves
|
||||
// can be told apart at a glance (the web Home's PlaylistCard has the same
|
||||
// three):
|
||||
// - WidePlaylistCard: a main mix or playlist. Its lead cover on the left,
|
||||
// the name and what it is built from on a wash of the cover's colour.
|
||||
// - SongsLikeCard: a circle, the shape artists have everywhere else.
|
||||
// - GenreBandCard: a colour field with a fan of three covers.
|
||||
// `covers` are the album ids the shelf assigned this tile
|
||||
// (assignShelfCovers), so neighbouring tiles show different pictures. The
|
||||
// size and refresh time the tiles share are said once in the shelf heading
|
||||
// (shelfMeta), so no tile repeats them.
|
||||
|
||||
/**
|
||||
* A main mix or user playlist on Home. [greyed] dims it (not playable
|
||||
* offline) while keeping it tappable, as [PlaylistCard] does.
|
||||
*/
|
||||
@Composable
|
||||
fun WidePlaylistCard(
|
||||
playlist: PlaylistRef,
|
||||
covers: List<String>,
|
||||
onClick: () -> Unit,
|
||||
onPlay: suspend () -> Unit,
|
||||
playEnabled: Boolean,
|
||||
greyed: Boolean,
|
||||
) {
|
||||
val lead = leadCoverUrl(playlist, covers)
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.width(WIDE_WIDTH)
|
||||
.height(WIDE_HEIGHT)
|
||||
.alpha(if (greyed) GREYED_ALPHA else 1f)
|
||||
.clip(RoundedCornerShape(CARD_RADIUS))
|
||||
.background(washBrush(rememberWash(lead)))
|
||||
.stashingClick(playlist, onClick),
|
||||
) {
|
||||
Row(modifier = Modifier.fillMaxSize()) {
|
||||
LeadArt(url = lead, modifier = Modifier.size(WIDE_HEIGHT))
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.padding(start = 12.dp, top = 12.dp, end = 52.dp, bottom = 12.dp),
|
||||
) {
|
||||
Text(
|
||||
text = playlist.name,
|
||||
style = MaterialTheme.typography.headlineSmall,
|
||||
color = OnWash,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
text = sublineFor(playlist),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = OnWash.copy(alpha = ON_WASH_2),
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
PlayCircleButton(
|
||||
onPlay = onPlay,
|
||||
enabled = playEnabled && !greyed,
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomEnd)
|
||||
.padding(8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** A "Songs like {artist}" mix: a circle labelled with the seed artist. */
|
||||
@Composable
|
||||
fun SongsLikeCard(
|
||||
playlist: PlaylistRef,
|
||||
covers: List<String>,
|
||||
onClick: () -> Unit,
|
||||
onPlay: suspend () -> Unit,
|
||||
playEnabled: Boolean,
|
||||
greyed: Boolean,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.width(ROUND_WIDTH)
|
||||
.alpha(if (greyed) GREYED_ALPHA else 1f)
|
||||
.stashingClick(playlist, onClick)
|
||||
.padding(horizontal = 8.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
CoverTile(
|
||||
url = leadCoverUrl(playlist, covers),
|
||||
contentDescription = playlist.name,
|
||||
size = ROUND_SIZE,
|
||||
shape = CircleShape,
|
||||
background = MaterialTheme.colorScheme.surfaceVariant,
|
||||
fallback = { NoArtIcon() },
|
||||
overlay = {
|
||||
PlayCircleButton(
|
||||
onPlay = onPlay,
|
||||
enabled = playEnabled && !greyed,
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomEnd)
|
||||
.padding(4.dp),
|
||||
)
|
||||
},
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
text = "SONGS LIKE",
|
||||
style = MaterialTheme.typography.labelSmall.copy(letterSpacing = MICRO_LABEL_TRACKING),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Text(
|
||||
text = songsLikeArtist(playlist),
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A genre mix: a field of its lead cover's colour, the genre in large type,
|
||||
* and a fan of up to three covers across most of its width. The leftmost
|
||||
* cover sits on top and each one to its right tucks under it.
|
||||
*/
|
||||
@Composable
|
||||
fun GenreBandCard(
|
||||
playlist: PlaylistRef,
|
||||
covers: List<String>,
|
||||
onClick: () -> Unit,
|
||||
onPlay: suspend () -> Unit,
|
||||
playEnabled: Boolean,
|
||||
greyed: Boolean,
|
||||
) {
|
||||
val fan = covers.map(::albumCoverPath).ifEmpty { listOfNotNull(playlist.coverUrl.ifEmpty { null }) }
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.width(BAND_WIDTH)
|
||||
.height(BAND_HEIGHT)
|
||||
.alpha(if (greyed) GREYED_ALPHA else 1f)
|
||||
.clip(RoundedCornerShape(CARD_RADIUS))
|
||||
.background(washBrush(rememberWash(fan.firstOrNull())))
|
||||
.stashingClick(playlist, onClick),
|
||||
) {
|
||||
CoverFan(urls = fan, modifier = Modifier.align(Alignment.CenterEnd).padding(end = 12.dp))
|
||||
Text(
|
||||
text = playlist.name.replace(MIX_SUFFIX, ""),
|
||||
style = MaterialTheme.typography.headlineSmall.copy(
|
||||
shadow = Shadow(color = Color.Black.copy(alpha = NAME_SHADOW_ALPHA), blurRadius = 4f),
|
||||
),
|
||||
color = OnWash,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomStart)
|
||||
.padding(start = 8.dp, bottom = 10.dp)
|
||||
.widthIn(max = BAND_WIDTH * NAME_MAX_FRACTION)
|
||||
.zIndex(FAN_LAYERS)
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.background(NameBacking)
|
||||
.padding(horizontal = 8.dp, vertical = 2.dp),
|
||||
)
|
||||
PlayCircleButton(
|
||||
onPlay = onPlay,
|
||||
enabled = playEnabled && !greyed,
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomEnd)
|
||||
.zIndex(FAN_LAYERS + 1)
|
||||
.padding(8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Up to three covers spanning [FAN_SPAN] of the band's width, as tall as the
|
||||
* band allows and overlapping to fit, tilted -8° / 0° / +8°.
|
||||
*/
|
||||
@Composable
|
||||
private fun CoverFan(urls: List<String>, modifier: Modifier = Modifier) {
|
||||
val n = urls.size.coerceAtMost(FAN_MAX)
|
||||
if (n == 0) return
|
||||
val span = BAND_WIDTH * FAN_SPAN
|
||||
val step: Dp = if (n > 1) (span - FAN_COVER) / (n - 1) else 0.dp
|
||||
Box(modifier = modifier.width(if (n > 1) span else FAN_COVER).height(BAND_HEIGHT)) {
|
||||
urls.take(n).forEachIndexed { i, url ->
|
||||
val tilt = if (n > 1) FAN_TILT_DEG * (2f * i / (n - 1) - 1f) else 0f
|
||||
ServerImage(
|
||||
url = url,
|
||||
contentDescription = null,
|
||||
modifier = Modifier
|
||||
.align(Alignment.CenterStart)
|
||||
.offset(x = step * i, y = if (tilt == 0f) (-4).dp else 4.dp)
|
||||
.zIndex((n - i).toFloat())
|
||||
.rotate(tilt)
|
||||
.shadow(elevation = 6.dp, shape = RoundedCornerShape(6.dp))
|
||||
.size(FAN_COVER)
|
||||
.clip(RoundedCornerShape(6.dp)),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun LeadArt(url: String?, modifier: Modifier) {
|
||||
Box(
|
||||
modifier = modifier
|
||||
.fillMaxHeight()
|
||||
.background(MaterialTheme.colorScheme.surfaceVariant),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
ServerImage(
|
||||
url = url,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
fallback = { NoArtIcon() },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun NoArtIcon() {
|
||||
Icon(
|
||||
imageVector = Lucide.ListMusic,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(40.dp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun Modifier.stashingClick(playlist: PlaylistRef, onClick: () -> Unit): Modifier {
|
||||
val seedCache = LocalDetailSeedCache.current
|
||||
return clickable {
|
||||
seedCache.stashPlaylist(playlist)
|
||||
onClick()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The wash colour for a tile whose lead cover is [url]: the cover's main
|
||||
* colour, toned by [washTone] so light text reads on it. A neutral slate
|
||||
* until the colour is known, or when there is no cover.
|
||||
*/
|
||||
@Composable
|
||||
internal fun rememberWash(url: String?): Color {
|
||||
val dominant = rememberDominantColor(url)
|
||||
if (dominant == Color.Transparent) return NeutralWash
|
||||
val toned = washTone(
|
||||
Rgb(
|
||||
r = (dominant.red * CHANNEL_MAX).roundToInt(),
|
||||
g = (dominant.green * CHANNEL_MAX).roundToInt(),
|
||||
b = (dominant.blue * CHANNEL_MAX).roundToInt(),
|
||||
),
|
||||
)
|
||||
return Color(red = toned.r, green = toned.g, blue = toned.b)
|
||||
}
|
||||
|
||||
/**
|
||||
* The tile background: the wash darkened toward near-black, 62% wash at the
|
||||
* art end fading to 30% (left to right, or top to bottom when [vertical]).
|
||||
* With [washTone]'s caps this keeps [OnWash] text at 4.5:1 or better on any
|
||||
* cover (ShelfTest checks the numbers).
|
||||
*/
|
||||
internal fun washBrush(wash: Color, vertical: Boolean = false): Brush {
|
||||
val stops = listOf(lerp(WashBase, wash, WASH_NEAR), lerp(WashBase, wash, WASH_FAR))
|
||||
return if (vertical) Brush.verticalGradient(stops) else Brush.horizontalGradient(stops)
|
||||
}
|
||||
|
||||
internal fun leadCoverUrl(playlist: PlaylistRef, covers: List<String>): String? =
|
||||
covers.firstOrNull()?.let(::albumCoverPath) ?: playlist.coverUrl.ifEmpty { null }
|
||||
|
||||
/** A system mix says what it is built from; anything else says its size and owner. */
|
||||
internal fun sublineFor(p: PlaylistRef): String =
|
||||
if (p.isSystem && p.description.isNotEmpty()) {
|
||||
p.description
|
||||
} else {
|
||||
plural(p.trackCount, "track", "tracks") +
|
||||
if (p.ownerUsername.isNotEmpty()) " · by ${p.ownerUsername}" else ""
|
||||
}
|
||||
|
||||
// The wash is dark in both themes, so its text is the dark theme's light
|
||||
// parchment in both themes too; the theme-switching tokens would turn it
|
||||
// dark in light mode and lose the contrast.
|
||||
internal val OnWash = FabledSwordDarkTokens.parchment
|
||||
private val WashBase = Color(red = 14, green = 16, blue = 19)
|
||||
private val NeutralWash = Color(red = 44, green = 49, blue = 58)
|
||||
|
||||
// 70% near-black behind a genre name keeps it above 4.5:1 even where the
|
||||
// fan's covers run under it and one of them is white.
|
||||
private val NameBacking = Color(red = 14, green = 16, blue = 19, alpha = 179)
|
||||
private val MIX_SUFFIX = Regex("\\s+mix$", RegexOption.IGNORE_CASE)
|
||||
|
||||
// Wide card 64:27 and band 16:7, the web Home's proportions.
|
||||
private val WIDE_WIDTH = 296.dp
|
||||
private val WIDE_HEIGHT = 125.dp
|
||||
private val BAND_WIDTH = 280.dp
|
||||
private val BAND_HEIGHT = 122.dp
|
||||
private val ROUND_WIDTH = 136.dp
|
||||
private val ROUND_SIZE = 120.dp
|
||||
internal val CARD_RADIUS = 12.dp
|
||||
private val FAN_COVER = 95.dp
|
||||
private val MICRO_LABEL_TRACKING = 0.9.sp
|
||||
|
||||
private const val FAN_SPAN = 0.8f
|
||||
private const val FAN_MAX = 3
|
||||
private const val FAN_LAYERS = 4f
|
||||
private const val FAN_TILT_DEG = 8f
|
||||
private const val NAME_MAX_FRACTION = 0.85f
|
||||
private const val NAME_SHADOW_ALPHA = 0.6f
|
||||
private const val WASH_NEAR = 0.62f
|
||||
private const val WASH_FAR = 0.30f
|
||||
internal const val ON_WASH_2 = 0.9f
|
||||
internal const val GREYED_ALPHA = 0.45f
|
||||
private const val CHANNEL_MAX = 255f
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package com.fabledsword.minstrel.playlists.widgets
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.fabledsword.minstrel.models.PlaylistRef
|
||||
import com.fabledsword.minstrel.shared.widgets.PlayCircleButton
|
||||
|
||||
/**
|
||||
* The phone-portrait form of [WidePlaylistCard], for screens where a wide
|
||||
* card would leave only one playlist in view: the lead cover on top, and
|
||||
* under it a panel washed in the cover's colour holding the name, what the
|
||||
* mix is built from, and the play button, which sits on the panel and never
|
||||
* over the art. [width] is chosen by the shelf so two cards show whole.
|
||||
*/
|
||||
@Composable
|
||||
fun TallPlaylistCard(
|
||||
playlist: PlaylistRef,
|
||||
covers: List<String>,
|
||||
width: Dp,
|
||||
onClick: () -> Unit,
|
||||
onPlay: suspend () -> Unit,
|
||||
playEnabled: Boolean,
|
||||
greyed: Boolean,
|
||||
) {
|
||||
val lead = leadCoverUrl(playlist, covers)
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.width(width)
|
||||
.alpha(if (greyed) GREYED_ALPHA else 1f)
|
||||
.clip(RoundedCornerShape(CARD_RADIUS))
|
||||
.background(washBrush(rememberWash(lead), vertical = true))
|
||||
.stashingClick(playlist, onClick),
|
||||
) {
|
||||
LeadArt(url = lead, modifier = Modifier.fillMaxWidth().aspectRatio(1f))
|
||||
Box(modifier = Modifier.fillMaxWidth().height(TALL_PANEL_HEIGHT)) {
|
||||
Column(modifier = Modifier.padding(start = 10.dp, top = 8.dp, end = 10.dp, bottom = 8.dp)) {
|
||||
Text(
|
||||
text = playlist.name,
|
||||
style = MaterialTheme.typography.headlineSmall,
|
||||
color = OnWash,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(
|
||||
text = sublineFor(playlist),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = OnWash.copy(alpha = ON_WASH_2),
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
// Leaves the play button's corner clear.
|
||||
modifier = Modifier.padding(end = 40.dp),
|
||||
)
|
||||
}
|
||||
PlayCircleButton(
|
||||
onPlay = onPlay,
|
||||
enabled = playEnabled && !greyed,
|
||||
size = 36.dp,
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomEnd)
|
||||
.padding(8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Name, two lines of description, and room for the play button under them.
|
||||
private val TALL_PANEL_HEIGHT = 96.dp
|
||||
-73
@@ -1,73 +0,0 @@
|
||||
package com.fabledsword.minstrel.requests.data
|
||||
|
||||
import com.fabledsword.minstrel.api.endpoints.RequestsApi
|
||||
import com.fabledsword.minstrel.cache.mutations.MutationQueue
|
||||
import com.fabledsword.minstrel.models.RequestRef
|
||||
import com.fabledsword.minstrel.models.RequestStatus
|
||||
import com.fabledsword.minstrel.models.wire.RequestWire
|
||||
import retrofit2.Retrofit
|
||||
import retrofit2.create
|
||||
import java.io.IOException
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Outcome of a [RequestsRepository.cancel] call. Mirrors the
|
||||
* [com.fabledsword.minstrel.likes.data.UnflagOutcome] / etc. shape.
|
||||
*/
|
||||
enum class CancelOutcome { Synced, Queued }
|
||||
|
||||
/**
|
||||
* Read-through accessor for the caller's own requests +
|
||||
* cancel-while-pending write. No Room caching. Cancel is offline-first:
|
||||
* direct REST on the happy
|
||||
* path, MutationQueue fallback on transport failure so the user's
|
||||
* intent persists across connectivity loss.
|
||||
*/
|
||||
@Singleton
|
||||
class RequestsRepository @Inject constructor(
|
||||
private val mutationQueue: MutationQueue,
|
||||
retrofit: Retrofit,
|
||||
) {
|
||||
private val api: RequestsApi = retrofit.create()
|
||||
|
||||
suspend fun listMine(): List<RequestRef> =
|
||||
api.listMine().map { it.toDomain() }
|
||||
|
||||
/**
|
||||
* Cancels a pending request. On 2xx, returns the canonical
|
||||
* cancelled row from the server (status=rejected). On transport
|
||||
* failure, enqueues a REQUEST_CANCEL mutation for later replay
|
||||
* and returns null — the caller's optimistic UI removal already
|
||||
* reflects the user's intent, and the next listMine() refetch
|
||||
* (post-replay) will surface the canonical row.
|
||||
*/
|
||||
suspend fun cancel(id: String): Pair<CancelOutcome, RequestRef?> = try {
|
||||
CancelOutcome.Synced to api.cancel(id).toDomain()
|
||||
} catch (
|
||||
@Suppress("SwallowedException") _: IOException,
|
||||
) {
|
||||
mutationQueue.enqueueRequestCancel(id)
|
||||
CancelOutcome.Queued to null
|
||||
}
|
||||
}
|
||||
|
||||
// ── Mappers (internal — wire stays out of UI) ──
|
||||
|
||||
private fun RequestWire.toDomain(): RequestRef = RequestRef(
|
||||
id = id,
|
||||
userId = userId,
|
||||
status = RequestStatus.fromWire(status),
|
||||
kind = kind,
|
||||
artistName = artistName,
|
||||
albumTitle = albumTitle,
|
||||
trackTitle = trackTitle,
|
||||
requestedAt = requestedAt,
|
||||
decidedAt = decidedAt,
|
||||
notes = notes,
|
||||
importedAlbumCount = importedAlbumCount,
|
||||
importedTrackCount = importedTrackCount,
|
||||
matchedTrackId = matchedTrackId,
|
||||
matchedAlbumId = matchedAlbumId,
|
||||
matchedArtistId = matchedArtistId,
|
||||
)
|
||||
@@ -1,313 +0,0 @@
|
||||
@file:Suppress("TooManyFunctions") // Compose screen + private helper composables
|
||||
|
||||
package com.fabledsword.minstrel.requests.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.AssistChip
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.navigation.NavHostController
|
||||
import com.composables.icons.lucide.Disc3
|
||||
import com.composables.icons.lucide.LibraryBig
|
||||
import com.composables.icons.lucide.Lucide
|
||||
import com.composables.icons.lucide.Music
|
||||
import com.composables.icons.lucide.Play
|
||||
import com.composables.icons.lucide.X
|
||||
import com.fabledsword.minstrel.models.RequestRef
|
||||
import com.fabledsword.minstrel.models.RequestStatus
|
||||
import com.fabledsword.minstrel.nav.AlbumDetail
|
||||
import com.fabledsword.minstrel.shared.UiState
|
||||
import com.fabledsword.minstrel.nav.ArtistDetail
|
||||
import com.fabledsword.minstrel.nav.Requests
|
||||
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
|
||||
import com.fabledsword.minstrel.shared.widgets.EmptyState
|
||||
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
|
||||
import com.fabledsword.minstrel.shared.widgets.LoadingCentered
|
||||
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
|
||||
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
|
||||
|
||||
@Composable
|
||||
fun RequestsScreen(
|
||||
navController: NavHostController,
|
||||
viewModel: RequestsViewModel = hiltViewModel(),
|
||||
) {
|
||||
val state by viewModel.uiState.collectAsStateWithLifecycle()
|
||||
Scaffold(
|
||||
contentWindowInsets = ShellContentWindowInsets,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
topBar = {
|
||||
MinstrelTopAppBar(
|
||||
title = "Your requests",
|
||||
navController = navController,
|
||||
currentRouteName = Requests::class.qualifiedName,
|
||||
onBack = { navController.popBackStack() },
|
||||
)
|
||||
},
|
||||
) { inner ->
|
||||
PullToRefreshScaffold(
|
||||
onRefresh = { viewModel.refresh().join() },
|
||||
modifier = Modifier.fillMaxSize().padding(inner),
|
||||
) {
|
||||
when (val s = state) {
|
||||
UiState.Loading -> LoadingCentered()
|
||||
UiState.Empty -> EmptyState(
|
||||
title = "Nothing requested yet",
|
||||
body = "Use Discover to ask for new music; your " +
|
||||
"requests show up here.",
|
||||
)
|
||||
is UiState.Error -> ErrorRetry(
|
||||
title = "Couldn't load requests",
|
||||
message = s.message,
|
||||
onRetry = { viewModel.refresh() },
|
||||
)
|
||||
is UiState.Success -> RequestList(
|
||||
rows = s.data,
|
||||
onCancel = viewModel::cancel,
|
||||
onListen = { id -> navController.navigate(id) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RequestList(
|
||||
rows: List<RequestRef>,
|
||||
onCancel: (String) -> Unit,
|
||||
onListen: (Any) -> Unit,
|
||||
) {
|
||||
LazyColumn(modifier = Modifier.fillMaxSize()) {
|
||||
items(items = rows, key = { it.id }) { req ->
|
||||
RequestRow(
|
||||
req = req,
|
||||
onCancel = { onCancel(req.id) },
|
||||
onListen = req.listenRoute()?.let { route -> { onListen(route) } },
|
||||
)
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RequestRow(
|
||||
req: RequestRef,
|
||||
onCancel: () -> Unit,
|
||||
onListen: (() -> Unit)?,
|
||||
) {
|
||||
var showCancelConfirm by remember { mutableStateOf(false) }
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
KindAvatar(kind = req.kind)
|
||||
RequestRowBody(req = req, modifier = Modifier.weight(1f))
|
||||
RequestRowAction(
|
||||
req = req,
|
||||
onListen = onListen,
|
||||
onAskCancel = { showCancelConfirm = true },
|
||||
)
|
||||
}
|
||||
if (showCancelConfirm) {
|
||||
CancelConfirmDialog(
|
||||
displayName = req.displayName,
|
||||
onConfirm = {
|
||||
showCancelConfirm = false
|
||||
onCancel()
|
||||
},
|
||||
onDismiss = { showCancelConfirm = false },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RequestRowBody(req: RequestRef, modifier: Modifier = Modifier) {
|
||||
Column(modifier = modifier) {
|
||||
Text(
|
||||
text = req.displayName,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Row(
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
StatusPill(status = req.status)
|
||||
KindPill(label = req.kind)
|
||||
}
|
||||
val progress = req.ingestProgressText()
|
||||
if (progress != null) {
|
||||
Text(
|
||||
text = progress,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
if (req.status == RequestStatus.REJECTED && !req.notes.isNullOrEmpty()) {
|
||||
Text(
|
||||
text = req.notes,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RequestRowAction(
|
||||
req: RequestRef,
|
||||
onListen: (() -> Unit)?,
|
||||
onAskCancel: () -> Unit,
|
||||
) {
|
||||
when {
|
||||
onListen != null -> OutlinedButton(onClick = onListen) {
|
||||
Icon(
|
||||
Lucide.Play,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(16.dp).padding(end = 4.dp),
|
||||
)
|
||||
Text("Listen")
|
||||
}
|
||||
req.status == RequestStatus.PENDING -> TextButton(onClick = onAskCancel) {
|
||||
Icon(Lucide.X, contentDescription = null, modifier = Modifier.padding(end = 4.dp))
|
||||
Text("Cancel")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CancelConfirmDialog(
|
||||
displayName: String,
|
||||
onConfirm: () -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text("Cancel request?") },
|
||||
text = { Text("Cancel “$displayName”? Your request is withdrawn.") },
|
||||
confirmButton = {
|
||||
Button(onClick = onConfirm) { Text("Cancel request") }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = onDismiss) { Text("Keep") }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun KindAvatar(kind: String) {
|
||||
// Icons: disc-3 for artist, library-big for album, music for track.
|
||||
val icon = when (kind) {
|
||||
"artist" -> Lucide.Disc3
|
||||
"album" -> Lucide.LibraryBig
|
||||
"track" -> Lucide.Music
|
||||
else -> Lucide.Music
|
||||
}
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(28.dp),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Most-specific listenable detail-screen route for a completed
|
||||
* request, or null when nothing's been matched / the status isn't
|
||||
* completed. Track-level matches resolve to AlbumDetail since the
|
||||
* client has no TrackDetail screen.
|
||||
*/
|
||||
private fun RequestRef.listenRoute(): Any? = when {
|
||||
status != RequestStatus.COMPLETED -> null
|
||||
!matchedAlbumId.isNullOrEmpty() -> AlbumDetail(matchedAlbumId)
|
||||
!matchedArtistId.isNullOrEmpty() -> ArtistDetail(matchedArtistId)
|
||||
else -> null
|
||||
}
|
||||
|
||||
/**
|
||||
* "2 albums · 14 tracks ingested" — null when both counts are zero.
|
||||
* Singular when the count is 1 ("1 album · 1 track ingested").
|
||||
*/
|
||||
private fun RequestRef.ingestProgressText(): String? {
|
||||
if (importedAlbumCount == 0 && importedTrackCount == 0) return null
|
||||
val parts = buildList {
|
||||
if (importedAlbumCount > 0) {
|
||||
add(
|
||||
"$importedAlbumCount ${if (importedAlbumCount == 1) "album" else "albums"}",
|
||||
)
|
||||
}
|
||||
if (importedTrackCount > 0) {
|
||||
add(
|
||||
"$importedTrackCount ${if (importedTrackCount == 1) "track" else "tracks"}",
|
||||
)
|
||||
}
|
||||
}
|
||||
return "${parts.joinToString(" · ")} ingested"
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StatusPill(status: RequestStatus) {
|
||||
val (label, isError) = when (status) {
|
||||
RequestStatus.PENDING -> "pending" to false
|
||||
RequestStatus.APPROVED -> "approved" to false
|
||||
RequestStatus.COMPLETED -> "completed" to false
|
||||
RequestStatus.REJECTED -> "rejected" to true
|
||||
RequestStatus.FAILED -> "failed" to true
|
||||
RequestStatus.UNKNOWN -> "unknown" to false
|
||||
}
|
||||
val color = if (isError) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary
|
||||
AssistChip(
|
||||
onClick = {},
|
||||
enabled = false,
|
||||
label = { Text(label, color = color) },
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun KindPill(label: String) {
|
||||
AssistChip(
|
||||
onClick = {},
|
||||
enabled = false,
|
||||
label = {
|
||||
Text(
|
||||
label,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -1,177 +0,0 @@
|
||||
package com.fabledsword.minstrel.requests.ui
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.fabledsword.minstrel.api.ErrorCopy
|
||||
import com.fabledsword.minstrel.connectivity.NetworkStatusController
|
||||
import com.fabledsword.minstrel.connectivity.recoveries
|
||||
import com.fabledsword.minstrel.events.EventsStream
|
||||
import com.fabledsword.minstrel.models.RequestRef
|
||||
import com.fabledsword.minstrel.models.RequestStatus
|
||||
import com.fabledsword.minstrel.requests.data.CancelOutcome
|
||||
import com.fabledsword.minstrel.requests.data.RequestsRepository
|
||||
import com.fabledsword.minstrel.shared.UiState
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.filter
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
|
||||
private val RELEVANT_EVENT_KINDS = setOf("request.status_changed")
|
||||
|
||||
// Cadence for in-flight request polling — matches the web client:
|
||||
// fast enough to feel live, slow enough not to hammer the server.
|
||||
private const val POLL_INTERVAL_MS = 12_000L
|
||||
|
||||
@HiltViewModel
|
||||
class RequestsViewModel @Inject constructor(
|
||||
private val repository: RequestsRepository,
|
||||
private val eventsStream: EventsStream,
|
||||
networkStatus: NetworkStatusController,
|
||||
) : ViewModel() {
|
||||
|
||||
private val internal = MutableStateFlow<UiState<List<RequestRef>>>(UiState.Loading)
|
||||
val uiState: StateFlow<UiState<List<RequestRef>>> = internal.asStateFlow()
|
||||
|
||||
init {
|
||||
refresh()
|
||||
// SSE push: reconciler completions arrive here; reload silently so the
|
||||
// row updates in place rather than flashing the loading spinner.
|
||||
viewModelScope.launch {
|
||||
eventsStream.events
|
||||
.filter { it.kind in RELEVANT_EVENT_KINDS }
|
||||
.collect { silentReload() }
|
||||
}
|
||||
viewModelScope.launch { pollWhileInFlight() }
|
||||
// Screen-level auto-recovery: a load that failed while
|
||||
// the server was unreachable heals the moment health returns, without
|
||||
// waiting for the next poll tick.
|
||||
viewModelScope.launch {
|
||||
networkStatus.recoveries().collect {
|
||||
if (internal.value is UiState.Error) silentReload()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun refresh(): Job = viewModelScope.launch {
|
||||
internal.value = UiState.Loading
|
||||
try {
|
||||
val rows = repository.listMine()
|
||||
internal.value = if (rows.isEmpty()) {
|
||||
UiState.Empty
|
||||
} else {
|
||||
UiState.Success(rows)
|
||||
}
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
||||
) {
|
||||
internal.value = UiState.Error(ErrorCopy.fromThrowable(e))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto-poll while any request is mid-ingest (status APPROVED), matching the
|
||||
* web client. Reloads silently every [POLL_INTERVAL_MS] and pauses
|
||||
* when nothing is in-flight — complements the SSE push so progress stays
|
||||
* live even if the event stream drops.
|
||||
*/
|
||||
private suspend fun pollWhileInFlight() {
|
||||
while (true) {
|
||||
// Also retry from a failed load: from UiState.Error
|
||||
// the in-flight predicate can never become true, so without this
|
||||
// the poll never self-heals the screen — e.g. after a transient
|
||||
// 500 that health monitoring (transport-level) never saw.
|
||||
if (hasInFlightRequest() || internal.value is UiState.Error) {
|
||||
silentReload()
|
||||
}
|
||||
delay(POLL_INTERVAL_MS)
|
||||
}
|
||||
}
|
||||
|
||||
private fun hasInFlightRequest(): Boolean {
|
||||
val state = internal.value
|
||||
return state is UiState.Success &&
|
||||
state.data.any { it.status == RequestStatus.APPROVED }
|
||||
}
|
||||
|
||||
/**
|
||||
* Reload the list in place without flipping to Loading — used by the poll
|
||||
* loop and the SSE collector so visible rows update without a spinner
|
||||
* flash. A transient failure keeps the current view; the next reload wins.
|
||||
*/
|
||||
private suspend fun silentReload() {
|
||||
try {
|
||||
val rows = repository.listMine()
|
||||
internal.value = if (rows.isEmpty()) UiState.Empty else UiState.Success(rows)
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
|
||||
) {
|
||||
// Keep the current view; the next poll / SSE / pull reconciles.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Optimistically removes [id] from the success list so the row
|
||||
* disappears immediately; on server-side success the row is
|
||||
* replaced by the canonical cancelled state from the return value.
|
||||
* On error rolls back by refetching the list.
|
||||
*/
|
||||
fun cancel(id: String) {
|
||||
val before = internal.value
|
||||
if (before is UiState.Success) {
|
||||
val filtered = before.data.filterNot { it.id == id }
|
||||
internal.value = if (filtered.isEmpty()) {
|
||||
UiState.Empty
|
||||
} else {
|
||||
UiState.Success(filtered)
|
||||
}
|
||||
}
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val (outcome, updated) = repository.cancel(id)
|
||||
if (updated != null) {
|
||||
internal.update { state ->
|
||||
if (state !is UiState.Success) {
|
||||
// Mid-refresh — let the refresh result win, but
|
||||
// splice the cancelled row in so it shows the new
|
||||
// status if the user re-pulls.
|
||||
UiState.Success(listOf(updated))
|
||||
} else {
|
||||
// Re-insert the cancelled row in its old position
|
||||
// would require remembering the prior ordering;
|
||||
// simpler to refetch in the background.
|
||||
state
|
||||
}
|
||||
}
|
||||
}
|
||||
// Only refetch on the Synced outcome. The
|
||||
// Queued path is offline by definition — the optimistic
|
||||
// removal at the top of cancel() is correct, and a
|
||||
// refresh() call here would either (a) get the
|
||||
// not-yet-delivered cancelled row back from the server
|
||||
// and snap it into the list (confusing), or (b) fail
|
||||
// with a transport error and flip the whole screen to
|
||||
// UiState.Error, making the user think the cancel
|
||||
// failed. The mutation queue will replay the cancel
|
||||
// when connectivity returns; the next on-screen refresh
|
||||
// (pull-to-refresh, navigation back) reconciles.
|
||||
if (outcome == CancelOutcome.Synced) {
|
||||
refresh()
|
||||
}
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
|
||||
) {
|
||||
// Roll back by re-fetching; the failed cancel might
|
||||
// already be visible to the server (eventual consistency)
|
||||
// or not at all (transport drop). The refetch makes
|
||||
// local state match either outcome.
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
package com.fabledsword.minstrel.settings.ui
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.fabledsword.minstrel.BuildConfig
|
||||
import com.fabledsword.minstrel.api.ErrorCopy
|
||||
import com.fabledsword.minstrel.models.UpdateInfo
|
||||
import com.fabledsword.minstrel.update.data.ApkInstaller
|
||||
import com.fabledsword.minstrel.update.data.InstallStage
|
||||
import com.fabledsword.minstrel.update.data.UpdateRepository
|
||||
import com.fabledsword.minstrel.update.data.isBusy
|
||||
import com.fabledsword.minstrel.update.data.isUpdateAvailable
|
||||
import com.fabledsword.minstrel.update.data.message
|
||||
import com.fabledsword.minstrel.update.data.stage
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import java.io.File
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* One of three terminal states the Check-for-updates button surfaces.
|
||||
* `Idle` is the pre-check state; `Latest` means the installed build
|
||||
* matches or exceeds the server's bundled APK; `UpdateAvailable`
|
||||
* surfaces an "Install vX.Y.Z" button that downloads the APK and
|
||||
* installs it via [ApkInstaller].
|
||||
*/
|
||||
sealed interface UpdateCheckResult {
|
||||
data object Idle : UpdateCheckResult
|
||||
data object Latest : UpdateCheckResult
|
||||
data class UpdateAvailable(val info: UpdateInfo) : UpdateCheckResult
|
||||
data class Error(val message: String) : UpdateCheckResult
|
||||
}
|
||||
|
||||
data class AboutUiState(
|
||||
val installedVersion: String = BuildConfig.VERSION_NAME,
|
||||
// The value the platform installs by, and therefore the one the update
|
||||
// check must decide on. Held in state rather than read inline so a test
|
||||
// can drive the comparison without a BuildConfig.
|
||||
val installedCode: Long = BuildConfig.VERSION_CODE.toLong(),
|
||||
// A debug build is signed with this machine's debug key, so the server's
|
||||
// release-signed APK can never install over it. It updates from Android
|
||||
// Studio instead.
|
||||
val selfUpdates: Boolean = !BuildConfig.DEBUG,
|
||||
val isChecking: Boolean = false,
|
||||
val installStage: InstallStage = InstallStage.IDLE,
|
||||
val installMessage: String? = null,
|
||||
val result: UpdateCheckResult = UpdateCheckResult.Idle,
|
||||
)
|
||||
|
||||
/**
|
||||
* Backs the About card's update controls. "Check for updates" calls
|
||||
* [UpdateRepository.getLatest], compares versus this build via
|
||||
* [isUpdateAvailable] — on the ordering key where the server reports one,
|
||||
* on the name otherwise — and reports the terminal state.
|
||||
* When an update is available, [install] downloads the APK via
|
||||
* [ApkInstaller] and installs it — routing the user to the "install
|
||||
* unknown apps" settings page first when that permission hasn't been
|
||||
* granted.
|
||||
*/
|
||||
@HiltViewModel
|
||||
class AboutCardViewModel @Inject constructor(
|
||||
private val repository: UpdateRepository,
|
||||
private val installer: ApkInstaller,
|
||||
) : ViewModel() {
|
||||
|
||||
private val internal = MutableStateFlow(AboutUiState())
|
||||
val state: StateFlow<AboutUiState> = internal.asStateFlow()
|
||||
|
||||
fun checkForUpdates() {
|
||||
if (internal.value.isChecking || !internal.value.selfUpdates) return
|
||||
viewModelScope.launch {
|
||||
internal.update { it.copy(isChecking = true, installMessage = null) }
|
||||
val installed = internal.value.installedVersion
|
||||
val installedCode = internal.value.installedCode
|
||||
val result = runCatching { repository.getLatest() }
|
||||
.map { latest ->
|
||||
if (
|
||||
isUpdateAvailable(
|
||||
serverCode = latest.code,
|
||||
serverName = latest.version,
|
||||
installedCode = installedCode,
|
||||
installedName = installed,
|
||||
)
|
||||
) {
|
||||
UpdateCheckResult.UpdateAvailable(latest)
|
||||
} else {
|
||||
UpdateCheckResult.Latest
|
||||
}
|
||||
}
|
||||
.getOrElse { e -> UpdateCheckResult.Error(ErrorCopy.fromThrowable(e)) }
|
||||
internal.update { it.copy(isChecking = false, result = result) }
|
||||
}
|
||||
}
|
||||
|
||||
fun install(info: UpdateInfo) {
|
||||
if (internal.value.installStage.isBusy()) return
|
||||
if (!installer.canInstall()) {
|
||||
installer.requestInstallPermission()
|
||||
internal.update {
|
||||
it.copy(installMessage = "Allow installs for Minstrel, then tap Install again.")
|
||||
}
|
||||
return
|
||||
}
|
||||
viewModelScope.launch {
|
||||
internal.update {
|
||||
it.copy(installStage = InstallStage.DOWNLOADING, installMessage = null)
|
||||
}
|
||||
val apk = download(info.apkUrl)
|
||||
if (apk != null) {
|
||||
// The install half now suspends on the platform's verdict, so it
|
||||
// gets its own stage — reporting "Downloading…" through it would
|
||||
// be a lie once a confirm dialog is on screen.
|
||||
internal.update { it.copy(installStage = InstallStage.INSTALLING) }
|
||||
val outcome = installer.install(apk)
|
||||
internal.update {
|
||||
it.copy(installStage = outcome.stage(), installMessage = outcome.message())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun download(apkUrl: String): File? =
|
||||
runCatching { installer.downloadApk(apkUrl) }
|
||||
.onFailure { e ->
|
||||
internal.update {
|
||||
it.copy(
|
||||
installStage = InstallStage.ERROR,
|
||||
installMessage = "Couldn't download update: ${ErrorCopy.fromThrowable(e)}",
|
||||
)
|
||||
}
|
||||
}
|
||||
.getOrNull()
|
||||
}
|
||||
+18
-71
@@ -1,20 +1,14 @@
|
||||
package com.fabledsword.minstrel.settings.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ElevatedCard
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
@@ -25,28 +19,14 @@ import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.fabledsword.minstrel.models.ListenBrainzStatus
|
||||
import com.fabledsword.minstrel.theme.Muted
|
||||
import com.fabledsword.minstrel.theme.Section
|
||||
import com.fabledsword.minstrel.theme.SwitchRow
|
||||
|
||||
@Composable
|
||||
fun ListenBrainzCard(viewModel: ListenBrainzViewModel = hiltViewModel()) {
|
||||
val state by viewModel.state.collectAsStateWithLifecycle()
|
||||
ElevatedCard(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Text(
|
||||
text = "ListenBrainz",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
Text(
|
||||
text = "Send your plays to ListenBrainz so you can keep your " +
|
||||
"scrobble history portable. Get a token at " +
|
||||
"listenbrainz.org/profile — it's stored encrypted on " +
|
||||
"the server and never read back.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Section("ListenBrainz") {
|
||||
if (state.isLoading) {
|
||||
Box(
|
||||
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
||||
@@ -65,7 +45,6 @@ fun ListenBrainzCard(viewModel: ListenBrainzViewModel = hiltViewModel()) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ListenBrainzForm(
|
||||
@@ -77,25 +56,25 @@ private fun ListenBrainzForm(
|
||||
onSaveToken: () -> Unit,
|
||||
onSetEnabled: (Boolean) -> Unit,
|
||||
) {
|
||||
TokenField(
|
||||
tokenInput = tokenInput,
|
||||
tokenSet = status?.tokenSet == true,
|
||||
onChange = onTokenChange,
|
||||
val tokenSet = status?.tokenSet == true
|
||||
SwitchRow(
|
||||
title = "Send my plays to ListenBrainz",
|
||||
summary = when {
|
||||
!tokenSet -> "Save a token first"
|
||||
status?.lastScrobbledAt != null -> "Last scrobble: ${status.lastScrobbledAt}"
|
||||
else -> null
|
||||
},
|
||||
checked = status?.enabled == true,
|
||||
onCheckedChange = onSetEnabled,
|
||||
enabled = !isSaving && tokenSet,
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
TokenField(tokenInput = tokenInput, tokenSet = tokenSet, onChange = onTokenChange)
|
||||
SaveTokenButton(
|
||||
isSaving = isSaving,
|
||||
enabled = !isSaving && tokenInput.isNotBlank(),
|
||||
onClick = onSaveToken,
|
||||
)
|
||||
EnabledRow(status = status, isSaving = isSaving, onSetEnabled = onSetEnabled)
|
||||
if (message != null) {
|
||||
Text(
|
||||
text = message,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
if (message != null) Muted(message)
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -105,6 +84,7 @@ private fun TokenField(tokenInput: String, tokenSet: Boolean, onChange: (String)
|
||||
onValueChange = onChange,
|
||||
label = { Text(if (tokenSet) "Replace token" else "Token") },
|
||||
placeholder = { Text(if (tokenSet) "Token saved" else "") },
|
||||
supportingText = { Text("From listenbrainz.org/profile; never shown again") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
visualTransformation = PasswordVisualTransformation(),
|
||||
@@ -129,36 +109,3 @@ private fun SaveTokenButton(isSaving: Boolean, enabled: Boolean, onClick: () ->
|
||||
Text(if (isSaving) "Saving…" else "Save token")
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EnabledRow(
|
||||
status: ListenBrainzStatus?,
|
||||
isSaving: Boolean,
|
||||
onSetEnabled: (Boolean) -> Unit,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
Column(modifier = Modifier.padding(end = 12.dp)) {
|
||||
Text(
|
||||
text = "Send my plays to ListenBrainz",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
if (status?.lastScrobbledAt != null) {
|
||||
Text(
|
||||
text = "Last scrobble: ${status.lastScrobbledAt}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
Switch(
|
||||
checked = status?.enabled == true,
|
||||
onCheckedChange = onSetEnabled,
|
||||
enabled = !isSaving && status?.tokenSet == true,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
+18
-92
@@ -1,30 +1,15 @@
|
||||
package com.fabledsword.minstrel.settings.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material3.ElevatedCard
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.SegmentedButton
|
||||
import androidx.compose.material3.SegmentedButtonDefaults
|
||||
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.fabledsword.minstrel.settings.data.NormalizationBoost
|
||||
import com.fabledsword.minstrel.settings.data.NormalizationMode
|
||||
import com.fabledsword.minstrel.settings.data.NormalizationPrefs
|
||||
import com.fabledsword.minstrel.theme.ChoiceRow
|
||||
import com.fabledsword.minstrel.theme.Section
|
||||
import com.fabledsword.minstrel.theme.SwitchRow
|
||||
|
||||
/**
|
||||
* Volume leveling. The choice is stored on the server, so the
|
||||
@@ -36,80 +21,29 @@ fun NormalizationCard(viewModel: NormalizationViewModel = hiltViewModel()) {
|
||||
NormalizationCardContent(prefs = prefs, onChange = viewModel::update)
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
internal fun NormalizationCardContent(
|
||||
prefs: NormalizationPrefs,
|
||||
onChange: (NormalizationPrefs) -> Unit,
|
||||
) {
|
||||
ElevatedCard(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Text(
|
||||
text = "Volume leveling",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
Section("Volume leveling") {
|
||||
ChoiceRow(
|
||||
title = "Leveling",
|
||||
summary = modeHint(prefs.mode),
|
||||
options = NormalizationMode.entries.map { it to modeLabel(it) },
|
||||
selected = prefs.mode,
|
||||
onSelect = { onChange(prefs.copy(mode = it)) },
|
||||
)
|
||||
Hint(modeHint(prefs.mode))
|
||||
val modes = NormalizationMode.entries
|
||||
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
|
||||
modes.forEachIndexed { index, mode ->
|
||||
SegmentedButton(
|
||||
selected = mode == prefs.mode,
|
||||
onClick = { onChange(prefs.copy(mode = mode)) },
|
||||
shape = SegmentedButtonDefaults.itemShape(
|
||||
index = index,
|
||||
count = modes.size,
|
||||
),
|
||||
) { Text(modeLabel(mode)) }
|
||||
}
|
||||
}
|
||||
if (prefs.mode != NormalizationMode.OFF) {
|
||||
TargetRow(prefs = prefs, onChange = onChange)
|
||||
BoostRow(prefs = prefs, onChange = onChange)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun TargetRow(prefs: NormalizationPrefs, onChange: (NormalizationPrefs) -> Unit) {
|
||||
Text(
|
||||
text = "Target loudness",
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
ChoiceRow(
|
||||
title = "Target loudness",
|
||||
options = NormalizationPrefs.TARGETS.map { it to "$it LUFS" },
|
||||
selected = prefs.targetLufs,
|
||||
onSelect = { onChange(prefs.copy(targetLufs = it)) },
|
||||
)
|
||||
val targets = NormalizationPrefs.TARGETS
|
||||
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
|
||||
targets.forEachIndexed { index, lufs ->
|
||||
SegmentedButton(
|
||||
selected = lufs == prefs.targetLufs,
|
||||
onClick = { onChange(prefs.copy(targetLufs = lufs)) },
|
||||
shape = SegmentedButtonDefaults.itemShape(
|
||||
index = index,
|
||||
count = targets.size,
|
||||
),
|
||||
) { Text("$lufs LUFS") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun BoostRow(prefs: NormalizationPrefs, onChange: (NormalizationPrefs) -> Unit) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = "Boost quiet tracks fully",
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
Hint("A limiter catches the peaks.")
|
||||
}
|
||||
Spacer(Modifier.size(12.dp))
|
||||
Switch(
|
||||
SwitchRow(
|
||||
title = "Boost quiet tracks fully",
|
||||
summary = "A limiter catches the peaks",
|
||||
checked = prefs.boost == NormalizationBoost.LIMITER,
|
||||
onCheckedChange = { on ->
|
||||
val boost = if (on) NormalizationBoost.LIMITER else NormalizationBoost.HEADROOM
|
||||
@@ -118,14 +52,6 @@ private fun BoostRow(prefs: NormalizationPrefs, onChange: (NormalizationPrefs) -
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Hint(text: String) {
|
||||
Text(
|
||||
text = text,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
|
||||
private fun modeLabel(mode: NormalizationMode): String = when (mode) {
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
package com.fabledsword.minstrel.settings.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
@@ -10,7 +8,6 @@ import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ElevatedCard
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
@@ -22,20 +19,13 @@ import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.fabledsword.minstrel.theme.Muted
|
||||
import com.fabledsword.minstrel.theme.Section
|
||||
|
||||
@Composable
|
||||
fun PasswordCard(viewModel: PasswordViewModel = hiltViewModel()) {
|
||||
val state by viewModel.state.collectAsStateWithLifecycle()
|
||||
ElevatedCard(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Text(
|
||||
text = "Password",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
Section("Password") {
|
||||
PasswordField(
|
||||
value = state.current,
|
||||
label = "Current password",
|
||||
@@ -67,14 +57,7 @@ fun PasswordCard(viewModel: PasswordViewModel = hiltViewModel()) {
|
||||
}
|
||||
Text(if (state.isChanging) "Changing…" else "Change password")
|
||||
}
|
||||
if (state.message != null) {
|
||||
Text(
|
||||
text = state.message!!,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
state.message?.let { Muted(it) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
package com.fabledsword.minstrel.settings.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
@@ -10,7 +8,6 @@ import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ElevatedCard
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
@@ -21,20 +18,13 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.fabledsword.minstrel.theme.Muted
|
||||
import com.fabledsword.minstrel.theme.Section
|
||||
|
||||
@Composable
|
||||
fun ProfileCard(viewModel: ProfileViewModel = hiltViewModel()) {
|
||||
val state by viewModel.state.collectAsStateWithLifecycle()
|
||||
ElevatedCard(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Text(
|
||||
text = "Profile",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
Section("Profile") {
|
||||
if (state.isLoading) {
|
||||
Box(
|
||||
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
||||
@@ -53,7 +43,6 @@ fun ProfileCard(viewModel: ProfileViewModel = hiltViewModel()) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ProfileForm(
|
||||
@@ -95,11 +84,5 @@ private fun ProfileForm(
|
||||
}
|
||||
Text(if (isSaving) "Saving…" else "Save profile")
|
||||
}
|
||||
if (message != null) {
|
||||
Text(
|
||||
text = message,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
if (message != null) Muted(message)
|
||||
}
|
||||
|
||||
@@ -1,34 +1,19 @@
|
||||
@file:Suppress("TooManyFunctions") // Settings screen + per-card helper composables
|
||||
@file:Suppress("TooManyFunctions") // Settings screen + per-section composables
|
||||
|
||||
package com.fabledsword.minstrel.settings.ui
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ElevatedCard
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SegmentedButton
|
||||
import androidx.compose.material3.SegmentedButtonDefaults
|
||||
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
@@ -37,32 +22,33 @@ import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.navigation.NavHostController
|
||||
import com.composables.icons.lucide.Bell
|
||||
import com.composables.icons.lucide.ChevronRight
|
||||
import com.composables.icons.lucide.ListMusic
|
||||
import com.composables.icons.lucide.LogOut
|
||||
import com.composables.icons.lucide.Lucide
|
||||
import com.composables.icons.lucide.Shield
|
||||
import com.fabledsword.minstrel.BuildConfig
|
||||
import com.fabledsword.minstrel.nav.Admin
|
||||
import com.fabledsword.minstrel.nav.NotificationSettings
|
||||
import com.fabledsword.minstrel.nav.Requests
|
||||
import com.fabledsword.minstrel.nav.Settings as SettingsRoute
|
||||
import com.fabledsword.minstrel.nav.ServerUrl
|
||||
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
|
||||
import com.fabledsword.minstrel.nav.Settings as SettingsRoute
|
||||
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
|
||||
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
|
||||
import com.fabledsword.minstrel.theme.ChoiceRow
|
||||
import com.fabledsword.minstrel.theme.RowChevron
|
||||
import com.fabledsword.minstrel.theme.RowSpinner
|
||||
import com.fabledsword.minstrel.theme.Section
|
||||
import com.fabledsword.minstrel.theme.SectionEdge
|
||||
import com.fabledsword.minstrel.theme.SectionGap
|
||||
import com.fabledsword.minstrel.theme.SettingRow
|
||||
import com.fabledsword.minstrel.theme.SwitchRow
|
||||
import com.fabledsword.minstrel.theme.ThemeMode
|
||||
import com.fabledsword.minstrel.theme.ThemePreferenceViewModel
|
||||
import com.fabledsword.minstrel.update.data.InstallStage
|
||||
import com.fabledsword.minstrel.update.data.isBusy
|
||||
import com.fabledsword.minstrel.update.ui.AppVersionCard
|
||||
import com.fabledsword.minstrel.update.ui.CheckWhileShown
|
||||
import com.fabledsword.minstrel.update.ui.UpdateViewModel
|
||||
|
||||
@Composable
|
||||
fun SettingsScreen(
|
||||
@@ -99,7 +85,6 @@ fun SettingsScreen(
|
||||
state = state,
|
||||
themeMode = themeMode,
|
||||
onPickTheme = themeVm::setThemeMode,
|
||||
onNavToRequests = { navController.navigate(Requests) },
|
||||
onNavToNotifications = { navController.navigate(NotificationSettings) },
|
||||
onNavToAdmin = { navController.navigate(Admin) },
|
||||
onToggleDiagnostics = viewModel::setDiagnosticsOptOut,
|
||||
@@ -119,11 +104,10 @@ fun SettingsScreen(
|
||||
|
||||
@Composable
|
||||
private fun SettingsList(
|
||||
inner: androidx.compose.foundation.layout.PaddingValues,
|
||||
inner: PaddingValues,
|
||||
state: SettingsState,
|
||||
themeMode: ThemeMode,
|
||||
onPickTheme: (ThemeMode) -> Unit,
|
||||
onNavToRequests: () -> Unit,
|
||||
onNavToNotifications: () -> Unit,
|
||||
onNavToAdmin: () -> Unit,
|
||||
onToggleDiagnostics: (Boolean) -> Unit,
|
||||
@@ -134,48 +118,25 @@ private fun SettingsList(
|
||||
.fillMaxSize()
|
||||
.padding(inner)
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
.padding(horizontal = SectionEdge, vertical = SectionEdge),
|
||||
verticalArrangement = Arrangement.spacedBy(SectionGap),
|
||||
) {
|
||||
AccountCard(
|
||||
username = state.username,
|
||||
isAdmin = state.isAdmin,
|
||||
serverUrl = state.serverUrl,
|
||||
AccountSection(
|
||||
state = state,
|
||||
onNavToNotifications = onNavToNotifications,
|
||||
onNavToAdmin = onNavToAdmin,
|
||||
onSignOutClick = onSignOutClick,
|
||||
)
|
||||
NavTile(
|
||||
icon = Lucide.ListMusic,
|
||||
title = "My requests",
|
||||
subtitle = "Track what you've asked Minstrel to add",
|
||||
onClick = onNavToRequests,
|
||||
)
|
||||
NavTile(
|
||||
icon = Lucide.Bell,
|
||||
title = "Notifications",
|
||||
subtitle = "What reaches you, and where",
|
||||
onClick = onNavToNotifications,
|
||||
)
|
||||
if (state.isAdmin) {
|
||||
NavTile(
|
||||
icon = Lucide.Shield,
|
||||
title = "Admin",
|
||||
subtitle = "Manage requests, quarantine, and users",
|
||||
onClick = onNavToAdmin,
|
||||
)
|
||||
}
|
||||
ProfileCard()
|
||||
PasswordCard()
|
||||
ListenBrainzCard()
|
||||
if (state.diagnosticsEnabledByAdmin) {
|
||||
DiagnosticsCard(
|
||||
optOut = state.diagnosticsOptOut,
|
||||
onToggle = onToggleDiagnostics,
|
||||
)
|
||||
DiagnosticsSection(optOut = state.diagnosticsOptOut, onToggle = onToggleDiagnostics)
|
||||
}
|
||||
NormalizationCard()
|
||||
AppearanceCard(themeMode = themeMode, onPick = onPickTheme)
|
||||
AppearanceSection(themeMode = themeMode, onPick = onPickTheme)
|
||||
StorageCard()
|
||||
AboutCard()
|
||||
SignOutButton(isSigningOut = state.isSigningOut, onSignOut = onSignOutClick)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,84 +166,41 @@ private fun SignOutConfirmDialog(onConfirm: () -> Unit, onDismiss: () -> Unit) {
|
||||
)
|
||||
}
|
||||
|
||||
/** Who is signed in, where, the screens that belong to the account, and signing out. */
|
||||
@Composable
|
||||
private fun NavTile(
|
||||
icon: ImageVector,
|
||||
title: String,
|
||||
subtitle: String,
|
||||
onClick: () -> Unit,
|
||||
private fun AccountSection(
|
||||
state: SettingsState,
|
||||
onNavToNotifications: () -> Unit,
|
||||
onNavToAdmin: () -> Unit,
|
||||
onSignOutClick: () -> Unit,
|
||||
) {
|
||||
ElevatedCard(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable(onClick = onClick),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
Spacer(Modifier.size(16.dp))
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = title,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
Text(
|
||||
text = subtitle,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
Icon(
|
||||
imageVector = Lucide.ChevronRight,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AccountCard(username: String, isAdmin: Boolean, serverUrl: String) {
|
||||
ElevatedCard(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
Text(
|
||||
text = "Account",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
val adminTag = if (isAdmin) " · admin" else ""
|
||||
Text(
|
||||
text = when {
|
||||
username.isEmpty() -> "Signed in"
|
||||
else -> "Signed in as $username$adminTag"
|
||||
},
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
text = "Server",
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
Text(
|
||||
text = serverUrl,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
Section("Account") {
|
||||
SettingRow(
|
||||
title = state.username.ifEmpty { "Signed in" },
|
||||
summary = if (state.isAdmin) "Signed in · admin" else "Signed in",
|
||||
)
|
||||
SettingRow(title = "Server", summary = state.serverUrl)
|
||||
SettingRow(
|
||||
title = "Notifications",
|
||||
summary = "What reaches you, and where",
|
||||
icon = Lucide.Bell,
|
||||
onClick = onNavToNotifications,
|
||||
) { RowChevron() }
|
||||
if (state.isAdmin) {
|
||||
SettingRow(
|
||||
title = "Admin",
|
||||
summary = "Library health, users and metadata",
|
||||
icon = Lucide.Shield,
|
||||
onClick = onNavToAdmin,
|
||||
) { RowChevron() }
|
||||
}
|
||||
SettingRow(
|
||||
title = if (state.isSigningOut) "Signing out…" else "Sign out",
|
||||
icon = Lucide.LogOut,
|
||||
tone = MaterialTheme.colorScheme.error,
|
||||
enabled = !state.isSigningOut,
|
||||
onClick = onSignOutClick,
|
||||
) { if (state.isSigningOut) RowSpinner() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -290,74 +208,27 @@ private fun AccountCard(username: String, isAdmin: Boolean, serverUrl: String) {
|
||||
// the user turn reporting OFF on this device (battery/privacy) without
|
||||
// touching the account flag. Checked = reporting on = NOT opted out.
|
||||
@Composable
|
||||
private fun DiagnosticsCard(optOut: Boolean, onToggle: (Boolean) -> Unit) {
|
||||
ElevatedCard(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Text(
|
||||
text = "Diagnostics",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = "Send diagnostic reports",
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
Text(
|
||||
text = "Your admin enabled debug mode to investigate an " +
|
||||
"issue. This device streams connectivity and playback " +
|
||||
"diagnostics. Turn off any time.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.size(12.dp))
|
||||
Switch(
|
||||
private fun DiagnosticsSection(optOut: Boolean, onToggle: (Boolean) -> Unit) {
|
||||
Section("Diagnostics") {
|
||||
SwitchRow(
|
||||
title = "Send diagnostic reports",
|
||||
summary = "Your admin turned on debug mode",
|
||||
checked = !optOut,
|
||||
onCheckedChange = { checked -> onToggle(!checked) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun AppearanceCard(themeMode: ThemeMode, onPick: (ThemeMode) -> Unit) {
|
||||
val options = ThemeMode.entries
|
||||
ElevatedCard(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Text(
|
||||
text = "Appearance",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
private fun AppearanceSection(themeMode: ThemeMode, onPick: (ThemeMode) -> Unit) {
|
||||
Section("Appearance") {
|
||||
ChoiceRow(
|
||||
title = "Theme",
|
||||
summary = if (themeMode == ThemeMode.SYSTEM) "Follows your device" else null,
|
||||
options = ThemeMode.entries.map { it to displayName(it) },
|
||||
selected = themeMode,
|
||||
onSelect = onPick,
|
||||
)
|
||||
Text(
|
||||
text = "System follows your device setting.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
|
||||
options.forEachIndexed { index, mode ->
|
||||
SegmentedButton(
|
||||
selected = mode == themeMode,
|
||||
onClick = { onPick(mode) },
|
||||
shape = SegmentedButtonDefaults.itemShape(
|
||||
index = index,
|
||||
count = options.size,
|
||||
),
|
||||
) { Text(displayName(mode)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -367,136 +238,12 @@ private fun displayName(mode: ThemeMode): String = when (mode) {
|
||||
ThemeMode.DARK -> "Dark"
|
||||
}
|
||||
|
||||
/**
|
||||
* The About card is the app-version card Home's update sheet holds too; on
|
||||
* Settings it also asks the server again while the screen is up.
|
||||
*/
|
||||
@Composable
|
||||
private fun AboutCard(viewModel: AboutCardViewModel = hiltViewModel()) {
|
||||
val state by viewModel.state.collectAsStateWithLifecycle()
|
||||
ElevatedCard(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Text(
|
||||
text = "About",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
Text(
|
||||
text = "Installed: Minstrel ${state.installedVersion} " +
|
||||
"(${BuildConfig.VERSION_CODE})",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
UpdateControls(state = state, viewModel = viewModel)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun UpdateControls(state: AboutUiState, viewModel: AboutCardViewModel) {
|
||||
if (!state.selfUpdates) {
|
||||
Text(
|
||||
text = "Debug build: updates install from Android Studio.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
return
|
||||
}
|
||||
UpdateCheckLine(result = state.result)
|
||||
Button(
|
||||
onClick = viewModel::checkForUpdates,
|
||||
enabled = !state.isChecking && !state.installStage.isBusy(),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
if (state.isChecking) {
|
||||
ButtonSpinner()
|
||||
}
|
||||
Text(if (state.isChecking) "Checking…" else "Check for updates")
|
||||
}
|
||||
val available = state.result as? UpdateCheckResult.UpdateAvailable
|
||||
if (available != null) {
|
||||
InstallButton(
|
||||
version = available.info.version,
|
||||
stage = state.installStage,
|
||||
onClick = { viewModel.install(available.info) },
|
||||
)
|
||||
}
|
||||
if (state.installMessage != null) {
|
||||
Text(
|
||||
text = state.installMessage,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun InstallButton(version: String, stage: InstallStage, onClick: () -> Unit) {
|
||||
Button(
|
||||
onClick = onClick,
|
||||
enabled = !stage.isBusy(),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
if (stage.isBusy()) {
|
||||
ButtonSpinner()
|
||||
}
|
||||
Text(
|
||||
when (stage) {
|
||||
InstallStage.DOWNLOADING -> "Downloading…"
|
||||
InstallStage.INSTALLING -> "Installing…"
|
||||
else -> "Install $version"
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ButtonSpinner() {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(16.dp),
|
||||
strokeWidth = 2.dp,
|
||||
color = MaterialTheme.colorScheme.onPrimary,
|
||||
)
|
||||
Spacer(Modifier.size(8.dp))
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun UpdateCheckLine(result: UpdateCheckResult) {
|
||||
val text = when (result) {
|
||||
UpdateCheckResult.Idle -> return
|
||||
UpdateCheckResult.Latest -> "You're on the latest version."
|
||||
is UpdateCheckResult.UpdateAvailable ->
|
||||
"Update available: ${result.info.version}"
|
||||
is UpdateCheckResult.Error -> "Couldn't check: ${result.message}"
|
||||
}
|
||||
Text(
|
||||
text = text,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SignOutButton(isSigningOut: Boolean, onSignOut: () -> Unit) {
|
||||
Button(
|
||||
onClick = onSignOut,
|
||||
enabled = !isSigningOut,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
containerColor = MaterialTheme.colorScheme.errorContainer,
|
||||
contentColor = MaterialTheme.colorScheme.onErrorContainer,
|
||||
),
|
||||
) {
|
||||
if (isSigningOut) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(20.dp),
|
||||
color = MaterialTheme.colorScheme.onErrorContainer,
|
||||
strokeWidth = 2.dp,
|
||||
)
|
||||
} else {
|
||||
Box(modifier = Modifier.padding(end = 4.dp)) {
|
||||
Icon(Lucide.LogOut, contentDescription = null)
|
||||
}
|
||||
Text("Sign out")
|
||||
}
|
||||
}
|
||||
private fun AboutCard(model: UpdateViewModel = hiltViewModel()) {
|
||||
CheckWhileShown(model)
|
||||
AppVersionCard(model)
|
||||
}
|
||||
|
||||
@@ -1,21 +1,9 @@
|
||||
package com.fabledsword.minstrel.settings.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ElevatedCard
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
@@ -23,11 +11,13 @@ import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.fabledsword.minstrel.theme.ChoiceRow
|
||||
import com.fabledsword.minstrel.theme.RowSpinner
|
||||
import com.fabledsword.minstrel.theme.Section
|
||||
import com.fabledsword.minstrel.theme.SettingRow
|
||||
import com.fabledsword.minstrel.theme.SwitchRow
|
||||
|
||||
private const val GIB: Long = 1024L * 1024 * 1024
|
||||
private const val MIB: Long = 1024L * 1024
|
||||
@@ -45,39 +35,39 @@ private val CAP_OPTIONS: List<Pair<Long, String>> = listOf(
|
||||
fun StorageCard(viewModel: StorageViewModel = hiltViewModel()) {
|
||||
val state by viewModel.state.collectAsStateWithLifecycle()
|
||||
var showClearConfirm by remember { mutableStateOf(false) }
|
||||
ElevatedCard(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Text(
|
||||
text = "Storage",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
Section("Storage") {
|
||||
// Two budgets: a liked track that is also recently played counts
|
||||
// against Liked songs only. The prefetch window has no control;
|
||||
// AudioPrefetcher uses the stored value (default 5).
|
||||
CapRow(
|
||||
title = "Liked songs",
|
||||
used = state.likedBytes,
|
||||
value = state.settings.likedCapBytes,
|
||||
onSet = viewModel::setLikedCapBytes,
|
||||
)
|
||||
UsageRow(usedBytes = state.usedBytes)
|
||||
// Only the rolling cap is shown. Nothing enforces a separate
|
||||
// liked cap or pins liked tracks yet, and a control that silently
|
||||
// does nothing is worse than none. The prefetch window has no
|
||||
// control either; AudioPrefetcher uses the stored value (default
|
||||
// 5). CacheSettings keeps every field so the controls can return.
|
||||
CapDropdown(
|
||||
label = "Cache limit",
|
||||
CapRow(
|
||||
title = "Recently played",
|
||||
used = state.recentBytes,
|
||||
value = state.settings.rollingCapBytes,
|
||||
onSet = viewModel::setRollingCapBytes,
|
||||
)
|
||||
Text(
|
||||
text = "Takes effect on the next app launch.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
SwitchRow(
|
||||
title = "Keep liked songs offline",
|
||||
summary = "Downloads on Wi-Fi",
|
||||
checked = state.settings.cacheLikedTracks,
|
||||
onCheckedChange = viewModel::setCacheLikedTracks,
|
||||
)
|
||||
StorageActions(
|
||||
isSyncing = state.isSyncing,
|
||||
isClearing = state.isClearing,
|
||||
onSync = viewModel::syncNow,
|
||||
onClear = { showClearConfirm = true },
|
||||
)
|
||||
}
|
||||
SettingRow(
|
||||
title = if (state.isSyncing) "Syncing…" else "Sync library now",
|
||||
enabled = !state.isSyncing,
|
||||
onClick = viewModel::syncNow,
|
||||
) { if (state.isSyncing) RowSpinner() }
|
||||
SettingRow(
|
||||
title = if (state.isClearing) "Clearing…" else "Clear cached audio",
|
||||
tone = MaterialTheme.colorScheme.error,
|
||||
enabled = !state.isClearing,
|
||||
onClick = { showClearConfirm = true },
|
||||
) { if (state.isClearing) RowSpinner() }
|
||||
}
|
||||
if (showClearConfirm) {
|
||||
ClearCacheConfirmDialog(
|
||||
@@ -90,117 +80,19 @@ fun StorageCard(viewModel: StorageViewModel = hiltViewModel()) {
|
||||
}
|
||||
}
|
||||
|
||||
/** A storage budget: how much it holds now, and the cap it may grow to. */
|
||||
@Composable
|
||||
private fun UsageRow(usedBytes: Long) {
|
||||
Row(modifier = Modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
text = "Used",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
text = formatBytes(usedBytes),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CapDropdown(label: String, value: Long, onSet: (Long) -> Unit) {
|
||||
val selectedLabel = CAP_OPTIONS.firstOrNull { it.first == value }?.second
|
||||
?: formatBytes(value)
|
||||
LabeledDropdown(
|
||||
label = label,
|
||||
selectedLabel = selectedLabel,
|
||||
private fun CapRow(title: String, used: Long, value: Long, onSet: (Long) -> Unit) {
|
||||
ChoiceRow(
|
||||
title = title,
|
||||
summary = "${formatBytes(used)} used",
|
||||
options = CAP_OPTIONS,
|
||||
selected = value,
|
||||
onSelect = onSet,
|
||||
selectedLabel = CAP_OPTIONS.firstOrNull { it.first == value }?.second ?: formatBytes(value),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Label on the left, button-with-current-value on the right that opens
|
||||
* a DropdownMenu of [options]. Used by the cap selectors.
|
||||
*/
|
||||
@Composable
|
||||
private fun <T> LabeledDropdown(
|
||||
label: String,
|
||||
selectedLabel: String,
|
||||
options: List<Pair<T, String>>,
|
||||
onSelect: (T) -> Unit,
|
||||
) {
|
||||
var expanded by remember { mutableStateOf(false) }
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
text = label,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
OutlinedButton(onClick = { expanded = true }) {
|
||||
Text(selectedLabel)
|
||||
DropdownMenu(
|
||||
expanded = expanded,
|
||||
onDismissRequest = { expanded = false },
|
||||
) {
|
||||
options.forEach { (value, name) ->
|
||||
DropdownMenuItem(
|
||||
text = { Text(name) },
|
||||
onClick = {
|
||||
expanded = false
|
||||
onSelect(value)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StorageActions(
|
||||
isSyncing: Boolean,
|
||||
isClearing: Boolean,
|
||||
onSync: () -> Unit,
|
||||
onClear: () -> Unit,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
OutlinedButton(
|
||||
onClick = onClear,
|
||||
enabled = !isClearing,
|
||||
) {
|
||||
if (isClearing) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(16.dp),
|
||||
strokeWidth = 2.dp,
|
||||
)
|
||||
Spacer(Modifier.size(8.dp))
|
||||
}
|
||||
Text(if (isClearing) "Clearing…" else "Clear cache")
|
||||
}
|
||||
OutlinedButton(
|
||||
onClick = onSync,
|
||||
enabled = !isSyncing,
|
||||
) {
|
||||
if (isSyncing) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(16.dp),
|
||||
strokeWidth = 2.dp,
|
||||
)
|
||||
Spacer(Modifier.size(8.dp))
|
||||
}
|
||||
Text(if (isSyncing) "Syncing…" else "Sync now")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ClearCacheConfirmDialog(onConfirm: () -> Unit, onDismiss: () -> Unit) {
|
||||
AlertDialog(
|
||||
@@ -227,7 +119,7 @@ private fun ClearCacheConfirmDialog(onConfirm: () -> Unit, onDismiss: () -> Unit
|
||||
)
|
||||
}
|
||||
|
||||
private fun formatBytes(n: Long): String {
|
||||
internal fun formatBytes(n: Long): String {
|
||||
if (n <= 0L) return "0 B"
|
||||
return when {
|
||||
n < KIB -> "$n B"
|
||||
|
||||
+13
-13
@@ -4,6 +4,7 @@ import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.fabledsword.minstrel.auth.AuthStore
|
||||
import com.fabledsword.minstrel.cache.audiocache.CacheSettings
|
||||
import com.fabledsword.minstrel.cache.audiocache.TwoBucketCacheEvictor
|
||||
import com.fabledsword.minstrel.cache.sync.SyncController
|
||||
import com.fabledsword.minstrel.player.PlayerFactory
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
@@ -18,25 +19,25 @@ import javax.inject.Inject
|
||||
|
||||
data class StorageUiState(
|
||||
val settings: CacheSettings = CacheSettings.DEFAULT,
|
||||
val usedBytes: Long = 0L,
|
||||
val likedBytes: Long = 0L,
|
||||
val recentBytes: Long = 0L,
|
||||
val isSyncing: Boolean = false,
|
||||
val isClearing: Boolean = false,
|
||||
)
|
||||
|
||||
/**
|
||||
* Backs the Storage section of the Settings screen. Exposes the
|
||||
* persisted CacheSettings + the current SimpleCache usage, plus
|
||||
* actions for "Sync now" and "Clear cache".
|
||||
* persisted CacheSettings and how much of each audio budget (Liked
|
||||
* songs, Recently played) is in use, plus "Sync now" and "Clear cache".
|
||||
*
|
||||
* Settings changes go through AuthStore.setCacheSettings (write-
|
||||
* through to Room). The cap settings only take effect on next app
|
||||
* launch because SimpleCache is constructed once per process; the
|
||||
* UI surfaces that caveat (next commit).
|
||||
* through to Room), and the evictor applies a new cap at once.
|
||||
*/
|
||||
@HiltViewModel
|
||||
class StorageViewModel @Inject constructor(
|
||||
private val authStore: AuthStore,
|
||||
private val playerFactory: PlayerFactory,
|
||||
private val cacheEvictor: TwoBucketCacheEvictor,
|
||||
private val syncController: SyncController,
|
||||
) : ViewModel() {
|
||||
|
||||
@@ -47,10 +48,11 @@ class StorageViewModel @Inject constructor(
|
||||
viewModelScope.launch {
|
||||
authStore.cacheSettings.collect { s ->
|
||||
internal.update { it.copy(settings = s) }
|
||||
}
|
||||
}
|
||||
// A smaller cap trims the cache, so re-read the usage.
|
||||
refreshUsage()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun setLikedCapBytes(bytes: Long) {
|
||||
val current = authStore.cacheSettings.value
|
||||
@@ -108,13 +110,11 @@ class StorageViewModel @Inject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
/** Recomputes used bytes from SimpleCache. Cheap; just reads a long. */
|
||||
/** Re-reads each budget's usage from the evictor. Cheap: two longs. */
|
||||
private fun refreshUsage() {
|
||||
viewModelScope.launch {
|
||||
val used = withContext(Dispatchers.IO) {
|
||||
runCatching { playerFactory.simpleCache.cacheSpace }.getOrDefault(0L)
|
||||
}
|
||||
internal.update { it.copy(usedBytes = used) }
|
||||
val usage = withContext(Dispatchers.IO) { cacheEvictor.usage() }
|
||||
internal.update { it.copy(likedBytes = usage.likedBytes, recentBytes = usage.recentBytes) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user