Compare commits
16
Commits
@@ -5,6 +5,7 @@
|
||||
ci/ export-ignore
|
||||
ci-requirements.md export-ignore
|
||||
renovate.json export-ignore
|
||||
.gitleaks.toml export-ignore
|
||||
internal/server/release_gate_test.go export-ignore
|
||||
internal/server/release_version_test.go export-ignore
|
||||
.gitattributes export-ignore
|
||||
|
||||
@@ -122,7 +122,7 @@ jobs:
|
||||
go:
|
||||
runs-on: go-ci
|
||||
container:
|
||||
image: git.fabledsword.com/bvandeusen/ci-go:1.26
|
||||
image: git.fabledsword.com/bvandeusen/ci-go:1.27
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -176,10 +176,10 @@ jobs:
|
||||
integration:
|
||||
runs-on: go-ci
|
||||
container:
|
||||
image: git.fabledsword.com/bvandeusen/ci-go:1.26
|
||||
image: git.fabledsword.com/bvandeusen/ci-go:1.27
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
image: postgres:19-alpine
|
||||
env:
|
||||
POSTGRES_USER: minstrel
|
||||
POSTGRES_PASSWORD: minstrel
|
||||
@@ -211,7 +211,7 @@ jobs:
|
||||
echo "self ($SELF) networks: $SELF_NETS"
|
||||
PG_ID=""
|
||||
PG_NAME=""
|
||||
for cid in $(docker ps --filter "ancestor=postgres:16-alpine" -q); do
|
||||
for cid in $(docker ps --filter "ancestor=postgres:19-alpine" -q); do
|
||||
nm=$(docker inspect -f '{{.Name}}' "$cid" | sed 's#^/##')
|
||||
case "$nm" in *minstrel-postgres*|*_postgres_*) continue ;; esac
|
||||
for net in $(docker inspect -f '{{range $k,$v := .NetworkSettings.Networks}}{{$k}} {{end}}' "$cid"); do
|
||||
@@ -223,6 +223,9 @@ jobs:
|
||||
PG_IP=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$PG_ID")
|
||||
test -n "$PG_IP"
|
||||
export MINSTREL_TEST_DATABASE_URL="postgres://minstrel:minstrel@${PG_IP}:5432/minstrel_test?sslmode=disable"
|
||||
# A database test that finds no database fails here instead of
|
||||
# skipping, so this lane can't pass with nothing run.
|
||||
export MINSTREL_TEST_DATABASE_REQUIRED=1
|
||||
|
||||
# Wait for Postgres to accept connections. Asked of the service
|
||||
# container itself: the run: shell is dash, where a `/dev/tcp`
|
||||
@@ -303,7 +306,7 @@ jobs:
|
||||
web:
|
||||
runs-on: go-ci
|
||||
container:
|
||||
image: git.fabledsword.com/bvandeusen/ci-go:1.26
|
||||
image: git.fabledsword.com/bvandeusen/ci-go:1.27
|
||||
|
||||
defaults:
|
||||
run:
|
||||
@@ -332,7 +335,7 @@ jobs:
|
||||
# docker that can pull our container.image.
|
||||
runs-on: flutter-ci
|
||||
container:
|
||||
image: git.fabledsword.com/bvandeusen/ci-android:36
|
||||
image: git.fabledsword.com/bvandeusen/ci-android:37
|
||||
|
||||
defaults:
|
||||
run:
|
||||
@@ -410,7 +413,7 @@ jobs:
|
||||
govulncheck:
|
||||
runs-on: go-ci
|
||||
container:
|
||||
image: golang:1.26-bookworm
|
||||
image: golang:1.27-trixie
|
||||
|
||||
steps:
|
||||
# Plain git, not actions/checkout: that action runs on node, which the
|
||||
@@ -443,7 +446,7 @@ jobs:
|
||||
|| github.ref == 'refs/heads/main'
|
||||
runs-on: flutter-ci
|
||||
container:
|
||||
image: git.fabledsword.com/bvandeusen/ci-android:36
|
||||
image: git.fabledsword.com/bvandeusen/ci-android:37
|
||||
|
||||
defaults:
|
||||
run:
|
||||
@@ -557,10 +560,14 @@ jobs:
|
||||
signer="$(ls "$sdk"/build-tools/*/apksigner 2>/dev/null | sort -V | tail -1 || true)"
|
||||
test -n "$signer" || { echo "::error::no apksigner under '$sdk/build-tools'"; exit 1; }
|
||||
certs="$("$signer" verify --print-certs app/build/outputs/apk/release/app-release.apk)"
|
||||
printf '%s\n' "$certs" | grep -E '^Signer #[0-9]+ certificate (DN|SHA-256 digest)'
|
||||
# One signer, and it is ours. A second signer would be a lineage or
|
||||
# apksigner's signer label varies between versions: "Signer #1
|
||||
# certificate ..." before build-tools 37, "V3.0 Signer: certificate
|
||||
# ..." from 37 on. So the digests are read without relying on it.
|
||||
printf '%s\n' "$certs" | grep -E 'certificate (DN|SHA-256 digest):' || true
|
||||
# One signer, and it is ours: exactly one distinct SHA-256 across
|
||||
# every scheme apksigner reports. A second key would be a lineage or
|
||||
# a mistake; either way not something to ship unexamined.
|
||||
digests="$(printf '%s\n' "$certs" | sed -n 's/^Signer #[0-9]* certificate SHA-256 digest: //p')"
|
||||
digests="$(printf '%s\n' "$certs" | sed -n 's/^.*certificate SHA-256 digest: //p' | sort -u)"
|
||||
if [ "$digests" != "$RELEASE_CERT_SHA256" ]; then
|
||||
if printf '%s' "$certs" | grep -q 'CN=Android Debug'; then
|
||||
echo "::error::the release APK is signed with a debug key"
|
||||
@@ -615,7 +622,7 @@ jobs:
|
||||
&& needs.android-release.result == 'success' }}
|
||||
runs-on: go-ci
|
||||
container:
|
||||
image: git.fabledsword.com/bvandeusen/ci-go:1.26
|
||||
image: git.fabledsword.com/bvandeusen/ci-go:1.27
|
||||
|
||||
env:
|
||||
IMAGE: git.fabledsword.com/bvandeusen/minstrel
|
||||
@@ -700,7 +707,7 @@ jobs:
|
||||
rm -rf "${EXPORT}"
|
||||
mkdir -p "${EXPORT}"
|
||||
git archive HEAD | tar -x -C "${EXPORT}"
|
||||
for private in .gitea .forgejo .github ci ci-requirements.md .gitattributes renovate.json; do
|
||||
for private in .gitea .forgejo .github ci ci-requirements.md .gitattributes renovate.json .gitleaks.toml; do
|
||||
if [ -e "${EXPORT}/${private}" ]; then
|
||||
echo "::error::the export carries ${private}; .gitattributes export-ignore no longer covers it"
|
||||
exit 1
|
||||
@@ -783,8 +790,8 @@ jobs:
|
||||
|
||||
- name: Build and push
|
||||
shell: bash
|
||||
# --pull: the Dockerfile's base images are floating tags (golang:1.26,
|
||||
# debian:bookworm-slim). Without it the runner's daemon reuses
|
||||
# --pull: the Dockerfile's base images are floating tags (golang:1.27,
|
||||
# debian:trixie-slim). Without it the runner's daemon reuses
|
||||
# whatever it cached, and the shipped binary can sit on a Go patch
|
||||
# release govulncheck already flagged while the lane, which pulls
|
||||
# fresh, reports clean.
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
# The weekly security sweep reads this file in place of the family gitleaks
|
||||
# config, so it extends that config and adds only this repository's
|
||||
# allowlist. The path is where the sweep's image keeps the family rules.
|
||||
#
|
||||
# Every entry says why the matched value is not a secret.
|
||||
|
||||
[extend]
|
||||
path = "/opt/security-rules/gitleaks-family.toml"
|
||||
|
||||
[allowlist]
|
||||
description = "Minstrel: test values that look like credentials and are not"
|
||||
regexes = [
|
||||
# AWS's published SigV4 example credentials ("Examples: Signature
|
||||
# Calculations in AWS Signature Version 4", Amazon S3 API reference).
|
||||
# internal/backup/s3_test.go signs AWS's own worked example with them and
|
||||
# checks the signature AWS prints, so they must stay exactly as published.
|
||||
'''AKIAIOSFODNN7EXAMPLE''',
|
||||
'''wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY''',
|
||||
# An invite token that a register test inserts into the throwaway test
|
||||
# database and then redeems (internal/api/auth_register_test.go).
|
||||
'''test-invite-abc123''',
|
||||
]
|
||||
+4
-4
@@ -1,13 +1,13 @@
|
||||
# syntax=docker/dockerfile:1.6
|
||||
# syntax=docker/dockerfile:1.29
|
||||
|
||||
FROM node:22-bookworm-slim AS web
|
||||
FROM node:26-trixie-slim AS web
|
||||
WORKDIR /web
|
||||
COPY web/package.json web/package-lock.json ./
|
||||
RUN npm ci
|
||||
COPY web/ ./
|
||||
RUN npm run build
|
||||
|
||||
FROM golang:1.26-bookworm AS builder
|
||||
FROM golang:1.27-trixie AS builder
|
||||
WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
@@ -31,7 +31,7 @@ RUN go build -trimpath \
|
||||
-X 'github.com/Fabled-Sword/minstrel/internal/buildinfo.Channel=${MINSTREL_CHANNEL}'" \
|
||||
-o /out/minstrel ./cmd/minstrel
|
||||
|
||||
FROM debian:bookworm-slim
|
||||
FROM debian:trixie-slim
|
||||
# ffmpeg: duration probes and the exact-tier audio hash (a SHA-256 of the
|
||||
# encoded audio packets, so no decode). libchromaprint-tools: fpcalc, the
|
||||
# acoustic fingerprint that tells the same recording at two bitrates apart
|
||||
|
||||
@@ -32,7 +32,7 @@ services:
|
||||
depends_on: [db]
|
||||
|
||||
db:
|
||||
image: postgres:17
|
||||
image: postgres:19
|
||||
environment:
|
||||
POSTGRES_USER: minstrel
|
||||
POSTGRES_PASSWORD: minstrel
|
||||
@@ -94,6 +94,8 @@ Every image carries a signed Android app, all with the same key, so a phone can
|
||||
|
||||
**Back up the Postgres volume** with `pg_dump`. It holds accounts, likes, play history, playlists and settings, and a migration can only be undone by restoring a dump. The `minstrel-data` volume holds artwork and caches that Minstrel rebuilds if lost.
|
||||
|
||||
**Keep the Postgres image on the major version your database was created with.** The quick start uses `postgres:19`. Postgres can't open a data folder made by another major version, so moving an existing database to a newer one takes a `pg_dump`, a fresh volume and a restore.
|
||||
|
||||
## Features
|
||||
|
||||
**Listening**
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# ktlint reads this. The code style is ktlint's default (ktlint_official)
|
||||
# with two changes:
|
||||
# - Lines wrap at 120, detekt's MaxLineLength, so the two checks agree.
|
||||
# ktlint_official alone would wrap at 140.
|
||||
# - @Composable functions are exempt from the lowercase naming rule, because
|
||||
# Compose names them like types (PlayerScreen, not playerScreen).
|
||||
root = true
|
||||
|
||||
[*.{kt,kts}]
|
||||
max_line_length = 120
|
||||
ktlint_function_naming_ignore_when_annotated_with = Composable
|
||||
@@ -15,7 +15,10 @@ plugins {
|
||||
|
||||
android {
|
||||
namespace = "com.fabledsword.minstrel"
|
||||
compileSdk = 36
|
||||
// 37.1: Compose 1.13 requires compiling against Android 37.1 or later.
|
||||
compileSdk {
|
||||
version = release(37) { minorApiLevel = 1 }
|
||||
}
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "com.fabledsword.minstrel"
|
||||
|
||||
@@ -30,8 +30,8 @@ import com.fabledsword.minstrel.auth.AuthStore
|
||||
import com.fabledsword.minstrel.auth.ui.AuthGateViewModel
|
||||
import com.fabledsword.minstrel.cache.CachedTrackIds
|
||||
import com.fabledsword.minstrel.connectivity.LocalServerHealth
|
||||
import com.fabledsword.minstrel.connectivity.ServerHealth
|
||||
import com.fabledsword.minstrel.connectivity.NetworkStatusController
|
||||
import com.fabledsword.minstrel.connectivity.ServerHealth
|
||||
import com.fabledsword.minstrel.nav.DetailSeedCache
|
||||
import com.fabledsword.minstrel.nav.LocalDetailSeedCache
|
||||
import com.fabledsword.minstrel.nav.Login
|
||||
@@ -56,8 +56,11 @@ import javax.inject.Inject
|
||||
@AndroidEntryPoint
|
||||
class MainActivity : ComponentActivity() {
|
||||
@Inject lateinit var seedCache: DetailSeedCache
|
||||
|
||||
@Inject lateinit var cachedTrackIds: CachedTrackIds
|
||||
|
||||
@Inject lateinit var serverHealth: NetworkStatusController
|
||||
|
||||
@Inject lateinit var authStore: AuthStore
|
||||
|
||||
// Set when the user taps a notification: the media one asks for the full
|
||||
@@ -120,8 +123,9 @@ class MainActivity : ComponentActivity() {
|
||||
val signedIn = authStore.sessionCookie.map { !it.isNullOrEmpty() }
|
||||
combine(signedIn, authStore.backgroundDelivery, ::deliveryWanted).first { it }
|
||||
val permission = Manifest.permission.POST_NOTIFICATIONS
|
||||
val granted = ContextCompat.checkSelfPermission(this@MainActivity, permission) ==
|
||||
PackageManager.PERMISSION_GRANTED
|
||||
val granted =
|
||||
ContextCompat.checkSelfPermission(this@MainActivity, permission) ==
|
||||
PackageManager.PERMISSION_GRANTED
|
||||
if (!granted) askToNotify.launch(permission)
|
||||
}
|
||||
}
|
||||
@@ -196,7 +200,10 @@ private fun App(
|
||||
* request fails.
|
||||
*/
|
||||
@Composable
|
||||
private fun SignInWhenSessionRejected(gate: AuthGateViewModel, navController: NavHostController) {
|
||||
private fun SignInWhenSessionRejected(
|
||||
gate: AuthGateViewModel,
|
||||
navController: NavHostController,
|
||||
) {
|
||||
val sessionRejected by gate.sessionRejected.collectAsStateWithLifecycle()
|
||||
LaunchedEffect(sessionRejected, navController) {
|
||||
if (!sessionRejected) return@LaunchedEffect
|
||||
|
||||
@@ -11,6 +11,7 @@ import com.fabledsword.minstrel.cache.CacheIndexer
|
||||
import com.fabledsword.minstrel.cache.audiocache.CacheBudgetSync
|
||||
import com.fabledsword.minstrel.cache.mutations.MutationReplayer
|
||||
import com.fabledsword.minstrel.cache.sync.SyncController
|
||||
import com.fabledsword.minstrel.connectivity.NetworkStatusController
|
||||
import com.fabledsword.minstrel.di.ApplicationScope
|
||||
import com.fabledsword.minstrel.diagnostics.DiagnosticsReporter
|
||||
import com.fabledsword.minstrel.diagnostics.DiagnosticsUploader
|
||||
@@ -24,7 +25,6 @@ import com.fabledsword.minstrel.player.LikedAudioPinner
|
||||
import com.fabledsword.minstrel.player.PlayEventsReporter
|
||||
import com.fabledsword.minstrel.player.PlaybackErrorReporter
|
||||
import com.fabledsword.minstrel.player.ResumeController
|
||||
import com.fabledsword.minstrel.connectivity.NetworkStatusController
|
||||
import dagger.hilt.android.HiltAndroidApp
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -41,7 +41,6 @@ class MinstrelApplication :
|
||||
Application(),
|
||||
Configuration.Provider,
|
||||
SingletonImageLoader.Factory {
|
||||
|
||||
@Inject lateinit var workerFactory: HiltWorkerFactory
|
||||
|
||||
/**
|
||||
@@ -66,7 +65,9 @@ class MinstrelApplication :
|
||||
* cold start with persisted cookie). Without this @Inject the
|
||||
* singleton would never instantiate.
|
||||
*/
|
||||
@Suppress("unused") @Inject lateinit var syncController: SyncController
|
||||
@Suppress("unused")
|
||||
@Inject
|
||||
lateinit var syncController: SyncController
|
||||
|
||||
/**
|
||||
* Same construct-the-singleton trick — MutationReplayer's init
|
||||
@@ -75,7 +76,9 @@ class MinstrelApplication :
|
||||
* cold start with persisted cookie). Without this @Inject the
|
||||
* queue would only enqueue, never replay.
|
||||
*/
|
||||
@Suppress("unused") @Inject lateinit var mutationReplayer: MutationReplayer
|
||||
@Suppress("unused")
|
||||
@Inject
|
||||
lateinit var mutationReplayer: MutationReplayer
|
||||
|
||||
/**
|
||||
* Same construct-the-singleton trick — DeliveryLauncher starts and stops
|
||||
@@ -83,7 +86,9 @@ class MinstrelApplication :
|
||||
* every nudge and reconnect. Without this @Inject no phone
|
||||
* notification would ever be posted.
|
||||
*/
|
||||
@Suppress("unused") @Inject lateinit var deliveryLauncher: DeliveryLauncher
|
||||
@Suppress("unused")
|
||||
@Inject
|
||||
lateinit var deliveryLauncher: DeliveryLauncher
|
||||
|
||||
/**
|
||||
* Same construct-the-singleton trick — PlayEventsReporter's init
|
||||
@@ -92,7 +97,9 @@ class MinstrelApplication :
|
||||
* server. Without this @Inject the singleton would never
|
||||
* instantiate and Android plays would never reach the server.
|
||||
*/
|
||||
@Suppress("unused") @Inject lateinit var playEventsReporter: PlayEventsReporter
|
||||
@Suppress("unused")
|
||||
@Inject
|
||||
lateinit var playEventsReporter: PlayEventsReporter
|
||||
|
||||
/**
|
||||
* Same construct-the-singleton trick — PlaybackErrorReporter
|
||||
@@ -102,7 +109,9 @@ class MinstrelApplication :
|
||||
* snackbar. Without this construct ExoPlayer skip-on-error is
|
||||
* invisible to the user.
|
||||
*/
|
||||
@Suppress("unused") @Inject lateinit var playbackErrorReporter: PlaybackErrorReporter
|
||||
@Suppress("unused")
|
||||
@Inject
|
||||
lateinit var playbackErrorReporter: PlaybackErrorReporter
|
||||
|
||||
/**
|
||||
* Same construct-the-singleton trick — CoverPrefetcher's init
|
||||
@@ -110,7 +119,9 @@ class MinstrelApplication :
|
||||
* cache with the next track's cover so track changes don't flash
|
||||
* a loading state.
|
||||
*/
|
||||
@Suppress("unused") @Inject lateinit var coverPrefetcher: CoverPrefetcher
|
||||
@Suppress("unused")
|
||||
@Inject
|
||||
lateinit var coverPrefetcher: CoverPrefetcher
|
||||
|
||||
/**
|
||||
* Same construct-the-singleton trick — CacheIndexer's init block
|
||||
@@ -119,7 +130,9 @@ class MinstrelApplication :
|
||||
* and the cached indicator their data source. Without this @Inject
|
||||
* the index would stay empty and the offline pools would be inert.
|
||||
*/
|
||||
@Suppress("unused") @Inject lateinit var cacheIndexer: CacheIndexer
|
||||
@Suppress("unused")
|
||||
@Inject
|
||||
lateinit var cacheIndexer: CacheIndexer
|
||||
|
||||
/**
|
||||
* Same construct-the-singleton trick — CacheBudgetSync's init block
|
||||
@@ -127,14 +140,18 @@ class MinstrelApplication :
|
||||
* Without this @Inject the evictor would never arm, and the cache
|
||||
* would grow without a limit.
|
||||
*/
|
||||
@Suppress("unused") @Inject lateinit var cacheBudgetSync: CacheBudgetSync
|
||||
@Suppress("unused")
|
||||
@Inject
|
||||
lateinit var cacheBudgetSync: CacheBudgetSync
|
||||
|
||||
/**
|
||||
* Same construct-the-singleton trick — LikedAudioPinner's init block
|
||||
* downloads liked tracks into the Liked songs budget. Without this
|
||||
* @Inject, liking a track would not keep it offline.
|
||||
*/
|
||||
@Suppress("unused") @Inject lateinit var likedAudioPinner: LikedAudioPinner
|
||||
@Suppress("unused")
|
||||
@Inject
|
||||
lateinit var likedAudioPinner: LikedAudioPinner
|
||||
|
||||
/**
|
||||
* Same construct-the-singleton trick — AudioPrefetcher's init
|
||||
@@ -143,7 +160,9 @@ class MinstrelApplication :
|
||||
* SimpleCache via CacheWriter. Without this @Inject the
|
||||
* prefetchWindow setting would be inert and skips would re-fetch.
|
||||
*/
|
||||
@Suppress("unused") @Inject lateinit var audioPrefetcher: AudioPrefetcher
|
||||
@Suppress("unused")
|
||||
@Inject
|
||||
lateinit var audioPrefetcher: AudioPrefetcher
|
||||
|
||||
/**
|
||||
* Same construct-the-singleton trick — NetworkStatusController owns the
|
||||
@@ -152,7 +171,9 @@ class MinstrelApplication :
|
||||
* signal (plus the VersionTooOld byproduct). It must exist from launch so
|
||||
* the poll loop runs and the StateFlow stays warm for every consumer.
|
||||
*/
|
||||
@Suppress("unused") @Inject lateinit var networkStatusController: NetworkStatusController
|
||||
@Suppress("unused")
|
||||
@Inject
|
||||
lateinit var networkStatusController: NetworkStatusController
|
||||
|
||||
/**
|
||||
* Same construct-the-singleton trick — FreshnessSweeper's init
|
||||
@@ -161,7 +182,9 @@ class MinstrelApplication :
|
||||
* via MetadataProvider, so the cache stays warm without
|
||||
* user-driven pull-to-refresh.
|
||||
*/
|
||||
@Suppress("unused") @Inject lateinit var freshnessSweeper: FreshnessSweeper
|
||||
@Suppress("unused")
|
||||
@Inject
|
||||
lateinit var freshnessSweeper: FreshnessSweeper
|
||||
|
||||
/**
|
||||
* Same construct-the-singleton trick — EventsStream's init block
|
||||
@@ -170,21 +193,31 @@ class MinstrelApplication :
|
||||
* Without this @Inject the events SharedFlow would have no
|
||||
* upstream and consumers would never see anything.
|
||||
*/
|
||||
@Suppress("unused") @Inject lateinit var eventsStream: EventsStream
|
||||
@Suppress("unused")
|
||||
@Inject
|
||||
lateinit var eventsStream: EventsStream
|
||||
|
||||
/**
|
||||
* Same construct-the-singleton trick — LiveEventsDispatcher's
|
||||
* init block subscribes to EventsStream.events + the process
|
||||
* lifecycle and routes cross-screen state refreshes.
|
||||
*/
|
||||
@Suppress("unused") @Inject lateinit var liveEventsDispatcher: LiveEventsDispatcher
|
||||
@Suppress("unused")
|
||||
@Inject
|
||||
lateinit var liveEventsDispatcher: LiveEventsDispatcher
|
||||
|
||||
// Device diagnostics. The reporter gates itself on the account's
|
||||
// debug flag; the uploader drains its buffer on a tick / recovery.
|
||||
@Suppress("unused") @Inject lateinit var diagnosticsReporter: DiagnosticsReporter
|
||||
@Suppress("unused") @Inject lateinit var diagnosticsUploader: DiagnosticsUploader
|
||||
@Suppress("unused")
|
||||
@Inject
|
||||
lateinit var diagnosticsReporter: DiagnosticsReporter
|
||||
|
||||
@Inject @ApplicationScope lateinit var appScope: CoroutineScope
|
||||
@Suppress("unused")
|
||||
@Inject
|
||||
lateinit var diagnosticsUploader: DiagnosticsUploader
|
||||
|
||||
@Inject @ApplicationScope
|
||||
lateinit var appScope: CoroutineScope
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
@@ -208,10 +241,17 @@ class MinstrelApplication :
|
||||
* to the package-stack-trace tag DebugTree produces.
|
||||
*/
|
||||
private class ReleaseTree : Timber.Tree() {
|
||||
override fun isLoggable(tag: String?, priority: Int): Boolean =
|
||||
priority >= android.util.Log.WARN
|
||||
override fun isLoggable(
|
||||
tag: String?,
|
||||
priority: Int,
|
||||
): Boolean = priority >= android.util.Log.WARN
|
||||
|
||||
override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
|
||||
override fun log(
|
||||
priority: Int,
|
||||
tag: String?,
|
||||
message: String,
|
||||
t: Throwable?,
|
||||
) {
|
||||
val resolvedTag = tag ?: "Minstrel"
|
||||
if (t == null) {
|
||||
android.util.Log.println(priority, resolvedTag, message)
|
||||
@@ -226,9 +266,11 @@ class MinstrelApplication :
|
||||
}
|
||||
|
||||
override val workManagerConfiguration: Configuration
|
||||
get() = Configuration.Builder()
|
||||
.setWorkerFactory(workerFactory)
|
||||
.build()
|
||||
get() =
|
||||
Configuration
|
||||
.Builder()
|
||||
.setWorkerFactory(workerFactory)
|
||||
.build()
|
||||
|
||||
/**
|
||||
* Builds the process-singleton Coil ImageLoader with our shared
|
||||
@@ -242,10 +284,10 @@ class MinstrelApplication :
|
||||
* two read as one cross-dissolve.
|
||||
*/
|
||||
override fun newImageLoader(context: android.content.Context): ImageLoader =
|
||||
ImageLoader.Builder(context)
|
||||
ImageLoader
|
||||
.Builder(context)
|
||||
.components {
|
||||
add(OkHttpNetworkFetcherFactory(callFactory = { okHttpClient }))
|
||||
}
|
||||
.crossfade(ART_CROSSFADE_MS)
|
||||
}.crossfade(ART_CROSSFADE_MS)
|
||||
.build()
|
||||
}
|
||||
|
||||
+30
-17
@@ -14,25 +14,38 @@ import javax.inject.Singleton
|
||||
* admin repos — direct REST, no caching.
|
||||
*/
|
||||
@Singleton
|
||||
class AdminInvitesRepository @Inject constructor(retrofit: Retrofit) {
|
||||
private val api: AdminInvitesApi = retrofit.create()
|
||||
class AdminInvitesRepository
|
||||
@Inject
|
||||
constructor(
|
||||
retrofit: Retrofit,
|
||||
) {
|
||||
private val api: AdminInvitesApi = retrofit.create()
|
||||
|
||||
suspend fun list(): List<Invite> = api.list().invites.map { it.toDomain() }
|
||||
suspend fun list(): List<Invite> = api.list().invites.map { it.toDomain() }
|
||||
|
||||
suspend fun create(note: String?): Invite =
|
||||
api.create(CreateInviteBody(note = note?.takeIf { it.isNotEmpty() })).toDomain()
|
||||
suspend fun create(note: String?): Invite =
|
||||
api
|
||||
.create(
|
||||
CreateInviteBody(
|
||||
note =
|
||||
note?.takeIf {
|
||||
it.isNotEmpty()
|
||||
},
|
||||
),
|
||||
).toDomain()
|
||||
|
||||
suspend fun revoke(token: String) {
|
||||
api.revoke(token)
|
||||
suspend fun revoke(token: String) {
|
||||
api.revoke(token)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun InviteWire.toDomain(): Invite = Invite(
|
||||
token = token,
|
||||
invitedBy = invitedBy,
|
||||
note = note,
|
||||
createdAt = createdAt,
|
||||
expiresAt = expiresAt,
|
||||
redeemedAt = redeemedAt,
|
||||
redeemedBy = redeemedBy,
|
||||
)
|
||||
private fun InviteWire.toDomain(): Invite =
|
||||
Invite(
|
||||
token = token,
|
||||
invitedBy = invitedBy,
|
||||
note = note,
|
||||
createdAt = createdAt,
|
||||
expiresAt = expiresAt,
|
||||
redeemedAt = redeemedAt,
|
||||
redeemedBy = redeemedBy,
|
||||
)
|
||||
|
||||
+11
-9
@@ -17,19 +17,21 @@ import javax.inject.Singleton
|
||||
* Each action takes the row off the queue once the server accepts it.
|
||||
*/
|
||||
@Singleton
|
||||
class AdminQuarantineRepository @Inject constructor(
|
||||
retrofit: Retrofit,
|
||||
) {
|
||||
private val api: AdminQuarantineApi = retrofit.create()
|
||||
class AdminQuarantineRepository
|
||||
@Inject
|
||||
constructor(
|
||||
retrofit: Retrofit,
|
||||
) {
|
||||
private val api: AdminQuarantineApi = retrofit.create()
|
||||
|
||||
suspend fun list(): List<AdminQuarantineItemRef> = api.list().map { it.toDomain() }
|
||||
suspend fun list(): List<AdminQuarantineItemRef> = api.list().map { it.toDomain() }
|
||||
|
||||
suspend fun resolve(trackId: String) = api.resolve(trackId)
|
||||
suspend fun resolve(trackId: String) = api.resolve(trackId)
|
||||
|
||||
suspend fun removeFile(trackId: String) = api.removeFile(trackId)
|
||||
suspend fun removeFile(trackId: String) = api.removeFile(trackId)
|
||||
|
||||
suspend fun deleteFile(trackId: String) = api.deleteFile(trackId)
|
||||
}
|
||||
suspend fun deleteFile(trackId: String) = api.deleteFile(trackId)
|
||||
}
|
||||
|
||||
// ── Mappers ──
|
||||
|
||||
|
||||
+27
-20
@@ -18,31 +18,38 @@ import javax.inject.Singleton
|
||||
* Exceptions propagate to the ViewModel (which maps them via ErrorCopy).
|
||||
*/
|
||||
@Singleton
|
||||
class AdminTagSourcesRepository @Inject constructor(
|
||||
retrofit: Retrofit,
|
||||
) {
|
||||
private val api: AdminTagSourcesApi = retrofit.create()
|
||||
class AdminTagSourcesRepository
|
||||
@Inject
|
||||
constructor(
|
||||
retrofit: Retrofit,
|
||||
) {
|
||||
private val api: AdminTagSourcesApi = retrofit.create()
|
||||
|
||||
suspend fun list(): List<AdminTagSourceRef> = api.list().providers.map { it.toDomain() }
|
||||
suspend fun list(): List<AdminTagSourceRef> = api.list().providers.map { it.toDomain() }
|
||||
|
||||
suspend fun setEnabled(id: String, enabled: Boolean): AdminTagSourceRef =
|
||||
api.update(id, UpdateTagSourceBody(enabled = enabled)).toDomain()
|
||||
suspend fun setEnabled(
|
||||
id: String,
|
||||
enabled: Boolean,
|
||||
): AdminTagSourceRef = api.update(id, UpdateTagSourceBody(enabled = enabled)).toDomain()
|
||||
|
||||
suspend fun setApiKey(id: String, apiKey: String): AdminTagSourceRef =
|
||||
api.update(id, UpdateTagSourceBody(apiKey = apiKey)).toDomain()
|
||||
suspend fun setApiKey(
|
||||
id: String,
|
||||
apiKey: String,
|
||||
): AdminTagSourceRef = api.update(id, UpdateTagSourceBody(apiKey = apiKey)).toDomain()
|
||||
|
||||
suspend fun test(id: String): TagSourceTestResult = api.test(id).toResult()
|
||||
}
|
||||
suspend fun test(id: String): TagSourceTestResult = api.test(id).toResult()
|
||||
}
|
||||
|
||||
private fun AdminTagSourceWire.toDomain(): AdminTagSourceRef = AdminTagSourceRef(
|
||||
id = id,
|
||||
displayName = displayName,
|
||||
requiresApiKey = requiresApiKey,
|
||||
supports = supports,
|
||||
enabled = enabled,
|
||||
apiKeySet = apiKeySet,
|
||||
testable = testable,
|
||||
)
|
||||
private fun AdminTagSourceWire.toDomain(): AdminTagSourceRef =
|
||||
AdminTagSourceRef(
|
||||
id = id,
|
||||
displayName = displayName,
|
||||
requiresApiKey = requiresApiKey,
|
||||
supports = supports,
|
||||
enabled = enabled,
|
||||
apiKeySet = apiKeySet,
|
||||
testable = testable,
|
||||
)
|
||||
|
||||
private fun TestTagSourceWire.toResult(): TagSourceTestResult =
|
||||
TagSourceTestResult(ok = ok, durationMs = durationMs, error = error)
|
||||
|
||||
+25
-18
@@ -16,26 +16,33 @@ import javax.inject.Singleton
|
||||
* admin repositories.
|
||||
*/
|
||||
@Singleton
|
||||
class AdminUsersRepository @Inject constructor(
|
||||
retrofit: Retrofit,
|
||||
) {
|
||||
private val api: AdminUsersApi = retrofit.create()
|
||||
class AdminUsersRepository
|
||||
@Inject
|
||||
constructor(
|
||||
retrofit: Retrofit,
|
||||
) {
|
||||
private val api: AdminUsersApi = retrofit.create()
|
||||
|
||||
suspend fun list(): List<AdminUserRef> = api.list().users.map { it.toDomain() }
|
||||
suspend fun list(): List<AdminUserRef> = api.list().users.map { it.toDomain() }
|
||||
|
||||
suspend fun setAdmin(id: String, isAdmin: Boolean) =
|
||||
api.setAdmin(id, SetAdminBody(isAdmin))
|
||||
suspend fun setAdmin(
|
||||
id: String,
|
||||
isAdmin: Boolean,
|
||||
) = api.setAdmin(id, SetAdminBody(isAdmin))
|
||||
|
||||
suspend fun resetPassword(id: String, newPassword: String) =
|
||||
api.resetPassword(id, ResetPasswordBody(newPassword))
|
||||
suspend fun resetPassword(
|
||||
id: String,
|
||||
newPassword: String,
|
||||
) = api.resetPassword(id, ResetPasswordBody(newPassword))
|
||||
|
||||
suspend fun delete(id: String) = api.delete(id)
|
||||
}
|
||||
suspend fun delete(id: String) = api.delete(id)
|
||||
}
|
||||
|
||||
private fun AdminUserWire.toDomain(): AdminUserRef = AdminUserRef(
|
||||
id = id,
|
||||
username = username,
|
||||
displayName = displayName,
|
||||
isAdmin = isAdmin,
|
||||
createdAt = createdAt,
|
||||
)
|
||||
private fun AdminUserWire.toDomain(): AdminUserRef =
|
||||
AdminUserRef(
|
||||
id = id,
|
||||
username = username,
|
||||
displayName = displayName,
|
||||
isAdmin = isAdmin,
|
||||
createdAt = createdAt,
|
||||
)
|
||||
|
||||
+58
-57
@@ -25,72 +25,73 @@ data class AdminInvitesUiState(
|
||||
)
|
||||
|
||||
@HiltViewModel
|
||||
class AdminInvitesViewModel @Inject constructor(
|
||||
private val repository: AdminInvitesRepository,
|
||||
networkStatus: NetworkStatusController,
|
||||
) : ViewModel() {
|
||||
class AdminInvitesViewModel
|
||||
@Inject
|
||||
constructor(
|
||||
private val repository: AdminInvitesRepository,
|
||||
networkStatus: NetworkStatusController,
|
||||
) : ViewModel() {
|
||||
private val internal = MutableStateFlow(AdminInvitesUiState())
|
||||
val state: StateFlow<AdminInvitesUiState> = internal.asStateFlow()
|
||||
|
||||
private val internal = MutableStateFlow(AdminInvitesUiState())
|
||||
val state: StateFlow<AdminInvitesUiState> = internal.asStateFlow()
|
||||
/** One-shot signal for screens to show the generated token + copy UI. */
|
||||
private val createdChannel = Channel<Invite>(Channel.BUFFERED)
|
||||
val created: Flow<Invite> = createdChannel.receiveAsFlow()
|
||||
|
||||
/** One-shot signal for screens to show the generated token + copy UI. */
|
||||
private val createdChannel = Channel<Invite>(Channel.BUFFERED)
|
||||
val created: Flow<Invite> = createdChannel.receiveAsFlow()
|
||||
|
||||
init {
|
||||
refresh()
|
||||
// Screen-level auto-recovery: reload a failed list
|
||||
// when server health returns instead of waiting for a manual pull.
|
||||
viewModelScope.launch {
|
||||
networkStatus.recoveries().collect {
|
||||
if (internal.value.message != null) refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun refresh() {
|
||||
viewModelScope.launch {
|
||||
internal.update { it.copy(isLoading = true, message = null) }
|
||||
try {
|
||||
val rows = repository.list()
|
||||
internal.update { it.copy(isLoading = false, invites = rows) }
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
||||
) {
|
||||
internal.update {
|
||||
it.copy(
|
||||
isLoading = false,
|
||||
message = ErrorCopy.fromThrowable(e),
|
||||
)
|
||||
init {
|
||||
refresh()
|
||||
// Screen-level auto-recovery: reload a failed list
|
||||
// when server health returns instead of waiting for a manual pull.
|
||||
viewModelScope.launch {
|
||||
networkStatus.recoveries().collect {
|
||||
if (internal.value.message != null) refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun generate(note: String?) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val invite = repository.create(note)
|
||||
createdChannel.trySend(invite)
|
||||
// Optimistically prepend; next refresh reconciles.
|
||||
internal.update { it.copy(invites = listOf(invite) + it.invites) }
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
||||
) {
|
||||
internal.update {
|
||||
it.copy(message = ErrorCopy.fromThrowable(e))
|
||||
fun refresh() {
|
||||
viewModelScope.launch {
|
||||
internal.update { it.copy(isLoading = true, message = null) }
|
||||
try {
|
||||
val rows = repository.list()
|
||||
internal.update { it.copy(isLoading = false, invites = rows) }
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
||||
) {
|
||||
internal.update {
|
||||
it.copy(
|
||||
isLoading = false,
|
||||
message = ErrorCopy.fromThrowable(e),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun revoke(token: String) {
|
||||
val before = internal.value.invites
|
||||
// Optimistic removal.
|
||||
internal.update { it.copy(invites = before.filterNot { i -> i.token == token }) }
|
||||
viewModelScope.launch {
|
||||
runCatching { repository.revoke(token) }
|
||||
.onFailure { refresh() }
|
||||
fun generate(note: String?) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val invite = repository.create(note)
|
||||
createdChannel.trySend(invite)
|
||||
// Optimistically prepend; next refresh reconciles.
|
||||
internal.update { it.copy(invites = listOf(invite) + it.invites) }
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
||||
) {
|
||||
internal.update {
|
||||
it.copy(message = ErrorCopy.fromThrowable(e))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun revoke(token: String) {
|
||||
val before = internal.value.invites
|
||||
// Optimistic removal.
|
||||
internal.update { it.copy(invites = before.filterNot { i -> i.token == token }) }
|
||||
viewModelScope.launch {
|
||||
runCatching { repository.revoke(token) }
|
||||
.onFailure { refresh() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,11 +39,11 @@ import com.fabledsword.minstrel.nav.AdminTagSources
|
||||
import com.fabledsword.minstrel.nav.AdminUsers
|
||||
import com.fabledsword.minstrel.shared.UiState
|
||||
import com.fabledsword.minstrel.shared.loadUiState
|
||||
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
|
||||
import com.fabledsword.minstrel.shared.widgets.EmptyState
|
||||
import com.fabledsword.minstrel.shared.widgets.LoadingCentered
|
||||
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
|
||||
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
|
||||
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.async
|
||||
@@ -56,7 +56,11 @@ import javax.inject.Inject
|
||||
|
||||
// ─── State ───────────────────────────────────────────────────────────
|
||||
|
||||
data class AdminCounts(val quarantine: Int, val users: Int, val tagSources: Int)
|
||||
data class AdminCounts(
|
||||
val quarantine: Int,
|
||||
val users: Int,
|
||||
val tagSources: Int,
|
||||
)
|
||||
|
||||
/** The admin landing's counts, as the shared [UiState] (never Empty: it always has counts). */
|
||||
typealias AdminLandingUiState = UiState<AdminCounts>
|
||||
@@ -64,31 +68,34 @@ typealias AdminLandingUiState = UiState<AdminCounts>
|
||||
// ─── ViewModel ───────────────────────────────────────────────────────
|
||||
|
||||
@HiltViewModel
|
||||
class AdminLandingViewModel @Inject constructor(
|
||||
private val quarantineRepo: AdminQuarantineRepository,
|
||||
private val usersRepo: AdminUsersRepository,
|
||||
private val tagSourcesRepo: AdminTagSourcesRepository,
|
||||
) : ViewModel() {
|
||||
class AdminLandingViewModel
|
||||
@Inject
|
||||
constructor(
|
||||
private val quarantineRepo: AdminQuarantineRepository,
|
||||
private val usersRepo: AdminUsersRepository,
|
||||
private val tagSourcesRepo: AdminTagSourcesRepository,
|
||||
) : ViewModel() {
|
||||
private val internal = MutableStateFlow<AdminLandingUiState>(UiState.Loading)
|
||||
val uiState: StateFlow<AdminLandingUiState> = internal.asStateFlow()
|
||||
|
||||
private val internal = MutableStateFlow<AdminLandingUiState>(UiState.Loading)
|
||||
val uiState: StateFlow<AdminLandingUiState> = internal.asStateFlow()
|
||||
|
||||
init {
|
||||
refresh()
|
||||
}
|
||||
|
||||
fun refresh(): Job = viewModelScope.launch {
|
||||
internal.value = UiState.Loading
|
||||
internal.value = loadUiState {
|
||||
coroutineScope {
|
||||
val qua = async { quarantineRepo.list().size }
|
||||
val usr = async { usersRepo.list().size }
|
||||
val tag = async { tagSourcesRepo.list().count { it.enabled } }
|
||||
UiState.Success(AdminCounts(qua.await(), usr.await(), tag.await()))
|
||||
}
|
||||
init {
|
||||
refresh()
|
||||
}
|
||||
|
||||
fun refresh(): Job =
|
||||
viewModelScope.launch {
|
||||
internal.value = UiState.Loading
|
||||
internal.value =
|
||||
loadUiState {
|
||||
coroutineScope {
|
||||
val qua = async { quarantineRepo.list().size }
|
||||
val usr = async { usersRepo.list().size }
|
||||
val tag = async { tagSourcesRepo.list().count { it.enabled } }
|
||||
UiState.Success(AdminCounts(qua.await(), usr.await(), tag.await()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Screen ──────────────────────────────────────────────────────────
|
||||
|
||||
@@ -116,21 +123,26 @@ fun AdminLandingScreen(
|
||||
) {
|
||||
when (val s = state) {
|
||||
UiState.Loading, UiState.Empty -> LoadingCentered()
|
||||
is UiState.Error -> EmptyState(
|
||||
title = "Couldn't load admin counts",
|
||||
body = s.message,
|
||||
)
|
||||
is UiState.Success -> SectionList(
|
||||
counts = s.data,
|
||||
navController = navController,
|
||||
)
|
||||
is UiState.Error ->
|
||||
EmptyState(
|
||||
title = "Couldn't load admin counts",
|
||||
body = s.message,
|
||||
)
|
||||
is UiState.Success ->
|
||||
SectionList(
|
||||
counts = s.data,
|
||||
navController = navController,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SectionList(counts: AdminCounts, navController: NavHostController) {
|
||||
private fun SectionList(
|
||||
counts: AdminCounts,
|
||||
navController: NavHostController,
|
||||
) {
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
@@ -175,9 +187,10 @@ private fun SectionCard(
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
ElevatedCard(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable(onClick = onClick),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable(onClick = onClick),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
|
||||
+46
-35
@@ -35,12 +35,12 @@ import com.fabledsword.minstrel.models.AdminQuarantineItemRef
|
||||
import com.fabledsword.minstrel.nav.AdminQuarantine
|
||||
import com.fabledsword.minstrel.shared.UiState
|
||||
import com.fabledsword.minstrel.shared.widgets.ConfirmDestructiveDialog
|
||||
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
|
||||
import com.fabledsword.minstrel.shared.widgets.EmptyState
|
||||
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
|
||||
import com.fabledsword.minstrel.shared.widgets.LoadingCentered
|
||||
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
|
||||
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
|
||||
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
@@ -74,22 +74,26 @@ fun AdminQuarantineScreen(
|
||||
) {
|
||||
when (val s = state) {
|
||||
UiState.Loading -> LoadingCentered()
|
||||
UiState.Empty -> EmptyState(
|
||||
title = "No reports",
|
||||
body = "When listeners flag a track as a bad rip, wrong tags or " +
|
||||
"a duplicate, their reports gather here.",
|
||||
)
|
||||
is UiState.Error -> ErrorRetry(
|
||||
title = "Couldn't load queue",
|
||||
message = s.message,
|
||||
onRetry = { viewModel.refresh() },
|
||||
)
|
||||
is UiState.Success -> QueueList(
|
||||
rows = s.data,
|
||||
onResolve = viewModel::resolve,
|
||||
onRemoveFile = viewModel::removeFile,
|
||||
onDeleteFile = viewModel::deleteFile,
|
||||
)
|
||||
UiState.Empty ->
|
||||
EmptyState(
|
||||
title = "No reports",
|
||||
body =
|
||||
"When listeners flag a track as a bad rip, wrong tags or " +
|
||||
"a duplicate, their reports gather here.",
|
||||
)
|
||||
is UiState.Error ->
|
||||
ErrorRetry(
|
||||
title = "Couldn't load queue",
|
||||
message = s.message,
|
||||
onRetry = { viewModel.refresh() },
|
||||
)
|
||||
is UiState.Success ->
|
||||
QueueList(
|
||||
rows = s.data,
|
||||
onResolve = viewModel::resolve,
|
||||
onRemoveFile = viewModel::removeFile,
|
||||
onDeleteFile = viewModel::deleteFile,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -98,7 +102,10 @@ fun AdminQuarantineScreen(
|
||||
/** A confirm asked of the admin before a removal: which one, and of which track. */
|
||||
private enum class Removal { File, Library }
|
||||
|
||||
private data class PendingRemoval(val row: AdminQuarantineItemRef, val kind: Removal)
|
||||
private data class PendingRemoval(
|
||||
val row: AdminQuarantineItemRef,
|
||||
val kind: Removal,
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun QueueList(
|
||||
@@ -146,20 +153,23 @@ private fun RemovalConfirm(
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
val title = pending.row.trackTitle
|
||||
val (heading, body, action) = when (pending.kind) {
|
||||
Removal.File -> Triple(
|
||||
"Remove the file?",
|
||||
"Delete the file of \u201c$title\u201d and keep the track. It waits, with its likes " +
|
||||
"and plays, and takes over a good copy when one is in the library. Its reports are cleared.",
|
||||
"Remove the file",
|
||||
)
|
||||
Removal.Library -> Triple(
|
||||
"Remove from library?",
|
||||
"Remove \u201c$title\u201d and its file for good, with its likes, plays and playlist " +
|
||||
"places. To keep the track for a good copy, remove the file instead.",
|
||||
"Remove from library",
|
||||
)
|
||||
}
|
||||
val (heading, body, action) =
|
||||
when (pending.kind) {
|
||||
Removal.File ->
|
||||
Triple(
|
||||
"Remove the file?",
|
||||
"Delete the file of \u201c$title\u201d and keep the track. It waits, with its likes " +
|
||||
"and plays, and takes over a good copy when one is in the library. Its reports are cleared.",
|
||||
"Remove the file",
|
||||
)
|
||||
Removal.Library ->
|
||||
Triple(
|
||||
"Remove from library?",
|
||||
"Remove \u201c$title\u201d and its file for good, with its likes, plays and playlist " +
|
||||
"places. To keep the track for a good copy, remove the file instead.",
|
||||
"Remove from library",
|
||||
)
|
||||
}
|
||||
ConfirmDestructiveDialog(
|
||||
title = heading,
|
||||
text = body,
|
||||
@@ -177,9 +187,10 @@ private fun QuarantineRow(
|
||||
onDeleteFile: () -> Unit,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Text(
|
||||
|
||||
+60
-53
@@ -27,62 +27,69 @@ import javax.inject.Inject
|
||||
typealias AdminQuarantineUiState = UiState<List<AdminQuarantineItemRef>>
|
||||
|
||||
@HiltViewModel
|
||||
class AdminQuarantineViewModel @Inject constructor(
|
||||
private val repository: AdminQuarantineRepository,
|
||||
private val eventsStream: EventsStream,
|
||||
networkStatus: NetworkStatusController,
|
||||
) : ViewModel() {
|
||||
class AdminQuarantineViewModel
|
||||
@Inject
|
||||
constructor(
|
||||
private val repository: AdminQuarantineRepository,
|
||||
private val eventsStream: EventsStream,
|
||||
networkStatus: NetworkStatusController,
|
||||
) : ViewModel() {
|
||||
private val internal = MutableStateFlow<AdminQuarantineUiState>(UiState.Loading)
|
||||
val uiState: StateFlow<AdminQuarantineUiState> = internal.asStateFlow()
|
||||
|
||||
private val internal = MutableStateFlow<AdminQuarantineUiState>(UiState.Loading)
|
||||
val uiState: StateFlow<AdminQuarantineUiState> = internal.asStateFlow()
|
||||
/**
|
||||
* One-shot messages for the screen's snackbar. A failed action has to say
|
||||
* why: the row quietly reappearing reads as a glitch, and for a removal
|
||||
* refused by a read-only library it hides the one thing an admin can fix.
|
||||
*/
|
||||
private val transientMessagesChannel = Channel<String>(Channel.BUFFERED)
|
||||
val transientMessages: Flow<String> = transientMessagesChannel.receiveAsFlow()
|
||||
|
||||
/**
|
||||
* One-shot messages for the screen's snackbar. A failed action has to say
|
||||
* why: the row quietly reappearing reads as a glitch, and for a removal
|
||||
* refused by a read-only library it hides the one thing an admin can fix.
|
||||
*/
|
||||
private val transientMessagesChannel = Channel<String>(Channel.BUFFERED)
|
||||
val transientMessages: Flow<String> = transientMessagesChannel.receiveAsFlow()
|
||||
|
||||
init {
|
||||
refresh()
|
||||
viewModelScope.launch {
|
||||
eventsStream.events
|
||||
.filter { it.kind.startsWith("quarantine.") }
|
||||
.collect { refresh() }
|
||||
init {
|
||||
refresh()
|
||||
viewModelScope.launch {
|
||||
eventsStream.events
|
||||
.filter { it.kind.startsWith("quarantine.") }
|
||||
.collect { refresh() }
|
||||
}
|
||||
// Screen-level auto-recovery: reload a failed list
|
||||
// when server health returns instead of waiting for a manual pull.
|
||||
viewModelScope.launch {
|
||||
networkStatus.recoveries().collect {
|
||||
if (internal.value is UiState.Error) refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
// Screen-level auto-recovery: reload a failed list
|
||||
// when server health returns instead of waiting for a manual pull.
|
||||
viewModelScope.launch {
|
||||
networkStatus.recoveries().collect {
|
||||
if (internal.value is UiState.Error) refresh()
|
||||
|
||||
fun refresh(): Job =
|
||||
viewModelScope.launch {
|
||||
internal.value = UiState.Loading
|
||||
internal.value = loadUiState { repository.list().toListState() }
|
||||
}
|
||||
|
||||
fun resolve(trackId: String) = act(trackId) { repository.resolve(it) }
|
||||
|
||||
fun removeFile(trackId: String) = act(trackId) { repository.removeFile(it) }
|
||||
|
||||
fun deleteFile(trackId: String) = act(trackId) { repository.deleteFile(it) }
|
||||
|
||||
private fun act(
|
||||
trackId: String,
|
||||
action: suspend (String) -> Unit,
|
||||
) {
|
||||
val before = internal.value
|
||||
if (before is UiState.Success) {
|
||||
internal.value = before.data.filterNot { it.trackId == trackId }.toListState()
|
||||
}
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
action(trackId)
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
||||
) {
|
||||
transientMessagesChannel.trySend(ErrorCopy.fromThrowable(e))
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun refresh(): Job = viewModelScope.launch {
|
||||
internal.value = UiState.Loading
|
||||
internal.value = loadUiState { repository.list().toListState() }
|
||||
}
|
||||
|
||||
fun resolve(trackId: String) = act(trackId) { repository.resolve(it) }
|
||||
fun removeFile(trackId: String) = act(trackId) { repository.removeFile(it) }
|
||||
fun deleteFile(trackId: String) = act(trackId) { repository.deleteFile(it) }
|
||||
|
||||
private fun act(trackId: String, action: suspend (String) -> Unit) {
|
||||
val before = internal.value
|
||||
if (before is UiState.Success) {
|
||||
internal.value = before.data.filterNot { it.trackId == trackId }.toListState()
|
||||
}
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
action(trackId)
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
||||
) {
|
||||
transientMessagesChannel.trySend(ErrorCopy.fromThrowable(e))
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+24
-18
@@ -36,12 +36,12 @@ import com.fabledsword.minstrel.models.AdminTagSourceRef
|
||||
import com.fabledsword.minstrel.models.TagSourceTestResult
|
||||
import com.fabledsword.minstrel.nav.AdminTagSources
|
||||
import com.fabledsword.minstrel.shared.UiState
|
||||
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
|
||||
import com.fabledsword.minstrel.shared.widgets.EmptyState
|
||||
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
|
||||
import com.fabledsword.minstrel.shared.widgets.LoadingCentered
|
||||
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
|
||||
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
|
||||
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
@@ -68,22 +68,25 @@ fun AdminTagSourcesScreen(
|
||||
) {
|
||||
when (val s = state) {
|
||||
UiState.Loading -> LoadingCentered()
|
||||
UiState.Empty -> EmptyState(
|
||||
title = "No tag sources",
|
||||
body = "Tag-enrichment providers register on the server; none are available.",
|
||||
)
|
||||
is UiState.Error -> ErrorRetry(
|
||||
title = "Couldn't load tag sources",
|
||||
message = s.message,
|
||||
onRetry = { viewModel.refresh() },
|
||||
)
|
||||
is UiState.Success -> TagSourceList(
|
||||
providers = s.data.providers,
|
||||
testResults = s.data.testResults,
|
||||
onToggle = viewModel::setEnabled,
|
||||
onSaveKey = viewModel::saveApiKey,
|
||||
onTest = viewModel::test,
|
||||
)
|
||||
UiState.Empty ->
|
||||
EmptyState(
|
||||
title = "No tag sources",
|
||||
body = "Tag-enrichment providers register on the server; none are available.",
|
||||
)
|
||||
is UiState.Error ->
|
||||
ErrorRetry(
|
||||
title = "Couldn't load tag sources",
|
||||
message = s.message,
|
||||
onRetry = { viewModel.refresh() },
|
||||
)
|
||||
is UiState.Success ->
|
||||
TagSourceList(
|
||||
providers = s.data.providers,
|
||||
testResults = s.data.testResults,
|
||||
onToggle = viewModel::setEnabled,
|
||||
onSaveKey = viewModel::saveApiKey,
|
||||
onTest = viewModel::test,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -156,7 +159,10 @@ private fun TagSourceCard(
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ApiKeyRow(provider: AdminTagSourceRef, onSaveKey: (String, String) -> Unit) {
|
||||
private fun ApiKeyRow(
|
||||
provider: AdminTagSourceRef,
|
||||
onSaveKey: (String, String) -> Unit,
|
||||
) {
|
||||
var key by remember(provider.id) { mutableStateOf("") }
|
||||
OutlinedTextField(
|
||||
value = key,
|
||||
|
||||
+82
-69
@@ -28,86 +28,99 @@ data class AdminTagSources(
|
||||
typealias AdminTagSourcesUiState = UiState<AdminTagSources>
|
||||
|
||||
@HiltViewModel
|
||||
class AdminTagSourcesViewModel @Inject constructor(
|
||||
private val repository: AdminTagSourcesRepository,
|
||||
networkStatus: NetworkStatusController,
|
||||
) : ViewModel() {
|
||||
class AdminTagSourcesViewModel
|
||||
@Inject
|
||||
constructor(
|
||||
private val repository: AdminTagSourcesRepository,
|
||||
networkStatus: NetworkStatusController,
|
||||
) : ViewModel() {
|
||||
private val internal = MutableStateFlow<AdminTagSourcesUiState>(UiState.Loading)
|
||||
val uiState: StateFlow<AdminTagSourcesUiState> = internal.asStateFlow()
|
||||
|
||||
private val internal = MutableStateFlow<AdminTagSourcesUiState>(UiState.Loading)
|
||||
val uiState: StateFlow<AdminTagSourcesUiState> = internal.asStateFlow()
|
||||
|
||||
init {
|
||||
refresh()
|
||||
// Screen-level auto-recovery: reload a failed list when server
|
||||
// health returns instead of waiting for a manual pull.
|
||||
viewModelScope.launch {
|
||||
networkStatus.recoveries().collect {
|
||||
if (internal.value is UiState.Error) refresh()
|
||||
init {
|
||||
refresh()
|
||||
// Screen-level auto-recovery: reload a failed list when server
|
||||
// health returns instead of waiting for a manual pull.
|
||||
viewModelScope.launch {
|
||||
networkStatus.recoveries().collect {
|
||||
if (internal.value is UiState.Error) refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun refresh(): Job = viewModelScope.launch {
|
||||
internal.value = UiState.Loading
|
||||
internal.value = loadUiState {
|
||||
val providers = repository.list()
|
||||
if (providers.isEmpty()) UiState.Empty else UiState.Success(AdminTagSources(providers))
|
||||
}
|
||||
}
|
||||
fun refresh(): Job =
|
||||
viewModelScope.launch {
|
||||
internal.value = UiState.Loading
|
||||
internal.value =
|
||||
loadUiState {
|
||||
val providers = repository.list()
|
||||
if (providers.isEmpty()) UiState.Empty else UiState.Success(AdminTagSources(providers))
|
||||
}
|
||||
}
|
||||
|
||||
fun setEnabled(id: String, enabled: Boolean) {
|
||||
val before = (internal.value as? UiState.Success<AdminTagSources>)?.data ?: return
|
||||
// Optimistic toggle; reconcile via refresh() if the server rejects.
|
||||
internal.value = UiState.Success(
|
||||
before.copy(
|
||||
providers = before.providers.map {
|
||||
if (it.id == id) it.copy(enabled = enabled) else it
|
||||
},
|
||||
),
|
||||
)
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
repository.setEnabled(id, enabled)
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
|
||||
) {
|
||||
refresh()
|
||||
fun setEnabled(
|
||||
id: String,
|
||||
enabled: Boolean,
|
||||
) {
|
||||
val before = (internal.value as? UiState.Success<AdminTagSources>)?.data ?: return
|
||||
// Optimistic toggle; reconcile via refresh() if the server rejects.
|
||||
internal.value =
|
||||
UiState.Success(
|
||||
before.copy(
|
||||
providers =
|
||||
before.providers.map {
|
||||
if (it.id == id) it.copy(enabled = enabled) else it
|
||||
},
|
||||
),
|
||||
)
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
repository.setEnabled(id, enabled)
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
|
||||
) {
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun saveApiKey(id: String, apiKey: String) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
replaceProvider(repository.setApiKey(id, apiKey))
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
|
||||
) {
|
||||
refresh()
|
||||
fun saveApiKey(
|
||||
id: String,
|
||||
apiKey: String,
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
replaceProvider(repository.setApiKey(id, apiKey))
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
|
||||
) {
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun test(id: String) {
|
||||
viewModelScope.launch {
|
||||
val result = try {
|
||||
repository.test(id)
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
||||
) {
|
||||
TagSourceTestResult(ok = false, error = ErrorCopy.fromThrowable(e))
|
||||
fun test(id: String) {
|
||||
viewModelScope.launch {
|
||||
val result =
|
||||
try {
|
||||
repository.test(id)
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
||||
) {
|
||||
TagSourceTestResult(ok = false, error = ErrorCopy.fromThrowable(e))
|
||||
}
|
||||
val current = (internal.value as? UiState.Success<AdminTagSources>)?.data ?: return@launch
|
||||
internal.value = UiState.Success(current.copy(testResults = current.testResults + (id to result)))
|
||||
}
|
||||
val current = (internal.value as? UiState.Success<AdminTagSources>)?.data ?: return@launch
|
||||
internal.value = UiState.Success(current.copy(testResults = current.testResults + (id to result)))
|
||||
}
|
||||
|
||||
private fun replaceProvider(updated: AdminTagSourceRef) {
|
||||
val current = (internal.value as? UiState.Success<AdminTagSources>)?.data ?: return
|
||||
internal.value =
|
||||
UiState.Success(
|
||||
current.copy(
|
||||
providers = current.providers.map { if (it.id == updated.id) updated else it },
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun replaceProvider(updated: AdminTagSourceRef) {
|
||||
val current = (internal.value as? UiState.Success<AdminTagSources>)?.data ?: return
|
||||
internal.value = UiState.Success(
|
||||
current.copy(
|
||||
providers = current.providers.map { if (it.id == updated.id) updated else it },
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,37 +2,27 @@
|
||||
|
||||
package com.fabledsword.minstrel.admin.ui
|
||||
|
||||
import android.content.ClipData
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import com.composables.icons.lucide.Lucide
|
||||
import com.composables.icons.lucide.Copy
|
||||
import com.composables.icons.lucide.KeyRound
|
||||
import com.composables.icons.lucide.Plus
|
||||
import com.composables.icons.lucide.Trash2
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import android.content.ClipData
|
||||
import androidx.compose.ui.platform.ClipEntry
|
||||
import androidx.compose.ui.platform.LocalClipboard
|
||||
import com.fabledsword.minstrel.auth.PasswordRules
|
||||
import com.fabledsword.minstrel.models.Invite
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
@@ -42,19 +32,28 @@ import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.ClipEntry
|
||||
import androidx.compose.ui.platform.LocalClipboard
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.navigation.NavHostController
|
||||
import com.composables.icons.lucide.Copy
|
||||
import com.composables.icons.lucide.KeyRound
|
||||
import com.composables.icons.lucide.Lucide
|
||||
import com.composables.icons.lucide.Plus
|
||||
import com.composables.icons.lucide.Trash2
|
||||
import com.fabledsword.minstrel.auth.PasswordRules
|
||||
import com.fabledsword.minstrel.models.AdminUserRef
|
||||
import com.fabledsword.minstrel.models.Invite
|
||||
import com.fabledsword.minstrel.nav.AdminUsers
|
||||
import com.fabledsword.minstrel.shared.UiState
|
||||
import com.fabledsword.minstrel.shared.widgets.ConfirmDestructiveDialog
|
||||
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
|
||||
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
|
||||
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
|
||||
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@Composable
|
||||
@@ -175,11 +174,15 @@ private fun AdminUsersScaffold(
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SectionHeader(label: String, trailing: (@Composable () -> Unit)? = null) {
|
||||
private fun SectionHeader(
|
||||
label: String,
|
||||
trailing: (@Composable () -> Unit)? = null,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
@@ -202,15 +205,16 @@ private fun androidx.compose.foundation.lazy.LazyListScope.usersSection(
|
||||
UiState.Loading -> item { CenteredHint("Loading users…") }
|
||||
UiState.Empty -> item { CenteredHint("No registered users.") }
|
||||
is UiState.Error -> item { CenteredHint(state.message) }
|
||||
is UiState.Success -> items(items = state.data, key = { it.id }) { user ->
|
||||
UserRow(
|
||||
user = user,
|
||||
onSetAdmin = { onSetAdmin(user.id, it) },
|
||||
onResetPassword = { onAskResetPassword(user) },
|
||||
onDelete = { onAskDelete(user) },
|
||||
)
|
||||
HorizontalDivider()
|
||||
}
|
||||
is UiState.Success ->
|
||||
items(items = state.data, key = { it.id }) { user ->
|
||||
UserRow(
|
||||
user = user,
|
||||
onSetAdmin = { onSetAdmin(user.id, it) },
|
||||
onResetPassword = { onAskResetPassword(user) },
|
||||
onDelete = { onAskDelete(user) },
|
||||
)
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -220,13 +224,15 @@ private fun androidx.compose.foundation.lazy.LazyListScope.invitesSection(
|
||||
) {
|
||||
when {
|
||||
state.isLoading -> item { CenteredHint("Loading invites…") }
|
||||
state.invites.isEmpty() -> item {
|
||||
CenteredHint("No active invites. Use Generate to create one.")
|
||||
}
|
||||
else -> items(items = state.invites, key = { it.token }) { invite ->
|
||||
InviteRow(invite = invite, onRevoke = { onRevoke(invite.token) })
|
||||
HorizontalDivider()
|
||||
}
|
||||
state.invites.isEmpty() ->
|
||||
item {
|
||||
CenteredHint("No active invites. Use Generate to create one.")
|
||||
}
|
||||
else ->
|
||||
items(items = state.invites, key = { it.token }) { invite ->
|
||||
InviteRow(invite = invite, onRevoke = { onRevoke(invite.token) })
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,11 +247,15 @@ private fun CenteredHint(text: String) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun InviteRow(invite: Invite, onRevoke: () -> Unit) {
|
||||
private fun InviteRow(
|
||||
invite: Invite,
|
||||
onRevoke: () -> Unit,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
@@ -256,13 +266,14 @@ private fun InviteRow(invite: Invite, onRevoke: () -> Unit) {
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
val subtitle = buildString {
|
||||
if (!invite.note.isNullOrEmpty()) {
|
||||
append(invite.note)
|
||||
append(" · ")
|
||||
val subtitle =
|
||||
buildString {
|
||||
if (!invite.note.isNullOrEmpty()) {
|
||||
append(invite.note)
|
||||
append(" · ")
|
||||
}
|
||||
append(if (invite.isRedeemed) "redeemed" else "expires ${invite.expiresAt}")
|
||||
}
|
||||
append(if (invite.isRedeemed) "redeemed" else "expires ${invite.expiresAt}")
|
||||
}
|
||||
Text(
|
||||
text = subtitle,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
@@ -284,7 +295,10 @@ private fun InviteRow(invite: Invite, onRevoke: () -> Unit) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GenerateInviteDialog(onDismiss: () -> Unit, onConfirm: (String?) -> Unit) {
|
||||
private fun GenerateInviteDialog(
|
||||
onDismiss: () -> Unit,
|
||||
onConfirm: (String?) -> Unit,
|
||||
) {
|
||||
var note by remember { mutableStateOf("") }
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
@@ -317,7 +331,10 @@ private fun GenerateInviteDialog(onDismiss: () -> Unit, onConfirm: (String?) ->
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GeneratedInviteDialog(invite: Invite, onDismiss: () -> Unit) {
|
||||
private fun GeneratedInviteDialog(
|
||||
invite: Invite,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
val clipboard = LocalClipboard.current
|
||||
val scope = rememberCoroutineScope()
|
||||
AlertDialog(
|
||||
@@ -399,9 +416,10 @@ private fun UserRow(
|
||||
onDelete: () -> Unit,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Text(
|
||||
@@ -444,7 +462,11 @@ private fun UserRow(
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ToggleRow(label: String, checked: Boolean, onChange: (Boolean) -> Unit) {
|
||||
private fun ToggleRow(
|
||||
label: String,
|
||||
checked: Boolean,
|
||||
onChange: (Boolean) -> Unit,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
@@ -496,8 +518,9 @@ private fun DeleteConfirmDialog(
|
||||
) {
|
||||
ConfirmDestructiveDialog(
|
||||
title = "Delete user?",
|
||||
text = "Delete @${user.username}? This removes the account and all " +
|
||||
"their data. Type $DELETE_CONFIRM_WORD to confirm.",
|
||||
text =
|
||||
"Delete @${user.username}? This removes the account and all " +
|
||||
"their data. Type $DELETE_CONFIRM_WORD to confirm.",
|
||||
confirmLabel = "Delete",
|
||||
onConfirm = onConfirm,
|
||||
onDismiss = onDismiss,
|
||||
@@ -506,4 +529,3 @@ private fun DeleteConfirmDialog(
|
||||
}
|
||||
|
||||
private const val DELETE_CONFIRM_WORD = "DELETE"
|
||||
|
||||
|
||||
+78
-69
@@ -21,77 +21,86 @@ import javax.inject.Inject
|
||||
typealias AdminUsersUiState = UiState<List<AdminUserRef>>
|
||||
|
||||
@HiltViewModel
|
||||
class AdminUsersViewModel @Inject constructor(
|
||||
private val repository: AdminUsersRepository,
|
||||
networkStatus: NetworkStatusController,
|
||||
) : ViewModel() {
|
||||
class AdminUsersViewModel
|
||||
@Inject
|
||||
constructor(
|
||||
private val repository: AdminUsersRepository,
|
||||
networkStatus: NetworkStatusController,
|
||||
) : ViewModel() {
|
||||
private val internal = MutableStateFlow<AdminUsersUiState>(UiState.Loading)
|
||||
val uiState: StateFlow<AdminUsersUiState> = internal.asStateFlow()
|
||||
|
||||
private val internal = MutableStateFlow<AdminUsersUiState>(UiState.Loading)
|
||||
val uiState: StateFlow<AdminUsersUiState> = internal.asStateFlow()
|
||||
init {
|
||||
refresh()
|
||||
// Screen-level auto-recovery: reload a failed list
|
||||
// when server health returns instead of waiting for a manual pull.
|
||||
viewModelScope.launch {
|
||||
networkStatus.recoveries().collect {
|
||||
if (internal.value is UiState.Error) refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
refresh()
|
||||
// Screen-level auto-recovery: reload a failed list
|
||||
// when server health returns instead of waiting for a manual pull.
|
||||
viewModelScope.launch {
|
||||
networkStatus.recoveries().collect {
|
||||
if (internal.value is UiState.Error) refresh()
|
||||
fun refresh(): Job =
|
||||
viewModelScope.launch {
|
||||
internal.value = UiState.Loading
|
||||
internal.value = loadUiState { repository.list().toListState() }
|
||||
}
|
||||
|
||||
fun setAdmin(
|
||||
id: String,
|
||||
isAdmin: Boolean,
|
||||
) = patch(id, { it.copy(isAdmin = isAdmin) }) {
|
||||
repository.setAdmin(it, isAdmin)
|
||||
}
|
||||
|
||||
fun resetPassword(
|
||||
id: String,
|
||||
newPassword: String,
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
runCatching { repository.resetPassword(id, newPassword) }
|
||||
}
|
||||
}
|
||||
|
||||
fun delete(id: String) {
|
||||
val before = internal.value
|
||||
if (before is UiState.Success) {
|
||||
internal.value = before.data.filterNot { it.id == id }.toListState()
|
||||
}
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
repository.delete(id)
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
|
||||
) {
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun patch(
|
||||
id: String,
|
||||
mutate: (AdminUserRef) -> AdminUserRef,
|
||||
action: suspend (String) -> Unit,
|
||||
) {
|
||||
val before = internal.value
|
||||
if (before is UiState.Success) {
|
||||
internal.value =
|
||||
UiState.Success(
|
||||
before.data.map { if (it.id == id) mutate(it) else it },
|
||||
)
|
||||
}
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
action(id)
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
|
||||
) {
|
||||
// Server-side guard might have rejected the toggle (e.g.
|
||||
// last-admin protection); refetch reconciles state.
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun refresh(): Job = viewModelScope.launch {
|
||||
internal.value = UiState.Loading
|
||||
internal.value = loadUiState { repository.list().toListState() }
|
||||
}
|
||||
|
||||
fun setAdmin(id: String, isAdmin: Boolean) = patch(id, { it.copy(isAdmin = isAdmin) }) {
|
||||
repository.setAdmin(it, isAdmin)
|
||||
}
|
||||
|
||||
fun resetPassword(id: String, newPassword: String) {
|
||||
viewModelScope.launch {
|
||||
runCatching { repository.resetPassword(id, newPassword) }
|
||||
}
|
||||
}
|
||||
|
||||
fun delete(id: String) {
|
||||
val before = internal.value
|
||||
if (before is UiState.Success) {
|
||||
internal.value = before.data.filterNot { it.id == id }.toListState()
|
||||
}
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
repository.delete(id)
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
|
||||
) {
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun patch(
|
||||
id: String,
|
||||
mutate: (AdminUserRef) -> AdminUserRef,
|
||||
action: suspend (String) -> Unit,
|
||||
) {
|
||||
val before = internal.value
|
||||
if (before is UiState.Success) {
|
||||
internal.value = UiState.Success(
|
||||
before.data.map { if (it.id == id) mutate(it) else it },
|
||||
)
|
||||
}
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
action(id)
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
|
||||
) {
|
||||
// Server-side guard might have rejected the toggle (e.g.
|
||||
// last-admin protection); refetch reconciles state.
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,43 +20,47 @@ import javax.inject.Singleton
|
||||
* from any of those hosts would sign the user out of Minstrel.
|
||||
*/
|
||||
@Singleton
|
||||
class AuthCookieInterceptor @Inject constructor(
|
||||
private val authStore: AuthStore,
|
||||
) : Interceptor {
|
||||
|
||||
override fun intercept(chain: Interceptor.Chain): Response {
|
||||
val original = chain.request()
|
||||
if (original.url.host != BaseUrlInterceptor.PLACEHOLDER_HOST) {
|
||||
// External request — no Minstrel session cookie attached,
|
||||
// and a 401 from this host does NOT clear the user's
|
||||
// session. Pass through untouched.
|
||||
return chain.proceed(original)
|
||||
}
|
||||
val cookie = authStore.sessionCookieForRequest()
|
||||
val request = original.newBuilder().apply {
|
||||
if (!cookie.isNullOrEmpty()) header("Cookie", cookie)
|
||||
}.build()
|
||||
|
||||
val response = chain.proceed(request)
|
||||
|
||||
if (response.code == HTTP_UNAUTHORIZED) {
|
||||
// Only a refusal of the cookie this request carried ends the
|
||||
// session. A request sent without one says nothing about the
|
||||
// stored login, and a refusal of an older cookie must not
|
||||
// discard one a sign-in has stored since.
|
||||
if (!cookie.isNullOrEmpty()) authStore.dropRejectedSessionCookie(cookie)
|
||||
} else if (response.isSuccessful) {
|
||||
// Capture the first Set-Cookie pair on login; subsequent
|
||||
// responses that include Set-Cookie keep the store fresh.
|
||||
response.headers("Set-Cookie").firstOrNull()?.let { sc ->
|
||||
val firstPair = sc.substringBefore(';')
|
||||
if (firstPair.isNotBlank()) authStore.setSessionCookie(firstPair)
|
||||
class AuthCookieInterceptor
|
||||
@Inject
|
||||
constructor(
|
||||
private val authStore: AuthStore,
|
||||
) : Interceptor {
|
||||
override fun intercept(chain: Interceptor.Chain): Response {
|
||||
val original = chain.request()
|
||||
if (original.url.host != BaseUrlInterceptor.PLACEHOLDER_HOST) {
|
||||
// External request — no Minstrel session cookie attached,
|
||||
// and a 401 from this host does NOT clear the user's
|
||||
// session. Pass through untouched.
|
||||
return chain.proceed(original)
|
||||
}
|
||||
}
|
||||
return response
|
||||
}
|
||||
val cookie = authStore.sessionCookieForRequest()
|
||||
val request =
|
||||
original
|
||||
.newBuilder()
|
||||
.apply {
|
||||
if (!cookie.isNullOrEmpty()) header("Cookie", cookie)
|
||||
}.build()
|
||||
|
||||
private companion object {
|
||||
const val HTTP_UNAUTHORIZED = 401
|
||||
val response = chain.proceed(request)
|
||||
|
||||
if (response.code == HTTP_UNAUTHORIZED) {
|
||||
// Only a refusal of the cookie this request carried ends the
|
||||
// session. A request sent without one says nothing about the
|
||||
// stored login, and a refusal of an older cookie must not
|
||||
// discard one a sign-in has stored since.
|
||||
if (!cookie.isNullOrEmpty()) authStore.dropRejectedSessionCookie(cookie)
|
||||
} else if (response.isSuccessful) {
|
||||
// Capture the first Set-Cookie pair on login; subsequent
|
||||
// responses that include Set-Cookie keep the store fresh.
|
||||
response.headers("Set-Cookie").firstOrNull()?.let { sc ->
|
||||
val firstPair = sc.substringBefore(';')
|
||||
if (firstPair.isNotBlank()) authStore.setSessionCookie(firstPair)
|
||||
}
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val HTTP_UNAUTHORIZED = 401
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,39 +31,43 @@ import javax.inject.Singleton
|
||||
* error in the caller's normal error path.
|
||||
*/
|
||||
@Singleton
|
||||
class BaseUrlInterceptor @Inject constructor(
|
||||
private val authStore: AuthStore,
|
||||
) : Interceptor {
|
||||
class BaseUrlInterceptor
|
||||
@Inject
|
||||
constructor(
|
||||
private val authStore: AuthStore,
|
||||
) : Interceptor {
|
||||
override fun intercept(chain: Interceptor.Chain): Response {
|
||||
val original = chain.request()
|
||||
// Early-bail keeps the no-op path for external URLs cheap
|
||||
// (no AuthStore read, no URL parse).
|
||||
if (original.url.host != PLACEHOLDER_HOST) return chain.proceed(original)
|
||||
// Unparseable baseUrl folds into the same proceed path — keeps
|
||||
// detekt's ReturnCount happy by avoiding a second early return.
|
||||
val rewritten: HttpUrl =
|
||||
authStore.baseUrl.value.toHttpUrlOrNull()?.let { baseUrl ->
|
||||
original.url
|
||||
.newBuilder()
|
||||
.scheme(baseUrl.scheme)
|
||||
.host(baseUrl.host)
|
||||
.port(baseUrl.port)
|
||||
.build()
|
||||
} ?: original.url
|
||||
return chain.proceed(
|
||||
original
|
||||
.newBuilder()
|
||||
.url(rewritten)
|
||||
// Lets CleartextGuardInterceptor tell server requests from
|
||||
// external fetches once the placeholder host is gone.
|
||||
.tag(MinstrelServerRequest::class.java, MinstrelServerRequest)
|
||||
.build(),
|
||||
)
|
||||
}
|
||||
|
||||
override fun intercept(chain: Interceptor.Chain): Response {
|
||||
val original = chain.request()
|
||||
// Early-bail keeps the no-op path for external URLs cheap
|
||||
// (no AuthStore read, no URL parse).
|
||||
if (original.url.host != PLACEHOLDER_HOST) return chain.proceed(original)
|
||||
// Unparseable baseUrl folds into the same proceed path — keeps
|
||||
// detekt's ReturnCount happy by avoiding a second early return.
|
||||
val rewritten: HttpUrl = authStore.baseUrl.value.toHttpUrlOrNull()?.let { baseUrl ->
|
||||
original.url.newBuilder()
|
||||
.scheme(baseUrl.scheme)
|
||||
.host(baseUrl.host)
|
||||
.port(baseUrl.port)
|
||||
.build()
|
||||
} ?: original.url
|
||||
return chain.proceed(
|
||||
original.newBuilder()
|
||||
.url(rewritten)
|
||||
// Lets CleartextGuardInterceptor tell server requests from
|
||||
// external fetches once the placeholder host is gone.
|
||||
.tag(MinstrelServerRequest::class.java, MinstrelServerRequest)
|
||||
.build(),
|
||||
)
|
||||
companion object {
|
||||
/** Sentinel host used by Retrofit + every code path that builds
|
||||
* a Minstrel-server URL via the `http://placeholder.invalid/...`
|
||||
* form (see [com.fabledsword.minstrel.shared.resolveServerUrl],
|
||||
* CoverUrls.kt, AlbumRef/TrackRef cover getters). */
|
||||
const val PLACEHOLDER_HOST = "placeholder.invalid"
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** Sentinel host used by Retrofit + every code path that builds
|
||||
* a Minstrel-server URL via the `http://placeholder.invalid/...`
|
||||
* form (see [com.fabledsword.minstrel.shared.resolveServerUrl],
|
||||
* CoverUrls.kt, AlbumRef/TrackRef cover getters). */
|
||||
const val PLACEHOLDER_HOST = "placeholder.invalid"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,7 +39,12 @@ class CleartextGuardInterceptor(
|
||||
if (request.isHttps || request.tag(MinstrelServerRequest::class.java) == null) {
|
||||
return chain.proceed(request)
|
||||
}
|
||||
val address = chain.connection()?.route()?.socketAddress?.address
|
||||
val address =
|
||||
chain
|
||||
.connection()
|
||||
?.route()
|
||||
?.socketAddress
|
||||
?.address
|
||||
if (address != null && !allows(address)) {
|
||||
throw CleartextToPublicHostException(request.url.host)
|
||||
}
|
||||
@@ -48,8 +53,9 @@ class CleartextGuardInterceptor(
|
||||
}
|
||||
|
||||
/** The server was reached over plain HTTP at a public address, and refused. */
|
||||
class CleartextToPublicHostException(host: String) :
|
||||
IOException("refusing plain http:// to $host: it is a public address")
|
||||
class CleartextToPublicHostException(
|
||||
host: String,
|
||||
) : IOException("refusing plain http:// to $host: it is a public address")
|
||||
|
||||
/** Which addresses plain HTTP may reach: the home network, never the internet. */
|
||||
object CleartextPolicy {
|
||||
@@ -62,8 +68,10 @@ object CleartextPolicy {
|
||||
|
||||
fun allows(address: InetAddress): Boolean =
|
||||
address.isLoopbackAddress ||
|
||||
address.isSiteLocalAddress || // 10/8, 172.16/12, 192.168/16
|
||||
address.isLinkLocalAddress || // 169.254/16, fe80::/10
|
||||
address.isSiteLocalAddress ||
|
||||
// 10/8, 172.16/12, 192.168/16
|
||||
address.isLinkLocalAddress ||
|
||||
// 169.254/16, fe80::/10
|
||||
address.isAnyLocalAddress ||
|
||||
isCarrierGradeNat(address) ||
|
||||
isUniqueLocal(address)
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.fabledsword.minstrel.api
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
import retrofit2.HttpException
|
||||
@@ -23,10 +22,15 @@ object ErrorCopy {
|
||||
private val json = Json { ignoreUnknownKeys = true }
|
||||
|
||||
@Serializable
|
||||
private data class Envelope(val error: Body? = null)
|
||||
private data class Envelope(
|
||||
val error: Body? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
private data class Body(val code: String = "", val message: String = "")
|
||||
private data class Body(
|
||||
val code: String = "",
|
||||
val message: String = "",
|
||||
)
|
||||
|
||||
/** Friendly copy for a known error [code], or the `unknown` fallback. */
|
||||
fun messageFor(code: String): String = TABLE[code] ?: TABLE.getValue("unknown")
|
||||
@@ -36,12 +40,13 @@ object ErrorCopy {
|
||||
* HttpException bodies for the server code; treats IOExceptions
|
||||
* as connection failures.
|
||||
*/
|
||||
fun fromThrowable(t: Throwable): String = when (t) {
|
||||
is HttpException -> fromHttp(t)
|
||||
is CleartextToPublicHostException -> messageFor("cleartext_public")
|
||||
is IOException -> messageFor("connection_refused")
|
||||
else -> TABLE.getValue("unknown")
|
||||
}
|
||||
fun fromThrowable(t: Throwable): String =
|
||||
when (t) {
|
||||
is HttpException -> fromHttp(t)
|
||||
is CleartextToPublicHostException -> messageFor("cleartext_public")
|
||||
is IOException -> messageFor("connection_refused")
|
||||
else -> TABLE.getValue("unknown")
|
||||
}
|
||||
|
||||
/**
|
||||
* Codes whose server message carries specifics an admin needs in order
|
||||
@@ -65,8 +70,9 @@ object ErrorCopy {
|
||||
}
|
||||
|
||||
private fun bodyFromHttp(e: HttpException): Body {
|
||||
val raw = runCatching { e.response()?.errorBody()?.string() }.getOrNull()
|
||||
?: return Body()
|
||||
val raw =
|
||||
runCatching { e.response()?.errorBody()?.string() }.getOrNull()
|
||||
?: return Body()
|
||||
return runCatching { json.decodeFromString<Envelope>(raw).error }
|
||||
.getOrNull() ?: Body()
|
||||
}
|
||||
|
||||
@@ -28,7 +28,6 @@ import javax.inject.Singleton
|
||||
@Module
|
||||
@InstallIn(SingletonComponent::class)
|
||||
object NetworkModule {
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideHttpLogging(): HttpLoggingInterceptor =
|
||||
@@ -49,7 +48,8 @@ object NetworkModule {
|
||||
reachability: ReachabilityReportingInterceptor,
|
||||
logging: HttpLoggingInterceptor,
|
||||
): OkHttpClient =
|
||||
OkHttpClient.Builder()
|
||||
OkHttpClient
|
||||
.Builder()
|
||||
// ReachabilityReportingInterceptor MUST run first: it identifies
|
||||
// Minstrel-bound requests by the still-unrewritten PLACEHOLDER_HOST
|
||||
// (so external artwork fetches don't read as server reachability)
|
||||
@@ -82,7 +82,8 @@ object NetworkModule {
|
||||
okHttp: OkHttpClient,
|
||||
json: Json,
|
||||
): Retrofit =
|
||||
Retrofit.Builder()
|
||||
Retrofit
|
||||
.Builder()
|
||||
// Placeholder base URL — BaseUrlInterceptor rewrites every
|
||||
// outgoing request to the live AuthStore value, so this
|
||||
// string only has to satisfy Retrofit's parser and is
|
||||
|
||||
@@ -6,4 +6,6 @@ package com.fabledsword.minstrel.api
|
||||
* the graph.
|
||||
*/
|
||||
@JvmInline
|
||||
value class ServerBaseUrl(val value: String)
|
||||
value class ServerBaseUrl(
|
||||
val value: String,
|
||||
)
|
||||
|
||||
@@ -20,10 +20,14 @@ interface AdminInvitesApi {
|
||||
suspend fun list(): AdminInvitesListWire
|
||||
|
||||
@POST("api/admin/invites")
|
||||
suspend fun create(@Body body: CreateInviteBody): InviteWire
|
||||
suspend fun create(
|
||||
@Body body: CreateInviteBody,
|
||||
): InviteWire
|
||||
|
||||
@DELETE("api/admin/invites/{token}")
|
||||
suspend fun revoke(@Path("token") token: String)
|
||||
suspend fun revoke(
|
||||
@Path("token") token: String,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -31,4 +35,6 @@ interface AdminInvitesApi {
|
||||
* which the server treats the same as an absent field.
|
||||
*/
|
||||
@Serializable
|
||||
data class CreateInviteBody(val note: String? = null)
|
||||
data class CreateInviteBody(
|
||||
val note: String? = null,
|
||||
)
|
||||
|
||||
+9
-3
@@ -19,11 +19,17 @@ interface AdminQuarantineApi {
|
||||
suspend fun list(): List<AdminQuarantineItemWire>
|
||||
|
||||
@POST("api/admin/quarantine/{trackId}/resolve")
|
||||
suspend fun resolve(@Path("trackId") trackId: String)
|
||||
suspend fun resolve(
|
||||
@Path("trackId") trackId: String,
|
||||
)
|
||||
|
||||
@POST("api/admin/quarantine/{trackId}/remove-file")
|
||||
suspend fun removeFile(@Path("trackId") trackId: String)
|
||||
suspend fun removeFile(
|
||||
@Path("trackId") trackId: String,
|
||||
)
|
||||
|
||||
@POST("api/admin/quarantine/{trackId}/delete-file")
|
||||
suspend fun deleteFile(@Path("trackId") trackId: String)
|
||||
suspend fun deleteFile(
|
||||
@Path("trackId") trackId: String,
|
||||
)
|
||||
}
|
||||
|
||||
+7
-2
@@ -23,10 +23,15 @@ interface AdminTagSourcesApi {
|
||||
suspend fun list(): AdminTagSourcesListWire
|
||||
|
||||
@PATCH("api/admin/tag-sources/{id}")
|
||||
suspend fun update(@Path("id") id: String, @Body body: UpdateTagSourceBody): AdminTagSourceWire
|
||||
suspend fun update(
|
||||
@Path("id") id: String,
|
||||
@Body body: UpdateTagSourceBody,
|
||||
): AdminTagSourceWire
|
||||
|
||||
@POST("api/admin/tag-sources/{id}/test")
|
||||
suspend fun test(@Path("id") id: String): TestTagSourceWire
|
||||
suspend fun test(
|
||||
@Path("id") id: String,
|
||||
): TestTagSourceWire
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -15,13 +15,21 @@ interface AdminUsersApi {
|
||||
suspend fun list(): AdminUsersListWire
|
||||
|
||||
@PUT("api/admin/users/{id}/admin")
|
||||
suspend fun setAdmin(@Path("id") id: String, @Body body: SetAdminBody)
|
||||
suspend fun setAdmin(
|
||||
@Path("id") id: String,
|
||||
@Body body: SetAdminBody,
|
||||
)
|
||||
|
||||
@POST("api/admin/users/{id}/reset-password")
|
||||
suspend fun resetPassword(@Path("id") id: String, @Body body: ResetPasswordBody)
|
||||
suspend fun resetPassword(
|
||||
@Path("id") id: String,
|
||||
@Body body: ResetPasswordBody,
|
||||
)
|
||||
|
||||
@DELETE("api/admin/users/{id}")
|
||||
suspend fun delete(@Path("id") id: String)
|
||||
suspend fun delete(
|
||||
@Path("id") id: String,
|
||||
)
|
||||
}
|
||||
|
||||
@Serializable
|
||||
@@ -30,4 +38,6 @@ data class SetAdminBody(
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ResetPasswordBody(val password: String)
|
||||
data class ResetPasswordBody(
|
||||
val password: String,
|
||||
)
|
||||
|
||||
@@ -14,7 +14,9 @@ import retrofit2.http.POST
|
||||
*/
|
||||
interface AuthApi {
|
||||
@POST("api/auth/login")
|
||||
suspend fun login(@Body body: LoginRequestBody): LoginResponseWire
|
||||
suspend fun login(
|
||||
@Body body: LoginRequestBody,
|
||||
): LoginResponseWire
|
||||
|
||||
@POST("api/auth/logout")
|
||||
suspend fun logout()
|
||||
|
||||
@@ -22,7 +22,9 @@ import retrofit2.http.POST
|
||||
*/
|
||||
interface CastApi {
|
||||
@POST("api/cast/stream-token")
|
||||
suspend fun streamToken(@Body req: StreamTokenRequest): StreamTokenResponse
|
||||
suspend fun streamToken(
|
||||
@Body req: StreamTokenRequest,
|
||||
): StreamTokenResponse
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -14,7 +14,9 @@ import retrofit2.http.POST
|
||||
*/
|
||||
interface DiagnosticsApi {
|
||||
@POST("api/diagnostics")
|
||||
suspend fun report(@Body body: DiagnosticsReportRequest)
|
||||
suspend fun report(
|
||||
@Body body: DiagnosticsReportRequest,
|
||||
)
|
||||
}
|
||||
|
||||
@Serializable
|
||||
|
||||
@@ -17,14 +17,22 @@ import retrofit2.http.POST
|
||||
*/
|
||||
interface EventsApi {
|
||||
@POST("api/events")
|
||||
suspend fun playStarted(@Body body: PlayStartedRequest): PlayStartedResponse
|
||||
suspend fun playStarted(
|
||||
@Body body: PlayStartedRequest,
|
||||
): PlayStartedResponse
|
||||
|
||||
@POST("api/events")
|
||||
suspend fun playEnded(@Body body: PlayEndedRequest)
|
||||
suspend fun playEnded(
|
||||
@Body body: PlayEndedRequest,
|
||||
)
|
||||
|
||||
@POST("api/events")
|
||||
suspend fun playSkipped(@Body body: PlaySkippedRequest)
|
||||
suspend fun playSkipped(
|
||||
@Body body: PlaySkippedRequest,
|
||||
)
|
||||
|
||||
@POST("api/events")
|
||||
suspend fun playOffline(@Body body: PlayOfflineRequest)
|
||||
suspend fun playOffline(
|
||||
@Body body: PlayOfflineRequest,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -30,13 +30,19 @@ import retrofit2.http.Query
|
||||
*/
|
||||
interface LibraryApi {
|
||||
@GET("api/tracks/{id}")
|
||||
suspend fun getTrack(@Path("id") id: String): TrackWire
|
||||
suspend fun getTrack(
|
||||
@Path("id") id: String,
|
||||
): TrackWire
|
||||
|
||||
@GET("api/artists/{id}")
|
||||
suspend fun getArtistDetail(@Path("id") id: String): ArtistDetailWire
|
||||
suspend fun getArtistDetail(
|
||||
@Path("id") id: String,
|
||||
): ArtistDetailWire
|
||||
|
||||
@GET("api/artists/{id}/tracks")
|
||||
suspend fun getArtistTracks(@Path("id") id: String): List<TrackWire>
|
||||
suspend fun getArtistTracks(
|
||||
@Path("id") id: String,
|
||||
): List<TrackWire>
|
||||
|
||||
@GET("api/artists/{id}/similar")
|
||||
suspend fun getSimilarArtists(
|
||||
@@ -51,10 +57,14 @@ interface LibraryApi {
|
||||
): List<TrackWire>
|
||||
|
||||
@GET("api/albums/{id}")
|
||||
suspend fun getAlbumDetail(@Path("id") id: String): AlbumDetailWire
|
||||
suspend fun getAlbumDetail(
|
||||
@Path("id") id: String,
|
||||
): AlbumDetailWire
|
||||
|
||||
@GET("api/library/shuffle")
|
||||
suspend fun shuffleLibrary(@Query("limit") limit: Int = 100): List<TrackWire>
|
||||
suspend fun shuffleLibrary(
|
||||
@Query("limit") limit: Int = 100,
|
||||
): List<TrackWire>
|
||||
|
||||
// Browse axes. Both indexes are unpaged by design: the client needs
|
||||
// the whole set to render a browsable picker, and even a messy library
|
||||
|
||||
@@ -20,10 +20,16 @@ import retrofit2.http.Path
|
||||
*/
|
||||
interface LikesApi {
|
||||
@POST("api/likes/{kind}/{id}")
|
||||
suspend fun like(@Path("kind") kind: String, @Path("id") id: String)
|
||||
suspend fun like(
|
||||
@Path("kind") kind: String,
|
||||
@Path("id") id: String,
|
||||
)
|
||||
|
||||
@DELETE("api/likes/{kind}/{id}")
|
||||
suspend fun unlike(@Path("kind") kind: String, @Path("id") id: String)
|
||||
suspend fun unlike(
|
||||
@Path("kind") kind: String,
|
||||
@Path("id") id: String,
|
||||
)
|
||||
|
||||
@GET("api/likes/ids")
|
||||
suspend fun ids(): LikedIdsWire
|
||||
|
||||
@@ -27,14 +27,18 @@ interface MeApi {
|
||||
* state without an extra GET.
|
||||
*/
|
||||
@PUT("api/me/profile")
|
||||
suspend fun updateProfile(@Body body: UpdateProfileRequest): MyProfileWire
|
||||
suspend fun updateProfile(
|
||||
@Body body: UpdateProfileRequest,
|
||||
): MyProfileWire
|
||||
|
||||
/**
|
||||
* Change the caller's password. Server validates `current_password`
|
||||
* before accepting `new_password`. No body on success (204).
|
||||
*/
|
||||
@PUT("api/me/password")
|
||||
suspend fun changePassword(@Body body: ChangePasswordRequest)
|
||||
suspend fun changePassword(
|
||||
@Body body: ChangePasswordRequest,
|
||||
)
|
||||
|
||||
/**
|
||||
* Caller's ListenBrainz state — never returns the token itself,
|
||||
@@ -59,7 +63,9 @@ interface MeApi {
|
||||
* post-write status so callers refresh without a separate GET.
|
||||
*/
|
||||
@PUT("api/me/listenbrainz")
|
||||
suspend fun setListenBrainz(@Body body: ListenBrainzPutBody): ListenBrainzStatusWire
|
||||
suspend fun setListenBrainz(
|
||||
@Body body: ListenBrainzPutBody,
|
||||
): ListenBrainzStatusWire
|
||||
|
||||
/** The caller's loudness-normalization preference, or the defaults if never set. */
|
||||
@GET("api/me/normalization")
|
||||
@@ -67,7 +73,9 @@ interface MeApi {
|
||||
|
||||
/** Replaces the whole preference; returns what the server stored. */
|
||||
@PUT("api/me/normalization")
|
||||
suspend fun putNormalization(@Body body: NormalizationPrefs): NormalizationPrefs
|
||||
suspend fun putNormalization(
|
||||
@Body body: NormalizationPrefs,
|
||||
): NormalizationPrefs
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+18
-6
@@ -15,20 +15,28 @@ import retrofit2.http.Query
|
||||
*/
|
||||
interface NotificationsApi {
|
||||
@GET("api/me/notifications")
|
||||
suspend fun list(@Query("limit") limit: Int): NotificationsPageWire
|
||||
suspend fun list(
|
||||
@Query("limit") limit: Int,
|
||||
): NotificationsPageWire
|
||||
|
||||
/** 204; 404 when the notice is gone, which a replay treats as done. */
|
||||
@POST("api/me/notifications/{id}/read")
|
||||
suspend fun markRead(@Path("id") id: String)
|
||||
suspend fun markRead(
|
||||
@Path("id") id: String,
|
||||
)
|
||||
|
||||
@POST("api/me/notifications/read-all")
|
||||
suspend fun readAll(@Body body: ReadAllBody)
|
||||
suspend fun readAll(
|
||||
@Body body: ReadAllBody,
|
||||
)
|
||||
|
||||
@GET("api/me/notification-settings")
|
||||
suspend fun getSettings(): NotificationSettingsWire
|
||||
|
||||
@PUT("api/me/notification-settings")
|
||||
suspend fun putSettings(@Body body: PutNotificationSettingsBody): NotificationSettingsWire
|
||||
suspend fun putSettings(
|
||||
@Body body: PutNotificationSettingsBody,
|
||||
): NotificationSettingsWire
|
||||
}
|
||||
|
||||
@Serializable
|
||||
@@ -55,7 +63,9 @@ data class NotificationsPageWire(
|
||||
* the app's Json drops default-valued fields.
|
||||
*/
|
||||
@Serializable
|
||||
data class ReadAllBody(@SerialName("up_to") val upTo: String?)
|
||||
data class ReadAllBody(
|
||||
@SerialName("up_to") val upTo: String?,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class NotificationKindSettingWire(
|
||||
@@ -87,4 +97,6 @@ data class NotificationSettingChangeWire(
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class PutNotificationSettingsBody(val kinds: List<NotificationSettingChangeWire>)
|
||||
data class PutNotificationSettingsBody(
|
||||
val kinds: List<NotificationSettingChangeWire>,
|
||||
)
|
||||
|
||||
+3
-1
@@ -13,7 +13,9 @@ import retrofit2.http.POST
|
||||
*/
|
||||
interface PlaybackErrorsApi {
|
||||
@POST("api/playback-errors")
|
||||
suspend fun report(@Body body: PlaybackErrorReportRequest)
|
||||
suspend fun report(
|
||||
@Body body: PlaybackErrorReportRequest,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -24,24 +24,35 @@ interface PlaylistsApi {
|
||||
* playlists (not kind-filtered).
|
||||
*/
|
||||
@GET("api/playlists")
|
||||
suspend fun list(@Query("kind") kind: String = "all"): PlaylistsListWire
|
||||
suspend fun list(
|
||||
@Query("kind") kind: String = "all",
|
||||
): PlaylistsListWire
|
||||
|
||||
@GET("api/playlists/{id}")
|
||||
suspend fun get(@Path("id") id: String): PlaylistDetailWire
|
||||
suspend fun get(
|
||||
@Path("id") id: String,
|
||||
): PlaylistDetailWire
|
||||
|
||||
/**
|
||||
* POST /api/playlists — make a playlist under the id the app chose,
|
||||
* so a create queued offline and sent again finds the same list.
|
||||
*/
|
||||
@POST("api/playlists")
|
||||
suspend fun create(@Body body: CreatePlaylistRequest)
|
||||
suspend fun create(
|
||||
@Body body: CreatePlaylistRequest,
|
||||
)
|
||||
|
||||
/** PATCH /api/playlists/{id} — rename, or make public or private. Null fields stay as they are. */
|
||||
@PATCH("api/playlists/{id}")
|
||||
suspend fun update(@Path("id") id: String, @Body body: UpdatePlaylistRequest)
|
||||
suspend fun update(
|
||||
@Path("id") id: String,
|
||||
@Body body: UpdatePlaylistRequest,
|
||||
)
|
||||
|
||||
@DELETE("api/playlists/{id}")
|
||||
suspend fun delete(@Path("id") id: String)
|
||||
suspend fun delete(
|
||||
@Path("id") id: String,
|
||||
)
|
||||
|
||||
/**
|
||||
* DELETE /api/playlists/{id}/tracks/{position}. [trackId] is the song
|
||||
@@ -62,7 +73,10 @@ interface PlaylistsApi {
|
||||
* changes nothing the second time.
|
||||
*/
|
||||
@PUT("api/playlists/{id}/tracks")
|
||||
suspend fun reorder(@Path("id") id: String, @Body body: ReorderTracksRequest)
|
||||
suspend fun reorder(
|
||||
@Path("id") id: String,
|
||||
@Body body: ReorderTracksRequest,
|
||||
)
|
||||
|
||||
/** POST /api/playlists/{id}/tracks — append the given track IDs to the owner's playlist. */
|
||||
@POST("api/playlists/{id}/tracks")
|
||||
@@ -79,7 +93,9 @@ interface PlaylistsApi {
|
||||
* pick seed tracks. The kind is the raw system_variant.
|
||||
*/
|
||||
@POST("api/playlists/system/{kind}/refresh")
|
||||
suspend fun refreshSystem(@Path("kind") variant: String): RefreshSystemResponse
|
||||
suspend fun refreshSystem(
|
||||
@Path("kind") variant: String,
|
||||
): RefreshSystemResponse
|
||||
|
||||
/**
|
||||
* GET /api/playlists/system/{kind}/shuffle. Returns
|
||||
@@ -89,7 +105,9 @@ interface PlaylistsApi {
|
||||
* the stored order.
|
||||
*/
|
||||
@GET("api/playlists/system/{kind}/shuffle")
|
||||
suspend fun systemShuffle(@Path("kind") variant: String): PlaylistDetailWire
|
||||
suspend fun systemShuffle(
|
||||
@Path("kind") variant: String,
|
||||
): PlaylistDetailWire
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -20,10 +20,14 @@ interface QuarantineApi {
|
||||
suspend fun listMine(): List<QuarantineMineWire>
|
||||
|
||||
@POST("api/quarantine")
|
||||
suspend fun flag(@Body body: FlagRequest)
|
||||
suspend fun flag(
|
||||
@Body body: FlagRequest,
|
||||
)
|
||||
|
||||
@DELETE("api/quarantine/{trackId}")
|
||||
suspend fun unflag(@Path("trackId") trackId: String)
|
||||
suspend fun unflag(
|
||||
@Path("trackId") trackId: String,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -11,5 +11,7 @@ interface ReplayGainApi {
|
||||
* missing from `items` has not been measured yet.
|
||||
*/
|
||||
@GET("api/tracks/replay-gain")
|
||||
suspend fun getReplayGain(@Query("ids") ids: String): ReplayGainResponseWire
|
||||
suspend fun getReplayGain(
|
||||
@Query("ids") ids: String,
|
||||
): ReplayGainResponseWire
|
||||
}
|
||||
|
||||
@@ -19,5 +19,7 @@ import retrofit2.http.Query
|
||||
*/
|
||||
interface SyncApi {
|
||||
@GET("api/library/sync")
|
||||
suspend fun sync(@Query("since") since: Long): Response<SyncResponseWire>
|
||||
suspend fun sync(
|
||||
@Query("since") since: Long,
|
||||
): Response<SyncResponseWire>
|
||||
}
|
||||
|
||||
@@ -29,114 +29,124 @@ import javax.inject.Singleton
|
||||
* username after a fresh app launch without re-prompting.
|
||||
*/
|
||||
@Singleton
|
||||
class AuthController @Inject constructor(
|
||||
private val authStore: AuthStore,
|
||||
private val json: Json,
|
||||
@ApplicationScope private val scope: CoroutineScope,
|
||||
retrofit: Retrofit,
|
||||
) {
|
||||
private val api: AuthApi = retrofit.create()
|
||||
private val meApi: MeApi = retrofit.create()
|
||||
class AuthController
|
||||
@Inject
|
||||
constructor(
|
||||
private val authStore: AuthStore,
|
||||
private val json: Json,
|
||||
@ApplicationScope private val scope: CoroutineScope,
|
||||
retrofit: Retrofit,
|
||||
) {
|
||||
private val api: AuthApi = retrofit.create()
|
||||
private val meApi: MeApi = retrofit.create()
|
||||
|
||||
private val currentUserState = MutableStateFlow<UserRef?>(null)
|
||||
val currentUser: StateFlow<UserRef?> = currentUserState.asStateFlow()
|
||||
private val currentUserState = MutableStateFlow<UserRef?>(null)
|
||||
val currentUser: StateFlow<UserRef?> = currentUserState.asStateFlow()
|
||||
|
||||
val sessionCookie: StateFlow<String?> get() = authStore.sessionCookie
|
||||
val sessionCookie: StateFlow<String?> get() = authStore.sessionCookie
|
||||
|
||||
val isSignedIn: Boolean
|
||||
get() = !authStore.sessionCookie.value.isNullOrEmpty()
|
||||
val isSignedIn: Boolean
|
||||
get() = !authStore.sessionCookie.value.isNullOrEmpty()
|
||||
|
||||
init {
|
||||
// Rehydrate currentUser whenever the persisted userJson emits
|
||||
// (cold start with a saved cookie OR explicit sign-in/out
|
||||
// writing through AuthStore). Decode failures collapse to null
|
||||
// so a malformed row can't crash the app — worst case is a
|
||||
// blank username until the next sign-in writes a valid value.
|
||||
scope.launch {
|
||||
authStore.userJson.collect { raw ->
|
||||
currentUserState.value = raw?.let { decodeUser(it) }
|
||||
init {
|
||||
// Rehydrate currentUser whenever the persisted userJson emits
|
||||
// (cold start with a saved cookie OR explicit sign-in/out
|
||||
// writing through AuthStore). Decode failures collapse to null
|
||||
// so a malformed row can't crash the app — worst case is a
|
||||
// blank username until the next sign-in writes a valid value.
|
||||
scope.launch {
|
||||
authStore.userJson.collect { raw ->
|
||||
currentUserState.value = raw?.let { decodeUser(it) }
|
||||
}
|
||||
}
|
||||
// Refresh from /api/me on startup so a remotely-changed account
|
||||
// flag (e.g. an admin enabling debug mode) reaches the device
|
||||
// without a re-login. Best-effort; failures keep the cached value.
|
||||
scope.launch { refreshProfile() }
|
||||
}
|
||||
// Refresh from /api/me on startup so a remotely-changed account
|
||||
// flag (e.g. an admin enabling debug mode) reaches the device
|
||||
// without a re-login. Best-effort; failures keep the cached value.
|
||||
scope.launch { refreshProfile() }
|
||||
}
|
||||
|
||||
/**
|
||||
* Submit credentials. On success the AuthCookieInterceptor will
|
||||
* have captured the Set-Cookie before this method returns; the
|
||||
* caller can safely navigate to the in-shell graph. Throws on
|
||||
* any non-2xx response (caller surfaces in UI).
|
||||
*/
|
||||
suspend fun signIn(username: String, password: String): UserRef {
|
||||
val response = api.login(LoginRequestBody(username = username, password = password))
|
||||
val user = UserRef(
|
||||
id = response.user.id,
|
||||
username = response.user.username,
|
||||
isAdmin = response.user.isAdmin,
|
||||
)
|
||||
currentUserState.value = user
|
||||
authStore.setUserJson(json.encodeToString(UserRef.serializer(), user))
|
||||
// Pull the fuller /me shape (carries debug_mode_enabled) right
|
||||
// after login so the diagnostics gate is correct without waiting
|
||||
// for the next startup refresh.
|
||||
scope.launch { refreshProfile() }
|
||||
return user
|
||||
}
|
||||
/**
|
||||
* Submit credentials. On success the AuthCookieInterceptor will
|
||||
* have captured the Set-Cookie before this method returns; the
|
||||
* caller can safely navigate to the in-shell graph. Throws on
|
||||
* any non-2xx response (caller surfaces in UI).
|
||||
*/
|
||||
suspend fun signIn(
|
||||
username: String,
|
||||
password: String,
|
||||
): UserRef {
|
||||
val response = api.login(LoginRequestBody(username = username, password = password))
|
||||
val user =
|
||||
UserRef(
|
||||
id = response.user.id,
|
||||
username = response.user.username,
|
||||
isAdmin = response.user.isAdmin,
|
||||
)
|
||||
currentUserState.value = user
|
||||
authStore.setUserJson(json.encodeToString(UserRef.serializer(), user))
|
||||
// Pull the fuller /me shape (carries debug_mode_enabled) right
|
||||
// after login so the diagnostics gate is correct without waiting
|
||||
// for the next startup refresh.
|
||||
scope.launch { refreshProfile() }
|
||||
return user
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-fetch the caller's profile from /api/me and update currentUser
|
||||
* + persisted userJson. Carries account-level flags (debug mode)
|
||||
* that aren't in the login response. Best-effort: a network failure
|
||||
* leaves the cached identity untouched. No-op when signed out.
|
||||
* Waits for the stored login to load first: at launch this runs before
|
||||
* it has, and would otherwise read the user as signed out and skip.
|
||||
*/
|
||||
suspend fun refreshProfile() {
|
||||
authStore.awaitSessionHydrated()
|
||||
if (!isSignedIn) return
|
||||
val p = runCatching { meApi.getProfile() }.getOrNull() ?: return
|
||||
val user = UserRef(
|
||||
id = p.id,
|
||||
username = p.username,
|
||||
isAdmin = p.isAdmin,
|
||||
debugModeEnabled = p.debugModeEnabled,
|
||||
)
|
||||
currentUserState.value = user
|
||||
authStore.setUserJson(json.encodeToString(UserRef.serializer(), user))
|
||||
}
|
||||
/**
|
||||
* Re-fetch the caller's profile from /api/me and update currentUser
|
||||
* + persisted userJson. Carries account-level flags (debug mode)
|
||||
* that aren't in the login response. Best-effort: a network failure
|
||||
* leaves the cached identity untouched. No-op when signed out.
|
||||
* Waits for the stored login to load first: at launch this runs before
|
||||
* it has, and would otherwise read the user as signed out and skip.
|
||||
*/
|
||||
suspend fun refreshProfile() {
|
||||
authStore.awaitSessionHydrated()
|
||||
if (!isSignedIn) return
|
||||
val p = runCatching { meApi.getProfile() }.getOrNull() ?: return
|
||||
val user =
|
||||
UserRef(
|
||||
id = p.id,
|
||||
username = p.username,
|
||||
isAdmin = p.isAdmin,
|
||||
debugModeEnabled = p.debugModeEnabled,
|
||||
)
|
||||
currentUserState.value = user
|
||||
authStore.setUserJson(json.encodeToString(UserRef.serializer(), user))
|
||||
}
|
||||
|
||||
/**
|
||||
* Signs out here at once and ends the session on the server too.
|
||||
*
|
||||
* The app shows signed-out straight away, then calls
|
||||
* `/api/auth/logout` while the session cookie is still set: the cookie
|
||||
* is what tells the server which session to drop, so the call has to go
|
||||
* before the cookie is cleared. The call waits at most
|
||||
* [LOGOUT_TIMEOUT_MS]; offline, or on an error, the cookie is cleared
|
||||
* anyway and the server session expires on its own. It runs in the
|
||||
* application scope, so the screen that asked closing as the app shows
|
||||
* signed-out can't cancel it halfway.
|
||||
*/
|
||||
suspend fun signOut() {
|
||||
currentUserState.value = null
|
||||
authStore.setUserJson(null)
|
||||
scope.launch {
|
||||
try {
|
||||
withTimeoutOrNull(LOGOUT_TIMEOUT_MS) { runCatching { api.logout() } }
|
||||
} finally {
|
||||
authStore.setSessionCookie(null)
|
||||
}
|
||||
}.join()
|
||||
}
|
||||
/**
|
||||
* Signs out here at once and ends the session on the server too.
|
||||
*
|
||||
* The app shows signed-out straight away, then calls
|
||||
* `/api/auth/logout` while the session cookie is still set: the cookie
|
||||
* is what tells the server which session to drop, so the call has to go
|
||||
* before the cookie is cleared. The call waits at most
|
||||
* [LOGOUT_TIMEOUT_MS]; offline, or on an error, the cookie is cleared
|
||||
* anyway and the server session expires on its own. It runs in the
|
||||
* application scope, so the screen that asked closing as the app shows
|
||||
* signed-out can't cancel it halfway.
|
||||
*/
|
||||
suspend fun signOut() {
|
||||
currentUserState.value = null
|
||||
authStore.setUserJson(null)
|
||||
scope
|
||||
.launch {
|
||||
try {
|
||||
withTimeoutOrNull(LOGOUT_TIMEOUT_MS) { runCatching { api.logout() } }
|
||||
} finally {
|
||||
authStore.setSessionCookie(null)
|
||||
}
|
||||
}.join()
|
||||
}
|
||||
|
||||
private fun decodeUser(raw: String): UserRef? =
|
||||
runCatching { json.decodeFromString(UserRef.serializer(), raw) }.getOrNull()
|
||||
private fun decodeUser(raw: String): UserRef? =
|
||||
runCatching {
|
||||
json.decodeFromString(UserRef.serializer(), raw)
|
||||
}.getOrNull()
|
||||
|
||||
private companion object {
|
||||
// Long enough for a logout on a slow connection, short enough that
|
||||
// signing out offline doesn't seem to hang.
|
||||
const val LOGOUT_TIMEOUT_MS = 5_000L
|
||||
private companion object {
|
||||
// Long enough for a logout on a slow connection, short enough that
|
||||
// signing out offline doesn't seem to hang.
|
||||
const val LOGOUT_TIMEOUT_MS = 5_000L
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,6 +21,14 @@ import timber.log.Timber
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
// AuthStore is the single-row facade over auth_session (de-facto
|
||||
// app_preferences — see entity comment). It legitimately owns one
|
||||
// getter + one setter + one persist helper per pref column; the
|
||||
// function count scales with the pref count, not with feature
|
||||
// complexity. Splitting into per-pref stores would scatter the
|
||||
// shared dao + scope + json plumbing for no real gain. Suppress
|
||||
// the cap rather than fragment.
|
||||
|
||||
/**
|
||||
* Holds the user's session cookie and configured server base URL.
|
||||
*
|
||||
@@ -44,353 +52,352 @@ import javax.inject.Singleton
|
||||
* [awaitSessionHydrated] lets a caller that needs a definitive answer
|
||||
* (the auth gate) wait for this.
|
||||
*/
|
||||
// AuthStore is the single-row facade over auth_session (de-facto
|
||||
// app_preferences — see entity comment). It legitimately owns one
|
||||
// getter + one setter + one persist helper per pref column; the
|
||||
// function count scales with the pref count, not with feature
|
||||
// complexity. Splitting into per-pref stores would scatter the
|
||||
// shared dao + scope + json plumbing for no real gain. Suppress
|
||||
// the cap rather than fragment.
|
||||
@Suppress("TooManyFunctions")
|
||||
@Singleton
|
||||
class AuthStore @Inject constructor(
|
||||
private val dao: AuthSessionDao,
|
||||
private val vault: SessionVault,
|
||||
@ApplicationScope private val scope: CoroutineScope,
|
||||
) {
|
||||
private val sessionCookieState = MutableStateFlow<String?>(null)
|
||||
val sessionCookie: StateFlow<String?> = sessionCookieState.asStateFlow()
|
||||
class AuthStore
|
||||
@Inject
|
||||
constructor(
|
||||
private val dao: AuthSessionDao,
|
||||
private val vault: SessionVault,
|
||||
@ApplicationScope private val scope: CoroutineScope,
|
||||
) {
|
||||
private val sessionCookieState = MutableStateFlow<String?>(null)
|
||||
val sessionCookie: StateFlow<String?> = sessionCookieState.asStateFlow()
|
||||
|
||||
private val baseUrlState = MutableStateFlow(DEFAULT_BASE_URL)
|
||||
val baseUrl: StateFlow<String> = baseUrlState.asStateFlow()
|
||||
private val baseUrlState = MutableStateFlow(DEFAULT_BASE_URL)
|
||||
val baseUrl: StateFlow<String> = baseUrlState.asStateFlow()
|
||||
|
||||
private val userJsonState = MutableStateFlow<String?>(null)
|
||||
val userJson: StateFlow<String?> = userJsonState.asStateFlow()
|
||||
private val userJsonState = MutableStateFlow<String?>(null)
|
||||
val userJson: StateFlow<String?> = userJsonState.asStateFlow()
|
||||
|
||||
private val themeModeState = MutableStateFlow<String?>(null)
|
||||
val themeMode: StateFlow<String?> = themeModeState.asStateFlow()
|
||||
private val themeModeState = MutableStateFlow<String?>(null)
|
||||
val themeMode: StateFlow<String?> = themeModeState.asStateFlow()
|
||||
|
||||
private val clientIdState = MutableStateFlow<String?>(null)
|
||||
val clientId: StateFlow<String?> = clientIdState.asStateFlow()
|
||||
private val clientIdState = MutableStateFlow<String?>(null)
|
||||
val clientId: StateFlow<String?> = clientIdState.asStateFlow()
|
||||
|
||||
private val cacheSettingsState = MutableStateFlow(CacheSettings.DEFAULT)
|
||||
val cacheSettings: StateFlow<CacheSettings> = cacheSettingsState.asStateFlow()
|
||||
private val cacheSettingsState = MutableStateFlow(CacheSettings.DEFAULT)
|
||||
val cacheSettings: StateFlow<CacheSettings> = cacheSettingsState.asStateFlow()
|
||||
|
||||
private val diagnosticsOptOutState = MutableStateFlow(false)
|
||||
val diagnosticsOptOut: StateFlow<Boolean> = diagnosticsOptOutState.asStateFlow()
|
||||
private val diagnosticsOptOutState = MutableStateFlow(false)
|
||||
val diagnosticsOptOut: StateFlow<Boolean> = diagnosticsOptOutState.asStateFlow()
|
||||
|
||||
private val normalizationState = MutableStateFlow(NormalizationPrefs.DEFAULT)
|
||||
val normalization: StateFlow<NormalizationPrefs> = normalizationState.asStateFlow()
|
||||
private val normalizationState = MutableStateFlow(NormalizationPrefs.DEFAULT)
|
||||
val normalization: StateFlow<NormalizationPrefs> = normalizationState.asStateFlow()
|
||||
|
||||
// Background delivery: the device's choice, on by default.
|
||||
// The shade's high-water mark lives in the same row but is read and
|
||||
// written through the DAO by NotificationSync, awaited, never cached here.
|
||||
private val backgroundDeliveryState = MutableStateFlow(true)
|
||||
val backgroundDelivery: StateFlow<Boolean> = backgroundDeliveryState.asStateFlow()
|
||||
// Background delivery: the device's choice, on by default.
|
||||
// The shade's high-water mark lives in the same row but is read and
|
||||
// written through the DAO by NotificationSync, awaited, never cached here.
|
||||
private val backgroundDeliveryState = MutableStateFlow(true)
|
||||
val backgroundDelivery: StateFlow<Boolean> = backgroundDeliveryState.asStateFlow()
|
||||
|
||||
// The account the cached data belongs to (AuthSessionEntity.cacheOwnerUserId).
|
||||
// Null while the stored row is still loading, and before any account
|
||||
// has been adopted; [settingsLoaded] tells the two apart.
|
||||
private val cacheOwnerState = MutableStateFlow<String?>(null)
|
||||
val cacheOwnerUserId: StateFlow<String?> = cacheOwnerState.asStateFlow()
|
||||
// The account the cached data belongs to (AuthSessionEntity.cacheOwnerUserId).
|
||||
// Null while the stored row is still loading, and before any account
|
||||
// has been adopted; [settingsLoaded] tells the two apart.
|
||||
private val cacheOwnerState = MutableStateFlow<String?>(null)
|
||||
val cacheOwnerUserId: StateFlow<String?> = cacheOwnerState.asStateFlow()
|
||||
|
||||
private val settingsLoadedState = MutableStateFlow(false)
|
||||
private val settingsLoadedState = MutableStateFlow(false)
|
||||
|
||||
/** True once the stored settings row has been read at least once. */
|
||||
val settingsLoaded: StateFlow<Boolean> = settingsLoadedState.asStateFlow()
|
||||
/** True once the stored settings row has been read at least once. */
|
||||
val settingsLoaded: StateFlow<Boolean> = settingsLoadedState.asStateFlow()
|
||||
|
||||
private val json = Json { ignoreUnknownKeys = true }
|
||||
private val json = Json { ignoreUnknownKeys = true }
|
||||
|
||||
// Serialises every cookie persist with the one-time hydration, so a
|
||||
// sign-in or a 401 that lands while hydration runs is never overwritten
|
||||
// by the stale value hydration read.
|
||||
private val cookieLock = Mutex()
|
||||
// Serialises every cookie persist with the one-time hydration, so a
|
||||
// sign-in or a 401 that lands while hydration runs is never overwritten
|
||||
// by the stale value hydration read.
|
||||
private val cookieLock = Mutex()
|
||||
|
||||
// Set by setSessionCookie. Once something has written the cookie this
|
||||
// process, that value wins over whatever hydration finds on disk.
|
||||
@Volatile private var cookieTouched = false
|
||||
// Set by setSessionCookie. Once something has written the cookie this
|
||||
// process, that value wins over whatever hydration finds on disk.
|
||||
@Volatile private var cookieTouched = false
|
||||
|
||||
private val cookieHydration: Deferred<Unit> = scope.async { hydrateSessionCookie() }
|
||||
private val cookieHydration: Deferred<Unit> = scope.async { hydrateSessionCookie() }
|
||||
|
||||
init {
|
||||
scope.launch {
|
||||
dao.observe().collect { row ->
|
||||
baseUrlState.value = row?.baseUrl ?: DEFAULT_BASE_URL
|
||||
userJsonState.value = row?.userJson
|
||||
themeModeState.value = row?.themeMode
|
||||
clientIdState.value = row?.clientId
|
||||
cacheSettingsState.value = decodeCacheSettings(row?.cacheSettingsJson)
|
||||
diagnosticsOptOutState.value = row?.diagnosticsOptOut ?: false
|
||||
normalizationState.value = decodeNormalization(row?.normalizationJson)
|
||||
backgroundDeliveryState.value = row?.backgroundDelivery ?: true
|
||||
cacheOwnerState.value = row?.cacheOwnerUserId
|
||||
settingsLoadedState.value = true
|
||||
init {
|
||||
scope.launch {
|
||||
dao.observe().collect { row ->
|
||||
baseUrlState.value = row?.baseUrl ?: DEFAULT_BASE_URL
|
||||
userJsonState.value = row?.userJson
|
||||
themeModeState.value = row?.themeMode
|
||||
clientIdState.value = row?.clientId
|
||||
cacheSettingsState.value = decodeCacheSettings(row?.cacheSettingsJson)
|
||||
diagnosticsOptOutState.value = row?.diagnosticsOptOut ?: false
|
||||
normalizationState.value = decodeNormalization(row?.normalizationJson)
|
||||
backgroundDeliveryState.value = row?.backgroundDelivery ?: true
|
||||
cacheOwnerState.value = row?.cacheOwnerUserId
|
||||
settingsLoadedState.value = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun decodeCacheSettings(raw: String?): CacheSettings {
|
||||
if (raw.isNullOrEmpty()) return CacheSettings.DEFAULT
|
||||
return runCatching {
|
||||
json.decodeFromString(CacheSettings.serializer(), raw)
|
||||
}.getOrDefault(CacheSettings.DEFAULT)
|
||||
}
|
||||
|
||||
private fun decodeNormalization(raw: String?): NormalizationPrefs {
|
||||
if (raw.isNullOrEmpty()) return NormalizationPrefs.DEFAULT
|
||||
return runCatching {
|
||||
json.decodeFromString(NormalizationPrefs.serializer(), raw)
|
||||
}.getOrDefault(NormalizationPrefs.DEFAULT)
|
||||
}
|
||||
|
||||
/**
|
||||
* Suspends until the stored session cookie has been loaded into
|
||||
* [sessionCookie], or [HYDRATION_DEADLINE_MS] passes, so a wedged
|
||||
* Keystore cannot leave the start screen spinning. Returns false on
|
||||
* the deadline; the caller then decides from whatever has loaded, and a
|
||||
* late hydration still lands in [sessionCookie].
|
||||
*/
|
||||
suspend fun awaitSessionHydrated(): Boolean {
|
||||
val done = withTimeoutOrNull(HYDRATION_DEADLINE_MS) { cookieHydration.await() } != null
|
||||
if (!done) Timber.w("auth store: session hydration passed its deadline; deciding without it")
|
||||
return done
|
||||
}
|
||||
|
||||
fun setSessionCookie(value: String?) {
|
||||
cookieTouched = true
|
||||
sessionCookieState.value = value
|
||||
scope.launch { cookieLock.withLock { storeCookie(value) } }
|
||||
}
|
||||
|
||||
/**
|
||||
* The cookie to attach to an outgoing request. Blocks the calling
|
||||
* (OkHttp) thread until the stored cookie has loaded, up to
|
||||
* [HYDRATION_DEADLINE_MS], so a request made in the first moment after
|
||||
* launch carries the login instead of going out without it. Once
|
||||
* hydration has finished this is a plain read.
|
||||
*/
|
||||
fun sessionCookieForRequest(): String? {
|
||||
if (!cookieHydration.isCompleted) {
|
||||
runBlocking { withTimeoutOrNull(HYDRATION_DEADLINE_MS) { cookieHydration.await() } }
|
||||
private fun decodeCacheSettings(raw: String?): CacheSettings {
|
||||
if (raw.isNullOrEmpty()) return CacheSettings.DEFAULT
|
||||
return runCatching {
|
||||
json.decodeFromString(CacheSettings.serializer(), raw)
|
||||
}.getOrDefault(CacheSettings.DEFAULT)
|
||||
}
|
||||
return sessionCookieState.value
|
||||
}
|
||||
|
||||
/**
|
||||
* True once the server has refused the current session (see
|
||||
* [dropRejectedSessionCookie]) and the UI has not yet sent the user to
|
||||
* sign in. Held rather than fired, so a refusal that lands while the app
|
||||
* is in the background is still acted on when it comes back. A sign-out
|
||||
* the user asked for does not set it.
|
||||
*/
|
||||
private val sessionRejectedState = MutableStateFlow(false)
|
||||
val sessionRejected: StateFlow<Boolean> = sessionRejectedState.asStateFlow()
|
||||
|
||||
/** The UI has opened the sign-in screen for a refused session. */
|
||||
fun consumeSessionRejected() {
|
||||
sessionRejectedState.value = false
|
||||
}
|
||||
|
||||
/**
|
||||
* Signs out because the server answered 401 to a request that carried
|
||||
* [rejected]. Does nothing when the store has since moved on to another
|
||||
* cookie (a sign-in landed meanwhile), so a refusal of an old session
|
||||
* never discards a new one. What is persisted is read inside the lock,
|
||||
* so a sign-in racing this call is the value that ends up stored.
|
||||
*/
|
||||
fun dropRejectedSessionCookie(rejected: String) {
|
||||
if (!sessionCookieState.compareAndSet(rejected, null)) return
|
||||
cookieTouched = true
|
||||
scope.launch { cookieLock.withLock { storeCookie(sessionCookieState.value) } }
|
||||
sessionRejectedState.value = true
|
||||
}
|
||||
|
||||
private suspend fun hydrateSessionCookie() = cookieLock.withLock {
|
||||
val legacy = runCatching { dao.get()?.sessionCookie }.getOrNull()
|
||||
if (cookieTouched) return@withLock
|
||||
// A cookie in the row is the newer one when both exist: the row is
|
||||
// only written when the vault failed, and an install upgrading from
|
||||
// before the vault has nothing in the vault yet.
|
||||
val cookie = legacy ?: vault.read()
|
||||
// Best-effort: if moving it fails, the session still loads this time
|
||||
// and the move is retried on the next launch. Hydration must never
|
||||
// throw, or awaitSessionHydrated would leave the auth gate stuck.
|
||||
if (legacy != null) {
|
||||
runCatching { storeCookie(legacy) }
|
||||
.onFailure { Timber.w(it, "auth store: could not move the session cookie into the vault") }
|
||||
private fun decodeNormalization(raw: String?): NormalizationPrefs {
|
||||
if (raw.isNullOrEmpty()) return NormalizationPrefs.DEFAULT
|
||||
return runCatching {
|
||||
json.decodeFromString(NormalizationPrefs.serializer(), raw)
|
||||
}.getOrDefault(NormalizationPrefs.DEFAULT)
|
||||
}
|
||||
sessionCookieState.value = cookie
|
||||
}
|
||||
|
||||
// Vault first; the Room row only when the Keystore is unusable, so a
|
||||
// broken Keystore degrades to the old storage rather than a sign-out.
|
||||
private suspend fun storeCookie(value: String?) {
|
||||
if (vault.write(value)) {
|
||||
if (dao.get()?.sessionCookie != null) dao.setSessionCookie(null)
|
||||
} else {
|
||||
persistLegacyCookie(value)
|
||||
/**
|
||||
* Suspends until the stored session cookie has been loaded into
|
||||
* [sessionCookie], or [HYDRATION_DEADLINE_MS] passes, so a wedged
|
||||
* Keystore cannot leave the start screen spinning. Returns false on
|
||||
* the deadline; the caller then decides from whatever has loaded, and a
|
||||
* late hydration still lands in [sessionCookie].
|
||||
*/
|
||||
suspend fun awaitSessionHydrated(): Boolean {
|
||||
val done = withTimeoutOrNull(HYDRATION_DEADLINE_MS) { cookieHydration.await() } != null
|
||||
if (!done) Timber.w("auth store: session hydration passed its deadline; deciding without it")
|
||||
return done
|
||||
}
|
||||
}
|
||||
|
||||
fun setBaseUrl(value: String) {
|
||||
baseUrlState.value = value
|
||||
scope.launch { persistBaseUrl(value) }
|
||||
}
|
||||
fun setSessionCookie(value: String?) {
|
||||
cookieTouched = true
|
||||
sessionCookieState.value = value
|
||||
scope.launch { cookieLock.withLock { storeCookie(value) } }
|
||||
}
|
||||
|
||||
fun setUserJson(value: String?) {
|
||||
userJsonState.value = value
|
||||
scope.launch { persistUserJson(value) }
|
||||
}
|
||||
/**
|
||||
* The cookie to attach to an outgoing request. Blocks the calling
|
||||
* (OkHttp) thread until the stored cookie has loaded, up to
|
||||
* [HYDRATION_DEADLINE_MS], so a request made in the first moment after
|
||||
* launch carries the login instead of going out without it. Once
|
||||
* hydration has finished this is a plain read.
|
||||
*/
|
||||
fun sessionCookieForRequest(): String? {
|
||||
if (!cookieHydration.isCompleted) {
|
||||
runBlocking { withTimeoutOrNull(HYDRATION_DEADLINE_MS) { cookieHydration.await() } }
|
||||
}
|
||||
return sessionCookieState.value
|
||||
}
|
||||
|
||||
fun setThemeMode(value: String?) {
|
||||
themeModeState.value = value
|
||||
scope.launch { persistThemeMode(value) }
|
||||
}
|
||||
/**
|
||||
* True once the server has refused the current session (see
|
||||
* [dropRejectedSessionCookie]) and the UI has not yet sent the user to
|
||||
* sign in. Held rather than fired, so a refusal that lands while the app
|
||||
* is in the background is still acted on when it comes back. A sign-out
|
||||
* the user asked for does not set it.
|
||||
*/
|
||||
private val sessionRejectedState = MutableStateFlow(false)
|
||||
val sessionRejected: StateFlow<Boolean> = sessionRejectedState.asStateFlow()
|
||||
|
||||
fun setClientId(value: String?) {
|
||||
clientIdState.value = value
|
||||
scope.launch { persistClientId(value) }
|
||||
}
|
||||
/** The UI has opened the sign-in screen for a refused session. */
|
||||
fun consumeSessionRejected() {
|
||||
sessionRejectedState.value = false
|
||||
}
|
||||
|
||||
fun setCacheSettings(value: CacheSettings) {
|
||||
cacheSettingsState.value = value
|
||||
val encoded = json.encodeToString(CacheSettings.serializer(), value)
|
||||
scope.launch { persistCacheSettings(encoded) }
|
||||
}
|
||||
/**
|
||||
* Signs out because the server answered 401 to a request that carried
|
||||
* [rejected]. Does nothing when the store has since moved on to another
|
||||
* cookie (a sign-in landed meanwhile), so a refusal of an old session
|
||||
* never discards a new one. What is persisted is read inside the lock,
|
||||
* so a sign-in racing this call is the value that ends up stored.
|
||||
*/
|
||||
fun dropRejectedSessionCookie(rejected: String) {
|
||||
if (!sessionCookieState.compareAndSet(rejected, null)) return
|
||||
cookieTouched = true
|
||||
scope.launch { cookieLock.withLock { storeCookie(sessionCookieState.value) } }
|
||||
sessionRejectedState.value = true
|
||||
}
|
||||
|
||||
fun setDiagnosticsOptOut(value: Boolean) {
|
||||
diagnosticsOptOutState.value = value
|
||||
scope.launch { persistDiagnosticsOptOut(value) }
|
||||
}
|
||||
private suspend fun hydrateSessionCookie() =
|
||||
cookieLock.withLock {
|
||||
val legacy = runCatching { dao.get()?.sessionCookie }.getOrNull()
|
||||
if (cookieTouched) return@withLock
|
||||
// A cookie in the row is the newer one when both exist: the row is
|
||||
// only written when the vault failed, and an install upgrading from
|
||||
// before the vault has nothing in the vault yet.
|
||||
val cookie = legacy ?: vault.read()
|
||||
// Best-effort: if moving it fails, the session still loads this time
|
||||
// and the move is retried on the next launch. Hydration must never
|
||||
// throw, or awaitSessionHydrated would leave the auth gate stuck.
|
||||
if (legacy != null) {
|
||||
runCatching { storeCookie(legacy) }
|
||||
.onFailure { Timber.w(it, "auth store: could not move the session cookie into the vault") }
|
||||
}
|
||||
sessionCookieState.value = cookie
|
||||
}
|
||||
|
||||
fun setNormalization(value: NormalizationPrefs) {
|
||||
normalizationState.value = value
|
||||
val encoded = json.encodeToString(NormalizationPrefs.serializer(), value)
|
||||
scope.launch { persistNormalization(encoded) }
|
||||
}
|
||||
|
||||
fun setBackgroundDelivery(value: Boolean) {
|
||||
backgroundDeliveryState.value = value
|
||||
scope.launch {
|
||||
if (dao.get() == null) {
|
||||
dao.upsert(currentEntity().copy(backgroundDelivery = value))
|
||||
// Vault first; the Room row only when the Keystore is unusable, so a
|
||||
// broken Keystore degrades to the old storage rather than a sign-out.
|
||||
private suspend fun storeCookie(value: String?) {
|
||||
if (vault.write(value)) {
|
||||
if (dao.get()?.sessionCookie != null) dao.setSessionCookie(null)
|
||||
} else {
|
||||
dao.setBackgroundDelivery(value)
|
||||
persistLegacyCookie(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Records which account the cached data now belongs to. Suspends until
|
||||
* it is stored, so a caller that has just cleared the old account's
|
||||
* data can't have the adoption lost to a crash in between.
|
||||
*/
|
||||
suspend fun setCacheOwnerUserId(value: String?) {
|
||||
cacheOwnerState.value = value
|
||||
if (dao.get() == null) {
|
||||
dao.upsert(currentEntity().copy(cacheOwnerUserId = value))
|
||||
} else {
|
||||
dao.setCacheOwnerUserId(value)
|
||||
fun setBaseUrl(value: String) {
|
||||
baseUrlState.value = value
|
||||
scope.launch { persistBaseUrl(value) }
|
||||
}
|
||||
|
||||
fun setUserJson(value: String?) {
|
||||
userJsonState.value = value
|
||||
scope.launch { persistUserJson(value) }
|
||||
}
|
||||
|
||||
fun setThemeMode(value: String?) {
|
||||
themeModeState.value = value
|
||||
scope.launch { persistThemeMode(value) }
|
||||
}
|
||||
|
||||
fun setClientId(value: String?) {
|
||||
clientIdState.value = value
|
||||
scope.launch { persistClientId(value) }
|
||||
}
|
||||
|
||||
fun setCacheSettings(value: CacheSettings) {
|
||||
cacheSettingsState.value = value
|
||||
val encoded = json.encodeToString(CacheSettings.serializer(), value)
|
||||
scope.launch { persistCacheSettings(encoded) }
|
||||
}
|
||||
|
||||
fun setDiagnosticsOptOut(value: Boolean) {
|
||||
diagnosticsOptOutState.value = value
|
||||
scope.launch { persistDiagnosticsOptOut(value) }
|
||||
}
|
||||
|
||||
fun setNormalization(value: NormalizationPrefs) {
|
||||
normalizationState.value = value
|
||||
val encoded = json.encodeToString(NormalizationPrefs.serializer(), value)
|
||||
scope.launch { persistNormalization(encoded) }
|
||||
}
|
||||
|
||||
fun setBackgroundDelivery(value: Boolean) {
|
||||
backgroundDeliveryState.value = value
|
||||
scope.launch {
|
||||
if (dao.get() == null) {
|
||||
dao.upsert(currentEntity().copy(backgroundDelivery = value))
|
||||
} else {
|
||||
dao.setBackgroundDelivery(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Records which account the cached data now belongs to. Suspends until
|
||||
* it is stored, so a caller that has just cleared the old account's
|
||||
* data can't have the adoption lost to a crash in between.
|
||||
*/
|
||||
suspend fun setCacheOwnerUserId(value: String?) {
|
||||
cacheOwnerState.value = value
|
||||
if (dao.get() == null) {
|
||||
dao.upsert(currentEntity().copy(cacheOwnerUserId = value))
|
||||
} else {
|
||||
dao.setCacheOwnerUserId(value)
|
||||
}
|
||||
}
|
||||
|
||||
/** Forgets the newest notice announced, so the next account starts fresh. */
|
||||
suspend fun clearNotifiedUpTo() {
|
||||
if (dao.get() != null) dao.setNotifiedUpTo(null)
|
||||
}
|
||||
|
||||
private suspend fun persistLegacyCookie(value: String?) {
|
||||
if (dao.get() == null) {
|
||||
dao.upsert(currentEntity().copy(sessionCookie = value))
|
||||
} else {
|
||||
dao.setSessionCookie(value)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun persistBaseUrl(value: String) {
|
||||
if (dao.get() == null) {
|
||||
dao.upsert(currentEntity().copy(baseUrl = value))
|
||||
} else {
|
||||
dao.setBaseUrl(value)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun persistUserJson(value: String?) {
|
||||
if (dao.get() == null) {
|
||||
dao.upsert(currentEntity().copy(userJson = value))
|
||||
} else {
|
||||
dao.setUserJson(value)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun persistThemeMode(value: String?) {
|
||||
if (dao.get() == null) {
|
||||
dao.upsert(currentEntity().copy(themeMode = value))
|
||||
} else {
|
||||
dao.setThemeMode(value)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun persistClientId(value: String?) {
|
||||
if (dao.get() == null) {
|
||||
dao.upsert(currentEntity().copy(clientId = value))
|
||||
} else {
|
||||
dao.setClientId(value)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun persistCacheSettings(json: String) {
|
||||
if (dao.get() == null) {
|
||||
dao.upsert(currentEntity().copy(cacheSettingsJson = json))
|
||||
} else {
|
||||
dao.setCacheSettingsJson(json)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun persistDiagnosticsOptOut(value: Boolean) {
|
||||
if (dao.get() == null) {
|
||||
dao.upsert(currentEntity().copy(diagnosticsOptOut = value))
|
||||
} else {
|
||||
dao.setDiagnosticsOptOut(value)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun persistNormalization(json: String) {
|
||||
if (dao.get() == null) {
|
||||
dao.upsert(currentEntity().copy(normalizationJson = json))
|
||||
} else {
|
||||
dao.setNormalizationJson(json)
|
||||
}
|
||||
}
|
||||
|
||||
private fun currentEntity(): AuthSessionEntity =
|
||||
AuthSessionEntity(
|
||||
id = ROW_ID,
|
||||
// Never copied into the row: the cookie lives in the vault, and
|
||||
// persistLegacyCookie sets it explicitly on the fallback path.
|
||||
sessionCookie = null,
|
||||
baseUrl = baseUrlState.value,
|
||||
userJson = userJsonState.value,
|
||||
themeMode = themeModeState.value,
|
||||
clientId = clientIdState.value,
|
||||
cacheSettingsJson =
|
||||
json.encodeToString(
|
||||
CacheSettings.serializer(),
|
||||
cacheSettingsState.value,
|
||||
),
|
||||
diagnosticsOptOut = diagnosticsOptOutState.value,
|
||||
normalizationJson =
|
||||
json.encodeToString(
|
||||
NormalizationPrefs.serializer(),
|
||||
normalizationState.value,
|
||||
),
|
||||
backgroundDelivery = backgroundDeliveryState.value,
|
||||
cacheOwnerUserId = cacheOwnerState.value,
|
||||
)
|
||||
|
||||
companion object {
|
||||
const val DEFAULT_BASE_URL: String = "http://localhost:8080"
|
||||
|
||||
// Generous on purpose: hydration is one local row read and one
|
||||
// Keystore decrypt, normally milliseconds. This only bounds "never".
|
||||
const val HYDRATION_DEADLINE_MS: Long = 10_000
|
||||
private const val ROW_ID = 0
|
||||
}
|
||||
}
|
||||
|
||||
/** Forgets the newest notice announced, so the next account starts fresh. */
|
||||
suspend fun clearNotifiedUpTo() {
|
||||
if (dao.get() != null) dao.setNotifiedUpTo(null)
|
||||
}
|
||||
|
||||
private suspend fun persistLegacyCookie(value: String?) {
|
||||
if (dao.get() == null) {
|
||||
dao.upsert(currentEntity().copy(sessionCookie = value))
|
||||
} else {
|
||||
dao.setSessionCookie(value)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun persistBaseUrl(value: String) {
|
||||
if (dao.get() == null) {
|
||||
dao.upsert(currentEntity().copy(baseUrl = value))
|
||||
} else {
|
||||
dao.setBaseUrl(value)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun persistUserJson(value: String?) {
|
||||
if (dao.get() == null) {
|
||||
dao.upsert(currentEntity().copy(userJson = value))
|
||||
} else {
|
||||
dao.setUserJson(value)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun persistThemeMode(value: String?) {
|
||||
if (dao.get() == null) {
|
||||
dao.upsert(currentEntity().copy(themeMode = value))
|
||||
} else {
|
||||
dao.setThemeMode(value)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun persistClientId(value: String?) {
|
||||
if (dao.get() == null) {
|
||||
dao.upsert(currentEntity().copy(clientId = value))
|
||||
} else {
|
||||
dao.setClientId(value)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun persistCacheSettings(json: String) {
|
||||
if (dao.get() == null) {
|
||||
dao.upsert(currentEntity().copy(cacheSettingsJson = json))
|
||||
} else {
|
||||
dao.setCacheSettingsJson(json)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun persistDiagnosticsOptOut(value: Boolean) {
|
||||
if (dao.get() == null) {
|
||||
dao.upsert(currentEntity().copy(diagnosticsOptOut = value))
|
||||
} else {
|
||||
dao.setDiagnosticsOptOut(value)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun persistNormalization(json: String) {
|
||||
if (dao.get() == null) {
|
||||
dao.upsert(currentEntity().copy(normalizationJson = json))
|
||||
} else {
|
||||
dao.setNormalizationJson(json)
|
||||
}
|
||||
}
|
||||
|
||||
private fun currentEntity(): AuthSessionEntity = AuthSessionEntity(
|
||||
id = ROW_ID,
|
||||
// Never copied into the row: the cookie lives in the vault, and
|
||||
// persistLegacyCookie sets it explicitly on the fallback path.
|
||||
sessionCookie = null,
|
||||
baseUrl = baseUrlState.value,
|
||||
userJson = userJsonState.value,
|
||||
themeMode = themeModeState.value,
|
||||
clientId = clientIdState.value,
|
||||
cacheSettingsJson = json.encodeToString(
|
||||
CacheSettings.serializer(),
|
||||
cacheSettingsState.value,
|
||||
),
|
||||
diagnosticsOptOut = diagnosticsOptOutState.value,
|
||||
normalizationJson = json.encodeToString(
|
||||
NormalizationPrefs.serializer(),
|
||||
normalizationState.value,
|
||||
),
|
||||
backgroundDelivery = backgroundDeliveryState.value,
|
||||
cacheOwnerUserId = cacheOwnerState.value,
|
||||
)
|
||||
|
||||
companion object {
|
||||
const val DEFAULT_BASE_URL: String = "http://localhost:8080"
|
||||
|
||||
// Generous on purpose: hydration is one local row read and one
|
||||
// Keystore decrypt, normally milliseconds. This only bounds "never".
|
||||
const val HYDRATION_DEADLINE_MS: Long = 10_000
|
||||
private const val ROW_ID = 0
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,21 +35,30 @@ import kotlin.coroutines.resumeWithException
|
||||
* Plain http still passes through [com.fabledsword.minstrel.api.CleartextGuardInterceptor]
|
||||
* on [client], so the fallback can only succeed on a home-network address.
|
||||
*/
|
||||
class ServerProbe internal constructor(client: OkHttpClient, callTimeoutMillis: Long) {
|
||||
|
||||
class ServerProbe internal constructor(
|
||||
client: OkHttpClient,
|
||||
callTimeoutMillis: Long,
|
||||
) {
|
||||
// Each attempt is short: a probe that stalls holds the sign-in screen.
|
||||
@Inject constructor(client: OkHttpClient) : this(client, CALL_TIMEOUT_MILLIS)
|
||||
@Inject
|
||||
constructor(client: OkHttpClient) : this(client, CALL_TIMEOUT_MILLIS)
|
||||
|
||||
private val client: OkHttpClient = client.newBuilder()
|
||||
.connectTimeout(callTimeoutMillis, TimeUnit.MILLISECONDS)
|
||||
.callTimeout(callTimeoutMillis, TimeUnit.MILLISECONDS)
|
||||
.build()
|
||||
private val client: OkHttpClient =
|
||||
client
|
||||
.newBuilder()
|
||||
.connectTimeout(callTimeoutMillis, TimeUnit.MILLISECONDS)
|
||||
.callTimeout(callTimeoutMillis, TimeUnit.MILLISECONDS)
|
||||
.build()
|
||||
|
||||
sealed interface Result {
|
||||
/** Minstrel answered at [baseUrl], which includes its scheme. */
|
||||
data class Found(val baseUrl: String) : Result
|
||||
data class Found(
|
||||
val baseUrl: String,
|
||||
) : Result
|
||||
|
||||
data class Failed(val message: String) : Result
|
||||
data class Failed(
|
||||
val message: String,
|
||||
) : Result
|
||||
}
|
||||
|
||||
suspend fun find(input: String): Result {
|
||||
@@ -100,21 +109,28 @@ class ServerProbe internal constructor(client: OkHttpClient, callTimeoutMillis:
|
||||
data object Minstrel : Outcome
|
||||
|
||||
/** Nothing answered: the next scheme may be tried. */
|
||||
data class Unreachable(val publicCleartext: Boolean = false) : Outcome
|
||||
data class Unreachable(
|
||||
val publicCleartext: Boolean = false,
|
||||
) : Outcome
|
||||
|
||||
/** Something answered, or TLS failed to verify: stop here. */
|
||||
data class Stop(val message: String) : Outcome
|
||||
data class Stop(
|
||||
val message: String,
|
||||
) : Outcome
|
||||
}
|
||||
|
||||
private suspend fun attempt(baseUrl: String): Outcome {
|
||||
val url = "$baseUrl$SETUP_STATUS_PATH".toHttpUrlOrNull()
|
||||
?: return Outcome.Stop("That doesn't look like a server address.")
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
// Lets CleartextGuardInterceptor treat the probe as a Minstrel
|
||||
// server request, as it treats sign-in.
|
||||
.tag(MinstrelServerRequest::class.java, MinstrelServerRequest)
|
||||
.build()
|
||||
val url =
|
||||
"$baseUrl$SETUP_STATUS_PATH".toHttpUrlOrNull()
|
||||
?: return Outcome.Stop("That doesn't look like a server address.")
|
||||
val request =
|
||||
Request
|
||||
.Builder()
|
||||
.url(url)
|
||||
// Lets CleartextGuardInterceptor treat the probe as a Minstrel
|
||||
// server request, as it treats sign-in.
|
||||
.tag(MinstrelServerRequest::class.java, MinstrelServerRequest)
|
||||
.build()
|
||||
return try {
|
||||
client.newCall(request).await().use { response ->
|
||||
if (isMinstrel(response)) {
|
||||
@@ -123,9 +139,13 @@ class ServerProbe internal constructor(client: OkHttpClient, callTimeoutMillis:
|
||||
Outcome.Stop("A server answered at $baseUrl, but it isn't Minstrel.")
|
||||
}
|
||||
}
|
||||
} catch (@Suppress("SwallowedException") e: CleartextToPublicHostException) {
|
||||
} catch (
|
||||
@Suppress("SwallowedException") e: CleartextToPublicHostException,
|
||||
) {
|
||||
Outcome.Unreachable(publicCleartext = true)
|
||||
} catch (@Suppress("SwallowedException") e: UnknownHostException) {
|
||||
} catch (
|
||||
@Suppress("SwallowedException") e: UnknownHostException,
|
||||
) {
|
||||
Outcome.Stop("Couldn't find a server named ${url.host}.")
|
||||
} catch (e: IOException) {
|
||||
if (isCertificateFailure(e)) {
|
||||
@@ -151,21 +171,43 @@ class ServerProbe internal constructor(client: OkHttpClient, callTimeoutMillis:
|
||||
// (hostname) or as an SSLHandshakeException caused by a
|
||||
// CertificateException or CertPathValidatorException (trust). A port
|
||||
// with no TLS fails the handshake too, but with no such cause.
|
||||
private fun isCertificateFailure(e: IOException): Boolean =
|
||||
generateSequence<Throwable>(e) { it.cause }
|
||||
.take(MAX_CAUSE_DEPTH)
|
||||
.any { it is SSLPeerUnverifiedException || it is GeneralSecurityException }
|
||||
//
|
||||
// OkHttp tries a host's addresses in parallel (fast fallback). When
|
||||
// all of them fail it throws one failure and attaches the rest as
|
||||
// suppressed, so the certificate error can sit behind a refused
|
||||
// connection to the host's other address. Both causes and suppressed
|
||||
// exceptions are searched.
|
||||
private fun isCertificateFailure(e: IOException): Boolean {
|
||||
val seen = mutableSetOf<Throwable>()
|
||||
val pending = ArrayDeque<Throwable>().apply { add(e) }
|
||||
var found = false
|
||||
while (!found && pending.isNotEmpty() && seen.size < MAX_EXCEPTIONS_SEARCHED) {
|
||||
val t = pending.removeFirst()
|
||||
if (seen.add(t)) {
|
||||
found = t is SSLPeerUnverifiedException || t is GeneralSecurityException
|
||||
t.cause?.let { pending.addLast(it) }
|
||||
pending.addAll(t.suppressed)
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
private suspend fun Call.await(): Response =
|
||||
suspendCancellableCoroutine { continuation ->
|
||||
continuation.invokeOnCancellation { cancel() }
|
||||
enqueue(
|
||||
object : Callback {
|
||||
override fun onResponse(call: Call, response: Response) {
|
||||
override fun onResponse(
|
||||
call: Call,
|
||||
response: Response,
|
||||
) {
|
||||
if (continuation.isActive) continuation.resume(response) else response.close()
|
||||
}
|
||||
|
||||
override fun onFailure(call: Call, e: IOException) {
|
||||
override fun onFailure(
|
||||
call: Call,
|
||||
e: IOException,
|
||||
) {
|
||||
if (continuation.isActive) continuation.resumeWithException(e)
|
||||
}
|
||||
},
|
||||
@@ -175,6 +217,6 @@ class ServerProbe internal constructor(client: OkHttpClient, callTimeoutMillis:
|
||||
private companion object {
|
||||
const val SETUP_STATUS_PATH = "/api/auth/setup-status"
|
||||
const val CALL_TIMEOUT_MILLIS = 8_000L
|
||||
const val MAX_CAUSE_DEPTH = 8
|
||||
const val MAX_EXCEPTIONS_SEARCHED = 16
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,7 +54,10 @@ internal object SealedBox {
|
||||
// under the same key will not open as a session cookie.
|
||||
private val AAD = "minstrel-session-cookie-v1".toByteArray(Charsets.UTF_8)
|
||||
|
||||
fun seal(key: SecretKey, plaintext: String): String {
|
||||
fun seal(
|
||||
key: SecretKey,
|
||||
plaintext: String,
|
||||
): String {
|
||||
val cipher = Cipher.getInstance(TRANSFORMATION)
|
||||
// No IV passed: the provider generates a fresh random one. Keystore
|
||||
// keys refuse a caller-chosen IV for encryption by default.
|
||||
@@ -64,7 +67,10 @@ internal object SealedBox {
|
||||
return Base64.getEncoder().encodeToString(sealed)
|
||||
}
|
||||
|
||||
fun open(key: SecretKey, sealed: String): String {
|
||||
fun open(
|
||||
key: SecretKey,
|
||||
sealed: String,
|
||||
): String {
|
||||
val bytes = Base64.getDecoder().decode(sealed)
|
||||
require(bytes.size > IV_BYTES) { "sealed value too short" }
|
||||
val cipher = Cipher.getInstance(TRANSFORMATION)
|
||||
@@ -85,58 +91,60 @@ internal object SealedBox {
|
||||
* credential that no longer verifies.
|
||||
*/
|
||||
@Singleton
|
||||
class KeystoreSessionVault @Inject constructor(
|
||||
@ApplicationContext context: Context,
|
||||
) : SessionVault {
|
||||
private val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
||||
class KeystoreSessionVault
|
||||
@Inject
|
||||
constructor(
|
||||
@ApplicationContext context: Context,
|
||||
) : SessionVault {
|
||||
private val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
||||
|
||||
override fun read(): String? {
|
||||
val sealed = prefs.getString(KEY_COOKIE, null) ?: return null
|
||||
return runCatching { SealedBox.open(key(), sealed) }
|
||||
.onFailure {
|
||||
Timber.w(it, "session vault: stored cookie would not decrypt; discarding it")
|
||||
prefs.edit().remove(KEY_COOKIE).commit()
|
||||
}
|
||||
.getOrNull()
|
||||
}
|
||||
|
||||
override fun write(value: String?): Boolean = runCatching {
|
||||
val editor = prefs.edit()
|
||||
if (value == null) {
|
||||
editor.remove(KEY_COOKIE)
|
||||
} else {
|
||||
editor.putString(KEY_COOKIE, SealedBox.seal(key(), value))
|
||||
override fun read(): String? {
|
||||
val sealed = prefs.getString(KEY_COOKIE, null) ?: return null
|
||||
return runCatching { SealedBox.open(key(), sealed) }
|
||||
.onFailure {
|
||||
Timber.w(it, "session vault: stored cookie would not decrypt; discarding it")
|
||||
prefs.edit().remove(KEY_COOKIE).commit()
|
||||
}.getOrNull()
|
||||
}
|
||||
editor.commit()
|
||||
}.onFailure {
|
||||
Timber.w(it, "session vault: Keystore unavailable; cookie not stored in the vault")
|
||||
}.getOrDefault(false)
|
||||
|
||||
private fun key(): SecretKey {
|
||||
val keyStore = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }
|
||||
(keyStore.getKey(KEY_ALIAS, null) as? SecretKey)?.let { return it }
|
||||
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE)
|
||||
generator.init(
|
||||
KeyGenParameterSpec.Builder(
|
||||
KEY_ALIAS,
|
||||
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
|
||||
override fun write(value: String?): Boolean =
|
||||
runCatching {
|
||||
val editor = prefs.edit()
|
||||
if (value == null) {
|
||||
editor.remove(KEY_COOKIE)
|
||||
} else {
|
||||
editor.putString(KEY_COOKIE, SealedBox.seal(key(), value))
|
||||
}
|
||||
editor.commit()
|
||||
}.onFailure {
|
||||
Timber.w(it, "session vault: Keystore unavailable; cookie not stored in the vault")
|
||||
}.getOrDefault(false)
|
||||
|
||||
private fun key(): SecretKey {
|
||||
val keyStore = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }
|
||||
(keyStore.getKey(KEY_ALIAS, null) as? SecretKey)?.let { return it }
|
||||
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE)
|
||||
generator.init(
|
||||
KeyGenParameterSpec
|
||||
.Builder(
|
||||
KEY_ALIAS,
|
||||
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
|
||||
).setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
||||
.setKeySize(KEY_BITS)
|
||||
.build(),
|
||||
)
|
||||
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
||||
.setKeySize(KEY_BITS)
|
||||
.build(),
|
||||
)
|
||||
return generator.generateKey()
|
||||
}
|
||||
return generator.generateKey()
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val ANDROID_KEYSTORE = "AndroidKeyStore"
|
||||
const val KEY_ALIAS = "minstrel_session_cookie"
|
||||
const val KEY_BITS = 256
|
||||
const val PREFS_NAME = "session_vault"
|
||||
const val KEY_COOKIE = "sealed_cookie"
|
||||
private companion object {
|
||||
const val ANDROID_KEYSTORE = "AndroidKeyStore"
|
||||
const val KEY_ALIAS = "minstrel_session_cookie"
|
||||
const val KEY_BITS = 256
|
||||
const val PREFS_NAME = "session_vault"
|
||||
const val KEY_COOKIE = "sealed_cookie"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Module
|
||||
@InstallIn(SingletonComponent::class)
|
||||
|
||||
@@ -30,34 +30,36 @@ import javax.inject.Inject
|
||||
* and then exactly one resolved value.
|
||||
*/
|
||||
@HiltViewModel
|
||||
class AuthGateViewModel @Inject constructor(
|
||||
private val dao: AuthSessionDao,
|
||||
private val authStore: AuthStore,
|
||||
) : ViewModel() {
|
||||
class AuthGateViewModel
|
||||
@Inject
|
||||
constructor(
|
||||
private val dao: AuthSessionDao,
|
||||
private val authStore: AuthStore,
|
||||
) : ViewModel() {
|
||||
private val internal = MutableStateFlow<Any?>(null)
|
||||
val startDestination: StateFlow<Any?> = internal.asStateFlow()
|
||||
|
||||
private val internal = MutableStateFlow<Any?>(null)
|
||||
val startDestination: StateFlow<Any?> = internal.asStateFlow()
|
||||
/**
|
||||
* True when the server has ended the session while the app was in use;
|
||||
* the root NavHost answers by opening the sign-in screen, then calls
|
||||
* [consumeSessionRejected].
|
||||
*/
|
||||
val sessionRejected: StateFlow<Boolean> = authStore.sessionRejected
|
||||
|
||||
/**
|
||||
* True when the server has ended the session while the app was in use;
|
||||
* the root NavHost answers by opening the sign-in screen, then calls
|
||||
* [consumeSessionRejected].
|
||||
*/
|
||||
val sessionRejected: StateFlow<Boolean> = authStore.sessionRejected
|
||||
fun consumeSessionRejected() = authStore.consumeSessionRejected()
|
||||
|
||||
fun consumeSessionRejected() = authStore.consumeSessionRejected()
|
||||
|
||||
init {
|
||||
viewModelScope.launch {
|
||||
authStore.awaitSessionHydrated()
|
||||
val signedIn = !authStore.sessionCookie.value.isNullOrEmpty()
|
||||
val row = dao.get()
|
||||
internal.value = when {
|
||||
row == null -> ServerUrl
|
||||
row.baseUrl == AuthStore.DEFAULT_BASE_URL && !signedIn -> ServerUrl
|
||||
!signedIn -> Login
|
||||
else -> Home
|
||||
init {
|
||||
viewModelScope.launch {
|
||||
authStore.awaitSessionHydrated()
|
||||
val signedIn = !authStore.sessionCookie.value.isNullOrEmpty()
|
||||
val row = dao.get()
|
||||
internal.value =
|
||||
when {
|
||||
row == null -> ServerUrl
|
||||
row.baseUrl == AuthStore.DEFAULT_BASE_URL && !signedIn -> ServerUrl
|
||||
!signedIn -> Login
|
||||
else -> Home
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,9 +71,10 @@ private fun LoginForm(
|
||||
onChangeServerUrl: () -> Unit,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(24.dp),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.padding(24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
@@ -89,10 +90,11 @@ private fun LoginForm(
|
||||
label = { Text("Username") },
|
||||
singleLine = true,
|
||||
enabled = !state.isSubmitting,
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Email,
|
||||
imeAction = ImeAction.Next,
|
||||
),
|
||||
keyboardOptions =
|
||||
KeyboardOptions(
|
||||
keyboardType = KeyboardType.Email,
|
||||
imeAction = ImeAction.Next,
|
||||
),
|
||||
)
|
||||
OutlinedTextField(
|
||||
value = state.password,
|
||||
@@ -102,10 +104,11 @@ private fun LoginForm(
|
||||
singleLine = true,
|
||||
enabled = !state.isSubmitting,
|
||||
visualTransformation = PasswordVisualTransformation(),
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Password,
|
||||
imeAction = ImeAction.Done,
|
||||
),
|
||||
keyboardOptions =
|
||||
KeyboardOptions(
|
||||
keyboardType = KeyboardType.Password,
|
||||
imeAction = ImeAction.Done,
|
||||
),
|
||||
keyboardActions = KeyboardActions(onDone = { onSubmit() }),
|
||||
)
|
||||
if (state.errorMessage != null) {
|
||||
@@ -126,12 +129,16 @@ private fun LoginForm(
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SubmitButton(state: LoginFormState, onSubmit: () -> Unit) {
|
||||
private fun SubmitButton(
|
||||
state: LoginFormState,
|
||||
onSubmit: () -> Unit,
|
||||
) {
|
||||
Button(
|
||||
onClick = onSubmit,
|
||||
enabled = !state.isSubmitting &&
|
||||
state.username.isNotBlank() &&
|
||||
state.password.isNotBlank(),
|
||||
enabled =
|
||||
!state.isSubmitting &&
|
||||
state.username.isNotBlank() &&
|
||||
state.password.isNotBlank(),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
if (state.isSubmitting) {
|
||||
|
||||
@@ -21,44 +21,45 @@ data class LoginFormState(
|
||||
)
|
||||
|
||||
@HiltViewModel
|
||||
class LoginViewModel @Inject constructor(
|
||||
private val auth: AuthController,
|
||||
) : ViewModel() {
|
||||
class LoginViewModel
|
||||
@Inject
|
||||
constructor(
|
||||
private val auth: AuthController,
|
||||
) : ViewModel() {
|
||||
private val internal = MutableStateFlow(LoginFormState())
|
||||
val state: StateFlow<LoginFormState> = internal.asStateFlow()
|
||||
|
||||
private val internal = MutableStateFlow(LoginFormState())
|
||||
val state: StateFlow<LoginFormState> = internal.asStateFlow()
|
||||
fun setUsername(value: String) {
|
||||
internal.update { it.copy(username = value, errorMessage = null) }
|
||||
}
|
||||
|
||||
fun setUsername(value: String) {
|
||||
internal.update { it.copy(username = value, errorMessage = null) }
|
||||
}
|
||||
fun setPassword(value: String) {
|
||||
internal.update { it.copy(password = value, errorMessage = null) }
|
||||
}
|
||||
|
||||
fun setPassword(value: String) {
|
||||
internal.update { it.copy(password = value, errorMessage = null) }
|
||||
}
|
||||
|
||||
fun submit() {
|
||||
val s = internal.value
|
||||
if (s.username.isBlank() || s.password.isBlank() || s.isSubmitting) return
|
||||
viewModelScope.launch {
|
||||
internal.update { it.copy(isSubmitting = true, errorMessage = null) }
|
||||
try {
|
||||
auth.signIn(s.username, s.password)
|
||||
internal.update { it.copy(isSubmitting = false, signedIn = true) }
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
||||
) {
|
||||
internal.update {
|
||||
it.copy(
|
||||
isSubmitting = false,
|
||||
errorMessage = ErrorCopy.fromThrowable(e),
|
||||
)
|
||||
fun submit() {
|
||||
val s = internal.value
|
||||
if (s.username.isBlank() || s.password.isBlank() || s.isSubmitting) return
|
||||
viewModelScope.launch {
|
||||
internal.update { it.copy(isSubmitting = true, errorMessage = null) }
|
||||
try {
|
||||
auth.signIn(s.username, s.password)
|
||||
internal.update { it.copy(isSubmitting = false, signedIn = true) }
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
||||
) {
|
||||
internal.update {
|
||||
it.copy(
|
||||
isSubmitting = false,
|
||||
errorMessage = ErrorCopy.fromThrowable(e),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Called after the navigation away from /login completes. */
|
||||
fun consumeSignedIn() {
|
||||
internal.update { it.copy(signedIn = false) }
|
||||
/** Called after the navigation away from /login completes. */
|
||||
fun consumeSignedIn() {
|
||||
internal.update { it.copy(signedIn = false) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,64 +51,68 @@ data class ServerUrlFormState(
|
||||
)
|
||||
|
||||
@HiltViewModel
|
||||
class ServerUrlViewModel @Inject constructor(
|
||||
private val authStore: AuthStore,
|
||||
private val probe: ServerProbe,
|
||||
) : ViewModel() {
|
||||
class ServerUrlViewModel
|
||||
@Inject
|
||||
constructor(
|
||||
private val authStore: AuthStore,
|
||||
private val probe: ServerProbe,
|
||||
) : ViewModel() {
|
||||
private val internal =
|
||||
MutableStateFlow(
|
||||
// Pre-fill ONLY if the user has previously saved a real URL —
|
||||
// the DEFAULT_BASE_URL placeholder (`http://localhost:8080`) is
|
||||
// an internal HTTP-client fallback, not something a user
|
||||
// typed. Leaving the field empty lets the OutlinedTextField's
|
||||
// placeholder ("minstrel.example.com") show through so the user
|
||||
// can just type without first having to clear.
|
||||
ServerUrlFormState(
|
||||
url =
|
||||
authStore.baseUrl.value
|
||||
.takeIf { it != AuthStore.DEFAULT_BASE_URL }
|
||||
.orEmpty(),
|
||||
),
|
||||
)
|
||||
val state: StateFlow<ServerUrlFormState> = internal.asStateFlow()
|
||||
|
||||
private val internal = MutableStateFlow(
|
||||
// Pre-fill ONLY if the user has previously saved a real URL —
|
||||
// the DEFAULT_BASE_URL placeholder (`http://localhost:8080`) is
|
||||
// an internal HTTP-client fallback, not something a user
|
||||
// typed. Leaving the field empty lets the OutlinedTextField's
|
||||
// placeholder ("minstrel.example.com") show through so the user
|
||||
// can just type without first having to clear.
|
||||
ServerUrlFormState(
|
||||
url = authStore.baseUrl.value
|
||||
.takeIf { it != AuthStore.DEFAULT_BASE_URL }
|
||||
.orEmpty(),
|
||||
),
|
||||
)
|
||||
val state: StateFlow<ServerUrlFormState> = internal.asStateFlow()
|
||||
private var probeJob: Job? = null
|
||||
|
||||
private var probeJob: Job? = null
|
||||
fun setUrl(value: String) {
|
||||
internal.update { it.copy(url = value, errorMessage = null) }
|
||||
}
|
||||
|
||||
fun setUrl(value: String) {
|
||||
internal.update { it.copy(url = value, errorMessage = null) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Looks for Minstrel at the typed address ([ServerProbe]) and saves the
|
||||
* full URL that answered, scheme included, so every caller of
|
||||
* [AuthStore.baseUrl] still receives a complete URL.
|
||||
*/
|
||||
fun submit() {
|
||||
if (internal.value.probing) return
|
||||
val typed = internal.value.url
|
||||
probeJob = viewModelScope.launch {
|
||||
internal.update { it.copy(probing = true, errorMessage = null) }
|
||||
when (val result = probe.find(typed)) {
|
||||
is ServerProbe.Result.Found -> {
|
||||
authStore.setBaseUrl(result.baseUrl)
|
||||
internal.update { it.copy(probing = false, saved = true) }
|
||||
/**
|
||||
* Looks for Minstrel at the typed address ([ServerProbe]) and saves the
|
||||
* full URL that answered, scheme included, so every caller of
|
||||
* [AuthStore.baseUrl] still receives a complete URL.
|
||||
*/
|
||||
fun submit() {
|
||||
if (internal.value.probing) return
|
||||
val typed = internal.value.url
|
||||
probeJob =
|
||||
viewModelScope.launch {
|
||||
internal.update { it.copy(probing = true, errorMessage = null) }
|
||||
when (val result = probe.find(typed)) {
|
||||
is ServerProbe.Result.Found -> {
|
||||
authStore.setBaseUrl(result.baseUrl)
|
||||
internal.update { it.copy(probing = false, saved = true) }
|
||||
}
|
||||
is ServerProbe.Result.Failed ->
|
||||
internal.update { it.copy(probing = false, errorMessage = result.message) }
|
||||
}
|
||||
}
|
||||
is ServerProbe.Result.Failed ->
|
||||
internal.update { it.copy(probing = false, errorMessage = result.message) }
|
||||
}
|
||||
}
|
||||
|
||||
fun cancelProbe() {
|
||||
probeJob?.cancel()
|
||||
probeJob = null
|
||||
internal.update { it.copy(probing = false) }
|
||||
}
|
||||
|
||||
fun consumeSaved() {
|
||||
internal.update { it.copy(saved = false) }
|
||||
}
|
||||
}
|
||||
|
||||
fun cancelProbe() {
|
||||
probeJob?.cancel()
|
||||
probeJob = null
|
||||
internal.update { it.copy(probing = false) }
|
||||
}
|
||||
|
||||
fun consumeSaved() {
|
||||
internal.update { it.copy(saved = false) }
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Screen ───────────────────────────────────────────────────────────
|
||||
|
||||
@Composable
|
||||
@@ -149,9 +153,10 @@ private fun ServerUrlForm(
|
||||
onCancel: () -> Unit,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(24.dp),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.padding(24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
@@ -176,10 +181,11 @@ private fun ServerUrlForm(
|
||||
},
|
||||
singleLine = true,
|
||||
enabled = !state.probing,
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Uri,
|
||||
imeAction = ImeAction.Done,
|
||||
),
|
||||
keyboardOptions =
|
||||
KeyboardOptions(
|
||||
keyboardType = KeyboardType.Uri,
|
||||
imeAction = ImeAction.Done,
|
||||
),
|
||||
keyboardActions = KeyboardActions(onDone = { onSubmit() }),
|
||||
)
|
||||
if (state.errorMessage != null) {
|
||||
|
||||
@@ -31,34 +31,36 @@ import javax.inject.Singleton
|
||||
* the construct-the-singleton trick in `MinstrelApplication`.
|
||||
*/
|
||||
@Singleton
|
||||
class CacheIndexer @Inject constructor(
|
||||
playerController: PlayerController,
|
||||
private val dao: AudioCacheIndexDao,
|
||||
@ApplicationScope private val scope: CoroutineScope,
|
||||
) {
|
||||
init {
|
||||
scope.launch {
|
||||
playerController.uiState
|
||||
.map { it.currentTrack }
|
||||
.distinctUntilChanged { a, b -> a?.id == b?.id }
|
||||
.collect { track -> if (track != null) record(track) }
|
||||
class CacheIndexer
|
||||
@Inject
|
||||
constructor(
|
||||
playerController: PlayerController,
|
||||
private val dao: AudioCacheIndexDao,
|
||||
@ApplicationScope private val scope: CoroutineScope,
|
||||
) {
|
||||
init {
|
||||
scope.launch {
|
||||
playerController.uiState
|
||||
.map { it.currentTrack }
|
||||
.distinctUntilChanged { a, b -> a?.id == b?.id }
|
||||
.collect { track -> if (track != null) record(track) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun record(track: TrackRef) {
|
||||
val now = Clock.System.now()
|
||||
if (dao.get(track.id) != null) {
|
||||
dao.touchLastPlayed(track.id, now)
|
||||
} else {
|
||||
dao.upsert(
|
||||
AudioCacheIndexEntity(
|
||||
trackId = track.id,
|
||||
path = track.streamUrl,
|
||||
sizeBytes = 0,
|
||||
lastPlayedAt = now,
|
||||
source = CacheSource.INCIDENTAL,
|
||||
),
|
||||
)
|
||||
private suspend fun record(track: TrackRef) {
|
||||
val now = Clock.System.now()
|
||||
if (dao.get(track.id) != null) {
|
||||
dao.touchLastPlayed(track.id, now)
|
||||
} else {
|
||||
dao.upsert(
|
||||
AudioCacheIndexEntity(
|
||||
trackId = track.id,
|
||||
path = track.streamUrl,
|
||||
sizeBytes = 0,
|
||||
lastPlayedAt = now,
|
||||
source = CacheSource.INCIDENTAL,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+23
-21
@@ -33,28 +33,30 @@ import javax.inject.Singleton
|
||||
* library is opened offline with no active playback.
|
||||
*/
|
||||
@Singleton
|
||||
class CachedTrackIds @Inject constructor(
|
||||
playerController: PlayerController,
|
||||
private val playerFactory: PlayerFactory,
|
||||
@ApplicationScope scope: CoroutineScope,
|
||||
) {
|
||||
private val refresh = MutableStateFlow(0L)
|
||||
class CachedTrackIds
|
||||
@Inject
|
||||
constructor(
|
||||
playerController: PlayerController,
|
||||
private val playerFactory: PlayerFactory,
|
||||
@ApplicationScope scope: CoroutineScope,
|
||||
) {
|
||||
private val refresh = MutableStateFlow(0L)
|
||||
|
||||
val ids: StateFlow<Set<String>> =
|
||||
refresh
|
||||
.map { readKeys() }
|
||||
.flowOn(Dispatchers.IO)
|
||||
.stateIn(scope, SharingStarted.Eagerly, emptySet())
|
||||
val ids: StateFlow<Set<String>> =
|
||||
refresh
|
||||
.map { readKeys() }
|
||||
.flowOn(Dispatchers.IO)
|
||||
.stateIn(scope, SharingStarted.Eagerly, emptySet())
|
||||
|
||||
init {
|
||||
scope.launch {
|
||||
playerController.uiState
|
||||
.map { it.currentTrack?.id }
|
||||
.distinctUntilChanged()
|
||||
.collect { refresh.value += 1 }
|
||||
init {
|
||||
scope.launch {
|
||||
playerController.uiState
|
||||
.map { it.currentTrack?.id }
|
||||
.distinctUntilChanged()
|
||||
.collect { refresh.value += 1 }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun readKeys(): Set<String> =
|
||||
runCatching { playerFactory.simpleCache.keys.toSet() }.getOrDefault(emptySet())
|
||||
}
|
||||
private fun readKeys(): Set<String> =
|
||||
runCatching { playerFactory.simpleCache.keys.toSet() }.getOrDefault(emptySet())
|
||||
}
|
||||
|
||||
+37
-34
@@ -28,42 +28,45 @@ private const val POOL_LIMIT = 100
|
||||
* plays the pool from the cache.
|
||||
*/
|
||||
@Singleton
|
||||
class ShuffleSource @Inject constructor(
|
||||
private val cacheIndexDao: AudioCacheIndexDao,
|
||||
private val trackDao: CachedTrackDao,
|
||||
private val likes: LikesRepository,
|
||||
private val playerFactory: PlayerFactory,
|
||||
) {
|
||||
/** Cached tracks, most-recently-played first (liked included). */
|
||||
suspend fun recentlyPlayed(limit: Int = POOL_LIMIT): List<TrackRef> =
|
||||
materialize(residentIdsByRecency()).take(limit)
|
||||
class ShuffleSource
|
||||
@Inject
|
||||
constructor(
|
||||
private val cacheIndexDao: AudioCacheIndexDao,
|
||||
private val trackDao: CachedTrackDao,
|
||||
private val likes: LikesRepository,
|
||||
private val playerFactory: PlayerFactory,
|
||||
) {
|
||||
/** Cached tracks, most-recently-played first (liked included). */
|
||||
suspend fun recentlyPlayed(limit: Int = POOL_LIMIT): List<TrackRef> =
|
||||
materialize(residentIdsByRecency()).take(limit)
|
||||
|
||||
/** Cached tracks that are in the user's liked set, recency-ordered. */
|
||||
suspend fun liked(limit: Int = POOL_LIMIT): List<TrackRef> {
|
||||
val likedSet = likes.likedTrackIds()
|
||||
val ids = residentIdsByRecency().filter { it in likedSet }
|
||||
return materialize(ids).take(limit)
|
||||
}
|
||||
/** Cached tracks that are in the user's liked set, recency-ordered. */
|
||||
suspend fun liked(limit: Int = POOL_LIMIT): List<TrackRef> {
|
||||
val likedSet = likes.likedTrackIds()
|
||||
val ids = residentIdsByRecency().filter { it in likedSet }
|
||||
return materialize(ids).take(limit)
|
||||
}
|
||||
|
||||
/** Recency-ordered ids whose audio is actually resident in the cache. */
|
||||
private suspend fun residentIdsByRecency(): List<String> {
|
||||
val resident = runCatching { playerFactory.simpleCache.keys.toSet() }
|
||||
.getOrDefault(emptySet())
|
||||
return cacheIndexDao.trackIdsByRecency().filter { it in resident }
|
||||
}
|
||||
/** Recency-ordered ids whose audio is actually resident in the cache. */
|
||||
private suspend fun residentIdsByRecency(): List<String> {
|
||||
val resident =
|
||||
runCatching { playerFactory.simpleCache.keys.toSet() }
|
||||
.getOrDefault(emptySet())
|
||||
return cacheIndexDao.trackIdsByRecency().filter { it in resident }
|
||||
}
|
||||
|
||||
/** Materialize ordered ids into TrackRefs from cached metadata, preserving order. */
|
||||
private suspend fun materialize(orderedIds: List<String>): List<TrackRef> {
|
||||
if (orderedIds.isEmpty()) return emptyList()
|
||||
val byId = trackDao.getByIds(orderedIds).associateBy { it.id }
|
||||
return orderedIds.mapNotNull { id ->
|
||||
// Clear the server's missing mark. Every id reaching here
|
||||
// came through residentIdsByRecency, which already proved the
|
||||
// AUDIO is in the local cache — so these play regardless of what
|
||||
// the server has lost, and the queue filter in PlayerController
|
||||
// would otherwise throw away tracks that work perfectly. Missing
|
||||
// means "cannot stream", not "cannot play".
|
||||
byId[id]?.toDomain()?.copy(unavailable = false)
|
||||
/** Materialize ordered ids into TrackRefs from cached metadata, preserving order. */
|
||||
private suspend fun materialize(orderedIds: List<String>): List<TrackRef> {
|
||||
if (orderedIds.isEmpty()) return emptyList()
|
||||
val byId = trackDao.getByIds(orderedIds).associateBy { it.id }
|
||||
return orderedIds.mapNotNull { id ->
|
||||
// Clear the server's missing mark. Every id reaching here
|
||||
// came through residentIdsByRecency, which already proved the
|
||||
// AUDIO is in the local cache — so these play regardless of what
|
||||
// the server has lost, and the queue filter in PlayerController
|
||||
// would otherwise throw away tracks that work perfectly. Missing
|
||||
// means "cannot stream", not "cannot play".
|
||||
byId[id]?.toDomain()?.copy(unavailable = false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+56
-46
@@ -34,12 +34,17 @@ internal enum class OwnerStep {
|
||||
OWNED,
|
||||
}
|
||||
|
||||
internal fun ownerStep(loaded: Boolean, signedInUserId: String?, ownerUserId: String?): OwnerStep = when {
|
||||
!loaded || signedInUserId == null -> OwnerStep.WAIT
|
||||
ownerUserId == null -> OwnerStep.ADOPT
|
||||
ownerUserId != signedInUserId -> OwnerStep.SWITCH
|
||||
else -> OwnerStep.OWNED
|
||||
}
|
||||
internal fun ownerStep(
|
||||
loaded: Boolean,
|
||||
signedInUserId: String?,
|
||||
ownerUserId: String?,
|
||||
): OwnerStep =
|
||||
when {
|
||||
!loaded || signedInUserId == null -> OwnerStep.WAIT
|
||||
ownerUserId == null -> OwnerStep.ADOPT
|
||||
ownerUserId != signedInUserId -> OwnerStep.SWITCH
|
||||
else -> OwnerStep.OWNED
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps one account's cached data from reaching another account on a
|
||||
@@ -62,48 +67,53 @@ internal fun ownerStep(loaded: Boolean, signedInUserId: String?, ownerUserId: St
|
||||
* out under another account's session.
|
||||
*/
|
||||
@Singleton
|
||||
class AccountCache @Inject constructor(
|
||||
private val authStore: AuthStore,
|
||||
authController: AuthController,
|
||||
private val tables: AccountTables,
|
||||
private val player: Lazy<PlayerController>,
|
||||
@ApplicationScope scope: CoroutineScope,
|
||||
) {
|
||||
private val ownedState = MutableStateFlow(false)
|
||||
class AccountCache
|
||||
@Inject
|
||||
constructor(
|
||||
private val authStore: AuthStore,
|
||||
authController: AuthController,
|
||||
private val tables: AccountTables,
|
||||
private val player: Lazy<PlayerController>,
|
||||
@ApplicationScope scope: CoroutineScope,
|
||||
) {
|
||||
private val ownedState = MutableStateFlow(false)
|
||||
|
||||
/** True while the signed-in account is the one the cached data belongs to. */
|
||||
val ownedBySignedInUser: StateFlow<Boolean> = ownedState.asStateFlow()
|
||||
/** True while the signed-in account is the one the cached data belongs to. */
|
||||
val ownedBySignedInUser: StateFlow<Boolean> = ownedState.asStateFlow()
|
||||
|
||||
init {
|
||||
scope.launch {
|
||||
combine(
|
||||
authStore.settingsLoaded,
|
||||
authController.currentUser,
|
||||
authStore.cacheOwnerUserId,
|
||||
) { loaded, user, owner -> Triple(loaded, user?.id, owner) }
|
||||
.distinctUntilChanged()
|
||||
.collect { (loaded, userId, owner) -> step(ownerStep(loaded, userId, owner), userId) }
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun step(step: OwnerStep, userId: String?) {
|
||||
when (step) {
|
||||
OwnerStep.WAIT -> ownedState.value = false
|
||||
// The stored owner changes next, and that emission reports OWNED.
|
||||
OwnerStep.ADOPT -> authStore.setCacheOwnerUserId(userId)
|
||||
OwnerStep.SWITCH -> {
|
||||
ownedState.value = false
|
||||
clearAccountData()
|
||||
authStore.setCacheOwnerUserId(userId)
|
||||
init {
|
||||
scope.launch {
|
||||
combine(
|
||||
authStore.settingsLoaded,
|
||||
authController.currentUser,
|
||||
authStore.cacheOwnerUserId,
|
||||
) { loaded, user, owner -> Triple(loaded, user?.id, owner) }
|
||||
.distinctUntilChanged()
|
||||
.collect { (loaded, userId, owner) -> step(ownerStep(loaded, userId, owner), userId) }
|
||||
}
|
||||
OwnerStep.OWNED -> ownedState.value = true
|
||||
}
|
||||
|
||||
private suspend fun step(
|
||||
step: OwnerStep,
|
||||
userId: String?,
|
||||
) {
|
||||
when (step) {
|
||||
OwnerStep.WAIT -> ownedState.value = false
|
||||
// The stored owner changes next, and that emission reports OWNED.
|
||||
OwnerStep.ADOPT -> authStore.setCacheOwnerUserId(userId)
|
||||
OwnerStep.SWITCH -> {
|
||||
ownedState.value = false
|
||||
clearAccountData()
|
||||
authStore.setCacheOwnerUserId(userId)
|
||||
}
|
||||
OwnerStep.OWNED -> ownedState.value = true
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun clearAccountData() {
|
||||
Timber.i("account cache: another account signed in; clearing the last one's data")
|
||||
tables.clear()
|
||||
authStore.clearNotifiedUpTo()
|
||||
player.get().clearQueue()
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun clearAccountData() {
|
||||
Timber.i("account cache: another account signed in; clearing the last one's data")
|
||||
tables.clear()
|
||||
authStore.clearNotifiedUpTo()
|
||||
player.get().clearQueue()
|
||||
}
|
||||
}
|
||||
|
||||
+16
-12
@@ -12,17 +12,21 @@ import javax.inject.Singleton
|
||||
* (likes, playlists) or shared by every account (the library) does not.
|
||||
*/
|
||||
@Singleton
|
||||
class AccountTables @Inject constructor(private val db: AppDatabase) {
|
||||
/** Clears them in one transaction, so a crash can't leave half of them. */
|
||||
suspend fun clear() {
|
||||
db.withTransaction {
|
||||
db.cachedMutationDao().clear()
|
||||
db.cachedHomeIndexDao().clear()
|
||||
db.cachedHistorySnapshotDao().clear()
|
||||
db.cachedQuarantineDao().clear()
|
||||
db.cachedResumeStateDao().clear()
|
||||
db.cachedNotificationDao().clear()
|
||||
db.cachedNotificationDao().clearSettings()
|
||||
class AccountTables
|
||||
@Inject
|
||||
constructor(
|
||||
private val db: AppDatabase,
|
||||
) {
|
||||
/** Clears them in one transaction, so a crash can't leave half of them. */
|
||||
suspend fun clear() {
|
||||
db.withTransaction {
|
||||
db.cachedMutationDao().clear()
|
||||
db.cachedHomeIndexDao().clear()
|
||||
db.cachedHistorySnapshotDao().clear()
|
||||
db.cachedQuarantineDao().clear()
|
||||
db.cachedResumeStateDao().clear()
|
||||
db.cachedNotificationDao().clear()
|
||||
db.cachedNotificationDao().clearSettings()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+19
-12
@@ -27,10 +27,11 @@ class BucketLedger<S : Any>(
|
||||
private val lengthOf: (S) -> Long,
|
||||
lruOrder: Comparator<S>,
|
||||
) {
|
||||
private val spans = mapOf(
|
||||
CacheBucket.LIKED to TreeSet(lruOrder),
|
||||
CacheBucket.RECENT to TreeSet(lruOrder),
|
||||
)
|
||||
private val spans =
|
||||
mapOf(
|
||||
CacheBucket.LIKED to TreeSet(lruOrder),
|
||||
CacheBucket.RECENT to TreeSet(lruOrder),
|
||||
)
|
||||
private val bytes = mutableMapOf(CacheBucket.LIKED to 0L, CacheBucket.RECENT to 0L)
|
||||
private val spansByKey = HashMap<String, MutableSet<S>>()
|
||||
private val bucketByKey = HashMap<String, CacheBucket>()
|
||||
@@ -43,16 +44,16 @@ class BucketLedger<S : Any>(
|
||||
/** Cap on Recently played bytes; 0 means unlimited. */
|
||||
var recentCapBytes: Long = 0L
|
||||
|
||||
fun bucketOf(key: String): CacheBucket =
|
||||
if (key in liked) CacheBucket.LIKED else CacheBucket.RECENT
|
||||
fun bucketOf(key: String): CacheBucket = if (key in liked) CacheBucket.LIKED else CacheBucket.RECENT
|
||||
|
||||
fun bytesIn(bucket: CacheBucket): Long = bytes.getValue(bucket)
|
||||
|
||||
/** Bytes the Liked budget can still take; [Long.MAX_VALUE] when unlimited. */
|
||||
fun likedRoomBytes(): Long = when {
|
||||
likedCapBytes <= 0L -> Long.MAX_VALUE
|
||||
else -> (likedCapBytes - bytesIn(CacheBucket.LIKED)).coerceAtLeast(0L)
|
||||
}
|
||||
fun likedRoomBytes(): Long =
|
||||
when {
|
||||
likedCapBytes <= 0L -> Long.MAX_VALUE
|
||||
else -> (likedCapBytes - bytesIn(CacheBucket.LIKED)).coerceAtLeast(0L)
|
||||
}
|
||||
|
||||
fun add(span: S) {
|
||||
val key = keyOf(span)
|
||||
@@ -105,7 +106,10 @@ class BucketLedger<S : Any>(
|
||||
* [pendingBytes] describe a write about to start, so room is made for it
|
||||
* in its own bucket first. Recently played is trimmed before Liked.
|
||||
*/
|
||||
fun nextEviction(pendingKey: String? = null, pendingBytes: Long = 0L): S? {
|
||||
fun nextEviction(
|
||||
pendingKey: String? = null,
|
||||
pendingBytes: Long = 0L,
|
||||
): S? {
|
||||
if (!armed) return null
|
||||
val pendingBucket = pendingKey?.let(::bucketOf)
|
||||
return listOf(CacheBucket.RECENT, CacheBucket.LIKED).firstNotNullOfOrNull { bucket ->
|
||||
@@ -114,7 +118,10 @@ class BucketLedger<S : Any>(
|
||||
}
|
||||
}
|
||||
|
||||
private fun oldestIfOver(bucket: CacheBucket, incoming: Long): S? {
|
||||
private fun oldestIfOver(
|
||||
bucket: CacheBucket,
|
||||
incoming: Long,
|
||||
): S? {
|
||||
val cap = if (bucket == CacheBucket.LIKED) likedCapBytes else recentCapBytes
|
||||
val over = cap > 0L && bytesIn(bucket) + incoming > cap
|
||||
return if (over) spans.getValue(bucket).firstOrNull() else null
|
||||
|
||||
+15
-13
@@ -23,18 +23,20 @@ import javax.inject.Singleton
|
||||
* `MinstrelApplication`.
|
||||
*/
|
||||
@Singleton
|
||||
class CacheBudgetSync @Inject constructor(
|
||||
likes: LikesRepository,
|
||||
authStore: AuthStore,
|
||||
evictor: TwoBucketCacheEvictor,
|
||||
@ApplicationScope scope: CoroutineScope,
|
||||
) {
|
||||
init {
|
||||
scope.launch(Dispatchers.IO) {
|
||||
combine(likes.observeSignedInLikedTrackIds(), authStore.cacheSettings, ::Pair)
|
||||
.collect { (ids, settings) ->
|
||||
evictor.update(ids, settings.likedCapBytes, settings.rollingCapBytes)
|
||||
}
|
||||
class CacheBudgetSync
|
||||
@Inject
|
||||
constructor(
|
||||
likes: LikesRepository,
|
||||
authStore: AuthStore,
|
||||
evictor: TwoBucketCacheEvictor,
|
||||
@ApplicationScope scope: CoroutineScope,
|
||||
) {
|
||||
init {
|
||||
scope.launch(Dispatchers.IO) {
|
||||
combine(likes.observeSignedInLikedTrackIds(), authStore.cacheSettings, ::Pair)
|
||||
.collect { (ids, settings) ->
|
||||
evictor.update(ids, settings.likedCapBytes, settings.rollingCapBytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+101
-70
@@ -11,7 +11,11 @@ import javax.inject.Singleton
|
||||
* Bytes held against each audio-cache budget, and how much more the Liked
|
||||
* budget can take ([Long.MAX_VALUE] when it is unlimited).
|
||||
*/
|
||||
data class CacheUsage(val likedBytes: Long, val recentBytes: Long, val likedRoomBytes: Long)
|
||||
data class CacheUsage(
|
||||
val likedBytes: Long,
|
||||
val recentBytes: Long,
|
||||
val likedRoomBytes: Long,
|
||||
)
|
||||
|
||||
/**
|
||||
* The audio cache's eviction policy: two budgets, Liked songs and Recently
|
||||
@@ -29,84 +33,111 @@ data class CacheUsage(val likedBytes: Long, val recentBytes: Long, val likedRoom
|
||||
* deadlock.
|
||||
*/
|
||||
@Singleton
|
||||
class TwoBucketCacheEvictor @Inject constructor() : CacheEvictor {
|
||||
private val ledger = BucketLedger<CacheSpan>(
|
||||
keyOf = { it.key },
|
||||
lengthOf = { it.length },
|
||||
lruOrder = compareBy<CacheSpan> { it.lastTouchTimestamp }.then(naturalOrder()),
|
||||
)
|
||||
class TwoBucketCacheEvictor
|
||||
@Inject
|
||||
constructor() : CacheEvictor {
|
||||
private val ledger =
|
||||
BucketLedger<CacheSpan>(
|
||||
keyOf = { it.key },
|
||||
lengthOf = { it.length },
|
||||
lruOrder = compareBy<CacheSpan> { it.lastTouchTimestamp }.then(naturalOrder()),
|
||||
)
|
||||
|
||||
@Volatile private var cache: Cache? = null
|
||||
@Volatile private var cache: Cache? = null
|
||||
|
||||
/** Called once the SimpleCache exists, so updates can trim it. */
|
||||
fun attach(cache: Cache) {
|
||||
this.cache = cache
|
||||
}
|
||||
|
||||
/** Apply a new liked set and caps, then trim whatever no longer fits. */
|
||||
fun update(likedIds: Set<String>, likedCapBytes: Long, recentCapBytes: Long) {
|
||||
val c = cache
|
||||
val apply = {
|
||||
ledger.likedCapBytes = likedCapBytes
|
||||
ledger.recentCapBytes = recentCapBytes
|
||||
ledger.setLiked(likedIds)
|
||||
/** Called once the SimpleCache exists, so updates can trim it. */
|
||||
fun attach(cache: Cache) {
|
||||
this.cache = cache
|
||||
}
|
||||
if (c == null) {
|
||||
synchronized(ledger) { apply() }
|
||||
} else {
|
||||
synchronized(c) {
|
||||
synchronized(ledger) {
|
||||
apply()
|
||||
evict(c, pendingKey = null, pendingBytes = 0L)
|
||||
|
||||
/** Apply a new liked set and caps, then trim whatever no longer fits. */
|
||||
fun update(
|
||||
likedIds: Set<String>,
|
||||
likedCapBytes: Long,
|
||||
recentCapBytes: Long,
|
||||
) {
|
||||
val c = cache
|
||||
val apply = {
|
||||
ledger.likedCapBytes = likedCapBytes
|
||||
ledger.recentCapBytes = recentCapBytes
|
||||
ledger.setLiked(likedIds)
|
||||
}
|
||||
if (c == null) {
|
||||
synchronized(ledger) { apply() }
|
||||
} else {
|
||||
synchronized(c) {
|
||||
synchronized(ledger) {
|
||||
apply()
|
||||
evict(c, pendingKey = null, pendingBytes = 0L)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun usage(): CacheUsage = synchronized(ledger) {
|
||||
CacheUsage(
|
||||
likedBytes = ledger.bytesIn(CacheBucket.LIKED),
|
||||
recentBytes = ledger.bytesIn(CacheBucket.RECENT),
|
||||
likedRoomBytes = ledger.likedRoomBytes(),
|
||||
)
|
||||
}
|
||||
fun usage(): CacheUsage =
|
||||
synchronized(ledger) {
|
||||
CacheUsage(
|
||||
likedBytes = ledger.bytesIn(CacheBucket.LIKED),
|
||||
recentBytes = ledger.bytesIn(CacheBucket.RECENT),
|
||||
likedRoomBytes = ledger.likedRoomBytes(),
|
||||
)
|
||||
}
|
||||
|
||||
override fun requiresCacheSpanTouches(): Boolean = true
|
||||
override fun requiresCacheSpanTouches(): Boolean = true
|
||||
|
||||
override fun onCacheInitialized() = Unit
|
||||
override fun onCacheInitialized() = Unit
|
||||
|
||||
override fun onStartFile(cache: Cache, key: String, position: Long, length: Long) {
|
||||
synchronized(ledger) {
|
||||
evict(cache, key, if (length == C.LENGTH_UNSET.toLong()) 0L else length)
|
||||
override fun onStartFile(
|
||||
cache: Cache,
|
||||
key: String,
|
||||
position: Long,
|
||||
length: Long,
|
||||
) {
|
||||
synchronized(ledger) {
|
||||
evict(cache, key, if (length == C.LENGTH_UNSET.toLong()) 0L else length)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onSpanAdded(
|
||||
cache: Cache,
|
||||
span: CacheSpan,
|
||||
) {
|
||||
synchronized(ledger) {
|
||||
ledger.add(span)
|
||||
evict(cache, pendingKey = null, pendingBytes = 0L)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onSpanRemoved(
|
||||
cache: Cache,
|
||||
span: CacheSpan,
|
||||
) {
|
||||
synchronized(ledger) { ledger.remove(span) }
|
||||
}
|
||||
|
||||
override fun onSpanTouched(
|
||||
cache: Cache,
|
||||
oldSpan: CacheSpan,
|
||||
newSpan: CacheSpan,
|
||||
) {
|
||||
synchronized(ledger) {
|
||||
ledger.remove(oldSpan)
|
||||
ledger.add(newSpan)
|
||||
evict(cache, pendingKey = null, pendingBytes = 0L)
|
||||
}
|
||||
}
|
||||
|
||||
private fun evict(
|
||||
cache: Cache,
|
||||
pendingKey: String?,
|
||||
pendingBytes: Long,
|
||||
) {
|
||||
while (true) {
|
||||
val span = ledger.nextEviction(pendingKey, pendingBytes) ?: return
|
||||
cache.removeSpan(span)
|
||||
// removeSpan reports back through onSpanRemoved; removing here as
|
||||
// well guarantees the loop advances even if it did not.
|
||||
ledger.remove(span)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onSpanAdded(cache: Cache, span: CacheSpan) {
|
||||
synchronized(ledger) {
|
||||
ledger.add(span)
|
||||
evict(cache, pendingKey = null, pendingBytes = 0L)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onSpanRemoved(cache: Cache, span: CacheSpan) {
|
||||
synchronized(ledger) { ledger.remove(span) }
|
||||
}
|
||||
|
||||
override fun onSpanTouched(cache: Cache, oldSpan: CacheSpan, newSpan: CacheSpan) {
|
||||
synchronized(ledger) {
|
||||
ledger.remove(oldSpan)
|
||||
ledger.add(newSpan)
|
||||
evict(cache, pendingKey = null, pendingBytes = 0L)
|
||||
}
|
||||
}
|
||||
|
||||
private fun evict(cache: Cache, pendingKey: String?, pendingBytes: Long) {
|
||||
while (true) {
|
||||
val span = ledger.nextEviction(pendingKey, pendingBytes) ?: return
|
||||
cache.removeSpan(span)
|
||||
// removeSpan reports back through onSpanRemoved; removing here as
|
||||
// well guarantees the loop advances even if it did not.
|
||||
ledger.remove(span)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+67
-45
@@ -15,9 +15,9 @@ import com.fabledsword.minstrel.cache.db.dao.CachedLikeDao
|
||||
import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao
|
||||
import com.fabledsword.minstrel.cache.db.dao.CachedNotificationDao
|
||||
import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistDao
|
||||
import com.fabledsword.minstrel.cache.db.dao.CachedResumeStateDao
|
||||
import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistTrackDao
|
||||
import com.fabledsword.minstrel.cache.db.dao.CachedQuarantineDao
|
||||
import com.fabledsword.minstrel.cache.db.dao.CachedResumeStateDao
|
||||
import com.fabledsword.minstrel.cache.db.dao.CachedTrackDao
|
||||
import com.fabledsword.minstrel.cache.db.dao.DiagnosticEventDao
|
||||
import com.fabledsword.minstrel.cache.db.dao.SyncMetadataDao
|
||||
@@ -32,9 +32,9 @@ import com.fabledsword.minstrel.cache.db.entities.CachedMutationEntity
|
||||
import com.fabledsword.minstrel.cache.db.entities.CachedNotificationEntity
|
||||
import com.fabledsword.minstrel.cache.db.entities.CachedNotificationSettingsEntity
|
||||
import com.fabledsword.minstrel.cache.db.entities.CachedPlaylistEntity
|
||||
import com.fabledsword.minstrel.cache.db.entities.CachedResumeStateEntity
|
||||
import com.fabledsword.minstrel.cache.db.entities.CachedPlaylistTrackEntity
|
||||
import com.fabledsword.minstrel.cache.db.entities.CachedQuarantineEntity
|
||||
import com.fabledsword.minstrel.cache.db.entities.CachedResumeStateEntity
|
||||
import com.fabledsword.minstrel.cache.db.entities.CachedTrackEntity
|
||||
import com.fabledsword.minstrel.cache.db.entities.DiagnosticEventEntity
|
||||
import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity
|
||||
@@ -101,104 +101,126 @@ import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity
|
||||
@TypeConverters(MinstrelTypeConverters::class)
|
||||
abstract class AppDatabase : RoomDatabase() {
|
||||
abstract fun syncMetadataDao(): SyncMetadataDao
|
||||
|
||||
abstract fun cachedArtistDao(): CachedArtistDao
|
||||
|
||||
abstract fun cachedAlbumDao(): CachedAlbumDao
|
||||
|
||||
abstract fun cachedTrackDao(): CachedTrackDao
|
||||
|
||||
abstract fun cachedLikeDao(): CachedLikeDao
|
||||
|
||||
abstract fun cachedPlaylistDao(): CachedPlaylistDao
|
||||
|
||||
abstract fun cachedPlaylistTrackDao(): CachedPlaylistTrackDao
|
||||
|
||||
abstract fun cachedQuarantineDao(): CachedQuarantineDao
|
||||
|
||||
abstract fun audioCacheIndexDao(): AudioCacheIndexDao
|
||||
|
||||
abstract fun cachedMutationDao(): CachedMutationDao
|
||||
|
||||
abstract fun cachedResumeStateDao(): CachedResumeStateDao
|
||||
|
||||
abstract fun cachedHomeIndexDao(): CachedHomeIndexDao
|
||||
|
||||
abstract fun cachedHistorySnapshotDao(): CachedHistorySnapshotDao
|
||||
|
||||
abstract fun authSessionDao(): AuthSessionDao
|
||||
|
||||
abstract fun diagnosticEventDao(): DiagnosticEventDao
|
||||
|
||||
abstract fun cachedNotificationDao(): CachedNotificationDao
|
||||
}
|
||||
|
||||
/** v8 → v9: add the nullable normalization preference column. */
|
||||
val MIGRATION_8_9: Migration = object : Migration(8, 9) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL("ALTER TABLE auth_session ADD COLUMN normalizationJson TEXT")
|
||||
val MIGRATION_8_9: Migration =
|
||||
object : Migration(8, 9) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL("ALTER TABLE auth_session ADD COLUMN normalizationJson TEXT")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* v9 → v10: the gain columns. Rows synced before this carry no gains,
|
||||
* and the sync is incremental, so it would never re-send them: the cursor goes
|
||||
* back to 0 and the next sync is a full one, upserting every row in place.
|
||||
*/
|
||||
val MIGRATION_9_10: Migration = object : Migration(9, 10) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL("ALTER TABLE cached_tracks ADD COLUMN trackGain REAL")
|
||||
db.execSQL("ALTER TABLE cached_tracks ADD COLUMN trackPeak REAL")
|
||||
db.execSQL("ALTER TABLE cached_albums ADD COLUMN albumGain REAL")
|
||||
db.execSQL("ALTER TABLE cached_albums ADD COLUMN albumPeak REAL")
|
||||
db.execSQL("UPDATE sync_metadata SET cursor = 0")
|
||||
val MIGRATION_9_10: Migration =
|
||||
object : Migration(9, 10) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL("ALTER TABLE cached_tracks ADD COLUMN trackGain REAL")
|
||||
db.execSQL("ALTER TABLE cached_tracks ADD COLUMN trackPeak REAL")
|
||||
db.execSQL("ALTER TABLE cached_albums ADD COLUMN albumGain REAL")
|
||||
db.execSQL("ALTER TABLE cached_albums ADD COLUMN albumPeak REAL")
|
||||
db.execSQL("UPDATE sync_metadata SET cursor = 0")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* v10 → v11: the notifications inbox cache and its settings. The SQL
|
||||
* matches what Room generates for the two entities; Room checks it on open.
|
||||
*/
|
||||
val MIGRATION_10_11: Migration = object : Migration(10, 11) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL(
|
||||
"CREATE TABLE IF NOT EXISTS `cached_notifications` (" +
|
||||
"`id` TEXT NOT NULL, `kind` TEXT NOT NULL, `title` TEXT NOT NULL, " +
|
||||
"`body` TEXT NOT NULL, `link` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, " +
|
||||
"`readAt` INTEGER, PRIMARY KEY(`id`))",
|
||||
)
|
||||
db.execSQL(
|
||||
"CREATE TABLE IF NOT EXISTS `cached_notification_settings` (" +
|
||||
"`id` INTEGER NOT NULL, `json` TEXT NOT NULL, PRIMARY KEY(`id`))",
|
||||
)
|
||||
val MIGRATION_10_11: Migration =
|
||||
object : Migration(10, 11) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL(
|
||||
"CREATE TABLE IF NOT EXISTS `cached_notifications` (" +
|
||||
"`id` TEXT NOT NULL, `kind` TEXT NOT NULL, `title` TEXT NOT NULL, " +
|
||||
"`body` TEXT NOT NULL, `link` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, " +
|
||||
"`readAt` INTEGER, PRIMARY KEY(`id`))",
|
||||
)
|
||||
db.execSQL(
|
||||
"CREATE TABLE IF NOT EXISTS `cached_notification_settings` (" +
|
||||
"`id` INTEGER NOT NULL, `json` TEXT NOT NULL, PRIMARY KEY(`id`))",
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* v11 → v12: background delivery. The device choice defaults on,
|
||||
* as the entity's column default says; the high-water mark starts empty, so
|
||||
* the first catch-up sets it without announcing anything.
|
||||
*/
|
||||
val MIGRATION_11_12: Migration = object : Migration(11, 12) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL("ALTER TABLE auth_session ADD COLUMN backgroundDelivery INTEGER NOT NULL DEFAULT 1")
|
||||
db.execSQL("ALTER TABLE auth_session ADD COLUMN notifiedUpTo INTEGER")
|
||||
val MIGRATION_11_12: Migration =
|
||||
object : Migration(11, 12) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL("ALTER TABLE auth_session ADD COLUMN backgroundDelivery INTEGER NOT NULL DEFAULT 1")
|
||||
db.execSQL("ALTER TABLE auth_session ADD COLUMN notifiedUpTo INTEGER")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* v12 → v13: a playlist's cover albums and creation time. Both start empty;
|
||||
* Home refreshes the playlist list on open, which fills them.
|
||||
*/
|
||||
val MIGRATION_12_13: Migration = object : Migration(12, 13) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL("ALTER TABLE cached_playlists ADD COLUMN coverAlbumIds TEXT NOT NULL DEFAULT ''")
|
||||
db.execSQL("ALTER TABLE cached_playlists ADD COLUMN createdAt TEXT NOT NULL DEFAULT ''")
|
||||
val MIGRATION_12_13: Migration =
|
||||
object : Migration(12, 13) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL("ALTER TABLE cached_playlists ADD COLUMN coverAlbumIds TEXT NOT NULL DEFAULT ''")
|
||||
db.execSQL("ALTER TABLE cached_playlists ADD COLUMN createdAt TEXT NOT NULL DEFAULT ''")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* v13 → v14: a playlist's place on its Home shelf. Starts at 0 (unranked);
|
||||
* Home refreshes the playlist list on open, which fills it.
|
||||
*/
|
||||
val MIGRATION_13_14: Migration = object : Migration(13, 14) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL("ALTER TABLE cached_playlists ADD COLUMN shelfRank INTEGER NOT NULL DEFAULT 0")
|
||||
val MIGRATION_13_14: Migration =
|
||||
object : Migration(13, 14) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL("ALTER TABLE cached_playlists ADD COLUMN shelfRank INTEGER NOT NULL DEFAULT 0")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* v14 → v15: the account the cached data belongs to. Starts empty, and
|
||||
* AccountCache adopts whoever is signed in without clearing anything, so
|
||||
* an update keeps the signed-in person's queued writes and cache.
|
||||
*/
|
||||
val MIGRATION_14_15: Migration = object : Migration(14, 15) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL("ALTER TABLE auth_session ADD COLUMN cacheOwnerUserId TEXT")
|
||||
val MIGRATION_14_15: Migration =
|
||||
object : Migration(14, 15) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL("ALTER TABLE auth_session ADD COLUMN cacheOwnerUserId TEXT")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+17
-25
@@ -11,12 +11,12 @@ import com.fabledsword.minstrel.cache.db.dao.CachedHomeIndexDao
|
||||
import com.fabledsword.minstrel.cache.db.dao.CachedLikeDao
|
||||
import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao
|
||||
import com.fabledsword.minstrel.cache.db.dao.CachedNotificationDao
|
||||
import com.fabledsword.minstrel.cache.db.dao.DiagnosticEventDao
|
||||
import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistDao
|
||||
import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistTrackDao
|
||||
import com.fabledsword.minstrel.cache.db.dao.CachedQuarantineDao
|
||||
import com.fabledsword.minstrel.cache.db.dao.CachedResumeStateDao
|
||||
import com.fabledsword.minstrel.cache.db.dao.CachedTrackDao
|
||||
import com.fabledsword.minstrel.cache.db.dao.DiagnosticEventDao
|
||||
import com.fabledsword.minstrel.cache.db.dao.SyncMetadataDao
|
||||
import dagger.Module
|
||||
import dagger.Provides
|
||||
@@ -31,8 +31,11 @@ import javax.inject.Singleton
|
||||
object DatabaseModule {
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideDatabase(@ApplicationContext context: Context): AppDatabase =
|
||||
Room.databaseBuilder(context, AppDatabase::class.java, DATABASE_NAME)
|
||||
fun provideDatabase(
|
||||
@ApplicationContext context: Context,
|
||||
): AppDatabase =
|
||||
Room
|
||||
.databaseBuilder(context, AppDatabase::class.java, DATABASE_NAME)
|
||||
// Explicit migrations from v8 onward; an older schema has no path
|
||||
// and rebuilds. The sync controller refills the cache from the
|
||||
// server on first launch, so a rebuild loses only the unsynced
|
||||
@@ -45,8 +48,7 @@ object DatabaseModule {
|
||||
MIGRATION_12_13,
|
||||
MIGRATION_13_14,
|
||||
MIGRATION_14_15,
|
||||
)
|
||||
.fallbackToDestructiveMigration(dropAllTables = true)
|
||||
).fallbackToDestructiveMigration(dropAllTables = true)
|
||||
.build()
|
||||
|
||||
// DAO @Provides — Hilt can't inject AppDatabase abstract accessors
|
||||
@@ -69,33 +71,27 @@ object DatabaseModule {
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideCachedResumeStateDao(db: AppDatabase): CachedResumeStateDao =
|
||||
db.cachedResumeStateDao()
|
||||
fun provideCachedResumeStateDao(db: AppDatabase): CachedResumeStateDao = db.cachedResumeStateDao()
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideCachedHomeIndexDao(db: AppDatabase): CachedHomeIndexDao =
|
||||
db.cachedHomeIndexDao()
|
||||
fun provideCachedHomeIndexDao(db: AppDatabase): CachedHomeIndexDao = db.cachedHomeIndexDao()
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideCachedHistorySnapshotDao(db: AppDatabase): CachedHistorySnapshotDao =
|
||||
db.cachedHistorySnapshotDao()
|
||||
fun provideCachedHistorySnapshotDao(db: AppDatabase): CachedHistorySnapshotDao = db.cachedHistorySnapshotDao()
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideCachedQuarantineDao(db: AppDatabase): CachedQuarantineDao =
|
||||
db.cachedQuarantineDao()
|
||||
fun provideCachedQuarantineDao(db: AppDatabase): CachedQuarantineDao = db.cachedQuarantineDao()
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideCachedPlaylistDao(db: AppDatabase): CachedPlaylistDao =
|
||||
db.cachedPlaylistDao()
|
||||
fun provideCachedPlaylistDao(db: AppDatabase): CachedPlaylistDao = db.cachedPlaylistDao()
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideCachedPlaylistTrackDao(db: AppDatabase): CachedPlaylistTrackDao =
|
||||
db.cachedPlaylistTrackDao()
|
||||
fun provideCachedPlaylistTrackDao(db: AppDatabase): CachedPlaylistTrackDao = db.cachedPlaylistTrackDao()
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
@@ -103,8 +99,7 @@ object DatabaseModule {
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideCachedMutationDao(db: AppDatabase): CachedMutationDao =
|
||||
db.cachedMutationDao()
|
||||
fun provideCachedMutationDao(db: AppDatabase): CachedMutationDao = db.cachedMutationDao()
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
@@ -112,18 +107,15 @@ object DatabaseModule {
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideAudioCacheIndexDao(db: AppDatabase): AudioCacheIndexDao =
|
||||
db.audioCacheIndexDao()
|
||||
fun provideAudioCacheIndexDao(db: AppDatabase): AudioCacheIndexDao = db.audioCacheIndexDao()
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideDiagnosticEventDao(db: AppDatabase): DiagnosticEventDao =
|
||||
db.diagnosticEventDao()
|
||||
fun provideDiagnosticEventDao(db: AppDatabase): DiagnosticEventDao = db.diagnosticEventDao()
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideCachedNotificationDao(db: AppDatabase): CachedNotificationDao =
|
||||
db.cachedNotificationDao()
|
||||
fun provideCachedNotificationDao(db: AppDatabase): CachedNotificationDao = db.cachedNotificationDao()
|
||||
|
||||
private const val DATABASE_NAME = "minstrel.db"
|
||||
}
|
||||
|
||||
+2
-4
@@ -21,11 +21,9 @@ enum class CacheSource { MANUAL, AUTO_LIKED, AUTO_PLAYLIST, AUTO_PREFETCH, INCID
|
||||
class MinstrelTypeConverters {
|
||||
@TypeConverter fun instantToLong(i: Instant?): Long? = i?.toEpochMilliseconds()
|
||||
|
||||
@TypeConverter fun longToInstant(l: Long?): Instant? =
|
||||
l?.let { Instant.fromEpochMilliseconds(it) }
|
||||
@TypeConverter fun longToInstant(l: Long?): Instant? = l?.let { Instant.fromEpochMilliseconds(it) }
|
||||
|
||||
@TypeConverter fun sourceToName(s: CacheSource?): String? = s?.name
|
||||
|
||||
@TypeConverter fun nameToSource(n: String?): CacheSource? =
|
||||
n?.let { CacheSource.valueOf(it) }
|
||||
@TypeConverter fun nameToSource(n: String?): CacheSource? = n?.let { CacheSource.valueOf(it) }
|
||||
}
|
||||
|
||||
+4
-1
@@ -37,7 +37,10 @@ interface AudioCacheIndexDao {
|
||||
@Query(
|
||||
"UPDATE audio_cache_index SET lastPlayedAt = :at WHERE trackId = :trackId",
|
||||
)
|
||||
suspend fun touchLastPlayed(trackId: String, at: kotlinx.datetime.Instant)
|
||||
suspend fun touchLastPlayed(
|
||||
trackId: String,
|
||||
at: kotlinx.datetime.Instant,
|
||||
)
|
||||
|
||||
@Query("DELETE FROM audio_cache_index WHERE trackId = :trackId")
|
||||
suspend fun deleteByTrackId(trackId: String)
|
||||
|
||||
+8
-2
@@ -30,10 +30,16 @@ interface CachedAlbumDao {
|
||||
"ORDER BY sortTitle COLLATE NOCASE ASC " +
|
||||
"LIMIT :limit",
|
||||
)
|
||||
suspend fun searchByTitle(q: String, limit: Int): List<CachedAlbumEntity>
|
||||
suspend fun searchByTitle(
|
||||
q: String,
|
||||
limit: Int,
|
||||
): List<CachedAlbumEntity>
|
||||
|
||||
@Query("SELECT id FROM cached_albums WHERE fetchedAt < :before LIMIT :limit")
|
||||
suspend fun idsStaleBefore(before: Long, limit: Int): List<String>
|
||||
suspend fun idsStaleBefore(
|
||||
before: Long,
|
||||
limit: Int,
|
||||
): List<String>
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun upsertAll(rows: List<CachedAlbumEntity>)
|
||||
|
||||
+8
-2
@@ -24,10 +24,16 @@ interface CachedArtistDao {
|
||||
"ORDER BY sortName COLLATE NOCASE ASC " +
|
||||
"LIMIT :limit",
|
||||
)
|
||||
suspend fun searchByName(q: String, limit: Int): List<CachedArtistEntity>
|
||||
suspend fun searchByName(
|
||||
q: String,
|
||||
limit: Int,
|
||||
): List<CachedArtistEntity>
|
||||
|
||||
@Query("SELECT id FROM cached_artists WHERE fetchedAt < :before LIMIT :limit")
|
||||
suspend fun idsStaleBefore(before: Long, limit: Int): List<String>
|
||||
suspend fun idsStaleBefore(
|
||||
before: Long,
|
||||
limit: Int,
|
||||
): List<String>
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun upsertAll(rows: List<CachedArtistEntity>)
|
||||
|
||||
+4
-1
@@ -44,7 +44,10 @@ interface CachedHomeIndexDao {
|
||||
* sequence rather than as a single content swap.
|
||||
*/
|
||||
@Transaction
|
||||
suspend fun replaceSections(sections: List<String>, rows: List<CachedHomeIndexEntity>) {
|
||||
suspend fun replaceSections(
|
||||
sections: List<String>,
|
||||
rows: List<CachedHomeIndexEntity>,
|
||||
) {
|
||||
deleteSections(sections)
|
||||
if (rows.isNotEmpty()) upsertAll(rows)
|
||||
}
|
||||
|
||||
+18
-4
@@ -25,13 +25,20 @@ interface CachedLikeDao {
|
||||
"SELECT entityId FROM cached_likes " +
|
||||
"WHERE userId = :userId AND entityType = :entityType",
|
||||
)
|
||||
fun observeLikedIdsOfType(userId: String, entityType: String): Flow<List<String>>
|
||||
fun observeLikedIdsOfType(
|
||||
userId: String,
|
||||
entityType: String,
|
||||
): Flow<List<String>>
|
||||
|
||||
@Query(
|
||||
"SELECT EXISTS(SELECT 1 FROM cached_likes " +
|
||||
"WHERE userId = :userId AND entityType = :entityType AND entityId = :entityId)",
|
||||
)
|
||||
fun observeIsLiked(userId: String, entityType: String, entityId: String): Flow<Boolean>
|
||||
fun observeIsLiked(
|
||||
userId: String,
|
||||
entityType: String,
|
||||
entityId: String,
|
||||
): Flow<Boolean>
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun upsertAll(rows: List<CachedLikeEntity>)
|
||||
@@ -40,7 +47,11 @@ interface CachedLikeDao {
|
||||
"DELETE FROM cached_likes " +
|
||||
"WHERE userId = :userId AND entityType = :entityType AND entityId = :entityId",
|
||||
)
|
||||
suspend fun delete(userId: String, entityType: String, entityId: String)
|
||||
suspend fun delete(
|
||||
userId: String,
|
||||
entityType: String,
|
||||
entityId: String,
|
||||
)
|
||||
|
||||
@Query("DELETE FROM cached_likes WHERE userId = :userId")
|
||||
suspend fun clearForUser(userId: String)
|
||||
@@ -53,7 +64,10 @@ interface CachedLikeDao {
|
||||
* stale Liked tab entry forever.
|
||||
*/
|
||||
@Transaction
|
||||
suspend fun replaceAllForUser(userId: String, rows: List<CachedLikeEntity>) {
|
||||
suspend fun replaceAllForUser(
|
||||
userId: String,
|
||||
rows: List<CachedLikeEntity>,
|
||||
) {
|
||||
clearForUser(userId)
|
||||
upsertAll(rows)
|
||||
}
|
||||
|
||||
+4
-1
@@ -24,7 +24,10 @@ interface CachedMutationDao {
|
||||
"UPDATE cached_mutations SET attempts = attempts + 1, lastAttemptAt = :at " +
|
||||
"WHERE id = :id",
|
||||
)
|
||||
suspend fun recordAttempt(id: Long, at: Instant)
|
||||
suspend fun recordAttempt(
|
||||
id: Long,
|
||||
at: Instant,
|
||||
)
|
||||
|
||||
@Query("DELETE FROM cached_mutations WHERE id = :id")
|
||||
suspend fun delete(id: Long)
|
||||
|
||||
+4
-1
@@ -35,7 +35,10 @@ interface CachedNotificationDao {
|
||||
}
|
||||
|
||||
@Query("UPDATE cached_notifications SET readAt = :at WHERE id = :id AND readAt IS NULL")
|
||||
suspend fun markRead(id: String, at: Instant)
|
||||
suspend fun markRead(
|
||||
id: String,
|
||||
at: Instant,
|
||||
)
|
||||
|
||||
@Query("UPDATE cached_notifications SET readAt = :at WHERE readAt IS NULL")
|
||||
suspend fun markAllRead(at: Instant)
|
||||
|
||||
+4
-1
@@ -55,7 +55,10 @@ interface CachedPlaylistDao {
|
||||
suspend fun deleteAllOwned(userId: String)
|
||||
|
||||
@Query("DELETE FROM cached_playlists WHERE userId = :userId AND id NOT IN (:keepIds)")
|
||||
suspend fun deleteOwnedNotIn(userId: String, keepIds: List<String>)
|
||||
suspend fun deleteOwnedNotIn(
|
||||
userId: String,
|
||||
keepIds: List<String>,
|
||||
)
|
||||
|
||||
/**
|
||||
* Atomically reconciles the cache against the fresh list response.
|
||||
|
||||
+4
-1
@@ -67,5 +67,8 @@ interface CachedPlaylistTrackDao {
|
||||
"DELETE FROM cached_playlist_tracks " +
|
||||
"WHERE playlistId = :playlistId AND trackId IN (:trackIds)",
|
||||
)
|
||||
suspend fun deleteTracksFromPlaylist(playlistId: String, trackIds: List<String>)
|
||||
suspend fun deleteTracksFromPlaylist(
|
||||
playlistId: String,
|
||||
trackIds: List<String>,
|
||||
)
|
||||
}
|
||||
|
||||
+8
-2
@@ -30,10 +30,16 @@ interface CachedTrackDao {
|
||||
"ORDER BY title COLLATE NOCASE ASC " +
|
||||
"LIMIT :limit",
|
||||
)
|
||||
suspend fun searchByTitle(q: String, limit: Int): List<CachedTrackEntity>
|
||||
suspend fun searchByTitle(
|
||||
q: String,
|
||||
limit: Int,
|
||||
): List<CachedTrackEntity>
|
||||
|
||||
@Query("SELECT id FROM cached_tracks WHERE fetchedAt < :before LIMIT :limit")
|
||||
suspend fun idsStaleBefore(before: Long, limit: Int): List<String>
|
||||
suspend fun idsStaleBefore(
|
||||
before: Long,
|
||||
limit: Int,
|
||||
): List<String>
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun upsertAll(rows: List<CachedTrackEntity>)
|
||||
|
||||
+218
-180
@@ -87,206 +87,238 @@ data class LikeTogglePayload(
|
||||
*/
|
||||
@Suppress("TooManyFunctions") // one enqueue per mutation kind, like the replayer's dispatchers
|
||||
@Singleton
|
||||
class MutationQueue @Inject constructor(
|
||||
private val dao: CachedMutationDao,
|
||||
private val json: Json,
|
||||
) {
|
||||
// capacity=1 DROP_OLDEST so a burst of user enqueues (e.g. liking N
|
||||
// tracks while offline) surfaces as one snackbar rather than queueing
|
||||
// N. replay=0 because a hint observed at enqueue time isn't useful
|
||||
// to a screen that mounts later.
|
||||
private val _userEnqueueHints = MutableSharedFlow<String>(
|
||||
replay = 0,
|
||||
extraBufferCapacity = 1,
|
||||
onBufferOverflow = BufferOverflow.DROP_OLDEST,
|
||||
)
|
||||
class MutationQueue
|
||||
@Inject
|
||||
constructor(
|
||||
private val dao: CachedMutationDao,
|
||||
private val json: Json,
|
||||
) {
|
||||
// capacity=1 DROP_OLDEST so a burst of user enqueues (e.g. liking N
|
||||
// tracks while offline) surfaces as one snackbar rather than queueing
|
||||
// N. replay=0 because a hint observed at enqueue time isn't useful
|
||||
// to a screen that mounts later.
|
||||
private val _userEnqueueHints =
|
||||
MutableSharedFlow<String>(
|
||||
replay = 0,
|
||||
extraBufferCapacity = 1,
|
||||
onBufferOverflow = BufferOverflow.DROP_OLDEST,
|
||||
)
|
||||
|
||||
/**
|
||||
* Hint stream consumed by [com.fabledsword.minstrel.shared.widgets.ShellScaffold]
|
||||
* to surface "Saved — will sync when online" as a snackbar whenever a
|
||||
* user-driven write hits the offline-fallback path. Background-only
|
||||
* enqueues (play-events, playback-error reports) do not emit — those
|
||||
* fire from non-foreground paths where a snackbar would be either
|
||||
* dropped (no shell mounted) or jarring (lock-screen toggle).
|
||||
*/
|
||||
val userEnqueueHints: SharedFlow<String> = _userEnqueueHints.asSharedFlow()
|
||||
/**
|
||||
* Hint stream consumed by [com.fabledsword.minstrel.shared.widgets.ShellScaffold]
|
||||
* to surface "Saved — will sync when online" as a snackbar whenever a
|
||||
* user-driven write hits the offline-fallback path. Background-only
|
||||
* enqueues (play-events, playback-error reports) do not emit — those
|
||||
* fire from non-foreground paths where a snackbar would be either
|
||||
* dropped (no shell mounted) or jarring (lock-screen toggle).
|
||||
*/
|
||||
val userEnqueueHints: SharedFlow<String> = _userEnqueueHints.asSharedFlow()
|
||||
|
||||
suspend fun enqueueLikeToggle(
|
||||
entityType: String,
|
||||
entityId: String,
|
||||
desiredState: Boolean,
|
||||
): Long = insertUserDriven(
|
||||
MutationKind.LIKE_TOGGLE,
|
||||
json.encodeToString(
|
||||
LikeTogglePayload.serializer(),
|
||||
LikeTogglePayload(entityType, entityId, desiredState),
|
||||
),
|
||||
)
|
||||
suspend fun enqueueLikeToggle(
|
||||
entityType: String,
|
||||
entityId: String,
|
||||
desiredState: Boolean,
|
||||
): Long =
|
||||
insertUserDriven(
|
||||
MutationKind.LIKE_TOGGLE,
|
||||
json.encodeToString(
|
||||
LikeTogglePayload.serializer(),
|
||||
LikeTogglePayload(entityType, entityId, desiredState),
|
||||
),
|
||||
)
|
||||
|
||||
suspend fun enqueueQuarantineUnflag(trackId: String): Long = insertUserDriven(
|
||||
MutationKind.QUARANTINE_UNFLAG,
|
||||
json.encodeToString(
|
||||
QuarantineUnflagPayload.serializer(),
|
||||
QuarantineUnflagPayload(trackId),
|
||||
),
|
||||
)
|
||||
suspend fun enqueueQuarantineUnflag(trackId: String): Long =
|
||||
insertUserDriven(
|
||||
MutationKind.QUARANTINE_UNFLAG,
|
||||
json.encodeToString(
|
||||
QuarantineUnflagPayload.serializer(),
|
||||
QuarantineUnflagPayload(trackId),
|
||||
),
|
||||
)
|
||||
|
||||
suspend fun enqueuePlaylistAppend(payload: PlaylistAppendPayload): Long = insertUserDriven(
|
||||
MutationKind.PLAYLIST_APPEND,
|
||||
json.encodeToString(PlaylistAppendPayload.serializer(), payload),
|
||||
)
|
||||
suspend fun enqueuePlaylistAppend(payload: PlaylistAppendPayload): Long =
|
||||
insertUserDriven(
|
||||
MutationKind.PLAYLIST_APPEND,
|
||||
json.encodeToString(PlaylistAppendPayload.serializer(), payload),
|
||||
)
|
||||
|
||||
suspend fun enqueuePlaylistCreate(payload: PlaylistCreatePayload): Long = insertUserDriven(
|
||||
MutationKind.PLAYLIST_CREATE,
|
||||
json.encodeToString(PlaylistCreatePayload.serializer(), payload),
|
||||
)
|
||||
suspend fun enqueuePlaylistCreate(payload: PlaylistCreatePayload): Long =
|
||||
insertUserDriven(
|
||||
MutationKind.PLAYLIST_CREATE,
|
||||
json.encodeToString(PlaylistCreatePayload.serializer(), payload),
|
||||
)
|
||||
|
||||
suspend fun enqueuePlaylistUpdate(payload: PlaylistUpdatePayload): Long = insertUserDriven(
|
||||
MutationKind.PLAYLIST_UPDATE,
|
||||
json.encodeToString(PlaylistUpdatePayload.serializer(), payload),
|
||||
)
|
||||
suspend fun enqueuePlaylistUpdate(payload: PlaylistUpdatePayload): Long =
|
||||
insertUserDriven(
|
||||
MutationKind.PLAYLIST_UPDATE,
|
||||
json.encodeToString(PlaylistUpdatePayload.serializer(), payload),
|
||||
)
|
||||
|
||||
suspend fun enqueuePlaylistDelete(playlistId: String): Long = insertUserDriven(
|
||||
MutationKind.PLAYLIST_DELETE,
|
||||
json.encodeToString(PlaylistDeletePayload.serializer(), PlaylistDeletePayload(playlistId)),
|
||||
)
|
||||
suspend fun enqueuePlaylistDelete(playlistId: String): Long =
|
||||
insertUserDriven(
|
||||
MutationKind.PLAYLIST_DELETE,
|
||||
json.encodeToString(PlaylistDeletePayload.serializer(), PlaylistDeletePayload(playlistId)),
|
||||
)
|
||||
|
||||
suspend fun enqueuePlaylistRemoveTrack(payload: PlaylistRemoveTrackPayload): Long = insertUserDriven(
|
||||
MutationKind.PLAYLIST_REMOVE_TRACK,
|
||||
json.encodeToString(PlaylistRemoveTrackPayload.serializer(), payload),
|
||||
)
|
||||
suspend fun enqueuePlaylistRemoveTrack(payload: PlaylistRemoveTrackPayload): Long =
|
||||
insertUserDriven(
|
||||
MutationKind.PLAYLIST_REMOVE_TRACK,
|
||||
json.encodeToString(PlaylistRemoveTrackPayload.serializer(), payload),
|
||||
)
|
||||
|
||||
suspend fun enqueuePlaylistReorder(payload: PlaylistReorderPayload): Long = insertUserDriven(
|
||||
MutationKind.PLAYLIST_REORDER,
|
||||
json.encodeToString(PlaylistReorderPayload.serializer(), payload),
|
||||
)
|
||||
suspend fun enqueuePlaylistReorder(payload: PlaylistReorderPayload): Long =
|
||||
insertUserDriven(
|
||||
MutationKind.PLAYLIST_REORDER,
|
||||
json.encodeToString(PlaylistReorderPayload.serializer(), payload),
|
||||
)
|
||||
|
||||
/**
|
||||
* Ids of playlists made on this device that the server hasn't been
|
||||
* sent yet. A list refresh keeps them, so a playlist made offline
|
||||
* doesn't vanish before its create goes out.
|
||||
*/
|
||||
suspend fun pendingPlaylistCreateIds(): Set<String> = dao.getAll()
|
||||
.asSequence()
|
||||
.filter { it.kind == MutationKind.PLAYLIST_CREATE }
|
||||
.mapNotNull { row ->
|
||||
runCatching { json.decodeFromString(PlaylistCreatePayload.serializer(), row.payload) }
|
||||
.getOrNull()?.id
|
||||
}
|
||||
.toSet()
|
||||
/**
|
||||
* Ids of playlists made on this device that the server hasn't been
|
||||
* sent yet. A list refresh keeps them, so a playlist made offline
|
||||
* doesn't vanish before its create goes out.
|
||||
*/
|
||||
suspend fun pendingPlaylistCreateIds(): Set<String> =
|
||||
dao
|
||||
.getAll()
|
||||
.asSequence()
|
||||
.filter { it.kind == MutationKind.PLAYLIST_CREATE }
|
||||
.mapNotNull { row ->
|
||||
runCatching { json.decodeFromString(PlaylistCreatePayload.serializer(), row.payload) }
|
||||
.getOrNull()
|
||||
?.id
|
||||
}.toSet()
|
||||
|
||||
/**
|
||||
* The like state each still-queued like toggle sets, by
|
||||
* [likeToggleKey], the newest toggle winning. A toggle for an entity
|
||||
* found here must queue behind it rather than go live, or the older
|
||||
* one replays after it and undoes it; and a refresh keeps these states
|
||||
* over the server's, which hasn't seen them yet.
|
||||
*/
|
||||
suspend fun pendingLikeStates(): Map<String, Boolean> = buildMap {
|
||||
dao.getAll().filter { it.kind == MutationKind.LIKE_TOGGLE }.forEach { row ->
|
||||
runCatching { json.decodeFromString(LikeTogglePayload.serializer(), row.payload) }
|
||||
.getOrNull()
|
||||
?.let { put(likeToggleKey(it.entityType, it.entityId), it.desiredState) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether each track with a quarantine flag or unflag still queued ends
|
||||
* up flagged (true) or not, the newest winning. Read for the same two
|
||||
* reasons as [pendingLikeStates].
|
||||
*/
|
||||
suspend fun pendingQuarantineStates(): Map<String, Boolean> = buildMap {
|
||||
dao.getAll().forEach { row ->
|
||||
when (row.kind) {
|
||||
MutationKind.QUARANTINE_FLAG -> runCatching {
|
||||
json.decodeFromString(QuarantineFlagPayload.serializer(), row.payload)
|
||||
}.getOrNull()?.let { put(it.trackId, true) }
|
||||
MutationKind.QUARANTINE_UNFLAG -> runCatching {
|
||||
json.decodeFromString(QuarantineUnflagPayload.serializer(), row.payload)
|
||||
}.getOrNull()?.let { put(it.trackId, false) }
|
||||
/**
|
||||
* The like state each still-queued like toggle sets, by
|
||||
* [likeToggleKey], the newest toggle winning. A toggle for an entity
|
||||
* found here must queue behind it rather than go live, or the older
|
||||
* one replays after it and undoes it; and a refresh keeps these states
|
||||
* over the server's, which hasn't seen them yet.
|
||||
*/
|
||||
suspend fun pendingLikeStates(): Map<String, Boolean> =
|
||||
buildMap {
|
||||
dao.getAll().filter { it.kind == MutationKind.LIKE_TOGGLE }.forEach { row ->
|
||||
runCatching { json.decodeFromString(LikeTogglePayload.serializer(), row.payload) }
|
||||
.getOrNull()
|
||||
?.let { put(likeToggleKey(it.entityType, it.entityId), it.desiredState) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether each track with a quarantine flag or unflag still queued ends
|
||||
* up flagged (true) or not, the newest winning. Read for the same two
|
||||
* reasons as [pendingLikeStates].
|
||||
*/
|
||||
suspend fun pendingQuarantineStates(): Map<String, Boolean> =
|
||||
buildMap {
|
||||
dao.getAll().forEach { row ->
|
||||
when (row.kind) {
|
||||
MutationKind.QUARANTINE_FLAG ->
|
||||
runCatching {
|
||||
json.decodeFromString(QuarantineFlagPayload.serializer(), row.payload)
|
||||
}.getOrNull()?.let { put(it.trackId, true) }
|
||||
MutationKind.QUARANTINE_UNFLAG ->
|
||||
runCatching {
|
||||
json.decodeFromString(QuarantineUnflagPayload.serializer(), row.payload)
|
||||
}.getOrNull()?.let { put(it.trackId, false) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun enqueueQuarantineFlag(
|
||||
trackId: String,
|
||||
reason: String,
|
||||
notes: String,
|
||||
): Long =
|
||||
insertUserDriven(
|
||||
MutationKind.QUARANTINE_FLAG,
|
||||
json.encodeToString(
|
||||
QuarantineFlagPayload.serializer(),
|
||||
QuarantineFlagPayload(trackId, reason, notes),
|
||||
),
|
||||
)
|
||||
|
||||
/** Queues the user's whole normalization preference for replay. */
|
||||
suspend fun enqueueNormalizationSet(prefs: NormalizationPrefs): Long =
|
||||
insertUserDriven(
|
||||
MutationKind.NORMALIZATION_SET,
|
||||
json.encodeToString(NormalizationPrefs.serializer(), prefs),
|
||||
)
|
||||
|
||||
suspend fun enqueueNotificationRead(id: String): Long =
|
||||
insertUserDriven(
|
||||
MutationKind.NOTIFICATION_READ,
|
||||
json.encodeToString(NotificationReadPayload.serializer(), NotificationReadPayload(id)),
|
||||
)
|
||||
|
||||
suspend fun enqueueNotificationsReadAll(upToIso: String?): Long =
|
||||
insertUserDriven(
|
||||
MutationKind.NOTIFICATIONS_READ_ALL,
|
||||
json.encodeToString(
|
||||
NotificationsReadAllPayload.serializer(),
|
||||
NotificationsReadAllPayload(upToIso),
|
||||
),
|
||||
)
|
||||
|
||||
suspend fun enqueueNotificationSettingSet(payload: NotificationSettingPayload): Long =
|
||||
insertUserDriven(
|
||||
MutationKind.NOTIFICATION_SETTING_SET,
|
||||
json.encodeToString(NotificationSettingPayload.serializer(), payload),
|
||||
)
|
||||
|
||||
suspend fun enqueuePlayOffline(payload: PlayOfflinePayload): Long =
|
||||
dao.insert(
|
||||
CachedMutationEntity(
|
||||
kind = MutationKind.PLAY_OFFLINE,
|
||||
payload = json.encodeToString(PlayOfflinePayload.serializer(), payload),
|
||||
),
|
||||
)
|
||||
|
||||
suspend fun enqueuePlaybackErrorReport(payload: PlaybackErrorReportPayload): Long =
|
||||
dao.insert(
|
||||
CachedMutationEntity(
|
||||
kind = MutationKind.PLAYBACK_ERROR_REPORT,
|
||||
payload = json.encodeToString(PlaybackErrorReportPayload.serializer(), payload),
|
||||
),
|
||||
)
|
||||
|
||||
/**
|
||||
* Durable close-by-id for an already-open server play row. Background
|
||||
* path only (no user hint) — same as [enqueuePlayOffline].
|
||||
*/
|
||||
suspend fun enqueuePlayEnded(payload: PlayEndedPayload): Long =
|
||||
dao.insert(
|
||||
CachedMutationEntity(
|
||||
kind = MutationKind.PLAY_ENDED,
|
||||
payload = json.encodeToString(PlayEndedPayload.serializer(), payload),
|
||||
),
|
||||
)
|
||||
|
||||
private suspend fun insertUserDriven(
|
||||
kind: String,
|
||||
payload: String,
|
||||
): Long {
|
||||
val id = dao.insert(CachedMutationEntity(kind = kind, payload = payload))
|
||||
_userEnqueueHints.tryEmit(QUEUED_MESSAGE)
|
||||
return id
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun enqueueQuarantineFlag(
|
||||
trackId: String,
|
||||
reason: String,
|
||||
notes: String,
|
||||
): Long = insertUserDriven(
|
||||
MutationKind.QUARANTINE_FLAG,
|
||||
json.encodeToString(
|
||||
QuarantineFlagPayload.serializer(),
|
||||
QuarantineFlagPayload(trackId, reason, notes),
|
||||
),
|
||||
)
|
||||
|
||||
/** Queues the user's whole normalization preference for replay. */
|
||||
suspend fun enqueueNormalizationSet(prefs: NormalizationPrefs): Long = insertUserDriven(
|
||||
MutationKind.NORMALIZATION_SET,
|
||||
json.encodeToString(NormalizationPrefs.serializer(), prefs),
|
||||
)
|
||||
|
||||
suspend fun enqueueNotificationRead(id: String): Long = insertUserDriven(
|
||||
MutationKind.NOTIFICATION_READ,
|
||||
json.encodeToString(NotificationReadPayload.serializer(), NotificationReadPayload(id)),
|
||||
)
|
||||
|
||||
suspend fun enqueueNotificationsReadAll(upToIso: String?): Long = insertUserDriven(
|
||||
MutationKind.NOTIFICATIONS_READ_ALL,
|
||||
json.encodeToString(
|
||||
NotificationsReadAllPayload.serializer(),
|
||||
NotificationsReadAllPayload(upToIso),
|
||||
),
|
||||
)
|
||||
|
||||
suspend fun enqueueNotificationSettingSet(payload: NotificationSettingPayload): Long =
|
||||
insertUserDriven(
|
||||
MutationKind.NOTIFICATION_SETTING_SET,
|
||||
json.encodeToString(NotificationSettingPayload.serializer(), payload),
|
||||
)
|
||||
|
||||
suspend fun enqueuePlayOffline(payload: PlayOfflinePayload): Long = dao.insert(
|
||||
CachedMutationEntity(
|
||||
kind = MutationKind.PLAY_OFFLINE,
|
||||
payload = json.encodeToString(PlayOfflinePayload.serializer(), payload),
|
||||
),
|
||||
)
|
||||
|
||||
suspend fun enqueuePlaybackErrorReport(payload: PlaybackErrorReportPayload): Long = dao.insert(
|
||||
CachedMutationEntity(
|
||||
kind = MutationKind.PLAYBACK_ERROR_REPORT,
|
||||
payload = json.encodeToString(PlaybackErrorReportPayload.serializer(), payload),
|
||||
),
|
||||
)
|
||||
|
||||
/**
|
||||
* Durable close-by-id for an already-open server play row. Background
|
||||
* path only (no user hint) — same as [enqueuePlayOffline].
|
||||
*/
|
||||
suspend fun enqueuePlayEnded(payload: PlayEndedPayload): Long = dao.insert(
|
||||
CachedMutationEntity(
|
||||
kind = MutationKind.PLAY_ENDED,
|
||||
payload = json.encodeToString(PlayEndedPayload.serializer(), payload),
|
||||
),
|
||||
)
|
||||
|
||||
private suspend fun insertUserDriven(kind: String, payload: String): Long {
|
||||
val id = dao.insert(CachedMutationEntity(kind = kind, payload = payload))
|
||||
_userEnqueueHints.tryEmit(QUEUED_MESSAGE)
|
||||
return id
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Persisted payload for `MutationKind.QUARANTINE_UNFLAG` — the
|
||||
* `DELETE /api/quarantine/{trackId}` call lost during a connectivity
|
||||
* hiccup. The replayer just re-fires the DELETE; idempotent server-side.
|
||||
*/
|
||||
@Serializable
|
||||
data class QuarantineUnflagPayload(val trackId: String)
|
||||
data class QuarantineUnflagPayload(
|
||||
val trackId: String,
|
||||
)
|
||||
|
||||
/** The key [MutationQueue.pendingLikeStates] files a like toggle under. */
|
||||
fun likeToggleKey(entityType: String, entityId: String): String = "$entityType:$entityId"
|
||||
fun likeToggleKey(
|
||||
entityType: String,
|
||||
entityId: String,
|
||||
): String = "$entityType:$entityId"
|
||||
|
||||
/**
|
||||
* Persisted payload for `MutationKind.PLAYLIST_APPEND`: the track IDs to
|
||||
@@ -320,7 +352,9 @@ data class PlaylistUpdatePayload(
|
||||
|
||||
/** Persisted payload for `MutationKind.PLAYLIST_DELETE`. */
|
||||
@Serializable
|
||||
data class PlaylistDeletePayload(val playlistId: String)
|
||||
data class PlaylistDeletePayload(
|
||||
val playlistId: String,
|
||||
)
|
||||
|
||||
/**
|
||||
* Persisted payload for `MutationKind.PLAYLIST_REMOVE_TRACK`. [trackId] is
|
||||
@@ -405,7 +439,9 @@ data class PlaybackErrorReportPayload(
|
||||
|
||||
/** Persisted payload for `MutationKind.NOTIFICATION_READ`. */
|
||||
@Serializable
|
||||
data class NotificationReadPayload(val id: String)
|
||||
data class NotificationReadPayload(
|
||||
val id: String,
|
||||
)
|
||||
|
||||
/**
|
||||
* Persisted payload for `MutationKind.NOTIFICATIONS_READ_ALL`.
|
||||
@@ -413,7 +449,9 @@ data class NotificationReadPayload(val id: String)
|
||||
* when the inbox was empty on the device, which marks everything.
|
||||
*/
|
||||
@Serializable
|
||||
data class NotificationsReadAllPayload(val upToIso: String?)
|
||||
data class NotificationsReadAllPayload(
|
||||
val upToIso: String?,
|
||||
)
|
||||
|
||||
/**
|
||||
* Persisted payload for `MutationKind.NOTIFICATION_SETTING_SET`: one
|
||||
|
||||
+349
-319
@@ -9,24 +9,24 @@ import com.fabledsword.minstrel.api.endpoints.FlagRequest
|
||||
import com.fabledsword.minstrel.api.endpoints.LikesApi
|
||||
import com.fabledsword.minstrel.api.endpoints.MeApi
|
||||
import com.fabledsword.minstrel.api.endpoints.NotificationsApi
|
||||
import com.fabledsword.minstrel.api.endpoints.PutNotificationSettingsBody
|
||||
import com.fabledsword.minstrel.api.endpoints.ReadAllBody
|
||||
import com.fabledsword.minstrel.api.endpoints.PlaybackErrorReportRequest
|
||||
import com.fabledsword.minstrel.api.endpoints.PlaybackErrorsApi
|
||||
import com.fabledsword.minstrel.api.endpoints.PlaylistsApi
|
||||
import com.fabledsword.minstrel.api.endpoints.PutNotificationSettingsBody
|
||||
import com.fabledsword.minstrel.api.endpoints.QuarantineApi
|
||||
import com.fabledsword.minstrel.api.endpoints.ReadAllBody
|
||||
import com.fabledsword.minstrel.api.endpoints.ReorderTracksRequest
|
||||
import com.fabledsword.minstrel.api.endpoints.UpdatePlaylistRequest
|
||||
import com.fabledsword.minstrel.connectivity.NetworkStatusController
|
||||
import com.fabledsword.minstrel.connectivity.ServerHealth
|
||||
import com.fabledsword.minstrel.models.wire.PlayEndedRequest
|
||||
import com.fabledsword.minstrel.models.wire.PlayOfflineRequest
|
||||
import com.fabledsword.minstrel.auth.AuthStore
|
||||
import com.fabledsword.minstrel.cache.account.AccountCache
|
||||
import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao
|
||||
import com.fabledsword.minstrel.cache.db.entities.CachedMutationEntity
|
||||
import com.fabledsword.minstrel.connectivity.NetworkStatusController
|
||||
import com.fabledsword.minstrel.connectivity.ServerHealth
|
||||
import com.fabledsword.minstrel.di.ApplicationScope
|
||||
import com.fabledsword.minstrel.likes.data.LikesRepository
|
||||
import com.fabledsword.minstrel.models.wire.PlayEndedRequest
|
||||
import com.fabledsword.minstrel.models.wire.PlayOfflineRequest
|
||||
import com.fabledsword.minstrel.settings.data.NormalizationPrefs
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
@@ -35,7 +35,6 @@ import kotlinx.coroutines.flow.filterNotNull
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.datetime.Clock
|
||||
import kotlinx.serialization.SerializationException
|
||||
import kotlinx.serialization.json.Json
|
||||
@@ -75,296 +74,311 @@ import javax.inject.Singleton
|
||||
* forever.
|
||||
*/
|
||||
@Singleton
|
||||
class MutationReplayer @Inject constructor(
|
||||
private val dao: CachedMutationDao,
|
||||
private val authStore: AuthStore,
|
||||
private val accountCache: AccountCache,
|
||||
private val json: Json,
|
||||
@ApplicationScope private val scope: CoroutineScope,
|
||||
networkStatus: NetworkStatusController,
|
||||
retrofit: Retrofit,
|
||||
) {
|
||||
private val likesApi: LikesApi = retrofit.create()
|
||||
private val quarantineApi: QuarantineApi = retrofit.create()
|
||||
private val playlistsApi: PlaylistsApi = retrofit.create()
|
||||
private val eventsApi: EventsApi = retrofit.create()
|
||||
private val playbackErrorsApi: PlaybackErrorsApi = retrofit.create()
|
||||
private val meApi: MeApi = retrofit.create()
|
||||
private val notificationsApi: NotificationsApi = retrofit.create()
|
||||
class MutationReplayer
|
||||
@Inject
|
||||
constructor(
|
||||
private val dao: CachedMutationDao,
|
||||
private val authStore: AuthStore,
|
||||
private val accountCache: AccountCache,
|
||||
private val json: Json,
|
||||
@ApplicationScope private val scope: CoroutineScope,
|
||||
networkStatus: NetworkStatusController,
|
||||
retrofit: Retrofit,
|
||||
) {
|
||||
private val likesApi: LikesApi = retrofit.create()
|
||||
private val quarantineApi: QuarantineApi = retrofit.create()
|
||||
private val playlistsApi: PlaylistsApi = retrofit.create()
|
||||
private val eventsApi: EventsApi = retrofit.create()
|
||||
private val playbackErrorsApi: PlaybackErrorsApi = retrofit.create()
|
||||
private val meApi: MeApi = retrofit.create()
|
||||
private val notificationsApi: NotificationsApi = retrofit.create()
|
||||
|
||||
private val mutex = Mutex()
|
||||
private val mutex = Mutex()
|
||||
|
||||
private enum class Outcome { SENT, DROP, RETRY }
|
||||
private enum class Outcome { SENT, DROP, RETRY }
|
||||
|
||||
init {
|
||||
scope.launch {
|
||||
authStore.sessionCookie
|
||||
.filterNotNull()
|
||||
.distinctUntilChanged()
|
||||
.collect { drainSafe() }
|
||||
init {
|
||||
scope.launch {
|
||||
authStore.sessionCookie
|
||||
.filterNotNull()
|
||||
.distinctUntilChanged()
|
||||
.collect { drainSafe() }
|
||||
}
|
||||
scope.launch {
|
||||
accountCache.ownedBySignedInUser
|
||||
.filter { it }
|
||||
.collect { drainSafe() }
|
||||
}
|
||||
// Server-reachable-again: replay queued writes the moment the
|
||||
// health signal recovers, so an offline→online transition mid-
|
||||
// session doesn't wait for the next cold start / re-auth.
|
||||
scope.launch {
|
||||
networkStatus.state
|
||||
.map { it == ServerHealth.Healthy }
|
||||
.distinctUntilChanged()
|
||||
.filter { it }
|
||||
.collect { drainSafe() }
|
||||
}
|
||||
}
|
||||
scope.launch {
|
||||
accountCache.ownedBySignedInUser
|
||||
.filter { it }
|
||||
.collect { drainSafe() }
|
||||
}
|
||||
// Server-reachable-again: replay queued writes the moment the
|
||||
// health signal recovers, so an offline→online transition mid-
|
||||
// session doesn't wait for the next cold start / re-auth.
|
||||
scope.launch {
|
||||
networkStatus.state
|
||||
.map { it == ServerHealth.Healthy }
|
||||
.distinctUntilChanged()
|
||||
.filter { it }
|
||||
.collect { drainSafe() }
|
||||
}
|
||||
}
|
||||
|
||||
/** Public entry-point; coalesces concurrent triggers via a Mutex. */
|
||||
suspend fun drainSafe() {
|
||||
if (!mutex.tryLock()) return
|
||||
try {
|
||||
drain()
|
||||
} finally {
|
||||
mutex.unlock()
|
||||
/** Public entry-point; coalesces concurrent triggers via a Mutex. */
|
||||
suspend fun drainSafe() {
|
||||
if (!mutex.tryLock()) return
|
||||
try {
|
||||
drain()
|
||||
} finally {
|
||||
mutex.unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun drain() {
|
||||
// Another account's writes must not go out under this session.
|
||||
if (!accountCache.ownedBySignedInUser.value) return
|
||||
val rows = dao.getAll()
|
||||
// Collapse superseded toggles (likes, settings): only the latest
|
||||
// desired state per entity is replayed; older toggles for the same
|
||||
// entity are dropped unsent. Without this, partial-failure +
|
||||
// differential retry could replay an older toggle last and invert the
|
||||
// final state — an unlike the user already made would be undone.
|
||||
val superseded = supersededToggleIds(rows, json)
|
||||
// A playlist's changes go out in the order they were made: once one
|
||||
// has to wait, the rest for that list wait behind it, so an add
|
||||
// never reaches the server before the create of its list.
|
||||
val waiting = HashSet<String>()
|
||||
for (row in rows) {
|
||||
replayRow(row, superseded = row.id in superseded, waiting = waiting)
|
||||
private suspend fun drain() {
|
||||
// Another account's writes must not go out under this session.
|
||||
if (!accountCache.ownedBySignedInUser.value) return
|
||||
val rows = dao.getAll()
|
||||
// Collapse superseded toggles (likes, settings): only the latest
|
||||
// desired state per entity is replayed; older toggles for the same
|
||||
// entity are dropped unsent. Without this, partial-failure +
|
||||
// differential retry could replay an older toggle last and invert the
|
||||
// final state — an unlike the user already made would be undone.
|
||||
val superseded = supersededToggleIds(rows, json)
|
||||
// A playlist's changes go out in the order they were made: once one
|
||||
// has to wait, the rest for that list wait behind it, so an add
|
||||
// never reaches the server before the create of its list.
|
||||
val waiting = HashSet<String>()
|
||||
for (row in rows) {
|
||||
replayRow(row, superseded = row.id in superseded, waiting = waiting)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends one row, or drops it when a later row has superseded it, or
|
||||
* leaves it queued when an earlier change to the same playlist is still
|
||||
* waiting. A row that has to retry makes its playlist wait in [waiting].
|
||||
*/
|
||||
private suspend fun replayRow(row: CachedMutationEntity, superseded: Boolean, waiting: MutableSet<String>) {
|
||||
val playlistId = playlistIdOf(row, json)
|
||||
when {
|
||||
superseded -> dao.delete(row.id)
|
||||
playlistId != null && playlistId in waiting -> Unit
|
||||
else -> when (outcomeFor(row)) {
|
||||
Outcome.SENT, Outcome.DROP -> dao.delete(row.id)
|
||||
Outcome.RETRY -> {
|
||||
dao.recordAttempt(row.id, Clock.System.now())
|
||||
playlistId?.let(waiting::add)
|
||||
/**
|
||||
* Sends one row, or drops it when a later row has superseded it, or
|
||||
* leaves it queued when an earlier change to the same playlist is still
|
||||
* waiting. A row that has to retry makes its playlist wait in [waiting].
|
||||
*/
|
||||
private suspend fun replayRow(
|
||||
row: CachedMutationEntity,
|
||||
superseded: Boolean,
|
||||
waiting: MutableSet<String>,
|
||||
) {
|
||||
val playlistId = playlistIdOf(row, json)
|
||||
when {
|
||||
superseded -> dao.delete(row.id)
|
||||
playlistId != null && playlistId in waiting -> Unit
|
||||
else ->
|
||||
when (outcomeFor(row)) {
|
||||
Outcome.SENT, Outcome.DROP -> dao.delete(row.id)
|
||||
Outcome.RETRY -> {
|
||||
dao.recordAttempt(row.id, Clock.System.now())
|
||||
playlistId?.let(waiting::add)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun outcomeFor(row: CachedMutationEntity): Outcome =
|
||||
try {
|
||||
dispatch(row)
|
||||
} catch (e: HttpException) {
|
||||
if (isPermanent(e.code())) Outcome.DROP else Outcome.RETRY
|
||||
} catch (
|
||||
@Suppress("SwallowedException") e: SerializationException,
|
||||
) {
|
||||
// Corrupt / schema-incompatible payload — permanent, drop it.
|
||||
Outcome.DROP
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
|
||||
) {
|
||||
// Transport / unknown — leave queued for the next pass.
|
||||
Outcome.RETRY
|
||||
}
|
||||
|
||||
/** A refusal that a replay would only get again ([isRetryableStatus]'s complement). */
|
||||
private fun isPermanent(code: Int): Boolean = !isRetryableStatus(code)
|
||||
|
||||
/**
|
||||
* Returns the outcome of replaying one row. SENT on a 2xx; DROP for an
|
||||
* unknown kind/variant. Network / HTTP failures THROW and are classified
|
||||
* by [outcomeFor] — dispatchers never swallow them.
|
||||
*/
|
||||
private suspend fun dispatch(row: CachedMutationEntity): Outcome =
|
||||
when (row.kind) {
|
||||
MutationKind.LIKE_TOGGLE -> dispatchLikeToggle(row.payload)
|
||||
MutationKind.QUARANTINE_UNFLAG -> dispatchQuarantineUnflag(row.payload)
|
||||
MutationKind.PLAYLIST_APPEND,
|
||||
MutationKind.PLAYLIST_CREATE,
|
||||
MutationKind.PLAYLIST_UPDATE,
|
||||
MutationKind.PLAYLIST_DELETE,
|
||||
MutationKind.PLAYLIST_REMOVE_TRACK,
|
||||
MutationKind.PLAYLIST_REORDER,
|
||||
-> dispatchPlaylist(row)
|
||||
MutationKind.QUARANTINE_FLAG -> dispatchQuarantineFlag(row.payload)
|
||||
MutationKind.PLAY_OFFLINE -> dispatchPlayOffline(row.payload)
|
||||
MutationKind.PLAY_ENDED -> dispatchPlayEnded(row.payload)
|
||||
MutationKind.PLAYBACK_ERROR_REPORT -> dispatchPlaybackErrorReport(row.payload)
|
||||
MutationKind.NORMALIZATION_SET -> dispatchNormalizationSet(row.payload)
|
||||
MutationKind.NOTIFICATION_READ,
|
||||
MutationKind.NOTIFICATIONS_READ_ALL,
|
||||
MutationKind.NOTIFICATION_SETTING_SET,
|
||||
-> dispatchNotification(row)
|
||||
// Unknown kind — drop so a stale schema entry can't wedge the queue.
|
||||
else -> Outcome.DROP
|
||||
}
|
||||
|
||||
/** The notifications inbox's kinds, split out to keep [dispatch] simple. */
|
||||
private suspend fun dispatchNotification(row: CachedMutationEntity): Outcome =
|
||||
when (row.kind) {
|
||||
MutationKind.NOTIFICATION_READ -> dispatchNotificationRead(row.payload)
|
||||
MutationKind.NOTIFICATIONS_READ_ALL -> dispatchNotificationsReadAll(row.payload)
|
||||
MutationKind.NOTIFICATION_SETTING_SET -> dispatchNotificationSettingSet(row.payload)
|
||||
else -> Outcome.DROP
|
||||
}
|
||||
|
||||
private suspend fun dispatchLikeToggle(payload: String): Outcome {
|
||||
val decoded = json.decodeFromString(LikeTogglePayload.serializer(), payload)
|
||||
val kindPath =
|
||||
when (decoded.entityType) {
|
||||
LikesRepository.ENTITY_ARTIST -> "artists"
|
||||
LikesRepository.ENTITY_ALBUM -> "albums"
|
||||
LikesRepository.ENTITY_TRACK -> "tracks"
|
||||
else -> return Outcome.DROP
|
||||
}
|
||||
if (decoded.desiredState) {
|
||||
likesApi.like(kindPath, decoded.entityId)
|
||||
} else {
|
||||
likesApi.unlike(kindPath, decoded.entityId)
|
||||
}
|
||||
return Outcome.SENT
|
||||
}
|
||||
|
||||
private suspend fun dispatchQuarantineUnflag(payload: String): Outcome {
|
||||
val decoded = json.decodeFromString(QuarantineUnflagPayload.serializer(), payload)
|
||||
quarantineApi.unflag(decoded.trackId)
|
||||
return Outcome.SENT
|
||||
}
|
||||
|
||||
/**
|
||||
* A listener's own playlists, split out to keep [dispatch] simple. A
|
||||
* 404 or 409 is a 4xx, so DROP: the list is gone, or has changed since,
|
||||
* and nothing is left to do.
|
||||
*/
|
||||
private suspend fun dispatchPlaylist(row: CachedMutationEntity): Outcome {
|
||||
val payload = row.payload
|
||||
when (row.kind) {
|
||||
MutationKind.PLAYLIST_APPEND -> {
|
||||
val p = json.decodeFromString(PlaylistAppendPayload.serializer(), payload)
|
||||
playlistsApi.appendTracks(
|
||||
p.playlistId,
|
||||
AppendTracksRequest(trackIds = p.trackIds, requestId = p.requestId),
|
||||
)
|
||||
}
|
||||
MutationKind.PLAYLIST_CREATE -> {
|
||||
val p = json.decodeFromString(PlaylistCreatePayload.serializer(), payload)
|
||||
playlistsApi.create(CreatePlaylistRequest(id = p.id, name = p.name, isPublic = p.isPublic))
|
||||
}
|
||||
MutationKind.PLAYLIST_UPDATE -> {
|
||||
val p = json.decodeFromString(PlaylistUpdatePayload.serializer(), payload)
|
||||
playlistsApi.update(p.playlistId, UpdatePlaylistRequest(name = p.name, isPublic = p.isPublic))
|
||||
}
|
||||
MutationKind.PLAYLIST_DELETE -> {
|
||||
val p = json.decodeFromString(PlaylistDeletePayload.serializer(), payload)
|
||||
playlistsApi.delete(p.playlistId)
|
||||
}
|
||||
MutationKind.PLAYLIST_REMOVE_TRACK -> {
|
||||
val p = json.decodeFromString(PlaylistRemoveTrackPayload.serializer(), payload)
|
||||
playlistsApi.removeTrack(p.playlistId, p.position, p.trackId)
|
||||
}
|
||||
MutationKind.PLAYLIST_REORDER -> {
|
||||
val p = json.decodeFromString(PlaylistReorderPayload.serializer(), payload)
|
||||
playlistsApi.reorder(p.playlistId, ReorderTracksRequest(trackIds = p.trackIds))
|
||||
}
|
||||
else -> return Outcome.DROP
|
||||
}
|
||||
return Outcome.SENT
|
||||
}
|
||||
|
||||
private suspend fun dispatchQuarantineFlag(payload: String): Outcome {
|
||||
val decoded = json.decodeFromString(QuarantineFlagPayload.serializer(), payload)
|
||||
quarantineApi.flag(
|
||||
FlagRequest(
|
||||
trackId = decoded.trackId,
|
||||
reason = decoded.reason,
|
||||
notes = decoded.notes,
|
||||
),
|
||||
)
|
||||
return Outcome.SENT
|
||||
}
|
||||
|
||||
private suspend fun dispatchPlayOffline(payload: String): Outcome {
|
||||
val decoded = json.decodeFromString(PlayOfflinePayload.serializer(), payload)
|
||||
eventsApi.playOffline(
|
||||
PlayOfflineRequest(
|
||||
trackId = decoded.trackId,
|
||||
clientId = decoded.clientId,
|
||||
at = decoded.atIso,
|
||||
durationPlayedMs = decoded.durationPlayedMs,
|
||||
source = decoded.source,
|
||||
deviceClass = decoded.deviceClass,
|
||||
),
|
||||
)
|
||||
return Outcome.SENT
|
||||
}
|
||||
|
||||
private suspend fun dispatchPlayEnded(payload: String): Outcome {
|
||||
val decoded = json.decodeFromString(PlayEndedPayload.serializer(), payload)
|
||||
eventsApi.playEnded(
|
||||
PlayEndedRequest(
|
||||
playEventId = decoded.playEventId,
|
||||
durationPlayedMs = decoded.durationPlayedMs,
|
||||
),
|
||||
)
|
||||
return Outcome.SENT
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends the queued normalization preference. The device already shows
|
||||
* it, so the server's echo is not written back: a change made since the
|
||||
* row was queued would be a newer row, and the collapse keeps only that.
|
||||
*/
|
||||
private suspend fun dispatchNormalizationSet(payload: String): Outcome {
|
||||
meApi.putNormalization(json.decodeFromString(NormalizationPrefs.serializer(), payload))
|
||||
return Outcome.SENT
|
||||
}
|
||||
|
||||
/** A 404 (the notice was trimmed or already gone) is a 4xx, so DROP: nothing left to do. */
|
||||
private suspend fun dispatchNotificationRead(payload: String): Outcome {
|
||||
val decoded = json.decodeFromString(NotificationReadPayload.serializer(), payload)
|
||||
notificationsApi.markRead(decoded.id)
|
||||
return Outcome.SENT
|
||||
}
|
||||
|
||||
private suspend fun dispatchNotificationsReadAll(payload: String): Outcome {
|
||||
val decoded = json.decodeFromString(NotificationsReadAllPayload.serializer(), payload)
|
||||
notificationsApi.readAll(ReadAllBody(upTo = decoded.upToIso))
|
||||
return Outcome.SENT
|
||||
}
|
||||
|
||||
/** An unknown channel can only come from a corrupt row: DROP it. */
|
||||
private suspend fun dispatchNotificationSettingSet(payload: String): Outcome {
|
||||
val decoded = json.decodeFromString(NotificationSettingPayload.serializer(), payload)
|
||||
val change = notificationSettingChange(decoded) ?: return Outcome.DROP
|
||||
notificationsApi.putSettings(PutNotificationSettingsBody(listOf(change)))
|
||||
return Outcome.SENT
|
||||
}
|
||||
|
||||
private suspend fun dispatchPlaybackErrorReport(payload: String): Outcome {
|
||||
val decoded = json.decodeFromString(PlaybackErrorReportPayload.serializer(), payload)
|
||||
playbackErrorsApi.report(
|
||||
PlaybackErrorReportRequest(
|
||||
trackId = decoded.trackId,
|
||||
kind = decoded.kind,
|
||||
detail = decoded.detail,
|
||||
clientId = decoded.clientId,
|
||||
),
|
||||
)
|
||||
return Outcome.SENT
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun outcomeFor(row: CachedMutationEntity): Outcome = try {
|
||||
dispatch(row)
|
||||
} catch (e: HttpException) {
|
||||
if (isPermanent(e.code())) Outcome.DROP else Outcome.RETRY
|
||||
} catch (@Suppress("SwallowedException") e: SerializationException) {
|
||||
// Corrupt / schema-incompatible payload — permanent, drop it.
|
||||
Outcome.DROP
|
||||
} catch (@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable) {
|
||||
// Transport / unknown — leave queued for the next pass.
|
||||
Outcome.RETRY
|
||||
}
|
||||
|
||||
/** A refusal that a replay would only get again ([isRetryableStatus]'s complement). */
|
||||
private fun isPermanent(code: Int): Boolean = !isRetryableStatus(code)
|
||||
|
||||
/**
|
||||
* Returns the outcome of replaying one row. SENT on a 2xx; DROP for an
|
||||
* unknown kind/variant. Network / HTTP failures THROW and are classified
|
||||
* by [outcomeFor] — dispatchers never swallow them.
|
||||
*/
|
||||
private suspend fun dispatch(row: CachedMutationEntity): Outcome = when (row.kind) {
|
||||
MutationKind.LIKE_TOGGLE -> dispatchLikeToggle(row.payload)
|
||||
MutationKind.QUARANTINE_UNFLAG -> dispatchQuarantineUnflag(row.payload)
|
||||
MutationKind.PLAYLIST_APPEND,
|
||||
MutationKind.PLAYLIST_CREATE,
|
||||
MutationKind.PLAYLIST_UPDATE,
|
||||
MutationKind.PLAYLIST_DELETE,
|
||||
MutationKind.PLAYLIST_REMOVE_TRACK,
|
||||
MutationKind.PLAYLIST_REORDER,
|
||||
-> dispatchPlaylist(row)
|
||||
MutationKind.QUARANTINE_FLAG -> dispatchQuarantineFlag(row.payload)
|
||||
MutationKind.PLAY_OFFLINE -> dispatchPlayOffline(row.payload)
|
||||
MutationKind.PLAY_ENDED -> dispatchPlayEnded(row.payload)
|
||||
MutationKind.PLAYBACK_ERROR_REPORT -> dispatchPlaybackErrorReport(row.payload)
|
||||
MutationKind.NORMALIZATION_SET -> dispatchNormalizationSet(row.payload)
|
||||
MutationKind.NOTIFICATION_READ,
|
||||
MutationKind.NOTIFICATIONS_READ_ALL,
|
||||
MutationKind.NOTIFICATION_SETTING_SET,
|
||||
-> dispatchNotification(row)
|
||||
// Unknown kind — drop so a stale schema entry can't wedge the queue.
|
||||
else -> Outcome.DROP
|
||||
}
|
||||
|
||||
/** The notifications inbox's kinds, split out to keep [dispatch] simple. */
|
||||
private suspend fun dispatchNotification(row: CachedMutationEntity): Outcome = when (row.kind) {
|
||||
MutationKind.NOTIFICATION_READ -> dispatchNotificationRead(row.payload)
|
||||
MutationKind.NOTIFICATIONS_READ_ALL -> dispatchNotificationsReadAll(row.payload)
|
||||
MutationKind.NOTIFICATION_SETTING_SET -> dispatchNotificationSettingSet(row.payload)
|
||||
else -> Outcome.DROP
|
||||
}
|
||||
|
||||
private suspend fun dispatchLikeToggle(payload: String): Outcome {
|
||||
val decoded = json.decodeFromString(LikeTogglePayload.serializer(), payload)
|
||||
val kindPath = when (decoded.entityType) {
|
||||
LikesRepository.ENTITY_ARTIST -> "artists"
|
||||
LikesRepository.ENTITY_ALBUM -> "albums"
|
||||
LikesRepository.ENTITY_TRACK -> "tracks"
|
||||
else -> return Outcome.DROP
|
||||
}
|
||||
if (decoded.desiredState) {
|
||||
likesApi.like(kindPath, decoded.entityId)
|
||||
} else {
|
||||
likesApi.unlike(kindPath, decoded.entityId)
|
||||
}
|
||||
return Outcome.SENT
|
||||
}
|
||||
|
||||
private suspend fun dispatchQuarantineUnflag(payload: String): Outcome {
|
||||
val decoded = json.decodeFromString(QuarantineUnflagPayload.serializer(), payload)
|
||||
quarantineApi.unflag(decoded.trackId)
|
||||
return Outcome.SENT
|
||||
}
|
||||
|
||||
/**
|
||||
* A listener's own playlists, split out to keep [dispatch] simple. A
|
||||
* 404 or 409 is a 4xx, so DROP: the list is gone, or has changed since,
|
||||
* and nothing is left to do.
|
||||
*/
|
||||
private suspend fun dispatchPlaylist(row: CachedMutationEntity): Outcome {
|
||||
val payload = row.payload
|
||||
when (row.kind) {
|
||||
MutationKind.PLAYLIST_APPEND -> {
|
||||
val p = json.decodeFromString(PlaylistAppendPayload.serializer(), payload)
|
||||
playlistsApi.appendTracks(
|
||||
p.playlistId,
|
||||
AppendTracksRequest(trackIds = p.trackIds, requestId = p.requestId),
|
||||
)
|
||||
}
|
||||
MutationKind.PLAYLIST_CREATE -> {
|
||||
val p = json.decodeFromString(PlaylistCreatePayload.serializer(), payload)
|
||||
playlistsApi.create(CreatePlaylistRequest(id = p.id, name = p.name, isPublic = p.isPublic))
|
||||
}
|
||||
MutationKind.PLAYLIST_UPDATE -> {
|
||||
val p = json.decodeFromString(PlaylistUpdatePayload.serializer(), payload)
|
||||
playlistsApi.update(p.playlistId, UpdatePlaylistRequest(name = p.name, isPublic = p.isPublic))
|
||||
}
|
||||
MutationKind.PLAYLIST_DELETE -> {
|
||||
val p = json.decodeFromString(PlaylistDeletePayload.serializer(), payload)
|
||||
playlistsApi.delete(p.playlistId)
|
||||
}
|
||||
MutationKind.PLAYLIST_REMOVE_TRACK -> {
|
||||
val p = json.decodeFromString(PlaylistRemoveTrackPayload.serializer(), payload)
|
||||
playlistsApi.removeTrack(p.playlistId, p.position, p.trackId)
|
||||
}
|
||||
MutationKind.PLAYLIST_REORDER -> {
|
||||
val p = json.decodeFromString(PlaylistReorderPayload.serializer(), payload)
|
||||
playlistsApi.reorder(p.playlistId, ReorderTracksRequest(trackIds = p.trackIds))
|
||||
}
|
||||
else -> return Outcome.DROP
|
||||
}
|
||||
return Outcome.SENT
|
||||
}
|
||||
|
||||
private suspend fun dispatchQuarantineFlag(payload: String): Outcome {
|
||||
val decoded = json.decodeFromString(QuarantineFlagPayload.serializer(), payload)
|
||||
quarantineApi.flag(
|
||||
FlagRequest(
|
||||
trackId = decoded.trackId,
|
||||
reason = decoded.reason,
|
||||
notes = decoded.notes,
|
||||
),
|
||||
)
|
||||
return Outcome.SENT
|
||||
}
|
||||
|
||||
private suspend fun dispatchPlayOffline(payload: String): Outcome {
|
||||
val decoded = json.decodeFromString(PlayOfflinePayload.serializer(), payload)
|
||||
eventsApi.playOffline(
|
||||
PlayOfflineRequest(
|
||||
trackId = decoded.trackId,
|
||||
clientId = decoded.clientId,
|
||||
at = decoded.atIso,
|
||||
durationPlayedMs = decoded.durationPlayedMs,
|
||||
source = decoded.source,
|
||||
deviceClass = decoded.deviceClass,
|
||||
),
|
||||
)
|
||||
return Outcome.SENT
|
||||
}
|
||||
|
||||
private suspend fun dispatchPlayEnded(payload: String): Outcome {
|
||||
val decoded = json.decodeFromString(PlayEndedPayload.serializer(), payload)
|
||||
eventsApi.playEnded(
|
||||
PlayEndedRequest(
|
||||
playEventId = decoded.playEventId,
|
||||
durationPlayedMs = decoded.durationPlayedMs,
|
||||
),
|
||||
)
|
||||
return Outcome.SENT
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends the queued normalization preference. The device already shows
|
||||
* it, so the server's echo is not written back: a change made since the
|
||||
* row was queued would be a newer row, and the collapse keeps only that.
|
||||
*/
|
||||
private suspend fun dispatchNormalizationSet(payload: String): Outcome {
|
||||
meApi.putNormalization(json.decodeFromString(NormalizationPrefs.serializer(), payload))
|
||||
return Outcome.SENT
|
||||
}
|
||||
|
||||
/** A 404 (the notice was trimmed or already gone) is a 4xx, so DROP: nothing left to do. */
|
||||
private suspend fun dispatchNotificationRead(payload: String): Outcome {
|
||||
val decoded = json.decodeFromString(NotificationReadPayload.serializer(), payload)
|
||||
notificationsApi.markRead(decoded.id)
|
||||
return Outcome.SENT
|
||||
}
|
||||
|
||||
private suspend fun dispatchNotificationsReadAll(payload: String): Outcome {
|
||||
val decoded = json.decodeFromString(NotificationsReadAllPayload.serializer(), payload)
|
||||
notificationsApi.readAll(ReadAllBody(upTo = decoded.upToIso))
|
||||
return Outcome.SENT
|
||||
}
|
||||
|
||||
/** An unknown channel can only come from a corrupt row: DROP it. */
|
||||
private suspend fun dispatchNotificationSettingSet(payload: String): Outcome {
|
||||
val decoded = json.decodeFromString(NotificationSettingPayload.serializer(), payload)
|
||||
val change = notificationSettingChange(decoded) ?: return Outcome.DROP
|
||||
notificationsApi.putSettings(PutNotificationSettingsBody(listOf(change)))
|
||||
return Outcome.SENT
|
||||
}
|
||||
|
||||
private suspend fun dispatchPlaybackErrorReport(payload: String): Outcome {
|
||||
val decoded = json.decodeFromString(PlaybackErrorReportPayload.serializer(), payload)
|
||||
playbackErrorsApi.report(
|
||||
PlaybackErrorReportRequest(
|
||||
trackId = decoded.trackId,
|
||||
kind = decoded.kind,
|
||||
detail = decoded.detail,
|
||||
clientId = decoded.clientId,
|
||||
),
|
||||
)
|
||||
return Outcome.SENT
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Row ids of desired-state toggles superseded by a later toggle for the same
|
||||
* entity. Applies to every kind whose payload encodes a TARGET state rather
|
||||
@@ -376,10 +390,14 @@ class MutationReplayer @Inject constructor(
|
||||
* instance. [rows] must be ascending by id (FIFO), which is what
|
||||
* `CachedMutationDao.getAll()` returns.
|
||||
*/
|
||||
internal fun supersededToggleIds(rows: List<CachedMutationEntity>, json: Json): Set<Long> {
|
||||
internal fun supersededToggleIds(
|
||||
rows: List<CachedMutationEntity>,
|
||||
json: Json,
|
||||
): Set<Long> {
|
||||
val latestByEntity = HashMap<String, Long>()
|
||||
val superseded = HashSet<Long>()
|
||||
rows.asSequence()
|
||||
rows
|
||||
.asSequence()
|
||||
.mapNotNull { row -> toggleKeyOf(row, json)?.let { key -> key to row.id } }
|
||||
.forEach { (key, id) ->
|
||||
// Ascending ids mean a prior entry for this key is always older.
|
||||
@@ -397,46 +415,58 @@ internal fun supersededToggleIds(rows: List<CachedMutationEntity>, json: Json):
|
||||
* The kind is part of the key so two toggle kinds can never collide on the
|
||||
* 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}" }
|
||||
private fun toggleKeyOf(
|
||||
row: CachedMutationEntity,
|
||||
json: Json,
|
||||
): String? =
|
||||
when (row.kind) {
|
||||
MutationKind.LIKE_TOGGLE ->
|
||||
runCatching {
|
||||
json.decodeFromString(LikeTogglePayload.serializer(), row.payload)
|
||||
}.getOrNull()?.let { "${row.kind}:${it.entityType}:${it.entityId}" }
|
||||
|
||||
MutationKind.NOTIFICATION_SETTING_SET -> runCatching {
|
||||
json.decodeFromString(NotificationSettingPayload.serializer(), row.payload)
|
||||
}.getOrNull()?.let { "${row.kind}:${it.kind}:${it.channel}" }
|
||||
MutationKind.NOTIFICATION_SETTING_SET ->
|
||||
runCatching {
|
||||
json.decodeFromString(NotificationSettingPayload.serializer(), row.payload)
|
||||
}.getOrNull()?.let { "${row.kind}:${it.kind}:${it.channel}" }
|
||||
|
||||
// A reorder is the list's whole new order, so only the last one counts.
|
||||
MutationKind.PLAYLIST_REORDER -> runCatching {
|
||||
json.decodeFromString(PlaylistReorderPayload.serializer(), row.payload)
|
||||
}.getOrNull()?.let { "${row.kind}:${it.playlistId}" }
|
||||
// A reorder is the list's whole new order, so only the last one counts.
|
||||
MutationKind.PLAYLIST_REORDER ->
|
||||
runCatching {
|
||||
json.decodeFromString(PlaylistReorderPayload.serializer(), row.payload)
|
||||
}.getOrNull()?.let { "${row.kind}:${it.playlistId}" }
|
||||
|
||||
// One preference per user, so every normalization row shares one key.
|
||||
MutationKind.NORMALIZATION_SET -> runCatching {
|
||||
json.decodeFromString(NormalizationPrefs.serializer(), row.payload)
|
||||
}.getOrNull()?.let { row.kind }
|
||||
// One preference per user, so every normalization row shares one key.
|
||||
MutationKind.NORMALIZATION_SET ->
|
||||
runCatching {
|
||||
json.decodeFromString(NormalizationPrefs.serializer(), row.payload)
|
||||
}.getOrNull()?.let { row.kind }
|
||||
|
||||
else -> null
|
||||
}
|
||||
else -> null
|
||||
}
|
||||
|
||||
/**
|
||||
* The playlist a queued row changes, or null for a row that isn't a
|
||||
* playlist change (or won't decode, which its dispatcher then DROPs).
|
||||
*/
|
||||
internal fun playlistIdOf(row: CachedMutationEntity, json: Json): String? = runCatching {
|
||||
when (row.kind) {
|
||||
MutationKind.PLAYLIST_APPEND ->
|
||||
json.decodeFromString(PlaylistAppendPayload.serializer(), row.payload).playlistId
|
||||
MutationKind.PLAYLIST_CREATE ->
|
||||
json.decodeFromString(PlaylistCreatePayload.serializer(), row.payload).id
|
||||
MutationKind.PLAYLIST_UPDATE ->
|
||||
json.decodeFromString(PlaylistUpdatePayload.serializer(), row.payload).playlistId
|
||||
MutationKind.PLAYLIST_DELETE ->
|
||||
json.decodeFromString(PlaylistDeletePayload.serializer(), row.payload).playlistId
|
||||
MutationKind.PLAYLIST_REMOVE_TRACK ->
|
||||
json.decodeFromString(PlaylistRemoveTrackPayload.serializer(), row.payload).playlistId
|
||||
MutationKind.PLAYLIST_REORDER ->
|
||||
json.decodeFromString(PlaylistReorderPayload.serializer(), row.payload).playlistId
|
||||
else -> null
|
||||
}
|
||||
}.getOrNull()
|
||||
internal fun playlistIdOf(
|
||||
row: CachedMutationEntity,
|
||||
json: Json,
|
||||
): String? =
|
||||
runCatching {
|
||||
when (row.kind) {
|
||||
MutationKind.PLAYLIST_APPEND ->
|
||||
json.decodeFromString(PlaylistAppendPayload.serializer(), row.payload).playlistId
|
||||
MutationKind.PLAYLIST_CREATE ->
|
||||
json.decodeFromString(PlaylistCreatePayload.serializer(), row.payload).id
|
||||
MutationKind.PLAYLIST_UPDATE ->
|
||||
json.decodeFromString(PlaylistUpdatePayload.serializer(), row.payload).playlistId
|
||||
MutationKind.PLAYLIST_DELETE ->
|
||||
json.decodeFromString(PlaylistDeletePayload.serializer(), row.payload).playlistId
|
||||
MutationKind.PLAYLIST_REMOVE_TRACK ->
|
||||
json.decodeFromString(PlaylistRemoveTrackPayload.serializer(), row.payload).playlistId
|
||||
MutationKind.PLAYLIST_REORDER ->
|
||||
json.decodeFromString(PlaylistReorderPayload.serializer(), row.payload).playlistId
|
||||
else -> null
|
||||
}
|
||||
}.getOrNull()
|
||||
|
||||
Vendored
+7
-5
@@ -13,8 +13,10 @@ import javax.inject.Inject
|
||||
* accessor. Mirrors PlaybackErrorViewModel.
|
||||
*/
|
||||
@HiltViewModel
|
||||
class OfflineWriteHintViewModel @Inject constructor(
|
||||
mutationQueue: MutationQueue,
|
||||
) : ViewModel() {
|
||||
val messages: Flow<String> = mutationQueue.userEnqueueHints
|
||||
}
|
||||
class OfflineWriteHintViewModel
|
||||
@Inject
|
||||
constructor(
|
||||
mutationQueue: MutationQueue,
|
||||
) : ViewModel() {
|
||||
val messages: Flow<String> = mutationQueue.userEnqueueHints
|
||||
}
|
||||
|
||||
+191
-186
@@ -3,8 +3,6 @@ package com.fabledsword.minstrel.cache.sync
|
||||
import com.fabledsword.minstrel.api.ErrorCopy
|
||||
import com.fabledsword.minstrel.api.endpoints.SyncApi
|
||||
import com.fabledsword.minstrel.auth.AuthStore
|
||||
import com.fabledsword.minstrel.connectivity.NetworkStatusController
|
||||
import com.fabledsword.minstrel.connectivity.ServerHealth
|
||||
import com.fabledsword.minstrel.cache.db.dao.CachedAlbumDao
|
||||
import com.fabledsword.minstrel.cache.db.dao.CachedArtistDao
|
||||
import com.fabledsword.minstrel.cache.db.dao.CachedTrackDao
|
||||
@@ -13,6 +11,8 @@ import com.fabledsword.minstrel.cache.db.entities.CachedAlbumEntity
|
||||
import com.fabledsword.minstrel.cache.db.entities.CachedArtistEntity
|
||||
import com.fabledsword.minstrel.cache.db.entities.CachedTrackEntity
|
||||
import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity
|
||||
import com.fabledsword.minstrel.connectivity.NetworkStatusController
|
||||
import com.fabledsword.minstrel.connectivity.ServerHealth
|
||||
import com.fabledsword.minstrel.di.ApplicationScope
|
||||
import com.fabledsword.minstrel.models.wire.SyncAlbumWire
|
||||
import com.fabledsword.minstrel.models.wire.SyncArtistWire
|
||||
@@ -50,199 +50,204 @@ import javax.inject.Singleton
|
||||
* cursor to 0 and pulls the full entity set again (see [resetCursor]).
|
||||
*/
|
||||
@Singleton
|
||||
class SyncController @Inject constructor(
|
||||
private val syncMetadataDao: SyncMetadataDao,
|
||||
private val artistDao: CachedArtistDao,
|
||||
private val albumDao: CachedAlbumDao,
|
||||
private val trackDao: CachedTrackDao,
|
||||
private val authStore: AuthStore,
|
||||
@ApplicationScope private val scope: CoroutineScope,
|
||||
networkStatus: NetworkStatusController,
|
||||
retrofit: Retrofit,
|
||||
) {
|
||||
private val api: SyncApi = retrofit.create()
|
||||
|
||||
// Single in-flight guard: the cookie + health-recovery triggers (and a
|
||||
// pull-to-refresh) can fire concurrently; coalesce them into one pass.
|
||||
private val mutex = Mutex()
|
||||
|
||||
private val lastSyncErrorInternal = MutableStateFlow<String?>(null)
|
||||
|
||||
/**
|
||||
* Human copy for the most recent sync failure; null after any clean
|
||||
* pass. Lets the Library screen distinguish "empty because the first
|
||||
* sync failed" (show error + retry) from "genuinely empty library"
|
||||
* (show welcome copy) — a failed sync over a populated cache stays
|
||||
* silent, since the cached content is still the better surface.
|
||||
*/
|
||||
val lastSyncError: StateFlow<String?> = lastSyncErrorInternal.asStateFlow()
|
||||
|
||||
init {
|
||||
scope.launch {
|
||||
authStore.sessionCookie
|
||||
.filterNotNull()
|
||||
.distinctUntilChanged()
|
||||
.collect { syncSafe() }
|
||||
}
|
||||
// Re-sync when the server becomes reachable again mid-session, so a
|
||||
// delta missed while offline lands without waiting for a cold start.
|
||||
scope.launch {
|
||||
networkStatus.state
|
||||
.map { it == ServerHealth.Healthy }
|
||||
.distinctUntilChanged()
|
||||
.filter { it }
|
||||
.collect { syncSafe() }
|
||||
}
|
||||
}
|
||||
|
||||
/** Public entry-point for "Sync now" affordances. Swallows errors into [lastSyncError]. */
|
||||
suspend fun syncSafe() {
|
||||
if (!mutex.tryLock()) return
|
||||
try {
|
||||
runCatching { sync() }
|
||||
.onSuccess { lastSyncErrorInternal.value = null }
|
||||
.onFailure { lastSyncErrorInternal.value = ErrorCopy.fromThrowable(it) }
|
||||
} finally {
|
||||
mutex.unlock()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pulls pages until the server has nothing newer. The server returns
|
||||
* at most 1000 changes a call, and a full library re-read adds tens
|
||||
* of thousands, so one page per trigger would leave the cache behind:
|
||||
* merge deletes would never arrive and the freshness sweep would keep
|
||||
* asking for tracks that are gone. The cursor is stored after each
|
||||
* page, so an interrupted pass resumes where it stopped.
|
||||
*/
|
||||
private suspend fun sync() {
|
||||
repeat(MAX_PAGES_PER_PASS) {
|
||||
if (!syncPage()) return
|
||||
}
|
||||
}
|
||||
|
||||
/** One page of the change log. True when the server may hold more. */
|
||||
private suspend fun syncPage(): Boolean {
|
||||
val meta = syncMetadataDao.get()
|
||||
val cursor = meta?.cursor ?: 0L
|
||||
val response = api.sync(cursor)
|
||||
return when (response.code()) {
|
||||
HTTP_NO_CONTENT -> {
|
||||
touchLastSyncAt(cursor)
|
||||
false
|
||||
}
|
||||
HTTP_GONE -> {
|
||||
resetCursor()
|
||||
true
|
||||
}
|
||||
HTTP_OK -> {
|
||||
val body = response.body() ?: return false
|
||||
applyDeltas(body.upserts.artist, body.upserts.album, body.upserts.track)
|
||||
applyDeletes(body.deletes.artist, body.deletes.album, body.deletes.track)
|
||||
syncMetadataDao.upsert(
|
||||
SyncMetadataEntity(
|
||||
id = 0,
|
||||
cursor = body.cursor,
|
||||
lastSyncAt = Clock.System.now(),
|
||||
),
|
||||
)
|
||||
// A cursor that did not advance would ask for the same page
|
||||
// again; stop rather than spin.
|
||||
body.cursor > cursor
|
||||
}
|
||||
else -> {
|
||||
// Unhandled status — treat as a no-op; the next
|
||||
// app start retries from the same cursor.
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun applyDeltas(
|
||||
artists: List<SyncArtistWire>,
|
||||
albums: List<SyncAlbumWire>,
|
||||
tracks: List<SyncTrackWire>,
|
||||
class SyncController
|
||||
@Inject
|
||||
constructor(
|
||||
private val syncMetadataDao: SyncMetadataDao,
|
||||
private val artistDao: CachedArtistDao,
|
||||
private val albumDao: CachedAlbumDao,
|
||||
private val trackDao: CachedTrackDao,
|
||||
private val authStore: AuthStore,
|
||||
@ApplicationScope private val scope: CoroutineScope,
|
||||
networkStatus: NetworkStatusController,
|
||||
retrofit: Retrofit,
|
||||
) {
|
||||
if (artists.isNotEmpty()) artistDao.upsertAll(artists.map { it.toEntity() })
|
||||
if (albums.isNotEmpty()) albumDao.upsertAll(albums.map { it.toEntity() })
|
||||
if (tracks.isNotEmpty()) trackDao.upsertAll(tracks.map { it.toEntity() })
|
||||
}
|
||||
private val api: SyncApi = retrofit.create()
|
||||
|
||||
private suspend fun applyDeletes(
|
||||
artistIds: List<String>,
|
||||
albumIds: List<String>,
|
||||
trackIds: List<String>,
|
||||
) {
|
||||
if (artistIds.isNotEmpty()) artistDao.deleteByIds(artistIds)
|
||||
if (albumIds.isNotEmpty()) albumDao.deleteByIds(albumIds)
|
||||
if (trackIds.isNotEmpty()) trackDao.deleteByIds(trackIds)
|
||||
}
|
||||
// Single in-flight guard: the cookie + health-recovery triggers (and a
|
||||
// pull-to-refresh) can fire concurrently; coalesce them into one pass.
|
||||
private val mutex = Mutex()
|
||||
|
||||
private suspend fun touchLastSyncAt(cursor: Long) {
|
||||
syncMetadataDao.upsert(
|
||||
SyncMetadataEntity(id = 0, cursor = cursor, lastSyncAt = Clock.System.now()),
|
||||
)
|
||||
}
|
||||
private val lastSyncErrorInternal = MutableStateFlow<String?>(null)
|
||||
|
||||
private suspend fun resetCursor() {
|
||||
// The Library DAOs only expose deleteByIds; for the rare 410
|
||||
// path the next page is requested with cursor=0 after
|
||||
// resetting our cursor. The following pages carry the full
|
||||
// entity set, which upsertAll overwrites the existing rows
|
||||
// with — old rows for entities the server no longer knows
|
||||
// about linger until MetadataProvider's refresh meets their
|
||||
// 404 and drops them.
|
||||
syncMetadataDao.upsert(
|
||||
SyncMetadataEntity(id = 0, cursor = 0, lastSyncAt = null),
|
||||
)
|
||||
}
|
||||
/**
|
||||
* Human copy for the most recent sync failure; null after any clean
|
||||
* pass. Lets the Library screen distinguish "empty because the first
|
||||
* sync failed" (show error + retry) from "genuinely empty library"
|
||||
* (show welcome copy) — a failed sync over a populated cache stays
|
||||
* silent, since the cached content is still the better surface.
|
||||
*/
|
||||
val lastSyncError: StateFlow<String?> = lastSyncErrorInternal.asStateFlow()
|
||||
|
||||
private companion object {
|
||||
const val HTTP_OK = 200
|
||||
const val HTTP_NO_CONTENT = 204
|
||||
const val HTTP_GONE = 410
|
||||
init {
|
||||
scope.launch {
|
||||
authStore.sessionCookie
|
||||
.filterNotNull()
|
||||
.distinctUntilChanged()
|
||||
.collect { syncSafe() }
|
||||
}
|
||||
// Re-sync when the server becomes reachable again mid-session, so a
|
||||
// delta missed while offline lands without waiting for a cold start.
|
||||
scope.launch {
|
||||
networkStatus.state
|
||||
.map { it == ServerHealth.Healthy }
|
||||
.distinctUntilChanged()
|
||||
.filter { it }
|
||||
.collect { syncSafe() }
|
||||
}
|
||||
}
|
||||
|
||||
// A guard, not a budget: 1000 pages is a million changes, far past
|
||||
// anything a library writes between two app starts.
|
||||
const val MAX_PAGES_PER_PASS = 1000
|
||||
/** Public entry-point for "Sync now" affordances. Swallows errors into [lastSyncError]. */
|
||||
suspend fun syncSafe() {
|
||||
if (!mutex.tryLock()) return
|
||||
try {
|
||||
runCatching { sync() }
|
||||
.onSuccess { lastSyncErrorInternal.value = null }
|
||||
.onFailure { lastSyncErrorInternal.value = ErrorCopy.fromThrowable(it) }
|
||||
} finally {
|
||||
mutex.unlock()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pulls pages until the server has nothing newer. The server returns
|
||||
* at most 1000 changes a call, and a full library re-read adds tens
|
||||
* of thousands, so one page per trigger would leave the cache behind:
|
||||
* merge deletes would never arrive and the freshness sweep would keep
|
||||
* asking for tracks that are gone. The cursor is stored after each
|
||||
* page, so an interrupted pass resumes where it stopped.
|
||||
*/
|
||||
private suspend fun sync() {
|
||||
repeat(MAX_PAGES_PER_PASS) {
|
||||
if (!syncPage()) return
|
||||
}
|
||||
}
|
||||
|
||||
/** One page of the change log. True when the server may hold more. */
|
||||
private suspend fun syncPage(): Boolean {
|
||||
val meta = syncMetadataDao.get()
|
||||
val cursor = meta?.cursor ?: 0L
|
||||
val response = api.sync(cursor)
|
||||
return when (response.code()) {
|
||||
HTTP_NO_CONTENT -> {
|
||||
touchLastSyncAt(cursor)
|
||||
false
|
||||
}
|
||||
HTTP_GONE -> {
|
||||
resetCursor()
|
||||
true
|
||||
}
|
||||
HTTP_OK -> {
|
||||
val body = response.body() ?: return false
|
||||
applyDeltas(body.upserts.artist, body.upserts.album, body.upserts.track)
|
||||
applyDeletes(body.deletes.artist, body.deletes.album, body.deletes.track)
|
||||
syncMetadataDao.upsert(
|
||||
SyncMetadataEntity(
|
||||
id = 0,
|
||||
cursor = body.cursor,
|
||||
lastSyncAt = Clock.System.now(),
|
||||
),
|
||||
)
|
||||
// A cursor that did not advance would ask for the same page
|
||||
// again; stop rather than spin.
|
||||
body.cursor > cursor
|
||||
}
|
||||
else -> {
|
||||
// Unhandled status — treat as a no-op; the next
|
||||
// app start retries from the same cursor.
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun applyDeltas(
|
||||
artists: List<SyncArtistWire>,
|
||||
albums: List<SyncAlbumWire>,
|
||||
tracks: List<SyncTrackWire>,
|
||||
) {
|
||||
if (artists.isNotEmpty()) artistDao.upsertAll(artists.map { it.toEntity() })
|
||||
if (albums.isNotEmpty()) albumDao.upsertAll(albums.map { it.toEntity() })
|
||||
if (tracks.isNotEmpty()) trackDao.upsertAll(tracks.map { it.toEntity() })
|
||||
}
|
||||
|
||||
private suspend fun applyDeletes(
|
||||
artistIds: List<String>,
|
||||
albumIds: List<String>,
|
||||
trackIds: List<String>,
|
||||
) {
|
||||
if (artistIds.isNotEmpty()) artistDao.deleteByIds(artistIds)
|
||||
if (albumIds.isNotEmpty()) albumDao.deleteByIds(albumIds)
|
||||
if (trackIds.isNotEmpty()) trackDao.deleteByIds(trackIds)
|
||||
}
|
||||
|
||||
private suspend fun touchLastSyncAt(cursor: Long) {
|
||||
syncMetadataDao.upsert(
|
||||
SyncMetadataEntity(id = 0, cursor = cursor, lastSyncAt = Clock.System.now()),
|
||||
)
|
||||
}
|
||||
|
||||
private suspend fun resetCursor() {
|
||||
// The Library DAOs only expose deleteByIds; for the rare 410
|
||||
// path the next page is requested with cursor=0 after
|
||||
// resetting our cursor. The following pages carry the full
|
||||
// entity set, which upsertAll overwrites the existing rows
|
||||
// with — old rows for entities the server no longer knows
|
||||
// about linger until MetadataProvider's refresh meets their
|
||||
// 404 and drops them.
|
||||
syncMetadataDao.upsert(
|
||||
SyncMetadataEntity(id = 0, cursor = 0, lastSyncAt = null),
|
||||
)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val HTTP_OK = 200
|
||||
const val HTTP_NO_CONTENT = 204
|
||||
const val HTTP_GONE = 410
|
||||
|
||||
// A guard, not a budget: 1000 pages is a million changes, far past
|
||||
// anything a library writes between two app starts.
|
||||
const val MAX_PAGES_PER_PASS = 1000
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Mappers (file-internal — sync wire types stay out of UI) ──
|
||||
|
||||
private fun SyncArtistWire.toEntity(): CachedArtistEntity = CachedArtistEntity(
|
||||
id = id,
|
||||
name = name,
|
||||
sortName = sortName,
|
||||
mbid = mbid,
|
||||
artistThumbPath = artistThumbPath,
|
||||
artistFanartPath = artistFanartPath,
|
||||
)
|
||||
private fun SyncArtistWire.toEntity(): CachedArtistEntity =
|
||||
CachedArtistEntity(
|
||||
id = id,
|
||||
name = name,
|
||||
sortName = sortName,
|
||||
mbid = mbid,
|
||||
artistThumbPath = artistThumbPath,
|
||||
artistFanartPath = artistFanartPath,
|
||||
)
|
||||
|
||||
private fun SyncAlbumWire.toEntity(): CachedAlbumEntity = CachedAlbumEntity(
|
||||
id = id,
|
||||
artistId = artistId,
|
||||
title = title,
|
||||
sortTitle = sortTitle,
|
||||
releaseDate = releaseDate,
|
||||
coverPath = coverArtPath,
|
||||
mbid = mbid,
|
||||
albumGain = albumGain,
|
||||
albumPeak = albumPeak,
|
||||
)
|
||||
private fun SyncAlbumWire.toEntity(): CachedAlbumEntity =
|
||||
CachedAlbumEntity(
|
||||
id = id,
|
||||
artistId = artistId,
|
||||
title = title,
|
||||
sortTitle = sortTitle,
|
||||
releaseDate = releaseDate,
|
||||
coverPath = coverArtPath,
|
||||
mbid = mbid,
|
||||
albumGain = albumGain,
|
||||
albumPeak = albumPeak,
|
||||
)
|
||||
|
||||
private fun SyncTrackWire.toEntity(): CachedTrackEntity = CachedTrackEntity(
|
||||
id = id,
|
||||
albumId = albumId,
|
||||
artistId = artistId,
|
||||
title = title,
|
||||
durationMs = durationMs,
|
||||
trackNumber = trackNumber,
|
||||
discNumber = discNumber,
|
||||
filePath = filePath,
|
||||
fileFormat = fileFormat,
|
||||
genre = genre,
|
||||
missing = missing,
|
||||
trackGain = trackGain,
|
||||
trackPeak = trackPeak,
|
||||
)
|
||||
private fun SyncTrackWire.toEntity(): CachedTrackEntity =
|
||||
CachedTrackEntity(
|
||||
id = id,
|
||||
albumId = albumId,
|
||||
artistId = artistId,
|
||||
title = title,
|
||||
durationMs = durationMs,
|
||||
trackNumber = trackNumber,
|
||||
discNumber = discNumber,
|
||||
filePath = filePath,
|
||||
fileFormat = fileFormat,
|
||||
genre = genre,
|
||||
missing = missing,
|
||||
trackGain = trackGain,
|
||||
trackPeak = trackPeak,
|
||||
)
|
||||
|
||||
+78
-67
@@ -36,76 +36,87 @@ import javax.inject.Singleton
|
||||
* repositories can also collect this to gate retry loops.
|
||||
*/
|
||||
@Singleton
|
||||
class ConnectivityObserver @Inject constructor(
|
||||
@ApplicationContext context: Context,
|
||||
) {
|
||||
private val cm = context.getSystemService(ConnectivityManager::class.java)
|
||||
class ConnectivityObserver
|
||||
@Inject
|
||||
constructor(
|
||||
@ApplicationContext context: Context,
|
||||
) {
|
||||
private val cm = context.getSystemService(ConnectivityManager::class.java)
|
||||
|
||||
val online: Flow<Boolean> = callbackFlow {
|
||||
val request = NetworkRequest.Builder()
|
||||
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||
.build()
|
||||
val callback = object : ConnectivityManager.NetworkCallback() {
|
||||
override fun onAvailable(network: Network) {
|
||||
val online: Flow<Boolean> =
|
||||
callbackFlow {
|
||||
val request =
|
||||
NetworkRequest
|
||||
.Builder()
|
||||
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||
.build()
|
||||
val callback =
|
||||
object : ConnectivityManager.NetworkCallback() {
|
||||
override fun onAvailable(network: Network) {
|
||||
trySend(hasActiveNetwork())
|
||||
}
|
||||
|
||||
override fun onLost(network: Network) {
|
||||
trySend(hasActiveNetwork())
|
||||
}
|
||||
|
||||
override fun onCapabilitiesChanged(
|
||||
network: Network,
|
||||
capabilities: NetworkCapabilities,
|
||||
) {
|
||||
// INTERNET only -- NOT VALIDATED. A WAN/validation flicker
|
||||
// must not read as "device offline" when the LAN (and the
|
||||
// Minstrel server on it) is still reachable. /healthz is the
|
||||
// authority on server reachability.
|
||||
trySend(
|
||||
capabilities.hasCapability(
|
||||
NetworkCapabilities.NET_CAPABILITY_INTERNET,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
cm.registerNetworkCallback(request, callback)
|
||||
// Seed the initial value so the banner doesn't flash before the
|
||||
// first capability callback fires.
|
||||
trySend(hasActiveNetwork())
|
||||
}
|
||||
override fun onLost(network: Network) {
|
||||
trySend(hasActiveNetwork())
|
||||
}
|
||||
override fun onCapabilitiesChanged(
|
||||
network: Network,
|
||||
capabilities: NetworkCapabilities,
|
||||
) {
|
||||
// INTERNET only -- NOT VALIDATED. A WAN/validation flicker
|
||||
// must not read as "device offline" when the LAN (and the
|
||||
// Minstrel server on it) is still reachable. /healthz is the
|
||||
// authority on server reachability.
|
||||
trySend(
|
||||
capabilities.hasCapability(
|
||||
NetworkCapabilities.NET_CAPABILITY_INTERNET,
|
||||
),
|
||||
)
|
||||
}
|
||||
awaitClose { cm.unregisterNetworkCallback(callback) }
|
||||
}.distinctUntilChanged()
|
||||
|
||||
/**
|
||||
* Whether the network the device is using now is unmetered: Wi-Fi or
|
||||
* Ethernet, but not mobile data or a hotspot Android marks metered.
|
||||
* Downloads the user did not start (the liked-song downloads) wait for
|
||||
* this.
|
||||
*/
|
||||
val unmetered: Flow<Boolean> =
|
||||
callbackFlow {
|
||||
val callback =
|
||||
object : ConnectivityManager.NetworkCallback() {
|
||||
override fun onCapabilitiesChanged(
|
||||
network: Network,
|
||||
capabilities: NetworkCapabilities,
|
||||
) {
|
||||
trySend(capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED))
|
||||
}
|
||||
|
||||
override fun onLost(network: Network) {
|
||||
trySend(false)
|
||||
}
|
||||
}
|
||||
cm.registerDefaultNetworkCallback(callback)
|
||||
trySend(isActiveNetworkUnmetered())
|
||||
awaitClose { cm.unregisterNetworkCallback(callback) }
|
||||
}.distinctUntilChanged()
|
||||
|
||||
private fun isActiveNetworkUnmetered(): Boolean {
|
||||
val caps = cm.activeNetwork?.let { cm.getNetworkCapabilities(it) }
|
||||
return caps != null &&
|
||||
caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
|
||||
}
|
||||
cm.registerNetworkCallback(request, callback)
|
||||
// Seed the initial value so the banner doesn't flash before the
|
||||
// first capability callback fires.
|
||||
trySend(hasActiveNetwork())
|
||||
awaitClose { cm.unregisterNetworkCallback(callback) }
|
||||
}.distinctUntilChanged()
|
||||
|
||||
/**
|
||||
* Whether the network the device is using now is unmetered: Wi-Fi or
|
||||
* Ethernet, but not mobile data or a hotspot Android marks metered.
|
||||
* Downloads the user did not start (the liked-song downloads) wait for
|
||||
* this.
|
||||
*/
|
||||
val unmetered: Flow<Boolean> = callbackFlow {
|
||||
val callback = object : ConnectivityManager.NetworkCallback() {
|
||||
override fun onCapabilitiesChanged(
|
||||
network: Network,
|
||||
capabilities: NetworkCapabilities,
|
||||
) {
|
||||
trySend(capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED))
|
||||
}
|
||||
override fun onLost(network: Network) {
|
||||
trySend(false)
|
||||
}
|
||||
private fun hasActiveNetwork(): Boolean {
|
||||
val caps = cm.activeNetwork?.let { cm.getNetworkCapabilities(it) }
|
||||
return caps != null &&
|
||||
caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||
}
|
||||
cm.registerDefaultNetworkCallback(callback)
|
||||
trySend(isActiveNetworkUnmetered())
|
||||
awaitClose { cm.unregisterNetworkCallback(callback) }
|
||||
}.distinctUntilChanged()
|
||||
|
||||
private fun isActiveNetworkUnmetered(): Boolean {
|
||||
val caps = cm.activeNetwork?.let { cm.getNetworkCapabilities(it) }
|
||||
return caps != null &&
|
||||
caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
|
||||
}
|
||||
|
||||
private fun hasActiveNetwork(): Boolean {
|
||||
val caps = cm.activeNetwork?.let { cm.getNetworkCapabilities(it) }
|
||||
return caps != null &&
|
||||
caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||
}
|
||||
}
|
||||
|
||||
+129
-114
@@ -55,140 +55,155 @@ private const val ARBITRATE_MIN_GAP_MS = 2_000L
|
||||
* [com.fabledsword.minstrel.MinstrelApplication].
|
||||
*/
|
||||
@Singleton
|
||||
class NetworkStatusController @Inject constructor(
|
||||
@ApplicationScope private val scope: CoroutineScope,
|
||||
connectivity: ConnectivityObserver,
|
||||
private val authStore: AuthStore,
|
||||
retrofit: Retrofit,
|
||||
) : DefaultLifecycleObserver {
|
||||
private val api: HealthzApi = retrofit.create(HealthzApi::class.java)
|
||||
private val machine = ReachabilityMachine()
|
||||
private val lastProbeAtMs = AtomicLong(0)
|
||||
class NetworkStatusController
|
||||
@Inject
|
||||
constructor(
|
||||
@ApplicationScope private val scope: CoroutineScope,
|
||||
connectivity: ConnectivityObserver,
|
||||
private val authStore: AuthStore,
|
||||
retrofit: Retrofit,
|
||||
) : DefaultLifecycleObserver {
|
||||
private val api: HealthzApi = retrofit.create(HealthzApi::class.java)
|
||||
private val machine = ReachabilityMachine()
|
||||
private val lastProbeAtMs = AtomicLong(0)
|
||||
|
||||
private val stateInternal = MutableStateFlow(ServerHealth.Healthy)
|
||||
val state: StateFlow<ServerHealth> = stateInternal.asStateFlow()
|
||||
private val stateInternal = MutableStateFlow(ServerHealth.Healthy)
|
||||
val state: StateFlow<ServerHealth> = stateInternal.asStateFlow()
|
||||
|
||||
private val versionInternal = MutableStateFlow(VersionResult.SKIPPED)
|
||||
val versionResult: StateFlow<VersionResult> = versionInternal.asStateFlow()
|
||||
private val versionInternal = MutableStateFlow(VersionResult.SKIPPED)
|
||||
val versionResult: StateFlow<VersionResult> = versionInternal.asStateFlow()
|
||||
|
||||
private sealed interface Intent {
|
||||
data class Link(val up: Boolean) : Intent
|
||||
data class Probe(val resp: HealthzResponse?) : Intent
|
||||
object OpSuccess : Intent
|
||||
object OpFailure : Intent
|
||||
}
|
||||
private sealed interface Intent {
|
||||
data class Link(
|
||||
val up: Boolean,
|
||||
) : Intent
|
||||
|
||||
private val intents = Channel<Intent>(Channel.UNLIMITED)
|
||||
data class Probe(
|
||||
val resp: HealthzResponse?,
|
||||
) : Intent
|
||||
|
||||
init {
|
||||
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
|
||||
scope.launch { reduceLoop() }
|
||||
scope.launch {
|
||||
connectivity.online.collect { up ->
|
||||
intents.trySend(Intent.Link(up))
|
||||
if (up) probeOnce()
|
||||
}
|
||||
object OpSuccess : Intent
|
||||
|
||||
object OpFailure : Intent
|
||||
}
|
||||
scope.launch { pollLoop() }
|
||||
}
|
||||
|
||||
/** A real server op verifiably succeeded — self-proving recovery. Cheap; safe on hot paths. */
|
||||
fun reportSuccess() {
|
||||
if (stateInternal.value != ServerHealth.Healthy) intents.trySend(Intent.OpSuccess)
|
||||
}
|
||||
private val intents = Channel<Intent>(Channel.UNLIMITED)
|
||||
|
||||
/** A real network op failed — triggers /healthz arbitration. No-op when already Offline. */
|
||||
fun reportFailure() {
|
||||
if (stateInternal.value == ServerHealth.Offline) return
|
||||
intents.trySend(Intent.OpFailure)
|
||||
}
|
||||
|
||||
/** One-shot recheck for pull-to-refresh and the banner. */
|
||||
fun recheck() {
|
||||
scope.launch { probeOnce(force = true) }
|
||||
}
|
||||
|
||||
/**
|
||||
* App returned to the foreground — probe now rather than waiting for the
|
||||
* poll loop.
|
||||
*
|
||||
* The link-return probe in `init` does NOT cover this: it fires on a
|
||||
* connectivity *change*, and an app backgrounded on stable Wi-Fi sees none.
|
||||
* force = true so this also bypasses the ARBITRATE_MIN_GAP_MS throttle —
|
||||
* a user bringing the app up is exactly when a stale banner and a refused
|
||||
* track are most visible, and it's a once-per-foreground cost.
|
||||
*/
|
||||
override fun onStart(owner: LifecycleOwner) {
|
||||
recheck()
|
||||
}
|
||||
|
||||
private suspend fun reduceLoop() {
|
||||
for (intent in intents) {
|
||||
val now = System.currentTimeMillis()
|
||||
when (intent) {
|
||||
is Intent.Link -> machine.onLinkChange(intent.up)
|
||||
is Intent.Probe -> applyProbe(intent.resp, now)
|
||||
Intent.OpSuccess -> machine.onSuccess()
|
||||
Intent.OpFailure -> {
|
||||
machine.onOpFailure(now)
|
||||
// Arbitrate off the reducer thread: awaiting a stalled
|
||||
// /healthz here would block a concurrent self-proving
|
||||
// success from snapping us straight back to Healthy.
|
||||
scope.launch { probeOnce() }
|
||||
init {
|
||||
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
|
||||
scope.launch { reduceLoop() }
|
||||
scope.launch {
|
||||
connectivity.online.collect { up ->
|
||||
intents.trySend(Intent.Link(up))
|
||||
if (up) probeOnce()
|
||||
}
|
||||
}
|
||||
emit(machine.health())
|
||||
scope.launch { pollLoop() }
|
||||
}
|
||||
}
|
||||
|
||||
private fun applyProbe(resp: HealthzResponse?, now: Long) {
|
||||
if (resp == null) {
|
||||
machine.onProbeFailure(now)
|
||||
} else {
|
||||
machine.onSuccess()
|
||||
versionInternal.value = versionResultFor(resp)
|
||||
/** A real server op verifiably succeeded — self-proving recovery. Cheap; safe on hot paths. */
|
||||
fun reportSuccess() {
|
||||
if (stateInternal.value != ServerHealth.Healthy) intents.trySend(Intent.OpSuccess)
|
||||
}
|
||||
}
|
||||
|
||||
private fun emit(next: ServerHealth) {
|
||||
if (stateInternal.value != next) {
|
||||
Timber.w("NetworkStatus -> %s", next)
|
||||
stateInternal.value = next
|
||||
/** A real network op failed — triggers /healthz arbitration. No-op when already Offline. */
|
||||
fun reportFailure() {
|
||||
if (stateInternal.value == ServerHealth.Offline) return
|
||||
intents.trySend(Intent.OpFailure)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun pollLoop() {
|
||||
probeOnce()
|
||||
while (true) {
|
||||
val interval =
|
||||
if (stateInternal.value == ServerHealth.Healthy) POLL_HEALTHY_MS
|
||||
else POLL_DEGRADED_MS
|
||||
delay(interval)
|
||||
/** One-shot recheck for pull-to-refresh and the banner. */
|
||||
fun recheck() {
|
||||
scope.launch { probeOnce(force = true) }
|
||||
}
|
||||
|
||||
/**
|
||||
* App returned to the foreground — probe now rather than waiting for the
|
||||
* poll loop.
|
||||
*
|
||||
* The link-return probe in `init` does NOT cover this: it fires on a
|
||||
* connectivity *change*, and an app backgrounded on stable Wi-Fi sees none.
|
||||
* force = true so this also bypasses the ARBITRATE_MIN_GAP_MS throttle —
|
||||
* a user bringing the app up is exactly when a stale banner and a refused
|
||||
* track are most visible, and it's a once-per-foreground cost.
|
||||
*/
|
||||
override fun onStart(owner: LifecycleOwner) {
|
||||
recheck()
|
||||
}
|
||||
|
||||
private suspend fun reduceLoop() {
|
||||
for (intent in intents) {
|
||||
val now = System.currentTimeMillis()
|
||||
when (intent) {
|
||||
is Intent.Link -> machine.onLinkChange(intent.up)
|
||||
is Intent.Probe -> applyProbe(intent.resp, now)
|
||||
Intent.OpSuccess -> machine.onSuccess()
|
||||
Intent.OpFailure -> {
|
||||
machine.onOpFailure(now)
|
||||
// Arbitrate off the reducer thread: awaiting a stalled
|
||||
// /healthz here would block a concurrent self-proving
|
||||
// success from snapping us straight back to Healthy.
|
||||
scope.launch { probeOnce() }
|
||||
}
|
||||
}
|
||||
emit(machine.health())
|
||||
}
|
||||
}
|
||||
|
||||
private fun applyProbe(
|
||||
resp: HealthzResponse?,
|
||||
now: Long,
|
||||
) {
|
||||
if (resp == null) {
|
||||
machine.onProbeFailure(now)
|
||||
} else {
|
||||
machine.onSuccess()
|
||||
versionInternal.value = versionResultFor(resp)
|
||||
}
|
||||
}
|
||||
|
||||
private fun emit(next: ServerHealth) {
|
||||
if (stateInternal.value != next) {
|
||||
Timber.w("NetworkStatus -> %s", next)
|
||||
stateInternal.value = next
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun pollLoop() {
|
||||
probeOnce()
|
||||
while (true) {
|
||||
val interval =
|
||||
if (stateInternal.value == ServerHealth.Healthy) {
|
||||
POLL_HEALTHY_MS
|
||||
} else {
|
||||
POLL_DEGRADED_MS
|
||||
}
|
||||
delay(interval)
|
||||
probeOnce()
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun probeOnce(force: Boolean = false) {
|
||||
// Startup guard: don't poll the localhost placeholder before AuthStore
|
||||
// hydrates the real base URL — that false failure would flash the banner.
|
||||
if (authStore.baseUrl.value == AuthStore.DEFAULT_BASE_URL) return
|
||||
val now = System.currentTimeMillis()
|
||||
if (!force && now - lastProbeAtMs.get() < ARBITRATE_MIN_GAP_MS) return
|
||||
lastProbeAtMs.set(now)
|
||||
val resp = runCatching { api.check() }.getOrNull()
|
||||
intents.trySend(Intent.Probe(resp))
|
||||
}
|
||||
|
||||
private fun versionResultFor(resp: HealthzResponse): VersionResult {
|
||||
val min = resp.minClientVersion
|
||||
return when {
|
||||
min.isEmpty() -> VersionResult.SKIPPED
|
||||
isVersionNewer(min, BuildConfig.VERSION_NAME) -> VersionResult.TOO_OLD
|
||||
else -> VersionResult.OK
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun probeOnce(force: Boolean = false) {
|
||||
// Startup guard: don't poll the localhost placeholder before AuthStore
|
||||
// hydrates the real base URL — that false failure would flash the banner.
|
||||
if (authStore.baseUrl.value == AuthStore.DEFAULT_BASE_URL) return
|
||||
val now = System.currentTimeMillis()
|
||||
if (!force && now - lastProbeAtMs.get() < ARBITRATE_MIN_GAP_MS) return
|
||||
lastProbeAtMs.set(now)
|
||||
val resp = runCatching { api.check() }.getOrNull()
|
||||
intents.trySend(Intent.Probe(resp))
|
||||
}
|
||||
|
||||
private fun versionResultFor(resp: HealthzResponse): VersionResult {
|
||||
val min = resp.minClientVersion
|
||||
return when {
|
||||
min.isEmpty() -> VersionResult.SKIPPED
|
||||
isVersionNewer(min, BuildConfig.VERSION_NAME) -> VersionResult.TOO_OLD
|
||||
else -> VersionResult.OK
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reactive [ServerHealth] snapshot provided once at the app root. Lets leaf
|
||||
* composables (TrackRow gating, write-affordance disabling) branch on health
|
||||
|
||||
+7
-7
@@ -41,7 +41,6 @@ internal const val CORROBORATION_MIN_SPACING_MS = 3_000L
|
||||
* sustained-time backstop.
|
||||
*/
|
||||
class ReachabilityMachine {
|
||||
|
||||
private enum class Reachability { Reachable, Unstable, Unreachable }
|
||||
|
||||
private var linkUp = true
|
||||
@@ -89,12 +88,13 @@ class ReachabilityMachine {
|
||||
}
|
||||
}
|
||||
|
||||
fun health(): ServerHealth = when {
|
||||
!linkUp -> ServerHealth.Offline
|
||||
reachability == Reachability.Reachable -> ServerHealth.Healthy
|
||||
reachability == Reachability.Unstable -> ServerHealth.Unstable
|
||||
else -> ServerHealth.ServerDown
|
||||
}
|
||||
fun health(): ServerHealth =
|
||||
when {
|
||||
!linkUp -> ServerHealth.Offline
|
||||
reachability == Reachability.Reachable -> ServerHealth.Healthy
|
||||
reachability == Reachability.Unstable -> ServerHealth.Unstable
|
||||
else -> ServerHealth.ServerDown
|
||||
}
|
||||
|
||||
private fun shouldEscalate(nowMs: Long): Boolean {
|
||||
val corroborated = recentOpFailures.size >= CORROBORATION_OP_THRESHOLD
|
||||
|
||||
+18
-16
@@ -29,21 +29,23 @@ private const val HEALTHZ_PATH = "/healthz"
|
||||
* already constructed (construct-the-singleton trick in MinstrelApplication).
|
||||
*/
|
||||
@Singleton
|
||||
class ReachabilityReportingInterceptor @Inject constructor(
|
||||
private val networkStatus: Lazy<NetworkStatusController>,
|
||||
) : Interceptor {
|
||||
override fun intercept(chain: Interceptor.Chain): Response {
|
||||
val request = chain.request()
|
||||
val isMinstrel = request.url.host == PLACEHOLDER_HOST
|
||||
val isHealthz = request.url.encodedPath.endsWith(HEALTHZ_PATH)
|
||||
if (!isMinstrel || isHealthz) return chain.proceed(request)
|
||||
return try {
|
||||
val response = chain.proceed(request)
|
||||
if (response.isSuccessful) networkStatus.get().reportSuccess()
|
||||
response
|
||||
} catch (e: IOException) {
|
||||
networkStatus.get().reportFailure()
|
||||
throw e
|
||||
class ReachabilityReportingInterceptor
|
||||
@Inject
|
||||
constructor(
|
||||
private val networkStatus: Lazy<NetworkStatusController>,
|
||||
) : Interceptor {
|
||||
override fun intercept(chain: Interceptor.Chain): Response {
|
||||
val request = chain.request()
|
||||
val isMinstrel = request.url.host == PLACEHOLDER_HOST
|
||||
val isHealthz = request.url.encodedPath.endsWith(HEALTHZ_PATH)
|
||||
if (!isMinstrel || isHealthz) return chain.proceed(request)
|
||||
return try {
|
||||
val response = chain.proceed(request)
|
||||
if (response.isSuccessful) networkStatus.get().reportSuccess()
|
||||
response
|
||||
} catch (e: IOException) {
|
||||
networkStatus.get().reportFailure()
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,9 +19,10 @@ import kotlinx.coroutines.flow.map
|
||||
* heals itself the moment connectivity returns instead of sitting in the
|
||||
* failed state until a manual pull-to-refresh.
|
||||
*/
|
||||
fun NetworkStatusController.recoveries(): Flow<Unit> = state
|
||||
.map { it == ServerHealth.Healthy }
|
||||
.distinctUntilChanged()
|
||||
.drop(1)
|
||||
.filter { it }
|
||||
.map { }
|
||||
fun NetworkStatusController.recoveries(): Flow<Unit> =
|
||||
state
|
||||
.map { it == ServerHealth.Healthy }
|
||||
.distinctUntilChanged()
|
||||
.drop(1)
|
||||
.filter { it }
|
||||
.map { }
|
||||
|
||||
+30
-22
@@ -43,12 +43,14 @@ private const val BACK_ONLINE_FLASH_MS = 2_000L
|
||||
* re-wrapping StateFlow — the controller's is already app-scoped and warm.
|
||||
*/
|
||||
@HiltViewModel
|
||||
class ConnectivityBannerViewModel @Inject constructor(
|
||||
networkStatus: NetworkStatusController,
|
||||
@Suppress("UnusedPrivateProperty") savedStateHandle: SavedStateHandle,
|
||||
) : ViewModel() {
|
||||
val health: StateFlow<ServerHealth> = networkStatus.state
|
||||
}
|
||||
class ConnectivityBannerViewModel
|
||||
@Inject
|
||||
constructor(
|
||||
networkStatus: NetworkStatusController,
|
||||
@Suppress("UnusedPrivateProperty") savedStateHandle: SavedStateHandle,
|
||||
) : ViewModel() {
|
||||
val health: StateFlow<ServerHealth> = networkStatus.state
|
||||
}
|
||||
|
||||
/**
|
||||
* Shell banner. Tells the user *why* they're degraded — no link vs server-down
|
||||
@@ -57,9 +59,7 @@ class ConnectivityBannerViewModel @Inject constructor(
|
||||
* recovery is unmistakable. Sentence case, understated voice (design system).
|
||||
*/
|
||||
@Composable
|
||||
fun ConnectionErrorBanner(
|
||||
viewModel: ConnectivityBannerViewModel = hiltViewModel(),
|
||||
) {
|
||||
fun ConnectionErrorBanner(viewModel: ConnectivityBannerViewModel = hiltViewModel()) {
|
||||
val health by viewModel.health.collectAsStateWithLifecycle()
|
||||
var showBackOnline by remember { mutableStateOf(false) }
|
||||
var wasDown by remember { mutableStateOf(false) }
|
||||
@@ -89,7 +89,10 @@ fun ConnectionErrorBanner(
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun BannerContent(health: ServerHealth, backOnline: Boolean) {
|
||||
private fun BannerContent(
|
||||
health: ServerHealth,
|
||||
backOnline: Boolean,
|
||||
) {
|
||||
val scheme = MaterialTheme.colorScheme
|
||||
val background: Color
|
||||
val foreground: Color
|
||||
@@ -108,10 +111,11 @@ private fun BannerContent(health: ServerHealth, backOnline: Boolean) {
|
||||
}
|
||||
}
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.background(background)
|
||||
.padding(horizontal = 16.dp, vertical = 10.dp),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.background(background)
|
||||
.padding(horizontal = 16.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
@@ -124,11 +128,15 @@ private fun BannerContent(health: ServerHealth, backOnline: Boolean) {
|
||||
}
|
||||
}
|
||||
|
||||
private fun bannerText(health: ServerHealth, backOnline: Boolean): String = when {
|
||||
backOnline -> "Back online."
|
||||
health == ServerHealth.Offline -> "No connection — check Wi-Fi or mobile data."
|
||||
health == ServerHealth.ServerDown ->
|
||||
"Server unreachable — your cached content is still available."
|
||||
health == ServerHealth.Unstable -> "Reconnecting…"
|
||||
else -> ""
|
||||
}
|
||||
private fun bannerText(
|
||||
health: ServerHealth,
|
||||
backOnline: Boolean,
|
||||
): String =
|
||||
when {
|
||||
backOnline -> "Back online."
|
||||
health == ServerHealth.Offline -> "No connection — check Wi-Fi or mobile data."
|
||||
health == ServerHealth.ServerDown ->
|
||||
"Server unreachable — your cached content is still available."
|
||||
health == ServerHealth.Unstable -> "Reconnecting…"
|
||||
else -> ""
|
||||
}
|
||||
|
||||
@@ -20,11 +20,12 @@ annotation class ApplicationScope
|
||||
object AppModule {
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideJson(): Json = Json {
|
||||
ignoreUnknownKeys = true
|
||||
explicitNulls = false
|
||||
coerceInputValues = true
|
||||
}
|
||||
fun provideJson(): Json =
|
||||
Json {
|
||||
ignoreUnknownKeys = true
|
||||
explicitNulls = false
|
||||
coerceInputValues = true
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
|
||||
+364
-314
@@ -5,9 +5,9 @@ import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.os.PowerManager
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.DefaultLifecycleObserver
|
||||
import androidx.lifecycle.LifecycleOwner
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.ProcessLifecycleOwner
|
||||
import com.fabledsword.minstrel.auth.AuthController
|
||||
import com.fabledsword.minstrel.auth.AuthStore
|
||||
@@ -52,338 +52,388 @@ import javax.inject.Singleton
|
||||
*/
|
||||
@Suppress("TooManyFunctions") // one collector + one (un)register pair per signal; cohesive
|
||||
@Singleton
|
||||
class DiagnosticsReporter @Inject constructor(
|
||||
@ApplicationContext private val context: Context,
|
||||
@ApplicationScope private val scope: CoroutineScope,
|
||||
private val dao: DiagnosticEventDao,
|
||||
private val authController: AuthController,
|
||||
private val authStore: AuthStore,
|
||||
private val connectivity: ConnectivityObserver,
|
||||
private val networkStatus: NetworkStatusController,
|
||||
private val playerController: PlayerController,
|
||||
private val outputPicker: OutputPickerController,
|
||||
private val remoteState: RemotePlayerState,
|
||||
private val json: Json,
|
||||
) {
|
||||
@Volatile private var enabled = false
|
||||
private var collectorJob: Job? = null
|
||||
private var powerReceiver: BroadcastReceiver? = null
|
||||
private var lifecycleObserver: DefaultLifecycleObserver? = null
|
||||
class DiagnosticsReporter
|
||||
@Inject
|
||||
constructor(
|
||||
@ApplicationContext private val context: Context,
|
||||
@ApplicationScope private val scope: CoroutineScope,
|
||||
private val dao: DiagnosticEventDao,
|
||||
private val authController: AuthController,
|
||||
private val authStore: AuthStore,
|
||||
private val connectivity: ConnectivityObserver,
|
||||
private val networkStatus: NetworkStatusController,
|
||||
private val playerController: PlayerController,
|
||||
private val outputPicker: OutputPickerController,
|
||||
private val remoteState: RemotePlayerState,
|
||||
private val json: Json,
|
||||
) {
|
||||
@Volatile private var enabled = false
|
||||
private var collectorJob: Job? = null
|
||||
private var powerReceiver: BroadcastReceiver? = null
|
||||
private var lifecycleObserver: DefaultLifecycleObserver? = null
|
||||
|
||||
init {
|
||||
// Gate = account flag (currentUser.debugModeEnabled) AND not the
|
||||
// per-device local opt-out.
|
||||
scope.launch {
|
||||
combine(authController.currentUser, authStore.diagnosticsOptOut) { user, optOut ->
|
||||
(user?.debugModeEnabled == true) && !optOut
|
||||
}.distinctUntilChanged().collect { setEnabled(it) }
|
||||
}
|
||||
// Periodically re-pull /me so a remote admin flip propagates
|
||||
// without a re-login or app restart.
|
||||
scope.launch {
|
||||
while (true) {
|
||||
delay(GATE_REFRESH_MS)
|
||||
authController.refreshProfile()
|
||||
init {
|
||||
// Gate = account flag (currentUser.debugModeEnabled) AND not the
|
||||
// per-device local opt-out.
|
||||
scope.launch {
|
||||
combine(authController.currentUser, authStore.diagnosticsOptOut) { user, optOut ->
|
||||
(user?.debugModeEnabled == true) && !optOut
|
||||
}.distinctUntilChanged().collect { setEnabled(it) }
|
||||
}
|
||||
// Periodically re-pull /me so a remote admin flip propagates
|
||||
// without a re-login or app restart.
|
||||
scope.launch {
|
||||
while (true) {
|
||||
delay(GATE_REFRESH_MS)
|
||||
authController.refreshProfile()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun setEnabled(value: Boolean) {
|
||||
if (value == enabled) return
|
||||
enabled = value
|
||||
if (value) start() else stop()
|
||||
}
|
||||
|
||||
private fun start() {
|
||||
registerPowerReceiver()
|
||||
registerLifecycleObserver()
|
||||
collectorJob = scope.launch {
|
||||
record("lifecycle", buildJsonObject { put("event", "reporting_started") })
|
||||
launch { collectConnectivity() }
|
||||
launch { collectServerHealth() }
|
||||
launch { collectUpnpDrops() }
|
||||
launch { collectPlayerState() }
|
||||
launch { collectTrackChanges() }
|
||||
launch { collectTransportFlap() }
|
||||
launch { collectRoutes() }
|
||||
launch { heartbeatLoop() }
|
||||
private fun setEnabled(value: Boolean) {
|
||||
if (value == enabled) return
|
||||
enabled = value
|
||||
if (value) start() else stop()
|
||||
}
|
||||
}
|
||||
|
||||
private fun stop() {
|
||||
collectorJob?.cancel()
|
||||
collectorJob = null
|
||||
unregisterPowerReceiver()
|
||||
unregisterLifecycleObserver()
|
||||
// Off means off: drop any unsent buffer (honors the user OFF
|
||||
// intent and avoids leaking data captured before disable).
|
||||
scope.launch { runCatching { dao.clear() } }
|
||||
}
|
||||
|
||||
private suspend fun collectConnectivity() {
|
||||
connectivity.online.distinctUntilChanged().collect { online ->
|
||||
record("connectivity", buildJsonObject {
|
||||
put("event", "online_changed")
|
||||
put("online", online)
|
||||
})
|
||||
private fun start() {
|
||||
registerPowerReceiver()
|
||||
registerLifecycleObserver()
|
||||
collectorJob =
|
||||
scope.launch {
|
||||
record("lifecycle", buildJsonObject { put("event", "reporting_started") })
|
||||
launch { collectConnectivity() }
|
||||
launch { collectServerHealth() }
|
||||
launch { collectUpnpDrops() }
|
||||
launch { collectPlayerState() }
|
||||
launch { collectTrackChanges() }
|
||||
launch { collectTransportFlap() }
|
||||
launch { collectRoutes() }
|
||||
launch { heartbeatLoop() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun collectServerHealth() {
|
||||
// state is a StateFlow — already conflated/distinct, so no
|
||||
// distinctUntilChanged (it's a deprecation warning = build error).
|
||||
networkStatus.state.collect { s ->
|
||||
record("connectivity", buildJsonObject {
|
||||
put("event", "server_health")
|
||||
put("state", s.name)
|
||||
})
|
||||
private fun stop() {
|
||||
collectorJob?.cancel()
|
||||
collectorJob = null
|
||||
unregisterPowerReceiver()
|
||||
unregisterLifecycleObserver()
|
||||
// Off means off: drop any unsent buffer (honors the user OFF
|
||||
// intent and avoids leaking data captured before disable).
|
||||
scope.launch { runCatching { dao.clear() } }
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun collectUpnpDrops() {
|
||||
playerController.dropEvents.collect { msg ->
|
||||
record("upnp_sync", buildJsonObject {
|
||||
put("event", "drop")
|
||||
put("message", msg)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun collectPlayerState() {
|
||||
// 'playback', not 'upnp_sync' — player state applies to every output
|
||||
// route (phone speaker, Bluetooth, UPnP), not just casting.
|
||||
playerController.uiState
|
||||
.map { Triple(it.currentSource, it.isUpnpLoading, it.playbackError) }
|
||||
.distinctUntilChanged()
|
||||
.collect { (source, upnpLoading, err) ->
|
||||
record("playback", buildJsonObject {
|
||||
put("event", "player_state")
|
||||
put("source", source ?: "")
|
||||
put("upnp_loading", upnpLoading)
|
||||
if (err != null) put("error", err)
|
||||
})
|
||||
private suspend fun collectConnectivity() {
|
||||
connectivity.online.distinctUntilChanged().collect { online ->
|
||||
record(
|
||||
"connectivity",
|
||||
buildJsonObject {
|
||||
put("event", "online_changed")
|
||||
put("online", online)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Emit a snapshot at each track/queue-index change — captures a
|
||||
// skip-induced local↔Sonos desync at the INSTANT it happens, which the
|
||||
// 45s heartbeat misses. Note: uiState is a conflated StateFlow, so a
|
||||
// very rapid skip burst may coalesce intermediate indices (we still get
|
||||
// the boundaries + the local-vs-Sonos snapshot).
|
||||
private suspend fun collectTrackChanges() {
|
||||
playerController.uiState
|
||||
.map { it.queueIndex to it.currentTrack?.id }
|
||||
.distinctUntilChanged()
|
||||
.collect { (index, _) ->
|
||||
val ui = playerController.uiState.value
|
||||
val casting = outputPicker.routesState.value.current.protocol !=
|
||||
private suspend fun collectServerHealth() {
|
||||
// state is a StateFlow — already conflated/distinct, so no
|
||||
// distinctUntilChanged (it's a deprecation warning = build error).
|
||||
networkStatus.state.collect { s ->
|
||||
record(
|
||||
"connectivity",
|
||||
buildJsonObject {
|
||||
put("event", "server_health")
|
||||
put("state", s.name)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun collectUpnpDrops() {
|
||||
playerController.dropEvents.collect { msg ->
|
||||
record(
|
||||
"upnp_sync",
|
||||
buildJsonObject {
|
||||
put("event", "drop")
|
||||
put("message", msg)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun collectPlayerState() {
|
||||
// 'playback', not 'upnp_sync' — player state applies to every output
|
||||
// route (phone speaker, Bluetooth, UPnP), not just casting.
|
||||
playerController.uiState
|
||||
.map { Triple(it.currentSource, it.isUpnpLoading, it.playbackError) }
|
||||
.distinctUntilChanged()
|
||||
.collect { (source, upnpLoading, err) ->
|
||||
record(
|
||||
"playback",
|
||||
buildJsonObject {
|
||||
put("event", "player_state")
|
||||
put("source", source ?: "")
|
||||
put("upnp_loading", upnpLoading)
|
||||
if (err != null) put("error", err)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Emit a snapshot at each track/queue-index change — captures a
|
||||
// skip-induced local↔Sonos desync at the INSTANT it happens, which the
|
||||
// 45s heartbeat misses. Note: uiState is a conflated StateFlow, so a
|
||||
// very rapid skip burst may coalesce intermediate indices (we still get
|
||||
// the boundaries + the local-vs-Sonos snapshot).
|
||||
private suspend fun collectTrackChanges() {
|
||||
playerController.uiState
|
||||
.map { it.queueIndex to it.currentTrack?.id }
|
||||
.distinctUntilChanged()
|
||||
.collect { (index, _) ->
|
||||
val ui = playerController.uiState.value
|
||||
val casting =
|
||||
outputPicker.routesState.value.current.protocol !=
|
||||
OutputRoute.Protocol.SYSTEM
|
||||
record(
|
||||
"playback",
|
||||
buildJsonObject {
|
||||
put("event", "track_change")
|
||||
put("local_index", index)
|
||||
// Track IDENTITY, not just index — indices wobble across
|
||||
// re-casts, so the id + Sonos URI make a desync unambiguous.
|
||||
put("local_track_id", ui.currentTrack?.id ?: "")
|
||||
put("local_pos_ms", ui.positionMs)
|
||||
putSonos(this, casting)
|
||||
put("upnp_loading", ui.isUpnpLoading)
|
||||
put("server_health", networkStatus.state.value.name)
|
||||
put("route", outputPicker.routesState.value.current.name)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Catch the renderer rapidly leaving and re-entering PLAYING.
|
||||
*
|
||||
* The symptom: a Sonos rapidly play-pause-play-pausing, about every half
|
||||
* second, usually as a track starts, cleared by a manual pause or skip.
|
||||
* No other collector sees it: `player_state` carries
|
||||
* source/loading/error but not playing, `track_change` needs the index
|
||||
* to move, and the heartbeat samples once per 45s.
|
||||
*
|
||||
* Records every raw transport change (cheap — steady playback produces
|
||||
* a couple per track) and, when they come in a burst, one summary event
|
||||
* carrying the whole sequence. The summary is the useful artefact: it
|
||||
* pairs the renderer's states with local-vs-Sonos track and position, so
|
||||
* an episode says whether the app and the renderer disagreed about which
|
||||
* track was playing, or agreed while the renderer rebuffered.
|
||||
*
|
||||
* See [TransportObservation] on the 1 Hz sampling limit.
|
||||
*/
|
||||
private suspend fun collectTransportFlap() {
|
||||
val detector = TransportFlapDetector()
|
||||
playerController.transportEvents.collect { obs ->
|
||||
record(
|
||||
"upnp_sync",
|
||||
buildJsonObject {
|
||||
put("event", "transport")
|
||||
put("state", obs.state)
|
||||
put("status_ok", obs.statusOk)
|
||||
put("sonos_track", obs.trackNumber)
|
||||
put("sonos_pos_ms", obs.positionMs)
|
||||
put("play_intent", obs.playIntent)
|
||||
},
|
||||
)
|
||||
detector.onChange(obs)?.let { recordFlapSummary(it) }
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun recordFlapSummary(recent: List<TransportObservation>) {
|
||||
val ui = playerController.uiState.value
|
||||
val casting =
|
||||
outputPicker.routesState.value.current.protocol !=
|
||||
OutputRoute.Protocol.SYSTEM
|
||||
record("playback", buildJsonObject {
|
||||
put("event", "track_change")
|
||||
put("local_index", index)
|
||||
// Track IDENTITY, not just index — indices wobble across
|
||||
// re-casts, so the id + Sonos URI make a desync unambiguous.
|
||||
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)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Catch the renderer rapidly leaving and re-entering PLAYING.
|
||||
*
|
||||
* The symptom: a Sonos rapidly play-pause-play-pausing, about every half
|
||||
* second, usually as a track starts, cleared by a manual pause or skip.
|
||||
* No other collector sees it: `player_state` carries
|
||||
* source/loading/error but not playing, `track_change` needs the index
|
||||
* to move, and the heartbeat samples once per 45s.
|
||||
*
|
||||
* Records every raw transport change (cheap — steady playback produces
|
||||
* a couple per track) and, when they come in a burst, one summary event
|
||||
* carrying the whole sequence. The summary is the useful artefact: it
|
||||
* pairs the renderer's states with local-vs-Sonos track and position, so
|
||||
* an episode says whether the app and the renderer disagreed about which
|
||||
* track was playing, or agreed while the renderer rebuffered.
|
||||
*
|
||||
* See [TransportObservation] on the 1 Hz sampling limit.
|
||||
*/
|
||||
private suspend fun collectTransportFlap() {
|
||||
val detector = TransportFlapDetector()
|
||||
playerController.transportEvents.collect { obs ->
|
||||
record("upnp_sync", buildJsonObject {
|
||||
put("event", "transport")
|
||||
put("state", obs.state)
|
||||
put("status_ok", obs.statusOk)
|
||||
put("sonos_track", obs.trackNumber)
|
||||
put("sonos_pos_ms", obs.positionMs)
|
||||
put("play_intent", obs.playIntent)
|
||||
})
|
||||
detector.onChange(obs)?.let { recordFlapSummary(it) }
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun recordFlapSummary(recent: List<TransportObservation>) {
|
||||
val ui = playerController.uiState.value
|
||||
val casting = outputPicker.routesState.value.current.protocol !=
|
||||
OutputRoute.Protocol.SYSTEM
|
||||
val spanMs = recent.last().atElapsedMs - recent.first().atElapsedMs
|
||||
record("upnp_sync", buildJsonObject {
|
||||
put("event", "transport_flap")
|
||||
put("changes", recent.size)
|
||||
put("window_ms", spanMs)
|
||||
// The sequence itself, e.g. "PLAYING>TRANSITIONING>STOPPED>PLAYING".
|
||||
// Whether STOPPED appears at all is the first question to ask of a
|
||||
// captured episode.
|
||||
put("sequence", recent.joinToString(">") { it.state })
|
||||
put("sonos_positions_ms", recent.joinToString(",") { it.positionMs.toString() })
|
||||
put("sonos_tracks", recent.joinToString(",") { it.trackNumber.toString() })
|
||||
put("local_index", ui.queueIndex)
|
||||
put("local_track_id", ui.currentTrack?.id ?: "")
|
||||
put("local_pos_ms", ui.positionMs)
|
||||
putSonos(this, casting)
|
||||
put("upnp_loading", ui.isUpnpLoading)
|
||||
put("server_health", networkStatus.state.value.name)
|
||||
put("route", outputPicker.routesState.value.current.name)
|
||||
addPowerFields(this)
|
||||
})
|
||||
}
|
||||
|
||||
private suspend fun collectRoutes() {
|
||||
// 'playback' — route changes happen for all outputs. This only ever
|
||||
// logs the ACTIVE route (routesState.current), so no "connected" flag.
|
||||
outputPicker.routesState.map { it.current }.distinctUntilChanged().collect { r ->
|
||||
record("playback", buildJsonObject {
|
||||
put("event", "route")
|
||||
put("id", r.id)
|
||||
put("name", r.name)
|
||||
put("kind", r.kind.name)
|
||||
put("protocol", r.protocol.name)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun heartbeatLoop() {
|
||||
while (true) {
|
||||
delay(HEARTBEAT_MS)
|
||||
val ui = playerController.uiState.value
|
||||
val route = outputPicker.routesState.value.current
|
||||
val routeActive = route.protocol != OutputRoute.Protocol.SYSTEM
|
||||
// Idle = nothing worth sampling. Skip to keep the buffer lean.
|
||||
if (!ui.isPlaying && !routeActive) continue
|
||||
record("heartbeat", buildJsonObject {
|
||||
put("server_health", networkStatus.state.value.name)
|
||||
put("is_playing", ui.isPlaying)
|
||||
put("source", ui.currentSource ?: "")
|
||||
put("local_index", ui.queueIndex)
|
||||
put("local_track_id", ui.currentTrack?.id ?: "")
|
||||
put("local_pos_ms", ui.positionMs)
|
||||
put("route", route.name)
|
||||
put("route_protocol", route.protocol.name)
|
||||
putSonos(this, routeActive)
|
||||
addPowerFields(this)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// --- power + lifecycle taps -------------------------------------------
|
||||
|
||||
private fun registerPowerReceiver() {
|
||||
if (powerReceiver != null) return
|
||||
val receiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(c: Context?, intent: Intent?) {
|
||||
val action = intent?.action ?: return
|
||||
if (!enabled) return
|
||||
scope.launch { record("power", powerEvent(action)) }
|
||||
}
|
||||
}
|
||||
val filter = IntentFilter().apply {
|
||||
addAction(Intent.ACTION_SCREEN_ON)
|
||||
addAction(Intent.ACTION_SCREEN_OFF)
|
||||
addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED)
|
||||
}
|
||||
// System-protected broadcasts, but pass NOT_EXPORTED explicitly so
|
||||
// the API 34+ registerReceiver flag requirement is satisfied.
|
||||
ContextCompat.registerReceiver(
|
||||
context, receiver, filter, ContextCompat.RECEIVER_NOT_EXPORTED,
|
||||
)
|
||||
powerReceiver = receiver
|
||||
}
|
||||
|
||||
private fun unregisterPowerReceiver() {
|
||||
powerReceiver?.let { runCatching { context.unregisterReceiver(it) } }
|
||||
powerReceiver = null
|
||||
}
|
||||
|
||||
private fun registerLifecycleObserver() {
|
||||
if (lifecycleObserver != null) return
|
||||
val obs = object : DefaultLifecycleObserver {
|
||||
override fun onStart(owner: LifecycleOwner) = logLifecycle("app_foreground")
|
||||
override fun onStop(owner: LifecycleOwner) = logLifecycle("app_background")
|
||||
}
|
||||
lifecycleObserver = obs
|
||||
scope.launch(Dispatchers.Main) {
|
||||
ProcessLifecycleOwner.get().lifecycle.addObserver(obs)
|
||||
}
|
||||
}
|
||||
|
||||
private fun unregisterLifecycleObserver() {
|
||||
val obs = lifecycleObserver ?: return
|
||||
lifecycleObserver = null
|
||||
scope.launch(Dispatchers.Main) {
|
||||
ProcessLifecycleOwner.get().lifecycle.removeObserver(obs)
|
||||
}
|
||||
}
|
||||
|
||||
private fun logLifecycle(event: String) {
|
||||
if (!enabled) return
|
||||
scope.launch { record("lifecycle", buildJsonObject { put("event", event) }) }
|
||||
}
|
||||
|
||||
private fun powerEvent(action: String): JsonObject = buildJsonObject {
|
||||
put("event", action.substringAfterLast('.'))
|
||||
addPowerFields(this)
|
||||
}
|
||||
|
||||
// Sonos/UPnP remote-vs-local desync fields. Only meaningful while a
|
||||
// remote route is active; zeroed otherwise so a stale RemotePlayerState
|
||||
// from a just-ended cast can't masquerade as live Sonos data (the
|
||||
// cast→phone handoff artifact). currentTrackUri is the desync ground
|
||||
// truth — it carries the track the speaker is actually streaming.
|
||||
private fun putSonos(builder: kotlinx.serialization.json.JsonObjectBuilder, casting: Boolean) {
|
||||
builder.put("sonos_track", if (casting) remoteState.trackNumber else 0)
|
||||
builder.put("sonos_pos_ms", if (casting) remoteState.positionMs else 0)
|
||||
builder.put("sonos_playing", casting && remoteState.isPlaying)
|
||||
if (casting) builder.put("sonos_uri", remoteState.currentTrackUri)
|
||||
}
|
||||
|
||||
private fun addPowerFields(builder: kotlinx.serialization.json.JsonObjectBuilder) {
|
||||
val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager
|
||||
builder.put("doze", pm.isDeviceIdleMode)
|
||||
builder.put("screen_on", pm.isInteractive)
|
||||
builder.put("battery_opt_ignored", pm.isIgnoringBatteryOptimizations(context.packageName))
|
||||
}
|
||||
|
||||
private suspend fun record(kind: String, payload: JsonObject) {
|
||||
runCatching {
|
||||
val id = dao.insert(
|
||||
DiagnosticEventEntity(
|
||||
kind = kind,
|
||||
occurredAtMillis = System.currentTimeMillis(),
|
||||
payloadJson = json.encodeToString(JsonObject.serializer(), payload),
|
||||
),
|
||||
addPowerFields(this)
|
||||
},
|
||||
)
|
||||
if (id % TRIM_INTERVAL == 0L) dao.trimToNewest(MAX_BUFFER)
|
||||
}
|
||||
|
||||
private suspend fun collectRoutes() {
|
||||
// 'playback' — route changes happen for all outputs. This only ever
|
||||
// logs the ACTIVE route (routesState.current), so no "connected" flag.
|
||||
outputPicker.routesState.map { it.current }.distinctUntilChanged().collect { r ->
|
||||
record(
|
||||
"playback",
|
||||
buildJsonObject {
|
||||
put("event", "route")
|
||||
put("id", r.id)
|
||||
put("name", r.name)
|
||||
put("kind", r.kind.name)
|
||||
put("protocol", r.protocol.name)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun heartbeatLoop() {
|
||||
while (true) {
|
||||
delay(HEARTBEAT_MS)
|
||||
val ui = playerController.uiState.value
|
||||
val route = outputPicker.routesState.value.current
|
||||
val routeActive = route.protocol != OutputRoute.Protocol.SYSTEM
|
||||
// Idle = nothing worth sampling. Skip to keep the buffer lean.
|
||||
if (!ui.isPlaying && !routeActive) continue
|
||||
record(
|
||||
"heartbeat",
|
||||
buildJsonObject {
|
||||
put("server_health", networkStatus.state.value.name)
|
||||
put("is_playing", ui.isPlaying)
|
||||
put("source", ui.currentSource ?: "")
|
||||
put("local_index", ui.queueIndex)
|
||||
put("local_track_id", ui.currentTrack?.id ?: "")
|
||||
put("local_pos_ms", ui.positionMs)
|
||||
put("route", route.name)
|
||||
put("route_protocol", route.protocol.name)
|
||||
putSonos(this, routeActive)
|
||||
addPowerFields(this)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// --- power + lifecycle taps -------------------------------------------
|
||||
|
||||
private fun registerPowerReceiver() {
|
||||
if (powerReceiver != null) return
|
||||
val receiver =
|
||||
object : BroadcastReceiver() {
|
||||
override fun onReceive(
|
||||
c: Context?,
|
||||
intent: Intent?,
|
||||
) {
|
||||
val action = intent?.action ?: return
|
||||
if (!enabled) return
|
||||
scope.launch { record("power", powerEvent(action)) }
|
||||
}
|
||||
}
|
||||
val filter =
|
||||
IntentFilter().apply {
|
||||
addAction(Intent.ACTION_SCREEN_ON)
|
||||
addAction(Intent.ACTION_SCREEN_OFF)
|
||||
addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED)
|
||||
}
|
||||
// System-protected broadcasts, but pass NOT_EXPORTED explicitly so
|
||||
// the API 34+ registerReceiver flag requirement is satisfied.
|
||||
ContextCompat.registerReceiver(
|
||||
context,
|
||||
receiver,
|
||||
filter,
|
||||
ContextCompat.RECEIVER_NOT_EXPORTED,
|
||||
)
|
||||
powerReceiver = receiver
|
||||
}
|
||||
|
||||
private fun unregisterPowerReceiver() {
|
||||
powerReceiver?.let { runCatching { context.unregisterReceiver(it) } }
|
||||
powerReceiver = null
|
||||
}
|
||||
|
||||
private fun registerLifecycleObserver() {
|
||||
if (lifecycleObserver != null) return
|
||||
val obs =
|
||||
object : DefaultLifecycleObserver {
|
||||
override fun onStart(owner: LifecycleOwner) = logLifecycle("app_foreground")
|
||||
|
||||
override fun onStop(owner: LifecycleOwner) = logLifecycle("app_background")
|
||||
}
|
||||
lifecycleObserver = obs
|
||||
scope.launch(Dispatchers.Main) {
|
||||
ProcessLifecycleOwner.get().lifecycle.addObserver(obs)
|
||||
}
|
||||
}
|
||||
|
||||
private fun unregisterLifecycleObserver() {
|
||||
val obs = lifecycleObserver ?: return
|
||||
lifecycleObserver = null
|
||||
scope.launch(Dispatchers.Main) {
|
||||
ProcessLifecycleOwner.get().lifecycle.removeObserver(obs)
|
||||
}
|
||||
}
|
||||
|
||||
private fun logLifecycle(event: String) {
|
||||
if (!enabled) return
|
||||
scope.launch { record("lifecycle", buildJsonObject { put("event", event) }) }
|
||||
}
|
||||
|
||||
private fun powerEvent(action: String): JsonObject =
|
||||
buildJsonObject {
|
||||
put("event", action.substringAfterLast('.'))
|
||||
addPowerFields(this)
|
||||
}
|
||||
|
||||
// Sonos/UPnP remote-vs-local desync fields. Only meaningful while a
|
||||
// remote route is active; zeroed otherwise so a stale RemotePlayerState
|
||||
// from a just-ended cast can't masquerade as live Sonos data (the
|
||||
// cast→phone handoff artifact). currentTrackUri is the desync ground
|
||||
// truth — it carries the track the speaker is actually streaming.
|
||||
private fun putSonos(
|
||||
builder: kotlinx.serialization.json.JsonObjectBuilder,
|
||||
casting: Boolean,
|
||||
) {
|
||||
builder.put("sonos_track", if (casting) remoteState.trackNumber else 0)
|
||||
builder.put("sonos_pos_ms", if (casting) remoteState.positionMs else 0)
|
||||
builder.put("sonos_playing", casting && remoteState.isPlaying)
|
||||
if (casting) builder.put("sonos_uri", remoteState.currentTrackUri)
|
||||
}
|
||||
|
||||
private fun addPowerFields(builder: kotlinx.serialization.json.JsonObjectBuilder) {
|
||||
val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager
|
||||
builder.put("doze", pm.isDeviceIdleMode)
|
||||
builder.put("screen_on", pm.isInteractive)
|
||||
builder.put("battery_opt_ignored", pm.isIgnoringBatteryOptimizations(context.packageName))
|
||||
}
|
||||
|
||||
private suspend fun record(
|
||||
kind: String,
|
||||
payload: JsonObject,
|
||||
) {
|
||||
runCatching {
|
||||
val id =
|
||||
dao.insert(
|
||||
DiagnosticEventEntity(
|
||||
kind = kind,
|
||||
occurredAtMillis = System.currentTimeMillis(),
|
||||
payloadJson = json.encodeToString(JsonObject.serializer(), payload),
|
||||
),
|
||||
)
|
||||
if (id % TRIM_INTERVAL == 0L) dao.trimToNewest(MAX_BUFFER)
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val HEARTBEAT_MS = 45_000L
|
||||
const val GATE_REFRESH_MS = 300_000L // re-pull /me every 5 min
|
||||
const val MAX_BUFFER = 5_000 // ring-buffer ceiling, oldest dropped
|
||||
const val TRIM_INTERVAL = 50L // trim every N inserts, not every one
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val HEARTBEAT_MS = 45_000L
|
||||
const val GATE_REFRESH_MS = 300_000L // re-pull /me every 5 min
|
||||
const val MAX_BUFFER = 5_000 // ring-buffer ceiling, oldest dropped
|
||||
const val TRIM_INTERVAL = 50L // trim every N inserts, not every one
|
||||
}
|
||||
}
|
||||
|
||||
+84
-75
@@ -38,84 +38,93 @@ import javax.inject.Singleton
|
||||
* uploader treats as success so the buffer drains either way.
|
||||
*/
|
||||
@Singleton
|
||||
class DiagnosticsUploader @Inject constructor(
|
||||
private val dao: DiagnosticEventDao,
|
||||
private val authStore: AuthStore,
|
||||
private val json: Json,
|
||||
@ApplicationScope private val scope: CoroutineScope,
|
||||
networkStatus: NetworkStatusController,
|
||||
retrofit: Retrofit,
|
||||
) {
|
||||
private val api: DiagnosticsApi = retrofit.create()
|
||||
private val mutex = Mutex()
|
||||
class DiagnosticsUploader
|
||||
@Inject
|
||||
constructor(
|
||||
private val dao: DiagnosticEventDao,
|
||||
private val authStore: AuthStore,
|
||||
private val json: Json,
|
||||
@ApplicationScope private val scope: CoroutineScope,
|
||||
networkStatus: NetworkStatusController,
|
||||
retrofit: Retrofit,
|
||||
) {
|
||||
private val api: DiagnosticsApi = retrofit.create()
|
||||
private val mutex = Mutex()
|
||||
|
||||
init {
|
||||
scope.launch {
|
||||
while (true) {
|
||||
delay(UPLOAD_INTERVAL_MS)
|
||||
drainSafe()
|
||||
init {
|
||||
scope.launch {
|
||||
while (true) {
|
||||
delay(UPLOAD_INTERVAL_MS)
|
||||
drainSafe()
|
||||
}
|
||||
}
|
||||
scope.launch {
|
||||
authStore.sessionCookie
|
||||
.filterNotNull()
|
||||
.distinctUntilChanged()
|
||||
.collect { drainSafe() }
|
||||
}
|
||||
scope.launch {
|
||||
networkStatus.state
|
||||
.map { it == ServerHealth.Healthy }
|
||||
.distinctUntilChanged()
|
||||
.filter { it }
|
||||
.collect { drainSafe() }
|
||||
}
|
||||
}
|
||||
scope.launch {
|
||||
authStore.sessionCookie.filterNotNull().distinctUntilChanged().collect { drainSafe() }
|
||||
|
||||
/** Coalesces concurrent triggers via tryLock — a drain in flight wins. */
|
||||
private suspend fun drainSafe() {
|
||||
// A trigger at launch can fire before the stored login has loaded;
|
||||
// wait for it, so a signed-in user is not read as signed out.
|
||||
authStore.awaitSessionHydrated()
|
||||
val clientId = authStore.clientId.value
|
||||
// Signed out / no client id yet → nothing to do. Single guard keeps
|
||||
// the return count within the detekt gate.
|
||||
if (authStore.sessionCookie.value.isNullOrEmpty() || clientId == null) return
|
||||
if (!mutex.tryLock()) return
|
||||
try {
|
||||
drain(clientId)
|
||||
} finally {
|
||||
mutex.unlock()
|
||||
}
|
||||
}
|
||||
scope.launch {
|
||||
networkStatus.state
|
||||
.map { it == ServerHealth.Healthy }
|
||||
.distinctUntilChanged()
|
||||
.filter { it }
|
||||
.collect { drainSafe() }
|
||||
|
||||
private suspend fun drain(clientId: String) {
|
||||
var more = true
|
||||
while (more) {
|
||||
val batch = runCatching { dao.takeBatch(BATCH_SIZE) }.getOrNull().orEmpty()
|
||||
val sent = batch.isNotEmpty() && runCatching { upload(clientId, batch) }.isSuccess
|
||||
if (sent) runCatching { dao.deleteByIds(batch.map { it.id }) }
|
||||
// Keep going only while a full batch sent cleanly; otherwise stop
|
||||
// (empty buffer, or a failure to retry on the next trigger).
|
||||
more = sent && batch.size >= BATCH_SIZE
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun upload(
|
||||
clientId: String,
|
||||
batch: List<DiagnosticEventEntity>,
|
||||
) {
|
||||
api.report(
|
||||
DiagnosticsReportRequest(
|
||||
clientId = clientId,
|
||||
appVersion = BuildConfig.VERSION_NAME,
|
||||
osVersion = "Android ${Build.VERSION.RELEASE} (${Build.MODEL})",
|
||||
events =
|
||||
batch.map { row ->
|
||||
DiagnosticEventWire(
|
||||
kind = row.kind,
|
||||
occurredAt = row.occurredAtMillis,
|
||||
payload = json.parseToJsonElement(row.payloadJson),
|
||||
)
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val UPLOAD_INTERVAL_MS = 60_000L
|
||||
const val BATCH_SIZE = 100
|
||||
}
|
||||
}
|
||||
|
||||
/** Coalesces concurrent triggers via tryLock — a drain in flight wins. */
|
||||
private suspend fun drainSafe() {
|
||||
// A trigger at launch can fire before the stored login has loaded;
|
||||
// wait for it, so a signed-in user is not read as signed out.
|
||||
authStore.awaitSessionHydrated()
|
||||
val clientId = authStore.clientId.value
|
||||
// Signed out / no client id yet → nothing to do. Single guard keeps
|
||||
// the return count within the detekt gate.
|
||||
if (authStore.sessionCookie.value.isNullOrEmpty() || clientId == null) return
|
||||
if (!mutex.tryLock()) return
|
||||
try {
|
||||
drain(clientId)
|
||||
} finally {
|
||||
mutex.unlock()
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun drain(clientId: String) {
|
||||
var more = true
|
||||
while (more) {
|
||||
val batch = runCatching { dao.takeBatch(BATCH_SIZE) }.getOrNull().orEmpty()
|
||||
val sent = batch.isNotEmpty() && runCatching { upload(clientId, batch) }.isSuccess
|
||||
if (sent) runCatching { dao.deleteByIds(batch.map { it.id }) }
|
||||
// Keep going only while a full batch sent cleanly; otherwise stop
|
||||
// (empty buffer, or a failure to retry on the next trigger).
|
||||
more = sent && batch.size >= BATCH_SIZE
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun upload(clientId: String, batch: List<DiagnosticEventEntity>) {
|
||||
api.report(
|
||||
DiagnosticsReportRequest(
|
||||
clientId = clientId,
|
||||
appVersion = BuildConfig.VERSION_NAME,
|
||||
osVersion = "Android ${Build.VERSION.RELEASE} (${Build.MODEL})",
|
||||
events = batch.map { row ->
|
||||
DiagnosticEventWire(
|
||||
kind = row.kind,
|
||||
occurredAt = row.occurredAtMillis,
|
||||
payload = json.parseToJsonElement(row.payloadJson),
|
||||
)
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val UPLOAD_INTERVAL_MS = 60_000L
|
||||
const val BATCH_SIZE = 100
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,157 +63,171 @@ private const val EVENTS_BUFFER_CAPACITY = 64
|
||||
* needing a separate path through here.
|
||||
*/
|
||||
@Singleton
|
||||
class EventsStream @Inject constructor(
|
||||
private val authStore: AuthStore,
|
||||
@ApplicationScope private val scope: CoroutineScope,
|
||||
private val okHttpClient: OkHttpClient,
|
||||
private val json: Json,
|
||||
private val connectivity: ConnectivityObserver,
|
||||
) {
|
||||
private val factory = EventSources.createFactory(okHttpClient)
|
||||
class EventsStream
|
||||
@Inject
|
||||
constructor(
|
||||
private val authStore: AuthStore,
|
||||
@ApplicationScope private val scope: CoroutineScope,
|
||||
private val okHttpClient: OkHttpClient,
|
||||
private val json: Json,
|
||||
private val connectivity: ConnectivityObserver,
|
||||
) {
|
||||
private val factory = EventSources.createFactory(okHttpClient)
|
||||
|
||||
private val emitter = MutableSharedFlow<LiveEvent>(
|
||||
replay = 0,
|
||||
extraBufferCapacity = EVENTS_BUFFER_CAPACITY,
|
||||
onBufferOverflow = BufferOverflow.DROP_OLDEST,
|
||||
)
|
||||
val events: SharedFlow<LiveEvent> = emitter.asSharedFlow()
|
||||
private val emitter =
|
||||
MutableSharedFlow<LiveEvent>(
|
||||
replay = 0,
|
||||
extraBufferCapacity = EVENTS_BUFFER_CAPACITY,
|
||||
onBufferOverflow = BufferOverflow.DROP_OLDEST,
|
||||
)
|
||||
val events: SharedFlow<LiveEvent> = emitter.asSharedFlow()
|
||||
|
||||
private val connectedState = MutableStateFlow(false)
|
||||
val connected: StateFlow<Boolean> = connectedState.asStateFlow()
|
||||
private val connectedState = MutableStateFlow(false)
|
||||
val connected: StateFlow<Boolean> = connectedState.asStateFlow()
|
||||
|
||||
private var currentSource: EventSource? = null
|
||||
@Volatile private var signedIn = false
|
||||
private var reconnectJob: Job? = null
|
||||
private var backoffMs = ReconnectBackoff.BASE_MS
|
||||
private var currentSource: EventSource? = null
|
||||
|
||||
init {
|
||||
scope.launch {
|
||||
authStore.sessionCookie
|
||||
.map { !it.isNullOrEmpty() }
|
||||
.distinctUntilChanged()
|
||||
.collect { isSignedIn ->
|
||||
signedIn = isSignedIn
|
||||
if (isSignedIn) {
|
||||
backoffMs = ReconnectBackoff.BASE_MS
|
||||
connect()
|
||||
} else {
|
||||
disconnect()
|
||||
@Volatile private var signedIn = false
|
||||
private var reconnectJob: Job? = null
|
||||
private var backoffMs = ReconnectBackoff.BASE_MS
|
||||
|
||||
init {
|
||||
scope.launch {
|
||||
authStore.sessionCookie
|
||||
.map { !it.isNullOrEmpty() }
|
||||
.distinctUntilChanged()
|
||||
.collect { isSignedIn ->
|
||||
signedIn = isSignedIn
|
||||
if (isSignedIn) {
|
||||
backoffMs = ReconnectBackoff.BASE_MS
|
||||
connect()
|
||||
} else {
|
||||
disconnect()
|
||||
}
|
||||
}
|
||||
}
|
||||
scope.launch {
|
||||
connectivity.online.collect { up -> if (up) reconnectNow() }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cuts a pending backoff short: reconnects at once and starts the ladder
|
||||
* over. For a network that has just come up, or the app coming to the
|
||||
* foreground, where waiting out a five-minute backoff would leave the
|
||||
* server unheard from for nothing. Does nothing while a stream is open or
|
||||
* opening.
|
||||
*/
|
||||
@Synchronized
|
||||
fun reconnectNow() {
|
||||
if (!signedIn || reconnectJob?.isActive != true) return
|
||||
backoffMs = ReconnectBackoff.BASE_MS
|
||||
connect()
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
private fun connect() {
|
||||
reconnectJob?.cancel()
|
||||
currentSource?.cancel()
|
||||
currentSource = openSubscription()
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
private fun disconnect() {
|
||||
reconnectJob?.cancel()
|
||||
currentSource?.cancel()
|
||||
currentSource = null
|
||||
connectedState.value = false
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedule a reconnect after the current backoff, jittered, then
|
||||
* double it (capped). No-op when signed out — sign-out's [disconnect]
|
||||
* cancels the pending job. A successful [Listener.onOpen] resets
|
||||
* the backoff to the floor.
|
||||
*/
|
||||
@Synchronized
|
||||
private fun scheduleReconnect() {
|
||||
connectedState.value = false
|
||||
if (!signedIn) return
|
||||
reconnectJob?.cancel()
|
||||
val waitMs = ReconnectBackoff.jittered(backoffMs)
|
||||
backoffMs = ReconnectBackoff.next(backoffMs)
|
||||
reconnectJob =
|
||||
scope.launch {
|
||||
delay(waitMs)
|
||||
if (signedIn) connect()
|
||||
}
|
||||
}
|
||||
scope.launch {
|
||||
connectivity.online.collect { up -> if (up) reconnectNow() }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cuts a pending backoff short: reconnects at once and starts the ladder
|
||||
* over. For a network that has just come up, or the app coming to the
|
||||
* foreground, where waiting out a five-minute backoff would leave the
|
||||
* server unheard from for nothing. Does nothing while a stream is open or
|
||||
* opening.
|
||||
*/
|
||||
@Synchronized
|
||||
fun reconnectNow() {
|
||||
if (!signedIn || reconnectJob?.isActive != true) return
|
||||
backoffMs = ReconnectBackoff.BASE_MS
|
||||
connect()
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
private fun connect() {
|
||||
reconnectJob?.cancel()
|
||||
currentSource?.cancel()
|
||||
currentSource = openSubscription()
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
private fun disconnect() {
|
||||
reconnectJob?.cancel()
|
||||
currentSource?.cancel()
|
||||
currentSource = null
|
||||
connectedState.value = false
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedule a reconnect after the current backoff, jittered, then
|
||||
* double it (capped). No-op when signed out — sign-out's [disconnect]
|
||||
* cancels the pending job. A successful [Listener.onOpen] resets
|
||||
* the backoff to the floor.
|
||||
*/
|
||||
@Synchronized
|
||||
private fun scheduleReconnect() {
|
||||
connectedState.value = false
|
||||
if (!signedIn) return
|
||||
reconnectJob?.cancel()
|
||||
val waitMs = ReconnectBackoff.jittered(backoffMs)
|
||||
backoffMs = ReconnectBackoff.next(backoffMs)
|
||||
reconnectJob = scope.launch {
|
||||
delay(waitMs)
|
||||
if (signedIn) connect()
|
||||
}
|
||||
}
|
||||
|
||||
private fun openSubscription(): EventSource {
|
||||
val request = Request.Builder()
|
||||
.url("http://placeholder.invalid$SSE_PATH")
|
||||
.header("Accept", "text/event-stream")
|
||||
.build()
|
||||
return factory.newEventSource(request, Listener())
|
||||
}
|
||||
|
||||
private inner class Listener : EventSourceListener() {
|
||||
override fun onOpen(eventSource: EventSource, response: Response) {
|
||||
backoffMs = ReconnectBackoff.BASE_MS
|
||||
connectedState.value = true
|
||||
private fun openSubscription(): EventSource {
|
||||
val request =
|
||||
Request
|
||||
.Builder()
|
||||
.url("http://placeholder.invalid$SSE_PATH")
|
||||
.header("Accept", "text/event-stream")
|
||||
.build()
|
||||
return factory.newEventSource(request, Listener())
|
||||
}
|
||||
|
||||
override fun onEvent(
|
||||
eventSource: EventSource,
|
||||
id: String?,
|
||||
type: String?,
|
||||
private inner class Listener : EventSourceListener() {
|
||||
override fun onOpen(
|
||||
eventSource: EventSource,
|
||||
response: Response,
|
||||
) {
|
||||
backoffMs = ReconnectBackoff.BASE_MS
|
||||
connectedState.value = true
|
||||
}
|
||||
|
||||
override fun onEvent(
|
||||
eventSource: EventSource,
|
||||
id: String?,
|
||||
type: String?,
|
||||
data: String,
|
||||
) {
|
||||
parseFrame(kind = type, data = data)?.let(emitter::tryEmit)
|
||||
}
|
||||
|
||||
override fun onClosed(eventSource: EventSource) {
|
||||
scheduleReconnect()
|
||||
}
|
||||
|
||||
override fun onFailure(
|
||||
eventSource: EventSource,
|
||||
t: Throwable?,
|
||||
response: Response?,
|
||||
) {
|
||||
scheduleReconnect()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses one SSE frame into a [LiveEvent]. The SSE `event:` field
|
||||
* carries the kind; the `data:` field is a JSON object with
|
||||
* `kind`/`user_id`/`data` (the kind in the payload is redundant
|
||||
* with the SSE event field — we prefer the SSE field, falling
|
||||
* back to the payload field). Heartbeat comment frames don't
|
||||
* reach here (okhttp-sse filters them).
|
||||
*/
|
||||
private fun parseFrame(
|
||||
kind: String?,
|
||||
data: String,
|
||||
) {
|
||||
parseFrame(kind = type, data = data)?.let(emitter::tryEmit)
|
||||
}
|
||||
|
||||
override fun onClosed(eventSource: EventSource) {
|
||||
scheduleReconnect()
|
||||
}
|
||||
|
||||
override fun onFailure(
|
||||
eventSource: EventSource,
|
||||
t: Throwable?,
|
||||
response: Response?,
|
||||
) {
|
||||
scheduleReconnect()
|
||||
}
|
||||
): LiveEvent? =
|
||||
try {
|
||||
val payload = json.parseToJsonElement(data).jsonObject
|
||||
val resolvedKind = kind ?: payload["kind"]?.jsonPrimitive?.contentOrNull
|
||||
if (resolvedKind.isNullOrEmpty()) {
|
||||
null
|
||||
} else {
|
||||
LiveEvent(
|
||||
kind = resolvedKind,
|
||||
userId = payload["user_id"]?.jsonPrimitive?.contentOrNull.orEmpty(),
|
||||
data = (payload["data"] as? JsonObject) ?: JsonObject(emptyMap()),
|
||||
)
|
||||
}
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught") _: Throwable,
|
||||
) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses one SSE frame into a [LiveEvent]. The SSE `event:` field
|
||||
* carries the kind; the `data:` field is a JSON object with
|
||||
* `kind`/`user_id`/`data` (the kind in the payload is redundant
|
||||
* with the SSE event field — we prefer the SSE field, falling
|
||||
* back to the payload field). Heartbeat comment frames don't
|
||||
* reach here (okhttp-sse filters them).
|
||||
*/
|
||||
private fun parseFrame(kind: String?, data: String): LiveEvent? = try {
|
||||
val payload = json.parseToJsonElement(data).jsonObject
|
||||
val resolvedKind = kind ?: payload["kind"]?.jsonPrimitive?.contentOrNull
|
||||
if (resolvedKind.isNullOrEmpty()) {
|
||||
null
|
||||
} else {
|
||||
LiveEvent(
|
||||
kind = resolvedKind,
|
||||
userId = payload["user_id"]?.jsonPrimitive?.contentOrNull.orEmpty(),
|
||||
data = (payload["data"] as? JsonObject) ?: JsonObject(emptyMap()),
|
||||
)
|
||||
}
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught") _: Throwable,
|
||||
) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,57 +28,58 @@ import javax.inject.Singleton
|
||||
* stream reconnects and the re-refresh avoids stale data flashing.
|
||||
*/
|
||||
@Singleton
|
||||
class LiveEventsDispatcher @Inject constructor(
|
||||
private val eventsStream: EventsStream,
|
||||
private val likes: LikesRepository,
|
||||
private val notifications: NotificationsRepository,
|
||||
@ApplicationScope private val scope: CoroutineScope,
|
||||
) : DefaultLifecycleObserver {
|
||||
class LiveEventsDispatcher
|
||||
@Inject
|
||||
constructor(
|
||||
private val eventsStream: EventsStream,
|
||||
private val likes: LikesRepository,
|
||||
private val notifications: NotificationsRepository,
|
||||
@ApplicationScope private val scope: CoroutineScope,
|
||||
) : DefaultLifecycleObserver {
|
||||
init {
|
||||
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
|
||||
scope.launch {
|
||||
eventsStream.events.collect { e -> handle(e) }
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
|
||||
scope.launch {
|
||||
eventsStream.events.collect { e -> handle(e) }
|
||||
private fun handle(event: LiveEvent) {
|
||||
when (event.kind) {
|
||||
"track.liked",
|
||||
"track.unliked",
|
||||
"album.liked",
|
||||
"album.unliked",
|
||||
"artist.liked",
|
||||
"artist.unliked",
|
||||
-> refreshLikes()
|
||||
// a contentless nudge; the inbox refetches its newest page.
|
||||
"notification.created" -> refreshNotifications()
|
||||
}
|
||||
// Other kinds (playlist.*, quarantine.*, request.status_changed,
|
||||
// scan.*) reach screen-scoped subscribers via EventsStream
|
||||
// directly. Add cross-screen cases here only when a new
|
||||
// Repository-level refresh becomes available.
|
||||
}
|
||||
|
||||
override fun onStart(owner: LifecycleOwner) {
|
||||
// App returned to the foreground. SSE will catch up but might
|
||||
// not have reconnected yet (it may be deep in its backoff, so it
|
||||
// is told to try now); flush the cross-screen refreshes
|
||||
// defensively.
|
||||
eventsStream.reconnectNow()
|
||||
refreshLikes()
|
||||
refreshNotifications()
|
||||
}
|
||||
|
||||
private fun refreshNotifications() {
|
||||
scope.launch {
|
||||
runCatching { notifications.refresh() }
|
||||
}
|
||||
}
|
||||
|
||||
private fun refreshLikes() {
|
||||
scope.launch {
|
||||
runCatching { likes.refreshIds() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun handle(event: LiveEvent) {
|
||||
when (event.kind) {
|
||||
"track.liked",
|
||||
"track.unliked",
|
||||
"album.liked",
|
||||
"album.unliked",
|
||||
"artist.liked",
|
||||
"artist.unliked",
|
||||
-> refreshLikes()
|
||||
// a contentless nudge; the inbox refetches its newest page.
|
||||
"notification.created" -> refreshNotifications()
|
||||
}
|
||||
// Other kinds (playlist.*, quarantine.*, request.status_changed,
|
||||
// scan.*) reach screen-scoped subscribers via EventsStream
|
||||
// directly. Add cross-screen cases here only when a new
|
||||
// Repository-level refresh becomes available.
|
||||
}
|
||||
|
||||
override fun onStart(owner: LifecycleOwner) {
|
||||
// App returned to the foreground. SSE will catch up but might
|
||||
// not have reconnected yet (it may be deep in its backoff, so it
|
||||
// is told to try now); flush the cross-screen refreshes
|
||||
// defensively.
|
||||
eventsStream.reconnectNow()
|
||||
refreshLikes()
|
||||
refreshNotifications()
|
||||
}
|
||||
|
||||
private fun refreshNotifications() {
|
||||
scope.launch {
|
||||
runCatching { notifications.refresh() }
|
||||
}
|
||||
}
|
||||
|
||||
private fun refreshLikes() {
|
||||
scope.launch {
|
||||
runCatching { likes.refreshIds() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,10 @@ internal object ReconnectBackoff {
|
||||
fun next(currentMs: Long): Long = (currentMs * 2).coerceAtMost(MAX_MS)
|
||||
|
||||
/** [ms] moved by up to a quarter either way. */
|
||||
fun jittered(ms: Long, random: Random = Random.Default): Long {
|
||||
fun jittered(
|
||||
ms: Long,
|
||||
random: Random = Random.Default,
|
||||
): Long {
|
||||
val spread = ms * JITTER
|
||||
return (ms + random.nextDouble(-spread, spread)).toLong()
|
||||
}
|
||||
|
||||
+26
-22
@@ -49,29 +49,33 @@ data class HistoryPage(
|
||||
* ordering/paging bookkeeping for no UX gain.
|
||||
*/
|
||||
@Singleton
|
||||
class HistoryRepository @Inject constructor(
|
||||
private val snapshotDao: CachedHistorySnapshotDao,
|
||||
private val json: Json,
|
||||
retrofit: Retrofit,
|
||||
) {
|
||||
private val api: HistoryApi = retrofit.create()
|
||||
class HistoryRepository
|
||||
@Inject
|
||||
constructor(
|
||||
private val snapshotDao: CachedHistorySnapshotDao,
|
||||
private val json: Json,
|
||||
retrofit: Retrofit,
|
||||
) {
|
||||
private val api: HistoryApi = retrofit.create()
|
||||
|
||||
fun observeHistory(): Flow<HistoryPage?> =
|
||||
snapshotDao.observe().map { row ->
|
||||
row?.let { json.decodeFromString<HistoryPageWire>(it.json).toDomain() }
|
||||
fun observeHistory(): Flow<HistoryPage?> =
|
||||
snapshotDao.observe().map { row ->
|
||||
row?.let { json.decodeFromString<HistoryPageWire>(it.json).toDomain() }
|
||||
}
|
||||
|
||||
/** Fetch the latest history and overwrite the cached snapshot. */
|
||||
suspend fun refresh() {
|
||||
val wire = api.getHistory()
|
||||
val blob = json.encodeToString(HistoryPageWire.serializer(), wire)
|
||||
snapshotDao.upsert(CachedHistorySnapshotEntity(json = blob))
|
||||
}
|
||||
|
||||
/** Fetch the latest history and overwrite the cached snapshot. */
|
||||
suspend fun refresh() {
|
||||
val wire = api.getHistory()
|
||||
val blob = json.encodeToString(HistoryPageWire.serializer(), wire)
|
||||
snapshotDao.upsert(CachedHistorySnapshotEntity(json = blob))
|
||||
}
|
||||
}
|
||||
|
||||
private fun HistoryPageWire.toDomain(): HistoryPage = HistoryPage(
|
||||
entries = events.map {
|
||||
HistoryEntry(id = it.id, playedAt = it.playedAt, track = it.track.toDomain())
|
||||
},
|
||||
hasMore = hasMore,
|
||||
)
|
||||
private fun HistoryPageWire.toDomain(): HistoryPage =
|
||||
HistoryPage(
|
||||
entries =
|
||||
events.map {
|
||||
HistoryEntry(id = it.id, playedAt = it.playedAt, track = it.track.toDomain())
|
||||
},
|
||||
hasMore = hasMore,
|
||||
)
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
package com.fabledsword.minstrel.history.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
@@ -26,12 +23,12 @@ import com.fabledsword.minstrel.history.data.HistoryRepository
|
||||
import com.fabledsword.minstrel.models.TrackRef
|
||||
import com.fabledsword.minstrel.player.PlayerController
|
||||
import com.fabledsword.minstrel.shared.UiState
|
||||
import com.fabledsword.minstrel.shared.widgets.TrackRow
|
||||
import com.fabledsword.minstrel.shared.widgets.EmptyState
|
||||
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
|
||||
import com.fabledsword.minstrel.shared.widgets.LoadingCentered
|
||||
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
|
||||
import com.fabledsword.minstrel.shared.widgets.TrackCoverThumb
|
||||
import com.fabledsword.minstrel.shared.widgets.TrackRow
|
||||
import com.fabledsword.minstrel.shared.widgets.trackactions.TrackActionsButton
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.Job
|
||||
@@ -56,56 +53,58 @@ private const val SHARE_STOP_TIMEOUT_MS = 5_000L
|
||||
// ─── ViewModel ───────────────────────────────────────────────────────
|
||||
|
||||
@HiltViewModel
|
||||
class HistoryTabViewModel @Inject constructor(
|
||||
private val repository: HistoryRepository,
|
||||
private val player: PlayerController,
|
||||
networkStatus: NetworkStatusController,
|
||||
) : ViewModel() {
|
||||
class HistoryTabViewModel
|
||||
@Inject
|
||||
constructor(
|
||||
private val repository: HistoryRepository,
|
||||
private val player: PlayerController,
|
||||
networkStatus: NetworkStatusController,
|
||||
) : ViewModel() {
|
||||
private val refreshError = MutableStateFlow<String?>(null)
|
||||
|
||||
private val refreshError = MutableStateFlow<String?>(null)
|
||||
/**
|
||||
* Cache-first: emits the cached snapshot instantly (paints from
|
||||
* disk on cold open), then SWR-refreshes underneath. Shows Error
|
||||
* only when there's nothing cached AND the refresh failed — a
|
||||
* failed refresh over a populated cache stays silent.
|
||||
*/
|
||||
val uiState: StateFlow<UiState<List<HistoryEntry>>> =
|
||||
combine(repository.observeHistory(), refreshError) { page, err ->
|
||||
when {
|
||||
page != null && page.entries.isNotEmpty() -> UiState.Success(page.entries)
|
||||
page != null -> UiState.Empty
|
||||
err != null -> UiState.Error(err)
|
||||
else -> UiState.Loading
|
||||
}
|
||||
}.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS),
|
||||
initialValue = UiState.Loading,
|
||||
)
|
||||
|
||||
/**
|
||||
* Cache-first: emits the cached snapshot instantly (paints from
|
||||
* disk on cold open), then SWR-refreshes underneath. Shows Error
|
||||
* only when there's nothing cached AND the refresh failed — a
|
||||
* failed refresh over a populated cache stays silent.
|
||||
*/
|
||||
val uiState: StateFlow<UiState<List<HistoryEntry>>> =
|
||||
combine(repository.observeHistory(), refreshError) { page, err ->
|
||||
when {
|
||||
page != null && page.entries.isNotEmpty() -> UiState.Success(page.entries)
|
||||
page != null -> UiState.Empty
|
||||
err != null -> UiState.Error(err)
|
||||
else -> UiState.Loading
|
||||
init {
|
||||
refresh()
|
||||
// Screen-level auto-recovery: re-pull when server
|
||||
// health returns, so a load that failed offline heals unprompted.
|
||||
viewModelScope.launch {
|
||||
networkStatus.recoveries().collect { refresh() }
|
||||
}
|
||||
}.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS),
|
||||
initialValue = UiState.Loading,
|
||||
)
|
||||
}
|
||||
|
||||
init {
|
||||
refresh()
|
||||
// Screen-level auto-recovery: re-pull when server
|
||||
// health returns, so a load that failed offline heals unprompted.
|
||||
viewModelScope.launch {
|
||||
networkStatus.recoveries().collect { refresh() }
|
||||
fun refresh(): Job =
|
||||
viewModelScope.launch {
|
||||
refreshError.value = null
|
||||
runCatching { repository.refresh() }
|
||||
.onFailure { refreshError.value = ErrorCopy.fromThrowable(it) }
|
||||
}
|
||||
|
||||
/** Plays the tapped track on its own. */
|
||||
fun playTrack(track: TrackRef) {
|
||||
if (track.streamUrl.isEmpty()) return
|
||||
player.setQueue(listOf(track), initialIndex = 0, source = "history")
|
||||
}
|
||||
}
|
||||
|
||||
fun refresh(): Job = viewModelScope.launch {
|
||||
refreshError.value = null
|
||||
runCatching { repository.refresh() }
|
||||
.onFailure { refreshError.value = ErrorCopy.fromThrowable(it) }
|
||||
}
|
||||
|
||||
/** Plays the tapped track on its own. */
|
||||
fun playTrack(track: TrackRef) {
|
||||
if (track.streamUrl.isEmpty()) return
|
||||
player.setQueue(listOf(track), initialIndex = 0, source = "history")
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Composable ──────────────────────────────────────────────────────
|
||||
|
||||
@Composable
|
||||
@@ -121,22 +120,25 @@ fun HistoryTab(
|
||||
PullToRefreshScaffold(onRefresh = { viewModel.refresh().join() }) {
|
||||
when (val s = state) {
|
||||
UiState.Loading -> LoadingCentered()
|
||||
UiState.Empty -> EmptyState(
|
||||
title = "No listening history yet",
|
||||
body = "Play something — your recent plays will show up here.",
|
||||
)
|
||||
is UiState.Error -> ErrorRetry(
|
||||
title = "Couldn't load history",
|
||||
message = s.message,
|
||||
onRetry = { viewModel.refresh() },
|
||||
)
|
||||
is UiState.Success -> HistoryList(
|
||||
entries = s.data,
|
||||
playingTrackId = playingTrackId,
|
||||
onPlay = viewModel::playTrack,
|
||||
onNavigateToAlbum = onNavigateToAlbum,
|
||||
onNavigateToArtist = onNavigateToArtist,
|
||||
)
|
||||
UiState.Empty ->
|
||||
EmptyState(
|
||||
title = "No listening history yet",
|
||||
body = "Play something — your recent plays will show up here.",
|
||||
)
|
||||
is UiState.Error ->
|
||||
ErrorRetry(
|
||||
title = "Couldn't load history",
|
||||
message = s.message,
|
||||
onRetry = { viewModel.refresh() },
|
||||
)
|
||||
is UiState.Success ->
|
||||
HistoryList(
|
||||
entries = s.data,
|
||||
playingTrackId = playingTrackId,
|
||||
onPlay = viewModel::playTrack,
|
||||
onNavigateToAlbum = onNavigateToAlbum,
|
||||
onNavigateToArtist = onNavigateToArtist,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -215,8 +217,9 @@ private const val DAYS_PER_WEEK = 7L
|
||||
* up the row over malformed timestamps.
|
||||
*/
|
||||
private fun relativeTime(iso: String): String {
|
||||
val parsed = runCatching { OffsetDateTime.parse(iso) }.getOrNull()
|
||||
?: return iso
|
||||
val parsed =
|
||||
runCatching { OffsetDateTime.parse(iso) }.getOrNull()
|
||||
?: return iso
|
||||
val local = parsed.atZoneSameInstant(ZoneId.systemDefault())
|
||||
val now = OffsetDateTime.now(ZoneId.systemDefault())
|
||||
val minutes = ChronoUnit.MINUTES.between(local, now)
|
||||
|
||||
@@ -44,163 +44,167 @@ import javax.inject.Singleton
|
||||
// Per-section observe accessors (one per Home row) inflate the function
|
||||
// count past detekt's 11 default — accessor density, not complexity.
|
||||
@Suppress("TooManyFunctions")
|
||||
class HomeRepository @Inject constructor(
|
||||
private val homeIndexDao: CachedHomeIndexDao,
|
||||
private val metadataProvider: MetadataProvider,
|
||||
private val prewarmer: HomeArtistPrewarmer,
|
||||
retrofit: Retrofit,
|
||||
) {
|
||||
private val api: HomeApi = retrofit.create()
|
||||
private val meApi: MeApi = retrofit.create()
|
||||
class HomeRepository
|
||||
@Inject
|
||||
constructor(
|
||||
private val homeIndexDao: CachedHomeIndexDao,
|
||||
private val metadataProvider: MetadataProvider,
|
||||
private val prewarmer: HomeArtistPrewarmer,
|
||||
retrofit: Retrofit,
|
||||
) {
|
||||
private val api: HomeApi = retrofit.create()
|
||||
private val meApi: MeApi = retrofit.create()
|
||||
|
||||
/**
|
||||
* Caller's system-playlist build state for the Home placeholder
|
||||
* cards. One-shot GET; the caller refreshes alongside the index.
|
||||
*/
|
||||
suspend fun getSystemPlaylistsStatus(): SystemPlaylistsStatus =
|
||||
meApi.getSystemPlaylistsStatus().let {
|
||||
SystemPlaylistsStatus(
|
||||
inFlight = it.inFlight,
|
||||
lastRunAt = it.lastRunAt,
|
||||
lastError = it.lastError,
|
||||
/**
|
||||
* Caller's system-playlist build state for the Home placeholder
|
||||
* cards. One-shot GET; the caller refreshes alongside the index.
|
||||
*/
|
||||
suspend fun getSystemPlaylistsStatus(): SystemPlaylistsStatus =
|
||||
meApi.getSystemPlaylistsStatus().let {
|
||||
SystemPlaylistsStatus(
|
||||
inFlight = it.inFlight,
|
||||
lastRunAt = it.lastRunAt,
|
||||
lastError = it.lastError,
|
||||
)
|
||||
}
|
||||
|
||||
fun observeRecentlyAddedAlbums(): Flow<List<HomeTile<AlbumRef>>> =
|
||||
observeAlbumSection(SECTION_RECENTLY_ADDED_ALBUMS)
|
||||
|
||||
fun observeRediscoverAlbums(): Flow<List<HomeTile<AlbumRef>>> = observeAlbumSection(SECTION_REDISCOVER_ALBUMS)
|
||||
|
||||
fun observeRediscoverArtists(): Flow<List<HomeTile<ArtistRef>>> =
|
||||
observeArtistSection(SECTION_REDISCOVER_ARTISTS)
|
||||
|
||||
fun observeMostPlayedTracks(): Flow<List<HomeTile<TrackRef>>> = observeTrackSection(SECTION_MOST_PLAYED_TRACKS)
|
||||
|
||||
fun observeLastPlayedArtists(): Flow<List<HomeTile<ArtistRef>>> =
|
||||
observeArtistSection(SECTION_LAST_PLAYED_ARTISTS)
|
||||
|
||||
fun observeYouMightLikeAlbums(): Flow<List<HomeTile<AlbumRef>>> =
|
||||
observeAlbumSection(SECTION_YOU_MIGHT_LIKE_ALBUMS)
|
||||
|
||||
fun observeYouMightLikeArtists(): Flow<List<HomeTile<ArtistRef>>> =
|
||||
observeArtistSection(SECTION_YOU_MIGHT_LIKE_ARTISTS)
|
||||
|
||||
/** True when the index cache already has content on screen to protect. */
|
||||
suspend fun hasCachedIndex(): Boolean = homeIndexDao.hasAny()
|
||||
|
||||
/**
|
||||
* Pulls /api/home/index and swaps every cached_home_index section in
|
||||
* a single transaction, then pre-warms the top artists. Missing
|
||||
* entity rows hydrate via the on-miss path.
|
||||
*
|
||||
* One transaction for all seven sections is deliberate: Room notifies
|
||||
* observers once, on commit, so Home swaps from the old content to
|
||||
* the new in a single emission. Per-section, un-transacted writes
|
||||
* would make every row visibly collapse to empty and refill, one
|
||||
* after another.
|
||||
*/
|
||||
suspend fun refreshIndex() {
|
||||
val wire = api.getHomeIndex()
|
||||
homeIndexDao.replaceSections(
|
||||
sections = ALL_SECTIONS,
|
||||
rows =
|
||||
rowsFor(SECTION_RECENTLY_ADDED_ALBUMS, "album", wire.recentlyAddedAlbums) +
|
||||
rowsFor(SECTION_REDISCOVER_ALBUMS, "album", wire.rediscoverAlbums) +
|
||||
rowsFor(SECTION_REDISCOVER_ARTISTS, "artist", wire.rediscoverArtists) +
|
||||
rowsFor(SECTION_MOST_PLAYED_TRACKS, "track", wire.mostPlayedTracks) +
|
||||
rowsFor(SECTION_LAST_PLAYED_ARTISTS, "artist", wire.lastPlayedArtists) +
|
||||
rowsFor(SECTION_YOU_MIGHT_LIKE_ALBUMS, "album", wire.youMightLikeAlbums) +
|
||||
rowsFor(SECTION_YOU_MIGHT_LIKE_ARTISTS, "artist", wire.youMightLikeArtists),
|
||||
)
|
||||
prewarmer.warm(
|
||||
wire.rediscoverArtists + wire.lastPlayedArtists + wire.youMightLikeArtists,
|
||||
)
|
||||
}
|
||||
|
||||
fun observeRecentlyAddedAlbums(): Flow<List<HomeTile<AlbumRef>>> =
|
||||
observeAlbumSection(SECTION_RECENTLY_ADDED_ALBUMS)
|
||||
private fun rowsFor(
|
||||
section: String,
|
||||
entityType: String,
|
||||
ids: List<String>,
|
||||
): List<CachedHomeIndexEntity> =
|
||||
ids.mapIndexed { index, id ->
|
||||
CachedHomeIndexEntity(
|
||||
section = section,
|
||||
position = index,
|
||||
entityType = entityType,
|
||||
entityId = id,
|
||||
)
|
||||
}
|
||||
|
||||
fun observeRediscoverAlbums(): Flow<List<HomeTile<AlbumRef>>> =
|
||||
observeAlbumSection(SECTION_REDISCOVER_ALBUMS)
|
||||
/**
|
||||
* The section's ordered entity ids, deduplicated.
|
||||
*
|
||||
* Room re-runs the query on every write to `cached_home_index` — and
|
||||
* `CachedHomeIndexEntity.fetchedAt` is stamped fresh each time — so
|
||||
* comparing whole rows would call every rewrite a change. Comparing
|
||||
* the id list instead means a section whose contents didn't actually
|
||||
* move never restarts the `flatMapLatest` below, which would
|
||||
* otherwise tear down and rebuild all of its tiles' hydration flows
|
||||
* and flicker unchanged tiles.
|
||||
*/
|
||||
private fun observeSectionIds(section: String): Flow<List<String>> =
|
||||
homeIndexDao
|
||||
.observeBySection(section)
|
||||
.map { rows -> rows.map { it.entityId } }
|
||||
.distinctUntilChanged()
|
||||
|
||||
fun observeRediscoverArtists(): Flow<List<HomeTile<ArtistRef>>> =
|
||||
observeArtistSection(SECTION_REDISCOVER_ARTISTS)
|
||||
|
||||
fun observeMostPlayedTracks(): Flow<List<HomeTile<TrackRef>>> =
|
||||
observeTrackSection(SECTION_MOST_PLAYED_TRACKS)
|
||||
|
||||
fun observeLastPlayedArtists(): Flow<List<HomeTile<ArtistRef>>> =
|
||||
observeArtistSection(SECTION_LAST_PLAYED_ARTISTS)
|
||||
|
||||
fun observeYouMightLikeAlbums(): Flow<List<HomeTile<AlbumRef>>> =
|
||||
observeAlbumSection(SECTION_YOU_MIGHT_LIKE_ALBUMS)
|
||||
|
||||
fun observeYouMightLikeArtists(): Flow<List<HomeTile<ArtistRef>>> =
|
||||
observeArtistSection(SECTION_YOU_MIGHT_LIKE_ARTISTS)
|
||||
|
||||
/** True when the index cache already has content on screen to protect. */
|
||||
suspend fun hasCachedIndex(): Boolean = homeIndexDao.hasAny()
|
||||
|
||||
/**
|
||||
* Pulls /api/home/index and swaps every cached_home_index section in
|
||||
* a single transaction, then pre-warms the top artists. Missing
|
||||
* entity rows hydrate via the on-miss path.
|
||||
*
|
||||
* One transaction for all seven sections is deliberate: Room notifies
|
||||
* observers once, on commit, so Home swaps from the old content to
|
||||
* the new in a single emission. Per-section, un-transacted writes
|
||||
* would make every row visibly collapse to empty and refill, one
|
||||
* after another.
|
||||
*/
|
||||
suspend fun refreshIndex() {
|
||||
val wire = api.getHomeIndex()
|
||||
homeIndexDao.replaceSections(
|
||||
sections = ALL_SECTIONS,
|
||||
rows = rowsFor(SECTION_RECENTLY_ADDED_ALBUMS, "album", wire.recentlyAddedAlbums) +
|
||||
rowsFor(SECTION_REDISCOVER_ALBUMS, "album", wire.rediscoverAlbums) +
|
||||
rowsFor(SECTION_REDISCOVER_ARTISTS, "artist", wire.rediscoverArtists) +
|
||||
rowsFor(SECTION_MOST_PLAYED_TRACKS, "track", wire.mostPlayedTracks) +
|
||||
rowsFor(SECTION_LAST_PLAYED_ARTISTS, "artist", wire.lastPlayedArtists) +
|
||||
rowsFor(SECTION_YOU_MIGHT_LIKE_ALBUMS, "album", wire.youMightLikeAlbums) +
|
||||
rowsFor(SECTION_YOU_MIGHT_LIKE_ARTISTS, "artist", wire.youMightLikeArtists),
|
||||
)
|
||||
prewarmer.warm(
|
||||
wire.rediscoverArtists + wire.lastPlayedArtists + wire.youMightLikeArtists,
|
||||
)
|
||||
}
|
||||
|
||||
private fun rowsFor(
|
||||
section: String,
|
||||
entityType: String,
|
||||
ids: List<String>,
|
||||
): List<CachedHomeIndexEntity> = ids.mapIndexed { index, id ->
|
||||
CachedHomeIndexEntity(
|
||||
section = section,
|
||||
position = index,
|
||||
entityType = entityType,
|
||||
entityId = id,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The section's ordered entity ids, deduplicated.
|
||||
*
|
||||
* Room re-runs the query on every write to `cached_home_index` — and
|
||||
* `CachedHomeIndexEntity.fetchedAt` is stamped fresh each time — so
|
||||
* comparing whole rows would call every rewrite a change. Comparing
|
||||
* the id list instead means a section whose contents didn't actually
|
||||
* move never restarts the `flatMapLatest` below, which would
|
||||
* otherwise tear down and rebuild all of its tiles' hydration flows
|
||||
* and flicker unchanged tiles.
|
||||
*/
|
||||
private fun observeSectionIds(section: String): Flow<List<String>> =
|
||||
homeIndexDao.observeBySection(section)
|
||||
.map { rows -> rows.map { it.entityId } }
|
||||
.distinctUntilChanged()
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
private fun observeAlbumSection(section: String): Flow<List<HomeTile<AlbumRef>>> =
|
||||
observeSectionIds(section).flatMapLatest { ids ->
|
||||
if (ids.isEmpty()) {
|
||||
flowOf(emptyList())
|
||||
} else {
|
||||
combine(ids.map { metadataProvider.observeAlbum(it) }) { refs ->
|
||||
ids.mapIndexed { i, id -> HomeTile(id, refs[i]) }
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
private fun observeAlbumSection(section: String): Flow<List<HomeTile<AlbumRef>>> =
|
||||
observeSectionIds(section).flatMapLatest { ids ->
|
||||
if (ids.isEmpty()) {
|
||||
flowOf(emptyList())
|
||||
} else {
|
||||
combine(ids.map { metadataProvider.observeAlbum(it) }) { refs ->
|
||||
ids.mapIndexed { i, id -> HomeTile(id, refs[i]) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
private fun observeArtistSection(section: String): Flow<List<HomeTile<ArtistRef>>> =
|
||||
observeSectionIds(section).flatMapLatest { ids ->
|
||||
if (ids.isEmpty()) {
|
||||
flowOf(emptyList())
|
||||
} else {
|
||||
combine(ids.map { metadataProvider.observeArtist(it) }) { refs ->
|
||||
ids.mapIndexed { i, id -> HomeTile(id, refs[i]) }
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
private fun observeArtistSection(section: String): Flow<List<HomeTile<ArtistRef>>> =
|
||||
observeSectionIds(section).flatMapLatest { ids ->
|
||||
if (ids.isEmpty()) {
|
||||
flowOf(emptyList())
|
||||
} else {
|
||||
combine(ids.map { metadataProvider.observeArtist(it) }) { refs ->
|
||||
ids.mapIndexed { i, id -> HomeTile(id, refs[i]) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
private fun observeTrackSection(section: String): Flow<List<HomeTile<TrackRef>>> =
|
||||
observeSectionIds(section).flatMapLatest { ids ->
|
||||
if (ids.isEmpty()) {
|
||||
flowOf(emptyList())
|
||||
} else {
|
||||
combine(ids.map { metadataProvider.observeTrack(it) }) { refs ->
|
||||
ids.mapIndexed { i, id -> HomeTile(id, refs[i]) }
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
private fun observeTrackSection(section: String): Flow<List<HomeTile<TrackRef>>> =
|
||||
observeSectionIds(section).flatMapLatest { ids ->
|
||||
if (ids.isEmpty()) {
|
||||
flowOf(emptyList())
|
||||
} else {
|
||||
combine(ids.map { metadataProvider.observeTrack(it) }) { refs ->
|
||||
ids.mapIndexed { i, id -> HomeTile(id, refs[i]) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val SECTION_RECENTLY_ADDED_ALBUMS = "recently_added_albums"
|
||||
const val SECTION_REDISCOVER_ALBUMS = "rediscover_albums"
|
||||
const val SECTION_REDISCOVER_ARTISTS = "rediscover_artists"
|
||||
const val SECTION_MOST_PLAYED_TRACKS = "most_played_tracks"
|
||||
const val SECTION_LAST_PLAYED_ARTISTS = "last_played_artists"
|
||||
const val SECTION_YOU_MIGHT_LIKE_ALBUMS = "you_might_like_albums"
|
||||
const val SECTION_YOU_MIGHT_LIKE_ARTISTS = "you_might_like_artists"
|
||||
|
||||
/** Every section [refreshIndex] owns — the unit of one atomic swap. */
|
||||
val ALL_SECTIONS =
|
||||
listOf(
|
||||
SECTION_RECENTLY_ADDED_ALBUMS,
|
||||
SECTION_REDISCOVER_ALBUMS,
|
||||
SECTION_REDISCOVER_ARTISTS,
|
||||
SECTION_MOST_PLAYED_TRACKS,
|
||||
SECTION_LAST_PLAYED_ARTISTS,
|
||||
SECTION_YOU_MIGHT_LIKE_ALBUMS,
|
||||
SECTION_YOU_MIGHT_LIKE_ARTISTS,
|
||||
)
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val SECTION_RECENTLY_ADDED_ALBUMS = "recently_added_albums"
|
||||
const val SECTION_REDISCOVER_ALBUMS = "rediscover_albums"
|
||||
const val SECTION_REDISCOVER_ARTISTS = "rediscover_artists"
|
||||
const val SECTION_MOST_PLAYED_TRACKS = "most_played_tracks"
|
||||
const val SECTION_LAST_PLAYED_ARTISTS = "last_played_artists"
|
||||
const val SECTION_YOU_MIGHT_LIKE_ALBUMS = "you_might_like_albums"
|
||||
const val SECTION_YOU_MIGHT_LIKE_ARTISTS = "you_might_like_artists"
|
||||
|
||||
/** Every section [refreshIndex] owns — the unit of one atomic swap. */
|
||||
val ALL_SECTIONS = listOf(
|
||||
SECTION_RECENTLY_ADDED_ALBUMS,
|
||||
SECTION_REDISCOVER_ALBUMS,
|
||||
SECTION_REDISCOVER_ARTISTS,
|
||||
SECTION_MOST_PLAYED_TRACKS,
|
||||
SECTION_LAST_PLAYED_ARTISTS,
|
||||
SECTION_YOU_MIGHT_LIKE_ALBUMS,
|
||||
SECTION_YOU_MIGHT_LIKE_ARTISTS,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+180
-156
@@ -17,6 +17,11 @@ import retrofit2.create
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
// LibraryRepository owns reads + refreshes for three entity families
|
||||
// (artists / albums / tracks) plus shuffle. Function count scales with
|
||||
// entity-family count; splitting into per-family repos would
|
||||
// scatter the shared dao + retrofit plumbing for no real gain.
|
||||
|
||||
/**
|
||||
* Cache-first reads of artists/albums/tracks. The Room DAOs are the
|
||||
* source of truth ViewModels observe; refresh* methods pull from the
|
||||
@@ -27,183 +32,202 @@ import javax.inject.Singleton
|
||||
* own their interfaces (see NetworkModule), so there is no @Provides
|
||||
* per endpoint — fewer Hilt bindings, locality of reference.
|
||||
*/
|
||||
// LibraryRepository owns reads + refreshes for three entity families
|
||||
// (artists / albums / tracks) plus shuffle. Function count scales with
|
||||
// entity-family count; splitting into per-family repos would
|
||||
// scatter the shared dao + retrofit plumbing for no real gain.
|
||||
@Suppress("TooManyFunctions")
|
||||
@Singleton
|
||||
class LibraryRepository @Inject constructor(
|
||||
private val artistDao: CachedArtistDao,
|
||||
private val albumDao: CachedAlbumDao,
|
||||
private val trackDao: CachedTrackDao,
|
||||
retrofit: Retrofit,
|
||||
) {
|
||||
private val api: LibraryApi = retrofit.create()
|
||||
class LibraryRepository
|
||||
@Inject
|
||||
constructor(
|
||||
private val artistDao: CachedArtistDao,
|
||||
private val albumDao: CachedAlbumDao,
|
||||
private val trackDao: CachedTrackDao,
|
||||
retrofit: Retrofit,
|
||||
) {
|
||||
private val api: LibraryApi = retrofit.create()
|
||||
|
||||
// ---- Reads (Flow, cache-first; the cache is the source of truth) ----
|
||||
// ---- Reads (Flow, cache-first; the cache is the source of truth) ----
|
||||
|
||||
// Joins each artist to its first cached album (by sort title) so the
|
||||
// tile cover derives from /api/albums/{id}/cover — cached_artists
|
||||
// stores no cover and sync carries none.
|
||||
fun observeArtists(): Flow<List<ArtistRef>> =
|
||||
combine(artistDao.observeAll(), albumDao.observeAll()) { artists, albums ->
|
||||
val firstAlbumByArtist = albums
|
||||
.groupBy { it.artistId }
|
||||
.mapValues { (_, list) -> list.minByOrNull { it.sortTitle }?.id ?: "" }
|
||||
artists.map { it.toDomain(coverAlbumId = firstAlbumByArtist[it.id] ?: "") }
|
||||
// Joins each artist to its first cached album (by sort title) so the
|
||||
// tile cover derives from /api/albums/{id}/cover — cached_artists
|
||||
// stores no cover and sync carries none.
|
||||
fun observeArtists(): Flow<List<ArtistRef>> =
|
||||
combine(artistDao.observeAll(), albumDao.observeAll()) { artists, albums ->
|
||||
val firstAlbumByArtist =
|
||||
albums
|
||||
.groupBy { it.artistId }
|
||||
.mapValues { (_, list) -> list.minByOrNull { it.sortTitle }?.id ?: "" }
|
||||
artists.map { it.toDomain(coverAlbumId = firstAlbumByArtist[it.id] ?: "") }
|
||||
}
|
||||
|
||||
fun observeAlbums(): Flow<List<AlbumRef>> = albumDao.observeAll().map { rows -> rows.map { it.toDomain() } }
|
||||
|
||||
fun observeAlbumsForArtist(artistId: String): Flow<List<AlbumRef>> =
|
||||
albumDao.observeByArtist(artistId).map { rows -> rows.map { it.toDomain() } }
|
||||
|
||||
fun observeTracksForAlbum(albumId: String): Flow<List<TrackRef>> =
|
||||
trackDao.observeByAlbum(albumId).map { rows -> rows.map { it.toDomain() } }
|
||||
|
||||
// ---- Single-shot lookups ----
|
||||
|
||||
suspend fun getArtist(id: String): ArtistRef? = artistDao.getById(id)?.toDomain()
|
||||
|
||||
suspend fun getAlbum(id: String): AlbumRef? = albumDao.getById(id)?.toDomain()
|
||||
|
||||
suspend fun getTrack(id: String): TrackRef? = trackDao.getById(id)?.toDomain()
|
||||
|
||||
// ---- Server refreshes (sync-style writes; errors propagate) ----
|
||||
|
||||
/**
|
||||
* Pulls the full artist detail (ArtistRef + albums), persists both,
|
||||
* and returns the in-memory snapshot. Lets the ArtistDetail screen
|
||||
* render from the wire response without the Room round-trip.
|
||||
*/
|
||||
suspend fun refreshArtistDetail(id: String): ArtistDetailRef {
|
||||
val wire = api.getArtistDetail(id)
|
||||
artistDao.upsertAll(listOf(wire.toArtistEntity()))
|
||||
albumDao.upsertAll(wire.albums.map { it.toEntity() })
|
||||
return ArtistDetailRef(
|
||||
artist =
|
||||
ArtistRef(
|
||||
id = wire.id,
|
||||
name = wire.name,
|
||||
sortName = wire.sortName,
|
||||
albumCount = wire.albumCount,
|
||||
coverUrl = wire.coverUrl,
|
||||
),
|
||||
albums = wire.albums.map { it.toDomain() },
|
||||
)
|
||||
}
|
||||
|
||||
fun observeAlbums(): Flow<List<AlbumRef>> =
|
||||
albumDao.observeAll().map { rows -> rows.map { it.toDomain() } }
|
||||
/**
|
||||
* Pulls every track for an artist (across all their albums). Used
|
||||
* by the "Play artist" button on the ArtistDetail header. No
|
||||
* persistence — the response is consumed straight into a player
|
||||
* queue.
|
||||
*/
|
||||
suspend fun fetchArtistTracks(id: String): List<TrackRef> = api.getArtistTracks(id).map { it.toDomain() }
|
||||
|
||||
fun observeAlbumsForArtist(artistId: String): Flow<List<AlbumRef>> =
|
||||
albumDao.observeByArtist(artistId).map { rows -> rows.map { it.toDomain() } }
|
||||
/**
|
||||
* Pulls related artists for the ArtistDetail "Similar artists"
|
||||
* strip. Network-only — non-critical UI, callers swallow failures
|
||||
* and render nothing rather than blocking the screen.
|
||||
*/
|
||||
suspend fun fetchSimilarArtists(id: String): List<ArtistRef> = api.getSimilarArtists(id).map { it.toDomain() }
|
||||
|
||||
fun observeTracksForAlbum(albumId: String): Flow<List<TrackRef>> =
|
||||
trackDao.observeByAlbum(albumId).map { rows -> rows.map { it.toDomain() } }
|
||||
/**
|
||||
* Pulls the artist's top tracks for the ArtistDetail "Top tracks"
|
||||
* panel. Network-only; tapping a row plays this exact list as a
|
||||
* queue, so no persistence is needed.
|
||||
*/
|
||||
suspend fun fetchArtistTopTracks(id: String): List<TrackRef> = api.getArtistTopTracks(id).map { it.toDomain() }
|
||||
|
||||
// ---- Single-shot lookups ----
|
||||
/**
|
||||
* Pulls the album detail (AlbumRef + tracks), persists both, and
|
||||
* returns the in-memory snapshot. Lets the AlbumDetail screen
|
||||
* render immediately from the wire response without waiting for
|
||||
* the Room round-trip.
|
||||
*/
|
||||
suspend fun refreshAlbumDetail(id: String): AlbumDetailRef {
|
||||
val wire = api.getAlbumDetail(id)
|
||||
albumDao.upsertAll(listOf(wire.toAlbumEntity()))
|
||||
trackDao.upsertAll(wire.tracks.map { it.toEntity() })
|
||||
return AlbumDetailRef(
|
||||
album =
|
||||
AlbumRef(
|
||||
id = wire.id,
|
||||
title = wire.title,
|
||||
artistId = wire.artistId,
|
||||
sortTitle = wire.sortTitle,
|
||||
artistName = wire.artistName,
|
||||
year = wire.year,
|
||||
trackCount = wire.trackCount,
|
||||
durationSec = wire.durationSec,
|
||||
coverUrl = wire.coverUrl,
|
||||
),
|
||||
tracks = wire.tracks.map { it.toDomain() },
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun getArtist(id: String): ArtistRef? = artistDao.getById(id)?.toDomain()
|
||||
/** Track detail — single track, mainly for the hydration queue. */
|
||||
suspend fun refreshTrack(id: String) {
|
||||
val wire = api.getTrack(id)
|
||||
trackDao.upsertAll(listOf(wire.toEntity()))
|
||||
}
|
||||
|
||||
suspend fun getAlbum(id: String): AlbumRef? = albumDao.getById(id)?.toDomain()
|
||||
/**
|
||||
* "Shuffle all" — server picks random tracks across the entire
|
||||
* library. Backs the Library AppBar Shuffle button. No cache hit;
|
||||
* the user-facing semantics are "give me something fresh".
|
||||
*/
|
||||
suspend fun shuffleLibrary(limit: Int = SHUFFLE_DEFAULT_LIMIT): List<TrackRef> =
|
||||
api.shuffleLibrary(limit = limit).map { it.toDomain() }
|
||||
|
||||
suspend fun getTrack(id: String): TrackRef? = trackDao.getById(id)?.toDomain()
|
||||
// ---- Browse axes ----
|
||||
//
|
||||
// Server-backed rather than cache-first, unlike everything above: the
|
||||
// server's index leaves out tracks whose files are missing and is the
|
||||
// one the web client shows. See LibraryApi for why the cache's own
|
||||
// missing mark is not used to build it locally.
|
||||
|
||||
// ---- Server refreshes (sync-style writes; errors propagate) ----
|
||||
/** Genre index, ordered by track count then name (server order). */
|
||||
suspend fun genres(): List<GenreCount> =
|
||||
api.getGenres().map {
|
||||
GenreCount(genre = it.genre, trackCount = it.trackCount)
|
||||
}
|
||||
|
||||
/**
|
||||
* Pulls the full artist detail (ArtistRef + albums), persists both,
|
||||
* and returns the in-memory snapshot. Lets the ArtistDetail screen
|
||||
* render from the wire response without the Room round-trip.
|
||||
*/
|
||||
suspend fun refreshArtistDetail(id: String): ArtistDetailRef {
|
||||
val wire = api.getArtistDetail(id)
|
||||
artistDao.upsertAll(listOf(wire.toArtistEntity()))
|
||||
albumDao.upsertAll(wire.albums.map { it.toEntity() })
|
||||
return ArtistDetailRef(
|
||||
artist = ArtistRef(
|
||||
id = wire.id,
|
||||
name = wire.name,
|
||||
sortName = wire.sortName,
|
||||
albumCount = wire.albumCount,
|
||||
coverUrl = wire.coverUrl,
|
||||
),
|
||||
albums = wire.albums.map { it.toDomain() },
|
||||
)
|
||||
/** Year index, newest first. Albums with no release date are absent. */
|
||||
suspend fun albumYears(): List<YearCount> =
|
||||
api.getAlbumYears().map {
|
||||
YearCount(year = it.year, albumCount = it.albumCount)
|
||||
}
|
||||
|
||||
/** One page of albums carrying [genre] on any track. */
|
||||
suspend fun albumsByGenre(
|
||||
genre: String,
|
||||
limit: Int,
|
||||
offset: Int,
|
||||
): AlbumPage {
|
||||
val page = api.getAlbumsByGenre(genre = genre, limit = limit, offset = offset)
|
||||
return AlbumPage(items = page.items.map { it.toDomain() }, total = page.total)
|
||||
}
|
||||
|
||||
/** One page of albums released in [year]. */
|
||||
suspend fun albumsByYear(
|
||||
year: Int,
|
||||
limit: Int,
|
||||
offset: Int,
|
||||
): AlbumPage {
|
||||
val page =
|
||||
api.getAlbumsByYear(
|
||||
yearFrom = year,
|
||||
yearTo = year,
|
||||
limit = limit,
|
||||
offset = offset,
|
||||
)
|
||||
return AlbumPage(items = page.items.map { it.toDomain() }, total = page.total)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val SHUFFLE_DEFAULT_LIMIT = 100
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pulls every track for an artist (across all their albums). Used
|
||||
* by the "Play artist" button on the ArtistDetail header. No
|
||||
* persistence — the response is consumed straight into a player
|
||||
* queue.
|
||||
*/
|
||||
suspend fun fetchArtistTracks(id: String): List<TrackRef> =
|
||||
api.getArtistTracks(id).map { it.toDomain() }
|
||||
|
||||
/**
|
||||
* Pulls related artists for the ArtistDetail "Similar artists"
|
||||
* strip. Network-only — non-critical UI, callers swallow failures
|
||||
* and render nothing rather than blocking the screen.
|
||||
*/
|
||||
suspend fun fetchSimilarArtists(id: String): List<ArtistRef> =
|
||||
api.getSimilarArtists(id).map { it.toDomain() }
|
||||
|
||||
/**
|
||||
* Pulls the artist's top tracks for the ArtistDetail "Top tracks"
|
||||
* panel. Network-only; tapping a row plays this exact list as a
|
||||
* queue, so no persistence is needed.
|
||||
*/
|
||||
suspend fun fetchArtistTopTracks(id: String): List<TrackRef> =
|
||||
api.getArtistTopTracks(id).map { it.toDomain() }
|
||||
|
||||
/**
|
||||
* Pulls the album detail (AlbumRef + tracks), persists both, and
|
||||
* returns the in-memory snapshot. Lets the AlbumDetail screen
|
||||
* render immediately from the wire response without waiting for
|
||||
* the Room round-trip.
|
||||
*/
|
||||
suspend fun refreshAlbumDetail(id: String): AlbumDetailRef {
|
||||
val wire = api.getAlbumDetail(id)
|
||||
albumDao.upsertAll(listOf(wire.toAlbumEntity()))
|
||||
trackDao.upsertAll(wire.tracks.map { it.toEntity() })
|
||||
return AlbumDetailRef(
|
||||
album = AlbumRef(
|
||||
id = wire.id,
|
||||
title = wire.title,
|
||||
artistId = wire.artistId,
|
||||
sortTitle = wire.sortTitle,
|
||||
artistName = wire.artistName,
|
||||
year = wire.year,
|
||||
trackCount = wire.trackCount,
|
||||
durationSec = wire.durationSec,
|
||||
coverUrl = wire.coverUrl,
|
||||
),
|
||||
tracks = wire.tracks.map { it.toDomain() },
|
||||
)
|
||||
}
|
||||
|
||||
/** Track detail — single track, mainly for the hydration queue. */
|
||||
suspend fun refreshTrack(id: String) {
|
||||
val wire = api.getTrack(id)
|
||||
trackDao.upsertAll(listOf(wire.toEntity()))
|
||||
}
|
||||
|
||||
/**
|
||||
* "Shuffle all" — server picks random tracks across the entire
|
||||
* library. Backs the Library AppBar Shuffle button. No cache hit;
|
||||
* the user-facing semantics are "give me something fresh".
|
||||
*/
|
||||
suspend fun shuffleLibrary(limit: Int = SHUFFLE_DEFAULT_LIMIT): List<TrackRef> =
|
||||
api.shuffleLibrary(limit = limit).map { it.toDomain() }
|
||||
|
||||
// ---- Browse axes ----
|
||||
//
|
||||
// Server-backed rather than cache-first, unlike everything above: the
|
||||
// server's index leaves out tracks whose files are missing and is the
|
||||
// one the web client shows. See LibraryApi for why the cache's own
|
||||
// missing mark is not used to build it locally.
|
||||
|
||||
/** Genre index, ordered by track count then name (server order). */
|
||||
suspend fun genres(): List<GenreCount> =
|
||||
api.getGenres().map { GenreCount(genre = it.genre, trackCount = it.trackCount) }
|
||||
|
||||
/** Year index, newest first. Albums with no release date are absent. */
|
||||
suspend fun albumYears(): List<YearCount> =
|
||||
api.getAlbumYears().map { YearCount(year = it.year, albumCount = it.albumCount) }
|
||||
|
||||
/** One page of albums carrying [genre] on any track. */
|
||||
suspend fun albumsByGenre(genre: String, limit: Int, offset: Int): AlbumPage {
|
||||
val page = api.getAlbumsByGenre(genre = genre, limit = limit, offset = offset)
|
||||
return AlbumPage(items = page.items.map { it.toDomain() }, total = page.total)
|
||||
}
|
||||
|
||||
/** One page of albums released in [year]. */
|
||||
suspend fun albumsByYear(year: Int, limit: Int, offset: Int): AlbumPage {
|
||||
val page = api.getAlbumsByYear(
|
||||
yearFrom = year,
|
||||
yearTo = year,
|
||||
limit = limit,
|
||||
offset = offset,
|
||||
)
|
||||
return AlbumPage(items = page.items.map { it.toDomain() }, total = page.total)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val SHUFFLE_DEFAULT_LIMIT = 100
|
||||
}
|
||||
}
|
||||
|
||||
/** One row of the genre index. */
|
||||
data class GenreCount(val genre: String, val trackCount: Int)
|
||||
data class GenreCount(
|
||||
val genre: String,
|
||||
val trackCount: Int,
|
||||
)
|
||||
|
||||
/** One row of the year index. */
|
||||
data class YearCount(val year: Int, val albumCount: Int)
|
||||
data class YearCount(
|
||||
val year: Int,
|
||||
val albumCount: Int,
|
||||
)
|
||||
|
||||
/**
|
||||
* A page of albums plus the server's total for the whole filter, which is
|
||||
* what lets the UI say how many are left rather than just offering "more".
|
||||
*/
|
||||
data class AlbumPage(val items: List<AlbumRef>, val total: Int)
|
||||
data class AlbumPage(
|
||||
val items: List<AlbumRef>,
|
||||
val total: Int,
|
||||
)
|
||||
|
||||
+19
-17
@@ -2,6 +2,7 @@
|
||||
|
||||
package com.fabledsword.minstrel.library.ui
|
||||
|
||||
import androidx.compose.animation.Crossfade
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
@@ -12,7 +13,6 @@ import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.animation.Crossfade
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
@@ -29,7 +29,6 @@ import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
@@ -51,12 +50,12 @@ import com.fabledsword.minstrel.shared.formatDuration
|
||||
import com.fabledsword.minstrel.shared.plural
|
||||
import com.fabledsword.minstrel.shared.widgets.CoverFallbackIcon
|
||||
import com.fabledsword.minstrel.shared.widgets.CoverTile
|
||||
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
|
||||
import com.fabledsword.minstrel.shared.widgets.TrackRow
|
||||
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
|
||||
import com.fabledsword.minstrel.shared.widgets.LikeButton
|
||||
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
|
||||
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
|
||||
import com.fabledsword.minstrel.shared.widgets.SkeletonTrackRow
|
||||
import com.fabledsword.minstrel.shared.widgets.TrackRow
|
||||
import com.fabledsword.minstrel.shared.widgets.trackactions.TrackActionsButton
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@@ -95,11 +94,12 @@ fun AlbumDetailScreen(
|
||||
}
|
||||
}
|
||||
|
||||
private fun titleFor(state: AlbumDetailUiState): String = when (state) {
|
||||
is AlbumDetailUiState.Success -> state.detail.album.title
|
||||
is AlbumDetailUiState.Loading -> state.seed?.title ?: "Album"
|
||||
is AlbumDetailUiState.Error -> "Album"
|
||||
}
|
||||
private fun titleFor(state: AlbumDetailUiState): String =
|
||||
when (state) {
|
||||
is AlbumDetailUiState.Success -> state.detail.album.title
|
||||
is AlbumDetailUiState.Loading -> state.seed?.title ?: "Album"
|
||||
is AlbumDetailUiState.Error -> "Album"
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AlbumDetailStateContent(
|
||||
@@ -115,11 +115,12 @@ private fun AlbumDetailStateContent(
|
||||
when (val s = state) {
|
||||
is AlbumDetailUiState.Loading ->
|
||||
if (s.seed != null) SeededAlbumLoading(s.seed) else SkeletonTrackList()
|
||||
is AlbumDetailUiState.Error -> ErrorRetry(
|
||||
title = "Couldn't load album",
|
||||
message = s.message,
|
||||
onRetry = { viewModel.refresh() },
|
||||
)
|
||||
is AlbumDetailUiState.Error ->
|
||||
ErrorRetry(
|
||||
title = "Couldn't load album",
|
||||
message = s.message,
|
||||
onRetry = { viewModel.refresh() },
|
||||
)
|
||||
is AlbumDetailUiState.Success -> {
|
||||
val albumLiked by viewModel.albumLiked.collectAsStateWithLifecycle()
|
||||
val likedTrackIds by viewModel.likedTrackIds
|
||||
@@ -209,9 +210,10 @@ private fun AlbumHeader(
|
||||
onToggleAlbumLike: () -> Unit,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(16.dp),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Row(
|
||||
|
||||
+110
-96
@@ -28,112 +28,126 @@ import javax.inject.Inject
|
||||
private const val SHARE_STOP_TIMEOUT_MS = 5_000L
|
||||
|
||||
sealed interface AlbumDetailUiState {
|
||||
data class Loading(val seed: AlbumRef? = null) : AlbumDetailUiState
|
||||
data class Success(val detail: AlbumDetailRef) : AlbumDetailUiState
|
||||
data class Error(val message: String) : AlbumDetailUiState
|
||||
data class Loading(
|
||||
val seed: AlbumRef? = null,
|
||||
) : AlbumDetailUiState
|
||||
|
||||
data class Success(
|
||||
val detail: AlbumDetailRef,
|
||||
) : AlbumDetailUiState
|
||||
|
||||
data class Error(
|
||||
val message: String,
|
||||
) : AlbumDetailUiState
|
||||
}
|
||||
|
||||
@HiltViewModel
|
||||
class AlbumDetailViewModel @Inject constructor(
|
||||
private val repository: LibraryRepository,
|
||||
private val likes: LikesRepository,
|
||||
private val player: PlayerController,
|
||||
private val seedCache: DetailSeedCache,
|
||||
networkStatus: NetworkStatusController,
|
||||
savedStateHandle: SavedStateHandle,
|
||||
) : ViewModel() {
|
||||
class AlbumDetailViewModel
|
||||
@Inject
|
||||
constructor(
|
||||
private val repository: LibraryRepository,
|
||||
private val likes: LikesRepository,
|
||||
private val player: PlayerController,
|
||||
private val seedCache: DetailSeedCache,
|
||||
networkStatus: NetworkStatusController,
|
||||
savedStateHandle: SavedStateHandle,
|
||||
) : ViewModel() {
|
||||
private val route: AlbumDetail = savedStateHandle.toRoute()
|
||||
val albumId: String = route.id
|
||||
|
||||
private val route: AlbumDetail = savedStateHandle.toRoute()
|
||||
val albumId: String = route.id
|
||||
private val internal =
|
||||
MutableStateFlow<AlbumDetailUiState>(AlbumDetailUiState.Loading())
|
||||
val uiState: StateFlow<AlbumDetailUiState> = internal.asStateFlow()
|
||||
|
||||
private val internal =
|
||||
MutableStateFlow<AlbumDetailUiState>(AlbumDetailUiState.Loading())
|
||||
val uiState: StateFlow<AlbumDetailUiState> = internal.asStateFlow()
|
||||
val albumLiked: StateFlow<Boolean> =
|
||||
likes
|
||||
.observeIsLiked(LikesRepository.ENTITY_ALBUM, albumId)
|
||||
.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS),
|
||||
initialValue = false,
|
||||
)
|
||||
|
||||
val albumLiked: StateFlow<Boolean> =
|
||||
likes.observeIsLiked(LikesRepository.ENTITY_ALBUM, albumId)
|
||||
.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS),
|
||||
initialValue = false,
|
||||
)
|
||||
val likedTrackIds: StateFlow<Set<String>> =
|
||||
likes
|
||||
.observeLikedTrackIds()
|
||||
.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS),
|
||||
initialValue = emptySet(),
|
||||
)
|
||||
|
||||
val likedTrackIds: StateFlow<Set<String>> =
|
||||
likes.observeLikedTrackIds()
|
||||
.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS),
|
||||
initialValue = emptySet(),
|
||||
)
|
||||
|
||||
init {
|
||||
refresh()
|
||||
// Screen-level auto-recovery: a detail that failed to
|
||||
// load while the server was unreachable re-fetches when health
|
||||
// returns, so coming back to the screen shows content, not an error.
|
||||
viewModelScope.launch {
|
||||
networkStatus.recoveries().collect {
|
||||
if (internal.value is AlbumDetailUiState.Error) refresh()
|
||||
init {
|
||||
refresh()
|
||||
// Screen-level auto-recovery: a detail that failed to
|
||||
// load while the server was unreachable re-fetches when health
|
||||
// returns, so coming back to the screen shows content, not an error.
|
||||
viewModelScope.launch {
|
||||
networkStatus.recoveries().collect {
|
||||
if (internal.value is AlbumDetailUiState.Error) refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun refresh(): Job = viewModelScope.launch {
|
||||
val carried = when (val cur = internal.value) {
|
||||
is AlbumDetailUiState.Loading -> cur.seed
|
||||
is AlbumDetailUiState.Success -> cur.detail.album
|
||||
is AlbumDetailUiState.Error -> null
|
||||
fun refresh(): Job =
|
||||
viewModelScope.launch {
|
||||
val carried =
|
||||
when (val cur = internal.value) {
|
||||
is AlbumDetailUiState.Loading -> cur.seed
|
||||
is AlbumDetailUiState.Success -> cur.detail.album
|
||||
is AlbumDetailUiState.Error -> null
|
||||
}
|
||||
internal.value = AlbumDetailUiState.Loading(carried ?: seedCache.peekAlbum(albumId))
|
||||
try {
|
||||
val detail = repository.refreshAlbumDetail(albumId)
|
||||
internal.value = AlbumDetailUiState.Success(detail)
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
||||
) {
|
||||
internal.value = AlbumDetailUiState.Error(ErrorCopy.fromThrowable(e))
|
||||
}
|
||||
}
|
||||
|
||||
/** Play the album starting at [startTrackId] (or the first track when null). */
|
||||
fun play(startTrackId: String?) {
|
||||
val detail = (internal.value as? AlbumDetailUiState.Success)?.detail ?: return
|
||||
if (detail.tracks.isEmpty()) return
|
||||
val startIndex =
|
||||
detail.tracks
|
||||
.indexOfFirst { it.id == startTrackId }
|
||||
.coerceAtLeast(0)
|
||||
player.setQueue(
|
||||
tracks = detail.tracks,
|
||||
initialIndex = startIndex,
|
||||
source = "album:${detail.album.id}",
|
||||
)
|
||||
}
|
||||
internal.value = AlbumDetailUiState.Loading(carried ?: seedCache.peekAlbum(albumId))
|
||||
try {
|
||||
val detail = repository.refreshAlbumDetail(albumId)
|
||||
internal.value = AlbumDetailUiState.Success(detail)
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
||||
) {
|
||||
internal.value = AlbumDetailUiState.Error(ErrorCopy.fromThrowable(e))
|
||||
|
||||
/**
|
||||
* Play the album in shuffled order. Pre-shuffles the list and hands
|
||||
* the result to the player — matches the PlaylistDetail shuffle
|
||||
* pattern. A future refinement could use Media3's
|
||||
* `setShuffleModeEnabled` for play-then-shuffle without disturbing
|
||||
* the original queue ordering.
|
||||
*/
|
||||
fun shuffle() {
|
||||
val detail = (internal.value as? AlbumDetailUiState.Success)?.detail ?: return
|
||||
if (detail.tracks.isEmpty()) return
|
||||
player.setQueue(
|
||||
tracks = detail.tracks.shuffled(),
|
||||
initialIndex = 0,
|
||||
source = "album:${detail.album.id}",
|
||||
)
|
||||
}
|
||||
|
||||
fun toggleLikeAlbum() {
|
||||
val desired = !albumLiked.value
|
||||
viewModelScope.launch {
|
||||
likes.toggleLike(LikesRepository.ENTITY_ALBUM, albumId, desired)
|
||||
}
|
||||
}
|
||||
|
||||
fun toggleLikeTrack(trackId: String) {
|
||||
viewModelScope.launch { likes.toggleTrackLike(trackId, likedTrackIds.value) }
|
||||
}
|
||||
}
|
||||
|
||||
/** Play the album starting at [startTrackId] (or the first track when null). */
|
||||
fun play(startTrackId: String?) {
|
||||
val detail = (internal.value as? AlbumDetailUiState.Success)?.detail ?: return
|
||||
if (detail.tracks.isEmpty()) return
|
||||
val startIndex = detail.tracks
|
||||
.indexOfFirst { it.id == startTrackId }
|
||||
.coerceAtLeast(0)
|
||||
player.setQueue(
|
||||
tracks = detail.tracks,
|
||||
initialIndex = startIndex,
|
||||
source = "album:${detail.album.id}",
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Play the album in shuffled order. Pre-shuffles the list and hands
|
||||
* the result to the player — matches the PlaylistDetail shuffle
|
||||
* pattern. A future refinement could use Media3's
|
||||
* `setShuffleModeEnabled` for play-then-shuffle without disturbing
|
||||
* the original queue ordering.
|
||||
*/
|
||||
fun shuffle() {
|
||||
val detail = (internal.value as? AlbumDetailUiState.Success)?.detail ?: return
|
||||
if (detail.tracks.isEmpty()) return
|
||||
player.setQueue(
|
||||
tracks = detail.tracks.shuffled(),
|
||||
initialIndex = 0,
|
||||
source = "album:${detail.album.id}",
|
||||
)
|
||||
}
|
||||
|
||||
fun toggleLikeAlbum() {
|
||||
val desired = !albumLiked.value
|
||||
viewModelScope.launch {
|
||||
likes.toggleLike(LikesRepository.ENTITY_ALBUM, albumId, desired)
|
||||
}
|
||||
}
|
||||
|
||||
fun toggleLikeTrack(trackId: String) {
|
||||
viewModelScope.launch { likes.toggleTrackLike(trackId, likedTrackIds.value) }
|
||||
}
|
||||
}
|
||||
|
||||
+40
-32
@@ -20,16 +20,15 @@ import androidx.compose.foundation.lazy.grid.GridCells
|
||||
import androidx.compose.foundation.lazy.grid.GridItemSpan
|
||||
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
|
||||
import androidx.compose.foundation.lazy.grid.items
|
||||
import androidx.compose.foundation.lazy.items as lazyItems
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
@@ -58,14 +57,15 @@ import com.fabledsword.minstrel.nav.ArtistDetail
|
||||
import com.fabledsword.minstrel.shared.formatDuration
|
||||
import com.fabledsword.minstrel.shared.plural
|
||||
import com.fabledsword.minstrel.shared.widgets.CoverFallbackIcon
|
||||
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
|
||||
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
|
||||
import com.fabledsword.minstrel.shared.widgets.HorizontalScrollRow
|
||||
import com.fabledsword.minstrel.shared.widgets.LikeButton
|
||||
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
|
||||
import com.fabledsword.minstrel.shared.widgets.ServerImage
|
||||
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
|
||||
import com.fabledsword.minstrel.shared.widgets.SkeletonAlbumTile
|
||||
import com.fabledsword.minstrel.shared.widgets.TrackRow
|
||||
import androidx.compose.foundation.lazy.items as lazyItems
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
@@ -111,11 +111,12 @@ fun ArtistDetailScreen(
|
||||
} else {
|
||||
SkeletonArtistAlbumsGrid()
|
||||
}
|
||||
is ArtistDetailUiState.Error -> ErrorRetry(
|
||||
title = "Couldn't load artist",
|
||||
message = s.message,
|
||||
onRetry = { viewModel.refresh() },
|
||||
)
|
||||
is ArtistDetailUiState.Error ->
|
||||
ErrorRetry(
|
||||
title = "Couldn't load artist",
|
||||
message = s.message,
|
||||
onRetry = { viewModel.refresh() },
|
||||
)
|
||||
is ArtistDetailUiState.Success ->
|
||||
ArtistSuccessBody(s, viewModel, playerViewModel, navController)
|
||||
}
|
||||
@@ -145,11 +146,12 @@ private fun ArtistSuccessBody(
|
||||
)
|
||||
}
|
||||
|
||||
private fun titleFor(state: ArtistDetailUiState): String = when (state) {
|
||||
is ArtistDetailUiState.Success -> state.detail.artist.name
|
||||
is ArtistDetailUiState.Loading -> state.seed?.name ?: "Artist"
|
||||
is ArtistDetailUiState.Error -> "Artist"
|
||||
}
|
||||
private fun titleFor(state: ArtistDetailUiState): String =
|
||||
when (state) {
|
||||
is ArtistDetailUiState.Success -> state.detail.artist.name
|
||||
is ArtistDetailUiState.Loading -> state.seed?.name ?: "Artist"
|
||||
is ArtistDetailUiState.Error -> "Artist"
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ArtistBody(
|
||||
@@ -278,9 +280,10 @@ private fun ArtistHeader(
|
||||
onToggleLike: () -> Unit,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(16.dp),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
@@ -311,20 +314,25 @@ private fun ArtistHeader(
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ArtistAvatar(artist: ArtistRef, fallbackAlbumId: String? = null) {
|
||||
private fun ArtistAvatar(
|
||||
artist: ArtistRef,
|
||||
fallbackAlbumId: String? = null,
|
||||
) {
|
||||
// Server coverUrl wins; otherwise use the first loaded album's
|
||||
// cover, the same rule the server applies. Bare Lucide.User only
|
||||
// when neither exists.
|
||||
val model = when {
|
||||
artist.coverUrl.isNotEmpty() -> artist.coverUrl
|
||||
fallbackAlbumId != null -> albumCoverPath(fallbackAlbumId)
|
||||
else -> null
|
||||
}
|
||||
val model =
|
||||
when {
|
||||
artist.coverUrl.isNotEmpty() -> artist.coverUrl
|
||||
fallbackAlbumId != null -> albumCoverPath(fallbackAlbumId)
|
||||
else -> null
|
||||
}
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(96.dp)
|
||||
.clip(CircleShape)
|
||||
.background(MaterialTheme.colorScheme.surfaceVariant),
|
||||
modifier =
|
||||
Modifier
|
||||
.size(96.dp)
|
||||
.clip(CircleShape)
|
||||
.background(MaterialTheme.colorScheme.surfaceVariant),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
ServerImage(
|
||||
@@ -335,15 +343,15 @@ private fun ArtistAvatar(artist: ArtistRef, fallbackAlbumId: String? = null) {
|
||||
}
|
||||
}
|
||||
|
||||
private fun albumCountLine(artist: ArtistRef): String =
|
||||
plural(artist.albumCount, "album", "albums")
|
||||
private fun albumCountLine(artist: ArtistRef): String = plural(artist.albumCount, "album", "albums")
|
||||
|
||||
@Composable
|
||||
private fun EmptyAlbumsHint() {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(24.dp),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Text(
|
||||
|
||||
+123
-113
@@ -33,136 +33,146 @@ import javax.inject.Inject
|
||||
private const val SHARE_STOP_TIMEOUT_MS = 5_000L
|
||||
|
||||
sealed interface ArtistDetailUiState {
|
||||
data class Loading(val seed: ArtistRef? = null) : ArtistDetailUiState
|
||||
data class Loading(
|
||||
val seed: ArtistRef? = null,
|
||||
) : ArtistDetailUiState
|
||||
|
||||
data class Success(
|
||||
val detail: ArtistDetailRef,
|
||||
val similarArtists: List<ArtistRef> = emptyList(),
|
||||
val topTracks: List<TrackRef> = emptyList(),
|
||||
) : ArtistDetailUiState
|
||||
data class Error(val message: String) : ArtistDetailUiState
|
||||
|
||||
data class Error(
|
||||
val message: String,
|
||||
) : ArtistDetailUiState
|
||||
}
|
||||
|
||||
@HiltViewModel
|
||||
class ArtistDetailViewModel @Inject constructor(
|
||||
private val repository: LibraryRepository,
|
||||
private val likes: LikesRepository,
|
||||
private val player: PlayerController,
|
||||
private val seedCache: DetailSeedCache,
|
||||
networkStatus: NetworkStatusController,
|
||||
savedStateHandle: SavedStateHandle,
|
||||
) : ViewModel() {
|
||||
class ArtistDetailViewModel
|
||||
@Inject
|
||||
constructor(
|
||||
private val repository: LibraryRepository,
|
||||
private val likes: LikesRepository,
|
||||
private val player: PlayerController,
|
||||
private val seedCache: DetailSeedCache,
|
||||
networkStatus: NetworkStatusController,
|
||||
savedStateHandle: SavedStateHandle,
|
||||
) : ViewModel() {
|
||||
private val route: ArtistDetail = savedStateHandle.toRoute()
|
||||
val artistId: String = route.id
|
||||
|
||||
private val route: ArtistDetail = savedStateHandle.toRoute()
|
||||
val artistId: String = route.id
|
||||
private val internal =
|
||||
MutableStateFlow<ArtistDetailUiState>(ArtistDetailUiState.Loading())
|
||||
val uiState: StateFlow<ArtistDetailUiState> = internal.asStateFlow()
|
||||
|
||||
private val internal =
|
||||
MutableStateFlow<ArtistDetailUiState>(ArtistDetailUiState.Loading())
|
||||
val uiState: StateFlow<ArtistDetailUiState> = internal.asStateFlow()
|
||||
/** Transient one-shot messages for the screen-level snackbar (e.g. Play-button failure). */
|
||||
private val transientMessagesChannel = Channel<String>(Channel.BUFFERED)
|
||||
val transientMessages: Flow<String> = transientMessagesChannel.receiveAsFlow()
|
||||
|
||||
/** Transient one-shot messages for the screen-level snackbar (e.g. Play-button failure). */
|
||||
private val transientMessagesChannel = Channel<String>(Channel.BUFFERED)
|
||||
val transientMessages: Flow<String> = transientMessagesChannel.receiveAsFlow()
|
||||
val artistLiked: StateFlow<Boolean> =
|
||||
likes
|
||||
.observeIsLiked(LikesRepository.ENTITY_ARTIST, artistId)
|
||||
.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS),
|
||||
initialValue = false,
|
||||
)
|
||||
|
||||
val artistLiked: StateFlow<Boolean> =
|
||||
likes.observeIsLiked(LikesRepository.ENTITY_ARTIST, artistId)
|
||||
.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS),
|
||||
initialValue = false,
|
||||
)
|
||||
|
||||
init {
|
||||
refresh()
|
||||
// Screen-level auto-recovery. From Error, redo the
|
||||
// whole load; from Success, re-pull just the secondary sections —
|
||||
// their fetch failures are swallowed to emptyList, so a dead zone
|
||||
// during the first load leaves them permanently absent otherwise.
|
||||
viewModelScope.launch {
|
||||
networkStatus.recoveries().collect {
|
||||
when (internal.value) {
|
||||
is ArtistDetailUiState.Error -> refresh()
|
||||
is ArtistDetailUiState.Success -> loadSecondarySections()
|
||||
is ArtistDetailUiState.Loading -> Unit
|
||||
init {
|
||||
refresh()
|
||||
// Screen-level auto-recovery. From Error, redo the
|
||||
// whole load; from Success, re-pull just the secondary sections —
|
||||
// their fetch failures are swallowed to emptyList, so a dead zone
|
||||
// during the first load leaves them permanently absent otherwise.
|
||||
viewModelScope.launch {
|
||||
networkStatus.recoveries().collect {
|
||||
when (internal.value) {
|
||||
is ArtistDetailUiState.Error -> refresh()
|
||||
is ArtistDetailUiState.Success -> loadSecondarySections()
|
||||
is ArtistDetailUiState.Loading -> Unit
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun toggleLikeArtist() {
|
||||
val desired = !artistLiked.value
|
||||
viewModelScope.launch {
|
||||
likes.toggleLike(LikesRepository.ENTITY_ARTIST, artistId, desired)
|
||||
}
|
||||
}
|
||||
|
||||
fun refresh(): Job = viewModelScope.launch {
|
||||
val carried = when (val cur = internal.value) {
|
||||
is ArtistDetailUiState.Loading -> cur.seed
|
||||
is ArtistDetailUiState.Success -> cur.detail.artist
|
||||
is ArtistDetailUiState.Error -> null
|
||||
}
|
||||
internal.value = ArtistDetailUiState.Loading(carried ?: seedCache.peekArtist(artistId))
|
||||
try {
|
||||
val detail = repository.refreshArtistDetail(artistId)
|
||||
internal.value = ArtistDetailUiState.Success(detail)
|
||||
loadSecondarySections()
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
||||
) {
|
||||
internal.value = ArtistDetailUiState.Error(ErrorCopy.fromThrowable(e))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pulls the non-critical "Similar artists" + "Top tracks" sections
|
||||
* and folds them into the live Success state. Each failure is
|
||||
* swallowed (logged only) — these sections render absent rather than
|
||||
* blocking, so the core artist view never depends on them.
|
||||
*/
|
||||
private suspend fun loadSecondarySections() {
|
||||
val similar = sectionOrEmpty { repository.fetchSimilarArtists(artistId) }
|
||||
val top = sectionOrEmpty { repository.fetchArtistTopTracks(artistId) }
|
||||
val current = internal.value
|
||||
if (current is ArtistDetailUiState.Success) {
|
||||
internal.value = current.copy(similarArtists = similar, topTracks = top)
|
||||
}
|
||||
}
|
||||
|
||||
private inline fun <T> sectionOrEmpty(block: () -> List<T>): List<T> =
|
||||
try {
|
||||
block()
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
||||
) {
|
||||
Timber.w(e, "Artist secondary section fetch failed for %s", artistId)
|
||||
emptyList()
|
||||
fun toggleLikeArtist() {
|
||||
val desired = !artistLiked.value
|
||||
viewModelScope.launch {
|
||||
likes.toggleLike(LikesRepository.ENTITY_ARTIST, artistId, desired)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pull every track across the artist's albums, shuffle, and start
|
||||
* playing. Pressing Play on an artist means "shuffle this artist",
|
||||
* not "play album by album in tracklist order". One network
|
||||
* round-trip per click; fine because the user explicitly tapped Play.
|
||||
*/
|
||||
fun playArtist() {
|
||||
viewModelScope.launch {
|
||||
shufflePlayArtist(artistId, repository, player) { transientMessagesChannel.trySend(it) }
|
||||
fun refresh(): Job =
|
||||
viewModelScope.launch {
|
||||
val carried =
|
||||
when (val cur = internal.value) {
|
||||
is ArtistDetailUiState.Loading -> cur.seed
|
||||
is ArtistDetailUiState.Success -> cur.detail.artist
|
||||
is ArtistDetailUiState.Error -> null
|
||||
}
|
||||
internal.value = ArtistDetailUiState.Loading(carried ?: seedCache.peekArtist(artistId))
|
||||
try {
|
||||
val detail = repository.refreshArtistDetail(artistId)
|
||||
internal.value = ArtistDetailUiState.Success(detail)
|
||||
loadSecondarySections()
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
||||
) {
|
||||
internal.value = ArtistDetailUiState.Error(ErrorCopy.fromThrowable(e))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pulls the non-critical "Similar artists" + "Top tracks" sections
|
||||
* and folds them into the live Success state. Each failure is
|
||||
* swallowed (logged only) — these sections render absent rather than
|
||||
* blocking, so the core artist view never depends on them.
|
||||
*/
|
||||
private suspend fun loadSecondarySections() {
|
||||
val similar = sectionOrEmpty { repository.fetchSimilarArtists(artistId) }
|
||||
val top = sectionOrEmpty { repository.fetchArtistTopTracks(artistId) }
|
||||
val current = internal.value
|
||||
if (current is ArtistDetailUiState.Success) {
|
||||
internal.value = current.copy(similarArtists = similar, topTracks = top)
|
||||
}
|
||||
}
|
||||
|
||||
private inline fun <T> sectionOrEmpty(block: () -> List<T>): List<T> =
|
||||
try {
|
||||
block()
|
||||
} catch (
|
||||
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
||||
) {
|
||||
Timber.w(e, "Artist secondary section fetch failed for %s", artistId)
|
||||
emptyList()
|
||||
}
|
||||
|
||||
/**
|
||||
* Pull every track across the artist's albums, shuffle, and start
|
||||
* playing. Pressing Play on an artist means "shuffle this artist",
|
||||
* not "play album by album in tracklist order". One network
|
||||
* round-trip per click; fine because the user explicitly tapped Play.
|
||||
*/
|
||||
fun playArtist() {
|
||||
viewModelScope.launch {
|
||||
shufflePlayArtist(artistId, repository, player) { transientMessagesChannel.trySend(it) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Plays the loaded "Top tracks" list starting at [index] — the top
|
||||
* tracks are themselves the playable queue (mirrors the web client's
|
||||
* sectionTracks = top-tracks behaviour). No network round-trip; the
|
||||
* list is already in the Success state.
|
||||
*/
|
||||
fun playTopTracks(index: Int) {
|
||||
val tracks = (internal.value as? ArtistDetailUiState.Success)?.topTracks.orEmpty()
|
||||
if (tracks.isEmpty()) return
|
||||
player.setQueue(
|
||||
tracks = tracks,
|
||||
initialIndex = index.coerceIn(0, tracks.lastIndex),
|
||||
source = "artist-top:$artistId",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Plays the loaded "Top tracks" list starting at [index] — the top
|
||||
* tracks are themselves the playable queue (mirrors the web client's
|
||||
* sectionTracks = top-tracks behaviour). No network round-trip; the
|
||||
* list is already in the Success state.
|
||||
*/
|
||||
fun playTopTracks(index: Int) {
|
||||
val tracks = (internal.value as? ArtistDetailUiState.Success)?.topTracks.orEmpty()
|
||||
if (tracks.isEmpty()) return
|
||||
player.setQueue(
|
||||
tracks = tracks,
|
||||
initialIndex = index.coerceIn(0, tracks.lastIndex),
|
||||
source = "artist-top:$artistId",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
+167
-150
@@ -41,6 +41,11 @@ data class AlbumBrowseState(
|
||||
val remaining: Int get() = (total - albums.size).coerceAtLeast(0)
|
||||
}
|
||||
|
||||
// Two browse axes, each with an index, a filter/sort or grouping, a
|
||||
// drill-down and a pager. The function count is two axes' worth of a
|
||||
// cohesive surface; splitting into GenresViewModel + YearsViewModel would
|
||||
// duplicate the shared paging body for no gain.
|
||||
|
||||
/**
|
||||
* Backs the Genres and Years tabs, the same browse axes the web client has.
|
||||
*
|
||||
@@ -49,171 +54,183 @@ data class AlbumBrowseState(
|
||||
* missing and matches the web client's. These two tabs therefore need a
|
||||
* connection; the empty states say so rather than looking broken.
|
||||
*/
|
||||
// Two browse axes, each with an index, a filter/sort or grouping, a
|
||||
// drill-down and a pager. The function count is two axes' worth of a
|
||||
// cohesive surface; splitting into GenresViewModel + YearsViewModel would
|
||||
// duplicate the shared paging body for no gain.
|
||||
@Suppress("TooManyFunctions")
|
||||
@HiltViewModel
|
||||
class BrowseViewModel @Inject constructor(
|
||||
private val repository: LibraryRepository,
|
||||
) : ViewModel() {
|
||||
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 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 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 genreFilterInternal = MutableStateFlow("")
|
||||
val genreFilter: StateFlow<String> = genreFilterInternal.asStateFlow()
|
||||
private val genreSortInternal = MutableStateFlow(GenreSort.COUNT)
|
||||
val genreSort: StateFlow<GenreSort> = genreSortInternal.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 selectedGenreInternal = MutableStateFlow<String?>(null)
|
||||
val selectedGenre: StateFlow<String?> = selectedGenreInternal.asStateFlow()
|
||||
private val selectedYearInternal = MutableStateFlow<Int?>(null)
|
||||
val selectedYear: StateFlow<Int?> = selectedYearInternal.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 genreAlbumsInternal = MutableStateFlow(AlbumBrowseState())
|
||||
val genreAlbums: StateFlow<AlbumBrowseState> = genreAlbumsInternal.asStateFlow()
|
||||
private val yearAlbumsInternal = MutableStateFlow(AlbumBrowseState())
|
||||
val yearAlbums: StateFlow<AlbumBrowseState> = yearAlbumsInternal.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
|
||||
|
||||
// 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)) },
|
||||
)
|
||||
init {
|
||||
loadGenres()
|
||||
loadYears()
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
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)) },
|
||||
)
|
||||
},
|
||||
onFailure = {
|
||||
if (!isCurrent()) return@launch
|
||||
state.value = state.value.copy(loading = false, failed = true)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fun loadYears() {
|
||||
viewModelScope.launch {
|
||||
yearsInternal.value = UiState.Loading
|
||||
yearsInternal.value =
|
||||
runCatching { repository.albumYears() }.fold(
|
||||
onSuccess = { if (it.isEmpty()) UiState.Empty else UiState.Success(it) },
|
||||
onFailure = { UiState.Error(ErrorCopy.fromThrowable(it)) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun setGenreFilter(value: String) {
|
||||
genreFilterInternal.value = value
|
||||
}
|
||||
|
||||
fun setGenreSort(sort: GenreSort) {
|
||||
genreSortInternal.value = sort
|
||||
}
|
||||
|
||||
/** Drill into [genre], or pass null to go back to the index. */
|
||||
fun selectGenre(genre: String?) {
|
||||
selectedGenreInternal.value = genre
|
||||
genreRequestToken += 1
|
||||
genreAlbumsInternal.value = AlbumBrowseState()
|
||||
if (genre == null) return
|
||||
fetchGenrePage(genre, offset = 0, token = genreRequestToken)
|
||||
}
|
||||
|
||||
fun loadMoreGenreAlbums() {
|
||||
val genre = selectedGenreInternal.value ?: return
|
||||
val state = genreAlbumsInternal.value
|
||||
if (state.loading || !state.hasMore) return
|
||||
fetchGenrePage(genre, offset = state.albums.size, token = genreRequestToken)
|
||||
}
|
||||
|
||||
fun retryGenreAlbums() {
|
||||
selectedGenreInternal.value?.let { selectGenre(it) }
|
||||
}
|
||||
|
||||
/** Drill into [year], or pass null to go back to the index. */
|
||||
fun selectYear(year: Int?) {
|
||||
selectedYearInternal.value = year
|
||||
yearRequestToken += 1
|
||||
yearAlbumsInternal.value = AlbumBrowseState()
|
||||
if (year == null) return
|
||||
fetchYearPage(year, offset = 0, token = yearRequestToken)
|
||||
}
|
||||
|
||||
fun loadMoreYearAlbums() {
|
||||
val year = selectedYearInternal.value ?: return
|
||||
val state = yearAlbumsInternal.value
|
||||
if (state.loading || !state.hasMore) return
|
||||
fetchYearPage(year, offset = state.albums.size, token = yearRequestToken)
|
||||
}
|
||||
|
||||
fun retryYearAlbums() {
|
||||
selectedYearInternal.value?.let { selectYear(it) }
|
||||
}
|
||||
|
||||
private fun fetchGenrePage(
|
||||
genre: String,
|
||||
offset: Int,
|
||||
token: Int,
|
||||
) {
|
||||
fetchPage(
|
||||
state = genreAlbumsInternal,
|
||||
offset = offset,
|
||||
isCurrent = { token == genreRequestToken },
|
||||
fetch = { repository.albumsByGenre(genre, PAGE_SIZE, offset) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
// 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
|
||||
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.
|
||||
@@ -257,12 +274,12 @@ data class DecadeGroup(
|
||||
* same reason as [visibleGenres].
|
||||
*/
|
||||
fun groupByDecade(years: List<YearCount>): List<DecadeGroup> =
|
||||
years.groupBy { (it.year / YEARS_PER_DECADE) * YEARS_PER_DECADE }
|
||||
years
|
||||
.groupBy { (it.year / YEARS_PER_DECADE) * YEARS_PER_DECADE }
|
||||
.map { (decade, entries) ->
|
||||
DecadeGroup(
|
||||
decade = decade,
|
||||
years = entries.sortedByDescending { it.year },
|
||||
albumCount = entries.sumOf { it.albumCount },
|
||||
)
|
||||
}
|
||||
.sortedByDescending { it.decade }
|
||||
}.sortedByDescending { it.decade }
|
||||
|
||||
@@ -10,11 +10,11 @@ import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.lazy.grid.GridCells
|
||||
import androidx.compose.foundation.lazy.grid.GridItemSpan
|
||||
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
|
||||
import androidx.compose.foundation.lazy.grid.items
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material3.FilterChip
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
@@ -32,8 +32,8 @@ import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.composables.icons.lucide.ArrowLeft
|
||||
import com.composables.icons.lucide.Lucide
|
||||
import com.composables.icons.lucide.LibraryBig
|
||||
import com.composables.icons.lucide.Lucide
|
||||
import com.fabledsword.minstrel.library.widgets.AlbumCard
|
||||
import com.fabledsword.minstrel.models.AlbumRef
|
||||
import com.fabledsword.minstrel.shared.UiState
|
||||
@@ -74,22 +74,26 @@ private fun GenreIndex(viewModel: BrowseViewModel) {
|
||||
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,
|
||||
)
|
||||
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()) {
|
||||
@@ -161,11 +165,12 @@ private fun GenreIndexControls(
|
||||
label = { Text("A–Z") },
|
||||
)
|
||||
Text(
|
||||
text = if (filter.isBlank()) {
|
||||
"$total genres"
|
||||
} else {
|
||||
"$shown of $total"
|
||||
},
|
||||
text =
|
||||
if (filter.isBlank()) {
|
||||
"$total genres"
|
||||
} else {
|
||||
"$shown of $total"
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
@@ -174,12 +179,17 @@ private fun GenreIndexControls(
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GenreRow(genre: String, trackCount: Int, onClick: () -> Unit) {
|
||||
private fun GenreRow(
|
||||
genre: String,
|
||||
trackCount: Int,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable(onClick = onClick)
|
||||
.padding(horizontal = 16.dp, vertical = 14.dp),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable(onClick = onClick)
|
||||
.padding(horizontal = 16.dp, vertical = 14.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
@@ -263,20 +273,23 @@ fun BrowseAlbumResults(
|
||||
}
|
||||
|
||||
when {
|
||||
state.failed && state.albums.isEmpty() -> ErrorRetry(
|
||||
message = "Couldn't load albums.",
|
||||
onRetry = onRetry,
|
||||
)
|
||||
state.loading && state.albums.isEmpty() -> EmptyState(
|
||||
title = "Loading…",
|
||||
body = "",
|
||||
)
|
||||
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,
|
||||
)
|
||||
else ->
|
||||
BrowseAlbumGrid(
|
||||
state = state,
|
||||
onLoadMore = onLoadMore,
|
||||
onAlbumClick = onAlbumClick,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -334,8 +347,13 @@ private fun BrowseAlbumGrid(
|
||||
* is still in flight — a count that appears as 0 and then corrects itself reads
|
||||
* as a bug.
|
||||
*/
|
||||
internal fun albumCountLabel(total: Int, loading: Boolean, loaded: Int): String = when {
|
||||
loading && loaded == 0 -> ""
|
||||
total == 1 -> "1 album"
|
||||
else -> "$total albums"
|
||||
}
|
||||
internal fun albumCountLabel(
|
||||
total: Int,
|
||||
loading: Boolean,
|
||||
loaded: Int,
|
||||
): String =
|
||||
when {
|
||||
loading && loaded == 0 -> ""
|
||||
total == 1 -> "1 album"
|
||||
else -> "$total albums"
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user