16 Commits
Author SHA1 Message Date
TapTap 8d7f6a0ccb fix: re-run search immediately when the mood source changes
CI / build (push) Successful in 3m54s
CI / play (push) Successful in 3m29s
The explicit source switch cancelled the debounced search and then waited
another 300 ms for no reason. It now searches right away, which also makes the
test deterministic.
2026-11-18 19:48:09 +00:00
TapTap 4048262fc5 feat: remove the Up next preview section
CI / build (push) Successful in 2m22s
CI / play (push) Skipped
The preview duplicated what the radio does and is not the real queue. Mood
detail now only loads songs and recommendations, so opening a mood makes one
fewer request.

Also drop the Wasm warm-up from the CI image recipe: the target is local-only.
Version 0.3.3.
2026-11-18 19:39:51 +00:00
TapTap 14e5b9d982 ci: drop the Wasm build from the pipeline
CI / build (push) Successful in 2m57s
CI / play (push) Skipped
It is CPU-bound and dominates the runtime. The target stays available for
local builds with :composeApp:wasmJsBrowserDistribution.
2026-11-18 19:26:04 +00:00
TapTap e28e95fa2b fix: notification skip/back drive the app queue
CI / build (push) Successful in 14m12s
CI / play (push) Successful in 3m20s
- advertise next/previous on a ForwardingPlayer so the notification and
  Android Auto show the buttons, and route them to the mood queue
- rename the preview section to 'Up next' with a clearer subtitle
- version 0.3.2
2026-11-18 19:14:05 +00:00
TapTap 2478505dba test: make the search download status assertion timing independent
CI / build (push) Successful in 13m58s
CI / play (push) Successful in 3m18s
2026-11-17 16:57:07 +00:00
TapTap 957ee3eb4b feat: inline search download status and headset transport
CI / build (push) Successful in 5m35s
CI / play (push) Skipped
- mood detail carries the server's download jobs
- search rows show Downloading… / Added / Failed, so the keyboard cannot hide it
- headset and Bluetooth next/previous drive the app queue; previous keeps the
  after-two-seconds restart rule
- 'Next batch' now explains what the preview is
- version 0.3.1
2026-11-17 16:43:21 +00:00
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
24 changed files with 2362 additions and 1957 deletions

No files matched your search

