diff --git a/README.md b/README.md index 6e3a36d..d99614c 100644 --- a/README.md +++ b/README.md @@ -24,9 +24,13 @@ The shared module contains the API client, session/cache storage, radio queue, a - 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 and new picks. Accepting a track the library already has adds it as a seed immediately. - Library search and playback, plus **Shuffle all** to queue the whole library without starting a mood. - **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. +- 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. @@ -95,6 +99,8 @@ Android cleartext HTTP is enabled for local development. Use HTTPS in production - **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 and current track are persisted on every queue change and restored on the next launch. +- **Offline retry** — a background loop retries the library sync until the server responds again. On startup the app is usable before the network call completes: cached moods and library render immediately, then refresh in the background. @@ -133,5 +139,6 @@ The image build performs one warm-up compile (`kotlinNodeJsSetup`, `kotlinYarnSe - The media notification exposes play/pause and seeking. Queue actions (skip, add to mood) stay in the app because the mood session and its events belong to the server. - Desktop playback cannot seek (sequential decoder); pause/resume and skipping work. MP3s are decoded to 16-bit PCM before the line is opened, because Java Sound has no line for the compressed format. - Web downloads are disabled because the browser owns its storage; the app still streams and caches metadata. -- YT Music recommendations are displayed when the server provides them; discovery and downloading are server-side roadmap items. +- Accepted recommendations that are not in the library wait for the server-side downloader before they can be played. +- YT Music discovery runs server-side through `yt-dlp`; downloading accepted tracks that are not in the library is still roadmap. - No iOS target yet. The shared module is ready for one. 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 d527725..5a0cca7 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 @@ -5,6 +5,7 @@ import io.ktor.client.call.body import io.ktor.client.engine.HttpClientEngine import io.ktor.client.plugins.HttpTimeout import io.ktor.client.plugins.contentnegotiation.ContentNegotiation +import io.ktor.client.plugins.timeout import io.ktor.client.request.HttpRequestBuilder import io.ktor.client.request.delete import io.ktor.client.request.get @@ -53,6 +54,7 @@ class ApiClient(private val http: HttpClient) { private set private val coverCache = mutableMapOf() + private val imageCache = mutableMapOf() suspend fun login( serverUrl: String, @@ -79,6 +81,7 @@ class ApiClient(private val http: HttpClient) { fun clear() { token = null coverCache.clear() + imageCache.clear() } suspend fun me(): User = get("/me") @@ -127,6 +130,35 @@ class ApiClient(private val http: HttpClient) { requestNoContent { http.delete(url("/moods/$moodId/seeds/$songId")) { auth() } } } + suspend fun recommendations(moodId: String): List = + get("/moods/$moodId/recommendations").recommendations + + suspend fun refreshRecommendations(moodId: String): MoodDetail = + parse( + http.post(url("/moods/$moodId/recommendations/refresh")) { + auth() + // yt-dlp searches a few queries in parallel; give the server room. + timeout { + requestTimeoutMillis = 120_000 + socketTimeoutMillis = 120_000 + } + }, + ) + + suspend fun acceptRecommendation(moodId: String, videoId: String): RecommendationDecision = + parse( + http.post(url("/moods/$moodId/recommendations/$videoId/accept")) { + auth() + }, + ) + + suspend fun rejectRecommendation(moodId: String, videoId: String): RecommendationDecision = + parse( + http.post(url("/moods/$moodId/recommendations/$videoId/reject")) { + auth() + }, + ) + suspend fun preview(moodId: String, limit: Int = 20): List = get("/moods/$moodId/preview?limit=$limit").songs @@ -208,10 +240,21 @@ class ApiClient(private val http: HttpClient) { .bodyAsBytes() }.getOrNull() val result = bytes?.takeIf { it.isNotEmpty() } + if (coverCache.size > MAX_CACHED_IMAGES) coverCache.clear() coverCache[key] = result return result } + /** Remote artwork such as YT thumbnails, cached for the app's lifetime. */ + suspend fun image(url: String): ByteArray? { + if (imageCache.containsKey(url)) return imageCache[url] + val bytes = runCatching { http.get(url).bodyAsBytes() }.getOrNull() + val result = bytes?.takeIf { it.isNotEmpty() } + if (imageCache.size > MAX_CACHED_IMAGES) imageCache.clear() + imageCache[url] = result + return result + } + suspend fun download(songId: String): ByteArray = http.get("$baseUrl/api/v1/songs/$songId/stream") { auth() @@ -253,6 +296,10 @@ class ApiClient(private val http: HttpClient) { ) } + private companion object { + const val MAX_CACHED_IMAGES = 200 + } + private fun normalize(serverUrl: String): String { var value = serverUrl.trim().trimEnd('/') if (value.isEmpty()) value = "http://localhost:8080" 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 823edea..3cf3cab 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 @@ -104,6 +104,16 @@ data class MoodDetail( @Serializable data class MoodsResponse(val moods: List) +@Serializable +data class RecommendationsResponse(val recommendations: List = emptyList()) + +@Serializable +data class RecommendationDecision( + val detail: MoodDetail, + val recommendation: Recommendation, + val seedAdded: Boolean = false, +) + @Serializable data class LibraryPage( val songs: List = emptyList(), diff --git a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/data/LibraryCache.kt b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/data/LibraryCache.kt index f301954..88cf250 100644 --- a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/data/LibraryCache.kt +++ b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/data/LibraryCache.kt @@ -4,6 +4,7 @@ import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import win.taptap.musicmanager.client.api.Mood import win.taptap.musicmanager.client.api.MoodDetail +import win.taptap.musicmanager.client.api.Session import win.taptap.musicmanager.client.api.Song import win.taptap.musicmanager.client.api.User @@ -24,6 +25,14 @@ data class CachedState( val moodDetails: List = emptyList(), ) +/** The queue survives a restart so the next launch can resume where it stopped. */ +@Serializable +data class PlaybackSnapshot( + val session: Session? = null, + val queue: List = emptyList(), + val current: Song? = null, +) + class LibraryCache(private val storage: AppStorage) { private val json = Json { @@ -50,12 +59,27 @@ class LibraryCache(private val storage: AppStorage) { storage.write(CACHE_FILE, json.encodeToString(state)) } + fun loadPlayback(): PlaybackSnapshot? = + storage.read(PLAYBACK_FILE)?.let { + runCatching { json.decodeFromString(it) }.getOrNull() + } + + fun savePlayback(snapshot: PlaybackSnapshot?) { + if (snapshot == null || (snapshot.current == null && snapshot.queue.isEmpty())) { + storage.delete(PLAYBACK_FILE) + } else { + storage.write(PLAYBACK_FILE, json.encodeToString(snapshot)) + } + } + fun clear() { storage.delete(CACHE_FILE) + storage.delete(PLAYBACK_FILE) } private companion object { const val SESSION_FILE = "session.json" const val CACHE_FILE = "library.json" + const val PLAYBACK_FILE = "playback.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 db28bd8..38800a4 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 @@ -26,6 +26,7 @@ import win.taptap.musicmanager.client.api.UpdateMoodRequest import win.taptap.musicmanager.client.api.configuredHttpClient import win.taptap.musicmanager.client.data.CachedState import win.taptap.musicmanager.client.data.LibraryCache +import win.taptap.musicmanager.client.data.PlaybackSnapshot import win.taptap.musicmanager.client.data.SessionState import win.taptap.musicmanager.client.playback.AudioPlayer import win.taptap.musicmanager.client.platformName @@ -56,6 +57,7 @@ data class AppState( val searching: Boolean = false, val loading: Boolean = false, val saving: Boolean = false, + val discovering: Boolean = false, val message: String? = null, val messageIsError: Boolean = false, val messageId: Long = 0, @@ -77,6 +79,8 @@ class AppStore( private var pollJob: Job? = null private var sleepJob: Job? = null + private var reconnectJob: Job? = null + private var playbackStarted = false private var advancing = false private var fetching = false private var finishing = false @@ -89,6 +93,7 @@ class AppStore( scope.launch { val session = cache.loadSession() val cached = cache.load() + val playback = cache.loadPlayback() _state.update { it.copy( booting = false, @@ -96,6 +101,10 @@ class AppStore( moods = cached.moods, library = cached.songs.sortedLibrary(), selectedMood = cached.moodDetails.firstOrNull(), + session = playback?.session, + queue = playback?.queue.orEmpty(), + current = playback?.current, + durationSeconds = playback?.current?.duration?.toDouble() ?: 0.0, ) } @@ -157,68 +166,71 @@ class AppStore( } fun refreshAll(silent: Boolean = false) { - scope.launch { - if (!silent) _state.update { it.copy(loading = true) } - try { - val moods = api.moods() - val cached = cache.load() - var songs = cached.songs.associateBy { it.id }.toMutableMap() - var revision = cached.revision + scope.launch { refreshAllNow(silent) } + } - if (revision == null) { - var cursor: String? = null - do { - val page = api.library(cursor = cursor, since = null, limit = 500) - 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 - } - } + private suspend fun refreshAllNow(silent: Boolean) { + if (!silent) _state.update { it.copy(loading = true) } + try { + val moods = api.moods() + val cached = cache.load() + var songs = cached.songs.associateBy { it.id }.toMutableMap() + var revision = cached.revision - val details = cached.moodDetails.filter { detail -> moods.any { it.id == detail.mood.id } } - cache.save( - CachedState( - serverUrl = _state.value.serverUrl, - userName = _state.value.user?.name.orEmpty(), - revision = revision, - songs = songs.values.toList(), - moods = moods, - moodDetails = details, - ), - ) - - _state.update { - it.copy( - loading = false, - offline = false, - moods = moods, - library = songs.values.sortedLibrary(), - ) - } - } catch (t: Throwable) { - if (t is ApiException && t.status == 401) { - logout() - return@launch - } - _state.update { - it.copy( - loading = false, - offline = true, - message = "Offline mode: ${t.friendlyMessage()}", - messageIsError = true, - messageId = it.messageId + 1, - ) + if (revision == null) { + var cursor: String? = null + do { + val page = api.library(cursor = cursor, since = null, limit = 500) + 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 } } + cache.save( + CachedState( + serverUrl = _state.value.serverUrl, + userName = _state.value.user?.name.orEmpty(), + revision = revision, + songs = songs.values.toList(), + moods = moods, + moodDetails = details, + ), + ) + + _state.update { + it.copy( + loading = false, + offline = false, + moods = moods, + library = songs.values.sortedLibrary(), + ) + } + } catch (t: Throwable) { + if (t is ApiException && t.status == 401) { + logout() + return + } + _state.update { + it.copy( + loading = false, + offline = true, + message = "Offline mode: ${t.friendlyMessage()}", + messageIsError = true, + messageId = it.messageId + 1, + ) + } + scheduleReconnect() } } @@ -435,6 +447,7 @@ class AppStore( ) } playNext() + persistPlayback() } catch (t: Throwable) { val fallback = state.library.filter { it.id in state.downloads } if (fallback.isNotEmpty()) { @@ -469,6 +482,7 @@ class AppStore( durationSeconds = song.duration.toDouble(), ) } + persistPlayback() startSong(song) } } @@ -504,6 +518,7 @@ class AppStore( val queue = if (shuffled) songs.shuffled(Random.Default) else songs _state.update { it.copy(session = null, queue = queue) } playNext() + persistPlayback() } } @@ -547,12 +562,78 @@ 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 - if (state.current == null) return + val song = state.current ?: return if (state.playing) { player.pause() _state.update { it.copy(playing = false) } + } else if (!playbackStarted || player.isFinished()) { + // Restored queue or finished track: start it from the beginning. + _state.update { + it.copy(playing = true, positionSeconds = 0.0, durationSeconds = song.duration.toDouble()) + } + startSong(song) } else { player.resume() _state.update { it.copy(playing = true) } @@ -640,19 +721,22 @@ class AppStore( scope.launch { _state.update { it.copy(downloading = it.downloading + song.id) } - try { - val bytes = api.download(song.id) - val path = storage.saveDownload(song.id, bytes) - if (path == null) { - _state.update { - it.copy( - downloading = it.downloading - song.id, - message = "Downloads are not available on this platform", - messageIsError = true, - messageId = it.messageId + 1, - ) + var lastError: Throwable? = null + repeat(DOWNLOAD_ATTEMPTS) { attempt -> + try { + val bytes = api.download(song.id) + val path = storage.saveDownload(song.id, bytes) + if (path == null) { + _state.update { + it.copy( + downloading = it.downloading - song.id, + message = "Downloads are not available on this platform", + messageIsError = true, + messageId = it.messageId + 1, + ) + } + return@launch } - } else { _state.update { it.copy( downloading = it.downloading - song.id, @@ -662,11 +746,16 @@ class AppStore( messageId = it.messageId + 1, ) } + return@launch + } catch (t: Throwable) { + lastError = t + if (attempt < DOWNLOAD_ATTEMPTS - 1) { + delay(1_000L * (attempt + 1)) + } } - } catch (t: Throwable) { - _state.update { it.copy(downloading = it.downloading - song.id) } - message(t) } + _state.update { it.copy(downloading = it.downloading - song.id) } + message(lastError ?: IllegalStateException("Download failed")) } } @@ -697,6 +786,9 @@ class AppStore( suspend fun cover(albumId: String): ByteArray? = api.cover(albumId, 320) + /** YT thumbnails and other remote artwork, cached inside the API client. */ + suspend fun image(url: String?): ByteArray? = url?.let { api.image(it) } + fun storageBytes(): Long = storage.storageUsedBytes() fun canSeek(): Boolean = player.canSeek @@ -710,8 +802,10 @@ class AppStore( } fun release() { + persistPlayback() pollJob?.cancel() sleepJob?.cancel() + reconnectJob?.cancel() player.release() } @@ -749,6 +843,7 @@ class AppStore( durationSeconds = song.duration.toDouble(), ) } + persistPlayback() startSong(song) report("started", song.id) if (_state.value.queue.size < 3) prefetch() @@ -791,6 +886,7 @@ class AppStore( } return } + playbackStarted = true startPolling() } @@ -843,6 +939,8 @@ class AppStore( pollJob?.cancel() sleepJob?.cancel() sleepJob = null + reconnectJob?.cancel() + playbackStarted = false player.scheduleSleepTimer(null) player.stop() _state.update { @@ -854,6 +952,7 @@ class AppStore( sleepTimerRemainingSeconds = null, ) } + cache.savePlayback(null) } private fun cacheDetail(detail: MoodDetail) { @@ -862,6 +961,41 @@ class AppStore( cache.save(cached.copy(moodDetails = details, moods = cached.moods)) } + private fun applyMoodDetail(detail: MoodDetail) { + cacheDetail(detail) + _state.update { state -> + state.copy( + selectedMood = detail, + moods = state.moods.map { mood -> if (mood.id == detail.mood.id) detail.mood else mood }, + ) + } + } + + private fun persistPlayback() { + val state = _state.value + cache.savePlayback( + PlaybackSnapshot( + session = state.session, + queue = state.queue, + current = state.current, + ), + ) + } + + /** Retries the library sync with exponential backoff while offline. */ + private fun scheduleReconnect() { + if (reconnectJob?.isActive == true) return + reconnectJob = scope.launch { + var waitMillis = RECONNECT_INITIAL_MS + while (isActive && _state.value.offline) { + delay(waitMillis) + refreshAllNow(silent = true) + if (!_state.value.offline) break + waitMillis = (waitMillis * 2).coerceAtMost(RECONNECT_MAX_MS) + } + } + } + private fun message(t: Throwable) { _state.update { it.copy( @@ -880,3 +1014,7 @@ private fun Throwable.friendlyMessage(): String = when (this) { private fun Collection.sortedLibrary(): List = sortedWith(compareBy({ it.artist.lowercase() }, { it.album.lowercase() }, { it.trackNumber ?: 0 })) + +private const val RECONNECT_INITIAL_MS = 15_000L +private const val RECONNECT_MAX_MS = 300_000L +private const val DOWNLOAD_ATTEMPTS = 3 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 5819770..3d6416c 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 @@ -91,6 +91,42 @@ fun Cover( } } +@Composable +fun RemoteImage(store: AppStore, url: String?, modifier: Modifier = Modifier) { + var bitmap by remember(url) { mutableStateOf(null) } + + LaunchedEffect(url) { + if (url == null) return@LaunchedEffect + bitmap = store.image(url)?.let { data -> runCatching { decodeImage(data) }.getOrNull() } + } + + Box( + modifier = modifier + .clip(RoundedCornerShape(10.dp)) + .background( + Brush.linearGradient(listOf(Color(0xFF28344A), Color(0xFF1A2230))), + ), + contentAlignment = Alignment.Center, + ) { + val image = bitmap + if (image != null) { + Image( + bitmap = image, + contentDescription = null, + modifier = Modifier.fillMaxSize(), + contentScale = ContentScale.Crop, + ) + } else { + Icon( + Icons.Rounded.MusicNote, + contentDescription = null, + tint = Color(0xFF5E6C84), + modifier = Modifier.size(20.dp), + ) + } + } +} + @Composable fun EmptyState(title: String, subtitle: String? = null, modifier: Modifier = Modifier) { Column( 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 c03df81..853e58d 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,7 +15,10 @@ 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.PlayArrow +import androidx.compose.material.icons.rounded.Refresh import androidx.compose.material.icons.rounded.RemoveCircleOutline import androidx.compose.material3.Button import androidx.compose.material3.CircularProgressIndicator @@ -29,6 +32,7 @@ import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Surface import androidx.compose.material3.Switch import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -39,6 +43,7 @@ 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.Recommendation import win.taptap.musicmanager.client.api.Song import win.taptap.musicmanager.client.store.AppState import win.taptap.musicmanager.client.store.AppStore @@ -188,25 +193,43 @@ fun MoodDetailScreen(state: AppState, store: AppStore) { } } - if (detail.recommendations.isNotEmpty()) { + if (mood.ytEnabled) { item { HorizontalDivider(Modifier.padding(vertical = 12.dp)) - SectionTitle("Recommendations") - } - items(detail.recommendations, key = { it.videoId }) { recommendation -> - Row( - modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Column(Modifier.weight(1f)) { - Text(recommendation.title, maxLines = 1, overflow = TextOverflow.Ellipsis) - Text( - recommendation.artist, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) + 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") + } } - Text(recommendation.state, style = MaterialTheme.typography.labelSmall) + } + } + + 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) } } } @@ -290,3 +313,71 @@ fun MoodDetailScreen(state: AppState, store: AppStore) { item { Spacer(Modifier.size(24.dp)) } } } + +@Composable +private fun RecommendationRow( + recommendation: Recommendation, + busy: Boolean, + store: AppStore, +) { + Row( + modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + RemoteImage(store, recommendation.thumbnail, Modifier.size(48.dp)) + Column(Modifier.weight(1f)) { + Text( + recommendation.title, + style = MaterialTheme.typography.bodyLarge, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Text( + buildString { + append(recommendation.artist) + recommendation.album?.takeIf { it.isNotBlank() }?.let { append(" · ").append(it) } + }, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Text( + when { + recommendation.state == "accepted" && recommendation.matchedSong != null -> "Seed added" + recommendation.state == "accepted" -> "Queued for download" + recommendation.matchedSong != null -> "In your library" + else -> "New" + }, + style = MaterialTheme.typography.labelSmall, + color = if (recommendation.state == "accepted") { + MaterialTheme.colorScheme.primary + } else { + MaterialTheme.colorScheme.onSurfaceVariant + }, + ) + } + if (recommendation.state == "accepted") { + Icon( + Icons.Rounded.Check, + contentDescription = "Accepted", + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(20.dp), + ) + } else { + IconButton( + onClick = { store.acceptRecommendation(recommendation.videoId) }, + enabled = !busy, + ) { + Icon(Icons.Rounded.Check, contentDescription = "Accept recommendation") + } + IconButton( + onClick = { store.rejectRecommendation(recommendation.videoId) }, + enabled = !busy, + ) { + Icon(Icons.Rounded.Close, contentDescription = "Reject recommendation") + } + } + } +} 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 1e70d4c..e8e5865 100644 --- a/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/AppStoreTest.kt +++ b/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/AppStoreTest.kt @@ -1,9 +1,16 @@ package win.taptap.musicmanager.client import io.ktor.client.engine.mock.MockEngine +import io.ktor.client.engine.mock.respond import io.ktor.client.engine.mock.respondError +import io.ktor.http.HttpHeaders import io.ktor.http.HttpStatusCode +import io.ktor.http.headersOf +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.delay +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.withContext import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest @@ -15,9 +22,12 @@ import kotlin.test.assertNull import kotlin.test.assertTrue import win.taptap.musicmanager.client.api.ApiClient import win.taptap.musicmanager.client.api.Song +import win.taptap.musicmanager.client.api.User import win.taptap.musicmanager.client.api.configuredHttpClient import win.taptap.musicmanager.client.data.CachedState import win.taptap.musicmanager.client.data.LibraryCache +import win.taptap.musicmanager.client.data.PlaybackSnapshot +import win.taptap.musicmanager.client.data.SessionState import win.taptap.musicmanager.client.playback.AudioPlayer import win.taptap.musicmanager.client.store.AppStore @@ -110,6 +120,134 @@ class AppStoreTest { store.release() } + + @Test + fun `bootstrap restores the saved queue and starts it on play`() = runTest { + val storage = MemoryStorage() + val cache = LibraryCache(storage) + cache.savePlayback( + PlaybackSnapshot( + queue = listOf(song("b")), + current = song("a"), + ), + ) + val player = FakePlayer() + val store = store(storage, cache, player) + runCurrent() + + val restored = store.state.value + assertEquals("a", restored.current?.id) + assertEquals(listOf("b"), restored.queue.map { it.id }) + assertFalse(restored.playing) + assertTrue(player.played.isEmpty()) + + store.togglePlayPause() + runCurrent() + + assertTrue(store.state.value.playing) + assertEquals(listOf("a"), player.played) + store.release() + } + + @Test + fun `accepting a recommendation replaces the selected mood`() = runTest { + val storage = MemoryStorage() + val cache = LibraryCache(storage) + cache.saveSession( + SessionState("http://music", "token", User("alice", admin = false)), + ) + val player = FakePlayer() + val detail = moodDetailJson(state = "new", seedCount = 1) + val acceptedDetail = moodDetailJson(state = "accepted", seedCount = 2) + val engine = MockEngine { request -> + when (request.url.encodedPath) { + "/api/v1/moods" -> respond("""{"moods":[]}""", HttpStatusCode.OK, jsonHeaders) + "/api/v1/library/songs" -> respond( + """{"songs":[],"revision":"r1"}""", + HttpStatusCode.OK, + jsonHeaders, + ) + "/api/v1/moods/mo-1" -> respond(detail, HttpStatusCode.OK, jsonHeaders) + "/api/v1/moods/mo-1/preview" -> respond( + """{"songs":[]}""", + HttpStatusCode.OK, + jsonHeaders, + ) + "/api/v1/moods/mo-1/recommendations/v-1/accept" -> respond( + """{"detail":$acceptedDetail,"recommendation":${recommendationJson("accepted")},"seedAdded":true}""", + HttpStatusCode.OK, + jsonHeaders, + ) + "/api/v1/moods/mo-1/recommendations/v-1/reject" -> respond( + """{"detail":$detail,"recommendation":${recommendationJson("rejected")},"seedAdded":false}""", + HttpStatusCode.OK, + jsonHeaders, + ) + else -> respondError(HttpStatusCode.NotFound) + } + } + val store = AppStore( + scope = this, + api = ApiClient(configuredHttpClient(engine)), + storage = storage, + player = player, + cache = cache, + ) + runCurrent() + store.openMood("mo-1") + awaitState { store.state.value.selectedMood != null || store.state.value.message != null } + + assertEquals( + "new", + store.state.value.selectedMood?.recommendations?.single()?.state, + "message=" + store.state.value.message, + ) + + store.acceptRecommendation("v-1") + awaitState { + store.state.value.selectedMood?.recommendations?.single()?.state == "accepted" + } + + val state = store.state.value + assertEquals("accepted", state.selectedMood?.recommendations?.single()?.state) + assertEquals(2, state.selectedMood?.mood?.seedCount) + assertEquals("Added to Focus", state.message) + assertFalse(state.messageIsError) + store.release() + } + + /** + * Ktor's mock engine responds on a real dispatcher, so queued test work has + * to be run between short real waits. + */ + private suspend fun TestScope.awaitState(predicate: () -> Boolean) { + repeat(500) { + runCurrent() + if (predicate()) return + withContext(Dispatchers.Default) { delay(10) } + } + throw AssertionError("state did not settle") + } + + private val jsonHeaders = headersOf(HttpHeaders.ContentType, "application/json") + + private fun moodJson(seedCount: Int) = """ + {"id":"mo-1","name":"Focus","targetSize":30,"refreshHours":24,"ytEnabled":true, + "createdAt":"2026-01-01T00:00:00Z","changedAt":"2026-01-01T00:00:00Z", + "seedCount":$seedCount,"newRecommendations":1} + """.trimIndent() + + private fun recommendationJson(state: String) = """ + {"videoId":"v-1","title":"Soft Light","artist":"Beta","duration":180, + "state":"$state","timesAdded":0, + "firstSeen":"2026-01-01T00:00:00Z","lastSeen":"2026-01-01T00:00:00Z", + "matchedSong":${song("a").let { """{"id":"${it.id}","title":"${it.title}","artist":"${it.artist}","album":"${it.album}","albumId":"${it.albumId}","duration":${it.duration},"bitRate":${it.bitRate},"size":${it.size},"suffix":"${it.suffix}","folderId":${it.folderId},"relativePath":"${it.relativePath}","updatedAt":"${it.updatedAt}"}""" }}} + """.trimIndent() + + private fun moodDetailJson(state: String, seedCount: Int) = """ + {"mood":${moodJson(seedCount)},"seeds":[],"recommendations":[${recommendationJson(state)}]} + """.trimIndent() + private fun kotlinx.coroutines.test.TestScope.store( storage: MemoryStorage, cache: LibraryCache,