18 Commits
Author SHA1 Message Date
TapTap 8cf77f156d fix: avoid duplicate playback events at the end of the timeline
CI / play (push) Successful in 3m38s
CI / build (push) Successful in 3m55s
Also prefer the freshest mood detail during offline sync and reset the skip
suppression after a previous that only restarted the track.
2026-11-19 16:41:41 +00:00
TapTap 1e3dac4e47 feat: service-owned queue, full player, audio consistency and mood settings
CI / build (push) Successful in 2m40s
CI / play (push) Skipped
- Android Media3 service owns a real timeline: gapless playback, notification
  and headset next/back, 2 s previous rule, queue survives task swipes
- per-track loudness gain via an Android PCM processor and desktop mixer
- optional 0-8 s fade between tracks; full-screen player with quality info
- per-mood offline switch auto-syncs songs on Wi-Fi, three at a time
- dedicated mood settings screen with delete at the bottom
- one-tap add-to-mood in the player; sleep timer can finish the current track
- version 0.4.0
2026-11-19 16:38:21 +00:00
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
34 changed files with 4245 additions and 2427 deletions

No files matched your search

+2 -5
View File
@@ -45,15 +45,13 @@ jobs:
:composeApp:desktopTest \
:composeApp:assembleDebug \
:composeApp:packageUberJarForCurrentOS \
:composeApp:wasmJsBrowserDistribution \
--console=plain
else
# The optimized Wasm build is CPU-bound and slow; main/PR builds
# only need to prove the web target compiles and bundles.
# The Wasm target is kept for local builds but is not part of CI:
# it is CPU-bound and dominates the pipeline runtime.
gradle \
:composeApp:desktopTest \
:composeApp:assembleDebug \
:composeApp:wasmJsBrowserDevelopmentExecutableDistribution \
--console=plain
fi
@@ -64,7 +62,6 @@ jobs:
cp composeApp/build/outputs/apk/debug/composeApp-debug.apk dist/AudioManager.apk
if [[ "$GITHUB_REF" == refs/tags/* ]]; then
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
- name: Publish release assets
+143 -77
View File
@@ -1,8 +1,11 @@
# AudioManager Client
Kotlin Multiplatform client for [AudioManager](../AudioManager) — a mood-first, self-hosted music server.
Kotlin Multiplatform client for [AudioManager](../AudioManager) — a mood-first,
self-hosted music server.
The client and server are designed together. There is no OpenSubsonic compatibility layer: the app speaks the native `/api/v1` API, where playback is a server-driven radio session and "likes" are replaced by explicit **add to mood** actions.
The client and server are designed together. There is no OpenSubsonic
compatibility layer: the app speaks the native `/api/v1` API, where playback is
a server-driven radio session and songs are added from Deezer or YouTube Music.
## Targets
@@ -12,33 +15,82 @@ The client and server are designed together. There is no OpenSubsonic compatibil
| **Desktop (JVM)** | Compose Multiplatform | MP3SPI, decoded to PCM + `SourceDataLine` | Yes |
| **Web (Wasm)** | Compose Multiplatform | HTML5 `Audio` | Browser-managed cache only |
The shared module contains the API client, session/cache storage, radio queue, app state and all screens. Platform code is limited to HTTP engines, storage, audio and back handling.
## Features
- Login with a server URL, username and password. The server returns a revocable bearer token.
- Mood grid with live counts; create, rename, delete and edit moods.
- Seed management: search the owner's music, add or remove anchors.
- Server-driven radio: the app keeps a small queue and asks for more from the same mood session.
- Playback events are reported automatically (`started`, `completed`, `skipped`) so the server learns.
- Two add-to-mood actions in the player:
- **Add to current mood** (the mood of the active radio session)
- **Choose another mood** (picker)
- YT Music recommendations in the mood editor: refresh on demand, accept or reject candidates, thumbnails, and a clear state for library matches (`Seed added`), accepted-for-download tracks (`Queued`, `Downloading`, `Download failed` with retry) and new picks. Accepting a track the library already has adds it as a seed immediately; the rest are downloaded by the server and promoted automatically.
- Library search and playback, plus **Shuffle all** to queue the whole library without starting a mood.
- A queue sheet from the player: the current track plus every upcoming track, with move up/down and remove. Changes are persisted locally.
- **Previous** from the player: after two seconds of playback it restarts the current track; before that it restores the last played track. The track it leaves is put back at the front of the queue.
- **Scrubbing**: the progress slider can be dragged on every platform. Android/web seek natively; desktop restarts the decoder at the requested position (`timeOffset` for remote streams, PCM skip for local files).
- **Seed mix** per mood: a slider chooses the share of seeds vs recommendations for each generated batch. The server rolls the percentage for every queued track and falls back to the other pool when one runs out.
- **Longform tab** for audiobooks and podcasts: per-artist read-only playlists, “Shuffle artist” for random episodes, a resume list with progress, and a separate search scope. Long-form never enters music search, Shuffle all, moods or radio.
- **Sleep timer** (15/30/45/60/90 minutes) that pauses playback. On Android the pause is scheduled inside the media service, so it still fires when the app is backgrounded or the task is swiped away.
- Offline library cache: moods, songs and the last sync revision are stored locally. When the server is unreachable, downloaded tracks still play.
- The play queue and current track are saved locally, so a restart reopens the player paused and resumes on the next tap.
- Login with a server URL, username and password. The server returns a revocable
bearer token.
- **Moods** are the only content model. Each user sees only their own moods.
- **Songs** belong to the mood's permanent collection. A mood needs at least one
song before it can play.
- **Search Deezer or YouTube Music** from inside a mood or globally with a mood
picker. Each mood has a **Download source** selector; search, recommendations
and downloads follow it. Tracks over 10 minutes are hidden. Results that are already downloaded are marked and
add instantly; other videos are queued for server-side download.
- **Paste a YouTube URL** to add a specific video.
- **Recommendations** are downloaded automatically and play in the radio without
being permanent. Rows show the download state with:
- Add to mood;
- Not interested (permanent for the mood);
- Retry for failed downloads.
- **Radio** mixes the collection and ready recommendations using the mood's
`collectionPercent`. The app keeps a small queue and asks for more from the
same mood session.
- Playback events are reported automatically (`started`, `completed`, `skipped`)
so the server learns.
- **Add to mood is one tap** in the bottom player and the full-screen player.
Choosing a different mood stays in the overflow/picker.
- A queue sheet from the player: the current track is pinned, upcoming tracks
can be reordered by **long-press and drag** or removed. Changes are persisted
locally.
- **Previous** from the player: after two seconds of playback it restarts the
current track; before that it restores the last played track.
- **Headset/Bluetooth next and previous** and the media notification's skip /
back buttons use the same queue rules as the in-app controls; they no longer
seek inside the single ExoPlayer item.
- The bottom player keeps the cover and title/artist readable on narrow phones.
Tapping it opens the **full-screen player**: large artwork, scrubber, transport,
add-to-mood, queue, sleep timer and Up next.
- **Audio consistency**: the server measures every track's integrated loudness
with ffmpeg and stores a gain (target `-16 LUFS`); the app applies it per
track. The player shows the source and bitrate, and settings explain when the
Deezer ARL is limited to 128 kbps.
- **Gapless playback** on Android with an optional 0–8 s fade between tracks.
- **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** live on their own screen: name, description, discovery hint,
genres, source, collection share, recommendations, refresh interval, a
**Keep this mood offline** switch, and Delete at the bottom.
- **Downloads** screen for device-side copies: play, delete, clear, storage
usage.
- **Sleep timer** (15/30/45/60/90 minutes or **finish this track**) that pauses
playback. On Android the
pause is scheduled inside the media service, so it still fires when the app is
backgrounded or the task is swiped away.
- Mood cache: moods and details are stored locally so the app opens instantly
and can show cached data offline.
- The play queue and current track are saved locally, so a restart reopens the
player paused and resumes on the next tap.
- Reconnects automatically with exponential backoff (15s to 5min) while offline.
- Downloads retry up to three times before reporting an error; covers and YT thumbnails are cached for the app's lifetime.
- Original MP3 downloads with progress state, removal and storage usage.
- Session persistence: the login survives app restarts until the token is revoked or expires.
- Android background playback through a Media3 `MediaSessionService`: notification, lock-screen and headset controls, audio focus, and playback that survives the app being backgrounded or the task being swiped away.
- Session persistence: the login survives app restarts until the token is
revoked or expires.
- Android background playback through a Media3 `MediaSessionService`:
notification, lock-screen and headset controls, audio focus, and playback that
survives the app being backgrounded or the task being swiped away.
## Screens
`Moods | Mood Detail | Mood settings | Search | Downloads | Settings | Now playing`
- **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, audio (normalization, crossfade, source
quality), offline storage and auto-synced moods, sign out.
There is no Library tab, no Longform tab and no global shuffle.
## Project layout
@@ -46,9 +98,9 @@ The shared module contains the API client, session/cache storage, radio queue, a
composeApp/
|-- src/commonMain/kotlin/win/taptap/musicmanager/client/
| |-- api/ # Ktor client and DTOs mirroring /api/v1
| |-- data/ # AppStorage, LibraryCache, session persistence
| |-- data/ # AppStorage, AppCache, session persistence
| |-- playback/ # AudioPlayer abstraction
| |-- store/ # AppStore: state, radio queue, downloads, editing
| |-- store/ # AppStore: state, search, radio queue, downloads
| `-- ui/ # Compose screens and theme
|-- src/androidMain/ # Activity, Media3 player, filesystem storage
|-- src/desktopMain/ # Main window, MP3SPI player, filesystem storage
@@ -60,15 +112,18 @@ composeApp/
## Build
Requirements: JDK 21, Android SDK 36 for the app target, Node (Kotlin downloads its own for web).
Requirements: JDK 21, Android SDK 36 for the app target, Node (Kotlin downloads
its own for web).
With Nix, everything is provided by `shell.nix` (JDK 21, Gradle 8, Node 22, Android SDK 36 with build-tools 36.0.0, and the desktop runtime libraries):
With Nix, everything is provided by `shell.nix` (JDK 21, Gradle 8, Node 22,
Android SDK 36 with build-tools 36.0.0, and the desktop runtime libraries):
```bash
nix-shell
```
The shell accepts the unfree Android SDK license for you; see the comment at the top of `shell.nix`. Without Nix, point `ANDROID_HOME` at an SDK containing platform 36 and build-tools 36.0.0.
Without Nix, point `ANDROID_HOME` at an SDK containing platform 36 and
build-tools 36.0.0.
```bash
export ANDROID_HOME=/opt/android-sdk
@@ -86,14 +141,17 @@ gradle :composeApp:run
# Desktop fat jar
gradle :composeApp:packageUberJarForCurrentOS
# Web bundle
# Web bundle (local only, not built by CI)
gradle :composeApp:wasmJsBrowserDistribution
# composeApp/build/dist/wasmJs/productionExecutable
```
Serve the web bundle from any static host (for example `python3 -m http.server` inside the production directory). The server allows cross-origin API calls; enter its URL on the login screen. When the bundle is hosted on the same origin as the server, the URL is prefilled.
Serve the web bundle from any static host (for example `python3 -m http.server`
inside the production directory). The server allows cross-origin API calls;
enter its URL on the login screen.
Android cleartext HTTP is enabled for local development. Use HTTPS in production.
Android cleartext HTTP is enabled for local development. Use HTTPS in
production.
## Publishing to Google Play (internal testing)
@@ -130,27 +188,17 @@ scripts/build-release-aab.sh <versionCode> <versionName>
# composeApp/build/outputs/bundle/release/composeApp-release.aab
```
The script verifies the signature and prints the SHA-256. Bump `versionCode` for
every upload; `VERSION_CODE`/`VERSION_NAME` can also be set in the environment.
The script verifies the signature and prints the SHA-256.
### 3. Upload
In Play Console: **Testing → Internal testing → Create new release → App
integrity → Google-generated key**, upload the AAB, add release notes, then
**Save → Roll out**. The first upload enrolls the app in Play App Signing. Share
the opt-in link from the Testers tab with your test list.
**Save → Roll out**.
### 4. Automated uploads
Tagged builds (`v*`) publish to internal testing from CI. One-time setup:
1. In Google Cloud, enable the **Google Play Android Developer API**.
2. Create a service account and download a JSON key.
3. In Play Console → **Users and permissions → Invite new user**, add the
service account's `client_email`, give it access to this app with
**Release to testing tracks** and **View app information** (do not grant
production or admin access).
4. Add these repository secrets in Gitea:
Tagged builds (`v*`) publish to internal testing from CI. The Gitea secrets are:
| Secret | Value |
| --- | --- |
@@ -160,32 +208,33 @@ Tagged builds (`v*`) publish to internal testing from CI. One-time setup:
| `ANDROID_KEY_PASSWORD` | key password |
| `PLAY_SERVICE_ACCOUNT_JSON` | contents of the service account JSON |
Then `git tag v0.2.0 && git push --tags` builds, signs and uploads the bundle.
Then `git tag v0.4.0 && git push --tags` builds, signs and uploads the bundle.
Gradle Play Publisher asks Play for the next free `versionCode`
(`ResolutionStrategy.AUTO`), so only the tag/version name needs to change.
Local equivalent (takes the JSON from an environment variable, never a file in
the repo):
```bash
ANDROID_PUBLISHER_CREDENTIALS="$(cat ~/play-service-account.json)" \
ANDROID_HOME=/opt/android-sdk gradle :composeApp:publishBundle
```
## App state and offline behaviour
`AppStore` is a plain Kotlin class with a `StateFlow<AppState>`; Compose observes it. It owns:
`AppStore` is a plain Kotlin class with a `StateFlow<AppState>`; Compose observes
it. It owns:
- **Auth** — restore the saved token on launch and log out.
- **Library sync** — first launch pages through `/library/songs`; later launches use the `since` delta and tombstones. Songs are split into music and longform using the folders assigned at login, so the two never mix client-side.
- **Mood cache** — mood details are stored so the app can open them offline.
- **Radio** — one session per mood, batches of 12, prefetch when the queue is short, no repeats within a session.
- **Downloads** — stored under the platform app directory, keyed by deterministic song ID.
- **Playback snapshot** — the session, upcoming queue, current track and play history are persisted on every queue change and restored on the next launch.
- **Longform progress** — position is saved locally and to `/longform/progress` while playing, on pause and on track changes; the resume list is fed from the server when online.
- **Offline retry** — a background loop retries the library sync until the server responds again.
- **Mood sync** — GET `/moods` on login/refresh; details are fetched when a mood
is opened and cached.
- **Mood cache** — cached details power offline mood lists and downloads.
- **Search** — debounced remote catalog search with the selected target mood and
its source.
- **Radio** — one session per mood, batches of 12, prefetch when the queue is
short, no repeats within a session.
- **Downloads** — stored under the platform app directory, keyed by the shared
song id.
- **Playback snapshot** — the session, upcoming queue, current track, history and
position are persisted and restored on the next launch.
- **Offline retry** — a background loop retries the mood sync until the server
responds again.
On startup the app is usable before the network call completes: cached moods and library render immediately, then refresh in the background.
On startup the app is usable before the network call completes: cached moods
render immediately, then refresh in the background. Offline playback uses the
mood's cached songs filtered by downloaded files.
## Radio and add-to-mood
@@ -200,14 +249,20 @@ open mood ──► POST /moods/{id}/sessions ──► queue (12 tracks)
└─ moodId: chosen mood
```
Adding a song makes it a permanent seed, so it is always eligible in future radio and visible in the mood editor.
Adding a song makes it permanent in the mood, so it is always eligible in future
radio and visible in the song list.
## CI and releases
`.gitea/workflows/ci.yaml` runs on Gitea Actions using `gitea.tap-tap.win/taptap/audiomanager-client-ci:3`. The image has the Android SDK, Node, Yarn and a warmed Gradle dependency cache, so jobs do not download them on every run.
`.gitea/workflows/ci.yaml` runs on Gitea Actions using
`gitea.tap-tap.win/taptap/audiomanager-client-ci:3`. The image has the Android
SDK, Node, Yarn and a warmed Gradle dependency cache.
- **main / PR:** run `desktopTest`, build the Android APK and the *development* Wasm bundle. The optimized Wasm build is CPU-bound and reserved for releases.
- **`v*` tag:** additionally build the desktop fat jar and the optimized Wasm bundle, then attach all three to the Gitea release.
- **main / PR:** run `desktopTest` and build the Android APK.
- **`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:
@@ -215,14 +270,25 @@ Rebuild the CI image after changing `ci/Dockerfile` or dependency versions:
scripts/build-ci-image.sh 3
```
The image build performs one warm-up compile (`kotlinNodeJsSetup`, `kotlinYarnSetup`, `desktopTest`, `assembleDebug`, `compileKotlinWasmJs`) and then removes the sources, keeping only `/root/.gradle`.
## Known limitations
- The media notification exposes play/pause and seeking. Queue actions (skip, add to mood) stay in the app because the mood session and its events belong to the server.
- Desktop playback supports seeking by reopening the decoder at the requested position (server `timeOffset` for remote streams, PCM skipping for local files). Longform resume works there too. MP3s are decoded to 16-bit PCM before the line is opened, because Java Sound has no line for the compressed format.
- Web downloads are disabled because the browser owns its storage; the app still streams and caches metadata.
- Accepted recommendations are downloaded by the server into `<music>/AudioManager Imports/<artist>/<title>/`, with the YT thumbnail embedded as cover art, scanned and added as seeds. The per-track folder keeps covers distinct. The server needs outbound network access for this.
- Offline downloads also store the 320 px cover next to the MP3 (`<songId>.jpg`), so the in-app cover and the Android notification artwork survive without the server. Deleting a download removes both files.
- YT Music discovery and automatic downloads run server-side through `yt-dlp`. Accepted tracks that are not in the library are imported into `AudioManager Imports` with embedded cover art and promoted to seeds.
- The media notification exposes play/pause, skip and back from the timeline.
Adding to a mood stays in the app because the session and its events belong to
the server. The queue lives in the Android media service, but the *next batch*
still comes from the app process; if the process is killed, the known queue
keeps working but nothing more is fetched.
- Desktop playback supports seeking by reopening the decoder at the requested
position. MP3s are decoded to 16-bit PCM before the line is opened, because
Java Sound has no line for the compressed format.
- Web downloads are disabled because the browser owns its storage; the app still
streams and caches metadata.
- Downloads store the 320 px cover next to the MP3 (`<songId>.jpg`), so the
in-app cover and the Android notification artwork survive without the server.
- Search and downloads depend on the server's catalogs. YouTube bot checks can
fail a YouTube Music search (`502`) or leave a recommendation in `failed`
with Retry. Music search resolves every result for its artist/album/duration,
so a YouTube Music search takes roughly 10–15 seconds for ten results;
Deezer search is much faster.
- Deezer downloads need `DEEZER_ARL` on the server. A Free ARL is limited to
128 kbps; Premium enables 320 kbps. The client never stores the ARL.
- No iOS target yet. The shared module is ready for one.
+4 -9
View File
@@ -43,21 +43,16 @@ RUN mkdir -p "$ANDROID_HOME/cmdline-tools" \
"build-tools;36.0.0" \
&& rm -rf "$ANDROID_HOME/.temp" "$ANDROID_HOME/.downloadIntermediates"
# Warm the Gradle dependency cache and the Kotlin/Wasm (node, yarn, binaryen)
# toolchain so CI jobs do not download them on every run. Rebuild this image
# when dependencies change.
# Warm the Gradle dependency cache and the common/Android/desktop compilers so
# CI jobs do not download them on every run. The Wasm toolchain is intentionally
# not warmed: Wasm is not part of the pipeline. Rebuild this image when
# dependencies change.
COPY . /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 \
&& gradle --no-daemon --max-workers=2 \
:kotlinNodeJsSetup \
:kotlinYarnSetup \
:composeApp:desktopTest \
:composeApp:assembleDebug \
:composeApp:compileKotlinWasmJs \
--console=plain \
&& 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 appVersionName = System.getenv("VERSION_NAME")
?: localProperties.getProperty("VERSION_NAME")
?: "0.1.0"
?: "0.4.0"
kotlin {
androidTarget {
@@ -2,6 +2,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
@@ -0,0 +1,105 @@
package win.taptap.musicmanager.client
import android.content.Context
import androidx.media3.common.C
import androidx.media3.common.audio.AudioProcessor
import androidx.media3.common.audio.AudioProcessor.AudioFormat
import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.DefaultRenderersFactory
import androidx.media3.exoplayer.audio.AudioSink
import androidx.media3.exoplayer.audio.DefaultAudioSink
import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlin.math.pow
/**
* Applies the server's per-track loudness gain to 16-bit PCM.
*
* ExoPlayer's own volume is limited to 0..1, so it can only attenuate. Measuring
* tracks against -16 LUFS needs small positive gains on quiet recordings too;
* scaling the PCM samples supports both directions while leaving the hardware
* volume untouched.
*/
@UnstableApi
class GainAudioProcessor : AudioProcessor {
@Volatile
var gain: Float = 1f
private var inputFormat: AudioFormat = AudioFormat.NOT_SET
private var outputFormat: AudioFormat = AudioFormat.NOT_SET
private var buffer: ByteBuffer = AudioProcessor.EMPTY_BUFFER
private var endOfStream = false
override fun configure(inputAudioFormat: AudioFormat): AudioFormat {
if (inputAudioFormat.encoding != C.ENCODING_PCM_16BIT) {
// Float output or compressed passthrough: leave the samples alone.
inputFormat = AudioFormat.NOT_SET
outputFormat = AudioFormat.NOT_SET
return AudioFormat.NOT_SET
}
inputFormat = inputAudioFormat
outputFormat = inputAudioFormat
return outputFormat
}
override fun isActive(): Boolean = inputFormat != AudioFormat.NOT_SET
override fun queueInput(inputBuffer: ByteBuffer) {
val value = gain
val output = ByteBuffer.allocateDirect(inputBuffer.remaining())
.order(ByteOrder.nativeOrder())
while (inputBuffer.remaining() >= 2) {
val sample = inputBuffer.short.toInt()
val scaled = (sample * value).toInt()
.coerceIn(Short.MIN_VALUE.toInt(), Short.MAX_VALUE.toInt())
output.putShort(scaled.toShort())
}
output.flip()
buffer = output
}
override fun queueEndOfStream() {
endOfStream = true
}
override fun getOutput(): ByteBuffer = buffer
override fun isEnded(): Boolean = endOfStream && !buffer.hasRemaining()
override fun flush() {
buffer = AudioProcessor.EMPTY_BUFFER
endOfStream = false
}
override fun reset() {
buffer = AudioProcessor.EMPTY_BUFFER
endOfStream = false
inputFormat = AudioFormat.NOT_SET
outputFormat = AudioFormat.NOT_SET
}
companion object {
fun fromDb(db: Double): Float =
10.0.pow(db / 20.0).toFloat().coerceIn(0f, 4f)
}
}
/** Wires the gain processor into ExoPlayer's audio sink. */
@UnstableApi
class GainRenderersFactory(
context: Context,
private val gainProcessor: GainAudioProcessor,
) : DefaultRenderersFactory(context) {
override fun buildAudioSink(
context: Context,
enableFloatOutput: Boolean,
enableAudioTrackPlaybackParams: Boolean,
): AudioSink = DefaultAudioSink.Builder(context)
.setAudioProcessors(arrayOf(gainProcessor))
// The processor works on 16-bit PCM; forcing float output would bypass it.
.setEnableFloatOutput(false)
.setEnableAudioTrackPlaybackParams(enableAudioTrackPlaybackParams)
.build()
}
@@ -10,8 +10,8 @@ import androidx.media3.common.MediaMetadata
import androidx.media3.common.Player
import androidx.media3.session.MediaController
import androidx.media3.session.SessionToken
import win.taptap.musicmanager.client.api.Song
import win.taptap.musicmanager.client.playback.AudioPlayer
import win.taptap.musicmanager.client.playback.PlaybackTrack
/**
* Client side of [PlaybackService]. The controller is created asynchronously;
@@ -55,42 +55,55 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
)
}
override fun play(
source: String,
song: Song,
local: Boolean,
artworkUri: String?,
artworkBytes: ByteArray?,
) {
override fun setQueue(tracks: List<PlaybackTrack>, startIndex: Int, startAtSeconds: Double) {
if (tracks.isEmpty()) return
finished = false
withController { controller ->
val uri = if (local) Uri.fromFile(java.io.File(source)) else Uri.parse(source)
val metadata = MediaMetadata.Builder()
.setTitle(song.title)
.setArtist(song.artist)
.setAlbumTitle(song.album)
.apply {
if (artworkBytes != null && artworkBytes.isNotEmpty()) {
setArtworkData(
artworkBytes,
MediaMetadata.PICTURE_TYPE_FRONT_COVER,
)
} else {
setArtworkUri(artworkUri?.let(Uri::parse))
val items = tracks.map(::mediaItem)
val index = startIndex.coerceIn(tracks.indices)
val positionMs = (startAtSeconds * 1_000).toLong().coerceAtLeast(0L)
withController { current ->
current.setMediaItems(items, index, positionMs)
current.prepare()
current.play()
}
}
.build()
val item = MediaItem.Builder()
.setUri(uri)
.setMimeType("audio/mpeg")
.setMediaMetadata(metadata)
.build()
controller.setMediaItem(item)
controller.prepare()
controller.play()
override fun appendToQueue(tracks: List<PlaybackTrack>) {
if (tracks.isEmpty()) return
val items = tracks.map(::mediaItem)
withController { current -> current.addMediaItems(items) }
}
override fun moveInQueue(fromIndex: Int, toIndex: Int) {
withController { current -> current.moveMediaItem(fromIndex, toIndex) }
}
override fun removeAt(index: Int) {
withController { current -> current.removeMediaItem(index) }
}
override fun playIndex(index: Int, startAtSeconds: Double) {
finished = false
val positionMs = (startAtSeconds * 1_000).toLong().coerceAtLeast(0L)
withController { current ->
if (index in 0 until current.mediaItemCount) {
current.seekTo(index, positionMs)
current.play()
}
}
}
override fun skipToNext() {
withController { current -> current.seekToNextMediaItem() }
}
override fun skipToPrevious(restartAfterSeconds: Double) {
withController { current -> current.seekToPreviousMediaItem() }
}
override fun currentIndex(): Int = controller?.currentMediaItemIndex ?: 0
override fun queueSize(): Int = controller?.mediaItemCount ?: 0
override fun pause() {
withController { it.pause() }
@@ -126,14 +139,26 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
withController { it.seekTo((seconds * 1000).toLong().coerceAtLeast(0L)) }
}
override val supportsCrossfade: Boolean = true
override fun setCrossfadeSeconds(seconds: Int) {
val args = Bundle().apply { putInt(CROSSFADE_SECONDS, seconds.coerceAtLeast(0)) }
withController { current ->
runCatching { current.sendCustomCommand(CROSSFADE_COMMAND, args) }
}
}
override fun scheduleSleepTimer(seconds: Long?): Boolean {
val args = Bundle().apply { putLong(SLEEP_TIMER_SECONDS, seconds ?: 0L) }
val send: (MediaController) -> Boolean = { current ->
runCatching { current.sendCustomCommand(SLEEP_TIMER_COMMAND, args) }.isSuccess
val send: (MediaController) -> Unit = { current ->
runCatching { current.sendCustomCommand(SLEEP_TIMER_COMMAND, args) }
}
val current = controller
if (current != null && connected) return send(current)
synchronized(pending) { pending.addLast { controller -> send(controller) } }
if (current != null && connected) {
send(current)
return true
}
synchronized(pending) { pending.addLast(send) }
return true
}
@@ -145,13 +170,39 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
synchronized(pending) { pending.clear() }
}
private fun mediaItem(track: PlaybackTrack): MediaItem {
val uri = if (track.local) {
Uri.fromFile(java.io.File(track.source))
} else {
Uri.parse(track.source)
}
val metadata = MediaMetadata.Builder()
.setTitle(track.song.title)
.setArtist(track.song.artist)
.setAlbumTitle(track.song.album)
.setExtras(
Bundle().apply { putDouble(GAIN_DB_KEY, track.gainDb ?: 0.0) },
)
.apply {
if (!track.artworkUri.isNullOrBlank()) {
setArtworkUri(Uri.parse(track.artworkUri))
}
}
.build()
return MediaItem.Builder()
.setUri(uri)
.setMimeType("audio/mpeg")
.setMediaMetadata(metadata)
.build()
}
private fun withController(block: (MediaController) -> Unit) {
val current = controller
if (current != null && connected) {
block(current)
} else {
// The first playback request can be followed immediately by a seek
// (long-form resume). Keep every action, not only the last one.
// The first playback request can be followed immediately by a seek.
// Keep every action, not only the last one.
synchronized(pending) { pending.addLast(block) }
}
}
@@ -2,6 +2,8 @@ package win.taptap.musicmanager.client
import android.content.Context
import android.graphics.BitmapFactory
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import io.ktor.client.engine.HttpClientEngine
@@ -21,6 +23,15 @@ actual fun platformStorage(): AppStorage = AndroidStorage(AndroidContextHolder.c
actual fun createAudioPlayer(): AudioPlayer = MediaControllerAudioPlayer(AndroidContextHolder.context)
actual fun isUnmeteredNetwork(): Boolean {
val manager = AndroidContextHolder.context
.getSystemService(ConnectivityManager::class.java) ?: return true
val network = manager.activeNetwork ?: return false
val capabilities = manager.getNetworkCapabilities(network) ?: return false
return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
}
class AndroidStorage(context: Context) : AppStorage {
private val root = File(context.filesDir, "audiomanager").apply { mkdirs() }
@@ -7,6 +7,9 @@ import android.os.Handler
import android.os.Looper
import androidx.media3.common.AudioAttributes
import androidx.media3.common.C
import androidx.media3.common.ForwardingPlayer
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.session.MediaSession
import androidx.media3.session.MediaSessionService
@@ -20,12 +23,22 @@ internal const val SLEEP_TIMER_ACTION = "win.taptap.musicmanager.client.SLEEP_TI
internal const val SLEEP_TIMER_SECONDS = "seconds"
internal val SLEEP_TIMER_COMMAND = SessionCommand(SLEEP_TIMER_ACTION, Bundle.EMPTY)
/** Custom session command that sets the crossfade/fade length. */
internal const val CROSSFADE_ACTION = "win.taptap.musicmanager.client.CROSSFADE"
internal const val CROSSFADE_SECONDS = "seconds"
internal val CROSSFADE_COMMAND = SessionCommand(CROSSFADE_ACTION, Bundle.EMPTY)
/** MediaItem metadata key carrying the server-measured gain in dB. */
internal const val GAIN_DB_KEY = "gainDb"
/**
* Hosts playback in a foreground service so audio continues when the activity
* is backgrounded, the screen is off, or the task is swiped away.
*
* Media3 publishes the media notification and exposes the session to lock-screen
* controls, Bluetooth/headset buttons and Android Auto.
* The queue lives here as a Media3 timeline. That lets the notification,
* headset buttons and Android Auto advance tracks even when the UI process is
* gone, and makes gapless playback possible because ExoPlayer prepares the next
* item ahead of time.
*/
class PlaybackService : MediaSessionService() {
@@ -33,10 +46,42 @@ class PlaybackService : MediaSessionService() {
private val handler = Handler(Looper.getMainLooper())
private val sleepTimer = Runnable { mediaSession?.player?.pause() }
@Volatile private var crossfadeSeconds = 0
@Volatile private var fade = 1f
private val gainProcessor = GainAudioProcessor()
private var player: ExoPlayer? = null
private val fadeLoop = object : Runnable {
override fun run() {
val exo = player ?: return
if (!exo.isPlaying) {
handler.postDelayed(this, FADE_TICK_MS)
return
}
val fadeMs = crossfadeSeconds * 1_000L
if (fadeMs > 0) {
val position = exo.currentPosition.coerceAtLeast(0L)
val duration = exo.duration
val fadeOut = if (duration > 0) {
((duration - position).toFloat() / fadeMs).coerceIn(0f, 1f)
} else {
1f
}
val fadeIn = (position.toFloat() / fadeMs).coerceIn(0f, 1f)
fade = minOf(fadeOut, fadeIn)
} else {
fade = 1f
}
exo.volume = fade.coerceIn(0f, 1f)
handler.postDelayed(this, FADE_TICK_MS)
}
}
override fun onCreate() {
super.onCreate()
val player = ExoPlayer.Builder(this)
val exoPlayer = ExoPlayer.Builder(this)
.setRenderersFactory(GainRenderersFactory(this, gainProcessor))
.setAudioAttributes(
AudioAttributes.Builder()
.setUsage(C.USAGE_MEDIA)
@@ -49,6 +94,47 @@ class PlaybackService : MediaSessionService() {
.apply {
setWakeMode(C.WAKE_MODE_NETWORK)
}
player = exoPlayer
// Media3's notification/next/previous map onto the real timeline. The
// only custom rule is Android's usual previous behaviour: after two
// seconds of playback it restarts the current item.
val sessionPlayer = object : ForwardingPlayer(exoPlayer) {
override fun seekToPrevious() {
if (exoPlayer.currentPosition > PREVIOUS_RESTART_MS) {
exoPlayer.seekTo(0)
} else if (exoPlayer.hasPreviousMediaItem()) {
exoPlayer.seekToPreviousMediaItem()
} else {
exoPlayer.seekTo(0)
}
}
override fun seekToPreviousMediaItem() {
if (exoPlayer.currentPosition > PREVIOUS_RESTART_MS) {
exoPlayer.seekTo(0)
} else if (exoPlayer.hasPreviousMediaItem()) {
exoPlayer.seekToPreviousMediaItem()
} else {
exoPlayer.seekTo(0)
}
}
}
exoPlayer.addListener(
object : Player.Listener {
override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
gainProcessor.gain = gainOf(mediaItem)
fade = if (crossfadeSeconds > 0) 0f else 1f
exoPlayer.volume = fade.coerceIn(0f, 1f)
}
override fun onIsPlayingChanged(isPlaying: Boolean) {
handler.removeCallbacks(fadeLoop)
if (isPlaying) handler.post(fadeLoop)
}
},
)
val sessionActivity = PendingIntent.getActivity(
this,
@@ -57,7 +143,7 @@ class PlaybackService : MediaSessionService() {
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
mediaSession = MediaSession.Builder(this, player)
mediaSession = MediaSession.Builder(this, sessionPlayer)
.setSessionActivity(sessionActivity)
.setCallback(object : MediaSession.Callback {
override fun onConnect(
@@ -67,6 +153,7 @@ class PlaybackService : MediaSessionService() {
val commands = MediaSession.ConnectionResult.DEFAULT_SESSION_AND_LIBRARY_COMMANDS
.buildUpon()
.add(SLEEP_TIMER_COMMAND)
.add(CROSSFADE_COMMAND)
.build()
return MediaSession.ConnectionResult.AcceptedResultBuilder(session)
.setAvailableSessionCommands(commands)
@@ -79,20 +166,36 @@ class PlaybackService : MediaSessionService() {
customCommand: SessionCommand,
args: Bundle,
): ListenableFuture<SessionResult> {
if (customCommand.customAction != SLEEP_TIMER_ACTION) {
return super.onCustomCommand(session, controller, customCommand, args)
}
when (customCommand.customAction) {
SLEEP_TIMER_ACTION -> {
handler.removeCallbacks(sleepTimer)
val seconds = args.getLong(SLEEP_TIMER_SECONDS, 0L)
if (seconds > 0) {
handler.postDelayed(sleepTimer, seconds * 1_000)
}
}
CROSSFADE_ACTION -> {
crossfadeSeconds = args.getInt(CROSSFADE_SECONDS, 0).coerceAtLeast(0)
fade = if (crossfadeSeconds > 0) 0f else 1f
exoPlayer.volume = fade.coerceIn(0f, 1f)
handler.removeCallbacks(fadeLoop)
if (exoPlayer.isPlaying) handler.post(fadeLoop)
}
else -> return super.onCustomCommand(session, controller, customCommand, args)
}
return Futures.immediateFuture(SessionResult(SessionResult.RESULT_SUCCESS))
}
})
.build()
}
private fun gainOf(item: MediaItem?): Float {
val db = item?.mediaMetadata?.extras?.getDouble(GAIN_DB_KEY, 0.0) ?: 0.0
return GainAudioProcessor.fromDb(db)
}
override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession? =
mediaSession
@@ -105,11 +208,18 @@ class PlaybackService : MediaSessionService() {
override fun onDestroy() {
handler.removeCallbacks(sleepTimer)
handler.removeCallbacks(fadeLoop)
mediaSession?.run {
player.release()
release()
}
mediaSession = null
player = null
super.onDestroy()
}
private companion object {
const val PREVIOUS_RESTART_MS = 2_000L
const val FADE_TICK_MS = 100L
}
}
@@ -16,3 +16,9 @@ expect fun platformStorage(): AppStorage
expect fun createAudioPlayer(): AudioPlayer
expect fun decodeImage(bytes: ByteArray): ImageBitmap?
/**
* True when bulk downloads may run. Android checks for an unmetered network;
* desktop and web have no metered flag and return true.
*/
expect fun isUnmeteredNetwork(): Boolean
@@ -12,7 +12,6 @@ import io.ktor.client.request.get
import io.ktor.client.request.header
import io.ktor.client.request.patch
import io.ktor.client.request.post
import io.ktor.client.request.put
import io.ktor.client.request.setBody
import io.ktor.client.statement.HttpResponse
import io.ktor.client.statement.bodyAsBytes
@@ -44,7 +43,6 @@ fun configuredHttpClient(engine: HttpClientEngine): HttpClient = HttpClient(engi
}
}
/**
* Native API client. Media URLs carry the token in the query string because
* Android's Media3, desktop playback and HTML audio all fetch them directly.
@@ -124,17 +122,30 @@ class ApiClient(private val http: HttpClient) {
requestNoContent { http.delete(url("/moods/$id")) { auth() } }
}
suspend fun addSeed(moodId: String, songId: String): AddToMoodResponse =
suspend fun addSong(
moodId: String,
songId: String? = null,
source: String? = null,
externalId: String? = null,
url: String? = null,
): AddSongResponse =
parse(
http.post(url("/moods/$moodId/seeds")) {
http.post(url("/moods/$moodId/songs")) {
auth()
contentType(ContentType.Application.Json)
setBody(AddSeedRequest(songId))
setBody(
AddSongRequest(
songId = songId,
source = source,
externalId = externalId,
url = url,
),
)
},
)
suspend fun removeSeed(moodId: String, songId: String) {
requestNoContent { http.delete(url("/moods/$moodId/seeds/$songId")) { auth() } }
suspend fun removeSong(moodId: String, songId: String) {
requestNoContent { http.delete(url("/moods/$moodId/songs/$songId")) { auth() } }
}
suspend fun recommendations(moodId: String): List<Recommendation> =
@@ -152,42 +163,48 @@ class ApiClient(private val http: HttpClient) {
},
)
suspend fun acceptRecommendation(moodId: String, videoId: String): RecommendationDecision =
suspend fun addRecommendation(moodId: String, externalId: String): RecommendationDecision =
parse(
http.post(url("/moods/$moodId/recommendations/$videoId/accept")) {
http.post(url("/moods/$moodId/recommendations/$externalId/add")) {
auth()
},
)
suspend fun rejectRecommendation(moodId: String, videoId: String): RecommendationDecision =
suspend fun rejectRecommendation(moodId: String, externalId: String): RecommendationDecision =
parse(
http.post(url("/moods/$moodId/recommendations/$videoId/reject")) {
http.post(url("/moods/$moodId/recommendations/$externalId/reject")) {
auth()
},
)
suspend fun preview(moodId: String, limit: Int = 20): List<Song> =
get<SearchResponse>("/moods/$moodId/preview?limit=$limit").songs
suspend fun retryRecommendation(moodId: String, externalId: String): MoodDetail =
parse(
http.post(url("/moods/$moodId/recommendations/$externalId/retry")) {
auth()
},
)
suspend fun search(query: String, limit: Int = 50, scope: String = "music"): List<Song> =
get<SearchResponse>(
"/library/search?q=${query.encodeURLParameter()}&limit=$limit&scope=$scope",
).songs
suspend fun info(): ServerInfo = get("/info")
suspend fun library(
cursor: String? = null,
since: String? = null,
limit: Int = 500,
scope: String = "all",
revision: String? = null,
): LibraryPage {
val query = buildString {
append("?limit=$limit&scope=$scope")
cursor?.let { append("&cursor=${it.encodeURLParameter()}") }
since?.let { append("&since=${it.encodeURLParameter()}") }
revision?.let { append("&revision=${it.encodeURLParameter()}") }
suspend fun search(
query: String,
limit: Int = 10,
source: String? = null,
moodId: String? = null,
): List<SearchResult> {
val sourceParam = source?.let { "&source=${it.encodeURLParameter()}" }.orEmpty()
val mood = moodId?.let { "&moodId=${it.encodeURLParameter()}" }.orEmpty()
return parse<SearchResponse>(
http.get(url("/search?q=${query.encodeURLParameter()}&limit=$limit$sourceParam$mood")) {
auth()
// yt-dlp resolves every YouTube Music hit to get artist, album
// and duration, so a search takes longer than a plain API call.
timeout {
requestTimeoutMillis = 60_000
socketTimeoutMillis = 60_000
}
return get("/library/songs$query")
},
).results
}
suspend fun startSession(moodId: String, limit: Int = 12): Session =
@@ -232,40 +249,14 @@ class ApiClient(private val http: HttpClient) {
runCatching { requestNoContent { http.delete(url("/sessions/$id")) { auth() } } }
}
suspend fun longformProgress(): List<LongformProgressItem> =
get<LongformProgressResponse>("/longform/progress").items
suspend fun saveLongformProgress(
songId: String,
positionSeconds: Int,
durationSeconds: Int,
completed: Boolean,
) {
val response = http.put(url("/longform/progress/$songId")) {
auth()
contentType(ContentType.Application.Json)
setBody(SaveLongformProgressRequest(positionSeconds, durationSeconds, completed))
}
if (!response.status.isSuccess()) throw error(response)
}
suspend fun devices(): List<Device> = get("/auth/devices")
suspend fun scanStatus(): ScanStatus = get("/scan")
suspend fun startScan(): ScanStatus =
parse(
http.post(url("/scan")) {
auth()
},
)
suspend fun cover(albumId: String, size: Int = 320): ByteArray? {
val key = "$albumId:$size"
suspend fun cover(songId: String, size: Int = 320): ByteArray? {
val key = "$songId:$size"
if (coverCache.containsKey(key)) return coverCache[key]
val result = runCatching {
val response = http.get(
"$baseUrl/api/v1/covers/$albumId?size=$size&token=${token.orEmpty().encodeURLParameter()}",
"$baseUrl/api/v1/songs/$songId/cover?size=$size&token=${token.orEmpty().encodeURLParameter()}",
)
if (response.status.isSuccess()) {
response.bodyAsBytes().takeIf { it.isNotEmpty() }
@@ -274,8 +265,7 @@ class ApiClient(private val http: HttpClient) {
}
}.getOrNull()
if (coverCache.size > MAX_CACHED_IMAGES) coverCache.clear()
// Do not cache failures: a cover can appear after the scanner indexes a
// newly downloaded track, and the UI should pick it up without a restart.
// Do not cache failures: a cover can appear after a download finishes.
if (result != null) coverCache[key] = result
return result
}
@@ -319,8 +309,6 @@ class ApiClient(private val http: HttpClient) {
val response = http.get("$baseUrl/api/v1/songs/$songId/stream") {
auth()
url.parameters.append("download", "true")
// A long audiobook must not be cancelled by the default 30s total
// request timeout.
timeout {
requestTimeoutMillis = 6 * 60 * 60 * 1000
socketTimeoutMillis = 60_000
@@ -333,8 +321,8 @@ class ApiClient(private val http: HttpClient) {
fun streamUrl(songId: String): String =
"$baseUrl/api/v1/songs/$songId/stream?token=${token.orEmpty().encodeURLParameter()}"
fun coverUrl(albumId: String, size: Int = 320): String =
"$baseUrl/api/v1/covers/$albumId?size=$size&token=${token.orEmpty().encodeURLParameter()}"
fun coverUrl(songId: String, size: Int = 320): String =
"$baseUrl/api/v1/songs/$songId/cover?size=$size&token=${token.orEmpty().encodeURLParameter()}"
private suspend inline fun <reified T> get(path: String): T =
parse(http.get(url(path)) { auth() })
@@ -23,8 +23,6 @@ data class LoginRequest(
data class User(
val name: String,
val admin: Boolean,
val musicFolders: List<Int> = emptyList(),
val longformFolders: List<Int> = emptyList(),
)
@Serializable
@@ -37,21 +35,29 @@ data class LoginResponse(
@Serializable
data class Song(
val id: String,
val source: String = "youtube",
val externalId: String,
val title: String,
val artist: String,
val album: String,
val albumId: String,
val trackNumber: Int? = null,
val discNumber: Int = 1,
val year: Int? = null,
val album: String? = null,
val duration: Int,
val bitRate: Int,
val size: Long,
val suffix: String,
val genres: List<String> = emptyList(),
val folderId: Int,
val relativePath: String,
val updatedAt: String,
val bitRate: Int = 0,
val size: Long = 0,
val suffix: String = "mp3",
val thumbnail: String? = null,
/** Server-measured loudness and the gain to apply; null when not analyzed. */
val loudnessLufs: Double? = null,
val gainDb: Double? = null,
) {
val subtitle: String get() = album?.takeIf { it.isNotBlank() } ?: artist
}
@Serializable
data class ServerInfo(
val defaultSource: String = "deezer",
val deezerQuality: Int = 0,
val loudnessEnabled: Boolean = false,
val loudnessTargetLufs: Double = -16.0,
)
@Serializable
@@ -61,21 +67,23 @@ data class Mood(
val description: String? = null,
val query: String? = null,
val genres: List<String> = emptyList(),
val targetSize: Int,
val seedPercent: Int = 50,
val source: String = "youtube",
val collectionPercent: Int = 50,
val recommendationPercent: Int = 50,
val refreshHours: Int,
val ytEnabled: Boolean,
val recommendationCount: Int = 10,
val refreshHours: Int = 24,
val lastDiscoveryAt: String? = null,
val createdAt: String,
val changedAt: String,
val lastError: String? = null,
val seedCount: Int,
val newRecommendations: Int = 0,
val songCount: Int = 0,
val recommendationReady: Int = 0,
val recommendationDownloading: Int = 0,
val recommendationFailed: Int = 0,
)
@Serializable
data class Seed(
data class MoodSong(
val song: Song,
val origin: String,
val addedAt: String,
@@ -86,62 +94,49 @@ data class Download(
val state: String,
val attempts: Int = 0,
val error: String? = null,
val updatedAt: String,
val updatedAt: String = "",
)
@Serializable
data class Recommendation(
val videoId: String,
val source: String = "youtube",
val externalId: String,
val title: String,
val artist: String,
val album: String? = null,
val duration: Int? = null,
val thumbnail: String? = null,
val state: String,
val matchedSong: Song? = null,
val timesAdded: Int = 0,
val firstSeen: String,
val lastSeen: String,
val song: Song? = null,
val download: Download? = null,
)
@Serializable
data class LongformProgressItem(
val song: Song,
val positionSeconds: Int,
val durationSeconds: Int,
val completed: Boolean,
val updatedAt: String,
)
@Serializable
data class LongformProgressResponse(val items: List<LongformProgressItem> = emptyList())
@Serializable
data class SaveLongformProgressRequest(
val positionSeconds: Int,
val durationSeconds: Int? = null,
val completed: Boolean = false,
)
@Serializable
data class LongformProgress(
val songId: String,
val positionSeconds: Int,
val durationSeconds: Int,
val completed: Boolean,
val updatedAt: String,
val error: String? = null,
val firstSeen: String = "",
val lastSeen: String = "",
)
@Serializable
data class MoodDetail(
val mood: Mood,
val seeds: List<Seed> = emptyList(),
val songs: List<MoodSong> = emptyList(),
val recommendations: List<Recommendation> = emptyList(),
val downloads: List<DownloadStatus> = emptyList(),
)
/** Server-side download state for one track, keyed by source and external id. */
@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
data class RecommendationsResponse(val recommendations: List<Recommendation> = emptyList())
@@ -150,20 +145,24 @@ data class RecommendationsResponse(val recommendations: List<Recommendation> = e
data class RecommendationDecision(
val detail: MoodDetail,
val recommendation: Recommendation,
val seedAdded: Boolean = false,
)
@Serializable
data class LibraryPage(
val songs: List<Song> = emptyList(),
val deletedSongIds: List<String> = emptyList(),
val revision: String,
val nextCursor: String? = null,
val nextSince: String? = null,
data class SearchResult(
val source: String = "youtube",
val externalId: String,
val title: String,
val artist: String,
val album: String? = null,
val duration: Int? = null,
val thumbnail: String? = null,
val songId: String? = null,
val downloaded: Boolean = false,
val inMood: Boolean = false,
)
@Serializable
data class SearchResponse(val songs: List<Song> = emptyList())
data class SearchResponse(val results: List<SearchResult> = emptyList())
@Serializable
data class Session(
@@ -206,8 +205,21 @@ data class AddToMoodRequest(val songId: String, val moodId: String? = null)
@Serializable
data class AddToMoodResponse(val mood: Mood, val added: Boolean)
/** Adds an existing song, a search result's video id, or a pasted URL. */
@Serializable
data class AddSeedRequest(val songId: String, val origin: String = "manual")
data class AddSongRequest(
val songId: String? = null,
val source: String? = null,
val externalId: String? = null,
val url: String? = null,
)
@Serializable
data class AddSongResponse(
val detail: MoodDetail,
val added: Boolean = false,
val downloading: Boolean = false,
)
@Serializable
data class CreateMoodRequest(
@@ -215,11 +227,10 @@ data class CreateMoodRequest(
val description: String? = null,
val query: String? = null,
val genres: List<String> = emptyList(),
val targetSize: Int = 30,
val source: String? = null,
val collectionPercent: Int = 50,
val recommendationCount: Int = 10,
val refreshHours: Int = 24,
val ytEnabled: Boolean = true,
val seedSongIds: List<String> = emptyList(),
val seedPercent: Int = 50,
)
@Serializable
@@ -230,10 +241,10 @@ data class UpdateMoodRequest(
val query: String? = null,
val clearQuery: Boolean = false,
val genres: List<String>? = null,
val targetSize: Int? = null,
val source: String? = null,
val collectionPercent: Int? = null,
val recommendationCount: Int? = null,
val refreshHours: Int? = null,
val ytEnabled: Boolean? = null,
val seedPercent: Int? = null,
)
@Serializable
@@ -2,7 +2,6 @@ package win.taptap.musicmanager.client.data
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import win.taptap.musicmanager.client.api.LongformProgress
import win.taptap.musicmanager.client.api.Mood
import win.taptap.musicmanager.client.api.MoodDetail
import win.taptap.musicmanager.client.api.Session
@@ -16,15 +15,31 @@ data class SessionState(
val user: User,
)
/**
* Offline cache. Version 3 adds the download source and the source-neutral
* external track id; older shapes are discarded instead of mis-decoding.
*/
@Serializable
data class CachedState(
val version: Int = CACHE_VERSION,
val serverUrl: String = "",
val userName: String = "",
val revision: String? = null,
val songs: List<Song> = emptyList(),
val longform: List<Song> = emptyList(),
val moods: List<Mood> = emptyList(),
val moodDetails: List<MoodDetail> = emptyList(),
) {
companion object {
const val CACHE_VERSION = 3
}
}
/** Client-only preferences that are not part of the server profile. */
@Serializable
data class ClientSettings(
/** Moods kept downloaded on this device and auto-synced. */
val offlineMoods: Set<String> = emptySet(),
val normalizationEnabled: Boolean = true,
/** 0 = gapless; other values are fade lengths in seconds. */
val crossfadeSeconds: Int = 0,
)
/** The queue survives a restart so the next launch can resume where it stopped. */
@@ -37,7 +52,7 @@ data class PlaybackSnapshot(
val positionSeconds: Double = 0.0,
)
class LibraryCache(private val storage: AppStorage) {
class AppCache(private val storage: AppStorage) {
private val json = Json {
ignoreUnknownKeys = true
@@ -54,15 +69,26 @@ class LibraryCache(private val storage: AppStorage) {
if (session == null) delete(SESSION_FILE) else write(SESSION_FILE, json.encodeToString(session))
}
fun load(): CachedState =
read(CACHE_FILE)?.let {
fun load(): CachedState {
val cached = read(CACHE_FILE)?.let {
runCatching { json.decodeFromString<CachedState>(it) }.getOrNull()
} ?: CachedState()
} ?: return CachedState()
return if (cached.version == CachedState.CACHE_VERSION) cached else CachedState()
}
fun save(state: CachedState) {
write(CACHE_FILE, json.encodeToString(state))
}
fun loadSettings(): ClientSettings =
read(SETTINGS_FILE)?.let {
runCatching { json.decodeFromString<ClientSettings>(it) }.getOrNull()
} ?: ClientSettings()
fun saveSettings(settings: ClientSettings) {
write(SETTINGS_FILE, json.encodeToString(settings))
}
fun loadPlayback(): PlaybackSnapshot? =
read(PLAYBACK_FILE)?.let {
runCatching { json.decodeFromString<PlaybackSnapshot>(it) }.getOrNull()
@@ -76,19 +102,10 @@ class LibraryCache(private val storage: AppStorage) {
}
}
fun loadProgress(): List<LongformProgress> =
read(PROGRESS_FILE)?.let {
runCatching { json.decodeFromString<List<LongformProgress>>(it) }.getOrNull()
} ?: emptyList()
fun saveProgress(progress: List<LongformProgress>) {
write(PROGRESS_FILE, json.encodeToString(progress))
}
fun clear() {
delete(CACHE_FILE)
delete(PLAYBACK_FILE)
delete(PROGRESS_FILE)
delete(SETTINGS_FILE)
}
// Web storage can be blocked (Safari private mode) or full. Cache failure
@@ -103,8 +120,8 @@ class LibraryCache(private val storage: AppStorage) {
private companion object {
const val SESSION_FILE = "session.json"
const val CACHE_FILE = "library.json"
const val CACHE_FILE = "mood-cache.json"
const val PLAYBACK_FILE = "playback.json"
const val PROGRESS_FILE = "longform-progress.json"
const val SETTINGS_FILE = "settings.json"
}
}
@@ -2,20 +2,39 @@ package win.taptap.musicmanager.client.playback
import win.taptap.musicmanager.client.api.Song
/**
* One entry in the playback timeline. The store resolves the stream or local
* file and holds the metadata the service needs for the notification.
*/
data class PlaybackTrack(
val song: Song,
/** HTTP stream URL or a local file path. */
val source: String,
val local: Boolean,
val artworkUri: String? = null,
/** Server-measured gain; null leaves the track untouched. */
val gainDb: Double? = null,
)
/**
* Minimal audio abstraction shared by all targets.
*
* `source` is either an HTTP URL (tokenized stream) or a local file handle. The
* store polls [isFinished] because some backends have no callback support.
* The timeline is owned by the player so Android's media service can keep
* advancing tracks when the UI process is gone. The store mirrors
* [currentIndex] and the song list it last supplied.
*/
interface AudioPlayer {
fun play(
source: String,
song: Song,
local: Boolean,
artworkUri: String? = null,
artworkBytes: ByteArray? = null,
)
/** Replaces the timeline and starts at [startIndex]. */
fun setQueue(tracks: List<PlaybackTrack>, startIndex: Int, startAtSeconds: Double = 0.0)
fun appendToQueue(tracks: List<PlaybackTrack>)
fun moveInQueue(fromIndex: Int, toIndex: Int)
fun removeAt(index: Int)
fun playIndex(index: Int, startAtSeconds: Double = 0.0)
fun skipToNext()
fun skipToPrevious(restartAfterSeconds: Double = 2.0)
fun currentIndex(): Int
fun queueSize(): Int
fun pause()
fun resume()
fun stop()
@@ -25,14 +44,17 @@ interface AudioPlayer {
fun durationSeconds(): Double
val canSeek: Boolean
fun seekTo(seconds: Double)
fun release()
/** Crossfade length in seconds; 0 means gapless. Platforms may ignore it. */
fun setCrossfadeSeconds(seconds: Int) = Unit
val supportsCrossfade: Boolean get() = false
/**
* Pauses playback after [seconds], or cancels a pending timer with null.
* Returns true when the platform scheduled the pause itself, so it still
* fires when the UI is gone (Android background playback). Callers keep
* their own countdown for the UI either way.
* fires when the UI is gone (Android background playback).
*/
fun scheduleSleepTimer(seconds: Long?): Boolean = false
}
fun release()
}
File diff suppressed because it is too large. Load diff
@@ -1,18 +1,17 @@
package win.taptap.musicmanager.client.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ArrowBack
import androidx.compose.material.icons.rounded.Delete
import androidx.compose.material.icons.rounded.LibraryMusic
import androidx.compose.material.icons.rounded.DownloadDone
import androidx.compose.material.icons.rounded.Refresh
import androidx.compose.material.icons.rounded.Search
import androidx.compose.material.icons.rounded.Settings
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
@@ -104,7 +103,6 @@ private fun Splash() {
@Composable
private fun MainScreen(state: AppState, store: AppStore) {
val snackbar = remember { SnackbarHostState() }
var confirmDelete by remember { mutableStateOf(false) }
LaunchedEffect(state.messageId) {
val message = state.message
@@ -115,7 +113,7 @@ private fun MainScreen(state: AppState, store: AppStore) {
}
PlatformBackHandler(enabled = state.screen != Screen.Moods) {
store.openMoods()
store.back()
}
Scaffold(
@@ -128,7 +126,7 @@ private fun MainScreen(state: AppState, store: AppStore) {
),
navigationIcon = {
if (state.screen != Screen.Moods) {
IconButton(onClick = { store.openMoods() }) {
IconButton(onClick = { store.back() }) {
Icon(Icons.Rounded.ArrowBack, contentDescription = "Back")
}
}
@@ -138,8 +136,11 @@ private fun MainScreen(state: AppState, store: AppStore) {
val title = when (state.screen) {
Screen.Moods -> "Moods"
Screen.MoodDetail -> state.selectedMood?.mood?.name ?: "Mood"
Screen.Library -> "Library & downloads"
Screen.MoodSettings -> "Mood settings"
Screen.Search -> "Add music"
Screen.Downloads -> "Downloads"
Screen.Settings -> "Settings"
Screen.NowPlaying -> "Now playing"
}
Text(title, fontWeight = FontWeight.SemiBold)
if (state.offline) {
@@ -157,19 +158,23 @@ private fun MainScreen(state: AppState, store: AppStore) {
IconButton(onClick = { store.refreshAll() }) {
Icon(Icons.Rounded.Refresh, contentDescription = "Refresh")
}
IconButton(onClick = { store.openLibrary() }) {
Icon(Icons.Rounded.LibraryMusic, contentDescription = "Library")
IconButton(onClick = { store.openSearch() }) {
Icon(Icons.Rounded.Search, contentDescription = "Add music")
}
IconButton(onClick = { store.openDownloads() }) {
Icon(Icons.Rounded.DownloadDone, contentDescription = "Downloads")
}
IconButton(onClick = { store.openSettings() }) {
Icon(Icons.Rounded.Settings, contentDescription = "Settings")
}
}
Screen.MoodDetail -> {
IconButton(onClick = { confirmDelete = true }) {
Icon(Icons.Rounded.Delete, contentDescription = "Delete mood")
IconButton(onClick = { store.openMoodSettings() }) {
Icon(Icons.Rounded.Settings, contentDescription = "Mood settings")
}
}
Screen.Library -> {
Screen.MoodSettings, Screen.NowPlaying, Screen.Search -> Unit
Screen.Downloads -> {
IconButton(onClick = { store.openSettings() }) {
Icon(Icons.Rounded.Settings, contentDescription = "Settings")
}
@@ -180,7 +185,7 @@ private fun MainScreen(state: AppState, store: AppStore) {
)
},
bottomBar = {
if (state.current != null) {
if (state.current != null && state.screen != Screen.NowPlaying) {
PlayerBar(state, store)
}
},
@@ -189,29 +194,12 @@ private fun MainScreen(state: AppState, store: AppStore) {
when (state.screen) {
Screen.Moods -> MoodsScreen(state, store)
Screen.MoodDetail -> MoodDetailScreen(state, store)
Screen.Library -> LibraryScreen(state, store)
Screen.MoodSettings -> MoodSettingsScreen(state, store)
Screen.Search -> SearchScreen(state, store)
Screen.Downloads -> DownloadsScreen(state, store)
Screen.Settings -> SettingsScreen(state, store)
Screen.NowPlaying -> NowPlayingScreen(state, store)
}
}
}
if (confirmDelete) {
val name = state.selectedMood?.mood?.name ?: "this mood"
AlertDialog(
onDismissRequest = { confirmDelete = false },
title = { Text("Delete mood?") },
text = { Text("\"$name\" and its seeds will be removed. Downloads stay on this device.") },
confirmButton = {
TextButton(
onClick = {
confirmDelete = false
state.selectedMood?.let { store.deleteMood(it.mood.id) }
},
) { Text("Delete", color = MaterialTheme.colorScheme.error) }
},
dismissButton = {
TextButton(onClick = { confirmDelete = false }) { Text("Cancel") }
},
)
}
}
@@ -50,15 +50,15 @@ import win.taptap.musicmanager.client.store.AppStore
@Composable
fun Cover(
store: AppStore,
albumId: String?,
songId: String?,
modifier: Modifier = Modifier,
size: Int = 320,
) {
var bitmap by remember(albumId, size) { mutableStateOf<ImageBitmap?>(null) }
var bitmap by remember(songId, size) { mutableStateOf<ImageBitmap?>(null) }
LaunchedEffect(albumId, size) {
if (albumId == null) return@LaunchedEffect
val bytes = store.cover(albumId)
LaunchedEffect(songId, size) {
if (songId == null) return@LaunchedEffect
val bytes = store.cover(songId)
bitmap = bytes?.let { data -> runCatching { decodeImage(data) }.getOrNull() }
}
@@ -185,7 +185,7 @@ fun SongRow(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Cover(store, song.albumId, Modifier.size(44.dp), size = 96)
Cover(store, song.id, Modifier.size(44.dp), size = 96)
Column(Modifier.weight(1f)) {
Text(
song.title,
@@ -194,7 +194,7 @@ fun SongRow(
overflow = TextOverflow.Ellipsis,
)
Text(
"${song.artist} · ${song.album}",
"${song.artist} · ${song.album ?: "Single"}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
@@ -277,7 +277,7 @@ fun MoodPickerDialog(
Column(Modifier.weight(1f)) {
Text(mood.name, style = MaterialTheme.typography.bodyLarge)
Text(
if (mood.id == currentMoodId) "Current mood" else "${mood.seedCount} seeds",
if (mood.id == currentMoodId) "Current mood" else "${mood.songCount} songs",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
@@ -0,0 +1,130 @@
package win.taptap.musicmanager.client.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Delete
import androidx.compose.material.icons.rounded.DeleteSweep
import androidx.compose.material.icons.rounded.DownloadDone
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
/** Device-side copies for offline playback. The server keeps the originals. */
@Composable
fun DownloadsScreen(state: AppState, store: AppStore) {
if (state.downloads.isEmpty()) {
EmptyState(
"No downloads",
"Download a song from a mood to play it without the server.",
Modifier.fillMaxSize(),
)
return
}
val songs = state.downloads.mapNotNull { state.knownSongs[it] }
val unknown = state.downloads - songs.map { it.id }.toSet()
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(20.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
item {
Surface(
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.surfaceVariant,
modifier = Modifier.fillMaxWidth(),
) {
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
"${state.downloads.size} downloaded",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
)
Text(
"${formatBytes(store.storageBytes())} used on this device",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
OutlinedButton(onClick = { store.clearDownloads() }) {
Icon(Icons.Rounded.DeleteSweep, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text("Clear all")
}
}
}
}
items(songs, key = { it.id }) { song ->
SongRow(store, song, onPlay = { store.playSong(song) }) {
Icon(
Icons.Rounded.DownloadDone,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(18.dp),
)
IconButton(onClick = { store.toggleDownload(song) }) {
Icon(Icons.Rounded.Delete, contentDescription = "Delete download")
}
}
}
items(unknown.toList(), key = { "unknown-$it" }) { id ->
Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Column(Modifier.weight(1f)) {
Text("Downloaded track", style = MaterialTheme.typography.bodyLarge)
Text(
id,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
IconButton(
onClick = {
store.toggleDownload(
win.taptap.musicmanager.client.api.Song(
id = id,
source = "youtube",
externalId = id,
title = id,
artist = "",
duration = 0,
),
)
},
) {
Icon(Icons.Rounded.Delete, contentDescription = "Delete download")
}
}
}
}
}
@@ -1,496 +0,0 @@
package win.taptap.musicmanager.client.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.CheckCircle
import androidx.compose.material.icons.rounded.DeleteOutline
import androidx.compose.material.icons.rounded.Download
import androidx.compose.material.icons.rounded.List
import androidx.compose.material.icons.rounded.PlayArrow
import androidx.compose.material.icons.rounded.Search
import androidx.compose.material.icons.rounded.Shuffle
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRow
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import win.taptap.musicmanager.client.api.LongformProgress
import win.taptap.musicmanager.client.api.Song
import win.taptap.musicmanager.client.platformName
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
@Composable
fun LibraryScreen(state: AppState, store: AppStore) {
var tab by remember { mutableStateOf(0) }
Column(Modifier.fillMaxSize()) {
TabRow(selectedTabIndex = tab) {
Tab(
selected = tab == 0,
onClick = { tab = 0 },
text = { Text("Music") },
)
Tab(
selected = tab == 1,
onClick = { tab = 1 },
text = { Text("Longform") },
)
}
when (tab) {
0 -> MusicLibrary(state, store)
else -> LongformLibrary(state, store)
}
}
}
@Composable
private fun MusicLibrary(state: AppState, store: AppStore) {
var query by remember { mutableStateOf("") }
val supported = platformName != "web"
val downloadedSongs = state.library.filter { it.id in state.downloads }
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(20.dp),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
item {
OutlinedTextField(
value = query,
onValueChange = {
query = it
store.searchMusic(it)
},
singleLine = true,
label = { Text("Search music") },
leadingIcon = { Icon(Icons.Rounded.Search, contentDescription = null) },
trailingIcon = {
if (state.searching) {
CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp)
}
},
modifier = Modifier.fillMaxWidth(),
)
}
item {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surfaceVariant,
modifier = Modifier.fillMaxWidth(),
) {
Row(
modifier = Modifier.padding(16.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Column(Modifier.weight(1f)) {
Text("All music", style = MaterialTheme.typography.titleMedium)
Text(
if (state.library.isEmpty()) {
"Nothing in the library yet"
} else {
"${state.library.size} tracks, shuffled into a queue"
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Button(
onClick = { store.playAll() },
enabled = state.library.isNotEmpty(),
) {
Icon(Icons.Rounded.Shuffle, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(6.dp))
Text("Shuffle all")
}
}
}
}
if (state.musicResults.isNotEmpty()) {
item {
SectionTitle("Search results") {
Text(
"${state.musicResults.size}",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
items(state.musicResults, key = { "search-${it.id}" }) { song ->
LibrarySongRow(song, state, store, supported)
}
item { HorizontalDivider(Modifier.padding(vertical = 14.dp)) }
}
item {
SectionTitle("Downloads") {
Text(
"${state.downloads.size} tracks · ${formatBytes(store.storageBytes())}",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
if (!supported) {
item {
Text(
"The browser plays from the server and lets the browser manage its cache. Install the Android or desktop app for offline downloads.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
} else if (downloadedSongs.isEmpty()) {
item {
Text(
"No downloads yet. Search for a song and press the download icon.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
} else {
items(downloadedSongs, key = { "download-${it.id}" }) { song ->
LibrarySongRow(song, state, store, supported)
}
item {
Text(
"Offline playback uses these files when the server is unreachable.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(top = 8.dp),
)
}
}
}
}
@Composable
private fun LongformLibrary(state: AppState, store: AppStore) {
var query by remember { mutableStateOf("") }
var artistDialog by remember { mutableStateOf<String?>(null) }
val supported = platformName != "web"
val byArtist = state.longform.groupBy { it.artist }
val artistNames = byArtist.keys.sortedBy { it.lowercase() }
val continueListening = state.longformProgress.values
.asSequence()
.filterNot { it.completed }
.sortedByDescending { it.updatedAt }
.mapNotNull { progress ->
state.longform.firstOrNull { it.id == progress.songId }?.let { it to progress }
}
.take(5)
.toList()
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(20.dp),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
item {
OutlinedTextField(
value = query,
onValueChange = {
query = it
store.searchLongform(it)
},
singleLine = true,
label = { Text("Search audiobooks and podcasts") },
leadingIcon = { Icon(Icons.Rounded.Search, contentDescription = null) },
trailingIcon = {
if (state.searching) {
CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp)
}
},
modifier = Modifier.fillMaxWidth(),
)
}
if (state.longformResults.isNotEmpty()) {
item { SectionTitle("Search results") }
items(state.longformResults, key = { "lf-search-${it.id}" }) { song ->
LongformSongRow(song, state, store, supported) { store.playLongformSong(song) }
}
item { HorizontalDivider(Modifier.padding(vertical = 14.dp)) }
}
if (continueListening.isNotEmpty()) {
item { SectionTitle("Continue listening") }
items(continueListening, key = { "continue-${it.first.id}" }) { (song, progress) ->
ContinueRow(song, progress, store)
}
item { HorizontalDivider(Modifier.padding(vertical = 14.dp)) }
}
item {
SectionTitle("Artists") {
Text(
"${artistNames.size}",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
if (artistNames.isEmpty()) {
item {
EmptyState(
"No long-form content",
"Add audiobooks or podcasts to a folder of type longform in library.yaml.",
)
}
} else {
items(artistNames, key = { "artist-$it" }) { artist ->
val songs = byArtist[artist].orEmpty()
ArtistRow(
name = artist,
count = songs.size,
onShuffle = { store.playLongformArtist(artist) },
onOpen = { artistDialog = artist },
)
}
}
}
artistDialog?.let { artist ->
LongformArtistDialog(
artist = artist,
songs = byArtist[artist].orEmpty(),
state = state,
store = store,
supported = supported,
onDismiss = { artistDialog = null },
)
}
}
@Composable
private fun ContinueRow(song: Song, progress: LongformProgress, store: AppStore) {
val duration = progress.durationSeconds.takeIf { it > 0 } ?: song.duration
val fraction = if (duration > 0) {
(progress.positionSeconds.toFloat() / duration).coerceIn(0f, 1f)
} else {
0f
}
Row(
modifier = Modifier
.fillMaxWidth()
.clickable { store.resumeLongform(song.id) }
.padding(vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Cover(store, song.albumId, Modifier.size(44.dp), size = 96)
Column(Modifier.weight(1f)) {
Text(song.title, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
song.artist,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Box(
Modifier
.fillMaxWidth()
.padding(top = 4.dp)
.height(3.dp)
.clip(RoundedCornerShape(2.dp))
.background(MaterialTheme.colorScheme.surfaceVariant),
) {
Box(
Modifier
.fillMaxWidth(fraction)
.height(3.dp)
.background(MaterialTheme.colorScheme.primary),
)
}
Text(
"${formatDuration(progress.positionSeconds)} / ${formatDuration(duration)}",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
IconButton(onClick = { store.resumeLongform(song.id) }) {
Icon(Icons.Rounded.PlayArrow, contentDescription = "Resume")
}
}
}
@Composable
private fun ArtistRow(
name: String,
count: Int,
onShuffle: () -> Unit,
onOpen: () -> Unit,
) {
Row(
modifier = Modifier.fillMaxWidth().clickable(onClick = onOpen).padding(vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
Column(Modifier.weight(1f)) {
Text(name, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
"$count tracks",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
IconButton(onClick = onShuffle) {
Icon(Icons.Rounded.Shuffle, contentDescription = "Play $name shuffled")
}
IconButton(onClick = onOpen) {
Icon(Icons.Rounded.List, contentDescription = "Show tracks")
}
}
}
@Composable
private fun LongformArtistDialog(
artist: String,
songs: List<Song>,
state: AppState,
store: AppStore,
supported: Boolean,
onDismiss: () -> Unit,
) {
Dialog(onDismissRequest = onDismiss) {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surface,
tonalElevation = 6.dp,
modifier = Modifier.fillMaxWidth().heightIn(max = 600.dp),
) {
Column {
Row(
modifier = Modifier.padding(20.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f)) {
Text(artist, style = MaterialTheme.typography.titleMedium, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
"${songs.size} tracks · read-only playlist",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
TextButton(onClick = onDismiss) { Text("Close") }
}
Row(modifier = Modifier.padding(horizontal = 20.dp)) {
Button(
onClick = {
store.playLongformArtist(artist)
onDismiss()
},
enabled = songs.isNotEmpty(),
) {
Icon(Icons.Rounded.Shuffle, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(6.dp))
Text("Shuffle artist")
}
}
HorizontalDivider(Modifier.padding(vertical = 12.dp))
LazyColumn(Modifier.fillMaxWidth().heightIn(max = 460.dp)) {
items(songs, key = { "artist-song-${it.id}" }) { song ->
LongformSongRow(song, state, store, supported) {
store.playLongformSong(song)
onDismiss()
}
}
}
}
}
}
}
@Composable
private fun LongformSongRow(
song: Song,
state: AppState,
store: AppStore,
supported: Boolean,
onPlay: () -> Unit,
) {
SongRow(store = store, song = song, onPlay = onPlay) {
DownloadAction(song, state, store, supported)
IconButton(onClick = onPlay) {
Icon(Icons.Rounded.PlayArrow, contentDescription = "Play")
}
}
}
@Composable
private fun LibrarySongRow(song: Song, state: AppState, store: AppStore, supported: Boolean) {
SongRow(store = store, song = song, onPlay = { store.playSong(song) }) {
DownloadAction(song, state, store, supported)
if (song.id in state.downloads) {
Icon(
Icons.Rounded.CheckCircle,
contentDescription = "Downloaded",
tint = MaterialTheme.colorScheme.secondary,
modifier = Modifier.size(18.dp),
)
}
IconButton(onClick = { store.playSong(song) }) {
Icon(Icons.Rounded.PlayArrow, contentDescription = "Play")
}
}
}
@Composable
private fun DownloadAction(song: Song, state: AppState, store: AppStore, supported: Boolean) {
if (!supported) return
when {
song.id in state.downloading -> CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp)
song.id in state.downloads -> {
IconButton(onClick = { store.toggleDownload(song) }) {
Icon(Icons.Rounded.DeleteOutline, contentDescription = "Delete download")
}
}
else -> {
IconButton(onClick = { store.toggleDownload(song) }) {
Icon(Icons.Rounded.Download, contentDescription = "Download")
}
}
}
}
@@ -1,10 +1,12 @@
package win.taptap.musicmanager.client.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
@@ -15,13 +17,18 @@ import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Add
import androidx.compose.material.icons.rounded.Check
import androidx.compose.material.icons.rounded.Close
import androidx.compose.material.icons.rounded.Download
import androidx.compose.material.icons.rounded.DownloadDone
import androidx.compose.material.icons.rounded.PlayArrow
import androidx.compose.material.icons.rounded.Refresh
import androidx.compose.material.icons.rounded.RemoveCircleOutline
import androidx.compose.material.icons.rounded.Search
import androidx.compose.material.icons.rounded.Settings
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
@@ -31,7 +38,6 @@ import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Slider
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
@@ -46,17 +52,22 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import kotlin.math.roundToInt
import win.taptap.musicmanager.client.api.MoodSong
import win.taptap.musicmanager.client.api.Recommendation
import win.taptap.musicmanager.client.api.Song
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
import win.taptap.musicmanager.client.store.sourceLabel
@Composable
fun MoodDetailScreen(state: AppState, store: AppStore) {
val detail = state.selectedMood
if (state.loading && detail == null) {
Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) {
Column(
Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
CircularProgressIndicator()
}
return
@@ -68,31 +79,23 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
}
val mood = detail.mood
var seedQuery by remember { mutableStateOf("") }
var name by remember(mood.id) { mutableStateOf(mood.name) }
var description by remember(mood.id) { mutableStateOf(mood.description.orEmpty()) }
var genres by remember(mood.id) { mutableStateOf(mood.genres.joinToString(", ")) }
var query by remember(mood.id) { mutableStateOf(mood.query.orEmpty()) }
var target by remember(mood.id) { mutableStateOf(mood.targetSize.toString()) }
var hours by remember(mood.id) { mutableStateOf(mood.refreshHours.toString()) }
var yt by remember(mood.id) { mutableStateOf(mood.ytEnabled) }
var seedPercent by remember(mood.id) { mutableStateOf(mood.seedPercent.toFloat()) }
val pendingDownloads = detail.recommendations.count {
val inFlight = mood.recommendationDownloading +
detail.recommendations.count {
it.download?.state == "queued" || it.download?.state == "downloading"
}
LaunchedEffect(detail.mood.id, pendingDownloads) {
// A new mood gets its first batch from a background discovery run, which
// resolves the YouTube Music search. Keep refreshing until it lands.
val waitingForFirstBatch = mood.recommendationCount > 0 && detail.recommendations.isEmpty()
LaunchedEffect(mood.id, inFlight, waitingForFirstBatch) {
var polls = 0
while (pendingDownloads > 0 && polls < 60) {
kotlinx.coroutines.delay(10_000)
while ((inFlight > 0 || waitingForFirstBatch) && polls < 60) {
kotlinx.coroutines.delay(5_000)
store.refreshSelectedMood()
polls += 1
}
}
val seedIds = detail.seeds.map { it.song.id }.toSet()
val searchResults = state.searchResults.filterNot { it.id in seedIds }
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(20.dp),
@@ -106,118 +109,83 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
) {
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text(
mood.description ?: "Server-driven radio",
mood.description ?: "Your private mix",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
Text("${mood.seedCount} seeds", style = MaterialTheme.typography.labelMedium)
Text("·", color = MaterialTheme.colorScheme.onSurfaceVariant)
Text("${mood.targetSize} batch", style = MaterialTheme.typography.labelMedium)
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
Text("${mood.songCount} songs", style = MaterialTheme.typography.labelMedium)
Text("·", color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(
"${mood.seedPercent}% seeds",
"${mood.collectionPercent}% collection",
style = MaterialTheme.typography.labelMedium,
)
Spacer(Modifier.weight(1f))
Button(onClick = { store.playMood(mood.id) }) {
Button(onClick = { store.playMood(mood.id) }, enabled = mood.songCount > 0) {
Icon(Icons.Rounded.PlayArrow, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(6.dp))
Text("Play radio")
}
}
if (mood.lastError != null) {
Text(mood.lastError, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
Text(
mood.lastError,
color = MaterialTheme.colorScheme.error,
style = MaterialTheme.typography.bodySmall,
)
}
}
}
}
item {
SectionTitle("Seeds") {
SectionTitle("Songs") {
Text(
"${detail.seeds.size}",
"${detail.songs.size}",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
if (detail.seeds.isEmpty()) {
if (detail.songs.isEmpty()) {
item {
Text(
"No seeds yet. Add a few songs below; every seed is always part of the radio.",
"A mood needs at least one song before it can play. Use Add music to search YouTube.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
} else {
items(detail.seeds, key = { it.song.id }) { seed ->
SongRow(
store = store,
song = seed.song,
onPlay = { store.playSong(seed.song) },
) {
Text(seed.origin, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
IconButton(onClick = { store.removeSeed(mood.id, seed.song.id) }) {
Icon(Icons.Rounded.RemoveCircleOutline, contentDescription = "Remove seed")
items(detail.songs, key = { it.song.id }) { entry ->
MoodSongRow(entry, store, mood.id, downloaded = entry.song.id in state.downloads)
}
}
}
}
item {
HorizontalDivider(Modifier.padding(vertical = 12.dp))
SectionTitle("Add songs")
}
item {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(top = 4.dp),
horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxWidth(),
) {
OutlinedTextField(
value = seedQuery,
onValueChange = { seedQuery = it },
singleLine = true,
label = { Text("Search your music") },
modifier = Modifier.weight(1f),
)
OutlinedButton(onClick = { store.search(seedQuery) }, enabled = seedQuery.isNotBlank()) {
Text("Search")
FilledTonalButton(onClick = { store.openSearch(mood.id) }) {
Icon(Icons.Rounded.Search, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(6.dp))
Text("Add music")
}
OutlinedButton(onClick = { store.openMoodSettings() }) {
Icon(Icons.Rounded.Settings, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(6.dp))
Text("Settings")
}
}
}
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 {
HorizontalDivider(Modifier.padding(vertical = 12.dp))
SectionTitle("Next batch")
}
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") {
SectionTitle("Recommendations") {
Row(verticalAlignment = Alignment.CenterVertically) {
if (state.discovering) {
CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
@@ -225,7 +193,7 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
}
TextButton(
onClick = { store.refreshRecommendations() },
enabled = !state.discovering,
enabled = !state.discovering && mood.recommendationCount > 0,
) {
Icon(Icons.Rounded.Refresh, contentDescription = null, modifier = Modifier.size(16.dp))
Spacer(Modifier.width(4.dp))
@@ -235,121 +203,55 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
}
}
val visible = detail.recommendations.filter { it.state != "rejected" }
if (visible.isEmpty()) {
if (mood.recommendationCount == 0) {
item {
Text(
"Recommendations are off for this mood. Raise the count in settings to let the server download picks.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
} else if (detail.recommendations.isEmpty()) {
item {
Text(
if (state.discovering) {
"Searching YouTube Music..."
"Searching and downloading picks…"
} else {
"No recommendations yet. Refresh to search for tracks that fit this mood."
"No recommendations yet. The server tops this mood up automatically."
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
} else {
items(visible, key = { "rec-${it.videoId}" }) { recommendation ->
items(detail.recommendations, key = { "rec-${it.source}-${it.externalId}" }) { recommendation ->
RecommendationRow(recommendation, state.discovering, store)
}
}
}
item {
HorizontalDivider(Modifier.padding(vertical = 12.dp))
SectionTitle("Settings")
}
item {
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
OutlinedTextField(
value = name,
onValueChange = { name = it },
label = { Text("Name") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
OutlinedTextField(
value = description,
onValueChange = { description = it },
label = { Text("Description") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
OutlinedTextField(
value = genres,
onValueChange = { genres = it },
label = { Text("Genres (comma separated)") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
OutlinedTextField(
value = query,
onValueChange = { query = it },
label = { Text("Free-text hint") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
OutlinedTextField(
value = target,
onValueChange = { target = it },
label = { Text("Batch size") },
singleLine = true,
modifier = Modifier.weight(1f),
)
OutlinedTextField(
value = hours,
onValueChange = { hours = it },
label = { Text("Refresh h") },
singleLine = true,
modifier = Modifier.weight(1f),
)
}
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(
"Seed mix: ${seedPercent.roundToInt()}% seeds · ${100 - seedPercent.roundToInt()}% recommendations",
style = MaterialTheme.typography.bodySmall,
)
Slider(
value = seedPercent,
onValueChange = { seedPercent = it },
valueRange = 0f..100f,
steps = 9,
)
Text(
"Each queued track rolls this share independently; if one side runs out, the other fills in.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Row(verticalAlignment = Alignment.CenterVertically) {
Text("YT Music discovery", Modifier.weight(1f))
Switch(checked = yt, onCheckedChange = { yt = it })
}
FilledTonalButton(
enabled = !state.saving && name.isNotBlank(),
onClick = {
store.saveMood(
detail = detail,
name = name.trim(),
description = description.trim().takeIf { it.isNotEmpty() },
genres = genres.split(',').map { it.trim() }.filter { it.isNotEmpty() },
query = query.trim().takeIf { it.isNotEmpty() },
targetSize = target.toIntOrNull() ?: mood.targetSize,
refreshHours = hours.toIntOrNull() ?: mood.refreshHours,
ytEnabled = yt,
seedPercent = seedPercent.roundToInt(),
)
},
modifier = Modifier.fillMaxWidth(),
) {
Text(if (state.saving) "Saving..." else "Save settings")
}
}
}
item { Spacer(Modifier.size(24.dp)) }
}
}
@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")
}
}
}
@@ -359,12 +261,18 @@ private fun RecommendationRow(
busy: Boolean,
store: AppStore,
) {
val failed = recommendation.state == "failed" ||
recommendation.download?.state == "failed"
Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
if (recommendation.song != null) {
Cover(store, recommendation.song.id, Modifier.size(48.dp), size = 96)
} else {
RemoteImage(store, recommendation.thumbnail, Modifier.size(48.dp))
}
Column(Modifier.weight(1f)) {
Text(
recommendation.title,
@@ -375,35 +283,29 @@ private fun RecommendationRow(
Text(
buildString {
append(recommendation.artist)
recommendation.album?.takeIf { it.isNotBlank() }?.let { append(" · ").append(it) }
recommendation.duration?.let { append(" · ").append(formatDuration(it)) }
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
val download = recommendation.download
Text(
when {
recommendation.state == "accepted" && recommendation.matchedSong != null -> "Seed added"
download?.state == "downloading" -> "Downloading..."
download?.state == "failed" -> "Download failed — tap ✓ to retry"
download?.state == "queued" -> "Download queued"
recommendation.state == "accepted" -> "Queued for download"
recommendation.matchedSong != null -> "In your library"
else -> "New"
failed -> "Download failed"
recommendation.state == "ready" -> "Ready to add"
else -> "Downloading…"
},
style = MaterialTheme.typography.labelSmall,
color = when {
download?.state == "failed" -> MaterialTheme.colorScheme.error
recommendation.state == "accepted" || download != null ->
color = if (failed) {
MaterialTheme.colorScheme.error
} else {
MaterialTheme.colorScheme.primary
else -> MaterialTheme.colorScheme.onSurfaceVariant
},
)
if (download?.state == "failed" && download.error != null) {
if (failed && recommendation.error != null) {
Text(
download.error,
recommendation.error,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.error,
maxLines = 2,
@@ -411,26 +313,26 @@ private fun RecommendationRow(
)
}
}
if (recommendation.state == "accepted" && recommendation.download?.state != "failed") {
Icon(
Icons.Rounded.Check,
contentDescription = "Accepted",
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(20.dp),
)
if (failed) {
IconButton(
onClick = { store.retryRecommendation(recommendation.externalId) },
enabled = !busy,
) {
Icon(Icons.Rounded.Refresh, contentDescription = "Retry download")
}
} else {
IconButton(
onClick = { store.acceptRecommendation(recommendation.videoId) },
onClick = { store.addRecommendation(recommendation.externalId) },
enabled = !busy,
) {
Icon(Icons.Rounded.Check, contentDescription = "Accept recommendation")
Icon(Icons.Rounded.Add, contentDescription = "Add to mood")
}
}
IconButton(
onClick = { store.rejectRecommendation(recommendation.videoId) },
onClick = { store.rejectRecommendation(recommendation.externalId) },
enabled = !busy,
) {
Icon(Icons.Rounded.Close, contentDescription = "Reject recommendation")
}
Icon(Icons.Rounded.Close, contentDescription = "Not interested")
}
}
}
@@ -0,0 +1,348 @@
package win.taptap.musicmanager.client.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Delete
import androidx.compose.material.icons.rounded.DownloadDone
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Slider
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
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.text.font.FontWeight
import androidx.compose.ui.unit.dp
import kotlin.math.roundToInt
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
import win.taptap.musicmanager.client.store.sourceLabel
/**
* Dedicated mood settings screen. Keeping the form out of the mood page makes
* the collection the focus and gives destructive actions their own place at the
* bottom instead of the top bar.
*/
@Composable
fun MoodSettingsScreen(state: AppState, store: AppStore) {
val detail = state.selectedMood
if (detail == null) {
EmptyState("Mood not available", "Open a mood first.")
return
}
val mood = detail.mood
var name by remember(mood.id) { mutableStateOf(mood.name) }
var description by remember(mood.id) { mutableStateOf(mood.description.orEmpty()) }
var genres by remember(mood.id) { mutableStateOf(mood.genres.joinToString(", ")) }
var query by remember(mood.id) { mutableStateOf(mood.query.orEmpty()) }
var 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 confirmDelete by remember { mutableStateOf(false) }
val offline = mood.id in state.offlineMoods
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(20.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
item {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surfaceVariant,
modifier = Modifier.fillMaxWidth(),
) {
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(
mood.name,
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.SemiBold,
)
Text(
"${mood.songCount} songs · ${mood.collectionPercent}% collection",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
item {
SectionTitle("Details")
}
item {
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
OutlinedTextField(
value = name,
onValueChange = { name = it },
label = { Text("Name") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
OutlinedTextField(
value = description,
onValueChange = { description = it },
label = { Text("Description") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
OutlinedTextField(
value = genres,
onValueChange = { genres = it },
label = { Text("Genres (comma separated)") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
OutlinedTextField(
value = query,
onValueChange = { query = it },
label = { Text("Discovery hint") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
}
}
item {
SectionTitle("Downloads")
}
item {
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f)) {
Text("Download source", style = MaterialTheme.typography.bodyMedium)
Text(
"Search, recommendations and downloads use this catalog.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Box {
OutlinedButton(onClick = { sourceMenu = true }) {
Text(sourceLabel(source))
}
DropdownMenu(
expanded = sourceMenu,
onDismissRequest = { sourceMenu = false },
) {
listOf("deezer", "youtube").forEach { option ->
DropdownMenuItem(
text = { Text(sourceLabel(option)) },
onClick = {
sourceMenu = false
source = option
},
)
}
}
}
}
if (source != mood.source) {
Text(
"Changing the source clears active recommendations and refills them.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.tertiary,
)
}
HorizontalDivider()
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
Icons.Rounded.DownloadDone,
contentDescription = null,
modifier = Modifier.size(18.dp),
tint = MaterialTheme.colorScheme.primary,
)
Spacer(Modifier.width(6.dp))
Text("Keep this mood offline", style = MaterialTheme.typography.bodyMedium)
}
Text(
"Downloads every song and keeps new additions in sync on Wi-Fi.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Switch(
checked = offline,
onCheckedChange = { store.setMoodOffline(mood.id, it) },
)
}
}
}
item {
SectionTitle("Mixing")
}
item {
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,
)
}
}
item {
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,
)
}
}
item {
OutlinedTextField(
value = hours,
onValueChange = { hours = it },
label = { Text("Refresh interval (hours)") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
}
item {
FilledTonalButton(
enabled = !state.saving && name.isNotBlank(),
onClick = {
store.saveMood(
detail = detail,
name = name.trim(),
description = description.trim().takeIf { it.isNotEmpty() },
genres = genres.split(',').map { it.trim() }.filter { it.isNotEmpty() },
query = query.trim().takeIf { it.isNotEmpty() },
source = source,
collectionPercent = collectionPercent.roundToInt(),
recommendationCount = recommendations.roundToInt(),
refreshHours = hours.toIntOrNull() ?: mood.refreshHours,
)
},
modifier = Modifier.fillMaxWidth(),
) {
if (state.saving) {
CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
Spacer(Modifier.width(8.dp))
}
Text(if (state.saving) "Saving..." else "Save settings")
}
}
item {
Spacer(Modifier.height(24.dp))
HorizontalDivider()
Spacer(Modifier.height(16.dp))
Text(
"Deleting a mood removes it for everyone who can see it. Downloaded files " +
"shared with other moods are kept.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.height(10.dp))
Button(
onClick = { confirmDelete = true },
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.errorContainer,
contentColor = MaterialTheme.colorScheme.onErrorContainer,
),
modifier = Modifier.fillMaxWidth(),
) {
Icon(Icons.Rounded.Delete, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(8.dp))
Text("Delete mood")
}
}
}
if (confirmDelete) {
AlertDialog(
onDismissRequest = { confirmDelete = false },
title = { Text("Delete \"${mood.name}\"?") },
text = {
Text(
"This cannot be undone. Downloaded tracks stay available to other moods " +
"that still use them.",
)
},
confirmButton = {
TextButton(
onClick = {
confirmDelete = false
store.deleteMood(mood.id)
},
) {
Text("Delete", color = MaterialTheme.colorScheme.error)
}
},
dismissButton = {
TextButton(onClick = { confirmDelete = false }) { Text("Cancel") }
},
)
}
}
@@ -27,12 +27,14 @@ import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Slider
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
@@ -51,6 +53,7 @@ import kotlin.math.roundToInt
import win.taptap.musicmanager.client.api.Mood
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
import win.taptap.musicmanager.client.store.sourceLabel
@Composable
fun MoodsScreen(state: AppState, store: AppStore) {
@@ -68,7 +71,7 @@ fun MoodsScreen(state: AppState, store: AppStore) {
fontWeight = FontWeight.SemiBold,
)
Text(
"Radio is generated live and learns from what you finish or skip.",
"Songs are downloaded from YouTube. Recommendations refill automatically.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
@@ -90,7 +93,7 @@ fun MoodsScreen(state: AppState, store: AppStore) {
if (state.moods.isEmpty()) {
EmptyState(
title = "No moods yet",
subtitle = "Create a mood, add a few seed songs, and press play. The server builds the rest.",
subtitle = "Create a mood, add a few songs, and press play. The server builds and downloads the rest.",
modifier = Modifier.fillMaxSize(),
)
} else {
@@ -116,9 +119,18 @@ fun MoodsScreen(state: AppState, store: AppStore) {
CreateMoodDialog(
saving = state.saving,
onDismiss = { creating = false },
onCreate = { name, description, genres, query, target, hours, yt, seedPercent ->
onCreate = { name, description, genres, query, source, collectionPercent, recommendations, hours ->
creating = false
store.createMood(name, description, genres, query, target, hours, yt, seedPercent)
store.createMood(
name,
description,
genres,
query,
source,
collectionPercent,
recommendations,
hours,
)
},
)
}
@@ -144,7 +156,7 @@ private fun MoodCard(mood: Mood, onOpen: () -> Unit, onPlay: () -> Unit) {
overflow = TextOverflow.Ellipsis,
)
Text(
mood.description ?: mood.genres.joinToString(" · ").ifBlank { "Server-driven radio" },
mood.description ?: mood.genres.joinToString(" · ").ifBlank { "Your private mix" },
style = MaterialTheme.typography.bodySmall,
color = Color.White.copy(alpha = 0.78f),
maxLines = 2,
@@ -153,21 +165,29 @@ private fun MoodCard(mood: Mood, onOpen: () -> Unit, onPlay: () -> Unit) {
)
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
"${mood.seedCount} seeds",
"${mood.songCount} songs",
style = MaterialTheme.typography.labelMedium,
color = Color.White.copy(alpha = 0.85f),
)
if (mood.newRecommendations > 0) {
val picks = mood.recommendationReady + mood.recommendationDownloading
if (picks > 0) {
Spacer(Modifier.width(8.dp))
Text(
"${mood.newRecommendations} picks",
"$picks picks",
style = MaterialTheme.typography.labelMedium,
color = Color.White.copy(alpha = 0.85f),
)
}
Spacer(Modifier.width(8.dp))
Text(
sourceLabel(mood.source),
style = MaterialTheme.typography.labelMedium,
color = Color.White.copy(alpha = 0.7f),
)
Spacer(Modifier.weight(1f))
FilledTonalButton(
onClick = onPlay,
enabled = mood.songCount > 0,
colors = ButtonDefaults.filledTonalButtonColors(
containerColor = Color.White.copy(alpha = 0.16f),
contentColor = Color.White,
@@ -186,16 +206,17 @@ private fun MoodCard(mood: Mood, onOpen: () -> Unit, onPlay: () -> Unit) {
private fun CreateMoodDialog(
saving: Boolean,
onDismiss: () -> Unit,
onCreate: (String, String?, List<String>, String?, Int, Int, Boolean, Int) -> Unit,
onCreate: (String, String?, List<String>, String?, String, Int, Int, Int) -> Unit,
) {
var name by remember { mutableStateOf("") }
var description by remember { mutableStateOf("") }
var genres by remember { mutableStateOf("") }
var query by remember { mutableStateOf("") }
var target by remember { mutableStateOf("30") }
var source by remember { mutableStateOf("deezer") }
var sourceMenu by remember { mutableStateOf(false) }
var collectionPercent by remember { mutableStateOf(50f) }
var recommendations by remember { mutableStateOf(10f) }
var hours by remember { mutableStateOf("24") }
var yt by remember { mutableStateOf(true) }
var seedPercent by remember { mutableStateOf(50f) }
AlertDialog(
onDismissRequest = onDismiss,
@@ -226,41 +247,68 @@ private fun CreateMoodDialog(
OutlinedTextField(
value = query,
onValueChange = { query = it },
label = { Text("Free-text hint") },
label = { Text("Discovery hint") },
singleLine = true,
)
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
OutlinedTextField(
value = target,
onValueChange = { target = it },
label = { Text("Batch size") },
singleLine = true,
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
"Download source",
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.weight(1f),
)
OutlinedTextField(
value = hours,
onValueChange = { hours = it },
label = { Text("Refresh h") },
singleLine = true,
modifier = Modifier.weight(1f),
Box {
OutlinedButton(onClick = { sourceMenu = true }) {
Text(sourceLabel(source))
}
DropdownMenu(
expanded = sourceMenu,
onDismissRequest = { sourceMenu = false },
) {
listOf("deezer", "youtube").forEach { option ->
DropdownMenuItem(
text = { Text(sourceLabel(option)) },
onClick = {
sourceMenu = false
source = option
},
)
}
}
}
}
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(
"Seed mix: ${seedPercent.roundToInt()}% seeds · ${100 - seedPercent.roundToInt()}% recommendations",
"Collection share: ${collectionPercent.roundToInt()}% · ${100 - collectionPercent.roundToInt()}% recommendations",
style = MaterialTheme.typography.bodySmall,
)
Slider(
value = seedPercent,
onValueChange = { seedPercent = it },
value = collectionPercent,
onValueChange = { collectionPercent = it },
valueRange = 0f..100f,
steps = 9,
)
}
Row(verticalAlignment = Alignment.CenterVertically) {
Text("YT Music discovery", Modifier.weight(1f))
Switch(checked = yt, onCheckedChange = { yt = it })
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(
"Active recommendations: ${recommendations.roundToInt()}",
style = MaterialTheme.typography.bodySmall,
)
Slider(
value = recommendations,
onValueChange = { recommendations = it },
valueRange = 0f..30f,
steps = 29,
)
}
OutlinedTextField(
value = hours,
onValueChange = { hours = it },
label = { Text("Refresh interval (hours)") },
singleLine = true,
)
}
},
confirmButton = {
@@ -272,10 +320,10 @@ private fun CreateMoodDialog(
description.trim().takeIf { it.isNotEmpty() },
genres.split(',').map { it.trim() }.filter { it.isNotEmpty() },
query.trim().takeIf { it.isNotEmpty() },
target.toIntOrNull() ?: 30,
source,
collectionPercent.roundToInt(),
recommendations.roundToInt(),
hours.toIntOrNull() ?: 24,
yt,
seedPercent.roundToInt(),
)
},
) { Text("Create") }
@@ -0,0 +1,353 @@
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.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Bedtime
import androidx.compose.material.icons.rounded.DownloadDone
import androidx.compose.material.icons.rounded.Pause
import androidx.compose.material.icons.rounded.PlayArrow
import androidx.compose.material.icons.rounded.PlaylistAdd
import androidx.compose.material.icons.rounded.QueueMusic
import androidx.compose.material.icons.rounded.SkipNext
import androidx.compose.material.icons.rounded.SkipPrevious
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
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.store.AppState
import win.taptap.musicmanager.client.store.AppStore
import win.taptap.musicmanager.client.store.sourceLabel
/**
* Full-screen player. The compact bar stays visible on other screens; tapping
* it opens this view with large artwork, the timeline, transport, offline and
* mood actions, and the upcoming queue.
*/
@Composable
fun NowPlayingScreen(state: AppState, store: AppStore) {
val song = state.current
if (song == null) {
EmptyState("Nothing playing", "Pick a mood and press play.", Modifier.fillMaxSize())
return
}
var sleepMenu by remember { mutableStateOf(false) }
var queueOpen by remember { mutableStateOf(false) }
var picker by remember { mutableStateOf(false) }
var dragSeconds by remember(song.id) { mutableStateOf<Float?>(null) }
val progress = if (state.durationSeconds > 0) {
(state.positionSeconds / state.durationSeconds).toFloat().coerceIn(0f, 1f)
} else {
0f
}
val quality = buildString {
append(sourceLabel(song.source))
if (song.bitRate > 0) {
append(" · ")
append(song.bitRate)
append(" kbps")
}
if (song.id in state.downloads) append(" · offline")
}
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(24.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
item {
Cover(
store = store,
songId = song.id,
modifier = Modifier
.fillMaxWidth()
.aspectRatio(1f)
.padding(horizontal = 12.dp),
size = 800,
)
}
item {
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(
song.title,
style = MaterialTheme.typography.headlineSmall,
fontWeight = FontWeight.Bold,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
Text(
song.artist,
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
quality,
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
)
}
}
item {
Column {
Slider(
value = dragSeconds ?: progress,
onValueChange = { dragSeconds = it },
onValueChangeFinished = {
dragSeconds?.let { fraction ->
if (state.durationSeconds > 0) {
store.seekTo(fraction * state.durationSeconds)
}
}
dragSeconds = null
},
enabled = store.canSeek() && state.durationSeconds > 0,
)
Row(Modifier.fillMaxWidth()) {
Text(
formatDuration(state.positionSeconds.toInt()),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.weight(1f))
Text(
formatDuration(state.durationSeconds.toInt()),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
item {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceEvenly,
) {
IconButton(onClick = { store.previous() }, modifier = Modifier.size(52.dp)) {
Icon(
Icons.Rounded.SkipPrevious,
contentDescription = "Previous",
modifier = Modifier.size(36.dp),
)
}
IconButton(onClick = { store.togglePlayPause() }, modifier = Modifier.size(76.dp)) {
Icon(
if (state.playing) Icons.Rounded.Pause else Icons.Rounded.PlayArrow,
contentDescription = if (state.playing) "Pause" else "Play",
modifier = Modifier.size(52.dp),
)
}
IconButton(onClick = { store.skip() }, modifier = Modifier.size(52.dp)) {
Icon(
Icons.Rounded.SkipNext,
contentDescription = "Skip",
modifier = Modifier.size(36.dp),
)
}
}
}
item {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
FilledTonalButton(
onClick = {
if (state.session != null) {
store.addCurrentToMood(null)
} else {
picker = true
}
},
modifier = Modifier.weight(1f),
) {
Icon(Icons.Rounded.PlaylistAdd, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(6.dp))
Text("Add to mood")
}
IconButton(onClick = { queueOpen = true }) {
Icon(Icons.Rounded.QueueMusic, contentDescription = "Queue")
}
androidx.compose.foundation.layout.Box {
IconButton(onClick = { sleepMenu = true }) {
Icon(
Icons.Rounded.Bedtime,
contentDescription = "Sleep timer",
tint = if (state.sleepTimerRemainingSeconds != null || state.sleepAtTrackEnd) {
MaterialTheme.colorScheme.primary
} else {
MaterialTheme.colorScheme.onSurfaceVariant
},
)
}
SleepTimerMenu(
expanded = sleepMenu,
onDismiss = { sleepMenu = false },
state = state,
store = store,
)
}
}
}
if (state.sleepAtTrackEnd) {
item {
Text(
"Sleep: stopping after this track",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
)
}
} else if (state.sleepTimerRemainingSeconds != null) {
item {
Text(
"Sleep in ${formatDuration(state.sleepTimerRemainingSeconds.toInt())}",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
)
}
}
if (song.id in state.downloads) {
item {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
Icons.Rounded.DownloadDone,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(18.dp),
)
Spacer(Modifier.width(6.dp))
Text(
"Available without the server",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
item {
HorizontalDivider()
SectionTitle("Up next") {
Text(
"${state.queue.size}",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
if (state.queue.isEmpty()) {
item {
Text(
"Nothing queued. The radio adds tracks automatically.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
} else {
itemsIndexed(
state.queue.take(10),
key = { _, item -> "np-${item.id}" },
) { index, queued ->
SongRow(
store = store,
song = queued,
onPlay = { store.playFromQueue(index) },
) {
Text(
formatDuration(queued.duration),
style = MaterialTheme.typography.labelSmall,
)
}
}
}
}
if (queueOpen) QueueDialog(state, store) { queueOpen = false }
if (picker) {
MoodPickerDialog(
moods = state.moods,
currentMoodId = state.session?.moodId,
onDismiss = { picker = false },
onSelect = { mood ->
picker = false
store.addCurrentToMood(mood.id)
},
)
}
}
@Composable
internal fun SleepTimerMenu(
expanded: Boolean,
onDismiss: () -> Unit,
state: AppState,
store: AppStore,
) {
DropdownMenu(expanded = expanded, onDismissRequest = onDismiss) {
DropdownMenuItem(
text = { Text("Finish this track") },
onClick = {
onDismiss()
store.setSleepAfterTrack()
},
)
listOf(15, 30, 45, 60, 90).forEach { minutes ->
DropdownMenuItem(
text = { Text("$minutes minutes") },
onClick = {
onDismiss()
store.setSleepTimer(minutes)
},
)
}
if (state.sleepTimerRemainingSeconds != null || state.sleepAtTrackEnd) {
HorizontalDivider()
DropdownMenuItem(
text = { Text("Turn off") },
onClick = {
onDismiss()
store.setSleepTimer(null)
},
)
}
}
}
@@ -1,11 +1,16 @@
package win.taptap.musicmanager.client.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress
import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
@@ -13,13 +18,14 @@ import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.AddCircleOutline
import androidx.compose.material.icons.rounded.Bedtime
import androidx.compose.material.icons.rounded.Close
import androidx.compose.material.icons.rounded.KeyboardArrowDown
import androidx.compose.material.icons.rounded.KeyboardArrowUp
import androidx.compose.material.icons.rounded.DragHandle
import androidx.compose.material.icons.rounded.MoreVert
import androidx.compose.material.icons.rounded.Pause
import androidx.compose.material.icons.rounded.PlayArrow
import androidx.compose.material.icons.rounded.PlaylistAdd
@@ -37,27 +43,36 @@ import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.zIndex
import kotlinx.coroutines.delay
import kotlin.math.roundToInt
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
private val QUEUE_ROW_HEIGHT = 58.dp
@Composable
fun PlayerBar(state: AppState, store: AppStore) {
val song = state.current ?: return
var picker by remember { mutableStateOf(false) }
var sleepMenu by remember { mutableStateOf(false) }
var moreMenu by remember { mutableStateOf(false) }
var queueOpen by remember { mutableStateOf(false) }
var dragSeconds by remember(song.id) { mutableStateOf<Float?>(null) }
val sleepRemaining = state.sleepTimerRemainingSeconds
val isLongform = state.user?.longformFolders?.contains(song.folderId) == true
Surface(
color = MaterialTheme.colorScheme.surfaceVariant,
@@ -88,54 +103,76 @@ fun PlayerBar(state: AppState, store: AppStore) {
enabled = store.canSeek() && state.durationSeconds > 0,
modifier = Modifier.weight(1f),
)
IconButton(
onClick = {
if (state.session != null) {
store.addCurrentToMood(null)
} else {
picker = true
}
},
) {
Icon(Icons.Rounded.PlaylistAdd, contentDescription = "Add to mood")
}
IconButton(onClick = { queueOpen = true }) {
Icon(Icons.Rounded.QueueMusic, contentDescription = "Queue")
}
Box {
IconButton(onClick = { moreMenu = true }) {
Icon(Icons.Rounded.MoreVert, contentDescription = "More actions")
}
DropdownMenu(
expanded = moreMenu,
onDismissRequest = { moreMenu = false },
) {
DropdownMenuItem(
text = { Text("Add to another mood") },
leadingIcon = {
Icon(Icons.Rounded.PlaylistAdd, contentDescription = null)
},
onClick = {
moreMenu = false
picker = true
},
)
}
}
Box {
IconButton(onClick = { sleepMenu = true }) {
Icon(
Icons.Rounded.Bedtime,
contentDescription = "Sleep timer",
tint = if (sleepRemaining != null) {
tint = if (sleepRemaining != null || state.sleepAtTrackEnd) {
MaterialTheme.colorScheme.primary
} else {
MaterialTheme.colorScheme.onSurfaceVariant
},
)
}
DropdownMenu(
SleepTimerMenu(
expanded = sleepMenu,
onDismissRequest = { sleepMenu = false },
) {
listOf(15, 30, 45, 60, 90).forEach { minutes ->
DropdownMenuItem(
text = { Text("$minutes minutes") },
onClick = {
sleepMenu = false
store.setSleepTimer(minutes)
},
onDismiss = { sleepMenu = false },
state = state,
store = store,
)
}
if (sleepRemaining != null) {
HorizontalDivider()
DropdownMenuItem(
text = { Text("Turn off") },
onClick = {
sleepMenu = false
store.setSleepTimer(null)
},
)
}
}
}
}
Row(
modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 8.dp, bottom = 8.dp),
modifier = Modifier
.fillMaxWidth()
.padding(start = 12.dp, end = 8.dp, bottom = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(6.dp),
) {
Row(
modifier = Modifier
.weight(1f)
.clickable(onClick = { store.openNowPlaying() }),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
Cover(store, song.albumId, Modifier.size(48.dp), size = 160)
Cover(store, song.id, Modifier.size(48.dp), size = 160)
Column(Modifier.weight(1f)) {
Text(
song.title,
@@ -155,7 +192,9 @@ fun PlayerBar(state: AppState, store: AppStore) {
append(formatDuration(state.positionSeconds.toInt()))
append(" / ")
append(formatDuration(state.durationSeconds.toInt()))
if (sleepRemaining != null) {
if (state.sleepAtTrackEnd) {
append(" · sleep after track")
} else if (sleepRemaining != null) {
append(" · sleep ")
append(formatDuration(sleepRemaining.toInt()))
}
@@ -166,28 +205,38 @@ fun PlayerBar(state: AppState, store: AppStore) {
overflow = TextOverflow.Ellipsis,
)
}
}
if (!isLongform) {
IconButton(onClick = { store.addCurrentToMood(null) }) {
Icon(Icons.Rounded.AddCircleOutline, contentDescription = "Add to current mood")
IconButton(
onClick = { store.previous() },
modifier = Modifier.size(40.dp),
) {
Icon(
Icons.Rounded.SkipPrevious,
contentDescription = "Previous",
modifier = Modifier.size(26.dp),
)
}
IconButton(onClick = { picker = true }) {
Icon(Icons.Rounded.PlaylistAdd, contentDescription = "Add to another mood")
}
}
IconButton(onClick = { store.previous() }) {
Icon(Icons.Rounded.SkipPrevious, contentDescription = "Previous")
}
IconButton(onClick = { store.skip() }) {
Icon(Icons.Rounded.SkipNext, contentDescription = "Skip")
}
IconButton(onClick = { store.togglePlayPause() }) {
IconButton(
onClick = { store.togglePlayPause() },
modifier = Modifier.size(48.dp),
) {
Icon(
if (state.playing) Icons.Rounded.Pause else Icons.Rounded.PlayArrow,
contentDescription = if (state.playing) "Pause" else "Play",
modifier = Modifier.size(30.dp),
)
}
IconButton(
onClick = { store.skip() },
modifier = Modifier.size(40.dp),
) {
Icon(
Icons.Rounded.SkipNext,
contentDescription = "Skip",
modifier = Modifier.size(26.dp),
)
}
}
}
}
@@ -210,13 +259,44 @@ fun PlayerBar(state: AppState, store: AppStore) {
}
@Composable
private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit) {
fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit) {
val listState = rememberLazyListState()
var draggingIndex by remember { mutableStateOf<Int?>(null) }
var dragPointerY by remember { mutableStateOf(0f) }
var grabOffset by remember { mutableStateOf(0f) }
val edgePx = with(LocalDensity.current) { 48.dp.toPx() }
fun queueIndexAt(y: Float): Int? =
listState.layoutInfo.visibleItemsInfo
.firstOrNull { y >= it.offset && y < it.offset + it.size }
?.index
LaunchedEffect(draggingIndex) {
while (draggingIndex != null) {
val y = dragPointerY
val edge = edgePx
val viewport = listState.layoutInfo.viewportEndOffset.toFloat()
if (y < edge) {
listState.scrollBy(-18f)
} else if (y > viewport - edge) {
listState.scrollBy(18f)
}
val from = draggingIndex
val to = queueIndexAt(y)
if (from != null && to != null && to != from) {
store.moveInQueue(from, to)
draggingIndex = to
}
delay(16)
}
}
Dialog(onDismissRequest = onDismiss) {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surface,
tonalElevation = 6.dp,
modifier = Modifier.fillMaxWidth().heightIn(max = 600.dp),
modifier = Modifier.fillMaxWidth().heightIn(max = 620.dp),
) {
Column {
Row(
@@ -226,7 +306,11 @@ private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit)
Column(Modifier.weight(1f)) {
Text("Queue", style = MaterialTheme.typography.titleMedium)
Text(
"${state.queue.size} upcoming",
if (state.queue.isEmpty()) {
"Nothing queued"
} else {
"${state.queue.size} upcoming · long-press and drag to reorder"
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
@@ -234,17 +318,23 @@ private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit)
TextButton(onClick = onDismiss) { Text("Close") }
}
HorizontalDivider()
LazyColumn(Modifier.fillMaxWidth().heightIn(max = 480.dp)) {
state.current?.let { song ->
item(key = "current") {
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 10.dp),
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Cover(store, song.albumId, Modifier.size(40.dp), size = 96)
Cover(store, song.id, Modifier.size(40.dp), size = 96)
Column(Modifier.weight(1f)) {
Text(song.title, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
song.title,
style = MaterialTheme.typography.bodyLarge,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
"Now playing",
style = MaterialTheme.typography.labelSmall,
@@ -252,29 +342,86 @@ private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit)
)
}
}
}
HorizontalDivider()
}
if (state.queue.isEmpty()) {
item {
Text(
"Nothing queued. Start a mood, shuffle all or an artist.",
"Nothing queued. Start a mood to build a radio queue.",
modifier = Modifier.padding(20.dp),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
} else {
Box(
modifier = Modifier
.fillMaxWidth()
.pointerInput(Unit) {
detectDragGesturesAfterLongPress(
onDragStart = { offset ->
val index = queueIndexAt(offset.y)
val info = listState.layoutInfo.visibleItemsInfo
.firstOrNull { it.index == index }
if (index != null && info != null) {
draggingIndex = index
dragPointerY = offset.y
grabOffset = offset.y - info.offset
}
},
onDrag = { change, _ ->
change.consume()
dragPointerY = change.position.y
val from = draggingIndex
val to = queueIndexAt(change.position.y)
if (from != null && to != null && to != from) {
store.moveInQueue(from, to)
draggingIndex = to
}
},
onDragEnd = { draggingIndex = null },
onDragCancel = { draggingIndex = null },
)
},
) {
LazyColumn(
state = listState,
modifier = Modifier.fillMaxWidth().heightIn(max = 500.dp),
) {
itemsIndexed(state.queue, key = { _, song -> song.id }) { index, song ->
val isDragging = index == draggingIndex
val rowInfo = if (isDragging) {
listState.layoutInfo.visibleItemsInfo
.firstOrNull { it.index == index }
} else {
null
}
val translation = if (rowInfo != null) {
dragPointerY - rowInfo.offset - grabOffset
} else {
0f
}
itemsIndexed(state.queue, key = { index, _ -> "queue-$index" }) { index, song ->
Row(
modifier = Modifier.fillMaxWidth().padding(start = 20.dp, end = 8.dp, top = 6.dp, bottom = 6.dp),
modifier = Modifier
.fillMaxWidth()
.height(QUEUE_ROW_HEIGHT)
.background(MaterialTheme.colorScheme.surface)
.zIndex(if (isDragging) 1f else 0f)
.graphicsLayer {
translationY = translation
shadowElevation = if (isDragging) 8.dp.toPx() else 0f
}
.padding(start = 20.dp, end = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
Cover(store, song.albumId, Modifier.size(36.dp), size = 96)
Cover(store, song.id, Modifier.size(36.dp), size = 96)
Column(Modifier.weight(1f)) {
Text(song.title, style = MaterialTheme.typography.bodyMedium, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
song.title,
style = MaterialTheme.typography.bodyMedium,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
song.artist,
style = MaterialTheme.typography.labelSmall,
@@ -283,19 +430,19 @@ private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit)
overflow = TextOverflow.Ellipsis,
)
}
Icon(
Icons.Rounded.DragHandle,
contentDescription = "Drag to reorder",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(22.dp),
)
IconButton(
onClick = { store.moveInQueue(index, index - 1) },
enabled = index > 0,
onClick = {
val from = store.state.value.queue
.indexOfFirst { it.id == song.id }
if (from >= 0) store.removeFromQueue(from)
},
) {
Icon(Icons.Rounded.KeyboardArrowUp, contentDescription = "Move up")
}
IconButton(
onClick = { store.moveInQueue(index, index + 1) },
enabled = index < state.queue.lastIndex,
) {
Icon(Icons.Rounded.KeyboardArrowDown, contentDescription = "Move down")
}
IconButton(onClick = { store.removeFromQueue(index) }) {
Icon(Icons.Rounded.Close, contentDescription = "Remove from queue")
}
}
@@ -304,4 +451,6 @@ 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,31 +2,34 @@ package win.taptap.musicmanager.client.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.DeleteSweep
import androidx.compose.material.icons.rounded.Logout
import androidx.compose.material.icons.rounded.Refresh
import androidx.compose.material.icons.rounded.TravelExplore
import androidx.compose.material3.Button
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Slider
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
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.unit.dp
import kotlin.math.roundToInt
import win.taptap.musicmanager.client.platformName
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
@@ -35,7 +38,7 @@ import win.taptap.musicmanager.client.store.AppStore
fun SettingsScreen(state: AppState, store: AppStore) {
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = androidx.compose.foundation.layout.PaddingValues(20.dp),
contentPadding = PaddingValues(20.dp),
verticalArrangement = Arrangement.spacedBy(14.dp),
) {
item {
@@ -57,6 +60,83 @@ fun SettingsScreen(state: AppState, store: AppStore) {
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
FilledTonalButton(onClick = { store.refreshAll() }) {
Icon(Icons.Rounded.Refresh, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text("Sync moods")
}
}
}
}
item {
val info = state.serverInfo
Surface(
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.surfaceVariant,
modifier = Modifier.fillMaxWidth(),
) {
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text("Audio", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
Row(verticalAlignment = Alignment.CenterVertically) {
Column(Modifier.weight(1f)) {
Text("Loudness normalization", style = MaterialTheme.typography.bodyMedium)
Text(
when {
info == null -> "The server does not report audio settings."
info.loudnessEnabled ->
"Server-measured gain per track, target ${info.loudnessTargetLufs} LUFS."
else -> "Disabled on this server."
},
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Switch(
checked = state.normalizationEnabled && info?.loudnessEnabled == true,
onCheckedChange = { store.setNormalizationEnabled(it) },
enabled = info?.loudnessEnabled == true,
)
}
if (store.supportsCrossfade()) {
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(
if (state.crossfadeSeconds == 0) {
"Track transition: gapless"
} else {
"Track transition: ${state.crossfadeSeconds}s fade"
},
style = MaterialTheme.typography.bodyMedium,
)
Slider(
value = state.crossfadeSeconds.toFloat(),
onValueChange = { store.setCrossfadeSeconds(it.roundToInt()) },
valueRange = 0f..8f,
steps = 7,
)
}
}
info?.let {
Text(
buildString {
append(if (it.defaultSource == "deezer") "Deezer" else "YouTube Music")
append(" default · ")
if (it.defaultSource == "deezer") {
append(
if (it.deezerQuality == 1) {
"320 kbps downloads"
} else {
"128 kbps downloads (320 needs a Premium/HiFi ARL)"
},
)
} else {
append("best available audio")
}
},
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
}
@@ -68,31 +148,36 @@ fun SettingsScreen(state: AppState, store: AppStore) {
modifier = Modifier.fillMaxWidth(),
) {
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text("Library", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
Text("Offline", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
Text(
"${state.library.size} songs cached · ${state.downloads.size} downloaded · ${formatBytes(store.storageBytes())}",
"${state.downloads.size} downloaded · ${formatBytes(store.storageBytes())}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) {
FilledTonalButton(onClick = { store.refreshAll() }) {
Icon(Icons.Rounded.Refresh, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text("Sync")
}
if (state.user?.admin == true) {
OutlinedButton(onClick = { store.scanLibrary() }) {
Icon(Icons.Rounded.TravelExplore, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text("Scan")
}
}
Text(
if (state.offlineMoods.isEmpty()) {
"No mood is kept offline."
} else {
"${state.offlineMoods.size} mood(s) auto-sync on Wi-Fi: " +
state.moods.filter { it.id in state.offlineMoods }
.joinToString(", ") { it.name }
},
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Row(
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
OutlinedButton(onClick = { store.openDownloads() }) {
Text("Manage downloads")
}
if (state.downloads.isNotEmpty()) {
OutlinedButton(onClick = { store.clearDownloads() }) {
Icon(Icons.Rounded.DeleteSweep, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text("Clear downloads")
Text("Clear")
}
}
}
}
@@ -108,12 +193,13 @@ fun SettingsScreen(state: AppState, store: AppStore) {
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text("About", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
Text(
"AudioManager 0.1.0 · $platformName",
"AudioManager 0.4.0 · $platformName",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Text(
"Moods are radio: the server chooses the next batch and learns from skips and completions. Add a track to a mood with the two buttons in the player.",
"Moods are private. Songs are downloaded from YouTube into a shared server store; " +
"recommendations refill automatically and stay playable without being permanent.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
@@ -8,17 +8,17 @@ import io.ktor.http.HttpStatusCode
import io.ktor.http.headersOf
import io.ktor.utils.io.readAvailable
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNull
import kotlin.test.assertTrue
import win.taptap.musicmanager.client.api.ApiClient
import win.taptap.musicmanager.client.api.ApiException
import win.taptap.musicmanager.client.api.Mood
import win.taptap.musicmanager.client.api.configuredHttpClient
import win.taptap.musicmanager.client.data.AppStorage
import win.taptap.musicmanager.client.data.AppCache
import win.taptap.musicmanager.client.data.CachedState
import win.taptap.musicmanager.client.data.LibraryCache
class ApiClientTest {
@@ -31,15 +31,16 @@ class ApiClientTest {
"/api/v1/auth/login" -> respond(
"""
{"token":"abc123","expiresAt":"2027-01-01T00:00:00Z",
"user":{"name":"alice","admin":true,"musicFolders":[1],"longformFolders":[10]}}
"user":{"name":"alice","admin":true}}
""".trimIndent(),
HttpStatusCode.OK,
jsonHeaders,
)
"/api/v1/moods" -> respond(
"""
{"moods":[{"id":"mo-1","name":"Focus","targetSize":30,"refreshHours":24,
"ytEnabled":true,"createdAt":"now","changedAt":"now","seedCount":2}]}
{"moods":[{"id":"mo-1","name":"Focus","source":"deezer","collectionPercent":60,
"recommendationPercent":40,"recommendationCount":10,"refreshHours":24,
"createdAt":"now","changedAt":"now","songCount":2,"recommendationReady":3}]}
""".trimIndent(),
HttpStatusCode.OK,
jsonHeaders,
@@ -56,7 +57,87 @@ class ApiClientTest {
val moods = client.moods()
assertEquals(1, moods.size)
assertEquals("Focus", moods.first().name)
assertEquals(2, moods.first().seedCount)
assertEquals(2, moods.first().songCount)
assertEquals(3, moods.first().recommendationReady)
}
@Test
fun `search returns badges and adding a video queues a download`() = runTest {
val engine = MockEngine { request ->
when (request.url.encodedPath) {
"/api/v1/search" -> respond(
"""
{"results":[
{"source":"deezer","externalId":"v1","title":"Fresh","artist":"Artist",
"duration":180,"downloaded":false},
{"source":"deezer","externalId":"v2","title":"Old","artist":"Artist",
"duration":200,"songId":"sg-2","downloaded":true}
]}
""".trimIndent(),
HttpStatusCode.OK,
jsonHeaders,
)
"/api/v1/moods/mo-1/songs" -> respond(
"""
{"detail":{"mood":{"id":"mo-1","name":"Focus","createdAt":"now",
"changedAt":"now","songCount":1},"songs":[],"recommendations":[]},
"added":false,"downloading":true}
""".trimIndent(),
HttpStatusCode.Accepted,
jsonHeaders,
)
else -> respondError(HttpStatusCode.NotFound)
}
}
val client = ApiClient(configuredHttpClient(engine))
client.restore("http://music", "token")
val results = client.search("fresh")
assertEquals(2, results.size)
assertNull(results[0].songId)
assertEquals("sg-2", results[1].songId)
assertTrue(results[1].downloaded)
assertEquals("v2", results[1].externalId)
val added = client.addSong("mo-1", source = "deezer", externalId = "v1")
assertTrue(added.downloading)
assertEquals(1, added.detail.mood.songCount)
}
@Test
fun `adding and rejecting recommendations parse the decision`() = runTest {
val engine = MockEngine { request ->
when (request.url.encodedPath) {
"/api/v1/moods/mo-1/recommendations/v1/add" -> respond(
"""
{"detail":{"mood":{"id":"mo-1","name":"Focus","createdAt":"now",
"changedAt":"now","songCount":2},"songs":[],"recommendations":[]},
"recommendation":{"source":"deezer","externalId":"v1","title":"Pick",
"artist":"Artist","state":"added"}}
""".trimIndent(),
HttpStatusCode.OK,
jsonHeaders,
)
"/api/v1/moods/mo-1/recommendations/v2/reject" -> respond(
"""
{"detail":{"mood":{"id":"mo-1","name":"Focus","createdAt":"now",
"changedAt":"now","songCount":2},"songs":[],"recommendations":[]},
"recommendation":{"source":"deezer","externalId":"v2","title":"Other",
"artist":"Artist","state":"rejected"}}
""".trimIndent(),
HttpStatusCode.OK,
jsonHeaders,
)
else -> respondError(HttpStatusCode.NotFound)
}
}
val client = ApiClient(configuredHttpClient(engine))
client.restore("http://music", "token")
assertEquals("added", client.addRecommendation("mo-1", "v1").recommendation.state)
assertEquals("rejected", client.rejectRecommendation("mo-1", "v2").recommendation.state)
}
@Test
@@ -116,23 +197,33 @@ class ApiClientTest {
}
@Test
fun `cache round-trips songs and moods`() = runTest {
fun `cache round-trips moods and discards the old cache version`() = runTest {
val storage = MemoryStorage()
val cache = LibraryCache(storage)
val cache = AppCache(storage)
assertNull(cache.loadSession())
val mood = Mood(
id = "mo-1",
name = "Focus",
createdAt = "now",
changedAt = "now",
songCount = 2,
)
cache.save(
CachedState(
serverUrl = "http://localhost:8080",
userName = "alice",
revision = "2026-11-14T00:00:00Z",
songs = emptyList(),
moods = emptyList(),
moods = listOf(mood),
),
)
val loaded = cache.load()
assertEquals("2026-11-14T00:00:00Z", loaded.revision)
assertEquals(listOf("mo-1"), loaded.moods.map { it.id })
assertEquals("alice", loaded.userName)
storage.write("mood-cache.json", """{"version":1,"songs":[{"id":"old"}]}""")
val invalidated = cache.load()
assertTrue(invalidated.moods.isEmpty())
assertEquals(3, invalidated.version)
}
}
File diff suppressed because it is too large. Load diff
@@ -1,11 +1,13 @@
package win.taptap.musicmanager.client
import io.ktor.utils.io.readAvailable
import win.taptap.musicmanager.client.data.AppStorage
/** In-memory [AppStorage] for store and cache tests. */
internal class MemoryStorage : AppStorage {
private val files = mutableMapOf<String, String>()
private val artwork = mutableMapOf<String, ByteArray>()
private val downloads = mutableMapOf<String, ByteArray>()
override fun read(name: String): String? = files[name]
@@ -17,16 +19,40 @@ internal class MemoryStorage : AppStorage {
files.remove(name)
}
override fun saveDownload(songId: String, bytes: ByteArray): String? = null
override fun downloadPath(songId: String): String? = null
override fun saveDownload(songId: String, bytes: ByteArray): String? {
downloads[songId] = bytes
return "memory://$songId.mp3"
}
override suspend fun saveDownloadStream(
songId: String,
source: io.ktor.utils.io.ByteReadChannel,
): String? {
val bytes = ArrayList<Byte>()
val buffer = ByteArray(8 * 1024)
while (true) {
val read = source.readAvailable(buffer)
if (read < 0) break
for (i in 0 until read) bytes += buffer[i]
}
downloads[songId] = bytes.toByteArray()
return "memory://$songId.mp3"
}
override fun downloadPath(songId: String): String? =
downloads[songId]?.let { "memory://$songId.mp3" }
override fun saveArtwork(songId: String, bytes: ByteArray): String? {
artwork[songId] = bytes
return "memory://$songId.jpg"
}
override fun artworkBytes(songId: String): ByteArray? = artwork[songId]
override fun listDownloads(): Map<String, Long> = emptyMap()
override fun listDownloads(): Map<String, Long> =
downloads.mapValues { it.value.size.toLong() }
override fun deleteDownload(songId: String) {
artwork.remove(songId)
downloads.remove(songId)
}
override fun storageUsedBytes(): Long = 0
override fun storageUsedBytes(): Long = downloads.values.sumOf { it.size.toLong() }
}
@@ -8,23 +8,24 @@ import java.net.URI
import javax.sound.sampled.AudioFormat
import javax.sound.sampled.AudioInputStream
import javax.sound.sampled.AudioSystem
import javax.sound.sampled.FloatControl
import javax.sound.sampled.SourceDataLine
import kotlin.concurrent.thread
import win.taptap.musicmanager.client.api.Song
import kotlin.math.pow
import win.taptap.musicmanager.client.playback.AudioPlayer
import win.taptap.musicmanager.client.playback.PlaybackTrack
/**
* Desktop playback through the MP3SPI decoder and a PCM line. Pause/resume is a
* decoder loop gate, so no audio device is reopened.
*
* The queue is kept here so the store can use the same timeline operations as
* Android. Desktop has no media service, so the store advances to the next item
* when the decoder reaches the end.
*
* Seeking restarts the decoder at the requested position. Remote streams ask
* the server to transcode from that offset (`timeOffset`); local files skip the
* decoded PCM frames. Both keep the reported position aligned with the song.
*
* Java Sound cannot open a line for the compressed MP3 format itself; the
* decoded stream has to be converted to PCM_SIGNED first. Opening the encoded
* format fails with "No line matching interface SourceDataLine supporting
* format MPEG1L3 ...".
*/
class DesktopAudioPlayer : AudioPlayer {
@@ -34,10 +35,10 @@ class DesktopAudioPlayer : AudioPlayer {
private var worker: Thread? = null
private val lock = Object()
private var currentSource: String? = null
private var currentSong: Song? = null
private var currentLocal = false
private var currentArtwork: String? = null
private var tracks: List<PlaybackTrack> = emptyList()
private var index = 0
private var currentTrack: PlaybackTrack? = null
private var gain = 1f
@Volatile private var paused = false
@Volatile private var stopped = false
@@ -48,29 +49,78 @@ class DesktopAudioPlayer : AudioPlayer {
private var frameRate = 44_100f
private var duration = 0.0
override fun play(
source: String,
song: Song,
local: Boolean,
artworkUri: String?,
artworkBytes: ByteArray?,
) {
currentSource = source
currentSong = song
currentLocal = local
currentArtwork = artworkUri
start(source, song, local, startAtSeconds = 0.0)
override fun setQueue(tracks: List<PlaybackTrack>, startIndex: Int, startAtSeconds: Double) {
if (tracks.isEmpty()) return
this.tracks = tracks
index = startIndex.coerceIn(tracks.indices)
playIndex(index, startAtSeconds)
}
private fun start(source: String, song: Song, local: Boolean, startAtSeconds: Double) {
override fun appendToQueue(tracks: List<PlaybackTrack>) {
this.tracks = this.tracks + tracks
}
override fun moveInQueue(fromIndex: Int, toIndex: Int) {
if (fromIndex !in tracks.indices || toIndex !in tracks.indices || fromIndex == toIndex) return
val moved = tracks.toMutableList()
val item = moved.removeAt(fromIndex)
moved.add(toIndex, item)
tracks = moved
if (index == fromIndex) {
index = toIndex
} else if (fromIndex < index && toIndex >= index) {
index -= 1
} else if (fromIndex > index && toIndex <= index) {
index += 1
}
}
override fun removeAt(index: Int) {
if (index !in tracks.indices) return
tracks = tracks.filterIndexed { i, _ -> i != index }
if (index < this.index) this.index = (this.index - 1).coerceAtLeast(0)
}
override fun playIndex(index: Int, startAtSeconds: Double) {
val track = tracks.getOrNull(index) ?: return
this.index = index
currentTrack = track
gain = track.gainDb?.let { 10.0.pow(it / 20.0).toFloat() }?.coerceIn(0f, 2f) ?: 1f
start(track, startAtSeconds)
}
override fun skipToNext() {
if (index + 1 < tracks.size) {
playIndex(index + 1)
} else {
finished = true
stop()
}
}
override fun skipToPrevious(restartAfterSeconds: Double) {
if (positionSeconds() > restartAfterSeconds || index == 0) {
seekTo(0.0)
} else {
playIndex(index - 1)
}
}
override fun currentIndex(): Int = index
override fun queueSize(): Int = tracks.size
private fun start(track: PlaybackTrack, startAtSeconds: Double) {
stop()
finished = false
paused = false
stopped = false
framesRead = 0
baseSeconds = startAtSeconds.coerceAtLeast(0.0)
duration = song.duration.toDouble()
duration = track.song.duration.toDouble()
val source = track.source
val local = track.local
val requestSource = if (!local && startAtSeconds > 0) {
withTimeOffset(source, startAtSeconds)
} else {
@@ -102,6 +152,7 @@ class DesktopAudioPlayer : AudioPlayer {
val info = javax.sound.sampled.DataLine.Info(SourceDataLine::class.java, audio.format)
val dataLine = AudioSystem.getLine(info) as SourceDataLine
dataLine.open(audio.format)
applyGain(dataLine)
dataLine.start()
line = dataLine
@@ -133,6 +184,14 @@ class DesktopAudioPlayer : AudioPlayer {
}
}
private fun applyGain(dataLine: SourceDataLine) {
val control = runCatching {
dataLine.getControl(FloatControl.Type.MASTER_GAIN) as FloatControl
}.getOrNull() ?: return
val db = 20.0 * kotlin.math.log10(gain.coerceAtLeast(0.0001f).toDouble())
control.value = db.coerceIn(control.minimum.toDouble(), control.maximum.toDouble()).toFloat()
}
private fun skipPcm(audio: AudioInputStream, seconds: Double) {
var remaining = (seconds * frameRate * frameSize).toLong().coerceAtLeast(0L)
val buffer = ByteArray(16 * 1024)
@@ -192,15 +251,15 @@ class DesktopAudioPlayer : AudioPlayer {
override val canSeek: Boolean = true
override fun seekTo(seconds: Double) {
val source = currentSource ?: return
val song = currentSong ?: return
val track = currentTrack ?: return
val wasPaused = paused
start(source, song, currentLocal, seconds.coerceAtLeast(0.0))
start(track, seconds.coerceAtLeast(0.0))
if (wasPaused) pause()
}
override fun release() {
stop()
tracks = emptyList()
}
/** Adds the server's `timeOffset` parameter, replacing an earlier one. */
@@ -124,3 +124,5 @@ class DesktopStorage : AppStorage {
actual fun decodeImage(bytes: ByteArray): ImageBitmap? =
runCatching { org.jetbrains.skia.Image.makeFromEncoded(bytes).toComposeImageBitmap() }.getOrNull()
actual fun isUnmeteredNetwork(): Boolean = true
@@ -47,3 +47,5 @@ actual fun PlatformBackHandler(enabled: Boolean, onBack: () -> Unit) {
actual fun decodeImage(bytes: ByteArray): ImageBitmap? =
runCatching { org.jetbrains.skia.Image.makeFromEncoded(bytes).toComposeImageBitmap() }.getOrNull()
actual fun isUnmeteredNetwork(): Boolean = true
@@ -1,10 +1,15 @@
package win.taptap.musicmanager.client
import kotlinx.browser.document
import kotlin.math.pow
import org.w3c.dom.HTMLAudioElement
import win.taptap.musicmanager.client.api.Song
import kotlinx.browser.document
import win.taptap.musicmanager.client.playback.AudioPlayer
import win.taptap.musicmanager.client.playback.PlaybackTrack
/**
* Browser playback. The queue lives here like on the other targets; the store
* advances at the end because HTMLAudioElement has one source at a time.
*/
class WebAudioPlayer : AudioPlayer {
private val audio: HTMLAudioElement =
@@ -12,17 +17,72 @@ class WebAudioPlayer : AudioPlayer {
preload = "auto"
}
override fun play(
source: String,
song: Song,
local: Boolean,
artworkUri: String?,
artworkBytes: ByteArray?,
) {
audio.src = source
private var tracks: List<PlaybackTrack> = emptyList()
private var index = 0
private var gain = 1.0
override fun setQueue(tracks: List<PlaybackTrack>, startIndex: Int, startAtSeconds: Double) {
if (tracks.isEmpty()) return
this.tracks = tracks
index = startIndex.coerceIn(tracks.indices)
playIndex(index, startAtSeconds)
}
override fun appendToQueue(tracks: List<PlaybackTrack>) {
this.tracks = this.tracks + tracks
}
override fun moveInQueue(fromIndex: Int, toIndex: Int) {
if (fromIndex !in tracks.indices || toIndex !in tracks.indices || fromIndex == toIndex) return
val moved = tracks.toMutableList()
val item = moved.removeAt(fromIndex)
moved.add(toIndex, item)
tracks = moved
if (index == fromIndex) {
index = toIndex
} else if (fromIndex < index && toIndex >= index) {
index -= 1
} else if (fromIndex > index && toIndex <= index) {
index += 1
}
}
override fun removeAt(index: Int) {
if (index !in tracks.indices) return
tracks = tracks.filterIndexed { i, _ -> i != index }
if (index < this.index) this.index = (this.index - 1).coerceAtLeast(0)
}
override fun playIndex(index: Int, startAtSeconds: Double) {
val track = tracks.getOrNull(index) ?: return
this.index = index
gain = track.gainDb?.let { 10.0.pow(it / 20.0) }?.coerceIn(0.0, 1.0) ?: 1.0
audio.volume = gain
audio.src = track.source
if (startAtSeconds > 0) audio.currentTime = startAtSeconds
audio.play()
}
override fun skipToNext() {
if (index + 1 < tracks.size) {
playIndex(index + 1)
} else {
audio.pause()
}
}
override fun skipToPrevious(restartAfterSeconds: Double) {
if (positionSeconds() > restartAfterSeconds || index == 0) {
seekTo(0.0)
} else {
playIndex(index - 1)
}
}
override fun currentIndex(): Int = index
override fun queueSize(): Int = tracks.size
override fun pause() {
audio.pause()
}
@@ -54,5 +114,6 @@ class WebAudioPlayer : AudioPlayer {
override fun release() {
stop()
tracks = emptyList()
}
}
+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`).