+2 -5
View File
@@ -45,15 +45,13 @@ jobs:
:composeApp:desktopTest \ :composeApp:desktopTest \
:composeApp:assembleDebug \ :composeApp:assembleDebug \
:composeApp:packageUberJarForCurrentOS \ :composeApp:packageUberJarForCurrentOS \
:composeApp:wasmJsBrowserDistribution \
--console=plain --console=plain
else else
# The optimized Wasm build is CPU-bound and slow; main/PR builds # The Wasm target is kept for local builds but is not part of CI:
# only need to prove the web target compiles and bundles. # it is CPU-bound and dominates the pipeline runtime.
gradle \ gradle \
:composeApp:desktopTest \ :composeApp:desktopTest \
:composeApp:assembleDebug \ :composeApp:assembleDebug \
:composeApp:wasmJsBrowserDevelopmentExecutableDistribution \
--console=plain --console=plain
fi fi
@@ -64,7 +62,6 @@ jobs:
cp composeApp/build/outputs/apk/debug/composeApp-debug.apk dist/AudioManager.apk cp composeApp/build/outputs/apk/debug/composeApp-debug.apk dist/AudioManager.apk
if [[ "$GITHUB_REF" == refs/tags/* ]]; then if [[ "$GITHUB_REF" == refs/tags/* ]]; then
cp composeApp/build/compose/jars/*.jar dist/AudioManager-desktop.jar cp composeApp/build/compose/jars/*.jar dist/AudioManager-desktop.jar
(cd composeApp/build/dist/wasmJs/productionExecutable && zip -qr "$GITHUB_WORKSPACE/dist/AudioManager-web.zip" .)
fi fi
- name: Publish release assets - name: Publish release assets
+130 -74
View File
@@ -1,8 +1,11 @@
# AudioManager Client # 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 ## Targets
@@ -12,33 +15,74 @@ The client and server are designed together. There is no OpenSubsonic compatibil
| **Desktop (JVM)** | Compose Multiplatform | MP3SPI, decoded to PCM + `SourceDataLine` | Yes | | **Desktop (JVM)** | Compose Multiplatform | MP3SPI, decoded to PCM + `SourceDataLine` | Yes |
| **Web (Wasm)** | Compose Multiplatform | HTML5 `Audio` | Browser-managed cache only | | **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 ## Features
- Login with a server URL, username and password. The server returns a revocable bearer token. - Login with a server URL, username and password. The server returns a revocable
- Mood grid with live counts; create, rename, delete and edit moods. bearer token.
- Seed management: search the owner's music, add or remove anchors. - **Moods** are the only content model. Each user sees only their own moods.
- Server-driven radio: the app keeps a small queue and asks for more from the same mood session. - **Songs** belong to the mood's permanent collection. A mood needs at least one
- Playback events are reported automatically (`started`, `completed`, `skipped`) so the server learns. 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: - Two add-to-mood actions in the player:
- **Add to current mood** (the mood of the active radio session) - **Add to current mood** (the mood of the active radio session)
- **Choose another mood** (picker) - **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. - A queue sheet from the player: the current track is pinned, upcoming tracks
- Library search and playback, plus **Shuffle all** to queue the whole library without starting a mood. can be reordered by **long-press and drag** or removed. Changes are persisted
- A queue sheet from the player: the current track plus every upcoming track, with move up/down and remove. Changes are persisted locally. 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. - **Previous** from the player: after two seconds of playback it restarts the
- **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). current track; before that it restores the last played track.
- **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. - **Headset/Bluetooth next and previous** and the media notification's skip /
- **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. back buttons use the same queue rules as the in-app controls; they no longer
- **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. seek inside the single ExoPlayer item.
- Offline library cache: moods, songs and the last sync revision are stored locally. When the server is unreachable, downloaded tracks still play. - The bottom player keeps the cover and title/artist readable on narrow phones;
- The play queue and current track are saved locally, so a restart reopens the player paused and resumes on the next tap. 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. - 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. - Session persistence: the login survives app restarts until the token is
- Original MP3 downloads with progress state, removal and storage usage. revoked or expires.
- Session persistence: the login survives app restarts until the token is revoked or expires. - Android background playback through a Media3 `MediaSessionService`:
- 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. 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 and an inline Downloading… / Added / Failed status per
result, so the keyboard never hides the feedback.
- **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 ## Project layout
@@ -46,9 +90,9 @@ The shared module contains the API client, session/cache storage, radio queue, a
composeApp/ composeApp/
|-- src/commonMain/kotlin/win/taptap/musicmanager/client/ |-- src/commonMain/kotlin/win/taptap/musicmanager/client/
| |-- api/ # Ktor client and DTOs mirroring /api/v1 | |-- api/ # Ktor client and DTOs mirroring /api/v1
| |-- data/ # AppStorage, LibraryCache, session persistence | |-- data/ # AppStorage, AppCache, session persistence
| |-- playback/ # AudioPlayer abstraction | |-- playback/ # AudioPlayer abstraction
| |-- store/ # AppStore: state, radio queue, downloads, editing | |-- store/ # AppStore: state, search, radio queue, downloads
| `-- ui/ # Compose screens and theme | `-- ui/ # Compose screens and theme
|-- src/androidMain/ # Activity, Media3 player, filesystem storage |-- src/androidMain/ # Activity, Media3 player, filesystem storage
|-- src/desktopMain/ # Main window, MP3SPI player, filesystem storage |-- src/desktopMain/ # Main window, MP3SPI player, filesystem storage
@@ -60,15 +104,18 @@ composeApp/
## Build ## 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 ```bash
nix-shell 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 ```bash
export ANDROID_HOME=/opt/android-sdk export ANDROID_HOME=/opt/android-sdk
@@ -86,14 +133,17 @@ gradle :composeApp:run
# Desktop fat jar # Desktop fat jar
gradle :composeApp:packageUberJarForCurrentOS gradle :composeApp:packageUberJarForCurrentOS
# Web bundle # Web bundle (local only, not built by CI)
gradle :composeApp:wasmJsBrowserDistribution gradle :composeApp:wasmJsBrowserDistribution
# composeApp/build/dist/wasmJs/productionExecutable # 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) ## Publishing to Google Play (internal testing)
@@ -130,27 +180,17 @@ scripts/build-release-aab.sh <versionCode> <versionName>
# composeApp/build/outputs/bundle/release/composeApp-release.aab # composeApp/build/outputs/bundle/release/composeApp-release.aab
``` ```
The script verifies the signature and prints the SHA-256. Bump `versionCode` for The script verifies the signature and prints the SHA-256.
every upload; `VERSION_CODE`/`VERSION_NAME` can also be set in the environment.
### 3. Upload ### 3. Upload
In Play Console: **Testing → Internal testing → Create new release → App In Play Console: **Testing → Internal testing → Create new release → App
integrity → Google-generated key**, upload the AAB, add release notes, then 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 **Save → Roll out**.
the opt-in link from the Testers tab with your test list.
### 4. Automated uploads ### 4. Automated uploads
Tagged builds (`v*`) publish to internal testing from CI. One-time setup: Tagged builds (`v*`) publish to internal testing from CI. The Gitea secrets are:
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:
| Secret | Value | | Secret | Value |
| --- | --- | | --- | --- |
@@ -160,32 +200,33 @@ Tagged builds (`v*`) publish to internal testing from CI. One-time setup:
| `ANDROID_KEY_PASSWORD` | key password | | `ANDROID_KEY_PASSWORD` | key password |
| `PLAY_SERVICE_ACCOUNT_JSON` | contents of the service account JSON | | `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.3 && git push --tags` builds, signs and uploads the bundle.
Gradle Play Publisher asks Play for the next free `versionCode` Gradle Play Publisher asks Play for the next free `versionCode`
(`ResolutionStrategy.AUTO`), so only the tag/version name needs to change. (`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 ## 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. - **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 sync** — GET `/moods` on login/refresh; details are fetched when a mood
- **Mood cache** — mood details are stored so the app can open them offline. is opened and cached.
- **Radio** — one session per mood, batches of 12, prefetch when the queue is short, no repeats within a session. - **Mood cache** — cached details power offline mood lists and downloads.
- **Downloads** — stored under the platform app directory, keyed by deterministic song ID. - **Search** — debounced remote catalog search with the selected target mood and
- **Playback snapshot** — the session, upcoming queue, current track and play history are persisted on every queue change and restored on the next launch. its source.
- **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. - **Radio** — one session per mood, batches of 12, prefetch when the queue is
- **Offline retry** — a background loop retries the library sync until the server responds again. 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 ## Radio and add-to-mood
@@ -200,14 +241,20 @@ open mood ──► POST /moods/{id}/sessions ──► queue (12 tracks)
└─ moodId: chosen mood └─ 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 ## 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. - **main / PR:** run `desktopTest` and build the Android APK.
- **`v*` tag:** additionally build the desktop fat jar and the optimized Wasm bundle, then attach all three to the Gitea release. - **`v*` tag:** additionally build the desktop fat jar, attach the artifacts to
the Gitea release, and publish the AAB to Play internal testing.
- The Wasm target stays in the project for local builds but is **not** part of
CI; compiling it dominates the pipeline runtime.
Rebuild the CI image after changing `ci/Dockerfile` or dependency versions: Rebuild the CI image after changing `ci/Dockerfile` or dependency versions:
@@ -215,14 +262,23 @@ Rebuild the CI image after changing `ci/Dockerfile` or dependency versions:
scripts/build-ci-image.sh 3 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 ## 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. - The media notification exposes play/pause and seeking. Queue actions (skip,
- 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. add to mood) stay in the app because the mood session and its events belong to
- Web downloads are disabled because the browser owns its storage; the app still streams and caches metadata. the server.
- 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. - Desktop playback supports seeking by reopening the decoder at the requested
- 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. position. MP3s are decoded to 16-bit PCM before the line is opened, because
- 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. 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. - No iOS target yet. The shared module is ready for one.
+4 -9
View File
@@ -43,21 +43,16 @@ RUN mkdir -p "$ANDROID_HOME/cmdline-tools" \
"build-tools;36.0.0" \ "build-tools;36.0.0" \
&& rm -rf "$ANDROID_HOME/.temp" "$ANDROID_HOME/.downloadIntermediates" && rm -rf "$ANDROID_HOME/.temp" "$ANDROID_HOME/.downloadIntermediates"
# Warm the Gradle dependency cache and the Kotlin/Wasm (node, yarn, binaryen) # Warm the Gradle dependency cache and the common/Android/desktop compilers so
# toolchain so CI jobs do not download them on every run. Rebuild this image # CI jobs do not download them on every run. The Wasm toolchain is intentionally
# when dependencies change. # not warmed: Wasm is not part of the pipeline. Rebuild this image when
# dependencies change.
COPY . /warmup COPY . /warmup
WORKDIR /warmup WORKDIR /warmup
# Warm dependencies and the common/Android/desktop compilers here. The Wasm
# executable build is memory hungry and stays in the web job, but node and yarn
# are cached: Kotlin downloads them from GitHub, which has been flaky during CI.
RUN sed -i 's/kotlin.daemon.jvmargs=-Xmx3g/kotlin.daemon.jvmargs=-Xmx2g/' gradle.properties \ RUN sed -i 's/kotlin.daemon.jvmargs=-Xmx3g/kotlin.daemon.jvmargs=-Xmx2g/' gradle.properties \
&& gradle --no-daemon --max-workers=2 \ && gradle --no-daemon --max-workers=2 \
:kotlinNodeJsSetup \
:kotlinYarnSetup \
:composeApp:desktopTest \ :composeApp:desktopTest \
:composeApp:assembleDebug \ :composeApp:assembleDebug \
:composeApp:compileKotlinWasmJs \
--console=plain \ --console=plain \
&& rm -rf /warmup && rm -rf /warmup
+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 appVersionCode = (System.getenv("VERSION_CODE") ?: localProperties.getProperty("VERSION_CODE") ?: "1").toInt()
val appVersionName = System.getenv("VERSION_NAME") val appVersionName = System.getenv("VERSION_NAME")
?: localProperties.getProperty("VERSION_NAME") ?: localProperties.getProperty("VERSION_NAME")
?: "0.1.0" ?: "0.3.3"
kotlin { kotlin {
androidTarget { androidTarget {
@@ -126,6 +126,11 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
withController { it.seekTo((seconds * 1000).toLong().coerceAtLeast(0L)) } withController { it.seekTo((seconds * 1000).toLong().coerceAtLeast(0L)) }
} }
override fun setSkipCallbacks(onNext: (() -> Unit)?, onPrevious: (() -> Unit)?) {
PlaybackCommands.onNext = onNext
PlaybackCommands.onPrevious = onPrevious
}
override fun scheduleSleepTimer(seconds: Long?): Boolean { override fun scheduleSleepTimer(seconds: Long?): Boolean {
val args = Bundle().apply { putLong(SLEEP_TIMER_SECONDS, seconds ?: 0L) } val args = Bundle().apply { putLong(SLEEP_TIMER_SECONDS, seconds ?: 0L) }
val send: (MediaController) -> Boolean = { current -> val send: (MediaController) -> Boolean = { current ->
@@ -0,0 +1,27 @@
package win.taptap.musicmanager.client
/**
* Bridge between the media session in [PlaybackService] and the queue that
* lives in the app's store. Media3 sends headset/Bluetooth next and previous
* here instead of seeking the single-item ExoPlayer.
*/
internal object PlaybackCommands {
@Volatile
var onNext: (() -> Unit)? = null
@Volatile
var onPrevious: (() -> Unit)? = null
/** Returns false when no store is attached, so the default handling applies. */
fun next(): Boolean {
val handler = onNext ?: return false
handler()
return true
}
fun previous(): Boolean {
val handler = onPrevious ?: return false
handler()
return true
}
}
@@ -5,8 +5,12 @@ import android.content.Intent
import android.os.Bundle import android.os.Bundle
import android.os.Handler import android.os.Handler
import android.os.Looper import android.os.Looper
import android.view.KeyEvent
import androidx.core.content.IntentCompat
import androidx.media3.common.AudioAttributes import androidx.media3.common.AudioAttributes
import androidx.media3.common.C import androidx.media3.common.C
import androidx.media3.common.ForwardingPlayer
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.session.MediaSession import androidx.media3.session.MediaSession
import androidx.media3.session.MediaSessionService import androidx.media3.session.MediaSessionService
@@ -36,7 +40,7 @@ class PlaybackService : MediaSessionService() {
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
val player = ExoPlayer.Builder(this) val exoPlayer = ExoPlayer.Builder(this)
.setAudioAttributes( .setAudioAttributes(
AudioAttributes.Builder() AudioAttributes.Builder()
.setUsage(C.USAGE_MEDIA) .setUsage(C.USAGE_MEDIA)
@@ -50,6 +54,44 @@ class PlaybackService : MediaSessionService() {
setWakeMode(C.WAKE_MODE_NETWORK) setWakeMode(C.WAKE_MODE_NETWORK)
} }
// ExoPlayer holds one item at a time; the queue lives in the app. Advertise
// next/previous so the notification and Android Auto show the buttons and
// route them to the queue instead of seeking inside the single item.
val player = object : ForwardingPlayer(exoPlayer) {
override fun getAvailableCommands(): Player.Commands =
super.getAvailableCommands().buildUpon()
.addAll(
Player.COMMAND_SEEK_TO_NEXT,
Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM,
Player.COMMAND_SEEK_TO_PREVIOUS,
Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM,
)
.build()
override fun isCommandAvailable(command: Int): Boolean =
command == Player.COMMAND_SEEK_TO_NEXT ||
command == Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM ||
command == Player.COMMAND_SEEK_TO_PREVIOUS ||
command == Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM ||
super.isCommandAvailable(command)
override fun seekToNext() {
if (!PlaybackCommands.next()) super.seekToNext()
}
override fun seekToNextMediaItem() {
if (!PlaybackCommands.next()) super.seekToNextMediaItem()
}
override fun seekToPrevious() {
if (!PlaybackCommands.previous()) super.seekToPrevious()
}
override fun seekToPreviousMediaItem() {
if (!PlaybackCommands.previous()) super.seekToPreviousMediaItem()
}
}
val sessionActivity = PendingIntent.getActivity( val sessionActivity = PendingIntent.getActivity(
this, this,
0, 0,
@@ -73,6 +115,38 @@ class PlaybackService : MediaSessionService() {
.build() .build()
} }
/**
* A headset skip must move the app's queue, not seek the one
* item ExoPlayer holds. Returning true consumes the event.
*/
override fun onMediaButtonEvent(
session: MediaSession,
controllerInfo: MediaSession.ControllerInfo,
intent: Intent,
): Boolean {
if (intent.action != Intent.ACTION_MEDIA_BUTTON) return false
val event = IntentCompat.getParcelableExtra(
intent,
Intent.EXTRA_KEY_EVENT,
KeyEvent::class.java,
) ?: return false
return when (event.keyCode) {
KeyEvent.KEYCODE_MEDIA_NEXT -> when (event.action) {
KeyEvent.ACTION_DOWN -> PlaybackCommands.next()
KeyEvent.ACTION_UP -> true
else -> false
}
KeyEvent.KEYCODE_MEDIA_PREVIOUS -> when (event.action) {
KeyEvent.ACTION_DOWN -> PlaybackCommands.previous()
KeyEvent.ACTION_UP -> true
else -> false
}
else -> false
}
}
override fun onCustomCommand( override fun onCustomCommand(
session: MediaSession, session: MediaSession,
controller: MediaSession.ControllerInfo, controller: MediaSession.ControllerInfo,
@@ -12,7 +12,6 @@ import io.ktor.client.request.get
import io.ktor.client.request.header import io.ktor.client.request.header
import io.ktor.client.request.patch import io.ktor.client.request.patch
import io.ktor.client.request.post import io.ktor.client.request.post
import io.ktor.client.request.put
import io.ktor.client.request.setBody import io.ktor.client.request.setBody
import io.ktor.client.statement.HttpResponse import io.ktor.client.statement.HttpResponse
import io.ktor.client.statement.bodyAsBytes 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 * 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. * 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() } } 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( parse(
http.post(url("/moods/$moodId/seeds")) { http.post(url("/moods/$moodId/songs")) {
auth() auth()
contentType(ContentType.Application.Json) contentType(ContentType.Application.Json)
setBody(AddSeedRequest(songId)) setBody(
AddSongRequest(
songId = songId,
source = source,
externalId = externalId,
url = url,
),
)
}, },
) )
suspend fun removeSeed(moodId: String, songId: String) { suspend fun removeSong(moodId: String, songId: String) {
requestNoContent { http.delete(url("/moods/$moodId/seeds/$songId")) { auth() } } requestNoContent { http.delete(url("/moods/$moodId/songs/$songId")) { auth() } }
} }
suspend fun recommendations(moodId: String): List<Recommendation> = suspend fun recommendations(moodId: String): List<Recommendation> =
@@ -152,42 +163,46 @@ class ApiClient(private val http: HttpClient) {
}, },
) )
suspend fun acceptRecommendation(moodId: String, videoId: String): RecommendationDecision = suspend fun addRecommendation(moodId: String, externalId: String): RecommendationDecision =
parse( parse(
http.post(url("/moods/$moodId/recommendations/$videoId/accept")) { http.post(url("/moods/$moodId/recommendations/$externalId/add")) {
auth() auth()
}, },
) )
suspend fun rejectRecommendation(moodId: String, videoId: String): RecommendationDecision = suspend fun rejectRecommendation(moodId: String, externalId: String): RecommendationDecision =
parse( parse(
http.post(url("/moods/$moodId/recommendations/$videoId/reject")) { http.post(url("/moods/$moodId/recommendations/$externalId/reject")) {
auth() auth()
}, },
) )
suspend fun preview(moodId: String, limit: Int = 20): List<Song> = suspend fun retryRecommendation(moodId: String, externalId: String): MoodDetail =
get<SearchResponse>("/moods/$moodId/preview?limit=$limit").songs parse(
http.post(url("/moods/$moodId/recommendations/$externalId/retry")) {
auth()
},
)
suspend fun search(query: String, limit: Int = 50, scope: String = "music"): List<Song> = suspend fun search(
get<SearchResponse>( query: String,
"/library/search?q=${query.encodeURLParameter()}&limit=$limit&scope=$scope", limit: Int = 10,
).songs source: String? = null,
moodId: String? = null,
suspend fun library( ): List<SearchResult> {
cursor: String? = null, val sourceParam = source?.let { "&source=${it.encodeURLParameter()}" }.orEmpty()
since: String? = null, val mood = moodId?.let { "&moodId=${it.encodeURLParameter()}" }.orEmpty()
limit: Int = 500, return parse<SearchResponse>(
scope: String = "all", http.get(url("/search?q=${query.encodeURLParameter()}&limit=$limit$sourceParam$mood")) {
revision: String? = null, auth()
): LibraryPage { // yt-dlp resolves every YouTube Music hit to get artist, album
val query = buildString { // and duration, so a search takes longer than a plain API call.
append("?limit=$limit&scope=$scope") timeout {
cursor?.let { append("&cursor=${it.encodeURLParameter()}") } requestTimeoutMillis = 60_000
since?.let { append("&since=${it.encodeURLParameter()}") } socketTimeoutMillis = 60_000
revision?.let { append("&revision=${it.encodeURLParameter()}") }
} }
return get("/library/songs$query") },
).results
} }
suspend fun startSession(moodId: String, limit: Int = 12): Session = suspend fun startSession(moodId: String, limit: Int = 12): Session =
@@ -232,40 +247,14 @@ class ApiClient(private val http: HttpClient) {
runCatching { requestNoContent { http.delete(url("/sessions/$id")) { auth() } } } 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 devices(): List<Device> = get("/auth/devices")
suspend fun scanStatus(): ScanStatus = get("/scan") suspend fun cover(songId: String, size: Int = 320): ByteArray? {
val key = "$songId:$size"
suspend fun startScan(): ScanStatus =
parse(
http.post(url("/scan")) {
auth()
},
)
suspend fun cover(albumId: String, size: Int = 320): ByteArray? {
val key = "$albumId:$size"
if (coverCache.containsKey(key)) return coverCache[key] if (coverCache.containsKey(key)) return coverCache[key]
val result = runCatching { val result = runCatching {
val response = http.get( 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()) { if (response.status.isSuccess()) {
response.bodyAsBytes().takeIf { it.isNotEmpty() } response.bodyAsBytes().takeIf { it.isNotEmpty() }
@@ -274,8 +263,7 @@ class ApiClient(private val http: HttpClient) {
} }
}.getOrNull() }.getOrNull()
if (coverCache.size > MAX_CACHED_IMAGES) coverCache.clear() if (coverCache.size > MAX_CACHED_IMAGES) coverCache.clear()
// Do not cache failures: a cover can appear after the scanner indexes a // Do not cache failures: a cover can appear after a download finishes.
// newly downloaded track, and the UI should pick it up without a restart.
if (result != null) coverCache[key] = result if (result != null) coverCache[key] = result
return result return result
} }
@@ -319,8 +307,6 @@ class ApiClient(private val http: HttpClient) {
val response = http.get("$baseUrl/api/v1/songs/$songId/stream") { val response = http.get("$baseUrl/api/v1/songs/$songId/stream") {
auth() auth()
url.parameters.append("download", "true") url.parameters.append("download", "true")
// A long audiobook must not be cancelled by the default 30s total
// request timeout.
timeout { timeout {
requestTimeoutMillis = 6 * 60 * 60 * 1000 requestTimeoutMillis = 6 * 60 * 60 * 1000
socketTimeoutMillis = 60_000 socketTimeoutMillis = 60_000
@@ -333,8 +319,8 @@ class ApiClient(private val http: HttpClient) {
fun streamUrl(songId: String): String = fun streamUrl(songId: String): String =
"$baseUrl/api/v1/songs/$songId/stream?token=${token.orEmpty().encodeURLParameter()}" "$baseUrl/api/v1/songs/$songId/stream?token=${token.orEmpty().encodeURLParameter()}"
fun coverUrl(albumId: String, size: Int = 320): String = fun coverUrl(songId: String, size: Int = 320): String =
"$baseUrl/api/v1/covers/$albumId?size=$size&token=${token.orEmpty().encodeURLParameter()}" "$baseUrl/api/v1/songs/$songId/cover?size=$size&token=${token.orEmpty().encodeURLParameter()}"
private suspend inline fun <reified T> get(path: String): T = private suspend inline fun <reified T> get(path: String): T =
parse(http.get(url(path)) { auth() }) parse(http.get(url(path)) { auth() })
@@ -23,8 +23,6 @@ data class LoginRequest(
data class User( data class User(
val name: String, val name: String,
val admin: Boolean, val admin: Boolean,
val musicFolders: List<Int> = emptyList(),
val longformFolders: List<Int> = emptyList(),
) )
@Serializable @Serializable
@@ -37,22 +35,19 @@ data class LoginResponse(
@Serializable @Serializable
data class Song( data class Song(
val id: String, val id: String,
val source: String = "youtube",
val externalId: String,
val title: String, val title: String,
val artist: String, val artist: String,
val album: String, val album: String? = null,
val albumId: String,
val trackNumber: Int? = null,
val discNumber: Int = 1,
val year: Int? = null,
val duration: Int, val duration: Int,
val bitRate: Int, val bitRate: Int = 0,
val size: Long, val size: Long = 0,
val suffix: String, val suffix: String = "mp3",
val genres: List<String> = emptyList(), val thumbnail: String? = null,
val folderId: Int, ) {
val relativePath: String, val subtitle: String get() = album?.takeIf { it.isNotBlank() } ?: artist
val updatedAt: String, }
)
@Serializable @Serializable
data class Mood( data class Mood(
@@ -61,21 +56,23 @@ data class Mood(
val description: String? = null, val description: String? = null,
val query: String? = null, val query: String? = null,
val genres: List<String> = emptyList(), val genres: List<String> = emptyList(),
val targetSize: Int, val source: String = "youtube",
val seedPercent: Int = 50, val collectionPercent: Int = 50,
val recommendationPercent: Int = 50, val recommendationPercent: Int = 50,
val refreshHours: Int, val recommendationCount: Int = 10,
val ytEnabled: Boolean, val refreshHours: Int = 24,
val lastDiscoveryAt: String? = null, val lastDiscoveryAt: String? = null,
val createdAt: String, val createdAt: String,
val changedAt: String, val changedAt: String,
val lastError: String? = null, val lastError: String? = null,
val seedCount: Int, val songCount: Int = 0,
val newRecommendations: Int = 0, val recommendationReady: Int = 0,
val recommendationDownloading: Int = 0,
val recommendationFailed: Int = 0,
) )
@Serializable @Serializable
data class Seed( data class MoodSong(
val song: Song, val song: Song,
val origin: String, val origin: String,
val addedAt: String, val addedAt: String,
@@ -86,62 +83,49 @@ data class Download(
val state: String, val state: String,
val attempts: Int = 0, val attempts: Int = 0,
val error: String? = null, val error: String? = null,
val updatedAt: String, val updatedAt: String = "",
) )
@Serializable @Serializable
data class Recommendation( data class Recommendation(
val videoId: String, val source: String = "youtube",
val externalId: String,
val title: String, val title: String,
val artist: String, val artist: String,
val album: String? = null, val album: String? = null,
val duration: Int? = null, val duration: Int? = null,
val thumbnail: String? = null, val thumbnail: String? = null,
val state: String, val state: String,
val matchedSong: Song? = null, val song: Song? = null,
val timesAdded: Int = 0,
val firstSeen: String,
val lastSeen: String,
val download: Download? = null, val download: Download? = null,
) val error: String? = null,
val firstSeen: String = "",
@Serializable val lastSeen: String = "",
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,
) )
@Serializable @Serializable
data class MoodDetail( data class MoodDetail(
val mood: Mood, val mood: Mood,
val seeds: List<Seed> = emptyList(), val songs: List<MoodSong> = emptyList(),
val recommendations: List<Recommendation> = emptyList(), val recommendations: List<Recommendation> = emptyList(),
val downloads: List<DownloadStatus> = emptyList(),
) )
/** Server-side download state for one track, keyed by source and external id. */
@Serializable @Serializable
data class MoodsResponse(val moods: List<Mood>) data class DownloadStatus(
val source: String = "youtube",
val externalId: String,
val state: String,
val attempts: Int = 0,
val error: String? = null,
val songId: String? = null,
) {
val active: Boolean get() = state == "queued" || state == "downloading"
}
@Serializable
data class MoodsResponse(val moods: List<Mood> = emptyList())
@Serializable @Serializable
data class RecommendationsResponse(val recommendations: List<Recommendation> = emptyList()) data class RecommendationsResponse(val recommendations: List<Recommendation> = emptyList())
@@ -150,20 +134,24 @@ data class RecommendationsResponse(val recommendations: List<Recommendation> = e
data class RecommendationDecision( data class RecommendationDecision(
val detail: MoodDetail, val detail: MoodDetail,
val recommendation: Recommendation, val recommendation: Recommendation,
val seedAdded: Boolean = false,
) )
@Serializable @Serializable
data class LibraryPage( data class SearchResult(
val songs: List<Song> = emptyList(), val source: String = "youtube",
val deletedSongIds: List<String> = emptyList(), val externalId: String,
val revision: String, val title: String,
val nextCursor: String? = null, val artist: String,
val nextSince: String? = null, 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 @Serializable
data class SearchResponse(val songs: List<Song> = emptyList()) data class SearchResponse(val results: List<SearchResult> = emptyList())
@Serializable @Serializable
data class Session( data class Session(
@@ -206,8 +194,21 @@ data class AddToMoodRequest(val songId: String, val moodId: String? = null)
@Serializable @Serializable
data class AddToMoodResponse(val mood: Mood, val added: Boolean) data class AddToMoodResponse(val mood: Mood, val added: Boolean)
/** Adds an existing song, a search result's video id, or a pasted URL. */
@Serializable @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 @Serializable
data class CreateMoodRequest( data class CreateMoodRequest(
@@ -215,11 +216,10 @@ data class CreateMoodRequest(
val description: String? = null, val description: String? = null,
val query: String? = null, val query: String? = null,
val genres: List<String> = emptyList(), 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 refreshHours: Int = 24,
val ytEnabled: Boolean = true,
val seedSongIds: List<String> = emptyList(),
val seedPercent: Int = 50,
) )
@Serializable @Serializable
@@ -230,10 +230,10 @@ data class UpdateMoodRequest(
val query: String? = null, val query: String? = null,
val clearQuery: Boolean = false, val clearQuery: Boolean = false,
val genres: List<String>? = null, 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 refreshHours: Int? = null,
val ytEnabled: Boolean? = null,
val seedPercent: Int? = null,
) )
@Serializable @Serializable
@@ -2,7 +2,6 @@ package win.taptap.musicmanager.client.data
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json 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.Mood
import win.taptap.musicmanager.client.api.MoodDetail import win.taptap.musicmanager.client.api.MoodDetail
import win.taptap.musicmanager.client.api.Session import win.taptap.musicmanager.client.api.Session
@@ -16,16 +15,22 @@ data class SessionState(
val user: User, 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 @Serializable
data class CachedState( data class CachedState(
val version: Int = CACHE_VERSION,
val serverUrl: String = "", val serverUrl: String = "",
val userName: String = "", val userName: String = "",
val revision: String? = null,
val songs: List<Song> = emptyList(),
val longform: List<Song> = emptyList(),
val moods: List<Mood> = emptyList(), val moods: List<Mood> = emptyList(),
val moodDetails: List<MoodDetail> = 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. */ /** The queue survives a restart so the next launch can resume where it stopped. */
@Serializable @Serializable
@@ -37,7 +42,7 @@ data class PlaybackSnapshot(
val positionSeconds: Double = 0.0, val positionSeconds: Double = 0.0,
) )
class LibraryCache(private val storage: AppStorage) { class AppCache(private val storage: AppStorage) {
private val json = Json { private val json = Json {
ignoreUnknownKeys = true 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)) if (session == null) delete(SESSION_FILE) else write(SESSION_FILE, json.encodeToString(session))
} }
fun load(): CachedState = fun load(): CachedState {
read(CACHE_FILE)?.let { val cached = read(CACHE_FILE)?.let {
runCatching { json.decodeFromString<CachedState>(it) }.getOrNull() runCatching { json.decodeFromString<CachedState>(it) }.getOrNull()
} ?: CachedState() } ?: return CachedState()
return if (cached.version == CachedState.CACHE_VERSION) cached else CachedState()
}
fun save(state: CachedState) { fun save(state: CachedState) {
write(CACHE_FILE, json.encodeToString(state)) 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() { fun clear() {
delete(CACHE_FILE) delete(CACHE_FILE)
delete(PLAYBACK_FILE) delete(PLAYBACK_FILE)
delete(PROGRESS_FILE)
} }
// Web storage can be blocked (Safari private mode) or full. Cache failure // 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 { private companion object {
const val SESSION_FILE = "session.json" 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 PLAYBACK_FILE = "playback.json"
const val PROGRESS_FILE = "longform-progress.json"
} }
} }
@@ -34,5 +34,12 @@ interface AudioPlayer {
* their own countdown for the UI either way. * their own countdown for the UI either way.
*/ */
fun scheduleSleepTimer(seconds: Long?): Boolean = false fun scheduleSleepTimer(seconds: Long?): Boolean = false
/**
* Routes hardware transport buttons (headset/Bluetooth next and previous)
* to the app's own queue. Android wires this to its MediaSession; other
* platforms ignore it. Null clears the handlers.
*/
fun setSkipCallbacks(onNext: (() -> Unit)?, onPrevious: (() -> Unit)?) = Unit
} }
File diff suppressed because it is too large. Load diff
@@ -1,18 +1,17 @@
package win.taptap.musicmanager.client.ui package win.taptap.musicmanager.client.ui
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ArrowBack import androidx.compose.material.icons.rounded.ArrowBack
import androidx.compose.material.icons.rounded.Delete 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.Refresh
import androidx.compose.material.icons.rounded.Search
import androidx.compose.material.icons.rounded.Settings import androidx.compose.material.icons.rounded.Settings
import androidx.compose.material3.AlertDialog import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.CircularProgressIndicator
@@ -138,7 +137,8 @@ private fun MainScreen(state: AppState, store: AppStore) {
val title = when (state.screen) { val title = when (state.screen) {
Screen.Moods -> "Moods" Screen.Moods -> "Moods"
Screen.MoodDetail -> state.selectedMood?.mood?.name ?: "Mood" Screen.MoodDetail -> state.selectedMood?.mood?.name ?: "Mood"
Screen.Library -> "Library & downloads" Screen.Search -> "Add music"
Screen.Downloads -> "Downloads"
Screen.Settings -> "Settings" Screen.Settings -> "Settings"
} }
Text(title, fontWeight = FontWeight.SemiBold) Text(title, fontWeight = FontWeight.SemiBold)
@@ -157,8 +157,11 @@ private fun MainScreen(state: AppState, store: AppStore) {
IconButton(onClick = { store.refreshAll() }) { IconButton(onClick = { store.refreshAll() }) {
Icon(Icons.Rounded.Refresh, contentDescription = "Refresh") Icon(Icons.Rounded.Refresh, contentDescription = "Refresh")
} }
IconButton(onClick = { store.openLibrary() }) { IconButton(onClick = { store.openSearch() }) {
Icon(Icons.Rounded.LibraryMusic, contentDescription = "Library") Icon(Icons.Rounded.Search, contentDescription = "Add music")
}
IconButton(onClick = { store.openDownloads() }) {
Icon(Icons.Rounded.DownloadDone, contentDescription = "Downloads")
} }
IconButton(onClick = { store.openSettings() }) { IconButton(onClick = { store.openSettings() }) {
Icon(Icons.Rounded.Settings, contentDescription = "Settings") Icon(Icons.Rounded.Settings, contentDescription = "Settings")
@@ -169,7 +172,8 @@ private fun MainScreen(state: AppState, store: AppStore) {
Icon(Icons.Rounded.Delete, contentDescription = "Delete mood") Icon(Icons.Rounded.Delete, contentDescription = "Delete mood")
} }
} }
Screen.Library -> { Screen.Search -> Unit
Screen.Downloads -> {
IconButton(onClick = { store.openSettings() }) { IconButton(onClick = { store.openSettings() }) {
Icon(Icons.Rounded.Settings, contentDescription = "Settings") Icon(Icons.Rounded.Settings, contentDescription = "Settings")
} }
@@ -189,7 +193,8 @@ private fun MainScreen(state: AppState, store: AppStore) {
when (state.screen) { when (state.screen) {
Screen.Moods -> MoodsScreen(state, store) Screen.Moods -> MoodsScreen(state, store)
Screen.MoodDetail -> MoodDetailScreen(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) Screen.Settings -> SettingsScreen(state, store)
} }
} }
@@ -200,7 +205,12 @@ private fun MainScreen(state: AppState, store: AppStore) {
AlertDialog( AlertDialog(
onDismissRequest = { confirmDelete = false }, onDismissRequest = { confirmDelete = false },
title = { Text("Delete mood?") }, 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 = { confirmButton = {
TextButton( TextButton(
onClick = { onClick = {
@@ -50,15 +50,15 @@ import win.taptap.musicmanager.client.store.AppStore
@Composable @Composable
fun Cover( fun Cover(
store: AppStore, store: AppStore,
albumId: String?, songId: String?,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
size: Int = 320, size: Int = 320,
) { ) {
var bitmap by remember(albumId, size) { mutableStateOf<ImageBitmap?>(null) } var bitmap by remember(songId, size) { mutableStateOf<ImageBitmap?>(null) }
LaunchedEffect(albumId, size) { LaunchedEffect(songId, size) {
if (albumId == null) return@LaunchedEffect if (songId == null) return@LaunchedEffect
val bytes = store.cover(albumId) val bytes = store.cover(songId)
bitmap = bytes?.let { data -> runCatching { decodeImage(data) }.getOrNull() } bitmap = bytes?.let { data -> runCatching { decodeImage(data) }.getOrNull() }
} }
@@ -185,7 +185,7 @@ fun SongRow(
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp), 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)) { Column(Modifier.weight(1f)) {
Text( Text(
song.title, song.title,
@@ -194,7 +194,7 @@ fun SongRow(
overflow = TextOverflow.Ellipsis, overflow = TextOverflow.Ellipsis,
) )
Text( Text(
"${song.artist} · ${song.album}", "${song.artist} · ${song.album ?: "Single"}",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1, maxLines = 1,
@@ -277,7 +277,7 @@ fun MoodPickerDialog(
Column(Modifier.weight(1f)) { Column(Modifier.weight(1f)) {
Text(mood.name, style = MaterialTheme.typography.bodyLarge) Text(mood.name, style = MaterialTheme.typography.bodyLarge)
Text( 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, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, 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,10 +1,12 @@
package win.taptap.musicmanager.client.ui package win.taptap.musicmanager.client.ui
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
@@ -15,13 +17,17 @@ import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Add 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.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.PlayArrow
import androidx.compose.material.icons.rounded.Refresh import androidx.compose.material.icons.rounded.Refresh
import androidx.compose.material.icons.rounded.RemoveCircleOutline import androidx.compose.material.icons.rounded.RemoveCircleOutline
import androidx.compose.material.icons.rounded.Search
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.FilledTonalButton import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
@@ -31,7 +37,6 @@ import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Slider import androidx.compose.material3.Slider
import androidx.compose.material3.Surface import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
@@ -46,17 +51,22 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import kotlin.math.roundToInt import kotlin.math.roundToInt
import win.taptap.musicmanager.client.api.MoodSong
import win.taptap.musicmanager.client.api.Recommendation 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.AppState
import win.taptap.musicmanager.client.store.AppStore import win.taptap.musicmanager.client.store.AppStore
import win.taptap.musicmanager.client.store.sourceLabel
@Composable @Composable
fun MoodDetailScreen(state: AppState, store: AppStore) { fun MoodDetailScreen(state: AppState, store: AppStore) {
val detail = state.selectedMood val detail = state.selectedMood
if (state.loading && detail == null) { if (state.loading && detail == null) {
Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) { Column(
Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
CircularProgressIndicator() CircularProgressIndicator()
} }
return return
@@ -68,31 +78,32 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
} }
val mood = detail.mood val mood = detail.mood
var seedQuery by remember { mutableStateOf("") }
var name by remember(mood.id) { mutableStateOf(mood.name) } var name by remember(mood.id) { mutableStateOf(mood.name) }
var description by remember(mood.id) { mutableStateOf(mood.description.orEmpty()) } var description by remember(mood.id) { mutableStateOf(mood.description.orEmpty()) }
var genres by remember(mood.id) { mutableStateOf(mood.genres.joinToString(", ")) } var genres by remember(mood.id) { mutableStateOf(mood.genres.joinToString(", ")) }
var query by remember(mood.id) { mutableStateOf(mood.query.orEmpty()) } 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 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" 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 var polls = 0
while (pendingDownloads > 0 && polls < 60) { while ((inFlight > 0 || waitingForFirstBatch) && polls < 60) {
kotlinx.coroutines.delay(10_000) kotlinx.coroutines.delay(5_000)
store.refreshSelectedMood() store.refreshSelectedMood()
polls += 1 polls += 1
} }
} }
val seedIds = detail.seeds.map { it.song.id }.toSet()
val searchResults = state.searchResults.filterNot { it.id in seedIds }
LazyColumn( LazyColumn(
modifier = Modifier.fillMaxSize(), modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(20.dp), contentPadding = PaddingValues(20.dp),
@@ -106,118 +117,78 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
) { ) {
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) { Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text( Text(
mood.description ?: "Server-driven radio", mood.description ?: "Your private mix",
style = MaterialTheme.typography.bodyMedium, style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { Row(
Text("${mood.seedCount} seeds", style = MaterialTheme.typography.labelMedium) verticalAlignment = Alignment.CenterVertically,
Text("·", color = MaterialTheme.colorScheme.onSurfaceVariant) horizontalArrangement = Arrangement.spacedBy(10.dp),
Text("${mood.targetSize} batch", style = MaterialTheme.typography.labelMedium) ) {
Text("${mood.songCount} songs", style = MaterialTheme.typography.labelMedium)
Text("·", color = MaterialTheme.colorScheme.onSurfaceVariant) Text("·", color = MaterialTheme.colorScheme.onSurfaceVariant)
Text( Text(
"${mood.seedPercent}% seeds", "${mood.collectionPercent}% collection",
style = MaterialTheme.typography.labelMedium, style = MaterialTheme.typography.labelMedium,
) )
Spacer(Modifier.weight(1f)) 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)) Icon(Icons.Rounded.PlayArrow, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(6.dp)) Spacer(Modifier.width(6.dp))
Text("Play radio") Text("Play radio")
} }
} }
if (mood.lastError != null) { 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 { item {
SectionTitle("Seeds") { SectionTitle("Songs") {
Text( Text(
"${detail.seeds.size}", "${detail.songs.size}",
style = MaterialTheme.typography.labelMedium, style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
} }
} }
if (detail.seeds.isEmpty()) { if (detail.songs.isEmpty()) {
item { item {
Text( 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, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
} }
} else { } else {
items(detail.seeds, key = { it.song.id }) { seed -> items(detail.songs, key = { it.song.id }) { entry ->
SongRow( MoodSongRow(entry, store, mood.id, downloaded = entry.song.id in state.downloads)
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")
} }
} }
}
}
item {
HorizontalDivider(Modifier.padding(vertical = 12.dp))
SectionTitle("Add songs")
}
item { item {
Row( Row(
verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(top = 4.dp),
horizontalArrangement = Arrangement.spacedBy(10.dp), horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxWidth(),
) { ) {
OutlinedTextField( FilledTonalButton(onClick = { store.openSearch(mood.id) }) {
value = seedQuery, Icon(Icons.Rounded.Search, contentDescription = null, modifier = Modifier.size(18.dp))
onValueChange = { seedQuery = it }, Spacer(Modifier.width(6.dp))
singleLine = true, Text("Add music")
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")
}
}
}
if (state.preview.isNotEmpty()) {
item { item {
HorizontalDivider(Modifier.padding(vertical = 12.dp)) HorizontalDivider(Modifier.padding(vertical = 12.dp))
SectionTitle("Next batch") SectionTitle("Recommendations") {
}
items(state.preview, key = { "preview-${it.id}" }) { song ->
SongRow(store = store, song = 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") {
Row(verticalAlignment = Alignment.CenterVertically) { Row(verticalAlignment = Alignment.CenterVertically) {
if (state.discovering) { if (state.discovering) {
CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp) CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
@@ -225,7 +196,7 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
} }
TextButton( TextButton(
onClick = { store.refreshRecommendations() }, onClick = { store.refreshRecommendations() },
enabled = !state.discovering, enabled = !state.discovering && mood.recommendationCount > 0,
) { ) {
Icon(Icons.Rounded.Refresh, contentDescription = null, modifier = Modifier.size(16.dp)) Icon(Icons.Rounded.Refresh, contentDescription = null, modifier = Modifier.size(16.dp))
Spacer(Modifier.width(4.dp)) Spacer(Modifier.width(4.dp))
@@ -235,25 +206,31 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
} }
} }
val visible = detail.recommendations.filter { it.state != "rejected" } if (mood.recommendationCount == 0) {
if (visible.isEmpty()) { 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 { item {
Text( Text(
if (state.discovering) { if (state.discovering) {
"Searching YouTube Music..." "Searching and downloading picks…"
} else { } 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, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
} }
} else { } else {
items(visible, key = { "rec-${it.videoId}" }) { recommendation -> items(detail.recommendations, key = { "rec-${it.source}-${it.externalId}" }) { recommendation ->
RecommendationRow(recommendation, state.discovering, store) RecommendationRow(recommendation, state.discovering, store)
} }
} }
}
item { item {
HorizontalDivider(Modifier.padding(vertical = 12.dp)) HorizontalDivider(Modifier.padding(vertical = 12.dp))
@@ -286,47 +263,90 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
OutlinedTextField( OutlinedTextField(
value = query, value = query,
onValueChange = { query = it }, onValueChange = { query = it },
label = { Text("Free-text hint") }, label = { Text("Discovery hint") },
singleLine = true, singleLine = true,
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
) )
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { Row(
OutlinedTextField( modifier = Modifier.fillMaxWidth(),
value = target, verticalAlignment = Alignment.CenterVertically,
onValueChange = { target = it }, ) {
label = { Text("Batch size") }, Column(Modifier.weight(1f)) {
singleLine = true, 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),
)
}
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text( Text(
"Seed mix: ${seedPercent.roundToInt()}% seeds · ${100 - seedPercent.roundToInt()}% recommendations", "Search, recommendations and downloads use this catalog.",
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.",
style = MaterialTheme.typography.labelSmall, style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
} }
Row(verticalAlignment = Alignment.CenterVertically) { Box {
Text("YT Music discovery", Modifier.weight(1f)) OutlinedButton(onClick = { sourceMenu = true }) {
Switch(checked = yt, onCheckedChange = { yt = it }) 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( FilledTonalButton(
enabled = !state.saving && name.isNotBlank(), enabled = !state.saving && name.isNotBlank(),
onClick = { onClick = {
@@ -336,10 +356,10 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
description = description.trim().takeIf { it.isNotEmpty() }, description = description.trim().takeIf { it.isNotEmpty() },
genres = genres.split(',').map { it.trim() }.filter { it.isNotEmpty() }, genres = genres.split(',').map { it.trim() }.filter { it.isNotEmpty() },
query = query.trim().takeIf { 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, refreshHours = hours.toIntOrNull() ?: mood.refreshHours,
ytEnabled = yt,
seedPercent = seedPercent.roundToInt(),
) )
}, },
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
@@ -353,18 +373,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 @Composable
private fun RecommendationRow( private fun RecommendationRow(
recommendation: Recommendation, recommendation: Recommendation,
busy: Boolean, busy: Boolean,
store: AppStore, store: AppStore,
) { ) {
val failed = recommendation.state == "failed" ||
recommendation.download?.state == "failed"
Row( Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp), modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp), 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)) RemoteImage(store, recommendation.thumbnail, Modifier.size(48.dp))
}
Column(Modifier.weight(1f)) { Column(Modifier.weight(1f)) {
Text( Text(
recommendation.title, recommendation.title,
@@ -375,35 +422,29 @@ private fun RecommendationRow(
Text( Text(
buildString { buildString {
append(recommendation.artist) append(recommendation.artist)
recommendation.album?.takeIf { it.isNotBlank() }?.let { append(" · ").append(it) } recommendation.duration?.let { append(" · ").append(formatDuration(it)) }
}, },
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1, maxLines = 1,
overflow = TextOverflow.Ellipsis, overflow = TextOverflow.Ellipsis,
) )
val download = recommendation.download
Text( Text(
when { when {
recommendation.state == "accepted" && recommendation.matchedSong != null -> "Seed added" failed -> "Download failed"
download?.state == "downloading" -> "Downloading..." recommendation.state == "ready" -> "Ready to add"
download?.state == "failed" -> "Download failed — tap ✓ to retry" else -> "Downloading…"
download?.state == "queued" -> "Download queued"
recommendation.state == "accepted" -> "Queued for download"
recommendation.matchedSong != null -> "In your library"
else -> "New"
}, },
style = MaterialTheme.typography.labelSmall, style = MaterialTheme.typography.labelSmall,
color = when { color = if (failed) {
download?.state == "failed" -> MaterialTheme.colorScheme.error MaterialTheme.colorScheme.error
recommendation.state == "accepted" || download != null -> } else {
MaterialTheme.colorScheme.primary MaterialTheme.colorScheme.primary
else -> MaterialTheme.colorScheme.onSurfaceVariant
}, },
) )
if (download?.state == "failed" && download.error != null) { if (failed && recommendation.error != null) {
Text( Text(
download.error, recommendation.error,
style = MaterialTheme.typography.labelSmall, style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.error, color = MaterialTheme.colorScheme.error,
maxLines = 2, maxLines = 2,
@@ -411,26 +452,26 @@ private fun RecommendationRow(
) )
} }
} }
if (recommendation.state == "accepted" && recommendation.download?.state != "failed") { if (failed) {
Icon( IconButton(
Icons.Rounded.Check, onClick = { store.retryRecommendation(recommendation.externalId) },
contentDescription = "Accepted", enabled = !busy,
tint = MaterialTheme.colorScheme.primary, ) {
modifier = Modifier.size(20.dp), Icon(Icons.Rounded.Refresh, contentDescription = "Retry download")
) }
} else { } else {
IconButton( IconButton(
onClick = { store.acceptRecommendation(recommendation.videoId) }, onClick = { store.addRecommendation(recommendation.externalId) },
enabled = !busy, enabled = !busy,
) { ) {
Icon(Icons.Rounded.Check, contentDescription = "Accept recommendation") Icon(Icons.Rounded.Add, contentDescription = "Add to mood")
}
} }
IconButton( IconButton(
onClick = { store.rejectRecommendation(recommendation.videoId) }, onClick = { store.rejectRecommendation(recommendation.externalId) },
enabled = !busy, 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.Button
import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.FilledTonalButton import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Slider import androidx.compose.material3.Slider
import androidx.compose.material3.Switch
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
@@ -51,6 +53,7 @@ import kotlin.math.roundToInt
import win.taptap.musicmanager.client.api.Mood import win.taptap.musicmanager.client.api.Mood
import win.taptap.musicmanager.client.store.AppState import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore import win.taptap.musicmanager.client.store.AppStore
import win.taptap.musicmanager.client.store.sourceLabel
@Composable @Composable
fun MoodsScreen(state: AppState, store: AppStore) { fun MoodsScreen(state: AppState, store: AppStore) {
@@ -68,7 +71,7 @@ fun MoodsScreen(state: AppState, store: AppStore) {
fontWeight = FontWeight.SemiBold, fontWeight = FontWeight.SemiBold,
) )
Text( 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, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
@@ -90,7 +93,7 @@ fun MoodsScreen(state: AppState, store: AppStore) {
if (state.moods.isEmpty()) { if (state.moods.isEmpty()) {
EmptyState( EmptyState(
title = "No moods yet", 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(), modifier = Modifier.fillMaxSize(),
) )
} else { } else {
@@ -116,9 +119,18 @@ fun MoodsScreen(state: AppState, store: AppStore) {
CreateMoodDialog( CreateMoodDialog(
saving = state.saving, saving = state.saving,
onDismiss = { creating = false }, onDismiss = { creating = false },
onCreate = { name, description, genres, query, target, hours, yt, seedPercent -> onCreate = { name, description, genres, query, source, collectionPercent, recommendations, hours ->
creating = false 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, overflow = TextOverflow.Ellipsis,
) )
Text( Text(
mood.description ?: mood.genres.joinToString(" · ").ifBlank { "Server-driven radio" }, mood.description ?: mood.genres.joinToString(" · ").ifBlank { "Your private mix" },
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = Color.White.copy(alpha = 0.78f), color = Color.White.copy(alpha = 0.78f),
maxLines = 2, maxLines = 2,
@@ -153,21 +165,29 @@ private fun MoodCard(mood: Mood, onOpen: () -> Unit, onPlay: () -> Unit) {
) )
Row(verticalAlignment = Alignment.CenterVertically) { Row(verticalAlignment = Alignment.CenterVertically) {
Text( Text(
"${mood.seedCount} seeds", "${mood.songCount} songs",
style = MaterialTheme.typography.labelMedium, style = MaterialTheme.typography.labelMedium,
color = Color.White.copy(alpha = 0.85f), 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)) Spacer(Modifier.width(8.dp))
Text( Text(
"${mood.newRecommendations} picks", "$picks picks",
style = MaterialTheme.typography.labelMedium, style = MaterialTheme.typography.labelMedium,
color = Color.White.copy(alpha = 0.85f), 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)) Spacer(Modifier.weight(1f))
FilledTonalButton( FilledTonalButton(
onClick = onPlay, onClick = onPlay,
enabled = mood.songCount > 0,
colors = ButtonDefaults.filledTonalButtonColors( colors = ButtonDefaults.filledTonalButtonColors(
containerColor = Color.White.copy(alpha = 0.16f), containerColor = Color.White.copy(alpha = 0.16f),
contentColor = Color.White, contentColor = Color.White,
@@ -186,16 +206,17 @@ private fun MoodCard(mood: Mood, onOpen: () -> Unit, onPlay: () -> Unit) {
private fun CreateMoodDialog( private fun CreateMoodDialog(
saving: Boolean, saving: Boolean,
onDismiss: () -> Unit, 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 name by remember { mutableStateOf("") }
var description by remember { mutableStateOf("") } var description by remember { mutableStateOf("") }
var genres by remember { mutableStateOf("") } var genres by remember { mutableStateOf("") }
var query 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 hours by remember { mutableStateOf("24") }
var yt by remember { mutableStateOf(true) }
var seedPercent by remember { mutableStateOf(50f) }
AlertDialog( AlertDialog(
onDismissRequest = onDismiss, onDismissRequest = onDismiss,
@@ -226,41 +247,68 @@ private fun CreateMoodDialog(
OutlinedTextField( OutlinedTextField(
value = query, value = query,
onValueChange = { query = it }, onValueChange = { query = it },
label = { Text("Free-text hint") }, label = { Text("Discovery hint") },
singleLine = true, singleLine = true,
) )
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { Row(
OutlinedTextField( modifier = Modifier.fillMaxWidth(),
value = target, verticalAlignment = Alignment.CenterVertically,
onValueChange = { target = it }, ) {
label = { Text("Batch size") }, Text(
singleLine = true, "Download source",
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.weight(1f), modifier = Modifier.weight(1f),
) )
OutlinedTextField( Box {
value = hours, OutlinedButton(onClick = { sourceMenu = true }) {
onValueChange = { hours = it }, Text(sourceLabel(source))
label = { Text("Refresh h") }, }
singleLine = true, DropdownMenu(
modifier = Modifier.weight(1f), 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)) { Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text( Text(
"Seed mix: ${seedPercent.roundToInt()}% seeds · ${100 - seedPercent.roundToInt()}% recommendations", "Collection share: ${collectionPercent.roundToInt()}% · ${100 - collectionPercent.roundToInt()}% recommendations",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
) )
Slider( Slider(
value = seedPercent, value = collectionPercent,
onValueChange = { seedPercent = it }, onValueChange = { collectionPercent = it },
valueRange = 0f..100f, valueRange = 0f..100f,
steps = 9, steps = 9,
) )
} }
Row(verticalAlignment = Alignment.CenterVertically) { Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text("YT Music discovery", Modifier.weight(1f)) Text(
Switch(checked = yt, onCheckedChange = { yt = it }) "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 = { confirmButton = {
@@ -272,10 +320,10 @@ private fun CreateMoodDialog(
description.trim().takeIf { it.isNotEmpty() }, description.trim().takeIf { it.isNotEmpty() },
genres.split(',').map { it.trim() }.filter { it.isNotEmpty() }, genres.split(',').map { it.trim() }.filter { it.isNotEmpty() },
query.trim().takeIf { it.isNotEmpty() }, query.trim().takeIf { it.isNotEmpty() },
target.toIntOrNull() ?: 30, source,
collectionPercent.roundToInt(),
recommendations.roundToInt(),
hours.toIntOrNull() ?: 24, hours.toIntOrNull() ?: 24,
yt,
seedPercent.roundToInt(),
) )
}, },
) { Text("Create") } ) { Text("Create") }
@@ -1,11 +1,15 @@
package win.taptap.musicmanager.client.ui 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.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding 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.layout.width
import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.AddCircleOutline import androidx.compose.material.icons.rounded.AddCircleOutline
import androidx.compose.material.icons.rounded.Bedtime import androidx.compose.material.icons.rounded.Bedtime
import androidx.compose.material.icons.rounded.Close import androidx.compose.material.icons.rounded.Close
import androidx.compose.material.icons.rounded.KeyboardArrowDown import androidx.compose.material.icons.rounded.DragHandle
import androidx.compose.material.icons.rounded.KeyboardArrowUp import androidx.compose.material.icons.rounded.MoreVert
import androidx.compose.material.icons.rounded.Pause import androidx.compose.material.icons.rounded.Pause
import androidx.compose.material.icons.rounded.PlayArrow import androidx.compose.material.icons.rounded.PlayArrow
import androidx.compose.material.icons.rounded.PlaylistAdd 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.Text
import androidx.compose.material3.TextButton import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.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.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog 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.AppState
import win.taptap.musicmanager.client.store.AppStore import win.taptap.musicmanager.client.store.AppStore
private val QUEUE_ROW_HEIGHT = 58.dp
@Composable @Composable
fun PlayerBar(state: AppState, store: AppStore) { fun PlayerBar(state: AppState, store: AppStore) {
val song = state.current ?: return val song = state.current ?: return
var picker by remember { mutableStateOf(false) } var picker by remember { mutableStateOf(false) }
var sleepMenu by remember { mutableStateOf(false) } var sleepMenu by remember { mutableStateOf(false) }
var moreMenu by remember { mutableStateOf(false) }
var queueOpen by remember { mutableStateOf(false) } var queueOpen by remember { mutableStateOf(false) }
var dragSeconds by remember(song.id) { mutableStateOf<Float?>(null) } var dragSeconds by remember(song.id) { mutableStateOf<Float?>(null) }
val sleepRemaining = state.sleepTimerRemainingSeconds val sleepRemaining = state.sleepTimerRemainingSeconds
val isLongform = state.user?.longformFolders?.contains(song.folderId) == true
Surface( Surface(
color = MaterialTheme.colorScheme.surfaceVariant, color = MaterialTheme.colorScheme.surfaceVariant,
@@ -91,6 +105,36 @@ fun PlayerBar(state: AppState, store: AppStore) {
IconButton(onClick = { queueOpen = true }) { IconButton(onClick = { queueOpen = true }) {
Icon(Icons.Rounded.QueueMusic, contentDescription = "Queue") 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 { Box {
IconButton(onClick = { sleepMenu = true }) { IconButton(onClick = { sleepMenu = true }) {
Icon( Icon(
@@ -131,11 +175,13 @@ fun PlayerBar(state: AppState, store: AppStore) {
} }
Row( 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, 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)) { Column(Modifier.weight(1f)) {
Text( Text(
song.title, song.title,
@@ -167,27 +213,36 @@ fun PlayerBar(state: AppState, store: AppStore) {
) )
} }
if (!isLongform) { IconButton(
IconButton(onClick = { store.addCurrentToMood(null) }) { onClick = { store.previous() },
Icon(Icons.Rounded.AddCircleOutline, contentDescription = "Add to current mood") modifier = Modifier.size(40.dp),
) {
Icon(
Icons.Rounded.SkipPrevious,
contentDescription = "Previous",
modifier = Modifier.size(26.dp),
)
} }
IconButton(onClick = { picker = true }) { IconButton(
Icon(Icons.Rounded.PlaylistAdd, contentDescription = "Add to another mood") onClick = { store.togglePlayPause() },
} modifier = Modifier.size(48.dp),
} ) {
IconButton(onClick = { store.previous() }) {
Icon(Icons.Rounded.SkipPrevious, contentDescription = "Previous")
}
IconButton(onClick = { store.skip() }) {
Icon(Icons.Rounded.SkipNext, contentDescription = "Skip")
}
IconButton(onClick = { store.togglePlayPause() }) {
Icon( Icon(
if (state.playing) Icons.Rounded.Pause else Icons.Rounded.PlayArrow, if (state.playing) Icons.Rounded.Pause else Icons.Rounded.PlayArrow,
contentDescription = if (state.playing) "Pause" else "Play", contentDescription = if (state.playing) "Pause" else "Play",
modifier = Modifier.size(30.dp), 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 @Composable
private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit) { 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) { Dialog(onDismissRequest = onDismiss) {
Surface( Surface(
shape = RoundedCornerShape(18.dp), shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surface, color = MaterialTheme.colorScheme.surface,
tonalElevation = 6.dp, tonalElevation = 6.dp,
modifier = Modifier.fillMaxWidth().heightIn(max = 600.dp), modifier = Modifier.fillMaxWidth().heightIn(max = 620.dp),
) { ) {
Column { Column {
Row( Row(
@@ -226,7 +312,11 @@ private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit)
Column(Modifier.weight(1f)) { Column(Modifier.weight(1f)) {
Text("Queue", style = MaterialTheme.typography.titleMedium) Text("Queue", style = MaterialTheme.typography.titleMedium)
Text( 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, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
@@ -234,17 +324,23 @@ private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit)
TextButton(onClick = onDismiss) { Text("Close") } TextButton(onClick = onDismiss) { Text("Close") }
} }
HorizontalDivider() HorizontalDivider()
LazyColumn(Modifier.fillMaxWidth().heightIn(max = 480.dp)) {
state.current?.let { song -> state.current?.let { song ->
item(key = "current") {
Row( Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 10.dp), modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp), 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)) { 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( Text(
"Now playing", "Now playing",
style = MaterialTheme.typography.labelSmall, style = MaterialTheme.typography.labelSmall,
@@ -252,29 +348,86 @@ private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit)
) )
} }
} }
} HorizontalDivider()
} }
if (state.queue.isEmpty()) { if (state.queue.isEmpty()) {
item {
Text( 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), modifier = Modifier.padding(20.dp),
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, 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( 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, verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp), 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)) { 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( Text(
song.artist, song.artist,
style = MaterialTheme.typography.labelSmall, style = MaterialTheme.typography.labelSmall,
@@ -283,19 +436,19 @@ private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit)
overflow = TextOverflow.Ellipsis, overflow = TextOverflow.Ellipsis,
) )
} }
Icon(
Icons.Rounded.DragHandle,
contentDescription = "Drag to reorder",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(22.dp),
)
IconButton( IconButton(
onClick = { store.moveInQueue(index, index - 1) }, onClick = {
enabled = index > 0, 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") Icon(Icons.Rounded.Close, contentDescription = "Remove from queue")
} }
} }
@@ -305,3 +458,5 @@ private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit)
} }
} }
} }
}
}
@@ -0,0 +1,310 @@
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.DownloadStatus
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.downloadKey
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,
download = state.searchDownloads[downloadKey(result.source, result.externalId)],
)
}
item { Spacer(Modifier.size(24.dp)) }
}
}
@Composable
private fun SearchRow(result: SearchResult, store: AppStore, download: DownloadStatus?) {
val pending = download?.active == true
val added = download?.state == "done"
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,
)
when {
pending -> Row(verticalAlignment = Alignment.CenterVertically) {
CircularProgressIndicator(Modifier.size(12.dp), strokeWidth = 2.dp)
Spacer(Modifier.width(6.dp))
Text(
"Downloading…",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
)
}
added -> 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(
"Added to this mood",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
)
}
download?.state == "failed" -> Text(
"Download failed" +
(download.error?.takeIf { it.isNotBlank() }?.let { " — ${it}" } ?: "") +
". Tap + to retry.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.error,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
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,
)
}
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 && !pending && !added,
) {
if (pending) {
CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp)
} else {
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.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.DeleteSweep import androidx.compose.material.icons.rounded.DeleteSweep
import androidx.compose.material.icons.rounded.Logout import androidx.compose.material.icons.rounded.Logout
import androidx.compose.material.icons.rounded.Refresh import androidx.compose.material.icons.rounded.Refresh
import androidx.compose.material.icons.rounded.TravelExplore
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.FilledTonalButton import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
@@ -35,7 +35,7 @@ import win.taptap.musicmanager.client.store.AppStore
fun SettingsScreen(state: AppState, store: AppStore) { fun SettingsScreen(state: AppState, store: AppStore) {
LazyColumn( LazyColumn(
modifier = Modifier.fillMaxSize(), modifier = Modifier.fillMaxSize(),
contentPadding = androidx.compose.foundation.layout.PaddingValues(20.dp), contentPadding = PaddingValues(20.dp),
verticalArrangement = Arrangement.spacedBy(14.dp), verticalArrangement = Arrangement.spacedBy(14.dp),
) { ) {
item { item {
@@ -57,6 +57,11 @@ fun SettingsScreen(state: AppState, store: AppStore) {
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, 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(), modifier = Modifier.fillMaxWidth(),
) { ) {
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) { 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( Text(
"${state.library.size} songs cached · ${state.downloads.size} downloaded · ${formatBytes(store.storageBytes())}", "${state.downloads.size} downloaded · ${formatBytes(store.storageBytes())}",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) { Row(
FilledTonalButton(onClick = { store.refreshAll() }) { horizontalArrangement = Arrangement.spacedBy(10.dp),
Icon(Icons.Rounded.Refresh, contentDescription = null) verticalAlignment = Alignment.CenterVertically,
Spacer(Modifier.width(6.dp)) ) {
Text("Sync") OutlinedButton(onClick = { store.openDownloads() }) {
} Text("Manage downloads")
if (state.user?.admin == true) {
OutlinedButton(onClick = { store.scanLibrary() }) {
Icon(Icons.Rounded.TravelExplore, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text("Scan")
}
}
} }
if (state.downloads.isNotEmpty()) { if (state.downloads.isNotEmpty()) {
OutlinedButton(onClick = { store.clearDownloads() }) { OutlinedButton(onClick = { store.clearDownloads() }) {
Icon(Icons.Rounded.DeleteSweep, contentDescription = null) Icon(Icons.Rounded.DeleteSweep, contentDescription = null)
Spacer(Modifier.width(6.dp)) 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)) { Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text("About", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Text("About", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
Text( Text(
"AudioManager 0.1.0 · $platformName", "AudioManager 0.3.3 · $platformName",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
Text( 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, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
@@ -8,17 +8,17 @@ import io.ktor.http.HttpStatusCode
import io.ktor.http.headersOf import io.ktor.http.headersOf
import io.ktor.utils.io.readAvailable import io.ktor.utils.io.readAvailable
import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json
import kotlin.test.Test import kotlin.test.Test
import kotlin.test.assertEquals import kotlin.test.assertEquals
import kotlin.test.assertFailsWith import kotlin.test.assertFailsWith
import kotlin.test.assertNull import kotlin.test.assertNull
import kotlin.test.assertTrue
import win.taptap.musicmanager.client.api.ApiClient import win.taptap.musicmanager.client.api.ApiClient
import win.taptap.musicmanager.client.api.ApiException 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.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.CachedState
import win.taptap.musicmanager.client.data.LibraryCache
class ApiClientTest { class ApiClientTest {
@@ -31,15 +31,16 @@ class ApiClientTest {
"/api/v1/auth/login" -> respond( "/api/v1/auth/login" -> respond(
""" """
{"token":"abc123","expiresAt":"2027-01-01T00:00:00Z", {"token":"abc123","expiresAt":"2027-01-01T00:00:00Z",
"user":{"name":"alice","admin":true,"musicFolders":[1],"longformFolders":[10]}} "user":{"name":"alice","admin":true}}
""".trimIndent(), """.trimIndent(),
HttpStatusCode.OK, HttpStatusCode.OK,
jsonHeaders, jsonHeaders,
) )
"/api/v1/moods" -> respond( "/api/v1/moods" -> respond(
""" """
{"moods":[{"id":"mo-1","name":"Focus","targetSize":30,"refreshHours":24, {"moods":[{"id":"mo-1","name":"Focus","source":"deezer","collectionPercent":60,
"ytEnabled":true,"createdAt":"now","changedAt":"now","seedCount":2}]} "recommendationPercent":40,"recommendationCount":10,"refreshHours":24,
"createdAt":"now","changedAt":"now","songCount":2,"recommendationReady":3}]}
""".trimIndent(), """.trimIndent(),
HttpStatusCode.OK, HttpStatusCode.OK,
jsonHeaders, jsonHeaders,
@@ -56,7 +57,87 @@ class ApiClientTest {
val moods = client.moods() val moods = client.moods()
assertEquals(1, moods.size) assertEquals(1, moods.size)
assertEquals("Focus", moods.first().name) 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 @Test
@@ -116,23 +197,33 @@ class ApiClientTest {
} }
@Test @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 storage = MemoryStorage()
val cache = LibraryCache(storage) val cache = AppCache(storage)
assertNull(cache.loadSession()) assertNull(cache.loadSession())
val mood = Mood(
id = "mo-1",
name = "Focus",
createdAt = "now",
changedAt = "now",
songCount = 2,
)
cache.save( cache.save(
CachedState( CachedState(
serverUrl = "http://localhost:8080", serverUrl = "http://localhost:8080",
userName = "alice", userName = "alice",
revision = "2026-11-14T00:00:00Z", moods = listOf(mood),
songs = emptyList(),
moods = emptyList(),
), ),
) )
val loaded = cache.load() 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) 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.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.withContext
import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
import kotlin.test.Test import kotlin.test.Test
import kotlin.test.assertEquals import kotlin.test.assertEquals
import kotlin.test.assertFalse 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.Song
import win.taptap.musicmanager.client.api.User import win.taptap.musicmanager.client.api.User
import win.taptap.musicmanager.client.api.configuredHttpClient 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.CachedState
import win.taptap.musicmanager.client.data.LibraryCache
import win.taptap.musicmanager.client.data.PlaybackSnapshot import win.taptap.musicmanager.client.data.PlaybackSnapshot
import win.taptap.musicmanager.client.data.SessionState import win.taptap.musicmanager.client.data.SessionState
import win.taptap.musicmanager.client.playback.AudioPlayer import win.taptap.musicmanager.client.playback.AudioPlayer
@@ -35,48 +35,252 @@ import win.taptap.musicmanager.client.store.AppStore
class AppStoreTest { class AppStoreTest {
@Test @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 storage = MemoryStorage()
val cache = LibraryCache(storage) val cache = AppCache(storage)
val songs = listOf(song("a"), song("b"), song("c")) cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
cache.save(CachedState(serverUrl = "http://music", songs = songs))
val player = FakePlayer() 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/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() runCurrent()
store.openMood("mo-1")
awaitState { store.state.value.selectedMood != null }
store.playAll() store.playMood("mo-1")
runCurrent() awaitState { store.state.value.current != null }
val state = store.state.value val state = store.state.value
val current = assertNotNull(state.current) assertEquals("a", state.current?.id)
assertEquals("s1", state.session?.id)
assertTrue(state.playing) assertTrue(state.playing)
assertEquals(listOf(current.id), player.played) assertEquals(listOf("a"), player.played)
assertEquals(2, state.queue.size)
assertEquals(songs.map { it.id }.toSet(), (state.queue + current).map { it.id }.toSet())
store.release() store.release()
} }
@Test @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 storage = MemoryStorage()
val cache = LibraryCache(storage) val cache = AppCache(storage)
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
val player = FakePlayer() 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)
else -> respondError(HttpStatusCode.NotFound)
}
}
val store = store(storage, cache, player, engine)
runCurrent() runCurrent()
store.openMood("mo-1")
awaitState { store.state.value.selectedMood != null }
store.playAll() store.playMood("mo-1")
runCurrent() awaitState { store.state.value.message != null }
assertNull(store.state.value.current) assertNull(store.state.value.current)
assertTrue(player.played.isEmpty()) assertTrue(player.played.isEmpty())
assertTrue(store.state.value.messageIsError) 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 `search shows the queued download status for a result`() = 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)
// Any detail the app may race with reports the job as active.
"/api/v1/moods/mo-1" -> respond(
detailJson(emptyList(), downloads = listOf(downloadJson("downloading"))),
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(), downloads = listOf(downloadJson("queued")) )},
"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("search results") { store.state.value.searchResults.isNotEmpty() }
store.addSearchResult(store.state.value.searchResults.single())
awaitState("queued download") {
store.state.value.searchDownloads["youtube|v1"]?.active == true
}
val status = store.state.value.searchDownloads.getValue("youtube|v1")
assertTrue(status.state == "queued" || status.state == "downloading")
assertTrue(status.active)
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/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/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("mood source updated") {
store.state.value.moods.first { it.id == "mo-1" }.source == "deezer"
}
// The source change re-runs the search immediately, without debounce.
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() store.release()
} }
@Test @Test
fun `sleep timer pauses playback when it expires`() = runTest { fun `sleep timer pauses playback when it expires`() = runTest {
val storage = MemoryStorage() val storage = MemoryStorage()
val cache = LibraryCache(storage) val cache = AppCache(storage)
val player = FakePlayer() val player = FakePlayer()
val store = store(storage, cache, player) val store = store(storage, cache, player)
runCurrent() runCurrent()
@@ -91,54 +295,30 @@ class AppStoreTest {
advanceTimeBy(60_000) advanceTimeBy(60_000)
runCurrent() runCurrent()
val state = store.state.value assertFalse(store.state.value.playing)
assertFalse(state.playing) assertNull(store.state.value.sleepTimerRemainingSeconds)
assertNull(state.sleepTimerRemainingSeconds)
assertTrue(player.paused) assertTrue(player.paused)
store.release() store.release()
} }
@Test @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 storage = MemoryStorage()
val cache = LibraryCache(storage) val cache = AppCache(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)
cache.savePlayback( cache.savePlayback(
PlaybackSnapshot( PlaybackSnapshot(
queue = listOf(song("b")), queue = listOf(song("b")),
current = song("a"), current = song("a"),
positionSeconds = 12.0,
), ),
) )
val player = FakePlayer() val player = FakePlayer()
val store = store(storage, cache, player) val store = store(storage, cache, player)
runCurrent() runCurrent()
val restored = store.state.value assertEquals("a", store.state.value.current?.id)
assertEquals("a", restored.current?.id) assertEquals(listOf("b"), store.state.value.queue.map { it.id })
assertEquals(listOf("b"), restored.queue.map { it.id }) assertEquals(12.0, store.state.value.positionSeconds)
assertFalse(restored.playing)
assertTrue(player.played.isEmpty()) assertTrue(player.played.isEmpty())
store.togglePlayPause() store.togglePlayPause()
@@ -146,93 +326,40 @@ class AppStoreTest {
assertTrue(store.state.value.playing) assertTrue(store.state.value.playing)
assertEquals(listOf("a"), player.played) assertEquals(listOf("a"), player.played)
assertEquals(12.0, player.seeks.last())
store.release() store.release()
} }
@Test @Test
fun `accepting a recommendation replaces the selected mood`() = runTest { fun `queue reordering and removal persist in the snapshot`() = runTest {
val storage = MemoryStorage() val storage = MemoryStorage()
val cache = LibraryCache(storage) val cache = AppCache(storage)
cache.saveSession( cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
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 engine = MockEngine { request -> val engine = MockEngine { request ->
when (request.url.encodedPath) { when (request.url.encodedPath) {
"/api/v1/moods" -> respond("""{"moods":[]}""", HttpStatusCode.OK, jsonHeaders) "/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/library/songs" -> respond( "/api/v1/moods" -> respond("""{"moods":[${moodJson(3)}]}""", HttpStatusCode.OK, jsonHeaders)
"""{"songs":[],"revision":"r1"}""", "/api/v1/moods/mo-1" -> respond(
detailJson(listOf("a", "b", "c")),
HttpStatusCode.OK, HttpStatusCode.OK,
jsonHeaders, jsonHeaders,
) )
"/api/v1/moods/mo-1" -> respond(detail, HttpStatusCode.OK, jsonHeaders) "/api/v1/moods/mo-1/sessions" -> respond(
"/api/v1/moods/mo-1/preview" -> respond( """{"id":"s1","moodId":"mo-1","moodName":"Focus","startedAt":"now",
"""{"songs":[]}""", "queue":[${songJson("a")},${songJson("b")},${songJson("c")}]}""",
HttpStatusCode.OK, HttpStatusCode.Created,
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,
jsonHeaders, jsonHeaders,
) )
else -> respondError(HttpStatusCode.NotFound) else -> respondError(HttpStatusCode.NotFound)
} }
} }
val store = AppStore( val store = store(storage, cache, FakePlayer(), engine)
scope = this,
api = ApiClient(configuredHttpClient(engine)),
storage = storage,
player = player,
cache = cache,
)
runCurrent() runCurrent()
store.openMood("mo-1") store.openMood("mo-1")
awaitState { store.state.value.selectedMood != null || store.state.value.message != null } awaitState { store.state.value.selectedMood != null }
assertEquals( store.playMood("mo-1")
"new", awaitState { store.state.value.current?.id == "a" }
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)
assertEquals(listOf("b", "c"), store.state.value.queue.map { it.id }) assertEquals(listOf("b", "c"), store.state.value.queue.map { it.id })
store.moveInQueue(1, 0) store.moveInQueue(1, 0)
@@ -245,400 +372,179 @@ class AppStoreTest {
} }
@Test @Test
fun `restored playback resumes from the saved position`() = runTest { fun `headset next and previous follow the queue instead of seeking`() = runTest {
val storage = MemoryStorage() val storage = MemoryStorage()
val cache = LibraryCache(storage) val cache = AppCache(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)
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false))) cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
cache.save(CachedState(serverUrl = "http://music", userName = "alice", songs = listOf(song("a")))) val player = FakePlayer()
cache.saveProgress( val engine = MockEngine { request ->
listOf( when (request.url.encodedPath) {
win.taptap.musicmanager.client.api.LongformProgress( "/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
songId = "l1", "/api/v1/moods" -> respond("""{"moods":[${moodJson(3)}]}""", HttpStatusCode.OK, jsonHeaders)
positionSeconds = 42, "/api/v1/moods/mo-1" -> respond(detailJson(listOf("a", "b", "c")), HttpStatusCode.OK, jsonHeaders)
durationSeconds = 180, "/api/v1/moods/mo-1/sessions" -> respond(
completed = false, """{"id":"s1","moodId":"mo-1","moodName":"Focus","startedAt":"now",
updatedAt = "2026-01-01T00:00:00Z", "queue":[${songJson("a")},${songJson("b")},${songJson("c")}]}""",
), 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.playMood("mo-1")
awaitState { store.state.value.current?.id == "a" }
// A headset next moves the app queue: a -> b, not a seek inside one item.
player.pressNext()
awaitState { store.state.value.current?.id == "b" }
assertEquals("b", store.state.value.current?.id)
// Within two seconds, previous restores the track that just finished.
player.pressPrevious()
awaitState { store.state.value.current?.id == "a" }
assertEquals("a", store.state.value.current?.id)
// After two seconds it restarts the current track instead.
store.seekTo(5.0)
player.pressPrevious()
runCurrent()
assertEquals("a", store.state.value.current?.id)
assertEquals(0.0, player.seeks.last())
store.release()
}
@Test
fun `logout clears the session and the mood cache`() = runTest {
val storage = MemoryStorage()
val cache = AppCache(storage)
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
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() runCurrent()
awaitState { store.state.value.authenticated }
store.logout() store.logout()
awaitState { !store.state.value.authenticated } awaitState { !store.state.value.authenticated }
assertTrue(cache.loadProgress().isEmpty()) assertNull(cache.loadSession())
assertTrue(cache.load().songs.isEmpty()) assertTrue(cache.load().moods.isEmpty())
store.release() store.release()
} }
@Test private suspend fun TestScope.awaitState(predicate: () -> Boolean) =
fun `music search is debounced and scoped to music`() = runTest { awaitState("state", predicate)
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") private suspend fun TestScope.awaitState(label: String, predicate: () -> Boolean) {
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)
store.release()
}
private suspend fun TestScope.awaitState(predicate: () -> Boolean) {
repeat(500) { repeat(500) {
runCurrent() runCurrent()
if (predicate()) return if (predicate()) return
withContext(Dispatchers.Default) { delay(10) } withContext(Dispatchers.Default) { delay(10) }
} }
throw AssertionError("state did not settle") throw AssertionError("$label did not settle")
} }
private val jsonHeaders = headersOf(HttpHeaders.ContentType, "application/json") private val jsonHeaders = headersOf(HttpHeaders.ContentType, "application/json")
private fun moodJson(seedCount: Int) = """ private fun songJson(id: String) = """
{"id":"mo-1","name":"Focus","targetSize":30,"refreshHours":24,"ytEnabled":true, {"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", "createdAt":"2026-01-01T00:00:00Z","changedAt":"2026-01-01T00:00:00Z",
"seedCount":$seedCount,"newRecommendations":1} "songCount":$songCount}
""".trimIndent() """.trimIndent()
private fun recommendationJson(state: String) = """ private fun recommendationJson(state: String = "new", songId: String? = null) = """
{"videoId":"v-1","title":"Soft Light","artist":"Beta","duration":180, {"source":"youtube","externalId":"v1","title":"Pick","artist":"Artist",
"state":"$state","timesAdded":0, "duration":180,"state":"$state",
"firstSeen":"2026-01-01T00:00:00Z","lastSeen":"2026-01-01T00:00:00Z", ${songId?.let { "\"song\":${songJson(it)}," } ?: ""}
"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}"}""" }}} "firstSeen":"2026-01-01T00:00:00Z","lastSeen":"2026-01-01T00:00:00Z"}
""".trimIndent() """.trimIndent()
private fun moodDetailJson(state: String, seedCount: Int) = """ private fun detailJson(
{"mood":${moodJson(seedCount)},"seeds":[],"recommendations":[${recommendationJson(state)}]} songs: List<String>,
recommendation: String? = null,
source: String = "youtube",
downloads: List<String> = emptyList(),
) = """
{"mood":${moodJson(songs.size, source)},
"songs":[${songs.joinToString(",") { """{"song":${songJson(it)},"origin":"search","addedAt":"now"}""" }}],
"recommendations":${recommendation?.let { "[$it]" } ?: "[]"},
"downloads":[${downloads.joinToString(",")}]}
""".trimIndent() """.trimIndent()
private fun kotlinx.coroutines.test.TestScope.store( private fun downloadJson(
state: String,
source: String = "youtube",
externalId: String = "v1",
) = """{"source":"$source","externalId":"$externalId","state":"$state",
"attempts":1,"songId":null}""".trimIndent()
private fun song(id: String, duration: Int = 180) = Song(
id = id,
source = "youtube",
externalId = "video-$id",
title = "Song $id",
artist = "Artist",
album = "Album",
duration = duration,
bitRate = 320,
size = 1_000,
)
private fun TestScope.store(
storage: MemoryStorage, storage: MemoryStorage,
cache: LibraryCache, cache: AppCache,
player: AudioPlayer, player: AudioPlayer,
engine: MockEngine = MockEngine { respondError(HttpStatusCode.NotFound) },
): AppStore = AppStore( ): AppStore = AppStore(
// Background scope so leftover store jobs (reconnect loops, refreshes) // Background scope so leftover store jobs (reconnect loops, refreshes)
// are cancelled by runTest instead of failing the next test with // are cancelled by runTest instead of failing with UncompletedCoroutinesError.
// UncompletedCoroutinesError.
scope = backgroundScope, scope = backgroundScope,
api = ApiClient(configuredHttpClient(MockEngine { respondError(HttpStatusCode.NotFound) })), api = ApiClient(configuredHttpClient(engine)),
storage = storage, storage = storage,
player = player, player = player,
cache = cache, cache = cache,
) )
private fun song(
id: String,
artist: String = "Artist",
folderId: Int = 1,
duration: Int = 180,
) = Song(
id = id,
title = "Song $id",
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 class FakePlayer : AudioPlayer { private class FakePlayer : AudioPlayer {
private var onNext: (() -> Unit)? = null
private var onPrevious: (() -> Unit)? = null
fun pressNext() {
onNext?.invoke()
}
fun pressPrevious() {
onPrevious?.invoke()
}
override fun setSkipCallbacks(onNext: (() -> Unit)?, onPrevious: (() -> Unit)?) {
this.onNext = onNext
this.onPrevious = onPrevious
}
val played = mutableListOf<String>() val played = mutableListOf<String>()
val seeks = mutableListOf<Double>() val seeks = mutableListOf<Double>()
var paused = false var paused = false
+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`).