feat: review YT recommendations and resume queues offline
CI / build (push) Successful in 1m56s

The mood screen now shows recommendation cards with thumbnails, a refresh
action, and accept/reject buttons. Accepting a library match adds it as a seed
immediately; other accepted tracks are marked as queued for download.

The player persists the session, queue and current track, restores them paused
on the next launch and starts the track on the next tap. While offline the
store retries the library sync with exponential backoff, downloads retry three
times before failing, and covers plus YT thumbnails are cached for the app's
lifetime.
This commit is contained in:
TapTap committed 2026-11-15 12:44:30 +00:00
1 parent 2234192dc7
commit dc719f3e1a
8 files changed
+510 -19

No files matched your search

+8 -1
View File
@@ -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: - Two add-to-mood actions in the player:
- **Add to current mood** (the mood of the active radio session) - **Add to current mood** (the mood of the active radio session)
- **Choose another mood** (picker) - **Choose another mood** (picker)
- YT Music recommendations in the mood editor: refresh on demand, accept or reject candidates, thumbnails, and a clear state for library matches (`Seed added`), accepted-for-download tracks 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. - 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. - **Sleep timer** (15/30/45/60/90 minutes) that pauses playback. On Android the pause is scheduled inside the media service, so it still fires when the app is backgrounded or the task is swiped away.
- Offline library cache: moods, songs and the last sync revision are stored locally. When the server is unreachable, downloaded tracks still play. - Offline library cache: moods, songs and the last sync revision are stored locally. When the server is unreachable, downloaded tracks still play.
- The play queue and current track are saved locally, so a restart reopens the player paused and resumes on the next tap.
- Reconnects automatically with exponential backoff (15s to 5min) while offline.
- Downloads retry up to three times before reporting an error; covers and YT thumbnails are cached for the app's lifetime.
- Original MP3 downloads with progress state, removal and storage usage. - Original MP3 downloads with progress state, removal and storage usage.
- Session persistence: the login survives app restarts until the token is revoked or expires. - Session persistence: the login survives app restarts until the token is revoked or expires.
- Android background playback through a Media3 `MediaSessionService`: notification, lock-screen and headset controls, audio focus, and playback that survives the app being backgrounded or the task being swiped away. - Android background playback through a Media3 `MediaSessionService`: notification, lock-screen and headset controls, audio focus, and playback that survives the app being backgrounded or the task being swiped away.
@@ -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. - **Mood cache** — mood details are stored so the app can open them offline.
- **Radio** — one session per mood, batches of 12, prefetch when the queue is short, no repeats within a session. - **Radio** — one session per mood, batches of 12, prefetch when the queue is short, no repeats within a session.
- **Downloads** — stored under the platform app directory, keyed by deterministic song ID. - **Downloads** — stored under the platform app directory, keyed by deterministic song ID.
- **Playback snapshot** — the session, upcoming queue 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. 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. - The media notification exposes play/pause and seeking. Queue actions (skip, add to mood) stay in the app because the mood session and its events belong to the server.
- Desktop playback cannot seek (sequential decoder); pause/resume and skipping work. MP3s are decoded to 16-bit PCM before the line is opened, because Java Sound has no line for the compressed format. - Desktop playback 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. - 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. - No iOS target yet. The shared module is ready for one.
@@ -5,6 +5,7 @@ import io.ktor.client.call.body
import io.ktor.client.engine.HttpClientEngine import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.plugins.HttpTimeout import io.ktor.client.plugins.HttpTimeout
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.plugins.timeout
import io.ktor.client.request.HttpRequestBuilder import io.ktor.client.request.HttpRequestBuilder
import io.ktor.client.request.delete import io.ktor.client.request.delete
import io.ktor.client.request.get import io.ktor.client.request.get
@@ -53,6 +54,7 @@ class ApiClient(private val http: HttpClient) {
private set private set
private val coverCache = mutableMapOf<String, ByteArray?>() private val coverCache = mutableMapOf<String, ByteArray?>()
private val imageCache = mutableMapOf<String, ByteArray?>()
suspend fun login( suspend fun login(
serverUrl: String, serverUrl: String,
@@ -79,6 +81,7 @@ class ApiClient(private val http: HttpClient) {
fun clear() { fun clear() {
token = null token = null
coverCache.clear() coverCache.clear()
imageCache.clear()
} }
suspend fun me(): User = get("/me") 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() } } requestNoContent { http.delete(url("/moods/$moodId/seeds/$songId")) { auth() } }
} }
suspend fun recommendations(moodId: String): List<Recommendation> =
get<RecommendationsResponse>("/moods/$moodId/recommendations").recommendations
suspend fun refreshRecommendations(moodId: String): MoodDetail =
parse(
http.post(url("/moods/$moodId/recommendations/refresh")) {
auth()
// yt-dlp searches a few queries in parallel; give the server room.
timeout {
requestTimeoutMillis = 120_000
socketTimeoutMillis = 120_000
}
},
)
suspend fun acceptRecommendation(moodId: String, videoId: String): RecommendationDecision =
parse(
http.post(url("/moods/$moodId/recommendations/$videoId/accept")) {
auth()
},
)
suspend fun rejectRecommendation(moodId: String, videoId: String): RecommendationDecision =
parse(
http.post(url("/moods/$moodId/recommendations/$videoId/reject")) {
auth()
},
)
suspend fun preview(moodId: String, limit: Int = 20): List<Song> = suspend fun preview(moodId: String, limit: Int = 20): List<Song> =
get<SearchResponse>("/moods/$moodId/preview?limit=$limit").songs get<SearchResponse>("/moods/$moodId/preview?limit=$limit").songs
@@ -208,10 +240,21 @@ class ApiClient(private val http: HttpClient) {
.bodyAsBytes() .bodyAsBytes()
}.getOrNull() }.getOrNull()
val result = bytes?.takeIf { it.isNotEmpty() } val result = bytes?.takeIf { it.isNotEmpty() }
if (coverCache.size > MAX_CACHED_IMAGES) coverCache.clear()
coverCache[key] = result coverCache[key] = result
return 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 = suspend fun download(songId: String): ByteArray =
http.get("$baseUrl/api/v1/songs/$songId/stream") { http.get("$baseUrl/api/v1/songs/$songId/stream") {
auth() 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 { private fun normalize(serverUrl: String): String {
var value = serverUrl.trim().trimEnd('/') var value = serverUrl.trim().trimEnd('/')
if (value.isEmpty()) value = "http://localhost:8080" if (value.isEmpty()) value = "http://localhost:8080"
@@ -104,6 +104,16 @@ data class MoodDetail(
@Serializable @Serializable
data class MoodsResponse(val moods: List<Mood>) data class MoodsResponse(val moods: List<Mood>)
@Serializable
data class RecommendationsResponse(val recommendations: List<Recommendation> = emptyList())
@Serializable
data class RecommendationDecision(
val detail: MoodDetail,
val recommendation: Recommendation,
val seedAdded: Boolean = false,
)
@Serializable @Serializable
data class LibraryPage( data class LibraryPage(
val songs: List<Song> = emptyList(), val songs: List<Song> = emptyList(),
@@ -4,6 +4,7 @@ import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json import kotlinx.serialization.json.Json
import win.taptap.musicmanager.client.api.Mood import win.taptap.musicmanager.client.api.Mood
import win.taptap.musicmanager.client.api.MoodDetail import win.taptap.musicmanager.client.api.MoodDetail
import win.taptap.musicmanager.client.api.Session
import win.taptap.musicmanager.client.api.Song import win.taptap.musicmanager.client.api.Song
import win.taptap.musicmanager.client.api.User import win.taptap.musicmanager.client.api.User
@@ -24,6 +25,14 @@ data class CachedState(
val moodDetails: List<MoodDetail> = emptyList(), val moodDetails: List<MoodDetail> = emptyList(),
) )
/** The queue survives a restart so the next launch can resume where it stopped. */
@Serializable
data class PlaybackSnapshot(
val session: Session? = null,
val queue: List<Song> = emptyList(),
val current: Song? = null,
)
class LibraryCache(private val storage: AppStorage) { class LibraryCache(private val storage: AppStorage) {
private val json = Json { private val json = Json {
@@ -50,12 +59,27 @@ class LibraryCache(private val storage: AppStorage) {
storage.write(CACHE_FILE, json.encodeToString(state)) storage.write(CACHE_FILE, json.encodeToString(state))
} }
fun loadPlayback(): PlaybackSnapshot? =
storage.read(PLAYBACK_FILE)?.let {
runCatching { json.decodeFromString<PlaybackSnapshot>(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() { fun clear() {
storage.delete(CACHE_FILE) storage.delete(CACHE_FILE)
storage.delete(PLAYBACK_FILE)
} }
private companion object { private companion object {
const val SESSION_FILE = "session.json" const val SESSION_FILE = "session.json"
const val CACHE_FILE = "library.json" const val CACHE_FILE = "library.json"
const val PLAYBACK_FILE = "playback.json"
} }
} }
@@ -26,6 +26,7 @@ import win.taptap.musicmanager.client.api.UpdateMoodRequest
import win.taptap.musicmanager.client.api.configuredHttpClient import win.taptap.musicmanager.client.api.configuredHttpClient
import win.taptap.musicmanager.client.data.CachedState import win.taptap.musicmanager.client.data.CachedState
import win.taptap.musicmanager.client.data.LibraryCache import win.taptap.musicmanager.client.data.LibraryCache
import win.taptap.musicmanager.client.data.PlaybackSnapshot
import win.taptap.musicmanager.client.data.SessionState import win.taptap.musicmanager.client.data.SessionState
import win.taptap.musicmanager.client.playback.AudioPlayer import win.taptap.musicmanager.client.playback.AudioPlayer
import win.taptap.musicmanager.client.platformName import win.taptap.musicmanager.client.platformName
@@ -56,6 +57,7 @@ data class AppState(
val searching: Boolean = false, val searching: Boolean = false,
val loading: Boolean = false, val loading: Boolean = false,
val saving: Boolean = false, val saving: Boolean = false,
val discovering: Boolean = false,
val message: String? = null, val message: String? = null,
val messageIsError: Boolean = false, val messageIsError: Boolean = false,
val messageId: Long = 0, val messageId: Long = 0,
@@ -77,6 +79,8 @@ class AppStore(
private var pollJob: Job? = null private var pollJob: Job? = null
private var sleepJob: Job? = null private var sleepJob: Job? = null
private var reconnectJob: Job? = null
private var playbackStarted = false
private var advancing = false private var advancing = false
private var fetching = false private var fetching = false
private var finishing = false private var finishing = false
@@ -89,6 +93,7 @@ class AppStore(
scope.launch { scope.launch {
val session = cache.loadSession() val session = cache.loadSession()
val cached = cache.load() val cached = cache.load()
val playback = cache.loadPlayback()
_state.update { _state.update {
it.copy( it.copy(
booting = false, booting = false,
@@ -96,6 +101,10 @@ class AppStore(
moods = cached.moods, moods = cached.moods,
library = cached.songs.sortedLibrary(), library = cached.songs.sortedLibrary(),
selectedMood = cached.moodDetails.firstOrNull(), selectedMood = cached.moodDetails.firstOrNull(),
session = playback?.session,
queue = playback?.queue.orEmpty(),
current = playback?.current,
durationSeconds = playback?.current?.duration?.toDouble() ?: 0.0,
) )
} }
@@ -157,7 +166,10 @@ class AppStore(
} }
fun refreshAll(silent: Boolean = false) { fun refreshAll(silent: Boolean = false) {
scope.launch { scope.launch { refreshAllNow(silent) }
}
private suspend fun refreshAllNow(silent: Boolean) {
if (!silent) _state.update { it.copy(loading = true) } if (!silent) _state.update { it.copy(loading = true) }
try { try {
val moods = api.moods() val moods = api.moods()
@@ -207,7 +219,7 @@ class AppStore(
} catch (t: Throwable) { } catch (t: Throwable) {
if (t is ApiException && t.status == 401) { if (t is ApiException && t.status == 401) {
logout() logout()
return@launch return
} }
_state.update { _state.update {
it.copy( it.copy(
@@ -218,7 +230,7 @@ class AppStore(
messageId = it.messageId + 1, messageId = it.messageId + 1,
) )
} }
} scheduleReconnect()
} }
} }
@@ -435,6 +447,7 @@ class AppStore(
) )
} }
playNext() playNext()
persistPlayback()
} catch (t: Throwable) { } catch (t: Throwable) {
val fallback = state.library.filter { it.id in state.downloads } val fallback = state.library.filter { it.id in state.downloads }
if (fallback.isNotEmpty()) { if (fallback.isNotEmpty()) {
@@ -469,6 +482,7 @@ class AppStore(
durationSeconds = song.duration.toDouble(), durationSeconds = song.duration.toDouble(),
) )
} }
persistPlayback()
startSong(song) startSong(song)
} }
} }
@@ -504,6 +518,7 @@ class AppStore(
val queue = if (shuffled) songs.shuffled(Random.Default) else songs val queue = if (shuffled) songs.shuffled(Random.Default) else songs
_state.update { it.copy(session = null, queue = queue) } _state.update { it.copy(session = null, queue = queue) }
playNext() 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() { fun togglePlayPause() {
val state = _state.value val state = _state.value
if (state.current == null) return val song = state.current ?: return
if (state.playing) { if (state.playing) {
player.pause() player.pause()
_state.update { it.copy(playing = false) } _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 { } else {
player.resume() player.resume()
_state.update { it.copy(playing = true) } _state.update { it.copy(playing = true) }
@@ -640,6 +721,8 @@ class AppStore(
scope.launch { scope.launch {
_state.update { it.copy(downloading = it.downloading + song.id) } _state.update { it.copy(downloading = it.downloading + song.id) }
var lastError: Throwable? = null
repeat(DOWNLOAD_ATTEMPTS) { attempt ->
try { try {
val bytes = api.download(song.id) val bytes = api.download(song.id)
val path = storage.saveDownload(song.id, bytes) val path = storage.saveDownload(song.id, bytes)
@@ -652,7 +735,8 @@ class AppStore(
messageId = it.messageId + 1, messageId = it.messageId + 1,
) )
} }
} else { return@launch
}
_state.update { _state.update {
it.copy( it.copy(
downloading = it.downloading - song.id, downloading = it.downloading - song.id,
@@ -662,13 +746,18 @@ class AppStore(
messageId = it.messageId + 1, messageId = it.messageId + 1,
) )
} }
} return@launch
} catch (t: Throwable) { } catch (t: Throwable) {
_state.update { it.copy(downloading = it.downloading - song.id) } lastError = t
message(t) if (attempt < DOWNLOAD_ATTEMPTS - 1) {
delay(1_000L * (attempt + 1))
} }
} }
} }
_state.update { it.copy(downloading = it.downloading - song.id) }
message(lastError ?: IllegalStateException("Download failed"))
}
}
fun clearDownloads() { fun clearDownloads() {
storage.listDownloads().keys.forEach(storage::deleteDownload) storage.listDownloads().keys.forEach(storage::deleteDownload)
@@ -697,6 +786,9 @@ class AppStore(
suspend fun cover(albumId: String): ByteArray? = api.cover(albumId, 320) 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 storageBytes(): Long = storage.storageUsedBytes()
fun canSeek(): Boolean = player.canSeek fun canSeek(): Boolean = player.canSeek
@@ -710,8 +802,10 @@ class AppStore(
} }
fun release() { fun release() {
persistPlayback()
pollJob?.cancel() pollJob?.cancel()
sleepJob?.cancel() sleepJob?.cancel()
reconnectJob?.cancel()
player.release() player.release()
} }
@@ -749,6 +843,7 @@ class AppStore(
durationSeconds = song.duration.toDouble(), durationSeconds = song.duration.toDouble(),
) )
} }
persistPlayback()
startSong(song) startSong(song)
report("started", song.id) report("started", song.id)
if (_state.value.queue.size < 3) prefetch() if (_state.value.queue.size < 3) prefetch()
@@ -791,6 +886,7 @@ class AppStore(
} }
return return
} }
playbackStarted = true
startPolling() startPolling()
} }
@@ -843,6 +939,8 @@ class AppStore(
pollJob?.cancel() pollJob?.cancel()
sleepJob?.cancel() sleepJob?.cancel()
sleepJob = null sleepJob = null
reconnectJob?.cancel()
playbackStarted = false
player.scheduleSleepTimer(null) player.scheduleSleepTimer(null)
player.stop() player.stop()
_state.update { _state.update {
@@ -854,6 +952,7 @@ class AppStore(
sleepTimerRemainingSeconds = null, sleepTimerRemainingSeconds = null,
) )
} }
cache.savePlayback(null)
} }
private fun cacheDetail(detail: MoodDetail) { private fun cacheDetail(detail: MoodDetail) {
@@ -862,6 +961,41 @@ class AppStore(
cache.save(cached.copy(moodDetails = details, moods = cached.moods)) 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) { private fun message(t: Throwable) {
_state.update { _state.update {
it.copy( it.copy(
@@ -880,3 +1014,7 @@ private fun Throwable.friendlyMessage(): String = when (this) {
private fun Collection<Song>.sortedLibrary(): List<Song> = private fun Collection<Song>.sortedLibrary(): List<Song> =
sortedWith(compareBy({ it.artist.lowercase() }, { it.album.lowercase() }, { it.trackNumber ?: 0 })) 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
@@ -91,6 +91,42 @@ fun Cover(
} }
} }
@Composable
fun RemoteImage(store: AppStore, url: String?, modifier: Modifier = Modifier) {
var bitmap by remember(url) { mutableStateOf<ImageBitmap?>(null) }
LaunchedEffect(url) {
if (url == null) return@LaunchedEffect
bitmap = store.image(url)?.let { data -> runCatching { decodeImage(data) }.getOrNull() }
}
Box(
modifier = modifier
.clip(RoundedCornerShape(10.dp))
.background(
Brush.linearGradient(listOf(Color(0xFF28344A), Color(0xFF1A2230))),
),
contentAlignment = Alignment.Center,
) {
val image = bitmap
if (image != null) {
Image(
bitmap = image,
contentDescription = null,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Crop,
)
} else {
Icon(
Icons.Rounded.MusicNote,
contentDescription = null,
tint = Color(0xFF5E6C84),
modifier = Modifier.size(20.dp),
)
}
}
}
@Composable @Composable
fun EmptyState(title: String, subtitle: String? = null, modifier: Modifier = Modifier) { fun EmptyState(title: String, subtitle: String? = null, modifier: Modifier = Modifier) {
Column( Column(
@@ -15,7 +15,10 @@ import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Add import androidx.compose.material.icons.rounded.Add
import androidx.compose.material.icons.rounded.Check
import androidx.compose.material.icons.rounded.Close
import androidx.compose.material.icons.rounded.PlayArrow import androidx.compose.material.icons.rounded.PlayArrow
import androidx.compose.material.icons.rounded.Refresh
import androidx.compose.material.icons.rounded.RemoveCircleOutline import androidx.compose.material.icons.rounded.RemoveCircleOutline
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.CircularProgressIndicator
@@ -29,6 +32,7 @@ import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface import androidx.compose.material3.Surface
import androidx.compose.material3.Switch import androidx.compose.material3.Switch
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf 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.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import win.taptap.musicmanager.client.api.Recommendation
import win.taptap.musicmanager.client.api.Song import win.taptap.musicmanager.client.api.Song
import win.taptap.musicmanager.client.store.AppState import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore import win.taptap.musicmanager.client.store.AppStore
@@ -188,25 +193,43 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
} }
} }
if (detail.recommendations.isNotEmpty()) { if (mood.ytEnabled) {
item { item {
HorizontalDivider(Modifier.padding(vertical = 12.dp)) HorizontalDivider(Modifier.padding(vertical = 12.dp))
SectionTitle("Recommendations") SectionTitle("Recommended for this mood") {
Row(verticalAlignment = Alignment.CenterVertically) {
if (state.discovering) {
CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
Spacer(Modifier.width(8.dp))
} }
items(detail.recommendations, key = { it.videoId }) { recommendation -> TextButton(
Row( onClick = { store.refreshRecommendations() },
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp), enabled = !state.discovering,
verticalAlignment = Alignment.CenterVertically,
) { ) {
Column(Modifier.weight(1f)) { Icon(Icons.Rounded.Refresh, contentDescription = null, modifier = Modifier.size(16.dp))
Text(recommendation.title, maxLines = 1, overflow = TextOverflow.Ellipsis) Spacer(Modifier.width(4.dp))
Text("Refresh")
}
}
}
}
val visible = detail.recommendations.filter { it.state != "rejected" }
if (visible.isEmpty()) {
item {
Text( Text(
recommendation.artist, if (state.discovering) {
"Searching YouTube Music..."
} else {
"No recommendations yet. Refresh to search for tracks that fit this mood."
},
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
} }
Text(recommendation.state, style = MaterialTheme.typography.labelSmall) } else {
items(visible, key = { "rec-${it.videoId}" }) { recommendation ->
RecommendationRow(recommendation, state.discovering, store)
} }
} }
} }
@@ -290,3 +313,71 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
item { Spacer(Modifier.size(24.dp)) } item { Spacer(Modifier.size(24.dp)) }
} }
} }
@Composable
private fun RecommendationRow(
recommendation: Recommendation,
busy: Boolean,
store: AppStore,
) {
Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
RemoteImage(store, recommendation.thumbnail, Modifier.size(48.dp))
Column(Modifier.weight(1f)) {
Text(
recommendation.title,
style = MaterialTheme.typography.bodyLarge,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
buildString {
append(recommendation.artist)
recommendation.album?.takeIf { it.isNotBlank() }?.let { append(" · ").append(it) }
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
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")
}
}
}
}
@@ -1,9 +1,16 @@
package win.taptap.musicmanager.client package win.taptap.musicmanager.client
import io.ktor.client.engine.mock.MockEngine import io.ktor.client.engine.mock.MockEngine
import io.ktor.client.engine.mock.respond
import io.ktor.client.engine.mock.respondError import io.ktor.client.engine.mock.respondError
import io.ktor.http.HttpHeaders
import io.ktor.http.HttpStatusCode import io.ktor.http.HttpStatusCode
import io.ktor.http.headersOf
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.withContext
import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.runTest
@@ -15,9 +22,12 @@ import kotlin.test.assertNull
import kotlin.test.assertTrue import kotlin.test.assertTrue
import win.taptap.musicmanager.client.api.ApiClient import win.taptap.musicmanager.client.api.ApiClient
import win.taptap.musicmanager.client.api.Song import win.taptap.musicmanager.client.api.Song
import win.taptap.musicmanager.client.api.User
import win.taptap.musicmanager.client.api.configuredHttpClient import win.taptap.musicmanager.client.api.configuredHttpClient
import win.taptap.musicmanager.client.data.CachedState import win.taptap.musicmanager.client.data.CachedState
import win.taptap.musicmanager.client.data.LibraryCache import win.taptap.musicmanager.client.data.LibraryCache
import win.taptap.musicmanager.client.data.PlaybackSnapshot
import win.taptap.musicmanager.client.data.SessionState
import win.taptap.musicmanager.client.playback.AudioPlayer import win.taptap.musicmanager.client.playback.AudioPlayer
import win.taptap.musicmanager.client.store.AppStore import win.taptap.musicmanager.client.store.AppStore
@@ -110,6 +120,134 @@ class AppStoreTest {
store.release() store.release()
} }
@Test
fun `bootstrap restores the saved queue and starts it on play`() = runTest {
val storage = MemoryStorage()
val cache = LibraryCache(storage)
cache.savePlayback(
PlaybackSnapshot(
queue = listOf(song("b")),
current = song("a"),
),
)
val player = FakePlayer()
val store = store(storage, cache, player)
runCurrent()
val restored = store.state.value
assertEquals("a", restored.current?.id)
assertEquals(listOf("b"), restored.queue.map { it.id })
assertFalse(restored.playing)
assertTrue(player.played.isEmpty())
store.togglePlayPause()
runCurrent()
assertTrue(store.state.value.playing)
assertEquals(listOf("a"), player.played)
store.release()
}
@Test
fun `accepting a recommendation replaces the selected mood`() = runTest {
val storage = MemoryStorage()
val cache = LibraryCache(storage)
cache.saveSession(
SessionState("http://music", "token", User("alice", admin = false)),
)
val player = FakePlayer()
val detail = moodDetailJson(state = "new", seedCount = 1)
val acceptedDetail = moodDetailJson(state = "accepted", seedCount = 2)
val engine = MockEngine { request ->
when (request.url.encodedPath) {
"/api/v1/moods" -> respond("""{"moods":[]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/library/songs" -> respond(
"""{"songs":[],"revision":"r1"}""",
HttpStatusCode.OK,
jsonHeaders,
)
"/api/v1/moods/mo-1" -> respond(detail, HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1/preview" -> respond(
"""{"songs":[]}""",
HttpStatusCode.OK,
jsonHeaders,
)
"/api/v1/moods/mo-1/recommendations/v-1/accept" -> respond(
"""{"detail":$acceptedDetail,"recommendation":${recommendationJson("accepted")},"seedAdded":true}""",
HttpStatusCode.OK,
jsonHeaders,
)
"/api/v1/moods/mo-1/recommendations/v-1/reject" -> respond(
"""{"detail":$detail,"recommendation":${recommendationJson("rejected")},"seedAdded":false}""",
HttpStatusCode.OK,
jsonHeaders,
)
else -> respondError(HttpStatusCode.NotFound)
}
}
val store = AppStore(
scope = this,
api = ApiClient(configuredHttpClient(engine)),
storage = storage,
player = player,
cache = cache,
)
runCurrent()
store.openMood("mo-1")
awaitState { store.state.value.selectedMood != null || store.state.value.message != null }
assertEquals(
"new",
store.state.value.selectedMood?.recommendations?.single()?.state,
"message=" + store.state.value.message,
)
store.acceptRecommendation("v-1")
awaitState {
store.state.value.selectedMood?.recommendations?.single()?.state == "accepted"
}
val state = store.state.value
assertEquals("accepted", state.selectedMood?.recommendations?.single()?.state)
assertEquals(2, state.selectedMood?.mood?.seedCount)
assertEquals("Added to Focus", state.message)
assertFalse(state.messageIsError)
store.release()
}
/**
* Ktor's mock engine responds on a real dispatcher, so queued test work has
* to be run between short real waits.
*/
private suspend fun TestScope.awaitState(predicate: () -> Boolean) {
repeat(500) {
runCurrent()
if (predicate()) return
withContext(Dispatchers.Default) { delay(10) }
}
throw AssertionError("state did not settle")
}
private val jsonHeaders = headersOf(HttpHeaders.ContentType, "application/json")
private fun moodJson(seedCount: Int) = """
{"id":"mo-1","name":"Focus","targetSize":30,"refreshHours":24,"ytEnabled":true,
"createdAt":"2026-01-01T00:00:00Z","changedAt":"2026-01-01T00:00:00Z",
"seedCount":$seedCount,"newRecommendations":1}
""".trimIndent()
private fun recommendationJson(state: String) = """
{"videoId":"v-1","title":"Soft Light","artist":"Beta","duration":180,
"state":"$state","timesAdded":0,
"firstSeen":"2026-01-01T00:00:00Z","lastSeen":"2026-01-01T00:00:00Z",
"matchedSong":${song("a").let { """{"id":"${it.id}","title":"${it.title}","artist":"${it.artist}","album":"${it.album}","albumId":"${it.albumId}","duration":${it.duration},"bitRate":${it.bitRate},"size":${it.size},"suffix":"${it.suffix}","folderId":${it.folderId},"relativePath":"${it.relativePath}","updatedAt":"${it.updatedAt}"}""" }}}
""".trimIndent()
private fun moodDetailJson(state: String, seedCount: Int) = """
{"mood":${moodJson(seedCount)},"seeds":[],"recommendations":[${recommendationJson(state)}]}
""".trimIndent()
private fun kotlinx.coroutines.test.TestScope.store( private fun kotlinx.coroutines.test.TestScope.store(
storage: MemoryStorage, storage: MemoryStorage,
cache: LibraryCache, cache: LibraryCache,