diff --git a/README.md b/README.md index add682b..936229b 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,11 @@ # AudioManager Client -Kotlin Multiplatform client for [AudioManager](../AudioManager) — a mood-first, self-hosted music server. +Kotlin Multiplatform client for [AudioManager](../AudioManager) — a mood-first, +self-hosted music server. -The client and server are designed together. There is no OpenSubsonic compatibility layer: the app speaks the native `/api/v1` API, where playback is a server-driven radio session and "likes" are replaced by explicit **add to mood** actions. +The client and server are designed together. There is no OpenSubsonic +compatibility layer: the app speaks the native `/api/v1` API, where playback is +a server-driven radio session and songs are added by searching YouTube. ## Targets @@ -12,33 +15,65 @@ The client and server are designed together. There is no OpenSubsonic compatibil | **Desktop (JVM)** | Compose Multiplatform | MP3SPI, decoded to PCM + `SourceDataLine` | Yes | | **Web (Wasm)** | Compose Multiplatform | HTML5 `Audio` | Browser-managed cache only | -The shared module contains the API client, session/cache storage, radio queue, app state and all screens. Platform code is limited to HTTP engines, storage, audio and back handling. - ## Features -- Login with a server URL, username and password. The server returns a revocable bearer token. -- Mood grid with live counts; create, rename, delete and edit moods. -- Seed management: search the owner's music, add or remove anchors. -- Server-driven radio: the app keeps a small queue and asks for more from the same mood session. -- Playback events are reported automatically (`started`, `completed`, `skipped`) so the server learns. +- Login with a server URL, username and password. The server returns a revocable + bearer token. +- **Moods** are the only content model. Each user sees only their own moods. +- **Songs** belong to the mood's permanent collection. A mood needs at least one + song before it can play. +- **Search YouTube** from inside a mood or globally with a mood picker. Tracks + over 10 minutes are hidden. Results that are already downloaded are marked and + add instantly; other videos are queued for server-side download. +- **Paste a YouTube URL** to add a specific video. +- **Recommendations** are downloaded automatically and play in the radio without + being permanent. Rows show the download state with: + - Add to mood; + - Not interested (permanent for the mood); + - Retry for failed downloads. +- **Radio** mixes the collection and ready recommendations using the mood's + `collectionPercent`. The app keeps a small queue and asks for more from the + same mood session. +- Playback events are reported automatically (`started`, `completed`, `skipped`) + so the server learns. - Two add-to-mood actions in the player: - **Add to current mood** (the mood of the active radio session) - **Choose another mood** (picker) -- YT Music recommendations in the mood editor: refresh on demand, accept or reject candidates, thumbnails, and a clear state for library matches (`Seed added`), accepted-for-download tracks (`Queued`, `Downloading`, `Download failed` with retry) and new picks. Accepting a track the library already has adds it as a seed immediately; the rest are downloaded by the server and promoted automatically. -- Library search and playback, plus **Shuffle all** to queue the whole library without starting a mood. -- A queue sheet from the player: the current track plus every upcoming track, with move up/down and remove. Changes are persisted locally. -- **Previous** from the player: after two seconds of playback it restarts the current track; before that it restores the last played track. The track it leaves is put back at the front of the queue. -- **Scrubbing**: the progress slider can be dragged on every platform. Android/web seek natively; desktop restarts the decoder at the requested position (`timeOffset` for remote streams, PCM skip for local files). -- **Seed mix** per mood: a slider chooses the share of seeds vs recommendations for each generated batch. The server rolls the percentage for every queued track and falls back to the other pool when one runs out. -- **Longform tab** for audiobooks and podcasts: per-artist read-only playlists, “Shuffle artist” for random episodes, a resume list with progress, and a separate search scope. Long-form never enters music search, Shuffle all, moods or radio. -- **Sleep timer** (15/30/45/60/90 minutes) that pauses playback. On Android the pause is scheduled inside the media service, so it still fires when the app is backgrounded or the task is swiped away. -- Offline library cache: moods, songs and the last sync revision are stored locally. When the server is unreachable, downloaded tracks still play. -- The play queue and current track are saved locally, so a restart reopens the player paused and resumes on the next tap. +- 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. +- **Scrubbing**: the progress slider can be dragged on every platform. Android and + web seek natively; desktop restarts the decoder at the requested position. +- **Mood settings**: name, description, discovery hint, genres, collection share, + active recommendation count (0–30), and refresh interval. +- **Downloads** screen for device-side copies: play, delete, clear, storage + usage. +- **Sleep timer** (15/30/45/60/90 minutes) that pauses playback. On Android the + pause is scheduled inside the media service, so it still fires when the app is + backgrounded or the task is swiped away. +- Mood cache: moods and details are stored locally so the app opens instantly + and can show cached data offline. +- The play queue and current track are saved locally, so a restart reopens the + player paused and resumes on the next tap. - Reconnects automatically with exponential backoff (15s to 5min) while offline. -- Downloads retry up to three times before reporting an error; covers and YT thumbnails are cached for the app's lifetime. -- Original MP3 downloads with progress state, removal and storage usage. -- Session persistence: the login survives app restarts until the token is revoked or expires. -- Android background playback through a Media3 `MediaSessionService`: notification, lock-screen and headset controls, audio focus, and playback that survives the app being backgrounded or the task being swiped away. +- Session persistence: the login survives app restarts until the token is + revoked or expires. +- Android background playback through a Media3 `MediaSessionService`: + notification, lock-screen and headset controls, audio focus, and playback that + survives the app being backgrounded or the task being swiped away. + +## Screens + +`Moods | Mood Detail | Search | Downloads | Settings` + +- **Moods** — grid with song and pick counts, create, global search. +- **Mood Detail** — songs, add music, recommendations, next batch, settings. +- **Search** — mood picker, YouTube search, paste URL, downloaded badges. +- **Downloads** — offline files and storage usage. +- **Settings** — account, server URL, offline storage, sign out. + +There is no Library tab, no Longform tab and no global shuffle. ## Project layout @@ -46,9 +81,9 @@ The shared module contains the API client, session/cache storage, radio queue, a composeApp/ |-- src/commonMain/kotlin/win/taptap/musicmanager/client/ | |-- api/ # Ktor client and DTOs mirroring /api/v1 -| |-- data/ # AppStorage, LibraryCache, session persistence +| |-- data/ # AppStorage, AppCache, session persistence | |-- playback/ # AudioPlayer abstraction -| |-- store/ # AppStore: state, radio queue, downloads, editing +| |-- store/ # AppStore: state, search, radio queue, downloads | `-- ui/ # Compose screens and theme |-- src/androidMain/ # Activity, Media3 player, filesystem storage |-- src/desktopMain/ # Main window, MP3SPI player, filesystem storage @@ -60,15 +95,18 @@ composeApp/ ## Build -Requirements: JDK 21, Android SDK 36 for the app target, Node (Kotlin downloads its own for web). +Requirements: JDK 21, Android SDK 36 for the app target, Node (Kotlin downloads +its own for web). -With Nix, everything is provided by `shell.nix` (JDK 21, Gradle 8, Node 22, Android SDK 36 with build-tools 36.0.0, and the desktop runtime libraries): +With Nix, everything is provided by `shell.nix` (JDK 21, Gradle 8, Node 22, +Android SDK 36 with build-tools 36.0.0, and the desktop runtime libraries): ```bash nix-shell ``` -The shell accepts the unfree Android SDK license for you; see the comment at the top of `shell.nix`. Without Nix, point `ANDROID_HOME` at an SDK containing platform 36 and build-tools 36.0.0. +Without Nix, point `ANDROID_HOME` at an SDK containing platform 36 and +build-tools 36.0.0. ```bash export ANDROID_HOME=/opt/android-sdk @@ -91,9 +129,12 @@ gradle :composeApp:wasmJsBrowserDistribution # composeApp/build/dist/wasmJs/productionExecutable ``` -Serve the web bundle from any static host (for example `python3 -m http.server` inside the production directory). The server allows cross-origin API calls; enter its URL on the login screen. When the bundle is hosted on the same origin as the server, the URL is prefilled. +Serve the web bundle from any static host (for example `python3 -m http.server` +inside the production directory). The server allows cross-origin API calls; +enter its URL on the login screen. -Android cleartext HTTP is enabled for local development. Use HTTPS in production. +Android cleartext HTTP is enabled for local development. Use HTTPS in +production. ## Publishing to Google Play (internal testing) @@ -130,27 +171,17 @@ scripts/build-release-aab.sh # composeApp/build/outputs/bundle/release/composeApp-release.aab ``` -The script verifies the signature and prints the SHA-256. Bump `versionCode` for -every upload; `VERSION_CODE`/`VERSION_NAME` can also be set in the environment. +The script verifies the signature and prints the SHA-256. ### 3. Upload In Play Console: **Testing → Internal testing → Create new release → App integrity → Google-generated key**, upload the AAB, add release notes, then -**Save → Roll out**. The first upload enrolls the app in Play App Signing. Share -the opt-in link from the Testers tab with your test list. +**Save → Roll out**. ### 4. Automated uploads -Tagged builds (`v*`) publish to internal testing from CI. One-time setup: - -1. In Google Cloud, enable the **Google Play Android Developer API**. -2. Create a service account and download a JSON key. -3. In Play Console → **Users and permissions → Invite new user**, add the - service account's `client_email`, give it access to this app with - **Release to testing tracks** and **View app information** (do not grant - production or admin access). -4. Add these repository secrets in Gitea: +Tagged builds (`v*`) publish to internal testing from CI. The Gitea secrets are: | Secret | Value | | --- | --- | @@ -164,28 +195,28 @@ 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 -`AppStore` is a plain Kotlin class with a `StateFlow`; Compose observes it. It owns: +`AppStore` is a plain Kotlin class with a `StateFlow`; Compose observes +it. It owns: - **Auth** — restore the saved token on launch and log out. -- **Library sync** — first launch pages through `/library/songs`; later launches use the `since` delta and tombstones. Songs are split into music and longform using the folders assigned at login, so the two never mix client-side. -- **Mood cache** — mood details are stored so the app can open them offline. -- **Radio** — one session per mood, batches of 12, prefetch when the queue is short, no repeats within a session. -- **Downloads** — stored under the platform app directory, keyed by deterministic song ID. -- **Playback snapshot** — the session, upcoming queue, current track and play history are persisted on every queue change and restored on the next launch. -- **Longform progress** — position is saved locally and to `/longform/progress` while playing, on pause and on track changes; the resume list is fed from the server when online. -- **Offline retry** — a background loop retries the library sync until the server responds again. +- **Mood sync** — GET `/moods` on login/refresh; details are fetched when a mood + is opened and cached. +- **Mood cache** — cached details power offline mood lists and downloads. +- **Search** — debounced remote YouTube search with the selected target mood. +- **Radio** — one session per mood, batches of 12, prefetch when the queue is + short, no repeats within a session. +- **Downloads** — stored under the platform app directory, keyed by the shared + song id. +- **Playback snapshot** — the session, upcoming queue, current track, history and + position are persisted and restored on the next launch. +- **Offline retry** — a background loop retries the mood sync until the server + responds again. -On startup the app is usable before the network call completes: cached moods and library render immediately, then refresh in the background. +On startup the app is usable before the network call completes: cached moods +render immediately, then refresh in the background. Offline playback uses the +mood's cached songs filtered by downloaded files. ## Radio and add-to-mood @@ -200,14 +231,20 @@ open mood ──► POST /moods/{id}/sessions ──► queue (12 tracks) └─ moodId: chosen mood ``` -Adding a song makes it a permanent seed, so it is always eligible in future radio and visible in the mood editor. +Adding a song makes it permanent in the mood, so it is always eligible in future +radio and visible in the song list. ## CI and releases -`.gitea/workflows/ci.yaml` runs on Gitea Actions using `gitea.tap-tap.win/taptap/audiomanager-client-ci:3`. The image has the Android SDK, Node, Yarn and a warmed Gradle dependency cache, so jobs do not download them on every run. +`.gitea/workflows/ci.yaml` runs on Gitea Actions using +`gitea.tap-tap.win/taptap/audiomanager-client-ci:3`. The image has the Android +SDK, Node, Yarn and a warmed Gradle dependency cache. -- **main / PR:** run `desktopTest`, build the Android APK and the *development* Wasm bundle. The optimized Wasm build is CPU-bound and reserved for releases. -- **`v*` tag:** additionally build the desktop fat jar and the optimized Wasm bundle, then attach all three to the Gitea release. +- **main / PR:** run `desktopTest`, build the Android APK and the *development* + Wasm bundle. +- **`v*` tag:** additionally build the desktop fat jar and the optimized Wasm + bundle, attach the artifacts to the Gitea release, and publish the AAB to Play + internal testing. Rebuild the CI image after changing `ci/Dockerfile` or dependency versions: @@ -215,14 +252,18 @@ Rebuild the CI image after changing `ci/Dockerfile` or dependency versions: scripts/build-ci-image.sh 3 ``` -The image build performs one warm-up compile (`kotlinNodeJsSetup`, `kotlinYarnSetup`, `desktopTest`, `assembleDebug`, `compileKotlinWasmJs`) and then removes the sources, keeping only `/root/.gradle`. - ## Known limitations -- The media notification exposes play/pause and seeking. Queue actions (skip, add to mood) stay in the app because the mood session and its events belong to the server. -- Desktop playback supports seeking by reopening the decoder at the requested position (server `timeOffset` for remote streams, PCM skipping for local files). Longform resume works there too. MP3s are decoded to 16-bit PCM before the line is opened, because Java Sound has no line for the compressed format. -- Web downloads are disabled because the browser owns its storage; the app still streams and caches metadata. -- Accepted recommendations are downloaded by the server into `/AudioManager Imports///`, with the YT thumbnail embedded as cover art, scanned and added as seeds. The per-track folder keeps covers distinct. The server needs outbound network access for this. -- Offline downloads also store the 320 px cover next to the MP3 (`<songId>.jpg`), so the in-app cover and the Android notification artwork survive without the server. Deleting a download removes both files. -- YT Music discovery and automatic downloads run server-side through `yt-dlp`. Accepted tracks that are not in the library are imported into `AudioManager Imports` with embedded cover art and promoted to seeds. +- The media notification exposes play/pause and seeking. Queue actions (skip, + add to mood) stay in the app because the mood session and its events belong to + the server. +- Desktop playback supports seeking by reopening the decoder at the requested + position. MP3s are decoded to 16-bit PCM before the line is opened, because + Java Sound has no line for the compressed format. +- Web downloads are disabled because the browser owns its storage; the app still + streams and caches metadata. +- Downloads store the 320 px cover next to the MP3 (`<songId>.jpg`), so the + in-app cover and the Android notification artwork survive without the server. +- Search and downloads depend on `yt-dlp` on the server. YouTube bot checks can + fail a search (`502`) or leave a recommendation in `failed` with Retry. - No iOS target yet. The shared module is ready for one. diff --git a/composeApp/build.gradle.kts b/composeApp/build.gradle.kts index 8bb6eee..5764b6b 100644 --- a/composeApp/build.gradle.kts +++ b/composeApp/build.gradle.kts @@ -41,7 +41,7 @@ val hasUploadKey = uploadKeyStore?.exists() == true && val appVersionCode = (System.getenv("VERSION_CODE") ?: localProperties.getProperty("VERSION_CODE") ?: "1").toInt() val appVersionName = System.getenv("VERSION_NAME") ?: localProperties.getProperty("VERSION_NAME") - ?: "0.1.0" + ?: "0.2.0" kotlin { androidTarget { diff --git a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/api/ApiClient.kt b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/api/ApiClient.kt index 498c890..6964cba 100644 --- a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/api/ApiClient.kt +++ b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/api/ApiClient.kt @@ -12,7 +12,6 @@ import io.ktor.client.request.get import io.ktor.client.request.header import io.ktor.client.request.patch import io.ktor.client.request.post -import io.ktor.client.request.put import io.ktor.client.request.setBody import io.ktor.client.statement.HttpResponse import io.ktor.client.statement.bodyAsBytes @@ -44,7 +43,6 @@ fun configuredHttpClient(engine: HttpClientEngine): HttpClient = HttpClient(engi } } - /** * Native API client. Media URLs carry the token in the query string because * Android's Media3, desktop playback and HTML audio all fetch them directly. @@ -124,17 +122,22 @@ class ApiClient(private val http: HttpClient) { requestNoContent { http.delete(url("/moods/$id")) { auth() } } } - suspend fun addSeed(moodId: String, songId: String): AddToMoodResponse = + suspend fun addSong( + moodId: String, + songId: String? = null, + videoId: String? = null, + url: String? = null, + ): AddSongResponse = parse( - http.post(url("/moods/$moodId/seeds")) { + http.post(url("/moods/$moodId/songs")) { auth() contentType(ContentType.Application.Json) - setBody(AddSeedRequest(songId)) + setBody(AddSongRequest(songId = songId, videoId = videoId, url = url)) }, ) - suspend fun removeSeed(moodId: String, songId: String) { - requestNoContent { http.delete(url("/moods/$moodId/seeds/$songId")) { auth() } } + suspend fun removeSong(moodId: String, songId: String) { + requestNoContent { http.delete(url("/moods/$moodId/songs/$songId")) { auth() } } } suspend fun recommendations(moodId: String): List<Recommendation> = @@ -152,9 +155,9 @@ class ApiClient(private val http: HttpClient) { }, ) - suspend fun acceptRecommendation(moodId: String, videoId: String): RecommendationDecision = + suspend fun addRecommendation(moodId: String, videoId: String): RecommendationDecision = parse( - http.post(url("/moods/$moodId/recommendations/$videoId/accept")) { + http.post(url("/moods/$moodId/recommendations/$videoId/add")) { auth() }, ) @@ -166,29 +169,18 @@ class ApiClient(private val http: HttpClient) { }, ) + suspend fun retryRecommendation(moodId: String, videoId: String): MoodDetail = + parse( + http.post(url("/moods/$moodId/recommendations/$videoId/retry")) { + auth() + }, + ) + suspend fun preview(moodId: String, limit: Int = 20): List<Song> = - get<SearchResponse>("/moods/$moodId/preview?limit=$limit").songs + get<TracksResponse>("/moods/$moodId/preview?limit=$limit").songs - suspend fun search(query: String, limit: Int = 50, scope: String = "music"): List<Song> = - get<SearchResponse>( - "/library/search?q=${query.encodeURLParameter()}&limit=$limit&scope=$scope", - ).songs - - suspend fun library( - cursor: String? = null, - since: String? = null, - limit: Int = 500, - scope: String = "all", - revision: String? = null, - ): LibraryPage { - val query = buildString { - append("?limit=$limit&scope=$scope") - cursor?.let { append("&cursor=${it.encodeURLParameter()}") } - since?.let { append("&since=${it.encodeURLParameter()}") } - revision?.let { append("&revision=${it.encodeURLParameter()}") } - } - return get("/library/songs$query") - } + suspend fun search(query: String, limit: Int = 20): List<SearchResult> = + get<SearchResponse>("/search?q=${query.encodeURLParameter()}&limit=$limit").results suspend fun startSession(moodId: String, limit: Int = 12): Session = parse( @@ -232,40 +224,14 @@ class ApiClient(private val http: HttpClient) { runCatching { requestNoContent { http.delete(url("/sessions/$id")) { auth() } } } } - suspend fun longformProgress(): List<LongformProgressItem> = - get<LongformProgressResponse>("/longform/progress").items - - suspend fun saveLongformProgress( - songId: String, - positionSeconds: Int, - durationSeconds: Int, - completed: Boolean, - ) { - val response = http.put(url("/longform/progress/$songId")) { - auth() - contentType(ContentType.Application.Json) - setBody(SaveLongformProgressRequest(positionSeconds, durationSeconds, completed)) - } - if (!response.status.isSuccess()) throw error(response) - } - suspend fun devices(): List<Device> = get("/auth/devices") - suspend fun scanStatus(): ScanStatus = get("/scan") - - suspend fun startScan(): ScanStatus = - parse( - http.post(url("/scan")) { - auth() - }, - ) - - suspend fun cover(albumId: String, size: Int = 320): ByteArray? { - val key = "$albumId:$size" + suspend fun cover(songId: String, size: Int = 320): ByteArray? { + val key = "$songId:$size" if (coverCache.containsKey(key)) return coverCache[key] val result = runCatching { val response = http.get( - "$baseUrl/api/v1/covers/$albumId?size=$size&token=${token.orEmpty().encodeURLParameter()}", + "$baseUrl/api/v1/songs/$songId/cover?size=$size&token=${token.orEmpty().encodeURLParameter()}", ) if (response.status.isSuccess()) { response.bodyAsBytes().takeIf { it.isNotEmpty() } @@ -274,8 +240,7 @@ class ApiClient(private val http: HttpClient) { } }.getOrNull() if (coverCache.size > MAX_CACHED_IMAGES) coverCache.clear() - // Do not cache failures: a cover can appear after the scanner indexes a - // newly downloaded track, and the UI should pick it up without a restart. + // Do not cache failures: a cover can appear after a download finishes. if (result != null) coverCache[key] = result return result } @@ -319,8 +284,6 @@ class ApiClient(private val http: HttpClient) { val response = http.get("$baseUrl/api/v1/songs/$songId/stream") { auth() url.parameters.append("download", "true") - // A long audiobook must not be cancelled by the default 30s total - // request timeout. timeout { requestTimeoutMillis = 6 * 60 * 60 * 1000 socketTimeoutMillis = 60_000 @@ -333,8 +296,8 @@ class ApiClient(private val http: HttpClient) { fun streamUrl(songId: String): String = "$baseUrl/api/v1/songs/$songId/stream?token=${token.orEmpty().encodeURLParameter()}" - fun coverUrl(albumId: String, size: Int = 320): String = - "$baseUrl/api/v1/covers/$albumId?size=$size&token=${token.orEmpty().encodeURLParameter()}" + fun coverUrl(songId: String, size: Int = 320): String = + "$baseUrl/api/v1/songs/$songId/cover?size=$size&token=${token.orEmpty().encodeURLParameter()}" private suspend inline fun <reified T> get(path: String): T = parse(http.get(url(path)) { auth() }) diff --git a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/api/Models.kt b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/api/Models.kt index 2a4913c..9408f0a 100644 --- a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/api/Models.kt +++ b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/api/Models.kt @@ -23,8 +23,6 @@ data class LoginRequest( data class User( val name: String, val admin: Boolean, - val musicFolders: List<Int> = emptyList(), - val longformFolders: List<Int> = emptyList(), ) @Serializable @@ -37,22 +35,18 @@ data class LoginResponse( @Serializable data class Song( val id: String, + val videoId: String, val title: String, val artist: String, - val album: String, - val albumId: String, - val trackNumber: Int? = null, - val discNumber: Int = 1, - val year: Int? = null, + val album: String? = null, val duration: Int, - val bitRate: Int, - val size: Long, - val suffix: String, - val genres: List<String> = emptyList(), - val folderId: Int, - val relativePath: String, - val updatedAt: String, -) + val bitRate: Int = 0, + val size: Long = 0, + val suffix: String = "mp3", + val thumbnail: String? = null, +) { + val subtitle: String get() = album?.takeIf { it.isNotBlank() } ?: artist +} @Serializable data class Mood( @@ -61,21 +55,22 @@ data class Mood( val description: String? = null, val query: String? = null, val genres: List<String> = emptyList(), - val targetSize: Int, - val seedPercent: Int = 50, + val collectionPercent: Int = 50, val recommendationPercent: Int = 50, - val refreshHours: Int, - val ytEnabled: Boolean, + val recommendationCount: Int = 10, + val refreshHours: Int = 24, val lastDiscoveryAt: String? = null, val createdAt: String, val changedAt: String, val lastError: String? = null, - val seedCount: Int, - val newRecommendations: Int = 0, + val songCount: Int = 0, + val recommendationReady: Int = 0, + val recommendationDownloading: Int = 0, + val recommendationFailed: Int = 0, ) @Serializable -data class Seed( +data class MoodSong( val song: Song, val origin: String, val addedAt: String, @@ -86,7 +81,7 @@ data class Download( val state: String, val attempts: Int = 0, val error: String? = null, - val updatedAt: String, + val updatedAt: String = "", ) @Serializable @@ -98,50 +93,22 @@ data class Recommendation( val duration: Int? = null, val thumbnail: String? = null, val state: String, - val matchedSong: Song? = null, - val timesAdded: Int = 0, - val firstSeen: String, - val lastSeen: String, + val song: Song? = null, val download: Download? = null, -) - -@Serializable -data class LongformProgressItem( - val song: Song, - val positionSeconds: Int, - val durationSeconds: Int, - val completed: Boolean, - val updatedAt: String, -) - -@Serializable -data class LongformProgressResponse(val items: List<LongformProgressItem> = emptyList()) - -@Serializable -data class SaveLongformProgressRequest( - val positionSeconds: Int, - val durationSeconds: Int? = null, - val completed: Boolean = false, -) - -@Serializable -data class LongformProgress( - val songId: String, - val positionSeconds: Int, - val durationSeconds: Int, - val completed: Boolean, - val updatedAt: String, + val error: String? = null, + val firstSeen: String = "", + val lastSeen: String = "", ) @Serializable data class MoodDetail( val mood: Mood, - val seeds: List<Seed> = emptyList(), + val songs: List<MoodSong> = emptyList(), val recommendations: List<Recommendation> = emptyList(), ) @Serializable -data class MoodsResponse(val moods: List<Mood>) +data class MoodsResponse(val moods: List<Mood> = emptyList()) @Serializable data class RecommendationsResponse(val recommendations: List<Recommendation> = emptyList()) @@ -150,20 +117,22 @@ data class RecommendationsResponse(val recommendations: List<Recommendation> = e data class RecommendationDecision( val detail: MoodDetail, val recommendation: Recommendation, - val seedAdded: Boolean = false, ) @Serializable -data class LibraryPage( - val songs: List<Song> = emptyList(), - val deletedSongIds: List<String> = emptyList(), - val revision: String, - val nextCursor: String? = null, - val nextSince: String? = null, +data class SearchResult( + val videoId: String, + val title: String, + val artist: String, + val album: String? = null, + val duration: Int? = null, + val thumbnail: String? = null, + val songId: String? = null, + val downloaded: Boolean = false, ) @Serializable -data class SearchResponse(val songs: List<Song> = emptyList()) +data class SearchResponse(val results: List<SearchResult> = emptyList()) @Serializable data class Session( @@ -206,8 +175,20 @@ data class AddToMoodRequest(val songId: String, val moodId: String? = null) @Serializable data class AddToMoodResponse(val mood: Mood, val added: Boolean) +/** Adds an existing song, a search result's video id, or a pasted URL. */ @Serializable -data class AddSeedRequest(val songId: String, val origin: String = "manual") +data class AddSongRequest( + val songId: String? = null, + val videoId: String? = null, + val url: String? = null, +) + +@Serializable +data class AddSongResponse( + val detail: MoodDetail, + val added: Boolean = false, + val downloading: Boolean = false, +) @Serializable data class CreateMoodRequest( @@ -215,11 +196,9 @@ data class CreateMoodRequest( val description: String? = null, val query: String? = null, val genres: List<String> = emptyList(), - val targetSize: Int = 30, + val collectionPercent: Int = 50, + val recommendationCount: Int = 10, val refreshHours: Int = 24, - val ytEnabled: Boolean = true, - val seedSongIds: List<String> = emptyList(), - val seedPercent: Int = 50, ) @Serializable @@ -230,10 +209,9 @@ data class UpdateMoodRequest( val query: String? = null, val clearQuery: Boolean = false, val genres: List<String>? = null, - val targetSize: Int? = null, + val collectionPercent: Int? = null, + val recommendationCount: Int? = null, val refreshHours: Int? = null, - val ytEnabled: Boolean? = null, - val seedPercent: Int? = null, ) @Serializable diff --git a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/data/LibraryCache.kt b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/data/AppCache.kt similarity index 77% rename from composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/data/LibraryCache.kt rename to composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/data/AppCache.kt index e35d421..09f75a3 100644 --- a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/data/LibraryCache.kt +++ b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/data/AppCache.kt @@ -2,7 +2,6 @@ package win.taptap.musicmanager.client.data import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json -import win.taptap.musicmanager.client.api.LongformProgress import win.taptap.musicmanager.client.api.Mood import win.taptap.musicmanager.client.api.MoodDetail import win.taptap.musicmanager.client.api.Session @@ -16,16 +15,22 @@ data class SessionState( val user: User, ) +/** + * Offline cache. Version 2 holds moods and their details only; the old + * mounted-library shape is discarded instead of silently mis-decoding. + */ @Serializable data class CachedState( + val version: Int = CACHE_VERSION, val serverUrl: String = "", val userName: String = "", - val revision: String? = null, - val songs: List<Song> = emptyList(), - val longform: List<Song> = emptyList(), val moods: List<Mood> = emptyList(), val moodDetails: List<MoodDetail> = emptyList(), -) +) { + companion object { + const val CACHE_VERSION = 2 + } +} /** The queue survives a restart so the next launch can resume where it stopped. */ @Serializable @@ -37,7 +42,7 @@ data class PlaybackSnapshot( val positionSeconds: Double = 0.0, ) -class LibraryCache(private val storage: AppStorage) { +class AppCache(private val storage: AppStorage) { private val json = Json { ignoreUnknownKeys = true @@ -54,10 +59,12 @@ class LibraryCache(private val storage: AppStorage) { if (session == null) delete(SESSION_FILE) else write(SESSION_FILE, json.encodeToString(session)) } - fun load(): CachedState = - read(CACHE_FILE)?.let { + fun load(): CachedState { + val cached = read(CACHE_FILE)?.let { runCatching { json.decodeFromString<CachedState>(it) }.getOrNull() - } ?: CachedState() + } ?: return CachedState() + return if (cached.version == CachedState.CACHE_VERSION) cached else CachedState() + } fun save(state: CachedState) { write(CACHE_FILE, json.encodeToString(state)) @@ -76,19 +83,9 @@ class LibraryCache(private val storage: AppStorage) { } } - fun loadProgress(): List<LongformProgress> = - read(PROGRESS_FILE)?.let { - runCatching { json.decodeFromString<List<LongformProgress>>(it) }.getOrNull() - } ?: emptyList() - - fun saveProgress(progress: List<LongformProgress>) { - write(PROGRESS_FILE, json.encodeToString(progress)) - } - fun clear() { delete(CACHE_FILE) delete(PLAYBACK_FILE) - delete(PROGRESS_FILE) } // Web storage can be blocked (Safari private mode) or full. Cache failure @@ -103,8 +100,7 @@ class LibraryCache(private val storage: AppStorage) { private companion object { const val SESSION_FILE = "session.json" - const val CACHE_FILE = "library.json" + const val CACHE_FILE = "mood-cache.json" const val PLAYBACK_FILE = "playback.json" - const val PROGRESS_FILE = "longform-progress.json" } } diff --git a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/store/AppStore.kt b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/store/AppStore.kt index eac3e74..6d96f1a 100644 --- a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/store/AppStore.kt +++ b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/store/AppStore.kt @@ -6,38 +6,34 @@ import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.launch -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update -import kotlinx.datetime.Clock import kotlin.random.Random import win.taptap.musicmanager.client.api.ApiClient -import win.taptap.musicmanager.client.createAudioPlayer -import win.taptap.musicmanager.client.platformEngine -import win.taptap.musicmanager.client.platformName -import win.taptap.musicmanager.client.platformStorage import win.taptap.musicmanager.client.api.ApiException import win.taptap.musicmanager.client.api.CreateMoodRequest -import win.taptap.musicmanager.client.api.LongformProgress -import win.taptap.musicmanager.client.api.LongformProgressItem import win.taptap.musicmanager.client.api.Mood import win.taptap.musicmanager.client.api.MoodDetail import win.taptap.musicmanager.client.api.PlaybackEvent +import win.taptap.musicmanager.client.api.SearchResult import win.taptap.musicmanager.client.api.Session import win.taptap.musicmanager.client.api.Song import win.taptap.musicmanager.client.api.UpdateMoodRequest import win.taptap.musicmanager.client.api.configuredHttpClient +import win.taptap.musicmanager.client.createAudioPlayer +import win.taptap.musicmanager.client.data.AppCache import win.taptap.musicmanager.client.data.CachedState -import win.taptap.musicmanager.client.data.LibraryCache import win.taptap.musicmanager.client.data.PlaybackSnapshot import win.taptap.musicmanager.client.data.SessionState +import win.taptap.musicmanager.client.data.AppStorage import win.taptap.musicmanager.client.playback.AudioPlayer +import win.taptap.musicmanager.client.platformEngine import win.taptap.musicmanager.client.platformName +import win.taptap.musicmanager.client.platformStorage -enum class Screen { Moods, MoodDetail, Library, Settings } +enum class Screen { Moods, MoodDetail, Search, Downloads, Settings } data class AppState( val booting: Boolean = true, @@ -59,14 +55,11 @@ data class AppState( val sleepTimerRemainingSeconds: Long? = null, val downloads: Set<String> = emptySet(), val downloading: Set<String> = emptySet(), - val library: List<Song> = emptyList(), - val longform: List<Song> = emptyList(), - val longformResults: List<Song> = emptyList(), - val longformProgress: Map<String, LongformProgress> = emptyMap(), - /** Results for the mood seed picker. */ - val searchResults: List<Song> = emptyList(), - /** Results for the Music library tab, kept separate from mood search. */ - val musicResults: List<Song> = emptyList(), + /** Metadata for songs seen in moods, queues and the cache, used by Downloads. */ + val knownSongs: Map<String, Song> = emptyMap(), + val searchQuery: String = "", + val searchResults: List<SearchResult> = emptyList(), + val searchTargetMoodId: String? = null, val searching: Boolean = false, val loading: Boolean = false, val saving: Boolean = false, @@ -83,9 +76,9 @@ data class AppState( class AppStore( private val scope: CoroutineScope, private val api: ApiClient = ApiClient(configuredHttpClient(platformEngine())), - private val storage: win.taptap.musicmanager.client.data.AppStorage = platformStorage(), + private val storage: AppStorage = platformStorage(), private val player: AudioPlayer = createAudioPlayer(), - private val cache: LibraryCache = LibraryCache(storage), + private val cache: AppCache = AppCache(storage), ) { private val _state = MutableStateFlow(AppState()) val state: StateFlow<AppState> = _state.asStateFlow() @@ -93,8 +86,7 @@ class AppStore( private var pollJob: Job? = null private var refreshJob: Job? = null private var sleepJob: Job? = null - private var musicSearchJob: Job? = null - private var longformSearchJob: Job? = null + private var searchJob: Job? = null private var reconnectJob: Job? = null private var playbackStarted = false private var advancing = false @@ -105,7 +97,6 @@ class AppStore( private var dataGeneration = 0 private var moodRequestGeneration = 0 private var loggingOut = false - private val progressSaveMutex = Mutex() init { bootstrap() @@ -116,27 +107,20 @@ class AppStore( val session = cache.loadSession() val cached = cache.load() val playback = cache.loadPlayback() - val progress = cache.loadProgress() - val progressById = progress.associateBy { entry -> entry.songId } val restoredSong = playback?.current - val restoredPosition = playback?.positionSeconds?.takeIf { it > 0.0 } - ?: restoredSong?.let { progressById[it.id]?.positionSeconds?.toDouble() } - ?: 0.0 - trackStartOffset = restoredPosition + _state.update { it.copy( booting = false, downloads = storage.listDownloads().keys, moods = cached.moods, - library = cached.songs.sortedLibrary(), - longform = cached.longform.sortedLibrary(), - longformProgress = progressById, selectedMood = cached.moodDetails.firstOrNull(), + knownSongs = cached.moodDetails.songMap(playback), session = playback?.session, queue = playback?.queue.orEmpty(), current = restoredSong, history = playback?.history.orEmpty(), - positionSeconds = restoredPosition, + positionSeconds = playback?.positionSeconds ?: 0.0, durationSeconds = restoredSong?.duration?.toDouble() ?: 0.0, ) } @@ -183,7 +167,12 @@ class AppStore( refreshAll() } catch (t: Throwable) { _state.update { - it.copy(loading = false, message = t.friendlyMessage(), messageIsError = true, messageId = it.messageId + 1) + it.copy( + loading = false, + message = t.friendlyMessage(), + messageIsError = true, + messageId = it.messageId + 1, + ) } } } @@ -193,8 +182,7 @@ class AppStore( dataGeneration += 1 loggingOut = true scope.launch { - musicSearchJob?.cancel() - longformSearchJob?.cancel() + searchJob?.cancel() refreshJob?.cancel() stopPlayback() runCatching { api.logout() } @@ -218,8 +206,6 @@ class AppStore( if (!silent) _state.update { it.copy(loading = true) } val generation = dataGeneration try { - // Folder assignments can change server-side after login. Re-read the - // user so the music/longform split does not keep using stale folders. val me = try { api.me() } catch (t: ApiException) { @@ -230,52 +216,13 @@ class AppStore( if (me != null) { cache.loadSession()?.let { session -> cache.saveSession(session.copy(user = me)) } } + val moods = api.moods() val loaded = cache.load() val cacheMatches = loaded.serverUrl == _state.value.serverUrl && (loaded.userName.isEmpty() || loaded.userName == currentUser?.name.orEmpty()) val cached = if (cacheMatches) loaded else CachedState() - // Both halves of the cache must feed the delta sync; otherwise the - // long-form list disappears as soon as the first delta arrives. - var songs = (cached.songs + cached.longform) - .associateBy { it.id } - .toMutableMap() - var revision = cached.revision - - if (revision == null) { - // Keep the first page's timestamp across the whole snapshot, so - // songs inserted between pages are fetched by the next delta. - var snapshotRevision: String? = null - var cursor: String? = null - do { - val page = api.library( - cursor = cursor, - since = null, - limit = 500, - revision = snapshotRevision, - ) - if (snapshotRevision == null) snapshotRevision = page.revision - page.songs.forEach { songs[it.id] = it } - cursor = page.nextCursor - revision = page.revision - } while (cursor != null) - } else { - var since: String? = revision - while (since != null) { - val page = api.library(cursor = null, since = since, limit = 500) - page.songs.forEach { songs[it.id] = it } - page.deletedSongIds.forEach { songs.remove(it) } - revision = page.revision - since = page.nextSince - } - } - val details = cached.moodDetails.filter { detail -> moods.any { it.id == detail.mood.id } } - val longformFolders = currentUser?.longformFolders?.toSet().orEmpty() - val allSongs = songs.values.toList() - val longformSongs = allSongs.filter { it.folderId in longformFolders } - val musicSongs = allSongs.filterNot { it.folderId in longformFolders } - val serverProgress = runCatching { api.longformProgress() }.getOrNull() if (generation != dataGeneration) return runCatching { @@ -283,55 +230,18 @@ class AppStore( CachedState( serverUrl = _state.value.serverUrl, userName = currentUser?.name.orEmpty(), - revision = revision, - songs = musicSongs, - longform = longformSongs, moods = moods, moodDetails = details, ), ) } - // Progress saved while offline must not be replaced by a stale - // server copy. Keep whichever entry was updated last. - val localProgress = _state.value.longformProgress - val mergedProgress = localProgress.toMutableMap() - serverProgress?.forEach { item -> - val remote = item.toProgress() - val existing = mergedProgress[remote.songId] - if (existing == null || remote.updatedAt >= existing.updatedAt) { - mergedProgress[remote.songId] = remote - } - } - if (generation != dataGeneration) return - if (serverProgress != null) { - cache.saveProgress(mergedProgress.values.toList()) - // Replay local positions that are newer than the server copy - // (typically written while offline). - mergedProgress.forEach { (songId, local) -> - val remote = serverProgress.firstOrNull { it.song.id == songId } - if (remote == null || local.updatedAt > remote.updatedAt) { - runCatching { - api.saveLongformProgress( - songId, - local.positionSeconds, - local.durationSeconds, - local.completed, - ) - } - } - } - } - - if (generation != dataGeneration) return _state.update { it.copy( loading = false, offline = false, user = currentUser, moods = moods, - library = musicSongs.sortedLibrary(), - longform = longformSongs.sortedLibrary(), - longformProgress = if (serverProgress != null) mergedProgress else it.longformProgress, + knownSongs = it.knownSongs + details.songMap(null), ) } } catch (t: Throwable) { @@ -366,7 +276,6 @@ class AppStore( screen = Screen.MoodDetail, selectedMood = null, preview = emptyList(), - searchResults = emptyList(), ) } try { @@ -374,7 +283,15 @@ class AppStore( val preview = runCatching { api.preview(id, 20) }.getOrDefault(emptyList()) if (request != moodRequestGeneration) return@launch cacheDetail(detail) - _state.update { it.copy(loading = false, selectedMood = detail, preview = preview) } + _state.update { + it.copy( + loading = false, + selectedMood = detail, + preview = preview, + knownSongs = it.knownSongs + detail.songMap(), + ) + } + mergeSongs(preview) } catch (t: Throwable) { if (request != moodRequestGeneration) return@launch val cached = cache.load().moodDetails.firstOrNull { it.mood.id == id } @@ -384,6 +301,7 @@ class AppStore( // Never leave a different mood editable under the new title. selectedMood = cached, preview = emptyList(), + knownSongs = it.knownSongs + (cached?.songMap() ?: emptyMap()), message = if (cached == null) t.friendlyMessage() else "Showing cached mood", messageIsError = cached == null, messageId = it.messageId + 1, @@ -403,23 +321,132 @@ class AppStore( } } - fun openLibrary() { - _state.update { it.copy(screen = Screen.Library) } + fun openSearch(targetMoodId: String? = null) { + _state.update { + val target = targetMoodId + ?: it.searchTargetMoodId?.takeIf { id -> it.moods.any { mood -> mood.id == id } } + ?: it.moods.firstOrNull()?.id + it.copy( + screen = Screen.Search, + searchTargetMoodId = target, + searchResults = emptyList(), + searchQuery = "", + ) + } + } + + fun openDownloads() { + _state.update { it.copy(screen = Screen.Downloads) } } fun openSettings() { _state.update { it.copy(screen = Screen.Settings) } } + fun selectSearchMood(moodId: String) { + _state.update { it.copy(searchTargetMoodId = moodId) } + } + + fun setSearchQuery(query: String) { + _state.update { it.copy(searchQuery = query) } + search(query) + } + + fun search(query: String) { + searchJob?.cancel() + if (query.isBlank()) { + _state.update { it.copy(searchResults = emptyList(), searching = false) } + return + } + searchJob = scope.launch { + delay(SEARCH_DEBOUNCE_MS) + _state.update { it.copy(searching = true) } + try { + val results = api.search(query, 20) + _state.update { it.copy(searchResults = results) } + } catch (t: CancellationException) { + throw t + } catch (t: Throwable) { + _state.update { it.copy(searchResults = emptyList()) } + message(t) + } finally { + _state.update { it.copy(searching = false) } + } + } + } + + fun addSearchResult(result: SearchResult) { + val target = _state.value.searchTargetMoodId + if (target == null) { + _state.update { + it.copy( + message = "Choose a mood first", + messageIsError = true, + messageId = it.messageId + 1, + ) + } + return + } + scope.launch { + try { + val response = if (result.songId != null) { + api.addSong(target, songId = result.songId) + } else { + api.addSong(target, videoId = result.videoId) + } + applyMoodDetail(response.detail) + val title = response.detail.mood.name + _state.update { + it.copy( + message = when { + response.added -> "Added to $title" + response.downloading -> "Downloading for $title" + else -> "Already in $title" + }, + messageIsError = false, + messageId = it.messageId + 1, + ) + } + } catch (t: Throwable) { + message(t) + } + } + } + + fun addByUrl(url: String) { + val target = _state.value.searchTargetMoodId ?: return + if (url.isBlank()) return + scope.launch { + try { + val response = api.addSong(target, url = url.trim()) + applyMoodDetail(response.detail) + _state.update { + it.copy( + searchQuery = "", + searchResults = emptyList(), + message = if (response.downloading) { + "Downloading for ${response.detail.mood.name}" + } else { + "Added to ${response.detail.mood.name}" + }, + messageIsError = false, + messageId = it.messageId + 1, + ) + } + } catch (t: Throwable) { + message(t) + } + } + } + fun createMood( name: String, description: String?, genres: List<String>, query: String?, - targetSize: Int, + collectionPercent: Int, + recommendationCount: Int, refreshHours: Int, - ytEnabled: Boolean, - seedPercent: Int = 50, ) { scope.launch { _state.update { it.copy(saving = true) } @@ -430,10 +457,9 @@ class AppStore( description = description?.takeIf { it.isNotBlank() }, query = query?.takeIf { it.isNotBlank() }, genres = genres, - targetSize = targetSize, + collectionPercent = collectionPercent, + recommendationCount = recommendationCount, refreshHours = refreshHours, - ytEnabled = ytEnabled, - seedPercent = seedPercent, ), ) cacheDetail(detail) @@ -443,13 +469,21 @@ class AppStore( selectedMood = detail, screen = Screen.MoodDetail, moods = it.moods + detail.mood, + knownSongs = it.knownSongs + detail.songMap(), message = "Mood created", messageIsError = false, messageId = it.messageId + 1, ) } } catch (t: Throwable) { - _state.update { it.copy(saving = false, message = t.friendlyMessage(), messageIsError = true, messageId = it.messageId + 1) } + _state.update { + it.copy( + saving = false, + message = t.friendlyMessage(), + messageIsError = true, + messageId = it.messageId + 1, + ) + } } } } @@ -460,10 +494,9 @@ class AppStore( description: String?, genres: List<String>, query: String?, - targetSize: Int, + collectionPercent: Int, + recommendationCount: Int, refreshHours: Int, - ytEnabled: Boolean, - seedPercent: Int = 50, ) { scope.launch { _state.update { it.copy(saving = true) } @@ -477,10 +510,9 @@ class AppStore( query = query ?: "", clearQuery = query.isNullOrBlank(), genres = genres, - targetSize = targetSize, + collectionPercent = collectionPercent, + recommendationCount = recommendationCount, refreshHours = refreshHours, - ytEnabled = ytEnabled, - seedPercent = seedPercent, ), ) applyMoodDetail(updated) @@ -493,7 +525,14 @@ class AppStore( ) } } catch (t: Throwable) { - _state.update { it.copy(saving = false, message = t.friendlyMessage(), messageIsError = true, messageId = it.messageId + 1) } + _state.update { + it.copy( + saving = false, + message = t.friendlyMessage(), + messageIsError = true, + messageId = it.messageId + 1, + ) + } } } } @@ -512,21 +551,22 @@ class AppStore( messageId = it.messageId + 1, ) } + cacheDetailRemoval(id) } catch (t: Throwable) { message(t) } } } - fun addSeed(moodId: String, songId: String) { + fun removeSong(moodId: String, songId: String) { scope.launch { try { - api.addSeed(moodId, songId) + api.removeSong(moodId, songId) val detail = api.mood(moodId) applyMoodDetail(detail) _state.update { it.copy( - message = "Seed added", + message = "Removed from mood", messageIsError = false, messageId = it.messageId + 1, ) @@ -537,15 +577,93 @@ class AppStore( } } - fun removeSeed(moodId: String, songId: String) { + fun refreshRecommendations() { + val moodId = _state.value.selectedMood?.mood?.id ?: return + if (_state.value.discovering) return + scope.launch { + _state.update { it.copy(discovering = true) } + try { + val detail = api.refreshRecommendations(moodId) + applyMoodDetail(detail) + val active = detail.recommendations.size + _state.update { + it.copy( + discovering = false, + message = if (active > 0) { + "$active recommendations" + } else { + "No recommendations yet" + }, + messageIsError = false, + messageId = it.messageId + 1, + ) + } + } catch (t: Throwable) { + _state.update { it.copy(discovering = false) } + message(t) + } + } + } + + fun addRecommendation(videoId: String) { + val moodId = _state.value.selectedMood?.mood?.id ?: return + if (_state.value.discovering) return + scope.launch { + _state.update { it.copy(discovering = true) } + try { + val decision = api.addRecommendation(moodId, videoId) + applyMoodDetail(decision.detail) + _state.update { + it.copy( + discovering = false, + message = if (decision.recommendation.song != null) { + "Added to ${decision.detail.mood.name}" + } else { + "Will be added when the download finishes" + }, + messageIsError = false, + messageId = it.messageId + 1, + ) + } + } catch (t: Throwable) { + _state.update { it.copy(discovering = false) } + message(t) + } + } + } + + fun rejectRecommendation(videoId: String) { + val moodId = _state.value.selectedMood?.mood?.id ?: return + if (_state.value.discovering) return + scope.launch { + _state.update { it.copy(discovering = true) } + try { + val decision = api.rejectRecommendation(moodId, videoId) + applyMoodDetail(decision.detail) + _state.update { + it.copy( + discovering = false, + message = "Not interested", + messageIsError = false, + messageId = it.messageId + 1, + ) + } + } catch (t: Throwable) { + _state.update { it.copy(discovering = false) } + message(t) + } + } + } + + fun retryRecommendation(videoId: String) { + val moodId = _state.value.selectedMood?.mood?.id ?: return scope.launch { try { - api.removeSeed(moodId, songId) - val detail = api.mood(moodId) + val detail = api.retryRecommendation(moodId, videoId) applyMoodDetail(detail) _state.update { it.copy( - message = "Seed removed", + message = "Retrying download", messageIsError = false, messageId = it.messageId + 1, ) @@ -556,74 +674,24 @@ class AppStore( } } - fun search(query: String) { - if (query.isBlank()) { - _state.update { it.copy(searchResults = emptyList()) } - return - } - scope.launch { - _state.update { it.copy(searching = true) } - try { - val songs = api.search(query, 60) - _state.update { it.copy(searching = false, searchResults = songs) } - } catch (t: Throwable) { - _state.update { it.copy(searching = false, searchResults = emptyList()) } - message(t) - } - } - } - - fun searchMusic(query: String) { - musicSearchJob?.cancel() - if (query.isBlank()) { - _state.update { it.copy(musicResults = emptyList()) } - return - } - musicSearchJob = scope.launch { - delay(SEARCH_DEBOUNCE_MS) - _state.update { it.copy(searching = true) } - try { - val songs = api.search(query, 60, scope = "music") - _state.update { it.copy(musicResults = songs) } - } catch (t: CancellationException) { - throw t - } catch (t: Throwable) { - _state.update { it.copy(musicResults = emptyList()) } - message(t) - } finally { - _state.update { it.copy(searching = false) } - } - } - } - - fun searchLongform(query: String) { - longformSearchJob?.cancel() - if (query.isBlank()) { - _state.update { it.copy(longformResults = emptyList()) } - return - } - longformSearchJob = scope.launch { - delay(SEARCH_DEBOUNCE_MS) - _state.update { it.copy(searching = true) } - try { - val songs = api.search(query, 60, scope = "longform") - _state.update { it.copy(longformResults = songs) } - } catch (t: CancellationException) { - throw t - } catch (t: Throwable) { - _state.update { it.copy(longformResults = emptyList()) } - message(t) - } finally { - _state.update { it.copy(searching = false) } - } - } - } - fun playMood(moodId: String) { scope.launch { val state = _state.value + val detail = state.selectedMood?.takeIf { it.mood.id == moodId } + ?: cache.load().moodDetails.firstOrNull { it.mood.id == moodId } + if (detail != null && detail.songs.isEmpty()) { + _state.update { + it.copy( + message = "Add at least one song before playing this mood", + messageIsError = true, + messageId = it.messageId + 1, + ) + } + return@launch + } try { val session = api.startSession(moodId, 12) + mergeSongs(session.queue) _state.update { it.copy( session = session, @@ -635,7 +703,10 @@ class AppStore( playNext() persistPlayback() } catch (t: Throwable) { - val fallback = state.library.filter { it.id in state.downloads } + val fallback = detail?.songs + ?.map { it.song } + ?.filter { it.id in state.downloads } + .orEmpty() if (fallback.isNotEmpty()) { _state.update { it.copy( @@ -659,8 +730,8 @@ class AppStore( fun playSong(song: Song) { scope.launch { - reportCurrentProgress(completed = false) _state.value.session?.let { api.closeSession(it.id) } + mergeSongs(listOf(song)) _state.update { it.copy( session = null, @@ -677,87 +748,6 @@ class AppStore( } } - /** - * Builds a local queue from the whole library, so playback does not depend on - * a mood session. Shuffled by default because "play everything" is most - * useful as a mix. - */ - fun playAll(shuffled: Boolean = true) { - val state = _state.value - val songs = if (state.offline) { - state.library.filter { it.id in state.downloads } - } else { - state.library - } - if (songs.isEmpty()) { - _state.update { - it.copy( - message = if (state.offline) { - "No downloaded tracks available offline." - } else { - "The library is empty. Scan a music folder first." - }, - messageIsError = true, - messageId = it.messageId + 1, - ) - } - return - } - scope.launch { - state.session?.let { runCatching { api.closeSession(it.id) } } - val queue = if (shuffled) songs.shuffled(Random.Default) else songs - _state.update { it.copy(session = null, queue = queue) } - playNext() - persistPlayback() - } - } - - /** Queues every long-form track of one artist, shuffled by default. */ - fun playLongformArtist(artist: String, shuffled: Boolean = true) { - val songs = _state.value.longform.filter { it.artist == artist } - if (songs.isEmpty()) return - scope.launch { - _state.value.session?.let { runCatching { api.closeSession(it.id) } } - val queue = if (shuffled) songs.shuffled(Random.Default) else songs - _state.update { it.copy(session = null, queue = queue) } - playNext() - persistPlayback() - } - } - - fun playLongformSong(song: Song, startAtSeconds: Double? = null) { - scope.launch { - reportCurrentProgress(completed = false) - _state.value.session?.let { runCatching { api.closeSession(it.id) } } - val startAt = startAtSeconds ?: savedPosition(song) - _state.update { - it.copy( - session = null, - queue = emptyList(), - current = song, - history = pushHistory(it.history, it.current), - playing = true, - positionSeconds = startAt, - durationSeconds = song.duration.toDouble(), - ) - } - persistPlayback() - startSong(song, startAt) - } - } - - fun resumeLongform(songId: String) { - val state = _state.value - val song = state.longform.firstOrNull { it.id == songId } ?: return - playLongformSong(song, savedPosition(song)) - } - - private fun savedPosition(song: Song): Double { - if (song.folderId !in longformFolders()) return 0.0 - val progress = _state.value.longformProgress[song.id] ?: return 0.0 - return if (progress.completed) 0.0 else progress.positionSeconds.toDouble().coerceAtLeast(0.0) - } - fun moveInQueue(fromIndex: Int, toIndex: Int) { _state.update { state -> if (fromIndex !in state.queue.indices || toIndex !in state.queue.indices || fromIndex == toIndex) { @@ -813,7 +803,6 @@ class AppStore( val wasPlaying = _state.value.playing player.pause() pollJob?.cancel() - reportCurrentProgress(completed = false) persistPlayback() _state.update { it.copy( @@ -826,66 +815,6 @@ class AppStore( } } - fun refreshRecommendations() { - val moodId = _state.value.selectedMood?.mood?.id ?: return - if (_state.value.discovering) return - scope.launch { - _state.update { it.copy(discovering = true) } - try { - val detail = api.refreshRecommendations(moodId) - val fresh = detail.recommendations.count { it.state == "new" } - applyMoodDetail(detail) - _state.update { - it.copy( - discovering = false, - message = if (fresh > 0) "$fresh recommendations" else "No new recommendations", - messageIsError = false, - messageId = it.messageId + 1, - ) - } - } catch (t: Throwable) { - _state.update { it.copy(discovering = false) } - message(t) - } - } - } - - fun acceptRecommendation(videoId: String) = decideRecommendation(videoId, accept = true) - - fun rejectRecommendation(videoId: String) = decideRecommendation(videoId, accept = false) - - private fun decideRecommendation(videoId: String, accept: Boolean) { - val moodId = _state.value.selectedMood?.mood?.id ?: return - if (_state.value.discovering) return - scope.launch { - _state.update { it.copy(discovering = true) } - try { - val decision = if (accept) { - api.acceptRecommendation(moodId, videoId) - } else { - api.rejectRecommendation(moodId, videoId) - } - applyMoodDetail(decision.detail) - val message = when { - !accept -> "Recommendation rejected" - decision.seedAdded -> "Added to ${decision.detail.mood.name}" - else -> "Queued for download" - } - _state.update { - it.copy( - discovering = false, - message = message, - messageIsError = false, - messageId = it.messageId + 1, - ) - } - } catch (t: Throwable) { - _state.update { it.copy(discovering = false) } - message(t) - } - } - } - fun togglePlayPause() { val state = _state.value val song = state.current ?: return @@ -893,7 +822,6 @@ class AppStore( player.pause() pollJob?.cancel() _state.update { it.copy(playing = false) } - reportCurrentProgress(completed = false) persistPlayback() } else if (!playbackStarted || player.isFinished()) { val finished = player.isFinished() @@ -944,20 +872,18 @@ class AppStore( return } - val targetStart = savedPosition(target) - reportCurrentProgress(completed = false) _state.update { it.copy( history = it.history.dropLast(1), queue = listOf(song) + it.queue, current = target, playing = true, - positionSeconds = targetStart, + positionSeconds = 0.0, durationSeconds = target.duration.toDouble(), ) } persistPlayback() - startSong(target, targetStart) + startSong(target) report("started", target.id, 0) } @@ -971,8 +897,6 @@ class AppStore( _state.update { it.copy(playing = true, positionSeconds = 0.0) } startSong(song) } - // Persist the restarted position for long-form right away. - reportCurrentProgress(completed = false) } fun seekTo(seconds: Double) { @@ -981,7 +905,6 @@ class AppStore( try { player.seekTo(target) _state.update { it.copy(positionSeconds = target) } - reportCurrentProgress(completed = false) persistPlayback() } catch (t: Throwable) { message(t) @@ -994,10 +917,9 @@ class AppStore( val session = state.session scope.launch { try { - val response = if (targetMoodId != null) { - api.addSeed(targetMoodId, song.id) - } else if (session != null) { - api.addToMood(session.id, song.id, null) + val target = targetMoodId ?: session?.moodId + val updatedMood = if (target != null) { + api.addSong(target, songId = song.id).detail.mood } else { _state.update { it.copy( @@ -1009,30 +931,19 @@ class AppStore( return@launch } - val updatedMoods = state.moods.map { mood -> - if (mood.id == response.mood.id) response.mood else mood - } _state.update { - val selected = it.selectedMood?.let { detail -> - if (detail.mood.id == response.mood.id) { - detail.copy(mood = response.mood) - } else { - detail - } - } it.copy( - moods = updatedMoods, - selectedMood = selected, - message = if (response.added) { - "Added to ${response.mood.name}" - } else { - "Already in ${response.mood.name}" + moods = it.moods.map { mood -> + if (mood.id == updatedMood.id) updatedMood else mood }, + message = "Added to ${updatedMood.name}", messageIsError = false, messageId = it.messageId + 1, ) } - _state.value.selectedMood?.let { cacheDetail(it) } + runCatching { api.mood(updatedMood.id) } + .getOrNull() + ?.let(::applyMoodDetail) } catch (t: Throwable) { message(t) } @@ -1064,7 +975,7 @@ class AppStore( storage.saveDownloadStream(song.id, channel) } if (path != null) { - runCatching { api.cover(song.albumId, 320) } + runCatching { api.cover(song.id, 320) } .getOrNull() ?.takeIf { it.isNotEmpty() } ?.let { artwork -> runCatching { storage.saveArtwork(song.id, artwork) } } @@ -1123,20 +1034,7 @@ class AppStore( } } - fun scanLibrary() { - scope.launch { - try { - api.startScan() - _state.update { - it.copy(message = "Library scan started", messageIsError = false, messageId = it.messageId + 1) - } - } catch (t: Throwable) { - message(t) - } - } - } - - suspend fun cover(albumId: String): ByteArray? = api.cover(albumId, 320) + suspend fun cover(songId: String): ByteArray? = api.cover(songId, 320) /** YT thumbnails and other remote artwork, cached inside the API client. */ suspend fun image(url: String?): ByteArray? = url?.let { api.image(it) } @@ -1159,8 +1057,7 @@ class AppStore( refreshJob?.cancel() sleepJob?.cancel() reconnectJob?.cancel() - musicSearchJob?.cancel() - longformSearchJob?.cancel() + searchJob?.cancel() player.release() api.close() } @@ -1179,6 +1076,7 @@ class AppStore( scope.launch { try { val more = api.nextTracks(sessionId, 12) + mergeSongs(more) if (_state.value.session?.id == sessionId) { _state.update { it.copy(queue = it.queue + more) } } @@ -1194,9 +1092,6 @@ class AppStore( } val song = state.queue.first() - // On natural completion the poll already saved completed=true for the - // outgoing track; do not immediately overwrite it with false. - if (!finishing) reportCurrentProgress(completed = false) _state.update { it.copy( queue = it.queue.drop(1), @@ -1221,6 +1116,7 @@ class AppStore( scope.launch { try { val more = api.nextTracks(sessionId, 12) + mergeSongs(more) if (_state.value.session?.id == sessionId) { _state.update { it.copy(queue = it.queue + more) } } @@ -1242,7 +1138,7 @@ class AppStore( source = localPath ?: api.streamUrl(song.id), song = song, local = localPath != null, - artworkUri = api.coverUrl(song.albumId), + artworkUri = api.coverUrl(song.id), artworkBytes = storage.artworkBytes(song.id), ) if (startAtSeconds > 0 && player.canSeek) { @@ -1281,15 +1177,12 @@ class AppStore( pollTicks += 1 if (pollTicks >= PROGRESS_POLL_TICKS) { pollTicks = 0 - // Pause/seek/track changes report explicitly; avoid - // rewriting the same position every few seconds while paused. - if (player.isPlaying()) reportCurrentProgress(completed = false) + persistPlayback() } if (player.isFinished()) { if (!finishing) { finishing = true - reportCurrentProgress(completed = true) report("completed", state.current?.id, state.positionSeconds.toInt()) playNext() } @@ -1318,7 +1211,6 @@ class AppStore( } private fun stopPlayback() { - reportCurrentProgress(completed = false) pollJob?.cancel() sleepJob?.cancel() sleepJob = null @@ -1343,7 +1235,14 @@ class AppStore( runCatching { val cached = cache.load() val details = cached.moodDetails.filterNot { it.mood.id == detail.mood.id } + detail - cache.save(cached.copy(moodDetails = details, moods = cached.moods)) + cache.save(cached.copy(moodDetails = details)) + } + } + + private fun cacheDetailRemoval(moodId: String) { + runCatching { + val cached = cache.load() + cache.save(cached.copy(moodDetails = cached.moodDetails.filterNot { it.mood.id == moodId })) } } @@ -1357,26 +1256,32 @@ class AppStore( state.selectedMood }, moods = state.moods.map { mood -> if (mood.id == detail.mood.id) detail.mood else mood }, + knownSongs = state.knownSongs + detail.songMap(), ) } } + private fun mergeSongs(songs: Collection<Song>) { + if (songs.isEmpty()) return + _state.update { it.copy(knownSongs = it.knownSongs + songs.associateBy { song -> song.id }) } + } + private fun persistPlayback() { val state = _state.value runCatching { cache.savePlayback( - PlaybackSnapshot( - session = state.session, - queue = state.queue, - current = state.current, - history = state.history, - positionSeconds = state.positionSeconds, - ), - ) + PlaybackSnapshot( + session = state.session, + queue = state.queue, + current = state.current, + history = state.history, + positionSeconds = state.positionSeconds, + ), + ) } } - /** Retries the library sync with exponential backoff while offline. */ + /** Retries the mood sync with exponential backoff while offline. */ private fun scheduleReconnect() { if (reconnectJob?.isActive == true) return reconnectJob = scope.launch { @@ -1394,42 +1299,6 @@ class AppStore( private fun pushHistory(history: List<Song>, current: Song?): List<Song> = if (current == null) history else (history + current).takeLast(MAX_HISTORY) - private fun longformFolders(): Set<Int> = - _state.value.user?.longformFolders?.toSet().orEmpty() - - private fun reportCurrentProgress(completed: Boolean) { - if (loggingOut) return - val state = _state.value - val song = state.current ?: return - if (song.folderId !in longformFolders()) return - val duration = if (state.durationSeconds > 0) state.durationSeconds else song.duration.toDouble() - reportLongformProgress(song.id, state.positionSeconds, duration, completed) - } - - private fun reportLongformProgress( - songId: String, - positionSeconds: Double, - durationSeconds: Double, - completed: Boolean, - ) { - val position = positionSeconds.toInt().coerceAtLeast(0) - val duration = durationSeconds.toInt().coerceAtLeast(0) - val entry = LongformProgress( - songId = songId, - positionSeconds = position, - durationSeconds = duration, - completed = completed, - updatedAt = Clock.System.now().toString(), - ) - _state.update { it.copy(longformProgress = it.longformProgress + (songId to entry)) } - cache.saveProgress(_state.value.longformProgress.values.toList()) - scope.launch { - progressSaveMutex.withLock { - runCatching { api.saveLongformProgress(songId, position, duration, completed) } - } - } - } - private fun message(t: Throwable) { _state.update { it.copy( @@ -1446,8 +1315,16 @@ private fun Throwable.friendlyMessage(): String = when (this) { else -> message ?: "Something went wrong" } -private fun Collection<Song>.sortedLibrary(): List<Song> = - sortedWith(compareBy({ it.artist.lowercase() }, { it.album.lowercase() }, { it.trackNumber ?: 0 })) +private fun MoodDetail.songMap(): Map<String, Song> = songs.associate { it.song.id to it.song } + +private fun List<MoodDetail>.songMap(playback: PlaybackSnapshot?): Map<String, Song> { + val result = mutableMapOf<String, Song>() + forEach { detail -> result.putAll(detail.songMap()) } + playback?.current?.let { result[it.id] = it } + playback?.queue?.forEach { result[it.id] = it } + playback?.history?.forEach { result[it.id] = it } + return result +} private const val RECONNECT_INITIAL_MS = 15_000L private const val RECONNECT_MAX_MS = 300_000L @@ -1455,11 +1332,3 @@ private const val DOWNLOAD_ATTEMPTS = 3 private const val PROGRESS_POLL_TICKS = 12 private const val MAX_HISTORY = 50 private const val SEARCH_DEBOUNCE_MS = 300L - -private fun LongformProgressItem.toProgress(): LongformProgress = LongformProgress( - songId = song.id, - positionSeconds = positionSeconds, - durationSeconds = durationSeconds, - completed = completed, - updatedAt = updatedAt, -) diff --git a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/App.kt b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/App.kt index df7e018..1db0581 100644 --- a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/App.kt +++ b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/App.kt @@ -1,18 +1,17 @@ package win.taptap.musicmanager.client.ui import androidx.compose.foundation.background -import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size -import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.ArrowBack import androidx.compose.material.icons.rounded.Delete -import androidx.compose.material.icons.rounded.LibraryMusic +import androidx.compose.material.icons.rounded.DownloadDone import androidx.compose.material.icons.rounded.Refresh +import androidx.compose.material.icons.rounded.Search import androidx.compose.material.icons.rounded.Settings import androidx.compose.material3.AlertDialog import androidx.compose.material3.CircularProgressIndicator @@ -138,7 +137,8 @@ private fun MainScreen(state: AppState, store: AppStore) { val title = when (state.screen) { Screen.Moods -> "Moods" Screen.MoodDetail -> state.selectedMood?.mood?.name ?: "Mood" - Screen.Library -> "Library & downloads" + Screen.Search -> "Add music" + Screen.Downloads -> "Downloads" Screen.Settings -> "Settings" } Text(title, fontWeight = FontWeight.SemiBold) @@ -157,8 +157,11 @@ private fun MainScreen(state: AppState, store: AppStore) { IconButton(onClick = { store.refreshAll() }) { Icon(Icons.Rounded.Refresh, contentDescription = "Refresh") } - IconButton(onClick = { store.openLibrary() }) { - Icon(Icons.Rounded.LibraryMusic, contentDescription = "Library") + IconButton(onClick = { store.openSearch() }) { + Icon(Icons.Rounded.Search, contentDescription = "Add music") + } + IconButton(onClick = { store.openDownloads() }) { + Icon(Icons.Rounded.DownloadDone, contentDescription = "Downloads") } IconButton(onClick = { store.openSettings() }) { Icon(Icons.Rounded.Settings, contentDescription = "Settings") @@ -169,7 +172,8 @@ private fun MainScreen(state: AppState, store: AppStore) { Icon(Icons.Rounded.Delete, contentDescription = "Delete mood") } } - Screen.Library -> { + Screen.Search -> Unit + Screen.Downloads -> { IconButton(onClick = { store.openSettings() }) { Icon(Icons.Rounded.Settings, contentDescription = "Settings") } @@ -189,7 +193,8 @@ private fun MainScreen(state: AppState, store: AppStore) { when (state.screen) { Screen.Moods -> MoodsScreen(state, store) Screen.MoodDetail -> MoodDetailScreen(state, store) - Screen.Library -> LibraryScreen(state, store) + Screen.Search -> SearchScreen(state, store) + Screen.Downloads -> DownloadsScreen(state, store) Screen.Settings -> SettingsScreen(state, store) } } @@ -200,7 +205,12 @@ private fun MainScreen(state: AppState, store: AppStore) { AlertDialog( onDismissRequest = { confirmDelete = false }, title = { Text("Delete mood?") }, - text = { Text("\"$name\" and its seeds will be removed. Downloads stay on this device.") }, + text = { + Text( + "\"$name\" and its recommendation history will be removed. " + + "Unused downloads are deleted from the server.", + ) + }, confirmButton = { TextButton( onClick = { diff --git a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/Components.kt b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/Components.kt index fa0f8e4..54fa936 100644 --- a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/Components.kt +++ b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/Components.kt @@ -50,15 +50,15 @@ import win.taptap.musicmanager.client.store.AppStore @Composable fun Cover( store: AppStore, - albumId: String?, + songId: String?, modifier: Modifier = Modifier, size: Int = 320, ) { - var bitmap by remember(albumId, size) { mutableStateOf<ImageBitmap?>(null) } + var bitmap by remember(songId, size) { mutableStateOf<ImageBitmap?>(null) } - LaunchedEffect(albumId, size) { - if (albumId == null) return@LaunchedEffect - val bytes = store.cover(albumId) + LaunchedEffect(songId, size) { + if (songId == null) return@LaunchedEffect + val bytes = store.cover(songId) bitmap = bytes?.let { data -> runCatching { decodeImage(data) }.getOrNull() } } @@ -185,7 +185,7 @@ fun SongRow( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), ) { - Cover(store, song.albumId, Modifier.size(44.dp), size = 96) + Cover(store, song.id, Modifier.size(44.dp), size = 96) Column(Modifier.weight(1f)) { Text( song.title, @@ -194,7 +194,7 @@ fun SongRow( overflow = TextOverflow.Ellipsis, ) Text( - "${song.artist} · ${song.album}", + "${song.artist} · ${song.album ?: "Single"}", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, @@ -277,7 +277,7 @@ fun MoodPickerDialog( Column(Modifier.weight(1f)) { Text(mood.name, style = MaterialTheme.typography.bodyLarge) Text( - if (mood.id == currentMoodId) "Current mood" else "${mood.seedCount} seeds", + if (mood.id == currentMoodId) "Current mood" else "${mood.songCount} songs", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) diff --git a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/DownloadsScreen.kt b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/DownloadsScreen.kt new file mode 100644 index 0000000..58a9cfb --- /dev/null +++ b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/DownloadsScreen.kt @@ -0,0 +1,129 @@ +package win.taptap.musicmanager.client.ui + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.Delete +import androidx.compose.material.icons.rounded.DeleteSweep +import androidx.compose.material.icons.rounded.DownloadDone +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import win.taptap.musicmanager.client.store.AppState +import win.taptap.musicmanager.client.store.AppStore + +/** Device-side copies for offline playback. The server keeps the originals. */ +@Composable +fun DownloadsScreen(state: AppState, store: AppStore) { + if (state.downloads.isEmpty()) { + EmptyState( + "No downloads", + "Download a song from a mood to play it without the server.", + Modifier.fillMaxSize(), + ) + return + } + + val songs = state.downloads.mapNotNull { state.knownSongs[it] } + val unknown = state.downloads - songs.map { it.id }.toSet() + + LazyColumn( + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues(20.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + item { + Surface( + shape = RoundedCornerShape(16.dp), + color = MaterialTheme.colorScheme.surfaceVariant, + modifier = Modifier.fillMaxWidth(), + ) { + Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Text( + "${state.downloads.size} downloaded", + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.SemiBold, + ) + Text( + "${formatBytes(store.storageBytes())} used on this device", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + OutlinedButton(onClick = { store.clearDownloads() }) { + Icon(Icons.Rounded.DeleteSweep, contentDescription = null) + Spacer(Modifier.width(6.dp)) + Text("Clear all") + } + } + } + } + + items(songs, key = { it.id }) { song -> + SongRow(store, song, onPlay = { store.playSong(song) }) { + Icon( + Icons.Rounded.DownloadDone, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(18.dp), + ) + IconButton(onClick = { store.toggleDownload(song) }) { + Icon(Icons.Rounded.Delete, contentDescription = "Delete download") + } + } + } + + items(unknown.toList(), key = { "unknown-$it" }) { id -> + Row( + modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Column(Modifier.weight(1f)) { + Text("Downloaded track", style = MaterialTheme.typography.bodyLarge) + Text( + id, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + IconButton( + onClick = { + store.toggleDownload( + win.taptap.musicmanager.client.api.Song( + id = id, + videoId = id, + title = id, + artist = "", + duration = 0, + ), + ) + }, + ) { + Icon(Icons.Rounded.Delete, contentDescription = "Delete download") + } + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/LibraryScreen.kt b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/LibraryScreen.kt deleted file mode 100644 index c410773..0000000 --- a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/LibraryScreen.kt +++ /dev/null @@ -1,496 +0,0 @@ -package win.taptap.musicmanager.client.ui - -import androidx.compose.foundation.background -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.PaddingValues -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.heightIn -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.rounded.CheckCircle -import androidx.compose.material.icons.rounded.DeleteOutline -import androidx.compose.material.icons.rounded.Download -import androidx.compose.material.icons.rounded.List -import androidx.compose.material.icons.rounded.PlayArrow -import androidx.compose.material.icons.rounded.Search -import androidx.compose.material.icons.rounded.Shuffle -import androidx.compose.material3.Button -import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.Surface -import androidx.compose.material3.Tab -import androidx.compose.material3.TabRow -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import androidx.compose.ui.window.Dialog -import win.taptap.musicmanager.client.api.LongformProgress -import win.taptap.musicmanager.client.api.Song -import win.taptap.musicmanager.client.platformName -import win.taptap.musicmanager.client.store.AppState -import win.taptap.musicmanager.client.store.AppStore - -@Composable -fun LibraryScreen(state: AppState, store: AppStore) { - var tab by remember { mutableStateOf(0) } - - Column(Modifier.fillMaxSize()) { - TabRow(selectedTabIndex = tab) { - Tab( - selected = tab == 0, - onClick = { tab = 0 }, - text = { Text("Music") }, - ) - Tab( - selected = tab == 1, - onClick = { tab = 1 }, - text = { Text("Longform") }, - ) - } - when (tab) { - 0 -> MusicLibrary(state, store) - else -> LongformLibrary(state, store) - } - } -} - -@Composable -private fun MusicLibrary(state: AppState, store: AppStore) { - var query by remember { mutableStateOf("") } - val supported = platformName != "web" - val downloadedSongs = state.library.filter { it.id in state.downloads } - - LazyColumn( - modifier = Modifier.fillMaxSize(), - contentPadding = PaddingValues(20.dp), - verticalArrangement = Arrangement.spacedBy(6.dp), - ) { - item { - OutlinedTextField( - value = query, - onValueChange = { - query = it - store.searchMusic(it) - }, - singleLine = true, - label = { Text("Search music") }, - leadingIcon = { Icon(Icons.Rounded.Search, contentDescription = null) }, - trailingIcon = { - if (state.searching) { - CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp) - } - }, - modifier = Modifier.fillMaxWidth(), - ) - } - - item { - Surface( - shape = RoundedCornerShape(18.dp), - color = MaterialTheme.colorScheme.surfaceVariant, - modifier = Modifier.fillMaxWidth(), - ) { - Row( - modifier = Modifier.padding(16.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - Column(Modifier.weight(1f)) { - Text("All music", style = MaterialTheme.typography.titleMedium) - Text( - if (state.library.isEmpty()) { - "Nothing in the library yet" - } else { - "${state.library.size} tracks, shuffled into a queue" - }, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - Button( - onClick = { store.playAll() }, - enabled = state.library.isNotEmpty(), - ) { - Icon(Icons.Rounded.Shuffle, contentDescription = null, modifier = Modifier.size(18.dp)) - Spacer(Modifier.width(6.dp)) - Text("Shuffle all") - } - } - } - } - - if (state.musicResults.isNotEmpty()) { - item { - SectionTitle("Search results") { - Text( - "${state.musicResults.size}", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - items(state.musicResults, key = { "search-${it.id}" }) { song -> - LibrarySongRow(song, state, store, supported) - } - item { HorizontalDivider(Modifier.padding(vertical = 14.dp)) } - } - - item { - SectionTitle("Downloads") { - Text( - "${state.downloads.size} tracks · ${formatBytes(store.storageBytes())}", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - - if (!supported) { - item { - Text( - "The browser plays from the server and lets the browser manage its cache. Install the Android or desktop app for offline downloads.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } else if (downloadedSongs.isEmpty()) { - item { - Text( - "No downloads yet. Search for a song and press the download icon.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } else { - items(downloadedSongs, key = { "download-${it.id}" }) { song -> - LibrarySongRow(song, state, store, supported) - } - item { - Text( - "Offline playback uses these files when the server is unreachable.", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(top = 8.dp), - ) - } - } - } -} - -@Composable -private fun LongformLibrary(state: AppState, store: AppStore) { - var query by remember { mutableStateOf("") } - var artistDialog by remember { mutableStateOf<String?>(null) } - val supported = platformName != "web" - - val byArtist = state.longform.groupBy { it.artist } - val artistNames = byArtist.keys.sortedBy { it.lowercase() } - val continueListening = state.longformProgress.values - .asSequence() - .filterNot { it.completed } - .sortedByDescending { it.updatedAt } - .mapNotNull { progress -> - state.longform.firstOrNull { it.id == progress.songId }?.let { it to progress } - } - .take(5) - .toList() - - LazyColumn( - modifier = Modifier.fillMaxSize(), - contentPadding = PaddingValues(20.dp), - verticalArrangement = Arrangement.spacedBy(6.dp), - ) { - item { - OutlinedTextField( - value = query, - onValueChange = { - query = it - store.searchLongform(it) - }, - singleLine = true, - label = { Text("Search audiobooks and podcasts") }, - leadingIcon = { Icon(Icons.Rounded.Search, contentDescription = null) }, - trailingIcon = { - if (state.searching) { - CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp) - } - }, - modifier = Modifier.fillMaxWidth(), - ) - } - - if (state.longformResults.isNotEmpty()) { - item { SectionTitle("Search results") } - items(state.longformResults, key = { "lf-search-${it.id}" }) { song -> - LongformSongRow(song, state, store, supported) { store.playLongformSong(song) } - } - item { HorizontalDivider(Modifier.padding(vertical = 14.dp)) } - } - - if (continueListening.isNotEmpty()) { - item { SectionTitle("Continue listening") } - items(continueListening, key = { "continue-${it.first.id}" }) { (song, progress) -> - ContinueRow(song, progress, store) - } - item { HorizontalDivider(Modifier.padding(vertical = 14.dp)) } - } - - item { - SectionTitle("Artists") { - Text( - "${artistNames.size}", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - - if (artistNames.isEmpty()) { - item { - EmptyState( - "No long-form content", - "Add audiobooks or podcasts to a folder of type longform in library.yaml.", - ) - } - } else { - items(artistNames, key = { "artist-$it" }) { artist -> - val songs = byArtist[artist].orEmpty() - ArtistRow( - name = artist, - count = songs.size, - onShuffle = { store.playLongformArtist(artist) }, - onOpen = { artistDialog = artist }, - ) - } - } - } - - artistDialog?.let { artist -> - LongformArtistDialog( - artist = artist, - songs = byArtist[artist].orEmpty(), - state = state, - store = store, - supported = supported, - onDismiss = { artistDialog = null }, - ) - } -} - -@Composable -private fun ContinueRow(song: Song, progress: LongformProgress, store: AppStore) { - val duration = progress.durationSeconds.takeIf { it > 0 } ?: song.duration - val fraction = if (duration > 0) { - (progress.positionSeconds.toFloat() / duration).coerceIn(0f, 1f) - } else { - 0f - } - - Row( - modifier = Modifier - .fillMaxWidth() - .clickable { store.resumeLongform(song.id) } - .padding(vertical = 8.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - Cover(store, song.albumId, Modifier.size(44.dp), size = 96) - Column(Modifier.weight(1f)) { - Text(song.title, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis) - Text( - song.artist, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - Box( - Modifier - .fillMaxWidth() - .padding(top = 4.dp) - .height(3.dp) - .clip(RoundedCornerShape(2.dp)) - .background(MaterialTheme.colorScheme.surfaceVariant), - ) { - Box( - Modifier - .fillMaxWidth(fraction) - .height(3.dp) - .background(MaterialTheme.colorScheme.primary), - ) - } - Text( - "${formatDuration(progress.positionSeconds)} / ${formatDuration(duration)}", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - IconButton(onClick = { store.resumeLongform(song.id) }) { - Icon(Icons.Rounded.PlayArrow, contentDescription = "Resume") - } - } -} - -@Composable -private fun ArtistRow( - name: String, - count: Int, - onShuffle: () -> Unit, - onOpen: () -> Unit, -) { - Row( - modifier = Modifier.fillMaxWidth().clickable(onClick = onOpen).padding(vertical = 8.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - Column(Modifier.weight(1f)) { - Text(name, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis) - Text( - "$count tracks", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - IconButton(onClick = onShuffle) { - Icon(Icons.Rounded.Shuffle, contentDescription = "Play $name shuffled") - } - IconButton(onClick = onOpen) { - Icon(Icons.Rounded.List, contentDescription = "Show tracks") - } - } -} - -@Composable -private fun LongformArtistDialog( - artist: String, - songs: List<Song>, - state: AppState, - store: AppStore, - supported: Boolean, - onDismiss: () -> Unit, -) { - Dialog(onDismissRequest = onDismiss) { - Surface( - shape = RoundedCornerShape(18.dp), - color = MaterialTheme.colorScheme.surface, - tonalElevation = 6.dp, - modifier = Modifier.fillMaxWidth().heightIn(max = 600.dp), - ) { - Column { - Row( - modifier = Modifier.padding(20.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Column(Modifier.weight(1f)) { - Text(artist, style = MaterialTheme.typography.titleMedium, maxLines = 1, overflow = TextOverflow.Ellipsis) - Text( - "${songs.size} tracks · read-only playlist", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - TextButton(onClick = onDismiss) { Text("Close") } - } - Row(modifier = Modifier.padding(horizontal = 20.dp)) { - Button( - onClick = { - store.playLongformArtist(artist) - onDismiss() - }, - enabled = songs.isNotEmpty(), - ) { - Icon(Icons.Rounded.Shuffle, contentDescription = null, modifier = Modifier.size(18.dp)) - Spacer(Modifier.width(6.dp)) - Text("Shuffle artist") - } - } - HorizontalDivider(Modifier.padding(vertical = 12.dp)) - LazyColumn(Modifier.fillMaxWidth().heightIn(max = 460.dp)) { - items(songs, key = { "artist-song-${it.id}" }) { song -> - LongformSongRow(song, state, store, supported) { - store.playLongformSong(song) - onDismiss() - } - } - } - } - } - } -} - -@Composable -private fun LongformSongRow( - song: Song, - state: AppState, - store: AppStore, - supported: Boolean, - onPlay: () -> Unit, -) { - SongRow(store = store, song = song, onPlay = onPlay) { - DownloadAction(song, state, store, supported) - IconButton(onClick = onPlay) { - Icon(Icons.Rounded.PlayArrow, contentDescription = "Play") - } - } -} - -@Composable -private fun LibrarySongRow(song: Song, state: AppState, store: AppStore, supported: Boolean) { - SongRow(store = store, song = song, onPlay = { store.playSong(song) }) { - DownloadAction(song, state, store, supported) - if (song.id in state.downloads) { - Icon( - Icons.Rounded.CheckCircle, - contentDescription = "Downloaded", - tint = MaterialTheme.colorScheme.secondary, - modifier = Modifier.size(18.dp), - ) - } - IconButton(onClick = { store.playSong(song) }) { - Icon(Icons.Rounded.PlayArrow, contentDescription = "Play") - } - } -} - -@Composable -private fun DownloadAction(song: Song, state: AppState, store: AppStore, supported: Boolean) { - if (!supported) return - when { - song.id in state.downloading -> CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp) - song.id in state.downloads -> { - IconButton(onClick = { store.toggleDownload(song) }) { - Icon(Icons.Rounded.DeleteOutline, contentDescription = "Delete download") - } - } - else -> { - IconButton(onClick = { store.toggleDownload(song) }) { - Icon(Icons.Rounded.Download, contentDescription = "Download") - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/MoodDetailScreen.kt b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/MoodDetailScreen.kt index cf2709d..5fda7a0 100644 --- a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/MoodDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/MoodDetailScreen.kt @@ -15,11 +15,13 @@ import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Add -import androidx.compose.material.icons.rounded.Check import androidx.compose.material.icons.rounded.Close +import androidx.compose.material.icons.rounded.Download +import androidx.compose.material.icons.rounded.DownloadDone import androidx.compose.material.icons.rounded.PlayArrow import androidx.compose.material.icons.rounded.Refresh import androidx.compose.material.icons.rounded.RemoveCircleOutline +import androidx.compose.material.icons.rounded.Search import androidx.compose.material3.Button import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.FilledTonalButton @@ -27,11 +29,9 @@ import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Slider import androidx.compose.material3.Surface -import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable @@ -46,8 +46,8 @@ import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import kotlin.math.roundToInt +import win.taptap.musicmanager.client.api.MoodSong import win.taptap.musicmanager.client.api.Recommendation -import win.taptap.musicmanager.client.api.Song import win.taptap.musicmanager.client.store.AppState import win.taptap.musicmanager.client.store.AppStore @@ -56,7 +56,11 @@ fun MoodDetailScreen(state: AppState, store: AppStore) { val detail = state.selectedMood if (state.loading && detail == null) { - Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) { + Column( + Modifier.fillMaxSize(), + verticalArrangement = Arrangement.Center, + horizontalAlignment = Alignment.CenterHorizontally, + ) { CircularProgressIndicator() } return @@ -68,31 +72,27 @@ fun MoodDetailScreen(state: AppState, store: AppStore) { } val mood = detail.mood - var seedQuery by remember { mutableStateOf("") } var name by remember(mood.id) { mutableStateOf(mood.name) } var description by remember(mood.id) { mutableStateOf(mood.description.orEmpty()) } var genres by remember(mood.id) { mutableStateOf(mood.genres.joinToString(", ")) } var query by remember(mood.id) { mutableStateOf(mood.query.orEmpty()) } - var target by remember(mood.id) { mutableStateOf(mood.targetSize.toString()) } + var collectionPercent by remember(mood.id) { mutableStateOf(mood.collectionPercent.toFloat()) } + var recommendations by remember(mood.id) { mutableStateOf(mood.recommendationCount.toFloat()) } var hours by remember(mood.id) { mutableStateOf(mood.refreshHours.toString()) } - var 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) { + val inFlight = mood.recommendationDownloading + + detail.recommendations.count { + it.download?.state == "queued" || it.download?.state == "downloading" + } + LaunchedEffect(mood.id, inFlight) { var polls = 0 - while (pendingDownloads > 0 && polls < 60) { - kotlinx.coroutines.delay(10_000) + while (inFlight > 0 && polls < 60) { + kotlinx.coroutines.delay(5_000) store.refreshSelectedMood() polls += 1 } } - val seedIds = detail.seeds.map { it.song.id }.toSet() - val searchResults = state.searchResults.filterNot { it.id in seedIds } - LazyColumn( modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(20.dp), @@ -106,17 +106,18 @@ fun MoodDetailScreen(state: AppState, store: AppStore) { ) { Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) { Text( - mood.description ?: "Server-driven radio", + mood.description ?: "Your private mix", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, ) - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { - Text("${mood.seedCount} seeds", style = MaterialTheme.typography.labelMedium) - Text("·", color = MaterialTheme.colorScheme.onSurfaceVariant) - Text("${mood.targetSize} batch", style = MaterialTheme.typography.labelMedium) + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + Text("${mood.songCount} songs", style = MaterialTheme.typography.labelMedium) Text("·", color = MaterialTheme.colorScheme.onSurfaceVariant) Text( - "${mood.seedPercent}% seeds", + "${mood.collectionPercent}% collection", style = MaterialTheme.typography.labelMedium, ) Spacer(Modifier.weight(1f)) @@ -127,77 +128,49 @@ fun MoodDetailScreen(state: AppState, store: AppStore) { } } if (mood.lastError != null) { - Text(mood.lastError, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) + Text( + mood.lastError, + color = MaterialTheme.colorScheme.error, + style = MaterialTheme.typography.bodySmall, + ) } } } } item { - SectionTitle("Seeds") { + SectionTitle("Songs") { Text( - "${detail.seeds.size}", + "${detail.songs.size}", style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, ) } } - if (detail.seeds.isEmpty()) { + if (detail.songs.isEmpty()) { item { Text( - "No seeds yet. Add a few songs below; every seed is always part of the radio.", + "A mood needs at least one song before it can play. Use Add music to search YouTube.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) } } else { - items(detail.seeds, key = { it.song.id }) { seed -> - SongRow( - store = store, - song = seed.song, - onPlay = { store.playSong(seed.song) }, - ) { - Text(seed.origin, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant) - IconButton(onClick = { store.removeSeed(mood.id, seed.song.id) }) { - Icon(Icons.Rounded.RemoveCircleOutline, contentDescription = "Remove seed") - } - } + items(detail.songs, key = { it.song.id }) { entry -> + MoodSongRow(entry, store, mood.id, downloaded = entry.song.id in state.downloads) } } - item { - HorizontalDivider(Modifier.padding(vertical = 12.dp)) - SectionTitle("Add songs") - } - item { Row( - verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth().padding(top = 4.dp), horizontalArrangement = Arrangement.spacedBy(10.dp), - modifier = Modifier.fillMaxWidth(), ) { - OutlinedTextField( - value = seedQuery, - onValueChange = { seedQuery = it }, - singleLine = true, - label = { Text("Search your music") }, - modifier = Modifier.weight(1f), - ) - OutlinedButton(onClick = { store.search(seedQuery) }, enabled = seedQuery.isNotBlank()) { - Text("Search") - } - } - } - - if (state.searching) { - item { CircularProgressIndicator(Modifier.size(22.dp)) } - } - - items(searchResults.take(12), key = { it.id }) { song -> - SongRow(store = store, song = song, onPlay = { store.playSong(song) }) { - IconButton(onClick = { store.addSeed(mood.id, song.id) }) { - Icon(Icons.Rounded.Add, contentDescription = "Add seed") + FilledTonalButton(onClick = { store.openSearch(mood.id) }) { + Icon(Icons.Rounded.Search, contentDescription = null, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(6.dp)) + Text("Add music") } } } @@ -208,50 +181,55 @@ fun MoodDetailScreen(state: AppState, store: AppStore) { SectionTitle("Next batch") } items(state.preview, key = { "preview-${it.id}" }) { song -> - SongRow(store = store, song = song, onPlay = { store.playSong(song) }) { + SongRow(store, song, onPlay = { store.playSong(song) }) { Text(formatDuration(song.duration), style = MaterialTheme.typography.labelSmall) } } } - if (mood.ytEnabled) { - item { - HorizontalDivider(Modifier.padding(vertical = 12.dp)) - 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)) - } - TextButton( - onClick = { store.refreshRecommendations() }, - enabled = !state.discovering, - ) { - Icon(Icons.Rounded.Refresh, contentDescription = null, modifier = Modifier.size(16.dp)) - Spacer(Modifier.width(4.dp)) - Text("Refresh") - } + item { + HorizontalDivider(Modifier.padding(vertical = 12.dp)) + SectionTitle("Recommendations") { + Row(verticalAlignment = Alignment.CenterVertically) { + if (state.discovering) { + CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp) + Spacer(Modifier.width(8.dp)) + } + TextButton( + onClick = { store.refreshRecommendations() }, + enabled = !state.discovering && mood.recommendationCount > 0, + ) { + Icon(Icons.Rounded.Refresh, contentDescription = null, modifier = Modifier.size(16.dp)) + Spacer(Modifier.width(4.dp)) + Text("Refresh") } } } + } - val visible = detail.recommendations.filter { it.state != "rejected" } - if (visible.isEmpty()) { - item { - Text( - if (state.discovering) { - "Searching YouTube Music..." - } else { - "No recommendations yet. Refresh to search for tracks that fit this mood." - }, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } else { - items(visible, key = { "rec-${it.videoId}" }) { recommendation -> - RecommendationRow(recommendation, state.discovering, store) - } + if (mood.recommendationCount == 0) { + item { + Text( + "Recommendations are off for this mood. Raise the count in settings to let the server download picks.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } else if (detail.recommendations.isEmpty()) { + item { + Text( + if (state.discovering) { + "Searching and downloading picks…" + } else { + "No recommendations yet. The server tops this mood up automatically." + }, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } else { + items(detail.recommendations, key = { "rec-${it.videoId}" }) { recommendation -> + RecommendationRow(recommendation, state.discovering, store) } } @@ -286,47 +264,51 @@ fun MoodDetailScreen(state: AppState, store: AppStore) { OutlinedTextField( value = query, onValueChange = { query = it }, - label = { Text("Free-text hint") }, + label = { Text("Discovery hint") }, singleLine = true, modifier = Modifier.fillMaxWidth(), ) - Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { - OutlinedTextField( - value = target, - onValueChange = { target = it }, - label = { Text("Batch size") }, - singleLine = true, - modifier = Modifier.weight(1f), - ) - OutlinedTextField( - value = hours, - onValueChange = { hours = it }, - label = { Text("Refresh h") }, - singleLine = true, - modifier = Modifier.weight(1f), - ) - } Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { Text( - "Seed mix: ${seedPercent.roundToInt()}% seeds · ${100 - seedPercent.roundToInt()}% recommendations", + "Collection share: ${collectionPercent.roundToInt()}% · ${100 - collectionPercent.roundToInt()}% recommendations", style = MaterialTheme.typography.bodySmall, ) Slider( - value = seedPercent, - onValueChange = { seedPercent = it }, + value = collectionPercent, + onValueChange = { collectionPercent = it }, valueRange = 0f..100f, steps = 9, ) Text( - "Each queued track rolls this share independently; if one side runs out, the other fills in.", + "Each queue slot rolls this share; when one pool runs out the other fills in.", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) } - Row(verticalAlignment = Alignment.CenterVertically) { - Text("YT Music discovery", Modifier.weight(1f)) - Switch(checked = yt, onCheckedChange = { yt = it }) + Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text( + "Active recommendations: ${recommendations.roundToInt()}", + style = MaterialTheme.typography.bodySmall, + ) + Slider( + value = recommendations, + onValueChange = { recommendations = it }, + valueRange = 0f..30f, + steps = 29, + ) + Text( + "Downloaded picks that count as active slots (0 turns discovery off).", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) } + OutlinedTextField( + value = hours, + onValueChange = { hours = it }, + label = { Text("Refresh interval (hours)") }, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) FilledTonalButton( enabled = !state.saving && name.isNotBlank(), onClick = { @@ -336,10 +318,9 @@ fun MoodDetailScreen(state: AppState, store: AppStore) { description = description.trim().takeIf { it.isNotEmpty() }, genres = genres.split(',').map { it.trim() }.filter { it.isNotEmpty() }, query = query.trim().takeIf { it.isNotEmpty() }, - targetSize = target.toIntOrNull() ?: mood.targetSize, + collectionPercent = collectionPercent.roundToInt(), + recommendationCount = recommendations.roundToInt(), refreshHours = hours.toIntOrNull() ?: mood.refreshHours, - ytEnabled = yt, - seedPercent = seedPercent.roundToInt(), ) }, modifier = Modifier.fillMaxWidth(), @@ -353,18 +334,45 @@ fun MoodDetailScreen(state: AppState, store: AppStore) { } } +@Composable +private fun MoodSongRow(entry: MoodSong, store: AppStore, moodId: String, downloaded: Boolean) { + val song = entry.song + SongRow(store, song, onPlay = { store.playSong(song) }) { + IconButton(onClick = { store.toggleDownload(song) }) { + Icon( + if (downloaded) Icons.Rounded.DownloadDone else Icons.Rounded.Download, + contentDescription = if (downloaded) "Delete download" else "Download for offline", + tint = if (downloaded) { + MaterialTheme.colorScheme.primary + } else { + MaterialTheme.colorScheme.onSurfaceVariant + }, + ) + } + IconButton(onClick = { store.removeSong(moodId, song.id) }) { + Icon(Icons.Rounded.RemoveCircleOutline, contentDescription = "Remove from mood") + } + } +} + @Composable private fun RecommendationRow( recommendation: Recommendation, busy: Boolean, store: AppStore, ) { + val failed = recommendation.state == "failed" || + recommendation.download?.state == "failed" Row( modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), ) { - RemoteImage(store, recommendation.thumbnail, Modifier.size(48.dp)) + if (recommendation.song != null) { + Cover(store, recommendation.song.id, Modifier.size(48.dp), size = 96) + } else { + RemoteImage(store, recommendation.thumbnail, Modifier.size(48.dp)) + } Column(Modifier.weight(1f)) { Text( recommendation.title, @@ -375,35 +383,29 @@ private fun RecommendationRow( Text( buildString { append(recommendation.artist) - recommendation.album?.takeIf { it.isNotBlank() }?.let { append(" · ").append(it) } + recommendation.duration?.let { append(" · ").append(formatDuration(it)) } }, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, ) - val download = recommendation.download Text( when { - recommendation.state == "accepted" && recommendation.matchedSong != null -> "Seed added" - download?.state == "downloading" -> "Downloading..." - download?.state == "failed" -> "Download failed — tap ✓ to retry" - download?.state == "queued" -> "Download queued" - recommendation.state == "accepted" -> "Queued for download" - recommendation.matchedSong != null -> "In your library" - else -> "New" + failed -> "Download failed" + recommendation.state == "ready" -> "Ready to add" + else -> "Downloading…" }, style = MaterialTheme.typography.labelSmall, - color = when { - download?.state == "failed" -> MaterialTheme.colorScheme.error - recommendation.state == "accepted" || download != null -> - MaterialTheme.colorScheme.primary - else -> MaterialTheme.colorScheme.onSurfaceVariant + color = if (failed) { + MaterialTheme.colorScheme.error + } else { + MaterialTheme.colorScheme.primary }, ) - if (download?.state == "failed" && download.error != null) { + if (failed && recommendation.error != null) { Text( - download.error, + recommendation.error, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.error, maxLines = 2, @@ -411,26 +413,26 @@ private fun RecommendationRow( ) } } - if (recommendation.state == "accepted" && recommendation.download?.state != "failed") { - Icon( - Icons.Rounded.Check, - contentDescription = "Accepted", - tint = MaterialTheme.colorScheme.primary, - modifier = Modifier.size(20.dp), - ) + if (failed) { + IconButton( + onClick = { store.retryRecommendation(recommendation.videoId) }, + enabled = !busy, + ) { + Icon(Icons.Rounded.Refresh, contentDescription = "Retry download") + } } else { IconButton( - onClick = { store.acceptRecommendation(recommendation.videoId) }, + onClick = { store.addRecommendation(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") + Icon(Icons.Rounded.Add, contentDescription = "Add to mood") } } + IconButton( + onClick = { store.rejectRecommendation(recommendation.videoId) }, + enabled = !busy, + ) { + Icon(Icons.Rounded.Close, contentDescription = "Not interested") + } } } diff --git a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/MoodsScreen.kt b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/MoodsScreen.kt index fcb2c54..2438269 100644 --- a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/MoodsScreen.kt +++ b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/MoodsScreen.kt @@ -32,7 +32,6 @@ import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Slider -import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable @@ -68,7 +67,7 @@ fun MoodsScreen(state: AppState, store: AppStore) { fontWeight = FontWeight.SemiBold, ) Text( - "Radio is generated live and learns from what you finish or skip.", + "Songs are downloaded from YouTube. Recommendations refill automatically.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -90,7 +89,7 @@ fun MoodsScreen(state: AppState, store: AppStore) { if (state.moods.isEmpty()) { EmptyState( title = "No moods yet", - subtitle = "Create a mood, add a few seed songs, and press play. The server builds the rest.", + subtitle = "Create a mood, add a few songs, and press play. The server builds and downloads the rest.", modifier = Modifier.fillMaxSize(), ) } else { @@ -116,9 +115,9 @@ fun MoodsScreen(state: AppState, store: AppStore) { CreateMoodDialog( saving = state.saving, onDismiss = { creating = false }, - onCreate = { name, description, genres, query, target, hours, yt, seedPercent -> + onCreate = { name, description, genres, query, collectionPercent, recommendations, hours -> creating = false - store.createMood(name, description, genres, query, target, hours, yt, seedPercent) + store.createMood(name, description, genres, query, collectionPercent, recommendations, hours) }, ) } @@ -144,7 +143,7 @@ private fun MoodCard(mood: Mood, onOpen: () -> Unit, onPlay: () -> Unit) { overflow = TextOverflow.Ellipsis, ) Text( - mood.description ?: mood.genres.joinToString(" · ").ifBlank { "Server-driven radio" }, + mood.description ?: mood.genres.joinToString(" · ").ifBlank { "Your private mix" }, style = MaterialTheme.typography.bodySmall, color = Color.White.copy(alpha = 0.78f), maxLines = 2, @@ -153,14 +152,15 @@ private fun MoodCard(mood: Mood, onOpen: () -> Unit, onPlay: () -> Unit) { ) Row(verticalAlignment = Alignment.CenterVertically) { Text( - "${mood.seedCount} seeds", + "${mood.songCount} songs", style = MaterialTheme.typography.labelMedium, color = Color.White.copy(alpha = 0.85f), ) - if (mood.newRecommendations > 0) { + val picks = mood.recommendationReady + mood.recommendationDownloading + if (picks > 0) { Spacer(Modifier.width(8.dp)) Text( - "${mood.newRecommendations} picks", + "$picks picks", style = MaterialTheme.typography.labelMedium, color = Color.White.copy(alpha = 0.85f), ) @@ -186,16 +186,15 @@ private fun MoodCard(mood: Mood, onOpen: () -> Unit, onPlay: () -> Unit) { private fun CreateMoodDialog( saving: Boolean, onDismiss: () -> Unit, - onCreate: (String, String?, List<String>, String?, Int, Int, Boolean, Int) -> Unit, + onCreate: (String, String?, List<String>, String?, Int, Int, Int) -> Unit, ) { var name by remember { mutableStateOf("") } var description by remember { mutableStateOf("") } var genres by remember { mutableStateOf("") } var query by remember { mutableStateOf("") } - var target by remember { mutableStateOf("30") } + var collectionPercent by remember { mutableStateOf(50f) } + var recommendations by remember { mutableStateOf(10f) } var hours by remember { mutableStateOf("24") } - var yt by remember { mutableStateOf(true) } - var seedPercent by remember { mutableStateOf(50f) } AlertDialog( onDismissRequest = onDismiss, @@ -226,41 +225,39 @@ private fun CreateMoodDialog( OutlinedTextField( value = query, onValueChange = { query = it }, - label = { Text("Free-text hint") }, + label = { Text("Discovery hint") }, singleLine = true, ) - Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { - OutlinedTextField( - value = target, - onValueChange = { target = it }, - label = { Text("Batch size") }, - singleLine = true, - modifier = Modifier.weight(1f), - ) - OutlinedTextField( - value = hours, - onValueChange = { hours = it }, - label = { Text("Refresh h") }, - singleLine = true, - modifier = Modifier.weight(1f), - ) - } Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { Text( - "Seed mix: ${seedPercent.roundToInt()}% seeds · ${100 - seedPercent.roundToInt()}% recommendations", + "Collection share: ${collectionPercent.roundToInt()}% · ${100 - collectionPercent.roundToInt()}% recommendations", style = MaterialTheme.typography.bodySmall, ) Slider( - value = seedPercent, - onValueChange = { seedPercent = it }, + value = collectionPercent, + onValueChange = { collectionPercent = it }, valueRange = 0f..100f, steps = 9, ) } - Row(verticalAlignment = Alignment.CenterVertically) { - Text("YT Music discovery", Modifier.weight(1f)) - Switch(checked = yt, onCheckedChange = { yt = it }) + Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text( + "Active recommendations: ${recommendations.roundToInt()}", + style = MaterialTheme.typography.bodySmall, + ) + Slider( + value = recommendations, + onValueChange = { recommendations = it }, + valueRange = 0f..30f, + steps = 29, + ) } + OutlinedTextField( + value = hours, + onValueChange = { hours = it }, + label = { Text("Refresh interval (hours)") }, + singleLine = true, + ) } }, confirmButton = { @@ -272,10 +269,9 @@ private fun CreateMoodDialog( description.trim().takeIf { it.isNotEmpty() }, genres.split(',').map { it.trim() }.filter { it.isNotEmpty() }, query.trim().takeIf { it.isNotEmpty() }, - target.toIntOrNull() ?: 30, + collectionPercent.roundToInt(), + recommendations.roundToInt(), hours.toIntOrNull() ?: 24, - yt, - seedPercent.roundToInt(), ) }, ) { Text("Create") } diff --git a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/PlayerBar.kt b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/PlayerBar.kt index 2a1415f..2df8348 100644 --- a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/PlayerBar.kt +++ b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/PlayerBar.kt @@ -57,7 +57,6 @@ fun PlayerBar(state: AppState, store: AppStore) { var queueOpen by remember { mutableStateOf(false) } var dragSeconds by remember(song.id) { mutableStateOf<Float?>(null) } val sleepRemaining = state.sleepTimerRemainingSeconds - val isLongform = state.user?.longformFolders?.contains(song.folderId) == true Surface( color = MaterialTheme.colorScheme.surfaceVariant, @@ -135,7 +134,7 @@ fun PlayerBar(state: AppState, store: AppStore) { verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), ) { - Cover(store, song.albumId, Modifier.size(48.dp), size = 160) + Cover(store, song.id, Modifier.size(48.dp), size = 160) Column(Modifier.weight(1f)) { Text( song.title, @@ -167,13 +166,11 @@ fun PlayerBar(state: AppState, store: AppStore) { ) } - if (!isLongform) { - IconButton(onClick = { store.addCurrentToMood(null) }) { - Icon(Icons.Rounded.AddCircleOutline, contentDescription = "Add to current mood") - } - IconButton(onClick = { picker = true }) { - Icon(Icons.Rounded.PlaylistAdd, contentDescription = "Add to another mood") - } + IconButton(onClick = { store.addCurrentToMood(null) }) { + Icon(Icons.Rounded.AddCircleOutline, contentDescription = "Add to current mood") + } + IconButton(onClick = { picker = true }) { + Icon(Icons.Rounded.PlaylistAdd, contentDescription = "Add to another mood") } IconButton(onClick = { store.previous() }) { Icon(Icons.Rounded.SkipPrevious, contentDescription = "Previous") @@ -242,7 +239,7 @@ private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit) verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), ) { - Cover(store, song.albumId, Modifier.size(40.dp), size = 96) + Cover(store, song.id, Modifier.size(40.dp), size = 96) Column(Modifier.weight(1f)) { Text(song.title, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis) Text( @@ -258,7 +255,7 @@ private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit) if (state.queue.isEmpty()) { item { Text( - "Nothing queued. Start a mood, shuffle all or an artist.", + "Nothing queued. Start a mood to build a radio queue.", modifier = Modifier.padding(20.dp), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, @@ -272,7 +269,7 @@ private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit) verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), ) { - Cover(store, song.albumId, Modifier.size(36.dp), size = 96) + Cover(store, song.id, Modifier.size(36.dp), size = 96) Column(Modifier.weight(1f)) { Text(song.title, style = MaterialTheme.typography.bodyMedium, maxLines = 1, overflow = TextOverflow.Ellipsis) Text( diff --git a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/SearchScreen.kt b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/SearchScreen.kt new file mode 100644 index 0000000..108673c --- /dev/null +++ b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/SearchScreen.kt @@ -0,0 +1,213 @@ +package win.taptap.musicmanager.client.ui + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.Add +import androidx.compose.material.icons.rounded.ArrowDropDown +import androidx.compose.material.icons.rounded.Check +import androidx.compose.material.icons.rounded.DownloadDone +import androidx.compose.material.icons.rounded.Link +import androidx.compose.material.icons.rounded.Search +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.FilledTonalButton +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import win.taptap.musicmanager.client.api.SearchResult +import win.taptap.musicmanager.client.store.AppState +import win.taptap.musicmanager.client.store.AppStore + +@Composable +fun SearchScreen(state: AppState, store: AppStore) { + if (state.moods.isEmpty()) { + EmptyState( + "Create a mood first", + "Search results are always added to a mood.", + Modifier.fillMaxSize(), + ) + return + } + + var url by remember { mutableStateOf("") } + var moodMenu by remember { mutableStateOf(false) } + val target = state.moods.firstOrNull { it.id == state.searchTargetMoodId } ?: state.moods.first() + + LazyColumn( + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues(20.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + item { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + Text("Add to", style = MaterialTheme.typography.bodyMedium) + Box { + OutlinedButton(onClick = { moodMenu = true }) { + Text(target.name, maxLines = 1, overflow = TextOverflow.Ellipsis) + Icon(Icons.Rounded.ArrowDropDown, contentDescription = null) + } + DropdownMenu(expanded = moodMenu, onDismissRequest = { moodMenu = false }) { + state.moods.forEach { mood -> + DropdownMenuItem( + text = { Text(mood.name) }, + onClick = { + moodMenu = false + store.selectSearchMood(mood.id) + }, + ) + } + } + } + } + } + + item { + OutlinedTextField( + value = state.searchQuery, + onValueChange = store::setSearchQuery, + label = { Text("Search YouTube") }, + singleLine = true, + leadingIcon = { Icon(Icons.Rounded.Search, contentDescription = null) }, + modifier = Modifier.fillMaxWidth(), + ) + } + + item { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp), + modifier = Modifier.fillMaxWidth(), + ) { + OutlinedTextField( + value = url, + onValueChange = { url = it }, + label = { Text("Paste a YouTube URL") }, + singleLine = true, + leadingIcon = { Icon(Icons.Rounded.Link, contentDescription = null) }, + modifier = Modifier.weight(1f), + ) + FilledTonalButton( + enabled = url.isNotBlank(), + onClick = { + store.addByUrl(url) + url = "" + }, + ) { + Text("Add") + } + } + } + + if (state.searching) { + item { + Row(verticalAlignment = Alignment.CenterVertically) { + CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp) + Spacer(Modifier.width(10.dp)) + Text("Searching YouTube…", style = MaterialTheme.typography.bodySmall) + } + } + } + + if (!state.searching && state.searchQuery.isNotBlank() && state.searchResults.isEmpty()) { + item { + Text( + "No tracks up to 10 minutes were found.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + + items(state.searchResults, key = { it.videoId }) { result -> + SearchRow(result, store) + } + + item { Spacer(Modifier.size(24.dp)) } + } +} + +@Composable +private fun SearchRow(result: SearchResult, store: AppStore) { + Row( + modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + RemoteImage(store, result.thumbnail, Modifier.size(52.dp)) + Column(Modifier.weight(1f)) { + Text( + result.title, + style = MaterialTheme.typography.bodyLarge, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + Text( + buildString { + append(result.artist) + result.album?.takeIf { it.isNotBlank() }?.let { append(" · ").append(it) } + result.duration?.let { append(" · ").append(formatDuration(it)) } + }, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (result.downloaded) { + Row(verticalAlignment = Alignment.CenterVertically) { + Icon( + Icons.Rounded.DownloadDone, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(14.dp), + ) + Spacer(Modifier.width(4.dp)) + Text( + "Downloaded — adds instantly", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.primary, + ) + } + } + } + IconButton(onClick = { store.addSearchResult(result) }) { + Icon( + Icons.Rounded.Add, + contentDescription = "Add to ${result.title}", + ) + } + } +} diff --git a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/SettingsScreen.kt b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/SettingsScreen.kt index 9e4928a..e4c089f 100644 --- a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/SettingsScreen.kt +++ b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/SettingsScreen.kt @@ -2,19 +2,19 @@ package win.taptap.musicmanager.client.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.DeleteSweep import androidx.compose.material.icons.rounded.Logout import androidx.compose.material.icons.rounded.Refresh -import androidx.compose.material.icons.rounded.TravelExplore import androidx.compose.material3.Button import androidx.compose.material3.FilledTonalButton import androidx.compose.material3.Icon @@ -35,7 +35,7 @@ import win.taptap.musicmanager.client.store.AppStore fun SettingsScreen(state: AppState, store: AppStore) { LazyColumn( modifier = Modifier.fillMaxSize(), - contentPadding = androidx.compose.foundation.layout.PaddingValues(20.dp), + contentPadding = PaddingValues(20.dp), verticalArrangement = Arrangement.spacedBy(14.dp), ) { item { @@ -57,6 +57,11 @@ fun SettingsScreen(state: AppState, store: AppStore) { style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) + FilledTonalButton(onClick = { store.refreshAll() }) { + Icon(Icons.Rounded.Refresh, contentDescription = null) + Spacer(Modifier.width(6.dp)) + Text("Sync moods") + } } } } @@ -68,33 +73,27 @@ fun SettingsScreen(state: AppState, store: AppStore) { modifier = Modifier.fillMaxWidth(), ) { Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) { - Text("Library", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text("Offline", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Text( - "${state.library.size} songs cached · ${state.downloads.size} downloaded · ${formatBytes(store.storageBytes())}", + "${state.downloads.size} downloaded · ${formatBytes(store.storageBytes())}", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) - Row(horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) { - FilledTonalButton(onClick = { store.refreshAll() }) { - Icon(Icons.Rounded.Refresh, contentDescription = null) - Spacer(Modifier.width(6.dp)) - Text("Sync") + Row( + horizontalArrangement = Arrangement.spacedBy(10.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + OutlinedButton(onClick = { store.openDownloads() }) { + Text("Manage downloads") } - if (state.user?.admin == true) { - OutlinedButton(onClick = { store.scanLibrary() }) { - Icon(Icons.Rounded.TravelExplore, contentDescription = null) + if (state.downloads.isNotEmpty()) { + OutlinedButton(onClick = { store.clearDownloads() }) { + Icon(Icons.Rounded.DeleteSweep, contentDescription = null) Spacer(Modifier.width(6.dp)) - Text("Scan") + Text("Clear") } } } - if (state.downloads.isNotEmpty()) { - OutlinedButton(onClick = { store.clearDownloads() }) { - Icon(Icons.Rounded.DeleteSweep, contentDescription = null) - Spacer(Modifier.width(6.dp)) - Text("Clear downloads") - } - } } } } @@ -108,12 +107,13 @@ fun SettingsScreen(state: AppState, store: AppStore) { Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) { Text("About", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Text( - "AudioManager 0.1.0 · $platformName", + "AudioManager 0.2.0 · $platformName", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) Text( - "Moods are radio: the server chooses the next batch and learns from skips and completions. Add a track to a mood with the two buttons in the player.", + "Moods are private. Songs are downloaded from YouTube into a shared server store; " + + "recommendations refill automatically and stay playable without being permanent.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) diff --git a/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/ApiClientTest.kt b/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/ApiClientTest.kt index 68de268..0ca8cc7 100644 --- a/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/ApiClientTest.kt +++ b/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/ApiClientTest.kt @@ -8,17 +8,17 @@ import io.ktor.http.HttpStatusCode import io.ktor.http.headersOf import io.ktor.utils.io.readAvailable import kotlinx.coroutines.test.runTest -import kotlinx.serialization.json.Json import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertNull +import kotlin.test.assertTrue import win.taptap.musicmanager.client.api.ApiClient import win.taptap.musicmanager.client.api.ApiException +import win.taptap.musicmanager.client.api.Mood import win.taptap.musicmanager.client.api.configuredHttpClient -import win.taptap.musicmanager.client.data.AppStorage +import win.taptap.musicmanager.client.data.AppCache import win.taptap.musicmanager.client.data.CachedState -import win.taptap.musicmanager.client.data.LibraryCache class ApiClientTest { @@ -31,15 +31,16 @@ class ApiClientTest { "/api/v1/auth/login" -> respond( """ {"token":"abc123","expiresAt":"2027-01-01T00:00:00Z", - "user":{"name":"alice","admin":true,"musicFolders":[1],"longformFolders":[10]}} + "user":{"name":"alice","admin":true}} """.trimIndent(), HttpStatusCode.OK, jsonHeaders, ) "/api/v1/moods" -> respond( """ - {"moods":[{"id":"mo-1","name":"Focus","targetSize":30,"refreshHours":24, - "ytEnabled":true,"createdAt":"now","changedAt":"now","seedCount":2}]} + {"moods":[{"id":"mo-1","name":"Focus","collectionPercent":60, + "recommendationPercent":40,"recommendationCount":10,"refreshHours":24, + "createdAt":"now","changedAt":"now","songCount":2,"recommendationReady":3}]} """.trimIndent(), HttpStatusCode.OK, jsonHeaders, @@ -56,7 +57,86 @@ class ApiClientTest { val moods = client.moods() assertEquals(1, moods.size) assertEquals("Focus", moods.first().name) - assertEquals(2, moods.first().seedCount) + assertEquals(2, moods.first().songCount) + assertEquals(3, moods.first().recommendationReady) + } + + @Test + fun `search returns badges and adding a video queues a download`() = runTest { + val engine = MockEngine { request -> + when (request.url.encodedPath) { + "/api/v1/search" -> respond( + """ + {"results":[ + {"videoId":"v1","title":"Fresh","artist":"Artist","duration":180, + "downloaded":false}, + {"videoId":"v2","title":"Old","artist":"Artist","duration":200, + "songId":"sg-2","downloaded":true} + ]} + """.trimIndent(), + HttpStatusCode.OK, + jsonHeaders, + ) + "/api/v1/moods/mo-1/songs" -> respond( + """ + {"detail":{"mood":{"id":"mo-1","name":"Focus","createdAt":"now", + "changedAt":"now","songCount":1},"songs":[],"recommendations":[]}, + "added":false,"downloading":true} + """.trimIndent(), + HttpStatusCode.Accepted, + jsonHeaders, + ) + else -> respondError(HttpStatusCode.NotFound) + } + } + + val client = ApiClient(configuredHttpClient(engine)) + client.restore("http://music", "token") + + val results = client.search("fresh") + assertEquals(2, results.size) + assertNull(results[0].songId) + assertEquals("sg-2", results[1].songId) + assertTrue(results[1].downloaded) + + val added = client.addSong("mo-1", videoId = "v1") + assertTrue(added.downloading) + assertEquals(1, added.detail.mood.songCount) + } + + @Test + fun `adding and rejecting recommendations parse the decision`() = runTest { + val engine = MockEngine { request -> + when (request.url.encodedPath) { + "/api/v1/moods/mo-1/recommendations/v1/add" -> respond( + """ + {"detail":{"mood":{"id":"mo-1","name":"Focus","createdAt":"now", + "changedAt":"now","songCount":2},"songs":[],"recommendations":[]}, + "recommendation":{"videoId":"v1","title":"Pick","artist":"Artist", + "state":"added"}} + """.trimIndent(), + HttpStatusCode.OK, + jsonHeaders, + ) + "/api/v1/moods/mo-1/recommendations/v2/reject" -> respond( + """ + {"detail":{"mood":{"id":"mo-1","name":"Focus","createdAt":"now", + "changedAt":"now","songCount":2},"songs":[],"recommendations":[]}, + "recommendation":{"videoId":"v2","title":"Other","artist":"Artist", + "state":"rejected"}} + """.trimIndent(), + HttpStatusCode.OK, + jsonHeaders, + ) + else -> respondError(HttpStatusCode.NotFound) + } + } + + val client = ApiClient(configuredHttpClient(engine)) + client.restore("http://music", "token") + + assertEquals("added", client.addRecommendation("mo-1", "v1").recommendation.state) + assertEquals("rejected", client.rejectRecommendation("mo-1", "v2").recommendation.state) } @Test @@ -116,23 +196,33 @@ class ApiClientTest { } @Test - fun `cache round-trips songs and moods`() = runTest { + fun `cache round-trips moods and discards the old cache version`() = runTest { val storage = MemoryStorage() - val cache = LibraryCache(storage) + val cache = AppCache(storage) assertNull(cache.loadSession()) + val mood = Mood( + id = "mo-1", + name = "Focus", + createdAt = "now", + changedAt = "now", + songCount = 2, + ) cache.save( CachedState( serverUrl = "http://localhost:8080", userName = "alice", - revision = "2026-11-14T00:00:00Z", - songs = emptyList(), - moods = emptyList(), + moods = listOf(mood), ), ) val loaded = cache.load() - assertEquals("2026-11-14T00:00:00Z", loaded.revision) + assertEquals(listOf("mo-1"), loaded.moods.map { it.id }) assertEquals("alice", loaded.userName) + + storage.write("mood-cache.json", """{"version":1,"songs":[{"id":"old"}]}""") + val invalidated = cache.load() + assertTrue(invalidated.moods.isEmpty()) + assertEquals(2, invalidated.version) } } diff --git a/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/AppStoreTest.kt b/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/AppStoreTest.kt index 7a34281..c0e969c 100644 --- a/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/AppStoreTest.kt +++ b/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/AppStoreTest.kt @@ -10,10 +10,10 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.delay import kotlinx.coroutines.test.TestScope -import kotlinx.coroutines.withContext import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.withContext import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse @@ -24,8 +24,8 @@ import win.taptap.musicmanager.client.api.ApiClient import win.taptap.musicmanager.client.api.Song import win.taptap.musicmanager.client.api.User import win.taptap.musicmanager.client.api.configuredHttpClient +import win.taptap.musicmanager.client.data.AppCache import win.taptap.musicmanager.client.data.CachedState -import win.taptap.musicmanager.client.data.LibraryCache import win.taptap.musicmanager.client.data.PlaybackSnapshot import win.taptap.musicmanager.client.data.SessionState import win.taptap.musicmanager.client.playback.AudioPlayer @@ -35,48 +35,155 @@ import win.taptap.musicmanager.client.store.AppStore class AppStoreTest { @Test - fun `play all queues the whole library and starts playback`() = runTest { + fun `playing a mood starts the server session and the first track`() = runTest { val storage = MemoryStorage() - val cache = LibraryCache(storage) - val songs = listOf(song("a"), song("b"), song("c")) - cache.save(CachedState(serverUrl = "http://music", songs = songs)) + val cache = AppCache(storage) + cache.saveSession(SessionState("http://music", "token", User("alice", admin = false))) val player = FakePlayer() - val store = store(storage, cache, player) + val engine = MockEngine { request -> + when (request.url.encodedPath) { + "/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders) + "/api/v1/moods" -> respond("""{"moods":[${moodJson(1)}]}""", HttpStatusCode.OK, jsonHeaders) + "/api/v1/moods/mo-1" -> respond(detailJson(listOf("a")), HttpStatusCode.OK, jsonHeaders) + "/api/v1/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders) + "/api/v1/moods/mo-1/sessions" -> respond( + """{"id":"s1","moodId":"mo-1","moodName":"Focus","startedAt":"now", + "queue":[${songJson("a")}]}""", + HttpStatusCode.Created, + jsonHeaders, + ) + else -> respondError(HttpStatusCode.NotFound) + } + } + val store = store(storage, cache, player, engine) runCurrent() + store.openMood("mo-1") + awaitState { store.state.value.selectedMood != null } - store.playAll() - runCurrent() + store.playMood("mo-1") + awaitState { store.state.value.current != null } val state = store.state.value - val current = assertNotNull(state.current) + assertEquals("a", state.current?.id) + assertEquals("s1", state.session?.id) assertTrue(state.playing) - assertEquals(listOf(current.id), player.played) - assertEquals(2, state.queue.size) - assertEquals(songs.map { it.id }.toSet(), (state.queue + current).map { it.id }.toSet()) + assertEquals(listOf("a"), player.played) store.release() } @Test - fun `play all reports an empty library instead of starting playback`() = runTest { + fun `an empty mood is rejected before any request`() = runTest { val storage = MemoryStorage() - val cache = LibraryCache(storage) + val cache = AppCache(storage) + cache.saveSession(SessionState("http://music", "token", User("alice", admin = false))) val player = FakePlayer() - val store = store(storage, cache, player) + val engine = MockEngine { request -> + when (request.url.encodedPath) { + "/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders) + "/api/v1/moods" -> respond("""{"moods":[${moodJson(0)}]}""", HttpStatusCode.OK, jsonHeaders) + "/api/v1/moods/mo-1" -> respond(detailJson(emptyList()), HttpStatusCode.OK, jsonHeaders) + "/api/v1/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders) + else -> respondError(HttpStatusCode.NotFound) + } + } + val store = store(storage, cache, player, engine) runCurrent() + store.openMood("mo-1") + awaitState { store.state.value.selectedMood != null } - store.playAll() - runCurrent() + store.playMood("mo-1") + awaitState { store.state.value.message != null } assertNull(store.state.value.current) assertTrue(player.played.isEmpty()) assertTrue(store.state.value.messageIsError) + assertTrue(store.state.value.message!!.contains("at least one song")) + store.release() + } + + @Test + fun `search is debounced and adding a result targets the chosen mood`() = runTest { + val storage = MemoryStorage() + val cache = AppCache(storage) + cache.saveSession(SessionState("http://music", "token", User("alice", admin = false))) + val engine = MockEngine { request -> + when (request.url.encodedPath) { + "/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders) + "/api/v1/moods" -> respond("""{"moods":[${moodJson(0)}]}""", HttpStatusCode.OK, jsonHeaders) + "/api/v1/search" -> respond( + """{"results":[{"videoId":"v1","title":"Fresh","artist":"Artist", + "duration":180,"downloaded":false}]}""", + HttpStatusCode.OK, + jsonHeaders, + ) + "/api/v1/moods/mo-1/songs" -> respond( + """{"detail":${detailJson(emptyList())},"added":false,"downloading":true}""", + HttpStatusCode.Accepted, + jsonHeaders, + ) + else -> respondError(HttpStatusCode.NotFound) + } + } + val store = store(storage, cache, FakePlayer(), engine) + runCurrent() + awaitState { store.state.value.moods.isNotEmpty() } + + store.openSearch("mo-1") + store.setSearchQuery("fresh") + advanceTimeBy(350) + runCurrent() + awaitState { store.state.value.searchResults.isNotEmpty() } + assertEquals("v1", store.state.value.searchResults.single().videoId) + + store.addSearchResult(store.state.value.searchResults.single()) + awaitState { store.state.value.message != null } + assertEquals("Downloading for Focus", store.state.value.message) + store.release() + } + + @Test + fun `adding a recommendation refreshes the selected mood`() = runTest { + val storage = MemoryStorage() + val cache = AppCache(storage) + cache.saveSession(SessionState("http://music", "token", User("alice", admin = false))) + val engine = MockEngine { request -> + when (request.url.encodedPath) { + "/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders) + "/api/v1/moods" -> respond("""{"moods":[${moodJson(1)}]}""", HttpStatusCode.OK, jsonHeaders) + "/api/v1/moods/mo-1" -> respond( + detailJson(listOf("a"), recommendationJson()), + HttpStatusCode.OK, + jsonHeaders, + ) + "/api/v1/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders) + "/api/v1/moods/mo-1/recommendations/v1/add" -> respond( + """{"detail":${detailJson(listOf("a"))}, + "recommendation":${recommendationJson(state = "added", songId = "a")}}""", + HttpStatusCode.OK, + jsonHeaders, + ) + else -> respondError(HttpStatusCode.NotFound) + } + } + val store = store(storage, cache, FakePlayer(), engine) + runCurrent() + store.openMood("mo-1") + awaitState { store.state.value.selectedMood != null } + + store.addRecommendation("v1") + awaitState { store.state.value.message != null } + + val detail = assertNotNull(store.state.value.selectedMood) + assertTrue(detail.recommendations.isEmpty()) + assertEquals(1, detail.mood.songCount) + assertEquals("Added to Focus", store.state.value.message) store.release() } @Test fun `sleep timer pauses playback when it expires`() = runTest { val storage = MemoryStorage() - val cache = LibraryCache(storage) + val cache = AppCache(storage) val player = FakePlayer() val store = store(storage, cache, player) runCurrent() @@ -91,54 +198,30 @@ class AppStoreTest { advanceTimeBy(60_000) runCurrent() - val state = store.state.value - assertFalse(state.playing) - assertNull(state.sleepTimerRemainingSeconds) + assertFalse(store.state.value.playing) + assertNull(store.state.value.sleepTimerRemainingSeconds) assertTrue(player.paused) store.release() } @Test - fun `turning the sleep timer off keeps playback running`() = runTest { + fun `bootstrap restores the saved queue and resumes on play`() = runTest { val storage = MemoryStorage() - val cache = LibraryCache(storage) - val player = FakePlayer() - val store = store(storage, cache, player) - runCurrent() - - store.playSong(song("a")) - runCurrent() - - store.setSleepTimer(30) - assertEquals(1_800L, store.state.value.sleepTimerRemainingSeconds) - store.setSleepTimer(null) - assertNull(store.state.value.sleepTimerRemainingSeconds) - - advanceTimeBy(120_000) - runCurrent() - assertTrue(store.state.value.playing) - store.release() - } - - - @Test - fun `bootstrap restores the saved queue and starts it on play`() = runTest { - val storage = MemoryStorage() - val cache = LibraryCache(storage) + val cache = AppCache(storage) cache.savePlayback( PlaybackSnapshot( queue = listOf(song("b")), current = song("a"), + positionSeconds = 12.0, ), ) val player = FakePlayer() val store = store(storage, cache, player) runCurrent() - val restored = store.state.value - assertEquals("a", restored.current?.id) - assertEquals(listOf("b"), restored.queue.map { it.id }) - assertFalse(restored.playing) + assertEquals("a", store.state.value.current?.id) + assertEquals(listOf("b"), store.state.value.queue.map { it.id }) + assertEquals(12.0, store.state.value.positionSeconds) assertTrue(player.played.isEmpty()) store.togglePlayPause() @@ -146,93 +229,41 @@ class AppStoreTest { assertTrue(store.state.value.playing) assertEquals(listOf("a"), player.played) + assertEquals(12.0, player.seeks.last()) store.release() } @Test - fun `accepting a recommendation replaces the selected mood`() = runTest { + fun `queue reordering and removal persist in the snapshot`() = 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 cache = AppCache(storage) + cache.saveSession(SessionState("http://music", "token", User("alice", admin = false))) val engine = MockEngine { request -> when (request.url.encodedPath) { - "/api/v1/moods" -> respond("""{"moods":[]}""", HttpStatusCode.OK, jsonHeaders) - "/api/v1/library/songs" -> respond( - """{"songs":[],"revision":"r1"}""", + "/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders) + "/api/v1/moods" -> respond("""{"moods":[${moodJson(3)}]}""", HttpStatusCode.OK, jsonHeaders) + "/api/v1/moods/mo-1" -> respond( + detailJson(listOf("a", "b", "c")), HttpStatusCode.OK, jsonHeaders, ) - "/api/v1/moods/mo-1" -> 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, + "/api/v1/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders) + "/api/v1/moods/mo-1/sessions" -> respond( + """{"id":"s1","moodId":"mo-1","moodName":"Focus","startedAt":"now", + "queue":[${songJson("a")},${songJson("b")},${songJson("c")}]}""", + HttpStatusCode.Created, jsonHeaders, ) else -> respondError(HttpStatusCode.NotFound) } } - val store = AppStore( - scope = this, - api = ApiClient(configuredHttpClient(engine)), - storage = storage, - player = player, - cache = cache, - ) + val store = store(storage, cache, FakePlayer(), engine) runCurrent() store.openMood("mo-1") - awaitState { store.state.value.selectedMood != null || store.state.value.message != null } + awaitState { store.state.value.selectedMood != 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) + store.playMood("mo-1") + awaitState { store.state.value.current?.id == "a" } assertEquals(listOf("b", "c"), store.state.value.queue.map { it.id }) store.moveInQueue(1, 0) @@ -245,333 +276,34 @@ class AppStoreTest { } @Test - fun `restored playback resumes from the saved position`() = runTest { + fun `logout clears the session and the mood cache`() = 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) + val cache = AppCache(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", - ), + cache.save( + CachedState( + serverUrl = "http://music", + userName = "alice", + moods = emptyList(), ), ) - val store = store(storage, cache, FakePlayer()) + val engine = MockEngine { request -> + when (request.url.encodedPath) { + "/api/v1/auth/logout" -> respond("", HttpStatusCode.NoContent) + "/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders) + "/api/v1/moods" -> respond("""{"moods":[]}""", HttpStatusCode.OK, jsonHeaders) + else -> respondError(HttpStatusCode.NotFound) + } + } + val store = store(storage, cache, FakePlayer(), engine) runCurrent() + awaitState { store.state.value.authenticated } 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) + assertNull(cache.loadSession()) + assertTrue(cache.load().moods.isEmpty()) store.release() } @@ -586,56 +318,53 @@ class AppStoreTest { 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} + private fun songJson(id: String) = """ + {"id":"$id","videoId":"video-$id","title":"Song $id","artist":"Artist", + "album":"Album","duration":180,"bitRate":320,"size":1000,"suffix":"mp3"} """.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}"}""" }}} + private fun moodJson(songCount: Int) = """ + {"id":"mo-1","name":"Focus","collectionPercent":50,"recommendationPercent":50, + "recommendationCount":10,"refreshHours":24,"createdAt":"2026-01-01T00:00:00Z", + "changedAt":"2026-01-01T00:00:00Z","songCount":$songCount} """.trimIndent() - private fun moodDetailJson(state: String, seedCount: Int) = """ - {"mood":${moodJson(seedCount)},"seeds":[],"recommendations":[${recommendationJson(state)}]} + private fun recommendationJson(state: String = "new", songId: String? = null) = """ + {"videoId":"v1","title":"Pick","artist":"Artist","duration":180,"state":"$state", + ${songId?.let { "\"song\":${songJson(it)}," } ?: ""} + "firstSeen":"2026-01-01T00:00:00Z","lastSeen":"2026-01-01T00:00:00Z"} """.trimIndent() - private fun kotlinx.coroutines.test.TestScope.store( - storage: MemoryStorage, - cache: LibraryCache, - player: AudioPlayer, - ): AppStore = AppStore( - // Background scope so leftover store jobs (reconnect loops, refreshes) - // are cancelled by runTest instead of failing the next test with - // UncompletedCoroutinesError. - scope = backgroundScope, - api = ApiClient(configuredHttpClient(MockEngine { respondError(HttpStatusCode.NotFound) })), - storage = storage, - player = player, - cache = cache, - ) + private fun detailJson(songs: List<String>, recommendation: String? = null) = """ + {"mood":${moodJson(songs.size)}, + "songs":[${songs.joinToString(",") { """{"song":${songJson(it)},"origin":"search","addedAt":"now"}""" }}], + "recommendations":${recommendation?.let { "[$it]" } ?: "[]"}} + """.trimIndent() - private fun song( - id: String, - artist: String = "Artist", - folderId: Int = 1, - duration: Int = 180, - ) = Song( + private fun song(id: String, duration: Int = 180) = Song( id = id, + videoId = "video-$id", title = "Song $id", - artist = artist, + artist = "Artist", album = "Album", - albumId = "al-1", duration = duration, bitRate = 320, size = 1_000, - suffix = "mp3", - folderId = folderId, - relativePath = "$id.mp3", - updatedAt = "2026-01-01T00:00:00Z", + ) + + private fun TestScope.store( + storage: MemoryStorage, + cache: AppCache, + player: AudioPlayer, + engine: MockEngine = MockEngine { respondError(HttpStatusCode.NotFound) }, + ): AppStore = AppStore( + // Background scope so leftover store jobs (reconnect loops, refreshes) + // are cancelled by runTest instead of failing with UncompletedCoroutinesError. + scope = backgroundScope, + api = ApiClient(configuredHttpClient(engine)), + storage = storage, + player = player, + cache = cache, ) private class FakePlayer : AudioPlayer { diff --git a/docs/mood-first-client.md b/docs/mood-first-client.md index 833c84a..53a2b5e 100644 --- a/docs/mood-first-client.md +++ b/docs/mood-first-client.md @@ -46,3 +46,23 @@ Remove `LibraryScreen` and all longform UI. - Playback snapshot/history, desktop seek, Android media session, sleep timer and device downloads remain. - Offline mood playback uses device downloads and cached mood details. + +## Implementation status (2026-11-15) + +Implemented. Concretely: + +- `Models.kt` reflects the mood-first DTOs: `Song(videoId, thumbnail)`, + `Mood(collectionPercent, recommendationCount, song counts)`, + `MoodSong`, `Recommendation(song, download)`, `SearchResult`. +- `ApiClient` uses `/moods/{id}/songs`, `/search`, recommendation + `add|reject|retry`, and `/songs/{id}/cover`. +- `AppCache` (version 2) stores moods and details only; old cache shapes are + discarded. Session and playback snapshots are kept. +- `AppStore` has `Moods | MoodDetail | Search | Downloads | Settings`, remote + search with a target mood, add/remove song, recommendation actions, offline + playback from device downloads, and no longform/library paths. +- The UI has a dedicated Search screen (mood picker, paste URL, downloaded + badges) and a Downloads screen. Mood Detail shows songs, add music, + recommendation states and the new options. The player keeps queue editing, + previous/seek and the sleep timer. +- Device downloads store covers by song id (`<songId>.jpg`).