Compare commits
6
Commits
dev
..
7e4727fc49
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e4727fc49 | ||
|
|
1b7fa635d8 | ||
|
|
57d2299180 | ||
|
|
fa7ea41ccf | ||
|
|
324059b2bd | ||
|
|
1138d75a45 |
+6
-11
@@ -6,16 +6,10 @@
|
|||||||
**/build
|
**/build
|
||||||
web/build
|
web/build
|
||||||
|
|
||||||
# The Android client — built by its own job, never from this context. The APK
|
# Flutter mobile client — built separately on developer machines / Flutter CI.
|
||||||
# reaches the image through client/, downloaded as a CI artifact, so nothing
|
# Including it in the Go build context wastes ~70 files and invalidates the
|
||||||
# here reads android/ sources.
|
# `COPY . .` layer cache on every Flutter-only change.
|
||||||
# Excluded so the Gradle project neither bloats the context nor busts the
|
flutter_client/
|
||||||
# `COPY . .` layer on every Android-only change.
|
|
||||||
android/
|
|
||||||
|
|
||||||
# Local `make build` output — an 18 MB binary the image never uses, since the
|
|
||||||
# builder stage compiles its own.
|
|
||||||
bin/
|
|
||||||
|
|
||||||
# Docs and IDE noise
|
# Docs and IDE noise
|
||||||
docs/
|
docs/
|
||||||
@@ -33,4 +27,5 @@ docs/
|
|||||||
!.env.example
|
!.env.example
|
||||||
|
|
||||||
# CI workflow files don't need to ship in the image.
|
# CI workflow files don't need to ship in the image.
|
||||||
.gitea/
|
.forgejo/
|
||||||
|
.github/
|
||||||
|
|||||||
+10
-9
@@ -1,11 +1,12 @@
|
|||||||
# Environment for running the server outside Docker (`go run ./cmd/minstrel`).
|
# Minstrel environment variable overrides.
|
||||||
# The values match the Postgres in docker-compose.yml.
|
# Copy to .env for docker compose, or export before `go run ./cmd/minstrel`.
|
||||||
|
# Values shown are sensible defaults for the local docker-compose postgres.
|
||||||
|
|
||||||
MINSTREL_SERVER_ADDRESS=:4533
|
SMARTMUSIC_SERVER_ADDRESS=:4533
|
||||||
MINSTREL_DATABASE_URL=postgres://minstrel:minstrel@localhost:5432/minstrel?sslmode=disable
|
SMARTMUSIC_DATABASE_URL=postgres://minstrel:minstrel@localhost:5432/minstrel?sslmode=disable
|
||||||
MINSTREL_LOG_LEVEL=info
|
SMARTMUSIC_LOG_LEVEL=info
|
||||||
MINSTREL_LOG_FORMAT=text
|
SMARTMUSIC_LOG_FORMAT=text
|
||||||
|
|
||||||
# Runs the database tests in `go test ./...` (without -short). Use a separate
|
# Set this when running `go test ./...` without -short to exercise the
|
||||||
# database: the tests truncate every table.
|
# migration test against a running postgres.
|
||||||
# MINSTREL_TEST_DATABASE_URL=postgres://minstrel:minstrel@localhost:5432/minstrel_test?sslmode=disable
|
# MINSTREL_TEST_DATABASE_URL=postgres://minstrel:minstrel@localhost:5432/minstrel?sslmode=disable
|
||||||
|
|||||||
@@ -1,9 +0,0 @@
|
|||||||
# Files only the build pipeline uses stay out of `git archive`, which makes
|
|
||||||
# the public source release. The two release tests pin the workflow file, so
|
|
||||||
# they leave with it; without it they would fail `go test ./...`.
|
|
||||||
.gitea/ export-ignore
|
|
||||||
ci/ export-ignore
|
|
||||||
ci-requirements.md export-ignore
|
|
||||||
renovate.json export-ignore
|
|
||||||
internal/server/release_gate_test.go export-ignore
|
|
||||||
internal/server/release_version_test.go export-ignore
|
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
name: android
|
||||||
|
|
||||||
|
# Native Android (Kotlin/Compose/Media3) — M8 rewrite, now the only client.
|
||||||
|
# This workflow is testing only — lint + detekt + unit tests on every push
|
||||||
|
# to dev/main, plus a debug APK artifact for main. The signed-release
|
||||||
|
# build + asset attach + image-bundling lives in release.yml under a
|
||||||
|
# `needs:` chain so the docker image cannot ship without the APK.
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main, dev]
|
||||||
|
paths:
|
||||||
|
- 'android/**'
|
||||||
|
- '.gitea/workflows/android.yml'
|
||||||
|
|
||||||
|
# pull_request trigger intentionally omitted — see test-web.yml for
|
||||||
|
# the rationale (single-author repo, push covers PR-merge equivalent).
|
||||||
|
concurrency:
|
||||||
|
group: ${{ github.workflow }}-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
env:
|
||||||
|
# Silences the JDK 22+ "restricted method in java.lang.System has been
|
||||||
|
# called" warning that Gradle 9.1's bundled native-platform jar trips
|
||||||
|
# at launch (System.load for native primitives). Affects the LAUNCHER
|
||||||
|
# JVM, not the daemon — that's why org.gradle.jvmargs in
|
||||||
|
# gradle.properties isn't enough. Future-compat: required opt-in once
|
||||||
|
# JDK 25 promotes the warning to an error.
|
||||||
|
JAVA_TOOL_OPTIONS: "--enable-native-access=ALL-UNNAMED"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
name: Build + lint + test
|
||||||
|
# Using flutter-ci runner label because it's the only proven-working
|
||||||
|
# label with docker that can pull our container.image. Switch to
|
||||||
|
# android-ci once the operator registers that runner label.
|
||||||
|
runs-on: flutter-ci
|
||||||
|
container:
|
||||||
|
image: git.fabledsword.com/bvandeusen/ci-android:36
|
||||||
|
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: android
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Cache Gradle dirs
|
||||||
|
# Resolved deps + Gradle distribution + Kotlin daemon caches.
|
||||||
|
# Saves ~3 min per CI run after the first warm-up.
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
~/.gradle/caches
|
||||||
|
~/.gradle/wrapper
|
||||||
|
~/.kotlin
|
||||||
|
key: gradle-${{ runner.os }}-${{ hashFiles('android/gradle/wrapper/gradle-wrapper.properties', 'android/gradle/libs.versions.toml', 'android/**/*.gradle.kts') }}
|
||||||
|
restore-keys: |
|
||||||
|
gradle-${{ runner.os }}-
|
||||||
|
|
||||||
|
- name: Make gradlew executable
|
||||||
|
run: chmod +x ./gradlew
|
||||||
|
|
||||||
|
- name: Gradle wrapper validation
|
||||||
|
run: ./gradlew --version
|
||||||
|
|
||||||
|
- name: ktlint
|
||||||
|
run: ./gradlew ktlintCheck
|
||||||
|
|
||||||
|
- name: detekt
|
||||||
|
run: ./gradlew detekt
|
||||||
|
|
||||||
|
- name: Unit tests
|
||||||
|
run: ./gradlew testDebugUnitTest
|
||||||
|
|
||||||
|
- name: Assemble debug
|
||||||
|
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||||
|
run: ./gradlew assembleDebug
|
||||||
|
|
||||||
|
- name: Upload debug APK
|
||||||
|
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||||
|
# Mirrored action, never actions/upload-artifact. @v4+ throws
|
||||||
|
# GHESNotSupportedError client-side on the hostname (no server setting
|
||||||
|
# reaches that check), and @v3 is worse — it reports success while Gitea
|
||||||
|
# serves artifacts back only through the v4 API, so the upload is stored
|
||||||
|
# and invisible to every retrieval path. @v3 is what left 72 unreachable
|
||||||
|
# artifacts on this repo. Pinned by SHA because the mirror auto-syncs;
|
||||||
|
# full URL because DEFAULT_ACTIONS_URL sends bare owner/repo to github.com.
|
||||||
|
# See Scribe issues 2255 / 2270.
|
||||||
|
uses: https://git.fabledsword.com/bvandeusen/upload-artifact@cb8afe72b42edc798abfb8fcb556cf660d894245
|
||||||
|
with:
|
||||||
|
name: minstrel-android-debug-${{ github.sha }}
|
||||||
|
path: android/app/build/outputs/apk/debug/app-debug.apk
|
||||||
|
if-no-files-found: error
|
||||||
+124
-911
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,150 @@
|
|||||||
|
name: test-go
|
||||||
|
|
||||||
|
# Go server: vet + golangci-lint + short race tests. Runs on push to
|
||||||
|
# dev/main and PRs to main, scoped to Go-side files only — web-only or
|
||||||
|
# Flutter-only diffs don't trigger this workflow.
|
||||||
|
#
|
||||||
|
# Two jobs: `test` (fast — vet + lint + `go test -short -race`, no DB) and
|
||||||
|
# `integration` (full `go test -race` against an ephemeral Postgres).
|
||||||
|
#
|
||||||
|
# Integration-job 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 service container by the job-scoped
|
||||||
|
# name filter via 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).
|
||||||
|
#
|
||||||
|
# `web/build/` has a committed placeholder index.html so go:embed succeeds
|
||||||
|
# without needing the SPA to be freshly built. Real builds happen in
|
||||||
|
# release.yml (container) and locally during dev.
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [dev, main]
|
||||||
|
paths:
|
||||||
|
- '**/*.go'
|
||||||
|
- 'go.mod'
|
||||||
|
- 'go.sum'
|
||||||
|
- 'sqlc.yaml'
|
||||||
|
- 'Makefile'
|
||||||
|
- 'internal/**'
|
||||||
|
- 'cmd/**'
|
||||||
|
- '.golangci.yml'
|
||||||
|
- '.gitea/workflows/test-go.yml'
|
||||||
|
|
||||||
|
# pull_request trigger intentionally omitted — see test-web.yml for
|
||||||
|
# the rationale (single-author repo, push covers PR-merge equivalent).
|
||||||
|
concurrency:
|
||||||
|
group: ${{ github.workflow }}-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
runs-on: go-ci
|
||||||
|
container:
|
||||||
|
image: git.fabledsword.com/bvandeusen/ci-go:1.26
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Toolchain versions
|
||||||
|
run: |
|
||||||
|
go version
|
||||||
|
golangci-lint --version
|
||||||
|
|
||||||
|
- name: Generated code matches queries (sqlc)
|
||||||
|
run: make verify-generate
|
||||||
|
|
||||||
|
- name: go vet
|
||||||
|
run: go vet ./...
|
||||||
|
|
||||||
|
- name: golangci-lint
|
||||||
|
run: golangci-lint run ./...
|
||||||
|
|
||||||
|
- name: go test (short, race)
|
||||||
|
run: go test -short -race ./...
|
||||||
|
|
||||||
|
integration:
|
||||||
|
runs-on: go-ci
|
||||||
|
container:
|
||||||
|
image: git.fabledsword.com/bvandeusen/ci-go:1.26
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:16-alpine
|
||||||
|
env:
|
||||||
|
POSTGRES_USER: minstrel
|
||||||
|
POSTGRES_PASSWORD: minstrel
|
||||||
|
POSTGRES_DB: minstrel_test
|
||||||
|
# No `ports:` — the runner shares the operator's dev compose
|
||||||
|
# Docker daemon; publishing a fixed host port collides.
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Integration suite (discover service by bridge IP, migrate, test)
|
||||||
|
run: |
|
||||||
|
set -eux
|
||||||
|
# Discover THIS job's Postgres service container via the
|
||||||
|
# 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).
|
||||||
|
SELF=$(cat /etc/hostname)
|
||||||
|
SELF_NETS=$(docker inspect -f '{{range $k,$v := .NetworkSettings.Networks}}{{$k}} {{end}}' "$SELF")
|
||||||
|
test -n "$SELF_NETS"
|
||||||
|
echo "self ($SELF) networks: $SELF_NETS"
|
||||||
|
PG_ID=""
|
||||||
|
PG_NAME=""
|
||||||
|
for cid in $(docker ps --filter "ancestor=postgres:16-alpine" -q); do
|
||||||
|
nm=$(docker inspect -f '{{.Name}}' "$cid" | sed 's#^/##')
|
||||||
|
case "$nm" in *minstrel-postgres*|*_postgres_*) continue ;; esac
|
||||||
|
for net in $(docker inspect -f '{{range $k,$v := .NetworkSettings.Networks}}{{$k}} {{end}}' "$cid"); do
|
||||||
|
case " $SELF_NETS " in *" $net "*) PG_ID="$cid"; PG_NAME="$nm"; break 2 ;; esac
|
||||||
|
done
|
||||||
|
done
|
||||||
|
test -n "$PG_ID" || { echo "FATAL: no postgres service container on this job's network (self nets: $SELF_NETS)"; exit 1; }
|
||||||
|
echo "selected postgres: $PG_ID $PG_NAME"
|
||||||
|
PG_IP=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$PG_ID")
|
||||||
|
test -n "$PG_IP"
|
||||||
|
export MINSTREL_TEST_DATABASE_URL="postgres://minstrel:minstrel@${PG_IP}:5432/minstrel_test?sslmode=disable"
|
||||||
|
|
||||||
|
# Wait for Postgres to accept TCP (no health-check dependency).
|
||||||
|
for i in $(seq 1 60); do (echo > "/dev/tcp/${PG_IP}/5432") 2>/dev/null && break; sleep 2; done
|
||||||
|
|
||||||
|
# Relax durability on the throwaway CI Postgres. Our test pattern
|
||||||
|
# is dbtest.ResetDB → TRUNCATE … RESTART IDENTITY CASCADE before
|
||||||
|
# every test, and the per-TRUNCATE commit fsync is the dominant
|
||||||
|
# cost of the integration suite. The CI DB is rebuilt every run so
|
||||||
|
# fsync / full_page_writes / synchronous_commit buy nothing. Apply
|
||||||
|
# via docker exec because:
|
||||||
|
# - The act_runner `services:` block can't override the container
|
||||||
|
# command, so `postgres -c fsync=off` at boot isn't an option.
|
||||||
|
# - ALTER SYSTEM cannot run inside a transaction; psql -c
|
||||||
|
# auto-commits each statement, which is what we need.
|
||||||
|
# - fsync / full_page_writes are sighup GUCs and
|
||||||
|
# synchronous_commit is user-context, so pg_reload_conf() picks
|
||||||
|
# all three up with no restart.
|
||||||
|
# Non-fatal: a perms surprise degrades to "slower", never red CI.
|
||||||
|
docker exec "$PG_ID" psql -U minstrel -d minstrel_test \
|
||||||
|
-c "ALTER SYSTEM SET fsync = off" \
|
||||||
|
-c "ALTER SYSTEM SET synchronous_commit = off" \
|
||||||
|
-c "ALTER SYSTEM SET full_page_writes = off" \
|
||||||
|
-c "SELECT pg_reload_conf()" \
|
||||||
|
|| echo "WARN: durability relax failed; continuing"
|
||||||
|
|
||||||
|
# Apply embedded migrations to the fresh test DB, then run the
|
||||||
|
# full suite (no -short → integration tests execute). -p 1:
|
||||||
|
# every integration package TRUNCATEs the one shared test DB;
|
||||||
|
# concurrent package binaries → TRUNCATE deadlocks. Serialize
|
||||||
|
# package execution (the documented local invocation too).
|
||||||
|
MINSTREL_DATABASE_URL="$MINSTREL_TEST_DATABASE_URL" go run ./cmd/minstrel migrate
|
||||||
|
go test -p 1 -race ./...
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
name: test-web
|
||||||
|
|
||||||
|
# Web SPA: vitest + svelte-check. Runs on push to dev/main only —
|
||||||
|
# the `pull_request` trigger is intentionally omitted because every
|
||||||
|
# branch on this repo is local-only (no fork PRs), so the dev push
|
||||||
|
# fully covers what a PR run would re-execute. Keeping both events
|
||||||
|
# doubled CI cost on every commit.
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [dev, main]
|
||||||
|
paths:
|
||||||
|
- 'web/**'
|
||||||
|
- '.gitea/workflows/test-web.yml'
|
||||||
|
|
||||||
|
# Cancel an earlier in-flight run for the same ref when a newer
|
||||||
|
# commit arrives. With cancel-in-progress, rapid re-pushes don't
|
||||||
|
# pile up zombie runs.
|
||||||
|
concurrency:
|
||||||
|
group: ${{ github.workflow }}-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
runs-on: go-ci
|
||||||
|
container:
|
||||||
|
image: git.fabledsword.com/bvandeusen/ci-go:1.26
|
||||||
|
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: web
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Install deps
|
||||||
|
run: npm ci
|
||||||
|
|
||||||
|
- name: Type-check + svelte-check
|
||||||
|
run: npm run check
|
||||||
|
|
||||||
|
- name: Vitest
|
||||||
|
run: npm test
|
||||||
+25
-13
@@ -12,11 +12,8 @@
|
|||||||
# Test binary, built with `go test -c`
|
# Test binary, built with `go test -c`
|
||||||
*.test
|
*.test
|
||||||
|
|
||||||
# `make build` output — an 18 MB binary that is never committed.
|
# Bundled Android APK + version sidecar (#397). Populated by CI for
|
||||||
bin/
|
# 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
|
||||||
client/minstrel.apk.version
|
client/minstrel.apk.version
|
||||||
|
|
||||||
@@ -42,9 +39,10 @@ go.work.sum
|
|||||||
docs/superpowers/
|
docs/superpowers/
|
||||||
|
|
||||||
# Per-machine Claude Code settings + remember-skill memory artifacts +
|
# Per-machine Claude Code settings + remember-skill memory artifacts +
|
||||||
# project-level Claude/AI instruction files. All per-machine;
|
# project-level Claude/AI instruction files. All operator-scoped; the
|
||||||
# CLAUDE.md/AGENTS.md/GEMINI.md are tool-specific working notes, not
|
# canonical project memory lives under ~/.claude/projects/ outside the
|
||||||
# project artifacts.
|
# repo. CLAUDE.md/AGENTS.md/GEMINI.md stay on the operator's machine
|
||||||
|
# only — they're tool-specific working notes, not project artifacts.
|
||||||
.claude/
|
.claude/
|
||||||
.remember/
|
.remember/
|
||||||
CLAUDE.md
|
CLAUDE.md
|
||||||
@@ -54,7 +52,21 @@ GEMINI.md
|
|||||||
.windsurfrules
|
.windsurfrules
|
||||||
.aider.conf.yml
|
.aider.conf.yml
|
||||||
|
|
||||||
# Native Android (Kotlin/Compose)
|
# Flutter
|
||||||
|
flutter_client/.dart_tool/
|
||||||
|
flutter_client/.flutter-plugins
|
||||||
|
flutter_client/.flutter-plugins-dependencies
|
||||||
|
flutter_client/build/
|
||||||
|
flutter_client/.idea/
|
||||||
|
flutter_client/ios/Podfile.lock
|
||||||
|
flutter_client/ios/Pods/
|
||||||
|
flutter_client/android/.gradle/
|
||||||
|
flutter_client/android/app/build/
|
||||||
|
flutter_client/android/local.properties
|
||||||
|
flutter_client/android/key.properties
|
||||||
|
flutter_client/*.iml
|
||||||
|
|
||||||
|
# Native Android (Kotlin/Compose) — M8 rewrite
|
||||||
android/.gradle/
|
android/.gradle/
|
||||||
android/.kotlin/
|
android/.kotlin/
|
||||||
android/.idea/
|
android/.idea/
|
||||||
@@ -63,11 +75,11 @@ android/app/build/
|
|||||||
android/local.properties
|
android/local.properties
|
||||||
android/*.iml
|
android/*.iml
|
||||||
android/app/*.iml
|
android/app/*.iml
|
||||||
# Release signing material: a keystore never belongs in the repo.
|
# Release signing material — keystore + extracted credentials live local
|
||||||
|
# only; the canonical copy is the Gitea repo secret (ANDROID_KEYSTORE_B64
|
||||||
|
# + the alias/password secrets). Losing the local file is fine; losing
|
||||||
|
# the secret means rebuilding the keystore + reinstalling all clients.
|
||||||
android/*.keystore
|
android/*.keystore
|
||||||
android/*.keystore.*
|
android/*.keystore.*
|
||||||
android/*.jks
|
android/*.jks
|
||||||
android/keystore.properties
|
android/keystore.properties
|
||||||
|
|
||||||
# Python bytecode from the tools/ scripts
|
|
||||||
__pycache__/
|
|
||||||
|
|||||||
+10
-25
@@ -7,7 +7,7 @@ RUN npm ci
|
|||||||
COPY web/ ./
|
COPY web/ ./
|
||||||
RUN npm run build
|
RUN npm run build
|
||||||
|
|
||||||
FROM golang:1.26-bookworm AS builder
|
FROM golang:1.25-bookworm AS builder
|
||||||
WORKDIR /src
|
WORKDIR /src
|
||||||
COPY go.mod go.sum ./
|
COPY go.mod go.sum ./
|
||||||
RUN go mod download
|
RUN go mod download
|
||||||
@@ -15,31 +15,17 @@ COPY . .
|
|||||||
# Overwrite the committed placeholder with the freshly-built SPA assets.
|
# Overwrite the committed placeholder with the freshly-built SPA assets.
|
||||||
COPY --from=web /web/build ./web/build
|
COPY --from=web /web/build ./web/build
|
||||||
ENV CGO_ENABLED=0
|
ENV CGO_ENABLED=0
|
||||||
# Version stamping. The release build passes the DERIVED version name
|
# Version stamping: release.yml passes the git tag via MINSTREL_VERSION
|
||||||
# (YYYY.MM.DD.HHMM) and the lane's channel; a local `docker build` falls back
|
# build-arg; local `docker build` falls back to "dev". Surfaced at
|
||||||
# to "dev"/"local". Both are surfaced at /healthz.
|
# /healthz for operator-side image-version verification.
|
||||||
#
|
|
||||||
# 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_VERSION=dev
|
||||||
ARG MINSTREL_CHANNEL=local
|
|
||||||
RUN go build -trimpath \
|
RUN go build -trimpath \
|
||||||
-ldflags="-s -w \
|
-ldflags="-s -w -X 'git.fabledsword.com/bvandeusen/minstrel/internal/server.ServerVersion=${MINSTREL_VERSION}'" \
|
||||||
-X 'github.com/Fabled-Sword/minstrel/internal/buildinfo.Version=${MINSTREL_VERSION}' \
|
|
||||||
-X 'github.com/Fabled-Sword/minstrel/internal/buildinfo.Channel=${MINSTREL_CHANNEL}'" \
|
|
||||||
-o /out/minstrel ./cmd/minstrel
|
-o /out/minstrel ./cmd/minstrel
|
||||||
|
|
||||||
FROM debian:bookworm-slim
|
FROM debian:bookworm-slim
|
||||||
# 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. 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 \
|
RUN apt-get update \
|
||||||
&& apt-get install -y --no-install-recommends ca-certificates ffmpeg libchromaprint-tools \
|
&& apt-get install -y --no-install-recommends ca-certificates ffmpeg \
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
RUN groupadd --system --gid 1000 minstrel \
|
RUN groupadd --system --gid 1000 minstrel \
|
||||||
@@ -56,11 +42,10 @@ COPY config.example.yaml /etc/smartmusic/config.yaml
|
|||||||
RUN mkdir -p /app/data /app/client && chown -R minstrel:minstrel /app
|
RUN mkdir -p /app/data /app/client && chown -R minstrel:minstrel /app
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
# In-app update channel. client/ in the build context holds
|
# In-app update channel (#397). client/ in the build context holds
|
||||||
# minstrel.apk + minstrel.apk.version, which the release build fills; a
|
# minstrel.apk + minstrel.apk.version (populated by release.yml on tag
|
||||||
# local build has only .gitkeep + README. Endpoints return
|
# pushes; .gitkeep + README otherwise). Endpoints return 404 when the
|
||||||
# 404 when the APK files aren't present, so such an image degrades
|
# APK files aren't present, so non-tag images degrade gracefully.
|
||||||
# gracefully.
|
|
||||||
COPY --chown=minstrel:minstrel client/ /app/client/
|
COPY --chown=minstrel:minstrel client/ /app/client/
|
||||||
|
|
||||||
USER minstrel
|
USER minstrel
|
||||||
|
|||||||
@@ -1,661 +1,9 @@
|
|||||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
MIT License
|
||||||
Version 3, 19 November 2007
|
|
||||||
|
|
||||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
Copyright (c) 2026 bvandeusen
|
||||||
Everyone is permitted to copy and distribute verbatim copies
|
|
||||||
of this license document, but changing it is not allowed.
|
|
||||||
|
|
||||||
Preamble
|
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:
|
||||||
|
|
||||||
The GNU Affero General Public License is a free, copyleft license for
|
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||||
software and other kinds of works, specifically designed to ensure
|
|
||||||
cooperation with the community in the case of network server software.
|
|
||||||
|
|
||||||
The licenses for most software and other practical works are designed
|
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.
|
||||||
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/>.
|
|
||||||
|
|||||||
@@ -7,14 +7,17 @@ SQLC_VERSION := 1.31.1
|
|||||||
generate:
|
generate:
|
||||||
docker run --rm -v "$(CURDIR):/src" -w /src sqlc/sqlc:$(SQLC_VERSION) generate
|
docker run --rm -v "$(CURDIR):/src" -w /src sqlc/sqlc:$(SQLC_VERSION) generate
|
||||||
|
|
||||||
# Same codegen, run as a Go tool instead of a container, for a machine that
|
# Same codegen, run as a Go tool instead of a container. This is the CI path:
|
||||||
# has Go but no Docker. Pinned to the
|
# the ci-go image already has Go, so it avoids docker-in-docker. Pinned to the
|
||||||
# SAME version as `generate` above so both routes emit identical output.
|
# SAME version as `generate` above so both routes emit identical output.
|
||||||
generate-go:
|
generate-go:
|
||||||
go run github.com/sqlc-dev/sqlc/cmd/sqlc@v$(SQLC_VERSION) generate
|
go run github.com/sqlc-dev/sqlc/cmd/sqlc@v$(SQLC_VERSION) generate
|
||||||
|
|
||||||
# Fail if the committed generated code no longer matches the .sql sources:
|
# Fail if the committed generated code no longer matches the .sql sources.
|
||||||
# a hand-edit, a half-applied regen, or a schema change without a regen.
|
#
|
||||||
|
# Nothing verified this before, so internal/db/dbq could silently drift from
|
||||||
|
# internal/db/queries — a hand-edit, a half-applied regen, or a schema change
|
||||||
|
# without a regen would all pass CI while the typed layer lied about the SQL.
|
||||||
#
|
#
|
||||||
# The diff is printed BEFORE the exit-code check on purpose: when this fails,
|
# The diff is printed BEFORE the exit-code check on purpose: when this fails,
|
||||||
# the log then contains sqlc's exact expected output, which is what you commit.
|
# the log then contains sqlc's exact expected output, which is what you commit.
|
||||||
@@ -33,15 +36,14 @@ test-short:
|
|||||||
go test -short -race ./...
|
go test -short -race ./...
|
||||||
|
|
||||||
# Full suite incl. integration tests, against the dedicated minstrel_test
|
# Full suite incl. integration tests, against the dedicated minstrel_test
|
||||||
# DB so a run never truncates the dev `minstrel` DB. Ensures the test DB
|
# DB so a run never truncates the dev `minstrel` DB (Fable #339). Ensures
|
||||||
# exists (createdb fails harmlessly if it is already there).
|
# the test DB exists (idempotent — createdb errors if present, ignored).
|
||||||
test-integration:
|
test-integration:
|
||||||
docker compose up -d postgres
|
docker compose up -d postgres
|
||||||
-docker compose exec -T postgres createdb -U minstrel minstrel_test
|
-docker compose exec -T postgres createdb -U minstrel minstrel_test
|
||||||
# Only packages with database tests; test-short covers the rest.
|
# -p 1: integration packages share one test DB and each TRUNCATEs it;
|
||||||
# -p 1: they share one test DB and each TRUNCATEs it; concurrent
|
# concurrent package binaries deadlock on TRUNCATE. Serialize packages.
|
||||||
# package binaries deadlock on TRUNCATE. Serialize packages.
|
MINSTREL_TEST_DATABASE_URL=postgres://minstrel:minstrel@localhost:5432/minstrel_test?sslmode=disable go test -p 1 -race ./...
|
||||||
MINSTREL_TEST_DATABASE_URL=postgres://minstrel:minstrel@localhost:5432/minstrel_test?sslmode=disable go test -p 1 -race $$(sh ci/db-test-packages.sh)
|
|
||||||
|
|
||||||
lint:
|
lint:
|
||||||
golangci-lint run ./...
|
golangci-lint run ./...
|
||||||
|
|||||||
@@ -1,33 +1,53 @@
|
|||||||
<p align="center"><img src="web/static/brand/mark.svg" width="120" alt="Fabled Minstrel logo"></p>
|
# Minstrel
|
||||||
|
|
||||||
<h1 align="center">Fabled Minstrel</h1>
|
A self-hosted music server that thinks for you. Smart shuffle, contextual likes, ListenBrainz-aware radio, and Lidarr automation — server-side, so every client (web, mobile, Subsonic third-party) gets the same intelligence.
|
||||||
|
|
||||||
<p align="center">A self-hosted music server that picks what to play next.</p>
|
> State and intelligence belong on the server, not the client.
|
||||||
|
|
||||||
Fabled Minstrel serves your music library to the web, to its own Android app, and to Subsonic apps. Shuffle, radio, likes and play history are worked out on the server, so the web app, the Android app and Subsonic apps get the same mixes and the same history, and what you like and play in a Subsonic app counts too. It is for anyone who keeps their own music collection and wants it to sound like more than a random shuffle.
|
<a href="docs/screenshots/home.png"><img src="docs/screenshots/home.png" width="820" alt="Minstrel home — your library at a glance"></a>
|
||||||
|
|
||||||
<a href="docs/screenshots/home.png"><img src="docs/screenshots/home.png" width="820" alt="Minstrel's Home: daily mixes, Songs like, and genre mixes ordered by what you play most"></a>
|
## Highlights
|
||||||
|
|
||||||
<p>
|
- **OpenSubsonic-compatible.** Existing Subsonic clients (DSub, Symfonium, play:Sub, etc.) connect with no special configuration.
|
||||||
<a href="docs/screenshots/now-playing.png"><img src="docs/screenshots/now-playing.png" width="560" alt="Now playing, with the queue beside it"></a>
|
- **Server-side smart shuffle.** Track-similarity vectors, dual-like model (general + contextual), and session memory keep mixes coherent across devices.
|
||||||
<a href="docs/screenshots/home-phone.png"><img src="docs/screenshots/home-phone.png" width="200" alt="Home on a phone"></a>
|
- **ListenBrainz radio.** Session-aware "more like this" pulls from ListenBrainz similarity data, not a static genre tag.
|
||||||
</p>
|
- **Lidarr integration.** Triggered scans, request-driven album imports, and a quarantine flow when something doesn't fit — against a Lidarr instance *you* run and configure. Optional, and off until you supply a URL and API key.
|
||||||
|
- **Built-in web SPA.** Full-feature library, search, queue, playlists, and admin — no separate frontend container to deploy.
|
||||||
|
- **Native Android client, shipped with the server.** The signed APK is bundled into every image and attached to each [release](https://git.fabledsword.com/bvandeusen/minstrel/releases) — sideload it once, then the app self-updates straight from your own server (no app store, no separate download to track).
|
||||||
|
|
||||||
<sub>The music in these screenshots is invented: every artist, album, cover and song was generated for them (<a href="tools/demo-library">tools/demo-library</a>).</sub>
|
## Scope and responsible use
|
||||||
|
|
||||||
## Quick start
|
**Minstrel serves music you already have.** It is a library server: it indexes files on disk you point it at, and streams them to your own clients. It does not source, search for, or acquire content, and it has no opinion about where your files came from.
|
||||||
|
|
||||||
|
Concretely, Minstrel ships **no** indexers, **no** trackers, **no** torrent / Usenet / NZB client, and **no** DRM circumvention of any kind. There is nothing to point at a content source because Minstrel has no such subsystem.
|
||||||
|
|
||||||
|
The **Lidarr integration is optional and inert until you configure it.** You supply the URL and API key of a Lidarr instance you are already running; Minstrel then calls that instance's API to trigger scans, submit album requests, and reconcile imports. Minstrel neither bundles nor installs Lidarr, and configures no indexers on your behalf — Lidarr ships with none either, and any it uses are ones you added yourself.
|
||||||
|
|
||||||
|
**What you put in your library, and what sources you configure in your own Lidarr, are your responsibility.** Copyright law applies to your collection the same way it applies to any other software that plays a file. Please respect it, and respect the terms of any service you connect.
|
||||||
|
|
||||||
|
Minstrel is not affiliated with or endorsed by Lidarr, ListenBrainz, MusicBrainz, or Subsonic.
|
||||||
|
|
||||||
|
## Quickstart
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
# compose.yaml
|
# compose.yaml
|
||||||
services:
|
services:
|
||||||
minstrel:
|
minstrel:
|
||||||
image: ghcr.io/fabled-sword/minstrel:latest
|
image: git.fabledsword.com/bvandeusen/minstrel:latest
|
||||||
ports: ['4533:4533']
|
ports: ['4533:4533']
|
||||||
volumes:
|
volumes:
|
||||||
- ./music:/music # your library; must be writable by uid 1000
|
# Your music library. Point ./music at wherever your audio files
|
||||||
- minstrel-data:/app/data # art and caches
|
# live. Mounted read-only — Minstrel never writes to your library.
|
||||||
|
- ./music:/music:ro
|
||||||
|
# Generated data: playlist cover collages, artist art, caches.
|
||||||
|
# The path must match MINSTREL_STORAGE_DATA_DIR, which the image
|
||||||
|
# sets to /app/data — keep this mount on /app/data or your cache
|
||||||
|
# won't survive a container recreate.
|
||||||
|
- minstrel-data:/app/data
|
||||||
environment:
|
environment:
|
||||||
MINSTREL_DATABASE_URL: postgres://minstrel:minstrel@db:5432/minstrel?sslmode=disable
|
MINSTREL_DATABASE_URL: postgres://minstrel:minstrel@db:5432/minstrel?sslmode=disable
|
||||||
|
# Colon-separated library roots to scan; must match the container
|
||||||
|
# path of the read-only music mount above (/music here).
|
||||||
MINSTREL_LIBRARY_SCAN_PATHS: /music
|
MINSTREL_LIBRARY_SCAN_PATHS: /music
|
||||||
depends_on: [db]
|
depends_on: [db]
|
||||||
|
|
||||||
@@ -37,7 +57,9 @@ services:
|
|||||||
POSTGRES_USER: minstrel
|
POSTGRES_USER: minstrel
|
||||||
POSTGRES_PASSWORD: minstrel
|
POSTGRES_PASSWORD: minstrel
|
||||||
POSTGRES_DB: minstrel
|
POSTGRES_DB: minstrel
|
||||||
volumes: [pgdata:/var/lib/postgresql/data] # users, likes, history: back this up
|
# Postgres data dir — users, likes, play history, sessions, settings.
|
||||||
|
# The one volume you must never lose; back it up with pg_dump.
|
||||||
|
volumes: [pgdata:/var/lib/postgresql/data]
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
minstrel-data:
|
minstrel-data:
|
||||||
@@ -46,96 +68,92 @@ volumes:
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker compose up -d
|
docker compose up -d
|
||||||
docker compose logs minstrel | grep setup_token
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Open `http://<host>:4533/register` and create the first account with that setup token. The first account is the administrator.
|
## First run
|
||||||
|
|
||||||
### First run
|
With the stack up, a handful of in-app steps get you to a working library. Use your own host in place of `localhost` if you're reaching the server over a LAN/VPN address (plain `http://` is fine — no TLS required).
|
||||||
|
|
||||||
1. **Let the first scan finish.** Minstrel scans the library on startup. Watch it, or scan again, on the **Admin** page (`/admin`). Later scans only pick up what changed.
|
**1. Create your admin account.** Visit `http://localhost:4533/register`. The first account on a fresh instance is automatically the administrator; later users join through the same form or an invite token (step 5).
|
||||||
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.
|
|
||||||
|
|
||||||
**On an iPhone** there is no Minstrel app; use a Subsonic app such as play:Sub or Amperfy. Make a password for it in **Settings › Connections › Subsonic apps**, and give the app your server's address, your username and that password. Subsonic apps can browse, search, play, like and scrobble, and make and edit playlists. Minstrel's daily mixes appear in them as playlists, and when an app asks the server for random songs or an instant mix it gets Minstrel's smart shuffle and radio. An app that shuffles on the phone instead shuffles at random.
|
<a href="docs/screenshots/register.png"><img src="docs/screenshots/register.png" width="320" alt="Creating the first (admin) account on a fresh instance"></a>
|
||||||
3. **Invite the household.** In **Admin › Users** (`/admin/users`), make an invite token for each person; an invite is the only way to an account. Each person gets their own likes, history and recommendations.
|
|
||||||
4. **Optional: connect ListenBrainz.** Each person adds their own ListenBrainz token in **Settings › Connections**.
|
**2. Let the first library scan finish.** `scan_on_startup` is on by default, so Minstrel walks your mounted library on boot and imports artists, albums, and tracks — no button to press. Watch progress (and re-scan any time) on the **Admin** page (`/admin`); the scan runs in stages and is incremental, so later restarts only pick up what changed.
|
||||||
|
|
||||||
|
<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>
|
||||||
|
|
||||||
|
**3. (Optional) Name the instance and wire up integrations.** In admin **Settings → Integrations** (`/admin/integrations`), add a ListenBrainz token (scrobbling + similarity radio) and/or a Lidarr URL + API key (the request flow). These live in the UI and apply without a restart; the display name can also be set via `MINSTREL_BRANDING_APP_NAME`.
|
||||||
|
|
||||||
|
<a href="docs/screenshots/integrations.png"><img src="docs/screenshots/integrations.png" width="820" alt="ListenBrainz and Lidarr integration cards in admin Settings"></a>
|
||||||
|
|
||||||
|
**4. Install the Android app.** Open **Settings** (`/settings`) and use the *Install the Android app* card to download the APK that ships inside this server image, then sign in with the same account. From then on the app self-updates straight from your server.
|
||||||
|
|
||||||
|
<a href="docs/screenshots/android-download.png"><img src="docs/screenshots/android-download.png" width="820" alt="The "Install the Android app" download card in Settings"></a>
|
||||||
|
|
||||||
|
**5. Invite the rest of the household.** From admin **Users** (`/admin/users`), generate an invite token (or enable open registration). Each person gets their own account, so likes, play history, and recommendations stay per-user.
|
||||||
|
|
||||||
|
<a href="docs/screenshots/invite-users.png"><img src="docs/screenshots/invite-users.png" width="820" alt="Generating an invite token in admin Users"></a>
|
||||||
|
|
||||||
|
For the full configuration surface, see [`config.example.yaml`](./config.example.yaml).
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
The quick start sets everything that's required. These are the settings people most often change:
|
Most operators only need the env vars in the quickstart above. A few extras worth knowing:
|
||||||
|
|
||||||
| Variable | What it does |
|
- `MINSTREL_BRANDING_APP_NAME` — rename the instance ("Family Jukebox", "Office Music"). Surfaces in the header, browser tab, and OG share previews.
|
||||||
|---|---|
|
- `MINSTREL_STORAGE_DATA_DIR` — where generated artefacts (playlist cover collages, artist art, caches) are written. The container image sets this to `/app/data`, which is why the quickstart mounts the `minstrel-data` volume there.
|
||||||
| `MINSTREL_DATABASE_URL` | Postgres connection string. Required. |
|
- `MINSTREL_LIBRARY_SCAN_PATHS` — colon-separated list of music library roots to scan. Supports multiple roots (`/music:/podcasts`).
|
||||||
| `MINSTREL_LIBRARY_SCAN_PATHS` | Library folders inside the container, colon-separated (`/music:/audiobooks`). They are used on first start only; after that, change them in **Admin › Library**. |
|
|
||||||
| `MINSTREL_BRANDING_APP_NAME` | The name shown in the header, the browser tab and link previews. |
|
|
||||||
| `MINSTREL_LOG_LEVEL` | `debug`, `info`, `warn` or `error`. |
|
|
||||||
|
|
||||||
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`.
|
ListenBrainz integration (per-user scrobble + similarity tokens) and Lidarr integration (URL + API key) are configured through the admin Settings UI rather than env vars or yaml — per Minstrel's "config in UI" rule, integration settings live where operators can edit them without restarting.
|
||||||
|
|
||||||
## Setup pitfalls
|
Most operational keys have a `MINSTREL_<SECTION>_<FIELD>` env override. Recommendation and events tuning are yaml-only. See [`config.example.yaml`](./config.example.yaml) for the authoritative surface.
|
||||||
|
|
||||||
- **The library mount has to be writable by uid 1000.** Minstrel deletes a file only when an admin asks it to, such as merging duplicates. It never adds, moves, renames or retags files there (album art it finds or fetches is kept in its own data folder), so a tagger or download manager can keep filing into the same folder. Mount the library `:ro` to forbid writes: those actions then refuse and say why.
|
## Updating
|
||||||
- **`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).
|
|
||||||
|
|
||||||
## Updating and backups
|
Image tags (`git.fabledsword.com/bvandeusen/minstrel:<tag>`):
|
||||||
|
|
||||||
```bash
|
- `:latest` — the newest blessed image. Moves on every `main` push **and** every release. Recommended for most operators.
|
||||||
docker compose pull && docker compose up -d
|
- `:vYYYY.MM.DD` — immutable per-day release tags. Pin one of these for a deployment you don't want moving under you. (Per-day CalVer — no trailing patch digit; a same-day re-cut moves the tag forward.)
|
||||||
```
|
- `:main` — the rolling post-merge tip. Same image as `:latest` at push time; choose it if you want to track `main` explicitly rather than the release line.
|
||||||
|
|
||||||
Database migrations run at startup. Image tags:
|
Every `:latest` and every `:vYYYY.MM.DD` bundles the current signed Android APK, so the in-app update channel is always live. Database migrations run automatically at startup; rollbacks require restoring a Postgres dump.
|
||||||
|
|
||||||
- `:latest`: the stable release. Most people should run this.
|
## Specs
|
||||||
- `:<commit-sha>`: one fixed build. Pin one to stop updates, or to roll back.
|
|
||||||
- `:dev`: the test channel, rebuilt on every change. It may break, and the fix is the next build.
|
|
||||||
|
|
||||||
Every image carries a signed Android app, all with the same key, so a phone can move between channels without reinstalling. Rolling back a SHA tag rolls back the app it carries too.
|
Authoritative scope lives under [`docs/`](./docs):
|
||||||
|
|
||||||
**Back up the Postgres volume** with `pg_dump`. It holds accounts, likes, play history, playlists and settings, and a migration can only be undone by restoring a dump. The `minstrel-data` volume holds artwork and caches that Minstrel rebuilds if lost.
|
- [Server spec](./docs/smart-music-server-spec.md) — current implementation focus.
|
||||||
|
- [Client spec](./docs/smart-music-client-spec.md) — Flutter companion app.
|
||||||
## Features
|
|
||||||
|
|
||||||
**Listening**
|
|
||||||
- Smart shuffle that weighs what you like, what you skip and what you've heard lately, instead of picking at random.
|
|
||||||
- Two kinds of like: a song you love, and a song that's right for what you're listening to now.
|
|
||||||
- Radio that starts from any song, using ListenBrainz similarity as well as your own history.
|
|
||||||
- Daily mixes and system playlists built from your listening.
|
|
||||||
- Playback on Sonos and other UPnP speakers from the Android app.
|
|
||||||
- Loudness levelling between tracks, so you never reach for the volume.
|
|
||||||
|
|
||||||
**Your library**
|
|
||||||
- Browse by artist, album, genre and year, with search across everything.
|
|
||||||
- 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.
|
|
||||||
|
|
||||||
**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.
|
|
||||||
- OpenSubsonic-compatible, so Subsonic apps such as Symfonium, DSub, play:Sub and Amperfy can browse by artist, album, genre or folder, search, play, like and scrobble, carry a play queue from one device to another, show lyrics (from a `.lrc` file beside the song, or the song's own tags), see the daily mixes, make and edit your playlists, and get Minstrel's smart shuffle and radio when they ask for random songs or similar songs.
|
|
||||||
- Separate accounts for each person, with invites, and an inbox for what happened while you were away.
|
|
||||||
|
|
||||||
## Scope and responsible use
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
Minstrel is not affiliated with or endorsed by ListenBrainz, MusicBrainz or Subsonic.
|
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
- **Backend:** `docker compose up` in this repo runs Postgres and Minstrel on `:4533`.
|
Two concurrent dev processes:
|
||||||
- **Web:** `cd web && npm install && npm run dev` starts Vite on `:5173`. It proxies `/api/*` and `/rest/*` to `:4533`.
|
|
||||||
- **Tests:** `make test-short` runs the unit tests. `make test-integration` runs the database tests, against a separate `minstrel_test` database so your dev data is never truncated.
|
|
||||||
- **Image:** `docker build -t minstrel .` builds the web app and embeds it in the server binary.
|
|
||||||
- **Branches:** work lands on `dev`; `main` changes through pull requests from `dev`.
|
|
||||||
|
|
||||||
How accounts and sessions are protected, and which outside services Minstrel contacts: [docs/security.md](docs/security.md).
|
1. **Backend:** `docker compose up` — Postgres + Minstrel on `:4533`.
|
||||||
|
2. **Frontend:** `cd web && npm install && npm run dev` — Vite dev server on `:5173` with HMR. The Vite server proxies `/api/*` and `/rest/*` to `:4533` so session cookies work.
|
||||||
|
|
||||||
|
### Testing
|
||||||
|
|
||||||
|
- Unit + race (no DB): `make test-short`.
|
||||||
|
- Full suite incl. integration tests: `make test-integration`. This runs
|
||||||
|
against a dedicated `minstrel_test` database so a test run never
|
||||||
|
truncates your dev `minstrel` data (admin user, library, likes). It
|
||||||
|
brings up the compose Postgres and creates the test DB if missing.
|
||||||
|
- CI runs both: a fast `go test -short -race` gate plus an integration
|
||||||
|
job with its own ephemeral Postgres (`.gitea/workflows/test-go.yml`).
|
||||||
|
|
||||||
|
### Production build
|
||||||
|
|
||||||
|
`docker build -t minstrel .` runs the SvelteKit build inside a `node` stage, copies the output into the `golang` stage, and `//go:embed`s it into the final binary. The container serves the SPA from `/` alongside the API surfaces; no separate static-file server is required.
|
||||||
|
|
||||||
|
### Branches
|
||||||
|
|
||||||
|
- Day-to-day work happens on `dev` (or feature branches merged into `dev`).
|
||||||
|
- `main` is **protected** — changes land via PR from `dev`.
|
||||||
|
- Releases are cut by tagging `v*` off `main`; the release workflow builds and pushes the container image to the Gitea registry.
|
||||||
|
|
||||||
|
Task and milestone tracking: Fable (`Minstrel` project, id 12).
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
GNU Affero General Public License v3.0. See [LICENSE](./LICENSE).
|
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.
|
|
||||||
|
|||||||
Generated
+3
@@ -0,0 +1,3 @@
|
|||||||
|
# Default ignored files
|
||||||
|
/shelf/
|
||||||
|
/workspace.xml
|
||||||
Generated
+1
@@ -0,0 +1 @@
|
|||||||
|
Minstrel
|
||||||
Generated
+6
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="AndroidProjectSystem">
|
||||||
|
<option name="providerId" value="com.android.tools.idea.GradleProjectSystem" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
Generated
+1857
File diff suppressed because it is too large
Load Diff
Generated
+123
@@ -0,0 +1,123 @@
|
|||||||
|
<component name="ProjectCodeStyleConfiguration">
|
||||||
|
<code_scheme name="Project" version="173">
|
||||||
|
<JetCodeStyleSettings>
|
||||||
|
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
|
||||||
|
</JetCodeStyleSettings>
|
||||||
|
<codeStyleSettings language="XML">
|
||||||
|
<option name="FORCE_REARRANGE_MODE" value="1" />
|
||||||
|
<indentOptions>
|
||||||
|
<option name="CONTINUATION_INDENT_SIZE" value="4" />
|
||||||
|
</indentOptions>
|
||||||
|
<arrangement>
|
||||||
|
<rules>
|
||||||
|
<section>
|
||||||
|
<rule>
|
||||||
|
<match>
|
||||||
|
<AND>
|
||||||
|
<NAME>xmlns:android</NAME>
|
||||||
|
<XML_ATTRIBUTE />
|
||||||
|
<XML_NAMESPACE>^$</XML_NAMESPACE>
|
||||||
|
</AND>
|
||||||
|
</match>
|
||||||
|
</rule>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
<rule>
|
||||||
|
<match>
|
||||||
|
<AND>
|
||||||
|
<NAME>xmlns:.*</NAME>
|
||||||
|
<XML_ATTRIBUTE />
|
||||||
|
<XML_NAMESPACE>^$</XML_NAMESPACE>
|
||||||
|
</AND>
|
||||||
|
</match>
|
||||||
|
<order>BY_NAME</order>
|
||||||
|
</rule>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
<rule>
|
||||||
|
<match>
|
||||||
|
<AND>
|
||||||
|
<NAME>.*:id</NAME>
|
||||||
|
<XML_ATTRIBUTE />
|
||||||
|
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
|
||||||
|
</AND>
|
||||||
|
</match>
|
||||||
|
</rule>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
<rule>
|
||||||
|
<match>
|
||||||
|
<AND>
|
||||||
|
<NAME>.*:name</NAME>
|
||||||
|
<XML_ATTRIBUTE />
|
||||||
|
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
|
||||||
|
</AND>
|
||||||
|
</match>
|
||||||
|
</rule>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
<rule>
|
||||||
|
<match>
|
||||||
|
<AND>
|
||||||
|
<NAME>name</NAME>
|
||||||
|
<XML_ATTRIBUTE />
|
||||||
|
<XML_NAMESPACE>^$</XML_NAMESPACE>
|
||||||
|
</AND>
|
||||||
|
</match>
|
||||||
|
</rule>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
<rule>
|
||||||
|
<match>
|
||||||
|
<AND>
|
||||||
|
<NAME>style</NAME>
|
||||||
|
<XML_ATTRIBUTE />
|
||||||
|
<XML_NAMESPACE>^$</XML_NAMESPACE>
|
||||||
|
</AND>
|
||||||
|
</match>
|
||||||
|
</rule>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
<rule>
|
||||||
|
<match>
|
||||||
|
<AND>
|
||||||
|
<NAME>.*</NAME>
|
||||||
|
<XML_ATTRIBUTE />
|
||||||
|
<XML_NAMESPACE>^$</XML_NAMESPACE>
|
||||||
|
</AND>
|
||||||
|
</match>
|
||||||
|
<order>BY_NAME</order>
|
||||||
|
</rule>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
<rule>
|
||||||
|
<match>
|
||||||
|
<AND>
|
||||||
|
<NAME>.*</NAME>
|
||||||
|
<XML_ATTRIBUTE />
|
||||||
|
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
|
||||||
|
</AND>
|
||||||
|
</match>
|
||||||
|
<order>ANDROID_ATTRIBUTE_ORDER</order>
|
||||||
|
</rule>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
<rule>
|
||||||
|
<match>
|
||||||
|
<AND>
|
||||||
|
<NAME>.*</NAME>
|
||||||
|
<XML_ATTRIBUTE />
|
||||||
|
<XML_NAMESPACE>.*</XML_NAMESPACE>
|
||||||
|
</AND>
|
||||||
|
</match>
|
||||||
|
<order>BY_NAME</order>
|
||||||
|
</rule>
|
||||||
|
</section>
|
||||||
|
</rules>
|
||||||
|
</arrangement>
|
||||||
|
</codeStyleSettings>
|
||||||
|
<codeStyleSettings language="kotlin">
|
||||||
|
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
|
||||||
|
</codeStyleSettings>
|
||||||
|
</code_scheme>
|
||||||
|
</component>
|
||||||
+5
@@ -0,0 +1,5 @@
|
|||||||
|
<component name="ProjectCodeStyleConfiguration">
|
||||||
|
<state>
|
||||||
|
<option name="USE_PER_PROJECT_SETTINGS" value="true" />
|
||||||
|
</state>
|
||||||
|
</component>
|
||||||
Generated
+6
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="CompilerConfiguration">
|
||||||
|
<bytecodeTargetLevel target="21" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
+11
@@ -0,0 +1,11 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="deploymentTargetSelector">
|
||||||
|
<selectionStates>
|
||||||
|
<SelectionState runConfigName="app">
|
||||||
|
<option name="selectionMode" value="DROPDOWN" />
|
||||||
|
<DialogSelection />
|
||||||
|
</SelectionState>
|
||||||
|
</selectionStates>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
Generated
+13
@@ -0,0 +1,13 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="DeviceTable">
|
||||||
|
<option name="columnSorters">
|
||||||
|
<list>
|
||||||
|
<ColumnSorterState>
|
||||||
|
<option name="column" value="Name" />
|
||||||
|
<option name="order" value="ASCENDING" />
|
||||||
|
</ColumnSorterState>
|
||||||
|
</list>
|
||||||
|
</option>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
Generated
+19
@@ -0,0 +1,19 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="GradleMigrationSettings" migrationVersion="1" />
|
||||||
|
<component name="GradleSettings">
|
||||||
|
<option name="linkedExternalProjectsSettings">
|
||||||
|
<GradleProjectSettings>
|
||||||
|
<option name="testRunner" value="CHOOSE_PER_TEST" />
|
||||||
|
<option name="externalProjectPath" value="$PROJECT_DIR$" />
|
||||||
|
<option name="gradleJvm" value="#GRADLE_LOCAL_JAVA_HOME" />
|
||||||
|
<option name="modules">
|
||||||
|
<set>
|
||||||
|
<option value="$PROJECT_DIR$" />
|
||||||
|
<option value="$PROJECT_DIR$/app" />
|
||||||
|
</set>
|
||||||
|
</option>
|
||||||
|
</GradleProjectSettings>
|
||||||
|
</option>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
Generated
+10
@@ -0,0 +1,10 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="ProjectMigrations">
|
||||||
|
<option name="MigrateToGradleLocalJavaHome">
|
||||||
|
<set>
|
||||||
|
<option value="$PROJECT_DIR$" />
|
||||||
|
</set>
|
||||||
|
</option>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
Generated
+9
@@ -0,0 +1,9 @@
|
|||||||
|
<project version="4">
|
||||||
|
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
||||||
|
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="jbr-21" project-jdk-type="JavaSDK">
|
||||||
|
<output url="file://$PROJECT_DIR$/build/classes" />
|
||||||
|
</component>
|
||||||
|
<component name="ProjectType">
|
||||||
|
<option name="id" value="Android" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
Generated
+17
@@ -0,0 +1,17 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="RunConfigurationProducerService">
|
||||||
|
<option name="ignoredProducers">
|
||||||
|
<set>
|
||||||
|
<option value="com.intellij.execution.junit.AbstractAllInDirectoryConfigurationProducer" />
|
||||||
|
<option value="com.intellij.execution.junit.AllInPackageConfigurationProducer" />
|
||||||
|
<option value="com.intellij.execution.junit.PatternConfigurationProducer" />
|
||||||
|
<option value="com.intellij.execution.junit.TestInClassConfigurationProducer" />
|
||||||
|
<option value="com.intellij.execution.junit.UniqueIdConfigurationProducer" />
|
||||||
|
<option value="com.intellij.execution.junit.testDiscovery.JUnitTestDiscoveryConfigurationProducer" />
|
||||||
|
<option value="org.jetbrains.kotlin.idea.junit.KotlinJUnitRunConfigurationProducer" />
|
||||||
|
<option value="org.jetbrains.kotlin.idea.junit.KotlinPatternConfigurationProducer" />
|
||||||
|
</set>
|
||||||
|
</option>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
Generated
+6
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="VcsDirectoryMappings">
|
||||||
|
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
plugins {
|
plugins {
|
||||||
alias(libs.plugins.android.application)
|
alias(libs.plugins.android.application)
|
||||||
// kotlin-android NOT applied: AGP 9 enables built-in Kotlin by default,
|
// kotlin-android NOT applied: AGP 9 enables built-in Kotlin by default,
|
||||||
// and KSP 2.3.x supports it. serialization + compose-compiler are
|
// and KSP 2.3.x supports it (PR #2674, merged Oct 2025). serialization
|
||||||
// language-level Kotlin compiler plugins and still need explicit
|
// + compose-compiler are language-level Kotlin compiler plugins and
|
||||||
// application.
|
// still need explicit application.
|
||||||
alias(libs.plugins.kotlin.serialization)
|
alias(libs.plugins.kotlin.serialization)
|
||||||
alias(libs.plugins.compose.compiler)
|
alias(libs.plugins.compose.compiler)
|
||||||
alias(libs.plugins.ksp)
|
alias(libs.plugins.ksp)
|
||||||
@@ -21,19 +21,13 @@ android {
|
|||||||
applicationId = "com.fabledsword.minstrel"
|
applicationId = "com.fabledsword.minstrel"
|
||||||
minSdk = 26
|
minSdk = 26
|
||||||
targetSdk = 36
|
targetSdk = 36
|
||||||
// versionName / versionCode are released-build values injected by CI.
|
// versionName / versionCode are released-build values injected by
|
||||||
// Local / debug builds fall back to "dev" so the About card reads
|
// CI from the git tag + commit count. Local / debug builds fall
|
||||||
// honestly.
|
// back to "dev" so the About card reads honestly. Releases ship
|
||||||
//
|
// versionName="YYYY.MM.DD.<commits>" (e.g. "2026.06.02.142") and
|
||||||
// versionName is "YYYY.MM.DD.HHMM" from the COMMIT's timestamp, so
|
// versionCode=<commits>, which is monotonic forever and lets the
|
||||||
// every lane building this source reports the same string and the
|
// shared isVersionNewer comparator distinguish two same-day
|
||||||
// channel is the only thing that differs between them.
|
// re-cuts (the iteration suffix differs).
|
||||||
//
|
|
||||||
// versionCode is minutes since 2020-01-01 at BUILD time. It is the
|
|
||||||
// value the platform decides installs by, so it must be monotonic by
|
|
||||||
// construction. Not a commit count: that runs ahead on `dev`, so a dev
|
|
||||||
// build would outrank the `main` release meant to replace it and
|
|
||||||
// Android would refuse the install as a downgrade.
|
|
||||||
val versionNameOverride =
|
val versionNameOverride =
|
||||||
(project.findProperty("MINSTREL_VERSION_NAME") as String?)?.takeIf { it.isNotBlank() }
|
(project.findProperty("MINSTREL_VERSION_NAME") as String?)?.takeIf { it.isNotBlank() }
|
||||||
val versionCodeOverride =
|
val versionCodeOverride =
|
||||||
@@ -67,13 +61,9 @@ android {
|
|||||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||||
"proguard-rules.pro",
|
"proguard-rules.pro",
|
||||||
)
|
)
|
||||||
// Signed with the release key or not at all. Falling back to the
|
|
||||||
// debug key would turn a missing secret into a published APK that no
|
|
||||||
// install could ever update. An unsigned build installs nowhere, so
|
|
||||||
// the gap shows at once.
|
|
||||||
signingConfig =
|
signingConfig =
|
||||||
if (System.getenv("ANDROID_KEYSTORE_PATH").isNullOrEmpty()) {
|
if (System.getenv("ANDROID_KEYSTORE_PATH").isNullOrEmpty()) {
|
||||||
null
|
signingConfigs.getByName("debug")
|
||||||
} else {
|
} else {
|
||||||
signingConfigs.getByName("release")
|
signingConfigs.getByName("release")
|
||||||
}
|
}
|
||||||
@@ -100,42 +90,6 @@ android {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// The app's error messages are the web app's: web/src/lib/styles holds the
|
|
||||||
// copy for each server error code (error-copy.json) and the codes whose
|
|
||||||
// server message is appended (error-detail-codes.json). Both are copied in as
|
|
||||||
// Java resources, which ErrorCopy reads, so the two clients say the same thing
|
|
||||||
// and a new code is added once.
|
|
||||||
abstract class CopySharedCopyTask : DefaultTask() {
|
|
||||||
@get:InputFiles
|
|
||||||
@get:PathSensitive(PathSensitivity.NAME_ONLY)
|
|
||||||
abstract val sources: ConfigurableFileCollection
|
|
||||||
|
|
||||||
@get:OutputDirectory
|
|
||||||
abstract val outputDir: DirectoryProperty
|
|
||||||
|
|
||||||
@TaskAction
|
|
||||||
fun copy() {
|
|
||||||
val out = outputDir.get().asFile
|
|
||||||
out.deleteRecursively()
|
|
||||||
out.mkdirs()
|
|
||||||
sources.forEach { it.copyTo(File(out, it.name), overwrite = true) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
val copySharedCopy =
|
|
||||||
tasks.register<CopySharedCopyTask>("copySharedCopy") {
|
|
||||||
sources.from(
|
|
||||||
rootProject.file("../web/src/lib/styles/error-copy.json"),
|
|
||||||
rootProject.file("../web/src/lib/styles/error-detail-codes.json"),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
androidComponents {
|
|
||||||
onVariants { variant ->
|
|
||||||
variant.sources.resources?.addGeneratedSourceDirectory(copySharedCopy, CopySharedCopyTask::outputDir)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Kotlin 2.x: `kotlinOptions { ... }` inside `android { }` is gone; the
|
// Kotlin 2.x: `kotlinOptions { ... }` inside `android { }` is gone; the
|
||||||
// modern shape is the top-level `kotlin { compilerOptions { ... } }` block,
|
// modern shape is the top-level `kotlin { compilerOptions { ... } }` block,
|
||||||
// which works whether Kotlin comes from AGP 9's built-in path or an
|
// which works whether Kotlin comes from AGP 9's built-in path or an
|
||||||
@@ -196,6 +150,7 @@ dependencies {
|
|||||||
implementation(libs.compose.ui)
|
implementation(libs.compose.ui)
|
||||||
implementation(libs.compose.ui.graphics)
|
implementation(libs.compose.ui.graphics)
|
||||||
implementation(libs.compose.material3)
|
implementation(libs.compose.material3)
|
||||||
|
implementation(libs.compose.ui.text.google.fonts)
|
||||||
debugImplementation(libs.compose.ui.tooling)
|
debugImplementation(libs.compose.ui.tooling)
|
||||||
implementation(libs.compose.ui.tooling.preview)
|
implementation(libs.compose.ui.tooling.preview)
|
||||||
|
|
||||||
|
|||||||
@@ -8,10 +8,6 @@
|
|||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
|
||||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
<!-- Notifications when the app is closed: the delivery
|
|
||||||
service, and starting it again after a reboot or an update. -->
|
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
|
||||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
|
||||||
<!-- In-app self-update. REQUEST_INSTALL_PACKAGES lets us hand an APK to the
|
<!-- In-app self-update. REQUEST_INSTALL_PACKAGES lets us hand an APK to the
|
||||||
platform installer at all; UPDATE_PACKAGES_WITHOUT_USER_ACTION (API 31+)
|
platform installer at all; UPDATE_PACKAGES_WITHOUT_USER_ACTION (API 31+)
|
||||||
is what lets that install happen with NO confirm dialog. The platform
|
is what lets that install happen with NO confirm dialog. The platform
|
||||||
@@ -61,31 +57,11 @@
|
|||||||
</intent-filter>
|
</intent-filter>
|
||||||
</service>
|
</service>
|
||||||
|
|
||||||
<!-- Keeps the process alive so notifications arrive with the app
|
<!-- The FileProvider that used to live here existed solely to expose the
|
||||||
closed. specialUse: dataSync is stopped after six hours on
|
downloaded update APK as a content:// URI for the old ACTION_VIEW
|
||||||
Android 15, and shortService after three minutes. -->
|
install intent. A PackageInstaller session takes a stream instead,
|
||||||
<service
|
so both the provider and res/xml/file_paths.xml are gone — nothing
|
||||||
android:name=".notifications.delivery.DeliveryService"
|
else in the app ever used that authority. -->
|
||||||
android:exported="false"
|
|
||||||
android:foregroundServiceType="specialUse">
|
|
||||||
<property
|
|
||||||
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
|
|
||||||
android:value="Maintains the connection to the user's own Minstrel server that delivers their notifications, in place of a third-party push service." />
|
|
||||||
</service>
|
|
||||||
|
|
||||||
<!-- Starts delivery after a reboot or an update; both broadcasts may
|
|
||||||
start a foreground service from the background. -->
|
|
||||||
<receiver
|
|
||||||
android:name=".notifications.delivery.BootReceiver"
|
|
||||||
android:exported="true">
|
|
||||||
<intent-filter>
|
|
||||||
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
|
||||||
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
|
|
||||||
</intent-filter>
|
|
||||||
</receiver>
|
|
||||||
|
|
||||||
<!-- No FileProvider: the self-update streams the downloaded APK into a
|
|
||||||
PackageInstaller session, so nothing needs a content:// URI. -->
|
|
||||||
|
|
||||||
<!-- On-demand WorkManager initialization: MinstrelApplication
|
<!-- On-demand WorkManager initialization: MinstrelApplication
|
||||||
implements Configuration.Provider and supplies the
|
implements Configuration.Provider and supplies the
|
||||||
|
|||||||
@@ -1,14 +1,10 @@
|
|||||||
package com.fabledsword.minstrel
|
package com.fabledsword.minstrel
|
||||||
|
|
||||||
import android.Manifest
|
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.content.pm.PackageManager
|
|
||||||
import android.os.Build
|
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import androidx.activity.ComponentActivity
|
import androidx.activity.ComponentActivity
|
||||||
import androidx.activity.compose.setContent
|
import androidx.activity.compose.setContent
|
||||||
import androidx.activity.enableEdgeToEdge
|
import androidx.activity.enableEdgeToEdge
|
||||||
import androidx.activity.result.contract.ActivityResultContracts
|
|
||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.material3.CircularProgressIndicator
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
@@ -20,13 +16,9 @@ import androidx.compose.runtime.LaunchedEffect
|
|||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.core.content.ContextCompat
|
|
||||||
import androidx.hilt.navigation.compose.hiltViewModel
|
import androidx.hilt.navigation.compose.hiltViewModel
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import androidx.lifecycle.lifecycleScope
|
|
||||||
import androidx.navigation.NavHostController
|
|
||||||
import androidx.navigation.compose.rememberNavController
|
import androidx.navigation.compose.rememberNavController
|
||||||
import com.fabledsword.minstrel.auth.AuthStore
|
|
||||||
import com.fabledsword.minstrel.auth.ui.AuthGateViewModel
|
import com.fabledsword.minstrel.auth.ui.AuthGateViewModel
|
||||||
import com.fabledsword.minstrel.cache.CachedTrackIds
|
import com.fabledsword.minstrel.cache.CachedTrackIds
|
||||||
import com.fabledsword.minstrel.connectivity.LocalServerHealth
|
import com.fabledsword.minstrel.connectivity.LocalServerHealth
|
||||||
@@ -34,12 +26,8 @@ import com.fabledsword.minstrel.connectivity.ServerHealth
|
|||||||
import com.fabledsword.minstrel.connectivity.NetworkStatusController
|
import com.fabledsword.minstrel.connectivity.NetworkStatusController
|
||||||
import com.fabledsword.minstrel.nav.DetailSeedCache
|
import com.fabledsword.minstrel.nav.DetailSeedCache
|
||||||
import com.fabledsword.minstrel.nav.LocalDetailSeedCache
|
import com.fabledsword.minstrel.nav.LocalDetailSeedCache
|
||||||
import com.fabledsword.minstrel.nav.Login
|
|
||||||
import com.fabledsword.minstrel.nav.MinstrelNavGraph
|
import com.fabledsword.minstrel.nav.MinstrelNavGraph
|
||||||
import com.fabledsword.minstrel.nav.Notifications
|
|
||||||
import com.fabledsword.minstrel.nav.NowPlaying
|
import com.fabledsword.minstrel.nav.NowPlaying
|
||||||
import com.fabledsword.minstrel.notifications.delivery.deliveryWanted
|
|
||||||
import com.fabledsword.minstrel.notifications.ui.routeForLink
|
|
||||||
import com.fabledsword.minstrel.shared.widgets.LocalCachedTrackIds
|
import com.fabledsword.minstrel.shared.widgets.LocalCachedTrackIds
|
||||||
import com.fabledsword.minstrel.theme.MinstrelTheme
|
import com.fabledsword.minstrel.theme.MinstrelTheme
|
||||||
import com.fabledsword.minstrel.theme.ThemePreferenceViewModel
|
import com.fabledsword.minstrel.theme.ThemePreferenceViewModel
|
||||||
@@ -47,10 +35,6 @@ import dagger.hilt.android.AndroidEntryPoint
|
|||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
import kotlinx.coroutines.flow.combine
|
|
||||||
import kotlinx.coroutines.flow.first
|
|
||||||
import kotlinx.coroutines.flow.map
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
@AndroidEntryPoint
|
@AndroidEntryPoint
|
||||||
@@ -58,72 +42,41 @@ class MainActivity : ComponentActivity() {
|
|||||||
@Inject lateinit var seedCache: DetailSeedCache
|
@Inject lateinit var seedCache: DetailSeedCache
|
||||||
@Inject lateinit var cachedTrackIds: CachedTrackIds
|
@Inject lateinit var cachedTrackIds: CachedTrackIds
|
||||||
@Inject lateinit var serverHealth: NetworkStatusController
|
@Inject lateinit var serverHealth: NetworkStatusController
|
||||||
@Inject lateinit var authStore: AuthStore
|
|
||||||
|
|
||||||
// Set when the user taps a notification: the media one asks for the full
|
// Flipped to true when the user taps the media notification (or
|
||||||
// player, a Minstrel notice for what it is about. The App composable
|
// any other entry point that asks for the full player). The App
|
||||||
// navigates there once the NavHost is ready, then calls back to clear it
|
// composable observes this, navigates to NowPlaying once the
|
||||||
// so the navigation doesn't re-fire on the next recomposition.
|
// NavHost is ready, then calls back to reset the flag so the
|
||||||
private val pendingRoute = MutableStateFlow<Any?>(null)
|
// navigation doesn't re-fire on the next recomposition.
|
||||||
|
private val pendingOpenNowPlaying = MutableStateFlow(false)
|
||||||
// The answer needs no handling: the system remembers it, and the
|
|
||||||
// notification settings screen reads it on every resume.
|
|
||||||
private val askToNotify = registerForActivityResult(ActivityResultContracts.RequestPermission()) { }
|
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
enableEdgeToEdge()
|
enableEdgeToEdge()
|
||||||
consumeRouteIntent(intent)
|
consumeOpenNowPlayingIntent(intent)
|
||||||
askToNotifyOnceWanted()
|
|
||||||
setContent {
|
setContent {
|
||||||
App(
|
App(
|
||||||
seedCache = seedCache,
|
seedCache = seedCache,
|
||||||
cachedTrackIds = cachedTrackIds,
|
cachedTrackIds = cachedTrackIds,
|
||||||
serverHealth = serverHealth,
|
serverHealth = serverHealth,
|
||||||
pendingRoute = pendingRoute.asStateFlow(),
|
pendingOpenNowPlaying = pendingOpenNowPlaying.asStateFlow(),
|
||||||
onOpenedRoute = { pendingRoute.value = null },
|
onOpenedNowPlaying = { pendingOpenNowPlaying.value = false },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onNewIntent(intent: Intent) {
|
override fun onNewIntent(intent: Intent) {
|
||||||
super.onNewIntent(intent)
|
super.onNewIntent(intent)
|
||||||
consumeRouteIntent(intent)
|
consumeOpenNowPlayingIntent(intent)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun consumeRouteIntent(intent: Intent?) {
|
private fun consumeOpenNowPlayingIntent(intent: Intent?) {
|
||||||
if (intent == null) return
|
if (intent?.getBooleanExtra(EXTRA_OPEN_NOW_PLAYING, false) == true) {
|
||||||
if (intent.getBooleanExtra(EXTRA_OPEN_NOW_PLAYING, false)) {
|
pendingOpenNowPlaying.value = true
|
||||||
pendingRoute.value = NowPlaying
|
|
||||||
// Strip the extra so a subsequent config-change recreation
|
// Strip the extra so a subsequent config-change recreation
|
||||||
// doesn't re-trigger the navigation.
|
// doesn't re-trigger the navigation.
|
||||||
intent.removeExtra(EXTRA_OPEN_NOW_PLAYING)
|
intent.removeExtra(EXTRA_OPEN_NOW_PLAYING)
|
||||||
}
|
}
|
||||||
intent.getStringExtra(EXTRA_NOTIFICATION_LINK)?.let { link ->
|
|
||||||
// A notice the app has no screen for, or a pile of them, opens
|
|
||||||
// the inbox.
|
|
||||||
pendingRoute.value = routeForLink(link) ?: Notifications
|
|
||||||
intent.removeExtra(EXTRA_NOTIFICATION_LINK)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Android 13+ asks before an app may post notifications.
|
|
||||||
* Asked once delivery is wanted (signed in, background delivery on),
|
|
||||||
* each launch until answered: after a second "no" the system stops
|
|
||||||
* showing the prompt by itself, and Settings → Notifications links to
|
|
||||||
* the system page.
|
|
||||||
*/
|
|
||||||
private fun askToNotifyOnceWanted() {
|
|
||||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return
|
|
||||||
lifecycleScope.launch {
|
|
||||||
val signedIn = authStore.sessionCookie.map { !it.isNullOrEmpty() }
|
|
||||||
combine(signedIn, authStore.backgroundDelivery, ::deliveryWanted).first { it }
|
|
||||||
val permission = Manifest.permission.POST_NOTIFICATIONS
|
|
||||||
val granted = ContextCompat.checkSelfPermission(this@MainActivity, permission) ==
|
|
||||||
PackageManager.PERMISSION_GRANTED
|
|
||||||
if (!granted) askToNotify.launch(permission)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
@@ -131,10 +84,6 @@ class MainActivity : ComponentActivity() {
|
|||||||
* so a media-notification tap lands on the full NowPlaying screen
|
* so a media-notification tap lands on the full NowPlaying screen
|
||||||
* instead of whatever shell route MainActivity last rendered. */
|
* instead of whatever shell route MainActivity last rendered. */
|
||||||
const val EXTRA_OPEN_NOW_PLAYING = "com.fabledsword.minstrel.action.OPEN_NOW_PLAYING"
|
const val EXTRA_OPEN_NOW_PLAYING = "com.fabledsword.minstrel.action.OPEN_NOW_PLAYING"
|
||||||
|
|
||||||
/** PendingIntent extra on a Minstrel notice: the web path it links to,
|
|
||||||
* or empty for a pile, which opens the inbox. */
|
|
||||||
const val EXTRA_NOTIFICATION_LINK = "com.fabledsword.minstrel.action.NOTIFICATION_LINK"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -143,15 +92,15 @@ private fun App(
|
|||||||
seedCache: DetailSeedCache,
|
seedCache: DetailSeedCache,
|
||||||
cachedTrackIds: CachedTrackIds,
|
cachedTrackIds: CachedTrackIds,
|
||||||
serverHealth: NetworkStatusController,
|
serverHealth: NetworkStatusController,
|
||||||
pendingRoute: StateFlow<Any?>,
|
pendingOpenNowPlaying: StateFlow<Boolean>,
|
||||||
onOpenedRoute: () -> Unit,
|
onOpenedNowPlaying: () -> Unit,
|
||||||
themeVm: ThemePreferenceViewModel = hiltViewModel(),
|
themeVm: ThemePreferenceViewModel = hiltViewModel(),
|
||||||
gate: AuthGateViewModel = hiltViewModel(),
|
gate: AuthGateViewModel = hiltViewModel(),
|
||||||
) {
|
) {
|
||||||
val theme by themeVm.themeMode.collectAsStateWithLifecycle()
|
val theme by themeVm.themeMode.collectAsStateWithLifecycle()
|
||||||
val cached by cachedTrackIds.ids.collectAsStateWithLifecycle()
|
val cached by cachedTrackIds.ids.collectAsStateWithLifecycle()
|
||||||
val health: ServerHealth by serverHealth.state.collectAsStateWithLifecycle()
|
val health: ServerHealth by serverHealth.state.collectAsStateWithLifecycle()
|
||||||
val pending by pendingRoute.collectAsStateWithLifecycle()
|
val pending by pendingOpenNowPlaying.collectAsStateWithLifecycle()
|
||||||
MinstrelTheme(darkOverride = theme.toDarkOverride()) {
|
MinstrelTheme(darkOverride = theme.toDarkOverride()) {
|
||||||
CompositionLocalProvider(
|
CompositionLocalProvider(
|
||||||
LocalDetailSeedCache provides seedCache,
|
LocalDetailSeedCache provides seedCache,
|
||||||
@@ -170,16 +119,17 @@ private fun App(
|
|||||||
// Queue / unauthenticated) bypass the shell entirely.
|
// Queue / unauthenticated) bypass the shell entirely.
|
||||||
val navController = rememberNavController()
|
val navController = rememberNavController()
|
||||||
// Honour a pending notification-tap once the NavHost is
|
// Honour a pending notification-tap once the NavHost is
|
||||||
// mounted. launchSingleTop avoids stacking copies of a
|
// mounted. launchSingleTop avoids stacking copies of
|
||||||
// screen if the user taps the notification while already
|
// NowPlaying if the user taps the notification while
|
||||||
// on it; the callback clears it so a later recomposition
|
// already on it; the callback clears the flag so a later
|
||||||
// (config change, theme switch) doesn't re-navigate.
|
// recomposition (config change, theme switch) doesn't
|
||||||
|
// re-navigate.
|
||||||
LaunchedEffect(pending, navController) {
|
LaunchedEffect(pending, navController) {
|
||||||
val route = pending ?: return@LaunchedEffect
|
if (pending) {
|
||||||
navController.navigate(route) { launchSingleTop = true }
|
navController.navigate(NowPlaying) { launchSingleTop = true }
|
||||||
onOpenedRoute()
|
onOpenedNowPlaying()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
SignInWhenSessionRejected(gate, navController)
|
|
||||||
MinstrelNavGraph(
|
MinstrelNavGraph(
|
||||||
navController = navController,
|
navController = navController,
|
||||||
startDestination = resolved,
|
startDestination = resolved,
|
||||||
@@ -190,24 +140,6 @@ private fun App(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* When the server ends the session while the app is in use, opens the
|
|
||||||
* sign-in screen rather than leaving the user on screens whose every
|
|
||||||
* request fails.
|
|
||||||
*/
|
|
||||||
@Composable
|
|
||||||
private fun SignInWhenSessionRejected(gate: AuthGateViewModel, navController: NavHostController) {
|
|
||||||
val sessionRejected by gate.sessionRejected.collectAsStateWithLifecycle()
|
|
||||||
LaunchedEffect(sessionRejected, navController) {
|
|
||||||
if (!sessionRejected) return@LaunchedEffect
|
|
||||||
navController.navigate(Login) {
|
|
||||||
popUpTo(0) { inclusive = true }
|
|
||||||
launchSingleTop = true
|
|
||||||
}
|
|
||||||
gate.consumeSessionRejected()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun BootSplash() {
|
private fun BootSplash() {
|
||||||
Surface(
|
Surface(
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import coil3.SingletonImageLoader
|
|||||||
import coil3.network.okhttp.OkHttpNetworkFetcherFactory
|
import coil3.network.okhttp.OkHttpNetworkFetcherFactory
|
||||||
import coil3.request.crossfade
|
import coil3.request.crossfade
|
||||||
import com.fabledsword.minstrel.cache.CacheIndexer
|
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.mutations.MutationReplayer
|
||||||
import com.fabledsword.minstrel.cache.sync.SyncController
|
import com.fabledsword.minstrel.cache.sync.SyncController
|
||||||
import com.fabledsword.minstrel.di.ApplicationScope
|
import com.fabledsword.minstrel.di.ApplicationScope
|
||||||
@@ -17,13 +16,12 @@ import com.fabledsword.minstrel.diagnostics.DiagnosticsUploader
|
|||||||
import com.fabledsword.minstrel.events.EventsStream
|
import com.fabledsword.minstrel.events.EventsStream
|
||||||
import com.fabledsword.minstrel.events.LiveEventsDispatcher
|
import com.fabledsword.minstrel.events.LiveEventsDispatcher
|
||||||
import com.fabledsword.minstrel.metadata.FreshnessSweeper
|
import com.fabledsword.minstrel.metadata.FreshnessSweeper
|
||||||
import com.fabledsword.minstrel.notifications.delivery.DeliveryLauncher
|
|
||||||
import com.fabledsword.minstrel.player.AudioPrefetcher
|
import com.fabledsword.minstrel.player.AudioPrefetcher
|
||||||
import com.fabledsword.minstrel.player.CoverPrefetcher
|
import com.fabledsword.minstrel.player.CoverPrefetcher
|
||||||
import com.fabledsword.minstrel.player.LikedAudioPinner
|
|
||||||
import com.fabledsword.minstrel.player.PlayEventsReporter
|
import com.fabledsword.minstrel.player.PlayEventsReporter
|
||||||
import com.fabledsword.minstrel.player.PlaybackErrorReporter
|
import com.fabledsword.minstrel.player.PlaybackErrorReporter
|
||||||
import com.fabledsword.minstrel.player.ResumeController
|
import com.fabledsword.minstrel.player.ResumeController
|
||||||
|
import com.fabledsword.minstrel.update.data.UpdateBannerController
|
||||||
import com.fabledsword.minstrel.connectivity.NetworkStatusController
|
import com.fabledsword.minstrel.connectivity.NetworkStatusController
|
||||||
import dagger.hilt.android.HiltAndroidApp
|
import dagger.hilt.android.HiltAndroidApp
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
@@ -77,14 +75,6 @@ class MinstrelApplication :
|
|||||||
*/
|
*/
|
||||||
@Suppress("unused") @Inject lateinit var mutationReplayer: MutationReplayer
|
@Suppress("unused") @Inject lateinit var mutationReplayer: MutationReplayer
|
||||||
|
|
||||||
/**
|
|
||||||
* Same construct-the-singleton trick — DeliveryLauncher starts and stops
|
|
||||||
* the background-delivery service and runs the notification catch-up on
|
|
||||||
* every nudge and reconnect. Without this @Inject no phone
|
|
||||||
* notification would ever be posted.
|
|
||||||
*/
|
|
||||||
@Suppress("unused") @Inject lateinit var deliveryLauncher: DeliveryLauncher
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Same construct-the-singleton trick — PlayEventsReporter's init
|
* Same construct-the-singleton trick — PlayEventsReporter's init
|
||||||
* block subscribes to PlayerController.uiState and reports the
|
* block subscribes to PlayerController.uiState and reports the
|
||||||
@@ -121,21 +111,6 @@ class MinstrelApplication :
|
|||||||
*/
|
*/
|
||||||
@Suppress("unused") @Inject lateinit var cacheIndexer: CacheIndexer
|
@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
|
* Same construct-the-singleton trick — AudioPrefetcher's init
|
||||||
* block subscribes to PlayerController.uiState +
|
* block subscribes to PlayerController.uiState +
|
||||||
@@ -154,6 +129,14 @@ class MinstrelApplication :
|
|||||||
*/
|
*/
|
||||||
@Suppress("unused") @Inject lateinit var networkStatusController: NetworkStatusController
|
@Suppress("unused") @Inject lateinit var networkStatusController: NetworkStatusController
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Same construct-the-singleton trick — UpdateBannerController polls
|
||||||
|
* /api/client/version at launch + every 24h and drives the shell's
|
||||||
|
* soft "update available" banner. Without this @Inject the poll
|
||||||
|
* loop would never start and the banner would never surface.
|
||||||
|
*/
|
||||||
|
@Suppress("unused") @Inject lateinit var updateBannerController: UpdateBannerController
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Same construct-the-singleton trick — FreshnessSweeper's init
|
* Same construct-the-singleton trick — FreshnessSweeper's init
|
||||||
* block starts a 30-min sweep loop that re-fetches cached
|
* block starts a 30-min sweep loop that re-fetches cached
|
||||||
@@ -179,7 +162,7 @@ class MinstrelApplication :
|
|||||||
*/
|
*/
|
||||||
@Suppress("unused") @Inject lateinit var liveEventsDispatcher: LiveEventsDispatcher
|
@Suppress("unused") @Inject lateinit var liveEventsDispatcher: LiveEventsDispatcher
|
||||||
|
|
||||||
// Device diagnostics. The reporter gates itself on the account's
|
// Device diagnostics (M9). The reporter gates itself on the account's
|
||||||
// debug flag; the uploader drains its buffer on a tick / recovery.
|
// debug flag; the uploader drains its buffer on a tick / recovery.
|
||||||
@Suppress("unused") @Inject lateinit var diagnosticsReporter: DiagnosticsReporter
|
@Suppress("unused") @Inject lateinit var diagnosticsReporter: DiagnosticsReporter
|
||||||
@Suppress("unused") @Inject lateinit var diagnosticsUploader: DiagnosticsUploader
|
@Suppress("unused") @Inject lateinit var diagnosticsUploader: DiagnosticsUploader
|
||||||
@@ -189,7 +172,7 @@ class MinstrelApplication :
|
|||||||
override fun onCreate() {
|
override fun onCreate() {
|
||||||
super.onCreate()
|
super.onCreate()
|
||||||
// Debug builds get the full DebugTree (verbose). Release builds
|
// Debug builds get the full DebugTree (verbose). Release builds
|
||||||
// get a WARN+ tree so diagnosis via `adb logcat`
|
// get a WARN+ tree so operator-driven diagnosis via `adb logcat`
|
||||||
// still surfaces UPnP / cast failures, OkHttp errors, and our
|
// still surfaces UPnP / cast failures, OkHttp errors, and our
|
||||||
// own Timber.w / Timber.e calls — without the chatty DEBUG /
|
// own Timber.w / Timber.e calls — without the chatty DEBUG /
|
||||||
// INFO traffic flooding the buffer in production.
|
// INFO traffic flooding the buffer in production.
|
||||||
@@ -237,9 +220,10 @@ class MinstrelApplication :
|
|||||||
* before Coil makes its first request.
|
* before Coil makes its first request.
|
||||||
*
|
*
|
||||||
* Crossfade is set here rather than per-call so every cover surface
|
* Crossfade is set here rather than per-call so every cover surface
|
||||||
* in the app fades its artwork in instead of snapping it, and
|
* in the app fades its artwork in instead of snapping it. Art
|
||||||
* `ServerImage` fades its placeholder out over the same window so the
|
* landing a beat after its tile was the most visible pop-in on Home
|
||||||
* two read as one cross-dissolve.
|
* (issue #2327); `ServerImage` fades its placeholder out over the
|
||||||
|
* same window so the two read as one cross-dissolve.
|
||||||
*/
|
*/
|
||||||
override fun newImageLoader(context: android.content.Context): ImageLoader =
|
override fun newImageLoader(context: android.content.Context): ImageLoader =
|
||||||
ImageLoader.Builder(context)
|
ImageLoader.Builder(context)
|
||||||
|
|||||||
+7
-6
@@ -11,10 +11,10 @@ import javax.inject.Inject
|
|||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Read-through accessor for the admin Reports queue. No Room cache: it is an
|
* Read-through accessor for the admin quarantine queue. Mirrors the
|
||||||
* admin's live work list, read fresh each time, and its actions go straight
|
* Flutter `AdminQuarantineController`. No Room cache — same rationale
|
||||||
* to the server, so offline they fail with the reason rather than queueing.
|
* as AdminRequests. Three resolution actions all delete the row from
|
||||||
* Each action takes the row off the queue once the server accepts it.
|
* the queue once the server accepts them.
|
||||||
*/
|
*/
|
||||||
@Singleton
|
@Singleton
|
||||||
class AdminQuarantineRepository @Inject constructor(
|
class AdminQuarantineRepository @Inject constructor(
|
||||||
@@ -26,9 +26,9 @@ class AdminQuarantineRepository @Inject constructor(
|
|||||||
|
|
||||||
suspend fun resolve(trackId: String) = api.resolve(trackId)
|
suspend fun resolve(trackId: String) = api.resolve(trackId)
|
||||||
|
|
||||||
suspend fun removeFile(trackId: String) = api.removeFile(trackId)
|
|
||||||
|
|
||||||
suspend fun deleteFile(trackId: String) = api.deleteFile(trackId)
|
suspend fun deleteFile(trackId: String) = api.deleteFile(trackId)
|
||||||
|
|
||||||
|
suspend fun deleteViaLidarr(trackId: String) = api.deleteViaLidarr(trackId)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Mappers ──
|
// ── Mappers ──
|
||||||
@@ -49,6 +49,7 @@ private fun AdminQuarantineItemWire.toDomain(): AdminQuarantineItemRef =
|
|||||||
artistName = artistName,
|
artistName = artistName,
|
||||||
albumTitle = albumTitle,
|
albumTitle = albumTitle,
|
||||||
albumId = albumId,
|
albumId = albumId,
|
||||||
|
lidarrAlbumMbid = lidarrAlbumMbid,
|
||||||
reportCount = reportCount,
|
reportCount = reportCount,
|
||||||
latestAt = latestAt,
|
latestAt = latestAt,
|
||||||
reasonCounts = reasonCounts,
|
reasonCounts = reasonCounts,
|
||||||
|
|||||||
+51
@@ -0,0 +1,51 @@
|
|||||||
|
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.
|
||||||
|
* Mirrors `flutter_client/lib/admin/admin_providers.dart`'s
|
||||||
|
* AdminRequestsController.
|
||||||
|
*
|
||||||
|
* No Room caching — admin actions are infrequent and don't benefit
|
||||||
|
* from offline scrollback. `approve` and `reject` fire direct REST
|
||||||
|
* (no mutation queue) because operator 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,
|
||||||
|
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
-1
@@ -12,7 +12,7 @@ import javax.inject.Inject
|
|||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Read-through accessor for the tag-enrichment provider settings.
|
* Read-through accessor for the tag-enrichment provider settings (#1521).
|
||||||
* No Room caching — admin settings are infrequent point-and-shoot edits;
|
* No Room caching — admin settings are infrequent point-and-shoot edits;
|
||||||
* mutations fire direct REST and the ViewModel reconciles on failure.
|
* mutations fire direct REST and the ViewModel reconciles on failure.
|
||||||
* Exceptions propagate to the ViewModel (which maps them via ErrorCopy).
|
* Exceptions propagate to the ViewModel (which maps them via ErrorCopy).
|
||||||
|
|||||||
+7
-2
@@ -3,6 +3,7 @@ package com.fabledsword.minstrel.admin.data
|
|||||||
import com.fabledsword.minstrel.api.endpoints.AdminUsersApi
|
import com.fabledsword.minstrel.api.endpoints.AdminUsersApi
|
||||||
import com.fabledsword.minstrel.api.endpoints.ResetPasswordBody
|
import com.fabledsword.minstrel.api.endpoints.ResetPasswordBody
|
||||||
import com.fabledsword.minstrel.api.endpoints.SetAdminBody
|
import com.fabledsword.minstrel.api.endpoints.SetAdminBody
|
||||||
|
import com.fabledsword.minstrel.api.endpoints.SetAutoApproveBody
|
||||||
import com.fabledsword.minstrel.models.AdminUserRef
|
import com.fabledsword.minstrel.models.AdminUserRef
|
||||||
import com.fabledsword.minstrel.models.wire.AdminUserWire
|
import com.fabledsword.minstrel.models.wire.AdminUserWire
|
||||||
import retrofit2.Retrofit
|
import retrofit2.Retrofit
|
||||||
@@ -12,8 +13,8 @@ import javax.inject.Singleton
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Read-through accessor for the admin users list + the four per-user
|
* Read-through accessor for the admin users list + the four per-user
|
||||||
* mutations. Same no-Room-cache, no-MutationQueue pattern as the other
|
* mutations. Mirrors Flutter's `AdminUsersController`. Same
|
||||||
* admin repositories.
|
* no-Room-cache, no-MutationQueue pattern as the other admin slices.
|
||||||
*/
|
*/
|
||||||
@Singleton
|
@Singleton
|
||||||
class AdminUsersRepository @Inject constructor(
|
class AdminUsersRepository @Inject constructor(
|
||||||
@@ -26,6 +27,9 @@ class AdminUsersRepository @Inject constructor(
|
|||||||
suspend fun setAdmin(id: String, isAdmin: Boolean) =
|
suspend fun setAdmin(id: String, isAdmin: Boolean) =
|
||||||
api.setAdmin(id, SetAdminBody(isAdmin))
|
api.setAdmin(id, SetAdminBody(isAdmin))
|
||||||
|
|
||||||
|
suspend fun setAutoApprove(id: String, autoApprove: Boolean) =
|
||||||
|
api.setAutoApprove(id, SetAutoApproveBody(autoApprove))
|
||||||
|
|
||||||
suspend fun resetPassword(id: String, newPassword: String) =
|
suspend fun resetPassword(id: String, newPassword: String) =
|
||||||
api.resetPassword(id, ResetPasswordBody(newPassword))
|
api.resetPassword(id, ResetPasswordBody(newPassword))
|
||||||
|
|
||||||
@@ -37,5 +41,6 @@ private fun AdminUserWire.toDomain(): AdminUserRef = AdminUserRef(
|
|||||||
username = username,
|
username = username,
|
||||||
displayName = displayName,
|
displayName = displayName,
|
||||||
isAdmin = isAdmin,
|
isAdmin = isAdmin,
|
||||||
|
autoApproveRequests = autoApproveRequests,
|
||||||
createdAt = createdAt,
|
createdAt = createdAt,
|
||||||
)
|
)
|
||||||
|
|||||||
+1
-1
@@ -39,7 +39,7 @@ class AdminInvitesViewModel @Inject constructor(
|
|||||||
|
|
||||||
init {
|
init {
|
||||||
refresh()
|
refresh()
|
||||||
// Screen-level auto-recovery: reload a failed list
|
// Screen-level auto-recovery (issue #1245): reload a failed list
|
||||||
// when server health returns instead of waiting for a manual pull.
|
// when server health returns instead of waiting for a manual pull.
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
networkStatus.recoveries().collect {
|
networkStatus.recoveries().collect {
|
||||||
|
|||||||
@@ -26,20 +26,21 @@ import androidx.lifecycle.ViewModel
|
|||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
import androidx.navigation.NavHostController
|
import androidx.navigation.NavHostController
|
||||||
|
import com.composables.icons.lucide.Inbox
|
||||||
import com.composables.icons.lucide.Lucide
|
import com.composables.icons.lucide.Lucide
|
||||||
import com.composables.icons.lucide.Music
|
import com.composables.icons.lucide.Music
|
||||||
import com.composables.icons.lucide.TriangleAlert
|
import com.composables.icons.lucide.TriangleAlert
|
||||||
import com.composables.icons.lucide.Users
|
import com.composables.icons.lucide.Users
|
||||||
import com.fabledsword.minstrel.admin.data.AdminQuarantineRepository
|
import com.fabledsword.minstrel.admin.data.AdminQuarantineRepository
|
||||||
|
import com.fabledsword.minstrel.admin.data.AdminRequestsRepository
|
||||||
import com.fabledsword.minstrel.admin.data.AdminTagSourcesRepository
|
import com.fabledsword.minstrel.admin.data.AdminTagSourcesRepository
|
||||||
import com.fabledsword.minstrel.admin.data.AdminUsersRepository
|
import com.fabledsword.minstrel.admin.data.AdminUsersRepository
|
||||||
|
import com.fabledsword.minstrel.api.ErrorCopy
|
||||||
import com.fabledsword.minstrel.nav.Admin
|
import com.fabledsword.minstrel.nav.Admin
|
||||||
import com.fabledsword.minstrel.nav.AdminQuarantine
|
import com.fabledsword.minstrel.nav.AdminQuarantine
|
||||||
|
import com.fabledsword.minstrel.nav.AdminRequests
|
||||||
import com.fabledsword.minstrel.nav.AdminTagSources
|
import com.fabledsword.minstrel.nav.AdminTagSources
|
||||||
import com.fabledsword.minstrel.nav.AdminUsers
|
import com.fabledsword.minstrel.nav.AdminUsers
|
||||||
import com.fabledsword.minstrel.shared.UiState
|
|
||||||
import com.fabledsword.minstrel.shared.loadUiState
|
|
||||||
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
|
|
||||||
import com.fabledsword.minstrel.shared.widgets.EmptyState
|
import com.fabledsword.minstrel.shared.widgets.EmptyState
|
||||||
import com.fabledsword.minstrel.shared.widgets.LoadingCentered
|
import com.fabledsword.minstrel.shared.widgets.LoadingCentered
|
||||||
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
|
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
|
||||||
@@ -56,21 +57,25 @@ import javax.inject.Inject
|
|||||||
|
|
||||||
// ─── State ───────────────────────────────────────────────────────────
|
// ─── State ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
data class AdminCounts(val quarantine: Int, val users: Int, val tagSources: Int)
|
data class AdminCounts(val requests: Int, val quarantine: Int, val users: Int, val tagSources: Int)
|
||||||
|
|
||||||
/** The admin landing's counts, as the shared [UiState] (never Empty: it always has counts). */
|
sealed interface AdminLandingUiState {
|
||||||
typealias AdminLandingUiState = UiState<AdminCounts>
|
data object Loading : AdminLandingUiState
|
||||||
|
data class Success(val counts: AdminCounts) : AdminLandingUiState
|
||||||
|
data class Error(val message: String) : AdminLandingUiState
|
||||||
|
}
|
||||||
|
|
||||||
// ─── ViewModel ───────────────────────────────────────────────────────
|
// ─── ViewModel ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
@HiltViewModel
|
@HiltViewModel
|
||||||
class AdminLandingViewModel @Inject constructor(
|
class AdminLandingViewModel @Inject constructor(
|
||||||
|
private val requestsRepo: AdminRequestsRepository,
|
||||||
private val quarantineRepo: AdminQuarantineRepository,
|
private val quarantineRepo: AdminQuarantineRepository,
|
||||||
private val usersRepo: AdminUsersRepository,
|
private val usersRepo: AdminUsersRepository,
|
||||||
private val tagSourcesRepo: AdminTagSourcesRepository,
|
private val tagSourcesRepo: AdminTagSourcesRepository,
|
||||||
) : ViewModel() {
|
) : ViewModel() {
|
||||||
|
|
||||||
private val internal = MutableStateFlow<AdminLandingUiState>(UiState.Loading)
|
private val internal = MutableStateFlow<AdminLandingUiState>(AdminLandingUiState.Loading)
|
||||||
val uiState: StateFlow<AdminLandingUiState> = internal.asStateFlow()
|
val uiState: StateFlow<AdminLandingUiState> = internal.asStateFlow()
|
||||||
|
|
||||||
init {
|
init {
|
||||||
@@ -78,14 +83,22 @@ class AdminLandingViewModel @Inject constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun refresh(): Job = viewModelScope.launch {
|
fun refresh(): Job = viewModelScope.launch {
|
||||||
internal.value = UiState.Loading
|
internal.value = AdminLandingUiState.Loading
|
||||||
internal.value = loadUiState {
|
try {
|
||||||
coroutineScope {
|
val counts = coroutineScope {
|
||||||
|
val req = async { requestsRepo.list().size }
|
||||||
val qua = async { quarantineRepo.list().size }
|
val qua = async { quarantineRepo.list().size }
|
||||||
val usr = async { usersRepo.list().size }
|
val usr = async { usersRepo.list().size }
|
||||||
val tag = async { tagSourcesRepo.list().count { it.enabled } }
|
val tag = async { tagSourcesRepo.list().count { it.enabled } }
|
||||||
UiState.Success(AdminCounts(qua.await(), usr.await(), tag.await()))
|
AdminCounts(req.await(), qua.await(), usr.await(), tag.await())
|
||||||
}
|
}
|
||||||
|
internal.value = AdminLandingUiState.Success(counts)
|
||||||
|
} catch (
|
||||||
|
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
||||||
|
) {
|
||||||
|
internal.value = AdminLandingUiState.Error(
|
||||||
|
ErrorCopy.fromThrowable(e),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -99,7 +112,6 @@ fun AdminLandingScreen(
|
|||||||
) {
|
) {
|
||||||
val state by viewModel.uiState.collectAsStateWithLifecycle()
|
val state by viewModel.uiState.collectAsStateWithLifecycle()
|
||||||
Scaffold(
|
Scaffold(
|
||||||
contentWindowInsets = ShellContentWindowInsets,
|
|
||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.fillMaxSize(),
|
||||||
topBar = {
|
topBar = {
|
||||||
MinstrelTopAppBar(
|
MinstrelTopAppBar(
|
||||||
@@ -115,13 +127,13 @@ fun AdminLandingScreen(
|
|||||||
modifier = Modifier.fillMaxSize().padding(inner),
|
modifier = Modifier.fillMaxSize().padding(inner),
|
||||||
) {
|
) {
|
||||||
when (val s = state) {
|
when (val s = state) {
|
||||||
UiState.Loading, UiState.Empty -> LoadingCentered()
|
AdminLandingUiState.Loading -> LoadingCentered()
|
||||||
is UiState.Error -> EmptyState(
|
is AdminLandingUiState.Error -> EmptyState(
|
||||||
title = "Couldn't load admin counts",
|
title = "Couldn't load admin counts",
|
||||||
body = s.message,
|
body = s.message,
|
||||||
)
|
)
|
||||||
is UiState.Success -> SectionList(
|
is AdminLandingUiState.Success -> SectionList(
|
||||||
counts = s.data,
|
counts = s.counts,
|
||||||
navController = navController,
|
navController = navController,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -136,11 +148,20 @@ private fun SectionList(counts: AdminCounts, navController: NavHostController) {
|
|||||||
contentPadding = PaddingValues(16.dp),
|
contentPadding = PaddingValues(16.dp),
|
||||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
) {
|
) {
|
||||||
|
item {
|
||||||
|
SectionCard(
|
||||||
|
icon = Lucide.Inbox,
|
||||||
|
title = "Requests",
|
||||||
|
subtitle = "Approve or reject Lidarr requests",
|
||||||
|
count = counts.requests,
|
||||||
|
onClick = { navController.navigate(AdminRequests) },
|
||||||
|
)
|
||||||
|
}
|
||||||
item {
|
item {
|
||||||
SectionCard(
|
SectionCard(
|
||||||
icon = Lucide.TriangleAlert,
|
icon = Lucide.TriangleAlert,
|
||||||
title = "Reports",
|
title = "Quarantine",
|
||||||
subtitle = "Tracks listeners flagged",
|
subtitle = "Resolve scan failures",
|
||||||
count = counts.quarantine,
|
count = counts.quarantine,
|
||||||
onClick = { navController.navigate(AdminQuarantine) },
|
onClick = { navController.navigate(AdminQuarantine) },
|
||||||
)
|
)
|
||||||
|
|||||||
+19
-89
@@ -9,21 +9,16 @@ import androidx.compose.foundation.layout.padding
|
|||||||
import androidx.compose.foundation.lazy.LazyColumn
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
import androidx.compose.foundation.lazy.items
|
import androidx.compose.foundation.lazy.items
|
||||||
import androidx.compose.material3.AssistChip
|
import androidx.compose.material3.AssistChip
|
||||||
|
import androidx.compose.material3.Button
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
import androidx.compose.material3.HorizontalDivider
|
import androidx.compose.material3.HorizontalDivider
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.OutlinedButton
|
import androidx.compose.material3.OutlinedButton
|
||||||
import androidx.compose.material3.Scaffold
|
import androidx.compose.material3.Scaffold
|
||||||
import androidx.compose.material3.SnackbarHost
|
|
||||||
import androidx.compose.material3.SnackbarHostState
|
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.material3.TextButton
|
import androidx.compose.material3.TextButton
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
|
||||||
import androidx.compose.runtime.remember
|
|
||||||
import androidx.compose.runtime.setValue
|
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
@@ -33,9 +28,6 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
|||||||
import androidx.navigation.NavHostController
|
import androidx.navigation.NavHostController
|
||||||
import com.fabledsword.minstrel.models.AdminQuarantineItemRef
|
import com.fabledsword.minstrel.models.AdminQuarantineItemRef
|
||||||
import com.fabledsword.minstrel.nav.AdminQuarantine
|
import com.fabledsword.minstrel.nav.AdminQuarantine
|
||||||
import com.fabledsword.minstrel.shared.UiState
|
|
||||||
import com.fabledsword.minstrel.shared.widgets.ConfirmDestructiveDialog
|
|
||||||
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
|
|
||||||
import com.fabledsword.minstrel.shared.widgets.EmptyState
|
import com.fabledsword.minstrel.shared.widgets.EmptyState
|
||||||
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
|
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
|
||||||
import com.fabledsword.minstrel.shared.widgets.LoadingCentered
|
import com.fabledsword.minstrel.shared.widgets.LoadingCentered
|
||||||
@@ -49,132 +41,70 @@ fun AdminQuarantineScreen(
|
|||||||
viewModel: AdminQuarantineViewModel = hiltViewModel(),
|
viewModel: AdminQuarantineViewModel = hiltViewModel(),
|
||||||
) {
|
) {
|
||||||
val state by viewModel.uiState.collectAsStateWithLifecycle()
|
val state by viewModel.uiState.collectAsStateWithLifecycle()
|
||||||
val snackbarHostState = remember { SnackbarHostState() }
|
|
||||||
LaunchedEffect(Unit) {
|
|
||||||
viewModel.transientMessages.collect { msg ->
|
|
||||||
snackbarHostState.showSnackbar(msg)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Scaffold(
|
Scaffold(
|
||||||
contentWindowInsets = ShellContentWindowInsets,
|
|
||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.fillMaxSize(),
|
||||||
topBar = {
|
topBar = {
|
||||||
MinstrelTopAppBar(
|
MinstrelTopAppBar(
|
||||||
title = "Admin · Reports",
|
title = "Admin · Quarantine",
|
||||||
navController = navController,
|
navController = navController,
|
||||||
currentRouteName = AdminQuarantine::class.qualifiedName,
|
currentRouteName = AdminQuarantine::class.qualifiedName,
|
||||||
onBack = { navController.popBackStack() },
|
onBack = { navController.popBackStack() },
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
snackbarHost = { SnackbarHost(snackbarHostState) },
|
|
||||||
) { inner ->
|
) { inner ->
|
||||||
PullToRefreshScaffold(
|
PullToRefreshScaffold(
|
||||||
onRefresh = { viewModel.refresh().join() },
|
onRefresh = { viewModel.refresh().join() },
|
||||||
modifier = Modifier.fillMaxSize().padding(inner),
|
modifier = Modifier.fillMaxSize().padding(inner),
|
||||||
) {
|
) {
|
||||||
when (val s = state) {
|
when (val s = state) {
|
||||||
UiState.Loading -> LoadingCentered()
|
AdminQuarantineUiState.Loading -> LoadingCentered()
|
||||||
UiState.Empty -> EmptyState(
|
AdminQuarantineUiState.Empty -> EmptyState(
|
||||||
title = "No reports",
|
title = "Queue is empty",
|
||||||
body = "When listeners flag a track as a bad rip, wrong tags or " +
|
body = "When users flag tracks as bad rips, wrong tags, or " +
|
||||||
"a duplicate, their reports gather here.",
|
"duplicates, their reports get aggregated and surfaced here.",
|
||||||
)
|
)
|
||||||
is UiState.Error -> ErrorRetry(
|
is AdminQuarantineUiState.Error -> ErrorRetry(
|
||||||
title = "Couldn't load queue",
|
title = "Couldn't load queue",
|
||||||
message = s.message,
|
message = s.message,
|
||||||
onRetry = { viewModel.refresh() },
|
onRetry = { viewModel.refresh() },
|
||||||
)
|
)
|
||||||
is UiState.Success -> QueueList(
|
is AdminQuarantineUiState.Success -> QueueList(
|
||||||
rows = s.data,
|
rows = s.rows,
|
||||||
onResolve = viewModel::resolve,
|
onResolve = viewModel::resolve,
|
||||||
onRemoveFile = viewModel::removeFile,
|
|
||||||
onDeleteFile = viewModel::deleteFile,
|
onDeleteFile = viewModel::deleteFile,
|
||||||
|
onDeleteViaLidarr = viewModel::deleteViaLidarr,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A confirm asked of the admin before a removal: which one, and of which track. */
|
|
||||||
private enum class Removal { File, Library }
|
|
||||||
|
|
||||||
private data class PendingRemoval(val row: AdminQuarantineItemRef, val kind: Removal)
|
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun QueueList(
|
private fun QueueList(
|
||||||
rows: List<AdminQuarantineItemRef>,
|
rows: List<AdminQuarantineItemRef>,
|
||||||
onResolve: (String) -> Unit,
|
onResolve: (String) -> Unit,
|
||||||
onRemoveFile: (String) -> Unit,
|
|
||||||
onDeleteFile: (String) -> Unit,
|
onDeleteFile: (String) -> Unit,
|
||||||
|
onDeleteViaLidarr: (String) -> Unit,
|
||||||
) {
|
) {
|
||||||
var pending by remember { mutableStateOf<PendingRemoval?>(null) }
|
|
||||||
LazyColumn(modifier = Modifier.fillMaxSize()) {
|
LazyColumn(modifier = Modifier.fillMaxSize()) {
|
||||||
items(items = rows, key = { it.trackId }) { row ->
|
items(items = rows, key = { it.trackId }) { row ->
|
||||||
QuarantineRow(
|
QuarantineRow(
|
||||||
row = row,
|
row = row,
|
||||||
onResolve = { onResolve(row.trackId) },
|
onResolve = { onResolve(row.trackId) },
|
||||||
onRemoveFile = { pending = PendingRemoval(row, Removal.File) },
|
onDeleteFile = { onDeleteFile(row.trackId) },
|
||||||
onDeleteFile = { pending = PendingRemoval(row, Removal.Library) },
|
onDeleteViaLidarr = { onDeleteViaLidarr(row.trackId) },
|
||||||
)
|
)
|
||||||
HorizontalDivider()
|
HorizontalDivider()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pending?.let { p ->
|
|
||||||
RemovalConfirm(
|
|
||||||
pending = p,
|
|
||||||
onConfirm = {
|
|
||||||
pending = null
|
|
||||||
when (p.kind) {
|
|
||||||
Removal.File -> onRemoveFile(p.row.trackId)
|
|
||||||
Removal.Library -> onDeleteFile(p.row.trackId)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
onDismiss = { pending = null },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Both removals delete the file, so each asks first. Remove the file keeps the
|
|
||||||
* track waiting for a good copy, with its likes and plays; Remove from library
|
|
||||||
* takes the track and its history too.
|
|
||||||
*/
|
|
||||||
@Composable
|
|
||||||
private fun RemovalConfirm(
|
|
||||||
pending: PendingRemoval,
|
|
||||||
onConfirm: () -> Unit,
|
|
||||||
onDismiss: () -> Unit,
|
|
||||||
) {
|
|
||||||
val title = pending.row.trackTitle
|
|
||||||
val (heading, body, action) = when (pending.kind) {
|
|
||||||
Removal.File -> Triple(
|
|
||||||
"Remove the file?",
|
|
||||||
"Delete the file of \u201c$title\u201d and keep the track. It waits, with its likes " +
|
|
||||||
"and plays, and takes over a good copy when one is in the library. Its reports are cleared.",
|
|
||||||
"Remove the file",
|
|
||||||
)
|
|
||||||
Removal.Library -> Triple(
|
|
||||||
"Remove from library?",
|
|
||||||
"Remove \u201c$title\u201d and its file for good, with its likes, plays and playlist " +
|
|
||||||
"places. To keep the track for a good copy, remove the file instead.",
|
|
||||||
"Remove from library",
|
|
||||||
)
|
|
||||||
}
|
|
||||||
ConfirmDestructiveDialog(
|
|
||||||
title = heading,
|
|
||||||
text = body,
|
|
||||||
confirmLabel = action,
|
|
||||||
onConfirm = onConfirm,
|
|
||||||
onDismiss = onDismiss,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun QuarantineRow(
|
private fun QuarantineRow(
|
||||||
row: AdminQuarantineItemRef,
|
row: AdminQuarantineItemRef,
|
||||||
onResolve: () -> Unit,
|
onResolve: () -> Unit,
|
||||||
onRemoveFile: () -> Unit,
|
|
||||||
onDeleteFile: () -> Unit,
|
onDeleteFile: () -> Unit,
|
||||||
|
onDeleteViaLidarr: () -> Unit,
|
||||||
) {
|
) {
|
||||||
Column(
|
Column(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
@@ -222,8 +152,8 @@ private fun QuarantineRow(
|
|||||||
}
|
}
|
||||||
ActionButtons(
|
ActionButtons(
|
||||||
onResolve = onResolve,
|
onResolve = onResolve,
|
||||||
onRemoveFile = onRemoveFile,
|
|
||||||
onDeleteFile = onDeleteFile,
|
onDeleteFile = onDeleteFile,
|
||||||
|
onDeleteViaLidarr = onDeleteViaLidarr,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -231,15 +161,15 @@ private fun QuarantineRow(
|
|||||||
@Composable
|
@Composable
|
||||||
private fun ActionButtons(
|
private fun ActionButtons(
|
||||||
onResolve: () -> Unit,
|
onResolve: () -> Unit,
|
||||||
onRemoveFile: () -> Unit,
|
|
||||||
onDeleteFile: () -> Unit,
|
onDeleteFile: () -> Unit,
|
||||||
|
onDeleteViaLidarr: () -> Unit,
|
||||||
) {
|
) {
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End),
|
horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End),
|
||||||
) {
|
) {
|
||||||
TextButton(onClick = onResolve) { Text("Resolve") }
|
TextButton(onClick = onResolve) { Text("Resolve") }
|
||||||
TextButton(onClick = onDeleteFile) { Text("Remove from library") }
|
OutlinedButton(onClick = onDeleteFile) { Text("Delete file") }
|
||||||
OutlinedButton(onClick = onRemoveFile) { Text("Remove the file") }
|
Button(onClick = onDeleteViaLidarr) { Text("Delete + Lidarr") }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+33
-26
@@ -8,23 +8,21 @@ import com.fabledsword.minstrel.connectivity.NetworkStatusController
|
|||||||
import com.fabledsword.minstrel.connectivity.recoveries
|
import com.fabledsword.minstrel.connectivity.recoveries
|
||||||
import com.fabledsword.minstrel.events.EventsStream
|
import com.fabledsword.minstrel.events.EventsStream
|
||||||
import com.fabledsword.minstrel.models.AdminQuarantineItemRef
|
import com.fabledsword.minstrel.models.AdminQuarantineItemRef
|
||||||
import com.fabledsword.minstrel.shared.UiState
|
|
||||||
import com.fabledsword.minstrel.shared.loadUiState
|
|
||||||
import com.fabledsword.minstrel.shared.toListState
|
|
||||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
import kotlinx.coroutines.Job
|
import kotlinx.coroutines.Job
|
||||||
import kotlinx.coroutines.channels.Channel
|
|
||||||
import kotlinx.coroutines.flow.Flow
|
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
import kotlinx.coroutines.flow.filter
|
import kotlinx.coroutines.flow.filter
|
||||||
import kotlinx.coroutines.flow.receiveAsFlow
|
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
/** The Reports queue, as the shared [UiState]. */
|
sealed interface AdminQuarantineUiState {
|
||||||
typealias AdminQuarantineUiState = UiState<List<AdminQuarantineItemRef>>
|
data object Loading : AdminQuarantineUiState
|
||||||
|
data object Empty : AdminQuarantineUiState
|
||||||
|
data class Success(val rows: List<AdminQuarantineItemRef>) : AdminQuarantineUiState
|
||||||
|
data class Error(val message: String) : AdminQuarantineUiState
|
||||||
|
}
|
||||||
|
|
||||||
@HiltViewModel
|
@HiltViewModel
|
||||||
class AdminQuarantineViewModel @Inject constructor(
|
class AdminQuarantineViewModel @Inject constructor(
|
||||||
@@ -33,17 +31,9 @@ class AdminQuarantineViewModel @Inject constructor(
|
|||||||
networkStatus: NetworkStatusController,
|
networkStatus: NetworkStatusController,
|
||||||
) : ViewModel() {
|
) : ViewModel() {
|
||||||
|
|
||||||
private val internal = MutableStateFlow<AdminQuarantineUiState>(UiState.Loading)
|
private val internal = MutableStateFlow<AdminQuarantineUiState>(AdminQuarantineUiState.Loading)
|
||||||
val uiState: StateFlow<AdminQuarantineUiState> = internal.asStateFlow()
|
val uiState: StateFlow<AdminQuarantineUiState> = internal.asStateFlow()
|
||||||
|
|
||||||
/**
|
|
||||||
* One-shot messages for the screen's snackbar. A failed action has to say
|
|
||||||
* why: the row quietly reappearing reads as a glitch, and for a removal
|
|
||||||
* refused by a read-only library it hides the one thing an admin can fix.
|
|
||||||
*/
|
|
||||||
private val transientMessagesChannel = Channel<String>(Channel.BUFFERED)
|
|
||||||
val transientMessages: Flow<String> = transientMessagesChannel.receiveAsFlow()
|
|
||||||
|
|
||||||
init {
|
init {
|
||||||
refresh()
|
refresh()
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
@@ -51,36 +41,53 @@ class AdminQuarantineViewModel @Inject constructor(
|
|||||||
.filter { it.kind.startsWith("quarantine.") }
|
.filter { it.kind.startsWith("quarantine.") }
|
||||||
.collect { refresh() }
|
.collect { refresh() }
|
||||||
}
|
}
|
||||||
// Screen-level auto-recovery: reload a failed list
|
// Screen-level auto-recovery (issue #1245): reload a failed list
|
||||||
// when server health returns instead of waiting for a manual pull.
|
// when server health returns instead of waiting for a manual pull.
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
networkStatus.recoveries().collect {
|
networkStatus.recoveries().collect {
|
||||||
if (internal.value is UiState.Error) refresh()
|
if (internal.value is AdminQuarantineUiState.Error) refresh()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun refresh(): Job = viewModelScope.launch {
|
fun refresh(): Job = viewModelScope.launch {
|
||||||
internal.value = UiState.Loading
|
internal.value = AdminQuarantineUiState.Loading
|
||||||
internal.value = loadUiState { repository.list().toListState() }
|
try {
|
||||||
|
val rows = repository.list()
|
||||||
|
internal.value = if (rows.isEmpty()) {
|
||||||
|
AdminQuarantineUiState.Empty
|
||||||
|
} else {
|
||||||
|
AdminQuarantineUiState.Success(rows)
|
||||||
|
}
|
||||||
|
} catch (
|
||||||
|
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
||||||
|
) {
|
||||||
|
internal.value = AdminQuarantineUiState.Error(
|
||||||
|
ErrorCopy.fromThrowable(e),
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun resolve(trackId: String) = act(trackId) { repository.resolve(it) }
|
fun resolve(trackId: String) = act(trackId) { repository.resolve(it) }
|
||||||
fun removeFile(trackId: String) = act(trackId) { repository.removeFile(it) }
|
|
||||||
fun deleteFile(trackId: String) = act(trackId) { repository.deleteFile(it) }
|
fun deleteFile(trackId: String) = act(trackId) { repository.deleteFile(it) }
|
||||||
|
fun deleteViaLidarr(trackId: String) = act(trackId) { repository.deleteViaLidarr(it) }
|
||||||
|
|
||||||
private fun act(trackId: String, action: suspend (String) -> Unit) {
|
private fun act(trackId: String, action: suspend (String) -> Unit) {
|
||||||
val before = internal.value
|
val before = internal.value
|
||||||
if (before is UiState.Success) {
|
if (before is AdminQuarantineUiState.Success) {
|
||||||
internal.value = before.data.filterNot { it.trackId == trackId }.toListState()
|
val filtered = before.rows.filterNot { it.trackId == trackId }
|
||||||
|
internal.value = if (filtered.isEmpty()) {
|
||||||
|
AdminQuarantineUiState.Empty
|
||||||
|
} else {
|
||||||
|
AdminQuarantineUiState.Success(filtered)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
try {
|
try {
|
||||||
action(trackId)
|
action(trackId)
|
||||||
} catch (
|
} catch (
|
||||||
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
|
||||||
) {
|
) {
|
||||||
transientMessagesChannel.trySend(ErrorCopy.fromThrowable(e))
|
|
||||||
refresh()
|
refresh()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,163 @@
|
|||||||
|
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.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(
|
||||||
|
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 Lidarr 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,
|
||||||
|
usernames = s.usernames,
|
||||||
|
onApprove = viewModel::approve,
|
||||||
|
onReject = viewModel::reject,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun RequestList(
|
||||||
|
rows: List<RequestRef>,
|
||||||
|
usernames: Map<String, String>,
|
||||||
|
onApprove: (String) -> Unit,
|
||||||
|
onReject: (String) -> Unit,
|
||||||
|
) {
|
||||||
|
LazyColumn(modifier = Modifier.fillMaxSize()) {
|
||||||
|
items(items = rows, key = { it.id }) { req ->
|
||||||
|
AdminRequestRow(
|
||||||
|
req = req,
|
||||||
|
requester = usernames[req.userId]
|
||||||
|
?: req.userId.takeIf { it.isNotEmpty() }?.take(USER_ID_PREFIX_LEN)
|
||||||
|
?: "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
|
||||||
|
// the admin users list fetch fails and we can't resolve userId → name.
|
||||||
|
private const val USER_ID_PREFIX_LEN = 8
|
||||||
+120
@@ -0,0 +1,120 @@
|
|||||||
|
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.admin.data.AdminUsersRepository
|
||||||
|
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.async
|
||||||
|
import kotlinx.coroutines.coroutineScope
|
||||||
|
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>,
|
||||||
|
val usernames: Map<String, String>,
|
||||||
|
) : AdminRequestsUiState
|
||||||
|
data class Error(val message: String) : AdminRequestsUiState
|
||||||
|
}
|
||||||
|
|
||||||
|
@HiltViewModel
|
||||||
|
class AdminRequestsViewModel @Inject constructor(
|
||||||
|
private val repository: AdminRequestsRepository,
|
||||||
|
private val usersRepository: AdminUsersRepository,
|
||||||
|
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 (issue #1245): 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, usernames) = coroutineScope {
|
||||||
|
val requestsJob = async { repository.list() }
|
||||||
|
val usernamesJob = async {
|
||||||
|
runCatching {
|
||||||
|
usersRepository.list().associate { it.id to it.username }
|
||||||
|
}.getOrDefault(emptyMap())
|
||||||
|
}
|
||||||
|
requestsJob.await() to usernamesJob.await()
|
||||||
|
}
|
||||||
|
internal.value = if (rows.isEmpty()) {
|
||||||
|
AdminRequestsUiState.Empty
|
||||||
|
} else {
|
||||||
|
AdminRequestsUiState.Success(rows = rows, usernames = usernames)
|
||||||
|
}
|
||||||
|
} 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, usernames = before.usernames)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+6
-9
@@ -35,8 +35,6 @@ import androidx.navigation.NavHostController
|
|||||||
import com.fabledsword.minstrel.models.AdminTagSourceRef
|
import com.fabledsword.minstrel.models.AdminTagSourceRef
|
||||||
import com.fabledsword.minstrel.models.TagSourceTestResult
|
import com.fabledsword.minstrel.models.TagSourceTestResult
|
||||||
import com.fabledsword.minstrel.nav.AdminTagSources
|
import com.fabledsword.minstrel.nav.AdminTagSources
|
||||||
import com.fabledsword.minstrel.shared.UiState
|
|
||||||
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
|
|
||||||
import com.fabledsword.minstrel.shared.widgets.EmptyState
|
import com.fabledsword.minstrel.shared.widgets.EmptyState
|
||||||
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
|
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
|
||||||
import com.fabledsword.minstrel.shared.widgets.LoadingCentered
|
import com.fabledsword.minstrel.shared.widgets.LoadingCentered
|
||||||
@@ -51,7 +49,6 @@ fun AdminTagSourcesScreen(
|
|||||||
) {
|
) {
|
||||||
val state by viewModel.uiState.collectAsStateWithLifecycle()
|
val state by viewModel.uiState.collectAsStateWithLifecycle()
|
||||||
Scaffold(
|
Scaffold(
|
||||||
contentWindowInsets = ShellContentWindowInsets,
|
|
||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.fillMaxSize(),
|
||||||
topBar = {
|
topBar = {
|
||||||
MinstrelTopAppBar(
|
MinstrelTopAppBar(
|
||||||
@@ -67,19 +64,19 @@ fun AdminTagSourcesScreen(
|
|||||||
modifier = Modifier.fillMaxSize().padding(inner),
|
modifier = Modifier.fillMaxSize().padding(inner),
|
||||||
) {
|
) {
|
||||||
when (val s = state) {
|
when (val s = state) {
|
||||||
UiState.Loading -> LoadingCentered()
|
AdminTagSourcesUiState.Loading -> LoadingCentered()
|
||||||
UiState.Empty -> EmptyState(
|
AdminTagSourcesUiState.Empty -> EmptyState(
|
||||||
title = "No tag sources",
|
title = "No tag sources",
|
||||||
body = "Tag-enrichment providers register on the server; none are available.",
|
body = "Tag-enrichment providers register on the server; none are available.",
|
||||||
)
|
)
|
||||||
is UiState.Error -> ErrorRetry(
|
is AdminTagSourcesUiState.Error -> ErrorRetry(
|
||||||
title = "Couldn't load tag sources",
|
title = "Couldn't load tag sources",
|
||||||
message = s.message,
|
message = s.message,
|
||||||
onRetry = { viewModel.refresh() },
|
onRetry = { viewModel.refresh() },
|
||||||
)
|
)
|
||||||
is UiState.Success -> TagSourceList(
|
is AdminTagSourcesUiState.Success -> TagSourceList(
|
||||||
providers = s.data.providers,
|
providers = s.providers,
|
||||||
testResults = s.data.testResults,
|
testResults = s.testResults,
|
||||||
onToggle = viewModel::setEnabled,
|
onToggle = viewModel::setEnabled,
|
||||||
onSaveKey = viewModel::saveApiKey,
|
onSaveKey = viewModel::saveApiKey,
|
||||||
onTest = viewModel::test,
|
onTest = viewModel::test,
|
||||||
|
|||||||
+33
-30
@@ -8,8 +8,6 @@ import com.fabledsword.minstrel.connectivity.NetworkStatusController
|
|||||||
import com.fabledsword.minstrel.connectivity.recoveries
|
import com.fabledsword.minstrel.connectivity.recoveries
|
||||||
import com.fabledsword.minstrel.models.AdminTagSourceRef
|
import com.fabledsword.minstrel.models.AdminTagSourceRef
|
||||||
import com.fabledsword.minstrel.models.TagSourceTestResult
|
import com.fabledsword.minstrel.models.TagSourceTestResult
|
||||||
import com.fabledsword.minstrel.shared.UiState
|
|
||||||
import com.fabledsword.minstrel.shared.loadUiState
|
|
||||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
import kotlinx.coroutines.Job
|
import kotlinx.coroutines.Job
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
@@ -18,14 +16,15 @@ import kotlinx.coroutines.flow.asStateFlow
|
|||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
/** The tag sources and the last Test answer for each, by provider id. */
|
sealed interface AdminTagSourcesUiState {
|
||||||
data class AdminTagSources(
|
data object Loading : AdminTagSourcesUiState
|
||||||
val providers: List<AdminTagSourceRef>,
|
data object Empty : AdminTagSourcesUiState
|
||||||
val testResults: Map<String, TagSourceTestResult> = emptyMap(),
|
data class Success(
|
||||||
)
|
val providers: List<AdminTagSourceRef>,
|
||||||
|
val testResults: Map<String, TagSourceTestResult>,
|
||||||
/** The Tag sources screen, as the shared [UiState]. */
|
) : AdminTagSourcesUiState
|
||||||
typealias AdminTagSourcesUiState = UiState<AdminTagSources>
|
data class Error(val message: String) : AdminTagSourcesUiState
|
||||||
|
}
|
||||||
|
|
||||||
@HiltViewModel
|
@HiltViewModel
|
||||||
class AdminTagSourcesViewModel @Inject constructor(
|
class AdminTagSourcesViewModel @Inject constructor(
|
||||||
@@ -33,37 +32,43 @@ class AdminTagSourcesViewModel @Inject constructor(
|
|||||||
networkStatus: NetworkStatusController,
|
networkStatus: NetworkStatusController,
|
||||||
) : ViewModel() {
|
) : ViewModel() {
|
||||||
|
|
||||||
private val internal = MutableStateFlow<AdminTagSourcesUiState>(UiState.Loading)
|
private val internal = MutableStateFlow<AdminTagSourcesUiState>(AdminTagSourcesUiState.Loading)
|
||||||
val uiState: StateFlow<AdminTagSourcesUiState> = internal.asStateFlow()
|
val uiState: StateFlow<AdminTagSourcesUiState> = internal.asStateFlow()
|
||||||
|
|
||||||
init {
|
init {
|
||||||
refresh()
|
refresh()
|
||||||
// Screen-level auto-recovery: reload a failed list when server
|
// Screen-level auto-recovery: reload a failed list when server
|
||||||
// health returns instead of waiting for a manual pull.
|
// health returns instead of waiting for a manual pull (issue #1245).
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
networkStatus.recoveries().collect {
|
networkStatus.recoveries().collect {
|
||||||
if (internal.value is UiState.Error) refresh()
|
if (internal.value is AdminTagSourcesUiState.Error) refresh()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun refresh(): Job = viewModelScope.launch {
|
fun refresh(): Job = viewModelScope.launch {
|
||||||
internal.value = UiState.Loading
|
internal.value = AdminTagSourcesUiState.Loading
|
||||||
internal.value = loadUiState {
|
try {
|
||||||
val providers = repository.list()
|
val providers = repository.list()
|
||||||
if (providers.isEmpty()) UiState.Empty else UiState.Success(AdminTagSources(providers))
|
internal.value = if (providers.isEmpty()) {
|
||||||
|
AdminTagSourcesUiState.Empty
|
||||||
|
} else {
|
||||||
|
AdminTagSourcesUiState.Success(providers, emptyMap())
|
||||||
|
}
|
||||||
|
} catch (
|
||||||
|
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
||||||
|
) {
|
||||||
|
internal.value = AdminTagSourcesUiState.Error(ErrorCopy.fromThrowable(e))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun setEnabled(id: String, enabled: Boolean) {
|
fun setEnabled(id: String, enabled: Boolean) {
|
||||||
val before = (internal.value as? UiState.Success<AdminTagSources>)?.data ?: return
|
val before = internal.value as? AdminTagSourcesUiState.Success ?: return
|
||||||
// Optimistic toggle; reconcile via refresh() if the server rejects.
|
// Optimistic toggle; reconcile via refresh() if the server rejects.
|
||||||
internal.value = UiState.Success(
|
internal.value = before.copy(
|
||||||
before.copy(
|
providers = before.providers.map {
|
||||||
providers = before.providers.map {
|
if (it.id == id) it.copy(enabled = enabled) else it
|
||||||
if (it.id == id) it.copy(enabled = enabled) else it
|
},
|
||||||
},
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
try {
|
try {
|
||||||
@@ -97,17 +102,15 @@ class AdminTagSourcesViewModel @Inject constructor(
|
|||||||
) {
|
) {
|
||||||
TagSourceTestResult(ok = false, error = ErrorCopy.fromThrowable(e))
|
TagSourceTestResult(ok = false, error = ErrorCopy.fromThrowable(e))
|
||||||
}
|
}
|
||||||
val current = (internal.value as? UiState.Success<AdminTagSources>)?.data ?: return@launch
|
val current = internal.value as? AdminTagSourcesUiState.Success ?: return@launch
|
||||||
internal.value = UiState.Success(current.copy(testResults = current.testResults + (id to result)))
|
internal.value = current.copy(testResults = current.testResults + (id to result))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun replaceProvider(updated: AdminTagSourceRef) {
|
private fun replaceProvider(updated: AdminTagSourceRef) {
|
||||||
val current = (internal.value as? UiState.Success<AdminTagSources>)?.data ?: return
|
val current = internal.value as? AdminTagSourcesUiState.Success ?: return
|
||||||
internal.value = UiState.Success(
|
internal.value = current.copy(
|
||||||
current.copy(
|
providers = current.providers.map { if (it.id == updated.id) updated else it },
|
||||||
providers = current.providers.map { if (it.id == updated.id) updated else it },
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,7 +31,6 @@ import androidx.compose.material3.TextButton
|
|||||||
import android.content.ClipData
|
import android.content.ClipData
|
||||||
import androidx.compose.ui.platform.ClipEntry
|
import androidx.compose.ui.platform.ClipEntry
|
||||||
import androidx.compose.ui.platform.LocalClipboard
|
import androidx.compose.ui.platform.LocalClipboard
|
||||||
import com.fabledsword.minstrel.auth.PasswordRules
|
|
||||||
import com.fabledsword.minstrel.models.Invite
|
import com.fabledsword.minstrel.models.Invite
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
@@ -50,9 +49,6 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
|||||||
import androidx.navigation.NavHostController
|
import androidx.navigation.NavHostController
|
||||||
import com.fabledsword.minstrel.models.AdminUserRef
|
import com.fabledsword.minstrel.models.AdminUserRef
|
||||||
import com.fabledsword.minstrel.nav.AdminUsers
|
import com.fabledsword.minstrel.nav.AdminUsers
|
||||||
import com.fabledsword.minstrel.shared.UiState
|
|
||||||
import com.fabledsword.minstrel.shared.widgets.ConfirmDestructiveDialog
|
|
||||||
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
|
|
||||||
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
|
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
|
||||||
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
|
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
@@ -84,6 +80,7 @@ fun AdminUsersScreen(
|
|||||||
invitesViewModel.refresh()
|
invitesViewModel.refresh()
|
||||||
},
|
},
|
||||||
onSetAdmin = viewModel::setAdmin,
|
onSetAdmin = viewModel::setAdmin,
|
||||||
|
onSetAutoApprove = viewModel::setAutoApprove,
|
||||||
onAskResetPassword = { resetPasswordFor = it },
|
onAskResetPassword = { resetPasswordFor = it },
|
||||||
onAskDelete = { deleteCandidate = it },
|
onAskDelete = { deleteCandidate = it },
|
||||||
onAskGenerateInvite = { showGenerateInvite = true },
|
onAskGenerateInvite = { showGenerateInvite = true },
|
||||||
@@ -123,13 +120,13 @@ private fun AdminUsersScaffold(
|
|||||||
invitesState: AdminInvitesUiState,
|
invitesState: AdminInvitesUiState,
|
||||||
onRefresh: suspend () -> Unit,
|
onRefresh: suspend () -> Unit,
|
||||||
onSetAdmin: (String, Boolean) -> Unit,
|
onSetAdmin: (String, Boolean) -> Unit,
|
||||||
|
onSetAutoApprove: (String, Boolean) -> Unit,
|
||||||
onAskResetPassword: (AdminUserRef) -> Unit,
|
onAskResetPassword: (AdminUserRef) -> Unit,
|
||||||
onAskDelete: (AdminUserRef) -> Unit,
|
onAskDelete: (AdminUserRef) -> Unit,
|
||||||
onAskGenerateInvite: () -> Unit,
|
onAskGenerateInvite: () -> Unit,
|
||||||
onRevokeInvite: (String) -> Unit,
|
onRevokeInvite: (String) -> Unit,
|
||||||
) {
|
) {
|
||||||
Scaffold(
|
Scaffold(
|
||||||
contentWindowInsets = ShellContentWindowInsets,
|
|
||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.fillMaxSize(),
|
||||||
topBar = {
|
topBar = {
|
||||||
MinstrelTopAppBar(
|
MinstrelTopAppBar(
|
||||||
@@ -149,6 +146,7 @@ private fun AdminUsersScaffold(
|
|||||||
usersSection(
|
usersSection(
|
||||||
state = usersState,
|
state = usersState,
|
||||||
onSetAdmin = onSetAdmin,
|
onSetAdmin = onSetAdmin,
|
||||||
|
onSetAutoApprove = onSetAutoApprove,
|
||||||
onAskResetPassword = onAskResetPassword,
|
onAskResetPassword = onAskResetPassword,
|
||||||
onAskDelete = onAskDelete,
|
onAskDelete = onAskDelete,
|
||||||
)
|
)
|
||||||
@@ -195,17 +193,19 @@ private fun SectionHeader(label: String, trailing: (@Composable () -> Unit)? = n
|
|||||||
private fun androidx.compose.foundation.lazy.LazyListScope.usersSection(
|
private fun androidx.compose.foundation.lazy.LazyListScope.usersSection(
|
||||||
state: AdminUsersUiState,
|
state: AdminUsersUiState,
|
||||||
onSetAdmin: (String, Boolean) -> Unit,
|
onSetAdmin: (String, Boolean) -> Unit,
|
||||||
|
onSetAutoApprove: (String, Boolean) -> Unit,
|
||||||
onAskResetPassword: (AdminUserRef) -> Unit,
|
onAskResetPassword: (AdminUserRef) -> Unit,
|
||||||
onAskDelete: (AdminUserRef) -> Unit,
|
onAskDelete: (AdminUserRef) -> Unit,
|
||||||
) {
|
) {
|
||||||
when (state) {
|
when (state) {
|
||||||
UiState.Loading -> item { CenteredHint("Loading users…") }
|
AdminUsersUiState.Loading -> item { CenteredHint("Loading users…") }
|
||||||
UiState.Empty -> item { CenteredHint("No registered users.") }
|
AdminUsersUiState.Empty -> item { CenteredHint("No registered users.") }
|
||||||
is UiState.Error -> item { CenteredHint(state.message) }
|
is AdminUsersUiState.Error -> item { CenteredHint(state.message) }
|
||||||
is UiState.Success -> items(items = state.data, key = { it.id }) { user ->
|
is AdminUsersUiState.Success -> items(items = state.users, key = { it.id }) { user ->
|
||||||
UserRow(
|
UserRow(
|
||||||
user = user,
|
user = user,
|
||||||
onSetAdmin = { onSetAdmin(user.id, it) },
|
onSetAdmin = { onSetAdmin(user.id, it) },
|
||||||
|
onSetAutoApprove = { onSetAutoApprove(user.id, it) },
|
||||||
onResetPassword = { onAskResetPassword(user) },
|
onResetPassword = { onAskResetPassword(user) },
|
||||||
onDelete = { onAskDelete(user) },
|
onDelete = { onAskDelete(user) },
|
||||||
)
|
)
|
||||||
@@ -395,6 +395,7 @@ private fun PendingDialogs(
|
|||||||
private fun UserRow(
|
private fun UserRow(
|
||||||
user: AdminUserRef,
|
user: AdminUserRef,
|
||||||
onSetAdmin: (Boolean) -> Unit,
|
onSetAdmin: (Boolean) -> Unit,
|
||||||
|
onSetAutoApprove: (Boolean) -> Unit,
|
||||||
onResetPassword: () -> Unit,
|
onResetPassword: () -> Unit,
|
||||||
onDelete: () -> Unit,
|
onDelete: () -> Unit,
|
||||||
) {
|
) {
|
||||||
@@ -417,6 +418,11 @@ private fun UserRow(
|
|||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
ToggleRow(label = "Admin", checked = user.isAdmin, onChange = onSetAdmin)
|
ToggleRow(label = "Admin", checked = user.isAdmin, onChange = onSetAdmin)
|
||||||
|
ToggleRow(
|
||||||
|
label = "Auto-approve requests",
|
||||||
|
checked = user.autoApproveRequests,
|
||||||
|
onChange = onSetAutoApprove,
|
||||||
|
)
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
horizontalArrangement = Arrangement.spacedBy(4.dp, Alignment.End),
|
horizontalArrangement = Arrangement.spacedBy(4.dp, Alignment.End),
|
||||||
@@ -472,7 +478,6 @@ private fun ResetPasswordDialog(
|
|||||||
value = newPassword,
|
value = newPassword,
|
||||||
onValueChange = { newPassword = it },
|
onValueChange = { newPassword = it },
|
||||||
label = { Text("New password") },
|
label = { Text("New password") },
|
||||||
supportingText = { Text(PasswordRules.HINT) },
|
|
||||||
singleLine = true,
|
singleLine = true,
|
||||||
visualTransformation = PasswordVisualTransformation(),
|
visualTransformation = PasswordVisualTransformation(),
|
||||||
)
|
)
|
||||||
@@ -481,7 +486,7 @@ private fun ResetPasswordDialog(
|
|||||||
confirmButton = {
|
confirmButton = {
|
||||||
TextButton(
|
TextButton(
|
||||||
onClick = { onConfirm(newPassword) },
|
onClick = { onConfirm(newPassword) },
|
||||||
enabled = PasswordRules.isLongEnough(newPassword),
|
enabled = newPassword.isNotEmpty(),
|
||||||
) { Text("Reset") }
|
) { Text("Reset") }
|
||||||
},
|
},
|
||||||
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
|
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
|
||||||
@@ -494,14 +499,39 @@ private fun DeleteConfirmDialog(
|
|||||||
onDismiss: () -> Unit,
|
onDismiss: () -> Unit,
|
||||||
onConfirm: () -> Unit,
|
onConfirm: () -> Unit,
|
||||||
) {
|
) {
|
||||||
ConfirmDestructiveDialog(
|
var typed by remember { mutableStateOf("") }
|
||||||
title = "Delete user?",
|
val confirmed = typed.trim().equals(DELETE_CONFIRM_WORD, ignoreCase = true)
|
||||||
text = "Delete @${user.username}? This removes the account and all " +
|
AlertDialog(
|
||||||
"their data. Type $DELETE_CONFIRM_WORD to confirm.",
|
onDismissRequest = onDismiss,
|
||||||
confirmLabel = "Delete",
|
title = { Text("Delete user?") },
|
||||||
onConfirm = onConfirm,
|
text = {
|
||||||
onDismiss = onDismiss,
|
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
confirmWord = DELETE_CONFIRM_WORD,
|
Text(
|
||||||
|
"Delete @${user.username}? This removes the account and all " +
|
||||||
|
"their data. Type $DELETE_CONFIRM_WORD to confirm.",
|
||||||
|
)
|
||||||
|
OutlinedTextField(
|
||||||
|
value = typed,
|
||||||
|
onValueChange = { typed = it },
|
||||||
|
label = { Text("Type $DELETE_CONFIRM_WORD") },
|
||||||
|
singleLine = true,
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(onClick = onConfirm, enabled = confirmed) {
|
||||||
|
Text(
|
||||||
|
"Delete",
|
||||||
|
color = if (confirmed) {
|
||||||
|
MaterialTheme.colorScheme.error
|
||||||
|
} else {
|
||||||
|
MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+38
-15
@@ -3,12 +3,10 @@ package com.fabledsword.minstrel.admin.ui
|
|||||||
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModel
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
import com.fabledsword.minstrel.admin.data.AdminUsersRepository
|
import com.fabledsword.minstrel.admin.data.AdminUsersRepository
|
||||||
|
import com.fabledsword.minstrel.api.ErrorCopy
|
||||||
import com.fabledsword.minstrel.connectivity.NetworkStatusController
|
import com.fabledsword.minstrel.connectivity.NetworkStatusController
|
||||||
import com.fabledsword.minstrel.connectivity.recoveries
|
import com.fabledsword.minstrel.connectivity.recoveries
|
||||||
import com.fabledsword.minstrel.models.AdminUserRef
|
import com.fabledsword.minstrel.models.AdminUserRef
|
||||||
import com.fabledsword.minstrel.shared.UiState
|
|
||||||
import com.fabledsword.minstrel.shared.loadUiState
|
|
||||||
import com.fabledsword.minstrel.shared.toListState
|
|
||||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
import kotlinx.coroutines.Job
|
import kotlinx.coroutines.Job
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
@@ -17,8 +15,12 @@ import kotlinx.coroutines.flow.asStateFlow
|
|||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
/** The Users screen's list, as the shared [UiState]. */
|
sealed interface AdminUsersUiState {
|
||||||
typealias AdminUsersUiState = UiState<List<AdminUserRef>>
|
data object Loading : AdminUsersUiState
|
||||||
|
data object Empty : AdminUsersUiState
|
||||||
|
data class Success(val users: List<AdminUserRef>) : AdminUsersUiState
|
||||||
|
data class Error(val message: String) : AdminUsersUiState
|
||||||
|
}
|
||||||
|
|
||||||
@HiltViewModel
|
@HiltViewModel
|
||||||
class AdminUsersViewModel @Inject constructor(
|
class AdminUsersViewModel @Inject constructor(
|
||||||
@@ -26,29 +28,45 @@ class AdminUsersViewModel @Inject constructor(
|
|||||||
networkStatus: NetworkStatusController,
|
networkStatus: NetworkStatusController,
|
||||||
) : ViewModel() {
|
) : ViewModel() {
|
||||||
|
|
||||||
private val internal = MutableStateFlow<AdminUsersUiState>(UiState.Loading)
|
private val internal = MutableStateFlow<AdminUsersUiState>(AdminUsersUiState.Loading)
|
||||||
val uiState: StateFlow<AdminUsersUiState> = internal.asStateFlow()
|
val uiState: StateFlow<AdminUsersUiState> = internal.asStateFlow()
|
||||||
|
|
||||||
init {
|
init {
|
||||||
refresh()
|
refresh()
|
||||||
// Screen-level auto-recovery: reload a failed list
|
// Screen-level auto-recovery (issue #1245): reload a failed list
|
||||||
// when server health returns instead of waiting for a manual pull.
|
// when server health returns instead of waiting for a manual pull.
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
networkStatus.recoveries().collect {
|
networkStatus.recoveries().collect {
|
||||||
if (internal.value is UiState.Error) refresh()
|
if (internal.value is AdminUsersUiState.Error) refresh()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun refresh(): Job = viewModelScope.launch {
|
fun refresh(): Job = viewModelScope.launch {
|
||||||
internal.value = UiState.Loading
|
internal.value = AdminUsersUiState.Loading
|
||||||
internal.value = loadUiState { repository.list().toListState() }
|
try {
|
||||||
|
val users = repository.list()
|
||||||
|
internal.value = if (users.isEmpty()) {
|
||||||
|
AdminUsersUiState.Empty
|
||||||
|
} else {
|
||||||
|
AdminUsersUiState.Success(users)
|
||||||
|
}
|
||||||
|
} catch (
|
||||||
|
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
||||||
|
) {
|
||||||
|
internal.value = AdminUsersUiState.Error(ErrorCopy.fromThrowable(e))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun setAdmin(id: String, isAdmin: Boolean) = patch(id, { it.copy(isAdmin = isAdmin) }) {
|
fun setAdmin(id: String, isAdmin: Boolean) = patch(id, { it.copy(isAdmin = isAdmin) }) {
|
||||||
repository.setAdmin(it, isAdmin)
|
repository.setAdmin(it, isAdmin)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun setAutoApprove(id: String, autoApprove: Boolean) =
|
||||||
|
patch(id, { it.copy(autoApproveRequests = autoApprove) }) {
|
||||||
|
repository.setAutoApprove(it, autoApprove)
|
||||||
|
}
|
||||||
|
|
||||||
fun resetPassword(id: String, newPassword: String) {
|
fun resetPassword(id: String, newPassword: String) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
runCatching { repository.resetPassword(id, newPassword) }
|
runCatching { repository.resetPassword(id, newPassword) }
|
||||||
@@ -57,8 +75,13 @@ class AdminUsersViewModel @Inject constructor(
|
|||||||
|
|
||||||
fun delete(id: String) {
|
fun delete(id: String) {
|
||||||
val before = internal.value
|
val before = internal.value
|
||||||
if (before is UiState.Success) {
|
if (before is AdminUsersUiState.Success) {
|
||||||
internal.value = before.data.filterNot { it.id == id }.toListState()
|
val filtered = before.users.filterNot { it.id == id }
|
||||||
|
internal.value = if (filtered.isEmpty()) {
|
||||||
|
AdminUsersUiState.Empty
|
||||||
|
} else {
|
||||||
|
AdminUsersUiState.Success(filtered)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
try {
|
try {
|
||||||
@@ -77,9 +100,9 @@ class AdminUsersViewModel @Inject constructor(
|
|||||||
action: suspend (String) -> Unit,
|
action: suspend (String) -> Unit,
|
||||||
) {
|
) {
|
||||||
val before = internal.value
|
val before = internal.value
|
||||||
if (before is UiState.Success) {
|
if (before is AdminUsersUiState.Success) {
|
||||||
internal.value = UiState.Success(
|
internal.value = AdminUsersUiState.Success(
|
||||||
before.data.map { if (it.id == id) mutate(it) else it },
|
before.users.map { if (it.id == id) mutate(it) else it },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
|
|||||||
@@ -8,16 +8,22 @@ import javax.inject.Singleton
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Attaches the session cookie from [AuthStore] to Minstrel-server
|
* Attaches the session cookie from [AuthStore] to Minstrel-server
|
||||||
* requests (waiting for the stored one to load at launch), captures
|
* requests, captures Set-Cookie from successful responses (login
|
||||||
* Set-Cookie from successful responses (login flow), and signs out when
|
* flow), and clears the store on 401 so downstream code can react
|
||||||
* the server refuses the cookie a request carried.
|
* to logout.
|
||||||
|
*
|
||||||
|
* Mirrors the Flutter Dio interceptor pattern.
|
||||||
*
|
*
|
||||||
* Scoped to the [BaseUrlInterceptor.PLACEHOLDER_HOST] sentinel host
|
* Scoped to the [BaseUrlInterceptor.PLACEHOLDER_HOST] sentinel host
|
||||||
* the same way BaseUrlInterceptor is. The shared OkHttpClient also
|
* the same way BaseUrlInterceptor is. Drift #568 / #569 caught two
|
||||||
* serves Coil's image fetches to external hosts such as
|
* leaks here: (1) the session cookie was being attached to every
|
||||||
* artwork.musicbrainz.org and coverartarchive.org; unscoped, this
|
* external request the shared OkHttpClient services — including
|
||||||
* would hand the session identifier to third-party logging, and a 401
|
* Coil image fetches to artwork.musicbrainz.org / coverartarchive.org
|
||||||
* from any of those hosts would sign the user out of Minstrel.
|
* / Lidarr's /MediaCover endpoints — exposing the session
|
||||||
|
* identifier to third-party logging; (2) a 401 from any of those
|
||||||
|
* external hosts silently wiped the user's Minstrel session.
|
||||||
|
* Restricting both attach + clear to placeholder-host requests
|
||||||
|
* closes both gaps.
|
||||||
*/
|
*/
|
||||||
@Singleton
|
@Singleton
|
||||||
class AuthCookieInterceptor @Inject constructor(
|
class AuthCookieInterceptor @Inject constructor(
|
||||||
@@ -32,7 +38,7 @@ class AuthCookieInterceptor @Inject constructor(
|
|||||||
// session. Pass through untouched.
|
// session. Pass through untouched.
|
||||||
return chain.proceed(original)
|
return chain.proceed(original)
|
||||||
}
|
}
|
||||||
val cookie = authStore.sessionCookieForRequest()
|
val cookie = authStore.sessionCookie.value
|
||||||
val request = original.newBuilder().apply {
|
val request = original.newBuilder().apply {
|
||||||
if (!cookie.isNullOrEmpty()) header("Cookie", cookie)
|
if (!cookie.isNullOrEmpty()) header("Cookie", cookie)
|
||||||
}.build()
|
}.build()
|
||||||
@@ -40,11 +46,7 @@ class AuthCookieInterceptor @Inject constructor(
|
|||||||
val response = chain.proceed(request)
|
val response = chain.proceed(request)
|
||||||
|
|
||||||
if (response.code == HTTP_UNAUTHORIZED) {
|
if (response.code == HTTP_UNAUTHORIZED) {
|
||||||
// Only a refusal of the cookie this request carried ends the
|
authStore.setSessionCookie(null)
|
||||||
// session. A request sent without one says nothing about the
|
|
||||||
// stored login, and a refusal of an older cookie must not
|
|
||||||
// discard one a sign-in has stored since.
|
|
||||||
if (!cookie.isNullOrEmpty()) authStore.dropRejectedSessionCookie(cookie)
|
|
||||||
} else if (response.isSuccessful) {
|
} else if (response.isSuccessful) {
|
||||||
// Capture the first Set-Cookie pair on login; subsequent
|
// Capture the first Set-Cookie pair on login; subsequent
|
||||||
// responses that include Set-Cookie keep the store fresh.
|
// responses that include Set-Cookie keep the store fresh.
|
||||||
|
|||||||
@@ -17,14 +17,15 @@ import javax.inject.Singleton
|
|||||||
*
|
*
|
||||||
* This interceptor closes the gap: Retrofit can stay built with the
|
* This interceptor closes the gap: Retrofit can stay built with the
|
||||||
* placeholder forever, and every actual Minstrel-bound request gets
|
* placeholder forever, and every actual Minstrel-bound request gets
|
||||||
* retargeted at the live AuthStore value, so the user can change the
|
* retargeted at the live AuthStore value. Lets the user change
|
||||||
* server URL in Settings without an app relaunch.
|
* server URL in Settings without an app relaunch (Phase 11 wiring).
|
||||||
*
|
*
|
||||||
* Only requests whose host is the [PLACEHOLDER_HOST] sentinel are
|
* Only requests whose host is the [PLACEHOLDER_HOST] sentinel are
|
||||||
* rewritten. Absolute external URLs — artwork from
|
* rewritten. Absolute external URLs — Lidarr-surfaced artwork from
|
||||||
* artwork.musicbrainz.org / coverartarchive.org, for example — must
|
* artwork.musicbrainz.org / coverartarchive.org, for example — must
|
||||||
* reach their authored host unchanged: rewritten to the Minstrel host
|
* reach their authored host unchanged; rewriting them to the
|
||||||
* they 404, and the art never shows.
|
* Minstrel host produced 404s the user saw as missing Discover
|
||||||
|
* suggestion covers.
|
||||||
*
|
*
|
||||||
* No-op when the stored base URL is unparseable (falls through to
|
* No-op when the stored base URL is unparseable (falls through to
|
||||||
* whatever Retrofit had) — that case shows up as a transport-level
|
* whatever Retrofit had) — that case shows up as a transport-level
|
||||||
@@ -49,14 +50,7 @@ class BaseUrlInterceptor @Inject constructor(
|
|||||||
.port(baseUrl.port)
|
.port(baseUrl.port)
|
||||||
.build()
|
.build()
|
||||||
} ?: original.url
|
} ?: original.url
|
||||||
return chain.proceed(
|
return chain.proceed(original.newBuilder().url(rewritten).build())
|
||||||
original.newBuilder()
|
|
||||||
.url(rewritten)
|
|
||||||
// Lets CleartextGuardInterceptor tell server requests from
|
|
||||||
// external fetches once the placeholder host is gone.
|
|
||||||
.tag(MinstrelServerRequest::class.java, MinstrelServerRequest)
|
|
||||||
.build(),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
|||||||
@@ -1,83 +0,0 @@
|
|||||||
package com.fabledsword.minstrel.api
|
|
||||||
|
|
||||||
import okhttp3.Interceptor
|
|
||||||
import okhttp3.Response
|
|
||||||
import java.io.IOException
|
|
||||||
import java.net.Inet4Address
|
|
||||||
import java.net.Inet6Address
|
|
||||||
import java.net.InetAddress
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Marks a request as bound for the Minstrel server, set by
|
|
||||||
* [BaseUrlInterceptor] when it retargets the placeholder host. Those are the
|
|
||||||
* requests that carry the session cookie and the password.
|
|
||||||
*/
|
|
||||||
object MinstrelServerRequest
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Plain `http://` to the Minstrel server is allowed only when the connection
|
|
||||||
* actually lands on a private address.
|
|
||||||
*
|
|
||||||
* Cleartext stays permitted app-wide for LAN servers and UPnP
|
|
||||||
* (network_security_config.xml), but a password or session cookie sent
|
|
||||||
* over plain HTTP to a public address can be read by anyone on the path.
|
|
||||||
*
|
|
||||||
* Checked per connection, on the address the socket really reached, not on
|
|
||||||
* the URL when it was typed: a name that resolved to the home network when it
|
|
||||||
* was entered resolves to a public address once the phone leaves home, and
|
|
||||||
* that is exactly when the password would go out in the clear. A network
|
|
||||||
* interceptor runs after the connection is made and before any request byte
|
|
||||||
* is written, so nothing is sent.
|
|
||||||
*/
|
|
||||||
class CleartextGuardInterceptor(
|
|
||||||
// The policy is a parameter so a test can refuse loopback, the only
|
|
||||||
// address a test server can listen on.
|
|
||||||
private val allows: (InetAddress) -> Boolean = CleartextPolicy::allows,
|
|
||||||
) : Interceptor {
|
|
||||||
override fun intercept(chain: Interceptor.Chain): Response {
|
|
||||||
val request = chain.request()
|
|
||||||
if (request.isHttps || request.tag(MinstrelServerRequest::class.java) == null) {
|
|
||||||
return chain.proceed(request)
|
|
||||||
}
|
|
||||||
val address = chain.connection()?.route()?.socketAddress?.address
|
|
||||||
if (address != null && !allows(address)) {
|
|
||||||
throw CleartextToPublicHostException(request.url.host)
|
|
||||||
}
|
|
||||||
return chain.proceed(request)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The server was reached over plain HTTP at a public address, and refused. */
|
|
||||||
class CleartextToPublicHostException(host: String) :
|
|
||||||
IOException("refusing plain http:// to $host: it is a public address")
|
|
||||||
|
|
||||||
/** Which addresses plain HTTP may reach: the home network, never the internet. */
|
|
||||||
object CleartextPolicy {
|
|
||||||
private const val CGNAT_FIRST_OCTET = 100
|
|
||||||
private const val CGNAT_SECOND_MASK = 0xC0
|
|
||||||
private const val CGNAT_SECOND_PREFIX = 64
|
|
||||||
private const val ULA_MASK = 0xFE
|
|
||||||
private const val ULA_PREFIX = 0xFC
|
|
||||||
private const val BYTE = 0xFF
|
|
||||||
|
|
||||||
fun allows(address: InetAddress): Boolean =
|
|
||||||
address.isLoopbackAddress ||
|
|
||||||
address.isSiteLocalAddress || // 10/8, 172.16/12, 192.168/16
|
|
||||||
address.isLinkLocalAddress || // 169.254/16, fe80::/10
|
|
||||||
address.isAnyLocalAddress ||
|
|
||||||
isCarrierGradeNat(address) ||
|
|
||||||
isUniqueLocal(address)
|
|
||||||
|
|
||||||
// 100.64/10. Tailscale and other overlay VPNs hand these out; the overlay
|
|
||||||
// encrypts the traffic itself.
|
|
||||||
private fun isCarrierGradeNat(address: InetAddress): Boolean {
|
|
||||||
if (address !is Inet4Address) return false
|
|
||||||
val b = address.address
|
|
||||||
return (b[0].toInt() and BYTE) == CGNAT_FIRST_OCTET &&
|
|
||||||
(b[1].toInt() and CGNAT_SECOND_MASK) == CGNAT_SECOND_PREFIX
|
|
||||||
}
|
|
||||||
|
|
||||||
// fc00::/7, IPv6's private range.
|
|
||||||
private fun isUniqueLocal(address: InetAddress): Boolean =
|
|
||||||
address is Inet6Address && (address.address[0].toInt() and ULA_MASK) == ULA_PREFIX
|
|
||||||
}
|
|
||||||
@@ -8,7 +8,8 @@ import java.io.IOException
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Maps server error codes (and common transport failures) to
|
* Maps server error codes (and common transport failures) to
|
||||||
* friendly, sentence-case copy.
|
* friendly, sentence-case copy. Mirrors
|
||||||
|
* `flutter_client/assets/error-copy.json` + `error_copy.dart`.
|
||||||
*
|
*
|
||||||
* Server errors are `{"error":{"code":"...","message":"..."}}`.
|
* Server errors are `{"error":{"code":"...","message":"..."}}`.
|
||||||
* [fromThrowable] pulls the code out of a Retrofit [HttpException]'s
|
* [fromThrowable] pulls the code out of a Retrofit [HttpException]'s
|
||||||
@@ -37,51 +38,72 @@ object ErrorCopy {
|
|||||||
* as connection failures.
|
* as connection failures.
|
||||||
*/
|
*/
|
||||||
fun fromThrowable(t: Throwable): String = when (t) {
|
fun fromThrowable(t: Throwable): String = when (t) {
|
||||||
is HttpException -> fromHttp(t)
|
is HttpException -> messageFor(codeFromHttp(t))
|
||||||
is CleartextToPublicHostException -> messageFor("cleartext_public")
|
|
||||||
is IOException -> messageFor("connection_refused")
|
is IOException -> messageFor("connection_refused")
|
||||||
else -> TABLE.getValue("unknown")
|
else -> TABLE.getValue("unknown")
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
private fun codeFromHttp(e: HttpException): String {
|
||||||
* Codes whose server message carries specifics an admin needs in order
|
|
||||||
* to act (which directory, which uid) that fixed copy cannot say. For
|
|
||||||
* these the message follows the copy. Kept to a named set on purpose:
|
|
||||||
* most server messages are internal detail. The set is the web app's
|
|
||||||
* error-detail-codes.json.
|
|
||||||
*/
|
|
||||||
private val DETAIL_CODES: Set<String> by lazy {
|
|
||||||
json.decodeFromString<List<String>>(sharedResource("error-detail-codes.json")).toSet()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun fromHttp(e: HttpException): String {
|
|
||||||
val body = bodyFromHttp(e)
|
|
||||||
val copy = messageFor(body.code.ifEmpty { "unknown" })
|
|
||||||
return if (body.code in DETAIL_CODES && body.message.isNotBlank()) {
|
|
||||||
"$copy ${body.message}"
|
|
||||||
} else {
|
|
||||||
copy
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun bodyFromHttp(e: HttpException): Body {
|
|
||||||
val raw = runCatching { e.response()?.errorBody()?.string() }.getOrNull()
|
val raw = runCatching { e.response()?.errorBody()?.string() }.getOrNull()
|
||||||
?: return Body()
|
?: return "unknown"
|
||||||
return runCatching { json.decodeFromString<Envelope>(raw).error }
|
val code = runCatching { json.decodeFromString<Envelope>(raw).error?.code }
|
||||||
.getOrNull() ?: Body()
|
.getOrNull()
|
||||||
|
.orEmpty()
|
||||||
|
return code.ifEmpty { "unknown" }
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
private val TABLE: Map<String, String> = mapOf(
|
||||||
* The copy for each error code: the web app's error-copy.json, copied
|
"unknown" to "Something went wrong.",
|
||||||
* into the app's resources at build time (app/build.gradle.kts,
|
"unauthenticated" to "Your session has ended. Please sign in again.",
|
||||||
* copySharedCopy), so both clients word every error the same way.
|
"auth_required" to "You need to sign in to do that.",
|
||||||
*/
|
"forbidden" to "You don't have permission to do that.",
|
||||||
private val TABLE: Map<String, String> by lazy {
|
"not_authorized" to "You don't have permission to do that.",
|
||||||
json.decodeFromString<Map<String, String>>(sharedResource("error-copy.json"))
|
"invalid_credentials" to "Wrong username or password.",
|
||||||
}
|
"wrong_password" to "Current password is incorrect.",
|
||||||
|
"password_too_short" to "Password must be at least 8 characters.",
|
||||||
private fun sharedResource(name: String): String =
|
"username_invalid" to "That username isn't valid.",
|
||||||
checkNotNull(ErrorCopy::class.java.getResourceAsStream("/$name")) {
|
"username_taken" to "That username is already taken.",
|
||||||
"$name is missing from the app's resources (copySharedCopy in app/build.gradle.kts)"
|
"email_invalid" to "Enter a valid email address.",
|
||||||
}.use { it.reader().readText() }
|
"email_taken" to "That email is already in use.",
|
||||||
|
"invalid_token" to "That link has expired or already been used. Request a new one.",
|
||||||
|
"invite_invalid" to "That invite has expired or already been used.",
|
||||||
|
"invite_required" to "An invite is required to register on this server.",
|
||||||
|
"last_admin" to "Can't demote or delete the last admin.",
|
||||||
|
"no_email_on_file" to "No email is associated with that account.",
|
||||||
|
"not_configured" to "This integration isn't set up yet.",
|
||||||
|
"validation" to "Some fields aren't valid. Check and try again.",
|
||||||
|
"missing_fields" to "Required fields are missing.",
|
||||||
|
"missing_query" to "Search needs at least one keyword.",
|
||||||
|
"invalid_id" to "Invalid identifier.",
|
||||||
|
"invalid_body" to "Couldn't read the request.",
|
||||||
|
"bad_request" to "Invalid request.",
|
||||||
|
"bad_body" to "Couldn't read the request.",
|
||||||
|
"bad_kind" to "Invalid request type.",
|
||||||
|
"bad_paging" to "Invalid page size or offset.",
|
||||||
|
"bad_reason" to "Invalid quarantine reason.",
|
||||||
|
"mbid_required" to "An MBID is required for this lookup.",
|
||||||
|
"system_playlist_readonly" to "System playlists can't be edited directly.",
|
||||||
|
"connection_refused" to "Couldn't reach the server. Check the URL and try again.",
|
||||||
|
"lidarr_unreachable" to
|
||||||
|
"Lidarr is unreachable right now. Try again, or check Admin → Integrations.",
|
||||||
|
"lidarr_disabled" to "Lidarr integration is not enabled.",
|
||||||
|
"lidarr_auth_failed" to "Lidarr authentication failed.",
|
||||||
|
"lidarr_defaults_incomplete" to
|
||||||
|
"Lidarr is missing a default quality profile or root folder. " +
|
||||||
|
"Set them in Admin → Integrations.",
|
||||||
|
"lidarr_server_error" to "Lidarr returned an error. Check Lidarr's logs for the cause.",
|
||||||
|
"lidarr_rejected" to
|
||||||
|
"Lidarr rejected the request. Check the server logs for the field-level reason.",
|
||||||
|
"lidarr_album_lookup_failed" to
|
||||||
|
"Lidarr doesn't recognize this album. Try Resolve or Delete file instead.",
|
||||||
|
"album_mbid_missing" to "This track has no Lidarr album to remove.",
|
||||||
|
"request_not_pending" to "This request is no longer pending.",
|
||||||
|
"request_not_found" to "That request no longer exists.",
|
||||||
|
"track_not_found" to "That track no longer exists.",
|
||||||
|
"album_not_found" to "That album no longer exists.",
|
||||||
|
"artist_not_found" to "That artist no longer exists.",
|
||||||
|
"playlist_not_found" to "That playlist no longer exists.",
|
||||||
|
"user_not_found" to "That user no longer exists.",
|
||||||
|
"not_found" to "That no longer exists.",
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -57,21 +57,19 @@ object NetworkModule {
|
|||||||
.addInterceptor(reachability)
|
.addInterceptor(reachability)
|
||||||
// AuthCookieInterceptor MUST run before BaseUrlInterceptor.
|
// AuthCookieInterceptor MUST run before BaseUrlInterceptor.
|
||||||
// Both scope on `host == PLACEHOLDER_HOST` to distinguish
|
// Both scope on `host == PLACEHOLDER_HOST` to distinguish
|
||||||
// Minstrel-server requests from external image fetches. If
|
// Minstrel-server requests from external image fetches
|
||||||
// BaseUrlInterceptor runs first it rewrites the host to the real
|
// (drift #568 / #569). If BaseUrlInterceptor runs first it
|
||||||
// server before auth sees the request, auth's placeholder check
|
// rewrites the host to the real server before auth sees the
|
||||||
// fails, and the session cookie is neither attached on outgoing
|
// request, auth's placeholder check fails, and the session
|
||||||
// requests nor captured from Set-Cookie on login — fresh installs
|
// cookie is neither attached on outgoing requests nor
|
||||||
// get stuck at the Welcome screen. Auth first means it sees
|
// captured from Set-Cookie on login — fresh installs get
|
||||||
|
// stuck at the Welcome screen. Auth first means it sees
|
||||||
// placeholder.invalid, attaches/captures correctly, then
|
// placeholder.invalid, attaches/captures correctly, then
|
||||||
// BaseUrlInterceptor retargets to the live AuthStore host for
|
// BaseUrlInterceptor retargets to the live AuthStore host
|
||||||
// transport.
|
// for transport.
|
||||||
.addInterceptor(auth)
|
.addInterceptor(auth)
|
||||||
.addInterceptor(baseUrl)
|
.addInterceptor(baseUrl)
|
||||||
.addInterceptor(logging)
|
.addInterceptor(logging)
|
||||||
// A network interceptor, so it sees the address the connection
|
|
||||||
// really reached and runs before any request byte is written.
|
|
||||||
.addNetworkInterceptor(CleartextGuardInterceptor())
|
|
||||||
.connectTimeout(CONNECT_TIMEOUT_SECONDS, TimeUnit.SECONDS)
|
.connectTimeout(CONNECT_TIMEOUT_SECONDS, TimeUnit.SECONDS)
|
||||||
.readTimeout(READ_TIMEOUT_SECONDS, TimeUnit.SECONDS)
|
.readTimeout(READ_TIMEOUT_SECONDS, TimeUnit.SECONDS)
|
||||||
.build()
|
.build()
|
||||||
|
|||||||
@@ -10,7 +10,8 @@ import retrofit2.http.POST
|
|||||||
import retrofit2.http.Path
|
import retrofit2.http.Path
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for `/api/admin/invites`.
|
* Retrofit interface for `/api/admin/invites`. Mirrors
|
||||||
|
* `flutter_client/lib/api/endpoints/admin_invites.dart`.
|
||||||
*
|
*
|
||||||
* Server TTL is hardcoded at 24h; the only configurable field is the
|
* Server TTL is hardcoded at 24h; the only configurable field is the
|
||||||
* optional `note` on create.
|
* optional `note` on create.
|
||||||
@@ -27,8 +28,9 @@ interface AdminInvitesApi {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Body for `POST /api/admin/invites`. An empty note is sent as null,
|
* Body for `POST /api/admin/invites`. The Flutter client omits the
|
||||||
* which the server treats the same as an absent field.
|
* field when note is empty; Kotlin/serialization just serializes
|
||||||
|
* null which the server treats identically.
|
||||||
*/
|
*/
|
||||||
@Serializable
|
@Serializable
|
||||||
data class CreateInviteBody(val note: String? = null)
|
data class CreateInviteBody(val note: String? = null)
|
||||||
|
|||||||
+8
-8
@@ -6,13 +6,13 @@ import retrofit2.http.POST
|
|||||||
import retrofit2.http.Path
|
import retrofit2.http.Path
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for `/api/admin/quarantine`.
|
* Retrofit interface for `/api/admin/quarantine`. Mirrors
|
||||||
|
* `flutter_client/lib/api/endpoints/admin_quarantine.dart`.
|
||||||
*
|
*
|
||||||
* Three resolution endpoints:
|
* Three resolution endpoints:
|
||||||
* - `resolve` → admin reviewed, no action taken (clears the reports).
|
* - `resolve` → admin reviewed, no action taken (clears flags).
|
||||||
* - `remove-file` → delete the track's file and keep the track, which waits
|
* - `delete-file` → drop the local file; Lidarr keeps the track.
|
||||||
* for a good copy with its likes and plays.
|
* - `delete-via-lidarr` → ask Lidarr to remove the track upstream too.
|
||||||
* - `delete-file` → remove the track from the library, file and history.
|
|
||||||
*/
|
*/
|
||||||
interface AdminQuarantineApi {
|
interface AdminQuarantineApi {
|
||||||
@GET("api/admin/quarantine")
|
@GET("api/admin/quarantine")
|
||||||
@@ -21,9 +21,9 @@ interface AdminQuarantineApi {
|
|||||||
@POST("api/admin/quarantine/{trackId}/resolve")
|
@POST("api/admin/quarantine/{trackId}/resolve")
|
||||||
suspend fun resolve(@Path("trackId") trackId: String)
|
suspend fun resolve(@Path("trackId") trackId: String)
|
||||||
|
|
||||||
@POST("api/admin/quarantine/{trackId}/remove-file")
|
|
||||||
suspend fun removeFile(@Path("trackId") trackId: String)
|
|
||||||
|
|
||||||
@POST("api/admin/quarantine/{trackId}/delete-file")
|
@POST("api/admin/quarantine/{trackId}/delete-file")
|
||||||
suspend fun deleteFile(@Path("trackId") trackId: String)
|
suspend fun deleteFile(@Path("trackId") trackId: String)
|
||||||
|
|
||||||
|
@POST("api/admin/quarantine/{trackId}/delete-via-lidarr")
|
||||||
|
suspend fun deleteViaLidarr(@Path("trackId") trackId: String)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
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`. Mirrors
|
||||||
|
* `flutter_client/lib/api/endpoints/admin_requests.dart`.
|
||||||
|
*
|
||||||
|
* 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)
|
||||||
|
}
|
||||||
+3
-3
@@ -12,9 +12,9 @@ import retrofit2.http.POST
|
|||||||
import retrofit2.http.Path
|
import retrofit2.http.Path
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for `/api/admin/tag-sources` — the admin surface
|
* Retrofit interface for `/api/admin/tag-sources` (#1521) — the admin
|
||||||
* for the tag-enrichment provider settings. Mirrors the web
|
* surface for the tag-enrichment provider settings (#1490). Mirrors the
|
||||||
* integrations "Tag enrichment sources" card. Same shape as the
|
* web integrations "Tag enrichment sources" card. Same shape as the
|
||||||
* cover-sources admin surface; kept independent so a new tag source is
|
* cover-sources admin surface; kept independent so a new tag source is
|
||||||
* added without touching art settings.
|
* added without touching art settings.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -9,7 +9,15 @@ import retrofit2.http.POST
|
|||||||
import retrofit2.http.PUT
|
import retrofit2.http.PUT
|
||||||
import retrofit2.http.Path
|
import retrofit2.http.Path
|
||||||
|
|
||||||
/** Retrofit interface for `/api/admin/users`. */
|
/**
|
||||||
|
* Retrofit interface for `/api/admin/users`. Mirrors
|
||||||
|
* `flutter_client/lib/api/endpoints/admin_users.dart`.
|
||||||
|
*
|
||||||
|
* Note: the PUT-auto-approve body field is `auto_approve`, NOT
|
||||||
|
* `auto_approve_requests` — the request shape differs from the
|
||||||
|
* response field name. Verified against `internal/api/admin_users.go
|
||||||
|
* adminAutoApproveReq` (May 2026).
|
||||||
|
*/
|
||||||
interface AdminUsersApi {
|
interface AdminUsersApi {
|
||||||
@GET("api/admin/users")
|
@GET("api/admin/users")
|
||||||
suspend fun list(): AdminUsersListWire
|
suspend fun list(): AdminUsersListWire
|
||||||
@@ -17,6 +25,9 @@ interface AdminUsersApi {
|
|||||||
@PUT("api/admin/users/{id}/admin")
|
@PUT("api/admin/users/{id}/admin")
|
||||||
suspend fun setAdmin(@Path("id") id: String, @Body body: SetAdminBody)
|
suspend fun setAdmin(@Path("id") id: String, @Body body: SetAdminBody)
|
||||||
|
|
||||||
|
@PUT("api/admin/users/{id}/auto-approve")
|
||||||
|
suspend fun setAutoApprove(@Path("id") id: String, @Body body: SetAutoApproveBody)
|
||||||
|
|
||||||
@POST("api/admin/users/{id}/reset-password")
|
@POST("api/admin/users/{id}/reset-password")
|
||||||
suspend fun resetPassword(@Path("id") id: String, @Body body: ResetPasswordBody)
|
suspend fun resetPassword(@Path("id") id: String, @Body body: ResetPasswordBody)
|
||||||
|
|
||||||
@@ -29,5 +40,10 @@ data class SetAdminBody(
|
|||||||
@kotlinx.serialization.SerialName("is_admin") val isAdmin: Boolean,
|
@kotlinx.serialization.SerialName("is_admin") val isAdmin: Boolean,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class SetAutoApproveBody(
|
||||||
|
@kotlinx.serialization.SerialName("auto_approve") val autoApprove: Boolean,
|
||||||
|
)
|
||||||
|
|
||||||
@Serializable
|
@Serializable
|
||||||
data class ResetPasswordBody(val password: String)
|
data class ResetPasswordBody(val password: String)
|
||||||
|
|||||||
@@ -6,7 +6,8 @@ import retrofit2.http.Body
|
|||||||
import retrofit2.http.POST
|
import retrofit2.http.POST
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for `/api/auth`.
|
* Retrofit interface for `/api/auth`. Mirrors
|
||||||
|
* `flutter_client/lib/api/endpoints/auth.dart`.
|
||||||
*
|
*
|
||||||
* The actual session-cookie capture happens in
|
* The actual session-cookie capture happens in
|
||||||
* [com.fabledsword.minstrel.api.AuthCookieInterceptor]; we don't
|
* [com.fabledsword.minstrel.api.AuthCookieInterceptor]; we don't
|
||||||
|
|||||||
@@ -29,20 +29,11 @@ interface CastApi {
|
|||||||
* Request body. [expSeconds] is clamped server-side to [60, 86400];
|
* Request body. [expSeconds] is clamped server-side to [60, 86400];
|
||||||
* the 21_600 default (6h) is long enough to play through any typical
|
* the 21_600 default (6h) is long enough to play through any typical
|
||||||
* track without re-minting mid-playback.
|
* track without re-minting mid-playback.
|
||||||
*
|
|
||||||
* [level] asks for the leveled stream: the track rendered at
|
|
||||||
* the user's loudness gain, which the server works out from their setting.
|
|
||||||
* [asAlbum] says the track plays among its album in order, which picks
|
|
||||||
* album gain in auto mode. [prerender] says the speaker will fetch it
|
|
||||||
* soon, so the server renders it ahead.
|
|
||||||
*/
|
*/
|
||||||
@Serializable
|
@Serializable
|
||||||
data class StreamTokenRequest(
|
data class StreamTokenRequest(
|
||||||
val trackId: String,
|
val trackId: String,
|
||||||
val expSeconds: Int = 21_600,
|
val expSeconds: Int = 21_600,
|
||||||
val level: Boolean = false,
|
|
||||||
val asAlbum: Boolean = false,
|
|
||||||
val prerender: Boolean = false,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -62,6 +53,4 @@ data class StreamTokenResponse(
|
|||||||
val url: String,
|
val url: String,
|
||||||
val mime: String = "audio/mpeg",
|
val mime: String = "audio/mpeg",
|
||||||
val title: String = "",
|
val title: String = "",
|
||||||
/** [url] is the leveled stream; false when leveling is off or changes nothing. */
|
|
||||||
val leveled: Boolean = false,
|
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import retrofit2.http.Body
|
|||||||
import retrofit2.http.POST
|
import retrofit2.http.POST
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for device diagnostics ingest. One call
|
* Retrofit interface for device diagnostics ingest (M9). One call
|
||||||
* uploads a batch of buffered events. The server stores them only when
|
* uploads a batch of buffered events. The server stores them only when
|
||||||
* the account's debug_mode_enabled flag is on (it returns 204 otherwise,
|
* the account's debug_mode_enabled flag is on (it returns 204 otherwise,
|
||||||
* which the uploader treats as success so it can drop the batch).
|
* which the uploader treats as success so it can drop the batch).
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
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.LidarrSearchResultWire
|
||||||
|
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 / Lidarr search / request creation.
|
||||||
|
* Mirrors `flutter_client/lib/api/endpoints/discover.dart`.
|
||||||
|
*
|
||||||
|
* `/api/lidarr/search` has a 60s LRU on the server so quick re-types
|
||||||
|
* of the same query are cheap.
|
||||||
|
*
|
||||||
|
* Cancel + my-requests-list endpoints live on RequestsApi (Phase 10
|
||||||
|
* Commit B), not here.
|
||||||
|
*/
|
||||||
|
interface DiscoverApi {
|
||||||
|
@GET("api/discover/suggestions")
|
||||||
|
suspend fun listSuggestions(): List<ArtistSuggestionWire>
|
||||||
|
|
||||||
|
@GET("api/lidarr/search")
|
||||||
|
suspend fun search(
|
||||||
|
@Query("q") query: String,
|
||||||
|
@Query("kind") kind: String,
|
||||||
|
): List<LidarrSearchResultWire>
|
||||||
|
|
||||||
|
@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>
|
||||||
|
}
|
||||||
@@ -9,7 +9,8 @@ import retrofit2.http.Body
|
|||||||
import retrofit2.http.POST
|
import retrofit2.http.POST
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for `POST /api/events`. All four
|
* Retrofit interface for `POST /api/events`. Mirrors the relevant
|
||||||
|
* slice of `flutter_client/lib/api/endpoints/events.dart`. All four
|
||||||
* variants share the same URL — the discriminator is in the request
|
* variants share the same URL — the discriminator is in the request
|
||||||
* body's `type` field. Server contract is best-effort per spec;
|
* body's `type` field. Server contract is best-effort per spec;
|
||||||
* callers (the live path in PlayEventsReporter) swallow errors and
|
* callers (the live path in PlayEventsReporter) swallow errors and
|
||||||
|
|||||||
@@ -5,9 +5,10 @@ import retrofit2.http.GET
|
|||||||
import retrofit2.http.Query
|
import retrofit2.http.Query
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for `/api/me/history` — history only. The profile,
|
* Retrofit interface for `/api/me/history`. Mirrors the relevant
|
||||||
* timezone and quarantine endpoints on `/api/me` live with their own
|
* subset of `flutter_client/lib/api/endpoints/me.dart` (only
|
||||||
* features rather than here.
|
* `history()`; profile / timezone / quarantine endpoints land with
|
||||||
|
* their respective phases).
|
||||||
*/
|
*/
|
||||||
interface HistoryApi {
|
interface HistoryApi {
|
||||||
@GET("api/me/history")
|
@GET("api/me/history")
|
||||||
|
|||||||
@@ -4,9 +4,10 @@ import com.fabledsword.minstrel.models.wire.HomeIndexWire
|
|||||||
import retrofit2.http.GET
|
import retrofit2.http.GET
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for the Home discovery endpoint. Only the ID-only
|
* Retrofit interface for the Home discovery endpoint. Mirrors
|
||||||
* `/api/home/index` variant is used. The server also serves a heavier
|
* `flutter_client/lib/api/endpoints/home.dart` — just the ID-only
|
||||||
* `/api/home` (full embedded payload); we don't use it because
|
* `/api/home/index` variant. The Flutter port has a heavier
|
||||||
|
* `/api/home` (full embedded payload) too; we don't use it because
|
||||||
* the per-item hydration path (sync controller → Room → Flow) is
|
* the per-item hydration path (sync controller → Room → Flow) is
|
||||||
* the only one the native client needs.
|
* the only one the native client needs.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -3,16 +3,14 @@ package com.fabledsword.minstrel.api.endpoints
|
|||||||
import com.fabledsword.minstrel.models.wire.AlbumDetailWire
|
import com.fabledsword.minstrel.models.wire.AlbumDetailWire
|
||||||
import com.fabledsword.minstrel.models.wire.ArtistDetailWire
|
import com.fabledsword.minstrel.models.wire.ArtistDetailWire
|
||||||
import com.fabledsword.minstrel.models.wire.ArtistWire
|
import com.fabledsword.minstrel.models.wire.ArtistWire
|
||||||
import com.fabledsword.minstrel.models.wire.GenreCountWire
|
|
||||||
import com.fabledsword.minstrel.models.wire.PagedAlbumsWire
|
|
||||||
import com.fabledsword.minstrel.models.wire.TrackWire
|
import com.fabledsword.minstrel.models.wire.TrackWire
|
||||||
import com.fabledsword.minstrel.models.wire.YearCountWire
|
|
||||||
import retrofit2.http.GET
|
import retrofit2.http.GET
|
||||||
import retrofit2.http.Path
|
import retrofit2.http.Path
|
||||||
import retrofit2.http.Query
|
import retrofit2.http.Query
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for the server's native `/api/...` library surface.
|
* Retrofit interface for the server's native `/api/...` library surface.
|
||||||
|
* Mirrors `flutter_client/lib/api/endpoints/library.dart` 1:1.
|
||||||
*
|
*
|
||||||
* Notes on shapes:
|
* Notes on shapes:
|
||||||
* - `GET /api/artists/{id}` returns ArtistDetailWire (ArtistRef fields
|
* - `GET /api/artists/{id}` returns ArtistDetailWire (ArtistRef fields
|
||||||
@@ -56,48 +54,6 @@ interface LibraryApi {
|
|||||||
@GET("api/library/shuffle")
|
@GET("api/library/shuffle")
|
||||||
suspend fun shuffleLibrary(@Query("limit") limit: Int = 100): List<TrackWire>
|
suspend fun shuffleLibrary(@Query("limit") limit: Int = 100): List<TrackWire>
|
||||||
|
|
||||||
// Browse axes. Both indexes are unpaged by design: the client needs
|
|
||||||
// the whole set to render a browsable picker, and even a messy library
|
|
||||||
// yields hundreds of rows, not thousands.
|
|
||||||
//
|
|
||||||
// These read the server rather than the local cache on purpose: the
|
|
||||||
// server's index leaves out tracks whose files are missing and is the
|
|
||||||
// one the web client shows, so the two clients agree. The cache carries
|
|
||||||
// the same mark (cached_tracks.missing), but an index built from it
|
|
||||||
// would be a second copy of the server's grouping that could drift.
|
|
||||||
@GET("api/library/genres")
|
|
||||||
suspend fun getGenres(): List<GenreCountWire>
|
|
||||||
|
|
||||||
@GET("api/library/years")
|
|
||||||
suspend fun getAlbumYears(): List<YearCountWire>
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Albums carrying [genre] on any of their tracks.
|
|
||||||
*
|
|
||||||
* @Query, never @Path: "Rock/Pop" is a real ID3 tag and a slash cannot
|
|
||||||
* survive a path segment. Retrofit percent-encodes query values correctly;
|
|
||||||
* a @Path would either 404 or silently address a different genre.
|
|
||||||
*/
|
|
||||||
@GET("api/library/albums")
|
|
||||||
suspend fun getAlbumsByGenre(
|
|
||||||
@Query("genre") genre: String,
|
|
||||||
@Query("limit") limit: Int,
|
|
||||||
@Query("offset") offset: Int,
|
|
||||||
): PagedAlbumsWire
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Albums released in an inclusive year range. Pass the same year twice for
|
|
||||||
* a single year. Sending a genre alongside these is a deliberate 400 on the
|
|
||||||
* server (`unsupported_filter_combination`) -- they are separate axes.
|
|
||||||
*/
|
|
||||||
@GET("api/library/albums")
|
|
||||||
suspend fun getAlbumsByYear(
|
|
||||||
@Query("year_from") yearFrom: Int,
|
|
||||||
@Query("year_to") yearTo: Int,
|
|
||||||
@Query("limit") limit: Int,
|
|
||||||
@Query("offset") offset: Int,
|
|
||||||
): PagedAlbumsWire
|
|
||||||
|
|
||||||
private companion object {
|
private companion object {
|
||||||
const val SIMILAR_ARTISTS_LIMIT = 12
|
const val SIMILAR_ARTISTS_LIMIT = 12
|
||||||
const val TOP_TRACKS_LIMIT = 5
|
const val TOP_TRACKS_LIMIT = 5
|
||||||
|
|||||||
@@ -7,7 +7,8 @@ import retrofit2.http.POST
|
|||||||
import retrofit2.http.Path
|
import retrofit2.http.Path
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for `/api/likes`.
|
* Retrofit interface for `/api/likes`. Mirrors
|
||||||
|
* `flutter_client/lib/api/endpoints/likes.dart`.
|
||||||
*
|
*
|
||||||
* Path segment `kind` is one of "artists" | "albums" | "tracks"
|
* Path segment `kind` is one of "artists" | "albums" | "tracks"
|
||||||
* (plural, matching the server route). The Repository hides that
|
* (plural, matching the server route). The Repository hides that
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package com.fabledsword.minstrel.api.endpoints
|
|||||||
import com.fabledsword.minstrel.models.wire.ListenBrainzStatusWire
|
import com.fabledsword.minstrel.models.wire.ListenBrainzStatusWire
|
||||||
import com.fabledsword.minstrel.models.wire.MyProfileWire
|
import com.fabledsword.minstrel.models.wire.MyProfileWire
|
||||||
import com.fabledsword.minstrel.models.wire.SystemPlaylistsStatusWire
|
import com.fabledsword.minstrel.models.wire.SystemPlaylistsStatusWire
|
||||||
import com.fabledsword.minstrel.settings.data.NormalizationPrefs
|
|
||||||
import kotlinx.serialization.SerialName
|
import kotlinx.serialization.SerialName
|
||||||
import kotlinx.serialization.Serializable
|
import kotlinx.serialization.Serializable
|
||||||
import retrofit2.http.Body
|
import retrofit2.http.Body
|
||||||
@@ -12,6 +11,7 @@ import retrofit2.http.PUT
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for the `/api/me` endpoints — caller-scoped account endpoints.
|
* Retrofit interface for the `/api/me` endpoints — caller-scoped account endpoints.
|
||||||
|
* Mirrors the relevant slice of `flutter_client/lib/api/endpoints/settings.dart`.
|
||||||
*
|
*
|
||||||
* History + timezone + system-playlists-status live under /api/me too
|
* History + timezone + system-playlists-status live under /api/me too
|
||||||
* but are handled by their respective feature repositories; this
|
* but are handled by their respective feature repositories; this
|
||||||
@@ -60,14 +60,6 @@ interface MeApi {
|
|||||||
*/
|
*/
|
||||||
@PUT("api/me/listenbrainz")
|
@PUT("api/me/listenbrainz")
|
||||||
suspend fun setListenBrainz(@Body body: ListenBrainzPutBody): ListenBrainzStatusWire
|
suspend fun setListenBrainz(@Body body: ListenBrainzPutBody): ListenBrainzStatusWire
|
||||||
|
|
||||||
/** The caller's loudness-normalization preference, or the defaults if never set. */
|
|
||||||
@GET("api/me/normalization")
|
|
||||||
suspend fun getNormalization(): NormalizationPrefs
|
|
||||||
|
|
||||||
/** Replaces the whole preference; returns what the server stored. */
|
|
||||||
@PUT("api/me/normalization")
|
|
||||||
suspend fun putNormalization(@Body body: NormalizationPrefs): NormalizationPrefs
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -82,20 +74,19 @@ data class UpdateProfileRequest(
|
|||||||
)
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Body for `PUT /api/me/password`. Both passwords required.
|
* Body for `PUT /api/me/password`. Both fields required.
|
||||||
* [signOutSubsonic] also ends every Subsonic app's access: the API token and
|
|
||||||
* Subsonic password stop working.
|
|
||||||
*/
|
*/
|
||||||
@Serializable
|
@Serializable
|
||||||
data class ChangePasswordRequest(
|
data class ChangePasswordRequest(
|
||||||
@SerialName("current_password") val currentPassword: String,
|
@SerialName("current_password") val currentPassword: String,
|
||||||
@SerialName("new_password") val newPassword: String,
|
@SerialName("new_password") val newPassword: String,
|
||||||
@SerialName("sign_out_subsonic") val signOutSubsonic: Boolean = false,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Body for `PUT /api/me/listenbrainz`. Either `token` or `enabled`
|
* Body for `PUT /api/me/listenbrainz`. Either `token` or `enabled`
|
||||||
* is set; the server treats other fields as untouched.
|
* is set; the server treats other fields as untouched. Mirrors
|
||||||
|
* Flutter's `setListenBrainzToken` / `setListenBrainzEnabled` split
|
||||||
|
* over a single endpoint shape.
|
||||||
*/
|
*/
|
||||||
@Serializable
|
@Serializable
|
||||||
data class ListenBrainzPutBody(
|
data class ListenBrainzPutBody(
|
||||||
|
|||||||
@@ -1,90 +0,0 @@
|
|||||||
package com.fabledsword.minstrel.api.endpoints
|
|
||||||
|
|
||||||
import kotlinx.serialization.SerialName
|
|
||||||
import kotlinx.serialization.Serializable
|
|
||||||
import retrofit2.http.Body
|
|
||||||
import retrofit2.http.GET
|
|
||||||
import retrofit2.http.POST
|
|
||||||
import retrofit2.http.PUT
|
|
||||||
import retrofit2.http.Path
|
|
||||||
import retrofit2.http.Query
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The notifications inbox and its per-user settings. The server
|
|
||||||
* renders each notice's title, body and link, so the app shows them as given.
|
|
||||||
*/
|
|
||||||
interface NotificationsApi {
|
|
||||||
@GET("api/me/notifications")
|
|
||||||
suspend fun list(@Query("limit") limit: Int): NotificationsPageWire
|
|
||||||
|
|
||||||
/** 204; 404 when the notice is gone, which a replay treats as done. */
|
|
||||||
@POST("api/me/notifications/{id}/read")
|
|
||||||
suspend fun markRead(@Path("id") id: String)
|
|
||||||
|
|
||||||
@POST("api/me/notifications/read-all")
|
|
||||||
suspend fun readAll(@Body body: ReadAllBody)
|
|
||||||
|
|
||||||
@GET("api/me/notification-settings")
|
|
||||||
suspend fun getSettings(): NotificationSettingsWire
|
|
||||||
|
|
||||||
@PUT("api/me/notification-settings")
|
|
||||||
suspend fun putSettings(@Body body: PutNotificationSettingsBody): NotificationSettingsWire
|
|
||||||
}
|
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class NotificationWire(
|
|
||||||
val id: String,
|
|
||||||
val kind: String,
|
|
||||||
val title: String,
|
|
||||||
val body: String,
|
|
||||||
val link: String,
|
|
||||||
@SerialName("created_at") val createdAt: String,
|
|
||||||
@SerialName("read_at") val readAt: String? = null,
|
|
||||||
)
|
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class NotificationsPageWire(
|
|
||||||
val items: List<NotificationWire>,
|
|
||||||
@SerialName("unread_count") val unreadCount: Long,
|
|
||||||
@SerialName("next_before") val nextBefore: String? = null,
|
|
||||||
)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* `upTo` limits "mark all read" to what existed when the user asked, so a
|
|
||||||
* replay landing later leaves newer notices unread. No default on purpose:
|
|
||||||
* the app's Json drops default-valued fields.
|
|
||||||
*/
|
|
||||||
@Serializable
|
|
||||||
data class ReadAllBody(@SerialName("up_to") val upTo: String?)
|
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class NotificationKindSettingWire(
|
|
||||||
val kind: String,
|
|
||||||
@SerialName("admin_only") val adminOnly: Boolean,
|
|
||||||
val inbox: Boolean,
|
|
||||||
val phone: Boolean,
|
|
||||||
val email: Boolean,
|
|
||||||
)
|
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class NotificationSettingsWire(
|
|
||||||
val kinds: List<NotificationKindSettingWire>,
|
|
||||||
@SerialName("email_available") val emailAvailable: Boolean,
|
|
||||||
@SerialName("email_unavailable_reason") val emailUnavailableReason: String? = null,
|
|
||||||
)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* One kind's change. Untouched channels stay null and, being equal to their
|
|
||||||
* default, are left out of the JSON, so the server changes only the channel
|
|
||||||
* the user touched.
|
|
||||||
*/
|
|
||||||
@Serializable
|
|
||||||
data class NotificationSettingChangeWire(
|
|
||||||
val kind: String,
|
|
||||||
val inbox: Boolean? = null,
|
|
||||||
val phone: Boolean? = null,
|
|
||||||
val email: Boolean? = null,
|
|
||||||
)
|
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class PutNotificationSettingsBody(val kinds: List<NotificationSettingChangeWire>)
|
|
||||||
@@ -5,16 +5,14 @@ import com.fabledsword.minstrel.models.wire.PlaylistsListWire
|
|||||||
import kotlinx.serialization.SerialName
|
import kotlinx.serialization.SerialName
|
||||||
import kotlinx.serialization.Serializable
|
import kotlinx.serialization.Serializable
|
||||||
import retrofit2.http.Body
|
import retrofit2.http.Body
|
||||||
import retrofit2.http.DELETE
|
|
||||||
import retrofit2.http.GET
|
import retrofit2.http.GET
|
||||||
import retrofit2.http.PATCH
|
|
||||||
import retrofit2.http.POST
|
import retrofit2.http.POST
|
||||||
import retrofit2.http.PUT
|
|
||||||
import retrofit2.http.Path
|
import retrofit2.http.Path
|
||||||
import retrofit2.http.Query
|
import retrofit2.http.Query
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for `/api/playlists`.
|
* Retrofit interface for `/api/playlists`. Mirrors
|
||||||
|
* `flutter_client/lib/api/endpoints/playlists.dart`.
|
||||||
*/
|
*/
|
||||||
interface PlaylistsApi {
|
interface PlaylistsApi {
|
||||||
/**
|
/**
|
||||||
@@ -30,41 +28,11 @@ interface PlaylistsApi {
|
|||||||
suspend fun get(@Path("id") id: String): PlaylistDetailWire
|
suspend fun get(@Path("id") id: String): PlaylistDetailWire
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* POST /api/playlists — make a playlist under the id the app chose,
|
* POST /api/playlists/{id}/tracks — append the given track IDs to
|
||||||
* so a create queued offline and sent again finds the same list.
|
* the owner's playlist. Server is idempotent at the (playlist_id,
|
||||||
|
* track_id) pair level; re-firing the same payload yields no
|
||||||
|
* duplicates.
|
||||||
*/
|
*/
|
||||||
@POST("api/playlists")
|
|
||||||
suspend fun create(@Body body: CreatePlaylistRequest)
|
|
||||||
|
|
||||||
/** PATCH /api/playlists/{id} — rename, or make public or private. Null fields stay as they are. */
|
|
||||||
@PATCH("api/playlists/{id}")
|
|
||||||
suspend fun update(@Path("id") id: String, @Body body: UpdatePlaylistRequest)
|
|
||||||
|
|
||||||
@DELETE("api/playlists/{id}")
|
|
||||||
suspend fun delete(@Path("id") id: String)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* DELETE /api/playlists/{id}/tracks/{position}. [trackId] is the song
|
|
||||||
* expected there; if another song has moved into that place the server
|
|
||||||
* removes nothing and answers 409, so a removal sent twice takes out
|
|
||||||
* one song, not two.
|
|
||||||
*/
|
|
||||||
@DELETE("api/playlists/{id}/tracks/{position}")
|
|
||||||
suspend fun removeTrack(
|
|
||||||
@Path("id") id: String,
|
|
||||||
@Path("position") position: Int,
|
|
||||||
@Query("track_id") trackId: String?,
|
|
||||||
)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* PUT /api/playlists/{id}/tracks with the songs in their new order.
|
|
||||||
* Entries not named keep their places, and the same order sent twice
|
|
||||||
* changes nothing the second time.
|
|
||||||
*/
|
|
||||||
@PUT("api/playlists/{id}/tracks")
|
|
||||||
suspend fun reorder(@Path("id") id: String, @Body body: ReorderTracksRequest)
|
|
||||||
|
|
||||||
/** POST /api/playlists/{id}/tracks — append the given track IDs to the owner's playlist. */
|
|
||||||
@POST("api/playlists/{id}/tracks")
|
@POST("api/playlists/{id}/tracks")
|
||||||
suspend fun appendTracks(
|
suspend fun appendTracks(
|
||||||
@Path("id") playlistId: String,
|
@Path("id") playlistId: String,
|
||||||
@@ -82,25 +50,23 @@ interface PlaylistsApi {
|
|||||||
suspend fun refreshSystem(@Path("kind") variant: String): RefreshSystemResponse
|
suspend fun refreshSystem(@Path("kind") variant: String): RefreshSystemResponse
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* GET /api/playlists/system/{kind}/shuffle. Returns
|
* GET /api/playlists/system/{kind}/shuffle (#415 / #411 R2). Returns
|
||||||
* the system playlist's tracks in rotation-aware order without
|
* the system playlist's tracks in rotation-aware order without
|
||||||
* rebuilding — used by the Home play-button overlay so taps on For
|
* rebuilding — used by the Home play-button overlay so taps on For
|
||||||
* You / Discover / Today's mix advance rotation rather than picking
|
* You / Discover / Today's mix advance rotation rather than picking
|
||||||
* the stored order.
|
* the stored order. Mirrors `playlists.dart.systemShuffle`.
|
||||||
*/
|
*/
|
||||||
@GET("api/playlists/system/{kind}/shuffle")
|
@GET("api/playlists/system/{kind}/shuffle")
|
||||||
suspend fun systemShuffle(@Path("kind") variant: String): PlaylistDetailWire
|
suspend fun systemShuffle(@Path("kind") variant: String): PlaylistDetailWire
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* POST /api/playlists/{id}/tracks body. [requestId] names the append: the
|
* POST /api/playlists/{id}/tracks body. Server expects snake_case
|
||||||
* server applies an id once per playlist, so sending it again after a lost
|
* `track_ids` per the Flutter wire shape.
|
||||||
* reply adds nothing more.
|
|
||||||
*/
|
*/
|
||||||
@Serializable
|
@Serializable
|
||||||
data class AppendTracksRequest(
|
data class AppendTracksRequest(
|
||||||
@SerialName("track_ids") val trackIds: List<String>,
|
@SerialName("track_ids") val trackIds: List<String>,
|
||||||
@SerialName("request_id") val requestId: String? = null,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -112,22 +78,3 @@ data class AppendTracksRequest(
|
|||||||
data class RefreshSystemResponse(
|
data class RefreshSystemResponse(
|
||||||
@SerialName("playlist_id") val playlistId: String? = null,
|
@SerialName("playlist_id") val playlistId: String? = null,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class CreatePlaylistRequest(
|
|
||||||
val id: String,
|
|
||||||
val name: String,
|
|
||||||
@SerialName("is_public") val isPublic: Boolean = false,
|
|
||||||
)
|
|
||||||
|
|
||||||
/** PATCH body; a null field is left out, so the server leaves it alone. */
|
|
||||||
@Serializable
|
|
||||||
data class UpdatePlaylistRequest(
|
|
||||||
val name: String? = null,
|
|
||||||
@SerialName("is_public") val isPublic: Boolean? = null,
|
|
||||||
)
|
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class ReorderTracksRequest(
|
|
||||||
@SerialName("track_ids") val trackIds: List<String>,
|
|
||||||
)
|
|
||||||
|
|||||||
@@ -8,12 +8,13 @@ import retrofit2.http.POST
|
|||||||
import retrofit2.http.Path
|
import retrofit2.http.Path
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for `/api/quarantine`: flag and unflag, plus the
|
* Retrofit interface for `/api/quarantine`. Mirrors the relevant
|
||||||
* `/api/quarantine/mine` listing.
|
* parts of `flutter_client/lib/api/endpoints/quarantine.dart` (flag
|
||||||
|
* and unflag) plus the `/api/quarantine/mine` endpoint from `me.dart`.
|
||||||
*
|
*
|
||||||
* Both flag and unflag are user-scoped — callers act on their own
|
* Both flag and unflag are user-scoped — callers act on their own
|
||||||
* quarantine entries. The cross-user admin surface is a separate
|
* quarantine entries. The cross-user admin surface is a separate
|
||||||
* `/api/admin/quarantine` route.
|
* `/api/admin/quarantine` route (Phase 10 Commit D).
|
||||||
*/
|
*/
|
||||||
interface QuarantineApi {
|
interface QuarantineApi {
|
||||||
@GET("api/quarantine/mine")
|
@GET("api/quarantine/mine")
|
||||||
|
|||||||
@@ -5,7 +5,9 @@ import retrofit2.http.GET
|
|||||||
import retrofit2.http.Query
|
import retrofit2.http.Query
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for `/api/radio`. The server picks a fresh shuffle each
|
* Retrofit interface for `/api/radio`. Mirrors the relevant slice of
|
||||||
|
* `flutter_client/lib/api/endpoints/radio.dart` (a single GET that
|
||||||
|
* returns the seeded queue). The server picks a fresh shuffle each
|
||||||
* invocation — clients call this once per radio start.
|
* invocation — clients call this once per radio start.
|
||||||
*/
|
*/
|
||||||
interface RadioApi {
|
interface RadioApi {
|
||||||
|
|||||||
@@ -1,15 +0,0 @@
|
|||||||
package com.fabledsword.minstrel.api.endpoints
|
|
||||||
|
|
||||||
import com.fabledsword.minstrel.models.wire.ReplayGainResponseWire
|
|
||||||
import retrofit2.http.GET
|
|
||||||
import retrofit2.http.Query
|
|
||||||
|
|
||||||
/** The player's loudness lookup, kept apart from the browse surface in [LibraryApi]. */
|
|
||||||
interface ReplayGainApi {
|
|
||||||
/**
|
|
||||||
* ReplayGain values for up to 200 comma-separated track ids. An id
|
|
||||||
* missing from `items` has not been measured yet.
|
|
||||||
*/
|
|
||||||
@GET("api/tracks/replay-gain")
|
|
||||||
suspend fun getReplayGain(@Query("ids") ids: String): ReplayGainResponseWire
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
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`. Mirrors
|
||||||
|
* `flutter_client/lib/api/endpoints/requests.dart`.
|
||||||
|
*
|
||||||
|
* 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 (Phase 10 Commit D).
|
||||||
|
*
|
||||||
|
* 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
|
||||||
|
}
|
||||||
@@ -5,7 +5,8 @@ import retrofit2.http.GET
|
|||||||
import retrofit2.http.Query
|
import retrofit2.http.Query
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for `GET /api/search`. Server returns 400
|
* Retrofit interface for `GET /api/search`. Mirrors
|
||||||
|
* `flutter_client/lib/api/endpoints/search.dart`. Server returns 400
|
||||||
* on empty/whitespace-only `q` — the caller is responsible for
|
* on empty/whitespace-only `q` — the caller is responsible for
|
||||||
* guarding.
|
* guarding.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import retrofit2.http.GET
|
|||||||
import retrofit2.http.Query
|
import retrofit2.http.Query
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for `/api/library/sync`. The endpoint
|
* Retrofit interface for `/api/library/sync` (#357). The endpoint
|
||||||
* returns three possible status codes that the SyncController
|
* returns three possible status codes that the SyncController
|
||||||
* branches on:
|
* branches on:
|
||||||
* - 200: parsed body with cursor + upserts + deletes
|
* - 200: parsed body with cursor + upserts + deletes
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ import kotlinx.coroutines.flow.MutableStateFlow
|
|||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.withTimeoutOrNull
|
|
||||||
import kotlinx.serialization.json.Json
|
import kotlinx.serialization.json.Json
|
||||||
import retrofit2.Retrofit
|
import retrofit2.Retrofit
|
||||||
import retrofit2.create
|
import retrofit2.create
|
||||||
@@ -18,7 +17,8 @@ import javax.inject.Inject
|
|||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Singleton facade over the auth state machine.
|
* Singleton facade over the auth state machine. Mirrors Flutter's
|
||||||
|
* `AuthController` from `auth_provider.dart`.
|
||||||
*
|
*
|
||||||
* Cookie persistence is handled by [AuthCookieInterceptor] capturing
|
* Cookie persistence is handled by [AuthCookieInterceptor] capturing
|
||||||
* Set-Cookie on the login response; the user identity itself
|
* Set-Cookie on the login response; the user identity itself
|
||||||
@@ -58,7 +58,7 @@ class AuthController @Inject constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Refresh from /api/me on startup so a remotely-changed account
|
// Refresh from /api/me on startup so a remotely-changed account
|
||||||
// flag (e.g. an admin enabling debug mode) reaches the device
|
// flag (e.g. admin enabling debug mode, M9) reaches the device
|
||||||
// without a re-login. Best-effort; failures keep the cached value.
|
// without a re-login. Best-effort; failures keep the cached value.
|
||||||
scope.launch { refreshProfile() }
|
scope.launch { refreshProfile() }
|
||||||
}
|
}
|
||||||
@@ -90,11 +90,8 @@ class AuthController @Inject constructor(
|
|||||||
* + persisted userJson. Carries account-level flags (debug mode)
|
* + persisted userJson. Carries account-level flags (debug mode)
|
||||||
* that aren't in the login response. Best-effort: a network failure
|
* that aren't in the login response. Best-effort: a network failure
|
||||||
* leaves the cached identity untouched. No-op when signed out.
|
* leaves the cached identity untouched. No-op when signed out.
|
||||||
* Waits for the stored login to load first: at launch this runs before
|
|
||||||
* it has, and would otherwise read the user as signed out and skip.
|
|
||||||
*/
|
*/
|
||||||
suspend fun refreshProfile() {
|
suspend fun refreshProfile() {
|
||||||
authStore.awaitSessionHydrated()
|
|
||||||
if (!isSignedIn) return
|
if (!isSignedIn) return
|
||||||
val p = runCatching { meApi.getProfile() }.getOrNull() ?: return
|
val p = runCatching { meApi.getProfile() }.getOrNull() ?: return
|
||||||
val user = UserRef(
|
val user = UserRef(
|
||||||
@@ -108,35 +105,18 @@ class AuthController @Inject constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Signs out here at once and ends the session on the server too.
|
* Clears the local session immediately and best-effort hits
|
||||||
*
|
* `/api/auth/logout` so the server can drop its session row.
|
||||||
* The app shows signed-out straight away, then calls
|
* Network errors are swallowed — the user is already locally
|
||||||
* `/api/auth/logout` while the session cookie is still set: the cookie
|
* signed out and a stale server session times out on its own.
|
||||||
* is what tells the server which session to drop, so the call has to go
|
|
||||||
* before the cookie is cleared. The call waits at most
|
|
||||||
* [LOGOUT_TIMEOUT_MS]; offline, or on an error, the cookie is cleared
|
|
||||||
* anyway and the server session expires on its own. It runs in the
|
|
||||||
* application scope, so the screen that asked closing as the app shows
|
|
||||||
* signed-out can't cancel it halfway.
|
|
||||||
*/
|
*/
|
||||||
suspend fun signOut() {
|
suspend fun signOut() {
|
||||||
currentUserState.value = null
|
currentUserState.value = null
|
||||||
|
authStore.setSessionCookie(null)
|
||||||
authStore.setUserJson(null)
|
authStore.setUserJson(null)
|
||||||
scope.launch {
|
runCatching { api.logout() }
|
||||||
try {
|
|
||||||
withTimeoutOrNull(LOGOUT_TIMEOUT_MS) { runCatching { api.logout() } }
|
|
||||||
} finally {
|
|
||||||
authStore.setSessionCookie(null)
|
|
||||||
}
|
|
||||||
}.join()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun decodeUser(raw: String): UserRef? =
|
private fun decodeUser(raw: String): UserRef? =
|
||||||
runCatching { json.decodeFromString(UserRef.serializer(), raw) }.getOrNull()
|
runCatching { json.decodeFromString(UserRef.serializer(), raw) }.getOrNull()
|
||||||
|
|
||||||
private companion object {
|
|
||||||
// Long enough for a logout on a slow connection, short enough that
|
|
||||||
// signing out offline doesn't seem to hang.
|
|
||||||
const val LOGOUT_TIMEOUT_MS = 5_000L
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,20 +4,12 @@ import com.fabledsword.minstrel.cache.audiocache.CacheSettings
|
|||||||
import com.fabledsword.minstrel.cache.db.dao.AuthSessionDao
|
import com.fabledsword.minstrel.cache.db.dao.AuthSessionDao
|
||||||
import com.fabledsword.minstrel.cache.db.entities.AuthSessionEntity
|
import com.fabledsword.minstrel.cache.db.entities.AuthSessionEntity
|
||||||
import com.fabledsword.minstrel.di.ApplicationScope
|
import com.fabledsword.minstrel.di.ApplicationScope
|
||||||
import com.fabledsword.minstrel.settings.data.NormalizationPrefs
|
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Deferred
|
|
||||||
import kotlinx.coroutines.async
|
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.runBlocking
|
|
||||||
import kotlinx.coroutines.sync.Mutex
|
|
||||||
import kotlinx.coroutines.sync.withLock
|
|
||||||
import kotlinx.coroutines.withTimeoutOrNull
|
|
||||||
import kotlinx.serialization.json.Json
|
import kotlinx.serialization.json.Json
|
||||||
import timber.log.Timber
|
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
|
||||||
@@ -35,14 +27,6 @@ import javax.inject.Singleton
|
|||||||
* in-memory state changes synchronously so the next interceptor read
|
* in-memory state changes synchronously so the next interceptor read
|
||||||
* sees the new value immediately; the DAO write coroutine catches up
|
* sees the new value immediately; the DAO write coroutine catches up
|
||||||
* shortly after.
|
* shortly after.
|
||||||
*
|
|
||||||
* **The session cookie is the exception**: it is persisted through
|
|
||||||
* [SessionVault] (Keystore-encrypted), not the Room row. A cookie still
|
|
||||||
* in the row is moved into the vault on launch and the column cleared,
|
|
||||||
* so nobody is signed out by the move. If the Keystore cannot be used
|
|
||||||
* on a device, the cookie stays in the row rather than being lost.
|
|
||||||
* [awaitSessionHydrated] lets a caller that needs a definitive answer
|
|
||||||
* (the auth gate) wait for this.
|
|
||||||
*/
|
*/
|
||||||
// AuthStore is the single-row facade over auth_session (de-facto
|
// AuthStore is the single-row facade over auth_session (de-facto
|
||||||
// app_preferences — see entity comment). It legitimately owns one
|
// app_preferences — see entity comment). It legitimately owns one
|
||||||
@@ -55,7 +39,6 @@ import javax.inject.Singleton
|
|||||||
@Singleton
|
@Singleton
|
||||||
class AuthStore @Inject constructor(
|
class AuthStore @Inject constructor(
|
||||||
private val dao: AuthSessionDao,
|
private val dao: AuthSessionDao,
|
||||||
private val vault: SessionVault,
|
|
||||||
@ApplicationScope private val scope: CoroutineScope,
|
@ApplicationScope private val scope: CoroutineScope,
|
||||||
) {
|
) {
|
||||||
private val sessionCookieState = MutableStateFlow<String?>(null)
|
private val sessionCookieState = MutableStateFlow<String?>(null)
|
||||||
@@ -79,52 +62,18 @@ class AuthStore @Inject constructor(
|
|||||||
private val diagnosticsOptOutState = MutableStateFlow(false)
|
private val diagnosticsOptOutState = MutableStateFlow(false)
|
||||||
val diagnosticsOptOut: StateFlow<Boolean> = diagnosticsOptOutState.asStateFlow()
|
val diagnosticsOptOut: StateFlow<Boolean> = diagnosticsOptOutState.asStateFlow()
|
||||||
|
|
||||||
private val normalizationState = MutableStateFlow(NormalizationPrefs.DEFAULT)
|
|
||||||
val normalization: StateFlow<NormalizationPrefs> = normalizationState.asStateFlow()
|
|
||||||
|
|
||||||
// Background delivery: the device's choice, on by default.
|
|
||||||
// The shade's high-water mark lives in the same row but is read and
|
|
||||||
// written through the DAO by NotificationSync, awaited, never cached here.
|
|
||||||
private val backgroundDeliveryState = MutableStateFlow(true)
|
|
||||||
val backgroundDelivery: StateFlow<Boolean> = backgroundDeliveryState.asStateFlow()
|
|
||||||
|
|
||||||
// The account the cached data belongs to (AuthSessionEntity.cacheOwnerUserId).
|
|
||||||
// Null while the stored row is still loading, and before any account
|
|
||||||
// has been adopted; [settingsLoaded] tells the two apart.
|
|
||||||
private val cacheOwnerState = MutableStateFlow<String?>(null)
|
|
||||||
val cacheOwnerUserId: StateFlow<String?> = cacheOwnerState.asStateFlow()
|
|
||||||
|
|
||||||
private val settingsLoadedState = MutableStateFlow(false)
|
|
||||||
|
|
||||||
/** True once the stored settings row has been read at least once. */
|
|
||||||
val settingsLoaded: StateFlow<Boolean> = settingsLoadedState.asStateFlow()
|
|
||||||
|
|
||||||
private val json = Json { ignoreUnknownKeys = true }
|
private val json = Json { ignoreUnknownKeys = true }
|
||||||
|
|
||||||
// Serialises every cookie persist with the one-time hydration, so a
|
|
||||||
// sign-in or a 401 that lands while hydration runs is never overwritten
|
|
||||||
// by the stale value hydration read.
|
|
||||||
private val cookieLock = Mutex()
|
|
||||||
|
|
||||||
// Set by setSessionCookie. Once something has written the cookie this
|
|
||||||
// process, that value wins over whatever hydration finds on disk.
|
|
||||||
@Volatile private var cookieTouched = false
|
|
||||||
|
|
||||||
private val cookieHydration: Deferred<Unit> = scope.async { hydrateSessionCookie() }
|
|
||||||
|
|
||||||
init {
|
init {
|
||||||
scope.launch {
|
scope.launch {
|
||||||
dao.observe().collect { row ->
|
dao.observe().collect { row ->
|
||||||
|
sessionCookieState.value = row?.sessionCookie
|
||||||
baseUrlState.value = row?.baseUrl ?: DEFAULT_BASE_URL
|
baseUrlState.value = row?.baseUrl ?: DEFAULT_BASE_URL
|
||||||
userJsonState.value = row?.userJson
|
userJsonState.value = row?.userJson
|
||||||
themeModeState.value = row?.themeMode
|
themeModeState.value = row?.themeMode
|
||||||
clientIdState.value = row?.clientId
|
clientIdState.value = row?.clientId
|
||||||
cacheSettingsState.value = decodeCacheSettings(row?.cacheSettingsJson)
|
cacheSettingsState.value = decodeCacheSettings(row?.cacheSettingsJson)
|
||||||
diagnosticsOptOutState.value = row?.diagnosticsOptOut ?: false
|
diagnosticsOptOutState.value = row?.diagnosticsOptOut ?: false
|
||||||
normalizationState.value = decodeNormalization(row?.normalizationJson)
|
|
||||||
backgroundDeliveryState.value = row?.backgroundDelivery ?: true
|
|
||||||
cacheOwnerState.value = row?.cacheOwnerUserId
|
|
||||||
settingsLoadedState.value = true
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -136,100 +85,9 @@ class AuthStore @Inject constructor(
|
|||||||
}.getOrDefault(CacheSettings.DEFAULT)
|
}.getOrDefault(CacheSettings.DEFAULT)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun decodeNormalization(raw: String?): NormalizationPrefs {
|
|
||||||
if (raw.isNullOrEmpty()) return NormalizationPrefs.DEFAULT
|
|
||||||
return runCatching {
|
|
||||||
json.decodeFromString(NormalizationPrefs.serializer(), raw)
|
|
||||||
}.getOrDefault(NormalizationPrefs.DEFAULT)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Suspends until the stored session cookie has been loaded into
|
|
||||||
* [sessionCookie], or [HYDRATION_DEADLINE_MS] passes, so a wedged
|
|
||||||
* Keystore cannot leave the start screen spinning. Returns false on
|
|
||||||
* the deadline; the caller then decides from whatever has loaded, and a
|
|
||||||
* late hydration still lands in [sessionCookie].
|
|
||||||
*/
|
|
||||||
suspend fun awaitSessionHydrated(): Boolean {
|
|
||||||
val done = withTimeoutOrNull(HYDRATION_DEADLINE_MS) { cookieHydration.await() } != null
|
|
||||||
if (!done) Timber.w("auth store: session hydration passed its deadline; deciding without it")
|
|
||||||
return done
|
|
||||||
}
|
|
||||||
|
|
||||||
fun setSessionCookie(value: String?) {
|
fun setSessionCookie(value: String?) {
|
||||||
cookieTouched = true
|
|
||||||
sessionCookieState.value = value
|
sessionCookieState.value = value
|
||||||
scope.launch { cookieLock.withLock { storeCookie(value) } }
|
scope.launch { persistCookie(value) }
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The cookie to attach to an outgoing request. Blocks the calling
|
|
||||||
* (OkHttp) thread until the stored cookie has loaded, up to
|
|
||||||
* [HYDRATION_DEADLINE_MS], so a request made in the first moment after
|
|
||||||
* launch carries the login instead of going out without it. Once
|
|
||||||
* hydration has finished this is a plain read.
|
|
||||||
*/
|
|
||||||
fun sessionCookieForRequest(): String? {
|
|
||||||
if (!cookieHydration.isCompleted) {
|
|
||||||
runBlocking { withTimeoutOrNull(HYDRATION_DEADLINE_MS) { cookieHydration.await() } }
|
|
||||||
}
|
|
||||||
return sessionCookieState.value
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* True once the server has refused the current session (see
|
|
||||||
* [dropRejectedSessionCookie]) and the UI has not yet sent the user to
|
|
||||||
* sign in. Held rather than fired, so a refusal that lands while the app
|
|
||||||
* is in the background is still acted on when it comes back. A sign-out
|
|
||||||
* the user asked for does not set it.
|
|
||||||
*/
|
|
||||||
private val sessionRejectedState = MutableStateFlow(false)
|
|
||||||
val sessionRejected: StateFlow<Boolean> = sessionRejectedState.asStateFlow()
|
|
||||||
|
|
||||||
/** The UI has opened the sign-in screen for a refused session. */
|
|
||||||
fun consumeSessionRejected() {
|
|
||||||
sessionRejectedState.value = false
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Signs out because the server answered 401 to a request that carried
|
|
||||||
* [rejected]. Does nothing when the store has since moved on to another
|
|
||||||
* cookie (a sign-in landed meanwhile), so a refusal of an old session
|
|
||||||
* never discards a new one. What is persisted is read inside the lock,
|
|
||||||
* so a sign-in racing this call is the value that ends up stored.
|
|
||||||
*/
|
|
||||||
fun dropRejectedSessionCookie(rejected: String) {
|
|
||||||
if (!sessionCookieState.compareAndSet(rejected, null)) return
|
|
||||||
cookieTouched = true
|
|
||||||
scope.launch { cookieLock.withLock { storeCookie(sessionCookieState.value) } }
|
|
||||||
sessionRejectedState.value = true
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun hydrateSessionCookie() = cookieLock.withLock {
|
|
||||||
val legacy = runCatching { dao.get()?.sessionCookie }.getOrNull()
|
|
||||||
if (cookieTouched) return@withLock
|
|
||||||
// A cookie in the row is the newer one when both exist: the row is
|
|
||||||
// only written when the vault failed, and an install upgrading from
|
|
||||||
// before the vault has nothing in the vault yet.
|
|
||||||
val cookie = legacy ?: vault.read()
|
|
||||||
// Best-effort: if moving it fails, the session still loads this time
|
|
||||||
// and the move is retried on the next launch. Hydration must never
|
|
||||||
// throw, or awaitSessionHydrated would leave the auth gate stuck.
|
|
||||||
if (legacy != null) {
|
|
||||||
runCatching { storeCookie(legacy) }
|
|
||||||
.onFailure { Timber.w(it, "auth store: could not move the session cookie into the vault") }
|
|
||||||
}
|
|
||||||
sessionCookieState.value = cookie
|
|
||||||
}
|
|
||||||
|
|
||||||
// Vault first; the Room row only when the Keystore is unusable, so a
|
|
||||||
// broken Keystore degrades to the old storage rather than a sign-out.
|
|
||||||
private suspend fun storeCookie(value: String?) {
|
|
||||||
if (vault.write(value)) {
|
|
||||||
if (dao.get()?.sessionCookie != null) dao.setSessionCookie(null)
|
|
||||||
} else {
|
|
||||||
persistLegacyCookie(value)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun setBaseUrl(value: String) {
|
fun setBaseUrl(value: String) {
|
||||||
@@ -263,43 +121,7 @@ class AuthStore @Inject constructor(
|
|||||||
scope.launch { persistDiagnosticsOptOut(value) }
|
scope.launch { persistDiagnosticsOptOut(value) }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun setNormalization(value: NormalizationPrefs) {
|
private suspend fun persistCookie(value: String?) {
|
||||||
normalizationState.value = value
|
|
||||||
val encoded = json.encodeToString(NormalizationPrefs.serializer(), value)
|
|
||||||
scope.launch { persistNormalization(encoded) }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun setBackgroundDelivery(value: Boolean) {
|
|
||||||
backgroundDeliveryState.value = value
|
|
||||||
scope.launch {
|
|
||||||
if (dao.get() == null) {
|
|
||||||
dao.upsert(currentEntity().copy(backgroundDelivery = value))
|
|
||||||
} else {
|
|
||||||
dao.setBackgroundDelivery(value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Records which account the cached data now belongs to. Suspends until
|
|
||||||
* it is stored, so a caller that has just cleared the old account's
|
|
||||||
* data can't have the adoption lost to a crash in between.
|
|
||||||
*/
|
|
||||||
suspend fun setCacheOwnerUserId(value: String?) {
|
|
||||||
cacheOwnerState.value = value
|
|
||||||
if (dao.get() == null) {
|
|
||||||
dao.upsert(currentEntity().copy(cacheOwnerUserId = value))
|
|
||||||
} else {
|
|
||||||
dao.setCacheOwnerUserId(value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Forgets the newest notice announced, so the next account starts fresh. */
|
|
||||||
suspend fun clearNotifiedUpTo() {
|
|
||||||
if (dao.get() != null) dao.setNotifiedUpTo(null)
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun persistLegacyCookie(value: String?) {
|
|
||||||
if (dao.get() == null) {
|
if (dao.get() == null) {
|
||||||
dao.upsert(currentEntity().copy(sessionCookie = value))
|
dao.upsert(currentEntity().copy(sessionCookie = value))
|
||||||
} else {
|
} else {
|
||||||
@@ -355,19 +177,9 @@ class AuthStore @Inject constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun persistNormalization(json: String) {
|
|
||||||
if (dao.get() == null) {
|
|
||||||
dao.upsert(currentEntity().copy(normalizationJson = json))
|
|
||||||
} else {
|
|
||||||
dao.setNormalizationJson(json)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun currentEntity(): AuthSessionEntity = AuthSessionEntity(
|
private fun currentEntity(): AuthSessionEntity = AuthSessionEntity(
|
||||||
id = ROW_ID,
|
id = ROW_ID,
|
||||||
// Never copied into the row: the cookie lives in the vault, and
|
sessionCookie = sessionCookieState.value,
|
||||||
// persistLegacyCookie sets it explicitly on the fallback path.
|
|
||||||
sessionCookie = null,
|
|
||||||
baseUrl = baseUrlState.value,
|
baseUrl = baseUrlState.value,
|
||||||
userJson = userJsonState.value,
|
userJson = userJsonState.value,
|
||||||
themeMode = themeModeState.value,
|
themeMode = themeModeState.value,
|
||||||
@@ -377,20 +189,10 @@ class AuthStore @Inject constructor(
|
|||||||
cacheSettingsState.value,
|
cacheSettingsState.value,
|
||||||
),
|
),
|
||||||
diagnosticsOptOut = diagnosticsOptOutState.value,
|
diagnosticsOptOut = diagnosticsOptOutState.value,
|
||||||
normalizationJson = json.encodeToString(
|
|
||||||
NormalizationPrefs.serializer(),
|
|
||||||
normalizationState.value,
|
|
||||||
),
|
|
||||||
backgroundDelivery = backgroundDeliveryState.value,
|
|
||||||
cacheOwnerUserId = cacheOwnerState.value,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
const val DEFAULT_BASE_URL: String = "http://localhost:8080"
|
const val DEFAULT_BASE_URL: String = "http://localhost:8080"
|
||||||
|
|
||||||
// Generous on purpose: hydration is one local row read and one
|
|
||||||
// Keystore decrypt, normally milliseconds. This only bounds "never".
|
|
||||||
const val HYDRATION_DEADLINE_MS: Long = 10_000
|
|
||||||
private const val ROW_ID = 0
|
private const val ROW_ID = 0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,24 +0,0 @@
|
|||||||
package com.fabledsword.minstrel.auth
|
|
||||||
|
|
||||||
import com.fabledsword.minstrel.api.ErrorCopy
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The rules every new-password field shares (Settings › Password, an admin
|
|
||||||
* resetting someone's password), worded as the web app words them
|
|
||||||
* (web/src/lib/auth/password.ts). The server enforces the same minimum and
|
|
||||||
* answers password_too_short; checking here only saves the round trip.
|
|
||||||
*/
|
|
||||||
object PasswordRules {
|
|
||||||
const val MIN_LENGTH = 8
|
|
||||||
|
|
||||||
/** The hint under a new-password field. */
|
|
||||||
const val HINT = "At least $MIN_LENGTH characters."
|
|
||||||
|
|
||||||
/** Said when a new password is shorter than [MIN_LENGTH]: the server's own wording for it. */
|
|
||||||
val TOO_SHORT: String get() = ErrorCopy.messageFor("password_too_short")
|
|
||||||
|
|
||||||
/** Said when a password and its confirmation differ. */
|
|
||||||
const val DIFFER = "Passwords do not match."
|
|
||||||
|
|
||||||
fun isLongEnough(password: String): Boolean = password.length >= MIN_LENGTH
|
|
||||||
}
|
|
||||||
@@ -1,146 +0,0 @@
|
|||||||
package com.fabledsword.minstrel.auth
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.security.keystore.KeyGenParameterSpec
|
|
||||||
import android.security.keystore.KeyProperties
|
|
||||||
import dagger.Binds
|
|
||||||
import dagger.Module
|
|
||||||
import dagger.hilt.InstallIn
|
|
||||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
|
||||||
import dagger.hilt.components.SingletonComponent
|
|
||||||
import timber.log.Timber
|
|
||||||
import java.security.KeyStore
|
|
||||||
import java.util.Base64
|
|
||||||
import javax.crypto.Cipher
|
|
||||||
import javax.crypto.KeyGenerator
|
|
||||||
import javax.crypto.SecretKey
|
|
||||||
import javax.crypto.spec.GCMParameterSpec
|
|
||||||
import javax.inject.Inject
|
|
||||||
import javax.inject.Singleton
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Where the session cookie lives at rest.
|
|
||||||
*
|
|
||||||
* The cookie is a bearer credential: anyone holding it is signed in as the
|
|
||||||
* user until the server expires or revokes it. In plain text it would be
|
|
||||||
* readable from any copy of the app's data directory (a rooted device, an
|
|
||||||
* adb backup of a debuggable build, a forensic image). Only ciphertext is
|
|
||||||
* stored, under an AES key that lives in the Android Keystore and never
|
|
||||||
* leaves it, so a copy of the files alone yields nothing usable.
|
|
||||||
*/
|
|
||||||
interface SessionVault {
|
|
||||||
/** The stored cookie, or null when none is stored or it can't be decrypted. */
|
|
||||||
fun read(): String?
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Stores [value], or clears the stored cookie when null. Returns false
|
|
||||||
* when the Keystore could not be used, so the caller can fall back
|
|
||||||
* rather than lose the session.
|
|
||||||
*/
|
|
||||||
fun write(value: String?): Boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* AES-GCM sealing of a short string, framed as base64(iv || ciphertext+tag).
|
|
||||||
* Kept apart from the Keystore so the framing can be unit-tested on the JVM
|
|
||||||
* with an ordinary key; the Android Keystore has no JVM implementation.
|
|
||||||
*/
|
|
||||||
internal object SealedBox {
|
|
||||||
private const val TRANSFORMATION = "AES/GCM/NoPadding"
|
|
||||||
private const val TAG_BITS = 128
|
|
||||||
private const val IV_BYTES = 12
|
|
||||||
|
|
||||||
// Binds a sealed value to its purpose: a blob sealed for something else
|
|
||||||
// under the same key will not open as a session cookie.
|
|
||||||
private val AAD = "minstrel-session-cookie-v1".toByteArray(Charsets.UTF_8)
|
|
||||||
|
|
||||||
fun seal(key: SecretKey, plaintext: String): String {
|
|
||||||
val cipher = Cipher.getInstance(TRANSFORMATION)
|
|
||||||
// No IV passed: the provider generates a fresh random one. Keystore
|
|
||||||
// keys refuse a caller-chosen IV for encryption by default.
|
|
||||||
cipher.init(Cipher.ENCRYPT_MODE, key)
|
|
||||||
cipher.updateAAD(AAD)
|
|
||||||
val sealed = cipher.iv + cipher.doFinal(plaintext.toByteArray(Charsets.UTF_8))
|
|
||||||
return Base64.getEncoder().encodeToString(sealed)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun open(key: SecretKey, sealed: String): String {
|
|
||||||
val bytes = Base64.getDecoder().decode(sealed)
|
|
||||||
require(bytes.size > IV_BYTES) { "sealed value too short" }
|
|
||||||
val cipher = Cipher.getInstance(TRANSFORMATION)
|
|
||||||
cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(TAG_BITS, bytes, 0, IV_BYTES))
|
|
||||||
cipher.updateAAD(AAD)
|
|
||||||
return String(cipher.doFinal(bytes, IV_BYTES, bytes.size - IV_BYTES), Charsets.UTF_8)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* [SessionVault] backed by a Keystore AES key and a private prefs file that
|
|
||||||
* holds only the sealed value.
|
|
||||||
*
|
|
||||||
* A value that will not open (the key was wiped by a factory-reset of the
|
|
||||||
* Keystore, or the file was restored onto another device; app backup is off,
|
|
||||||
* but a vendor transfer tool may still copy files) is discarded and reported
|
|
||||||
* as absent. The user signs in again, which is the right outcome for a
|
|
||||||
* credential that no longer verifies.
|
|
||||||
*/
|
|
||||||
@Singleton
|
|
||||||
class KeystoreSessionVault @Inject constructor(
|
|
||||||
@ApplicationContext context: Context,
|
|
||||||
) : SessionVault {
|
|
||||||
private val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
|
||||||
|
|
||||||
override fun read(): String? {
|
|
||||||
val sealed = prefs.getString(KEY_COOKIE, null) ?: return null
|
|
||||||
return runCatching { SealedBox.open(key(), sealed) }
|
|
||||||
.onFailure {
|
|
||||||
Timber.w(it, "session vault: stored cookie would not decrypt; discarding it")
|
|
||||||
prefs.edit().remove(KEY_COOKIE).commit()
|
|
||||||
}
|
|
||||||
.getOrNull()
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun write(value: String?): Boolean = runCatching {
|
|
||||||
val editor = prefs.edit()
|
|
||||||
if (value == null) {
|
|
||||||
editor.remove(KEY_COOKIE)
|
|
||||||
} else {
|
|
||||||
editor.putString(KEY_COOKIE, SealedBox.seal(key(), value))
|
|
||||||
}
|
|
||||||
editor.commit()
|
|
||||||
}.onFailure {
|
|
||||||
Timber.w(it, "session vault: Keystore unavailable; cookie not stored in the vault")
|
|
||||||
}.getOrDefault(false)
|
|
||||||
|
|
||||||
private fun key(): SecretKey {
|
|
||||||
val keyStore = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }
|
|
||||||
(keyStore.getKey(KEY_ALIAS, null) as? SecretKey)?.let { return it }
|
|
||||||
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE)
|
|
||||||
generator.init(
|
|
||||||
KeyGenParameterSpec.Builder(
|
|
||||||
KEY_ALIAS,
|
|
||||||
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
|
|
||||||
)
|
|
||||||
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
|
||||||
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
|
||||||
.setKeySize(KEY_BITS)
|
|
||||||
.build(),
|
|
||||||
)
|
|
||||||
return generator.generateKey()
|
|
||||||
}
|
|
||||||
|
|
||||||
private companion object {
|
|
||||||
const val ANDROID_KEYSTORE = "AndroidKeyStore"
|
|
||||||
const val KEY_ALIAS = "minstrel_session_cookie"
|
|
||||||
const val KEY_BITS = 256
|
|
||||||
const val PREFS_NAME = "session_vault"
|
|
||||||
const val KEY_COOKIE = "sealed_cookie"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Module
|
|
||||||
@InstallIn(SingletonComponent::class)
|
|
||||||
abstract class SessionVaultModule {
|
|
||||||
@Binds
|
|
||||||
abstract fun bindSessionVault(impl: KeystoreSessionVault): SessionVault
|
|
||||||
}
|
|
||||||
@@ -16,11 +16,10 @@ import javax.inject.Inject
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Computes the initial startDestination for the root NavHost based on
|
* Computes the initial startDestination for the root NavHost based on
|
||||||
* persisted auth state. Reads the row from AuthSessionDao directly, and
|
* persisted auth state. Sits on top of AuthSessionDao directly rather
|
||||||
* the session cookie only after [AuthStore.awaitSessionHydrated]: both
|
* than AuthStore's StateFlow because the StateFlow defaults to null
|
||||||
* StateFlows default to null until their async load lands, and we need a
|
* until Room's first async emission — we need a definitive answer
|
||||||
* definitive answer before drawing any nav graph. The cookie lives in the
|
* before drawing any nav graph.
|
||||||
* Keystore-backed SessionVault, not the row.
|
|
||||||
*
|
*
|
||||||
* - no row at all → ServerUrl (first launch)
|
* - no row at all → ServerUrl (first launch)
|
||||||
* - row with baseUrl, no cookie → Login (URL configured, not yet signed in)
|
* - row with baseUrl, no cookie → Login (URL configured, not yet signed in)
|
||||||
@@ -32,30 +31,19 @@ import javax.inject.Inject
|
|||||||
@HiltViewModel
|
@HiltViewModel
|
||||||
class AuthGateViewModel @Inject constructor(
|
class AuthGateViewModel @Inject constructor(
|
||||||
private val dao: AuthSessionDao,
|
private val dao: AuthSessionDao,
|
||||||
private val authStore: AuthStore,
|
|
||||||
) : ViewModel() {
|
) : ViewModel() {
|
||||||
|
|
||||||
private val internal = MutableStateFlow<Any?>(null)
|
private val internal = MutableStateFlow<Any?>(null)
|
||||||
val startDestination: StateFlow<Any?> = internal.asStateFlow()
|
val startDestination: StateFlow<Any?> = internal.asStateFlow()
|
||||||
|
|
||||||
/**
|
|
||||||
* True when the server has ended the session while the app was in use;
|
|
||||||
* the root NavHost answers by opening the sign-in screen, then calls
|
|
||||||
* [consumeSessionRejected].
|
|
||||||
*/
|
|
||||||
val sessionRejected: StateFlow<Boolean> = authStore.sessionRejected
|
|
||||||
|
|
||||||
fun consumeSessionRejected() = authStore.consumeSessionRejected()
|
|
||||||
|
|
||||||
init {
|
init {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
authStore.awaitSessionHydrated()
|
|
||||||
val signedIn = !authStore.sessionCookie.value.isNullOrEmpty()
|
|
||||||
val row = dao.get()
|
val row = dao.get()
|
||||||
internal.value = when {
|
internal.value = when {
|
||||||
row == null -> ServerUrl
|
row == null -> ServerUrl
|
||||||
row.baseUrl == AuthStore.DEFAULT_BASE_URL && !signedIn -> ServerUrl
|
row.baseUrl == AuthStore.DEFAULT_BASE_URL && row.sessionCookie.isNullOrEmpty() ->
|
||||||
!signedIn -> Login
|
ServerUrl
|
||||||
|
row.sessionCookie.isNullOrEmpty() -> Login
|
||||||
else -> Home
|
else -> Home
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,13 +18,15 @@ import javax.inject.Singleton
|
|||||||
* Populates `audio_cache_index` from playback so the offline pools
|
* Populates `audio_cache_index` from playback so the offline pools
|
||||||
* ([ShuffleSource]) and the cached indicator have a data source.
|
* ([ShuffleSource]) and the cached indicator have a data source.
|
||||||
*
|
*
|
||||||
* A track you play gets cached as a side effect of streaming, and
|
* Mirrors the user-visible behavior of Flutter's `AudioCacheManager`
|
||||||
* playing it bumps its recency. Media3's `SimpleCache` is the real byte
|
* (`registerStreamCache` + `touch`): a track you play gets cached as a
|
||||||
* store (span-based, keyed by trackId via the MediaItem's custom cache
|
* side effect of streaming, and playing it bumps its recency. The
|
||||||
* key), so this index is a lightweight *play-recency* record
|
* Android idiom differs intentionally — Media3's `SimpleCache` is the
|
||||||
* (source = INCIDENTAL), not a file-per-track table. SimpleCache stays
|
* real byte store (span-based, keyed by trackId via the MediaItem's
|
||||||
* the source of truth for "is it actually on disk"; this index orders
|
* custom cache key), so this index is a lightweight *play-recency*
|
||||||
* "recently played" for the offline pools.
|
* record (source = INCIDENTAL) rather than Flutter's file-per-track
|
||||||
|
* table. SimpleCache stays the source of truth for "is it actually on
|
||||||
|
* disk"; this index orders "recently played" for the offline pools.
|
||||||
*
|
*
|
||||||
* State observed against [PlayerController.uiState], deduped by track
|
* State observed against [PlayerController.uiState], deduped by track
|
||||||
* id so each entry into the player records once. Eager-constructed via
|
* id so each entry into the player records once. Eager-constructed via
|
||||||
|
|||||||
@@ -12,17 +12,19 @@ import javax.inject.Singleton
|
|||||||
private const val POOL_LIMIT = 100
|
private const val POOL_LIMIT = 100
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Offline play sources over the local audio-cache index.
|
* Offline play sources over the local audio-cache index. Mirrors
|
||||||
|
* `flutter_client/lib/cache/shuffle_source.dart`.
|
||||||
*
|
*
|
||||||
* Both pools are UNIONs over the cache regardless of storage bucket
|
* Both pools are UNIONs over the cache regardless of storage bucket
|
||||||
* (liked AND recently-played both included). The two-bucket split is
|
* (liked AND recently-played both included). The two-bucket split is
|
||||||
* storage/eviction-only and never filters playback — exactly what
|
* storage/eviction-only and never filters playback — exactly what
|
||||||
* this relies on.
|
* this relies on.
|
||||||
*
|
*
|
||||||
* The index records plays (see `CacheIndexer`), not residency, so the
|
* Divergence note: Flutter's `audioCacheIndex` only holds fully-cached
|
||||||
* recency list is intersected with true Media3 SimpleCache residency
|
* tracks, so its pools are inherently resident. Android's index records
|
||||||
* here — the pool never offers a played-then-evicted track that would
|
* plays (see `CacheIndexer`), so the recency list is intersected with
|
||||||
* fail to play offline.
|
* true Media3 SimpleCache residency here — the pool never offers a
|
||||||
|
* played-then-evicted track that would fail to play offline.
|
||||||
*
|
*
|
||||||
* Surfaced on Home's Playlists row only when offline; tap shuffles +
|
* Surfaced on Home's Playlists row only when offline; tap shuffles +
|
||||||
* plays the pool from the cache.
|
* plays the pool from the cache.
|
||||||
@@ -56,14 +58,6 @@ class ShuffleSource @Inject constructor(
|
|||||||
private suspend fun materialize(orderedIds: List<String>): List<TrackRef> {
|
private suspend fun materialize(orderedIds: List<String>): List<TrackRef> {
|
||||||
if (orderedIds.isEmpty()) return emptyList()
|
if (orderedIds.isEmpty()) return emptyList()
|
||||||
val byId = trackDao.getByIds(orderedIds).associateBy { it.id }
|
val byId = trackDao.getByIds(orderedIds).associateBy { it.id }
|
||||||
return orderedIds.mapNotNull { id ->
|
return orderedIds.mapNotNull { byId[it]?.toDomain() }
|
||||||
// Clear the server's missing mark. Every id reaching here
|
|
||||||
// came through residentIdsByRecency, which already proved the
|
|
||||||
// AUDIO is in the local cache — so these play regardless of what
|
|
||||||
// the server has lost, and the queue filter in PlayerController
|
|
||||||
// would otherwise throw away tracks that work perfectly. Missing
|
|
||||||
// means "cannot stream", not "cannot play".
|
|
||||||
byId[id]?.toDomain()?.copy(unavailable = false)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
-109
@@ -1,109 +0,0 @@
|
|||||||
package com.fabledsword.minstrel.cache.account
|
|
||||||
|
|
||||||
import com.fabledsword.minstrel.auth.AuthController
|
|
||||||
import com.fabledsword.minstrel.auth.AuthStore
|
|
||||||
import com.fabledsword.minstrel.di.ApplicationScope
|
|
||||||
import com.fabledsword.minstrel.player.PlayerController
|
|
||||||
import dagger.Lazy
|
|
||||||
import kotlinx.coroutines.CoroutineScope
|
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
|
||||||
import kotlinx.coroutines.flow.combine
|
|
||||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import timber.log.Timber
|
|
||||||
import javax.inject.Inject
|
|
||||||
import javax.inject.Singleton
|
|
||||||
|
|
||||||
/** What [AccountCache] does about the signed-in account and the cache's owner. */
|
|
||||||
internal enum class OwnerStep {
|
|
||||||
/** Nobody is signed in, or the stored owner hasn't loaded yet. */
|
|
||||||
WAIT,
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The cache has no owner yet (a fresh install, or one updated from
|
|
||||||
* before owners): adopt the account, keeping the data.
|
|
||||||
*/
|
|
||||||
ADOPT,
|
|
||||||
|
|
||||||
/** Another account's data is cached: clear it, then adopt this account. */
|
|
||||||
SWITCH,
|
|
||||||
|
|
||||||
/** The signed-in account owns the cache. */
|
|
||||||
OWNED,
|
|
||||||
}
|
|
||||||
|
|
||||||
internal fun ownerStep(loaded: Boolean, signedInUserId: String?, ownerUserId: String?): OwnerStep = when {
|
|
||||||
!loaded || signedInUserId == null -> OwnerStep.WAIT
|
|
||||||
ownerUserId == null -> OwnerStep.ADOPT
|
|
||||||
ownerUserId != signedInUserId -> OwnerStep.SWITCH
|
|
||||||
else -> OwnerStep.OWNED
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Keeps one account's cached data from reaching another account on a
|
|
||||||
* shared device.
|
|
||||||
*
|
|
||||||
* The device caches data that belongs to whoever is signed in: their
|
|
||||||
* queued offline writes (likes, plays, quarantine flags, playlist adds,
|
|
||||||
* settings), Home, history, quarantine list, notifications and the queue
|
|
||||||
* the player resumes. Likes and playlists carry a user id of their own;
|
|
||||||
* these don't. So the cache has an owner, stored with the device's
|
|
||||||
* settings. When a different account signs in, that data is cleared and
|
|
||||||
* the player emptied before the new account is adopted, however the last
|
|
||||||
* one left: by signing out, or by the server refusing its session.
|
|
||||||
*
|
|
||||||
* The same person signing back in keeps everything, queued writes
|
|
||||||
* included, so a session that expires offline loses nothing.
|
|
||||||
*
|
|
||||||
* [ownedBySignedInUser] gates the offline-write replayer: queued writes
|
|
||||||
* are sent only while their owner is the one signed in, so they never go
|
|
||||||
* out under another account's session.
|
|
||||||
*/
|
|
||||||
@Singleton
|
|
||||||
class AccountCache @Inject constructor(
|
|
||||||
private val authStore: AuthStore,
|
|
||||||
authController: AuthController,
|
|
||||||
private val tables: AccountTables,
|
|
||||||
private val player: Lazy<PlayerController>,
|
|
||||||
@ApplicationScope scope: CoroutineScope,
|
|
||||||
) {
|
|
||||||
private val ownedState = MutableStateFlow(false)
|
|
||||||
|
|
||||||
/** True while the signed-in account is the one the cached data belongs to. */
|
|
||||||
val ownedBySignedInUser: StateFlow<Boolean> = ownedState.asStateFlow()
|
|
||||||
|
|
||||||
init {
|
|
||||||
scope.launch {
|
|
||||||
combine(
|
|
||||||
authStore.settingsLoaded,
|
|
||||||
authController.currentUser,
|
|
||||||
authStore.cacheOwnerUserId,
|
|
||||||
) { loaded, user, owner -> Triple(loaded, user?.id, owner) }
|
|
||||||
.distinctUntilChanged()
|
|
||||||
.collect { (loaded, userId, owner) -> step(ownerStep(loaded, userId, owner), userId) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun step(step: OwnerStep, userId: String?) {
|
|
||||||
when (step) {
|
|
||||||
OwnerStep.WAIT -> ownedState.value = false
|
|
||||||
// The stored owner changes next, and that emission reports OWNED.
|
|
||||||
OwnerStep.ADOPT -> authStore.setCacheOwnerUserId(userId)
|
|
||||||
OwnerStep.SWITCH -> {
|
|
||||||
ownedState.value = false
|
|
||||||
clearAccountData()
|
|
||||||
authStore.setCacheOwnerUserId(userId)
|
|
||||||
}
|
|
||||||
OwnerStep.OWNED -> ownedState.value = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun clearAccountData() {
|
|
||||||
Timber.i("account cache: another account signed in; clearing the last one's data")
|
|
||||||
tables.clear()
|
|
||||||
authStore.clearNotifiedUpTo()
|
|
||||||
player.get().clearQueue()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-28
@@ -1,28 +0,0 @@
|
|||||||
package com.fabledsword.minstrel.cache.account
|
|
||||||
|
|
||||||
import androidx.room.withTransaction
|
|
||||||
import com.fabledsword.minstrel.cache.db.AppDatabase
|
|
||||||
import javax.inject.Inject
|
|
||||||
import javax.inject.Singleton
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The cached tables that hold one account's data and carry no user id of
|
|
||||||
* their own, cleared together by [AccountCache] when another account signs
|
|
||||||
* in. A new table of that kind belongs in [clear]; one keyed by user id
|
|
||||||
* (likes, playlists) or shared by every account (the library) does not.
|
|
||||||
*/
|
|
||||||
@Singleton
|
|
||||||
class AccountTables @Inject constructor(private val db: AppDatabase) {
|
|
||||||
/** Clears them in one transaction, so a crash can't leave half of them. */
|
|
||||||
suspend fun clear() {
|
|
||||||
db.withTransaction {
|
|
||||||
db.cachedMutationDao().clear()
|
|
||||||
db.cachedHomeIndexDao().clear()
|
|
||||||
db.cachedHistorySnapshotDao().clear()
|
|
||||||
db.cachedQuarantineDao().clear()
|
|
||||||
db.cachedResumeStateDao().clear()
|
|
||||||
db.cachedNotificationDao().clear()
|
|
||||||
db.cachedNotificationDao().clearSettings()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-122
@@ -1,122 +0,0 @@
|
|||||||
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
@@ -1,40 +0,0 @@
|
|||||||
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
@@ -0,0 +1,23 @@
|
|||||||
|
package com.fabledsword.minstrel.cache.audiocache
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Defaults for the 2-bucket audio cache. Matches the Flutter client.
|
||||||
|
*
|
||||||
|
* - `likedCapBytes`: cap for the protected bucket — cached files for
|
||||||
|
* tracks the user has liked. Evicted only after the rolling bucket
|
||||||
|
* is fully drained (almost never under normal use).
|
||||||
|
* - `rollingCapBytes`: cap for the unprotected bucket — incidental /
|
||||||
|
* auto-prefetch downloads. LRU within this bucket.
|
||||||
|
*
|
||||||
|
* Phase 11 (Settings) will allow user overrides; the values are kept
|
||||||
|
* 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
|
||||||
|
}
|
||||||
|
}
|
||||||
+14
-13
@@ -6,22 +6,23 @@ private const val FIVE_GIB_BYTES = 5L * 1024 * 1024 * 1024
|
|||||||
private const val DEFAULT_PREFETCH_WINDOW = 5
|
private const val DEFAULT_PREFETCH_WINDOW = 5
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* User-tunable audio cache settings. Persisted as a JSON
|
* User-tunable audio cache settings. Mirrors Flutter's `CacheSettings`
|
||||||
|
* (cache_settings_provider.dart) field-for-field. Persisted as a JSON
|
||||||
* blob on the auth_session single-row table via [AuthStore].
|
* blob on the auth_session single-row table via [AuthStore].
|
||||||
*
|
*
|
||||||
* - [likedCapBytes]: the Liked songs budget, for the cached audio of
|
* - [likedCapBytes]: budget for cached files of liked tracks. 0 means
|
||||||
* liked tracks. 0 means unlimited.
|
* unlimited. Effective at next app start (SimpleCache is built once
|
||||||
* - [rollingCapBytes]: the Recently played budget, for everything else
|
* per process).
|
||||||
* streamed or prefetched. 0 means unlimited.
|
* - [rollingCapBytes]: budget for incidental / auto-prefetch downloads.
|
||||||
* A track that is liked and also recently played counts against Liked
|
* Same 0=unlimited / restart-to-apply caveat.
|
||||||
* only. Both caps apply as soon as they change ([TwoBucketCacheEvictor]).
|
* - [prefetchWindow]: 1..10. Number of next-tracks the prefetcher
|
||||||
* - [prefetchWindow]: 1..10. Number of next-tracks `AudioPrefetcher`
|
* pre-downloads. Has no effect until the prefetcher lands (separate
|
||||||
* pre-downloads.
|
* audit follow-up) — persisted now so the user can pre-configure.
|
||||||
* - [cacheLikedTracks]: "Keep liked songs offline". When true,
|
* - [cacheLikedTracks]: when true, liking a track should also pin its
|
||||||
* `LikedAudioPinner` downloads liked tracks into the Liked budget on
|
* audio to the liked-cache bucket. Has no effect until pin-on-like
|
||||||
* Wi-Fi, most recently liked first, while the budget has room.
|
* lands (separate follow-up).
|
||||||
*
|
*
|
||||||
* Defaults: 5 GiB per bucket, prefetch=5, cache-liked=true.
|
* Defaults match Flutter: 5 GiB per bucket, prefetch=5, cache-liked=true.
|
||||||
*/
|
*/
|
||||||
@Serializable
|
@Serializable
|
||||||
data class CacheSettings(
|
data class CacheSettings(
|
||||||
|
|||||||
Vendored
-112
@@ -1,112 +0,0 @@
|
|||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+13
-127
@@ -3,8 +3,6 @@ package com.fabledsword.minstrel.cache.db
|
|||||||
import androidx.room.Database
|
import androidx.room.Database
|
||||||
import androidx.room.RoomDatabase
|
import androidx.room.RoomDatabase
|
||||||
import androidx.room.TypeConverters
|
import androidx.room.TypeConverters
|
||||||
import androidx.room.migration.Migration
|
|
||||||
import androidx.sqlite.db.SupportSQLiteDatabase
|
|
||||||
import com.fabledsword.minstrel.cache.db.dao.AudioCacheIndexDao
|
import com.fabledsword.minstrel.cache.db.dao.AudioCacheIndexDao
|
||||||
import com.fabledsword.minstrel.cache.db.dao.AuthSessionDao
|
import com.fabledsword.minstrel.cache.db.dao.AuthSessionDao
|
||||||
import com.fabledsword.minstrel.cache.db.dao.CachedAlbumDao
|
import com.fabledsword.minstrel.cache.db.dao.CachedAlbumDao
|
||||||
@@ -13,7 +11,6 @@ import com.fabledsword.minstrel.cache.db.dao.CachedHistorySnapshotDao
|
|||||||
import com.fabledsword.minstrel.cache.db.dao.CachedHomeIndexDao
|
import com.fabledsword.minstrel.cache.db.dao.CachedHomeIndexDao
|
||||||
import com.fabledsword.minstrel.cache.db.dao.CachedLikeDao
|
import com.fabledsword.minstrel.cache.db.dao.CachedLikeDao
|
||||||
import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao
|
import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao
|
||||||
import com.fabledsword.minstrel.cache.db.dao.CachedNotificationDao
|
|
||||||
import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistDao
|
import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistDao
|
||||||
import com.fabledsword.minstrel.cache.db.dao.CachedResumeStateDao
|
import com.fabledsword.minstrel.cache.db.dao.CachedResumeStateDao
|
||||||
import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistTrackDao
|
import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistTrackDao
|
||||||
@@ -29,8 +26,6 @@ import com.fabledsword.minstrel.cache.db.entities.CachedHistorySnapshotEntity
|
|||||||
import com.fabledsword.minstrel.cache.db.entities.CachedHomeIndexEntity
|
import com.fabledsword.minstrel.cache.db.entities.CachedHomeIndexEntity
|
||||||
import com.fabledsword.minstrel.cache.db.entities.CachedLikeEntity
|
import com.fabledsword.minstrel.cache.db.entities.CachedLikeEntity
|
||||||
import com.fabledsword.minstrel.cache.db.entities.CachedMutationEntity
|
import com.fabledsword.minstrel.cache.db.entities.CachedMutationEntity
|
||||||
import com.fabledsword.minstrel.cache.db.entities.CachedNotificationEntity
|
|
||||||
import com.fabledsword.minstrel.cache.db.entities.CachedNotificationSettingsEntity
|
|
||||||
import com.fabledsword.minstrel.cache.db.entities.CachedPlaylistEntity
|
import com.fabledsword.minstrel.cache.db.entities.CachedPlaylistEntity
|
||||||
import com.fabledsword.minstrel.cache.db.entities.CachedResumeStateEntity
|
import com.fabledsword.minstrel.cache.db.entities.CachedResumeStateEntity
|
||||||
import com.fabledsword.minstrel.cache.db.entities.CachedPlaylistTrackEntity
|
import com.fabledsword.minstrel.cache.db.entities.CachedPlaylistTrackEntity
|
||||||
@@ -40,12 +35,17 @@ import com.fabledsword.minstrel.cache.db.entities.DiagnosticEventEntity
|
|||||||
import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity
|
import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Single Room database for the whole app, one entity family per @Entity.
|
* Single Room database for the whole app. Mirrors the Flutter client's
|
||||||
|
* Drift `AppDb` — same logical schema, one entity-family per @Entity.
|
||||||
*
|
*
|
||||||
* The server is the source of truth: the sync controller refills the
|
* Native v1 starts at schema version 1 (the Flutter Drift schemaVersion 11
|
||||||
* cache on first launch. Schema bumps land with explicit `Migration`
|
* is an internal client detail; the server is the source of truth and the
|
||||||
* entries; `fallbackToDestructiveMigration` in `DatabaseModule` rebuilds
|
* sync controller refills on first launch). Future schema bumps land per
|
||||||
* the database from a version that has no migration path.
|
* change with explicit `Migration` entries; `fallbackToDestructiveMigration`
|
||||||
|
* in `DatabaseModule` is the safety net while we're pre-v1.
|
||||||
|
*
|
||||||
|
* Entity families land in Task 4.2 slices. The set will grow until the
|
||||||
|
* whole Drift schema is mirrored.
|
||||||
*/
|
*/
|
||||||
@Database(
|
@Database(
|
||||||
entities = [
|
entities = [
|
||||||
@@ -64,38 +64,10 @@ import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity
|
|||||||
CachedHistorySnapshotEntity::class,
|
CachedHistorySnapshotEntity::class,
|
||||||
AuthSessionEntity::class,
|
AuthSessionEntity::class,
|
||||||
DiagnosticEventEntity::class,
|
DiagnosticEventEntity::class,
|
||||||
CachedNotificationEntity::class,
|
|
||||||
CachedNotificationSettingsEntity::class,
|
|
||||||
],
|
],
|
||||||
// v15: + auth_session.cacheOwnerUserId, the account the cached data
|
// v7: + diagnostic_events table (M9) and the diagnosticsOptOut column
|
||||||
// belongs to. MIGRATION_14_15 adds it empty; AccountCache adopts the
|
// on auth_session. Pre-v1 destructive fallback rebuilds on mismatch.
|
||||||
// signed-in account.
|
version = 7,
|
||||||
// v14: + cached_playlists.shelfRank, a system mix's place on its Home
|
|
||||||
// shelf. MIGRATION_13_14 adds it as 0; the next list refresh fills it.
|
|
||||||
// v13: + cached_playlists.coverAlbumIds and createdAt, the albums Home's
|
|
||||||
// shelves draw each playlist tile's picture from and when a mix was
|
|
||||||
// rebuilt. MIGRATION_12_13 adds both empty; the next list refresh fills them.
|
|
||||||
// v12: + auth_session.backgroundDelivery and notifiedUpTo, the device's
|
|
||||||
// background-delivery choice and its shade high-water mark.
|
|
||||||
// v11: + cached_notifications and cached_notification_settings, the
|
|
||||||
// notifications inbox and its settings. MIGRATION_10_11 creates
|
|
||||||
// both; nothing to backfill, the first refresh fills them.
|
|
||||||
// v10: + cached_tracks.trackGain/trackPeak and cached_albums.albumGain/
|
|
||||||
// albumPeak, the ReplayGain values the player levels by.
|
|
||||||
// MIGRATION_9_10 also rewinds the sync cursor, so the next sync re-sends
|
|
||||||
// every row and an existing cache gains its values.
|
|
||||||
// v9: + auth_session.normalizationJson, the loudness-normalization
|
|
||||||
// preference. The first schema step with an explicit Migration
|
|
||||||
// (MIGRATION_8_9): a destructive rebuild would also wipe this row —
|
|
||||||
// the server address and theme — and the queued offline writes,
|
|
||||||
// which is too much to lose for one added column.
|
|
||||||
// v8: + cached_tracks.missing, the server's missing-file mark,
|
|
||||||
// so cache-first surfaces stop offering files that cannot stream.
|
|
||||||
// v7: + diagnostic_events table and the diagnosticsOptOut column
|
|
||||||
// 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 = 15,
|
|
||||||
exportSchema = true,
|
exportSchema = true,
|
||||||
)
|
)
|
||||||
@TypeConverters(MinstrelTypeConverters::class)
|
@TypeConverters(MinstrelTypeConverters::class)
|
||||||
@@ -115,90 +87,4 @@ abstract class AppDatabase : RoomDatabase() {
|
|||||||
abstract fun cachedHistorySnapshotDao(): CachedHistorySnapshotDao
|
abstract fun cachedHistorySnapshotDao(): CachedHistorySnapshotDao
|
||||||
abstract fun authSessionDao(): AuthSessionDao
|
abstract fun authSessionDao(): AuthSessionDao
|
||||||
abstract fun diagnosticEventDao(): DiagnosticEventDao
|
abstract fun diagnosticEventDao(): DiagnosticEventDao
|
||||||
abstract fun cachedNotificationDao(): CachedNotificationDao
|
|
||||||
}
|
|
||||||
|
|
||||||
/** v8 → v9: add the nullable normalization preference column. */
|
|
||||||
val MIGRATION_8_9: Migration = object : Migration(8, 9) {
|
|
||||||
override fun migrate(db: SupportSQLiteDatabase) {
|
|
||||||
db.execSQL("ALTER TABLE auth_session ADD COLUMN normalizationJson TEXT")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* v9 → v10: the gain columns. Rows synced before this carry no gains,
|
|
||||||
* and the sync is incremental, so it would never re-send them: the cursor goes
|
|
||||||
* back to 0 and the next sync is a full one, upserting every row in place.
|
|
||||||
*/
|
|
||||||
val MIGRATION_9_10: Migration = object : Migration(9, 10) {
|
|
||||||
override fun migrate(db: SupportSQLiteDatabase) {
|
|
||||||
db.execSQL("ALTER TABLE cached_tracks ADD COLUMN trackGain REAL")
|
|
||||||
db.execSQL("ALTER TABLE cached_tracks ADD COLUMN trackPeak REAL")
|
|
||||||
db.execSQL("ALTER TABLE cached_albums ADD COLUMN albumGain REAL")
|
|
||||||
db.execSQL("ALTER TABLE cached_albums ADD COLUMN albumPeak REAL")
|
|
||||||
db.execSQL("UPDATE sync_metadata SET cursor = 0")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* v10 → v11: the notifications inbox cache and its settings. The SQL
|
|
||||||
* matches what Room generates for the two entities; Room checks it on open.
|
|
||||||
*/
|
|
||||||
val MIGRATION_10_11: Migration = object : Migration(10, 11) {
|
|
||||||
override fun migrate(db: SupportSQLiteDatabase) {
|
|
||||||
db.execSQL(
|
|
||||||
"CREATE TABLE IF NOT EXISTS `cached_notifications` (" +
|
|
||||||
"`id` TEXT NOT NULL, `kind` TEXT NOT NULL, `title` TEXT NOT NULL, " +
|
|
||||||
"`body` TEXT NOT NULL, `link` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, " +
|
|
||||||
"`readAt` INTEGER, PRIMARY KEY(`id`))",
|
|
||||||
)
|
|
||||||
db.execSQL(
|
|
||||||
"CREATE TABLE IF NOT EXISTS `cached_notification_settings` (" +
|
|
||||||
"`id` INTEGER NOT NULL, `json` TEXT NOT NULL, PRIMARY KEY(`id`))",
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* v11 → v12: background delivery. The device choice defaults on,
|
|
||||||
* as the entity's column default says; the high-water mark starts empty, so
|
|
||||||
* the first catch-up sets it without announcing anything.
|
|
||||||
*/
|
|
||||||
val MIGRATION_11_12: Migration = object : Migration(11, 12) {
|
|
||||||
override fun migrate(db: SupportSQLiteDatabase) {
|
|
||||||
db.execSQL("ALTER TABLE auth_session ADD COLUMN backgroundDelivery INTEGER NOT NULL DEFAULT 1")
|
|
||||||
db.execSQL("ALTER TABLE auth_session ADD COLUMN notifiedUpTo INTEGER")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* v12 → v13: a playlist's cover albums and creation time. Both start empty;
|
|
||||||
* Home refreshes the playlist list on open, which fills them.
|
|
||||||
*/
|
|
||||||
val MIGRATION_12_13: Migration = object : Migration(12, 13) {
|
|
||||||
override fun migrate(db: SupportSQLiteDatabase) {
|
|
||||||
db.execSQL("ALTER TABLE cached_playlists ADD COLUMN coverAlbumIds TEXT NOT NULL DEFAULT ''")
|
|
||||||
db.execSQL("ALTER TABLE cached_playlists ADD COLUMN createdAt TEXT NOT NULL DEFAULT ''")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* v13 → v14: a playlist's place on its Home shelf. Starts at 0 (unranked);
|
|
||||||
* Home refreshes the playlist list on open, which fills it.
|
|
||||||
*/
|
|
||||||
val MIGRATION_13_14: Migration = object : Migration(13, 14) {
|
|
||||||
override fun migrate(db: SupportSQLiteDatabase) {
|
|
||||||
db.execSQL("ALTER TABLE cached_playlists ADD COLUMN shelfRank INTEGER NOT NULL DEFAULT 0")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* v14 → v15: the account the cached data belongs to. Starts empty, and
|
|
||||||
* AccountCache adopts whoever is signed in without clearing anything, so
|
|
||||||
* an update keeps the signed-in person's queued writes and cache.
|
|
||||||
*/
|
|
||||||
val MIGRATION_14_15: Migration = object : Migration(14, 15) {
|
|
||||||
override fun migrate(db: SupportSQLiteDatabase) {
|
|
||||||
db.execSQL("ALTER TABLE auth_session ADD COLUMN cacheOwnerUserId TEXT")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-19
@@ -10,7 +10,6 @@ import com.fabledsword.minstrel.cache.db.dao.CachedHistorySnapshotDao
|
|||||||
import com.fabledsword.minstrel.cache.db.dao.CachedHomeIndexDao
|
import com.fabledsword.minstrel.cache.db.dao.CachedHomeIndexDao
|
||||||
import com.fabledsword.minstrel.cache.db.dao.CachedLikeDao
|
import com.fabledsword.minstrel.cache.db.dao.CachedLikeDao
|
||||||
import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao
|
import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao
|
||||||
import com.fabledsword.minstrel.cache.db.dao.CachedNotificationDao
|
|
||||||
import com.fabledsword.minstrel.cache.db.dao.DiagnosticEventDao
|
import com.fabledsword.minstrel.cache.db.dao.DiagnosticEventDao
|
||||||
import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistDao
|
import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistDao
|
||||||
import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistTrackDao
|
import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistTrackDao
|
||||||
@@ -33,19 +32,11 @@ object DatabaseModule {
|
|||||||
@Singleton
|
@Singleton
|
||||||
fun provideDatabase(@ApplicationContext context: Context): AppDatabase =
|
fun provideDatabase(@ApplicationContext context: Context): AppDatabase =
|
||||||
Room.databaseBuilder(context, AppDatabase::class.java, DATABASE_NAME)
|
Room.databaseBuilder(context, AppDatabase::class.java, DATABASE_NAME)
|
||||||
// Explicit migrations from v8 onward; an older schema has no path
|
// Pre-v1 safety net: rebuild on any schema mismatch. The sync
|
||||||
// and rebuilds. The sync controller refills the cache from the
|
// controller refills the cache from the server on first
|
||||||
// server on first launch, so a rebuild loses only the unsynced
|
// launch, so users lose only the unsynced mutation queue
|
||||||
// mutation queue.
|
// (acceptable while we're iterating). Replace with explicit
|
||||||
.addMigrations(
|
// Migration entries before the first tagged release.
|
||||||
MIGRATION_8_9,
|
|
||||||
MIGRATION_9_10,
|
|
||||||
MIGRATION_10_11,
|
|
||||||
MIGRATION_11_12,
|
|
||||||
MIGRATION_12_13,
|
|
||||||
MIGRATION_13_14,
|
|
||||||
MIGRATION_14_15,
|
|
||||||
)
|
|
||||||
.fallbackToDestructiveMigration(dropAllTables = true)
|
.fallbackToDestructiveMigration(dropAllTables = true)
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
@@ -120,10 +111,5 @@ object DatabaseModule {
|
|||||||
fun provideDiagnosticEventDao(db: AppDatabase): DiagnosticEventDao =
|
fun provideDiagnosticEventDao(db: AppDatabase): DiagnosticEventDao =
|
||||||
db.diagnosticEventDao()
|
db.diagnosticEventDao()
|
||||||
|
|
||||||
@Provides
|
|
||||||
@Singleton
|
|
||||||
fun provideCachedNotificationDao(db: AppDatabase): CachedNotificationDao =
|
|
||||||
db.cachedNotificationDao()
|
|
||||||
|
|
||||||
private const val DATABASE_NAME = "minstrel.db"
|
private const val DATABASE_NAME = "minstrel.db"
|
||||||
}
|
}
|
||||||
|
|||||||
+15
-6
@@ -4,10 +4,17 @@ import androidx.room.TypeConverter
|
|||||||
import kotlinx.datetime.Instant
|
import kotlinx.datetime.Instant
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* How a row reached `audio_cache_index`. `CacheIndexer` writes
|
* Source category for a cached audio file. Mirrors the Drift `CacheSource`
|
||||||
* `INCIDENTAL` (the track was played); the other values are stored names
|
* enum used by the Flutter client's `audio_cache_index` table 1:1.
|
||||||
* no writer uses. Eviction does not read this: the audio cache's two
|
*
|
||||||
* budgets follow the liked set (see `TwoBucketCacheEvictor`).
|
* - `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 order (first to evict): INCIDENTAL → AUTO_PREFETCH
|
||||||
|
* → AUTO_PLAYLIST → AUTO_LIKED → MANUAL.
|
||||||
*/
|
*/
|
||||||
enum class CacheSource { MANUAL, AUTO_LIKED, AUTO_PLAYLIST, AUTO_PREFETCH, INCIDENTAL }
|
enum class CacheSource { MANUAL, AUTO_LIKED, AUTO_PLAYLIST, AUTO_PREFETCH, INCIDENTAL }
|
||||||
|
|
||||||
@@ -15,8 +22,10 @@ enum class CacheSource { MANUAL, AUTO_LIKED, AUTO_PLAYLIST, AUTO_PREFETCH, INCID
|
|||||||
* Cross-cutting Room type converters. Registered on `@Database` via
|
* Cross-cutting Room type converters. Registered on `@Database` via
|
||||||
* `@TypeConverters(MinstrelTypeConverters::class)`.
|
* `@TypeConverters(MinstrelTypeConverters::class)`.
|
||||||
*
|
*
|
||||||
* `kotlinx.datetime.Instant` ↔ `Long` epoch millis: leaner than ISO-8601
|
* `kotlinx.datetime.Instant` ↔ `Long` epoch millis: the same convention the
|
||||||
* text, and nothing needs human-readable rows in the SQLite file.
|
* Flutter client uses (Drift `text()` column with ISO-8601 strings would
|
||||||
|
* also work but Long is leaner; we don't need human-readable rows in the
|
||||||
|
* SQLite file).
|
||||||
*/
|
*/
|
||||||
class MinstrelTypeConverters {
|
class MinstrelTypeConverters {
|
||||||
@TypeConverter fun instantToLong(i: Instant?): Long? = i?.toEpochMilliseconds()
|
@TypeConverter fun instantToLong(i: Instant?): Long? = i?.toEpochMilliseconds()
|
||||||
|
|||||||
+18
@@ -4,6 +4,7 @@ import androidx.room.Dao
|
|||||||
import androidx.room.Insert
|
import androidx.room.Insert
|
||||||
import androidx.room.OnConflictStrategy
|
import androidx.room.OnConflictStrategy
|
||||||
import androidx.room.Query
|
import androidx.room.Query
|
||||||
|
import com.fabledsword.minstrel.cache.db.CacheSource
|
||||||
import com.fabledsword.minstrel.cache.db.entities.AudioCacheIndexEntity
|
import com.fabledsword.minstrel.cache.db.entities.AudioCacheIndexEntity
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
|
||||||
@@ -31,6 +32,23 @@ interface AudioCacheIndexDao {
|
|||||||
@Query("SELECT trackId FROM audio_cache_index ORDER BY lastPlayedAt DESC NULLS LAST")
|
@Query("SELECT trackId FROM audio_cache_index ORDER BY lastPlayedAt DESC NULLS LAST")
|
||||||
suspend fun trackIdsByRecency(): List<String>
|
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)
|
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||||
suspend fun upsert(row: AudioCacheIndexEntity)
|
suspend fun upsert(row: AudioCacheIndexEntity)
|
||||||
|
|
||||||
|
|||||||
-16
@@ -6,7 +6,6 @@ import androidx.room.OnConflictStrategy
|
|||||||
import androidx.room.Query
|
import androidx.room.Query
|
||||||
import com.fabledsword.minstrel.cache.db.entities.AuthSessionEntity
|
import com.fabledsword.minstrel.cache.db.entities.AuthSessionEntity
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
import kotlinx.datetime.Instant
|
|
||||||
|
|
||||||
@Dao
|
@Dao
|
||||||
interface AuthSessionDao {
|
interface AuthSessionDao {
|
||||||
@@ -47,19 +46,4 @@ interface AuthSessionDao {
|
|||||||
/** Partial update: change only the per-device diagnostics opt-out. */
|
/** Partial update: change only the per-device diagnostics opt-out. */
|
||||||
@Query("UPDATE auth_session SET diagnosticsOptOut = :optOut WHERE id = 0")
|
@Query("UPDATE auth_session SET diagnosticsOptOut = :optOut WHERE id = 0")
|
||||||
suspend fun setDiagnosticsOptOut(optOut: Boolean)
|
suspend fun setDiagnosticsOptOut(optOut: Boolean)
|
||||||
|
|
||||||
/** Partial update: change only the serialized normalization preference. */
|
|
||||||
@Query("UPDATE auth_session SET normalizationJson = :json WHERE id = 0")
|
|
||||||
suspend fun setNormalizationJson(json: String?)
|
|
||||||
|
|
||||||
/** Partial update: change only the background-delivery choice. */
|
|
||||||
@Query("UPDATE auth_session SET backgroundDelivery = :enabled WHERE id = 0")
|
|
||||||
suspend fun setBackgroundDelivery(enabled: Boolean)
|
|
||||||
|
|
||||||
/** Partial update: change only the shade's high-water mark. */
|
|
||||||
@Query("UPDATE auth_session SET notifiedUpTo = :upTo WHERE id = 0")
|
|
||||||
suspend fun setNotifiedUpTo(upTo: Instant?)
|
|
||||||
|
|
||||||
@Query("UPDATE auth_session SET cacheOwnerUserId = :userId WHERE id = 0")
|
|
||||||
suspend fun setCacheOwnerUserId(userId: String?)
|
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
-3
@@ -15,7 +15,4 @@ interface CachedHistorySnapshotDao {
|
|||||||
|
|
||||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||||
suspend fun upsert(row: CachedHistorySnapshotEntity)
|
suspend fun upsert(row: CachedHistorySnapshotEntity)
|
||||||
|
|
||||||
@Query("DELETE FROM cached_history_snapshot")
|
|
||||||
suspend fun clear()
|
|
||||||
}
|
}
|
||||||
|
|||||||
+7
-10
@@ -10,16 +10,12 @@ import kotlinx.coroutines.flow.Flow
|
|||||||
|
|
||||||
@Dao
|
@Dao
|
||||||
interface CachedLikeDao {
|
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(
|
@Query(
|
||||||
"SELECT entityId FROM cached_likes " +
|
"SELECT entityId FROM cached_likes " +
|
||||||
"WHERE userId = :userId AND entityType = 'track' " +
|
"WHERE userId = :userId AND entityType = 'track'",
|
||||||
"ORDER BY likedAt DESC",
|
|
||||||
)
|
)
|
||||||
fun observeLikedTrackIdsNewestFirst(userId: String): Flow<List<String>>
|
fun observeLikedTrackIds(userId: String): Flow<List<String>>
|
||||||
|
|
||||||
@Query(
|
@Query(
|
||||||
"SELECT entityId FROM cached_likes " +
|
"SELECT entityId FROM cached_likes " +
|
||||||
@@ -48,9 +44,10 @@ interface CachedLikeDao {
|
|||||||
/**
|
/**
|
||||||
* Atomically replaces the user's entire cached_likes set with
|
* Atomically replaces the user's entire cached_likes set with
|
||||||
* [rows]. Used by [com.fabledsword.minstrel.likes.data.LikesRepository.refreshIds]
|
* [rows]. Used by [com.fabledsword.minstrel.likes.data.LikesRepository.refreshIds]
|
||||||
* so an unlike made on another device (a row the server no longer
|
* so cross-device unlikes (a row that the server no longer
|
||||||
* surfaces) leaves the local cache too; upserts alone would keep a
|
* surfaces) get removed from the local cache — drift #570
|
||||||
* stale Liked tab entry forever.
|
* caught the missing delete pass that left stale Liked tab
|
||||||
|
* entries pointing at tracks the user had unliked elsewhere.
|
||||||
*/
|
*/
|
||||||
@Transaction
|
@Transaction
|
||||||
suspend fun replaceAllForUser(userId: String, rows: List<CachedLikeEntity>) {
|
suspend fun replaceAllForUser(userId: String, rows: List<CachedLikeEntity>) {
|
||||||
|
|||||||
-4
@@ -31,8 +31,4 @@ interface CachedMutationDao {
|
|||||||
|
|
||||||
@Query("DELETE FROM cached_mutations")
|
@Query("DELETE FROM cached_mutations")
|
||||||
suspend fun clear()
|
suspend fun clear()
|
||||||
|
|
||||||
/** Whether a write of [kind] is still waiting to be replayed. */
|
|
||||||
@Query("SELECT EXISTS(SELECT 1 FROM cached_mutations WHERE kind = :kind)")
|
|
||||||
suspend fun hasPending(kind: String): Boolean
|
|
||||||
}
|
}
|
||||||
|
|||||||
-54
@@ -1,54 +0,0 @@
|
|||||||
package com.fabledsword.minstrel.cache.db.dao
|
|
||||||
|
|
||||||
import androidx.room.Dao
|
|
||||||
import androidx.room.Insert
|
|
||||||
import androidx.room.OnConflictStrategy
|
|
||||||
import androidx.room.Query
|
|
||||||
import androidx.room.Transaction
|
|
||||||
import com.fabledsword.minstrel.cache.db.entities.CachedNotificationEntity
|
|
||||||
import com.fabledsword.minstrel.cache.db.entities.CachedNotificationSettingsEntity
|
|
||||||
import kotlinx.coroutines.flow.Flow
|
|
||||||
import kotlinx.datetime.Instant
|
|
||||||
|
|
||||||
@Dao
|
|
||||||
interface CachedNotificationDao {
|
|
||||||
@Query("SELECT * FROM cached_notifications ORDER BY createdAt DESC, id DESC")
|
|
||||||
fun observeAll(): Flow<List<CachedNotificationEntity>>
|
|
||||||
|
|
||||||
@Query("SELECT COUNT(*) FROM cached_notifications WHERE readAt IS NULL")
|
|
||||||
fun observeUnreadCount(): Flow<Int>
|
|
||||||
|
|
||||||
@Query("SELECT * FROM cached_notifications")
|
|
||||||
suspend fun getAll(): List<CachedNotificationEntity>
|
|
||||||
|
|
||||||
@Query("DELETE FROM cached_notifications")
|
|
||||||
suspend fun clear()
|
|
||||||
|
|
||||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
|
||||||
suspend fun insertAll(rows: List<CachedNotificationEntity>)
|
|
||||||
|
|
||||||
/** The newest page replaces the cache whole: a notice gone server-side goes here too. */
|
|
||||||
@Transaction
|
|
||||||
suspend fun replaceAll(rows: List<CachedNotificationEntity>) {
|
|
||||||
clear()
|
|
||||||
insertAll(rows)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Query("UPDATE cached_notifications SET readAt = :at WHERE id = :id AND readAt IS NULL")
|
|
||||||
suspend fun markRead(id: String, at: Instant)
|
|
||||||
|
|
||||||
@Query("UPDATE cached_notifications SET readAt = :at WHERE readAt IS NULL")
|
|
||||||
suspend fun markAllRead(at: Instant)
|
|
||||||
|
|
||||||
@Query("SELECT * FROM cached_notification_settings WHERE id = 1")
|
|
||||||
fun observeSettings(): Flow<CachedNotificationSettingsEntity?>
|
|
||||||
|
|
||||||
@Query("SELECT * FROM cached_notification_settings WHERE id = 1")
|
|
||||||
suspend fun getSettings(): CachedNotificationSettingsEntity?
|
|
||||||
|
|
||||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
|
||||||
suspend fun upsertSettings(row: CachedNotificationSettingsEntity)
|
|
||||||
|
|
||||||
@Query("DELETE FROM cached_notification_settings")
|
|
||||||
suspend fun clearSettings()
|
|
||||||
}
|
|
||||||
+4
-3
@@ -14,12 +14,12 @@ interface CachedPlaylistDao {
|
|||||||
@Query("SELECT * FROM cached_playlists ORDER BY name COLLATE NOCASE ASC")
|
@Query("SELECT * FROM cached_playlists ORDER BY name COLLATE NOCASE ASC")
|
||||||
fun observeAll(): Flow<List<CachedPlaylistEntity>>
|
fun observeAll(): Flow<List<CachedPlaylistEntity>>
|
||||||
|
|
||||||
/** [userId]'s own playlists, not mixes: the lists they can add a song to. */
|
/** User playlists only (systemVariant IS NULL) — for the add-to-playlist sheet. */
|
||||||
@Query(
|
@Query(
|
||||||
"SELECT * FROM cached_playlists " +
|
"SELECT * FROM cached_playlists " +
|
||||||
"WHERE systemVariant IS NULL AND userId = :userId ORDER BY name COLLATE NOCASE ASC",
|
"WHERE systemVariant IS NULL ORDER BY name COLLATE NOCASE ASC",
|
||||||
)
|
)
|
||||||
fun observeOwnedUserPlaylists(userId: String): Flow<List<CachedPlaylistEntity>>
|
fun observeUserPlaylists(): Flow<List<CachedPlaylistEntity>>
|
||||||
|
|
||||||
/** System playlists for the home screen. */
|
/** System playlists for the home screen. */
|
||||||
@Query(
|
@Query(
|
||||||
@@ -59,6 +59,7 @@ interface CachedPlaylistDao {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Atomically reconciles the cache against the fresh list response.
|
* Atomically reconciles the cache against the fresh list response.
|
||||||
|
* Mirrors `flutter_client/lib/playlists/playlists_provider.dart:54` —
|
||||||
* `BuildSystemPlaylists` rotates system-playlist UUIDs every
|
* `BuildSystemPlaylists` rotates system-playlist UUIDs every
|
||||||
* rebuild, so upsert alone leaves stale rows whose detail fetch
|
* rebuild, so upsert alone leaves stale rows whose detail fetch
|
||||||
* 404s. Delete any of the user's rows not in [freshOwnedIds] (this
|
* 404s. Delete any of the user's rows not in [freshOwnedIds] (this
|
||||||
|
|||||||
+5
-5
@@ -46,13 +46,13 @@ interface CachedPlaylistTrackDao {
|
|||||||
* Atomic on purpose. Room's InvalidationTracker only notifies observers
|
* Atomic on purpose. Room's InvalidationTracker only notifies observers
|
||||||
* after the transaction commits, so [observeByPlaylist] never sees the
|
* after the transaction commits, so [observeByPlaylist] never sees the
|
||||||
* empty gap between the delete and the re-insert. Un-transacted, that
|
* empty gap between the delete and the re-insert. Un-transacted, that
|
||||||
* gap is a real observed state: the list visibly collapses to empty
|
* gap is a real observed state — it's what made every Home row visibly
|
||||||
* and refills, which is why `CachedHomeIndexDao` transacts its writes
|
* collapse to empty and refill before issue #2327 fixed the equivalent
|
||||||
* too.
|
* write in `CachedHomeIndexDao`.
|
||||||
*
|
*
|
||||||
* Nothing observes [observeByPlaylist] live today, so this is
|
* Nothing observes [observeByPlaylist] live today, so this is
|
||||||
* pre-emptive: making playlist detail cache-first later can't
|
* pre-emptive: it means making playlist detail cache-first later can't
|
||||||
* silently bring that flicker in.
|
* silently reintroduce that flicker.
|
||||||
*/
|
*/
|
||||||
@Transaction
|
@Transaction
|
||||||
suspend fun replacePlaylistTracks(
|
suspend fun replacePlaylistTracks(
|
||||||
|
|||||||
+2
-1
@@ -41,7 +41,8 @@ interface CachedQuarantineDao {
|
|||||||
/**
|
/**
|
||||||
* Atomic full-replace from the server snapshot — one transaction so
|
* Atomic full-replace from the server snapshot — one transaction so
|
||||||
* the `observeAll()` watcher sees a single merged emission, not a
|
* the `observeAll()` watcher sees a single merged emission, not a
|
||||||
* delete-then-insert flicker.
|
* delete-then-insert flicker. Mirrors Flutter's MyQuarantineController
|
||||||
|
* `_refreshFromServer` transaction.
|
||||||
*/
|
*/
|
||||||
@Transaction
|
@Transaction
|
||||||
suspend fun replaceAll(rows: List<CachedQuarantineEntity>) {
|
suspend fun replaceAll(rows: List<CachedQuarantineEntity>) {
|
||||||
|
|||||||
-21
@@ -38,27 +38,6 @@ interface CachedTrackDao {
|
|||||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||||
suspend fun upsertAll(rows: List<CachedTrackEntity>)
|
suspend fun upsertAll(rows: List<CachedTrackEntity>)
|
||||||
|
|
||||||
/**
|
|
||||||
* ReplayGain values for [ids]: the track's own from its row,
|
|
||||||
* the album's from its album row. A track not in the cache has no row.
|
|
||||||
*/
|
|
||||||
@Query(
|
|
||||||
"SELECT t.id AS id, t.trackGain AS trackGain, t.trackPeak AS trackPeak, " +
|
|
||||||
"a.albumGain AS albumGain, a.albumPeak AS albumPeak " +
|
|
||||||
"FROM cached_tracks t LEFT JOIN cached_albums a ON a.id = t.albumId " +
|
|
||||||
"WHERE t.id IN (:ids)",
|
|
||||||
)
|
|
||||||
suspend fun replayGains(ids: List<String>): List<CachedReplayGain>
|
|
||||||
|
|
||||||
@Query("DELETE FROM cached_tracks WHERE id IN (:ids)")
|
@Query("DELETE FROM cached_tracks WHERE id IN (:ids)")
|
||||||
suspend fun deleteByIds(ids: List<String>)
|
suspend fun deleteByIds(ids: List<String>)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** One row of [CachedTrackDao.replayGains]. */
|
|
||||||
data class CachedReplayGain(
|
|
||||||
val id: String,
|
|
||||||
val trackGain: Float?,
|
|
||||||
val trackPeak: Float?,
|
|
||||||
val albumGain: Float?,
|
|
||||||
val albumPeak: Float?,
|
|
||||||
)
|
|
||||||
|
|||||||
Vendored
+11
-7
@@ -7,14 +7,18 @@ import kotlinx.datetime.Clock
|
|||||||
import kotlinx.datetime.Instant
|
import kotlinx.datetime.Instant
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* One row per track that has played through the audio cache (see
|
* One row per fully-downloaded audio file. Mirrors
|
||||||
* `CacheIndexer`); SimpleCache, not this table, says what is on disk.
|
* `flutter_client/lib/cache/db.dart`'s `AudioCacheIndex` Drift table.
|
||||||
*
|
*
|
||||||
* `source` says how the row arrived (see [CacheSource]); eviction does
|
* Drives the 2-bucket LRU eviction (Phase 12 AudioCacheEvictionWorker):
|
||||||
* not read it. `cachedAt` = when the row was written. `lastPlayedAt` =
|
* - `incidental` files (streamed-and-cached side effect) evict first
|
||||||
* when the user last played the track, which orders the offline
|
* - `autoPrefetch` second
|
||||||
* "recently played" pool. Nullable on brand-new rows until the first
|
* - `manual` (user explicitly pinned) evict last
|
||||||
* post-cache play touches them.
|
*
|
||||||
|
* `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.
|
||||||
*/
|
*/
|
||||||
@Entity(tableName = "audio_cache_index")
|
@Entity(tableName = "audio_cache_index")
|
||||||
data class AudioCacheIndexEntity(
|
data class AudioCacheIndexEntity(
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user