11 Commits
Author SHA1 Message Date
TapTap d9976a62bd build: publish tagged builds to Play internal testing
CI / build (push) Successful in 12m22s
CI / play (push) Successful in 3m19s
Apply Gradle Play Publisher 3.13.0 to the Android target, target the
internal track with AUTO version codes, and add a tag-only CI job that
decodes the upload keystore and uploads with the service account JSON
from repository secrets.

Document the one-time service account and secret setup.
2026-11-15 19:11:38 +00:00
TapTap 0491c78c7f test: cancel leftover store jobs via backgroundScope
CI / build (push) Successful in 2m0s
The reconnect loop could outlive the test body and intermittently fail
runTest with UncompletedCoroutinesError.
2026-11-15 18:52:23 +00:00
TapTap c53ed0a1b8 build: use the Play Console package name
CI / build (push) Failing after 2m25s
Set applicationId to win.tap_tap.audiomanager.client so the first upload
matches the existing Play Console app. The Kotlin namespace is unchanged;
relative manifest components are expanded against it, so no code moves.
2026-11-15 18:48:38 +00:00
TapTap 67414b5986 ci: install API 36 without a SIGPIPE from yes
CI / build (push) Successful in 2m2s
Also add platform 36 to the CI image for the next rebuild.
2026-11-15 18:40:44 +00:00
TapTap 9b105b3925 build: target API 36 and sign Play upload bundles
CI / build (push) Failing after 33s
- compileSdk/targetSdk 36: Google Play rejects new apps below API 36 since
  31 August 2026.
- Release signing from ANDROID_KEYSTORE_* environment variables or
  local.properties; unsigned when no upload key is configured.
- versionCode/versionName overridable via VERSION_CODE/VERSION_NAME.
- scripts/build-release-aab.sh builds and verifies a signed AAB.
- CI installs platform 36 until the CI image is rebuilt.
- Document the internal-testing upload flow.
2026-11-15 18:39:24 +00:00
TapTap 43bd9629d3 fix: harden playback, sync, downloads and mood state
CI / build (push) Successful in 2m1s
Playback:
- Persist the playhead in the playback snapshot and resume from it; restored
  longform progress is no longer overwritten with 0 on first play.
- Previous compares elapsed playtime since the track start, so resuming at
  1:00:00 and pressing previous goes back instead of restarting the book.
- Auto-advance no longer overwrites completed=true with false, longform PUTs
  are serialized, and playing rows/search results resume saved positions.
- Pause cancels the 400 ms poll; seek errors are reported instead of crashing.

Sync and state:
- First-sync snapshots keep the first page revision; cached revisions are only
  trusted for the same server/user.
- Refresh re-reads /me, merges local and server longform progress by timestamp,
  replays newer local positions, and keeps cached longform after deltas.
- Logout cancels refresh jobs, suppresses late progress writes, clears after
  playback teardown, and closes the HTTP client on release.
- Failed/racing mood opens clear the previous mood; stale responses cannot
  replace a newer selection. Mood drafts survive background refreshes.

Downloads and storage:
- Stream downloads to a .part file and atomically rename on Android/desktop,
  with a download-specific timeout and no whole-file buffering.
- Cache writes are best-effort and atomic; blocked/full web storage no longer
  leaves the app on the splash screen or blocks playback.
- Artwork failures do not fail audio downloads; failed downloads refresh the
  download index.
- Android queues sleep-timer commands before the controller connects.

UI:
- Music search is wired, debounced and kept separate from mood search.
- Player bar respects navigation-bar insets and hides music-only mood actions
  for longform. Mood gradient handles Int.MIN_VALUE.
2026-11-15 18:18:30 +00:00
TapTap 14bebced10 fix: persist the restarted position for longform immediately
CI / build (push) Successful in 1m42s
Pressing previous after two seconds now saves position zero before the next
progress poll, so killing the app right after the restart keeps the right
resume point.
2026-11-15 17:13:08 +00:00
TapTap 17bda94bfc feat: previous/scrub controls, mood mix and artwork for downloads
CI / build (push) Successful in 2m16s
Playback:
- Previous button: after two seconds it restarts the current track, otherwise
  it restores the last played track and puts the outgoing one back in front of
  the queue. History is persisted in the playback snapshot.
