10 Commits
Author SHA1 Message Date
TapTap cfab559e5e fix: keep the dragged queue row opaque
CI / build (push) Successful in 11m56s
CI / play (push) Successful in 3m16s
2026-11-17 08:55:38 +00:00
TapTap a63ee62673 feat: drag-to-reorder queue and a compact mobile player
CI / build (push) Successful in 4m51s
CI / play (push) Skipped
- long-press and drag queue rows, with auto-scroll near the edges
- pin the now-playing row above the upcoming queue
- move add-to-mood actions into an overflow menu so the title and
  artist get the full width on narrow phones
2026-11-17 08:54:23 +00:00
TapTap 3b40726edb feat: choose Deezer or YouTube Music per mood
CI / build (push) Successful in 3m35s
CI / play (push) Skipped
- models carry source and externalId instead of videoId
- AppCache v3 discards the old shape
- source selector in the create dialog, mood settings and search screen
- switching source patches the mood and re-runs the search
- client requests ten catalog results with a 60s timeout
2026-11-17 07:32:40 +00:00
TapTap 96ab25a91d feat: search YouTube Music and poll for the first recommendation batch
CI / build (push) Successful in 12m2s
CI / play (push) Successful in 3m18s
- label and document the YouTube Music search source
- allow up to 60s for a search and request ten results
- keep refreshing a new mood until its first recommendations arrive
2026-11-16 18:38:58 +00:00
TapTap c896f81306 fix: disable adding a search result that is already in the mood
CI / build (push) Successful in 12m13s
CI / play (push) Successful in 3m14s
2026-11-15 21:55:47 +00:00
TapTap 7ed518b047 fix: disable play until a mood has a song
CI / build (push) Successful in 3m53s
CI / play (push) Skipped
2026-11-15 21:48:33 +00:00
TapTap 6bfa12d673 feat: show which search results are already in the target mood
CI / build (push) Successful in 4m7s
CI / play (push) Skipped
2026-11-15 21:46:57 +00:00
TapTap 375bcc9c37 fix: refresh a mood after adding a song that is still downloading
CI / build (push) Successful in 4m1s
CI / play (push) Skipped
2026-11-15 21:45:12 +00:00
TapTap dc270f863c feat: move the client to searchable, downloadable moods
CI / build (push) Successful in 3m28s
CI / play (push) Skipped
- new mood/song/search/recommendation models and API calls
- AppCache v2 with moods and details only
- Search and Downloads screens; remove Library and Longform
- new mood detail with songs, add music and recommendation states
- song-keyed covers and updated tests/docs
2026-11-15 21:37:39 +00:00
TapTap 1bb23901eb docs: record the client side of the mood-first redesign [skip ci] 2026-11-15 21:06:32 +00:00
18 changed files with 2000 additions and 1926 deletions

No files matched your search

