feat: move the client to searchable, downloadable moods
CI / build (push) Successful in 3m28s
CI / play (push) Skipped

- new mood/song/search/recommendation models and API calls
- AppCache v2 with moods and details only
- Search and Downloads screens; remove Library and Longform
- new mood detail with songs, add music and recommendation states
- song-keyed covers and updated tests/docs
This commit is contained in:
TapTap committed 2026-11-15 21:37:39 +00:00
1 parent 1bb23901eb
commit dc270f863c
18 files changed
+1466 -1929

No files matched your search

+1 -1
View File
@@ -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 {
@@ -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() })
@@ -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
@@ -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"
}
}
File diff suppressed because it is too large. Load diff
@@ -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 = {
@@ -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,
)
@@ -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")
}
}
}
}
}
@@ -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")
}
}
}
}
@@ -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")
}
}
}
@@ -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") }
@@ -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(
@@ -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}",
)
}
}
}
@@ -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,
)
@@ -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)
}
}
@@ -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 {