Compare commits
26
Commits
8f94bb18e7
...
v0.3.2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e28e95fa2b | ||
|
|
2478505dba | ||
|
|
957ee3eb4b | ||
|
|
cfab559e5e | ||
|
|
a63ee62673 | ||
|
|
3b40726edb | ||
|
|
96ab25a91d | ||
|
|
c896f81306 | ||
|
|
7ed518b047 | ||
|
|
6bfa12d673 | ||
|
|
375bcc9c37 | ||
|
|
dc270f863c | ||
|
|
1bb23901eb | ||
|
|
d9976a62bd | ||
|
|
0491c78c7f | ||
|
|
c53ed0a1b8 | ||
|
|
67414b5986 | ||
|
|
9b105b3925 | ||
|
|
43bd9629d3 | ||
|
|
14bebced10 | ||
|
|
17bda94bfc | ||
|
|
c0ff586686 | ||
|
|
dc719f3e1a | ||
|
|
2234192dc7 | ||
|
|
c7c1d59b70 | ||
|
|
f8953fb200 |
No files matched your search
@@ -22,6 +22,20 @@ jobs:
|
||||
image: gitea.tap-tap.win/taptap/audiomanager-client-ci:3
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
# The app targets API 36, which Play requires for new uploads. The CI
|
||||
# image still ships API 35, so install 36 on demand until it is rebuilt.
|
||||
- name: Ensure Android SDK 36
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ ! -d "$ANDROID_HOME/platforms/android-36" ]; then
|
||||
# stdin is already covered by the image's accepted licenses; do not
|
||||
# pipe `yes` here, it dies with SIGPIPE and fails under pipefail.
|
||||
"$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --install \
|
||||
"platforms;android-36" "build-tools;36.0.0" </dev/null >/dev/null
|
||||
fi
|
||||
|
||||
- name: Test and build
|
||||
run: |
|
||||
@@ -58,3 +72,48 @@ jobs:
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: scripts/publish-release.sh dist
|
||||
|
||||
play:
|
||||
# Publish tagged builds to the Google Play internal testing track.
|
||||
# Requires the repository secrets listed in README.md.
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
needs: [build]
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
container:
|
||||
image: gitea.tap-tap.win/taptap/audiomanager-client-ci:3
|
||||
env:
|
||||
ANDROID_KEYSTORE_PATH: /tmp/upload-keystore.jks
|
||||
ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
|
||||
ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
|
||||
ANDROID_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }}
|
||||
# GPP reads the JSON contents from this variable; nothing is written to
|
||||
# the repository.
|
||||
ANDROID_PUBLISHER_CREDENTIALS: ${{ secrets.PLAY_SERVICE_ACCOUNT_JSON }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Ensure Android SDK 36
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ ! -d "$ANDROID_HOME/platforms/android-36" ]; then
|
||||
"$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --install \
|
||||
"platforms;android-36" "build-tools;36.0.0" </dev/null >/dev/null
|
||||
fi
|
||||
|
||||
- name: Decode the upload keystore
|
||||
env:
|
||||
ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
printf '%s' "$ANDROID_KEYSTORE_BASE64" | base64 -d > "$ANDROID_KEYSTORE_PATH"
|
||||
chmod 600 "$ANDROID_KEYSTORE_PATH"
|
||||
|
||||
- name: Publish to internal testing
|
||||
run: |
|
||||
set -euo pipefail
|
||||
export VERSION_NAME="${GITHUB_REF#refs/tags/v}"
|
||||
gradle :composeApp:publishBundle --console=plain
|
||||
@@ -7,3 +7,5 @@ local.properties
|
||||
.DS_Store
|
||||
.kotlin/
|
||||
node_modules/
|
||||
*.jks
|
||||
*.keystore
|
||||
@@ -1,34 +1,88 @@
|
||||
# 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
|
||||
|
||||
| Target | UI | Playback | Offline downloads |
|
||||
| --- | --- | --- | --- |
|
||||
| **Android** | Compose Multiplatform | Media3 / ExoPlayer | Yes |
|
||||
| **Desktop (JVM)** | Compose Multiplatform | MP3SPI + `SourceDataLine` | Yes |
|
||||
| **Desktop (JVM)** | Compose Multiplatform | MP3SPI, decoded to PCM + `SourceDataLine` | Yes |
|
||||
| **Web (Wasm)** | Compose Multiplatform | HTML5 `Audio` | Browser-managed cache only |
|
||||
|
||||
The shared module contains the API client, session/cache storage, radio queue, app state and all screens. Platform code is limited to HTTP engines, storage, audio and back handling.
|
||||
|
||||
## Features
|
||||
|
||||
- Login with a server URL, username and password. The server returns a revocable bearer token.
|
||||
- Mood grid with live counts; create, rename, delete and edit moods.
|
||||
- Seed management: search the owner's music, add or remove anchors.
|
||||
- Server-driven radio: the app keeps a small queue and asks for more from the same mood session.
|
||||
- Playback events are reported automatically (`started`, `completed`, `skipped`) so the server learns.
|
||||
- Login with a server URL, username and password. The server returns a revocable
|
||||
bearer token.
|
||||
- **Moods** are the only content model. Each user sees only their own moods.
|
||||
- **Songs** belong to the mood's permanent collection. A mood needs at least one
|
||||
song before it can play.
|
||||
- **Search Deezer or YouTube Music** from inside a mood or globally with a mood
|
||||
picker. Each mood has a **Download source** selector; search, recommendations
|
||||
and downloads follow it. Tracks over 10 minutes are hidden. Results that are already downloaded are marked and
|
||||
add instantly; other videos are queued for server-side download.
|
||||
- **Paste a YouTube URL** to add a specific video.
|
||||
- **Recommendations** are downloaded automatically and play in the radio without
|
||||
being permanent. Rows show the download state with:
|
||||
- Add to mood;
|
||||
- Not interested (permanent for the mood);
|
||||
- Retry for failed downloads.
|
||||
- **Radio** mixes the collection and ready recommendations using the mood's
|
||||
`collectionPercent`. The app keeps a small queue and asks for more from the
|
||||
same mood session.
|
||||
- Playback events are reported automatically (`started`, `completed`, `skipped`)
|
||||
so the server learns.
|
||||
- Two add-to-mood actions in the player:
|
||||
- **Add to current mood** (the mood of the active radio session)
|
||||
- **Choose another mood** (picker)
|
||||
- Library search and playback.
|
||||
- Offline library cache: moods, songs and the last sync revision are stored locally. When the server is unreachable, downloaded tracks still play.
|
||||
- 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.
|
||||
- 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;
|
||||
add-to-mood actions moved into the overflow menu.
|
||||
- **Scrubbing**: the progress slider can be dragged on every platform. Android and
|
||||
web seek natively; desktop restarts the decoder at the requested position.
|
||||
- **Mood settings**: name, description, discovery hint, genres, collection share,
|
||||
active recommendation count (0–30), and refresh interval.
|
||||
- **Downloads** screen for device-side copies: play, delete, clear, storage
|
||||
usage.
|
||||
- **Sleep timer** (15/30/45/60/90 minutes) that pauses playback. On Android the
|
||||
pause is scheduled inside the media service, so it still fires when the app is
|
||||
backgrounded or the task is swiped away.
|
||||
- Mood cache: moods and details are stored locally so the app opens instantly
|
||||
and can show cached data offline.
|
||||
- The play queue and current track are saved locally, so a restart reopens the
|
||||
player paused and resumes on the next tap.
|
||||
- Reconnects automatically with exponential backoff (15s to 5min) while offline.
|
||||
- Session persistence: the login survives app restarts until the token is
|
||||
revoked or expires.
|
||||
- Android background playback through a Media3 `MediaSessionService`:
|
||||
notification, lock-screen and headset controls, audio focus, and playback that
|
||||
survives the app being backgrounded or the task being swiped away.
|
||||
|
||||
## Screens
|
||||
|
||||
`Moods | Mood Detail | Search | Downloads | Settings`
|
||||
|
||||
- **Moods** — grid with song and pick counts, create, global search.
|
||||
- **Mood Detail** — songs, add music, recommendations, next batch, settings.
|
||||
- **Search** — mood picker, source selector, catalog search, paste URL,
|
||||
downloaded badges and an inline Downloading… / Added / Failed status per
|
||||
result, so the keyboard never hides the feedback.
|
||||
- **Downloads** — offline files and storage usage.
|
||||
- **Settings** — account, server URL, offline storage, sign out.
|
||||
|
||||
There is no Library tab, no Longform tab and no global shuffle.
|
||||
|
||||
## Project layout
|
||||
|
||||
@@ -36,28 +90,32 @@ 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
|
||||
|-- src/wasmJsMain/ # Compose viewport, HTML audio, localStorage
|
||||
|-- src/commonTest/ # API parsing and cache tests
|
||||
|-- src/commonTest/ # API, cache and store tests
|
||||
|-- src/desktopTest/ # MP3 decoding and PCM conversion tests
|
||||
`-- ci/ # Android SDK CI image
|
||||
```
|
||||
|
||||
## Build
|
||||
|
||||
Requirements: JDK 21, Android SDK 35 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 35 with build-tools 35.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 35 and build-tools 35.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
|
||||
@@ -80,21 +138,95 @@ 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)
|
||||
|
||||
The application id `win.tap_tap.audiomanager.client` is fixed after the first
|
||||
upload. Google Play requires new apps to target API 36, and every upload needs a
|
||||
higher `versionCode`.
|
||||
|
||||
### 1. Upload key (once)
|
||||
|
||||
Play App Signing keeps the real signing key; this project only needs an upload
|
||||
key. Create it and store the keystore plus both passwords in a password manager:
|
||||
|
||||
```bash
|
||||
keytool -genkeypair -v -keystore upload-keystore.jks -storetype PKCS12 \
|
||||
-alias upload -keyalg RSA -keysize 4096 -validity 10000
|
||||
```
|
||||
|
||||
Add the values to `local.properties` (git-ignored) or export them in CI:
|
||||
|
||||
```properties
|
||||
UPLOAD_STORE_FILE=/absolute/path/upload-keystore.jks
|
||||
UPLOAD_STORE_PASSWORD=...
|
||||
UPLOAD_KEY_ALIAS=upload
|
||||
UPLOAD_KEY_PASSWORD=...
|
||||
```
|
||||
|
||||
CI equivalents: `ANDROID_KEYSTORE_PATH`, `ANDROID_KEYSTORE_PASSWORD`,
|
||||
`ANDROID_KEY_ALIAS`, `ANDROID_KEY_PASSWORD`.
|
||||
|
||||
### 2. Build the bundle
|
||||
|
||||
```bash
|
||||
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.
|
||||
|
||||
### 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**.
|
||||
|
||||
### 4. Automated uploads
|
||||
|
||||
Tagged builds (`v*`) publish to internal testing from CI. The Gitea secrets are:
|
||||
|
||||
| Secret | Value |
|
||||
| --- | --- |
|
||||
| `ANDROID_KEYSTORE_BASE64` | `base64 -w0 upload-keystore.jks` |
|
||||
| `ANDROID_KEYSTORE_PASSWORD` | keystore password |
|
||||
| `ANDROID_KEY_ALIAS` | `upload` |
|
||||
| `ANDROID_KEY_PASSWORD` | key password |
|
||||
| `PLAY_SERVICE_ACCOUNT_JSON` | contents of the service account JSON |
|
||||
|
||||
Then `git tag v0.3.2 && 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.
|
||||
|
||||
## 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 token, refresh token, logout.
|
||||
- **Library sync** — first launch pages through `/library/songs`; later launches use the `since` delta and tombstones.
|
||||
- **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.
|
||||
- **Auth** — restore the saved token on launch and log out.
|
||||
- **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
|
||||
|
||||
@@ -109,14 +241,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:2`. The image has the Android SDK installed and a warmed Gradle dependency cache, so jobs do not download either on every run.
|
||||
`.gitea/workflows/ci.yaml` runs on Gitea Actions using
|
||||
`gitea.tap-tap.win/taptap/audiomanager-client-ci:3`. The image has the Android
|
||||
SDK, Node, Yarn and a warmed Gradle dependency cache.
|
||||
|
||||
- **main / PR:** run `desktopTest`, build the Android APK and the *development* Wasm bundle. The optimized Wasm build is CPU-bound and reserved for releases.
|
||||
- **`v*` tag:** additionally build the desktop fat jar and the optimized Wasm bundle, then attach all three to the Gitea release.
|
||||
- **main / PR:** run `desktopTest`, build the Android APK and the *development*
|
||||
Wasm bundle.
|
||||
- **`v*` tag:** additionally build the desktop fat jar and the optimized Wasm
|
||||
bundle, attach the artifacts to the Gitea release, and publish the AAB to Play
|
||||
internal testing.
|
||||
|
||||
Rebuild the CI image after changing `ci/Dockerfile` or dependency versions:
|
||||
|
||||
@@ -124,12 +262,23 @@ Rebuild the CI image after changing `ci/Dockerfile` or dependency versions:
|
||||
scripts/build-ci-image.sh 3
|
||||
```
|
||||
|
||||
The image build performs one warm-up compile (`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 cannot seek (sequential decoder); pause/resume and skipping work.
|
||||
- Web downloads are disabled because the browser owns its storage; the app still streams and caches metadata.
|
||||
- YT Music recommendations are displayed when the server provides them; discovery and downloading are server-side roadmap items.
|
||||
- The media notification exposes play/pause and seeking. Queue actions (skip,
|
||||
add to mood) stay in the app because the mood session and its events belong to
|
||||
the server.
|
||||
- Desktop playback supports seeking by reopening the decoder at the requested
|
||||
position. MP3s are decoded to 16-bit PCM before the line is opened, because
|
||||
Java Sound has no line for the compressed format.
|
||||
- Web downloads are disabled because the browser owns its storage; the app still
|
||||
streams and caches metadata.
|
||||
- Downloads store the 320 px cover next to the MP3 (`<songId>.jpg`), so the
|
||||
in-app cover and the Android notification artwork survive without the server.
|
||||
- Search and downloads depend on the server's catalogs. YouTube bot checks can
|
||||
fail a YouTube Music search (`502`) or leave a recommendation in `failed`
|
||||
with Retry. Music search resolves every result for its artist/album/duration,
|
||||
so a YouTube Music search takes roughly 10–15 seconds for ten results;
|
||||
Deezer search is much faster.
|
||||
- Deezer downloads need `DEEZER_ARL` on the server. A Free ARL is limited to
|
||||
128 kbps; Premium enables 320 kbps. The client never stores the ARL.
|
||||
- No iOS target yet. The shared module is ready for one.
|
||||
@@ -4,4 +4,5 @@ plugins {
|
||||
id("org.jetbrains.kotlin.plugin.compose") version "2.1.20" apply false
|
||||
id("org.jetbrains.compose") version "1.8.0" apply false
|
||||
id("com.android.application") version "8.9.1" apply false
|
||||
id("com.github.triplet.play") version "3.13.0" apply false
|
||||
}
|
||||
+2
-2
@@ -39,8 +39,8 @@ RUN mkdir -p "$ANDROID_HOME/cmdline-tools" \
|
||||
&& yes | "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --licenses > /dev/null \
|
||||
&& "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" \
|
||||
"platform-tools" \
|
||||
"platforms;android-35" \
|
||||
"build-tools;35.0.0" \
|
||||
"platforms;android-36" \
|
||||
"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)
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
@file:OptIn(org.jetbrains.kotlin.gradle.ExperimentalWasmDsl::class)
|
||||
|
||||
import java.util.Properties
|
||||
import com.github.triplet.gradle.androidpublisher.ReleaseStatus
|
||||
import com.github.triplet.gradle.androidpublisher.ResolutionStrategy
|
||||
import org.jetbrains.compose.desktop.application.dsl.TargetFormat
|
||||
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
||||
|
||||
@@ -9,8 +12,37 @@ plugins {
|
||||
id("org.jetbrains.compose")
|
||||
id("org.jetbrains.kotlin.plugin.compose")
|
||||
id("com.android.application")
|
||||
id("com.github.triplet.play")
|
||||
}
|
||||
|
||||
// Release signing and version numbers come from the environment in CI, or from
|
||||
// local.properties for local release builds. Nothing secret is committed:
|
||||
// local.properties is git-ignored. Without an upload key the release build
|
||||
// still works, but the AAB is unsigned and cannot be uploaded to Play.
|
||||
val localProperties = Properties().apply {
|
||||
val file = rootProject.file("local.properties")
|
||||
if (file.exists()) file.inputStream().use { load(it) }
|
||||
}
|
||||
|
||||
fun signingValue(property: String, env: String): String? =
|
||||
(System.getenv(env) ?: localProperties.getProperty(property))?.takeIf { it.isNotBlank() }
|
||||
|
||||
val uploadKeyStore = signingValue("UPLOAD_STORE_FILE", "ANDROID_KEYSTORE_PATH")?.let { rootProject.file(it) }
|
||||
val uploadKeyStorePassword = signingValue("UPLOAD_STORE_PASSWORD", "ANDROID_KEYSTORE_PASSWORD")
|
||||
val uploadKeyAlias = signingValue("UPLOAD_KEY_ALIAS", "ANDROID_KEY_ALIAS")
|
||||
val uploadKeyPassword = signingValue("UPLOAD_KEY_PASSWORD", "ANDROID_KEY_PASSWORD")
|
||||
val hasUploadKey = uploadKeyStore?.exists() == true &&
|
||||
!uploadKeyStorePassword.isNullOrEmpty() &&
|
||||
!uploadKeyAlias.isNullOrEmpty() &&
|
||||
!uploadKeyPassword.isNullOrEmpty()
|
||||
|
||||
// Play requires a strictly increasing versionCode for every upload. CI can pass
|
||||
// VERSION_CODE / VERSION_NAME (for example from the git tag).
|
||||
val appVersionCode = (System.getenv("VERSION_CODE") ?: localProperties.getProperty("VERSION_CODE") ?: "1").toInt()
|
||||
val appVersionName = System.getenv("VERSION_NAME")
|
||||
?: localProperties.getProperty("VERSION_NAME")
|
||||
?: "0.3.2"
|
||||
|
||||
kotlin {
|
||||
androidTarget {
|
||||
compilerOptions {
|
||||
@@ -47,6 +79,7 @@ kotlin {
|
||||
implementation("io.ktor:ktor-serialization-kotlinx-json:3.1.2")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.1")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.8.0")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.6.2")
|
||||
}
|
||||
|
||||
commonTest.dependencies {
|
||||
@@ -84,14 +117,39 @@ kotlin {
|
||||
|
||||
android {
|
||||
namespace = "win.taptap.musicmanager.client"
|
||||
compileSdk = 35
|
||||
// Google Play requires new apps and updates to target API 36 from
|
||||
// 31 August 2026.
|
||||
compileSdk = 36
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "win.taptap.musicmanager.client"
|
||||
// The package name shown in Play Console. It is permanent after the
|
||||
// first upload. The Kotlin package/namespace stays as-is: the manifest
|
||||
// and generated R/BuildConfig classes use the namespace, Play uses the
|
||||
// application id.
|
||||
applicationId = "win.tap_tap.audiomanager.client"
|
||||
minSdk = 26
|
||||
targetSdk = 35
|
||||
versionCode = 1
|
||||
versionName = "0.1.0"
|
||||
targetSdk = 36
|
||||
versionCode = appVersionCode
|
||||
versionName = appVersionName
|
||||
}
|
||||
|
||||
signingConfigs {
|
||||
if (hasUploadKey) {
|
||||
create("release") {
|
||||
storeFile = uploadKeyStore
|
||||
storePassword = uploadKeyStorePassword
|
||||
keyAlias = uploadKeyAlias
|
||||
keyPassword = uploadKeyPassword
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
if (hasUploadKey) signingConfig = signingConfigs.getByName("release")
|
||||
isMinifyEnabled = false
|
||||
isShrinkResources = false
|
||||
}
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
@@ -106,6 +164,17 @@ android {
|
||||
}
|
||||
}
|
||||
|
||||
play {
|
||||
// Upload the release AAB to the internal testing track. Credentials are
|
||||
// never committed: CI sets ANDROID_PUBLISHER_CREDENTIALS, and local runs
|
||||
// can use the same variable or PLAY_SERVICE_ACCOUNT_JSON in local.properties.
|
||||
track.set("internal")
|
||||
defaultToAppBundles.set(true)
|
||||
releaseStatus.set(ReleaseStatus.COMPLETED)
|
||||
// Ask Play for the next free version code instead of hand-bumping it.
|
||||
resolutionStrategy.set(ResolutionStrategy.AUTO)
|
||||
}
|
||||
|
||||
compose.desktop {
|
||||
application {
|
||||
mainClass = "win.taptap.musicmanager.client.MainKt"
|
||||
|
||||
+43
-7
@@ -3,6 +3,7 @@ package win.taptap.musicmanager.client
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.media3.common.MediaItem
|
||||
import androidx.media3.common.MediaMetadata
|
||||
@@ -20,7 +21,7 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
|
||||
|
||||
private val appContext = context.applicationContext
|
||||
private var controller: MediaController? = null
|
||||
private var pending: ((MediaController) -> Unit)? = null
|
||||
private val pending = ArrayDeque<(MediaController) -> Unit>()
|
||||
private var connected = false
|
||||
|
||||
@Volatile private var finished = false
|
||||
@@ -44,15 +45,23 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
|
||||
controller = sessionController
|
||||
sessionController.addListener(listener)
|
||||
connected = true
|
||||
pending?.invoke(sessionController)
|
||||
pending = null
|
||||
val queued = synchronized(pending) {
|
||||
pending.toList().also { pending.clear() }
|
||||
}
|
||||
queued.forEach { action -> runCatching { action(sessionController) } }
|
||||
}
|
||||
},
|
||||
ContextCompat.getMainExecutor(appContext),
|
||||
)
|
||||
}
|
||||
|
||||
override fun play(source: String, song: Song, local: Boolean, artworkUri: String?) {
|
||||
override fun play(
|
||||
source: String,
|
||||
song: Song,
|
||||
local: Boolean,
|
||||
artworkUri: String?,
|
||||
artworkBytes: ByteArray?,
|
||||
) {
|
||||
finished = false
|
||||
withController { controller ->
|
||||
val uri = if (local) Uri.fromFile(java.io.File(source)) else Uri.parse(source)
|
||||
@@ -60,7 +69,16 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
|
||||
.setTitle(song.title)
|
||||
.setArtist(song.artist)
|
||||
.setAlbumTitle(song.album)
|
||||
.setArtworkUri(artworkUri?.let(Uri::parse))
|
||||
.apply {
|
||||
if (artworkBytes != null && artworkBytes.isNotEmpty()) {
|
||||
setArtworkData(
|
||||
artworkBytes,
|
||||
MediaMetadata.PICTURE_TYPE_FRONT_COVER,
|
||||
)
|
||||
} else {
|
||||
setArtworkUri(artworkUri?.let(Uri::parse))
|
||||
}
|
||||
}
|
||||
.build()
|
||||
val item = MediaItem.Builder()
|
||||
.setUri(uri)
|
||||
@@ -108,12 +126,28 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
|
||||
withController { it.seekTo((seconds * 1000).toLong().coerceAtLeast(0L)) }
|
||||
}
|
||||
|
||||
override fun setSkipCallbacks(onNext: (() -> Unit)?, onPrevious: (() -> Unit)?) {
|
||||
PlaybackCommands.onNext = onNext
|
||||
PlaybackCommands.onPrevious = onPrevious
|
||||
}
|
||||
|
||||
override fun scheduleSleepTimer(seconds: Long?): Boolean {
|
||||
val args = Bundle().apply { putLong(SLEEP_TIMER_SECONDS, seconds ?: 0L) }
|
||||
val send: (MediaController) -> Boolean = { current ->
|
||||
runCatching { current.sendCustomCommand(SLEEP_TIMER_COMMAND, args) }.isSuccess
|
||||
}
|
||||
val current = controller
|
||||
if (current != null && connected) return send(current)
|
||||
synchronized(pending) { pending.addLast { controller -> send(controller) } }
|
||||
return true
|
||||
}
|
||||
|
||||
override fun release() {
|
||||
controller?.release()
|
||||
MediaController.releaseFuture(future)
|
||||
controller = null
|
||||
connected = false
|
||||
pending = null
|
||||
synchronized(pending) { pending.clear() }
|
||||
}
|
||||
|
||||
private fun withController(block: (MediaController) -> Unit) {
|
||||
@@ -121,7 +155,9 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
|
||||
if (current != null && connected) {
|
||||
block(current)
|
||||
} else {
|
||||
pending = block
|
||||
// The first playback request can be followed immediately by a seek
|
||||
// (long-form resume). Keep every action, not only the last one.
|
||||
synchronized(pending) { pending.addLast(block) }
|
||||
}
|
||||
}
|
||||
}
|
||||
+58
-2
@@ -6,6 +6,7 @@ import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import io.ktor.client.engine.HttpClientEngine
|
||||
import io.ktor.client.engine.okhttp.OkHttp
|
||||
import io.ktor.utils.io.readAvailable
|
||||
import java.io.File
|
||||
import win.taptap.musicmanager.client.data.AppStorage
|
||||
import win.taptap.musicmanager.client.playback.AudioPlayer
|
||||
@@ -32,7 +33,7 @@ class AndroidStorage(context: Context) : AppStorage {
|
||||
|
||||
override fun write(name: String, text: String) {
|
||||
root.mkdirs()
|
||||
File(root, name).writeText(text)
|
||||
atomicWrite(File(root, name)) { it.writeText(text) }
|
||||
}
|
||||
|
||||
override fun delete(name: String) {
|
||||
@@ -42,13 +43,53 @@ class AndroidStorage(context: Context) : AppStorage {
|
||||
override fun saveDownload(songId: String, bytes: ByteArray): String? {
|
||||
downloads.mkdirs()
|
||||
val file = File(downloads, "${safeName(songId)}.mp3")
|
||||
file.writeBytes(bytes)
|
||||
atomicWrite(file) { it.writeBytes(bytes) }
|
||||
return file.absolutePath
|
||||
}
|
||||
|
||||
override suspend fun saveDownloadStream(
|
||||
songId: String,
|
||||
source: io.ktor.utils.io.ByteReadChannel,
|
||||
): String? {
|
||||
downloads.mkdirs()
|
||||
val target = File(downloads, "${safeName(songId)}.mp3")
|
||||
val temp = File(downloads, "${safeName(songId)}.mp3.part")
|
||||
try {
|
||||
temp.outputStream().use { output ->
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
while (true) {
|
||||
val read = source.readAvailable(buffer)
|
||||
if (read < 0) break
|
||||
if (read > 0) output.write(buffer, 0, read)
|
||||
}
|
||||
output.flush()
|
||||
}
|
||||
if (temp.length() == 0L) error("empty download")
|
||||
if (!temp.renameTo(target)) {
|
||||
temp.copyTo(target, overwrite = true)
|
||||
temp.delete()
|
||||
}
|
||||
return target.absolutePath
|
||||
} catch (t: Throwable) {
|
||||
temp.delete()
|
||||
throw t
|
||||
}
|
||||
}
|
||||
|
||||
override fun downloadPath(songId: String): String? =
|
||||
File(downloads, "${safeName(songId)}.mp3").takeIf { it.isFile }?.absolutePath
|
||||
|
||||
override fun saveArtwork(songId: String, bytes: ByteArray): String? {
|
||||
if (bytes.isEmpty()) return null
|
||||
downloads.mkdirs()
|
||||
val file = File(downloads, "${safeName(songId)}.jpg")
|
||||
atomicWrite(file) { it.writeBytes(bytes) }
|
||||
return file.absolutePath
|
||||
}
|
||||
|
||||
override fun artworkBytes(songId: String): ByteArray? =
|
||||
File(downloads, "${safeName(songId)}.jpg").takeIf { it.isFile }?.readBytes()
|
||||
|
||||
override fun listDownloads(): Map<String, Long> =
|
||||
downloads.listFiles()
|
||||
?.filter { it.isFile && it.extension == "mp3" }
|
||||
@@ -57,11 +98,26 @@ class AndroidStorage(context: Context) : AppStorage {
|
||||
|
||||
override fun deleteDownload(songId: String) {
|
||||
File(downloads, "${safeName(songId)}.mp3").delete()
|
||||
File(downloads, "${safeName(songId)}.jpg").delete()
|
||||
}
|
||||
|
||||
override fun storageUsedBytes(): Long =
|
||||
downloads.listFiles()?.sumOf { it.length() } ?: 0L
|
||||
|
||||
private fun atomicWrite(target: File, write: (File) -> Unit) {
|
||||
val temp = File(target.parentFile, "${target.name}.part")
|
||||
try {
|
||||
write(temp)
|
||||
if (!temp.renameTo(target)) {
|
||||
temp.copyTo(target, overwrite = true)
|
||||
temp.delete()
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
temp.delete()
|
||||
throw t
|
||||
}
|
||||
}
|
||||
|
||||
private fun safeName(songId: String): String =
|
||||
songId.map { if (it.isLetterOrDigit() || it == '-' || it == '_') it else '_' }.joinToString("")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package win.taptap.musicmanager.client
|
||||
|
||||
/**
|
||||
* Bridge between the media session in [PlaybackService] and the queue that
|
||||
* lives in the app's store. Media3 sends headset/Bluetooth next and previous
|
||||
* here instead of seeking the single-item ExoPlayer.
|
||||
*/
|
||||
internal object PlaybackCommands {
|
||||
@Volatile
|
||||
var onNext: (() -> Unit)? = null
|
||||
|
||||
@Volatile
|
||||
var onPrevious: (() -> Unit)? = null
|
||||
|
||||
/** Returns false when no store is attached, so the default handling applies. */
|
||||
fun next(): Boolean {
|
||||
val handler = onNext ?: return false
|
||||
handler()
|
||||
return true
|
||||
}
|
||||
|
||||
fun previous(): Boolean {
|
||||
val handler = onPrevious ?: return false
|
||||
handler()
|
||||
return true
|
||||
}
|
||||
}
|
||||
+121
-1
@@ -2,11 +2,27 @@ package win.taptap.musicmanager.client
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.KeyEvent
|
||||
import androidx.core.content.IntentCompat
|
||||
import androidx.media3.common.AudioAttributes
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.ForwardingPlayer
|
||||
import androidx.media3.common.Player
|
||||
import androidx.media3.exoplayer.ExoPlayer
|
||||
import androidx.media3.session.MediaSession
|
||||
import androidx.media3.session.MediaSessionService
|
||||
import androidx.media3.session.SessionCommand
|
||||
import androidx.media3.session.SessionResult
|
||||
import com.google.common.util.concurrent.Futures
|
||||
import com.google.common.util.concurrent.ListenableFuture
|
||||
|
||||
/** Custom session command used to arm or clear the sleep timer. */
|
||||
internal const val SLEEP_TIMER_ACTION = "win.taptap.musicmanager.client.SLEEP_TIMER"
|
||||
internal const val SLEEP_TIMER_SECONDS = "seconds"
|
||||
internal val SLEEP_TIMER_COMMAND = SessionCommand(SLEEP_TIMER_ACTION, Bundle.EMPTY)
|
||||
|
||||
/**
|
||||
* Hosts playback in a foreground service so audio continues when the activity
|
||||
@@ -18,11 +34,13 @@ import androidx.media3.session.MediaSessionService
|
||||
class PlaybackService : MediaSessionService() {
|
||||
|
||||
private var mediaSession: MediaSession? = null
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val sleepTimer = Runnable { mediaSession?.player?.pause() }
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
|
||||
val player = ExoPlayer.Builder(this)
|
||||
val exoPlayer = ExoPlayer.Builder(this)
|
||||
.setAudioAttributes(
|
||||
AudioAttributes.Builder()
|
||||
.setUsage(C.USAGE_MEDIA)
|
||||
@@ -36,6 +54,44 @@ class PlaybackService : MediaSessionService() {
|
||||
setWakeMode(C.WAKE_MODE_NETWORK)
|
||||
}
|
||||
|
||||
// ExoPlayer holds one item at a time; the queue lives in the app. Advertise
|
||||
// next/previous so the notification and Android Auto show the buttons and
|
||||
// route them to the queue instead of seeking inside the single item.
|
||||
val player = object : ForwardingPlayer(exoPlayer) {
|
||||
override fun getAvailableCommands(): Player.Commands =
|
||||
super.getAvailableCommands().buildUpon()
|
||||
.addAll(
|
||||
Player.COMMAND_SEEK_TO_NEXT,
|
||||
Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM,
|
||||
Player.COMMAND_SEEK_TO_PREVIOUS,
|
||||
Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM,
|
||||
)
|
||||
.build()
|
||||
|
||||
override fun isCommandAvailable(command: Int): Boolean =
|
||||
command == Player.COMMAND_SEEK_TO_NEXT ||
|
||||
command == Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM ||
|
||||
command == Player.COMMAND_SEEK_TO_PREVIOUS ||
|
||||
command == Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM ||
|
||||
super.isCommandAvailable(command)
|
||||
|
||||
override fun seekToNext() {
|
||||
if (!PlaybackCommands.next()) super.seekToNext()
|
||||
}
|
||||
|
||||
override fun seekToNextMediaItem() {
|
||||
if (!PlaybackCommands.next()) super.seekToNextMediaItem()
|
||||
}
|
||||
|
||||
override fun seekToPrevious() {
|
||||
if (!PlaybackCommands.previous()) super.seekToPrevious()
|
||||
}
|
||||
|
||||
override fun seekToPreviousMediaItem() {
|
||||
if (!PlaybackCommands.previous()) super.seekToPreviousMediaItem()
|
||||
}
|
||||
}
|
||||
|
||||
val sessionActivity = PendingIntent.getActivity(
|
||||
this,
|
||||
0,
|
||||
@@ -45,6 +101,69 @@ class PlaybackService : MediaSessionService() {
|
||||
|
||||
mediaSession = MediaSession.Builder(this, player)
|
||||
.setSessionActivity(sessionActivity)
|
||||
.setCallback(object : MediaSession.Callback {
|
||||
override fun onConnect(
|
||||
session: MediaSession,
|
||||
controller: MediaSession.ControllerInfo,
|
||||
): MediaSession.ConnectionResult {
|
||||
val commands = MediaSession.ConnectionResult.DEFAULT_SESSION_AND_LIBRARY_COMMANDS
|
||||
.buildUpon()
|
||||
.add(SLEEP_TIMER_COMMAND)
|
||||
.build()
|
||||
return MediaSession.ConnectionResult.AcceptedResultBuilder(session)
|
||||
.setAvailableSessionCommands(commands)
|
||||
.build()
|
||||
}
|
||||
|
||||
/**
|
||||
* A headset skip must move the app's queue, not seek the one
|
||||
* item ExoPlayer holds. Returning true consumes the event.
|
||||
*/
|
||||
override fun onMediaButtonEvent(
|
||||
session: MediaSession,
|
||||
controllerInfo: MediaSession.ControllerInfo,
|
||||
intent: Intent,
|
||||
): Boolean {
|
||||
if (intent.action != Intent.ACTION_MEDIA_BUTTON) return false
|
||||
val event = IntentCompat.getParcelableExtra(
|
||||
intent,
|
||||
Intent.EXTRA_KEY_EVENT,
|
||||
KeyEvent::class.java,
|
||||
) ?: return false
|
||||
return when (event.keyCode) {
|
||||
KeyEvent.KEYCODE_MEDIA_NEXT -> when (event.action) {
|
||||
KeyEvent.ACTION_DOWN -> PlaybackCommands.next()
|
||||
KeyEvent.ACTION_UP -> true
|
||||
else -> false
|
||||
}
|
||||
|
||||
KeyEvent.KEYCODE_MEDIA_PREVIOUS -> when (event.action) {
|
||||
KeyEvent.ACTION_DOWN -> PlaybackCommands.previous()
|
||||
KeyEvent.ACTION_UP -> true
|
||||
else -> false
|
||||
}
|
||||
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCustomCommand(
|
||||
session: MediaSession,
|
||||
controller: MediaSession.ControllerInfo,
|
||||
customCommand: SessionCommand,
|
||||
args: Bundle,
|
||||
): ListenableFuture<SessionResult> {
|
||||
if (customCommand.customAction != SLEEP_TIMER_ACTION) {
|
||||
return super.onCustomCommand(session, controller, customCommand, args)
|
||||
}
|
||||
handler.removeCallbacks(sleepTimer)
|
||||
val seconds = args.getLong(SLEEP_TIMER_SECONDS, 0L)
|
||||
if (seconds > 0) {
|
||||
handler.postDelayed(sleepTimer, seconds * 1_000)
|
||||
}
|
||||
return Futures.immediateFuture(SessionResult(SessionResult.RESULT_SUCCESS))
|
||||
}
|
||||
})
|
||||
.build()
|
||||
}
|
||||
|
||||
@@ -59,6 +178,7 @@ class PlaybackService : MediaSessionService() {
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
handler.removeCallbacks(sleepTimer)
|
||||
mediaSession?.run {
|
||||
player.release()
|
||||
release()
|
||||
|
||||
@@ -5,6 +5,7 @@ import io.ktor.client.call.body
|
||||
import io.ktor.client.engine.HttpClientEngine
|
||||
import io.ktor.client.plugins.HttpTimeout
|
||||
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
|
||||
import io.ktor.client.plugins.timeout
|
||||
import io.ktor.client.request.HttpRequestBuilder
|
||||
import io.ktor.client.request.delete
|
||||
import io.ktor.client.request.get
|
||||
@@ -14,6 +15,7 @@ import io.ktor.client.request.post
|
||||
import io.ktor.client.request.setBody
|
||||
import io.ktor.client.statement.HttpResponse
|
||||
import io.ktor.client.statement.bodyAsBytes
|
||||
import io.ktor.client.statement.bodyAsChannel
|
||||
import io.ktor.http.ContentType
|
||||
import io.ktor.http.HttpHeaders
|
||||
import io.ktor.http.HttpStatusCode
|
||||
@@ -21,6 +23,7 @@ import io.ktor.http.contentType
|
||||
import io.ktor.http.encodeURLParameter
|
||||
import io.ktor.http.isSuccess
|
||||
import io.ktor.serialization.kotlinx.json.json
|
||||
import io.ktor.utils.io.ByteReadChannel
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
fun configuredHttpClient(engine: HttpClientEngine): HttpClient = HttpClient(engine) {
|
||||
@@ -40,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.
|
||||
@@ -53,6 +55,7 @@ class ApiClient(private val http: HttpClient) {
|
||||
private set
|
||||
|
||||
private val coverCache = mutableMapOf<String, ByteArray?>()
|
||||
private val imageCache = mutableMapOf<String, ByteArray?>()
|
||||
|
||||
suspend fun login(
|
||||
serverUrl: String,
|
||||
@@ -79,6 +82,11 @@ class ApiClient(private val http: HttpClient) {
|
||||
fun clear() {
|
||||
token = null
|
||||
coverCache.clear()
|
||||
imageCache.clear()
|
||||
}
|
||||
|
||||
fun close() {
|
||||
http.close()
|
||||
}
|
||||
|
||||
suspend fun me(): User = get("/me")
|
||||
@@ -114,37 +122,90 @@ 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> =
|
||||
get<RecommendationsResponse>("/moods/$moodId/recommendations").recommendations
|
||||
|
||||
suspend fun refreshRecommendations(moodId: String): MoodDetail =
|
||||
parse(
|
||||
http.post(url("/moods/$moodId/recommendations/refresh")) {
|
||||
auth()
|
||||
// yt-dlp searches a few queries in parallel; give the server room.
|
||||
timeout {
|
||||
requestTimeoutMillis = 120_000
|
||||
socketTimeoutMillis = 120_000
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun addRecommendation(moodId: String, externalId: String): RecommendationDecision =
|
||||
parse(
|
||||
http.post(url("/moods/$moodId/recommendations/$externalId/add")) {
|
||||
auth()
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun rejectRecommendation(moodId: String, externalId: String): RecommendationDecision =
|
||||
parse(
|
||||
http.post(url("/moods/$moodId/recommendations/$externalId/reject")) {
|
||||
auth()
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun retryRecommendation(moodId: String, externalId: String): MoodDetail =
|
||||
parse(
|
||||
http.post(url("/moods/$moodId/recommendations/$externalId/retry")) {
|
||||
auth()
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun preview(moodId: String, limit: Int = 20): List<Song> =
|
||||
get<SearchResponse>("/moods/$moodId/preview?limit=$limit").songs
|
||||
get<TracksResponse>("/moods/$moodId/preview?limit=$limit").songs
|
||||
|
||||
suspend fun search(query: String, limit: Int = 50): List<Song> =
|
||||
get<SearchResponse>("/library/search?q=${query.encodeURLParameter()}&limit=$limit").songs
|
||||
|
||||
suspend fun library(
|
||||
cursor: String? = null,
|
||||
since: String? = null,
|
||||
limit: Int = 500,
|
||||
scope: String = "all",
|
||||
): LibraryPage {
|
||||
val query = buildString {
|
||||
append("?limit=$limit&scope=$scope")
|
||||
cursor?.let { append("&cursor=${it.encodeURLParameter()}") }
|
||||
since?.let { append("&since=${it.encodeURLParameter()}") }
|
||||
}
|
||||
return get("/library/songs$query")
|
||||
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
|
||||
}
|
||||
},
|
||||
).results
|
||||
}
|
||||
|
||||
suspend fun startSession(moodId: String, limit: Int = 12): Session =
|
||||
@@ -191,38 +252,78 @@ class ApiClient(private val http: HttpClient) {
|
||||
|
||||
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 bytes = runCatching {
|
||||
http.get("$baseUrl/api/v1/covers/$albumId?size=$size&token=${token.orEmpty().encodeURLParameter()}")
|
||||
.bodyAsBytes()
|
||||
val result = runCatching {
|
||||
val response = http.get(
|
||||
"$baseUrl/api/v1/songs/$songId/cover?size=$size&token=${token.orEmpty().encodeURLParameter()}",
|
||||
)
|
||||
if (response.status.isSuccess()) {
|
||||
response.bodyAsBytes().takeIf { it.isNotEmpty() }
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}.getOrNull()
|
||||
val result = bytes?.takeIf { it.isNotEmpty() }
|
||||
coverCache[key] = result
|
||||
if (coverCache.size > MAX_CACHED_IMAGES) coverCache.clear()
|
||||
// Do not cache failures: a cover can appear after a download finishes.
|
||||
if (result != null) coverCache[key] = result
|
||||
return result
|
||||
}
|
||||
|
||||
suspend fun download(songId: String): ByteArray =
|
||||
http.get("$baseUrl/api/v1/songs/$songId/stream") {
|
||||
/** Remote artwork such as YT thumbnails, cached for the app's lifetime. */
|
||||
suspend fun image(url: String): ByteArray? {
|
||||
if (imageCache.containsKey(url)) return imageCache[url]
|
||||
val result = runCatching {
|
||||
val response = http.get(url)
|
||||
if (response.status.isSuccess()) {
|
||||
response.bodyAsBytes().takeIf { it.isNotEmpty() }
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}.getOrNull()
|
||||
if (imageCache.size > MAX_CACHED_IMAGES) imageCache.clear()
|
||||
if (result != null) imageCache[url] = result
|
||||
return result
|
||||
}
|
||||
|
||||
suspend fun download(songId: String): ByteArray {
|
||||
val response = downloadResponse(songId)
|
||||
return response.bodyAsBytes().takeIf { it.isNotEmpty() }
|
||||
?: throw ApiException(
|
||||
status = response.status.value,
|
||||
code = "empty_download",
|
||||
message = "The server returned an empty audio file",
|
||||
)
|
||||
}
|
||||
|
||||
/** Streams an audio download into [sink] instead of buffering it in RAM. */
|
||||
suspend fun downloadTo(
|
||||
songId: String,
|
||||
sink: suspend (ByteReadChannel) -> String?,
|
||||
): String? {
|
||||
val response = downloadResponse(songId)
|
||||
return sink(response.bodyAsChannel())
|
||||
}
|
||||
|
||||
private suspend fun downloadResponse(songId: String): HttpResponse {
|
||||
val response = http.get("$baseUrl/api/v1/songs/$songId/stream") {
|
||||
auth()
|
||||
url.parameters.append("download", "true")
|
||||
}.bodyAsBytes()
|
||||
timeout {
|
||||
requestTimeoutMillis = 6 * 60 * 60 * 1000
|
||||
socketTimeoutMillis = 60_000
|
||||
}
|
||||
}
|
||||
if (!response.status.isSuccess()) throw error(response)
|
||||
return response
|
||||
}
|
||||
|
||||
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() })
|
||||
@@ -253,6 +354,10 @@ class ApiClient(private val http: HttpClient) {
|
||||
)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val MAX_CACHED_IMAGES = 200
|
||||
}
|
||||
|
||||
private fun normalize(serverUrl: String): String {
|
||||
var value = serverUrl.trim().trimEnd('/')
|
||||
if (value.isEmpty()) value = "http://localhost:8080"
|
||||
|
||||
@@ -23,8 +23,6 @@ data class LoginRequest(
|
||||
data class User(
|
||||
val name: String,
|
||||
val admin: Boolean,
|
||||
val musicFolders: List<Int> = emptyList(),
|
||||
val longformFolders: List<Int> = emptyList(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
@@ -37,22 +35,19 @@ data class LoginResponse(
|
||||
@Serializable
|
||||
data class Song(
|
||||
val id: String,
|
||||
val source: String = "youtube",
|
||||
val externalId: String,
|
||||
val title: String,
|
||||
val artist: String,
|
||||
val album: String,
|
||||
val albumId: String,
|
||||
val trackNumber: Int? = null,
|
||||
val discNumber: Int = 1,
|
||||
val year: Int? = null,
|
||||
val album: String? = null,
|
||||
val duration: Int,
|
||||
val bitRate: Int,
|
||||
val size: Long,
|
||||
val suffix: String,
|
||||
val genres: List<String> = emptyList(),
|
||||
val folderId: Int,
|
||||
val relativePath: String,
|
||||
val updatedAt: String,
|
||||
)
|
||||
val bitRate: Int = 0,
|
||||
val size: Long = 0,
|
||||
val suffix: String = "mp3",
|
||||
val thumbnail: String? = null,
|
||||
) {
|
||||
val subtitle: String get() = album?.takeIf { it.isNotBlank() } ?: artist
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class Mood(
|
||||
@@ -61,60 +56,102 @@ data class Mood(
|
||||
val description: String? = null,
|
||||
val query: String? = null,
|
||||
val genres: List<String> = emptyList(),
|
||||
val targetSize: Int,
|
||||
val refreshHours: Int,
|
||||
val ytEnabled: Boolean,
|
||||
val source: String = "youtube",
|
||||
val collectionPercent: Int = 50,
|
||||
val recommendationPercent: Int = 50,
|
||||
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,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class Download(
|
||||
val state: String,
|
||||
val attempts: Int = 0,
|
||||
val error: String? = null,
|
||||
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,
|
||||
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 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())
|
||||
|
||||
@Serializable
|
||||
data class RecommendationDecision(
|
||||
val detail: MoodDetail,
|
||||
val recommendation: Recommendation,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class MoodsResponse(val moods: List<Mood>)
|
||||
|
||||
@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(
|
||||
@@ -157,8 +194,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(
|
||||
@@ -166,10 +216,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(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
@@ -180,9 +230,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,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
package win.taptap.musicmanager.client.data
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
import win.taptap.musicmanager.client.api.Mood
|
||||
import win.taptap.musicmanager.client.api.MoodDetail
|
||||
import win.taptap.musicmanager.client.api.Session
|
||||
import win.taptap.musicmanager.client.api.Song
|
||||
import win.taptap.musicmanager.client.api.User
|
||||
|
||||
@Serializable
|
||||
data class SessionState(
|
||||
val serverUrl: String,
|
||||
val token: String,
|
||||
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 moods: List<Mood> = emptyList(),
|
||||
val moodDetails: List<MoodDetail> = emptyList(),
|
||||
) {
|
||||
companion object {
|
||||
const val CACHE_VERSION = 3
|
||||
}
|
||||
}
|
||||
|
||||
/** The queue survives a restart so the next launch can resume where it stopped. */
|
||||
@Serializable
|
||||
data class PlaybackSnapshot(
|
||||
val session: Session? = null,
|
||||
val queue: List<Song> = emptyList(),
|
||||
val current: Song? = null,
|
||||
val history: List<Song> = emptyList(),
|
||||
val positionSeconds: Double = 0.0,
|
||||
)
|
||||
|
||||
class AppCache(private val storage: AppStorage) {
|
||||
|
||||
private val json = Json {
|
||||
ignoreUnknownKeys = true
|
||||
encodeDefaults = true
|
||||
explicitNulls = false
|
||||
}
|
||||
|
||||
fun loadSession(): SessionState? =
|
||||
read(SESSION_FILE)?.let {
|
||||
runCatching { json.decodeFromString<SessionState>(it) }.getOrNull()
|
||||
}
|
||||
|
||||
fun saveSession(session: SessionState?) {
|
||||
if (session == null) delete(SESSION_FILE) else write(SESSION_FILE, json.encodeToString(session))
|
||||
}
|
||||
|
||||
fun load(): CachedState {
|
||||
val cached = read(CACHE_FILE)?.let {
|
||||
runCatching { json.decodeFromString<CachedState>(it) }.getOrNull()
|
||||
} ?: return CachedState()
|
||||
return if (cached.version == CachedState.CACHE_VERSION) cached else CachedState()
|
||||
}
|
||||
|
||||
fun save(state: CachedState) {
|
||||
write(CACHE_FILE, json.encodeToString(state))
|
||||
}
|
||||
|
||||
fun loadPlayback(): PlaybackSnapshot? =
|
||||
read(PLAYBACK_FILE)?.let {
|
||||
runCatching { json.decodeFromString<PlaybackSnapshot>(it) }.getOrNull()
|
||||
}
|
||||
|
||||
fun savePlayback(snapshot: PlaybackSnapshot?) {
|
||||
if (snapshot == null || (snapshot.current == null && snapshot.queue.isEmpty())) {
|
||||
delete(PLAYBACK_FILE)
|
||||
} else {
|
||||
write(PLAYBACK_FILE, json.encodeToString(snapshot))
|
||||
}
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
delete(CACHE_FILE)
|
||||
delete(PLAYBACK_FILE)
|
||||
}
|
||||
|
||||
// Web storage can be blocked (Safari private mode) or full. Cache failure
|
||||
// must never prevent the app from reaching the login screen or playing.
|
||||
private fun read(name: String): String? = runCatching { storage.read(name) }.getOrNull()
|
||||
private fun write(name: String, text: String) {
|
||||
runCatching { storage.write(name, text) }
|
||||
}
|
||||
private fun delete(name: String) {
|
||||
runCatching { storage.delete(name) }
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val SESSION_FILE = "session.json"
|
||||
const val CACHE_FILE = "mood-cache.json"
|
||||
const val PLAYBACK_FILE = "playback.json"
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,13 @@ interface AppStorage {
|
||||
/** Returns a platform-specific handle for playback, or null when unsupported. */
|
||||
fun saveDownload(songId: String, bytes: ByteArray): String?
|
||||
fun downloadPath(songId: String): String?
|
||||
|
||||
/** Streams a download to disk and returns the final playback path. */
|
||||
suspend fun saveDownloadStream(songId: String, source: io.ktor.utils.io.ByteReadChannel): String? = null
|
||||
|
||||
/** Stores the cover next to the audio file so offline playback keeps artwork. */
|
||||
fun saveArtwork(songId: String, bytes: ByteArray): String?
|
||||
fun artworkBytes(songId: String): ByteArray?
|
||||
fun listDownloads(): Map<String, Long>
|
||||
fun deleteDownload(songId: String)
|
||||
fun storageUsedBytes(): Long
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
package win.taptap.musicmanager.client.data
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
import win.taptap.musicmanager.client.api.Mood
|
||||
import win.taptap.musicmanager.client.api.MoodDetail
|
||||
import win.taptap.musicmanager.client.api.Song
|
||||
import win.taptap.musicmanager.client.api.User
|
||||
|
||||
@Serializable
|
||||
data class SessionState(
|
||||
val serverUrl: String,
|
||||
val token: String,
|
||||
val user: User,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class CachedState(
|
||||
val serverUrl: String = "",
|
||||
val userName: String = "",
|
||||
val revision: String? = null,
|
||||
val songs: List<Song> = emptyList(),
|
||||
val moods: List<Mood> = emptyList(),
|
||||
val moodDetails: List<MoodDetail> = emptyList(),
|
||||
)
|
||||
|
||||
class LibraryCache(private val storage: AppStorage) {
|
||||
|
||||
private val json = Json {
|
||||
ignoreUnknownKeys = true
|
||||
encodeDefaults = true
|
||||
explicitNulls = false
|
||||
}
|
||||
|
||||
fun loadSession(): SessionState? =
|
||||
storage.read(SESSION_FILE)?.let {
|
||||
runCatching { json.decodeFromString<SessionState>(it) }.getOrNull()
|
||||
}
|
||||
|
||||
fun saveSession(session: SessionState?) {
|
||||
if (session == null) storage.delete(SESSION_FILE) else storage.write(SESSION_FILE, json.encodeToString(session))
|
||||
}
|
||||
|
||||
fun load(): CachedState =
|
||||
storage.read(CACHE_FILE)?.let {
|
||||
runCatching { json.decodeFromString<CachedState>(it) }.getOrNull()
|
||||
} ?: CachedState()
|
||||
|
||||
fun save(state: CachedState) {
|
||||
storage.write(CACHE_FILE, json.encodeToString(state))
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
storage.delete(CACHE_FILE)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val SESSION_FILE = "session.json"
|
||||
const val CACHE_FILE = "library.json"
|
||||
}
|
||||
}
|
||||
+22
-1
@@ -9,7 +9,13 @@ import win.taptap.musicmanager.client.api.Song
|
||||
* store polls [isFinished] because some backends have no callback support.
|
||||
*/
|
||||
interface AudioPlayer {
|
||||
fun play(source: String, song: Song, local: Boolean, artworkUri: String? = null)
|
||||
fun play(
|
||||
source: String,
|
||||
song: Song,
|
||||
local: Boolean,
|
||||
artworkUri: String? = null,
|
||||
artworkBytes: ByteArray? = null,
|
||||
)
|
||||
fun pause()
|
||||
fun resume()
|
||||
fun stop()
|
||||
@@ -20,5 +26,20 @@ interface AudioPlayer {
|
||||
val canSeek: Boolean
|
||||
fun seekTo(seconds: Double)
|
||||
fun release()
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
fun scheduleSleepTimer(seconds: Long?): Boolean = false
|
||||
|
||||
/**
|
||||
* Routes hardware transport buttons (headset/Bluetooth next and previous)
|
||||
* to the app's own queue. Android wires this to its MediaSession; other
|
||||
* platforms ignore it. Null clears the handlers.
|
||||
*/
|
||||
fun setSkipCallbacks(onNext: (() -> Unit)?, onPrevious: (() -> Unit)?) = Unit
|
||||
}
|
||||
|
||||
+861
-181
File diff suppressed because it is too large.
Load diff
@@ -1,18 +1,17 @@
|
||||
package win.taptap.musicmanager.client.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.ArrowBack
|
||||
import androidx.compose.material.icons.rounded.Delete
|
||||
import androidx.compose.material.icons.rounded.LibraryMusic
|
||||
import androidx.compose.material.icons.rounded.DownloadDone
|
||||
import androidx.compose.material.icons.rounded.Refresh
|
||||
import androidx.compose.material.icons.rounded.Search
|
||||
import androidx.compose.material.icons.rounded.Settings
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
@@ -138,7 +137,8 @@ private fun MainScreen(state: AppState, store: AppStore) {
|
||||
val title = when (state.screen) {
|
||||
Screen.Moods -> "Moods"
|
||||
Screen.MoodDetail -> state.selectedMood?.mood?.name ?: "Mood"
|
||||
Screen.Library -> "Library & downloads"
|
||||
Screen.Search -> "Add music"
|
||||
Screen.Downloads -> "Downloads"
|
||||
Screen.Settings -> "Settings"
|
||||
}
|
||||
Text(title, fontWeight = FontWeight.SemiBold)
|
||||
@@ -157,8 +157,11 @@ private fun MainScreen(state: AppState, store: AppStore) {
|
||||
IconButton(onClick = { store.refreshAll() }) {
|
||||
Icon(Icons.Rounded.Refresh, contentDescription = "Refresh")
|
||||
}
|
||||
IconButton(onClick = { store.openLibrary() }) {
|
||||
Icon(Icons.Rounded.LibraryMusic, contentDescription = "Library")
|
||||
IconButton(onClick = { store.openSearch() }) {
|
||||
Icon(Icons.Rounded.Search, contentDescription = "Add music")
|
||||
}
|
||||
IconButton(onClick = { store.openDownloads() }) {
|
||||
Icon(Icons.Rounded.DownloadDone, contentDescription = "Downloads")
|
||||
}
|
||||
IconButton(onClick = { store.openSettings() }) {
|
||||
Icon(Icons.Rounded.Settings, contentDescription = "Settings")
|
||||
@@ -169,7 +172,8 @@ private fun MainScreen(state: AppState, store: AppStore) {
|
||||
Icon(Icons.Rounded.Delete, contentDescription = "Delete mood")
|
||||
}
|
||||
}
|
||||
Screen.Library -> {
|
||||
Screen.Search -> Unit
|
||||
Screen.Downloads -> {
|
||||
IconButton(onClick = { store.openSettings() }) {
|
||||
Icon(Icons.Rounded.Settings, contentDescription = "Settings")
|
||||
}
|
||||
@@ -189,7 +193,8 @@ private fun MainScreen(state: AppState, store: AppStore) {
|
||||
when (state.screen) {
|
||||
Screen.Moods -> MoodsScreen(state, store)
|
||||
Screen.MoodDetail -> MoodDetailScreen(state, store)
|
||||
Screen.Library -> LibraryScreen(state, store)
|
||||
Screen.Search -> SearchScreen(state, store)
|
||||
Screen.Downloads -> DownloadsScreen(state, store)
|
||||
Screen.Settings -> SettingsScreen(state, store)
|
||||
}
|
||||
}
|
||||
@@ -200,7 +205,12 @@ private fun MainScreen(state: AppState, store: AppStore) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { confirmDelete = false },
|
||||
title = { Text("Delete mood?") },
|
||||
text = { Text("\"$name\" and its seeds will be removed. Downloads stay on this device.") },
|
||||
text = {
|
||||
Text(
|
||||
"\"$name\" and its recommendation history will be removed. " +
|
||||
"Unused downloads are deleted from the server.",
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
|
||||
@@ -50,15 +50,15 @@ import win.taptap.musicmanager.client.store.AppStore
|
||||
@Composable
|
||||
fun Cover(
|
||||
store: AppStore,
|
||||
albumId: String?,
|
||||
songId: String?,
|
||||
modifier: Modifier = Modifier,
|
||||
size: Int = 320,
|
||||
) {
|
||||
var bitmap by remember(albumId, size) { mutableStateOf<ImageBitmap?>(null) }
|
||||
var bitmap by remember(songId, size) { mutableStateOf<ImageBitmap?>(null) }
|
||||
|
||||
LaunchedEffect(albumId, size) {
|
||||
if (albumId == null) return@LaunchedEffect
|
||||
val bytes = store.cover(albumId)
|
||||
LaunchedEffect(songId, size) {
|
||||
if (songId == null) return@LaunchedEffect
|
||||
val bytes = store.cover(songId)
|
||||
bitmap = bytes?.let { data -> runCatching { decodeImage(data) }.getOrNull() }
|
||||
}
|
||||
|
||||
@@ -91,6 +91,42 @@ fun Cover(
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun RemoteImage(store: AppStore, url: String?, modifier: Modifier = Modifier) {
|
||||
var bitmap by remember(url) { mutableStateOf<ImageBitmap?>(null) }
|
||||
|
||||
LaunchedEffect(url) {
|
||||
if (url == null) return@LaunchedEffect
|
||||
bitmap = store.image(url)?.let { data -> runCatching { decodeImage(data) }.getOrNull() }
|
||||
}
|
||||
|
||||
Box(
|
||||
modifier = modifier
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(
|
||||
Brush.linearGradient(listOf(Color(0xFF28344A), Color(0xFF1A2230))),
|
||||
),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
val image = bitmap
|
||||
if (image != null) {
|
||||
Image(
|
||||
bitmap = image,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Crop,
|
||||
)
|
||||
} else {
|
||||
Icon(
|
||||
Icons.Rounded.MusicNote,
|
||||
contentDescription = null,
|
||||
tint = Color(0xFF5E6C84),
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun EmptyState(title: String, subtitle: String? = null, modifier: Modifier = Modifier) {
|
||||
Column(
|
||||
@@ -149,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,
|
||||
@@ -158,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,
|
||||
@@ -179,7 +215,7 @@ fun MoodGradient(name: String): Brush {
|
||||
Color(0xFF1864AB) to Color(0xFF1098AD),
|
||||
Color(0xFF5F3DC4) to Color(0xFF862E9C),
|
||||
)
|
||||
val palette = palettes[abs(name.hashCode()) % palettes.size]
|
||||
val palette = palettes[(name.hashCode() % palettes.size + palettes.size) % palettes.size]
|
||||
return Brush.linearGradient(listOf(palette.first, palette.second))
|
||||
}
|
||||
|
||||
@@ -241,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,
|
||||
)
|
||||
|
||||
+130
@@ -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,155 +0,0 @@
|
||||
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.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.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.PlayArrow
|
||||
import androidx.compose.material.icons.rounded.Search
|
||||
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.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.unit.dp
|
||||
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 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 },
|
||||
singleLine = true,
|
||||
label = { Text("Search library") },
|
||||
leadingIcon = { Icon(Icons.Rounded.Search, contentDescription = null) },
|
||||
trailingIcon = {
|
||||
if (state.searching) {
|
||||
CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp)
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
|
||||
if (state.searchResults.isNotEmpty()) {
|
||||
item {
|
||||
SectionTitle("Search results") {
|
||||
Text(
|
||||
"${state.searchResults.size}",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
items(state.searchResults, 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 LibrarySongRow(song: Song, state: AppState, store: AppStore, supported: Boolean) {
|
||||
SongRow(store = store, song = song, onPlay = { store.playSong(song) }) {
|
||||
if (supported) {
|
||||
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")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
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")
|
||||
}
|
||||
}
|
||||
}
|
||||
+306
-102
@@ -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,10 +17,17 @@ import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.Add
|
||||
import androidx.compose.material.icons.rounded.Close
|
||||
import androidx.compose.material.icons.rounded.Download
|
||||
import androidx.compose.material.icons.rounded.DownloadDone
|
||||
import androidx.compose.material.icons.rounded.PlayArrow
|
||||
import androidx.compose.material.icons.rounded.Refresh
|
||||
import androidx.compose.material.icons.rounded.RemoveCircleOutline
|
||||
import androidx.compose.material.icons.rounded.Search
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.FilledTonalButton
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
@@ -26,10 +35,12 @@ import androidx.compose.material3.IconButton
|
||||
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.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
@@ -39,16 +50,23 @@ 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.Song
|
||||
import kotlin.math.roundToInt
|
||||
import win.taptap.musicmanager.client.api.MoodSong
|
||||
import win.taptap.musicmanager.client.api.Recommendation
|
||||
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
|
||||
@@ -60,17 +78,31 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
|
||||
}
|
||||
|
||||
val mood = detail.mood
|
||||
var seedQuery by remember { mutableStateOf("") }
|
||||
var name by remember(mood.id, mood.changedAt) { mutableStateOf(mood.name) }
|
||||
var description by remember(mood.id, mood.changedAt) { mutableStateOf(mood.description.orEmpty()) }
|
||||
var genres by remember(mood.id, mood.changedAt) { mutableStateOf(mood.genres.joinToString(", ")) }
|
||||
var query by remember(mood.id, mood.changedAt) { mutableStateOf(mood.query.orEmpty()) }
|
||||
var target by remember(mood.id, mood.changedAt) { mutableStateOf(mood.targetSize.toString()) }
|
||||
var hours by remember(mood.id, mood.changedAt) { mutableStateOf(mood.refreshHours.toString()) }
|
||||
var yt by remember(mood.id, mood.changedAt) { mutableStateOf(mood.ytEnabled) }
|
||||
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()) }
|
||||
|
||||
val seedIds = detail.seeds.map { it.song.id }.toSet()
|
||||
val searchResults = state.searchResults.filterNot { it.id in seedIds }
|
||||
val inFlight = mood.recommendationDownloading +
|
||||
detail.recommendations.count {
|
||||
it.download?.state == "queued" || it.download?.state == "downloading"
|
||||
}
|
||||
// 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 ((inFlight > 0 || waitingForFirstBatch) && polls < 60) {
|
||||
kotlinx.coroutines.delay(5_000)
|
||||
store.refreshSelectedMood()
|
||||
polls += 1
|
||||
}
|
||||
}
|
||||
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
@@ -85,93 +117,71 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
|
||||
) {
|
||||
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Text(
|
||||
mood.description ?: "Server-driven radio",
|
||||
mood.description ?: "Your private mix",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Text("${mood.seedCount} seeds", style = MaterialTheme.typography.labelMedium)
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
Text("${mood.songCount} songs", style = MaterialTheme.typography.labelMedium)
|
||||
Text("·", color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Text("${mood.targetSize} batch", style = MaterialTheme.typography.labelMedium)
|
||||
Text(
|
||||
"${mood.collectionPercent}% collection",
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Button(onClick = { store.playMood(mood.id) }) {
|
||||
Button(onClick = { store.playMood(mood.id) }, enabled = mood.songCount > 0) {
|
||||
Icon(Icons.Rounded.PlayArrow, contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text("Play radio")
|
||||
}
|
||||
}
|
||||
if (mood.lastError != null) {
|
||||
Text(mood.lastError, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
|
||||
Text(
|
||||
mood.lastError,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
item {
|
||||
SectionTitle("Seeds") {
|
||||
SectionTitle("Songs") {
|
||||
Text(
|
||||
"${detail.seeds.size}",
|
||||
"${detail.songs.size}",
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (detail.seeds.isEmpty()) {
|
||||
if (detail.songs.isEmpty()) {
|
||||
item {
|
||||
Text(
|
||||
"No seeds yet. Add a few songs below; every seed is always part of the radio.",
|
||||
"A mood needs at least one song before it can play. Use Add music to search YouTube.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
items(detail.seeds, key = { it.song.id }) { seed ->
|
||||
SongRow(
|
||||
store = store,
|
||||
song = seed.song,
|
||||
onPlay = { store.playSong(seed.song) },
|
||||
) {
|
||||
Text(seed.origin, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
IconButton(onClick = { store.removeSeed(mood.id, seed.song.id) }) {
|
||||
Icon(Icons.Rounded.RemoveCircleOutline, contentDescription = "Remove seed")
|
||||
}
|
||||
}
|
||||
items(detail.songs, key = { it.song.id }) { entry ->
|
||||
MoodSongRow(entry, store, mood.id, downloaded = entry.song.id in state.downloads)
|
||||
}
|
||||
}
|
||||
|
||||
item {
|
||||
HorizontalDivider(Modifier.padding(vertical = 12.dp))
|
||||
SectionTitle("Add songs")
|
||||
}
|
||||
|
||||
item {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 4.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = seedQuery,
|
||||
onValueChange = { seedQuery = it },
|
||||
singleLine = true,
|
||||
label = { Text("Search your music") },
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
OutlinedButton(onClick = { store.search(seedQuery) }, enabled = seedQuery.isNotBlank()) {
|
||||
Text("Search")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (state.searching) {
|
||||
item { CircularProgressIndicator(Modifier.size(22.dp)) }
|
||||
}
|
||||
|
||||
items(searchResults.take(12), key = { it.id }) { song ->
|
||||
SongRow(store = store, song = song, onPlay = { store.playSong(song) }) {
|
||||
IconButton(onClick = { store.addSeed(mood.id, song.id) }) {
|
||||
Icon(Icons.Rounded.Add, contentDescription = "Add seed")
|
||||
FilledTonalButton(onClick = { store.openSearch(mood.id) }) {
|
||||
Icon(Icons.Rounded.Search, contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text("Add music")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -179,38 +189,68 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
|
||||
if (state.preview.isNotEmpty()) {
|
||||
item {
|
||||
HorizontalDivider(Modifier.padding(vertical = 12.dp))
|
||||
SectionTitle("Next batch")
|
||||
SectionTitle("Up next")
|
||||
Text(
|
||||
"Preview of the radio mix: these are the tracks that would play next. " +
|
||||
"Nothing here is downloaded or saved.",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
}
|
||||
items(state.preview, key = { "preview-${it.id}" }) { song ->
|
||||
SongRow(store = store, song = song, onPlay = { store.playSong(song) }) {
|
||||
SongRow(store, song, onPlay = { store.playSong(song) }) {
|
||||
Text(formatDuration(song.duration), style = MaterialTheme.typography.labelSmall)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (detail.recommendations.isNotEmpty()) {
|
||||
item {
|
||||
HorizontalDivider(Modifier.padding(vertical = 12.dp))
|
||||
SectionTitle("Recommendations")
|
||||
}
|
||||
items(detail.recommendations, key = { it.videoId }) { recommendation ->
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(recommendation.title, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
recommendation.artist,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
item {
|
||||
HorizontalDivider(Modifier.padding(vertical = 12.dp))
|
||||
SectionTitle("Recommendations") {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
if (state.discovering) {
|
||||
CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
}
|
||||
TextButton(
|
||||
onClick = { store.refreshRecommendations() },
|
||||
enabled = !state.discovering && mood.recommendationCount > 0,
|
||||
) {
|
||||
Icon(Icons.Rounded.Refresh, contentDescription = null, modifier = Modifier.size(16.dp))
|
||||
Spacer(Modifier.width(4.dp))
|
||||
Text("Refresh")
|
||||
}
|
||||
Text(recommendation.state, style = MaterialTheme.typography.labelSmall)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 and downloading picks…"
|
||||
} else {
|
||||
"No recommendations yet. The server tops this mood up automatically."
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
items(detail.recommendations, key = { "rec-${it.source}-${it.externalId}" }) { recommendation ->
|
||||
RecommendationRow(recommendation, state.discovering, store)
|
||||
}
|
||||
}
|
||||
|
||||
item {
|
||||
HorizontalDivider(Modifier.padding(vertical = 12.dp))
|
||||
SectionTitle("Settings")
|
||||
@@ -242,30 +282,90 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
|
||||
OutlinedTextField(
|
||||
value = query,
|
||||
onValueChange = { query = it },
|
||||
label = { Text("Free-text hint") },
|
||||
label = { Text("Discovery hint") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
OutlinedTextField(
|
||||
value = target,
|
||||
onValueChange = { target = it },
|
||||
label = { Text("Batch size") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
OutlinedTextField(
|
||||
value = hours,
|
||||
onValueChange = { hours = it },
|
||||
label = { Text("Refresh h") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.weight(1f),
|
||||
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,
|
||||
)
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text("YT Music discovery", Modifier.weight(1f))
|
||||
Switch(checked = yt, onCheckedChange = { yt = it })
|
||||
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
Text(
|
||||
"Collection share: ${collectionPercent.roundToInt()}% · ${100 - collectionPercent.roundToInt()}% recommendations",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
Slider(
|
||||
value = collectionPercent,
|
||||
onValueChange = { collectionPercent = it },
|
||||
valueRange = 0f..100f,
|
||||
steps = 9,
|
||||
)
|
||||
Text(
|
||||
"Each queue slot rolls this share; when one pool runs out the other fills in.",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
Text(
|
||||
"Active recommendations: ${recommendations.roundToInt()}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
Slider(
|
||||
value = recommendations,
|
||||
onValueChange = { recommendations = it },
|
||||
valueRange = 0f..30f,
|
||||
steps = 29,
|
||||
)
|
||||
Text(
|
||||
"Downloaded picks that count as active slots (0 turns discovery off).",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
OutlinedTextField(
|
||||
value = hours,
|
||||
onValueChange = { hours = it },
|
||||
label = { Text("Refresh interval (hours)") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
FilledTonalButton(
|
||||
enabled = !state.saving && name.isNotBlank(),
|
||||
onClick = {
|
||||
@@ -275,9 +375,10 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
|
||||
description = description.trim().takeIf { it.isNotEmpty() },
|
||||
genres = genres.split(',').map { it.trim() }.filter { it.isNotEmpty() },
|
||||
query = query.trim().takeIf { it.isNotEmpty() },
|
||||
targetSize = target.toIntOrNull() ?: mood.targetSize,
|
||||
source = source,
|
||||
collectionPercent = collectionPercent.roundToInt(),
|
||||
recommendationCount = recommendations.roundToInt(),
|
||||
refreshHours = hours.toIntOrNull() ?: mood.refreshHours,
|
||||
ytEnabled = yt,
|
||||
)
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
@@ -290,3 +391,106 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
|
||||
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")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RecommendationRow(
|
||||
recommendation: Recommendation,
|
||||
busy: Boolean,
|
||||
store: AppStore,
|
||||
) {
|
||||
val failed = recommendation.state == "failed" ||
|
||||
recommendation.download?.state == "failed"
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
if (recommendation.song != null) {
|
||||
Cover(store, recommendation.song.id, Modifier.size(48.dp), size = 96)
|
||||
} else {
|
||||
RemoteImage(store, recommendation.thumbnail, Modifier.size(48.dp))
|
||||
}
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
recommendation.title,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(
|
||||
buildString {
|
||||
append(recommendation.artist)
|
||||
recommendation.duration?.let { append(" · ").append(formatDuration(it)) }
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(
|
||||
when {
|
||||
failed -> "Download failed"
|
||||
recommendation.state == "ready" -> "Ready to add"
|
||||
else -> "Downloading…"
|
||||
},
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = if (failed) {
|
||||
MaterialTheme.colorScheme.error
|
||||
} else {
|
||||
MaterialTheme.colorScheme.primary
|
||||
},
|
||||
)
|
||||
if (failed && recommendation.error != null) {
|
||||
Text(
|
||||
recommendation.error,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (failed) {
|
||||
IconButton(
|
||||
onClick = { store.retryRecommendation(recommendation.externalId) },
|
||||
enabled = !busy,
|
||||
) {
|
||||
Icon(Icons.Rounded.Refresh, contentDescription = "Retry download")
|
||||
}
|
||||
} else {
|
||||
IconButton(
|
||||
onClick = { store.addRecommendation(recommendation.externalId) },
|
||||
enabled = !busy,
|
||||
) {
|
||||
Icon(Icons.Rounded.Add, contentDescription = "Add to mood")
|
||||
}
|
||||
}
|
||||
IconButton(
|
||||
onClick = { store.rejectRecommendation(recommendation.externalId) },
|
||||
enabled = !busy,
|
||||
) {
|
||||
Icon(Icons.Rounded.Close, contentDescription = "Not interested")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,11 +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.Switch
|
||||
import androidx.compose.material3.Slider
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
@@ -46,9 +49,11 @@ import androidx.compose.ui.graphics.Color
|
||||
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.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) {
|
||||
@@ -66,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,
|
||||
)
|
||||
@@ -88,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 {
|
||||
@@ -114,9 +119,18 @@ fun MoodsScreen(state: AppState, store: AppStore) {
|
||||
CreateMoodDialog(
|
||||
saving = state.saving,
|
||||
onDismiss = { creating = false },
|
||||
onCreate = { name, description, genres, query, target, hours, yt ->
|
||||
onCreate = { name, description, genres, query, source, collectionPercent, recommendations, hours ->
|
||||
creating = false
|
||||
store.createMood(name, description, genres, query, target, hours, yt)
|
||||
store.createMood(
|
||||
name,
|
||||
description,
|
||||
genres,
|
||||
query,
|
||||
source,
|
||||
collectionPercent,
|
||||
recommendations,
|
||||
hours,
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -142,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,
|
||||
@@ -151,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,
|
||||
@@ -184,15 +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) -> 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) }
|
||||
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
@@ -223,29 +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(
|
||||
"Collection share: ${collectionPercent.roundToInt()}% · ${100 - collectionPercent.roundToInt()}% recommendations",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
Slider(
|
||||
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 = {
|
||||
@@ -257,9 +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,
|
||||
)
|
||||
},
|
||||
) { Text("Create") }
|
||||
|
||||
@@ -1,46 +1,82 @@
|
||||
package win.taptap.musicmanager.client.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress
|
||||
import androidx.compose.foundation.gestures.scrollBy
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
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.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
|
||||
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.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.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
|
||||
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||
tonalElevation = 8.dp,
|
||||
modifier = Modifier.navigationBarsPadding(),
|
||||
) {
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
val progress = if (state.durationSeconds > 0) {
|
||||
@@ -48,23 +84,104 @@ fun PlayerBar(state: AppState, store: AppStore) {
|
||||
} else {
|
||||
0f
|
||||
}
|
||||
Slider(
|
||||
value = dragSeconds ?: progress,
|
||||
onValueChange = { dragSeconds = it },
|
||||
onValueChangeFinished = {
|
||||
dragSeconds?.let { store.seekTo(it * state.durationSeconds) }
|
||||
dragSeconds = null
|
||||
},
|
||||
enabled = store.canSeek(),
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),
|
||||
)
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(start = 8.dp, end = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
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,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
IconButton(onClick = { queueOpen = true }) {
|
||||
Icon(Icons.Rounded.QueueMusic, contentDescription = "Queue")
|
||||
}
|
||||
Box {
|
||||
IconButton(onClick = { moreMenu = true }) {
|
||||
Icon(Icons.Rounded.MoreVert, contentDescription = "More actions")
|
||||
}
|
||||
DropdownMenu(
|
||||
expanded = moreMenu,
|
||||
onDismissRequest = { moreMenu = false },
|
||||
) {
|
||||
DropdownMenuItem(
|
||||
text = { Text("Add to current mood") },
|
||||
leadingIcon = {
|
||||
Icon(Icons.Rounded.AddCircleOutline, contentDescription = null)
|
||||
},
|
||||
onClick = {
|
||||
moreMenu = false
|
||||
store.addCurrentToMood(null)
|
||||
},
|
||||
)
|
||||
DropdownMenuItem(
|
||||
text = { Text("Add to another mood") },
|
||||
leadingIcon = {
|
||||
Icon(Icons.Rounded.PlaylistAdd, contentDescription = null)
|
||||
},
|
||||
onClick = {
|
||||
moreMenu = false
|
||||
picker = true
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
Box {
|
||||
IconButton(onClick = { sleepMenu = true }) {
|
||||
Icon(
|
||||
Icons.Rounded.Bedtime,
|
||||
contentDescription = "Sleep timer",
|
||||
tint = if (sleepRemaining != null) {
|
||||
MaterialTheme.colorScheme.primary
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant
|
||||
},
|
||||
)
|
||||
}
|
||||
DropdownMenu(
|
||||
expanded = sleepMenu,
|
||||
onDismissRequest = { sleepMenu = false },
|
||||
) {
|
||||
listOf(15, 30, 45, 60, 90).forEach { minutes ->
|
||||
DropdownMenuItem(
|
||||
text = { Text("$minutes minutes") },
|
||||
onClick = {
|
||||
sleepMenu = false
|
||||
store.setSleepTimer(minutes)
|
||||
},
|
||||
)
|
||||
}
|
||||
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(10.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
Cover(store, song.albumId, Modifier.size(48.dp), size = 160)
|
||||
Cover(store, song.id, Modifier.size(48.dp), size = 160)
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
song.title,
|
||||
@@ -80,32 +197,60 @@ fun PlayerBar(state: AppState, store: AppStore) {
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(
|
||||
"${formatDuration(state.positionSeconds.toInt())} / ${formatDuration(state.durationSeconds.toInt())}",
|
||||
buildString {
|
||||
append(formatDuration(state.positionSeconds.toInt()))
|
||||
append(" / ")
|
||||
append(formatDuration(state.durationSeconds.toInt()))
|
||||
if (sleepRemaining != null) {
|
||||
append(" · sleep ")
|
||||
append(formatDuration(sleepRemaining.toInt()))
|
||||
}
|
||||
},
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
|
||||
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.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),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (queueOpen) {
|
||||
QueueDialog(state, store) { queueOpen = false }
|
||||
}
|
||||
|
||||
if (picker) {
|
||||
MoodPickerDialog(
|
||||
moods = state.moods,
|
||||
@@ -118,3 +263,200 @@ fun PlayerBar(state: AppState, store: AppStore) {
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit) {
|
||||
val listState = rememberLazyListState()
|
||||
var draggingIndex by remember { mutableStateOf<Int?>(null) }
|
||||
var dragPointerY by remember { mutableStateOf(0f) }
|
||||
var grabOffset by remember { mutableStateOf(0f) }
|
||||
val edgePx = with(LocalDensity.current) { 48.dp.toPx() }
|
||||
|
||||
fun queueIndexAt(y: Float): Int? =
|
||||
listState.layoutInfo.visibleItemsInfo
|
||||
.firstOrNull { y >= it.offset && y < it.offset + it.size }
|
||||
?.index
|
||||
|
||||
LaunchedEffect(draggingIndex) {
|
||||
while (draggingIndex != null) {
|
||||
val y = dragPointerY
|
||||
val edge = edgePx
|
||||
val viewport = listState.layoutInfo.viewportEndOffset.toFloat()
|
||||
if (y < edge) {
|
||||
listState.scrollBy(-18f)
|
||||
} else if (y > viewport - edge) {
|
||||
listState.scrollBy(18f)
|
||||
}
|
||||
val from = draggingIndex
|
||||
val to = queueIndexAt(y)
|
||||
if (from != null && to != null && to != from) {
|
||||
store.moveInQueue(from, to)
|
||||
draggingIndex = to
|
||||
}
|
||||
delay(16)
|
||||
}
|
||||
}
|
||||
|
||||
Dialog(onDismissRequest = onDismiss) {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(18.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
tonalElevation = 6.dp,
|
||||
modifier = Modifier.fillMaxWidth().heightIn(max = 620.dp),
|
||||
) {
|
||||
Column {
|
||||
Row(
|
||||
modifier = Modifier.padding(20.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text("Queue", style = MaterialTheme.typography.titleMedium)
|
||||
Text(
|
||||
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,
|
||||
)
|
||||
}
|
||||
TextButton(onClick = onDismiss) { Text("Close") }
|
||||
}
|
||||
HorizontalDivider()
|
||||
|
||||
state.current?.let { song ->
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 20.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
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(
|
||||
"Now playing",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
}
|
||||
HorizontalDivider()
|
||||
}
|
||||
|
||||
if (state.queue.isEmpty()) {
|
||||
Text(
|
||||
"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
|
||||
}
|
||||
Row(
|
||||
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.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.artist,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
Icon(
|
||||
Icons.Rounded.DragHandle,
|
||||
contentDescription = "Drag to reorder",
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(22.dp),
|
||||
)
|
||||
IconButton(
|
||||
onClick = {
|
||||
val from = store.state.value.queue
|
||||
.indexOfFirst { it.id == song.id }
|
||||
if (from >= 0) store.removeFromQueue(from)
|
||||
},
|
||||
) {
|
||||
Icon(Icons.Rounded.Close, contentDescription = "Remove from queue")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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}",
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+23
-23
@@ -2,19 +2,19 @@ package win.taptap.musicmanager.client.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.DeleteSweep
|
||||
import androidx.compose.material.icons.rounded.Logout
|
||||
import androidx.compose.material.icons.rounded.Refresh
|
||||
import androidx.compose.material.icons.rounded.TravelExplore
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.FilledTonalButton
|
||||
import androidx.compose.material3.Icon
|
||||
@@ -35,7 +35,7 @@ import win.taptap.musicmanager.client.store.AppStore
|
||||
fun SettingsScreen(state: AppState, store: AppStore) {
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentPadding = androidx.compose.foundation.layout.PaddingValues(20.dp),
|
||||
contentPadding = PaddingValues(20.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||
) {
|
||||
item {
|
||||
@@ -57,6 +57,11 @@ fun SettingsScreen(state: AppState, store: AppStore) {
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
FilledTonalButton(onClick = { store.refreshAll() }) {
|
||||
Icon(Icons.Rounded.Refresh, contentDescription = null)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text("Sync moods")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -68,33 +73,27 @@ 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")
|
||||
Row(
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
OutlinedButton(onClick = { store.openDownloads() }) {
|
||||
Text("Manage downloads")
|
||||
}
|
||||
if (state.user?.admin == true) {
|
||||
OutlinedButton(onClick = { store.scanLibrary() }) {
|
||||
Icon(Icons.Rounded.TravelExplore, contentDescription = null)
|
||||
if (state.downloads.isNotEmpty()) {
|
||||
OutlinedButton(onClick = { store.clearDownloads() }) {
|
||||
Icon(Icons.Rounded.DeleteSweep, contentDescription = null)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text("Scan")
|
||||
Text("Clear")
|
||||
}
|
||||
}
|
||||
}
|
||||
if (state.downloads.isNotEmpty()) {
|
||||
OutlinedButton(onClick = { store.clearDownloads() }) {
|
||||
Icon(Icons.Rounded.DeleteSweep, contentDescription = null)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text("Clear downloads")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -108,12 +107,13 @@ fun SettingsScreen(state: AppState, store: AppStore) {
|
||||
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Text("About", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
|
||||
Text(
|
||||
"AudioManager 0.1.0 · $platformName",
|
||||
"AudioManager 0.3.2 · $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,
|
||||
)
|
||||
|
||||
@@ -6,18 +6,19 @@ import io.ktor.client.engine.mock.respondError
|
||||
import io.ktor.http.HttpHeaders
|
||||
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 {
|
||||
|
||||
@@ -30,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,
|
||||
@@ -55,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
|
||||
@@ -74,41 +156,74 @@ class ApiClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `cache round-trips songs and moods`() = runTest {
|
||||
fun `failed downloads and images do not return error bodies`() = runTest {
|
||||
val engine = MockEngine {
|
||||
respond(
|
||||
"""{"error":{"code":"not_found","message":"Song not found"}}""",
|
||||
HttpStatusCode.NotFound,
|
||||
jsonHeaders,
|
||||
)
|
||||
}
|
||||
val client = ApiClient(configuredHttpClient(engine))
|
||||
client.restore("http://music", "token")
|
||||
|
||||
val error = assertFailsWith<ApiException> { client.download("sg-missing") }
|
||||
assertEquals(404, error.status)
|
||||
assertNull(client.image("http://music/missing.jpg"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `downloadTo streams bytes into the storage sink`() = runTest {
|
||||
val payload = ByteArray(100_000) { (it % 251).toByte() }
|
||||
val engine = MockEngine {
|
||||
respond(payload, HttpStatusCode.OK, headersOf(HttpHeaders.ContentType, "audio/mpeg"))
|
||||
}
|
||||
val client = ApiClient(configuredHttpClient(engine))
|
||||
client.restore("http://music", "token")
|
||||
var received = 0
|
||||
|
||||
val path = client.downloadTo("sg-1") { channel ->
|
||||
val buffer = ByteArray(8 * 1024)
|
||||
while (true) {
|
||||
val read = channel.readAvailable(buffer)
|
||||
if (read < 0) break
|
||||
received += read
|
||||
}
|
||||
"saved.mp3"
|
||||
}
|
||||
|
||||
assertEquals("saved.mp3", path)
|
||||
assertEquals(payload.size, received)
|
||||
}
|
||||
|
||||
@Test
|
||||
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)
|
||||
}
|
||||
|
||||
private class MemoryStorage : AppStorage {
|
||||
private val files = mutableMapOf<String, String>()
|
||||
override fun read(name: String): String? = files[name]
|
||||
override fun write(name: String, text: String) {
|
||||
files[name] = text
|
||||
}
|
||||
|
||||
override fun delete(name: String) {
|
||||
files.remove(name)
|
||||
}
|
||||
|
||||
override fun saveDownload(songId: String, bytes: ByteArray): String? = null
|
||||
override fun downloadPath(songId: String): String? = null
|
||||
override fun listDownloads(): Map<String, Long> = emptyMap()
|
||||
override fun deleteDownload(songId: String) = Unit
|
||||
override fun storageUsedBytes(): Long = 0
|
||||
storage.write("mood-cache.json", """{"version":1,"songs":[{"id":"old"}]}""")
|
||||
val invalidated = cache.load()
|
||||
assertTrue(invalidated.moods.isEmpty())
|
||||
assertEquals(3, invalidated.version)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,604 @@
|
||||
package win.taptap.musicmanager.client
|
||||
|
||||
import io.ktor.client.engine.mock.MockEngine
|
||||
import io.ktor.client.engine.mock.respond
|
||||
import io.ktor.client.engine.mock.respondError
|
||||
import io.ktor.http.HttpHeaders
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import io.ktor.http.headersOf
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.test.TestScope
|
||||
import kotlinx.coroutines.test.advanceTimeBy
|
||||
import kotlinx.coroutines.test.runCurrent
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFalse
|
||||
import kotlin.test.assertNotNull
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.test.assertTrue
|
||||
import win.taptap.musicmanager.client.api.ApiClient
|
||||
import win.taptap.musicmanager.client.api.Song
|
||||
import win.taptap.musicmanager.client.api.User
|
||||
import win.taptap.musicmanager.client.api.configuredHttpClient
|
||||
import win.taptap.musicmanager.client.data.AppCache
|
||||
import win.taptap.musicmanager.client.data.CachedState
|
||||
import win.taptap.musicmanager.client.data.PlaybackSnapshot
|
||||
import win.taptap.musicmanager.client.data.SessionState
|
||||
import win.taptap.musicmanager.client.playback.AudioPlayer
|
||||
import win.taptap.musicmanager.client.store.AppStore
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
class AppStoreTest {
|
||||
|
||||
@Test
|
||||
fun `playing a mood starts the server session and the first track`() = runTest {
|
||||
val storage = MemoryStorage()
|
||||
val cache = AppCache(storage)
|
||||
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
|
||||
val player = FakePlayer()
|
||||
val engine = MockEngine { request ->
|
||||
when (request.url.encodedPath) {
|
||||
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods" -> respond("""{"moods":[${moodJson(1)}]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods/mo-1" -> respond(detailJson(listOf("a")), HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods/mo-1/sessions" -> respond(
|
||||
"""{"id":"s1","moodId":"mo-1","moodName":"Focus","startedAt":"now",
|
||||
"queue":[${songJson("a")}]}""",
|
||||
HttpStatusCode.Created,
|
||||
jsonHeaders,
|
||||
)
|
||||
else -> respondError(HttpStatusCode.NotFound)
|
||||
}
|
||||
}
|
||||
val store = store(storage, cache, player, engine)
|
||||
runCurrent()
|
||||
store.openMood("mo-1")
|
||||
awaitState { store.state.value.selectedMood != null }
|
||||
|
||||
store.playMood("mo-1")
|
||||
awaitState { store.state.value.current != null }
|
||||
|
||||
val state = store.state.value
|
||||
assertEquals("a", state.current?.id)
|
||||
assertEquals("s1", state.session?.id)
|
||||
assertTrue(state.playing)
|
||||
assertEquals(listOf("a"), player.played)
|
||||
store.release()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an empty mood is rejected before any request`() = runTest {
|
||||
val storage = MemoryStorage()
|
||||
val cache = AppCache(storage)
|
||||
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
|
||||
val player = FakePlayer()
|
||||
val engine = MockEngine { request ->
|
||||
when (request.url.encodedPath) {
|
||||
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods" -> respond("""{"moods":[${moodJson(0)}]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods/mo-1" -> respond(detailJson(emptyList()), HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
else -> respondError(HttpStatusCode.NotFound)
|
||||
}
|
||||
}
|
||||
val store = store(storage, cache, player, engine)
|
||||
runCurrent()
|
||||
store.openMood("mo-1")
|
||||
awaitState { store.state.value.selectedMood != null }
|
||||
|
||||
store.playMood("mo-1")
|
||||
awaitState { store.state.value.message != null }
|
||||
|
||||
assertNull(store.state.value.current)
|
||||
assertTrue(player.played.isEmpty())
|
||||
assertTrue(store.state.value.messageIsError)
|
||||
assertTrue(store.state.value.message!!.contains("at least one song"))
|
||||
store.release()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `search is debounced and adding a result targets the chosen mood`() = runTest {
|
||||
val storage = MemoryStorage()
|
||||
val cache = AppCache(storage)
|
||||
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
|
||||
val engine = MockEngine { request ->
|
||||
when (request.url.encodedPath) {
|
||||
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods" -> respond("""{"moods":[${moodJson(0)}]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/search" -> respond(
|
||||
"""{"results":[{"source":"youtube","externalId":"v1","title":"Fresh",
|
||||
"artist":"Artist","duration":180,"downloaded":false}]}""",
|
||||
HttpStatusCode.OK,
|
||||
jsonHeaders,
|
||||
)
|
||||
"/api/v1/moods/mo-1/songs" -> respond(
|
||||
"""{"detail":${detailJson(emptyList())},"added":false,"downloading":true}""",
|
||||
HttpStatusCode.Accepted,
|
||||
jsonHeaders,
|
||||
)
|
||||
else -> respondError(HttpStatusCode.NotFound)
|
||||
}
|
||||
}
|
||||
val store = store(storage, cache, FakePlayer(), engine)
|
||||
runCurrent()
|
||||
awaitState { store.state.value.moods.isNotEmpty() }
|
||||
|
||||
store.openSearch("mo-1")
|
||||
store.setSearchQuery("fresh")
|
||||
advanceTimeBy(350)
|
||||
runCurrent()
|
||||
awaitState { store.state.value.searchResults.isNotEmpty() }
|
||||
assertEquals("v1", store.state.value.searchResults.single().externalId)
|
||||
|
||||
store.addSearchResult(store.state.value.searchResults.single())
|
||||
awaitState { store.state.value.message != null }
|
||||
assertEquals("Downloading for Focus", store.state.value.message)
|
||||
store.release()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `search shows the queued download status for a result`() = runTest {
|
||||
val storage = MemoryStorage()
|
||||
val cache = AppCache(storage)
|
||||
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
|
||||
val engine = MockEngine { request ->
|
||||
when (request.url.encodedPath) {
|
||||
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods" -> respond("""{"moods":[${moodJson(0)}]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
// Any detail the app may race with reports the job as active.
|
||||
"/api/v1/moods/mo-1" -> respond(
|
||||
detailJson(emptyList(), downloads = listOf(downloadJson("downloading"))),
|
||||
HttpStatusCode.OK,
|
||||
jsonHeaders,
|
||||
)
|
||||
"/api/v1/search" -> respond(
|
||||
"""{"results":[{"source":"youtube","externalId":"v1","title":"Fresh",
|
||||
"artist":"Artist","duration":180,"downloaded":false}]}""",
|
||||
HttpStatusCode.OK,
|
||||
jsonHeaders,
|
||||
)
|
||||
"/api/v1/moods/mo-1/songs" -> respond(
|
||||
"""{"detail":${detailJson(emptyList(), downloads = listOf(downloadJson("queued")) )},
|
||||
"added":false,"downloading":true}""",
|
||||
HttpStatusCode.Accepted,
|
||||
jsonHeaders,
|
||||
)
|
||||
else -> respondError(HttpStatusCode.NotFound)
|
||||
}
|
||||
}
|
||||
val store = store(storage, cache, FakePlayer(), engine)
|
||||
runCurrent()
|
||||
awaitState { store.state.value.moods.isNotEmpty() }
|
||||
|
||||
store.openSearch("mo-1")
|
||||
store.setSearchQuery("fresh")
|
||||
advanceTimeBy(350)
|
||||
runCurrent()
|
||||
awaitState("search results") { store.state.value.searchResults.isNotEmpty() }
|
||||
|
||||
store.addSearchResult(store.state.value.searchResults.single())
|
||||
awaitState("queued download") {
|
||||
store.state.value.searchDownloads["youtube|v1"]?.active == true
|
||||
}
|
||||
val status = store.state.value.searchDownloads.getValue("youtube|v1")
|
||||
assertTrue(status.state == "queued" || status.state == "downloading")
|
||||
assertTrue(status.active)
|
||||
store.release()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `adding a recommendation refreshes the selected mood`() = runTest {
|
||||
val storage = MemoryStorage()
|
||||
val cache = AppCache(storage)
|
||||
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
|
||||
val engine = MockEngine { request ->
|
||||
when (request.url.encodedPath) {
|
||||
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods" -> respond("""{"moods":[${moodJson(1)}]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods/mo-1" -> respond(
|
||||
detailJson(listOf("a"), recommendationJson()),
|
||||
HttpStatusCode.OK,
|
||||
jsonHeaders,
|
||||
)
|
||||
"/api/v1/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods/mo-1/recommendations/v1/add" -> respond(
|
||||
"""{"detail":${detailJson(listOf("a"))},
|
||||
"recommendation":${recommendationJson(state = "added", songId = "a")}}""",
|
||||
HttpStatusCode.OK,
|
||||
jsonHeaders,
|
||||
)
|
||||
else -> respondError(HttpStatusCode.NotFound)
|
||||
}
|
||||
}
|
||||
val store = store(storage, cache, FakePlayer(), engine)
|
||||
runCurrent()
|
||||
store.openMood("mo-1")
|
||||
awaitState { store.state.value.selectedMood != null }
|
||||
|
||||
store.addRecommendation("v1")
|
||||
awaitState { store.state.value.message != null }
|
||||
|
||||
val detail = assertNotNull(store.state.value.selectedMood)
|
||||
assertTrue(detail.recommendations.isEmpty())
|
||||
assertEquals(1, detail.mood.songCount)
|
||||
assertEquals("Added to Focus", store.state.value.message)
|
||||
store.release()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `changing the mood source re-runs the search against the new catalog`() = runTest {
|
||||
val storage = MemoryStorage()
|
||||
val cache = AppCache(storage)
|
||||
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
|
||||
val engine = MockEngine { request ->
|
||||
when {
|
||||
request.url.encodedPath == "/api/v1/me" ->
|
||||
respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
|
||||
request.url.encodedPath == "/api/v1/moods" ->
|
||||
respond("""{"moods":[${moodJson(0)}]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
request.method.value == "PATCH" && request.url.encodedPath == "/api/v1/moods/mo-1" ->
|
||||
respond(detailJson(emptyList(), source = "deezer"), HttpStatusCode.OK, jsonHeaders)
|
||||
request.url.encodedPath == "/api/v1/moods/mo-1" ->
|
||||
respond(detailJson(emptyList()), HttpStatusCode.OK, jsonHeaders)
|
||||
request.url.encodedPath == "/api/v1/moods/mo-1/preview" ->
|
||||
respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
request.url.encodedPath == "/api/v1/search" -> {
|
||||
val source = request.url.parameters["source"]
|
||||
val body = if (source == "deezer") {
|
||||
"""{"results":[{"source":"deezer","externalId":"67238732",
|
||||
"title":"Instant Crush","artist":"Daft Punk","duration":337,
|
||||
"downloaded":false}]}"""
|
||||
} else {
|
||||
"""{"results":[]}"""
|
||||
}
|
||||
respond(body, HttpStatusCode.OK, jsonHeaders)
|
||||
}
|
||||
else -> respondError(HttpStatusCode.NotFound)
|
||||
}
|
||||
}
|
||||
val store = store(storage, cache, FakePlayer(), engine)
|
||||
runCurrent()
|
||||
store.openMood("mo-1")
|
||||
awaitState { store.state.value.selectedMood != null }
|
||||
store.openSearch("mo-1")
|
||||
store.setSearchQuery("daft")
|
||||
advanceTimeBy(350)
|
||||
runCurrent()
|
||||
|
||||
store.setMoodSource("mo-1", "deezer")
|
||||
awaitState { store.state.value.searchResults.any { it.source == "deezer" } }
|
||||
|
||||
assertEquals("deezer", store.state.value.moods.first { it.id == "mo-1" }.source)
|
||||
assertEquals("67238732", store.state.value.searchResults.single().externalId)
|
||||
store.release()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `sleep timer pauses playback when it expires`() = runTest {
|
||||
val storage = MemoryStorage()
|
||||
val cache = AppCache(storage)
|
||||
val player = FakePlayer()
|
||||
val store = store(storage, cache, player)
|
||||
runCurrent()
|
||||
|
||||
store.playSong(song("a"))
|
||||
runCurrent()
|
||||
assertTrue(store.state.value.playing)
|
||||
|
||||
store.setSleepTimer(1)
|
||||
assertEquals(60L, store.state.value.sleepTimerRemainingSeconds)
|
||||
|
||||
advanceTimeBy(60_000)
|
||||
runCurrent()
|
||||
|
||||
assertFalse(store.state.value.playing)
|
||||
assertNull(store.state.value.sleepTimerRemainingSeconds)
|
||||
assertTrue(player.paused)
|
||||
store.release()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `bootstrap restores the saved queue and resumes on play`() = runTest {
|
||||
val storage = MemoryStorage()
|
||||
val cache = AppCache(storage)
|
||||
cache.savePlayback(
|
||||
PlaybackSnapshot(
|
||||
queue = listOf(song("b")),
|
||||
current = song("a"),
|
||||
positionSeconds = 12.0,
|
||||
),
|
||||
)
|
||||
val player = FakePlayer()
|
||||
val store = store(storage, cache, player)
|
||||
runCurrent()
|
||||
|
||||
assertEquals("a", store.state.value.current?.id)
|
||||
assertEquals(listOf("b"), store.state.value.queue.map { it.id })
|
||||
assertEquals(12.0, store.state.value.positionSeconds)
|
||||
assertTrue(player.played.isEmpty())
|
||||
|
||||
store.togglePlayPause()
|
||||
runCurrent()
|
||||
|
||||
assertTrue(store.state.value.playing)
|
||||
assertEquals(listOf("a"), player.played)
|
||||
assertEquals(12.0, player.seeks.last())
|
||||
store.release()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `queue reordering and removal persist in the snapshot`() = runTest {
|
||||
val storage = MemoryStorage()
|
||||
val cache = AppCache(storage)
|
||||
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
|
||||
val engine = MockEngine { request ->
|
||||
when (request.url.encodedPath) {
|
||||
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods" -> respond("""{"moods":[${moodJson(3)}]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods/mo-1" -> respond(
|
||||
detailJson(listOf("a", "b", "c")),
|
||||
HttpStatusCode.OK,
|
||||
jsonHeaders,
|
||||
)
|
||||
"/api/v1/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods/mo-1/sessions" -> respond(
|
||||
"""{"id":"s1","moodId":"mo-1","moodName":"Focus","startedAt":"now",
|
||||
"queue":[${songJson("a")},${songJson("b")},${songJson("c")}]}""",
|
||||
HttpStatusCode.Created,
|
||||
jsonHeaders,
|
||||
)
|
||||
else -> respondError(HttpStatusCode.NotFound)
|
||||
}
|
||||
}
|
||||
val store = store(storage, cache, FakePlayer(), engine)
|
||||
runCurrent()
|
||||
store.openMood("mo-1")
|
||||
awaitState { store.state.value.selectedMood != null }
|
||||
|
||||
store.playMood("mo-1")
|
||||
awaitState { store.state.value.current?.id == "a" }
|
||||
assertEquals(listOf("b", "c"), store.state.value.queue.map { it.id })
|
||||
|
||||
store.moveInQueue(1, 0)
|
||||
assertEquals(listOf("c", "b"), store.state.value.queue.map { it.id })
|
||||
|
||||
store.removeFromQueue(0)
|
||||
assertEquals(listOf("b"), store.state.value.queue.map { it.id })
|
||||
assertEquals(listOf("b"), cache.loadPlayback()?.queue?.map { it.id })
|
||||
store.release()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `headset next and previous follow the queue instead of seeking`() = runTest {
|
||||
val storage = MemoryStorage()
|
||||
val cache = AppCache(storage)
|
||||
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
|
||||
val player = FakePlayer()
|
||||
val engine = MockEngine { request ->
|
||||
when (request.url.encodedPath) {
|
||||
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods" -> respond("""{"moods":[${moodJson(3)}]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods/mo-1" -> respond(detailJson(listOf("a", "b", "c")), HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods/mo-1/sessions" -> respond(
|
||||
"""{"id":"s1","moodId":"mo-1","moodName":"Focus","startedAt":"now",
|
||||
"queue":[${songJson("a")},${songJson("b")},${songJson("c")}]}""",
|
||||
HttpStatusCode.Created,
|
||||
jsonHeaders,
|
||||
)
|
||||
else -> respondError(HttpStatusCode.NotFound)
|
||||
}
|
||||
}
|
||||
val store = store(storage, cache, player, engine)
|
||||
runCurrent()
|
||||
store.openMood("mo-1")
|
||||
awaitState { store.state.value.selectedMood != null }
|
||||
store.playMood("mo-1")
|
||||
awaitState { store.state.value.current?.id == "a" }
|
||||
|
||||
// A headset next moves the app queue: a -> b, not a seek inside one item.
|
||||
player.pressNext()
|
||||
awaitState { store.state.value.current?.id == "b" }
|
||||
assertEquals("b", store.state.value.current?.id)
|
||||
|
||||
// Within two seconds, previous restores the track that just finished.
|
||||
player.pressPrevious()
|
||||
awaitState { store.state.value.current?.id == "a" }
|
||||
assertEquals("a", store.state.value.current?.id)
|
||||
|
||||
// After two seconds it restarts the current track instead.
|
||||
store.seekTo(5.0)
|
||||
player.pressPrevious()
|
||||
runCurrent()
|
||||
assertEquals("a", store.state.value.current?.id)
|
||||
assertEquals(0.0, player.seeks.last())
|
||||
store.release()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `logout clears the session and the mood cache`() = runTest {
|
||||
val storage = MemoryStorage()
|
||||
val cache = AppCache(storage)
|
||||
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
|
||||
cache.save(
|
||||
CachedState(
|
||||
serverUrl = "http://music",
|
||||
userName = "alice",
|
||||
moods = emptyList(),
|
||||
),
|
||||
)
|
||||
val engine = MockEngine { request ->
|
||||
when (request.url.encodedPath) {
|
||||
"/api/v1/auth/logout" -> respond("", HttpStatusCode.NoContent)
|
||||
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods" -> respond("""{"moods":[]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
else -> respondError(HttpStatusCode.NotFound)
|
||||
}
|
||||
}
|
||||
val store = store(storage, cache, FakePlayer(), engine)
|
||||
runCurrent()
|
||||
awaitState { store.state.value.authenticated }
|
||||
|
||||
store.logout()
|
||||
awaitState { !store.state.value.authenticated }
|
||||
|
||||
assertNull(cache.loadSession())
|
||||
assertTrue(cache.load().moods.isEmpty())
|
||||
store.release()
|
||||
}
|
||||
|
||||
private suspend fun TestScope.awaitState(predicate: () -> Boolean) =
|
||||
awaitState("state", predicate)
|
||||
|
||||
private suspend fun TestScope.awaitState(label: String, predicate: () -> Boolean) {
|
||||
repeat(500) {
|
||||
runCurrent()
|
||||
if (predicate()) return
|
||||
withContext(Dispatchers.Default) { delay(10) }
|
||||
}
|
||||
throw AssertionError("$label did not settle")
|
||||
}
|
||||
|
||||
private val jsonHeaders = headersOf(HttpHeaders.ContentType, "application/json")
|
||||
|
||||
private fun songJson(id: String) = """
|
||||
{"id":"$id","source":"youtube","externalId":"video-$id","title":"Song $id",
|
||||
"artist":"Artist","album":"Album","duration":180,"bitRate":320,"size":1000,"suffix":"mp3"}
|
||||
""".trimIndent()
|
||||
|
||||
private fun moodJson(songCount: Int, source: String = "youtube") = """
|
||||
{"id":"mo-1","name":"Focus","source":"$source","collectionPercent":50,
|
||||
"recommendationPercent":50,"recommendationCount":10,"refreshHours":24,
|
||||
"createdAt":"2026-01-01T00:00:00Z","changedAt":"2026-01-01T00:00:00Z",
|
||||
"songCount":$songCount}
|
||||
""".trimIndent()
|
||||
|
||||
private fun recommendationJson(state: String = "new", songId: String? = null) = """
|
||||
{"source":"youtube","externalId":"v1","title":"Pick","artist":"Artist",
|
||||
"duration":180,"state":"$state",
|
||||
${songId?.let { "\"song\":${songJson(it)}," } ?: ""}
|
||||
"firstSeen":"2026-01-01T00:00:00Z","lastSeen":"2026-01-01T00:00:00Z"}
|
||||
""".trimIndent()
|
||||
|
||||
private fun detailJson(
|
||||
songs: List<String>,
|
||||
recommendation: String? = null,
|
||||
source: String = "youtube",
|
||||
downloads: List<String> = emptyList(),
|
||||
) = """
|
||||
{"mood":${moodJson(songs.size, source)},
|
||||
"songs":[${songs.joinToString(",") { """{"song":${songJson(it)},"origin":"search","addedAt":"now"}""" }}],
|
||||
"recommendations":${recommendation?.let { "[$it]" } ?: "[]"},
|
||||
"downloads":[${downloads.joinToString(",")}]}
|
||||
""".trimIndent()
|
||||
|
||||
private fun downloadJson(
|
||||
state: String,
|
||||
source: String = "youtube",
|
||||
externalId: String = "v1",
|
||||
) = """{"source":"$source","externalId":"$externalId","state":"$state",
|
||||
"attempts":1,"songId":null}""".trimIndent()
|
||||
|
||||
private fun song(id: String, duration: Int = 180) = Song(
|
||||
id = id,
|
||||
source = "youtube",
|
||||
externalId = "video-$id",
|
||||
title = "Song $id",
|
||||
artist = "Artist",
|
||||
album = "Album",
|
||||
duration = duration,
|
||||
bitRate = 320,
|
||||
size = 1_000,
|
||||
)
|
||||
|
||||
private fun TestScope.store(
|
||||
storage: MemoryStorage,
|
||||
cache: AppCache,
|
||||
player: AudioPlayer,
|
||||
engine: MockEngine = MockEngine { respondError(HttpStatusCode.NotFound) },
|
||||
): AppStore = AppStore(
|
||||
// Background scope so leftover store jobs (reconnect loops, refreshes)
|
||||
// are cancelled by runTest instead of failing with UncompletedCoroutinesError.
|
||||
scope = backgroundScope,
|
||||
api = ApiClient(configuredHttpClient(engine)),
|
||||
storage = storage,
|
||||
player = player,
|
||||
cache = cache,
|
||||
)
|
||||
|
||||
private class FakePlayer : AudioPlayer {
|
||||
private var onNext: (() -> Unit)? = null
|
||||
private var onPrevious: (() -> Unit)? = null
|
||||
|
||||
fun pressNext() {
|
||||
onNext?.invoke()
|
||||
}
|
||||
|
||||
fun pressPrevious() {
|
||||
onPrevious?.invoke()
|
||||
}
|
||||
|
||||
override fun setSkipCallbacks(onNext: (() -> Unit)?, onPrevious: (() -> Unit)?) {
|
||||
this.onNext = onNext
|
||||
this.onPrevious = onPrevious
|
||||
}
|
||||
|
||||
val played = mutableListOf<String>()
|
||||
val seeks = mutableListOf<Double>()
|
||||
var paused = false
|
||||
private set
|
||||
private var playing = false
|
||||
var position = 0.0
|
||||
private var finished = false
|
||||
|
||||
fun finish() {
|
||||
finished = true
|
||||
}
|
||||
|
||||
override fun play(
|
||||
source: String,
|
||||
song: Song,
|
||||
local: Boolean,
|
||||
artworkUri: String?,
|
||||
artworkBytes: ByteArray?,
|
||||
) {
|
||||
played += song.id
|
||||
playing = true
|
||||
paused = false
|
||||
position = 0.0
|
||||
finished = false
|
||||
}
|
||||
|
||||
override fun pause() {
|
||||
playing = false
|
||||
paused = true
|
||||
}
|
||||
|
||||
override fun resume() {
|
||||
playing = true
|
||||
paused = false
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
playing = false
|
||||
}
|
||||
|
||||
override fun isPlaying(): Boolean = playing
|
||||
override fun isFinished(): Boolean = finished
|
||||
override fun positionSeconds(): Double = position
|
||||
override fun durationSeconds(): Double = 0.0
|
||||
override val canSeek: Boolean = true
|
||||
override fun seekTo(seconds: Double) {
|
||||
position = seconds
|
||||
seeks += seconds
|
||||
}
|
||||
override fun release() {
|
||||
playing = false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package win.taptap.musicmanager.client
|
||||
|
||||
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>()
|
||||
|
||||
override fun read(name: String): String? = files[name]
|
||||
|
||||
override fun write(name: String, text: String) {
|
||||
files[name] = text
|
||||
}
|
||||
|
||||
override fun delete(name: String) {
|
||||
files.remove(name)
|
||||
}
|
||||
|
||||
override fun saveDownload(songId: String, bytes: ByteArray): String? = null
|
||||
override fun downloadPath(songId: String): String? = null
|
||||
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 deleteDownload(songId: String) {
|
||||
artwork.remove(songId)
|
||||
}
|
||||
override fun storageUsedBytes(): Long = 0
|
||||
}
|
||||
+118
-7
@@ -5,6 +5,8 @@ import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.io.InputStream
|
||||
import java.net.URI
|
||||
import javax.sound.sampled.AudioFormat
|
||||
import javax.sound.sampled.AudioInputStream
|
||||
import javax.sound.sampled.AudioSystem
|
||||
import javax.sound.sampled.SourceDataLine
|
||||
import kotlin.concurrent.thread
|
||||
@@ -13,38 +15,90 @@ import win.taptap.musicmanager.client.playback.AudioPlayer
|
||||
|
||||
/**
|
||||
* Desktop playback through the MP3SPI decoder and a PCM line. Pause/resume is a
|
||||
* decoder loop gate, so no audio device is reopened. Seeking is not supported.
|
||||
* decoder loop gate, so no audio device is reopened.
|
||||
*
|
||||
* 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 {
|
||||
|
||||
private var input: InputStream? = null
|
||||
private var stream: AudioInputStream? = null
|
||||
private var line: SourceDataLine? = null
|
||||
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
|
||||
|
||||
@Volatile private var paused = false
|
||||
@Volatile private var stopped = false
|
||||
@Volatile private var finished = false
|
||||
@Volatile private var framesRead = 0L
|
||||
@Volatile private var baseSeconds = 0.0
|
||||
private var frameSize = 4
|
||||
private var frameRate = 44_100f
|
||||
private var duration = 0.0
|
||||
|
||||
override fun play(source: String, song: Song, local: Boolean, artworkUri: String?) {
|
||||
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)
|
||||
}
|
||||
|
||||
private fun start(source: String, song: Song, local: Boolean, startAtSeconds: Double) {
|
||||
stop()
|
||||
finished = false
|
||||
paused = false
|
||||
stopped = false
|
||||
framesRead = 0
|
||||
baseSeconds = startAtSeconds.coerceAtLeast(0.0)
|
||||
duration = song.duration.toDouble()
|
||||
|
||||
val raw = if (local) FileInputStream(File(source)) else URI(source).toURL().openStream()
|
||||
val requestSource = if (!local && startAtSeconds > 0) {
|
||||
withTimeOffset(source, startAtSeconds)
|
||||
} else {
|
||||
source
|
||||
}
|
||||
val raw = if (local) {
|
||||
FileInputStream(File(requestSource))
|
||||
} else {
|
||||
val connection = URI(requestSource).toURL().openConnection()
|
||||
connection.connectTimeout = 15_000
|
||||
connection.readTimeout = 30_000
|
||||
connection.getInputStream()
|
||||
}
|
||||
val buffered = BufferedInputStream(raw, 128 * 1024)
|
||||
input = buffered
|
||||
val audio = AudioSystem.getAudioInputStream(buffered)
|
||||
val encoded = AudioSystem.getAudioInputStream(buffered)
|
||||
val audio = decodeToPcm(encoded)
|
||||
stream = audio
|
||||
frameSize = audio.format.frameSize.takeIf { it > 0 } ?: 4
|
||||
frameRate = audio.format.frameRate.takeIf { it > 0 } ?: 44_100f
|
||||
|
||||
// A remote stream already starts at the whole-second offset; local
|
||||
// files and the fractional part are skipped in the decoded PCM.
|
||||
val skipSeconds = if (local) startAtSeconds else startAtSeconds - kotlin.math.floor(startAtSeconds)
|
||||
if (skipSeconds > 0) {
|
||||
skipPcm(audio, skipSeconds)
|
||||
}
|
||||
|
||||
val info = javax.sound.sampled.DataLine.Info(SourceDataLine::class.java, audio.format)
|
||||
val dataLine = AudioSystem.getLine(info) as SourceDataLine
|
||||
dataLine.open(audio.format)
|
||||
@@ -79,6 +133,23 @@ class DesktopAudioPlayer : AudioPlayer {
|
||||
}
|
||||
}
|
||||
|
||||
private fun skipPcm(audio: AudioInputStream, seconds: Double) {
|
||||
var remaining = (seconds * frameRate * frameSize).toLong().coerceAtLeast(0L)
|
||||
val buffer = ByteArray(16 * 1024)
|
||||
while (remaining > 0 && !stopped) {
|
||||
val skipped = runCatching { audio.skip(remaining) }.getOrDefault(0L)
|
||||
if (skipped > 0) {
|
||||
remaining -= skipped
|
||||
} else {
|
||||
val read = runCatching {
|
||||
audio.read(buffer, 0, minOf(buffer.size.toLong(), remaining).toInt())
|
||||
}.getOrDefault(-1)
|
||||
if (read <= 0) break
|
||||
remaining -= read
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun pause() {
|
||||
paused = true
|
||||
}
|
||||
@@ -98,8 +169,10 @@ class DesktopAudioPlayer : AudioPlayer {
|
||||
runCatching { line?.flush() }
|
||||
worker?.interrupt()
|
||||
runCatching { worker?.join(400) }
|
||||
runCatching { stream?.close() }
|
||||
runCatching { input?.close() }
|
||||
line = null
|
||||
stream = null
|
||||
input = null
|
||||
worker = null
|
||||
}
|
||||
@@ -110,17 +183,55 @@ class DesktopAudioPlayer : AudioPlayer {
|
||||
override fun isFinished(): Boolean = finished
|
||||
|
||||
override fun positionSeconds(): Double {
|
||||
val seconds = framesRead.toDouble() / frameSize / frameRate
|
||||
val seconds = baseSeconds + framesRead.toDouble() / frameSize / frameRate
|
||||
return seconds.coerceIn(0.0, duration.takeIf { it > 0 } ?: seconds)
|
||||
}
|
||||
|
||||
override fun durationSeconds(): Double = duration
|
||||
|
||||
override val canSeek: Boolean = false
|
||||
override val canSeek: Boolean = true
|
||||
|
||||
override fun seekTo(seconds: Double) = Unit
|
||||
override fun seekTo(seconds: Double) {
|
||||
val source = currentSource ?: return
|
||||
val song = currentSong ?: return
|
||||
val wasPaused = paused
|
||||
start(source, song, currentLocal, seconds.coerceAtLeast(0.0))
|
||||
if (wasPaused) pause()
|
||||
}
|
||||
|
||||
override fun release() {
|
||||
stop()
|
||||
}
|
||||
|
||||
/** Adds the server's `timeOffset` parameter, replacing an earlier one. */
|
||||
private fun withTimeOffset(source: String, seconds: Double): String {
|
||||
val cleaned = source.replace(Regex("[?&]timeOffset=\\d+"), "")
|
||||
val separator = if (cleaned.contains('?')) "&" else "?"
|
||||
return "$cleaned${separator}timeOffset=${seconds.toInt()}"
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* MP3SPI hands back a stream whose format is the compressed MPEG one. The audio
|
||||
* device only understands uncompressed PCM, so convert to 16-bit signed PCM at
|
||||
* the source sample rate before opening the line.
|
||||
*/
|
||||
internal fun decodeToPcm(encoded: AudioInputStream): AudioInputStream {
|
||||
val pcm = encoded.format.toPcmFormat()
|
||||
if (encoded.format.encoding == AudioFormat.Encoding.PCM_SIGNED) return encoded
|
||||
return AudioSystem.getAudioInputStream(pcm, encoded)
|
||||
}
|
||||
|
||||
internal fun AudioFormat.toPcmFormat(): AudioFormat {
|
||||
val rate = sampleRate.takeIf { it > 0 } ?: 44_100f
|
||||
val channelCount = channels.takeIf { it > 0 } ?: 2
|
||||
return AudioFormat(
|
||||
AudioFormat.Encoding.PCM_SIGNED,
|
||||
rate,
|
||||
16,
|
||||
channelCount,
|
||||
channelCount * 2,
|
||||
rate,
|
||||
false,
|
||||
)
|
||||
}
|
||||
+58
-2
@@ -4,6 +4,7 @@ import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.toComposeImageBitmap
|
||||
import io.ktor.client.engine.HttpClientEngine
|
||||
import io.ktor.client.engine.cio.CIO
|
||||
import io.ktor.utils.io.readAvailable
|
||||
import java.io.File
|
||||
import win.taptap.musicmanager.client.data.AppStorage
|
||||
import win.taptap.musicmanager.client.playback.AudioPlayer
|
||||
@@ -32,7 +33,7 @@ class DesktopStorage : AppStorage {
|
||||
|
||||
override fun write(name: String, text: String) {
|
||||
root.mkdirs()
|
||||
File(root, name).writeText(text)
|
||||
atomicWrite(File(root, name)) { it.writeText(text) }
|
||||
}
|
||||
|
||||
override fun delete(name: String) {
|
||||
@@ -42,13 +43,53 @@ class DesktopStorage : AppStorage {
|
||||
override fun saveDownload(songId: String, bytes: ByteArray): String? {
|
||||
downloads.mkdirs()
|
||||
val file = File(downloads, "${safeName(songId)}.mp3")
|
||||
file.writeBytes(bytes)
|
||||
atomicWrite(file) { it.writeBytes(bytes) }
|
||||
return file.absolutePath
|
||||
}
|
||||
|
||||
override suspend fun saveDownloadStream(
|
||||
songId: String,
|
||||
source: io.ktor.utils.io.ByteReadChannel,
|
||||
): String? {
|
||||
downloads.mkdirs()
|
||||
val target = File(downloads, "${safeName(songId)}.mp3")
|
||||
val temp = File(downloads, "${safeName(songId)}.mp3.part")
|
||||
try {
|
||||
temp.outputStream().use { output ->
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
while (true) {
|
||||
val read = source.readAvailable(buffer)
|
||||
if (read < 0) break
|
||||
if (read > 0) output.write(buffer, 0, read)
|
||||
}
|
||||
output.flush()
|
||||
}
|
||||
if (temp.length() == 0L) error("empty download")
|
||||
if (!temp.renameTo(target)) {
|
||||
temp.copyTo(target, overwrite = true)
|
||||
temp.delete()
|
||||
}
|
||||
return target.absolutePath
|
||||
} catch (t: Throwable) {
|
||||
temp.delete()
|
||||
throw t
|
||||
}
|
||||
}
|
||||
|
||||
override fun downloadPath(songId: String): String? =
|
||||
File(downloads, "${safeName(songId)}.mp3").takeIf { it.isFile }?.absolutePath
|
||||
|
||||
override fun saveArtwork(songId: String, bytes: ByteArray): String? {
|
||||
if (bytes.isEmpty()) return null
|
||||
downloads.mkdirs()
|
||||
val file = File(downloads, "${safeName(songId)}.jpg")
|
||||
atomicWrite(file) { it.writeBytes(bytes) }
|
||||
return file.absolutePath
|
||||
}
|
||||
|
||||
override fun artworkBytes(songId: String): ByteArray? =
|
||||
File(downloads, "${safeName(songId)}.jpg").takeIf { it.isFile }?.readBytes()
|
||||
|
||||
override fun listDownloads(): Map<String, Long> =
|
||||
downloads.listFiles()
|
||||
?.filter { it.isFile && it.extension == "mp3" }
|
||||
@@ -57,11 +98,26 @@ class DesktopStorage : AppStorage {
|
||||
|
||||
override fun deleteDownload(songId: String) {
|
||||
File(downloads, "${safeName(songId)}.mp3").delete()
|
||||
File(downloads, "${safeName(songId)}.jpg").delete()
|
||||
}
|
||||
|
||||
override fun storageUsedBytes(): Long =
|
||||
downloads.listFiles()?.sumOf { it.length() } ?: 0L
|
||||
|
||||
private fun atomicWrite(target: File, write: (File) -> Unit) {
|
||||
val temp = File(target.parentFile, "${target.name}.part")
|
||||
try {
|
||||
write(temp)
|
||||
if (!temp.renameTo(target)) {
|
||||
temp.copyTo(target, overwrite = true)
|
||||
temp.delete()
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
temp.delete()
|
||||
throw t
|
||||
}
|
||||
}
|
||||
|
||||
private fun safeName(songId: String): String =
|
||||
songId.map { if (it.isLetterOrDigit() || it == '-' || it == '_') it else '_' }.joinToString("")
|
||||
}
|
||||
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package win.taptap.musicmanager.client
|
||||
|
||||
import java.io.ByteArrayInputStream
|
||||
import javax.sound.sampled.AudioFormat
|
||||
import javax.sound.sampled.AudioSystem
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
class DesktopAudioPlayerTest {
|
||||
|
||||
@Test
|
||||
fun `mp3 is decoded to pcm before opening an audio line`() {
|
||||
val bytes = checkNotNull(javaClass.getResourceAsStream("/sample.mp3")) {
|
||||
"missing test fixture sample.mp3"
|
||||
}.use { it.readBytes() }
|
||||
|
||||
val encoded = AudioSystem.getAudioInputStream(ByteArrayInputStream(bytes))
|
||||
assertEquals("MPEG1L3", encoded.format.encoding.toString())
|
||||
|
||||
// Java Sound has no line for the compressed format; the player must
|
||||
// convert to PCM_SIGNED first.
|
||||
val pcm = decodeToPcm(encoded)
|
||||
assertEquals(AudioFormat.Encoding.PCM_SIGNED, pcm.format.encoding)
|
||||
assertEquals(44_100f, pcm.format.sampleRate)
|
||||
assertEquals(16, pcm.format.sampleSizeInBits)
|
||||
assertEquals(2, pcm.format.channels)
|
||||
assertEquals(4, pcm.format.frameSize)
|
||||
|
||||
val buffer = ByteArray(4_096)
|
||||
assertTrue(pcm.read(buffer) > 0)
|
||||
pcm.close()
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -29,6 +29,12 @@ class WebStorage : AppStorage {
|
||||
|
||||
override fun saveDownload(songId: String, bytes: ByteArray): String? = null
|
||||
override fun downloadPath(songId: String): String? = null
|
||||
override suspend fun saveDownloadStream(
|
||||
songId: String,
|
||||
source: io.ktor.utils.io.ByteReadChannel,
|
||||
): String? = null
|
||||
override fun saveArtwork(songId: String, bytes: ByteArray): String? = null
|
||||
override fun artworkBytes(songId: String): ByteArray? = null
|
||||
override fun listDownloads(): Map<String, Long> = emptyMap()
|
||||
override fun deleteDownload(songId: String) = Unit
|
||||
override fun storageUsedBytes(): Long = 0L
|
||||
|
||||
@@ -12,7 +12,13 @@ class WebAudioPlayer : AudioPlayer {
|
||||
preload = "auto"
|
||||
}
|
||||
|
||||
override fun play(source: String, song: Song, local: Boolean, artworkUri: String?) {
|
||||
override fun play(
|
||||
source: String,
|
||||
song: Song,
|
||||
local: Boolean,
|
||||
artworkUri: String?,
|
||||
artworkBytes: ByteArray?,
|
||||
) {
|
||||
audio.src = source
|
||||
audio.play()
|
||||
}
|
||||
|
||||
@@ -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`).
|
||||
Executable
+55
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Build a signed Android App Bundle for the Google Play internal testing track.
|
||||
#
|
||||
# Usage:
|
||||
# scripts/build-release-aab.sh [versionCode] [versionName]
|
||||
#
|
||||
# Signing values are read by Gradle from the environment or local.properties:
|
||||
# UPLOAD_STORE_FILE absolute path to the upload keystore
|
||||
# UPLOAD_STORE_PASSWORD
|
||||
# UPLOAD_KEY_ALIAS
|
||||
# UPLOAD_KEY_PASSWORD
|
||||
#
|
||||
# Play requires a versionCode that is higher than every previous upload.
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
cd "$ROOT"
|
||||
|
||||
GRADLE="${GRADLE:-gradle}"
|
||||
AAB="composeApp/build/outputs/bundle/release/composeApp-release.aab"
|
||||
|
||||
prop() {
|
||||
local key="$1"
|
||||
[ -f local.properties ] || return 0
|
||||
grep -E "^${key}=" local.properties | tail -1 | cut -d= -f2-
|
||||
}
|
||||
|
||||
if [ -z "${ANDROID_KEYSTORE_PATH:-}" ] && [ -z "$(prop UPLOAD_STORE_FILE)" ]; then
|
||||
echo "No upload key configured: set UPLOAD_STORE_FILE in local.properties" >&2
|
||||
echo "or ANDROID_KEYSTORE_PATH in the environment." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
VERSION_CODE="${1:-${VERSION_CODE:-$(prop VERSION_CODE)}}"
|
||||
VERSION_NAME="${2:-${VERSION_NAME:-$(prop VERSION_NAME)}}"
|
||||
VERSION_CODE="${VERSION_CODE:-1}"
|
||||
VERSION_NAME="${VERSION_NAME:-0.1.0}"
|
||||
|
||||
export VERSION_CODE VERSION_NAME
|
||||
export ANDROID_HOME="${ANDROID_HOME:-${ANDROID_SDK_ROOT:-$HOME/Android/Sdk}}"
|
||||
|
||||
echo "Building AAB versionCode=$VERSION_CODE versionName=$VERSION_NAME"
|
||||
"$GRADLE" :composeApp:bundleRelease --console=plain
|
||||
|
||||
if ! jarsigner -verify "$AAB" >/dev/null 2>&1; then
|
||||
echo "AAB is not signed; check the upload keystore settings." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo
|
||||
echo "Signed bundle: $ROOT/$AAB"
|
||||
sha256sum "$AAB"
|
||||
echo
|
||||
echo "Upload it to Play Console > Testing > Internal testing > Create new release."
|
||||
@@ -14,8 +14,8 @@ let
|
||||
node = pkgs.nodejs_22;
|
||||
|
||||
androidPackages = pkgs.androidenv.composeAndroidPackages {
|
||||
platformVersions = [ "35" ];
|
||||
buildToolsVersions = [ "35.0.0" ];
|
||||
platformVersions = [ "36" ];
|
||||
buildToolsVersions = [ "36.0.0" ];
|
||||
includeEmulator = false;
|
||||
includeSystemImages = false;
|
||||
includeNDK = false;
|
||||
|
||||
Reference in new issue
Block a user