+125 -73
View File
@@ -1,8 +1,11 @@
# AudioManager Client
Kotlin Multiplatform client for [AudioManager](../AudioManager) — a mood-first, self-hosted music server.
Kotlin Multiplatform client for [AudioManager](../AudioManager) — a mood-first,
self-hosted music server.
The client and server are designed together. There is no OpenSubsonic compatibility layer: the app speaks the native `/api/v1` API, where playback is a server-driven radio session and "likes" are replaced by explicit **add to mood** actions.
The client and server are designed together. There is no OpenSubsonic
compatibility layer: the app speaks the native `/api/v1` API, where playback is
a server-driven radio session and songs are added from Deezer or YouTube Music.
## Targets
@@ -12,33 +15,70 @@ The client and server are designed together. There is no OpenSubsonic compatibil
| **Desktop (JVM)** | Compose Multiplatform | MP3SPI, decoded to PCM + `SourceDataLine` | Yes |
| **Web (Wasm)** | Compose Multiplatform | HTML5 `Audio` | Browser-managed cache only |
The shared module contains the API client, session/cache storage, radio queue, app state and all screens. Platform code is limited to HTTP engines, storage, audio and back handling.
## Features
- Login with a server URL, username and password. The server returns a revocable bearer token.
- Mood grid with live counts; create, rename, delete and edit moods.
- Seed management: search the owner's music, add or remove anchors.
- Server-driven radio: the app keeps a small queue and asks for more from the same mood session.
- Playback events are reported automatically (`started`, `completed`, `skipped`) so the server learns.
- Login with a server URL, username and password. The server returns a revocable
bearer token.
- **Moods** are the only content model. Each user sees only their own moods.
- **Songs** belong to the mood's permanent collection. A mood needs at least one
song before it can play.
- **Search Deezer or YouTube Music** from inside a mood or globally with a mood
picker. Each mood has a **Download source** selector; search, recommendations
and downloads follow it. Tracks over 10 minutes are hidden. Results that are already downloaded are marked and
add instantly; other videos are queued for server-side download.
- **Paste a YouTube URL** to add a specific video.
- **Recommendations** are downloaded automatically and play in the radio without
being permanent. Rows show the download state with:
- Add to mood;
- Not interested (permanent for the mood);
- Retry for failed downloads.
- **Radio** mixes the collection and ready recommendations using the mood's
`collectionPercent`. The app keeps a small queue and asks for more from the
same mood session.
- Playback events are reported automatically (`started`, `completed`, `skipped`)
so the server learns.
- Two add-to-mood actions in the player:
- **Add to current mood** (the mood of the active radio session)
- **Choose another mood** (picker)
- YT Music recommendations in the mood editor: refresh on demand, accept or reject candidates, thumbnails, and a clear state for library matches (`Seed added`), accepted-for-download tracks (`Queued`, `Downloading`, `Download failed` with retry) and new picks. Accepting a track the library already has adds it as a seed immediately; the rest are downloaded by the server and promoted automatically.
- Library search and playback, plus **Shuffle all** to queue the whole library without starting a mood.
- A queue sheet from the player: the current track plus every upcoming track, with move up/down and remove. Changes are persisted locally.
- **Previous** from the player: after two seconds of playback it restarts the current track; before that it restores the last played track. The track it leaves is put back at the front of the queue.
- **Scrubbing**: the progress slider can be dragged on every platform. Android/web seek natively; desktop restarts the decoder at the requested position (`timeOffset` for remote streams, PCM skip for local files).
- **Seed mix** per mood: a slider chooses the share of seeds vs recommendations for each generated batch. The server rolls the percentage for every queued track and falls back to the other pool when one runs out.
- **Longform tab** for audiobooks and podcasts: per-artist read-only playlists, “Shuffle artist” for random episodes, a resume list with progress, and a separate search scope. Long-form never enters music search, Shuffle all, moods or radio.
- **Sleep timer** (15/30/45/60/90 minutes) that pauses playback. On Android the pause is scheduled inside the media service, so it still fires when the app is backgrounded or the task is swiped away.
- Offline library cache: moods, songs and the last sync revision are stored locally. When the server is unreachable, downloaded tracks still play.
- The play queue and current track are saved locally, so a restart reopens the player paused and resumes on the next tap.
- A queue sheet from the player: the current track is pinned, upcoming tracks
can be reordered by **long-press and drag** or removed. Changes are persisted
locally.
- **Previous** from the player: after two seconds of playback it restarts the
current track; before that it restores the last played track.
- The bottom player keeps the cover and title/artist readable on narrow phones;
add-to-mood actions moved into the overflow menu.
- **Scrubbing**: the progress slider can be dragged on every platform. Android and
web seek natively; desktop restarts the decoder at the requested position.
- **Mood settings**: name, description, discovery hint, genres, collection share,
active recommendation count (0–30), and refresh interval.
- **Downloads** screen for device-side copies: play, delete, clear, storage
usage.
- **Sleep timer** (15/30/45/60/90 minutes) that pauses playback. On Android the
pause is scheduled inside the media service, so it still fires when the app is
backgrounded or the task is swiped away.
- Mood cache: moods and details are stored locally so the app opens instantly
and can show cached data offline.
- The play queue and current track are saved locally, so a restart reopens the
player paused and resumes on the next tap.
- Reconnects automatically with exponential backoff (15s to 5min) while offline.
- Downloads retry up to three times before reporting an error; covers and YT thumbnails are cached for the app's lifetime.
- Original MP3 downloads with progress state, removal and storage usage.
- Session persistence: the login survives app restarts until the token is revoked or expires.
- Android background playback through a Media3 `MediaSessionService`: notification, lock-screen and headset controls, audio focus, and playback that survives the app being backgrounded or the task being swiped away.
- Session persistence: the login survives app restarts until the token is
revoked or expires.
- Android background playback through a Media3 `MediaSessionService`:
notification, lock-screen and headset controls, audio focus, and playback that
survives the app being backgrounded or the task being swiped away.
## Screens
`Moods | Mood Detail | Search | Downloads | Settings`
- **Moods** — grid with song and pick counts, create, global search.
- **Mood Detail** — songs, add music, recommendations, next batch, settings.
- **Search** — mood picker, source selector, catalog search, paste URL,
downloaded badges.
- **Downloads** — offline files and storage usage.
- **Settings** — account, server URL, offline storage, sign out.
There is no Library tab, no Longform tab and no global shuffle.
## Project layout
@@ -46,9 +86,9 @@ The shared module contains the API client, session/cache storage, radio queue, a
composeApp/
|-- src/commonMain/kotlin/win/taptap/musicmanager/client/
| |-- api/ # Ktor client and DTOs mirroring /api/v1
| |-- data/ # AppStorage, LibraryCache, session persistence
| |-- data/ # AppStorage, AppCache, session persistence
| |-- playback/ # AudioPlayer abstraction
| |-- store/ # AppStore: state, radio queue, downloads, editing
| |-- store/ # AppStore: state, search, radio queue, downloads
| `-- ui/ # Compose screens and theme
|-- src/androidMain/ # Activity, Media3 player, filesystem storage
|-- src/desktopMain/ # Main window, MP3SPI player, filesystem storage
@@ -60,15 +100,18 @@ composeApp/
## Build
Requirements: JDK 21, Android SDK 36 for the app target, Node (Kotlin downloads its own for web).
Requirements: JDK 21, Android SDK 36 for the app target, Node (Kotlin downloads
its own for web).
With Nix, everything is provided by `shell.nix` (JDK 21, Gradle 8, Node 22, Android SDK 36 with build-tools 36.0.0, and the desktop runtime libraries):
With Nix, everything is provided by `shell.nix` (JDK 21, Gradle 8, Node 22,
Android SDK 36 with build-tools 36.0.0, and the desktop runtime libraries):
```bash
nix-shell
```
The shell accepts the unfree Android SDK license for you; see the comment at the top of `shell.nix`. Without Nix, point `ANDROID_HOME` at an SDK containing platform 36 and build-tools 36.0.0.
Without Nix, point `ANDROID_HOME` at an SDK containing platform 36 and
build-tools 36.0.0.
```bash
export ANDROID_HOME=/opt/android-sdk
@@ -91,9 +134,12 @@ gradle :composeApp:wasmJsBrowserDistribution
# composeApp/build/dist/wasmJs/productionExecutable
```
Serve the web bundle from any static host (for example `python3 -m http.server` inside the production directory). The server allows cross-origin API calls; enter its URL on the login screen. When the bundle is hosted on the same origin as the server, the URL is prefilled.
Serve the web bundle from any static host (for example `python3 -m http.server`
inside the production directory). The server allows cross-origin API calls;
enter its URL on the login screen.
Android cleartext HTTP is enabled for local development. Use HTTPS in production.
Android cleartext HTTP is enabled for local development. Use HTTPS in
production.
## Publishing to Google Play (internal testing)
@@ -130,27 +176,17 @@ scripts/build-release-aab.sh <versionCode> <versionName>
# composeApp/build/outputs/bundle/release/composeApp-release.aab
```
The script verifies the signature and prints the SHA-256. Bump `versionCode` for
every upload; `VERSION_CODE`/`VERSION_NAME` can also be set in the environment.
The script verifies the signature and prints the SHA-256.
### 3. Upload
In Play Console: **Testing → Internal testing → Create new release → App
integrity → Google-generated key**, upload the AAB, add release notes, then
**Save → Roll out**. The first upload enrolls the app in Play App Signing. Share
the opt-in link from the Testers tab with your test list.
**Save → Roll out**.
### 4. Automated uploads
Tagged builds (`v*`) publish to internal testing from CI. One-time setup:
1. In Google Cloud, enable the **Google Play Android Developer API**.
2. Create a service account and download a JSON key.
3. In Play Console → **Users and permissions → Invite new user**, add the
service account's `client_email`, give it access to this app with
**Release to testing tracks** and **View app information** (do not grant
production or admin access).
4. Add these repository secrets in Gitea:
Tagged builds (`v*`) publish to internal testing from CI. The Gitea secrets are:
| Secret | Value |
| --- | --- |
@@ -160,32 +196,33 @@ Tagged builds (`v*`) publish to internal testing from CI. One-time setup:
| `ANDROID_KEY_PASSWORD` | key password |
| `PLAY_SERVICE_ACCOUNT_JSON` | contents of the service account JSON |
Then `git tag v0.2.0 && git push --tags` builds, signs and uploads the bundle.
Then `git tag v0.3.0 && git push --tags` builds, signs and uploads the bundle.
Gradle Play Publisher asks Play for the next free `versionCode`
(`ResolutionStrategy.AUTO`), so only the tag/version name needs to change.
Local equivalent (takes the JSON from an environment variable, never a file in
the repo):
```bash
ANDROID_PUBLISHER_CREDENTIALS="$(cat ~/play-service-account.json)" \
ANDROID_HOME=/opt/android-sdk gradle :composeApp:publishBundle
```
## App state and offline behaviour
`AppStore` is a plain Kotlin class with a `StateFlow<AppState>`; Compose observes it. It owns:
`AppStore` is a plain Kotlin class with a `StateFlow<AppState>`; Compose observes
it. It owns:
- **Auth** — restore the saved token on launch and log out.
- **Library sync** — first launch pages through `/library/songs`; later launches use the `since` delta and tombstones. Songs are split into music and longform using the folders assigned at login, so the two never mix client-side.
- **Mood cache** — mood details are stored so the app can open them offline.
- **Radio** — one session per mood, batches of 12, prefetch when the queue is short, no repeats within a session.
- **Downloads** — stored under the platform app directory, keyed by deterministic song ID.
- **Playback snapshot** — the session, upcoming queue, current track and play history are persisted on every queue change and restored on the next launch.
- **Longform progress** — position is saved locally and to `/longform/progress` while playing, on pause and on track changes; the resume list is fed from the server when online.
- **Offline retry** — a background loop retries the library sync until the server responds again.
- **Mood sync** — GET `/moods` on login/refresh; details are fetched when a mood
is opened and cached.
- **Mood cache** — cached details power offline mood lists and downloads.
- **Search** — debounced remote catalog search with the selected target mood and
its source.
- **Radio** — one session per mood, batches of 12, prefetch when the queue is
short, no repeats within a session.
- **Downloads** — stored under the platform app directory, keyed by the shared
song id.
- **Playback snapshot** — the session, upcoming queue, current track, history and
position are persisted and restored on the next launch.
- **Offline retry** — a background loop retries the mood sync until the server
responds again.
On startup the app is usable before the network call completes: cached moods and library render immediately, then refresh in the background.
On startup the app is usable before the network call completes: cached moods
render immediately, then refresh in the background. Offline playback uses the
mood's cached songs filtered by downloaded files.
## Radio and add-to-mood
@@ -200,14 +237,20 @@ open mood ──► POST /moods/{id}/sessions ──► queue (12 tracks)
└─ moodId: chosen mood
```
Adding a song makes it a permanent seed, so it is always eligible in future radio and visible in the mood editor.
Adding a song makes it permanent in the mood, so it is always eligible in future
radio and visible in the song list.
## CI and releases
`.gitea/workflows/ci.yaml` runs on Gitea Actions using `gitea.tap-tap.win/taptap/audiomanager-client-ci:3`. The image has the Android SDK, Node, Yarn and a warmed Gradle dependency cache, so jobs do not download them on every run.
`.gitea/workflows/ci.yaml` runs on Gitea Actions using
`gitea.tap-tap.win/taptap/audiomanager-client-ci:3`. The image has the Android
SDK, Node, Yarn and a warmed Gradle dependency cache.
- **main / PR:** run `desktopTest`, build the Android APK and the *development* Wasm bundle. The optimized Wasm build is CPU-bound and reserved for releases.
- **`v*` tag:** additionally build the desktop fat jar and the optimized Wasm bundle, then attach all three to the Gitea release.
- **main / PR:** run `desktopTest`, build the Android APK and the *development*
Wasm bundle.
- **`v*` tag:** additionally build the desktop fat jar and the optimized Wasm
bundle, attach the artifacts to the Gitea release, and publish the AAB to Play
internal testing.
Rebuild the CI image after changing `ci/Dockerfile` or dependency versions:
@@ -215,14 +258,23 @@ Rebuild the CI image after changing `ci/Dockerfile` or dependency versions:
scripts/build-ci-image.sh 3
```
The image build performs one warm-up compile (`kotlinNodeJsSetup`, `kotlinYarnSetup`, `desktopTest`, `assembleDebug`, `compileKotlinWasmJs`) and then removes the sources, keeping only `/root/.gradle`.
## Known limitations
- The media notification exposes play/pause and seeking. Queue actions (skip, add to mood) stay in the app because the mood session and its events belong to the server.
- Desktop playback supports seeking by reopening the decoder at the requested position (server `timeOffset` for remote streams, PCM skipping for local files). Longform resume works there too. MP3s are decoded to 16-bit PCM before the line is opened, because Java Sound has no line for the compressed format.
- Web downloads are disabled because the browser owns its storage; the app still streams and caches metadata.
- Accepted recommendations are downloaded by the server into `<music>/AudioManager Imports/<artist>/<title>/`, with the YT thumbnail embedded as cover art, scanned and added as seeds. The per-track folder keeps covers distinct. The server needs outbound network access for this.
- Offline downloads also store the 320 px cover next to the MP3 (`<songId>.jpg`), so the in-app cover and the Android notification artwork survive without the server. Deleting a download removes both files.
- YT Music discovery and automatic downloads run server-side through `yt-dlp`. Accepted tracks that are not in the library are imported into `AudioManager Imports` with embedded cover art and promoted to seeds.
- The media notification exposes play/pause and seeking. Queue actions (skip,
add to mood) stay in the app because the mood session and its events belong to
the server.
- Desktop playback supports seeking by reopening the decoder at the requested
position. MP3s are decoded to 16-bit PCM before the line is opened, because
Java Sound has no line for the compressed format.
- Web downloads are disabled because the browser owns its storage; the app still
streams and caches metadata.
- Downloads store the 320 px cover next to the MP3 (`<songId>.jpg`), so the
in-app cover and the Android notification artwork survive without the server.
- Search and downloads depend on the server's catalogs. YouTube bot checks can
fail a YouTube Music search (`502`) or leave a recommendation in `failed`
with Retry. Music search resolves every result for its artist/album/duration,
so a YouTube Music search takes roughly 10–15 seconds for ten results;
Deezer search is much faster.
- Deezer downloads need `DEEZER_ARL` on the server. A Free ARL is limited to
128 kbps; Premium enables 320 kbps. The client never stores the ARL.
- No iOS target yet. The shared module is ready for one.
+1 -1
View File
@@ -41,7 +41,7 @@ val hasUploadKey = uploadKeyStore?.exists() == true &&
val appVersionCode = (System.getenv("VERSION_CODE") ?: localProperties.getProperty("VERSION_CODE") ?: "1").toInt()
val appVersionName = System.getenv("VERSION_NAME")
?: localProperties.getProperty("VERSION_NAME")
?: "0.1.0"
?: "0.3.0"
kotlin {
androidTarget {
@@ -12,7 +12,6 @@ import io.ktor.client.request.get
import io.ktor.client.request.header
import io.ktor.client.request.patch
import io.ktor.client.request.post
import io.ktor.client.request.put
import io.ktor.client.request.setBody
import io.ktor.client.statement.HttpResponse
import io.ktor.client.statement.bodyAsBytes
@@ -44,7 +43,6 @@ fun configuredHttpClient(engine: HttpClientEngine): HttpClient = HttpClient(engi
}
}
/**
* Native API client. Media URLs carry the token in the query string because
* Android's Media3, desktop playback and HTML audio all fetch them directly.
@@ -124,17 +122,30 @@ class ApiClient(private val http: HttpClient) {
requestNoContent { http.delete(url("/moods/$id")) { auth() } }
}
suspend fun addSeed(moodId: String, songId: String): AddToMoodResponse =
suspend fun addSong(
moodId: String,
songId: String? = null,
source: String? = null,
externalId: String? = null,
url: String? = null,
): AddSongResponse =
parse(
http.post(url("/moods/$moodId/seeds")) {
http.post(url("/moods/$moodId/songs")) {
auth()
contentType(ContentType.Application.Json)
setBody(AddSeedRequest(songId))
setBody(
AddSongRequest(
songId = songId,
source = source,
externalId = externalId,
url = url,
),
)
},
)
suspend fun removeSeed(moodId: String, songId: String) {
requestNoContent { http.delete(url("/moods/$moodId/seeds/$songId")) { auth() } }
suspend fun removeSong(moodId: String, songId: String) {
requestNoContent { http.delete(url("/moods/$moodId/songs/$songId")) { auth() } }
}
suspend fun recommendations(moodId: String): List<Recommendation> =
@@ -152,42 +163,49 @@ class ApiClient(private val http: HttpClient) {
},
)
suspend fun acceptRecommendation(moodId: String, videoId: String): RecommendationDecision =
suspend fun addRecommendation(moodId: String, externalId: String): RecommendationDecision =
parse(
http.post(url("/moods/$moodId/recommendations/$videoId/accept")) {
http.post(url("/moods/$moodId/recommendations/$externalId/add")) {
auth()
},
)
suspend fun rejectRecommendation(moodId: String, videoId: String): RecommendationDecision =
suspend fun rejectRecommendation(moodId: String, externalId: String): RecommendationDecision =
parse(
http.post(url("/moods/$moodId/recommendations/$videoId/reject")) {
http.post(url("/moods/$moodId/recommendations/$externalId/reject")) {
auth()
},
)
suspend fun retryRecommendation(moodId: String, externalId: String): MoodDetail =
parse(
http.post(url("/moods/$moodId/recommendations/$externalId/retry")) {
auth()
},
)
suspend fun preview(moodId: String, limit: Int = 20): List<Song> =
get<SearchResponse>("/moods/$moodId/preview?limit=$limit").songs
get<TracksResponse>("/moods/$moodId/preview?limit=$limit").songs
suspend fun search(query: String, limit: Int = 50, scope: String = "music"): List<Song> =
get<SearchResponse>(
"/library/search?q=${query.encodeURLParameter()}&limit=$limit&scope=$scope",
).songs
suspend fun library(
cursor: String? = null,
since: String? = null,
limit: Int = 500,
scope: String = "all",
revision: String? = null,
): LibraryPage {
val query = buildString {
append("?limit=$limit&scope=$scope")
cursor?.let { append("&cursor=${it.encodeURLParameter()}") }
since?.let { append("&since=${it.encodeURLParameter()}") }
revision?.let { append("&revision=${it.encodeURLParameter()}") }
suspend fun search(
query: String,
limit: Int = 10,
source: String? = null,
moodId: String? = null,
): List<SearchResult> {
val sourceParam = source?.let { "&source=${it.encodeURLParameter()}" }.orEmpty()
val mood = moodId?.let { "&moodId=${it.encodeURLParameter()}" }.orEmpty()
return parse<SearchResponse>(
http.get(url("/search?q=${query.encodeURLParameter()}&limit=$limit$sourceParam$mood")) {
auth()
// yt-dlp resolves every YouTube Music hit to get artist, album
// and duration, so a search takes longer than a plain API call.
timeout {
requestTimeoutMillis = 60_000
socketTimeoutMillis = 60_000
}
return get("/library/songs$query")
},
).results
}
suspend fun startSession(moodId: String, limit: Int = 12): Session =
@@ -232,40 +250,14 @@ class ApiClient(private val http: HttpClient) {
runCatching { requestNoContent { http.delete(url("/sessions/$id")) { auth() } } }
}
suspend fun longformProgress(): List<LongformProgressItem> =
get<LongformProgressResponse>("/longform/progress").items
suspend fun saveLongformProgress(
songId: String,
positionSeconds: Int,
durationSeconds: Int,
completed: Boolean,
) {
val response = http.put(url("/longform/progress/$songId")) {
auth()
contentType(ContentType.Application.Json)
setBody(SaveLongformProgressRequest(positionSeconds, durationSeconds, completed))
}
if (!response.status.isSuccess()) throw error(response)
}
suspend fun devices(): List<Device> = get("/auth/devices")
suspend fun scanStatus(): ScanStatus = get("/scan")
suspend fun startScan(): ScanStatus =
parse(
http.post(url("/scan")) {
auth()
},
)
suspend fun cover(albumId: String, size: Int = 320): ByteArray? {
val key = "$albumId:$size"
suspend fun cover(songId: String, size: Int = 320): ByteArray? {
val key = "$songId:$size"
if (coverCache.containsKey(key)) return coverCache[key]
val result = runCatching {
val response = http.get(
"$baseUrl/api/v1/covers/$albumId?size=$size&token=${token.orEmpty().encodeURLParameter()}",
"$baseUrl/api/v1/songs/$songId/cover?size=$size&token=${token.orEmpty().encodeURLParameter()}",
)
if (response.status.isSuccess()) {
response.bodyAsBytes().takeIf { it.isNotEmpty() }
@@ -274,8 +266,7 @@ class ApiClient(private val http: HttpClient) {
}
}.getOrNull()
if (coverCache.size > MAX_CACHED_IMAGES) coverCache.clear()
// Do not cache failures: a cover can appear after the scanner indexes a
// newly downloaded track, and the UI should pick it up without a restart.
// Do not cache failures: a cover can appear after a download finishes.
if (result != null) coverCache[key] = result
return result
}
@@ -319,8 +310,6 @@ class ApiClient(private val http: HttpClient) {
val response = http.get("$baseUrl/api/v1/songs/$songId/stream") {
auth()
url.parameters.append("download", "true")
// A long audiobook must not be cancelled by the default 30s total
// request timeout.
timeout {
requestTimeoutMillis = 6 * 60 * 60 * 1000
socketTimeoutMillis = 60_000
@@ -333,8 +322,8 @@ class ApiClient(private val http: HttpClient) {
fun streamUrl(songId: String): String =
"$baseUrl/api/v1/songs/$songId/stream?token=${token.orEmpty().encodeURLParameter()}"
fun coverUrl(albumId: String, size: Int = 320): String =
"$baseUrl/api/v1/covers/$albumId?size=$size&token=${token.orEmpty().encodeURLParameter()}"
fun coverUrl(songId: String, size: Int = 320): String =
"$baseUrl/api/v1/songs/$songId/cover?size=$size&token=${token.orEmpty().encodeURLParameter()}"
private suspend inline fun <reified T> get(path: String): T =
parse(http.get(url(path)) { auth() })
@@ -23,8 +23,6 @@ data class LoginRequest(
data class User(
val name: String,
val admin: Boolean,
val musicFolders: List<Int> = emptyList(),
val longformFolders: List<Int> = emptyList(),
)
@Serializable
@@ -37,22 +35,19 @@ data class LoginResponse(
@Serializable
data class Song(
val id: String,
val source: String = "youtube",
val externalId: String,
val title: String,
val artist: String,
val album: String,
val albumId: String,
val trackNumber: Int? = null,
val discNumber: Int = 1,
val year: Int? = null,
val album: String? = null,
val duration: Int,
val bitRate: Int,
val size: Long,
val suffix: String,
val genres: List<String> = emptyList(),
val folderId: Int,
val relativePath: String,
val updatedAt: String,
)
val bitRate: Int = 0,
val size: Long = 0,
val suffix: String = "mp3",
val thumbnail: String? = null,
) {
val subtitle: String get() = album?.takeIf { it.isNotBlank() } ?: artist
}
@Serializable
data class Mood(
@@ -61,21 +56,23 @@ data class Mood(
val description: String? = null,
val query: String? = null,
val genres: List<String> = emptyList(),
val targetSize: Int,
val seedPercent: Int = 50,
val source: String = "youtube",
val collectionPercent: Int = 50,
val recommendationPercent: Int = 50,
val refreshHours: Int,
val ytEnabled: Boolean,
val recommendationCount: Int = 10,
val refreshHours: Int = 24,
val lastDiscoveryAt: String? = null,
val createdAt: String,
val changedAt: String,
val lastError: String? = null,
val seedCount: Int,
val newRecommendations: Int = 0,
val songCount: Int = 0,
val recommendationReady: Int = 0,
val recommendationDownloading: Int = 0,
val recommendationFailed: Int = 0,
)
@Serializable
data class Seed(
data class MoodSong(
val song: Song,
val origin: String,
val addedAt: String,
@@ -86,62 +83,35 @@ data class Download(
val state: String,
val attempts: Int = 0,
val error: String? = null,
val updatedAt: String,
val updatedAt: String = "",
)
@Serializable
data class Recommendation(
val videoId: String,
val source: String = "youtube",
val externalId: String,
val title: String,
val artist: String,
val album: String? = null,
val duration: Int? = null,
val thumbnail: String? = null,
val state: String,
val matchedSong: Song? = null,
val timesAdded: Int = 0,
val firstSeen: String,
val lastSeen: String,
val song: Song? = null,
val download: Download? = null,
)
@Serializable
data class LongformProgressItem(
val song: Song,
val positionSeconds: Int,
val durationSeconds: Int,
val completed: Boolean,
val updatedAt: String,
)
@Serializable
data class LongformProgressResponse(val items: List<LongformProgressItem> = emptyList())
@Serializable
data class SaveLongformProgressRequest(
val positionSeconds: Int,
val durationSeconds: Int? = null,
val completed: Boolean = false,
)
@Serializable
data class LongformProgress(
val songId: String,
val positionSeconds: Int,
val durationSeconds: Int,
val completed: Boolean,
val updatedAt: String,
val error: String? = null,
val firstSeen: String = "",
val lastSeen: String = "",
)
@Serializable
data class MoodDetail(
val mood: Mood,
val seeds: List<Seed> = emptyList(),
val songs: List<MoodSong> = emptyList(),
val recommendations: List<Recommendation> = emptyList(),
)
@Serializable
data class MoodsResponse(val moods: List<Mood>)
data class MoodsResponse(val moods: List<Mood> = emptyList())
@Serializable
data class RecommendationsResponse(val recommendations: List<Recommendation> = emptyList())
@@ -150,20 +120,24 @@ data class RecommendationsResponse(val recommendations: List<Recommendation> = e
data class RecommendationDecision(
val detail: MoodDetail,
val recommendation: Recommendation,
val seedAdded: Boolean = false,
)
@Serializable
data class LibraryPage(
val songs: List<Song> = emptyList(),
val deletedSongIds: List<String> = emptyList(),
val revision: String,
val nextCursor: String? = null,
val nextSince: String? = null,
data class SearchResult(
val source: String = "youtube",
val externalId: String,
val title: String,
val artist: String,
val album: String? = null,
val duration: Int? = null,
val thumbnail: String? = null,
val songId: String? = null,
val downloaded: Boolean = false,
val inMood: Boolean = false,
)
@Serializable
data class SearchResponse(val songs: List<Song> = emptyList())
data class SearchResponse(val results: List<SearchResult> = emptyList())
@Serializable
data class Session(
@@ -206,8 +180,21 @@ data class AddToMoodRequest(val songId: String, val moodId: String? = null)
@Serializable
data class AddToMoodResponse(val mood: Mood, val added: Boolean)
/** Adds an existing song, a search result's video id, or a pasted URL. */
@Serializable
data class AddSeedRequest(val songId: String, val origin: String = "manual")
data class AddSongRequest(
val songId: String? = null,
val source: String? = null,
val externalId: String? = null,
val url: String? = null,
)
@Serializable
data class AddSongResponse(
val detail: MoodDetail,
val added: Boolean = false,
val downloading: Boolean = false,
)
@Serializable
data class CreateMoodRequest(
@@ -215,11 +202,10 @@ data class CreateMoodRequest(
val description: String? = null,
val query: String? = null,
val genres: List<String> = emptyList(),
val targetSize: Int = 30,
val source: String? = null,
val collectionPercent: Int = 50,
val recommendationCount: Int = 10,
val refreshHours: Int = 24,
val ytEnabled: Boolean = true,
val seedSongIds: List<String> = emptyList(),
val seedPercent: Int = 50,
)
@Serializable
@@ -230,10 +216,10 @@ data class UpdateMoodRequest(
val query: String? = null,
val clearQuery: Boolean = false,
val genres: List<String>? = null,
val targetSize: Int? = null,
val source: String? = null,
val collectionPercent: Int? = null,
val recommendationCount: Int? = null,
val refreshHours: Int? = null,
val ytEnabled: Boolean? = null,
val seedPercent: Int? = null,
)
@Serializable
@@ -2,7 +2,6 @@ package win.taptap.musicmanager.client.data
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import win.taptap.musicmanager.client.api.LongformProgress
import win.taptap.musicmanager.client.api.Mood
import win.taptap.musicmanager.client.api.MoodDetail
import win.taptap.musicmanager.client.api.Session
@@ -16,16 +15,22 @@ data class SessionState(
val user: User,
)
/**
* Offline cache. Version 3 adds the download source and the source-neutral
* external track id; older shapes are discarded instead of mis-decoding.
*/
@Serializable
data class CachedState(
val version: Int = CACHE_VERSION,
val serverUrl: String = "",
val userName: String = "",
val revision: String? = null,
val songs: List<Song> = emptyList(),
val longform: List<Song> = emptyList(),
val moods: List<Mood> = emptyList(),
val moodDetails: List<MoodDetail> = emptyList(),
)
) {
companion object {
const val CACHE_VERSION = 3
}
}
/** The queue survives a restart so the next launch can resume where it stopped. */
@Serializable
@@ -37,7 +42,7 @@ data class PlaybackSnapshot(
val positionSeconds: Double = 0.0,
)
class LibraryCache(private val storage: AppStorage) {
class AppCache(private val storage: AppStorage) {
private val json = Json {
ignoreUnknownKeys = true
@@ -54,10 +59,12 @@ class LibraryCache(private val storage: AppStorage) {
if (session == null) delete(SESSION_FILE) else write(SESSION_FILE, json.encodeToString(session))
}
fun load(): CachedState =
read(CACHE_FILE)?.let {
fun load(): CachedState {
val cached = read(CACHE_FILE)?.let {
runCatching { json.decodeFromString<CachedState>(it) }.getOrNull()
} ?: CachedState()
} ?: return CachedState()
return if (cached.version == CachedState.CACHE_VERSION) cached else CachedState()
}
fun save(state: CachedState) {
write(CACHE_FILE, json.encodeToString(state))
@@ -76,19 +83,9 @@ class LibraryCache(private val storage: AppStorage) {
}
}
fun loadProgress(): List<LongformProgress> =
read(PROGRESS_FILE)?.let {
runCatching { json.decodeFromString<List<LongformProgress>>(it) }.getOrNull()
} ?: emptyList()
fun saveProgress(progress: List<LongformProgress>) {
write(PROGRESS_FILE, json.encodeToString(progress))
}
fun clear() {
delete(CACHE_FILE)
delete(PLAYBACK_FILE)
delete(PROGRESS_FILE)
}
// Web storage can be blocked (Safari private mode) or full. Cache failure
@@ -103,8 +100,7 @@ class LibraryCache(private val storage: AppStorage) {
private companion object {
const val SESSION_FILE = "session.json"
const val CACHE_FILE = "library.json"
const val CACHE_FILE = "mood-cache.json"
const val PLAYBACK_FILE = "playback.json"
const val PROGRESS_FILE = "longform-progress.json"
}
}
File diff suppressed because it is too large. Load diff
@@ -1,18 +1,17 @@
package win.taptap.musicmanager.client.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ArrowBack
import androidx.compose.material.icons.rounded.Delete
import androidx.compose.material.icons.rounded.LibraryMusic
import androidx.compose.material.icons.rounded.DownloadDone
import androidx.compose.material.icons.rounded.Refresh
import androidx.compose.material.icons.rounded.Search
import androidx.compose.material.icons.rounded.Settings
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
@@ -138,7 +137,8 @@ private fun MainScreen(state: AppState, store: AppStore) {
val title = when (state.screen) {
Screen.Moods -> "Moods"
Screen.MoodDetail -> state.selectedMood?.mood?.name ?: "Mood"
Screen.Library -> "Library & downloads"
Screen.Search -> "Add music"
Screen.Downloads -> "Downloads"
Screen.Settings -> "Settings"
}
Text(title, fontWeight = FontWeight.SemiBold)
@@ -157,8 +157,11 @@ private fun MainScreen(state: AppState, store: AppStore) {
IconButton(onClick = { store.refreshAll() }) {
Icon(Icons.Rounded.Refresh, contentDescription = "Refresh")
}
IconButton(onClick = { store.openLibrary() }) {
Icon(Icons.Rounded.LibraryMusic, contentDescription = "Library")
IconButton(onClick = { store.openSearch() }) {
Icon(Icons.Rounded.Search, contentDescription = "Add music")
}
IconButton(onClick = { store.openDownloads() }) {
Icon(Icons.Rounded.DownloadDone, contentDescription = "Downloads")
}
IconButton(onClick = { store.openSettings() }) {
Icon(Icons.Rounded.Settings, contentDescription = "Settings")
@@ -169,7 +172,8 @@ private fun MainScreen(state: AppState, store: AppStore) {
Icon(Icons.Rounded.Delete, contentDescription = "Delete mood")
}
}
Screen.Library -> {
Screen.Search -> Unit
Screen.Downloads -> {
IconButton(onClick = { store.openSettings() }) {
Icon(Icons.Rounded.Settings, contentDescription = "Settings")
}
@@ -189,7 +193,8 @@ private fun MainScreen(state: AppState, store: AppStore) {
when (state.screen) {
Screen.Moods -> MoodsScreen(state, store)
Screen.MoodDetail -> MoodDetailScreen(state, store)
Screen.Library -> LibraryScreen(state, store)
Screen.Search -> SearchScreen(state, store)
Screen.Downloads -> DownloadsScreen(state, store)
Screen.Settings -> SettingsScreen(state, store)
}
}
@@ -200,7 +205,12 @@ private fun MainScreen(state: AppState, store: AppStore) {
AlertDialog(
onDismissRequest = { confirmDelete = false },
title = { Text("Delete mood?") },
text = { Text("\"$name\" and its seeds will be removed. Downloads stay on this device.") },
text = {
Text(
"\"$name\" and its recommendation history will be removed. " +
"Unused downloads are deleted from the server.",
)
},
confirmButton = {
TextButton(
onClick = {
@@ -50,15 +50,15 @@ import win.taptap.musicmanager.client.store.AppStore
@Composable
fun Cover(
store: AppStore,
albumId: String?,
songId: String?,
modifier: Modifier = Modifier,
size: Int = 320,
) {
var bitmap by remember(albumId, size) { mutableStateOf<ImageBitmap?>(null) }
var bitmap by remember(songId, size) { mutableStateOf<ImageBitmap?>(null) }
LaunchedEffect(albumId, size) {
if (albumId == null) return@LaunchedEffect
val bytes = store.cover(albumId)
LaunchedEffect(songId, size) {
if (songId == null) return@LaunchedEffect
val bytes = store.cover(songId)
bitmap = bytes?.let { data -> runCatching { decodeImage(data) }.getOrNull() }
}
@@ -185,7 +185,7 @@ fun SongRow(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Cover(store, song.albumId, Modifier.size(44.dp), size = 96)
Cover(store, song.id, Modifier.size(44.dp), size = 96)
Column(Modifier.weight(1f)) {
Text(
song.title,
@@ -194,7 +194,7 @@ fun SongRow(
overflow = TextOverflow.Ellipsis,
)
Text(
"${song.artist} · ${song.album}",
"${song.artist} · ${song.album ?: "Single"}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
@@ -277,7 +277,7 @@ fun MoodPickerDialog(
Column(Modifier.weight(1f)) {
Text(mood.name, style = MaterialTheme.typography.bodyLarge)
Text(
if (mood.id == currentMoodId) "Current mood" else "${mood.seedCount} seeds",
if (mood.id == currentMoodId) "Current mood" else "${mood.songCount} songs",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
@@ -0,0 +1,130 @@
package win.taptap.musicmanager.client.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Delete
import androidx.compose.material.icons.rounded.DeleteSweep
import androidx.compose.material.icons.rounded.DownloadDone
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
/** Device-side copies for offline playback. The server keeps the originals. */
@Composable
fun DownloadsScreen(state: AppState, store: AppStore) {
if (state.downloads.isEmpty()) {
EmptyState(
"No downloads",
"Download a song from a mood to play it without the server.",
Modifier.fillMaxSize(),
)
return
}
val songs = state.downloads.mapNotNull { state.knownSongs[it] }
val unknown = state.downloads - songs.map { it.id }.toSet()
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(20.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
item {
Surface(
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.surfaceVariant,
modifier = Modifier.fillMaxWidth(),
) {
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
"${state.downloads.size} downloaded",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
)
Text(
"${formatBytes(store.storageBytes())} used on this device",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
OutlinedButton(onClick = { store.clearDownloads() }) {
Icon(Icons.Rounded.DeleteSweep, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text("Clear all")
}
}
}
}
items(songs, key = { it.id }) { song ->
SongRow(store, song, onPlay = { store.playSong(song) }) {
Icon(
Icons.Rounded.DownloadDone,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(18.dp),
)
IconButton(onClick = { store.toggleDownload(song) }) {
Icon(Icons.Rounded.Delete, contentDescription = "Delete download")
}
}
}
items(unknown.toList(), key = { "unknown-$it" }) { id ->
Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Column(Modifier.weight(1f)) {
Text("Downloaded track", style = MaterialTheme.typography.bodyLarge)
Text(
id,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
IconButton(
onClick = {
store.toggleDownload(
win.taptap.musicmanager.client.api.Song(
id = id,
source = "youtube",
externalId = id,
title = id,
artist = "",
duration = 0,
),
)
},
) {
Icon(Icons.Rounded.Delete, contentDescription = "Delete download")
}
}
}
}
}
@@ -1,496 +0,0 @@
package win.taptap.musicmanager.client.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.CheckCircle
import androidx.compose.material.icons.rounded.DeleteOutline
import androidx.compose.material.icons.rounded.Download
import androidx.compose.material.icons.rounded.List
import androidx.compose.material.icons.rounded.PlayArrow
import androidx.compose.material.icons.rounded.Search
import androidx.compose.material.icons.rounded.Shuffle
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRow
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import win.taptap.musicmanager.client.api.LongformProgress
import win.taptap.musicmanager.client.api.Song
import win.taptap.musicmanager.client.platformName
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
@Composable
fun LibraryScreen(state: AppState, store: AppStore) {
var tab by remember { mutableStateOf(0) }
Column(Modifier.fillMaxSize()) {
TabRow(selectedTabIndex = tab) {
Tab(
selected = tab == 0,
onClick = { tab = 0 },
text = { Text("Music") },
)
Tab(
selected = tab == 1,
onClick = { tab = 1 },
text = { Text("Longform") },
)
}
when (tab) {
0 -> MusicLibrary(state, store)
else -> LongformLibrary(state, store)
}
}
}
@Composable
private fun MusicLibrary(state: AppState, store: AppStore) {
var query by remember { mutableStateOf("") }
val supported = platformName != "web"
val downloadedSongs = state.library.filter { it.id in state.downloads }
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(20.dp),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
item {
OutlinedTextField(
value = query,
onValueChange = {
query = it
store.searchMusic(it)
},
singleLine = true,
label = { Text("Search music") },
leadingIcon = { Icon(Icons.Rounded.Search, contentDescription = null) },
trailingIcon = {
if (state.searching) {
CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp)
}
},
modifier = Modifier.fillMaxWidth(),
)
}
item {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surfaceVariant,
modifier = Modifier.fillMaxWidth(),
) {
Row(
modifier = Modifier.padding(16.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Column(Modifier.weight(1f)) {
Text("All music", style = MaterialTheme.typography.titleMedium)
Text(
if (state.library.isEmpty()) {
"Nothing in the library yet"
} else {
"${state.library.size} tracks, shuffled into a queue"
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Button(
onClick = { store.playAll() },
enabled = state.library.isNotEmpty(),
) {
Icon(Icons.Rounded.Shuffle, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(6.dp))
Text("Shuffle all")
}
}
}
}
if (state.musicResults.isNotEmpty()) {
item {
SectionTitle("Search results") {
Text(
"${state.musicResults.size}",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
items(state.musicResults, key = { "search-${it.id}" }) { song ->
LibrarySongRow(song, state, store, supported)
}
item { HorizontalDivider(Modifier.padding(vertical = 14.dp)) }
}
item {
SectionTitle("Downloads") {
Text(
"${state.downloads.size} tracks · ${formatBytes(store.storageBytes())}",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
if (!supported) {
item {
Text(
"The browser plays from the server and lets the browser manage its cache. Install the Android or desktop app for offline downloads.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
} else if (downloadedSongs.isEmpty()) {
item {
Text(
"No downloads yet. Search for a song and press the download icon.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
} else {
items(downloadedSongs, key = { "download-${it.id}" }) { song ->
LibrarySongRow(song, state, store, supported)
}
item {
Text(
"Offline playback uses these files when the server is unreachable.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(top = 8.dp),
)
}
}
}
}
@Composable
private fun LongformLibrary(state: AppState, store: AppStore) {
var query by remember { mutableStateOf("") }
var artistDialog by remember { mutableStateOf<String?>(null) }
val supported = platformName != "web"
val byArtist = state.longform.groupBy { it.artist }
val artistNames = byArtist.keys.sortedBy { it.lowercase() }
val continueListening = state.longformProgress.values
.asSequence()
.filterNot { it.completed }
.sortedByDescending { it.updatedAt }
.mapNotNull { progress ->
state.longform.firstOrNull { it.id == progress.songId }?.let { it to progress }
}
.take(5)
.toList()
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(20.dp),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
item {
OutlinedTextField(
value = query,
onValueChange = {
query = it
store.searchLongform(it)
},
singleLine = true,
label = { Text("Search audiobooks and podcasts") },
leadingIcon = { Icon(Icons.Rounded.Search, contentDescription = null) },
trailingIcon = {
if (state.searching) {
CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp)
}
},
modifier = Modifier.fillMaxWidth(),
)
}
if (state.longformResults.isNotEmpty()) {
item { SectionTitle("Search results") }
items(state.longformResults, key = { "lf-search-${it.id}" }) { song ->
LongformSongRow(song, state, store, supported) { store.playLongformSong(song) }
}
item { HorizontalDivider(Modifier.padding(vertical = 14.dp)) }
}
if (continueListening.isNotEmpty()) {
item { SectionTitle("Continue listening") }
items(continueListening, key = { "continue-${it.first.id}" }) { (song, progress) ->
ContinueRow(song, progress, store)
}
item { HorizontalDivider(Modifier.padding(vertical = 14.dp)) }
}
item {
SectionTitle("Artists") {
Text(
"${artistNames.size}",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
if (artistNames.isEmpty()) {
item {
EmptyState(
"No long-form content",
"Add audiobooks or podcasts to a folder of type longform in library.yaml.",
)
}
} else {
items(artistNames, key = { "artist-$it" }) { artist ->
val songs = byArtist[artist].orEmpty()
ArtistRow(
name = artist,
count = songs.size,
onShuffle = { store.playLongformArtist(artist) },
onOpen = { artistDialog = artist },
)
}
}
}
artistDialog?.let { artist ->
LongformArtistDialog(
artist = artist,
songs = byArtist[artist].orEmpty(),
state = state,
store = store,
supported = supported,
onDismiss = { artistDialog = null },
)
}
}
@Composable
private fun ContinueRow(song: Song, progress: LongformProgress, store: AppStore) {
val duration = progress.durationSeconds.takeIf { it > 0 } ?: song.duration
val fraction = if (duration > 0) {
(progress.positionSeconds.toFloat() / duration).coerceIn(0f, 1f)
} else {
0f
}
Row(
modifier = Modifier
.fillMaxWidth()
.clickable { store.resumeLongform(song.id) }
.padding(vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Cover(store, song.albumId, Modifier.size(44.dp), size = 96)
Column(Modifier.weight(1f)) {
Text(song.title, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
song.artist,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Box(
Modifier
.fillMaxWidth()
.padding(top = 4.dp)
.height(3.dp)
.clip(RoundedCornerShape(2.dp))
.background(MaterialTheme.colorScheme.surfaceVariant),
) {
Box(
Modifier
.fillMaxWidth(fraction)
.height(3.dp)
.background(MaterialTheme.colorScheme.primary),
)
}
Text(
"${formatDuration(progress.positionSeconds)} / ${formatDuration(duration)}",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
IconButton(onClick = { store.resumeLongform(song.id) }) {
Icon(Icons.Rounded.PlayArrow, contentDescription = "Resume")
}
}
}
@Composable
private fun ArtistRow(
name: String,
count: Int,
onShuffle: () -> Unit,
onOpen: () -> Unit,
) {
Row(
modifier = Modifier.fillMaxWidth().clickable(onClick = onOpen).padding(vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
Column(Modifier.weight(1f)) {
Text(name, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
"$count tracks",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
IconButton(onClick = onShuffle) {
Icon(Icons.Rounded.Shuffle, contentDescription = "Play $name shuffled")
}
IconButton(onClick = onOpen) {
Icon(Icons.Rounded.List, contentDescription = "Show tracks")
}
}
}
@Composable
private fun LongformArtistDialog(
artist: String,
songs: List<Song>,
state: AppState,
store: AppStore,
supported: Boolean,
onDismiss: () -> Unit,
) {
Dialog(onDismissRequest = onDismiss) {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surface,
tonalElevation = 6.dp,
modifier = Modifier.fillMaxWidth().heightIn(max = 600.dp),
) {
Column {
Row(
modifier = Modifier.padding(20.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f)) {
Text(artist, style = MaterialTheme.typography.titleMedium, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
"${songs.size} tracks · read-only playlist",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
TextButton(onClick = onDismiss) { Text("Close") }
}
Row(modifier = Modifier.padding(horizontal = 20.dp)) {
Button(
onClick = {
store.playLongformArtist(artist)
onDismiss()
},
enabled = songs.isNotEmpty(),
) {
Icon(Icons.Rounded.Shuffle, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(6.dp))
Text("Shuffle artist")
}
}
HorizontalDivider(Modifier.padding(vertical = 12.dp))
LazyColumn(Modifier.fillMaxWidth().heightIn(max = 460.dp)) {
items(songs, key = { "artist-song-${it.id}" }) { song ->
LongformSongRow(song, state, store, supported) {
store.playLongformSong(song)
onDismiss()
}
}
}
}
}
}
}
@Composable
private fun LongformSongRow(
song: Song,
state: AppState,
store: AppStore,
supported: Boolean,
onPlay: () -> Unit,
) {
SongRow(store = store, song = song, onPlay = onPlay) {
DownloadAction(song, state, store, supported)
IconButton(onClick = onPlay) {
Icon(Icons.Rounded.PlayArrow, contentDescription = "Play")
}
}
}
@Composable
private fun LibrarySongRow(song: Song, state: AppState, store: AppStore, supported: Boolean) {
SongRow(store = store, song = song, onPlay = { store.playSong(song) }) {
DownloadAction(song, state, store, supported)
if (song.id in state.downloads) {
Icon(
Icons.Rounded.CheckCircle,
contentDescription = "Downloaded",
tint = MaterialTheme.colorScheme.secondary,
modifier = Modifier.size(18.dp),
)
}
IconButton(onClick = { store.playSong(song) }) {
Icon(Icons.Rounded.PlayArrow, contentDescription = "Play")
}
}
}
@Composable
private fun DownloadAction(song: Song, state: AppState, store: AppStore, supported: Boolean) {
if (!supported) return
when {
song.id in state.downloading -> CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp)
song.id in state.downloads -> {
IconButton(onClick = { store.toggleDownload(song) }) {
Icon(Icons.Rounded.DeleteOutline, contentDescription = "Delete download")
}
}
else -> {
IconButton(onClick = { store.toggleDownload(song) }) {
Icon(Icons.Rounded.Download, contentDescription = "Download")
}
}
}
}
@@ -1,6 +1,7 @@
package win.taptap.musicmanager.client.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
@@ -15,13 +16,17 @@ import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Add
import androidx.compose.material.icons.rounded.Check
import androidx.compose.material.icons.rounded.Close
import androidx.compose.material.icons.rounded.Download
import androidx.compose.material.icons.rounded.DownloadDone
import androidx.compose.material.icons.rounded.PlayArrow
import androidx.compose.material.icons.rounded.Refresh
import androidx.compose.material.icons.rounded.RemoveCircleOutline
import androidx.compose.material.icons.rounded.Search
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
@@ -31,7 +36,6 @@ import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Slider
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
@@ -46,17 +50,22 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import kotlin.math.roundToInt
import win.taptap.musicmanager.client.api.MoodSong
import win.taptap.musicmanager.client.api.Recommendation
import win.taptap.musicmanager.client.api.Song
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
import win.taptap.musicmanager.client.store.sourceLabel
@Composable
fun MoodDetailScreen(state: AppState, store: AppStore) {
val detail = state.selectedMood
if (state.loading && detail == null) {
Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) {
Column(
Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
CircularProgressIndicator()
}
return
@@ -68,31 +77,32 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
}
val mood = detail.mood
var seedQuery by remember { mutableStateOf("") }
var name by remember(mood.id) { mutableStateOf(mood.name) }
var description by remember(mood.id) { mutableStateOf(mood.description.orEmpty()) }
var genres by remember(mood.id) { mutableStateOf(mood.genres.joinToString(", ")) }
var query by remember(mood.id) { mutableStateOf(mood.query.orEmpty()) }
var target by remember(mood.id) { mutableStateOf(mood.targetSize.toString()) }
var source by remember(mood.id) { mutableStateOf(mood.source) }
var sourceMenu by remember { mutableStateOf(false) }
var collectionPercent by remember(mood.id) { mutableStateOf(mood.collectionPercent.toFloat()) }
var recommendations by remember(mood.id) { mutableStateOf(mood.recommendationCount.toFloat()) }
var hours by remember(mood.id) { mutableStateOf(mood.refreshHours.toString()) }
var yt by remember(mood.id) { mutableStateOf(mood.ytEnabled) }
var seedPercent by remember(mood.id) { mutableStateOf(mood.seedPercent.toFloat()) }
val pendingDownloads = detail.recommendations.count {
val inFlight = mood.recommendationDownloading +
detail.recommendations.count {
it.download?.state == "queued" || it.download?.state == "downloading"
}
LaunchedEffect(detail.mood.id, pendingDownloads) {
// A new mood gets its first batch from a background discovery run, which
// resolves the YouTube Music search. Keep refreshing until it lands.
val waitingForFirstBatch = mood.recommendationCount > 0 && detail.recommendations.isEmpty()
LaunchedEffect(mood.id, inFlight, waitingForFirstBatch) {
var polls = 0
while (pendingDownloads > 0 && polls < 60) {
kotlinx.coroutines.delay(10_000)
while ((inFlight > 0 || waitingForFirstBatch) && polls < 60) {
kotlinx.coroutines.delay(5_000)
store.refreshSelectedMood()
polls += 1
}
}
val seedIds = detail.seeds.map { it.song.id }.toSet()
val searchResults = state.searchResults.filterNot { it.id in seedIds }
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(20.dp),
@@ -106,98 +116,71 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
) {
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text(
mood.description ?: "Server-driven radio",
mood.description ?: "Your private mix",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
Text("${mood.seedCount} seeds", style = MaterialTheme.typography.labelMedium)
Text("·", color = MaterialTheme.colorScheme.onSurfaceVariant)
Text("${mood.targetSize} batch", style = MaterialTheme.typography.labelMedium)
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
Text("${mood.songCount} songs", style = MaterialTheme.typography.labelMedium)
Text("·", color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(
"${mood.seedPercent}% seeds",
"${mood.collectionPercent}% collection",
style = MaterialTheme.typography.labelMedium,
)
Spacer(Modifier.weight(1f))
Button(onClick = { store.playMood(mood.id) }) {
Button(onClick = { store.playMood(mood.id) }, enabled = mood.songCount > 0) {
Icon(Icons.Rounded.PlayArrow, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(6.dp))
Text("Play radio")
}
}
if (mood.lastError != null) {
Text(mood.lastError, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
Text(
mood.lastError,
color = MaterialTheme.colorScheme.error,
style = MaterialTheme.typography.bodySmall,
)
}
}
}
}
item {
SectionTitle("Seeds") {
SectionTitle("Songs") {
Text(
"${detail.seeds.size}",
"${detail.songs.size}",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
if (detail.seeds.isEmpty()) {
if (detail.songs.isEmpty()) {
item {
Text(
"No seeds yet. Add a few songs below; every seed is always part of the radio.",
"A mood needs at least one song before it can play. Use Add music to search YouTube.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
} else {
items(detail.seeds, key = { it.song.id }) { seed ->
SongRow(
store = store,
song = seed.song,
onPlay = { store.playSong(seed.song) },
) {
Text(seed.origin, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
IconButton(onClick = { store.removeSeed(mood.id, seed.song.id) }) {
Icon(Icons.Rounded.RemoveCircleOutline, contentDescription = "Remove seed")
items(detail.songs, key = { it.song.id }) { entry ->
MoodSongRow(entry, store, mood.id, downloaded = entry.song.id in state.downloads)
}
}
}
}
item {
HorizontalDivider(Modifier.padding(vertical = 12.dp))
SectionTitle("Add songs")
}
item {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(top = 4.dp),
horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxWidth(),
) {
OutlinedTextField(
value = seedQuery,
onValueChange = { seedQuery = it },
singleLine = true,
label = { Text("Search your music") },
modifier = Modifier.weight(1f),
)
OutlinedButton(onClick = { store.search(seedQuery) }, enabled = seedQuery.isNotBlank()) {
Text("Search")
}
}
}
if (state.searching) {
item { CircularProgressIndicator(Modifier.size(22.dp)) }
}
items(searchResults.take(12), key = { it.id }) { song ->
SongRow(store = store, song = song, onPlay = { store.playSong(song) }) {
IconButton(onClick = { store.addSeed(mood.id, song.id) }) {
Icon(Icons.Rounded.Add, contentDescription = "Add seed")
FilledTonalButton(onClick = { store.openSearch(mood.id) }) {
Icon(Icons.Rounded.Search, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(6.dp))
Text("Add music")
}
}
}
@@ -208,16 +191,15 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
SectionTitle("Next batch")
}
items(state.preview, key = { "preview-${it.id}" }) { song ->
SongRow(store = store, song = song, onPlay = { store.playSong(song) }) {
SongRow(store, song, onPlay = { store.playSong(song) }) {
Text(formatDuration(song.duration), style = MaterialTheme.typography.labelSmall)
}
}
}
if (mood.ytEnabled) {
item {
HorizontalDivider(Modifier.padding(vertical = 12.dp))
SectionTitle("Recommended for this mood") {
SectionTitle("Recommendations") {
Row(verticalAlignment = Alignment.CenterVertically) {
if (state.discovering) {
CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
@@ -225,7 +207,7 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
}
TextButton(
onClick = { store.refreshRecommendations() },
enabled = !state.discovering,
enabled = !state.discovering && mood.recommendationCount > 0,
) {
Icon(Icons.Rounded.Refresh, contentDescription = null, modifier = Modifier.size(16.dp))
Spacer(Modifier.width(4.dp))
@@ -235,25 +217,31 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
}
}
val visible = detail.recommendations.filter { it.state != "rejected" }
if (visible.isEmpty()) {
if (mood.recommendationCount == 0) {
item {
Text(
"Recommendations are off for this mood. Raise the count in settings to let the server download picks.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
} else if (detail.recommendations.isEmpty()) {
item {
Text(
if (state.discovering) {
"Searching YouTube Music..."
"Searching and downloading picks…"
} else {
"No recommendations yet. Refresh to search for tracks that fit this mood."
"No recommendations yet. The server tops this mood up automatically."
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
} else {
items(visible, key = { "rec-${it.videoId}" }) { recommendation ->
items(detail.recommendations, key = { "rec-${it.source}-${it.externalId}" }) { recommendation ->
RecommendationRow(recommendation, state.discovering, store)
}
}
}
item {
HorizontalDivider(Modifier.padding(vertical = 12.dp))
@@ -286,47 +274,90 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
OutlinedTextField(
value = query,
onValueChange = { query = it },
label = { Text("Free-text hint") },
label = { Text("Discovery hint") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
OutlinedTextField(
value = target,
onValueChange = { target = it },
label = { Text("Batch size") },
singleLine = true,
modifier = Modifier.weight(1f),
)
OutlinedTextField(
value = hours,
onValueChange = { hours = it },
label = { Text("Refresh h") },
singleLine = true,
modifier = Modifier.weight(1f),
)
}
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f)) {
Text("Download source", style = MaterialTheme.typography.bodyMedium)
Text(
"Seed mix: ${seedPercent.roundToInt()}% seeds · ${100 - seedPercent.roundToInt()}% recommendations",
style = MaterialTheme.typography.bodySmall,
)
Slider(
value = seedPercent,
onValueChange = { seedPercent = it },
valueRange = 0f..100f,
steps = 9,
)
Text(
"Each queued track rolls this share independently; if one side runs out, the other fills in.",
"Search, recommendations and downloads use this catalog.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Row(verticalAlignment = Alignment.CenterVertically) {
Text("YT Music discovery", Modifier.weight(1f))
Switch(checked = yt, onCheckedChange = { yt = it })
Box {
OutlinedButton(onClick = { sourceMenu = true }) {
Text(sourceLabel(source))
}
DropdownMenu(
expanded = sourceMenu,
onDismissRequest = { sourceMenu = false },
) {
listOf("deezer", "youtube").forEach { option ->
DropdownMenuItem(
text = { Text(sourceLabel(option)) },
onClick = {
sourceMenu = false
source = option
},
)
}
}
}
}
if (source != mood.source) {
Text(
"Changing the source clears active recommendations and refills them.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.tertiary,
)
}
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(
"Collection share: ${collectionPercent.roundToInt()}% · ${100 - collectionPercent.roundToInt()}% recommendations",
style = MaterialTheme.typography.bodySmall,
)
Slider(
value = collectionPercent,
onValueChange = { collectionPercent = it },
valueRange = 0f..100f,
steps = 9,
)
Text(
"Each queue slot rolls this share; when one pool runs out the other fills in.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(
"Active recommendations: ${recommendations.roundToInt()}",
style = MaterialTheme.typography.bodySmall,
)
Slider(
value = recommendations,
onValueChange = { recommendations = it },
valueRange = 0f..30f,
steps = 29,
)
Text(
"Downloaded picks that count as active slots (0 turns discovery off).",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
OutlinedTextField(
value = hours,
onValueChange = { hours = it },
label = { Text("Refresh interval (hours)") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
FilledTonalButton(
enabled = !state.saving && name.isNotBlank(),
onClick = {
@@ -336,10 +367,10 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
description = description.trim().takeIf { it.isNotEmpty() },
genres = genres.split(',').map { it.trim() }.filter { it.isNotEmpty() },
query = query.trim().takeIf { it.isNotEmpty() },
targetSize = target.toIntOrNull() ?: mood.targetSize,
source = source,
collectionPercent = collectionPercent.roundToInt(),
recommendationCount = recommendations.roundToInt(),
refreshHours = hours.toIntOrNull() ?: mood.refreshHours,
ytEnabled = yt,
seedPercent = seedPercent.roundToInt(),
)
},
modifier = Modifier.fillMaxWidth(),
@@ -353,18 +384,45 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
}
}
@Composable
private fun MoodSongRow(entry: MoodSong, store: AppStore, moodId: String, downloaded: Boolean) {
val song = entry.song
SongRow(store, song, onPlay = { store.playSong(song) }) {
IconButton(onClick = { store.toggleDownload(song) }) {
Icon(
if (downloaded) Icons.Rounded.DownloadDone else Icons.Rounded.Download,
contentDescription = if (downloaded) "Delete download" else "Download for offline",
tint = if (downloaded) {
MaterialTheme.colorScheme.primary
} else {
MaterialTheme.colorScheme.onSurfaceVariant
},
)
}
IconButton(onClick = { store.removeSong(moodId, song.id) }) {
Icon(Icons.Rounded.RemoveCircleOutline, contentDescription = "Remove from mood")
}
}
}
@Composable
private fun RecommendationRow(
recommendation: Recommendation,
busy: Boolean,
store: AppStore,
) {
val failed = recommendation.state == "failed" ||
recommendation.download?.state == "failed"
Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
if (recommendation.song != null) {
Cover(store, recommendation.song.id, Modifier.size(48.dp), size = 96)
} else {
RemoteImage(store, recommendation.thumbnail, Modifier.size(48.dp))
}
Column(Modifier.weight(1f)) {
Text(
recommendation.title,
@@ -375,35 +433,29 @@ private fun RecommendationRow(
Text(
buildString {
append(recommendation.artist)
recommendation.album?.takeIf { it.isNotBlank() }?.let { append(" · ").append(it) }
recommendation.duration?.let { append(" · ").append(formatDuration(it)) }
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
val download = recommendation.download
Text(
when {
recommendation.state == "accepted" && recommendation.matchedSong != null -> "Seed added"
download?.state == "downloading" -> "Downloading..."
download?.state == "failed" -> "Download failed — tap ✓ to retry"
download?.state == "queued" -> "Download queued"
recommendation.state == "accepted" -> "Queued for download"
recommendation.matchedSong != null -> "In your library"
else -> "New"
failed -> "Download failed"
recommendation.state == "ready" -> "Ready to add"
else -> "Downloading…"
},
style = MaterialTheme.typography.labelSmall,
color = when {
download?.state == "failed" -> MaterialTheme.colorScheme.error
recommendation.state == "accepted" || download != null ->
color = if (failed) {
MaterialTheme.colorScheme.error
} else {
MaterialTheme.colorScheme.primary
else -> MaterialTheme.colorScheme.onSurfaceVariant
},
)
if (download?.state == "failed" && download.error != null) {
if (failed && recommendation.error != null) {
Text(
download.error,
recommendation.error,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.error,
maxLines = 2,
@@ -411,26 +463,26 @@ private fun RecommendationRow(
)
}
}
if (recommendation.state == "accepted" && recommendation.download?.state != "failed") {
Icon(
Icons.Rounded.Check,
contentDescription = "Accepted",
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(20.dp),
)
if (failed) {
IconButton(
onClick = { store.retryRecommendation(recommendation.externalId) },
enabled = !busy,
) {
Icon(Icons.Rounded.Refresh, contentDescription = "Retry download")
}
} else {
IconButton(
onClick = { store.acceptRecommendation(recommendation.videoId) },
onClick = { store.addRecommendation(recommendation.externalId) },
enabled = !busy,
) {
Icon(Icons.Rounded.Check, contentDescription = "Accept recommendation")
Icon(Icons.Rounded.Add, contentDescription = "Add to mood")
}
}
IconButton(
onClick = { store.rejectRecommendation(recommendation.videoId) },
onClick = { store.rejectRecommendation(recommendation.externalId) },
enabled = !busy,
) {
Icon(Icons.Rounded.Close, contentDescription = "Reject recommendation")
}
Icon(Icons.Rounded.Close, contentDescription = "Not interested")
}
}
}
@@ -27,12 +27,14 @@ import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Slider
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
@@ -51,6 +53,7 @@ import kotlin.math.roundToInt
import win.taptap.musicmanager.client.api.Mood
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
import win.taptap.musicmanager.client.store.sourceLabel
@Composable
fun MoodsScreen(state: AppState, store: AppStore) {
@@ -68,7 +71,7 @@ fun MoodsScreen(state: AppState, store: AppStore) {
fontWeight = FontWeight.SemiBold,
)
Text(
"Radio is generated live and learns from what you finish or skip.",
"Songs are downloaded from YouTube. Recommendations refill automatically.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
@@ -90,7 +93,7 @@ fun MoodsScreen(state: AppState, store: AppStore) {
if (state.moods.isEmpty()) {
EmptyState(
title = "No moods yet",
subtitle = "Create a mood, add a few seed songs, and press play. The server builds the rest.",
subtitle = "Create a mood, add a few songs, and press play. The server builds and downloads the rest.",
modifier = Modifier.fillMaxSize(),
)
} else {
@@ -116,9 +119,18 @@ fun MoodsScreen(state: AppState, store: AppStore) {
CreateMoodDialog(
saving = state.saving,
onDismiss = { creating = false },
onCreate = { name, description, genres, query, target, hours, yt, seedPercent ->
onCreate = { name, description, genres, query, source, collectionPercent, recommendations, hours ->
creating = false
store.createMood(name, description, genres, query, target, hours, yt, seedPercent)
store.createMood(
name,
description,
genres,
query,
source,
collectionPercent,
recommendations,
hours,
)
},
)
}
@@ -144,7 +156,7 @@ private fun MoodCard(mood: Mood, onOpen: () -> Unit, onPlay: () -> Unit) {
overflow = TextOverflow.Ellipsis,
)
Text(
mood.description ?: mood.genres.joinToString(" · ").ifBlank { "Server-driven radio" },
mood.description ?: mood.genres.joinToString(" · ").ifBlank { "Your private mix" },
style = MaterialTheme.typography.bodySmall,
color = Color.White.copy(alpha = 0.78f),
maxLines = 2,
@@ -153,21 +165,29 @@ private fun MoodCard(mood: Mood, onOpen: () -> Unit, onPlay: () -> Unit) {
)
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
"${mood.seedCount} seeds",
"${mood.songCount} songs",
style = MaterialTheme.typography.labelMedium,
color = Color.White.copy(alpha = 0.85f),
)
if (mood.newRecommendations > 0) {
val picks = mood.recommendationReady + mood.recommendationDownloading
if (picks > 0) {
Spacer(Modifier.width(8.dp))
Text(
"${mood.newRecommendations} picks",
"$picks picks",
style = MaterialTheme.typography.labelMedium,
color = Color.White.copy(alpha = 0.85f),
)
}
Spacer(Modifier.width(8.dp))
Text(
sourceLabel(mood.source),
style = MaterialTheme.typography.labelMedium,
color = Color.White.copy(alpha = 0.7f),
)
Spacer(Modifier.weight(1f))
FilledTonalButton(
onClick = onPlay,
enabled = mood.songCount > 0,
colors = ButtonDefaults.filledTonalButtonColors(
containerColor = Color.White.copy(alpha = 0.16f),
contentColor = Color.White,
@@ -186,16 +206,17 @@ private fun MoodCard(mood: Mood, onOpen: () -> Unit, onPlay: () -> Unit) {
private fun CreateMoodDialog(
saving: Boolean,
onDismiss: () -> Unit,
onCreate: (String, String?, List<String>, String?, Int, Int, Boolean, Int) -> Unit,
onCreate: (String, String?, List<String>, String?, String, Int, Int, Int) -> Unit,
) {
var name by remember { mutableStateOf("") }
var description by remember { mutableStateOf("") }
var genres by remember { mutableStateOf("") }
var query by remember { mutableStateOf("") }
var target by remember { mutableStateOf("30") }
var source by remember { mutableStateOf("deezer") }
var sourceMenu by remember { mutableStateOf(false) }
var collectionPercent by remember { mutableStateOf(50f) }
var recommendations by remember { mutableStateOf(10f) }
var hours by remember { mutableStateOf("24") }
var yt by remember { mutableStateOf(true) }
var seedPercent by remember { mutableStateOf(50f) }
AlertDialog(
onDismissRequest = onDismiss,
@@ -226,41 +247,68 @@ private fun CreateMoodDialog(
OutlinedTextField(
value = query,
onValueChange = { query = it },
label = { Text("Free-text hint") },
label = { Text("Discovery hint") },
singleLine = true,
)
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
OutlinedTextField(
value = target,
onValueChange = { target = it },
label = { Text("Batch size") },
singleLine = true,
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
"Download source",
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.weight(1f),
)
OutlinedTextField(
value = hours,
onValueChange = { hours = it },
label = { Text("Refresh h") },
singleLine = true,
modifier = Modifier.weight(1f),
Box {
OutlinedButton(onClick = { sourceMenu = true }) {
Text(sourceLabel(source))
}
DropdownMenu(
expanded = sourceMenu,
onDismissRequest = { sourceMenu = false },
) {
listOf("deezer", "youtube").forEach { option ->
DropdownMenuItem(
text = { Text(sourceLabel(option)) },
onClick = {
sourceMenu = false
source = option
},
)
}
}
}
}
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(
"Seed mix: ${seedPercent.roundToInt()}% seeds · ${100 - seedPercent.roundToInt()}% recommendations",
"Collection share: ${collectionPercent.roundToInt()}% · ${100 - collectionPercent.roundToInt()}% recommendations",
style = MaterialTheme.typography.bodySmall,
)
Slider(
value = seedPercent,
onValueChange = { seedPercent = it },
value = collectionPercent,
onValueChange = { collectionPercent = it },
valueRange = 0f..100f,
steps = 9,
)
}
Row(verticalAlignment = Alignment.CenterVertically) {
Text("YT Music discovery", Modifier.weight(1f))
Switch(checked = yt, onCheckedChange = { yt = it })
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(
"Active recommendations: ${recommendations.roundToInt()}",
style = MaterialTheme.typography.bodySmall,
)
Slider(
value = recommendations,
onValueChange = { recommendations = it },
valueRange = 0f..30f,
steps = 29,
)
}
OutlinedTextField(
value = hours,
onValueChange = { hours = it },
label = { Text("Refresh interval (hours)") },
singleLine = true,
)
}
},
confirmButton = {
@@ -272,10 +320,10 @@ private fun CreateMoodDialog(
description.trim().takeIf { it.isNotEmpty() },
genres.split(',').map { it.trim() }.filter { it.isNotEmpty() },
query.trim().takeIf { it.isNotEmpty() },
target.toIntOrNull() ?: 30,
source,
collectionPercent.roundToInt(),
recommendations.roundToInt(),
hours.toIntOrNull() ?: 24,
yt,
seedPercent.roundToInt(),
)
},
) { Text("Create") }
@@ -1,11 +1,15 @@
package win.taptap.musicmanager.client.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress
import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
@@ -13,13 +17,14 @@ import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.AddCircleOutline
import androidx.compose.material.icons.rounded.Bedtime
import androidx.compose.material.icons.rounded.Close
import androidx.compose.material.icons.rounded.KeyboardArrowDown
import androidx.compose.material.icons.rounded.KeyboardArrowUp
import androidx.compose.material.icons.rounded.DragHandle
import androidx.compose.material.icons.rounded.MoreVert
import androidx.compose.material.icons.rounded.Pause
import androidx.compose.material.icons.rounded.PlayArrow
import androidx.compose.material.icons.rounded.PlaylistAdd
@@ -37,27 +42,36 @@ import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.zIndex
import kotlinx.coroutines.delay
import kotlin.math.roundToInt
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
private val QUEUE_ROW_HEIGHT = 58.dp
@Composable
fun PlayerBar(state: AppState, store: AppStore) {
val song = state.current ?: return
var picker by remember { mutableStateOf(false) }
var sleepMenu by remember { mutableStateOf(false) }
var moreMenu by remember { mutableStateOf(false) }
var queueOpen by remember { mutableStateOf(false) }
var dragSeconds by remember(song.id) { mutableStateOf<Float?>(null) }
val sleepRemaining = state.sleepTimerRemainingSeconds
val isLongform = state.user?.longformFolders?.contains(song.folderId) == true
Surface(
color = MaterialTheme.colorScheme.surfaceVariant,
@@ -91,6 +105,36 @@ fun PlayerBar(state: AppState, store: AppStore) {
IconButton(onClick = { queueOpen = true }) {
Icon(Icons.Rounded.QueueMusic, contentDescription = "Queue")
}
Box {
IconButton(onClick = { moreMenu = true }) {
Icon(Icons.Rounded.MoreVert, contentDescription = "More actions")
}
DropdownMenu(
expanded = moreMenu,
onDismissRequest = { moreMenu = false },
) {
DropdownMenuItem(
text = { Text("Add to current mood") },
leadingIcon = {
Icon(Icons.Rounded.AddCircleOutline, contentDescription = null)
},
onClick = {
moreMenu = false
store.addCurrentToMood(null)
},
)
DropdownMenuItem(
text = { Text("Add to another mood") },
leadingIcon = {
Icon(Icons.Rounded.PlaylistAdd, contentDescription = null)
},
onClick = {
moreMenu = false
picker = true
},
)
}
}
Box {
IconButton(onClick = { sleepMenu = true }) {
Icon(
@@ -131,11 +175,13 @@ fun PlayerBar(state: AppState, store: AppStore) {
}
Row(
modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 8.dp, bottom = 8.dp),
modifier = Modifier
.fillMaxWidth()
.padding(start = 12.dp, end = 8.dp, bottom = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
horizontalArrangement = Arrangement.spacedBy(6.dp),
) {
Cover(store, song.albumId, Modifier.size(48.dp), size = 160)
Cover(store, song.id, Modifier.size(48.dp), size = 160)
Column(Modifier.weight(1f)) {
Text(
song.title,
@@ -167,27 +213,36 @@ fun PlayerBar(state: AppState, store: AppStore) {
)
}
if (!isLongform) {
IconButton(onClick = { store.addCurrentToMood(null) }) {
Icon(Icons.Rounded.AddCircleOutline, contentDescription = "Add to current mood")
IconButton(
onClick = { store.previous() },
modifier = Modifier.size(40.dp),
) {
Icon(
Icons.Rounded.SkipPrevious,
contentDescription = "Previous",
modifier = Modifier.size(26.dp),
)
}
IconButton(onClick = { picker = true }) {
Icon(Icons.Rounded.PlaylistAdd, contentDescription = "Add to another mood")
}
}
IconButton(onClick = { store.previous() }) {
Icon(Icons.Rounded.SkipPrevious, contentDescription = "Previous")
}
IconButton(onClick = { store.skip() }) {
Icon(Icons.Rounded.SkipNext, contentDescription = "Skip")
}
IconButton(onClick = { store.togglePlayPause() }) {
IconButton(
onClick = { store.togglePlayPause() },
modifier = Modifier.size(48.dp),
) {
Icon(
if (state.playing) Icons.Rounded.Pause else Icons.Rounded.PlayArrow,
contentDescription = if (state.playing) "Pause" else "Play",
modifier = Modifier.size(30.dp),
)
}
IconButton(
onClick = { store.skip() },
modifier = Modifier.size(40.dp),
) {
Icon(
Icons.Rounded.SkipNext,
contentDescription = "Skip",
modifier = Modifier.size(26.dp),
)
}
}
}
}
@@ -211,12 +266,43 @@ fun PlayerBar(state: AppState, store: AppStore) {
@Composable
private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit) {
val listState = rememberLazyListState()
var draggingIndex by remember { mutableStateOf<Int?>(null) }
var dragPointerY by remember { mutableStateOf(0f) }
var grabOffset by remember { mutableStateOf(0f) }
val edgePx = with(LocalDensity.current) { 48.dp.toPx() }
fun queueIndexAt(y: Float): Int? =
listState.layoutInfo.visibleItemsInfo
.firstOrNull { y >= it.offset && y < it.offset + it.size }
?.index
LaunchedEffect(draggingIndex) {
while (draggingIndex != null) {
val y = dragPointerY
val edge = edgePx
val viewport = listState.layoutInfo.viewportEndOffset.toFloat()
if (y < edge) {
listState.scrollBy(-18f)
} else if (y > viewport - edge) {
listState.scrollBy(18f)
}
val from = draggingIndex
val to = queueIndexAt(y)
if (from != null && to != null && to != from) {
store.moveInQueue(from, to)
draggingIndex = to
}
delay(16)
}
}
Dialog(onDismissRequest = onDismiss) {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surface,
tonalElevation = 6.dp,
modifier = Modifier.fillMaxWidth().heightIn(max = 600.dp),
modifier = Modifier.fillMaxWidth().heightIn(max = 620.dp),
) {
Column {
Row(
@@ -226,7 +312,11 @@ private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit)
Column(Modifier.weight(1f)) {
Text("Queue", style = MaterialTheme.typography.titleMedium)
Text(
"${state.queue.size} upcoming",
if (state.queue.isEmpty()) {
"Nothing queued"
} else {
"${state.queue.size} upcoming · long-press and drag to reorder"
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
@@ -234,17 +324,23 @@ private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit)
TextButton(onClick = onDismiss) { Text("Close") }
}
HorizontalDivider()
LazyColumn(Modifier.fillMaxWidth().heightIn(max = 480.dp)) {
state.current?.let { song ->
item(key = "current") {
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 10.dp),
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Cover(store, song.albumId, Modifier.size(40.dp), size = 96)
Cover(store, song.id, Modifier.size(40.dp), size = 96)
Column(Modifier.weight(1f)) {
Text(song.title, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
song.title,
style = MaterialTheme.typography.bodyLarge,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
"Now playing",
style = MaterialTheme.typography.labelSmall,
@@ -252,29 +348,86 @@ private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit)
)
}
}
}
HorizontalDivider()
}
if (state.queue.isEmpty()) {
item {
Text(
"Nothing queued. Start a mood, shuffle all or an artist.",
"Nothing queued. Start a mood to build a radio queue.",
modifier = Modifier.padding(20.dp),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
} else {
Box(
modifier = Modifier
.fillMaxWidth()
.pointerInput(Unit) {
detectDragGesturesAfterLongPress(
onDragStart = { offset ->
val index = queueIndexAt(offset.y)
val info = listState.layoutInfo.visibleItemsInfo
.firstOrNull { it.index == index }
if (index != null && info != null) {
draggingIndex = index
dragPointerY = offset.y
grabOffset = offset.y - info.offset
}
},
onDrag = { change, _ ->
change.consume()
dragPointerY = change.position.y
val from = draggingIndex
val to = queueIndexAt(change.position.y)
if (from != null && to != null && to != from) {
store.moveInQueue(from, to)
draggingIndex = to
}
},
onDragEnd = { draggingIndex = null },
onDragCancel = { draggingIndex = null },
)
},
) {
LazyColumn(
state = listState,
modifier = Modifier.fillMaxWidth().heightIn(max = 500.dp),
) {
itemsIndexed(state.queue, key = { _, song -> song.id }) { index, song ->
val isDragging = index == draggingIndex
val rowInfo = if (isDragging) {
listState.layoutInfo.visibleItemsInfo
.firstOrNull { it.index == index }
} else {
null
}
val translation = if (rowInfo != null) {
dragPointerY - rowInfo.offset - grabOffset
} else {
0f
}
itemsIndexed(state.queue, key = { index, _ -> "queue-$index" }) { index, song ->
Row(
modifier = Modifier.fillMaxWidth().padding(start = 20.dp, end = 8.dp, top = 6.dp, bottom = 6.dp),
modifier = Modifier
.fillMaxWidth()
.height(QUEUE_ROW_HEIGHT)
.background(MaterialTheme.colorScheme.surface)
.zIndex(if (isDragging) 1f else 0f)
.graphicsLayer {
translationY = translation
shadowElevation = if (isDragging) 8.dp.toPx() else 0f
}
.padding(start = 20.dp, end = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
Cover(store, song.albumId, Modifier.size(36.dp), size = 96)
Cover(store, song.id, Modifier.size(36.dp), size = 96)
Column(Modifier.weight(1f)) {
Text(song.title, style = MaterialTheme.typography.bodyMedium, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
song.title,
style = MaterialTheme.typography.bodyMedium,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
song.artist,
style = MaterialTheme.typography.labelSmall,
@@ -283,19 +436,19 @@ private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit)
overflow = TextOverflow.Ellipsis,
)
}
Icon(
Icons.Rounded.DragHandle,
contentDescription = "Drag to reorder",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(22.dp),
)
IconButton(
onClick = { store.moveInQueue(index, index - 1) },
enabled = index > 0,
onClick = {
val from = store.state.value.queue
.indexOfFirst { it.id == song.id }
if (from >= 0) store.removeFromQueue(from)
},
) {
Icon(Icons.Rounded.KeyboardArrowUp, contentDescription = "Move up")
}
IconButton(
onClick = { store.moveInQueue(index, index + 1) },
enabled = index < state.queue.lastIndex,
) {
Icon(Icons.Rounded.KeyboardArrowDown, contentDescription = "Move down")
}
IconButton(onClick = { store.removeFromQueue(index) }) {
Icon(Icons.Rounded.Close, contentDescription = "Remove from queue")
}
}
@@ -305,3 +458,5 @@ private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit)
}
}
}
}
}
@@ -0,0 +1,263 @@
package win.taptap.musicmanager.client.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Add
import androidx.compose.material.icons.rounded.ArrowDropDown
import androidx.compose.material.icons.rounded.Check
import androidx.compose.material.icons.rounded.DownloadDone
import androidx.compose.material.icons.rounded.Link
import androidx.compose.material.icons.rounded.Search
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.FilledTonalButton
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.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import win.taptap.musicmanager.client.api.SearchResult
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
import win.taptap.musicmanager.client.store.sourceLabel
@Composable
fun SearchScreen(state: AppState, store: AppStore) {
if (state.moods.isEmpty()) {
EmptyState(
"Create a mood first",
"Search results are always added to a mood.",
Modifier.fillMaxSize(),
)
return
}
var url by remember { mutableStateOf("") }
var moodMenu by remember { mutableStateOf(false) }
var sourceMenu by remember { mutableStateOf(false) }
val target = state.moods.firstOrNull { it.id == state.searchTargetMoodId } ?: state.moods.first()
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(20.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
item {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
Text("Add to", style = MaterialTheme.typography.bodyMedium)
Box {
OutlinedButton(onClick = { moodMenu = true }) {
Text(target.name, maxLines = 1, overflow = TextOverflow.Ellipsis)
Icon(Icons.Rounded.ArrowDropDown, contentDescription = null)
}
DropdownMenu(expanded = moodMenu, onDismissRequest = { moodMenu = false }) {
state.moods.forEach { mood ->
DropdownMenuItem(
text = { Text(mood.name) },
onClick = {
moodMenu = false
store.selectSearchMood(mood.id)
},
)
}
}
}
}
}
item {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
Text("Download source", style = MaterialTheme.typography.bodyMedium)
Box {
OutlinedButton(onClick = { sourceMenu = true }) {
Text(sourceLabel(target.source))
Icon(Icons.Rounded.ArrowDropDown, contentDescription = null)
}
DropdownMenu(
expanded = sourceMenu,
onDismissRequest = { sourceMenu = false },
) {
listOf("deezer", "youtube").forEach { option ->
DropdownMenuItem(
text = { Text(sourceLabel(option)) },
onClick = {
sourceMenu = false
store.setMoodSource(target.id, option)
},
)
}
}
}
}
}
item {
OutlinedTextField(
value = state.searchQuery,
onValueChange = store::setSearchQuery,
label = { Text("Search ${sourceLabel(target.source)}") },
singleLine = true,
leadingIcon = { Icon(Icons.Rounded.Search, contentDescription = null) },
modifier = Modifier.fillMaxWidth(),
)
}
item {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxWidth(),
) {
OutlinedTextField(
value = url,
onValueChange = { url = it },
label = { Text("Paste a YouTube or Deezer URL") },
singleLine = true,
leadingIcon = { Icon(Icons.Rounded.Link, contentDescription = null) },
modifier = Modifier.weight(1f),
)
FilledTonalButton(
enabled = url.isNotBlank(),
onClick = {
store.addByUrl(url)
url = ""
},
) {
Text("Add")
}
}
}
if (state.searching) {
item {
Row(verticalAlignment = Alignment.CenterVertically) {
CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp)
Spacer(Modifier.width(10.dp))
Text("Searching YouTube Music…", style = MaterialTheme.typography.bodySmall)
}
}
}
if (!state.searching && state.searchQuery.isNotBlank() && state.searchResults.isEmpty()) {
item {
Text(
"No tracks up to 10 minutes were found.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
items(state.searchResults, key = { "${it.source}-${it.externalId}" }) { result ->
SearchRow(result, store)
}
item { Spacer(Modifier.size(24.dp)) }
}
}
@Composable
private fun SearchRow(result: SearchResult, store: AppStore) {
Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
RemoteImage(store, result.thumbnail, Modifier.size(52.dp))
Column(Modifier.weight(1f)) {
Text(
result.title,
style = MaterialTheme.typography.bodyLarge,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
Text(
buildString {
append(result.artist)
result.album?.takeIf { it.isNotBlank() }?.let { append(" · ").append(it) }
result.duration?.let { append(" · ").append(formatDuration(it)) }
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
if (result.inMood) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
Icons.Rounded.Check,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(14.dp),
)
Spacer(Modifier.width(4.dp))
Text(
"Already in this mood",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
)
}
} else if (result.downloaded) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
Icons.Rounded.DownloadDone,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(14.dp),
)
Spacer(Modifier.width(4.dp))
Text(
"Downloaded — adds instantly",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
)
}
}
}
IconButton(
onClick = { store.addSearchResult(result) },
enabled = !result.inMood,
) {
Icon(
Icons.Rounded.Add,
contentDescription = "Add to ${result.title}",
)
}
}
}
@@ -2,19 +2,19 @@ package win.taptap.musicmanager.client.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.DeleteSweep
import androidx.compose.material.icons.rounded.Logout
import androidx.compose.material.icons.rounded.Refresh
import androidx.compose.material.icons.rounded.TravelExplore
import androidx.compose.material3.Button
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.Icon
@@ -35,7 +35,7 @@ import win.taptap.musicmanager.client.store.AppStore
fun SettingsScreen(state: AppState, store: AppStore) {
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = androidx.compose.foundation.layout.PaddingValues(20.dp),
contentPadding = PaddingValues(20.dp),
verticalArrangement = Arrangement.spacedBy(14.dp),
) {
item {
@@ -57,6 +57,11 @@ fun SettingsScreen(state: AppState, store: AppStore) {
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
FilledTonalButton(onClick = { store.refreshAll() }) {
Icon(Icons.Rounded.Refresh, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text("Sync moods")
}
}
}
}
@@ -68,31 +73,25 @@ fun SettingsScreen(state: AppState, store: AppStore) {
modifier = Modifier.fillMaxWidth(),
) {
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text("Library", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
Text("Offline", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
Text(
"${state.library.size} songs cached · ${state.downloads.size} downloaded · ${formatBytes(store.storageBytes())}",
"${state.downloads.size} downloaded · ${formatBytes(store.storageBytes())}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) {
FilledTonalButton(onClick = { store.refreshAll() }) {
Icon(Icons.Rounded.Refresh, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text("Sync")
}
if (state.user?.admin == true) {
OutlinedButton(onClick = { store.scanLibrary() }) {
Icon(Icons.Rounded.TravelExplore, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text("Scan")
}
}
Row(
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
OutlinedButton(onClick = { store.openDownloads() }) {
Text("Manage downloads")
}
if (state.downloads.isNotEmpty()) {
OutlinedButton(onClick = { store.clearDownloads() }) {
Icon(Icons.Rounded.DeleteSweep, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text("Clear downloads")
Text("Clear")
}
}
}
}
@@ -108,12 +107,13 @@ fun SettingsScreen(state: AppState, store: AppStore) {
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text("About", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
Text(
"AudioManager 0.1.0 · $platformName",
"AudioManager 0.3.0 · $platformName",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Text(
"Moods are radio: the server chooses the next batch and learns from skips and completions. Add a track to a mood with the two buttons in the player.",
"Moods are private. Songs are downloaded from YouTube into a shared server store; " +
"recommendations refill automatically and stay playable without being permanent.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
@@ -8,17 +8,17 @@ import io.ktor.http.HttpStatusCode
import io.ktor.http.headersOf
import io.ktor.utils.io.readAvailable
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNull
import kotlin.test.assertTrue
import win.taptap.musicmanager.client.api.ApiClient
import win.taptap.musicmanager.client.api.ApiException
import win.taptap.musicmanager.client.api.Mood
import win.taptap.musicmanager.client.api.configuredHttpClient
import win.taptap.musicmanager.client.data.AppStorage
import win.taptap.musicmanager.client.data.AppCache
import win.taptap.musicmanager.client.data.CachedState
import win.taptap.musicmanager.client.data.LibraryCache
class ApiClientTest {
@@ -31,15 +31,16 @@ class ApiClientTest {
"/api/v1/auth/login" -> respond(
"""
{"token":"abc123","expiresAt":"2027-01-01T00:00:00Z",
"user":{"name":"alice","admin":true,"musicFolders":[1],"longformFolders":[10]}}
"user":{"name":"alice","admin":true}}
""".trimIndent(),
HttpStatusCode.OK,
jsonHeaders,
)
"/api/v1/moods" -> respond(
"""
{"moods":[{"id":"mo-1","name":"Focus","targetSize":30,"refreshHours":24,
"ytEnabled":true,"createdAt":"now","changedAt":"now","seedCount":2}]}
{"moods":[{"id":"mo-1","name":"Focus","source":"deezer","collectionPercent":60,
"recommendationPercent":40,"recommendationCount":10,"refreshHours":24,
"createdAt":"now","changedAt":"now","songCount":2,"recommendationReady":3}]}
""".trimIndent(),
HttpStatusCode.OK,
jsonHeaders,
@@ -56,7 +57,87 @@ class ApiClientTest {
val moods = client.moods()
assertEquals(1, moods.size)
assertEquals("Focus", moods.first().name)
assertEquals(2, moods.first().seedCount)
assertEquals(2, moods.first().songCount)
assertEquals(3, moods.first().recommendationReady)
}
@Test
fun `search returns badges and adding a video queues a download`() = runTest {
val engine = MockEngine { request ->
when (request.url.encodedPath) {
"/api/v1/search" -> respond(
"""
{"results":[
{"source":"deezer","externalId":"v1","title":"Fresh","artist":"Artist",
"duration":180,"downloaded":false},
{"source":"deezer","externalId":"v2","title":"Old","artist":"Artist",
"duration":200,"songId":"sg-2","downloaded":true}
]}
""".trimIndent(),
HttpStatusCode.OK,
jsonHeaders,
)
"/api/v1/moods/mo-1/songs" -> respond(
"""
{"detail":{"mood":{"id":"mo-1","name":"Focus","createdAt":"now",
"changedAt":"now","songCount":1},"songs":[],"recommendations":[]},
"added":false,"downloading":true}
""".trimIndent(),
HttpStatusCode.Accepted,
jsonHeaders,
)
else -> respondError(HttpStatusCode.NotFound)
}
}
val client = ApiClient(configuredHttpClient(engine))
client.restore("http://music", "token")
val results = client.search("fresh")
assertEquals(2, results.size)
assertNull(results[0].songId)
assertEquals("sg-2", results[1].songId)
assertTrue(results[1].downloaded)
assertEquals("v2", results[1].externalId)
val added = client.addSong("mo-1", source = "deezer", externalId = "v1")
assertTrue(added.downloading)
assertEquals(1, added.detail.mood.songCount)
}
@Test
fun `adding and rejecting recommendations parse the decision`() = runTest {
val engine = MockEngine { request ->
when (request.url.encodedPath) {
"/api/v1/moods/mo-1/recommendations/v1/add" -> respond(
"""
{"detail":{"mood":{"id":"mo-1","name":"Focus","createdAt":"now",
"changedAt":"now","songCount":2},"songs":[],"recommendations":[]},
"recommendation":{"source":"deezer","externalId":"v1","title":"Pick",
"artist":"Artist","state":"added"}}
""".trimIndent(),
HttpStatusCode.OK,
jsonHeaders,
)
"/api/v1/moods/mo-1/recommendations/v2/reject" -> respond(
"""
{"detail":{"mood":{"id":"mo-1","name":"Focus","createdAt":"now",
"changedAt":"now","songCount":2},"songs":[],"recommendations":[]},
"recommendation":{"source":"deezer","externalId":"v2","title":"Other",
"artist":"Artist","state":"rejected"}}
""".trimIndent(),
HttpStatusCode.OK,
jsonHeaders,
)
else -> respondError(HttpStatusCode.NotFound)
}
}
val client = ApiClient(configuredHttpClient(engine))
client.restore("http://music", "token")
assertEquals("added", client.addRecommendation("mo-1", "v1").recommendation.state)
assertEquals("rejected", client.rejectRecommendation("mo-1", "v2").recommendation.state)
}
@Test
@@ -116,23 +197,33 @@ class ApiClientTest {
}
@Test
fun `cache round-trips songs and moods`() = runTest {
fun `cache round-trips moods and discards the old cache version`() = runTest {
val storage = MemoryStorage()
val cache = LibraryCache(storage)
val cache = AppCache(storage)
assertNull(cache.loadSession())
val mood = Mood(
id = "mo-1",
name = "Focus",
createdAt = "now",
changedAt = "now",
songCount = 2,
)
cache.save(
CachedState(
serverUrl = "http://localhost:8080",
userName = "alice",
revision = "2026-11-14T00:00:00Z",
songs = emptyList(),
moods = emptyList(),
moods = listOf(mood),
),
)
val loaded = cache.load()
assertEquals("2026-11-14T00:00:00Z", loaded.revision)
assertEquals(listOf("mo-1"), loaded.moods.map { it.id })
assertEquals("alice", loaded.userName)
storage.write("mood-cache.json", """{"version":1,"songs":[{"id":"old"}]}""")
val invalidated = cache.load()
assertTrue(invalidated.moods.isEmpty())
assertEquals(3, invalidated.version)
}
}
@@ -10,10 +10,10 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.withContext
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
@@ -24,8 +24,8 @@ import win.taptap.musicmanager.client.api.ApiClient
import win.taptap.musicmanager.client.api.Song
import win.taptap.musicmanager.client.api.User
import win.taptap.musicmanager.client.api.configuredHttpClient
import win.taptap.musicmanager.client.data.AppCache
import win.taptap.musicmanager.client.data.CachedState
import win.taptap.musicmanager.client.data.LibraryCache
import win.taptap.musicmanager.client.data.PlaybackSnapshot
import win.taptap.musicmanager.client.data.SessionState
import win.taptap.musicmanager.client.playback.AudioPlayer
@@ -35,48 +35,203 @@ import win.taptap.musicmanager.client.store.AppStore
class AppStoreTest {
@Test
fun `play all queues the whole library and starts playback`() = runTest {
fun `playing a mood starts the server session and the first track`() = runTest {
val storage = MemoryStorage()
val cache = LibraryCache(storage)
val songs = listOf(song("a"), song("b"), song("c"))
cache.save(CachedState(serverUrl = "http://music", songs = songs))
val cache = AppCache(storage)
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
val player = FakePlayer()
val store = store(storage, cache, player)
val engine = MockEngine { request ->
when (request.url.encodedPath) {
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods" -> respond("""{"moods":[${moodJson(1)}]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1" -> respond(detailJson(listOf("a")), HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1/sessions" -> respond(
"""{"id":"s1","moodId":"mo-1","moodName":"Focus","startedAt":"now",
"queue":[${songJson("a")}]}""",
HttpStatusCode.Created,
jsonHeaders,
)
else -> respondError(HttpStatusCode.NotFound)
}
}
val store = store(storage, cache, player, engine)
runCurrent()
store.openMood("mo-1")
awaitState { store.state.value.selectedMood != null }
store.playAll()
runCurrent()
store.playMood("mo-1")
awaitState { store.state.value.current != null }
val state = store.state.value
val current = assertNotNull(state.current)
assertEquals("a", state.current?.id)
assertEquals("s1", state.session?.id)
assertTrue(state.playing)
assertEquals(listOf(current.id), player.played)
assertEquals(2, state.queue.size)
assertEquals(songs.map { it.id }.toSet(), (state.queue + current).map { it.id }.toSet())
assertEquals(listOf("a"), player.played)
store.release()
}
@Test
fun `play all reports an empty library instead of starting playback`() = runTest {
fun `an empty mood is rejected before any request`() = runTest {
val storage = MemoryStorage()
val cache = LibraryCache(storage)
val cache = AppCache(storage)
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
val player = FakePlayer()
val store = store(storage, cache, player)
val engine = MockEngine { request ->
when (request.url.encodedPath) {
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods" -> respond("""{"moods":[${moodJson(0)}]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1" -> respond(detailJson(emptyList()), HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
else -> respondError(HttpStatusCode.NotFound)
}
}
val store = store(storage, cache, player, engine)
runCurrent()
store.openMood("mo-1")
awaitState { store.state.value.selectedMood != null }
store.playAll()
runCurrent()
store.playMood("mo-1")
awaitState { store.state.value.message != null }
assertNull(store.state.value.current)
assertTrue(player.played.isEmpty())
assertTrue(store.state.value.messageIsError)
assertTrue(store.state.value.message!!.contains("at least one song"))
store.release()
}
@Test
fun `search is debounced and adding a result targets the chosen mood`() = runTest {
val storage = MemoryStorage()
val cache = AppCache(storage)
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
val engine = MockEngine { request ->
when (request.url.encodedPath) {
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods" -> respond("""{"moods":[${moodJson(0)}]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/search" -> respond(
"""{"results":[{"source":"youtube","externalId":"v1","title":"Fresh",
"artist":"Artist","duration":180,"downloaded":false}]}""",
HttpStatusCode.OK,
jsonHeaders,
)
"/api/v1/moods/mo-1/songs" -> respond(
"""{"detail":${detailJson(emptyList())},"added":false,"downloading":true}""",
HttpStatusCode.Accepted,
jsonHeaders,
)
else -> respondError(HttpStatusCode.NotFound)
}
}
val store = store(storage, cache, FakePlayer(), engine)
runCurrent()
awaitState { store.state.value.moods.isNotEmpty() }
store.openSearch("mo-1")
store.setSearchQuery("fresh")
advanceTimeBy(350)
runCurrent()
awaitState { store.state.value.searchResults.isNotEmpty() }
assertEquals("v1", store.state.value.searchResults.single().externalId)
store.addSearchResult(store.state.value.searchResults.single())
awaitState { store.state.value.message != null }
assertEquals("Downloading for Focus", store.state.value.message)
store.release()
}
@Test
fun `adding a recommendation refreshes the selected mood`() = runTest {
val storage = MemoryStorage()
val cache = AppCache(storage)
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
val engine = MockEngine { request ->
when (request.url.encodedPath) {
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods" -> respond("""{"moods":[${moodJson(1)}]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1" -> respond(
detailJson(listOf("a"), recommendationJson()),
HttpStatusCode.OK,
jsonHeaders,
)
"/api/v1/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1/recommendations/v1/add" -> respond(
"""{"detail":${detailJson(listOf("a"))},
"recommendation":${recommendationJson(state = "added", songId = "a")}}""",
HttpStatusCode.OK,
jsonHeaders,
)
else -> respondError(HttpStatusCode.NotFound)
}
}
val store = store(storage, cache, FakePlayer(), engine)
runCurrent()
store.openMood("mo-1")
awaitState { store.state.value.selectedMood != null }
store.addRecommendation("v1")
awaitState { store.state.value.message != null }
val detail = assertNotNull(store.state.value.selectedMood)
assertTrue(detail.recommendations.isEmpty())
assertEquals(1, detail.mood.songCount)
assertEquals("Added to Focus", store.state.value.message)
store.release()
}
@Test
fun `changing the mood source re-runs the search against the new catalog`() = runTest {
val storage = MemoryStorage()
val cache = AppCache(storage)
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
val engine = MockEngine { request ->
when {
request.url.encodedPath == "/api/v1/me" ->
respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
request.url.encodedPath == "/api/v1/moods" ->
respond("""{"moods":[${moodJson(0)}]}""", HttpStatusCode.OK, jsonHeaders)
request.method.value == "PATCH" && request.url.encodedPath == "/api/v1/moods/mo-1" ->
respond(detailJson(emptyList(), source = "deezer"), HttpStatusCode.OK, jsonHeaders)
request.url.encodedPath == "/api/v1/moods/mo-1" ->
respond(detailJson(emptyList()), HttpStatusCode.OK, jsonHeaders)
request.url.encodedPath == "/api/v1/moods/mo-1/preview" ->
respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
request.url.encodedPath == "/api/v1/search" -> {
val source = request.url.parameters["source"]
val body = if (source == "deezer") {
"""{"results":[{"source":"deezer","externalId":"67238732",
"title":"Instant Crush","artist":"Daft Punk","duration":337,
"downloaded":false}]}"""
} else {
"""{"results":[]}"""
}
respond(body, HttpStatusCode.OK, jsonHeaders)
}
else -> respondError(HttpStatusCode.NotFound)
}
}
val store = store(storage, cache, FakePlayer(), engine)
runCurrent()
store.openMood("mo-1")
awaitState { store.state.value.selectedMood != null }
store.openSearch("mo-1")
store.setSearchQuery("daft")
advanceTimeBy(350)
runCurrent()
store.setMoodSource("mo-1", "deezer")
awaitState { store.state.value.searchResults.any { it.source == "deezer" } }
assertEquals("deezer", store.state.value.moods.first { it.id == "mo-1" }.source)
assertEquals("67238732", store.state.value.searchResults.single().externalId)
store.release()
}
@Test
fun `sleep timer pauses playback when it expires`() = runTest {
val storage = MemoryStorage()
val cache = LibraryCache(storage)
val cache = AppCache(storage)
val player = FakePlayer()
val store = store(storage, cache, player)
runCurrent()
@@ -91,54 +246,30 @@ class AppStoreTest {
advanceTimeBy(60_000)
runCurrent()
val state = store.state.value
assertFalse(state.playing)
assertNull(state.sleepTimerRemainingSeconds)
assertFalse(store.state.value.playing)
assertNull(store.state.value.sleepTimerRemainingSeconds)
assertTrue(player.paused)
store.release()
}
@Test
fun `turning the sleep timer off keeps playback running`() = runTest {
fun `bootstrap restores the saved queue and resumes on play`() = runTest {
val storage = MemoryStorage()
val cache = LibraryCache(storage)
val player = FakePlayer()
val store = store(storage, cache, player)
runCurrent()
store.playSong(song("a"))
runCurrent()
store.setSleepTimer(30)
assertEquals(1_800L, store.state.value.sleepTimerRemainingSeconds)
store.setSleepTimer(null)
assertNull(store.state.value.sleepTimerRemainingSeconds)
advanceTimeBy(120_000)
runCurrent()
assertTrue(store.state.value.playing)
store.release()
}
@Test
fun `bootstrap restores the saved queue and starts it on play`() = runTest {
val storage = MemoryStorage()
val cache = LibraryCache(storage)
val cache = AppCache(storage)
cache.savePlayback(
PlaybackSnapshot(
queue = listOf(song("b")),
current = song("a"),
positionSeconds = 12.0,
),
)
val player = FakePlayer()
val store = store(storage, cache, player)
runCurrent()
val restored = store.state.value
assertEquals("a", restored.current?.id)
assertEquals(listOf("b"), restored.queue.map { it.id })
assertFalse(restored.playing)
assertEquals("a", store.state.value.current?.id)
assertEquals(listOf("b"), store.state.value.queue.map { it.id })
assertEquals(12.0, store.state.value.positionSeconds)
assertTrue(player.played.isEmpty())
store.togglePlayPause()
@@ -146,93 +277,41 @@ class AppStoreTest {
assertTrue(store.state.value.playing)
assertEquals(listOf("a"), player.played)
assertEquals(12.0, player.seeks.last())
store.release()
}
@Test
fun `accepting a recommendation replaces the selected mood`() = runTest {
fun `queue reordering and removal persist in the snapshot`() = runTest {
val storage = MemoryStorage()
val cache = LibraryCache(storage)
cache.saveSession(
SessionState("http://music", "token", User("alice", admin = false)),
)
val player = FakePlayer()
val detail = moodDetailJson(state = "new", seedCount = 1)
val acceptedDetail = moodDetailJson(state = "accepted", seedCount = 2)
val cache = AppCache(storage)
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
val engine = MockEngine { request ->
when (request.url.encodedPath) {
"/api/v1/moods" -> respond("""{"moods":[]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/library/songs" -> respond(
"""{"songs":[],"revision":"r1"}""",
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods" -> respond("""{"moods":[${moodJson(3)}]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1" -> respond(
detailJson(listOf("a", "b", "c")),
HttpStatusCode.OK,
jsonHeaders,
)
"/api/v1/moods/mo-1" -> respond(detail, HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1/preview" -> respond(
"""{"songs":[]}""",
HttpStatusCode.OK,
jsonHeaders,
)
"/api/v1/moods/mo-1/recommendations/v-1/accept" -> respond(
"""{"detail":$acceptedDetail,"recommendation":${recommendationJson("accepted")},"seedAdded":true}""",
HttpStatusCode.OK,
jsonHeaders,
)
"/api/v1/moods/mo-1/recommendations/v-1/reject" -> respond(
"""{"detail":$detail,"recommendation":${recommendationJson("rejected")},"seedAdded":false}""",
HttpStatusCode.OK,
"/api/v1/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1/sessions" -> respond(
"""{"id":"s1","moodId":"mo-1","moodName":"Focus","startedAt":"now",
"queue":[${songJson("a")},${songJson("b")},${songJson("c")}]}""",
HttpStatusCode.Created,
jsonHeaders,
)
else -> respondError(HttpStatusCode.NotFound)
}
}
val store = AppStore(
scope = this,
api = ApiClient(configuredHttpClient(engine)),
storage = storage,
player = player,
cache = cache,
)
val store = store(storage, cache, FakePlayer(), engine)
runCurrent()
store.openMood("mo-1")
awaitState { store.state.value.selectedMood != null || store.state.value.message != null }
awaitState { store.state.value.selectedMood != null }
assertEquals(
"new",
store.state.value.selectedMood?.recommendations?.single()?.state,
"message=" + store.state.value.message,
)
store.acceptRecommendation("v-1")
awaitState {
store.state.value.selectedMood?.recommendations?.single()?.state == "accepted"
}
val state = store.state.value
assertEquals("accepted", state.selectedMood?.recommendations?.single()?.state)
assertEquals(2, state.selectedMood?.mood?.seedCount)
assertEquals("Added to Focus", state.message)
assertFalse(state.messageIsError)
store.release()
}
/**
* Ktor's mock engine responds on a real dispatcher, so queued test work has
* to be run between short real waits.
*/
@Test
fun `queue reordering and removal persist`() = runTest {
val storage = MemoryStorage()
val cache = LibraryCache(storage)
cache.save(CachedState(serverUrl = "http://music", songs = listOf(song("a"), song("b"), song("c"))))
val player = FakePlayer()
val store = store(storage, cache, player)
runCurrent()
store.playAll(shuffled = false)
runCurrent()
assertEquals("a", store.state.value.current?.id)
store.playMood("mo-1")
awaitState { store.state.value.current?.id == "a" }
assertEquals(listOf("b", "c"), store.state.value.queue.map { it.id })
store.moveInQueue(1, 0)
@@ -245,333 +324,34 @@ class AppStoreTest {
}
@Test
fun `restored playback resumes from the saved position`() = runTest {
fun `logout clears the session and the mood cache`() = runTest {
val storage = MemoryStorage()
val cache = LibraryCache(storage)
cache.saveSession(
SessionState(
"http://music",
"token",
User("alice", admin = false, musicFolders = listOf(1), longformFolders = listOf(10)),
),
)
cache.save(
CachedState(
serverUrl = "http://music",
userName = "alice",
longform = listOf(song("l1", artist = "Book", folderId = 10, duration = 5400)),
),
)
cache.savePlayback(
PlaybackSnapshot(
current = song("l1", artist = "Book", folderId = 10, duration = 5400),
positionSeconds = 3600.0,
),
)
cache.saveProgress(
listOf(
win.taptap.musicmanager.client.api.LongformProgress(
songId = "l1",
positionSeconds = 3600,
durationSeconds = 5400,
completed = false,
updatedAt = "2026-01-01T00:00:00Z",
),
),
)
val player = FakePlayer()
val store = store(storage, cache, player)
runCurrent()
awaitState { store.state.value.offline }
assertEquals(3600.0, store.state.value.positionSeconds)
store.togglePlayPause()
runCurrent()
assertEquals("l1", store.state.value.current?.id)
assertEquals(3600.0, player.seeks.last())
store.release()
}
@Test
fun `previous after resuming an audiobook goes back instead of restarting it`() = runTest {
val storage = MemoryStorage()
val cache = LibraryCache(storage)
cache.saveSession(
SessionState(
"http://music",
"token",
User("alice", admin = false, musicFolders = listOf(1), longformFolders = listOf(10)),
),
)
cache.save(CachedState(serverUrl = "http://music", userName = "alice"))
cache.savePlayback(
PlaybackSnapshot(
current = song("l1", artist = "Book", folderId = 10, duration = 5400),
history = listOf(song("a")),
positionSeconds = 3600.0,
),
)
val player = FakePlayer()
val store = store(storage, cache, player)
runCurrent()
awaitState { store.state.value.offline }
store.previous()
runCurrent()
assertEquals("a", store.state.value.current?.id)
assertEquals(listOf("l1"), store.state.value.queue.map { it.id })
assertEquals("a", player.played.last())
store.release()
}
@Test
fun `finishing a longform track stays completed when the next track starts`() = runTest {
val storage = MemoryStorage()
val cache = LibraryCache(storage)
cache.saveSession(
SessionState(
"http://music",
"token",
User("alice", admin = false, musicFolders = listOf(1), longformFolders = listOf(10)),
),
)
cache.save(
CachedState(
serverUrl = "http://music",
userName = "alice",
longform = listOf(
song("l1", artist = "Book", folderId = 10, duration = 180),
song("l2", artist = "Book", folderId = 10, duration = 180),
),
),
)
val player = FakePlayer()
val store = store(storage, cache, player)
runCurrent()
awaitState { store.state.value.offline }
store.playLongformArtist("Book", shuffled = false)
runCurrent()
player.position = 180.0
player.finish()
advanceTimeBy(600)
runCurrent()
assertEquals(true, store.state.value.longformProgress["l1"]?.completed)
assertEquals("l2", store.state.value.current?.id)
store.release()
runCurrent()
}
@Test
fun `logout removes progress and cached library`() = runTest {
val storage = MemoryStorage()
val cache = LibraryCache(storage)
val cache = AppCache(storage)
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
cache.save(CachedState(serverUrl = "http://music", userName = "alice", songs = listOf(song("a"))))
cache.saveProgress(
listOf(
win.taptap.musicmanager.client.api.LongformProgress(
songId = "l1",
positionSeconds = 42,
durationSeconds = 180,
completed = false,
updatedAt = "2026-01-01T00:00:00Z",
),
cache.save(
CachedState(
serverUrl = "http://music",
userName = "alice",
moods = emptyList(),
),
)
val store = store(storage, cache, FakePlayer())
val engine = MockEngine { request ->
when (request.url.encodedPath) {
"/api/v1/auth/logout" -> respond("", HttpStatusCode.NoContent)
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods" -> respond("""{"moods":[]}""", HttpStatusCode.OK, jsonHeaders)
else -> respondError(HttpStatusCode.NotFound)
}
}
val store = store(storage, cache, FakePlayer(), engine)
runCurrent()
awaitState { store.state.value.authenticated }
store.logout()
awaitState { !store.state.value.authenticated }
assertTrue(cache.loadProgress().isEmpty())
assertTrue(cache.load().songs.isEmpty())
store.release()
}
@Test
fun `music search is debounced and scoped to music`() = runTest {
val storage = MemoryStorage()
val cache = LibraryCache(storage)
var requestedScope: String? = null
val engine = MockEngine { request ->
when (request.url.encodedPath) {
"/api/v1/library/search" -> {
requestedScope = request.url.parameters["scope"]
respond(
"""{"songs":[{"id":"m1","title":"Focus","artist":"Alpha","album":"Album",
"albumId":"al-1","duration":180,"bitRate":320,"size":1000,"suffix":"mp3",
"folderId":1,"relativePath":"m1.mp3","updatedAt":"now"}]}""",
HttpStatusCode.OK,
jsonHeaders,
)
}
else -> respondError(HttpStatusCode.NotFound)
}
}
val store = AppStore(
scope = this,
api = ApiClient(configuredHttpClient(engine)),
storage = storage,
player = FakePlayer(),
cache = cache,
)
runCurrent()
store.searchMusic("focus")
advanceTimeBy(350)
runCurrent()
awaitState { store.state.value.musicResults.isNotEmpty() }
assertEquals(listOf("m1"), store.state.value.musicResults.map { it.id })
assertEquals("music", requestedScope)
store.release()
}
@Test
fun `previous restarts after two seconds and restores the last track before it`() = runTest {
val storage = MemoryStorage()
val cache = LibraryCache(storage)
cache.save(CachedState(serverUrl = "http://music", songs = listOf(song("a"), song("b"), song("c"))))
val player = FakePlayer()
val store = store(storage, cache, player)
runCurrent()
store.playAll(shuffled = false)
runCurrent()
store.skip()
runCurrent()
assertEquals("b", store.state.value.current?.id)
assertEquals(listOf("a"), store.state.value.history.map { it.id })
store.seekTo(5.0)
store.previous()
assertEquals("b", store.state.value.current?.id)
assertEquals(0.0, store.state.value.positionSeconds)
assertEquals(0.0, player.seeks.last())
store.previous()
runCurrent()
assertEquals("a", store.state.value.current?.id)
assertEquals(listOf("b", "c"), store.state.value.queue.map { it.id })
assertTrue(store.state.value.history.isEmpty())
assertEquals("a", player.played.last())
assertTrue(cache.loadPlayback()?.history?.isEmpty() == true)
store.release()
}
@Test
fun `delta refresh keeps cached longform songs`() = runTest {
val storage = MemoryStorage()
val cache = LibraryCache(storage)
cache.saveSession(
SessionState(
"http://music",
"token",
User("alice", admin = false, musicFolders = listOf(1), longformFolders = listOf(10)),
),
)
cache.save(
CachedState(
serverUrl = "http://music",
revision = "r1",
songs = listOf(song("m1")),
longform = listOf(song("l1", artist = "Die drei ???", folderId = 10)),
),
)
val engine = MockEngine { request ->
when (request.url.encodedPath) {
"/api/v1/moods" -> respond("""{"moods":[]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/library/songs" -> respond(
"""{"songs":[],"revision":"r2"}""",
HttpStatusCode.OK,
jsonHeaders,
)
"/api/v1/longform/progress" -> respond(
"""{"items":[]}""",
HttpStatusCode.OK,
jsonHeaders,
)
else -> respondError(HttpStatusCode.NotFound)
}
}
val store = AppStore(
scope = this,
api = ApiClient(configuredHttpClient(engine)),
storage = storage,
player = FakePlayer(),
cache = cache,
)
runCurrent()
awaitState { cache.load()?.revision == "r2" }
assertEquals(listOf("m1"), store.state.value.library.map { it.id })
assertEquals(listOf("l1"), store.state.value.longform.map { it.id })
store.release()
}
@Test
fun `playing an artist queues only that longform artist`() = runTest {
val storage = MemoryStorage()
val cache = LibraryCache(storage)
cache.save(
CachedState(
serverUrl = "http://music",
longform = listOf(
song("l1", artist = "Die drei ???", folderId = 10),
song("l2", artist = "Die drei ???", folderId = 10),
song("l3", artist = "Other", folderId = 10),
),
),
)
val player = FakePlayer()
val store = store(storage, cache, player)
runCurrent()
store.playLongformArtist("Die drei ???", shuffled = false)
runCurrent()
val state = store.state.value
assertEquals(setOf("l1", "l2"), (state.queue + listOfNotNull(state.current)).map { it.id }.toSet())
assertTrue(player.played.single() in setOf("l1", "l2"))
store.release()
}
@Test
fun `resuming a longform track starts it`() = runTest {
val storage = MemoryStorage()
val cache = LibraryCache(storage)
cache.save(
CachedState(
serverUrl = "http://music",
longform = listOf(song("l1", artist = "Die drei ???", folderId = 10)),
),
)
cache.saveProgress(
listOf(
win.taptap.musicmanager.client.api.LongformProgress(
songId = "l1",
positionSeconds = 30,
durationSeconds = 180,
completed = false,
updatedAt = "2026-01-01T00:00:00Z",
),
),
)
val player = FakePlayer()
val store = store(storage, cache, player)
runCurrent()
store.resumeLongform("l1")
runCurrent()
assertEquals("l1", store.state.value.current?.id)
assertEquals(listOf("l1"), player.played)
assertEquals(30, store.state.value.longformProgress["l1"]?.positionSeconds)
assertNull(cache.loadSession())
assertTrue(cache.load().moods.isEmpty())
store.release()
}
@@ -586,56 +366,60 @@ class AppStoreTest {
private val jsonHeaders = headersOf(HttpHeaders.ContentType, "application/json")
private fun moodJson(seedCount: Int) = """
{"id":"mo-1","name":"Focus","targetSize":30,"refreshHours":24,"ytEnabled":true,
private fun songJson(id: String) = """
{"id":"$id","source":"youtube","externalId":"video-$id","title":"Song $id",
"artist":"Artist","album":"Album","duration":180,"bitRate":320,"size":1000,"suffix":"mp3"}
""".trimIndent()
private fun moodJson(songCount: Int, source: String = "youtube") = """
{"id":"mo-1","name":"Focus","source":"$source","collectionPercent":50,
"recommendationPercent":50,"recommendationCount":10,"refreshHours":24,
"createdAt":"2026-01-01T00:00:00Z","changedAt":"2026-01-01T00:00:00Z",
"seedCount":$seedCount,"newRecommendations":1}
"songCount":$songCount}
""".trimIndent()
private fun recommendationJson(state: String) = """
{"videoId":"v-1","title":"Soft Light","artist":"Beta","duration":180,
"state":"$state","timesAdded":0,
"firstSeen":"2026-01-01T00:00:00Z","lastSeen":"2026-01-01T00:00:00Z",
"matchedSong":${song("a").let { """{"id":"${it.id}","title":"${it.title}","artist":"${it.artist}","album":"${it.album}","albumId":"${it.albumId}","duration":${it.duration},"bitRate":${it.bitRate},"size":${it.size},"suffix":"${it.suffix}","folderId":${it.folderId},"relativePath":"${it.relativePath}","updatedAt":"${it.updatedAt}"}""" }}}
private fun recommendationJson(state: String = "new", songId: String? = null) = """
{"source":"youtube","externalId":"v1","title":"Pick","artist":"Artist",
"duration":180,"state":"$state",
${songId?.let { "\"song\":${songJson(it)}," } ?: ""}
"firstSeen":"2026-01-01T00:00:00Z","lastSeen":"2026-01-01T00:00:00Z"}
""".trimIndent()
private fun moodDetailJson(state: String, seedCount: Int) = """
{"mood":${moodJson(seedCount)},"seeds":[],"recommendations":[${recommendationJson(state)}]}
private fun detailJson(
songs: List<String>,
recommendation: String? = null,
source: String = "youtube",
) = """
{"mood":${moodJson(songs.size, source)},
"songs":[${songs.joinToString(",") { """{"song":${songJson(it)},"origin":"search","addedAt":"now"}""" }}],
"recommendations":${recommendation?.let { "[$it]" } ?: "[]"}}
""".trimIndent()
private fun kotlinx.coroutines.test.TestScope.store(
storage: MemoryStorage,
cache: LibraryCache,
player: AudioPlayer,
): AppStore = AppStore(
// Background scope so leftover store jobs (reconnect loops, refreshes)
// are cancelled by runTest instead of failing the next test with
// UncompletedCoroutinesError.
scope = backgroundScope,
api = ApiClient(configuredHttpClient(MockEngine { respondError(HttpStatusCode.NotFound) })),
storage = storage,
player = player,
cache = cache,
)
private fun song(
id: String,
artist: String = "Artist",
folderId: Int = 1,
duration: Int = 180,
) = Song(
private fun song(id: String, duration: Int = 180) = Song(
id = id,
source = "youtube",
externalId = "video-$id",
title = "Song $id",
artist = artist,
artist = "Artist",
album = "Album",
albumId = "al-1",
duration = duration,
bitRate = 320,
size = 1_000,
suffix = "mp3",
folderId = folderId,
relativePath = "$id.mp3",
updatedAt = "2026-01-01T00:00:00Z",
)
private fun TestScope.store(
storage: MemoryStorage,
cache: AppCache,
player: AudioPlayer,
engine: MockEngine = MockEngine { respondError(HttpStatusCode.NotFound) },
): AppStore = AppStore(
// Background scope so leftover store jobs (reconnect loops, refreshes)
// are cancelled by runTest instead of failing with UncompletedCoroutinesError.
scope = backgroundScope,
api = ApiClient(configuredHttpClient(engine)),
storage = storage,
player = player,
cache = cache,
)
private class FakePlayer : AudioPlayer {
+68
View File
@@ -0,0 +1,68 @@
# Mood-first redesign — client notes
The canonical design and decision log lives in the server repo:
- local: `/home/taptap/AudioManager/docs/design/mood-first.md`
- web: https://gitea.tap-tap.win/TapTap/AudioManager/src/branch/main/docs/design/mood-first.md
Read that first. This file only records the client-side consequences.
## What the client becomes
- Moods are the only content model. No Library, no Longform, no mounted music.
- All music is downloaded on the server from Deezer or YouTube Music; the client searches and
adds songs to a mood.
- A mood has **songs** (collection) and **recommendations** (auto-downloaded,
playable in radio, not permanent until added).
- Playback mixes collection and ready recommendations using `collectionPercent`.
- A mood needs at least one song to play.
## Screens
`Moods | MoodDetail | Search | Downloads | Settings`
- **Moods**: mood list, create, global search.
- **MoodDetail**: songs, add music, recommendations (Add / Not interested /
Retry), next batch, mood settings (query, genres, collectionPercent,
recommendationCount 0–30, refreshHours).
- **Search**: remote Deezer/YouTube Music search, results over 10 minutes hidden, add to the
current or a chosen mood, already-downloaded/in-mood badges, paste URL.
- **Downloads**: device-side offline files, delete/clear, storage usage.
- **Settings**: server/account/devices/logout (no scan UI).
Remove `LibraryScreen` and all longform UI.
## State/API changes
- Remove `library`, `longform`, `longformResults`, `longformProgress`,
`musicResults`, local `searchResults`, `playAll`, `playLongform*`,
`resumeLongform`, longform progress reporting.
- Add remote search state (`searchResults`, `searchTargetMoodId`), add/remove
song, recommendation add/reject/retry, mood song counts.
- `CachedState` becomes version 2 with moods + mood details only; invalidate old
caches.
- `SongDto` gains `videoId` and `thumbnail`; loses folder/album-id/path/genres.
- Cover art is song-keyed: `coverUrl(songId)`.
- Playback snapshot/history, desktop seek, Android media session, sleep timer
and device downloads remain.
- Offline mood playback uses device downloads and cached mood details.
## Implementation status (2026-11-15)
Implemented. Concretely:
- `Models.kt` reflects the mood-first DTOs: `Song(videoId, thumbnail)`,
`Mood(collectionPercent, recommendationCount, song counts)`,
`MoodSong`, `Recommendation(song, download)`, `SearchResult`.
- `ApiClient` uses `/moods/{id}/songs`, `/search`, recommendation
`add|reject|retry`, and `/songs/{id}/cover`.
- `AppCache` (version 2) stores moods and details only; old cache shapes are
discarded. Session and playback snapshots are kept.
- `AppStore` has `Moods | MoodDetail | Search | Downloads | Settings`, remote
Deezer/YouTube Music search with a target mood and a per-mood source, add/remove song, recommendation actions, offline
playback from device downloads, and no longform/library paths.
- The UI has a dedicated Search screen (mood picker, paste URL, downloaded
badges) and a Downloads screen. Mood Detail shows songs, add music,
recommendation states and the new options. The player keeps drag-to-reorder queue editing,
previous/seek and the sleep timer.
- Device downloads store covers by song id (`<songId>.jpg`).