Compare commits
95
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4f077736b6 | ||
|
|
0103953953 | ||
|
|
72c0e96f92 | ||
|
|
e87516bbe4 | ||
|
|
8e21bce103 | ||
|
|
727f68950e | ||
|
|
955a61194e | ||
|
|
b96285d6d9 | ||
|
|
7ba673ed83 | ||
|
|
366692a1fc | ||
|
|
6d729d1512 | ||
|
|
414dfb23b6 | ||
|
|
952132714e | ||
|
|
c2862e97bd | ||
|
|
30a5ac56ce | ||
|
|
bab9b16831 | ||
|
|
03a8d12079 | ||
|
|
0036f534db | ||
|
|
bfb6c9acfe | ||
|
|
3eada70aac | ||
|
|
d9238ec5be | ||
|
|
a31b672b14 | ||
|
|
8d1f2674fd | ||
|
|
845f45fb0b | ||
|
|
aab90a7a39 | ||
|
|
4c49ee2cc6 | ||
|
|
4dd0a58d63 | ||
|
|
c3f3a17c6d | ||
|
|
20bd7bfaf8 | ||
|
|
aa9f534f3c | ||
|
|
8e1d25a772 | ||
|
|
4509f740f8 | ||
|
|
011b4d9a9c | ||
|
|
a254cb2273 | ||
|
|
e368b82f0a | ||
|
|
d5aa081157 | ||
|
|
304de88c50 | ||
|
|
96abb48086 | ||
|
|
a094d5f8b0 | ||
|
|
481f906059 | ||
|
|
a99f855e98 | ||
|
|
24d330424f | ||
|
|
f6d1cf24f0 | ||
|
|
7e4727fc49 | ||
|
|
fd27819cdd | ||
|
|
37b396a7e4 | ||
|
|
1b7fa635d8 | ||
|
|
78aa9befb6 | ||
|
|
a9ca49dc4e | ||
|
|
feb1c2eca8 | ||
|
|
f8f2273aec | ||
|
|
1126bfcf78 | ||
|
|
5b36d79ff9 | ||
|
|
11538095be | ||
|
|
d5ab3b0764 | ||
|
|
a07fb3867a | ||
|
|
381e9cedb7 | ||
|
|
bf649f3beb | ||
|
|
d86af7397d | ||
|
|
2e1a8a62d8 | ||
|
|
1bf0e388cb | ||
|
|
a4b6f22d86 | ||
|
|
57d2299180 | ||
|
|
8b630e71ca | ||
|
|
1910a5ce61 | ||
|
|
a92a9f2198 | ||
|
|
6dea45a634 | ||
|
|
fa7ea41ccf | ||
|
|
e1e591b520 | ||
|
|
324059b2bd | ||
|
|
eec59193fa | ||
|
|
ca4832e620 | ||
|
|
cf0d37bf8e | ||
|
|
799dab029a | ||
|
|
7315e37c15 | ||
|
|
4f9b083eec | ||
|
|
f17356560d | ||
|
|
18a61f1065 | ||
|
|
6e39471a70 | ||
|
|
86af79bd2f | ||
|
|
e006de5d4b | ||
|
|
94e2cac03b | ||
|
|
b27029f674 | ||
|
|
14aa22198f | ||
|
|
1138d75a45 | ||
|
|
cf7b489fec | ||
|
|
8483948f23 | ||
|
|
0cea82984c | ||
|
|
3acac985cd | ||
|
|
d3b40342b4 | ||
|
|
4f99b42844 | ||
|
|
5044e7a055 | ||
|
|
7d45a4e5c7 | ||
|
|
fa0827f668 | ||
|
|
52d53e0044 |
@@ -9,7 +9,6 @@ web/build
|
|||||||
# Flutter mobile client — built separately on developer machines / Flutter CI.
|
# Flutter mobile client — built separately on developer machines / Flutter CI.
|
||||||
# Including it in the Go build context wastes ~70 files and invalidates the
|
# Including it in the Go build context wastes ~70 files and invalidates the
|
||||||
# `COPY . .` layer cache on every Flutter-only change.
|
# `COPY . .` layer cache on every Flutter-only change.
|
||||||
flutter_client/
|
|
||||||
|
|
||||||
# Docs and IDE noise
|
# Docs and IDE noise
|
||||||
docs/
|
docs/
|
||||||
|
|||||||
@@ -80,10 +80,16 @@ jobs:
|
|||||||
|
|
||||||
- name: Upload debug APK
|
- name: Upload debug APK
|
||||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||||
# Gitea Actions runs in GHES-emulation mode; @actions/artifact v2+
|
# Mirrored action, never actions/upload-artifact. @v4+ throws
|
||||||
# (i.e. upload-artifact@v4+) errors with "GHESNotSupportedError".
|
# GHESNotSupportedError client-side on the hostname (no server setting
|
||||||
# Pin to @v3 until act_runner or the artifact backend catches up.
|
# reaches that check), and @v3 is worse — it reports success while Gitea
|
||||||
uses: actions/upload-artifact@v3
|
# 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:
|
with:
|
||||||
name: minstrel-android-debug-${{ github.sha }}
|
name: minstrel-android-debug-${{ github.sha }}
|
||||||
path: android/app/build/outputs/apk/debug/app-debug.apk
|
path: android/app/build/outputs/apk/debug/app-debug.apk
|
||||||
|
if-no-files-found: error
|
||||||
|
|||||||
@@ -98,6 +98,31 @@ jobs:
|
|||||||
echo "code=${COMMIT_COUNT}" >> "$GITHUB_OUTPUT"
|
echo "code=${COMMIT_COUNT}" >> "$GITHUB_OUTPUT"
|
||||||
echo "::notice::APK version: ${VERSION_NAME} (code=${COMMIT_COUNT})"
|
echo "::notice::APK version: ${VERSION_NAME} (code=${COMMIT_COUNT})"
|
||||||
|
|
||||||
|
# Checked BEFORE the expensive work, not after it. "Attach APK to gitea
|
||||||
|
# Release" below resolves the release by tag and fails if it is absent —
|
||||||
|
# but that is the final step, so a tag pushed without a release built an
|
||||||
|
# APK for several minutes first and only then discovered it had nowhere to
|
||||||
|
# put it. Same check, seconds in instead of minutes.
|
||||||
|
#
|
||||||
|
# Releases are normally created through the API (which creates the tag and
|
||||||
|
# the release together, so this passes). A bare `git push origin vX` is the
|
||||||
|
# case this catches.
|
||||||
|
- name: Release must exist for this tag
|
||||||
|
shell: bash
|
||||||
|
working-directory: ${{ github.workspace }}
|
||||||
|
env:
|
||||||
|
CI_TOKEN: ${{ secrets.CI_TOKEN }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
TAG="${GITHUB_REF#refs/tags/}"
|
||||||
|
if ! curl -fsSL -o /dev/null \
|
||||||
|
-H "Authorization: token ${CI_TOKEN}" \
|
||||||
|
"https://git.fabledsword.com/api/v1/repos/${GITHUB_REPOSITORY}/releases/tags/${TAG}"; then
|
||||||
|
echo "::error::no release exists for ${TAG}. Create the release (which creates the tag) rather than pushing a bare tag — otherwise there is nothing to attach the APK to."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "::notice::release found for ${TAG}"
|
||||||
|
|
||||||
- name: Cache Gradle dirs
|
- name: Cache Gradle dirs
|
||||||
uses: actions/cache@v4
|
uses: actions/cache@v4
|
||||||
with:
|
with:
|
||||||
@@ -131,12 +156,19 @@ jobs:
|
|||||||
-PMINSTREL_VERSION_CODE=${{ steps.ver.outputs.code }}
|
-PMINSTREL_VERSION_CODE=${{ steps.ver.outputs.code }}
|
||||||
|
|
||||||
- name: Upload APK as workflow artifact
|
- name: Upload APK as workflow artifact
|
||||||
# @v3 because Gitea Actions emulates GHES and the v2 artifact
|
# Mirrored action, never actions/upload-artifact — @v4+ refuses on the
|
||||||
# backend used by upload-artifact@v4 errors with GHESNotSupportedError.
|
# hostname, @v3 uploads something Gitea will never serve back. This is
|
||||||
uses: actions/upload-artifact@v3
|
# the producing half of a pair: image-release downloads `minstrel-apk`
|
||||||
|
# below with the matching download-artifact mirror. Both must stay on
|
||||||
|
# the v4 protocol — mixing a v3 upload with a v4 download (or the
|
||||||
|
# reverse) yields an empty listing, not an error. See Scribe 2255 / 2270.
|
||||||
|
uses: https://git.fabledsword.com/bvandeusen/upload-artifact@cb8afe72b42edc798abfb8fcb556cf660d894245
|
||||||
with:
|
with:
|
||||||
name: minstrel-apk
|
name: minstrel-apk
|
||||||
path: android/app/build/outputs/apk/release/app-release.apk
|
path: android/app/build/outputs/apk/release/app-release.apk
|
||||||
|
# error, not the default warn: image-release hard-depends on this
|
||||||
|
# artifact existing, so an empty upload must fail here, not there.
|
||||||
|
if-no-files-found: error
|
||||||
|
|
||||||
- name: Attach APK to gitea Release
|
- name: Attach APK to gitea Release
|
||||||
shell: bash
|
shell: bash
|
||||||
@@ -238,7 +270,20 @@ jobs:
|
|||||||
# Tag pushes only — android-release just produced this. Non-tag
|
# Tag pushes only — android-release just produced this. Non-tag
|
||||||
# builds take the "Bundle latest release APK" path below instead.
|
# builds take the "Bundle latest release APK" path below instead.
|
||||||
if: steps.guard.outputs.ready == 'true' && startsWith(github.ref, 'refs/tags/v')
|
if: steps.guard.outputs.ready == 'true' && startsWith(github.ref, 'refs/tags/v')
|
||||||
uses: actions/download-artifact@v3
|
# Consuming half of the pair — never actions/download-artifact. Same fork,
|
||||||
|
# same reason: upstream's client-side GHES check rejects this hostname
|
||||||
|
# before it connects. bvandeusen/download-artifact mirrors
|
||||||
|
# code.forgejo.org/forgejo/download-artifact.
|
||||||
|
#
|
||||||
|
# SHA below is that fork's `v6` tag. Match on @actions/artifact, NOT on
|
||||||
|
# the action's own version number — the two actions release on unrelated
|
||||||
|
# cadences, and download v5 would pair a ^2.3.2 client with this file's
|
||||||
|
# ^4.0.0 uploader. v6 is the tag whose bundled library major (^4.0.0) is
|
||||||
|
# the same one proven against this instance by the upload side.
|
||||||
|
# Deliberately NOT v7: it moves to node24 and upstream requires runner
|
||||||
|
# >= 2.327.1 for it, which act_runner does not claim to satisfy.
|
||||||
|
# Pinned, not tagged — the mirror auto-syncs every 8h.
|
||||||
|
uses: https://git.fabledsword.com/bvandeusen/download-artifact@8d4e9521a5f7e5f8b6351f341f719f9f45a92a3a
|
||||||
with:
|
with:
|
||||||
name: minstrel-apk
|
name: minstrel-apk
|
||||||
path: client/
|
path: client/
|
||||||
@@ -302,3 +347,79 @@ jobs:
|
|||||||
docker buildx build \
|
docker buildx build \
|
||||||
--build-arg MINSTREL_VERSION="${{ steps.tags.outputs.version }}" \
|
--build-arg MINSTREL_VERSION="${{ steps.tags.outputs.version }}" \
|
||||||
--push ${{ steps.tags.outputs.args }} .
|
--push ${{ steps.tags.outputs.args }} .
|
||||||
|
|
||||||
|
# Verifies a tag release actually ended up complete, and names the specific
|
||||||
|
# thing that's missing if not.
|
||||||
|
#
|
||||||
|
# Added 2026-08-07 after v2026.08.07 was re-cut. The android-release job never
|
||||||
|
# started — no log was written at all — so all eight of its steps reported
|
||||||
|
# `failure` with none executed and image-release showed `skipped`. The run was
|
||||||
|
# red, but the *release page rendered fine*, and `main`'s own push build had
|
||||||
|
# already moved `:latest`, so the code was deployable and nothing looked
|
||||||
|
# obviously wrong. The release was simply missing its APK and its immutable
|
||||||
|
# `:vYYYY.MM.DD` image, which is easy to skim past.
|
||||||
|
#
|
||||||
|
# This job cannot prevent that (the cause was a runner failing to launch, not
|
||||||
|
# anything in this file). What it does is turn an incomplete release into an
|
||||||
|
# explicit, named error instead of eight mystery step failures — so the
|
||||||
|
# consequence is legible without having to infer it.
|
||||||
|
#
|
||||||
|
# `if: always()` is the whole point: it has to report precisely when the jobs
|
||||||
|
# above did NOT succeed.
|
||||||
|
verify-release:
|
||||||
|
name: Verify release artifacts (tag releases only)
|
||||||
|
needs: [android-release, image-release]
|
||||||
|
if: ${{ always() && startsWith(github.ref, 'refs/tags/v') }}
|
||||||
|
runs-on: go-ci
|
||||||
|
container:
|
||||||
|
image: git.fabledsword.com/bvandeusen/ci-go:1.26
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Release must have an APK attached
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
CI_TOKEN: ${{ secrets.CI_TOKEN }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
TAG="${GITHUB_REF#refs/tags/}"
|
||||||
|
REPO="${GITHUB_REPOSITORY}"
|
||||||
|
|
||||||
|
REL_JSON="$(curl -fsSL \
|
||||||
|
-H "Authorization: token ${CI_TOKEN}" \
|
||||||
|
"https://git.fabledsword.com/api/v1/repos/${REPO}/releases/tags/${TAG}" || true)"
|
||||||
|
if [ -z "${REL_JSON}" ]; then
|
||||||
|
echo "::error::no release found for ${TAG} — the tag exists but nothing was published"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
APK="$(printf '%s' "${REL_JSON}" \
|
||||||
|
| grep -oP '"browser_download_url":\s*"\K[^"]+' \
|
||||||
|
| grep -E '\.apk$' | head -1 || true)"
|
||||||
|
if [ -z "${APK}" ]; then
|
||||||
|
echo "::error::release ${TAG} has NO APK attached — in-app update will offer nothing, and the bundled-APK path on future :latest builds has no source."
|
||||||
|
echo "::error::Fix by RE-RUNNING this workflow run. Do NOT delete and re-create the tag; if it fails again the runner never started the container, and the evidence is in act_runner on the host (Gitea will hold no job log)."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "::notice::APK attached: ${APK}"
|
||||||
|
|
||||||
|
# The other half. Checking only the APK would report success on a release
|
||||||
|
# whose image push failed — which is precisely the second thing that was
|
||||||
|
# missing when v2026.08.07 had to be re-cut. `always()` on this job means
|
||||||
|
# it runs even when image-release failed, so without this the guard would
|
||||||
|
# cheerfully verify an incomplete release.
|
||||||
|
- name: Immutable image tag must exist
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
TAG="${GITHUB_REF#refs/tags/}"
|
||||||
|
IMAGE="git.fabledsword.com/bvandeusen/minstrel"
|
||||||
|
|
||||||
|
echo "${{ secrets.CI_TOKEN }}" \
|
||||||
|
| docker login git.fabledsword.com -u "${{ github.actor }}" --password-stdin
|
||||||
|
|
||||||
|
if ! docker manifest inspect "${IMAGE}:${TAG}" > /dev/null 2>&1; then
|
||||||
|
echo "::error::image ${IMAGE}:${TAG} was never pushed — the release tag has no immutable image, so there is nothing to pin or roll back to. Re-run this workflow run."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "::notice::image verified: ${IMAGE}:${TAG}"
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ on:
|
|||||||
- 'go.mod'
|
- 'go.mod'
|
||||||
- 'go.sum'
|
- 'go.sum'
|
||||||
- 'sqlc.yaml'
|
- 'sqlc.yaml'
|
||||||
|
- 'Makefile'
|
||||||
- 'internal/**'
|
- 'internal/**'
|
||||||
- 'cmd/**'
|
- 'cmd/**'
|
||||||
- '.golangci.yml'
|
- '.golangci.yml'
|
||||||
@@ -53,6 +54,9 @@ jobs:
|
|||||||
go version
|
go version
|
||||||
golangci-lint --version
|
golangci-lint --version
|
||||||
|
|
||||||
|
- name: Generated code matches queries (sqlc)
|
||||||
|
run: make verify-generate
|
||||||
|
|
||||||
- name: go vet
|
- name: go vet
|
||||||
run: go vet ./...
|
run: go vet ./...
|
||||||
|
|
||||||
|
|||||||
-14
@@ -52,20 +52,6 @@ GEMINI.md
|
|||||||
.windsurfrules
|
.windsurfrules
|
||||||
.aider.conf.yml
|
.aider.conf.yml
|
||||||
|
|
||||||
# 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
|
# Native Android (Kotlin/Compose) — M8 rewrite
|
||||||
android/.gradle/
|
android/.gradle/
|
||||||
android/.kotlin/
|
android/.kotlin/
|
||||||
|
|||||||
@@ -1,10 +1,34 @@
|
|||||||
.PHONY: generate test test-short test-integration lint build
|
.PHONY: generate generate-go verify-generate test test-short test-integration lint build
|
||||||
|
|
||||||
|
# renovate: datasource=docker depName=sqlc/sqlc
|
||||||
SQLC_VERSION := 1.31.1
|
SQLC_VERSION := 1.31.1
|
||||||
|
|
||||||
|
# Local codegen. Containerised so a dev needs no sqlc install.
|
||||||
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. This is the CI path:
|
||||||
|
# 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.
|
||||||
|
generate-go:
|
||||||
|
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.
|
||||||
|
#
|
||||||
|
# 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 log then contains sqlc's exact expected output, which is what you commit.
|
||||||
|
verify-generate: generate-go
|
||||||
|
# -N (intent-to-add) so a BRAND-NEW generated file is visible to `git
|
||||||
|
# diff`, which otherwise ignores untracked paths entirely — a whole
|
||||||
|
# missing *.sql.go would sail through the check below.
|
||||||
|
git add -N -- internal/db/dbq
|
||||||
|
git --no-pager diff -- internal/db/dbq
|
||||||
|
git diff --quiet -- internal/db/dbq
|
||||||
|
|
||||||
test:
|
test:
|
||||||
go test -race ./...
|
go test -race ./...
|
||||||
|
|
||||||
|
|||||||
@@ -11,10 +11,22 @@ A self-hosted music server that thinks for you. Smart shuffle, contextual likes,
|
|||||||
- **OpenSubsonic-compatible.** Existing Subsonic clients (DSub, Symfonium, play:Sub, etc.) connect with no special configuration.
|
- **OpenSubsonic-compatible.** Existing Subsonic clients (DSub, Symfonium, play:Sub, etc.) connect with no special configuration.
|
||||||
- **Server-side smart shuffle.** Track-similarity vectors, dual-like model (general + contextual), and session memory keep mixes coherent across devices.
|
- **Server-side smart shuffle.** Track-similarity vectors, dual-like model (general + contextual), and session memory keep mixes coherent across devices.
|
||||||
- **ListenBrainz radio.** Session-aware "more like this" pulls from ListenBrainz similarity data, not a static genre tag.
|
- **ListenBrainz radio.** Session-aware "more like this" pulls from ListenBrainz similarity data, not a static genre tag.
|
||||||
- **Lidarr integration.** Triggered scans, request-driven album imports, and a quarantine flow when something doesn't fit.
|
- **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.
|
- **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).
|
- **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).
|
||||||
|
|
||||||
|
## Scope and responsible use
|
||||||
|
|
||||||
|
**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
|
## Quickstart
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
|
|||||||
@@ -210,4 +210,17 @@ dependencies {
|
|||||||
debugImplementation(libs.compose.ui.test.manifest)
|
debugImplementation(libs.compose.ui.test.manifest)
|
||||||
}
|
}
|
||||||
|
|
||||||
tasks.withType<Test> { useJUnitPlatform() }
|
tasks.withType<Test> {
|
||||||
|
useJUnitPlatform()
|
||||||
|
// Print the assertion message + full stack trace for failures. The
|
||||||
|
// default console output gives only "AssertionError at Foo.kt:12", and
|
||||||
|
// for a failure inside a `runTest { }` lambda even that line collapses
|
||||||
|
// to the test function's own line (the assertion frames live in the
|
||||||
|
// suspend-lambda class, which Gradle filters out) — leaving nothing to
|
||||||
|
// debug from when the HTML report isn't reachable, as in CI.
|
||||||
|
testLogging {
|
||||||
|
events("failed")
|
||||||
|
exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL
|
||||||
|
showStackTraces = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -8,7 +8,16 @@
|
|||||||
<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" />
|
||||||
|
<!-- 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+)
|
||||||
|
is what lets that install happen with NO confirm dialog. The platform
|
||||||
|
grants the silent path only when the installer opts in via
|
||||||
|
SessionParams.setRequireUserAction(USER_ACTION_NOT_REQUIRED), the
|
||||||
|
installed app targets API 29+, the installer holds this permission, and
|
||||||
|
the target is the installer itself — all true here, since Minstrel is
|
||||||
|
updating Minstrel. See update/data/SelfUpdateSession.kt. -->
|
||||||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||||
|
<uses-permission android:name="android.permission.UPDATE_PACKAGES_WITHOUT_USER_ACTION" />
|
||||||
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
|
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
|
||||||
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
|
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
|
||||||
|
|
||||||
@@ -19,9 +28,9 @@
|
|||||||
android:fullBackupContent="@xml/backup_rules"
|
android:fullBackupContent="@xml/backup_rules"
|
||||||
android:icon="@mipmap/ic_launcher"
|
android:icon="@mipmap/ic_launcher"
|
||||||
android:label="@string/app_name"
|
android:label="@string/app_name"
|
||||||
|
android:networkSecurityConfig="@xml/network_security_config"
|
||||||
android:supportsRtl="true"
|
android:supportsRtl="true"
|
||||||
android:theme="@style/Theme.Minstrel"
|
android:theme="@style/Theme.Minstrel"
|
||||||
android:usesCleartextTraffic="true"
|
|
||||||
tools:targetApi="34">
|
tools:targetApi="34">
|
||||||
|
|
||||||
<!-- Portrait-locked until a tablet/landscape layout exists.
|
<!-- Portrait-locked until a tablet/landscape layout exists.
|
||||||
@@ -48,15 +57,11 @@
|
|||||||
</intent-filter>
|
</intent-filter>
|
||||||
</service>
|
</service>
|
||||||
|
|
||||||
<provider
|
<!-- The FileProvider that used to live here existed solely to expose the
|
||||||
android:name="androidx.core.content.FileProvider"
|
downloaded update APK as a content:// URI for the old ACTION_VIEW
|
||||||
android:authorities="${applicationId}.fileprovider"
|
install intent. A PackageInstaller session takes a stream instead,
|
||||||
android:exported="false"
|
so both the provider and res/xml/file_paths.xml are gone — nothing
|
||||||
android:grantUriPermissions="true">
|
else in the app ever used that authority. -->
|
||||||
<meta-data
|
|
||||||
android:name="android.support.FILE_PROVIDER_PATHS"
|
|
||||||
android:resource="@xml/file_paths" />
|
|
||||||
</provider>
|
|
||||||
|
|
||||||
<!-- On-demand WorkManager initialization: MinstrelApplication
|
<!-- On-demand WorkManager initialization: MinstrelApplication
|
||||||
implements Configuration.Provider and supplies the
|
implements Configuration.Provider and supplies the
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import androidx.work.Configuration
|
|||||||
import coil3.ImageLoader
|
import coil3.ImageLoader
|
||||||
import coil3.SingletonImageLoader
|
import coil3.SingletonImageLoader
|
||||||
import coil3.network.okhttp.OkHttpNetworkFetcherFactory
|
import coil3.network.okhttp.OkHttpNetworkFetcherFactory
|
||||||
|
import coil3.request.crossfade
|
||||||
import com.fabledsword.minstrel.cache.CacheIndexer
|
import com.fabledsword.minstrel.cache.CacheIndexer
|
||||||
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
|
||||||
@@ -29,6 +30,10 @@ import okhttp3.OkHttpClient
|
|||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
|
// Cover-art fade-in. Coil skips the transition for memory-cache hits, so
|
||||||
|
// already-loaded art still appears instantly — only a genuine fetch fades.
|
||||||
|
private const val ART_CROSSFADE_MS = 220
|
||||||
|
|
||||||
@HiltAndroidApp
|
@HiltAndroidApp
|
||||||
class MinstrelApplication :
|
class MinstrelApplication :
|
||||||
Application(),
|
Application(),
|
||||||
@@ -213,11 +218,18 @@ class MinstrelApplication :
|
|||||||
* OkHttp client as the network fetcher. The `callFactory` lambda
|
* OkHttp client as the network fetcher. The `callFactory` lambda
|
||||||
* is invoked lazily so Hilt has time to inject `okHttpClient`
|
* is invoked lazily so Hilt has time to inject `okHttpClient`
|
||||||
* before Coil makes its first request.
|
* before Coil makes its first request.
|
||||||
|
*
|
||||||
|
* Crossfade is set here rather than per-call so every cover surface
|
||||||
|
* in the app fades its artwork in instead of snapping it. Art
|
||||||
|
* landing a beat after its tile was the most visible pop-in on Home
|
||||||
|
* (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)
|
||||||
.components {
|
.components {
|
||||||
add(OkHttpNetworkFetcherFactory(callFactory = { okHttpClient }))
|
add(OkHttpNetworkFetcherFactory(callFactory = { okHttpClient }))
|
||||||
}
|
}
|
||||||
|
.crossfade(ART_CROSSFADE_MS)
|
||||||
.build()
|
.build()
|
||||||
}
|
}
|
||||||
|
|||||||
-2
@@ -11,8 +11,6 @@ import javax.inject.Singleton
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Read-through accessor for the admin cross-user requests queue.
|
* 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
|
* No Room caching — admin actions are infrequent and don't benefit
|
||||||
* from offline scrollback. `approve` and `reject` fire direct REST
|
* from offline scrollback. `approve` and `reject` fire direct REST
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ import com.fabledsword.minstrel.nav.AdminQuarantine
|
|||||||
import com.fabledsword.minstrel.nav.AdminRequests
|
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.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
|
||||||
@@ -112,6 +113,7 @@ 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(
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ 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.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
|
||||||
@@ -42,6 +43,7 @@ fun AdminQuarantineScreen(
|
|||||||
) {
|
) {
|
||||||
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(
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
|||||||
import androidx.navigation.NavHostController
|
import androidx.navigation.NavHostController
|
||||||
import com.fabledsword.minstrel.models.RequestRef
|
import com.fabledsword.minstrel.models.RequestRef
|
||||||
import com.fabledsword.minstrel.nav.AdminRequests
|
import com.fabledsword.minstrel.nav.AdminRequests
|
||||||
|
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
|
||||||
import com.fabledsword.minstrel.shared.widgets.EmptyState
|
import com.fabledsword.minstrel.shared.widgets.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
|
||||||
@@ -41,6 +42,7 @@ fun AdminRequestsScreen(
|
|||||||
) {
|
) {
|
||||||
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(
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ 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.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,6 +50,7 @@ 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(
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ 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.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
|
||||||
@@ -127,6 +128,7 @@ private fun AdminUsersScaffold(
|
|||||||
onRevokeInvite: (String) -> Unit,
|
onRevokeInvite: (String) -> Unit,
|
||||||
) {
|
) {
|
||||||
Scaffold(
|
Scaffold(
|
||||||
|
contentWindowInsets = ShellContentWindowInsets,
|
||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.fillMaxSize(),
|
||||||
topBar = {
|
topBar = {
|
||||||
MinstrelTopAppBar(
|
MinstrelTopAppBar(
|
||||||
|
|||||||
@@ -8,8 +8,7 @@ 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. Mirrors
|
* friendly, sentence-case copy.
|
||||||
* `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
|
||||||
|
|||||||
@@ -10,8 +10,7 @@ import retrofit2.http.POST
|
|||||||
import retrofit2.http.Path
|
import retrofit2.http.Path
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for `/api/admin/invites`. Mirrors
|
* Retrofit interface for `/api/admin/invites`.
|
||||||
* `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.
|
||||||
|
|||||||
+1
-2
@@ -6,8 +6,7 @@ import retrofit2.http.POST
|
|||||||
import retrofit2.http.Path
|
import retrofit2.http.Path
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for `/api/admin/quarantine`. Mirrors
|
* Retrofit interface for `/api/admin/quarantine`.
|
||||||
* `flutter_client/lib/api/endpoints/admin_quarantine.dart`.
|
|
||||||
*
|
*
|
||||||
* Three resolution endpoints:
|
* Three resolution endpoints:
|
||||||
* - `resolve` → admin reviewed, no action taken (clears flags).
|
* - `resolve` → admin reviewed, no action taken (clears flags).
|
||||||
|
|||||||
+1
-2
@@ -6,8 +6,7 @@ import retrofit2.http.POST
|
|||||||
import retrofit2.http.Path
|
import retrofit2.http.Path
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for `/api/admin/requests`. Mirrors
|
* Retrofit interface for `/api/admin/requests`.
|
||||||
* `flutter_client/lib/api/endpoints/admin_requests.dart`.
|
|
||||||
*
|
*
|
||||||
* Server returns the same `requestView` shape as the user-side
|
* Server returns the same `requestView` shape as the user-side
|
||||||
* `/api/requests`, so RequestWire is reused. Different listing scope —
|
* `/api/requests`, so RequestWire is reused. Different listing scope —
|
||||||
|
|||||||
@@ -10,8 +10,7 @@ import retrofit2.http.PUT
|
|||||||
import retrofit2.http.Path
|
import retrofit2.http.Path
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for `/api/admin/users`. Mirrors
|
* Retrofit interface for `/api/admin/users`.
|
||||||
* `flutter_client/lib/api/endpoints/admin_users.dart`.
|
|
||||||
*
|
*
|
||||||
* Note: the PUT-auto-approve body field is `auto_approve`, NOT
|
* Note: the PUT-auto-approve body field is `auto_approve`, NOT
|
||||||
* `auto_approve_requests` — the request shape differs from the
|
* `auto_approve_requests` — the request shape differs from the
|
||||||
|
|||||||
@@ -6,8 +6,7 @@ import retrofit2.http.Body
|
|||||||
import retrofit2.http.POST
|
import retrofit2.http.POST
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for `/api/auth`. Mirrors
|
* Retrofit interface for `/api/auth`.
|
||||||
* `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
|
||||||
|
|||||||
@@ -3,14 +3,17 @@ package com.fabledsword.minstrel.api.endpoints
|
|||||||
import com.fabledsword.minstrel.models.wire.ArtistSuggestionWire
|
import com.fabledsword.minstrel.models.wire.ArtistSuggestionWire
|
||||||
import com.fabledsword.minstrel.models.wire.CreateRequestBody
|
import com.fabledsword.minstrel.models.wire.CreateRequestBody
|
||||||
import com.fabledsword.minstrel.models.wire.LidarrSearchResultWire
|
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.Body
|
||||||
|
import retrofit2.http.DELETE
|
||||||
import retrofit2.http.GET
|
import retrofit2.http.GET
|
||||||
import retrofit2.http.POST
|
import retrofit2.http.POST
|
||||||
|
import retrofit2.http.Path
|
||||||
import retrofit2.http.Query
|
import retrofit2.http.Query
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for Discover / Lidarr search / request creation.
|
* 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
|
* `/api/lidarr/search` has a 60s LRU on the server so quick re-types
|
||||||
* of the same query are cheap.
|
* of the same query are cheap.
|
||||||
@@ -30,4 +33,30 @@ interface DiscoverApi {
|
|||||||
|
|
||||||
@POST("api/requests")
|
@POST("api/requests")
|
||||||
suspend fun createRequest(@Body body: CreateRequestBody)
|
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,8 +9,7 @@ import retrofit2.http.Body
|
|||||||
import retrofit2.http.POST
|
import retrofit2.http.POST
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for `POST /api/events`. Mirrors the relevant
|
* Retrofit interface for `POST /api/events`. All four
|
||||||
* 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,10 +5,9 @@ import retrofit2.http.GET
|
|||||||
import retrofit2.http.Query
|
import retrofit2.http.Query
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for `/api/me/history`. Mirrors the relevant
|
* Retrofit interface for `/api/me/history` — history only. The profile,
|
||||||
* subset of `flutter_client/lib/api/endpoints/me.dart` (only
|
* timezone and quarantine endpoints on `/api/me` live with their own
|
||||||
* `history()`; profile / timezone / quarantine endpoints land with
|
* features rather than here.
|
||||||
* their respective phases).
|
|
||||||
*/
|
*/
|
||||||
interface HistoryApi {
|
interface HistoryApi {
|
||||||
@GET("api/me/history")
|
@GET("api/me/history")
|
||||||
|
|||||||
@@ -4,10 +4,9 @@ import com.fabledsword.minstrel.models.wire.HomeIndexWire
|
|||||||
import retrofit2.http.GET
|
import retrofit2.http.GET
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for the Home discovery endpoint. Mirrors
|
* Retrofit interface for the Home discovery endpoint. Only the ID-only
|
||||||
* `flutter_client/lib/api/endpoints/home.dart` — just the ID-only
|
* `/api/home/index` variant is used. The server also serves a heavier
|
||||||
* `/api/home/index` variant. The Flutter port has a heavier
|
* `/api/home` (full embedded payload); we don't use it because
|
||||||
* `/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,14 +3,16 @@ 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
|
||||||
@@ -54,6 +56,49 @@ 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 (#367). 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 cache
|
||||||
|
// is a full mirror of the library, but /api/library/sync ships tracks whose
|
||||||
|
// files are missing and carries no flag for it (#2704), while the browse
|
||||||
|
// index filters them out -- so a locally-computed index would disagree with
|
||||||
|
// the server's and with the web client. One source of truth wins over
|
||||||
|
// offline capability here until #2704 is resolved.
|
||||||
|
@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,8 +7,7 @@ import retrofit2.http.POST
|
|||||||
import retrofit2.http.Path
|
import retrofit2.http.Path
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for `/api/likes`. Mirrors
|
* Retrofit interface for `/api/likes`.
|
||||||
* `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
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ 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
|
||||||
|
|||||||
@@ -11,8 +11,7 @@ import retrofit2.http.Path
|
|||||||
import retrofit2.http.Query
|
import retrofit2.http.Query
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for `/api/playlists`. Mirrors
|
* Retrofit interface for `/api/playlists`.
|
||||||
* `flutter_client/lib/api/endpoints/playlists.dart`.
|
|
||||||
*/
|
*/
|
||||||
interface PlaylistsApi {
|
interface PlaylistsApi {
|
||||||
/**
|
/**
|
||||||
@@ -54,7 +53,7 @@ interface PlaylistsApi {
|
|||||||
* 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. Mirrors `playlists.dart.systemShuffle`.
|
* the stored order.
|
||||||
*/
|
*/
|
||||||
@GET("api/playlists/system/{kind}/shuffle")
|
@GET("api/playlists/system/{kind}/shuffle")
|
||||||
suspend fun systemShuffle(@Path("kind") variant: String): PlaylistDetailWire
|
suspend fun systemShuffle(@Path("kind") variant: String): PlaylistDetailWire
|
||||||
|
|||||||
@@ -8,9 +8,8 @@ import retrofit2.http.POST
|
|||||||
import retrofit2.http.Path
|
import retrofit2.http.Path
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for `/api/quarantine`. Mirrors the relevant
|
* Retrofit interface for `/api/quarantine`: flag and unflag, plus the
|
||||||
* parts of `flutter_client/lib/api/endpoints/quarantine.dart` (flag
|
* `/api/quarantine/mine` listing.
|
||||||
* 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
|
||||||
|
|||||||
@@ -5,9 +5,7 @@ import retrofit2.http.GET
|
|||||||
import retrofit2.http.Query
|
import retrofit2.http.Query
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for `/api/radio`. Mirrors the relevant slice of
|
* Retrofit interface for `/api/radio`. The server picks a fresh shuffle each
|
||||||
* `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 {
|
||||||
|
|||||||
@@ -6,8 +6,7 @@ import retrofit2.http.GET
|
|||||||
import retrofit2.http.Path
|
import retrofit2.http.Path
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for the user-side `/api/requests`. Mirrors
|
* Retrofit interface for the user-side `/api/requests`.
|
||||||
* `flutter_client/lib/api/endpoints/requests.dart`.
|
|
||||||
*
|
*
|
||||||
* Server scopes results to the caller — admins see only their own
|
* Server scopes results to the caller — admins see only their own
|
||||||
* requests through this endpoint. The cross-user admin view lives on
|
* requests through this endpoint. The cross-user admin view lives on
|
||||||
|
|||||||
@@ -5,8 +5,7 @@ import retrofit2.http.GET
|
|||||||
import retrofit2.http.Query
|
import retrofit2.http.Query
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrofit interface for `GET /api/search`. Mirrors
|
* Retrofit interface for `GET /api/search`. Server returns 400
|
||||||
* `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.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -17,8 +17,7 @@ import javax.inject.Inject
|
|||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Singleton facade over the auth state machine. Mirrors Flutter's
|
* Singleton facade over the auth state machine.
|
||||||
* `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
|
||||||
|
|||||||
@@ -12,8 +12,7 @@ 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. Mirrors
|
* Offline play sources over the local audio-cache index.
|
||||||
* `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
|
||||||
@@ -58,6 +57,14 @@ 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 { byId[it]?.toDomain() }
|
return orderedIds.mapNotNull { id ->
|
||||||
|
// Clear the server's missing mark (#2704). 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)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
package com.fabledsword.minstrel.cache.audiocache
|
package com.fabledsword.minstrel.cache.audiocache
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Defaults for the 2-bucket audio cache. Matches the Flutter client.
|
* Defaults for the 2-bucket audio cache.
|
||||||
*
|
*
|
||||||
* - `likedCapBytes`: cap for the protected bucket — cached files for
|
* - `likedCapBytes`: cap for the protected bucket — cached files for
|
||||||
* tracks the user has liked. Evicted only after the rolling bucket
|
* tracks the user has liked. Evicted only after the rolling bucket
|
||||||
|
|||||||
+1
-2
@@ -6,8 +6,7 @@ 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. Mirrors Flutter's `CacheSettings`
|
* User-tunable audio cache settings. Persisted as a JSON
|
||||||
* (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]: budget for cached files of liked tracks. 0 means
|
* - [likedCapBytes]: budget for cached files of liked tracks. 0 means
|
||||||
|
|||||||
@@ -65,9 +65,13 @@ import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity
|
|||||||
AuthSessionEntity::class,
|
AuthSessionEntity::class,
|
||||||
DiagnosticEventEntity::class,
|
DiagnosticEventEntity::class,
|
||||||
],
|
],
|
||||||
|
// v8: + cached_tracks.missing, the server's missing-file mark (#2704),
|
||||||
|
// so cache-first surfaces stop offering files that cannot stream.
|
||||||
// v7: + diagnostic_events table (M9) and the diagnosticsOptOut column
|
// v7: + diagnostic_events table (M9) and the diagnosticsOptOut column
|
||||||
// on auth_session. Pre-v1 destructive fallback rebuilds on mismatch.
|
// on auth_session. Pre-v1 destructive fallback rebuilds on mismatch —
|
||||||
version = 7,
|
// which is exactly right here: the next sync refills every row with the
|
||||||
|
// new column populated, so there is nothing to migrate by hand.
|
||||||
|
version = 8,
|
||||||
exportSchema = true,
|
exportSchema = true,
|
||||||
)
|
)
|
||||||
@TypeConverters(MinstrelTypeConverters::class)
|
@TypeConverters(MinstrelTypeConverters::class)
|
||||||
|
|||||||
+24
-3
@@ -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 androidx.room.Transaction
|
||||||
import com.fabledsword.minstrel.cache.db.entities.CachedHomeIndexEntity
|
import com.fabledsword.minstrel.cache.db.entities.CachedHomeIndexEntity
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
|
||||||
@@ -21,12 +22,32 @@ interface CachedHomeIndexDao {
|
|||||||
)
|
)
|
||||||
suspend fun getBySection(section: String): List<CachedHomeIndexEntity>
|
suspend fun getBySection(section: String): List<CachedHomeIndexEntity>
|
||||||
|
|
||||||
|
/** True when Home has any cached section rows to render. */
|
||||||
|
@Query("SELECT EXISTS(SELECT 1 FROM cached_home_index)")
|
||||||
|
suspend fun hasAny(): Boolean
|
||||||
|
|
||||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||||
suspend fun upsertAll(rows: List<CachedHomeIndexEntity>)
|
suspend fun upsertAll(rows: List<CachedHomeIndexEntity>)
|
||||||
|
|
||||||
/** Replace-all pattern; sync wipes a section then re-inserts. */
|
@Query("DELETE FROM cached_home_index WHERE section IN (:sections)")
|
||||||
@Query("DELETE FROM cached_home_index WHERE section = :section")
|
suspend fun deleteSections(sections: List<String>)
|
||||||
suspend fun deleteBySection(section: String)
|
|
||||||
|
/**
|
||||||
|
* Swaps every listed section's rows in ONE transaction.
|
||||||
|
*
|
||||||
|
* Atomicity is the point, not just tidiness: Room's
|
||||||
|
* InvalidationTracker only notifies observers after the transaction
|
||||||
|
* commits, so [observeBySection] never sees the empty gap between the
|
||||||
|
* delete and the re-insert. Replacing sections one at a time (and
|
||||||
|
* un-transacted) made each Home row emit `emptyList()` — visibly
|
||||||
|
* collapsing — before refilling, and made the seven sections do it in
|
||||||
|
* sequence rather than as a single content swap.
|
||||||
|
*/
|
||||||
|
@Transaction
|
||||||
|
suspend fun replaceSections(sections: List<String>, rows: List<CachedHomeIndexEntity>) {
|
||||||
|
deleteSections(sections)
|
||||||
|
if (rows.isNotEmpty()) upsertAll(rows)
|
||||||
|
}
|
||||||
|
|
||||||
@Query("DELETE FROM cached_home_index")
|
@Query("DELETE FROM cached_home_index")
|
||||||
suspend fun clear()
|
suspend fun clear()
|
||||||
|
|||||||
-1
@@ -59,7 +59,6 @@ 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
|
||||||
|
|||||||
+25
-1
@@ -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 androidx.room.Transaction
|
||||||
import com.fabledsword.minstrel.cache.db.entities.CachedPlaylistTrackEntity
|
import com.fabledsword.minstrel.cache.db.entities.CachedPlaylistTrackEntity
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
|
||||||
@@ -35,10 +36,33 @@ interface CachedPlaylistTrackDao {
|
|||||||
@Query("SELECT MAX(position) FROM cached_playlist_tracks WHERE playlistId = :playlistId")
|
@Query("SELECT MAX(position) FROM cached_playlist_tracks WHERE playlistId = :playlistId")
|
||||||
suspend fun maxPosition(playlistId: String): Int?
|
suspend fun maxPosition(playlistId: String): Int?
|
||||||
|
|
||||||
/** Replace-all pattern for a playlist; called after a sync delta lands. */
|
|
||||||
@Query("DELETE FROM cached_playlist_tracks WHERE playlistId = :playlistId")
|
@Query("DELETE FROM cached_playlist_tracks WHERE playlistId = :playlistId")
|
||||||
suspend fun deleteByPlaylist(playlistId: String)
|
suspend fun deleteByPlaylist(playlistId: String)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Replaces a playlist's whole membership in ONE transaction; called
|
||||||
|
* after a refresh or a sync delta lands.
|
||||||
|
*
|
||||||
|
* Atomic on purpose. Room's InvalidationTracker only notifies observers
|
||||||
|
* after the transaction commits, so [observeByPlaylist] never sees the
|
||||||
|
* empty gap between the delete and the re-insert. Un-transacted, that
|
||||||
|
* gap is a real observed state — it's what made every Home row visibly
|
||||||
|
* collapse to empty and refill before issue #2327 fixed the equivalent
|
||||||
|
* write in `CachedHomeIndexDao`.
|
||||||
|
*
|
||||||
|
* Nothing observes [observeByPlaylist] live today, so this is
|
||||||
|
* pre-emptive: it means making playlist detail cache-first later can't
|
||||||
|
* silently reintroduce that flicker.
|
||||||
|
*/
|
||||||
|
@Transaction
|
||||||
|
suspend fun replacePlaylistTracks(
|
||||||
|
playlistId: String,
|
||||||
|
rows: List<CachedPlaylistTrackEntity>,
|
||||||
|
) {
|
||||||
|
deleteByPlaylist(playlistId)
|
||||||
|
if (rows.isNotEmpty()) upsertAll(rows)
|
||||||
|
}
|
||||||
|
|
||||||
@Query(
|
@Query(
|
||||||
"DELETE FROM cached_playlist_tracks " +
|
"DELETE FROM cached_playlist_tracks " +
|
||||||
"WHERE playlistId = :playlistId AND trackId IN (:trackIds)",
|
"WHERE playlistId = :playlistId AND trackId IN (:trackIds)",
|
||||||
|
|||||||
Vendored
+1
-1
@@ -8,7 +8,7 @@ import kotlinx.datetime.Instant
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* One row per fully-downloaded audio file. Mirrors
|
* One row per fully-downloaded audio file. Mirrors
|
||||||
* `flutter_client/lib/cache/db.dart`'s `AudioCacheIndex` Drift table.
|
* the Flutter client's `AudioCacheIndex` Drift table.
|
||||||
*
|
*
|
||||||
* Drives the 2-bucket LRU eviction (Phase 12 AudioCacheEvictionWorker):
|
* Drives the 2-bucket LRU eviction (Phase 12 AudioCacheEvictionWorker):
|
||||||
* - `incidental` files (streamed-and-cached side effect) evict first
|
* - `incidental` files (streamed-and-cached side effect) evict first
|
||||||
|
|||||||
+1
-1
@@ -6,7 +6,7 @@ import kotlinx.datetime.Clock
|
|||||||
import kotlinx.datetime.Instant
|
import kotlinx.datetime.Instant
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Cache row for one album. Mirrors `flutter_client/lib/cache/db.dart`'s
|
* Cache row for one album. Mirrors the Flutter client's
|
||||||
* `CachedAlbums` Drift table.
|
* `CachedAlbums` Drift table.
|
||||||
*/
|
*/
|
||||||
@Entity(tableName = "cached_albums")
|
@Entity(tableName = "cached_albums")
|
||||||
|
|||||||
+1
-1
@@ -6,7 +6,7 @@ import kotlinx.datetime.Clock
|
|||||||
import kotlinx.datetime.Instant
|
import kotlinx.datetime.Instant
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Cache row for one artist. Mirrors `flutter_client/lib/cache/db.dart`'s
|
* Cache row for one artist. Mirrors the Flutter client's
|
||||||
* `CachedArtists` Drift table.
|
* `CachedArtists` Drift table.
|
||||||
*
|
*
|
||||||
* Column names follow Kotlin idiom (camelCase) rather than Drift's
|
* Column names follow Kotlin idiom (camelCase) rather than Drift's
|
||||||
|
|||||||
Vendored
+1
-1
@@ -6,7 +6,7 @@ import kotlinx.datetime.Instant
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Per-item row driving the Home screen sections. Mirrors
|
* Per-item row driving the Home screen sections. Mirrors
|
||||||
* `flutter_client/lib/cache/db.dart`'s `CachedHomeIndex` Drift table.
|
* the Flutter client's `CachedHomeIndex` Drift table.
|
||||||
*
|
*
|
||||||
* `section` is one of (matching /api/home keys):
|
* `section` is one of (matching /api/home keys):
|
||||||
* - "recently_added_albums"
|
* - "recently_added_albums"
|
||||||
|
|||||||
+1
-1
@@ -5,7 +5,7 @@ import kotlinx.datetime.Clock
|
|||||||
import kotlinx.datetime.Instant
|
import kotlinx.datetime.Instant
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Like membership row. Mirrors `flutter_client/lib/cache/db.dart`'s
|
* Like membership row. Mirrors the Flutter client's
|
||||||
* `CachedLikes` Drift table. Composite primary key — one user may
|
* `CachedLikes` Drift table. Composite primary key — one user may
|
||||||
* independently like a track AND its album AND its artist; rows are
|
* independently like a track AND its album AND its artist; rows are
|
||||||
* disambiguated by the (userId, entityType, entityId) triple.
|
* disambiguated by the (userId, entityType, entityId) triple.
|
||||||
|
|||||||
Vendored
+1
-1
@@ -7,7 +7,7 @@ import kotlinx.datetime.Instant
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* One row per pending offline-write. Mirrors
|
* One row per pending offline-write. Mirrors
|
||||||
* `flutter_client/lib/cache/db.dart`'s `CachedMutations` Drift table.
|
* the Flutter client's `CachedMutations` Drift table.
|
||||||
*
|
*
|
||||||
* MutationQueue.enqueue() inserts a row when a server-write fails with
|
* MutationQueue.enqueue() inserts a row when a server-write fails with
|
||||||
* an IOException; MutationReplayer.drain() pops and re-attempts each
|
* an IOException; MutationReplayer.drain() pops and re-attempts each
|
||||||
|
|||||||
Vendored
+1
-1
@@ -7,7 +7,7 @@ import kotlinx.datetime.Instant
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Cache row for one playlist (user or system). Mirrors
|
* Cache row for one playlist (user or system). Mirrors
|
||||||
* `flutter_client/lib/cache/db.dart`'s `CachedPlaylists` Drift table.
|
* the Flutter client's `CachedPlaylists` Drift table.
|
||||||
*
|
*
|
||||||
* `systemVariant` is null for user playlists and one of
|
* `systemVariant` is null for user playlists and one of
|
||||||
* "for_you" / "songs_like_artist" / "discover" / "todays_mix" / etc.
|
* "for_you" / "songs_like_artist" / "discover" / "todays_mix" / etc.
|
||||||
|
|||||||
Vendored
+1
-1
@@ -4,7 +4,7 @@ import androidx.room.Entity
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Ordered membership of tracks within a playlist. Mirrors
|
* Ordered membership of tracks within a playlist. Mirrors
|
||||||
* `flutter_client/lib/cache/db.dart`'s `CachedPlaylistTracks` Drift table.
|
* the Flutter client's `CachedPlaylistTracks` Drift table.
|
||||||
* Composite PK so the same track can only appear once per playlist;
|
* Composite PK so the same track can only appear once per playlist;
|
||||||
* `position` carries the ordering.
|
* `position` carries the ordering.
|
||||||
*/
|
*/
|
||||||
|
|||||||
Vendored
+1
-1
@@ -7,7 +7,7 @@ import kotlinx.datetime.Instant
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* The current user's quarantine flag for one track. Mirrors
|
* The current user's quarantine flag for one track. Mirrors
|
||||||
* `flutter_client/lib/cache/db.dart`'s `CachedQuarantineMine` Drift
|
* the Flutter client's `CachedQuarantineMine` Drift
|
||||||
* table.
|
* table.
|
||||||
*
|
*
|
||||||
* The flat denormalized track/album/artist columns let the Quarantine
|
* The flat denormalized track/album/artist columns let the Quarantine
|
||||||
|
|||||||
Vendored
+1
-1
@@ -8,7 +8,7 @@ import kotlinx.datetime.Instant
|
|||||||
/**
|
/**
|
||||||
* Single-row snapshot of the last playback session — queue (as JSON),
|
* Single-row snapshot of the last playback session — queue (as JSON),
|
||||||
* current index, position, and source tag. Mirrors
|
* current index, position, and source tag. Mirrors
|
||||||
* `flutter_client/lib/cache/db.dart`'s `CachedResumeState` Drift table.
|
* the Flutter client's `CachedResumeState` Drift table.
|
||||||
*
|
*
|
||||||
* Lets a torn-down session (the player's idle/dismissed teardown)
|
* Lets a torn-down session (the player's idle/dismissed teardown)
|
||||||
* resume on next launch; without it the headset / lock-screen play
|
* resume on next launch; without it the headset / lock-screen play
|
||||||
|
|||||||
+6
-1
@@ -6,8 +6,12 @@ import kotlinx.datetime.Clock
|
|||||||
import kotlinx.datetime.Instant
|
import kotlinx.datetime.Instant
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Cache row for one track. Mirrors `flutter_client/lib/cache/db.dart`'s
|
* Cache row for one track. Mirrors the Flutter client's
|
||||||
* `CachedTracks` Drift table.
|
* `CachedTracks` Drift table.
|
||||||
|
*
|
||||||
|
* [missing] carries the server's missing-file mark (#2704). Every read that
|
||||||
|
* can put a track in front of the user — or in a queue — must exclude it, and
|
||||||
|
* the DAO queries do that rather than each call site remembering to.
|
||||||
*/
|
*/
|
||||||
@Entity(tableName = "cached_tracks")
|
@Entity(tableName = "cached_tracks")
|
||||||
data class CachedTrackEntity(
|
data class CachedTrackEntity(
|
||||||
@@ -21,5 +25,6 @@ data class CachedTrackEntity(
|
|||||||
val filePath: String? = null,
|
val filePath: String? = null,
|
||||||
val fileFormat: String? = null,
|
val fileFormat: String? = null,
|
||||||
val genre: String? = null,
|
val genre: String? = null,
|
||||||
|
val missing: Boolean = false,
|
||||||
val fetchedAt: Instant = Clock.System.now(),
|
val fetchedAt: Instant = Clock.System.now(),
|
||||||
)
|
)
|
||||||
|
|||||||
+40
@@ -35,6 +35,12 @@ object MutationKind {
|
|||||||
// background avoids the duplicate + orphan row the old offline-on-stop
|
// background avoids the duplicate + orphan row the old offline-on-stop
|
||||||
// path produced (see 2026-06-11 contract audit).
|
// path produced (see 2026-06-11 contract audit).
|
||||||
const val PLAY_ENDED: String = "play_ended"
|
const val PLAY_ENDED: String = "play_ended"
|
||||||
|
|
||||||
|
// #2374 suggestion snooze. ONE toggle kind rather than separate
|
||||||
|
// snooze/unsnooze kinds, mirroring LIKE_TOGGLE, so a snooze followed by
|
||||||
|
// an undo collapses to the latest intent instead of replaying as two
|
||||||
|
// opposed calls whose order decides the outcome.
|
||||||
|
const val SUGGESTION_SNOOZE_TOGGLE: String = "suggestion_snooze_toggle"
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -152,6 +158,25 @@ class MutationQueue @Inject constructor(
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Queues a suggestion snooze (or its undo) for replay. [desiredSnoozed]
|
||||||
|
* is the TARGET state, so repeated taps collapse to one replay.
|
||||||
|
*
|
||||||
|
* [name] is carried even for an un-snooze, where the server ignores it,
|
||||||
|
* so a single payload shape serves both directions.
|
||||||
|
*/
|
||||||
|
suspend fun enqueueSuggestionSnoozeToggle(
|
||||||
|
mbid: String,
|
||||||
|
name: String,
|
||||||
|
desiredSnoozed: Boolean,
|
||||||
|
): Long = insertUserDriven(
|
||||||
|
MutationKind.SUGGESTION_SNOOZE_TOGGLE,
|
||||||
|
json.encodeToString(
|
||||||
|
SuggestionSnoozeTogglePayload.serializer(),
|
||||||
|
SuggestionSnoozeTogglePayload(mbid, name, desiredSnoozed),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
suspend fun enqueueRequestCancel(requestId: String): Long = insertUserDriven(
|
suspend fun enqueueRequestCancel(requestId: String): Long = insertUserDriven(
|
||||||
MutationKind.REQUEST_CANCEL,
|
MutationKind.REQUEST_CANCEL,
|
||||||
json.encodeToString(
|
json.encodeToString(
|
||||||
@@ -192,6 +217,21 @@ class MutationQueue @Inject constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Persisted payload for `MutationKind.SUGGESTION_SNOOZE_TOGGLE` (#2374).
|
||||||
|
* `desiredSnoozed` is the *target* state, matching [LikeTogglePayload], so
|
||||||
|
* the replayer can collapse repeated toggles for one candidate down to the
|
||||||
|
* last intent. Both directions are idempotent server-side: re-snoozing
|
||||||
|
* extends the window, and un-snoozing something already back is a 404 the
|
||||||
|
* replayer treats as permanent (nothing left to do).
|
||||||
|
*/
|
||||||
|
@Serializable
|
||||||
|
data class SuggestionSnoozeTogglePayload(
|
||||||
|
val mbid: String,
|
||||||
|
val name: String,
|
||||||
|
val desiredSnoozed: Boolean,
|
||||||
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Persisted payload for `MutationKind.QUARANTINE_UNFLAG` — the
|
* Persisted payload for `MutationKind.QUARANTINE_UNFLAG` — the
|
||||||
* `DELETE /api/quarantine/{trackId}` call lost during a connectivity
|
* `DELETE /api/quarantine/{trackId}` call lost during a connectivity
|
||||||
|
|||||||
+69
-24
@@ -16,6 +16,7 @@ import com.fabledsword.minstrel.connectivity.NetworkStatusController
|
|||||||
import com.fabledsword.minstrel.connectivity.ServerHealth
|
import com.fabledsword.minstrel.connectivity.ServerHealth
|
||||||
import com.fabledsword.minstrel.models.wire.PlayEndedRequest
|
import com.fabledsword.minstrel.models.wire.PlayEndedRequest
|
||||||
import com.fabledsword.minstrel.models.wire.PlayOfflineRequest
|
import com.fabledsword.minstrel.models.wire.PlayOfflineRequest
|
||||||
|
import com.fabledsword.minstrel.models.wire.SnoozeSuggestionBody
|
||||||
import com.fabledsword.minstrel.auth.AuthStore
|
import com.fabledsword.minstrel.auth.AuthStore
|
||||||
import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao
|
import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao
|
||||||
import com.fabledsword.minstrel.cache.db.entities.CachedMutationEntity
|
import com.fabledsword.minstrel.cache.db.entities.CachedMutationEntity
|
||||||
@@ -114,11 +115,12 @@ class MutationReplayer @Inject constructor(
|
|||||||
|
|
||||||
private suspend fun drain() {
|
private suspend fun drain() {
|
||||||
val rows = dao.getAll()
|
val rows = dao.getAll()
|
||||||
// Collapse superseded like-toggles: only the latest desired state per
|
// Collapse superseded toggles (likes, suggestion snoozes): only the
|
||||||
// (entity) is replayed; older toggles for the same entity are dropped
|
// latest desired state per entity is replayed; older toggles for the
|
||||||
// unsent. Without this, partial-failure + differential retry could
|
// same entity are dropped unsent. Without this, partial-failure +
|
||||||
// replay an older toggle last and invert the final like state.
|
// differential retry could replay an older toggle last and invert the
|
||||||
val superseded = supersededLikeToggleIds(rows)
|
// final state — a snooze the user already undid would come back.
|
||||||
|
val superseded = supersededToggleIds(rows, json)
|
||||||
for (row in rows) {
|
for (row in rows) {
|
||||||
if (row.id in superseded) {
|
if (row.id in superseded) {
|
||||||
dao.delete(row.id)
|
dao.delete(row.id)
|
||||||
@@ -131,25 +133,6 @@ class MutationReplayer @Inject constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Row ids of like-toggles superseded by a later toggle for the same entity. */
|
|
||||||
private fun supersededLikeToggleIds(rows: List<CachedMutationEntity>): Set<Long> {
|
|
||||||
val latestByEntity = HashMap<String, Long>()
|
|
||||||
val superseded = HashSet<Long>()
|
|
||||||
rows.asSequence()
|
|
||||||
.filter { it.kind == MutationKind.LIKE_TOGGLE }
|
|
||||||
.forEach { row ->
|
|
||||||
val decoded = runCatching {
|
|
||||||
json.decodeFromString(LikeTogglePayload.serializer(), row.payload)
|
|
||||||
}.getOrNull()
|
|
||||||
if (decoded != null) {
|
|
||||||
val key = "${decoded.entityType}:${decoded.entityId}"
|
|
||||||
// `rows` is ascending by id, so a prior entry is always older.
|
|
||||||
latestByEntity.put(key, row.id)?.let(superseded::add)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return superseded
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun outcomeFor(row: CachedMutationEntity): Outcome = try {
|
private suspend fun outcomeFor(row: CachedMutationEntity): Outcome = try {
|
||||||
dispatch(row)
|
dispatch(row)
|
||||||
} catch (e: HttpException) {
|
} catch (e: HttpException) {
|
||||||
@@ -182,6 +165,7 @@ class MutationReplayer @Inject constructor(
|
|||||||
MutationKind.PLAY_ENDED -> dispatchPlayEnded(row.payload)
|
MutationKind.PLAY_ENDED -> dispatchPlayEnded(row.payload)
|
||||||
MutationKind.REQUEST_CANCEL -> dispatchRequestCancel(row.payload)
|
MutationKind.REQUEST_CANCEL -> dispatchRequestCancel(row.payload)
|
||||||
MutationKind.PLAYBACK_ERROR_REPORT -> dispatchPlaybackErrorReport(row.payload)
|
MutationKind.PLAYBACK_ERROR_REPORT -> dispatchPlaybackErrorReport(row.payload)
|
||||||
|
MutationKind.SUGGESTION_SNOOZE_TOGGLE -> dispatchSuggestionSnoozeToggle(row.payload)
|
||||||
// Unknown kind — drop so a stale schema entry can't wedge the queue.
|
// Unknown kind — drop so a stale schema entry can't wedge the queue.
|
||||||
else -> Outcome.DROP
|
else -> Outcome.DROP
|
||||||
}
|
}
|
||||||
@@ -277,6 +261,24 @@ class MutationReplayer @Inject constructor(
|
|||||||
return Outcome.SENT
|
return Outcome.SENT
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Replays a suggestion snooze in whichever direction the payload asks for.
|
||||||
|
*
|
||||||
|
* The un-snooze branch can legitimately 404 (the row already lapsed, or a
|
||||||
|
* previous attempt landed and the response was lost). [outcomeFor] classes
|
||||||
|
* 404 as permanent → DROP, which is right: the user's intended end state
|
||||||
|
* already holds, so there is nothing left to send.
|
||||||
|
*/
|
||||||
|
private suspend fun dispatchSuggestionSnoozeToggle(payload: String): Outcome {
|
||||||
|
val decoded = json.decodeFromString(SuggestionSnoozeTogglePayload.serializer(), payload)
|
||||||
|
if (decoded.desiredSnoozed) {
|
||||||
|
discoverApi.snoozeSuggestion(decoded.mbid, SnoozeSuggestionBody(name = decoded.name))
|
||||||
|
} else {
|
||||||
|
discoverApi.unsnoozeSuggestion(decoded.mbid)
|
||||||
|
}
|
||||||
|
return Outcome.SENT
|
||||||
|
}
|
||||||
|
|
||||||
private suspend fun dispatchPlaybackErrorReport(payload: String): Outcome {
|
private suspend fun dispatchPlaybackErrorReport(payload: String): Outcome {
|
||||||
val decoded = json.decodeFromString(PlaybackErrorReportPayload.serializer(), payload)
|
val decoded = json.decodeFromString(PlaybackErrorReportPayload.serializer(), payload)
|
||||||
playbackErrorsApi.report(
|
playbackErrorsApi.report(
|
||||||
@@ -297,3 +299,46 @@ class MutationReplayer @Inject constructor(
|
|||||||
const val HTTP_TOO_MANY = 429
|
const val HTTP_TOO_MANY = 429
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Row ids of desired-state toggles superseded by a later toggle for the same
|
||||||
|
* entity. Applies to every kind whose payload encodes a TARGET state rather
|
||||||
|
* than an action — like-toggles and suggestion snoozes (#2374) — because
|
||||||
|
* replaying a stale one last would invert the final state.
|
||||||
|
*
|
||||||
|
* Top-level and pure so it can be unit-tested without standing up a Retrofit
|
||||||
|
* instance. [rows] must be ascending by id (FIFO), which is what
|
||||||
|
* `CachedMutationDao.getAll()` returns.
|
||||||
|
*/
|
||||||
|
internal fun supersededToggleIds(rows: List<CachedMutationEntity>, json: Json): Set<Long> {
|
||||||
|
val latestByEntity = HashMap<String, Long>()
|
||||||
|
val superseded = HashSet<Long>()
|
||||||
|
rows.asSequence()
|
||||||
|
.mapNotNull { row -> toggleKeyOf(row, json)?.let { key -> key to row.id } }
|
||||||
|
.forEach { (key, id) ->
|
||||||
|
// Ascending ids mean a prior entry for this key is always older.
|
||||||
|
latestByEntity.put(key, id)?.let(superseded::add)
|
||||||
|
}
|
||||||
|
return superseded
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Collapse key for a toggle row, or null when the row isn't a toggle — or its
|
||||||
|
* payload won't decode. Undecodable rows are deliberately left alone rather
|
||||||
|
* than grouped under a shared "corrupt" key, so one bad row can't suppress a
|
||||||
|
* good one behind it; the dispatcher DROPs it on its own.
|
||||||
|
*
|
||||||
|
* The kind is part of the key so two toggle kinds can never collide on the
|
||||||
|
* same entity id.
|
||||||
|
*/
|
||||||
|
private fun toggleKeyOf(row: CachedMutationEntity, json: Json): String? = when (row.kind) {
|
||||||
|
MutationKind.LIKE_TOGGLE -> runCatching {
|
||||||
|
json.decodeFromString(LikeTogglePayload.serializer(), row.payload)
|
||||||
|
}.getOrNull()?.let { "${row.kind}:${it.entityType}:${it.entityId}" }
|
||||||
|
|
||||||
|
MutationKind.SUGGESTION_SNOOZE_TOGGLE -> runCatching {
|
||||||
|
json.decodeFromString(SuggestionSnoozeTogglePayload.serializer(), row.payload)
|
||||||
|
}.getOrNull()?.let { "${row.kind}:${it.mbid}" }
|
||||||
|
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
|||||||
+1
@@ -219,4 +219,5 @@ private fun SyncTrackWire.toEntity(): CachedTrackEntity = CachedTrackEntity(
|
|||||||
filePath = filePath,
|
filePath = filePath,
|
||||||
fileFormat = fileFormat,
|
fileFormat = fileFormat,
|
||||||
genre = genre,
|
genre = genre,
|
||||||
|
missing = missing,
|
||||||
)
|
)
|
||||||
|
|||||||
+25
-1
@@ -1,6 +1,9 @@
|
|||||||
package com.fabledsword.minstrel.connectivity
|
package com.fabledsword.minstrel.connectivity
|
||||||
|
|
||||||
import androidx.compose.runtime.staticCompositionLocalOf
|
import androidx.compose.runtime.staticCompositionLocalOf
|
||||||
|
import androidx.lifecycle.DefaultLifecycleObserver
|
||||||
|
import androidx.lifecycle.LifecycleOwner
|
||||||
|
import androidx.lifecycle.ProcessLifecycleOwner
|
||||||
import com.fabledsword.minstrel.BuildConfig
|
import com.fabledsword.minstrel.BuildConfig
|
||||||
import com.fabledsword.minstrel.auth.AuthStore
|
import com.fabledsword.minstrel.auth.AuthStore
|
||||||
import com.fabledsword.minstrel.di.ApplicationScope
|
import com.fabledsword.minstrel.di.ApplicationScope
|
||||||
@@ -41,6 +44,12 @@ private const val ARBITRATE_MIN_GAP_MS = 2_000L
|
|||||||
* - reportSuccess / reportFailure from the API interceptor, the audio data
|
* - reportSuccess / reportFailure from the API interceptor, the audio data
|
||||||
* source, and the playback-error reporter.
|
* source, and the playback-error reporter.
|
||||||
* - recheck() from pull-to-refresh and the banner.
|
* - recheck() from pull-to-refresh and the banner.
|
||||||
|
* - a forced probe when the app returns to the foreground (#1209). Without
|
||||||
|
* it a stale ServerDown outlived the condition that caused it: the poll
|
||||||
|
* loop's delay() is throttled while screen-off/doze, so recovery waited on
|
||||||
|
* whenever the OS next let the loop run. Meanwhile ServerDown makes
|
||||||
|
* OfflineGatedDataSource refuse every uncached track, so the app declined
|
||||||
|
* to play music that would have played fine.
|
||||||
*
|
*
|
||||||
* Version compatibility is a byproduct of the same /healthz response.
|
* Version compatibility is a byproduct of the same /healthz response.
|
||||||
*
|
*
|
||||||
@@ -53,7 +62,7 @@ class NetworkStatusController @Inject constructor(
|
|||||||
connectivity: ConnectivityObserver,
|
connectivity: ConnectivityObserver,
|
||||||
private val authStore: AuthStore,
|
private val authStore: AuthStore,
|
||||||
retrofit: Retrofit,
|
retrofit: Retrofit,
|
||||||
) {
|
) : DefaultLifecycleObserver {
|
||||||
private val api: HealthzApi = retrofit.create(HealthzApi::class.java)
|
private val api: HealthzApi = retrofit.create(HealthzApi::class.java)
|
||||||
private val machine = ReachabilityMachine()
|
private val machine = ReachabilityMachine()
|
||||||
private val lastProbeAtMs = AtomicLong(0)
|
private val lastProbeAtMs = AtomicLong(0)
|
||||||
@@ -74,6 +83,7 @@ class NetworkStatusController @Inject constructor(
|
|||||||
private val intents = Channel<Intent>(Channel.UNLIMITED)
|
private val intents = Channel<Intent>(Channel.UNLIMITED)
|
||||||
|
|
||||||
init {
|
init {
|
||||||
|
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
|
||||||
scope.launch { reduceLoop() }
|
scope.launch { reduceLoop() }
|
||||||
scope.launch {
|
scope.launch {
|
||||||
connectivity.online.collect { up ->
|
connectivity.online.collect { up ->
|
||||||
@@ -100,6 +110,20 @@ class NetworkStatusController @Inject constructor(
|
|||||||
scope.launch { probeOnce(force = true) }
|
scope.launch { probeOnce(force = true) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* App returned to the foreground — probe now rather than waiting for the
|
||||||
|
* poll loop (#1209).
|
||||||
|
*
|
||||||
|
* The link-return probe in `init` does NOT cover this: it fires on a
|
||||||
|
* connectivity *change*, and an app backgrounded on stable Wi-Fi sees none.
|
||||||
|
* force = true so this also bypasses the ARBITRATE_MIN_GAP_MS throttle —
|
||||||
|
* a user bringing the app up is exactly when a stale banner and a refused
|
||||||
|
* track are most visible, and it's a once-per-foreground cost.
|
||||||
|
*/
|
||||||
|
override fun onStart(owner: LifecycleOwner) {
|
||||||
|
recheck()
|
||||||
|
}
|
||||||
|
|
||||||
private suspend fun reduceLoop() {
|
private suspend fun reduceLoop() {
|
||||||
for (intent in intents) {
|
for (intent in intents) {
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
|
|||||||
+27
-1
@@ -4,6 +4,24 @@ internal const val ESCALATE_AFTER_MS = 120_000L
|
|||||||
internal const val CORROBORATION_WINDOW_MS = 30_000L
|
internal const val CORROBORATION_WINDOW_MS = 30_000L
|
||||||
internal const val CORROBORATION_OP_THRESHOLD = 2
|
internal const val CORROBORATION_OP_THRESHOLD = 2
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Minimum gap between op failures for them to count as SEPARATE evidence
|
||||||
|
* (#1209).
|
||||||
|
*
|
||||||
|
* A link handoff fails every in-flight request at once, so a burst is one
|
||||||
|
* event producing N failures — not N independent observations that the server
|
||||||
|
* is gone. Without this, two simultaneous failures corroborated each other
|
||||||
|
* straight to Unreachable, and ServerDown makes OfflineGatedDataSource refuse
|
||||||
|
* every uncached track. The app declined to play music that would have played
|
||||||
|
* fine, for a blip that had already resolved.
|
||||||
|
*
|
||||||
|
* 3s is comfortably above the sub-second window an OS handoff occupies while
|
||||||
|
* still letting a genuine outage corroborate within seconds once a client
|
||||||
|
* retries. The sustained-time backstop covers the case where nothing retries
|
||||||
|
* at all — and if nothing is asking, a late ServerDown costs nothing.
|
||||||
|
*/
|
||||||
|
internal const val CORROBORATION_MIN_SPACING_MS = 3_000L
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Pure reachability state machine. No Android, no coroutines, no real clock —
|
* Pure reachability state machine. No Android, no coroutines, no real clock —
|
||||||
* every entry point takes `nowMs`, so it is fully deterministic and unit-
|
* every entry point takes `nowMs`, so it is fully deterministic and unit-
|
||||||
@@ -46,9 +64,17 @@ class ReachabilityMachine {
|
|||||||
recentOpFailures.clear()
|
recentOpFailures.clear()
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A real network op failed. Ambiguous on its own — records corroboration. */
|
/**
|
||||||
|
* A real network op failed. Ambiguous on its own — records corroboration.
|
||||||
|
*
|
||||||
|
* Failures arriving within [CORROBORATION_MIN_SPACING_MS] of the last
|
||||||
|
* recorded one are dropped rather than stacked: see that constant for why
|
||||||
|
* a burst must not corroborate itself.
|
||||||
|
*/
|
||||||
fun onOpFailure(nowMs: Long) {
|
fun onOpFailure(nowMs: Long) {
|
||||||
pruneOpFailures(nowMs)
|
pruneOpFailures(nowMs)
|
||||||
|
val last = recentOpFailures.lastOrNull()
|
||||||
|
if (last != null && nowMs - last < CORROBORATION_MIN_SPACING_MS) return
|
||||||
recentOpFailures.addLast(nowMs)
|
recentOpFailures.addLast(nowMs)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ import com.fabledsword.minstrel.connectivity.NetworkStatusController
|
|||||||
import com.fabledsword.minstrel.di.ApplicationScope
|
import com.fabledsword.minstrel.di.ApplicationScope
|
||||||
import com.fabledsword.minstrel.player.PlayerController
|
import com.fabledsword.minstrel.player.PlayerController
|
||||||
import com.fabledsword.minstrel.player.RemotePlayerState
|
import com.fabledsword.minstrel.player.RemotePlayerState
|
||||||
|
import com.fabledsword.minstrel.player.TransportObservation
|
||||||
import com.fabledsword.minstrel.player.output.OutputPickerController
|
import com.fabledsword.minstrel.player.output.OutputPickerController
|
||||||
import com.fabledsword.minstrel.player.output.OutputRoute
|
import com.fabledsword.minstrel.player.output.OutputRoute
|
||||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
@@ -103,6 +104,7 @@ class DiagnosticsReporter @Inject constructor(
|
|||||||
launch { collectUpnpDrops() }
|
launch { collectUpnpDrops() }
|
||||||
launch { collectPlayerState() }
|
launch { collectPlayerState() }
|
||||||
launch { collectTrackChanges() }
|
launch { collectTrackChanges() }
|
||||||
|
launch { collectTransportFlap() }
|
||||||
launch { collectRoutes() }
|
launch { collectRoutes() }
|
||||||
launch { heartbeatLoop() }
|
launch { heartbeatLoop() }
|
||||||
}
|
}
|
||||||
@@ -191,6 +193,67 @@ class DiagnosticsReporter @Inject constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Catch the renderer rapidly leaving and re-entering PLAYING.
|
||||||
|
*
|
||||||
|
* The operator reports the Sonos "play pause play pause, like someone
|
||||||
|
* pressing it every half second", usually as a track starts, cleared by a
|
||||||
|
* manual pause or skip. Nothing here could see that: `player_state`
|
||||||
|
* carries source/loading/error but not playing, `track_change` needs the
|
||||||
|
* index to move, and the heartbeat samples once per 45s. The symptom fell
|
||||||
|
* through every existing collector, which is why it has only ever been
|
||||||
|
* described and never measured.
|
||||||
|
*
|
||||||
|
* Records every raw transport change (cheap — steady playback produces
|
||||||
|
* a couple per track) and, when they come in a burst, one summary event
|
||||||
|
* carrying the whole sequence. The summary is the useful artefact: it
|
||||||
|
* pairs the renderer's states with local-vs-Sonos track and position, so
|
||||||
|
* an episode says whether the app and the renderer disagreed about which
|
||||||
|
* track was playing, or agreed while the renderer rebuffered.
|
||||||
|
*
|
||||||
|
* See [TransportObservation] on the 1 Hz sampling limit.
|
||||||
|
*/
|
||||||
|
private suspend fun collectTransportFlap() {
|
||||||
|
val detector = TransportFlapDetector()
|
||||||
|
playerController.transportEvents.collect { obs ->
|
||||||
|
record("upnp_sync", buildJsonObject {
|
||||||
|
put("event", "transport")
|
||||||
|
put("state", obs.state)
|
||||||
|
put("status_ok", obs.statusOk)
|
||||||
|
put("sonos_track", obs.trackNumber)
|
||||||
|
put("sonos_pos_ms", obs.positionMs)
|
||||||
|
put("play_intent", obs.playIntent)
|
||||||
|
})
|
||||||
|
detector.onChange(obs)?.let { recordFlapSummary(it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun recordFlapSummary(recent: List<TransportObservation>) {
|
||||||
|
val ui = playerController.uiState.value
|
||||||
|
val casting = outputPicker.routesState.value.current.protocol !=
|
||||||
|
OutputRoute.Protocol.SYSTEM
|
||||||
|
val spanMs = recent.last().atElapsedMs - recent.first().atElapsedMs
|
||||||
|
record("upnp_sync", buildJsonObject {
|
||||||
|
put("event", "transport_flap")
|
||||||
|
put("changes", recent.size)
|
||||||
|
put("window_ms", spanMs)
|
||||||
|
// The sequence itself, e.g. "PLAYING>TRANSITIONING>STOPPED>PLAYING".
|
||||||
|
// Whether STOPPED appears at all is the first question to ask of a
|
||||||
|
// captured episode.
|
||||||
|
put("sequence", recent.joinToString(">") { it.state })
|
||||||
|
put("sonos_positions_ms", recent.joinToString(",") { it.positionMs.toString() })
|
||||||
|
put("sonos_tracks", recent.joinToString(",") { it.trackNumber.toString() })
|
||||||
|
put("local_index", ui.queueIndex)
|
||||||
|
put("local_track_id", ui.currentTrack?.id ?: "")
|
||||||
|
put("local_pos_ms", ui.positionMs)
|
||||||
|
putSonos(this, casting)
|
||||||
|
put("upnp_loading", ui.isUpnpLoading)
|
||||||
|
put("server_health", networkStatus.state.value.name)
|
||||||
|
put("route", outputPicker.routesState.value.current.name)
|
||||||
|
addPowerFields(this)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
private suspend fun collectRoutes() {
|
private suspend fun collectRoutes() {
|
||||||
// 'playback' — route changes happen for all outputs. This only ever
|
// 'playback' — route changes happen for all outputs. This only ever
|
||||||
// logs the ACTIVE route (routesState.current), so no "connected" flag.
|
// logs the ACTIVE route (routesState.current), so no "connected" flag.
|
||||||
|
|||||||
+75
@@ -0,0 +1,75 @@
|
|||||||
|
package com.fabledsword.minstrel.diagnostics
|
||||||
|
|
||||||
|
import com.fabledsword.minstrel.player.TransportObservation
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decides when a run of renderer transport changes is a *flap* — the renderer
|
||||||
|
* repeatedly failing to settle — rather than an ordinary track transition.
|
||||||
|
*
|
||||||
|
* The operator reports the Sonos "play pause play pause, like someone pressing
|
||||||
|
* it every half second", usually as a track starts. No diagnostic event could
|
||||||
|
* see it, so it has been described several times and measured never. This is
|
||||||
|
* the rule that decides when an episode is worth writing down.
|
||||||
|
*
|
||||||
|
* Pure decision state, like [com.fabledsword.minstrel.player.RemoteStallWatchdog]:
|
||||||
|
* the caller owns the flow and the recording, this only answers "is this an
|
||||||
|
* episode, and which readings make it up". Keeps the windowing and the
|
||||||
|
* one-episode-one-summary rule testable without a renderer or a clock.
|
||||||
|
*/
|
||||||
|
class TransportFlapDetector(
|
||||||
|
private val windowMs: Long = FLAP_WINDOW_MS,
|
||||||
|
private val minChanges: Int = FLAP_MIN_CHANGES,
|
||||||
|
private val summaryCooldownMs: Long = FLAP_SUMMARY_COOLDOWN_MS,
|
||||||
|
) {
|
||||||
|
private val recent = ArrayDeque<TransportObservation>()
|
||||||
|
private var lastSummaryAtMs: Long? = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Feed one transport change. Returns the readings making up an episode
|
||||||
|
* worth recording, or null when there is nothing to say.
|
||||||
|
*
|
||||||
|
* The returned list is a copy: the caller may hold it while more readings
|
||||||
|
* arrive.
|
||||||
|
*/
|
||||||
|
fun onChange(observation: TransportObservation): List<TransportObservation>? {
|
||||||
|
recent.addLast(observation)
|
||||||
|
dropReadingsOlderThan(observation.atElapsedMs)
|
||||||
|
if (!isEpisode(observation.atElapsedMs)) return null
|
||||||
|
lastSummaryAtMs = observation.atElapsedMs
|
||||||
|
return recent.toList()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun dropReadingsOlderThan(nowMs: Long) {
|
||||||
|
while (recent.isNotEmpty() && nowMs - recent.first().atElapsedMs > windowMs) {
|
||||||
|
recent.removeFirst()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enough changes packed together, and far enough from the last thing we
|
||||||
|
* wrote down. The cooldown is what keeps one episode to one summary: a
|
||||||
|
* sustained fault produces a change every poll, and a summary per reading
|
||||||
|
* would bury the per-change events underneath them.
|
||||||
|
*/
|
||||||
|
private fun isEpisode(nowMs: Long): Boolean {
|
||||||
|
val since = lastSummaryAtMs
|
||||||
|
val cooled = since == null || nowMs - since >= summaryCooldownMs
|
||||||
|
return recent.size >= minChanges && cooled
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Forget everything — call when the route changes or casting ends. */
|
||||||
|
fun reset() {
|
||||||
|
recent.clear()
|
||||||
|
lastSummaryAtMs = null
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
// Readings arrive at the 1 Hz poll cadence, and a normal track
|
||||||
|
// transition is 2-3 changes (PLAYING -> TRANSITIONING -> PLAYING).
|
||||||
|
// Four inside six seconds is not a track change, and it is not a
|
||||||
|
// person at the Sonos app either; it is the renderer not settling.
|
||||||
|
const val FLAP_WINDOW_MS = 6_000L
|
||||||
|
const val FLAP_MIN_CHANGES = 4
|
||||||
|
const val FLAP_SUMMARY_COOLDOWN_MS = 60_000L
|
||||||
|
}
|
||||||
|
}
|
||||||
+81
@@ -7,10 +7,14 @@ import com.fabledsword.minstrel.models.ArtistSuggestionRef
|
|||||||
import com.fabledsword.minstrel.models.LidarrRequestKind
|
import com.fabledsword.minstrel.models.LidarrRequestKind
|
||||||
import com.fabledsword.minstrel.models.LidarrSearchResultRef
|
import com.fabledsword.minstrel.models.LidarrSearchResultRef
|
||||||
import com.fabledsword.minstrel.models.SeedContributionRef
|
import com.fabledsword.minstrel.models.SeedContributionRef
|
||||||
|
import com.fabledsword.minstrel.models.SuggestionSnoozeRef
|
||||||
import com.fabledsword.minstrel.models.wire.ArtistSuggestionWire
|
import com.fabledsword.minstrel.models.wire.ArtistSuggestionWire
|
||||||
import com.fabledsword.minstrel.models.wire.CreateRequestBody
|
import com.fabledsword.minstrel.models.wire.CreateRequestBody
|
||||||
import com.fabledsword.minstrel.models.wire.LidarrSearchResultWire
|
import com.fabledsword.minstrel.models.wire.LidarrSearchResultWire
|
||||||
import com.fabledsword.minstrel.models.wire.SeedContributionWire
|
import com.fabledsword.minstrel.models.wire.SeedContributionWire
|
||||||
|
import com.fabledsword.minstrel.models.wire.SnoozeSuggestionBody
|
||||||
|
import com.fabledsword.minstrel.models.wire.SuggestionSnoozeWire
|
||||||
|
import retrofit2.HttpException
|
||||||
import retrofit2.Retrofit
|
import retrofit2.Retrofit
|
||||||
import retrofit2.create
|
import retrofit2.create
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
@@ -46,6 +50,69 @@ class DiscoverRepository @Inject constructor(
|
|||||||
suspend fun listSuggestions(): List<ArtistSuggestionRef> =
|
suspend fun listSuggestions(): List<ArtistSuggestionRef> =
|
||||||
api.listSuggestions().map { it.toDomain() }
|
api.listSuggestions().map { it.toDomain() }
|
||||||
|
|
||||||
|
suspend fun listSnoozes(): List<SuggestionSnoozeRef> =
|
||||||
|
api.listSnoozes().map { it.toDomain() }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parks a suggestion ("not right now"). Offline-first per rule #100: on
|
||||||
|
* transport failure the target state is queued for the replayer rather
|
||||||
|
* than dropped.
|
||||||
|
*
|
||||||
|
* Always reports success to the caller. Unlike a request, a snooze has no
|
||||||
|
* meaningful failed state to show — the user asked for a card to go away,
|
||||||
|
* and it will, either now or when the queue drains.
|
||||||
|
*/
|
||||||
|
suspend fun snoozeSuggestion(mbid: String, name: String): Unit = toggleSnooze(
|
||||||
|
mbid = mbid,
|
||||||
|
name = name,
|
||||||
|
desiredSnoozed = true,
|
||||||
|
) { api.snoozeSuggestion(mbid, SnoozeSuggestionBody(name = name)) }
|
||||||
|
|
||||||
|
/** Brings a parked suggestion back. Same offline-first contract. */
|
||||||
|
suspend fun unsnoozeSuggestion(mbid: String, name: String): Unit = toggleSnooze(
|
||||||
|
mbid = mbid,
|
||||||
|
name = name,
|
||||||
|
desiredSnoozed = false,
|
||||||
|
) { api.unsnoozeSuggestion(mbid) }
|
||||||
|
|
||||||
|
private suspend fun toggleSnooze(
|
||||||
|
mbid: String,
|
||||||
|
name: String,
|
||||||
|
desiredSnoozed: Boolean,
|
||||||
|
call: suspend () -> Unit,
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
call()
|
||||||
|
} catch (e: HttpException) {
|
||||||
|
// A 4xx is the server's considered answer, not a lost call, so
|
||||||
|
// queueing it would be wrong twice over: the replay is guaranteed
|
||||||
|
// to fail again, and the enqueue would raise a "will sync when
|
||||||
|
// online" snackbar for something already settled. The common case
|
||||||
|
// is a 404 from un-snoozing a row that already lapsed — which is
|
||||||
|
// the end state the user wanted anyway.
|
||||||
|
if (!isPermanent(e.code())) {
|
||||||
|
mutationQueue.enqueueSuggestionSnoozeToggle(mbid, name, desiredSnoozed)
|
||||||
|
}
|
||||||
|
} catch (
|
||||||
|
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
|
||||||
|
) {
|
||||||
|
// Transport failure — intentional swallow, same offline-first
|
||||||
|
// rationale as createRequest above. The queue carries the desired
|
||||||
|
// STATE, so a later undo supersedes this rather than fighting it
|
||||||
|
// on replay.
|
||||||
|
mutationQueue.enqueueSuggestionSnoozeToggle(mbid, name, desiredSnoozed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mirrors MutationReplayer's classification so the enqueue decision here
|
||||||
|
* and the drop decision there can't disagree: 4xx is permanent except the
|
||||||
|
* two "retry me" statuses.
|
||||||
|
*/
|
||||||
|
private fun isPermanent(code: Int): Boolean =
|
||||||
|
code in HTTP_CLIENT_ERR_MIN..HTTP_CLIENT_ERR_MAX &&
|
||||||
|
code != HTTP_TIMEOUT && code != HTTP_TOO_MANY
|
||||||
|
|
||||||
suspend fun search(query: String, kind: LidarrRequestKind): List<LidarrSearchResultRef> =
|
suspend fun search(query: String, kind: LidarrRequestKind): List<LidarrSearchResultRef> =
|
||||||
api.search(query = query, kind = kind.wire).map { it.toDomain() }
|
api.search(query = query, kind = kind.wire).map { it.toDomain() }
|
||||||
|
|
||||||
@@ -85,6 +152,13 @@ class DiscoverRepository @Inject constructor(
|
|||||||
RequestOutcome.QUEUED
|
RequestOutcome.QUEUED
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val HTTP_CLIENT_ERR_MIN = 400
|
||||||
|
const val HTTP_CLIENT_ERR_MAX = 499
|
||||||
|
const val HTTP_TIMEOUT = 408
|
||||||
|
const val HTTP_TOO_MANY = 429
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Mappers (internal — wire types stay out of UI) ──
|
// ── Mappers (internal — wire types stay out of UI) ──
|
||||||
@@ -105,6 +179,7 @@ private fun ArtistSuggestionWire.toDomain(): ArtistSuggestionRef = ArtistSuggest
|
|||||||
name = name,
|
name = name,
|
||||||
imageUrl = imageUrl,
|
imageUrl = imageUrl,
|
||||||
attribution = attribution.map { it.toDomain() },
|
attribution = attribution.map { it.toDomain() },
|
||||||
|
matchedTags = matchedTags,
|
||||||
)
|
)
|
||||||
|
|
||||||
private fun SeedContributionWire.toDomain(): SeedContributionRef = SeedContributionRef(
|
private fun SeedContributionWire.toDomain(): SeedContributionRef = SeedContributionRef(
|
||||||
@@ -112,6 +187,12 @@ private fun SeedContributionWire.toDomain(): SeedContributionRef = SeedContribut
|
|||||||
isLiked = isLiked,
|
isLiked = isLiked,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
private fun SuggestionSnoozeWire.toDomain(): SuggestionSnoozeRef = SuggestionSnoozeRef(
|
||||||
|
mbid = mbid,
|
||||||
|
name = name,
|
||||||
|
snoozedUntil = snoozedUntil,
|
||||||
|
)
|
||||||
|
|
||||||
private fun RequestCreatePayload.toBody(): CreateRequestBody = CreateRequestBody(
|
private fun RequestCreatePayload.toBody(): CreateRequestBody = CreateRequestBody(
|
||||||
kind = kind,
|
kind = kind,
|
||||||
artistMbid = artistMbid,
|
artistMbid = artistMbid,
|
||||||
|
|||||||
@@ -40,7 +40,9 @@ import com.fabledsword.minstrel.discover.data.RequestOutcome
|
|||||||
import com.fabledsword.minstrel.models.ArtistSuggestionRef
|
import com.fabledsword.minstrel.models.ArtistSuggestionRef
|
||||||
import com.fabledsword.minstrel.models.LidarrRequestKind
|
import com.fabledsword.minstrel.models.LidarrRequestKind
|
||||||
import com.fabledsword.minstrel.models.LidarrSearchResultRef
|
import com.fabledsword.minstrel.models.LidarrSearchResultRef
|
||||||
|
import com.fabledsword.minstrel.models.SuggestionSnoozeRef
|
||||||
import com.fabledsword.minstrel.nav.Discover
|
import com.fabledsword.minstrel.nav.Discover
|
||||||
|
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
|
||||||
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
|
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
|
||||||
import com.fabledsword.minstrel.shared.widgets.LoadingCentered
|
import com.fabledsword.minstrel.shared.widgets.LoadingCentered
|
||||||
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
|
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
|
||||||
@@ -60,6 +62,7 @@ fun DiscoverScreen(
|
|||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
|
|
||||||
Scaffold(
|
Scaffold(
|
||||||
|
contentWindowInsets = ShellContentWindowInsets,
|
||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.fillMaxSize(),
|
||||||
topBar = {
|
topBar = {
|
||||||
MinstrelTopAppBar(
|
MinstrelTopAppBar(
|
||||||
@@ -104,6 +107,18 @@ private fun DiscoverBody(
|
|||||||
ResultsState.Idle -> SuggestionsPane(
|
ResultsState.Idle -> SuggestionsPane(
|
||||||
state = state.suggestions,
|
state = state.suggestions,
|
||||||
locallyRequestedMbids = state.locallyRequestedMbids,
|
locallyRequestedMbids = state.locallyRequestedMbids,
|
||||||
|
snoozeUi = SnoozeUi(
|
||||||
|
locallySnoozedMbids = state.locallySnoozedMbids,
|
||||||
|
snoozes = state.snoozes,
|
||||||
|
// No snackbar on snooze: the row itself flips to "Not
|
||||||
|
// right now" with an Undo, so a snackbar would only
|
||||||
|
// repeat what the user can already see — and cover the
|
||||||
|
// next row while doing it.
|
||||||
|
onSnooze = { s -> scope.launch { viewModel.snoozeSuggestion(s) } },
|
||||||
|
onUnsnooze = { mbid, name ->
|
||||||
|
scope.launch { viewModel.unsnoozeSuggestion(mbid, name) }
|
||||||
|
},
|
||||||
|
),
|
||||||
onRequest = { s ->
|
onRequest = { s ->
|
||||||
scope.launch {
|
scope.launch {
|
||||||
val outcome = viewModel.requestSuggestion(s)
|
val outcome = viewModel.requestSuggestion(s)
|
||||||
@@ -178,10 +193,23 @@ private fun KindChips(kind: LidarrRequestKind, onChange: (LidarrRequestKind) ->
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The snooze surface's data and callbacks, bundled rather than threaded
|
||||||
|
* through as four more parameters — the pane grew from one action to three
|
||||||
|
* with slice 4 and the signatures stopped being readable.
|
||||||
|
*/
|
||||||
|
private data class SnoozeUi(
|
||||||
|
val locallySnoozedMbids: Set<String>,
|
||||||
|
val snoozes: List<SuggestionSnoozeRef>,
|
||||||
|
val onSnooze: (ArtistSuggestionRef) -> Unit,
|
||||||
|
val onUnsnooze: (String, String) -> Unit,
|
||||||
|
)
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun SuggestionsPane(
|
private fun SuggestionsPane(
|
||||||
state: SuggestionState,
|
state: SuggestionState,
|
||||||
locallyRequestedMbids: Set<String>,
|
locallyRequestedMbids: Set<String>,
|
||||||
|
snoozeUi: SnoozeUi,
|
||||||
onRequest: (ArtistSuggestionRef) -> Unit,
|
onRequest: (ArtistSuggestionRef) -> Unit,
|
||||||
onRetry: () -> Unit,
|
onRetry: () -> Unit,
|
||||||
) {
|
) {
|
||||||
@@ -194,6 +222,7 @@ private fun SuggestionsPane(
|
|||||||
)
|
)
|
||||||
is SuggestionState.Loaded -> SuggestionsList(
|
is SuggestionState.Loaded -> SuggestionsList(
|
||||||
items = state.items.filter { it.mbid !in locallyRequestedMbids },
|
items = state.items.filter { it.mbid !in locallyRequestedMbids },
|
||||||
|
snoozeUi = snoozeUi,
|
||||||
onRequest = onRequest,
|
onRequest = onRequest,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -202,6 +231,7 @@ private fun SuggestionsPane(
|
|||||||
@Composable
|
@Composable
|
||||||
private fun SuggestionsList(
|
private fun SuggestionsList(
|
||||||
items: List<ArtistSuggestionRef>,
|
items: List<ArtistSuggestionRef>,
|
||||||
|
snoozeUi: SnoozeUi,
|
||||||
onRequest: (ArtistSuggestionRef) -> Unit,
|
onRequest: (ArtistSuggestionRef) -> Unit,
|
||||||
) {
|
) {
|
||||||
LazyColumn(
|
LazyColumn(
|
||||||
@@ -210,13 +240,61 @@ private fun SuggestionsList(
|
|||||||
) {
|
) {
|
||||||
item { SuggestionsHeader() }
|
item { SuggestionsHeader() }
|
||||||
if (items.isEmpty()) {
|
if (items.isEmpty()) {
|
||||||
item { CenteredMessage("Listen to or like an artist to fill this in.") }
|
// An empty deck used to mean one thing — no listening signal yet.
|
||||||
|
// With snoozing it can also mean "you parked them all", and telling
|
||||||
|
// that user to go listen to something would be wrong advice.
|
||||||
|
item {
|
||||||
|
CenteredMessage(
|
||||||
|
if (snoozeUi.snoozes.isEmpty()) {
|
||||||
|
"Listen to or like an artist to fill this in."
|
||||||
|
} else {
|
||||||
|
"Nothing new right now — the artists you've parked are below."
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
items(items = items, key = { it.mbid }) { s ->
|
items(items = items, key = { it.mbid }) { s ->
|
||||||
SuggestionTile(s = s, onRequest = { onRequest(s) })
|
SuggestionTile(
|
||||||
|
s = s,
|
||||||
|
snoozed = s.mbid in snoozeUi.locallySnoozedMbids,
|
||||||
|
onRequest = { onRequest(s) },
|
||||||
|
onSnooze = { snoozeUi.onSnooze(s) },
|
||||||
|
onUnsnooze = { snoozeUi.onUnsnooze(s.mbid, s.name) },
|
||||||
|
)
|
||||||
HorizontalDivider()
|
HorizontalDivider()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Parked candidates live at the bottom of the same scroll, not behind a
|
||||||
|
// separate screen: it's a short list the user rarely needs, but it must
|
||||||
|
// be reachable — a snoozed candidate is gone from the deck above, so
|
||||||
|
// this is the only way back to it.
|
||||||
|
if (snoozeUi.snoozes.isNotEmpty()) {
|
||||||
|
item { SnoozedHeader() }
|
||||||
|
items(items = snoozeUi.snoozes, key = { "snoozed-${it.mbid}" }) { row ->
|
||||||
|
SnoozedTile(
|
||||||
|
row = row,
|
||||||
|
onUnsnooze = { snoozeUi.onUnsnooze(row.mbid, row.name) },
|
||||||
|
)
|
||||||
|
HorizontalDivider()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun SnoozedHeader() {
|
||||||
|
Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp)) {
|
||||||
|
HorizontalDivider(modifier = Modifier.padding(bottom = 12.dp))
|
||||||
|
Text(
|
||||||
|
text = "Not right now",
|
||||||
|
style = MaterialTheme.typography.titleMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onBackground,
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = "These come back on their own. Nothing here counts against your taste profile.",
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -14,8 +14,10 @@ import androidx.compose.foundation.shape.RoundedCornerShape
|
|||||||
import androidx.compose.material3.AssistChip
|
import androidx.compose.material3.AssistChip
|
||||||
import androidx.compose.material3.Button
|
import androidx.compose.material3.Button
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
@@ -24,14 +26,22 @@ import androidx.compose.ui.graphics.vector.ImageVector
|
|||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import coil3.compose.AsyncImage
|
import coil3.compose.AsyncImage
|
||||||
|
import com.composables.icons.lucide.Clock
|
||||||
import com.composables.icons.lucide.Disc3
|
import com.composables.icons.lucide.Disc3
|
||||||
import com.composables.icons.lucide.Lucide
|
import com.composables.icons.lucide.Lucide
|
||||||
import com.composables.icons.lucide.User
|
import com.composables.icons.lucide.User
|
||||||
import com.fabledsword.minstrel.models.ArtistSuggestionRef
|
import com.fabledsword.minstrel.models.ArtistSuggestionRef
|
||||||
import com.fabledsword.minstrel.models.LidarrSearchResultRef
|
import com.fabledsword.minstrel.models.LidarrSearchResultRef
|
||||||
|
import com.fabledsword.minstrel.models.SuggestionSnoozeRef
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
internal fun SuggestionTile(s: ArtistSuggestionRef, onRequest: () -> Unit) {
|
internal fun SuggestionTile(
|
||||||
|
s: ArtistSuggestionRef,
|
||||||
|
snoozed: Boolean,
|
||||||
|
onRequest: () -> Unit,
|
||||||
|
onSnooze: () -> Unit,
|
||||||
|
onUnsnooze: () -> Unit,
|
||||||
|
) {
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
@@ -48,9 +58,13 @@ internal fun SuggestionTile(s: ArtistSuggestionRef, onRequest: () -> Unit) {
|
|||||||
maxLines = 1,
|
maxLines = 1,
|
||||||
overflow = TextOverflow.Ellipsis,
|
overflow = TextOverflow.Ellipsis,
|
||||||
)
|
)
|
||||||
if (s.attributionText.isNotEmpty()) {
|
// Once parked, the "because you liked X" line is no longer the
|
||||||
|
// useful thing to say — confirming what just happened is.
|
||||||
|
val secondary =
|
||||||
|
if (snoozed) "Not right now — hidden for a while" else s.reasonText
|
||||||
|
if (secondary.isNotEmpty()) {
|
||||||
Text(
|
Text(
|
||||||
text = s.attributionText,
|
text = secondary,
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
maxLines = 2,
|
maxLines = 2,
|
||||||
@@ -58,7 +72,52 @@ internal fun SuggestionTile(s: ArtistSuggestionRef, onRequest: () -> Unit) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (snoozed) {
|
||||||
|
TextButton(onClick = onUnsnooze) { Text("Undo") }
|
||||||
|
} else {
|
||||||
Button(onClick = onRequest) { Text("Request") }
|
Button(onClick = onRequest) { Text("Request") }
|
||||||
|
IconButton(onClick = onSnooze) {
|
||||||
|
Icon(
|
||||||
|
imageVector = Lucide.Clock,
|
||||||
|
// Rule #101: the label states what happens, and passes no
|
||||||
|
// judgement on the music. Never "not for me".
|
||||||
|
contentDescription = "Not right now — hide ${s.name} for a while",
|
||||||
|
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One row of the parked list. This exists because a snoozed candidate is by
|
||||||
|
* definition absent from the deck above, so without it there is no route back
|
||||||
|
* to an un-snooze once the card has gone.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
internal fun SnoozedTile(row: SuggestionSnoozeRef, onUnsnooze: () -> Unit) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text(
|
||||||
|
text = row.name,
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurface,
|
||||||
|
maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = "Back ${row.returnsIn()}",
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
TextButton(onClick = onUnsnooze) { Text("Bring back") }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import com.fabledsword.minstrel.discover.data.RequestOutcome
|
|||||||
import com.fabledsword.minstrel.models.ArtistSuggestionRef
|
import com.fabledsword.minstrel.models.ArtistSuggestionRef
|
||||||
import com.fabledsword.minstrel.models.LidarrRequestKind
|
import com.fabledsword.minstrel.models.LidarrRequestKind
|
||||||
import com.fabledsword.minstrel.models.LidarrSearchResultRef
|
import com.fabledsword.minstrel.models.LidarrSearchResultRef
|
||||||
|
import com.fabledsword.minstrel.models.SuggestionSnoozeRef
|
||||||
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
|
||||||
@@ -27,6 +28,17 @@ data class DiscoverState(
|
|||||||
val suggestions: SuggestionState = SuggestionState.Loading,
|
val suggestions: SuggestionState = SuggestionState.Loading,
|
||||||
val results: ResultsState = ResultsState.Idle,
|
val results: ResultsState = ResultsState.Idle,
|
||||||
val locallyRequestedMbids: Set<String> = emptySet(),
|
val locallyRequestedMbids: Set<String> = emptySet(),
|
||||||
|
/**
|
||||||
|
* Parked candidates, for the manage list under the feed. Empty is the
|
||||||
|
* normal case and hides the section entirely.
|
||||||
|
*/
|
||||||
|
val snoozes: List<SuggestionSnoozeRef> = emptyList(),
|
||||||
|
/**
|
||||||
|
* Just-snoozed MBIDs. These keep their row visible showing an Undo rather
|
||||||
|
* than yanking it out from under the user's finger; the row is gone on the
|
||||||
|
* next load, and [snoozes] is the way back after that.
|
||||||
|
*/
|
||||||
|
val locallySnoozedMbids: Set<String> = emptySet(),
|
||||||
)
|
)
|
||||||
|
|
||||||
sealed interface SuggestionState {
|
sealed interface SuggestionState {
|
||||||
@@ -96,6 +108,47 @@ class DiscoverViewModel @Inject constructor(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Refresh the parked list alongside the deck: a snooze made on another
|
||||||
|
// client should show up here, and one whose window lapsed should drop
|
||||||
|
// off. Sequenced after the deck load rather than raced with it so the
|
||||||
|
// two panes can't disagree about a candidate mid-refresh.
|
||||||
|
loadSnoozes()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Loads the parked list. Failure is deliberately silent: this is a
|
||||||
|
* secondary pane, and an error banner for it would sit above the suggestion
|
||||||
|
* feed the user actually came for. The list stays as-is and the next
|
||||||
|
* refresh retries.
|
||||||
|
*/
|
||||||
|
private suspend fun loadSnoozes() {
|
||||||
|
try {
|
||||||
|
val rows = repository.listSnoozes()
|
||||||
|
internal.update { it.copy(snoozes = rows) }
|
||||||
|
} catch (
|
||||||
|
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
|
||||||
|
) {
|
||||||
|
// Keep whatever we last showed rather than blanking the section.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parks a suggestion. Flips the row locally first so the tap registers
|
||||||
|
* immediately; the repository handles the offline case, so there is no
|
||||||
|
* failure branch to revert here — unlike the web client, where the fetch
|
||||||
|
* either lands or doesn't.
|
||||||
|
*/
|
||||||
|
suspend fun snoozeSuggestion(s: ArtistSuggestionRef) {
|
||||||
|
internal.update { it.copy(locallySnoozedMbids = it.locallySnoozedMbids + s.mbid) }
|
||||||
|
repository.snoozeSuggestion(s.mbid, s.name)
|
||||||
|
loadSnoozes()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Brings a parked suggestion back, from either the card or the list. */
|
||||||
|
suspend fun unsnoozeSuggestion(mbid: String, name: String) {
|
||||||
|
internal.update { it.copy(locallySnoozedMbids = it.locallySnoozedMbids - mbid) }
|
||||||
|
repository.unsnoozeSuggestion(mbid, name)
|
||||||
|
loadSnoozes()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun runSearch() {
|
fun runSearch() {
|
||||||
|
|||||||
@@ -38,8 +38,7 @@ private const val BACKOFF_FACTOR = 2
|
|||||||
* ViewModels + the central [LiveEventsDispatcher]) collect filtered
|
* ViewModels + the central [LiveEventsDispatcher]) collect filtered
|
||||||
* subsets of the stream.
|
* subsets of the stream.
|
||||||
*
|
*
|
||||||
* Connection lifecycle mirrors
|
* Connection lifecycle:
|
||||||
* `flutter_client/lib/shared/live_events_provider.dart`:
|
|
||||||
* - Gated on having a session cookie. Subscription opens when the
|
* - Gated on having a session cookie. Subscription opens when the
|
||||||
* cookie transitions to non-null and closes when it transitions
|
* cookie transitions to non-null and closes when it transitions
|
||||||
* back to null (sign-out).
|
* back to null (sign-out).
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import kotlinx.serialization.json.JsonObject
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Parsed event from the server's SSE stream. Mirrors
|
* Parsed event from the server's SSE stream. Mirrors
|
||||||
* `flutter_client/lib/shared/live_events_provider.dart`'s `LiveEvent`.
|
* the Flutter client's `LiveEvent`.
|
||||||
*
|
*
|
||||||
* - [kind] is the SSE `event:` field (e.g. "track.liked", "playlist.deleted").
|
* - [kind] is the SSE `event:` field (e.g. "track.liked", "playlist.deleted").
|
||||||
* - [userId] is the actor whose user-scoped state changed (empty for
|
* - [userId] is the actor whose user-scoped state changed (empty for
|
||||||
|
|||||||
@@ -11,8 +11,7 @@ import javax.inject.Inject
|
|||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Maps incoming [LiveEvent]s to cross-screen state refreshes. Mirrors
|
* Maps incoming [LiveEvent]s to cross-screen state refreshes. Activated
|
||||||
* `flutter_client/lib/shared/live_events_dispatcher.dart`. Activated
|
|
||||||
* by force-@Inject in MinstrelApplication.
|
* by force-@Inject in MinstrelApplication.
|
||||||
*
|
*
|
||||||
* Scope is deliberately narrow: this dispatcher only touches state
|
* Scope is deliberately narrow: this dispatcher only touches state
|
||||||
|
|||||||
@@ -204,8 +204,7 @@ private const val HOURS_PER_DAY = 24L
|
|||||||
private const val DAYS_PER_WEEK = 7L
|
private const val DAYS_PER_WEEK = 7L
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Lightweight relative-time formatter mirroring Flutter's
|
* Lightweight relative-time formatter:
|
||||||
* `library_screen.dart`'s `_relativeTime`:
|
|
||||||
*
|
*
|
||||||
* < 1h → "Nm ago"
|
* < 1h → "Nm ago"
|
||||||
* < 24h → "Nh ago"
|
* < 24h → "Nh ago"
|
||||||
|
|||||||
@@ -14,8 +14,10 @@ import com.fabledsword.minstrel.models.TrackRef
|
|||||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
import kotlinx.coroutines.flow.combine
|
import kotlinx.coroutines.flow.combine
|
||||||
|
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||||
import kotlinx.coroutines.flow.flatMapLatest
|
import kotlinx.coroutines.flow.flatMapLatest
|
||||||
import kotlinx.coroutines.flow.flowOf
|
import kotlinx.coroutines.flow.flowOf
|
||||||
|
import kotlinx.coroutines.flow.map
|
||||||
import retrofit2.Retrofit
|
import retrofit2.Retrofit
|
||||||
import retrofit2.create
|
import retrofit2.create
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
@@ -34,9 +36,10 @@ import javax.inject.Singleton
|
|||||||
* reveals when the fetch lands and Room re-emits. Mirrors Flutter's
|
* reveals when the fetch lands and Room re-emits. Mirrors Flutter's
|
||||||
* per-item tile providers.
|
* per-item tile providers.
|
||||||
*
|
*
|
||||||
* `refreshIndex()` pulls `GET /api/home/index`, replaces each section
|
* `refreshIndex()` pulls `GET /api/home/index`, swaps all sections in
|
||||||
* in-place (delete-then-insert, so the section Flows re-fire), and
|
* one transaction (so the rows update together in a single emission
|
||||||
* pre-warms the top artists via [HomeArtistPrewarmer].
|
* rather than collapsing and refilling), and pre-warms the top artists
|
||||||
|
* via [HomeArtistPrewarmer].
|
||||||
*/
|
*/
|
||||||
@Singleton
|
@Singleton
|
||||||
// Per-section observe accessors (one per Home row) inflate the function
|
// Per-section observe accessors (one per Home row) inflate the function
|
||||||
@@ -85,72 +88,98 @@ class HomeRepository @Inject constructor(
|
|||||||
fun observeYouMightLikeArtists(): Flow<List<HomeTile<ArtistRef>>> =
|
fun observeYouMightLikeArtists(): Flow<List<HomeTile<ArtistRef>>> =
|
||||||
observeArtistSection(SECTION_YOU_MIGHT_LIKE_ARTISTS)
|
observeArtistSection(SECTION_YOU_MIGHT_LIKE_ARTISTS)
|
||||||
|
|
||||||
|
/** True when the index cache already has content on screen to protect. */
|
||||||
|
suspend fun hasCachedIndex(): Boolean = homeIndexDao.hasAny()
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Pulls /api/home/index, replaces each cached_home_index section,
|
* Pulls /api/home/index and swaps every cached_home_index section in
|
||||||
* and pre-warms the top artists. The section Flows re-fire on the
|
* a single transaction, then pre-warms the top artists. Missing
|
||||||
* index change; missing entity rows hydrate via the on-miss path.
|
* entity rows hydrate via the on-miss path.
|
||||||
|
*
|
||||||
|
* One transaction for all seven sections is deliberate: Room notifies
|
||||||
|
* observers once, on commit, so Home swaps from the old content to
|
||||||
|
* the new in a single emission. Per-section, un-transacted writes
|
||||||
|
* made every row visibly collapse to empty and refill, one after
|
||||||
|
* another (issue #2327).
|
||||||
*/
|
*/
|
||||||
suspend fun refreshIndex() {
|
suspend fun refreshIndex() {
|
||||||
val wire = api.getHomeIndex()
|
val wire = api.getHomeIndex()
|
||||||
replaceSection(SECTION_RECENTLY_ADDED_ALBUMS, "album", wire.recentlyAddedAlbums)
|
homeIndexDao.replaceSections(
|
||||||
replaceSection(SECTION_REDISCOVER_ALBUMS, "album", wire.rediscoverAlbums)
|
sections = ALL_SECTIONS,
|
||||||
replaceSection(SECTION_REDISCOVER_ARTISTS, "artist", wire.rediscoverArtists)
|
rows = rowsFor(SECTION_RECENTLY_ADDED_ALBUMS, "album", wire.recentlyAddedAlbums) +
|
||||||
replaceSection(SECTION_MOST_PLAYED_TRACKS, "track", wire.mostPlayedTracks)
|
rowsFor(SECTION_REDISCOVER_ALBUMS, "album", wire.rediscoverAlbums) +
|
||||||
replaceSection(SECTION_LAST_PLAYED_ARTISTS, "artist", wire.lastPlayedArtists)
|
rowsFor(SECTION_REDISCOVER_ARTISTS, "artist", wire.rediscoverArtists) +
|
||||||
replaceSection(SECTION_YOU_MIGHT_LIKE_ALBUMS, "album", wire.youMightLikeAlbums)
|
rowsFor(SECTION_MOST_PLAYED_TRACKS, "track", wire.mostPlayedTracks) +
|
||||||
replaceSection(SECTION_YOU_MIGHT_LIKE_ARTISTS, "artist", wire.youMightLikeArtists)
|
rowsFor(SECTION_LAST_PLAYED_ARTISTS, "artist", wire.lastPlayedArtists) +
|
||||||
|
rowsFor(SECTION_YOU_MIGHT_LIKE_ALBUMS, "album", wire.youMightLikeAlbums) +
|
||||||
|
rowsFor(SECTION_YOU_MIGHT_LIKE_ARTISTS, "artist", wire.youMightLikeArtists),
|
||||||
|
)
|
||||||
prewarmer.warm(
|
prewarmer.warm(
|
||||||
wire.rediscoverArtists + wire.lastPlayedArtists + wire.youMightLikeArtists,
|
wire.rediscoverArtists + wire.lastPlayedArtists + wire.youMightLikeArtists,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun replaceSection(section: String, entityType: String, ids: List<String>) {
|
private fun rowsFor(
|
||||||
homeIndexDao.deleteBySection(section)
|
section: String,
|
||||||
if (ids.isEmpty()) return
|
entityType: String,
|
||||||
homeIndexDao.upsertAll(
|
ids: List<String>,
|
||||||
ids.mapIndexed { index, id ->
|
): List<CachedHomeIndexEntity> = ids.mapIndexed { index, id ->
|
||||||
CachedHomeIndexEntity(
|
CachedHomeIndexEntity(
|
||||||
section = section,
|
section = section,
|
||||||
position = index,
|
position = index,
|
||||||
entityType = entityType,
|
entityType = entityType,
|
||||||
entityId = id,
|
entityId = id,
|
||||||
)
|
)
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The section's ordered entity ids, deduplicated.
|
||||||
|
*
|
||||||
|
* Room re-runs the query on every write to `cached_home_index` — and
|
||||||
|
* `CachedHomeIndexEntity.fetchedAt` is stamped fresh each time — so
|
||||||
|
* comparing whole rows would call every rewrite a change. Comparing
|
||||||
|
* the id list instead means a section whose contents didn't actually
|
||||||
|
* move never restarts the `flatMapLatest` below, which would
|
||||||
|
* otherwise tear down and rebuild all of its tiles' hydration flows
|
||||||
|
* and flicker unchanged tiles (issue #2327).
|
||||||
|
*/
|
||||||
|
private fun observeSectionIds(section: String): Flow<List<String>> =
|
||||||
|
homeIndexDao.observeBySection(section)
|
||||||
|
.map { rows -> rows.map { it.entityId } }
|
||||||
|
.distinctUntilChanged()
|
||||||
|
|
||||||
@OptIn(ExperimentalCoroutinesApi::class)
|
@OptIn(ExperimentalCoroutinesApi::class)
|
||||||
private fun observeAlbumSection(section: String): Flow<List<HomeTile<AlbumRef>>> =
|
private fun observeAlbumSection(section: String): Flow<List<HomeTile<AlbumRef>>> =
|
||||||
homeIndexDao.observeBySection(section).flatMapLatest { rows ->
|
observeSectionIds(section).flatMapLatest { ids ->
|
||||||
if (rows.isEmpty()) {
|
if (ids.isEmpty()) {
|
||||||
flowOf(emptyList())
|
flowOf(emptyList())
|
||||||
} else {
|
} else {
|
||||||
combine(rows.map { metadataProvider.observeAlbum(it.entityId) }) { refs ->
|
combine(ids.map { metadataProvider.observeAlbum(it) }) { refs ->
|
||||||
rows.mapIndexed { i, r -> HomeTile(r.entityId, refs[i]) }
|
ids.mapIndexed { i, id -> HomeTile(id, refs[i]) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@OptIn(ExperimentalCoroutinesApi::class)
|
@OptIn(ExperimentalCoroutinesApi::class)
|
||||||
private fun observeArtistSection(section: String): Flow<List<HomeTile<ArtistRef>>> =
|
private fun observeArtistSection(section: String): Flow<List<HomeTile<ArtistRef>>> =
|
||||||
homeIndexDao.observeBySection(section).flatMapLatest { rows ->
|
observeSectionIds(section).flatMapLatest { ids ->
|
||||||
if (rows.isEmpty()) {
|
if (ids.isEmpty()) {
|
||||||
flowOf(emptyList())
|
flowOf(emptyList())
|
||||||
} else {
|
} else {
|
||||||
combine(rows.map { metadataProvider.observeArtist(it.entityId) }) { refs ->
|
combine(ids.map { metadataProvider.observeArtist(it) }) { refs ->
|
||||||
rows.mapIndexed { i, r -> HomeTile(r.entityId, refs[i]) }
|
ids.mapIndexed { i, id -> HomeTile(id, refs[i]) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@OptIn(ExperimentalCoroutinesApi::class)
|
@OptIn(ExperimentalCoroutinesApi::class)
|
||||||
private fun observeTrackSection(section: String): Flow<List<HomeTile<TrackRef>>> =
|
private fun observeTrackSection(section: String): Flow<List<HomeTile<TrackRef>>> =
|
||||||
homeIndexDao.observeBySection(section).flatMapLatest { rows ->
|
observeSectionIds(section).flatMapLatest { ids ->
|
||||||
if (rows.isEmpty()) {
|
if (ids.isEmpty()) {
|
||||||
flowOf(emptyList())
|
flowOf(emptyList())
|
||||||
} else {
|
} else {
|
||||||
combine(rows.map { metadataProvider.observeTrack(it.entityId) }) { refs ->
|
combine(ids.map { metadataProvider.observeTrack(it) }) { refs ->
|
||||||
rows.mapIndexed { i, r -> HomeTile(r.entityId, refs[i]) }
|
ids.mapIndexed { i, id -> HomeTile(id, refs[i]) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -163,5 +192,16 @@ class HomeRepository @Inject constructor(
|
|||||||
const val SECTION_LAST_PLAYED_ARTISTS = "last_played_artists"
|
const val SECTION_LAST_PLAYED_ARTISTS = "last_played_artists"
|
||||||
const val SECTION_YOU_MIGHT_LIKE_ALBUMS = "you_might_like_albums"
|
const val SECTION_YOU_MIGHT_LIKE_ALBUMS = "you_might_like_albums"
|
||||||
const val SECTION_YOU_MIGHT_LIKE_ARTISTS = "you_might_like_artists"
|
const val SECTION_YOU_MIGHT_LIKE_ARTISTS = "you_might_like_artists"
|
||||||
|
|
||||||
|
/** Every section [refreshIndex] owns — the unit of one atomic swap. */
|
||||||
|
val ALL_SECTIONS = listOf(
|
||||||
|
SECTION_RECENTLY_ADDED_ALBUMS,
|
||||||
|
SECTION_REDISCOVER_ALBUMS,
|
||||||
|
SECTION_REDISCOVER_ARTISTS,
|
||||||
|
SECTION_MOST_PLAYED_TRACKS,
|
||||||
|
SECTION_LAST_PLAYED_ARTISTS,
|
||||||
|
SECTION_YOU_MIGHT_LIKE_ALBUMS,
|
||||||
|
SECTION_YOU_MIGHT_LIKE_ARTISTS,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -43,6 +43,7 @@ import androidx.compose.material3.SnackbarHost
|
|||||||
import androidx.compose.material3.SnackbarHostState
|
import androidx.compose.material3.SnackbarHostState
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.CompositionLocalProvider
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
@@ -85,30 +86,39 @@ import com.fabledsword.minstrel.playlists.widgets.OfflinePoolCard
|
|||||||
import com.fabledsword.minstrel.playlists.widgets.PlaylistCard
|
import com.fabledsword.minstrel.playlists.widgets.PlaylistCard
|
||||||
import com.fabledsword.minstrel.playlists.widgets.PlaylistPlaceholderCard
|
import com.fabledsword.minstrel.playlists.widgets.PlaylistPlaceholderCard
|
||||||
import com.fabledsword.minstrel.shared.UiState
|
import com.fabledsword.minstrel.shared.UiState
|
||||||
|
import com.fabledsword.minstrel.shared.UpdateVeilController
|
||||||
|
import com.fabledsword.minstrel.shared.VeilOutcome
|
||||||
|
import com.fabledsword.minstrel.shared.VeilSessionResult
|
||||||
|
import com.fabledsword.minstrel.shared.VeilSettleState
|
||||||
import com.fabledsword.minstrel.shared.asCacheFirstStateFlow
|
import com.fabledsword.minstrel.shared.asCacheFirstStateFlow
|
||||||
|
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
|
||||||
|
import com.fabledsword.minstrel.shared.widgets.ArtSettleTracker
|
||||||
import com.fabledsword.minstrel.shared.widgets.EmptyState
|
import com.fabledsword.minstrel.shared.widgets.EmptyState
|
||||||
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
|
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
|
||||||
import com.fabledsword.minstrel.shared.widgets.HorizontalScrollRow
|
import com.fabledsword.minstrel.shared.widgets.HorizontalScrollRow
|
||||||
|
import com.fabledsword.minstrel.shared.widgets.LocalArtSettleTracker
|
||||||
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
|
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
|
||||||
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
|
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
|
||||||
import com.fabledsword.minstrel.shared.widgets.SkeletonAlbumTile
|
import com.fabledsword.minstrel.shared.widgets.SkeletonAlbumTile
|
||||||
import com.fabledsword.minstrel.shared.widgets.SkeletonArtistTile
|
import com.fabledsword.minstrel.shared.widgets.SkeletonArtistTile
|
||||||
import com.fabledsword.minstrel.shared.widgets.SkeletonSectionHeader
|
import com.fabledsword.minstrel.shared.widgets.SkeletonSectionHeader
|
||||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
import kotlinx.coroutines.Job
|
import kotlinx.coroutines.async
|
||||||
import kotlinx.coroutines.channels.Channel
|
import kotlinx.coroutines.channels.Channel
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.coroutineScope
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.SharingStarted
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
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.combine
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
import kotlinx.coroutines.flow.map
|
import kotlinx.coroutines.flow.map
|
||||||
import kotlinx.coroutines.flow.receiveAsFlow
|
import kotlinx.coroutines.flow.receiveAsFlow
|
||||||
import kotlinx.coroutines.flow.stateIn
|
import kotlinx.coroutines.flow.stateIn
|
||||||
import kotlinx.coroutines.flow.filter
|
import kotlinx.coroutines.flow.filter
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withTimeoutOrNull
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
private const val SHARE_STOP_TIMEOUT_MS = 5_000L
|
private const val SHARE_STOP_TIMEOUT_MS = 5_000L
|
||||||
@@ -120,16 +130,22 @@ private const val BOTTOM_PADDING_FOR_MINIPLAYER_DP = 140
|
|||||||
private const val RECENTLY_ADDED_GRID_ROWS = 2
|
private const val RECENTLY_ADDED_GRID_ROWS = 2
|
||||||
private const val RECENTLY_ADDED_GRID_HEIGHT_DP = 440
|
private const val RECENTLY_ADDED_GRID_HEIGHT_DP = 440
|
||||||
|
|
||||||
// "Updating your mixes…" veil (automatic refresh). Held through the pull
|
// "Updating your mixes…" veil. UpdateVeilController decides both whether it
|
||||||
// plus VEIL_SETTLE_MS so per-tile hydration lands behind it before it wipes
|
// appears at all — only when a refresh actually changes something — and how
|
||||||
// off; near-opaque (VEIL_ALPHA) so the section churn never bleeds through.
|
// long it stays, by watching the screen settle rather than by a fixed delay,
|
||||||
private const val VEIL_SETTLE_MS = 500L
|
// which lowered it while tiles and artwork were still landing (#2327).
|
||||||
|
// Near-opaque (VEIL_ALPHA) so the section churn never bleeds through.
|
||||||
private const val VEIL_WIPE_MS = 280
|
private const val VEIL_WIPE_MS = 280
|
||||||
private const val VEIL_ALPHA = 0.96f
|
private const val VEIL_ALPHA = 0.96f
|
||||||
private const val VEIL_SPINNER_DP = 22
|
private const val VEIL_SPINNER_DP = 22
|
||||||
private const val VEIL_SPINNER_STROKE_DP = 2
|
private const val VEIL_SPINNER_STROKE_DP = 2
|
||||||
private const val VEIL_LABEL_GAP_DP = 12
|
private const val VEIL_LABEL_GAP_DP = 12
|
||||||
|
|
||||||
|
// Backstop on how long a manual pull keeps its own indicator while waiting
|
||||||
|
// for its successor — the veil, or the "already up to date" snackbar — so the
|
||||||
|
// two never both vanish for a frame mid-handoff.
|
||||||
|
private const val PULL_HANDOFF_TIMEOUT_MS = 2_000L
|
||||||
|
|
||||||
// ─── State ───────────────────────────────────────────────────────────
|
// ─── State ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
data class HomeSections(
|
data class HomeSections(
|
||||||
@@ -184,10 +200,13 @@ class HomeViewModel @Inject constructor(
|
|||||||
initialValue = false,
|
initialValue = false,
|
||||||
)
|
)
|
||||||
|
|
||||||
private val poolMessages = Channel<String>(Channel.BUFFERED)
|
private val snackbarMessages = Channel<String>(Channel.BUFFERED)
|
||||||
|
|
||||||
/** Transient snackbar messages from offline-pool taps. */
|
/**
|
||||||
val transientMessages: Flow<String> = poolMessages.receiveAsFlow()
|
* Transient snackbar messages: offline-pool taps, playback failures, and
|
||||||
|
* the outcome of a refresh the user explicitly asked for.
|
||||||
|
*/
|
||||||
|
val transientMessages: Flow<String> = snackbarMessages.receiveAsFlow()
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Copy for the most recent /home/index refresh failure; null once a
|
* Copy for the most recent /home/index refresh failure; null once a
|
||||||
@@ -197,38 +216,13 @@ class HomeViewModel @Inject constructor(
|
|||||||
*/
|
*/
|
||||||
private val refreshError = MutableStateFlow<String?>(null)
|
private val refreshError = MutableStateFlow<String?>(null)
|
||||||
|
|
||||||
private val updatingInternal = MutableStateFlow(false)
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* True while an automatic background refresh (the 03:00 daily rebuild
|
* Cover-art loads in flight on Home, reported by every [ServerImage]
|
||||||
* or a reconnect re-pull) is repopulating Home. Drives the "Updating
|
* under [LocalArtSettleTracker]. The veil waits on this so artwork
|
||||||
* your mixes…" veil so the section churn — delete-then-insert in
|
* arriving a beat after its tile lands behind the veil rather than
|
||||||
* [HomeRepository.refreshIndex] plus per-tile hydration — happens
|
* popping in on screen.
|
||||||
* hidden behind the veil instead of on screen. Manual pull-to-refresh
|
|
||||||
* and cold start are NOT veiled (they own the pull spinner / skeleton).
|
|
||||||
*/
|
*/
|
||||||
val isUpdating: StateFlow<Boolean> = updatingInternal.asStateFlow()
|
val artTracker = ArtSettleTracker()
|
||||||
|
|
||||||
init {
|
|
||||||
refresh()
|
|
||||||
// Screen-level auto-recovery (issue #1245): a Home that failed to
|
|
||||||
// load while the server was unreachable re-pulls itself the moment
|
|
||||||
// health returns — same idiom as SyncController, one layer up.
|
|
||||||
// Veiled: content is already on screen and would otherwise churn.
|
|
||||||
viewModelScope.launch {
|
|
||||||
networkStatus.recoveries().collect { refreshBehindVeil() }
|
|
||||||
}
|
|
||||||
// #968: the daily 03:00 rebuild (and manual refresh) emit
|
|
||||||
// playlist.system_rebuilt; re-pull Home so the system-playlist tiles
|
|
||||||
// and You-might-like rows reflect the new snapshot without a manual
|
|
||||||
// reload. Mirrors the web SSE consumer. Veiled so the multi-section
|
|
||||||
// rebuild churn hides behind "Updating your mixes…".
|
|
||||||
viewModelScope.launch {
|
|
||||||
eventsStream.events
|
|
||||||
.filter { it.kind == "playlist.system_rebuilt" }
|
|
||||||
.collect { refreshBehindVeil() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tap an offline pool: shuffle + play its cached tracks. Empty
|
* Tap an offline pool: shuffle + play its cached tracks. Empty
|
||||||
@@ -241,7 +235,7 @@ class HomeViewModel @Inject constructor(
|
|||||||
OfflinePoolKind.LIKED -> shuffleSource.liked()
|
OfflinePoolKind.LIKED -> shuffleSource.liked()
|
||||||
}.shuffled()
|
}.shuffled()
|
||||||
if (tracks.isEmpty()) {
|
if (tracks.isEmpty()) {
|
||||||
poolMessages.trySend("No cached ${kind.label} tracks yet")
|
snackbarMessages.trySend("No cached ${kind.label} tracks yet")
|
||||||
} else {
|
} else {
|
||||||
player.setQueue(tracks, initialIndex = 0, source = "offline:${kind.name}")
|
player.setQueue(tracks, initialIndex = 0, source = "offline:${kind.name}")
|
||||||
}
|
}
|
||||||
@@ -278,14 +272,14 @@ class HomeViewModel @Inject constructor(
|
|||||||
try {
|
try {
|
||||||
val detail = libraryRepository.refreshAlbumDetail(albumId)
|
val detail = libraryRepository.refreshAlbumDetail(albumId)
|
||||||
if (detail.tracks.isEmpty()) {
|
if (detail.tracks.isEmpty()) {
|
||||||
poolMessages.trySend("This album has no tracks to play.")
|
snackbarMessages.trySend("This album has no tracks to play.")
|
||||||
} else {
|
} else {
|
||||||
player.setQueue(detail.tracks, initialIndex = 0, source = "album:$albumId")
|
player.setQueue(detail.tracks, initialIndex = 0, source = "album:$albumId")
|
||||||
}
|
}
|
||||||
} catch (
|
} catch (
|
||||||
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
||||||
) {
|
) {
|
||||||
poolMessages.trySend(
|
snackbarMessages.trySend(
|
||||||
"Couldn't start playback: ${ErrorCopy.fromThrowable(e)}",
|
"Couldn't start playback: ${ErrorCopy.fromThrowable(e)}",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -303,14 +297,14 @@ class HomeViewModel @Inject constructor(
|
|||||||
try {
|
try {
|
||||||
val tracks = libraryRepository.fetchArtistTracks(artistId).shuffled()
|
val tracks = libraryRepository.fetchArtistTracks(artistId).shuffled()
|
||||||
if (tracks.isEmpty()) {
|
if (tracks.isEmpty()) {
|
||||||
poolMessages.trySend("This artist has no tracks to play.")
|
snackbarMessages.trySend("This artist has no tracks to play.")
|
||||||
} else {
|
} else {
|
||||||
player.setQueue(tracks, initialIndex = 0, source = "artist:$artistId")
|
player.setQueue(tracks, initialIndex = 0, source = "artist:$artistId")
|
||||||
}
|
}
|
||||||
} catch (
|
} catch (
|
||||||
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
||||||
) {
|
) {
|
||||||
poolMessages.trySend(
|
snackbarMessages.trySend(
|
||||||
"Couldn't start playback: ${ErrorCopy.fromThrowable(e)}",
|
"Couldn't start playback: ${ErrorCopy.fromThrowable(e)}",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -328,52 +322,66 @@ class HomeViewModel @Inject constructor(
|
|||||||
suspend fun playPlaylist(playlist: PlaylistRef) {
|
suspend fun playPlaylist(playlist: PlaylistRef) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
playPlaylistShuffled(playlist, playlistsRepository, player) {
|
playPlaylistShuffled(playlist, playlistsRepository, player) {
|
||||||
poolMessages.trySend(it)
|
snackbarMessages.trySend(it)
|
||||||
}
|
}
|
||||||
}.join()
|
}.join()
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Pulls both /home/index and the playlists list. Returns the Job
|
* Pulls /home/index, the playlists list and the system-playlist
|
||||||
* for the combined refresh so a pull-to-refresh wrapper can await
|
* status. Returns true when the load-bearing /home/index pull
|
||||||
* actual completion before hiding the indicator.
|
* succeeded — the veil controller retries on false and reports the
|
||||||
|
* outcome, so this must report failure rather than swallow it.
|
||||||
*/
|
*/
|
||||||
fun refresh(): Job = viewModelScope.launch {
|
private suspend fun runRefresh(): Boolean = coroutineScope {
|
||||||
refreshError.value = null
|
|
||||||
val home = launch {
|
|
||||||
// /home/index is the load-bearing pull: its failure drives the
|
// /home/index is the load-bearing pull: its failure drives the
|
||||||
// empty-cache Error state. A failure over a populated cache
|
// empty-cache Error state. A failure over a populated cache
|
||||||
// stays silent — cached sections beat a full-screen error.
|
// stays silent — cached sections beat a full-screen error.
|
||||||
|
//
|
||||||
|
// Cleared on success, NOT at the start of each attempt: with the
|
||||||
|
// veil's retries, clearing up front made a failing cold start
|
||||||
|
// flash the "Welcome to Minstrel" empty state (empty cache + no
|
||||||
|
// error reads as Empty) between one attempt and the next.
|
||||||
|
val home = async {
|
||||||
runCatching { homeRepository.refreshIndex() }
|
runCatching { homeRepository.refreshIndex() }
|
||||||
|
.onSuccess { refreshError.value = null }
|
||||||
.onFailure { refreshError.value = ErrorCopy.fromThrowable(it) }
|
.onFailure { refreshError.value = ErrorCopy.fromThrowable(it) }
|
||||||
|
.isSuccess
|
||||||
}
|
}
|
||||||
val lists = launch { runCatching { playlistsRepository.refreshList() } }
|
val lists = launch { runCatching { playlistsRepository.refreshList() } }
|
||||||
val status = launch {
|
val status = launch {
|
||||||
runCatching { homeRepository.getSystemPlaylistsStatus() }
|
runCatching { homeRepository.getSystemPlaylistsStatus() }
|
||||||
.onSuccess { systemStatusInternal.value = it }
|
.onSuccess { systemStatusInternal.value = it }
|
||||||
}
|
}
|
||||||
home.join()
|
|
||||||
lists.join()
|
lists.join()
|
||||||
status.join()
|
status.join()
|
||||||
|
home.await()
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Automatic background refresh with the "Updating your mixes…" veil
|
* The Error state's explicit Retry button. User-initiated, so it gets
|
||||||
* raised (see [isUpdating]). Used by the daily-rebuild + reconnect
|
* the controller's retries and reports its outcome; over an empty cache
|
||||||
* paths where Home is already on screen. Holds the veil through the
|
* there's no content to protect, so no veil goes up.
|
||||||
* pull plus a short settle so per-tile hydration lands behind it, then
|
|
||||||
* lets it wipe off. Overlapping automatic refreshes are rare enough
|
|
||||||
* (once-daily rebuild, reconnect) that a plain flag beats a counter.
|
|
||||||
*/
|
*/
|
||||||
private fun refreshBehindVeil() {
|
fun retry() = veil.request(userInitiated = true)
|
||||||
viewModelScope.launch {
|
|
||||||
updatingInternal.value = true
|
/**
|
||||||
try {
|
* Manual pull-to-refresh. Goes behind the veil like every other refresh
|
||||||
refresh().join()
|
* (operator call, 2026-07-31: the churn a pull causes is identical to
|
||||||
delay(VEIL_SETTLE_MS)
|
* the automatic paths, and a small spinner didn't hide it).
|
||||||
} finally {
|
*
|
||||||
updatingInternal.value = false
|
* Suspends until the veil has taken over OR the session has finished,
|
||||||
}
|
* so the pull indicator hands off to exactly one successor: the veil if
|
||||||
|
* content changed, the "Already up to date" snackbar if it didn't. The
|
||||||
|
* timeout is only a backstop against a session that outlives it.
|
||||||
|
*/
|
||||||
|
suspend fun refreshFromPull() {
|
||||||
|
val before = veil.finishedSessions.value
|
||||||
|
veil.request(userInitiated = true)
|
||||||
|
withTimeoutOrNull(PULL_HANDOFF_TIMEOUT_MS) {
|
||||||
|
combine(veil.visible, veil.finishedSessions) { veiled, finished ->
|
||||||
|
veiled || finished != before
|
||||||
|
}.first { it }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -425,6 +433,124 @@ class HomeViewModel @Inject constructor(
|
|||||||
else -> UiState.Empty
|
else -> UiState.Empty
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── Updating veil ───────────────────────────────────────────────
|
||||||
|
// Declared after uiState: these initialisers read it, and Kotlin runs
|
||||||
|
// property initialisers and init blocks in declaration order.
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What the veil watches to decide Home has stopped moving: the whole
|
||||||
|
* rendered state, plus how many covers are still loading.
|
||||||
|
*
|
||||||
|
* [UiState.Success] wraps a [HomeSections] data class, so any visible
|
||||||
|
* change — a section swapping ids, one tile hydrating from skeleton to
|
||||||
|
* album — changes this value and re-arms the veil's quiet window.
|
||||||
|
*
|
||||||
|
* Unhydrated tiles deliberately do NOT gate `quiescent`. A tile whose
|
||||||
|
* on-miss fetch soft-fails keeps a null value indefinitely
|
||||||
|
* ([MetadataProvider] swallows those errors), so treating "no
|
||||||
|
* skeletons left" as the settle condition would pin the veil to its
|
||||||
|
* hard ceiling on every refresh. They're covered by the content key
|
||||||
|
* instead: each tile that lands re-arms the window, and once they stop
|
||||||
|
* landing the screen is genuinely still.
|
||||||
|
*/
|
||||||
|
private val settleSignal: Flow<VeilSettleState> =
|
||||||
|
combine(uiState, artTracker.inFlight) { state, artInFlight ->
|
||||||
|
VeilSettleState(
|
||||||
|
contentKey = state,
|
||||||
|
hasContent = state is UiState.Success,
|
||||||
|
quiescent = artInFlight == 0,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private val veil = UpdateVeilController(
|
||||||
|
scope = viewModelScope,
|
||||||
|
settleSignal = settleSignal,
|
||||||
|
shouldVeil = {
|
||||||
|
// Only worth hiding churn when there's already content to
|
||||||
|
// hide. A cold load over an empty cache keeps its skeleton —
|
||||||
|
// veiling that would replace a useful affordance with an
|
||||||
|
// opaque panel. `hasCachedIndex` is the honest check: uiState
|
||||||
|
// still reads Loading until the screen subscribes, so on a
|
||||||
|
// process restore over a warm cache it would say "no content"
|
||||||
|
// right before the cache emits.
|
||||||
|
uiState.value is UiState.Success || homeRepository.hasCachedIndex()
|
||||||
|
},
|
||||||
|
onSessionEnd = ::reportRefreshOutcome,
|
||||||
|
work = ::runRefresh,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tells the user how a refresh *they asked for* went, in the one case
|
||||||
|
* the veil can't: when nothing changed there's no veil to see, and a
|
||||||
|
* pull that produces no visible response at all reads as broken.
|
||||||
|
*
|
||||||
|
* Only user-initiated sessions say anything. The same outcome from a
|
||||||
|
* background check — the initial load, the 03:00 rebuild, a reconnect —
|
||||||
|
* is noise, and "Already up to date" on every launch would be worse
|
||||||
|
* than silence (operator's call, 2026-07-31).
|
||||||
|
*/
|
||||||
|
private fun reportRefreshOutcome(result: VeilSessionResult) {
|
||||||
|
if (!result.userInitiated) return
|
||||||
|
when (result.outcome) {
|
||||||
|
// The veil was the feedback.
|
||||||
|
VeilOutcome.CHANGED -> return
|
||||||
|
VeilOutcome.UNCHANGED -> snackbarMessages.trySend("Already up to date")
|
||||||
|
VeilOutcome.FAILED -> snackbarMessages.trySend("Couldn't check for updates")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True while the "Updating your mixes…" veil should be raised.
|
||||||
|
*
|
||||||
|
* Raised only when a refresh actually changes what's on screen, and then
|
||||||
|
* held until Home settles — tiles hydrated, artwork loaded — instead of
|
||||||
|
* for a fixed delay after the network pull returns (issue #2327). A
|
||||||
|
* refresh that returns what's already cached shows no veil at all;
|
||||||
|
* [reportRefreshOutcome] tells the user instead, if they asked.
|
||||||
|
*/
|
||||||
|
val isUpdating: StateFlow<Boolean> = veil.visible
|
||||||
|
|
||||||
|
init {
|
||||||
|
// Every refresh path goes through the controller, which decides
|
||||||
|
// per session whether to raise the veil. That includes the initial
|
||||||
|
// load: over a warm cache it's a full re-pull that churns every
|
||||||
|
// section, and it used to run completely unveiled.
|
||||||
|
veil.request()
|
||||||
|
// Screen-level auto-recovery (issue #1245): a Home that failed to
|
||||||
|
// load while the server was unreachable re-pulls itself the moment
|
||||||
|
// health returns — same idiom as SyncController, one layer up.
|
||||||
|
// This is also the recovery that keeps trying after the veil has
|
||||||
|
// given up and lowered; the controller sets no latch against it.
|
||||||
|
viewModelScope.launch {
|
||||||
|
networkStatus.recoveries().collect { veil.request() }
|
||||||
|
}
|
||||||
|
// Server-side changes that rewrite what Home renders (#968 and
|
||||||
|
// the 2026-07-31 widening) re-pull behind the veil. Mirrors the
|
||||||
|
// web SSE consumer.
|
||||||
|
viewModelScope.launch {
|
||||||
|
eventsStream.events
|
||||||
|
.filter { it.kind in VEILED_EVENT_KINDS }
|
||||||
|
.collect { veil.request() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
/**
|
||||||
|
* Events that change what Home shows. `playlist.system_rebuilt`
|
||||||
|
* is the 03:00 daily rebuild; the other `playlist.*` kinds move
|
||||||
|
* the Playlists and Songs-like rows; `scan.run_finished` changes
|
||||||
|
* Recently added (and Home never reacted to it at all before).
|
||||||
|
*/
|
||||||
|
private val VEILED_EVENT_KINDS = setOf(
|
||||||
|
"playlist.system_rebuilt",
|
||||||
|
"playlist.created",
|
||||||
|
"playlist.updated",
|
||||||
|
"playlist.deleted",
|
||||||
|
"playlist.tracks_changed",
|
||||||
|
"scan.run_finished",
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Screen ──────────────────────────────────────────────────────────
|
// ─── Screen ──────────────────────────────────────────────────────────
|
||||||
@@ -439,6 +565,7 @@ fun HomeScreen(
|
|||||||
viewModel.transientMessages.collect { snackbarHostState.showSnackbar(it) }
|
viewModel.transientMessages.collect { snackbarHostState.showSnackbar(it) }
|
||||||
}
|
}
|
||||||
Scaffold(
|
Scaffold(
|
||||||
|
contentWindowInsets = ShellContentWindowInsets,
|
||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.fillMaxSize(),
|
||||||
topBar = {
|
topBar = {
|
||||||
MinstrelTopAppBar(
|
MinstrelTopAppBar(
|
||||||
@@ -454,14 +581,20 @@ fun HomeScreen(
|
|||||||
val offline by viewModel.offline.collectAsStateWithLifecycle()
|
val offline by viewModel.offline.collectAsStateWithLifecycle()
|
||||||
val updating by viewModel.isUpdating.collectAsStateWithLifecycle()
|
val updating by viewModel.isUpdating.collectAsStateWithLifecycle()
|
||||||
PullToRefreshScaffold(
|
PullToRefreshScaffold(
|
||||||
onRefresh = { viewModel.refresh().join() },
|
onRefresh = { viewModel.refreshFromPull() },
|
||||||
modifier = Modifier.fillMaxSize().padding(inner),
|
modifier = Modifier.fillMaxSize().padding(inner),
|
||||||
) {
|
) {
|
||||||
Box(Modifier.fillMaxSize()) {
|
Box(Modifier.fillMaxSize()) {
|
||||||
|
// Every cover below reports its load state to the tracker,
|
||||||
|
// so the veil can wait for artwork instead of guessing.
|
||||||
|
CompositionLocalProvider(
|
||||||
|
LocalArtSettleTracker provides viewModel.artTracker,
|
||||||
|
) {
|
||||||
HomeStateCrossfade(state, systemStatus, offline, navController, viewModel)
|
HomeStateCrossfade(state, systemStatus, offline, navController, viewModel)
|
||||||
// Automatic-refresh veil: the daily rebuild / reconnect
|
}
|
||||||
// churn hides behind an "Updating your mixes…" wipe. Manual
|
// Refresh veil: rebuild / reconnect / pull / event churn all
|
||||||
// pull owns the PullToRefreshBox spinner instead.
|
// hide behind an "Updating your mixes…" wipe that stays up
|
||||||
|
// until the screen has actually stopped moving.
|
||||||
UpdatingVeil(visible = updating)
|
UpdatingVeil(visible = updating)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -499,7 +632,7 @@ private fun HomeStateCrossfade(
|
|||||||
is UiState.Error -> ErrorRetry(
|
is UiState.Error -> ErrorRetry(
|
||||||
title = "Couldn't load home",
|
title = "Couldn't load home",
|
||||||
message = s.message,
|
message = s.message,
|
||||||
onRetry = { viewModel.refresh() },
|
onRetry = { viewModel.retry() },
|
||||||
)
|
)
|
||||||
is UiState.Success -> HomeSuccessContent(
|
is UiState.Success -> HomeSuccessContent(
|
||||||
sections = s.data,
|
sections = s.data,
|
||||||
@@ -1039,7 +1172,7 @@ enum class OfflinePoolKind(val label: String) {
|
|||||||
* first / greyed after, and the "building/pending" placeholders are dropped
|
* first / greyed after, and the "building/pending" placeholders are dropped
|
||||||
* (they need the server to generate, so they're meaningless offline).
|
* (they need the server to generate, so they're meaningless offline).
|
||||||
*
|
*
|
||||||
* Diverges from Flutter (`flutter_client/lib/library/home_screen.dart`
|
* Diverges from Flutter (the Flutter client
|
||||||
* `_buildPlaylistsRow`) which only shows the 5 fixed slots and never
|
* `_buildPlaylistsRow`) which only shows the 5 fixed slots and never
|
||||||
* surfaces the secondary kinds on Home. Operator authorized the
|
* surfaces the secondary kinds on Home. Operator authorized the
|
||||||
* divergence on 2026-06-01; web UI catch-up tracked as task #53.
|
* divergence on 2026-06-01; web UI catch-up tracked as task #53.
|
||||||
@@ -1241,7 +1374,7 @@ private const val MOST_PLAYED_COVER_DP = 48
|
|||||||
|
|
||||||
// 3 rows of MOST_PLAYED_TILE_HEIGHT_DP + 2 * 8dp inter-row spacing,
|
// 3 rows of MOST_PLAYED_TILE_HEIGHT_DP + 2 * 8dp inter-row spacing,
|
||||||
// rounded up. Mirrors Flutter (`CompactTrackCard` in
|
// rounded up. Mirrors Flutter (`CompactTrackCard` in
|
||||||
// flutter_client/lib/library/widgets/compact_track_card.dart) which
|
// the Flutter client) which
|
||||||
// uses a horizontal-row card pattern - much denser than the square
|
// uses a horizontal-row card pattern - much denser than the square
|
||||||
// per-track tiles that web uses (operator request 2026-06-01: "in the
|
// per-track tiles that web uses (operator request 2026-06-01: "in the
|
||||||
// flutter iteration the tiles were different and smaller so more of
|
// flutter iteration the tiles were different and smaller so more of
|
||||||
|
|||||||
@@ -97,6 +97,7 @@ fun CachedTrackEntity.toDomain(
|
|||||||
trackNumber = trackNumber,
|
trackNumber = trackNumber,
|
||||||
discNumber = discNumber,
|
discNumber = discNumber,
|
||||||
durationSec = durationMs.millisToSeconds(),
|
durationSec = durationMs.millisToSeconds(),
|
||||||
|
unavailable = missing,
|
||||||
// Deterministic from track id; matches the server's stream_url
|
// Deterministic from track id; matches the server's stream_url
|
||||||
// (internal/api/convert.go:75 streamURL builder). Cached rows
|
// (internal/api/convert.go:75 streamURL builder). Cached rows
|
||||||
// didn't carry streamUrl before, which left MetadataProvider-
|
// didn't carry streamUrl before, which left MetadataProvider-
|
||||||
@@ -121,6 +122,7 @@ fun TrackWire.toDomain(): TrackRef =
|
|||||||
discNumber = discNumber,
|
discNumber = discNumber,
|
||||||
durationSec = durationSec,
|
durationSec = durationSec,
|
||||||
streamUrl = streamUrl,
|
streamUrl = streamUrl,
|
||||||
|
unavailable = unavailable,
|
||||||
)
|
)
|
||||||
|
|
||||||
fun ArtistWire.toDomain(): ArtistRef =
|
fun ArtistWire.toDomain(): ArtistRef =
|
||||||
|
|||||||
@@ -161,7 +161,52 @@ class LibraryRepository @Inject constructor(
|
|||||||
suspend fun shuffleLibrary(limit: Int = SHUFFLE_DEFAULT_LIMIT): List<TrackRef> =
|
suspend fun shuffleLibrary(limit: Int = SHUFFLE_DEFAULT_LIMIT): List<TrackRef> =
|
||||||
api.shuffleLibrary(limit = limit).map { it.toDomain() }
|
api.shuffleLibrary(limit = limit).map { it.toDomain() }
|
||||||
|
|
||||||
|
// ---- Browse axes (#367 / #2467) ----
|
||||||
|
//
|
||||||
|
// Server-backed rather than cache-first, unlike everything above. The
|
||||||
|
// cache mirrors the whole library but includes tracks whose files are
|
||||||
|
// missing, with no flag to spot them (#2704), while the server's index
|
||||||
|
// excludes them -- so a locally-derived index would quietly disagree with
|
||||||
|
// the web client's. Revisit when #2704 lands.
|
||||||
|
|
||||||
|
/** Genre index, ordered by track count then name (server order). */
|
||||||
|
suspend fun genres(): List<GenreCount> =
|
||||||
|
api.getGenres().map { GenreCount(genre = it.genre, trackCount = it.trackCount) }
|
||||||
|
|
||||||
|
/** Year index, newest first. Albums with no release date are absent. */
|
||||||
|
suspend fun albumYears(): List<YearCount> =
|
||||||
|
api.getAlbumYears().map { YearCount(year = it.year, albumCount = it.albumCount) }
|
||||||
|
|
||||||
|
/** One page of albums carrying [genre] on any track. */
|
||||||
|
suspend fun albumsByGenre(genre: String, limit: Int, offset: Int): AlbumPage {
|
||||||
|
val page = api.getAlbumsByGenre(genre = genre, limit = limit, offset = offset)
|
||||||
|
return AlbumPage(items = page.items.map { it.toDomain() }, total = page.total)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One page of albums released in [year]. */
|
||||||
|
suspend fun albumsByYear(year: Int, limit: Int, offset: Int): AlbumPage {
|
||||||
|
val page = api.getAlbumsByYear(
|
||||||
|
yearFrom = year,
|
||||||
|
yearTo = year,
|
||||||
|
limit = limit,
|
||||||
|
offset = offset,
|
||||||
|
)
|
||||||
|
return AlbumPage(items = page.items.map { it.toDomain() }, total = page.total)
|
||||||
|
}
|
||||||
|
|
||||||
private companion object {
|
private companion object {
|
||||||
const val SHUFFLE_DEFAULT_LIMIT = 100
|
const val SHUFFLE_DEFAULT_LIMIT = 100
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** One row of the genre index. */
|
||||||
|
data class GenreCount(val genre: String, val trackCount: Int)
|
||||||
|
|
||||||
|
/** One row of the year index. */
|
||||||
|
data class YearCount(val year: Int, val albumCount: Int)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A page of albums plus the server's total for the whole filter, which is
|
||||||
|
* what lets the UI say how many are left rather than just offering "more".
|
||||||
|
*/
|
||||||
|
data class AlbumPage(val items: List<AlbumRef>, val total: Int)
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import androidx.compose.foundation.background
|
|||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
import androidx.compose.foundation.layout.PaddingValues
|
|
||||||
import androidx.compose.foundation.layout.Row
|
import androidx.compose.foundation.layout.Row
|
||||||
import androidx.compose.foundation.layout.Spacer
|
import androidx.compose.foundation.layout.Spacer
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
@@ -52,6 +51,7 @@ import com.fabledsword.minstrel.models.TrackRef
|
|||||||
import com.fabledsword.minstrel.nav.AlbumDetail
|
import com.fabledsword.minstrel.nav.AlbumDetail
|
||||||
import com.fabledsword.minstrel.nav.ArtistDetail
|
import com.fabledsword.minstrel.nav.ArtistDetail
|
||||||
import com.fabledsword.minstrel.shared.formatDuration
|
import com.fabledsword.minstrel.shared.formatDuration
|
||||||
|
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
|
||||||
import com.fabledsword.minstrel.shared.widgets.TrackRow
|
import com.fabledsword.minstrel.shared.widgets.TrackRow
|
||||||
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
|
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
|
||||||
import com.fabledsword.minstrel.shared.widgets.LikeButton
|
import com.fabledsword.minstrel.shared.widgets.LikeButton
|
||||||
@@ -70,6 +70,7 @@ fun AlbumDetailScreen(
|
|||||||
) {
|
) {
|
||||||
val state by viewModel.uiState.collectAsStateWithLifecycle()
|
val state by viewModel.uiState.collectAsStateWithLifecycle()
|
||||||
Scaffold(
|
Scaffold(
|
||||||
|
contentWindowInsets = ShellContentWindowInsets,
|
||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.fillMaxSize(),
|
||||||
topBar = {
|
topBar = {
|
||||||
TopAppBar(
|
TopAppBar(
|
||||||
@@ -165,7 +166,6 @@ private fun AlbumBody(
|
|||||||
) {
|
) {
|
||||||
LazyColumn(
|
LazyColumn(
|
||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.fillMaxSize(),
|
||||||
contentPadding = PaddingValues(bottom = 140.dp),
|
|
||||||
) {
|
) {
|
||||||
item {
|
item {
|
||||||
AlbumHeader(
|
AlbumHeader(
|
||||||
|
|||||||
@@ -56,6 +56,7 @@ import com.fabledsword.minstrel.models.albumCoverPath
|
|||||||
import com.fabledsword.minstrel.nav.AlbumDetail
|
import com.fabledsword.minstrel.nav.AlbumDetail
|
||||||
import com.fabledsword.minstrel.nav.ArtistDetail
|
import com.fabledsword.minstrel.nav.ArtistDetail
|
||||||
import com.fabledsword.minstrel.shared.formatDuration
|
import com.fabledsword.minstrel.shared.formatDuration
|
||||||
|
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
|
||||||
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
|
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
|
||||||
import com.fabledsword.minstrel.shared.widgets.HorizontalScrollRow
|
import com.fabledsword.minstrel.shared.widgets.HorizontalScrollRow
|
||||||
import com.fabledsword.minstrel.shared.widgets.LikeButton
|
import com.fabledsword.minstrel.shared.widgets.LikeButton
|
||||||
@@ -79,6 +80,7 @@ fun ArtistDetailScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Scaffold(
|
Scaffold(
|
||||||
|
contentWindowInsets = ShellContentWindowInsets,
|
||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.fillMaxSize(),
|
||||||
topBar = {
|
topBar = {
|
||||||
TopAppBar(
|
TopAppBar(
|
||||||
|
|||||||
@@ -0,0 +1,271 @@
|
|||||||
|
package com.fabledsword.minstrel.library.ui
|
||||||
|
|
||||||
|
import androidx.lifecycle.ViewModel
|
||||||
|
import androidx.lifecycle.viewModelScope
|
||||||
|
import com.fabledsword.minstrel.api.ErrorCopy
|
||||||
|
import com.fabledsword.minstrel.library.data.AlbumPage
|
||||||
|
import com.fabledsword.minstrel.library.data.GenreCount
|
||||||
|
import com.fabledsword.minstrel.library.data.LibraryRepository
|
||||||
|
import com.fabledsword.minstrel.library.data.YearCount
|
||||||
|
import com.fabledsword.minstrel.models.AlbumRef
|
||||||
|
import com.fabledsword.minstrel.shared.UiState
|
||||||
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import javax.inject.Inject
|
||||||
|
|
||||||
|
/** How the genre index is ordered. */
|
||||||
|
enum class GenreSort {
|
||||||
|
/** Server order: track count descending, name breaking ties. */
|
||||||
|
COUNT,
|
||||||
|
|
||||||
|
/** Alphabetical, case-insensitive. */
|
||||||
|
NAME,
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Albums for whichever genre or year is currently drilled into.
|
||||||
|
*
|
||||||
|
* [total] is the server's count for the whole filter, not the loaded slice,
|
||||||
|
* so the UI can say how many are left instead of only offering "more".
|
||||||
|
*/
|
||||||
|
data class AlbumBrowseState(
|
||||||
|
val albums: List<AlbumRef> = emptyList(),
|
||||||
|
val total: Int = 0,
|
||||||
|
val loading: Boolean = false,
|
||||||
|
val failed: Boolean = false,
|
||||||
|
) {
|
||||||
|
val hasMore: Boolean get() = albums.size < total
|
||||||
|
val remaining: Int get() = (total - albums.size).coerceAtLeast(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Backs the Genres and Years tabs (#2467), mirroring the web surfaces #367
|
||||||
|
* shipped.
|
||||||
|
*
|
||||||
|
* Both indexes come from the server, which is a deliberate departure from the
|
||||||
|
* cache-first Artists/Albums tabs beside them: the local cache includes tracks
|
||||||
|
* whose files are missing and cannot tell you which (#2704), while the server's
|
||||||
|
* index excludes them, so a locally-derived index would disagree with the web
|
||||||
|
* client's. These two tabs therefore need a connection; the empty states say so
|
||||||
|
* rather than looking broken.
|
||||||
|
*/
|
||||||
|
// Two browse axes, each with an index, a filter/sort or grouping, a
|
||||||
|
// drill-down and a pager. The function count is two axes' worth of a
|
||||||
|
// cohesive surface; splitting into GenresViewModel + YearsViewModel would
|
||||||
|
// duplicate the shared paging body for no gain.
|
||||||
|
@Suppress("TooManyFunctions")
|
||||||
|
@HiltViewModel
|
||||||
|
class BrowseViewModel @Inject constructor(
|
||||||
|
private val repository: LibraryRepository,
|
||||||
|
) : ViewModel() {
|
||||||
|
|
||||||
|
private val genresInternal = MutableStateFlow<UiState<List<GenreCount>>>(UiState.Loading)
|
||||||
|
val genres: StateFlow<UiState<List<GenreCount>>> = genresInternal.asStateFlow()
|
||||||
|
|
||||||
|
private val yearsInternal = MutableStateFlow<UiState<List<YearCount>>>(UiState.Loading)
|
||||||
|
val years: StateFlow<UiState<List<YearCount>>> = yearsInternal.asStateFlow()
|
||||||
|
|
||||||
|
private val genreFilterInternal = MutableStateFlow("")
|
||||||
|
val genreFilter: StateFlow<String> = genreFilterInternal.asStateFlow()
|
||||||
|
|
||||||
|
private val genreSortInternal = MutableStateFlow(GenreSort.COUNT)
|
||||||
|
val genreSort: StateFlow<GenreSort> = genreSortInternal.asStateFlow()
|
||||||
|
|
||||||
|
private val selectedGenreInternal = MutableStateFlow<String?>(null)
|
||||||
|
val selectedGenre: StateFlow<String?> = selectedGenreInternal.asStateFlow()
|
||||||
|
|
||||||
|
private val selectedYearInternal = MutableStateFlow<Int?>(null)
|
||||||
|
val selectedYear: StateFlow<Int?> = selectedYearInternal.asStateFlow()
|
||||||
|
|
||||||
|
private val genreAlbumsInternal = MutableStateFlow(AlbumBrowseState())
|
||||||
|
val genreAlbums: StateFlow<AlbumBrowseState> = genreAlbumsInternal.asStateFlow()
|
||||||
|
|
||||||
|
private val yearAlbumsInternal = MutableStateFlow(AlbumBrowseState())
|
||||||
|
val yearAlbums: StateFlow<AlbumBrowseState> = yearAlbumsInternal.asStateFlow()
|
||||||
|
|
||||||
|
// Guards against a slow response for a previously-selected genre/year
|
||||||
|
// landing after the user has moved on and painting over the new list.
|
||||||
|
// One counter per axis, since the two drill-downs are independent.
|
||||||
|
private var genreRequestToken = 0
|
||||||
|
private var yearRequestToken = 0
|
||||||
|
|
||||||
|
init {
|
||||||
|
loadGenres()
|
||||||
|
loadYears()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun loadGenres() {
|
||||||
|
viewModelScope.launch {
|
||||||
|
genresInternal.value = UiState.Loading
|
||||||
|
genresInternal.value = runCatching { repository.genres() }.fold(
|
||||||
|
onSuccess = { if (it.isEmpty()) UiState.Empty else UiState.Success(it) },
|
||||||
|
onFailure = { UiState.Error(ErrorCopy.fromThrowable(it)) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun loadYears() {
|
||||||
|
viewModelScope.launch {
|
||||||
|
yearsInternal.value = UiState.Loading
|
||||||
|
yearsInternal.value = runCatching { repository.albumYears() }.fold(
|
||||||
|
onSuccess = { if (it.isEmpty()) UiState.Empty else UiState.Success(it) },
|
||||||
|
onFailure = { UiState.Error(ErrorCopy.fromThrowable(it)) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setGenreFilter(value: String) { genreFilterInternal.value = value }
|
||||||
|
|
||||||
|
fun setGenreSort(sort: GenreSort) { genreSortInternal.value = sort }
|
||||||
|
|
||||||
|
/** Drill into [genre], or pass null to go back to the index. */
|
||||||
|
fun selectGenre(genre: String?) {
|
||||||
|
selectedGenreInternal.value = genre
|
||||||
|
genreRequestToken += 1
|
||||||
|
genreAlbumsInternal.value = AlbumBrowseState()
|
||||||
|
if (genre == null) return
|
||||||
|
fetchGenrePage(genre, offset = 0, token = genreRequestToken)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun loadMoreGenreAlbums() {
|
||||||
|
val genre = selectedGenreInternal.value ?: return
|
||||||
|
val state = genreAlbumsInternal.value
|
||||||
|
if (state.loading || !state.hasMore) return
|
||||||
|
fetchGenrePage(genre, offset = state.albums.size, token = genreRequestToken)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun retryGenreAlbums() {
|
||||||
|
selectedGenreInternal.value?.let { selectGenre(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Drill into [year], or pass null to go back to the index. */
|
||||||
|
fun selectYear(year: Int?) {
|
||||||
|
selectedYearInternal.value = year
|
||||||
|
yearRequestToken += 1
|
||||||
|
yearAlbumsInternal.value = AlbumBrowseState()
|
||||||
|
if (year == null) return
|
||||||
|
fetchYearPage(year, offset = 0, token = yearRequestToken)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun loadMoreYearAlbums() {
|
||||||
|
val year = selectedYearInternal.value ?: return
|
||||||
|
val state = yearAlbumsInternal.value
|
||||||
|
if (state.loading || !state.hasMore) return
|
||||||
|
fetchYearPage(year, offset = state.albums.size, token = yearRequestToken)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun retryYearAlbums() {
|
||||||
|
selectedYearInternal.value?.let { selectYear(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun fetchGenrePage(genre: String, offset: Int, token: Int) {
|
||||||
|
fetchPage(
|
||||||
|
state = genreAlbumsInternal,
|
||||||
|
offset = offset,
|
||||||
|
isCurrent = { token == genreRequestToken },
|
||||||
|
fetch = { repository.albumsByGenre(genre, PAGE_SIZE, offset) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun fetchYearPage(year: Int, offset: Int, token: Int) {
|
||||||
|
fetchPage(
|
||||||
|
state = yearAlbumsInternal,
|
||||||
|
offset = offset,
|
||||||
|
isCurrent = { token == yearRequestToken },
|
||||||
|
fetch = { repository.albumsByYear(year, PAGE_SIZE, offset) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The paging body both axes share: append on success, and drop the result
|
||||||
|
* entirely if the selection moved while the request was in flight.
|
||||||
|
*/
|
||||||
|
private fun fetchPage(
|
||||||
|
state: MutableStateFlow<AlbumBrowseState>,
|
||||||
|
offset: Int,
|
||||||
|
isCurrent: () -> Boolean,
|
||||||
|
fetch: suspend () -> AlbumPage,
|
||||||
|
) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
state.value = state.value.copy(loading = true, failed = false)
|
||||||
|
runCatching { fetch() }.fold(
|
||||||
|
onSuccess = { page ->
|
||||||
|
if (!isCurrent()) return@launch
|
||||||
|
val merged =
|
||||||
|
if (offset == 0) page.items else state.value.albums + page.items
|
||||||
|
state.value = AlbumBrowseState(
|
||||||
|
albums = merged,
|
||||||
|
total = page.total,
|
||||||
|
loading = false,
|
||||||
|
failed = false,
|
||||||
|
)
|
||||||
|
},
|
||||||
|
onFailure = {
|
||||||
|
if (!isCurrent()) return@launch
|
||||||
|
state.value = state.value.copy(loading = false, failed = true)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
// Matches the web client's BROWSE_PAGE_SIZE so "Load more (N left)"
|
||||||
|
// steps at the same rate on both clients.
|
||||||
|
const val PAGE_SIZE = 50
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Apply the current filter and sort to a genre index.
|
||||||
|
*
|
||||||
|
* Pure so the ordering rules are testable without a ViewModel. Sorting copies
|
||||||
|
* first: the input is the list held in the loaded state, and sorting in place
|
||||||
|
* would reorder what every other reader sees.
|
||||||
|
*/
|
||||||
|
fun visibleGenres(
|
||||||
|
genres: List<GenreCount>,
|
||||||
|
filter: String,
|
||||||
|
sort: GenreSort,
|
||||||
|
): List<GenreCount> {
|
||||||
|
val q = filter.trim()
|
||||||
|
val matched =
|
||||||
|
if (q.isEmpty()) genres else genres.filter { it.genre.contains(q, ignoreCase = true) }
|
||||||
|
return when (sort) {
|
||||||
|
// Server order is already count DESC then name; don't re-sort it.
|
||||||
|
GenreSort.COUNT -> matched
|
||||||
|
GenreSort.NAME -> matched.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.genre })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Integer division by this floors a year to its decade: 2007 -> 2000. Named
|
||||||
|
// because detekt counts it as magic, and because the arithmetic reads as
|
||||||
|
// arbitrary otherwise.
|
||||||
|
private const val YEARS_PER_DECADE = 10
|
||||||
|
|
||||||
|
/** A decade's worth of the year index, newest year first. */
|
||||||
|
data class DecadeGroup(
|
||||||
|
val decade: Int,
|
||||||
|
val years: List<YearCount>,
|
||||||
|
val albumCount: Int,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Group the year index by decade, newest first.
|
||||||
|
*
|
||||||
|
* A flat list of every year in a decades-deep library is a wall of numbers, and
|
||||||
|
* the decade is usually how someone actually thinks about it. Pure, for the
|
||||||
|
* same reason as [visibleGenres].
|
||||||
|
*/
|
||||||
|
fun groupByDecade(years: List<YearCount>): List<DecadeGroup> =
|
||||||
|
years.groupBy { (it.year / YEARS_PER_DECADE) * YEARS_PER_DECADE }
|
||||||
|
.map { (decade, entries) ->
|
||||||
|
DecadeGroup(
|
||||||
|
decade = decade,
|
||||||
|
years = entries.sortedByDescending { it.year },
|
||||||
|
albumCount = entries.sumOf { it.albumCount },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
.sortedByDescending { it.decade }
|
||||||
@@ -0,0 +1,341 @@
|
|||||||
|
package com.fabledsword.minstrel.library.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.PaddingValues
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.lazy.grid.GridCells
|
||||||
|
import androidx.compose.foundation.lazy.grid.GridItemSpan
|
||||||
|
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
|
||||||
|
import androidx.compose.foundation.lazy.grid.items
|
||||||
|
import androidx.compose.material3.FilterChip
|
||||||
|
import androidx.compose.material3.HorizontalDivider
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
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 com.composables.icons.lucide.ArrowLeft
|
||||||
|
import com.composables.icons.lucide.Lucide
|
||||||
|
import com.composables.icons.lucide.LibraryBig
|
||||||
|
import com.fabledsword.minstrel.library.widgets.AlbumCard
|
||||||
|
import com.fabledsword.minstrel.models.AlbumRef
|
||||||
|
import com.fabledsword.minstrel.shared.UiState
|
||||||
|
import com.fabledsword.minstrel.shared.widgets.EmptyState
|
||||||
|
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Genres tab (#2467) — the Android half of the browse axis #367 shipped on web.
|
||||||
|
*
|
||||||
|
* Two states in one tab rather than a navigation destination: the index, and
|
||||||
|
* the albums for a chosen genre. Back returns to the index. A route would have
|
||||||
|
* meant carrying the genre in the path, and "Rock/Pop" is a real ID3 tag whose
|
||||||
|
* slash a path segment cannot carry — the same reason the server takes it as a
|
||||||
|
* query parameter.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun GenresTab(
|
||||||
|
onAlbumClick: (String) -> Unit,
|
||||||
|
viewModel: BrowseViewModel = hiltViewModel(),
|
||||||
|
) {
|
||||||
|
val selected by viewModel.selectedGenre.collectAsStateWithLifecycle()
|
||||||
|
val genre = selected
|
||||||
|
if (genre == null) {
|
||||||
|
GenreIndex(viewModel = viewModel)
|
||||||
|
} else {
|
||||||
|
GenreAlbums(
|
||||||
|
genre = genre,
|
||||||
|
viewModel = viewModel,
|
||||||
|
onAlbumClick = onAlbumClick,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun GenreIndex(viewModel: BrowseViewModel) {
|
||||||
|
val state by viewModel.genres.collectAsStateWithLifecycle()
|
||||||
|
val filter by viewModel.genreFilter.collectAsStateWithLifecycle()
|
||||||
|
val sort by viewModel.genreSort.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
|
when (val s = state) {
|
||||||
|
UiState.Loading -> EmptyState(
|
||||||
|
title = "Reading your genres…",
|
||||||
|
body = "",
|
||||||
|
icon = Lucide.LibraryBig,
|
||||||
|
)
|
||||||
|
UiState.Empty -> EmptyState(
|
||||||
|
title = "No genres found",
|
||||||
|
body = "Genres come from the genre tag on your audio files. If your " +
|
||||||
|
"library is tagged but this is empty, try a rescan from the admin " +
|
||||||
|
"screen.",
|
||||||
|
icon = Lucide.LibraryBig,
|
||||||
|
)
|
||||||
|
is UiState.Error -> ErrorRetry(
|
||||||
|
message = s.message,
|
||||||
|
onRetry = viewModel::loadGenres,
|
||||||
|
)
|
||||||
|
is UiState.Success -> {
|
||||||
|
val visible = visibleGenres(s.data, filter, sort)
|
||||||
|
Column(modifier = Modifier.fillMaxSize()) {
|
||||||
|
GenreIndexControls(
|
||||||
|
total = s.data.size,
|
||||||
|
shown = visible.size,
|
||||||
|
filter = filter,
|
||||||
|
sort = sort,
|
||||||
|
onFilterChange = viewModel::setGenreFilter,
|
||||||
|
onSortChange = viewModel::setGenreSort,
|
||||||
|
)
|
||||||
|
if (visible.isEmpty()) {
|
||||||
|
EmptyState(
|
||||||
|
title = "No genres match \"${filter.trim()}\"",
|
||||||
|
body = "Try a shorter search.",
|
||||||
|
icon = Lucide.LibraryBig,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
LazyColumn(modifier = Modifier.fillMaxSize()) {
|
||||||
|
items(items = visible, key = { it.genre }) { row ->
|
||||||
|
GenreRow(
|
||||||
|
genre = row.genre,
|
||||||
|
trackCount = row.trackCount,
|
||||||
|
onClick = { viewModel.selectGenre(row.genre) },
|
||||||
|
)
|
||||||
|
HorizontalDivider()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun GenreIndexControls(
|
||||||
|
total: Int,
|
||||||
|
shown: Int,
|
||||||
|
filter: String,
|
||||||
|
sort: GenreSort,
|
||||||
|
onFilterChange: (String) -> Unit,
|
||||||
|
onSortChange: (GenreSort) -> Unit,
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp)) {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = filter,
|
||||||
|
onValueChange = onFilterChange,
|
||||||
|
label = { Text("Filter genres") },
|
||||||
|
singleLine = true,
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
)
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
// Count-first is the default because the head of that list is
|
||||||
|
// genuinely where you are going; raw tags carry a long tail of
|
||||||
|
// one-offs that A-Z would bury the real genres under. A-Z is here
|
||||||
|
// for when you already know roughly what it is called.
|
||||||
|
FilterChip(
|
||||||
|
selected = sort == GenreSort.COUNT,
|
||||||
|
onClick = { onSortChange(GenreSort.COUNT) },
|
||||||
|
label = { Text("Most tracks") },
|
||||||
|
)
|
||||||
|
FilterChip(
|
||||||
|
selected = sort == GenreSort.NAME,
|
||||||
|
onClick = { onSortChange(GenreSort.NAME) },
|
||||||
|
label = { Text("A–Z") },
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = if (filter.isBlank()) {
|
||||||
|
"$total genres"
|
||||||
|
} else {
|
||||||
|
"$shown of $total"
|
||||||
|
},
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun GenreRow(genre: String, trackCount: Int, onClick: () -> Unit) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.clickable(onClick = onClick)
|
||||||
|
.padding(horizontal = 16.dp, vertical = 14.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = genre,
|
||||||
|
style = MaterialTheme.typography.bodyLarge,
|
||||||
|
color = MaterialTheme.colorScheme.onSurface,
|
||||||
|
maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = "$trackCount",
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun GenreAlbums(
|
||||||
|
genre: String,
|
||||||
|
viewModel: BrowseViewModel,
|
||||||
|
onAlbumClick: (String) -> Unit,
|
||||||
|
) {
|
||||||
|
val albums by viewModel.genreAlbums.collectAsStateWithLifecycle()
|
||||||
|
BrowseAlbumResults(
|
||||||
|
heading = genre,
|
||||||
|
subtitle = albumCountLabel(albums.total, albums.loading, albums.albums.size),
|
||||||
|
state = albums,
|
||||||
|
emptyTitle = "No albums for this genre",
|
||||||
|
emptyBody = "The library may have been rescanned since this list was built.",
|
||||||
|
onBack = { viewModel.selectGenre(null) },
|
||||||
|
onRetry = viewModel::retryGenreAlbums,
|
||||||
|
onLoadMore = viewModel::loadMoreGenreAlbums,
|
||||||
|
onAlbumClick = onAlbumClick,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shared results pane for both browse axes: a back affordance, a heading, the
|
||||||
|
* album grid, and the load-more footer. Genres and Years differ only in their
|
||||||
|
* heading and copy, so the layout lives once.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
@Suppress("LongParameterList") // one presentational surface; all of it varies by axis
|
||||||
|
fun BrowseAlbumResults(
|
||||||
|
heading: String,
|
||||||
|
subtitle: String,
|
||||||
|
state: AlbumBrowseState,
|
||||||
|
emptyTitle: String,
|
||||||
|
emptyBody: String,
|
||||||
|
onBack: () -> Unit,
|
||||||
|
onRetry: () -> Unit,
|
||||||
|
onLoadMore: () -> Unit,
|
||||||
|
onAlbumClick: (String) -> Unit,
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.fillMaxSize()) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth().padding(start = 4.dp, end = 12.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
IconButton(onClick = onBack) {
|
||||||
|
Icon(Lucide.ArrowLeft, contentDescription = "Back to the index")
|
||||||
|
}
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text(
|
||||||
|
text = heading,
|
||||||
|
style = MaterialTheme.typography.titleMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurface,
|
||||||
|
maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
)
|
||||||
|
if (subtitle.isNotEmpty()) {
|
||||||
|
Text(
|
||||||
|
text = subtitle,
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
when {
|
||||||
|
state.failed && state.albums.isEmpty() -> ErrorRetry(
|
||||||
|
message = "Couldn't load albums.",
|
||||||
|
onRetry = onRetry,
|
||||||
|
)
|
||||||
|
state.loading && state.albums.isEmpty() -> EmptyState(
|
||||||
|
title = "Loading…",
|
||||||
|
body = "",
|
||||||
|
)
|
||||||
|
state.albums.isEmpty() -> EmptyState(title = emptyTitle, body = emptyBody)
|
||||||
|
else -> BrowseAlbumGrid(
|
||||||
|
state = state,
|
||||||
|
onLoadMore = onLoadMore,
|
||||||
|
onAlbumClick = onAlbumClick,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun BrowseAlbumGrid(
|
||||||
|
state: AlbumBrowseState,
|
||||||
|
onLoadMore: () -> Unit,
|
||||||
|
onAlbumClick: (String) -> Unit,
|
||||||
|
) {
|
||||||
|
LazyVerticalGrid(
|
||||||
|
// Same 176dp cell as the Albums tab, so a genre's grid and the full
|
||||||
|
// album grid line up rather than each inventing a column count.
|
||||||
|
columns = GridCells.Adaptive(minSize = 176.dp),
|
||||||
|
contentPadding = PaddingValues(8.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
) {
|
||||||
|
items(items = state.albums, key = { it.id }) { album: AlbumRef ->
|
||||||
|
AlbumCard(album = album, onClick = { onAlbumClick(album.id) })
|
||||||
|
}
|
||||||
|
item(span = { GridItemSpan(maxLineSpan) }) {
|
||||||
|
Box(
|
||||||
|
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
if (state.hasMore) {
|
||||||
|
// Explicit rather than infinite scroll, matching web: the
|
||||||
|
// remaining count is useful, and a browse axis is a place
|
||||||
|
// people skim rather than fall through.
|
||||||
|
TextButton(onClick = onLoadMore, enabled = !state.loading) {
|
||||||
|
Text(
|
||||||
|
if (state.loading) {
|
||||||
|
"Loading…"
|
||||||
|
} else {
|
||||||
|
"Load more (${state.remaining} left)"
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Text(
|
||||||
|
text = "That's everything",
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* "12 albums" once the total is known, and nothing at all while the first page
|
||||||
|
* is still in flight — a count that appears as 0 and then corrects itself reads
|
||||||
|
* as a bug.
|
||||||
|
*/
|
||||||
|
internal fun albumCountLabel(total: Int, loading: Boolean, loaded: Int): String = when {
|
||||||
|
loading && loaded == 0 -> ""
|
||||||
|
total == 1 -> "1 album"
|
||||||
|
else -> "$total albums"
|
||||||
|
}
|
||||||
@@ -43,6 +43,7 @@ import com.fabledsword.minstrel.nav.Library
|
|||||||
import com.composables.icons.lucide.Lucide
|
import com.composables.icons.lucide.Lucide
|
||||||
import com.composables.icons.lucide.Shuffle
|
import com.composables.icons.lucide.Shuffle
|
||||||
import com.fabledsword.minstrel.shared.UiState
|
import com.fabledsword.minstrel.shared.UiState
|
||||||
|
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
|
||||||
import com.fabledsword.minstrel.shared.widgets.EmptyState
|
import com.fabledsword.minstrel.shared.widgets.EmptyState
|
||||||
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
|
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
|
||||||
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
|
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
|
||||||
@@ -51,8 +52,10 @@ import com.fabledsword.minstrel.shared.widgets.SkeletonAlbumTile
|
|||||||
import com.fabledsword.minstrel.shared.widgets.SkeletonArtistTile
|
import com.fabledsword.minstrel.shared.widgets.SkeletonArtistTile
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Library tab. Five-tab TabBar (Artists / Albums / History / Liked /
|
* Library tab. Seven-tab TabBar (Artists / Albums / Genres / Years /
|
||||||
* Hidden) matching `flutter_client/lib/library/library_screen.dart`.
|
* History / Liked / Hidden), matching the web client's library tab bar.
|
||||||
|
* Genres and Years arrived with #2467; the rest predate it and mirrored
|
||||||
|
* the Flutter client.
|
||||||
*
|
*
|
||||||
* Artists + Albums are wired against the existing LibraryViewModel
|
* Artists + Albums are wired against the existing LibraryViewModel
|
||||||
* (cache-first reads of cached_artists / cached_albums). The other
|
* (cache-first reads of cached_artists / cached_albums). The other
|
||||||
@@ -77,6 +80,7 @@ fun LibraryScreen(
|
|||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
|
|
||||||
Scaffold(
|
Scaffold(
|
||||||
|
contentWindowInsets = ShellContentWindowInsets,
|
||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.fillMaxSize(),
|
||||||
topBar = {
|
topBar = {
|
||||||
Column {
|
Column {
|
||||||
@@ -113,9 +117,31 @@ fun LibraryScreen(
|
|||||||
state = pagerState,
|
state = pagerState,
|
||||||
modifier = Modifier.fillMaxSize().padding(inner),
|
modifier = Modifier.fillMaxSize().padding(inner),
|
||||||
) { page ->
|
) { page ->
|
||||||
|
LibraryTabPage(page = page, viewModel = viewModel, navController = navController)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The pager's page bodies, split out of [LibraryScreen] so the screen stays
|
||||||
|
* the scaffold + tab bar and this stays the routing table. Adding a tab is
|
||||||
|
* then one line here and one label in [LIBRARY_TABS].
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
private fun LibraryTabPage(
|
||||||
|
page: Int,
|
||||||
|
viewModel: LibraryViewModel,
|
||||||
|
navController: NavHostController,
|
||||||
|
) {
|
||||||
when (page) {
|
when (page) {
|
||||||
TAB_ARTISTS -> ArtistsTab(viewModel = viewModel, navController = navController)
|
TAB_ARTISTS -> ArtistsTab(viewModel = viewModel, navController = navController)
|
||||||
TAB_ALBUMS -> AlbumsTab(viewModel = viewModel, navController = navController)
|
TAB_ALBUMS -> AlbumsTab(viewModel = viewModel, navController = navController)
|
||||||
|
TAB_GENRES -> GenresTab(
|
||||||
|
onAlbumClick = { id -> navController.navigate(AlbumDetail(id)) },
|
||||||
|
)
|
||||||
|
TAB_YEARS -> YearsTab(
|
||||||
|
onAlbumClick = { id -> navController.navigate(AlbumDetail(id)) },
|
||||||
|
)
|
||||||
TAB_HISTORY -> HistoryTab(
|
TAB_HISTORY -> HistoryTab(
|
||||||
onNavigateToAlbum = { id -> navController.navigate(AlbumDetail(id)) },
|
onNavigateToAlbum = { id -> navController.navigate(AlbumDetail(id)) },
|
||||||
onNavigateToArtist = { id -> navController.navigate(ArtistDetail(id)) },
|
onNavigateToArtist = { id -> navController.navigate(ArtistDetail(id)) },
|
||||||
@@ -123,17 +149,21 @@ fun LibraryScreen(
|
|||||||
TAB_LIKED -> LikedTab(navController = navController)
|
TAB_LIKED -> LikedTab(navController = navController)
|
||||||
TAB_HIDDEN -> HiddenTab()
|
TAB_HIDDEN -> HiddenTab()
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private const val TAB_ARTISTS = 0
|
private const val TAB_ARTISTS = 0
|
||||||
private const val TAB_ALBUMS = 1
|
private const val TAB_ALBUMS = 1
|
||||||
private const val TAB_HISTORY = 2
|
private const val TAB_GENRES = 2
|
||||||
private const val TAB_LIKED = 3
|
private const val TAB_YEARS = 3
|
||||||
private const val TAB_HIDDEN = 4
|
private const val TAB_HISTORY = 4
|
||||||
|
private const val TAB_LIKED = 5
|
||||||
|
private const val TAB_HIDDEN = 6
|
||||||
|
|
||||||
private val LIBRARY_TABS = listOf("Artists", "Albums", "History", "Liked", "Hidden")
|
// Genres and Years sit straight after Albums, matching the web tab bar's
|
||||||
|
// order (#2467) -- they are browse axes over the same albums, so they belong
|
||||||
|
// beside them rather than after the personal tabs.
|
||||||
|
private val LIBRARY_TABS =
|
||||||
|
listOf("Artists", "Albums", "Genres", "Years", "History", "Liked", "Hidden")
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun ArtistsTab(
|
private fun ArtistsTab(
|
||||||
|
|||||||
@@ -0,0 +1,161 @@
|
|||||||
|
package com.fabledsword.minstrel.library.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.PaddingValues
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.material3.HorizontalDivider
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.hilt.navigation.compose.hiltViewModel
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import com.composables.icons.lucide.Clock
|
||||||
|
import com.composables.icons.lucide.Lucide
|
||||||
|
import com.fabledsword.minstrel.shared.UiState
|
||||||
|
import com.fabledsword.minstrel.shared.widgets.EmptyState
|
||||||
|
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Years tab (#2467). Same two-state shape as [GenresTab]: the decade-grouped
|
||||||
|
* index, then the albums for a chosen year.
|
||||||
|
*
|
||||||
|
* Albums with no release date are absent from this axis entirely — the server
|
||||||
|
* leaves them out rather than inventing a year-0 bucket, and the empty state
|
||||||
|
* says so, because "my albums aren't here" otherwise looks like a bug.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun YearsTab(
|
||||||
|
onAlbumClick: (String) -> Unit,
|
||||||
|
viewModel: BrowseViewModel = hiltViewModel(),
|
||||||
|
) {
|
||||||
|
val selected by viewModel.selectedYear.collectAsStateWithLifecycle()
|
||||||
|
val year = selected
|
||||||
|
if (year == null) {
|
||||||
|
YearIndex(viewModel = viewModel)
|
||||||
|
} else {
|
||||||
|
YearAlbums(year = year, viewModel = viewModel, onAlbumClick = onAlbumClick)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun YearIndex(viewModel: BrowseViewModel) {
|
||||||
|
val state by viewModel.years.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
|
when (val s = state) {
|
||||||
|
UiState.Loading -> EmptyState(
|
||||||
|
title = "Reading release years…",
|
||||||
|
body = "",
|
||||||
|
icon = Lucide.Clock,
|
||||||
|
)
|
||||||
|
UiState.Empty -> EmptyState(
|
||||||
|
title = "No release years found",
|
||||||
|
body = "Years come from the release date on your albums. Albums " +
|
||||||
|
"without one don't appear on this axis at all.",
|
||||||
|
icon = Lucide.Clock,
|
||||||
|
)
|
||||||
|
is UiState.Error -> ErrorRetry(
|
||||||
|
message = s.message,
|
||||||
|
onRetry = viewModel::loadYears,
|
||||||
|
)
|
||||||
|
is UiState.Success -> {
|
||||||
|
val decades = groupByDecade(s.data)
|
||||||
|
LazyColumn(
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
contentPadding = PaddingValues(vertical = 8.dp),
|
||||||
|
) {
|
||||||
|
decades.forEach { group ->
|
||||||
|
item(key = "decade-${group.decade}") {
|
||||||
|
DecadeHeader(decade = group.decade, albumCount = group.albumCount)
|
||||||
|
}
|
||||||
|
items(
|
||||||
|
count = group.years.size,
|
||||||
|
key = { i -> "year-${group.years[i].year}" },
|
||||||
|
) { i ->
|
||||||
|
val row = group.years[i]
|
||||||
|
YearRow(
|
||||||
|
year = row.year,
|
||||||
|
albumCount = row.albumCount,
|
||||||
|
onClick = { viewModel.selectYear(row.year) },
|
||||||
|
)
|
||||||
|
HorizontalDivider()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun DecadeHeader(decade: Int, albumCount: Int) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(horizontal = 16.dp, vertical = 10.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "${decade}s",
|
||||||
|
style = MaterialTheme.typography.titleSmall,
|
||||||
|
color = MaterialTheme.colorScheme.primary,
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = albumCountLabel(albumCount, loading = false, loaded = albumCount),
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun YearRow(year: Int, albumCount: Int, onClick: () -> Unit) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.clickable(onClick = onClick)
|
||||||
|
.padding(horizontal = 16.dp, vertical = 14.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "$year",
|
||||||
|
style = MaterialTheme.typography.bodyLarge,
|
||||||
|
color = MaterialTheme.colorScheme.onSurface,
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = "$albumCount",
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun YearAlbums(
|
||||||
|
year: Int,
|
||||||
|
viewModel: BrowseViewModel,
|
||||||
|
onAlbumClick: (String) -> Unit,
|
||||||
|
) {
|
||||||
|
val albums by viewModel.yearAlbums.collectAsStateWithLifecycle()
|
||||||
|
BrowseAlbumResults(
|
||||||
|
heading = "$year",
|
||||||
|
subtitle = albumCountLabel(albums.total, albums.loading, albums.albums.size),
|
||||||
|
state = albums,
|
||||||
|
emptyTitle = "No albums for $year",
|
||||||
|
emptyBody = "The library may have been rescanned since this list was built.",
|
||||||
|
onBack = { viewModel.selectYear(null) },
|
||||||
|
onRetry = viewModel::retryYearAlbums,
|
||||||
|
onLoadMore = viewModel::loadMoreYearAlbums,
|
||||||
|
onAlbumClick = onAlbumClick,
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -2,7 +2,7 @@ package com.fabledsword.minstrel.models
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Lightweight reference to one album. Mirrors
|
* Lightweight reference to one album. Mirrors
|
||||||
* `flutter_client/lib/models/album.dart`'s `AlbumRef`.
|
* the Flutter client's `AlbumRef`.
|
||||||
*
|
*
|
||||||
* `coverUrl` and `durationSec` match the server contract (not
|
* `coverUrl` and `durationSec` match the server contract (not
|
||||||
* `cover_art_url` / `duration_ms`). `year` is omitempty server-side so
|
* `cover_art_url` / `duration_ms`). `year` is omitempty server-side so
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ package com.fabledsword.minstrel.models
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Lightweight reference to one artist. Mirrors
|
* Lightweight reference to one artist. Mirrors
|
||||||
* `flutter_client/lib/models/artist.dart`'s `ArtistRef`.
|
* the Flutter client's `ArtistRef`.
|
||||||
*
|
*
|
||||||
* `coverUrl` is the server's field name (NOT cover_art_url). Server emits
|
* `coverUrl` is the server's field name (NOT cover_art_url). Server emits
|
||||||
* empty string when the artist has no representative album cover; UI code
|
* empty string when the artist has no representative album cover; UI code
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
package com.fabledsword.minstrel.models
|
package com.fabledsword.minstrel.models
|
||||||
|
|
||||||
|
import kotlinx.datetime.Instant
|
||||||
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Kind of Lidarr request being created. Wire form is the lowercase
|
* Kind of Lidarr request being created. Wire form is the lowercase
|
||||||
* enum name; the helper [wire] keeps that mapping in one place.
|
* enum name; the helper [wire] keeps that mapping in one place.
|
||||||
@@ -11,7 +14,7 @@ enum class LidarrRequestKind {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Lidarr search hit. Mirrors `flutter_client/lib/models/lidarr.dart`'s
|
* Lidarr search hit. Mirrors the Flutter client's
|
||||||
* `LidarrSearchResult` — `mbid` is the result's own MBID; `artistMbid`
|
* `LidarrSearchResult` — `mbid` is the result's own MBID; `artistMbid`
|
||||||
* and `albumMbid` are filled when the row is an album/track and the
|
* and `albumMbid` are filled when the row is an album/track and the
|
||||||
* UI needs the parent IDs to build the request.
|
* UI needs the parent IDs to build the request.
|
||||||
@@ -49,6 +52,8 @@ data class ArtistSuggestionRef(
|
|||||||
val name: String,
|
val name: String,
|
||||||
val imageUrl: String = "",
|
val imageUrl: String = "",
|
||||||
val attribution: List<SeedContributionRef> = emptyList(),
|
val attribution: List<SeedContributionRef> = emptyList(),
|
||||||
|
/** Taste-profile tags this candidate matches, strongest first (#2377). */
|
||||||
|
val matchedTags: List<String> = emptyList(),
|
||||||
) {
|
) {
|
||||||
val attributionText: String
|
val attributionText: String
|
||||||
get() {
|
get() {
|
||||||
@@ -63,7 +68,92 @@ data class ArtistSuggestionRef(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The subtitle line for the card.
|
||||||
|
*
|
||||||
|
* Prefers the taste-tag reason over seed attribution when we have one,
|
||||||
|
* because it describes the MUSIC ("sounds like what you like") rather than
|
||||||
|
* the graph ("adjacent to something you played") — the whole point of
|
||||||
|
* milestone #268 slice 6. Falls back to attribution, which is the common
|
||||||
|
* case: tag coverage for out-of-library artists is partial by nature
|
||||||
|
* (#2376), so most candidates have no matched tags.
|
||||||
|
*
|
||||||
|
* Kept in lockstep with the web client's reasonText() in
|
||||||
|
* SuggestionFeed.svelte — same wording, same Oxford comma.
|
||||||
|
*/
|
||||||
|
val reasonText: String
|
||||||
|
get() {
|
||||||
|
val tags = matchedTags.take(MAX_ATTRIBUTION_PHRASES)
|
||||||
|
return when (tags.size) {
|
||||||
|
0 -> attributionText
|
||||||
|
1 -> "Matches your taste in ${tags[0]}."
|
||||||
|
2 -> "Matches your taste in ${tags[0]} and ${tags[1]}."
|
||||||
|
else -> "Matches your taste in ${tags[0]}, ${tags[1]}, and ${tags[2]}."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
private const val MAX_ATTRIBUTION_PHRASES = 3
|
private const val MAX_ATTRIBUTION_PHRASES = 3
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A suggestion the user parked with "not right now" (#2374).
|
||||||
|
*
|
||||||
|
* Deliberately NOT a dislike: it carries no verdict on the artist, expires on
|
||||||
|
* its own, and never reaches the taste profile. Anything that treats this as
|
||||||
|
* negative preference signal is a bug.
|
||||||
|
*
|
||||||
|
* [snoozedUntil] is the raw RFC3339 string from the wire. Only the server
|
||||||
|
* decides whether a snooze is still in effect — every row the client receives
|
||||||
|
* already is — so this is read purely to phrase "back in about 3 months".
|
||||||
|
*/
|
||||||
|
data class SuggestionSnoozeRef(
|
||||||
|
val mbid: String,
|
||||||
|
val name: String,
|
||||||
|
val snoozedUntil: String,
|
||||||
|
) {
|
||||||
|
/**
|
||||||
|
* Relative return phrase for the manage list. Relative rather than a
|
||||||
|
* calendar date because the exact day a 90-day snooze lapses is noise the
|
||||||
|
* user never asked for.
|
||||||
|
*
|
||||||
|
* [nowMs] is injectable so this is testable without freezing the clock.
|
||||||
|
* Returns "shortly" for an unparseable or already-past timestamp: the row
|
||||||
|
* is on screen, so the server still considers it snoozed, and guessing is
|
||||||
|
* better than rendering an empty line.
|
||||||
|
*/
|
||||||
|
fun returnsIn(nowMs: Long = System.currentTimeMillis()): String {
|
||||||
|
val remainingMs = runCatching { Instant.parse(snoozedUntil).toEpochMilliseconds() }
|
||||||
|
.getOrNull()?.minus(nowMs)
|
||||||
|
// Two ways to have nothing to state: an unparseable timestamp, or one
|
||||||
|
// already lapsed by our clock though the server still returned the row
|
||||||
|
// (the two disagree). Neither is "today", which would read as a real
|
||||||
|
// prediction.
|
||||||
|
if (remainingMs == null || remainingMs <= 0) return "shortly"
|
||||||
|
val days = (remainingMs.toDouble() / MILLIS_PER_DAY).roundToInt()
|
||||||
|
return when {
|
||||||
|
days < 1 -> "today"
|
||||||
|
days == 1 -> "tomorrow"
|
||||||
|
days < DAYS_BEFORE_MONTHS -> "in $days days"
|
||||||
|
else -> {
|
||||||
|
val months = (days.toDouble() / DAYS_PER_MONTH).roundToInt()
|
||||||
|
if (months == 1) "in about a month" else "in about $months months"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val MILLIS_PER_DAY = 86_400_000.0
|
||||||
|
|
||||||
|
// Below this, days read more naturally than a rounded month count.
|
||||||
|
//
|
||||||
|
// Must be <= DAYS_PER_MONTH, or the singular "in about a month" is
|
||||||
|
// unreachable: a rounded month count of 1 needs 15..44 days, and any
|
||||||
|
// threshold above 30 sends all of those down the days branch instead.
|
||||||
|
// This was 45 and the singular branch was dead code — the unit test
|
||||||
|
// for it is what surfaced that.
|
||||||
|
const val DAYS_BEFORE_MONTHS = 30
|
||||||
|
const val DAYS_PER_MONTH = 30.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ package com.fabledsword.minstrel.models
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Domain shape for one admin-issued registration invite. Mirrors
|
* Domain shape for one admin-issued registration invite. Mirrors
|
||||||
* `flutter_client/lib/models/invite.dart Invite` and the server's
|
* the Flutter client's `Invite` and the server's
|
||||||
* `inviteResp` from `internal/api/admin_invites.go`.
|
* `inviteResp` from `internal/api/admin_invites.go`.
|
||||||
*
|
*
|
||||||
* `invitedBy` and `redeemedBy` are UUIDs of users (not usernames);
|
* `invitedBy` and `redeemedBy` are UUIDs of users (not usernames);
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ package com.fabledsword.minstrel.models
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Caller's ListenBrainz integration state. Mirrors
|
* Caller's ListenBrainz integration state. Mirrors
|
||||||
* `flutter_client/lib/models/my_profile.dart ListenBrainzStatus`
|
* the Flutter client's `ListenBrainzStatus`
|
||||||
* and the server's `listenBrainzResp`.
|
* and the server's `listenBrainzResp`.
|
||||||
*
|
*
|
||||||
* The token itself is never read back from the server — `tokenSet`
|
* The token itself is never read back from the server — `tokenSet`
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ package com.fabledsword.minstrel.models
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Lightweight reference to one playlist (user or system-generated).
|
* Lightweight reference to one playlist (user or system-generated).
|
||||||
* Mirrors `flutter_client/lib/models/playlist.dart`'s `Playlist`.
|
* Mirrors the Flutter client's `Playlist`.
|
||||||
*
|
*
|
||||||
* `systemVariant` discriminates user vs. system playlists — null for
|
* `systemVariant` discriminates user vs. system playlists — null for
|
||||||
* user-owned, one of "for_you" / "discover" / "songs_like_artist" / etc.
|
* user-owned, one of "for_you" / "discover" / "songs_like_artist" / etc.
|
||||||
@@ -47,7 +47,10 @@ data class PlaylistRef(
|
|||||||
* `trackId` and `streamUrl` are nullable because the upstream track can
|
* `trackId` and `streamUrl` are nullable because the upstream track can
|
||||||
* be removed from the library while the row stays in the playlist —
|
* be removed from the library while the row stays in the playlist —
|
||||||
* those tiles render grey + unplayable per Flutter's `isAvailable`
|
* those tiles render grey + unplayable per Flutter's `isAvailable`
|
||||||
* convention.
|
* convention. [unavailable] is the second, softer case: the track is
|
||||||
|
* still there but its file is missing. Both render grey and refuse to
|
||||||
|
* play; only the second is worth explaining to the user, because it
|
||||||
|
* can fix itself.
|
||||||
*/
|
*/
|
||||||
data class PlaylistTrackRef(
|
data class PlaylistTrackRef(
|
||||||
val position: Int,
|
val position: Int,
|
||||||
@@ -59,8 +62,21 @@ data class PlaylistTrackRef(
|
|||||||
val artistName: String = "",
|
val artistName: String = "",
|
||||||
val durationSec: Int = 0,
|
val durationSec: Int = 0,
|
||||||
val streamUrl: String? = null,
|
val streamUrl: String? = null,
|
||||||
|
/**
|
||||||
|
* The track is still in the library but its file is missing from
|
||||||
|
* disk (#2527). Unlike a null [trackId] this is expected to be
|
||||||
|
* temporary — the scanner clears it when the file returns, and
|
||||||
|
* adopts the row if it returns under a new name (#2528) — so the
|
||||||
|
* row keeps its identity, its likes and its play history.
|
||||||
|
*/
|
||||||
|
val unavailable: Boolean = false,
|
||||||
) {
|
) {
|
||||||
val isAvailable: Boolean get() = trackId != null
|
/**
|
||||||
|
* Playable-ness, covering both ways a row can outlive its audio.
|
||||||
|
* Everything that greys a row or refuses to queue it reads this, so
|
||||||
|
* neither concern has to be re-derived at a call site.
|
||||||
|
*/
|
||||||
|
val isAvailable: Boolean get() = trackId != null && !unavailable
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Cover URL derived from the parent album's `/api/albums/{id}/cover`
|
* Cover URL derived from the parent album's `/api/albums/{id}/cover`
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ enum class RequestStatus {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* One Lidarr request the user has submitted. Mirrors
|
* One Lidarr request the user has submitted. Mirrors
|
||||||
* `flutter_client/lib/models/admin_request.dart AdminRequest` —
|
* the Flutter client's `AdminRequest` —
|
||||||
* shared between the user-side `/api/requests` view and the admin
|
* shared between the user-side `/api/requests` view and the admin
|
||||||
* cross-user view since the wire shape is identical.
|
* cross-user view since the wire shape is identical.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -3,8 +3,7 @@ package com.fabledsword.minstrel.models
|
|||||||
/**
|
/**
|
||||||
* Caller's most recent system_playlist_runs state, driving the Home
|
* Caller's most recent system_playlist_runs state, driving the Home
|
||||||
* placeholder cards for not-yet-generated system playlists. Mirrors
|
* placeholder cards for not-yet-generated system playlists. Mirrors
|
||||||
* `flutter_client/lib/models/system_playlists_status.dart` and the
|
* the server's `systemPlaylistsStatusResp`.
|
||||||
* server's `systemPlaylistsStatusResp`.
|
|
||||||
*
|
*
|
||||||
* Zero values (inFlight=false, both timestamps null) mean the user
|
* Zero values (inFlight=false, both timestamps null) mean the user
|
||||||
* has never had a build attempted — the placeholders read as
|
* has never had a build attempted — the placeholders read as
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import kotlinx.serialization.Serializable
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Lightweight reference to one track. Mirrors
|
* Lightweight reference to one track. Mirrors
|
||||||
* `flutter_client/lib/models/track.dart`'s `TrackRef`.
|
* the Flutter client's `TrackRef`.
|
||||||
*
|
*
|
||||||
* The `Ref` suffix matches the Flutter convention — these types carry
|
* The `Ref` suffix matches the Flutter convention — these types carry
|
||||||
* only the IDs + display fields needed for list rendering + the player
|
* only the IDs + display fields needed for list rendering + the player
|
||||||
@@ -31,6 +31,16 @@ data class TrackRef(
|
|||||||
val discNumber: Int? = null,
|
val discNumber: Int? = null,
|
||||||
val durationSec: Int = 0,
|
val durationSec: Int = 0,
|
||||||
val streamUrl: String = "",
|
val streamUrl: String = "",
|
||||||
|
/**
|
||||||
|
* The server has no file for this track right now (#2704). It still
|
||||||
|
* belongs to the library, keeps its history, and may come back — but
|
||||||
|
* streaming it will fail, so nothing should queue it.
|
||||||
|
*
|
||||||
|
* NOT the same as unplayable on this device: audio already resident in
|
||||||
|
* the local cache plays regardless of what the server has, which is why
|
||||||
|
* the offline pools in ShuffleSource deliberately ignore this.
|
||||||
|
*/
|
||||||
|
val unavailable: Boolean = false,
|
||||||
) {
|
) {
|
||||||
/**
|
/**
|
||||||
* Cover URL derived from the parent album's `/api/albums/{id}/cover`
|
* Cover URL derived from the parent album's `/api/albums/{id}/cover`
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ package com.fabledsword.minstrel.models
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Wire shape returned by `GET /api/client/version`. Mirrors
|
* Wire shape returned by `GET /api/client/version`. Mirrors
|
||||||
* `flutter_client/lib/update/update_info.dart UpdateInfo`.
|
* the Flutter client's `UpdateInfo`.
|
||||||
*
|
*
|
||||||
* `version` is the server-bundled APK version (may have a leading
|
* `version` is the server-bundled APK version (may have a leading
|
||||||
* "v" from the git tag); `apkUrl` is server-relative (e.g.
|
* "v" from the git tag); `apkUrl` is server-relative (e.g.
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import kotlinx.serialization.SerialName
|
|||||||
import kotlinx.serialization.Serializable
|
import kotlinx.serialization.Serializable
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Wire shape for `AlbumRef`. Mirrors `flutter_client/lib/models/album.dart`.
|
* Wire shape for `AlbumRef`.
|
||||||
*/
|
*/
|
||||||
@Serializable
|
@Serializable
|
||||||
data class AlbumWire(
|
data class AlbumWire(
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import kotlinx.serialization.SerialName
|
|||||||
import kotlinx.serialization.Serializable
|
import kotlinx.serialization.Serializable
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Wire shape for `ArtistRef`. Mirrors `flutter_client/lib/models/artist.dart`.
|
* Wire shape for `ArtistRef`.
|
||||||
*/
|
*/
|
||||||
@Serializable
|
@Serializable
|
||||||
data class ArtistWire(
|
data class ArtistWire(
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package com.fabledsword.minstrel.models.wire
|
||||||
|
|
||||||
|
import kotlinx.serialization.SerialName
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One row of `GET /api/library/genres` (#367).
|
||||||
|
*
|
||||||
|
* The label is the file tag's own string, split on `[;,]` and trimmed but
|
||||||
|
* otherwise untouched by the server — no case folding, no synonym mapping.
|
||||||
|
* So "Rock" and "rock" can both appear, as can "Rock/Pop" beside "Rock" and
|
||||||
|
* "Pop". Don't normalise it on the client either: the index and the album
|
||||||
|
* filter have to agree on the exact string, and the filter matches what the
|
||||||
|
* server stored.
|
||||||
|
*/
|
||||||
|
@Serializable
|
||||||
|
data class GenreCountWire(
|
||||||
|
val genre: String = "",
|
||||||
|
@SerialName("track_count") val trackCount: Int = 0,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One row of `GET /api/library/years`.
|
||||||
|
*
|
||||||
|
* Albums with no release date are absent from this axis entirely rather than
|
||||||
|
* bucketed under year 0 — "unknown" is not a year, and the UI should say so
|
||||||
|
* instead of showing a fake row.
|
||||||
|
*/
|
||||||
|
@Serializable
|
||||||
|
data class YearCountWire(
|
||||||
|
val year: Int = 0,
|
||||||
|
@SerialName("album_count") val albumCount: Int = 0,
|
||||||
|
)
|
||||||
@@ -6,7 +6,7 @@ import kotlinx.serialization.Serializable
|
|||||||
/**
|
/**
|
||||||
* One row of `GET /api/lidarr/search`. Mirrors
|
* One row of `GET /api/lidarr/search`. Mirrors
|
||||||
* `web/src/lib/api/types.ts LidarrSearchResult` /
|
* `web/src/lib/api/types.ts LidarrSearchResult` /
|
||||||
* `flutter_client/lib/models/lidarr.dart LidarrSearchResult`.
|
* the Flutter client's `LidarrSearchResult`.
|
||||||
*
|
*
|
||||||
* `inLibrary` and `requested` let the UI greyout rows the user can't
|
* `inLibrary` and `requested` let the UI greyout rows the user can't
|
||||||
* act on (already imported / already awaiting review). All defaults
|
* act on (already imported / already awaiting review). All defaults
|
||||||
@@ -35,6 +35,13 @@ data class ArtistSuggestionWire(
|
|||||||
val name: String = "",
|
val name: String = "",
|
||||||
@SerialName("image_url") val imageUrl: String = "",
|
@SerialName("image_url") val imageUrl: String = "",
|
||||||
val attribution: List<SeedContributionWire> = emptyList(),
|
val attribution: List<SeedContributionWire> = emptyList(),
|
||||||
|
/**
|
||||||
|
* Tags this candidate shares with the user's taste profile, strongest
|
||||||
|
* first (max 3, #2377). Absent for most candidates — tag coverage for
|
||||||
|
* out-of-library artists is partial by nature (#2376) — so the default
|
||||||
|
* empty list is the common case, not an error.
|
||||||
|
*/
|
||||||
|
@SerialName("matched_tags") val matchedTags: List<String> = emptyList(),
|
||||||
)
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -48,6 +55,36 @@ data class SeedContributionWire(
|
|||||||
@SerialName("is_liked") val isLiked: Boolean = false,
|
@SerialName("is_liked") val isLiked: Boolean = false,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One row of `GET /api/discover/snoozes` — a suggestion the user parked
|
||||||
|
* with "not right now". The server only returns rows that are still in
|
||||||
|
* effect, so the client never compares [snoozedUntil] against the clock to
|
||||||
|
* decide whether to show it; it reads it only to say when the artist comes
|
||||||
|
* back.
|
||||||
|
*/
|
||||||
|
@Serializable
|
||||||
|
data class SuggestionSnoozeWire(
|
||||||
|
val mbid: String = "",
|
||||||
|
val name: String = "",
|
||||||
|
@SerialName("snoozed_until") val snoozedUntil: String = "",
|
||||||
|
@SerialName("created_at") val createdAt: String = "",
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Body for `POST /api/discover/suggestions/{mbid}/snooze`.
|
||||||
|
*
|
||||||
|
* [name] is required by the server, not decorative: suggestions are
|
||||||
|
* out-of-library, so there is no artists row to resolve a display name from
|
||||||
|
* and the snooze list would have nothing to render. Omitting it is a 400.
|
||||||
|
*
|
||||||
|
* No `days` field. The duration is the server's to own (90 days); pinning it
|
||||||
|
* client-side would freeze the default at whatever this build shipped.
|
||||||
|
*/
|
||||||
|
@Serializable
|
||||||
|
data class SnoozeSuggestionBody(
|
||||||
|
val name: String,
|
||||||
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Body posted to `POST /api/requests`. Mirrors the Flutter `createRequest`
|
* Body posted to `POST /api/requests`. Mirrors the Flutter `createRequest`
|
||||||
* payload shape. Optional fields are emitted only when non-null
|
* payload shape. Optional fields are emitted only when non-null
|
||||||
|
|||||||
@@ -9,8 +9,7 @@ import kotlinx.serialization.Serializable
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Wire shapes for `POST /api/events`. The endpoint multiplexes four
|
* Wire shapes for `POST /api/events`. The endpoint multiplexes four
|
||||||
* variants on the `type` discriminator field, mirroring
|
* variants on the `type` discriminator field.
|
||||||
* `flutter_client/lib/api/endpoints/events.dart`.
|
|
||||||
*
|
*
|
||||||
* play_started returns the server-assigned play_event_id (nullable —
|
* play_started returns the server-assigned play_event_id (nullable —
|
||||||
* server may suppress under certain conditions); the other three
|
* server may suppress under certain conditions); the other three
|
||||||
|
|||||||
@@ -5,9 +5,8 @@ import kotlinx.serialization.Serializable
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Wire shape of `GET /api/home/index` — five flat slices of entity-ID
|
* Wire shape of `GET /api/home/index` — five flat slices of entity-ID
|
||||||
* strings, one per Home section. Mirrors
|
* strings, one per Home section. Mirrors the server's
|
||||||
* `flutter_client/lib/models/home_index.dart` (and the server's
|
* `HomeIndexPayload` in `internal/api/types.go`.
|
||||||
* `internal/api/types.go HomeIndexPayload`).
|
|
||||||
*
|
*
|
||||||
* Section name implies entity type; no per-entry type tag is needed:
|
* Section name implies entity type; no per-entry type tag is needed:
|
||||||
* - recentlyAddedAlbums → album
|
* - recentlyAddedAlbums → album
|
||||||
|
|||||||
@@ -5,8 +5,7 @@ import kotlinx.serialization.Serializable
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Wire shape for `GET /api/me` and the return value of
|
* Wire shape for `GET /api/me` and the return value of
|
||||||
* `PUT /api/me/profile`. Mirrors
|
* `PUT /api/me/profile`. Two things the shape assumes:
|
||||||
* `flutter_client/lib/models/my_profile.dart`:
|
|
||||||
* - `display_name` and `email` are nullable; server returns null
|
* - `display_name` and `email` are nullable; server returns null
|
||||||
* when the user hasn't set them yet (registration only requires
|
* when the user hasn't set them yet (registration only requires
|
||||||
* a username).
|
* a username).
|
||||||
|
|||||||
@@ -41,6 +41,14 @@ data class PlaylistsListWire(
|
|||||||
* / `artistId` / `streamUrl` are nullable because the upstream track
|
* / `artistId` / `streamUrl` are nullable because the upstream track
|
||||||
* may have been removed from the library while the row stays in the
|
* may have been removed from the library while the row stays in the
|
||||||
* playlist with its display fields preserved.
|
* playlist with its display fields preserved.
|
||||||
|
*
|
||||||
|
* [unavailable] is the other way a row outlives its audio (#2527): the
|
||||||
|
* track is still in the library, with its history and likes, but its
|
||||||
|
* file is missing from disk. The server withholds `stream_url` in that
|
||||||
|
* case too, so a client that only checked the URL would already skip
|
||||||
|
* it — the flag is what lets the UI say WHY instead of rendering a
|
||||||
|
* mysteriously dead row. Defaults false so a server that predates the
|
||||||
|
* field deserialises cleanly.
|
||||||
*/
|
*/
|
||||||
@Serializable
|
@Serializable
|
||||||
data class PlaylistTrackWire(
|
data class PlaylistTrackWire(
|
||||||
@@ -53,6 +61,7 @@ data class PlaylistTrackWire(
|
|||||||
@SerialName("artist_name") val artistName: String = "",
|
@SerialName("artist_name") val artistName: String = "",
|
||||||
@SerialName("duration_sec") val durationSec: Int = 0,
|
@SerialName("duration_sec") val durationSec: Int = 0,
|
||||||
@SerialName("stream_url") val streamUrl: String? = null,
|
@SerialName("stream_url") val streamUrl: String? = null,
|
||||||
|
val unavailable: Boolean = false,
|
||||||
)
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+1
-1
@@ -5,7 +5,7 @@ import kotlinx.serialization.Serializable
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* One row of `GET /api/quarantine/mine`. Mirrors
|
* One row of `GET /api/quarantine/mine`. Mirrors
|
||||||
* `flutter_client/lib/models/quarantine_mine.dart QuarantineMineRow`
|
* the Flutter client's `QuarantineMineRow`
|
||||||
* (web `LidarrQuarantineMineRow`).
|
* (web `LidarrQuarantineMineRow`).
|
||||||
*
|
*
|
||||||
* Reason values: `bad_rip` / `wrong_file` / `wrong_tags` / `duplicate`
|
* Reason values: `bad_rip` / `wrong_file` / `wrong_tags` / `duplicate`
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import kotlinx.serialization.Serializable
|
|||||||
* Wire shape of `requestView` from `internal/api/requests.go` — the
|
* Wire shape of `requestView` from `internal/api/requests.go` — the
|
||||||
* row returned by both `GET /api/requests` (caller's own requests) and
|
* row returned by both `GET /api/requests` (caller's own requests) and
|
||||||
* `GET /api/admin/requests` (cross-user admin view). Mirrors
|
* `GET /api/admin/requests` (cross-user admin view). Mirrors
|
||||||
* `flutter_client/lib/models/admin_request.dart AdminRequest`.
|
* the Flutter client's `AdminRequest`.
|
||||||
*
|
*
|
||||||
* Status values: `pending` / `approved` / `rejected` / `completed` /
|
* Status values: `pending` / `approved` / `rejected` / `completed` /
|
||||||
* `failed`. Kind values: `artist` / `album` / `track`.
|
* `failed`. Kind values: `artist` / `album` / `track`.
|
||||||
|
|||||||
@@ -42,6 +42,15 @@ data class SyncTrackWire(
|
|||||||
@SerialName("file_path") val filePath: String? = null,
|
@SerialName("file_path") val filePath: String? = null,
|
||||||
@SerialName("file_format") val fileFormat: String? = null,
|
@SerialName("file_format") val fileFormat: String? = null,
|
||||||
val genre: String? = null,
|
val genre: String? = null,
|
||||||
|
// The file is currently absent from disk server-side (#2704). Shipped as
|
||||||
|
// state rather than the row being withheld, because a missing file is
|
||||||
|
// expected to return — dropping it would churn the cache on every
|
||||||
|
// transient unmount and discard the identity #2528 preserves.
|
||||||
|
//
|
||||||
|
// Defaults false so a server predating the field deserialises cleanly and
|
||||||
|
// its tracks stay playable, which is the correct reading of "this server
|
||||||
|
// has nothing to say about missing files".
|
||||||
|
val missing: Boolean = false,
|
||||||
)
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import kotlinx.serialization.Serializable
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Wire shape for `TrackRef` as the server emits it. Mirrors
|
* Wire shape for `TrackRef` as the server emits it. Mirrors
|
||||||
* `flutter_client/lib/models/track.dart`'s `TrackRef.fromJson`
|
* the Flutter client's `TrackRef.fromJson`
|
||||||
* field-for-field; the keys are snake_case because the server is Go
|
* field-for-field; the keys are snake_case because the server is Go
|
||||||
* (json:"album_id" etc.).
|
* (json:"album_id" etc.).
|
||||||
*
|
*
|
||||||
@@ -26,4 +26,9 @@ data class TrackWire(
|
|||||||
@SerialName("disc_number") val discNumber: Int? = null,
|
@SerialName("disc_number") val discNumber: Int? = null,
|
||||||
@SerialName("duration_sec") val durationSec: Int = 0,
|
@SerialName("duration_sec") val durationSec: Int = 0,
|
||||||
@SerialName("stream_url") val streamUrl: String = "",
|
@SerialName("stream_url") val streamUrl: String = "",
|
||||||
|
// Omitted by the server when false, so the default carries most rows
|
||||||
|
// (#2704). True only from the direct-lookup surfaces — album detail and
|
||||||
|
// search — which return a track the user asked for by name or container
|
||||||
|
// rather than one Minstrel chose.
|
||||||
|
val unavailable: Boolean = false,
|
||||||
)
|
)
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user