- The progress slider is draggable on every platform. Desktop previously
  refused to seek; it now restarts the decoder at the requested position,
  asking the server for a timeOffset on remote streams and skipping PCM frames
  for local files.

Artwork:
- Client downloads store the 320px cover next to the MP3 and Android sets it as
  MediaMetadata artwork data, so the notification and offline playback keep the
  cover. Deleting a download removes the image too.

Moods:
- New mood setting and editor slider choose the seed share of each radio batch;
  the server generates the rest from recommendations.

Library:
- Delta refresh now seeds its song map from both cached music and cached
  longform. Longform used to disappear after the first delta, which is why the
  artist list and artist playlists were empty while search still worked.
2026-11-15 17:07:11 +00:00
TapTap c0ff586686 feat: edit the queue and browse longform with resume
CI / build (push) Successful in 2m32s
The player gains a queue sheet showing the current track and every upcoming
track, with move up/down and remove; changes are persisted in the playback
snapshot.

Music and longform are now separate: library sync splits songs by the user's
folder assignments, so longform no longer leaks into search, Shuffle all or
moods. The new Longform tab groups audiobooks and podcasts by artist, offers a
generated read-only playlist per artist, "Shuffle artist" for random tracks,
separate longform search, and a Continue listening list with progress bars and
resume. Positions are saved locally and to the server while playing, on pause
and on track changes.

Recommendation cards now show download progress (queued, downloading, failed
with error and retry) and the mood refreshes while downloads are running.
2026-11-15 13:26:22 +00:00
TapTap dc719f3e1a feat: review YT recommendations and resume queues offline
CI / build (push) Successful in 1m56s
The mood screen now shows recommendation cards with thumbnails, a refresh
action, and accept/reject buttons. Accepting a library match adds it as a seed
immediately; other accepted tracks are marked as queued for download.

The player persists the session, queue and current track, restores them paused
on the next launch and starts the track on the next tap. While offline the
store retries the library sync with exponential backoff, downloads retry three
times before failing, and covers plus YT thumbnails are cached for the app's
lifetime.
2026-11-15 12:44:30 +00:00
TapTap 2234192dc7 feat: shuffle downloads when the server is offline
CI / build (push) Successful in 2m19s
Shuffle all now queues only downloaded tracks in offline mode, matching how a
mood falls back to downloads, and says so when there are none.
2026-11-15 08:09:37 +00:00
28 changed files with 2664 additions and 151 deletions

No files matched your search

