Compare commits
13
Commits
8f94bb18e7
..
v0.1.1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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
|
image: gitea.tap-tap.win/taptap/audiomanager-client-ci:3
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- 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
|
- name: Test and build
|
||||||
run: |
|
run: |
|
||||||
@@ -58,3 +72,48 @@ jobs:
|
|||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
run: scripts/publish-release.sh dist
|
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
|
.DS_Store
|
||||||
.kotlin/
|
.kotlin/
|
||||||
node_modules/
|
node_modules/
|
||||||
|
*.jks
|
||||||
|
*.keystore
|
||||||
@@ -9,7 +9,7 @@ The client and server are designed together. There is no OpenSubsonic compatibil
|
|||||||
| Target | UI | Playback | Offline downloads |
|
| Target | UI | Playback | Offline downloads |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| **Android** | Compose Multiplatform | Media3 / ExoPlayer | Yes |
|
| **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 |
|
| **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.
|
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.
|
||||||
@@ -24,8 +24,18 @@ The shared module contains the API client, session/cache storage, radio queue, a
|
|||||||
- Two add-to-mood actions in the player:
|
- Two add-to-mood actions in the player:
|
||||||
- **Add to current mood** (the mood of the active radio session)
|
- **Add to current mood** (the mood of the active radio session)
|
||||||
- **Choose another mood** (picker)
|
- **Choose another mood** (picker)
|
||||||
- Library search and playback.
|
- YT Music recommendations in the mood editor: refresh on demand, accept or reject candidates, thumbnails, and a clear state for library matches (`Seed added`), accepted-for-download tracks (`Queued`, `Downloading`, `Download failed` with retry) and new picks. Accepting a track the library already has adds it as a seed immediately; the rest are downloaded by the server and promoted automatically.
|
||||||
|
- Library search and playback, plus **Shuffle all** to queue the whole library without starting a mood.
|
||||||
|
- A queue sheet from the player: the current track plus every upcoming track, with move up/down and remove. Changes are persisted locally.
|
||||||
|
- **Previous** from the player: after two seconds of playback it restarts the current track; before that it restores the last played track. The track it leaves is put back at the front of the queue.
|
||||||
|
- **Scrubbing**: the progress slider can be dragged on every platform. Android/web seek natively; desktop restarts the decoder at the requested position (`timeOffset` for remote streams, PCM skip for local files).
|
||||||
|
- **Seed mix** per mood: a slider chooses the share of seeds vs recommendations for each generated batch. The server rolls the percentage for every queued track and falls back to the other pool when one runs out.
|
||||||
|
- **Longform tab** for audiobooks and podcasts: per-artist read-only playlists, “Shuffle artist” for random episodes, a resume list with progress, and a separate search scope. Long-form never enters music search, Shuffle all, moods or radio.
|
||||||
|
- **Sleep timer** (15/30/45/60/90 minutes) that pauses playback. On Android the pause is scheduled inside the media service, so it still fires when the app is backgrounded or the task is swiped away.
|
||||||
- Offline library cache: moods, songs and the last sync revision are stored locally. When the server is unreachable, downloaded tracks still play.
|
- Offline library cache: moods, songs and the last sync revision are stored locally. When the server is unreachable, downloaded tracks still play.
|
||||||
|
- The play queue and current track are saved locally, so a restart reopens the player paused and resumes on the next tap.
|
||||||
|
- Reconnects automatically with exponential backoff (15s to 5min) while offline.
|
||||||
|
- Downloads retry up to three times before reporting an error; covers and YT thumbnails are cached for the app's lifetime.
|
||||||
- Original MP3 downloads with progress state, removal and storage usage.
|
- Original MP3 downloads with progress state, removal and storage usage.
|
||||||
- Session persistence: the login survives app restarts until the token is revoked or expires.
|
- 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.
|
- 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.
|
||||||
@@ -43,21 +53,22 @@ composeApp/
|
|||||||
|-- src/androidMain/ # Activity, Media3 player, filesystem storage
|
|-- src/androidMain/ # Activity, Media3 player, filesystem storage
|
||||||
|-- src/desktopMain/ # Main window, MP3SPI player, filesystem storage
|
|-- src/desktopMain/ # Main window, MP3SPI player, filesystem storage
|
||||||
|-- src/wasmJsMain/ # Compose viewport, HTML audio, localStorage
|
|-- 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
|
`-- ci/ # Android SDK CI image
|
||||||
```
|
```
|
||||||
|
|
||||||
## Build
|
## 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
|
```bash
|
||||||
nix-shell
|
nix-shell
|
||||||
```
|
```
|
||||||
|
|
||||||
The shell accepts the unfree Android SDK license for you; see the comment at the top of `shell.nix`. Without Nix, point `ANDROID_HOME` at an SDK containing platform 35 and build-tools 35.0.0.
|
The shell accepts the unfree Android SDK license for you; see the comment at the top of `shell.nix`. Without Nix, point `ANDROID_HOME` at an SDK containing platform 36 and build-tools 36.0.0.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
export ANDROID_HOME=/opt/android-sdk
|
export ANDROID_HOME=/opt/android-sdk
|
||||||
@@ -84,15 +95,95 @@ Serve the web bundle from any static host (for example `python3 -m http.server`
|
|||||||
|
|
||||||
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. Bump `versionCode` for
|
||||||
|
every upload; `VERSION_CODE`/`VERSION_NAME` can also be set in the environment.
|
||||||
|
|
||||||
|
### 3. Upload
|
||||||
|
|
||||||
|
In Play Console: **Testing → Internal testing → Create new release → App
|
||||||
|
integrity → Google-generated key**, upload the AAB, add release notes, then
|
||||||
|
**Save → Roll out**. The first upload enrolls the app in Play App Signing. Share
|
||||||
|
the opt-in link from the Testers tab with your test list.
|
||||||
|
|
||||||
|
### 4. Automated uploads
|
||||||
|
|
||||||
|
Tagged builds (`v*`) publish to internal testing from CI. One-time setup:
|
||||||
|
|
||||||
|
1. In Google Cloud, enable the **Google Play Android Developer API**.
|
||||||
|
2. Create a service account and download a JSON key.
|
||||||
|
3. In Play Console → **Users and permissions → Invite new user**, add the
|
||||||
|
service account's `client_email`, give it access to this app with
|
||||||
|
**Release to testing tracks** and **View app information** (do not grant
|
||||||
|
production or admin access).
|
||||||
|
4. Add these repository secrets in Gitea:
|
||||||
|
|
||||||
|
| 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.2.0 && git push --tags` builds, signs and uploads the bundle.
|
||||||
|
Gradle Play Publisher asks Play for the next free `versionCode`
|
||||||
|
(`ResolutionStrategy.AUTO`), so only the tag/version name needs to change.
|
||||||
|
|
||||||
|
Local equivalent (takes the JSON from an environment variable, never a file in
|
||||||
|
the repo):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ANDROID_PUBLISHER_CREDENTIALS="$(cat ~/play-service-account.json)" \
|
||||||
|
ANDROID_HOME=/opt/android-sdk gradle :composeApp:publishBundle
|
||||||
|
```
|
||||||
|
|
||||||
## App state and offline behaviour
|
## 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.
|
- **Auth** — restore the saved token on launch and log out.
|
||||||
- **Library sync** — first launch pages through `/library/songs`; later launches use the `since` delta and tombstones.
|
- **Library sync** — first launch pages through `/library/songs`; later launches use the `since` delta and tombstones. Songs are split into music and longform using the folders assigned at login, so the two never mix client-side.
|
||||||
- **Mood cache** — mood details are stored so the app can open them offline.
|
- **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.
|
- **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.
|
- **Downloads** — stored under the platform app directory, keyed by deterministic song ID.
|
||||||
|
- **Playback snapshot** — the session, upcoming queue, current track and play history are persisted on every queue change and restored on the next launch.
|
||||||
|
- **Longform progress** — position is saved locally and to `/longform/progress` while playing, on pause and on track changes; the resume list is fed from the server when online.
|
||||||
|
- **Offline retry** — a background loop retries the library sync until the server responds again.
|
||||||
|
|
||||||
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 and library render immediately, then refresh in the background.
|
||||||
|
|
||||||
@@ -113,7 +204,7 @@ Adding a song makes it a permanent seed, so it is always eligible in future radi
|
|||||||
|
|
||||||
## CI and releases
|
## 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, so jobs do not download them on every run.
|
||||||
|
|
||||||
- **main / PR:** run `desktopTest`, build the Android APK and the *development* Wasm bundle. The optimized Wasm build is CPU-bound and reserved for releases.
|
- **main / PR:** run `desktopTest`, 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.
|
- **`v*` tag:** additionally build the desktop fat jar and the optimized Wasm bundle, then attach all three to the Gitea release.
|
||||||
@@ -124,12 +215,14 @@ Rebuild the CI image after changing `ci/Dockerfile` or dependency versions:
|
|||||||
scripts/build-ci-image.sh 3
|
scripts/build-ci-image.sh 3
|
||||||
```
|
```
|
||||||
|
|
||||||
The image build performs one warm-up compile (`desktopTest`, `assembleDebug`, `compileKotlinWasmJs`) and then removes the sources, keeping only `/root/.gradle`.
|
The image build performs one warm-up compile (`kotlinNodeJsSetup`, `kotlinYarnSetup`, `desktopTest`, `assembleDebug`, `compileKotlinWasmJs`) and then removes the sources, keeping only `/root/.gradle`.
|
||||||
|
|
||||||
## Known limitations
|
## Known limitations
|
||||||
|
|
||||||
- The media notification exposes play/pause and seeking. Queue actions (skip, add to mood) stay in the app because the mood session and its events belong to the server.
|
- The media notification exposes play/pause and seeking. Queue actions (skip, 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.
|
- Desktop playback supports seeking by reopening the decoder at the requested position (server `timeOffset` for remote streams, PCM skipping for local files). Longform resume works there too. MP3s are decoded to 16-bit PCM before the line is opened, because Java Sound has no line for the compressed format.
|
||||||
- Web downloads are disabled because the browser owns its storage; the app still streams and caches metadata.
|
- 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.
|
- Accepted recommendations are downloaded by the server into `<music>/AudioManager Imports/<artist>/<title>/`, with the YT thumbnail embedded as cover art, scanned and added as seeds. The per-track folder keeps covers distinct. The server needs outbound network access for this.
|
||||||
|
- Offline downloads also store the 320 px cover next to the MP3 (`<songId>.jpg`), so the in-app cover and the Android notification artwork survive without the server. Deleting a download removes both files.
|
||||||
|
- YT Music discovery and automatic downloads run server-side through `yt-dlp`. Accepted tracks that are not in the library are imported into `AudioManager Imports` with embedded cover art and promoted to seeds.
|
||||||
- No iOS target yet. The shared module is ready for one.
|
- 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.kotlin.plugin.compose") version "2.1.20" apply false
|
||||||
id("org.jetbrains.compose") version "1.8.0" apply false
|
id("org.jetbrains.compose") version "1.8.0" apply false
|
||||||
id("com.android.application") version "8.9.1" 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 \
|
&& yes | "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --licenses > /dev/null \
|
||||||
&& "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" \
|
&& "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" \
|
||||||
"platform-tools" \
|
"platform-tools" \
|
||||||
"platforms;android-35" \
|
"platforms;android-36" \
|
||||||
"build-tools;35.0.0" \
|
"build-tools;36.0.0" \
|
||||||
&& rm -rf "$ANDROID_HOME/.temp" "$ANDROID_HOME/.downloadIntermediates"
|
&& rm -rf "$ANDROID_HOME/.temp" "$ANDROID_HOME/.downloadIntermediates"
|
||||||
|
|
||||||
# Warm the Gradle dependency cache and the Kotlin/Wasm (node, yarn, binaryen)
|
# Warm the Gradle dependency cache and the Kotlin/Wasm (node, yarn, binaryen)
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
@file:OptIn(org.jetbrains.kotlin.gradle.ExperimentalWasmDsl::class)
|
@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.compose.desktop.application.dsl.TargetFormat
|
||||||
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
||||||
|
|
||||||
@@ -9,8 +12,37 @@ plugins {
|
|||||||
id("org.jetbrains.compose")
|
id("org.jetbrains.compose")
|
||||||
id("org.jetbrains.kotlin.plugin.compose")
|
id("org.jetbrains.kotlin.plugin.compose")
|
||||||
id("com.android.application")
|
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.1.0"
|
||||||
|
|
||||||
kotlin {
|
kotlin {
|
||||||
androidTarget {
|
androidTarget {
|
||||||
compilerOptions {
|
compilerOptions {
|
||||||
@@ -47,6 +79,7 @@ kotlin {
|
|||||||
implementation("io.ktor:ktor-serialization-kotlinx-json:3.1.2")
|
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-coroutines-core:1.10.1")
|
||||||
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.8.0")
|
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.8.0")
|
||||||
|
implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.6.2")
|
||||||
}
|
}
|
||||||
|
|
||||||
commonTest.dependencies {
|
commonTest.dependencies {
|
||||||
@@ -84,14 +117,39 @@ kotlin {
|
|||||||
|
|
||||||
android {
|
android {
|
||||||
namespace = "win.taptap.musicmanager.client"
|
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 {
|
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
|
minSdk = 26
|
||||||
targetSdk = 35
|
targetSdk = 36
|
||||||
versionCode = 1
|
versionCode = appVersionCode
|
||||||
versionName = "0.1.0"
|
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 {
|
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 {
|
compose.desktop {
|
||||||
application {
|
application {
|
||||||
mainClass = "win.taptap.musicmanager.client.MainKt"
|
mainClass = "win.taptap.musicmanager.client.MainKt"
|
||||||
|
|||||||
+38
-7
@@ -3,6 +3,7 @@ package win.taptap.musicmanager.client
|
|||||||
import android.content.ComponentName
|
import android.content.ComponentName
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
|
import android.os.Bundle
|
||||||
import androidx.core.content.ContextCompat
|
import androidx.core.content.ContextCompat
|
||||||
import androidx.media3.common.MediaItem
|
import androidx.media3.common.MediaItem
|
||||||
import androidx.media3.common.MediaMetadata
|
import androidx.media3.common.MediaMetadata
|
||||||
@@ -20,7 +21,7 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
|
|||||||
|
|
||||||
private val appContext = context.applicationContext
|
private val appContext = context.applicationContext
|
||||||
private var controller: MediaController? = null
|
private var controller: MediaController? = null
|
||||||
private var pending: ((MediaController) -> Unit)? = null
|
private val pending = ArrayDeque<(MediaController) -> Unit>()
|
||||||
private var connected = false
|
private var connected = false
|
||||||
|
|
||||||
@Volatile private var finished = false
|
@Volatile private var finished = false
|
||||||
@@ -44,15 +45,23 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
|
|||||||
controller = sessionController
|
controller = sessionController
|
||||||
sessionController.addListener(listener)
|
sessionController.addListener(listener)
|
||||||
connected = true
|
connected = true
|
||||||
pending?.invoke(sessionController)
|
val queued = synchronized(pending) {
|
||||||
pending = null
|
pending.toList().also { pending.clear() }
|
||||||
|
}
|
||||||
|
queued.forEach { action -> runCatching { action(sessionController) } }
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
ContextCompat.getMainExecutor(appContext),
|
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
|
finished = false
|
||||||
withController { controller ->
|
withController { controller ->
|
||||||
val uri = if (local) Uri.fromFile(java.io.File(source)) else Uri.parse(source)
|
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)
|
.setTitle(song.title)
|
||||||
.setArtist(song.artist)
|
.setArtist(song.artist)
|
||||||
.setAlbumTitle(song.album)
|
.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()
|
.build()
|
||||||
val item = MediaItem.Builder()
|
val item = MediaItem.Builder()
|
||||||
.setUri(uri)
|
.setUri(uri)
|
||||||
@@ -108,12 +126,23 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
|
|||||||
withController { it.seekTo((seconds * 1000).toLong().coerceAtLeast(0L)) }
|
withController { it.seekTo((seconds * 1000).toLong().coerceAtLeast(0L)) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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() {
|
override fun release() {
|
||||||
controller?.release()
|
controller?.release()
|
||||||
MediaController.releaseFuture(future)
|
MediaController.releaseFuture(future)
|
||||||
controller = null
|
controller = null
|
||||||
connected = false
|
connected = false
|
||||||
pending = null
|
synchronized(pending) { pending.clear() }
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun withController(block: (MediaController) -> Unit) {
|
private fun withController(block: (MediaController) -> Unit) {
|
||||||
@@ -121,7 +150,9 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
|
|||||||
if (current != null && connected) {
|
if (current != null && connected) {
|
||||||
block(current)
|
block(current)
|
||||||
} else {
|
} 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 androidx.compose.ui.graphics.asImageBitmap
|
||||||
import io.ktor.client.engine.HttpClientEngine
|
import io.ktor.client.engine.HttpClientEngine
|
||||||
import io.ktor.client.engine.okhttp.OkHttp
|
import io.ktor.client.engine.okhttp.OkHttp
|
||||||
|
import io.ktor.utils.io.readAvailable
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import win.taptap.musicmanager.client.data.AppStorage
|
import win.taptap.musicmanager.client.data.AppStorage
|
||||||
import win.taptap.musicmanager.client.playback.AudioPlayer
|
import win.taptap.musicmanager.client.playback.AudioPlayer
|
||||||
@@ -32,7 +33,7 @@ class AndroidStorage(context: Context) : AppStorage {
|
|||||||
|
|
||||||
override fun write(name: String, text: String) {
|
override fun write(name: String, text: String) {
|
||||||
root.mkdirs()
|
root.mkdirs()
|
||||||
File(root, name).writeText(text)
|
atomicWrite(File(root, name)) { it.writeText(text) }
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun delete(name: String) {
|
override fun delete(name: String) {
|
||||||
@@ -42,13 +43,53 @@ class AndroidStorage(context: Context) : AppStorage {
|
|||||||
override fun saveDownload(songId: String, bytes: ByteArray): String? {
|
override fun saveDownload(songId: String, bytes: ByteArray): String? {
|
||||||
downloads.mkdirs()
|
downloads.mkdirs()
|
||||||
val file = File(downloads, "${safeName(songId)}.mp3")
|
val file = File(downloads, "${safeName(songId)}.mp3")
|
||||||
file.writeBytes(bytes)
|
atomicWrite(file) { it.writeBytes(bytes) }
|
||||||
return file.absolutePath
|
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? =
|
override fun downloadPath(songId: String): String? =
|
||||||
File(downloads, "${safeName(songId)}.mp3").takeIf { it.isFile }?.absolutePath
|
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> =
|
override fun listDownloads(): Map<String, Long> =
|
||||||
downloads.listFiles()
|
downloads.listFiles()
|
||||||
?.filter { it.isFile && it.extension == "mp3" }
|
?.filter { it.isFile && it.extension == "mp3" }
|
||||||
@@ -57,11 +98,26 @@ class AndroidStorage(context: Context) : AppStorage {
|
|||||||
|
|
||||||
override fun deleteDownload(songId: String) {
|
override fun deleteDownload(songId: String) {
|
||||||
File(downloads, "${safeName(songId)}.mp3").delete()
|
File(downloads, "${safeName(songId)}.mp3").delete()
|
||||||
|
File(downloads, "${safeName(songId)}.jpg").delete()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun storageUsedBytes(): Long =
|
override fun storageUsedBytes(): Long =
|
||||||
downloads.listFiles()?.sumOf { it.length() } ?: 0L
|
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 =
|
private fun safeName(songId: String): String =
|
||||||
songId.map { if (it.isLetterOrDigit() || it == '-' || it == '_') it else '_' }.joinToString("")
|
songId.map { if (it.isLetterOrDigit() || it == '-' || it == '_') it else '_' }.joinToString("")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,11 +2,23 @@ package win.taptap.musicmanager.client
|
|||||||
|
|
||||||
import android.app.PendingIntent
|
import android.app.PendingIntent
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
import androidx.media3.common.AudioAttributes
|
import androidx.media3.common.AudioAttributes
|
||||||
import androidx.media3.common.C
|
import androidx.media3.common.C
|
||||||
import androidx.media3.exoplayer.ExoPlayer
|
import androidx.media3.exoplayer.ExoPlayer
|
||||||
import androidx.media3.session.MediaSession
|
import androidx.media3.session.MediaSession
|
||||||
import androidx.media3.session.MediaSessionService
|
import androidx.media3.session.MediaSessionService
|
||||||
|
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
|
* Hosts playback in a foreground service so audio continues when the activity
|
||||||
@@ -18,6 +30,8 @@ import androidx.media3.session.MediaSessionService
|
|||||||
class PlaybackService : MediaSessionService() {
|
class PlaybackService : MediaSessionService() {
|
||||||
|
|
||||||
private var mediaSession: MediaSession? = null
|
private var mediaSession: MediaSession? = null
|
||||||
|
private val handler = Handler(Looper.getMainLooper())
|
||||||
|
private val sleepTimer = Runnable { mediaSession?.player?.pause() }
|
||||||
|
|
||||||
override fun onCreate() {
|
override fun onCreate() {
|
||||||
super.onCreate()
|
super.onCreate()
|
||||||
@@ -45,6 +59,37 @@ class PlaybackService : MediaSessionService() {
|
|||||||
|
|
||||||
mediaSession = MediaSession.Builder(this, player)
|
mediaSession = MediaSession.Builder(this, player)
|
||||||
.setSessionActivity(sessionActivity)
|
.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()
|
||||||
|
}
|
||||||
|
|
||||||
|
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()
|
.build()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,6 +104,7 @@ class PlaybackService : MediaSessionService() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun onDestroy() {
|
override fun onDestroy() {
|
||||||
|
handler.removeCallbacks(sleepTimer)
|
||||||
mediaSession?.run {
|
mediaSession?.run {
|
||||||
player.release()
|
player.release()
|
||||||
release()
|
release()
|
||||||
|
|||||||
@@ -5,15 +5,18 @@ import io.ktor.client.call.body
|
|||||||
import io.ktor.client.engine.HttpClientEngine
|
import io.ktor.client.engine.HttpClientEngine
|
||||||
import io.ktor.client.plugins.HttpTimeout
|
import io.ktor.client.plugins.HttpTimeout
|
||||||
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
|
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
|
||||||
|
import io.ktor.client.plugins.timeout
|
||||||
import io.ktor.client.request.HttpRequestBuilder
|
import io.ktor.client.request.HttpRequestBuilder
|
||||||
import io.ktor.client.request.delete
|
import io.ktor.client.request.delete
|
||||||
import io.ktor.client.request.get
|
import io.ktor.client.request.get
|
||||||
import io.ktor.client.request.header
|
import io.ktor.client.request.header
|
||||||
import io.ktor.client.request.patch
|
import io.ktor.client.request.patch
|
||||||
import io.ktor.client.request.post
|
import io.ktor.client.request.post
|
||||||
|
import io.ktor.client.request.put
|
||||||
import io.ktor.client.request.setBody
|
import io.ktor.client.request.setBody
|
||||||
import io.ktor.client.statement.HttpResponse
|
import io.ktor.client.statement.HttpResponse
|
||||||
import io.ktor.client.statement.bodyAsBytes
|
import io.ktor.client.statement.bodyAsBytes
|
||||||
|
import io.ktor.client.statement.bodyAsChannel
|
||||||
import io.ktor.http.ContentType
|
import io.ktor.http.ContentType
|
||||||
import io.ktor.http.HttpHeaders
|
import io.ktor.http.HttpHeaders
|
||||||
import io.ktor.http.HttpStatusCode
|
import io.ktor.http.HttpStatusCode
|
||||||
@@ -21,6 +24,7 @@ import io.ktor.http.contentType
|
|||||||
import io.ktor.http.encodeURLParameter
|
import io.ktor.http.encodeURLParameter
|
||||||
import io.ktor.http.isSuccess
|
import io.ktor.http.isSuccess
|
||||||
import io.ktor.serialization.kotlinx.json.json
|
import io.ktor.serialization.kotlinx.json.json
|
||||||
|
import io.ktor.utils.io.ByteReadChannel
|
||||||
import kotlinx.serialization.json.Json
|
import kotlinx.serialization.json.Json
|
||||||
|
|
||||||
fun configuredHttpClient(engine: HttpClientEngine): HttpClient = HttpClient(engine) {
|
fun configuredHttpClient(engine: HttpClientEngine): HttpClient = HttpClient(engine) {
|
||||||
@@ -53,6 +57,7 @@ class ApiClient(private val http: HttpClient) {
|
|||||||
private set
|
private set
|
||||||
|
|
||||||
private val coverCache = mutableMapOf<String, ByteArray?>()
|
private val coverCache = mutableMapOf<String, ByteArray?>()
|
||||||
|
private val imageCache = mutableMapOf<String, ByteArray?>()
|
||||||
|
|
||||||
suspend fun login(
|
suspend fun login(
|
||||||
serverUrl: String,
|
serverUrl: String,
|
||||||
@@ -79,6 +84,11 @@ class ApiClient(private val http: HttpClient) {
|
|||||||
fun clear() {
|
fun clear() {
|
||||||
token = null
|
token = null
|
||||||
coverCache.clear()
|
coverCache.clear()
|
||||||
|
imageCache.clear()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun close() {
|
||||||
|
http.close()
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun me(): User = get("/me")
|
suspend fun me(): User = get("/me")
|
||||||
@@ -127,22 +137,55 @@ class ApiClient(private val http: HttpClient) {
|
|||||||
requestNoContent { http.delete(url("/moods/$moodId/seeds/$songId")) { auth() } }
|
requestNoContent { http.delete(url("/moods/$moodId/seeds/$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 acceptRecommendation(moodId: String, videoId: String): RecommendationDecision =
|
||||||
|
parse(
|
||||||
|
http.post(url("/moods/$moodId/recommendations/$videoId/accept")) {
|
||||||
|
auth()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
suspend fun rejectRecommendation(moodId: String, videoId: String): RecommendationDecision =
|
||||||
|
parse(
|
||||||
|
http.post(url("/moods/$moodId/recommendations/$videoId/reject")) {
|
||||||
|
auth()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
suspend fun preview(moodId: String, limit: Int = 20): List<Song> =
|
suspend fun preview(moodId: String, limit: Int = 20): List<Song> =
|
||||||
get<SearchResponse>("/moods/$moodId/preview?limit=$limit").songs
|
get<SearchResponse>("/moods/$moodId/preview?limit=$limit").songs
|
||||||
|
|
||||||
suspend fun search(query: String, limit: Int = 50): List<Song> =
|
suspend fun search(query: String, limit: Int = 50, scope: String = "music"): List<Song> =
|
||||||
get<SearchResponse>("/library/search?q=${query.encodeURLParameter()}&limit=$limit").songs
|
get<SearchResponse>(
|
||||||
|
"/library/search?q=${query.encodeURLParameter()}&limit=$limit&scope=$scope",
|
||||||
|
).songs
|
||||||
|
|
||||||
suspend fun library(
|
suspend fun library(
|
||||||
cursor: String? = null,
|
cursor: String? = null,
|
||||||
since: String? = null,
|
since: String? = null,
|
||||||
limit: Int = 500,
|
limit: Int = 500,
|
||||||
scope: String = "all",
|
scope: String = "all",
|
||||||
|
revision: String? = null,
|
||||||
): LibraryPage {
|
): LibraryPage {
|
||||||
val query = buildString {
|
val query = buildString {
|
||||||
append("?limit=$limit&scope=$scope")
|
append("?limit=$limit&scope=$scope")
|
||||||
cursor?.let { append("&cursor=${it.encodeURLParameter()}") }
|
cursor?.let { append("&cursor=${it.encodeURLParameter()}") }
|
||||||
since?.let { append("&since=${it.encodeURLParameter()}") }
|
since?.let { append("&since=${it.encodeURLParameter()}") }
|
||||||
|
revision?.let { append("&revision=${it.encodeURLParameter()}") }
|
||||||
}
|
}
|
||||||
return get("/library/songs$query")
|
return get("/library/songs$query")
|
||||||
}
|
}
|
||||||
@@ -189,6 +232,23 @@ class ApiClient(private val http: HttpClient) {
|
|||||||
runCatching { requestNoContent { http.delete(url("/sessions/$id")) { auth() } } }
|
runCatching { requestNoContent { http.delete(url("/sessions/$id")) { auth() } } }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
suspend fun longformProgress(): List<LongformProgressItem> =
|
||||||
|
get<LongformProgressResponse>("/longform/progress").items
|
||||||
|
|
||||||
|
suspend fun saveLongformProgress(
|
||||||
|
songId: String,
|
||||||
|
positionSeconds: Int,
|
||||||
|
durationSeconds: Int,
|
||||||
|
completed: Boolean,
|
||||||
|
) {
|
||||||
|
val response = http.put(url("/longform/progress/$songId")) {
|
||||||
|
auth()
|
||||||
|
contentType(ContentType.Application.Json)
|
||||||
|
setBody(SaveLongformProgressRequest(positionSeconds, durationSeconds, completed))
|
||||||
|
}
|
||||||
|
if (!response.status.isSuccess()) throw error(response)
|
||||||
|
}
|
||||||
|
|
||||||
suspend fun devices(): List<Device> = get("/auth/devices")
|
suspend fun devices(): List<Device> = get("/auth/devices")
|
||||||
|
|
||||||
suspend fun scanStatus(): ScanStatus = get("/scan")
|
suspend fun scanStatus(): ScanStatus = get("/scan")
|
||||||
@@ -203,20 +263,72 @@ class ApiClient(private val http: HttpClient) {
|
|||||||
suspend fun cover(albumId: String, size: Int = 320): ByteArray? {
|
suspend fun cover(albumId: String, size: Int = 320): ByteArray? {
|
||||||
val key = "$albumId:$size"
|
val key = "$albumId:$size"
|
||||||
if (coverCache.containsKey(key)) return coverCache[key]
|
if (coverCache.containsKey(key)) return coverCache[key]
|
||||||
val bytes = runCatching {
|
val result = runCatching {
|
||||||
http.get("$baseUrl/api/v1/covers/$albumId?size=$size&token=${token.orEmpty().encodeURLParameter()}")
|
val response = http.get(
|
||||||
.bodyAsBytes()
|
"$baseUrl/api/v1/covers/$albumId?size=$size&token=${token.orEmpty().encodeURLParameter()}",
|
||||||
|
)
|
||||||
|
if (response.status.isSuccess()) {
|
||||||
|
response.bodyAsBytes().takeIf { it.isNotEmpty() }
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
}.getOrNull()
|
}.getOrNull()
|
||||||
val result = bytes?.takeIf { it.isNotEmpty() }
|
if (coverCache.size > MAX_CACHED_IMAGES) coverCache.clear()
|
||||||
coverCache[key] = result
|
// Do not cache failures: a cover can appear after the scanner indexes a
|
||||||
|
// newly downloaded track, and the UI should pick it up without a restart.
|
||||||
|
if (result != null) coverCache[key] = result
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun download(songId: String): ByteArray =
|
/** Remote artwork such as YT thumbnails, cached for the app's lifetime. */
|
||||||
http.get("$baseUrl/api/v1/songs/$songId/stream") {
|
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()
|
auth()
|
||||||
url.parameters.append("download", "true")
|
url.parameters.append("download", "true")
|
||||||
}.bodyAsBytes()
|
// A long audiobook must not be cancelled by the default 30s total
|
||||||
|
// request timeout.
|
||||||
|
timeout {
|
||||||
|
requestTimeoutMillis = 6 * 60 * 60 * 1000
|
||||||
|
socketTimeoutMillis = 60_000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!response.status.isSuccess()) throw error(response)
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
fun streamUrl(songId: String): String =
|
fun streamUrl(songId: String): String =
|
||||||
"$baseUrl/api/v1/songs/$songId/stream?token=${token.orEmpty().encodeURLParameter()}"
|
"$baseUrl/api/v1/songs/$songId/stream?token=${token.orEmpty().encodeURLParameter()}"
|
||||||
@@ -253,6 +365,10 @@ class ApiClient(private val http: HttpClient) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val MAX_CACHED_IMAGES = 200
|
||||||
|
}
|
||||||
|
|
||||||
private fun normalize(serverUrl: String): String {
|
private fun normalize(serverUrl: String): String {
|
||||||
var value = serverUrl.trim().trimEnd('/')
|
var value = serverUrl.trim().trimEnd('/')
|
||||||
if (value.isEmpty()) value = "http://localhost:8080"
|
if (value.isEmpty()) value = "http://localhost:8080"
|
||||||
|
|||||||
@@ -62,6 +62,8 @@ data class Mood(
|
|||||||
val query: String? = null,
|
val query: String? = null,
|
||||||
val genres: List<String> = emptyList(),
|
val genres: List<String> = emptyList(),
|
||||||
val targetSize: Int,
|
val targetSize: Int,
|
||||||
|
val seedPercent: Int = 50,
|
||||||
|
val recommendationPercent: Int = 50,
|
||||||
val refreshHours: Int,
|
val refreshHours: Int,
|
||||||
val ytEnabled: Boolean,
|
val ytEnabled: Boolean,
|
||||||
val lastDiscoveryAt: String? = null,
|
val lastDiscoveryAt: String? = null,
|
||||||
@@ -79,6 +81,14 @@ data class Seed(
|
|||||||
val addedAt: String,
|
val addedAt: String,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class Download(
|
||||||
|
val state: String,
|
||||||
|
val attempts: Int = 0,
|
||||||
|
val error: String? = null,
|
||||||
|
val updatedAt: String,
|
||||||
|
)
|
||||||
|
|
||||||
@Serializable
|
@Serializable
|
||||||
data class Recommendation(
|
data class Recommendation(
|
||||||
val videoId: String,
|
val videoId: String,
|
||||||
@@ -92,6 +102,35 @@ data class Recommendation(
|
|||||||
val timesAdded: Int = 0,
|
val timesAdded: Int = 0,
|
||||||
val firstSeen: String,
|
val firstSeen: String,
|
||||||
val lastSeen: String,
|
val lastSeen: String,
|
||||||
|
val download: Download? = null,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class LongformProgressItem(
|
||||||
|
val song: Song,
|
||||||
|
val positionSeconds: Int,
|
||||||
|
val durationSeconds: Int,
|
||||||
|
val completed: Boolean,
|
||||||
|
val updatedAt: String,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class LongformProgressResponse(val items: List<LongformProgressItem> = emptyList())
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class SaveLongformProgressRequest(
|
||||||
|
val positionSeconds: Int,
|
||||||
|
val durationSeconds: Int? = null,
|
||||||
|
val completed: Boolean = false,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class LongformProgress(
|
||||||
|
val songId: String,
|
||||||
|
val positionSeconds: Int,
|
||||||
|
val durationSeconds: Int,
|
||||||
|
val completed: Boolean,
|
||||||
|
val updatedAt: String,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
@Serializable
|
||||||
@@ -104,6 +143,16 @@ data class MoodDetail(
|
|||||||
@Serializable
|
@Serializable
|
||||||
data class MoodsResponse(val moods: List<Mood>)
|
data class MoodsResponse(val moods: List<Mood>)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class RecommendationsResponse(val recommendations: List<Recommendation> = emptyList())
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class RecommendationDecision(
|
||||||
|
val detail: MoodDetail,
|
||||||
|
val recommendation: Recommendation,
|
||||||
|
val seedAdded: Boolean = false,
|
||||||
|
)
|
||||||
|
|
||||||
@Serializable
|
@Serializable
|
||||||
data class LibraryPage(
|
data class LibraryPage(
|
||||||
val songs: List<Song> = emptyList(),
|
val songs: List<Song> = emptyList(),
|
||||||
@@ -170,6 +219,7 @@ data class CreateMoodRequest(
|
|||||||
val refreshHours: Int = 24,
|
val refreshHours: Int = 24,
|
||||||
val ytEnabled: Boolean = true,
|
val ytEnabled: Boolean = true,
|
||||||
val seedSongIds: List<String> = emptyList(),
|
val seedSongIds: List<String> = emptyList(),
|
||||||
|
val seedPercent: Int = 50,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
@Serializable
|
||||||
@@ -183,6 +233,7 @@ data class UpdateMoodRequest(
|
|||||||
val targetSize: Int? = null,
|
val targetSize: Int? = null,
|
||||||
val refreshHours: Int? = null,
|
val refreshHours: Int? = null,
|
||||||
val ytEnabled: Boolean? = null,
|
val ytEnabled: Boolean? = null,
|
||||||
|
val seedPercent: Int? = null,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
@Serializable
|
||||||
|
|||||||
@@ -9,6 +9,13 @@ interface AppStorage {
|
|||||||
/** Returns a platform-specific handle for playback, or null when unsupported. */
|
/** Returns a platform-specific handle for playback, or null when unsupported. */
|
||||||
fun saveDownload(songId: String, bytes: ByteArray): String?
|
fun saveDownload(songId: String, bytes: ByteArray): String?
|
||||||
fun downloadPath(songId: String): 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 listDownloads(): Map<String, Long>
|
||||||
fun deleteDownload(songId: String)
|
fun deleteDownload(songId: String)
|
||||||
fun storageUsedBytes(): Long
|
fun storageUsedBytes(): Long
|
||||||
|
|||||||
+54
-5
@@ -2,8 +2,10 @@ package win.taptap.musicmanager.client.data
|
|||||||
|
|
||||||
import kotlinx.serialization.Serializable
|
import kotlinx.serialization.Serializable
|
||||||
import kotlinx.serialization.json.Json
|
import kotlinx.serialization.json.Json
|
||||||
|
import win.taptap.musicmanager.client.api.LongformProgress
|
||||||
import win.taptap.musicmanager.client.api.Mood
|
import win.taptap.musicmanager.client.api.Mood
|
||||||
import win.taptap.musicmanager.client.api.MoodDetail
|
import win.taptap.musicmanager.client.api.MoodDetail
|
||||||
|
import win.taptap.musicmanager.client.api.Session
|
||||||
import win.taptap.musicmanager.client.api.Song
|
import win.taptap.musicmanager.client.api.Song
|
||||||
import win.taptap.musicmanager.client.api.User
|
import win.taptap.musicmanager.client.api.User
|
||||||
|
|
||||||
@@ -20,10 +22,21 @@ data class CachedState(
|
|||||||
val userName: String = "",
|
val userName: String = "",
|
||||||
val revision: String? = null,
|
val revision: String? = null,
|
||||||
val songs: List<Song> = emptyList(),
|
val songs: List<Song> = emptyList(),
|
||||||
|
val longform: List<Song> = emptyList(),
|
||||||
val moods: List<Mood> = emptyList(),
|
val moods: List<Mood> = emptyList(),
|
||||||
val moodDetails: List<MoodDetail> = emptyList(),
|
val moodDetails: List<MoodDetail> = emptyList(),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/** 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 LibraryCache(private val storage: AppStorage) {
|
class LibraryCache(private val storage: AppStorage) {
|
||||||
|
|
||||||
private val json = Json {
|
private val json = Json {
|
||||||
@@ -33,29 +46,65 @@ class LibraryCache(private val storage: AppStorage) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun loadSession(): SessionState? =
|
fun loadSession(): SessionState? =
|
||||||
storage.read(SESSION_FILE)?.let {
|
read(SESSION_FILE)?.let {
|
||||||
runCatching { json.decodeFromString<SessionState>(it) }.getOrNull()
|
runCatching { json.decodeFromString<SessionState>(it) }.getOrNull()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun saveSession(session: SessionState?) {
|
fun saveSession(session: SessionState?) {
|
||||||
if (session == null) storage.delete(SESSION_FILE) else storage.write(SESSION_FILE, json.encodeToString(session))
|
if (session == null) delete(SESSION_FILE) else write(SESSION_FILE, json.encodeToString(session))
|
||||||
}
|
}
|
||||||
|
|
||||||
fun load(): CachedState =
|
fun load(): CachedState =
|
||||||
storage.read(CACHE_FILE)?.let {
|
read(CACHE_FILE)?.let {
|
||||||
runCatching { json.decodeFromString<CachedState>(it) }.getOrNull()
|
runCatching { json.decodeFromString<CachedState>(it) }.getOrNull()
|
||||||
} ?: CachedState()
|
} ?: CachedState()
|
||||||
|
|
||||||
fun save(state: CachedState) {
|
fun save(state: CachedState) {
|
||||||
storage.write(CACHE_FILE, json.encodeToString(state))
|
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 loadProgress(): List<LongformProgress> =
|
||||||
|
read(PROGRESS_FILE)?.let {
|
||||||
|
runCatching { json.decodeFromString<List<LongformProgress>>(it) }.getOrNull()
|
||||||
|
} ?: emptyList()
|
||||||
|
|
||||||
|
fun saveProgress(progress: List<LongformProgress>) {
|
||||||
|
write(PROGRESS_FILE, json.encodeToString(progress))
|
||||||
}
|
}
|
||||||
|
|
||||||
fun clear() {
|
fun clear() {
|
||||||
storage.delete(CACHE_FILE)
|
delete(CACHE_FILE)
|
||||||
|
delete(PLAYBACK_FILE)
|
||||||
|
delete(PROGRESS_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 {
|
private companion object {
|
||||||
const val SESSION_FILE = "session.json"
|
const val SESSION_FILE = "session.json"
|
||||||
const val CACHE_FILE = "library.json"
|
const val CACHE_FILE = "library.json"
|
||||||
|
const val PLAYBACK_FILE = "playback.json"
|
||||||
|
const val PROGRESS_FILE = "longform-progress.json"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+15
-1
@@ -9,7 +9,13 @@ import win.taptap.musicmanager.client.api.Song
|
|||||||
* store polls [isFinished] because some backends have no callback support.
|
* store polls [isFinished] because some backends have no callback support.
|
||||||
*/
|
*/
|
||||||
interface AudioPlayer {
|
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 pause()
|
||||||
fun resume()
|
fun resume()
|
||||||
fun stop()
|
fun stop()
|
||||||
@@ -20,5 +26,13 @@ interface AudioPlayer {
|
|||||||
val canSeek: Boolean
|
val canSeek: Boolean
|
||||||
fun seekTo(seconds: Double)
|
fun seekTo(seconds: Double)
|
||||||
fun release()
|
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
|
||||||
}
|
}
|
||||||
|
|
||||||
+725
-42
File diff suppressed because it is too large.
Load diff
@@ -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
|
@Composable
|
||||||
fun EmptyState(title: String, subtitle: String? = null, modifier: Modifier = Modifier) {
|
fun EmptyState(title: String, subtitle: String? = null, modifier: Modifier = Modifier) {
|
||||||
Column(
|
Column(
|
||||||
@@ -179,7 +215,7 @@ fun MoodGradient(name: String): Brush {
|
|||||||
Color(0xFF1864AB) to Color(0xFF1098AD),
|
Color(0xFF1864AB) to Color(0xFF1098AD),
|
||||||
Color(0xFF5F3DC4) to Color(0xFF862E9C),
|
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))
|
return Brush.linearGradient(listOf(palette.first, palette.second))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+361
-20
@@ -1,28 +1,43 @@
|
|||||||
package win.taptap.musicmanager.client.ui
|
package win.taptap.musicmanager.client.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
import androidx.compose.foundation.layout.PaddingValues
|
import androidx.compose.foundation.layout.PaddingValues
|
||||||
import androidx.compose.foundation.layout.Row
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.heightIn
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
import androidx.compose.foundation.layout.size
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.layout.width
|
||||||
import androidx.compose.foundation.lazy.LazyColumn
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
import androidx.compose.foundation.lazy.items
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.rounded.CheckCircle
|
import androidx.compose.material.icons.rounded.CheckCircle
|
||||||
import androidx.compose.material.icons.rounded.DeleteOutline
|
import androidx.compose.material.icons.rounded.DeleteOutline
|
||||||
import androidx.compose.material.icons.rounded.Download
|
import androidx.compose.material.icons.rounded.Download
|
||||||
|
import androidx.compose.material.icons.rounded.List
|
||||||
import androidx.compose.material.icons.rounded.PlayArrow
|
import androidx.compose.material.icons.rounded.PlayArrow
|
||||||
import androidx.compose.material.icons.rounded.Search
|
import androidx.compose.material.icons.rounded.Search
|
||||||
|
import androidx.compose.material.icons.rounded.Shuffle
|
||||||
|
import androidx.compose.material3.Button
|
||||||
import androidx.compose.material3.CircularProgressIndicator
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
import androidx.compose.material3.HorizontalDivider
|
import androidx.compose.material3.HorizontalDivider
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
import androidx.compose.material3.IconButton
|
import androidx.compose.material3.IconButton
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.OutlinedTextField
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.material3.Tab
|
||||||
|
import androidx.compose.material3.TabRow
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
@@ -30,8 +45,11 @@ import androidx.compose.runtime.remember
|
|||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.draw.clip
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.window.Dialog
|
||||||
|
import win.taptap.musicmanager.client.api.LongformProgress
|
||||||
import win.taptap.musicmanager.client.api.Song
|
import win.taptap.musicmanager.client.api.Song
|
||||||
import win.taptap.musicmanager.client.platformName
|
import win.taptap.musicmanager.client.platformName
|
||||||
import win.taptap.musicmanager.client.store.AppState
|
import win.taptap.musicmanager.client.store.AppState
|
||||||
@@ -39,6 +57,30 @@ import win.taptap.musicmanager.client.store.AppStore
|
|||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun LibraryScreen(state: AppState, store: AppStore) {
|
fun LibraryScreen(state: AppState, store: AppStore) {
|
||||||
|
var tab by remember { mutableStateOf(0) }
|
||||||
|
|
||||||
|
Column(Modifier.fillMaxSize()) {
|
||||||
|
TabRow(selectedTabIndex = tab) {
|
||||||
|
Tab(
|
||||||
|
selected = tab == 0,
|
||||||
|
onClick = { tab = 0 },
|
||||||
|
text = { Text("Music") },
|
||||||
|
)
|
||||||
|
Tab(
|
||||||
|
selected = tab == 1,
|
||||||
|
onClick = { tab = 1 },
|
||||||
|
text = { Text("Longform") },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
when (tab) {
|
||||||
|
0 -> MusicLibrary(state, store)
|
||||||
|
else -> LongformLibrary(state, store)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun MusicLibrary(state: AppState, store: AppStore) {
|
||||||
var query by remember { mutableStateOf("") }
|
var query by remember { mutableStateOf("") }
|
||||||
val supported = platformName != "web"
|
val supported = platformName != "web"
|
||||||
val downloadedSongs = state.library.filter { it.id in state.downloads }
|
val downloadedSongs = state.library.filter { it.id in state.downloads }
|
||||||
@@ -51,9 +93,12 @@ fun LibraryScreen(state: AppState, store: AppStore) {
|
|||||||
item {
|
item {
|
||||||
OutlinedTextField(
|
OutlinedTextField(
|
||||||
value = query,
|
value = query,
|
||||||
onValueChange = { query = it },
|
onValueChange = {
|
||||||
|
query = it
|
||||||
|
store.searchMusic(it)
|
||||||
|
},
|
||||||
singleLine = true,
|
singleLine = true,
|
||||||
label = { Text("Search library") },
|
label = { Text("Search music") },
|
||||||
leadingIcon = { Icon(Icons.Rounded.Search, contentDescription = null) },
|
leadingIcon = { Icon(Icons.Rounded.Search, contentDescription = null) },
|
||||||
trailingIcon = {
|
trailingIcon = {
|
||||||
if (state.searching) {
|
if (state.searching) {
|
||||||
@@ -64,17 +109,52 @@ fun LibraryScreen(state: AppState, store: AppStore) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (state.searchResults.isNotEmpty()) {
|
item {
|
||||||
|
Surface(
|
||||||
|
shape = RoundedCornerShape(18.dp),
|
||||||
|
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.padding(16.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
|
) {
|
||||||
|
Column(Modifier.weight(1f)) {
|
||||||
|
Text("All music", style = MaterialTheme.typography.titleMedium)
|
||||||
|
Text(
|
||||||
|
if (state.library.isEmpty()) {
|
||||||
|
"Nothing in the library yet"
|
||||||
|
} else {
|
||||||
|
"${state.library.size} tracks, shuffled into a queue"
|
||||||
|
},
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Button(
|
||||||
|
onClick = { store.playAll() },
|
||||||
|
enabled = state.library.isNotEmpty(),
|
||||||
|
) {
|
||||||
|
Icon(Icons.Rounded.Shuffle, contentDescription = null, modifier = Modifier.size(18.dp))
|
||||||
|
Spacer(Modifier.width(6.dp))
|
||||||
|
Text("Shuffle all")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (state.musicResults.isNotEmpty()) {
|
||||||
item {
|
item {
|
||||||
SectionTitle("Search results") {
|
SectionTitle("Search results") {
|
||||||
Text(
|
Text(
|
||||||
"${state.searchResults.size}",
|
"${state.musicResults.size}",
|
||||||
style = MaterialTheme.typography.labelSmall,
|
style = MaterialTheme.typography.labelSmall,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
items(state.searchResults, key = { "search-${it.id}" }) { song ->
|
items(state.musicResults, key = { "search-${it.id}" }) { song ->
|
||||||
LibrarySongRow(song, state, store, supported)
|
LibrarySongRow(song, state, store, supported)
|
||||||
}
|
}
|
||||||
item { HorizontalDivider(Modifier.padding(vertical = 14.dp)) }
|
item { HorizontalDivider(Modifier.padding(vertical = 14.dp)) }
|
||||||
@@ -122,10 +202,284 @@ fun LibraryScreen(state: AppState, store: AppStore) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun LongformLibrary(state: AppState, store: AppStore) {
|
||||||
|
var query by remember { mutableStateOf("") }
|
||||||
|
var artistDialog by remember { mutableStateOf<String?>(null) }
|
||||||
|
val supported = platformName != "web"
|
||||||
|
|
||||||
|
val byArtist = state.longform.groupBy { it.artist }
|
||||||
|
val artistNames = byArtist.keys.sortedBy { it.lowercase() }
|
||||||
|
val continueListening = state.longformProgress.values
|
||||||
|
.asSequence()
|
||||||
|
.filterNot { it.completed }
|
||||||
|
.sortedByDescending { it.updatedAt }
|
||||||
|
.mapNotNull { progress ->
|
||||||
|
state.longform.firstOrNull { it.id == progress.songId }?.let { it to progress }
|
||||||
|
}
|
||||||
|
.take(5)
|
||||||
|
.toList()
|
||||||
|
|
||||||
|
LazyColumn(
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
contentPadding = PaddingValues(20.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||||
|
) {
|
||||||
|
item {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = query,
|
||||||
|
onValueChange = {
|
||||||
|
query = it
|
||||||
|
store.searchLongform(it)
|
||||||
|
},
|
||||||
|
singleLine = true,
|
||||||
|
label = { Text("Search audiobooks and podcasts") },
|
||||||
|
leadingIcon = { Icon(Icons.Rounded.Search, contentDescription = null) },
|
||||||
|
trailingIcon = {
|
||||||
|
if (state.searching) {
|
||||||
|
CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (state.longformResults.isNotEmpty()) {
|
||||||
|
item { SectionTitle("Search results") }
|
||||||
|
items(state.longformResults, key = { "lf-search-${it.id}" }) { song ->
|
||||||
|
LongformSongRow(song, state, store, supported) { store.playLongformSong(song) }
|
||||||
|
}
|
||||||
|
item { HorizontalDivider(Modifier.padding(vertical = 14.dp)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (continueListening.isNotEmpty()) {
|
||||||
|
item { SectionTitle("Continue listening") }
|
||||||
|
items(continueListening, key = { "continue-${it.first.id}" }) { (song, progress) ->
|
||||||
|
ContinueRow(song, progress, store)
|
||||||
|
}
|
||||||
|
item { HorizontalDivider(Modifier.padding(vertical = 14.dp)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
item {
|
||||||
|
SectionTitle("Artists") {
|
||||||
|
Text(
|
||||||
|
"${artistNames.size}",
|
||||||
|
style = MaterialTheme.typography.labelSmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (artistNames.isEmpty()) {
|
||||||
|
item {
|
||||||
|
EmptyState(
|
||||||
|
"No long-form content",
|
||||||
|
"Add audiobooks or podcasts to a folder of type longform in library.yaml.",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
items(artistNames, key = { "artist-$it" }) { artist ->
|
||||||
|
val songs = byArtist[artist].orEmpty()
|
||||||
|
ArtistRow(
|
||||||
|
name = artist,
|
||||||
|
count = songs.size,
|
||||||
|
onShuffle = { store.playLongformArtist(artist) },
|
||||||
|
onOpen = { artistDialog = artist },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
artistDialog?.let { artist ->
|
||||||
|
LongformArtistDialog(
|
||||||
|
artist = artist,
|
||||||
|
songs = byArtist[artist].orEmpty(),
|
||||||
|
state = state,
|
||||||
|
store = store,
|
||||||
|
supported = supported,
|
||||||
|
onDismiss = { artistDialog = null },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun ContinueRow(song: Song, progress: LongformProgress, store: AppStore) {
|
||||||
|
val duration = progress.durationSeconds.takeIf { it > 0 } ?: song.duration
|
||||||
|
val fraction = if (duration > 0) {
|
||||||
|
(progress.positionSeconds.toFloat() / duration).coerceIn(0f, 1f)
|
||||||
|
} else {
|
||||||
|
0f
|
||||||
|
}
|
||||||
|
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.clickable { store.resumeLongform(song.id) }
|
||||||
|
.padding(vertical = 8.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
|
) {
|
||||||
|
Cover(store, song.albumId, Modifier.size(44.dp), size = 96)
|
||||||
|
Column(Modifier.weight(1f)) {
|
||||||
|
Text(song.title, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
Text(
|
||||||
|
song.artist,
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
)
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(top = 4.dp)
|
||||||
|
.height(3.dp)
|
||||||
|
.clip(RoundedCornerShape(2.dp))
|
||||||
|
.background(MaterialTheme.colorScheme.surfaceVariant),
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.fillMaxWidth(fraction)
|
||||||
|
.height(3.dp)
|
||||||
|
.background(MaterialTheme.colorScheme.primary),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Text(
|
||||||
|
"${formatDuration(progress.positionSeconds)} / ${formatDuration(duration)}",
|
||||||
|
style = MaterialTheme.typography.labelSmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
IconButton(onClick = { store.resumeLongform(song.id) }) {
|
||||||
|
Icon(Icons.Rounded.PlayArrow, contentDescription = "Resume")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun ArtistRow(
|
||||||
|
name: String,
|
||||||
|
count: Int,
|
||||||
|
onShuffle: () -> Unit,
|
||||||
|
onOpen: () -> Unit,
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth().clickable(onClick = onOpen).padding(vertical = 8.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
|
) {
|
||||||
|
Column(Modifier.weight(1f)) {
|
||||||
|
Text(name, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
Text(
|
||||||
|
"$count tracks",
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
IconButton(onClick = onShuffle) {
|
||||||
|
Icon(Icons.Rounded.Shuffle, contentDescription = "Play $name shuffled")
|
||||||
|
}
|
||||||
|
IconButton(onClick = onOpen) {
|
||||||
|
Icon(Icons.Rounded.List, contentDescription = "Show tracks")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun LongformArtistDialog(
|
||||||
|
artist: String,
|
||||||
|
songs: List<Song>,
|
||||||
|
state: AppState,
|
||||||
|
store: AppStore,
|
||||||
|
supported: Boolean,
|
||||||
|
onDismiss: () -> Unit,
|
||||||
|
) {
|
||||||
|
Dialog(onDismissRequest = onDismiss) {
|
||||||
|
Surface(
|
||||||
|
shape = RoundedCornerShape(18.dp),
|
||||||
|
color = MaterialTheme.colorScheme.surface,
|
||||||
|
tonalElevation = 6.dp,
|
||||||
|
modifier = Modifier.fillMaxWidth().heightIn(max = 600.dp),
|
||||||
|
) {
|
||||||
|
Column {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.padding(20.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Column(Modifier.weight(1f)) {
|
||||||
|
Text(artist, style = MaterialTheme.typography.titleMedium, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
Text(
|
||||||
|
"${songs.size} tracks · read-only playlist",
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
TextButton(onClick = onDismiss) { Text("Close") }
|
||||||
|
}
|
||||||
|
Row(modifier = Modifier.padding(horizontal = 20.dp)) {
|
||||||
|
Button(
|
||||||
|
onClick = {
|
||||||
|
store.playLongformArtist(artist)
|
||||||
|
onDismiss()
|
||||||
|
},
|
||||||
|
enabled = songs.isNotEmpty(),
|
||||||
|
) {
|
||||||
|
Icon(Icons.Rounded.Shuffle, contentDescription = null, modifier = Modifier.size(18.dp))
|
||||||
|
Spacer(Modifier.width(6.dp))
|
||||||
|
Text("Shuffle artist")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
HorizontalDivider(Modifier.padding(vertical = 12.dp))
|
||||||
|
LazyColumn(Modifier.fillMaxWidth().heightIn(max = 460.dp)) {
|
||||||
|
items(songs, key = { "artist-song-${it.id}" }) { song ->
|
||||||
|
LongformSongRow(song, state, store, supported) {
|
||||||
|
store.playLongformSong(song)
|
||||||
|
onDismiss()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun LongformSongRow(
|
||||||
|
song: Song,
|
||||||
|
state: AppState,
|
||||||
|
store: AppStore,
|
||||||
|
supported: Boolean,
|
||||||
|
onPlay: () -> Unit,
|
||||||
|
) {
|
||||||
|
SongRow(store = store, song = song, onPlay = onPlay) {
|
||||||
|
DownloadAction(song, state, store, supported)
|
||||||
|
IconButton(onClick = onPlay) {
|
||||||
|
Icon(Icons.Rounded.PlayArrow, contentDescription = "Play")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun LibrarySongRow(song: Song, state: AppState, store: AppStore, supported: Boolean) {
|
private fun LibrarySongRow(song: Song, state: AppState, store: AppStore, supported: Boolean) {
|
||||||
SongRow(store = store, song = song, onPlay = { store.playSong(song) }) {
|
SongRow(store = store, song = song, onPlay = { store.playSong(song) }) {
|
||||||
if (supported) {
|
DownloadAction(song, state, store, supported)
|
||||||
|
if (song.id in state.downloads) {
|
||||||
|
Icon(
|
||||||
|
Icons.Rounded.CheckCircle,
|
||||||
|
contentDescription = "Downloaded",
|
||||||
|
tint = MaterialTheme.colorScheme.secondary,
|
||||||
|
modifier = Modifier.size(18.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
IconButton(onClick = { store.playSong(song) }) {
|
||||||
|
Icon(Icons.Rounded.PlayArrow, contentDescription = "Play")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun DownloadAction(song: Song, state: AppState, store: AppStore, supported: Boolean) {
|
||||||
|
if (!supported) return
|
||||||
when {
|
when {
|
||||||
song.id in state.downloading -> CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp)
|
song.id in state.downloading -> CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp)
|
||||||
song.id in state.downloads -> {
|
song.id in state.downloads -> {
|
||||||
@@ -140,16 +494,3 @@ private fun LibrarySongRow(song: Song, state: AppState, store: AppStore, support
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
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")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+161
-17
@@ -15,7 +15,10 @@ import androidx.compose.foundation.lazy.items
|
|||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.rounded.Add
|
import androidx.compose.material.icons.rounded.Add
|
||||||
|
import androidx.compose.material.icons.rounded.Check
|
||||||
|
import androidx.compose.material.icons.rounded.Close
|
||||||
import androidx.compose.material.icons.rounded.PlayArrow
|
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.RemoveCircleOutline
|
||||||
import androidx.compose.material3.Button
|
import androidx.compose.material3.Button
|
||||||
import androidx.compose.material3.CircularProgressIndicator
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
@@ -26,10 +29,13 @@ import androidx.compose.material3.IconButton
|
|||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.OutlinedButton
|
import androidx.compose.material3.OutlinedButton
|
||||||
import androidx.compose.material3.OutlinedTextField
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.Slider
|
||||||
import androidx.compose.material3.Surface
|
import androidx.compose.material3.Surface
|
||||||
import androidx.compose.material3.Switch
|
import androidx.compose.material3.Switch
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
@@ -39,6 +45,8 @@ import androidx.compose.ui.Modifier
|
|||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
|
import kotlin.math.roundToInt
|
||||||
|
import win.taptap.musicmanager.client.api.Recommendation
|
||||||
import win.taptap.musicmanager.client.api.Song
|
import win.taptap.musicmanager.client.api.Song
|
||||||
import win.taptap.musicmanager.client.store.AppState
|
import win.taptap.musicmanager.client.store.AppState
|
||||||
import win.taptap.musicmanager.client.store.AppStore
|
import win.taptap.musicmanager.client.store.AppStore
|
||||||
@@ -61,13 +69,26 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
|
|||||||
|
|
||||||
val mood = detail.mood
|
val mood = detail.mood
|
||||||
var seedQuery by remember { mutableStateOf("") }
|
var seedQuery by remember { mutableStateOf("") }
|
||||||
var name by remember(mood.id, mood.changedAt) { mutableStateOf(mood.name) }
|
var name by remember(mood.id) { mutableStateOf(mood.name) }
|
||||||
var description by remember(mood.id, mood.changedAt) { mutableStateOf(mood.description.orEmpty()) }
|
var description by remember(mood.id) { mutableStateOf(mood.description.orEmpty()) }
|
||||||
var genres by remember(mood.id, mood.changedAt) { mutableStateOf(mood.genres.joinToString(", ")) }
|
var genres by remember(mood.id) { mutableStateOf(mood.genres.joinToString(", ")) }
|
||||||
var query by remember(mood.id, mood.changedAt) { mutableStateOf(mood.query.orEmpty()) }
|
var query by remember(mood.id) { mutableStateOf(mood.query.orEmpty()) }
|
||||||
var target by remember(mood.id, mood.changedAt) { mutableStateOf(mood.targetSize.toString()) }
|
var target by remember(mood.id) { mutableStateOf(mood.targetSize.toString()) }
|
||||||
var hours by remember(mood.id, mood.changedAt) { mutableStateOf(mood.refreshHours.toString()) }
|
var hours by remember(mood.id) { mutableStateOf(mood.refreshHours.toString()) }
|
||||||
var yt by remember(mood.id, mood.changedAt) { mutableStateOf(mood.ytEnabled) }
|
var yt by remember(mood.id) { mutableStateOf(mood.ytEnabled) }
|
||||||
|
var seedPercent by remember(mood.id) { mutableStateOf(mood.seedPercent.toFloat()) }
|
||||||
|
|
||||||
|
val pendingDownloads = detail.recommendations.count {
|
||||||
|
it.download?.state == "queued" || it.download?.state == "downloading"
|
||||||
|
}
|
||||||
|
LaunchedEffect(detail.mood.id, pendingDownloads) {
|
||||||
|
var polls = 0
|
||||||
|
while (pendingDownloads > 0 && polls < 60) {
|
||||||
|
kotlinx.coroutines.delay(10_000)
|
||||||
|
store.refreshSelectedMood()
|
||||||
|
polls += 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
val seedIds = detail.seeds.map { it.song.id }.toSet()
|
val seedIds = detail.seeds.map { it.song.id }.toSet()
|
||||||
val searchResults = state.searchResults.filterNot { it.id in seedIds }
|
val searchResults = state.searchResults.filterNot { it.id in seedIds }
|
||||||
@@ -93,6 +114,11 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
|
|||||||
Text("${mood.seedCount} seeds", style = MaterialTheme.typography.labelMedium)
|
Text("${mood.seedCount} seeds", style = MaterialTheme.typography.labelMedium)
|
||||||
Text("·", color = MaterialTheme.colorScheme.onSurfaceVariant)
|
Text("·", color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
Text("${mood.targetSize} batch", style = MaterialTheme.typography.labelMedium)
|
Text("${mood.targetSize} batch", style = MaterialTheme.typography.labelMedium)
|
||||||
|
Text("·", color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
Text(
|
||||||
|
"${mood.seedPercent}% seeds",
|
||||||
|
style = MaterialTheme.typography.labelMedium,
|
||||||
|
)
|
||||||
Spacer(Modifier.weight(1f))
|
Spacer(Modifier.weight(1f))
|
||||||
Button(onClick = { store.playMood(mood.id) }) {
|
Button(onClick = { store.playMood(mood.id) }) {
|
||||||
Icon(Icons.Rounded.PlayArrow, contentDescription = null, modifier = Modifier.size(18.dp))
|
Icon(Icons.Rounded.PlayArrow, contentDescription = null, modifier = Modifier.size(18.dp))
|
||||||
@@ -188,25 +214,43 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (detail.recommendations.isNotEmpty()) {
|
if (mood.ytEnabled) {
|
||||||
item {
|
item {
|
||||||
HorizontalDivider(Modifier.padding(vertical = 12.dp))
|
HorizontalDivider(Modifier.padding(vertical = 12.dp))
|
||||||
SectionTitle("Recommendations")
|
SectionTitle("Recommended for this mood") {
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
if (state.discovering) {
|
||||||
|
CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
}
|
}
|
||||||
items(detail.recommendations, key = { it.videoId }) { recommendation ->
|
TextButton(
|
||||||
Row(
|
onClick = { store.refreshRecommendations() },
|
||||||
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
|
enabled = !state.discovering,
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
) {
|
) {
|
||||||
Column(Modifier.weight(1f)) {
|
Icon(Icons.Rounded.Refresh, contentDescription = null, modifier = Modifier.size(16.dp))
|
||||||
Text(recommendation.title, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
Spacer(Modifier.width(4.dp))
|
||||||
|
Text("Refresh")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val visible = detail.recommendations.filter { it.state != "rejected" }
|
||||||
|
if (visible.isEmpty()) {
|
||||||
|
item {
|
||||||
Text(
|
Text(
|
||||||
recommendation.artist,
|
if (state.discovering) {
|
||||||
|
"Searching YouTube Music..."
|
||||||
|
} else {
|
||||||
|
"No recommendations yet. Refresh to search for tracks that fit this mood."
|
||||||
|
},
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
Text(recommendation.state, style = MaterialTheme.typography.labelSmall)
|
} else {
|
||||||
|
items(visible, key = { "rec-${it.videoId}" }) { recommendation ->
|
||||||
|
RecommendationRow(recommendation, state.discovering, store)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -262,6 +306,23 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
|
|||||||
modifier = Modifier.weight(1f),
|
modifier = Modifier.weight(1f),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||||
|
Text(
|
||||||
|
"Seed mix: ${seedPercent.roundToInt()}% seeds · ${100 - seedPercent.roundToInt()}% recommendations",
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
)
|
||||||
|
Slider(
|
||||||
|
value = seedPercent,
|
||||||
|
onValueChange = { seedPercent = it },
|
||||||
|
valueRange = 0f..100f,
|
||||||
|
steps = 9,
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
"Each queued track rolls this share independently; if one side runs out, the other fills in.",
|
||||||
|
style = MaterialTheme.typography.labelSmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
Text("YT Music discovery", Modifier.weight(1f))
|
Text("YT Music discovery", Modifier.weight(1f))
|
||||||
Switch(checked = yt, onCheckedChange = { yt = it })
|
Switch(checked = yt, onCheckedChange = { yt = it })
|
||||||
@@ -278,6 +339,7 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
|
|||||||
targetSize = target.toIntOrNull() ?: mood.targetSize,
|
targetSize = target.toIntOrNull() ?: mood.targetSize,
|
||||||
refreshHours = hours.toIntOrNull() ?: mood.refreshHours,
|
refreshHours = hours.toIntOrNull() ?: mood.refreshHours,
|
||||||
ytEnabled = yt,
|
ytEnabled = yt,
|
||||||
|
seedPercent = seedPercent.roundToInt(),
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
@@ -290,3 +352,85 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
|
|||||||
item { Spacer(Modifier.size(24.dp)) }
|
item { Spacer(Modifier.size(24.dp)) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun RecommendationRow(
|
||||||
|
recommendation: Recommendation,
|
||||||
|
busy: Boolean,
|
||||||
|
store: AppStore,
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
|
) {
|
||||||
|
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.album?.takeIf { it.isNotBlank() }?.let { append(" · ").append(it) }
|
||||||
|
},
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
)
|
||||||
|
val download = recommendation.download
|
||||||
|
Text(
|
||||||
|
when {
|
||||||
|
recommendation.state == "accepted" && recommendation.matchedSong != null -> "Seed added"
|
||||||
|
download?.state == "downloading" -> "Downloading..."
|
||||||
|
download?.state == "failed" -> "Download failed — tap ✓ to retry"
|
||||||
|
download?.state == "queued" -> "Download queued"
|
||||||
|
recommendation.state == "accepted" -> "Queued for download"
|
||||||
|
recommendation.matchedSong != null -> "In your library"
|
||||||
|
else -> "New"
|
||||||
|
},
|
||||||
|
style = MaterialTheme.typography.labelSmall,
|
||||||
|
color = when {
|
||||||
|
download?.state == "failed" -> MaterialTheme.colorScheme.error
|
||||||
|
recommendation.state == "accepted" || download != null ->
|
||||||
|
MaterialTheme.colorScheme.primary
|
||||||
|
else -> MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if (download?.state == "failed" && download.error != null) {
|
||||||
|
Text(
|
||||||
|
download.error,
|
||||||
|
style = MaterialTheme.typography.labelSmall,
|
||||||
|
color = MaterialTheme.colorScheme.error,
|
||||||
|
maxLines = 2,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (recommendation.state == "accepted" && recommendation.download?.state != "failed") {
|
||||||
|
Icon(
|
||||||
|
Icons.Rounded.Check,
|
||||||
|
contentDescription = "Accepted",
|
||||||
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
|
modifier = Modifier.size(20.dp),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
IconButton(
|
||||||
|
onClick = { store.acceptRecommendation(recommendation.videoId) },
|
||||||
|
enabled = !busy,
|
||||||
|
) {
|
||||||
|
Icon(Icons.Rounded.Check, contentDescription = "Accept recommendation")
|
||||||
|
}
|
||||||
|
IconButton(
|
||||||
|
onClick = { store.rejectRecommendation(recommendation.videoId) },
|
||||||
|
enabled = !busy,
|
||||||
|
) {
|
||||||
|
Icon(Icons.Rounded.Close, contentDescription = "Reject recommendation")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -31,6 +31,7 @@ import androidx.compose.material3.FilledTonalButton
|
|||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.OutlinedTextField
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.Slider
|
||||||
import androidx.compose.material3.Switch
|
import androidx.compose.material3.Switch
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.material3.TextButton
|
import androidx.compose.material3.TextButton
|
||||||
@@ -46,6 +47,7 @@ import androidx.compose.ui.graphics.Color
|
|||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
|
import kotlin.math.roundToInt
|
||||||
import win.taptap.musicmanager.client.api.Mood
|
import win.taptap.musicmanager.client.api.Mood
|
||||||
import win.taptap.musicmanager.client.store.AppState
|
import win.taptap.musicmanager.client.store.AppState
|
||||||
import win.taptap.musicmanager.client.store.AppStore
|
import win.taptap.musicmanager.client.store.AppStore
|
||||||
@@ -114,9 +116,9 @@ fun MoodsScreen(state: AppState, store: AppStore) {
|
|||||||
CreateMoodDialog(
|
CreateMoodDialog(
|
||||||
saving = state.saving,
|
saving = state.saving,
|
||||||
onDismiss = { creating = false },
|
onDismiss = { creating = false },
|
||||||
onCreate = { name, description, genres, query, target, hours, yt ->
|
onCreate = { name, description, genres, query, target, hours, yt, seedPercent ->
|
||||||
creating = false
|
creating = false
|
||||||
store.createMood(name, description, genres, query, target, hours, yt)
|
store.createMood(name, description, genres, query, target, hours, yt, seedPercent)
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -184,7 +186,7 @@ private fun MoodCard(mood: Mood, onOpen: () -> Unit, onPlay: () -> Unit) {
|
|||||||
private fun CreateMoodDialog(
|
private fun CreateMoodDialog(
|
||||||
saving: Boolean,
|
saving: Boolean,
|
||||||
onDismiss: () -> Unit,
|
onDismiss: () -> Unit,
|
||||||
onCreate: (String, String?, List<String>, String?, Int, Int, Boolean) -> Unit,
|
onCreate: (String, String?, List<String>, String?, Int, Int, Boolean, Int) -> Unit,
|
||||||
) {
|
) {
|
||||||
var name by remember { mutableStateOf("") }
|
var name by remember { mutableStateOf("") }
|
||||||
var description by remember { mutableStateOf("") }
|
var description by remember { mutableStateOf("") }
|
||||||
@@ -193,6 +195,7 @@ private fun CreateMoodDialog(
|
|||||||
var target by remember { mutableStateOf("30") }
|
var target by remember { mutableStateOf("30") }
|
||||||
var hours by remember { mutableStateOf("24") }
|
var hours by remember { mutableStateOf("24") }
|
||||||
var yt by remember { mutableStateOf(true) }
|
var yt by remember { mutableStateOf(true) }
|
||||||
|
var seedPercent by remember { mutableStateOf(50f) }
|
||||||
|
|
||||||
AlertDialog(
|
AlertDialog(
|
||||||
onDismissRequest = onDismiss,
|
onDismissRequest = onDismiss,
|
||||||
@@ -242,6 +245,18 @@ private fun CreateMoodDialog(
|
|||||||
modifier = Modifier.weight(1f),
|
modifier = Modifier.weight(1f),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||||
|
Text(
|
||||||
|
"Seed mix: ${seedPercent.roundToInt()}% seeds · ${100 - seedPercent.roundToInt()}% recommendations",
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
)
|
||||||
|
Slider(
|
||||||
|
value = seedPercent,
|
||||||
|
onValueChange = { seedPercent = it },
|
||||||
|
valueRange = 0f..100f,
|
||||||
|
steps = 9,
|
||||||
|
)
|
||||||
|
}
|
||||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
Text("YT Music discovery", Modifier.weight(1f))
|
Text("YT Music discovery", Modifier.weight(1f))
|
||||||
Switch(checked = yt, onCheckedChange = { yt = it })
|
Switch(checked = yt, onCheckedChange = { yt = it })
|
||||||
@@ -260,6 +275,7 @@ private fun CreateMoodDialog(
|
|||||||
target.toIntOrNull() ?: 30,
|
target.toIntOrNull() ?: 30,
|
||||||
hours.toIntOrNull() ?: 24,
|
hours.toIntOrNull() ?: 24,
|
||||||
yt,
|
yt,
|
||||||
|
seedPercent.roundToInt(),
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
) { Text("Create") }
|
) { Text("Create") }
|
||||||
|
|||||||
@@ -1,25 +1,41 @@
|
|||||||
package win.taptap.musicmanager.client.ui
|
package win.taptap.musicmanager.client.ui
|
||||||
|
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
import androidx.compose.foundation.layout.Row
|
import androidx.compose.foundation.layout.Row
|
||||||
import androidx.compose.foundation.layout.Spacer
|
import androidx.compose.foundation.layout.Spacer
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.heightIn
|
||||||
|
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
import androidx.compose.foundation.layout.size
|
import androidx.compose.foundation.layout.size
|
||||||
import androidx.compose.foundation.layout.width
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.itemsIndexed
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.rounded.AddCircleOutline
|
import androidx.compose.material.icons.rounded.AddCircleOutline
|
||||||
|
import androidx.compose.material.icons.rounded.Bedtime
|
||||||
|
import androidx.compose.material.icons.rounded.Close
|
||||||
|
import androidx.compose.material.icons.rounded.KeyboardArrowDown
|
||||||
|
import androidx.compose.material.icons.rounded.KeyboardArrowUp
|
||||||
import androidx.compose.material.icons.rounded.Pause
|
import androidx.compose.material.icons.rounded.Pause
|
||||||
import androidx.compose.material.icons.rounded.PlayArrow
|
import androidx.compose.material.icons.rounded.PlayArrow
|
||||||
import androidx.compose.material.icons.rounded.PlaylistAdd
|
import androidx.compose.material.icons.rounded.PlaylistAdd
|
||||||
|
import androidx.compose.material.icons.rounded.QueueMusic
|
||||||
import androidx.compose.material.icons.rounded.SkipNext
|
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.Icon
|
||||||
import androidx.compose.material3.IconButton
|
import androidx.compose.material3.IconButton
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.Slider
|
import androidx.compose.material3.Slider
|
||||||
import androidx.compose.material3.Surface
|
import androidx.compose.material3.Surface
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
@@ -29,6 +45,7 @@ import androidx.compose.ui.Alignment
|
|||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.window.Dialog
|
||||||
import win.taptap.musicmanager.client.store.AppState
|
import win.taptap.musicmanager.client.store.AppState
|
||||||
import win.taptap.musicmanager.client.store.AppStore
|
import win.taptap.musicmanager.client.store.AppStore
|
||||||
|
|
||||||
@@ -36,11 +53,16 @@ import win.taptap.musicmanager.client.store.AppStore
|
|||||||
fun PlayerBar(state: AppState, store: AppStore) {
|
fun PlayerBar(state: AppState, store: AppStore) {
|
||||||
val song = state.current ?: return
|
val song = state.current ?: return
|
||||||
var picker by remember { mutableStateOf(false) }
|
var picker by remember { mutableStateOf(false) }
|
||||||
|
var sleepMenu by remember { mutableStateOf(false) }
|
||||||
|
var queueOpen by remember { mutableStateOf(false) }
|
||||||
var dragSeconds by remember(song.id) { mutableStateOf<Float?>(null) }
|
var dragSeconds by remember(song.id) { mutableStateOf<Float?>(null) }
|
||||||
|
val sleepRemaining = state.sleepTimerRemainingSeconds
|
||||||
|
val isLongform = state.user?.longformFolders?.contains(song.folderId) == true
|
||||||
|
|
||||||
Surface(
|
Surface(
|
||||||
color = MaterialTheme.colorScheme.surfaceVariant,
|
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||||
tonalElevation = 8.dp,
|
tonalElevation = 8.dp,
|
||||||
|
modifier = Modifier.navigationBarsPadding(),
|
||||||
) {
|
) {
|
||||||
Column(Modifier.fillMaxWidth()) {
|
Column(Modifier.fillMaxWidth()) {
|
||||||
val progress = if (state.durationSeconds > 0) {
|
val progress = if (state.durationSeconds > 0) {
|
||||||
@@ -48,16 +70,65 @@ fun PlayerBar(state: AppState, store: AppStore) {
|
|||||||
} else {
|
} else {
|
||||||
0f
|
0f
|
||||||
}
|
}
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth().padding(start = 8.dp, end = 4.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
Slider(
|
Slider(
|
||||||
value = dragSeconds ?: progress,
|
value = dragSeconds ?: progress,
|
||||||
onValueChange = { dragSeconds = it },
|
onValueChange = { dragSeconds = it },
|
||||||
onValueChangeFinished = {
|
onValueChangeFinished = {
|
||||||
dragSeconds?.let { store.seekTo(it * state.durationSeconds) }
|
dragSeconds?.let { fraction ->
|
||||||
|
if (state.durationSeconds > 0) {
|
||||||
|
store.seekTo(fraction * state.durationSeconds)
|
||||||
|
}
|
||||||
|
}
|
||||||
dragSeconds = null
|
dragSeconds = null
|
||||||
},
|
},
|
||||||
enabled = store.canSeek(),
|
enabled = store.canSeek() && state.durationSeconds > 0,
|
||||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),
|
modifier = Modifier.weight(1f),
|
||||||
)
|
)
|
||||||
|
IconButton(onClick = { queueOpen = true }) {
|
||||||
|
Icon(Icons.Rounded.QueueMusic, contentDescription = "Queue")
|
||||||
|
}
|
||||||
|
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(
|
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),
|
||||||
@@ -80,18 +151,33 @@ fun PlayerBar(state: AppState, store: AppStore) {
|
|||||||
overflow = TextOverflow.Ellipsis,
|
overflow = TextOverflow.Ellipsis,
|
||||||
)
|
)
|
||||||
Text(
|
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,
|
style = MaterialTheme.typography.labelSmall,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!isLongform) {
|
||||||
IconButton(onClick = { store.addCurrentToMood(null) }) {
|
IconButton(onClick = { store.addCurrentToMood(null) }) {
|
||||||
Icon(Icons.Rounded.AddCircleOutline, contentDescription = "Add to current mood")
|
Icon(Icons.Rounded.AddCircleOutline, contentDescription = "Add to current mood")
|
||||||
}
|
}
|
||||||
IconButton(onClick = { picker = true }) {
|
IconButton(onClick = { picker = true }) {
|
||||||
Icon(Icons.Rounded.PlaylistAdd, contentDescription = "Add to another mood")
|
Icon(Icons.Rounded.PlaylistAdd, contentDescription = "Add to another mood")
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
IconButton(onClick = { store.previous() }) {
|
||||||
|
Icon(Icons.Rounded.SkipPrevious, contentDescription = "Previous")
|
||||||
|
}
|
||||||
IconButton(onClick = { store.skip() }) {
|
IconButton(onClick = { store.skip() }) {
|
||||||
Icon(Icons.Rounded.SkipNext, contentDescription = "Skip")
|
Icon(Icons.Rounded.SkipNext, contentDescription = "Skip")
|
||||||
}
|
}
|
||||||
@@ -106,6 +192,10 @@ fun PlayerBar(state: AppState, store: AppStore) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (queueOpen) {
|
||||||
|
QueueDialog(state, store) { queueOpen = false }
|
||||||
|
}
|
||||||
|
|
||||||
if (picker) {
|
if (picker) {
|
||||||
MoodPickerDialog(
|
MoodPickerDialog(
|
||||||
moods = state.moods,
|
moods = state.moods,
|
||||||
@@ -118,3 +208,100 @@ fun PlayerBar(state: AppState, store: AppStore) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit) {
|
||||||
|
Dialog(onDismissRequest = onDismiss) {
|
||||||
|
Surface(
|
||||||
|
shape = RoundedCornerShape(18.dp),
|
||||||
|
color = MaterialTheme.colorScheme.surface,
|
||||||
|
tonalElevation = 6.dp,
|
||||||
|
modifier = Modifier.fillMaxWidth().heightIn(max = 600.dp),
|
||||||
|
) {
|
||||||
|
Column {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.padding(20.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Column(Modifier.weight(1f)) {
|
||||||
|
Text("Queue", style = MaterialTheme.typography.titleMedium)
|
||||||
|
Text(
|
||||||
|
"${state.queue.size} upcoming",
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
TextButton(onClick = onDismiss) { Text("Close") }
|
||||||
|
}
|
||||||
|
HorizontalDivider()
|
||||||
|
LazyColumn(Modifier.fillMaxWidth().heightIn(max = 480.dp)) {
|
||||||
|
state.current?.let { song ->
|
||||||
|
item(key = "current") {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 10.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
|
) {
|
||||||
|
Cover(store, song.albumId, 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,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (state.queue.isEmpty()) {
|
||||||
|
item {
|
||||||
|
Text(
|
||||||
|
"Nothing queued. Start a mood, shuffle all or an artist.",
|
||||||
|
modifier = Modifier.padding(20.dp),
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
itemsIndexed(state.queue, key = { index, _ -> "queue-$index" }) { index, song ->
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth().padding(start = 20.dp, end = 8.dp, top = 6.dp, bottom = 6.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||||
|
) {
|
||||||
|
Cover(store, song.albumId, 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,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
IconButton(
|
||||||
|
onClick = { store.moveInQueue(index, index - 1) },
|
||||||
|
enabled = index > 0,
|
||||||
|
) {
|
||||||
|
Icon(Icons.Rounded.KeyboardArrowUp, contentDescription = "Move up")
|
||||||
|
}
|
||||||
|
IconButton(
|
||||||
|
onClick = { store.moveInQueue(index, index + 1) },
|
||||||
|
enabled = index < state.queue.lastIndex,
|
||||||
|
) {
|
||||||
|
Icon(Icons.Rounded.KeyboardArrowDown, contentDescription = "Move down")
|
||||||
|
}
|
||||||
|
IconButton(onClick = { store.removeFromQueue(index) }) {
|
||||||
|
Icon(Icons.Rounded.Close, contentDescription = "Remove from queue")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ import io.ktor.client.engine.mock.respondError
|
|||||||
import io.ktor.http.HttpHeaders
|
import io.ktor.http.HttpHeaders
|
||||||
import io.ktor.http.HttpStatusCode
|
import io.ktor.http.HttpStatusCode
|
||||||
import io.ktor.http.headersOf
|
import io.ktor.http.headersOf
|
||||||
|
import io.ktor.utils.io.readAvailable
|
||||||
import kotlinx.coroutines.test.runTest
|
import kotlinx.coroutines.test.runTest
|
||||||
import kotlinx.serialization.json.Json
|
import kotlinx.serialization.json.Json
|
||||||
import kotlin.test.Test
|
import kotlin.test.Test
|
||||||
@@ -73,6 +74,47 @@ class ApiClientTest {
|
|||||||
assertEquals("unauthorized", error.code)
|
assertEquals("unauthorized", error.code)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
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
|
@Test
|
||||||
fun `cache round-trips songs and moods`() = runTest {
|
fun `cache round-trips songs and moods`() = runTest {
|
||||||
val storage = MemoryStorage()
|
val storage = MemoryStorage()
|
||||||
@@ -93,22 +135,4 @@ class ApiClientTest {
|
|||||||
assertEquals("2026-11-14T00:00:00Z", loaded.revision)
|
assertEquals("2026-11-14T00:00:00Z", loaded.revision)
|
||||||
assertEquals("alice", loaded.userName)
|
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
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,695 @@
|
|||||||
|
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.withContext
|
||||||
|
import kotlinx.coroutines.test.advanceTimeBy
|
||||||
|
import kotlinx.coroutines.test.runCurrent
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
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.CachedState
|
||||||
|
import win.taptap.musicmanager.client.data.LibraryCache
|
||||||
|
import win.taptap.musicmanager.client.data.PlaybackSnapshot
|
||||||
|
import win.taptap.musicmanager.client.data.SessionState
|
||||||
|
import win.taptap.musicmanager.client.playback.AudioPlayer
|
||||||
|
import win.taptap.musicmanager.client.store.AppStore
|
||||||
|
|
||||||
|
@OptIn(ExperimentalCoroutinesApi::class)
|
||||||
|
class AppStoreTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `play all queues the whole library and starts playback`() = runTest {
|
||||||
|
val storage = MemoryStorage()
|
||||||
|
val cache = LibraryCache(storage)
|
||||||
|
val songs = listOf(song("a"), song("b"), song("c"))
|
||||||
|
cache.save(CachedState(serverUrl = "http://music", songs = songs))
|
||||||
|
val player = FakePlayer()
|
||||||
|
val store = store(storage, cache, player)
|
||||||
|
runCurrent()
|
||||||
|
|
||||||
|
store.playAll()
|
||||||
|
runCurrent()
|
||||||
|
|
||||||
|
val state = store.state.value
|
||||||
|
val current = assertNotNull(state.current)
|
||||||
|
assertTrue(state.playing)
|
||||||
|
assertEquals(listOf(current.id), player.played)
|
||||||
|
assertEquals(2, state.queue.size)
|
||||||
|
assertEquals(songs.map { it.id }.toSet(), (state.queue + current).map { it.id }.toSet())
|
||||||
|
store.release()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `play all reports an empty library instead of starting playback`() = runTest {
|
||||||
|
val storage = MemoryStorage()
|
||||||
|
val cache = LibraryCache(storage)
|
||||||
|
val player = FakePlayer()
|
||||||
|
val store = store(storage, cache, player)
|
||||||
|
runCurrent()
|
||||||
|
|
||||||
|
store.playAll()
|
||||||
|
runCurrent()
|
||||||
|
|
||||||
|
assertNull(store.state.value.current)
|
||||||
|
assertTrue(player.played.isEmpty())
|
||||||
|
assertTrue(store.state.value.messageIsError)
|
||||||
|
store.release()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `sleep timer pauses playback when it expires`() = runTest {
|
||||||
|
val storage = MemoryStorage()
|
||||||
|
val cache = LibraryCache(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()
|
||||||
|
|
||||||
|
val state = store.state.value
|
||||||
|
assertFalse(state.playing)
|
||||||
|
assertNull(state.sleepTimerRemainingSeconds)
|
||||||
|
assertTrue(player.paused)
|
||||||
|
store.release()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `turning the sleep timer off keeps playback running`() = runTest {
|
||||||
|
val storage = MemoryStorage()
|
||||||
|
val cache = LibraryCache(storage)
|
||||||
|
val player = FakePlayer()
|
||||||
|
val store = store(storage, cache, player)
|
||||||
|
runCurrent()
|
||||||
|
|
||||||
|
store.playSong(song("a"))
|
||||||
|
runCurrent()
|
||||||
|
|
||||||
|
store.setSleepTimer(30)
|
||||||
|
assertEquals(1_800L, store.state.value.sleepTimerRemainingSeconds)
|
||||||
|
store.setSleepTimer(null)
|
||||||
|
assertNull(store.state.value.sleepTimerRemainingSeconds)
|
||||||
|
|
||||||
|
advanceTimeBy(120_000)
|
||||||
|
runCurrent()
|
||||||
|
assertTrue(store.state.value.playing)
|
||||||
|
store.release()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `bootstrap restores the saved queue and starts it on play`() = runTest {
|
||||||
|
val storage = MemoryStorage()
|
||||||
|
val cache = LibraryCache(storage)
|
||||||
|
cache.savePlayback(
|
||||||
|
PlaybackSnapshot(
|
||||||
|
queue = listOf(song("b")),
|
||||||
|
current = song("a"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
val player = FakePlayer()
|
||||||
|
val store = store(storage, cache, player)
|
||||||
|
runCurrent()
|
||||||
|
|
||||||
|
val restored = store.state.value
|
||||||
|
assertEquals("a", restored.current?.id)
|
||||||
|
assertEquals(listOf("b"), restored.queue.map { it.id })
|
||||||
|
assertFalse(restored.playing)
|
||||||
|
assertTrue(player.played.isEmpty())
|
||||||
|
|
||||||
|
store.togglePlayPause()
|
||||||
|
runCurrent()
|
||||||
|
|
||||||
|
assertTrue(store.state.value.playing)
|
||||||
|
assertEquals(listOf("a"), player.played)
|
||||||
|
store.release()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `accepting a recommendation replaces the selected mood`() = runTest {
|
||||||
|
val storage = MemoryStorage()
|
||||||
|
val cache = LibraryCache(storage)
|
||||||
|
cache.saveSession(
|
||||||
|
SessionState("http://music", "token", User("alice", admin = false)),
|
||||||
|
)
|
||||||
|
val player = FakePlayer()
|
||||||
|
val detail = moodDetailJson(state = "new", seedCount = 1)
|
||||||
|
val acceptedDetail = moodDetailJson(state = "accepted", seedCount = 2)
|
||||||
|
val engine = MockEngine { request ->
|
||||||
|
when (request.url.encodedPath) {
|
||||||
|
"/api/v1/moods" -> respond("""{"moods":[]}""", HttpStatusCode.OK, jsonHeaders)
|
||||||
|
"/api/v1/library/songs" -> respond(
|
||||||
|
"""{"songs":[],"revision":"r1"}""",
|
||||||
|
HttpStatusCode.OK,
|
||||||
|
jsonHeaders,
|
||||||
|
)
|
||||||
|
"/api/v1/moods/mo-1" -> respond(detail, HttpStatusCode.OK, jsonHeaders)
|
||||||
|
"/api/v1/moods/mo-1/preview" -> respond(
|
||||||
|
"""{"songs":[]}""",
|
||||||
|
HttpStatusCode.OK,
|
||||||
|
jsonHeaders,
|
||||||
|
)
|
||||||
|
"/api/v1/moods/mo-1/recommendations/v-1/accept" -> respond(
|
||||||
|
"""{"detail":$acceptedDetail,"recommendation":${recommendationJson("accepted")},"seedAdded":true}""",
|
||||||
|
HttpStatusCode.OK,
|
||||||
|
jsonHeaders,
|
||||||
|
)
|
||||||
|
"/api/v1/moods/mo-1/recommendations/v-1/reject" -> respond(
|
||||||
|
"""{"detail":$detail,"recommendation":${recommendationJson("rejected")},"seedAdded":false}""",
|
||||||
|
HttpStatusCode.OK,
|
||||||
|
jsonHeaders,
|
||||||
|
)
|
||||||
|
else -> respondError(HttpStatusCode.NotFound)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val store = AppStore(
|
||||||
|
scope = this,
|
||||||
|
api = ApiClient(configuredHttpClient(engine)),
|
||||||
|
storage = storage,
|
||||||
|
player = player,
|
||||||
|
cache = cache,
|
||||||
|
)
|
||||||
|
runCurrent()
|
||||||
|
store.openMood("mo-1")
|
||||||
|
awaitState { store.state.value.selectedMood != null || store.state.value.message != null }
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
"new",
|
||||||
|
store.state.value.selectedMood?.recommendations?.single()?.state,
|
||||||
|
"message=" + store.state.value.message,
|
||||||
|
)
|
||||||
|
|
||||||
|
store.acceptRecommendation("v-1")
|
||||||
|
awaitState {
|
||||||
|
store.state.value.selectedMood?.recommendations?.single()?.state == "accepted"
|
||||||
|
}
|
||||||
|
|
||||||
|
val state = store.state.value
|
||||||
|
assertEquals("accepted", state.selectedMood?.recommendations?.single()?.state)
|
||||||
|
assertEquals(2, state.selectedMood?.mood?.seedCount)
|
||||||
|
assertEquals("Added to Focus", state.message)
|
||||||
|
assertFalse(state.messageIsError)
|
||||||
|
store.release()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ktor's mock engine responds on a real dispatcher, so queued test work has
|
||||||
|
* to be run between short real waits.
|
||||||
|
*/
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `queue reordering and removal persist`() = runTest {
|
||||||
|
val storage = MemoryStorage()
|
||||||
|
val cache = LibraryCache(storage)
|
||||||
|
cache.save(CachedState(serverUrl = "http://music", songs = listOf(song("a"), song("b"), song("c"))))
|
||||||
|
val player = FakePlayer()
|
||||||
|
val store = store(storage, cache, player)
|
||||||
|
runCurrent()
|
||||||
|
|
||||||
|
store.playAll(shuffled = false)
|
||||||
|
runCurrent()
|
||||||
|
assertEquals("a", store.state.value.current?.id)
|
||||||
|
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 `restored playback resumes from the saved position`() = runTest {
|
||||||
|
val storage = MemoryStorage()
|
||||||
|
val cache = LibraryCache(storage)
|
||||||
|
cache.saveSession(
|
||||||
|
SessionState(
|
||||||
|
"http://music",
|
||||||
|
"token",
|
||||||
|
User("alice", admin = false, musicFolders = listOf(1), longformFolders = listOf(10)),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
cache.save(
|
||||||
|
CachedState(
|
||||||
|
serverUrl = "http://music",
|
||||||
|
userName = "alice",
|
||||||
|
longform = listOf(song("l1", artist = "Book", folderId = 10, duration = 5400)),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
cache.savePlayback(
|
||||||
|
PlaybackSnapshot(
|
||||||
|
current = song("l1", artist = "Book", folderId = 10, duration = 5400),
|
||||||
|
positionSeconds = 3600.0,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
cache.saveProgress(
|
||||||
|
listOf(
|
||||||
|
win.taptap.musicmanager.client.api.LongformProgress(
|
||||||
|
songId = "l1",
|
||||||
|
positionSeconds = 3600,
|
||||||
|
durationSeconds = 5400,
|
||||||
|
completed = false,
|
||||||
|
updatedAt = "2026-01-01T00:00:00Z",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
val player = FakePlayer()
|
||||||
|
val store = store(storage, cache, player)
|
||||||
|
runCurrent()
|
||||||
|
awaitState { store.state.value.offline }
|
||||||
|
|
||||||
|
assertEquals(3600.0, store.state.value.positionSeconds)
|
||||||
|
store.togglePlayPause()
|
||||||
|
runCurrent()
|
||||||
|
|
||||||
|
assertEquals("l1", store.state.value.current?.id)
|
||||||
|
assertEquals(3600.0, player.seeks.last())
|
||||||
|
store.release()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `previous after resuming an audiobook goes back instead of restarting it`() = runTest {
|
||||||
|
val storage = MemoryStorage()
|
||||||
|
val cache = LibraryCache(storage)
|
||||||
|
cache.saveSession(
|
||||||
|
SessionState(
|
||||||
|
"http://music",
|
||||||
|
"token",
|
||||||
|
User("alice", admin = false, musicFolders = listOf(1), longformFolders = listOf(10)),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
cache.save(CachedState(serverUrl = "http://music", userName = "alice"))
|
||||||
|
cache.savePlayback(
|
||||||
|
PlaybackSnapshot(
|
||||||
|
current = song("l1", artist = "Book", folderId = 10, duration = 5400),
|
||||||
|
history = listOf(song("a")),
|
||||||
|
positionSeconds = 3600.0,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
val player = FakePlayer()
|
||||||
|
val store = store(storage, cache, player)
|
||||||
|
runCurrent()
|
||||||
|
awaitState { store.state.value.offline }
|
||||||
|
|
||||||
|
store.previous()
|
||||||
|
runCurrent()
|
||||||
|
|
||||||
|
assertEquals("a", store.state.value.current?.id)
|
||||||
|
assertEquals(listOf("l1"), store.state.value.queue.map { it.id })
|
||||||
|
assertEquals("a", player.played.last())
|
||||||
|
store.release()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `finishing a longform track stays completed when the next track starts`() = runTest {
|
||||||
|
val storage = MemoryStorage()
|
||||||
|
val cache = LibraryCache(storage)
|
||||||
|
cache.saveSession(
|
||||||
|
SessionState(
|
||||||
|
"http://music",
|
||||||
|
"token",
|
||||||
|
User("alice", admin = false, musicFolders = listOf(1), longformFolders = listOf(10)),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
cache.save(
|
||||||
|
CachedState(
|
||||||
|
serverUrl = "http://music",
|
||||||
|
userName = "alice",
|
||||||
|
longform = listOf(
|
||||||
|
song("l1", artist = "Book", folderId = 10, duration = 180),
|
||||||
|
song("l2", artist = "Book", folderId = 10, duration = 180),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
val player = FakePlayer()
|
||||||
|
val store = store(storage, cache, player)
|
||||||
|
runCurrent()
|
||||||
|
awaitState { store.state.value.offline }
|
||||||
|
|
||||||
|
store.playLongformArtist("Book", shuffled = false)
|
||||||
|
runCurrent()
|
||||||
|
player.position = 180.0
|
||||||
|
player.finish()
|
||||||
|
advanceTimeBy(600)
|
||||||
|
runCurrent()
|
||||||
|
|
||||||
|
assertEquals(true, store.state.value.longformProgress["l1"]?.completed)
|
||||||
|
assertEquals("l2", store.state.value.current?.id)
|
||||||
|
store.release()
|
||||||
|
runCurrent()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `logout removes progress and cached library`() = runTest {
|
||||||
|
val storage = MemoryStorage()
|
||||||
|
val cache = LibraryCache(storage)
|
||||||
|
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
|
||||||
|
cache.save(CachedState(serverUrl = "http://music", userName = "alice", songs = listOf(song("a"))))
|
||||||
|
cache.saveProgress(
|
||||||
|
listOf(
|
||||||
|
win.taptap.musicmanager.client.api.LongformProgress(
|
||||||
|
songId = "l1",
|
||||||
|
positionSeconds = 42,
|
||||||
|
durationSeconds = 180,
|
||||||
|
completed = false,
|
||||||
|
updatedAt = "2026-01-01T00:00:00Z",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
val store = store(storage, cache, FakePlayer())
|
||||||
|
runCurrent()
|
||||||
|
|
||||||
|
store.logout()
|
||||||
|
awaitState { !store.state.value.authenticated }
|
||||||
|
|
||||||
|
assertTrue(cache.loadProgress().isEmpty())
|
||||||
|
assertTrue(cache.load().songs.isEmpty())
|
||||||
|
store.release()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `music search is debounced and scoped to music`() = runTest {
|
||||||
|
val storage = MemoryStorage()
|
||||||
|
val cache = LibraryCache(storage)
|
||||||
|
var requestedScope: String? = null
|
||||||
|
val engine = MockEngine { request ->
|
||||||
|
when (request.url.encodedPath) {
|
||||||
|
"/api/v1/library/search" -> {
|
||||||
|
requestedScope = request.url.parameters["scope"]
|
||||||
|
respond(
|
||||||
|
"""{"songs":[{"id":"m1","title":"Focus","artist":"Alpha","album":"Album",
|
||||||
|
"albumId":"al-1","duration":180,"bitRate":320,"size":1000,"suffix":"mp3",
|
||||||
|
"folderId":1,"relativePath":"m1.mp3","updatedAt":"now"}]}""",
|
||||||
|
HttpStatusCode.OK,
|
||||||
|
jsonHeaders,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
else -> respondError(HttpStatusCode.NotFound)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val store = AppStore(
|
||||||
|
scope = this,
|
||||||
|
api = ApiClient(configuredHttpClient(engine)),
|
||||||
|
storage = storage,
|
||||||
|
player = FakePlayer(),
|
||||||
|
cache = cache,
|
||||||
|
)
|
||||||
|
runCurrent()
|
||||||
|
|
||||||
|
store.searchMusic("focus")
|
||||||
|
advanceTimeBy(350)
|
||||||
|
runCurrent()
|
||||||
|
awaitState { store.state.value.musicResults.isNotEmpty() }
|
||||||
|
|
||||||
|
assertEquals(listOf("m1"), store.state.value.musicResults.map { it.id })
|
||||||
|
assertEquals("music", requestedScope)
|
||||||
|
store.release()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `previous restarts after two seconds and restores the last track before it`() = runTest {
|
||||||
|
val storage = MemoryStorage()
|
||||||
|
val cache = LibraryCache(storage)
|
||||||
|
cache.save(CachedState(serverUrl = "http://music", songs = listOf(song("a"), song("b"), song("c"))))
|
||||||
|
val player = FakePlayer()
|
||||||
|
val store = store(storage, cache, player)
|
||||||
|
runCurrent()
|
||||||
|
|
||||||
|
store.playAll(shuffled = false)
|
||||||
|
runCurrent()
|
||||||
|
store.skip()
|
||||||
|
runCurrent()
|
||||||
|
assertEquals("b", store.state.value.current?.id)
|
||||||
|
assertEquals(listOf("a"), store.state.value.history.map { it.id })
|
||||||
|
|
||||||
|
store.seekTo(5.0)
|
||||||
|
store.previous()
|
||||||
|
assertEquals("b", store.state.value.current?.id)
|
||||||
|
assertEquals(0.0, store.state.value.positionSeconds)
|
||||||
|
assertEquals(0.0, player.seeks.last())
|
||||||
|
|
||||||
|
store.previous()
|
||||||
|
runCurrent()
|
||||||
|
assertEquals("a", store.state.value.current?.id)
|
||||||
|
assertEquals(listOf("b", "c"), store.state.value.queue.map { it.id })
|
||||||
|
assertTrue(store.state.value.history.isEmpty())
|
||||||
|
assertEquals("a", player.played.last())
|
||||||
|
assertTrue(cache.loadPlayback()?.history?.isEmpty() == true)
|
||||||
|
store.release()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `delta refresh keeps cached longform songs`() = runTest {
|
||||||
|
val storage = MemoryStorage()
|
||||||
|
val cache = LibraryCache(storage)
|
||||||
|
cache.saveSession(
|
||||||
|
SessionState(
|
||||||
|
"http://music",
|
||||||
|
"token",
|
||||||
|
User("alice", admin = false, musicFolders = listOf(1), longformFolders = listOf(10)),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
cache.save(
|
||||||
|
CachedState(
|
||||||
|
serverUrl = "http://music",
|
||||||
|
revision = "r1",
|
||||||
|
songs = listOf(song("m1")),
|
||||||
|
longform = listOf(song("l1", artist = "Die drei ???", folderId = 10)),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
val engine = MockEngine { request ->
|
||||||
|
when (request.url.encodedPath) {
|
||||||
|
"/api/v1/moods" -> respond("""{"moods":[]}""", HttpStatusCode.OK, jsonHeaders)
|
||||||
|
"/api/v1/library/songs" -> respond(
|
||||||
|
"""{"songs":[],"revision":"r2"}""",
|
||||||
|
HttpStatusCode.OK,
|
||||||
|
jsonHeaders,
|
||||||
|
)
|
||||||
|
"/api/v1/longform/progress" -> respond(
|
||||||
|
"""{"items":[]}""",
|
||||||
|
HttpStatusCode.OK,
|
||||||
|
jsonHeaders,
|
||||||
|
)
|
||||||
|
else -> respondError(HttpStatusCode.NotFound)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val store = AppStore(
|
||||||
|
scope = this,
|
||||||
|
api = ApiClient(configuredHttpClient(engine)),
|
||||||
|
storage = storage,
|
||||||
|
player = FakePlayer(),
|
||||||
|
cache = cache,
|
||||||
|
)
|
||||||
|
runCurrent()
|
||||||
|
awaitState { cache.load()?.revision == "r2" }
|
||||||
|
|
||||||
|
assertEquals(listOf("m1"), store.state.value.library.map { it.id })
|
||||||
|
assertEquals(listOf("l1"), store.state.value.longform.map { it.id })
|
||||||
|
store.release()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `playing an artist queues only that longform artist`() = runTest {
|
||||||
|
val storage = MemoryStorage()
|
||||||
|
val cache = LibraryCache(storage)
|
||||||
|
cache.save(
|
||||||
|
CachedState(
|
||||||
|
serverUrl = "http://music",
|
||||||
|
longform = listOf(
|
||||||
|
song("l1", artist = "Die drei ???", folderId = 10),
|
||||||
|
song("l2", artist = "Die drei ???", folderId = 10),
|
||||||
|
song("l3", artist = "Other", folderId = 10),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
val player = FakePlayer()
|
||||||
|
val store = store(storage, cache, player)
|
||||||
|
runCurrent()
|
||||||
|
|
||||||
|
store.playLongformArtist("Die drei ???", shuffled = false)
|
||||||
|
runCurrent()
|
||||||
|
|
||||||
|
val state = store.state.value
|
||||||
|
assertEquals(setOf("l1", "l2"), (state.queue + listOfNotNull(state.current)).map { it.id }.toSet())
|
||||||
|
assertTrue(player.played.single() in setOf("l1", "l2"))
|
||||||
|
store.release()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `resuming a longform track starts it`() = runTest {
|
||||||
|
val storage = MemoryStorage()
|
||||||
|
val cache = LibraryCache(storage)
|
||||||
|
cache.save(
|
||||||
|
CachedState(
|
||||||
|
serverUrl = "http://music",
|
||||||
|
longform = listOf(song("l1", artist = "Die drei ???", folderId = 10)),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
cache.saveProgress(
|
||||||
|
listOf(
|
||||||
|
win.taptap.musicmanager.client.api.LongformProgress(
|
||||||
|
songId = "l1",
|
||||||
|
positionSeconds = 30,
|
||||||
|
durationSeconds = 180,
|
||||||
|
completed = false,
|
||||||
|
updatedAt = "2026-01-01T00:00:00Z",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
val player = FakePlayer()
|
||||||
|
val store = store(storage, cache, player)
|
||||||
|
runCurrent()
|
||||||
|
|
||||||
|
store.resumeLongform("l1")
|
||||||
|
runCurrent()
|
||||||
|
|
||||||
|
assertEquals("l1", store.state.value.current?.id)
|
||||||
|
assertEquals(listOf("l1"), player.played)
|
||||||
|
assertEquals(30, store.state.value.longformProgress["l1"]?.positionSeconds)
|
||||||
|
store.release()
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun TestScope.awaitState(predicate: () -> Boolean) {
|
||||||
|
repeat(500) {
|
||||||
|
runCurrent()
|
||||||
|
if (predicate()) return
|
||||||
|
withContext(Dispatchers.Default) { delay(10) }
|
||||||
|
}
|
||||||
|
throw AssertionError("state did not settle")
|
||||||
|
}
|
||||||
|
|
||||||
|
private val jsonHeaders = headersOf(HttpHeaders.ContentType, "application/json")
|
||||||
|
|
||||||
|
private fun moodJson(seedCount: Int) = """
|
||||||
|
{"id":"mo-1","name":"Focus","targetSize":30,"refreshHours":24,"ytEnabled":true,
|
||||||
|
"createdAt":"2026-01-01T00:00:00Z","changedAt":"2026-01-01T00:00:00Z",
|
||||||
|
"seedCount":$seedCount,"newRecommendations":1}
|
||||||
|
""".trimIndent()
|
||||||
|
|
||||||
|
private fun recommendationJson(state: String) = """
|
||||||
|
{"videoId":"v-1","title":"Soft Light","artist":"Beta","duration":180,
|
||||||
|
"state":"$state","timesAdded":0,
|
||||||
|
"firstSeen":"2026-01-01T00:00:00Z","lastSeen":"2026-01-01T00:00:00Z",
|
||||||
|
"matchedSong":${song("a").let { """{"id":"${it.id}","title":"${it.title}","artist":"${it.artist}","album":"${it.album}","albumId":"${it.albumId}","duration":${it.duration},"bitRate":${it.bitRate},"size":${it.size},"suffix":"${it.suffix}","folderId":${it.folderId},"relativePath":"${it.relativePath}","updatedAt":"${it.updatedAt}"}""" }}}
|
||||||
|
""".trimIndent()
|
||||||
|
|
||||||
|
private fun moodDetailJson(state: String, seedCount: Int) = """
|
||||||
|
{"mood":${moodJson(seedCount)},"seeds":[],"recommendations":[${recommendationJson(state)}]}
|
||||||
|
""".trimIndent()
|
||||||
|
|
||||||
|
private fun kotlinx.coroutines.test.TestScope.store(
|
||||||
|
storage: MemoryStorage,
|
||||||
|
cache: LibraryCache,
|
||||||
|
player: AudioPlayer,
|
||||||
|
): AppStore = AppStore(
|
||||||
|
// Background scope so leftover store jobs (reconnect loops, refreshes)
|
||||||
|
// are cancelled by runTest instead of failing the next test with
|
||||||
|
// UncompletedCoroutinesError.
|
||||||
|
scope = backgroundScope,
|
||||||
|
api = ApiClient(configuredHttpClient(MockEngine { respondError(HttpStatusCode.NotFound) })),
|
||||||
|
storage = storage,
|
||||||
|
player = player,
|
||||||
|
cache = cache,
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun song(
|
||||||
|
id: String,
|
||||||
|
artist: String = "Artist",
|
||||||
|
folderId: Int = 1,
|
||||||
|
duration: Int = 180,
|
||||||
|
) = Song(
|
||||||
|
id = id,
|
||||||
|
title = "Song $id",
|
||||||
|
artist = artist,
|
||||||
|
album = "Album",
|
||||||
|
albumId = "al-1",
|
||||||
|
duration = duration,
|
||||||
|
bitRate = 320,
|
||||||
|
size = 1_000,
|
||||||
|
suffix = "mp3",
|
||||||
|
folderId = folderId,
|
||||||
|
relativePath = "$id.mp3",
|
||||||
|
updatedAt = "2026-01-01T00:00:00Z",
|
||||||
|
)
|
||||||
|
|
||||||
|
private class FakePlayer : AudioPlayer {
|
||||||
|
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.FileInputStream
|
||||||
import java.io.InputStream
|
import java.io.InputStream
|
||||||
import java.net.URI
|
import java.net.URI
|
||||||
|
import javax.sound.sampled.AudioFormat
|
||||||
|
import javax.sound.sampled.AudioInputStream
|
||||||
import javax.sound.sampled.AudioSystem
|
import javax.sound.sampled.AudioSystem
|
||||||
import javax.sound.sampled.SourceDataLine
|
import javax.sound.sampled.SourceDataLine
|
||||||
import kotlin.concurrent.thread
|
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
|
* 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 {
|
class DesktopAudioPlayer : AudioPlayer {
|
||||||
|
|
||||||
private var input: InputStream? = null
|
private var input: InputStream? = null
|
||||||
|
private var stream: AudioInputStream? = null
|
||||||
private var line: SourceDataLine? = null
|
private var line: SourceDataLine? = null
|
||||||
private var worker: Thread? = null
|
private var worker: Thread? = null
|
||||||
private val lock = Object()
|
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 paused = false
|
||||||
@Volatile private var stopped = false
|
@Volatile private var stopped = false
|
||||||
@Volatile private var finished = false
|
@Volatile private var finished = false
|
||||||
@Volatile private var framesRead = 0L
|
@Volatile private var framesRead = 0L
|
||||||
|
@Volatile private var baseSeconds = 0.0
|
||||||
private var frameSize = 4
|
private var frameSize = 4
|
||||||
private var frameRate = 44_100f
|
private var frameRate = 44_100f
|
||||||
private var duration = 0.0
|
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()
|
stop()
|
||||||
finished = false
|
finished = false
|
||||||
paused = false
|
paused = false
|
||||||
stopped = false
|
stopped = false
|
||||||
framesRead = 0
|
framesRead = 0
|
||||||
|
baseSeconds = startAtSeconds.coerceAtLeast(0.0)
|
||||||
duration = song.duration.toDouble()
|
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)
|
val buffered = BufferedInputStream(raw, 128 * 1024)
|
||||||
input = buffered
|
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
|
frameSize = audio.format.frameSize.takeIf { it > 0 } ?: 4
|
||||||
frameRate = audio.format.frameRate.takeIf { it > 0 } ?: 44_100f
|
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 info = javax.sound.sampled.DataLine.Info(SourceDataLine::class.java, audio.format)
|
||||||
val dataLine = AudioSystem.getLine(info) as SourceDataLine
|
val dataLine = AudioSystem.getLine(info) as SourceDataLine
|
||||||
dataLine.open(audio.format)
|
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() {
|
override fun pause() {
|
||||||
paused = true
|
paused = true
|
||||||
}
|
}
|
||||||
@@ -98,8 +169,10 @@ class DesktopAudioPlayer : AudioPlayer {
|
|||||||
runCatching { line?.flush() }
|
runCatching { line?.flush() }
|
||||||
worker?.interrupt()
|
worker?.interrupt()
|
||||||
runCatching { worker?.join(400) }
|
runCatching { worker?.join(400) }
|
||||||
|
runCatching { stream?.close() }
|
||||||
runCatching { input?.close() }
|
runCatching { input?.close() }
|
||||||
line = null
|
line = null
|
||||||
|
stream = null
|
||||||
input = null
|
input = null
|
||||||
worker = null
|
worker = null
|
||||||
}
|
}
|
||||||
@@ -110,17 +183,55 @@ class DesktopAudioPlayer : AudioPlayer {
|
|||||||
override fun isFinished(): Boolean = finished
|
override fun isFinished(): Boolean = finished
|
||||||
|
|
||||||
override fun positionSeconds(): Double {
|
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)
|
return seconds.coerceIn(0.0, duration.takeIf { it > 0 } ?: seconds)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun durationSeconds(): Double = duration
|
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() {
|
override fun release() {
|
||||||
stop()
|
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 androidx.compose.ui.graphics.toComposeImageBitmap
|
||||||
import io.ktor.client.engine.HttpClientEngine
|
import io.ktor.client.engine.HttpClientEngine
|
||||||
import io.ktor.client.engine.cio.CIO
|
import io.ktor.client.engine.cio.CIO
|
||||||
|
import io.ktor.utils.io.readAvailable
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import win.taptap.musicmanager.client.data.AppStorage
|
import win.taptap.musicmanager.client.data.AppStorage
|
||||||
import win.taptap.musicmanager.client.playback.AudioPlayer
|
import win.taptap.musicmanager.client.playback.AudioPlayer
|
||||||
@@ -32,7 +33,7 @@ class DesktopStorage : AppStorage {
|
|||||||
|
|
||||||
override fun write(name: String, text: String) {
|
override fun write(name: String, text: String) {
|
||||||
root.mkdirs()
|
root.mkdirs()
|
||||||
File(root, name).writeText(text)
|
atomicWrite(File(root, name)) { it.writeText(text) }
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun delete(name: String) {
|
override fun delete(name: String) {
|
||||||
@@ -42,13 +43,53 @@ class DesktopStorage : AppStorage {
|
|||||||
override fun saveDownload(songId: String, bytes: ByteArray): String? {
|
override fun saveDownload(songId: String, bytes: ByteArray): String? {
|
||||||
downloads.mkdirs()
|
downloads.mkdirs()
|
||||||
val file = File(downloads, "${safeName(songId)}.mp3")
|
val file = File(downloads, "${safeName(songId)}.mp3")
|
||||||
file.writeBytes(bytes)
|
atomicWrite(file) { it.writeBytes(bytes) }
|
||||||
return file.absolutePath
|
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? =
|
override fun downloadPath(songId: String): String? =
|
||||||
File(downloads, "${safeName(songId)}.mp3").takeIf { it.isFile }?.absolutePath
|
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> =
|
override fun listDownloads(): Map<String, Long> =
|
||||||
downloads.listFiles()
|
downloads.listFiles()
|
||||||
?.filter { it.isFile && it.extension == "mp3" }
|
?.filter { it.isFile && it.extension == "mp3" }
|
||||||
@@ -57,11 +98,26 @@ class DesktopStorage : AppStorage {
|
|||||||
|
|
||||||
override fun deleteDownload(songId: String) {
|
override fun deleteDownload(songId: String) {
|
||||||
File(downloads, "${safeName(songId)}.mp3").delete()
|
File(downloads, "${safeName(songId)}.mp3").delete()
|
||||||
|
File(downloads, "${safeName(songId)}.jpg").delete()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun storageUsedBytes(): Long =
|
override fun storageUsedBytes(): Long =
|
||||||
downloads.listFiles()?.sumOf { it.length() } ?: 0L
|
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 =
|
private fun safeName(songId: String): String =
|
||||||
songId.map { if (it.isLetterOrDigit() || it == '-' || it == '_') it else '_' }.joinToString("")
|
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 saveDownload(songId: String, bytes: ByteArray): String? = null
|
||||||
override fun downloadPath(songId: String): 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 listDownloads(): Map<String, Long> = emptyMap()
|
||||||
override fun deleteDownload(songId: String) = Unit
|
override fun deleteDownload(songId: String) = Unit
|
||||||
override fun storageUsedBytes(): Long = 0L
|
override fun storageUsedBytes(): Long = 0L
|
||||||
|
|||||||
@@ -12,7 +12,13 @@ class WebAudioPlayer : AudioPlayer {
|
|||||||
preload = "auto"
|
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.src = source
|
||||||
audio.play()
|
audio.play()
|
||||||
}
|
}
|
||||||
|
|||||||
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;
|
node = pkgs.nodejs_22;
|
||||||
|
|
||||||
androidPackages = pkgs.androidenv.composeAndroidPackages {
|
androidPackages = pkgs.androidenv.composeAndroidPackages {
|
||||||
platformVersions = [ "35" ];
|
platformVersions = [ "36" ];
|
||||||
buildToolsVersions = [ "35.0.0" ];
|
buildToolsVersions = [ "36.0.0" ];
|
||||||
includeEmulator = false;
|
includeEmulator = false;
|
||||||
includeSystemImages = false;
|
includeSystemImages = false;
|
||||||
includeNDK = false;
|
includeNDK = false;
|
||||||
|
|||||||
Reference in new issue
Block a user