+59
View File
@@ -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
+2
View File
@@ -7,3 +7,5 @@ local.properties
.DS_Store .DS_Store
.kotlin/ .kotlin/
node_modules/ node_modules/
*.jks
*.keystore
+98 -7
View File
@@ -24,9 +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)
- 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. - 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. - **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.
@@ -51,15 +60,15 @@ composeApp/
## 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
@@ -86,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.
@@ -131,7 +220,9 @@ The image build performs one warm-up compile (`kotlinNodeJsSetup`, `kotlinYarnSe
## 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. MP3s are decoded to 16-bit PCM before the line is opened, because Java Sound has no line for the compressed format. - 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.
+1
View File
@@ -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
View File
@@ -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)
+74 -5
View File
@@ -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"
@@ -21,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
@@ -45,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)
@@ -61,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)
@@ -110,9 +127,14 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
} }
override fun scheduleSleepTimer(seconds: Long?): Boolean { override fun scheduleSleepTimer(seconds: Long?): Boolean {
val current = controller ?: return false
val args = Bundle().apply { putLong(SLEEP_TIMER_SECONDS, seconds ?: 0L) } val args = Bundle().apply { putLong(SLEEP_TIMER_SECONDS, seconds ?: 0L) }
return runCatching { current.sendCustomCommand(SLEEP_TIMER_COMMAND, args) }.isSuccess 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() {
@@ -120,7 +142,7 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
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) {
@@ -128,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) }
} }
} }
} }
@@ -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("")
} }
@@ -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
@@ -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"
} }
} }
@@ -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()
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))
} }
@@ -1,22 +1,28 @@
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.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.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
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.material.icons.rounded.Shuffle
@@ -28,7 +34,10 @@ 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.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
@@ -36,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
@@ -45,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 }
@@ -57,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) {
@@ -105,17 +144,17 @@ fun LibraryScreen(state: AppState, store: AppStore) {
} }
} }
if (state.searchResults.isNotEmpty()) { 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)) }
@@ -163,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 -> {
@@ -181,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")
}
}
}
@@ -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") }
@@ -6,16 +6,26 @@ 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.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.DropdownMenu
import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.HorizontalDivider
@@ -25,6 +35,7 @@ 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
@@ -34,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
@@ -42,12 +54,15 @@ fun PlayerBar(state: AppState, store: AppStore) {
val song = state.current ?: return val song = state.current ?: return
var picker by remember { mutableStateOf(false) } var picker by remember { mutableStateOf(false) }
var sleepMenu by remember { mutableStateOf(false) } var sleepMenu by remember { mutableStateOf(false) }
var queueOpen by remember { mutableStateOf(false) }
var dragSeconds by remember(song.id) { mutableStateOf<Float?>(null) } var dragSeconds by remember(song.id) { mutableStateOf<Float?>(null) }
val sleepRemaining = state.sleepTimerRemainingSeconds val sleepRemaining = state.sleepTimerRemainingSeconds
val isLongform = state.user?.longformFolders?.contains(song.folderId) == true
Surface( Surface(
color = MaterialTheme.colorScheme.surfaceVariant, color = MaterialTheme.colorScheme.surfaceVariant,
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) {
@@ -63,12 +78,19 @@ fun PlayerBar(state: AppState, store: AppStore) {
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.weight(1f), modifier = Modifier.weight(1f),
) )
IconButton(onClick = { queueOpen = true }) {
Icon(Icons.Rounded.QueueMusic, contentDescription = "Queue")
}
Box { Box {
IconButton(onClick = { sleepMenu = true }) { IconButton(onClick = { sleepMenu = true }) {
Icon( Icon(
@@ -145,12 +167,17 @@ fun PlayerBar(state: AppState, store: AppStore) {
) )
} }
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")
} }
@@ -165,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,
@@ -177,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()
@@ -1,9 +1,16 @@
package win.taptap.musicmanager.client package win.taptap.musicmanager.client
import io.ktor.client.engine.mock.MockEngine import io.ktor.client.engine.mock.MockEngine
import io.ktor.client.engine.mock.respond
import io.ktor.client.engine.mock.respondError import io.ktor.client.engine.mock.respondError
import io.ktor.http.HttpHeaders
import io.ktor.http.HttpStatusCode import io.ktor.http.HttpStatusCode
import io.ktor.http.headersOf
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi 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.advanceTimeBy
import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.runTest
@@ -15,9 +22,12 @@ import kotlin.test.assertNull
import kotlin.test.assertTrue import kotlin.test.assertTrue
import win.taptap.musicmanager.client.api.ApiClient import win.taptap.musicmanager.client.api.ApiClient
import win.taptap.musicmanager.client.api.Song import win.taptap.musicmanager.client.api.Song
import win.taptap.musicmanager.client.api.User
import win.taptap.musicmanager.client.api.configuredHttpClient import win.taptap.musicmanager.client.api.configuredHttpClient
import win.taptap.musicmanager.client.data.CachedState import win.taptap.musicmanager.client.data.CachedState
import win.taptap.musicmanager.client.data.LibraryCache import win.taptap.musicmanager.client.data.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.playback.AudioPlayer
import win.taptap.musicmanager.client.store.AppStore import win.taptap.musicmanager.client.store.AppStore
@@ -110,43 +120,549 @@ class AppStoreTest {
store.release() 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( private fun kotlinx.coroutines.test.TestScope.store(
storage: MemoryStorage, storage: MemoryStorage,
cache: LibraryCache, cache: LibraryCache,
player: AudioPlayer, player: AudioPlayer,
): AppStore = AppStore( ): AppStore = AppStore(
scope = this, // 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) })), api = ApiClient(configuredHttpClient(MockEngine { respondError(HttpStatusCode.NotFound) })),
storage = storage, storage = storage,
player = player, player = player,
cache = cache, cache = cache,
) )
private fun song(id: String) = Song( private fun song(
id: String,
artist: String = "Artist",
folderId: Int = 1,
duration: Int = 180,
) = Song(
id = id, id = id,
title = "Song $id", title = "Song $id",
artist = "Artist", artist = artist,
album = "Album", album = "Album",
albumId = "al-1", albumId = "al-1",
duration = 180, duration = duration,
bitRate = 320, bitRate = 320,
size = 1_000, size = 1_000,
suffix = "mp3", suffix = "mp3",
folderId = 1, folderId = folderId,
relativePath = "$id.mp3", relativePath = "$id.mp3",
updatedAt = "2026-01-01T00:00:00Z", updatedAt = "2026-01-01T00:00:00Z",
) )
private class FakePlayer : AudioPlayer { private class FakePlayer : AudioPlayer {
val played = mutableListOf<String>() val played = mutableListOf<String>()
val seeks = mutableListOf<Double>()
var paused = false var paused = false
private set private set
private var playing = false private var playing = false
var position = 0.0
private var finished = false
override fun play(source: String, song: Song, local: Boolean, artworkUri: String?) { fun finish() {
finished = true
}
override fun play(
source: String,
song: Song,
local: Boolean,
artworkUri: String?,
artworkBytes: ByteArray?,
) {
played += song.id played += song.id
playing = true playing = true
paused = false paused = false
position = 0.0
finished = false
} }
override fun pause() { override fun pause() {
@@ -164,11 +680,14 @@ class AppStoreTest {
} }
override fun isPlaying(): Boolean = playing override fun isPlaying(): Boolean = playing
override fun isFinished(): Boolean = false override fun isFinished(): Boolean = finished
override fun positionSeconds(): Double = 0.0 override fun positionSeconds(): Double = position
override fun durationSeconds(): Double = 0.0 override fun durationSeconds(): Double = 0.0
override val canSeek: Boolean = false override val canSeek: Boolean = true
override fun seekTo(seconds: Double) = Unit override fun seekTo(seconds: Double) {
position = seconds
seeks += seconds
}
override fun release() { override fun release() {
playing = false playing = false
} }
@@ -5,6 +5,7 @@ import win.taptap.musicmanager.client.data.AppStorage
/** In-memory [AppStorage] for store and cache tests. */ /** In-memory [AppStorage] for store and cache tests. */
internal class MemoryStorage : AppStorage { internal class MemoryStorage : AppStorage {
private val files = mutableMapOf<String, String>() private val files = mutableMapOf<String, String>()
private val artwork = mutableMapOf<String, ByteArray>()
override fun read(name: String): String? = files[name] override fun read(name: String): String? = files[name]
@@ -18,7 +19,14 @@ internal class MemoryStorage : 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 fun saveArtwork(songId: String, bytes: ByteArray): String? {
artwork[songId] = bytes
return "memory://$songId.jpg"
}
override fun artworkBytes(songId: String): ByteArray? = artwork[songId]
override fun listDownloads(): Map<String, Long> = emptyMap() override fun listDownloads(): Map<String, Long> = emptyMap()
override fun deleteDownload(songId: String) = Unit override fun deleteDownload(songId: String) {
artwork.remove(songId)
}
override fun storageUsedBytes(): Long = 0 override fun storageUsedBytes(): Long = 0
} }
@@ -15,7 +15,11 @@ 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 * 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 * decoded stream has to be converted to PCM_SIGNED first. Opening the encoded
@@ -30,23 +34,56 @@ class DesktopAudioPlayer : AudioPlayer {
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 encoded = AudioSystem.getAudioInputStream(buffered) val encoded = AudioSystem.getAudioInputStream(buffered)
@@ -55,6 +92,13 @@ class DesktopAudioPlayer : AudioPlayer {
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)
@@ -89,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
} }
@@ -122,19 +183,32 @@ 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()}"
}
} }
/** /**
@@ -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("")
} }
@@ -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()
} }
+55
View File
@@ -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."
+2 -2
View File
@@ -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;