4 Commits
Author SHA1 Message Date
TapTap cfab559e5e fix: keep the dragged queue row opaque
CI / build (push) Successful in 11m56s
CI / play (push) Successful in 3m16s
2026-11-17 08:55:38 +00:00
TapTap a63ee62673 feat: drag-to-reorder queue and a compact mobile player
CI / build (push) Successful in 4m51s
CI / play (push) Skipped
- long-press and drag queue rows, with auto-scroll near the edges
- pin the now-playing row above the upcoming queue
- move add-to-mood actions into an overflow menu so the title and
  artist get the full width on narrow phones
2026-11-17 08:54:23 +00:00
TapTap 3b40726edb feat: choose Deezer or YouTube Music per mood
CI / build (push) Successful in 3m35s
CI / play (push) Skipped
- models carry source and externalId instead of videoId
- AppCache v3 discards the old shape
- source selector in the create dialog, mood settings and search screen
- switching source patches the mood and re-runs the search
- client requests ten catalog results with a 60s timeout
2026-11-17 07:32:40 +00:00
TapTap 96ab25a91d feat: search YouTube Music and poll for the first recommendation batch
CI / build (push) Successful in 12m2s
CI / play (push) Successful in 3m18s
- label and document the YouTube Music search source
- allow up to 60s for a search and request ten results
- keep refreshing a new mood until its first recommendations arrive
2026-11-16 18:38:58 +00:00
15 changed files with 558 additions and 118 deletions

No files matched your search

+21 -10
View File
@@ -5,7 +5,7 @@ self-hosted music server.
The client and server are designed together. There is no OpenSubsonic
compatibility layer: the app speaks the native `/api/v1` API, where playback is
a server-driven radio session and songs are added by searching YouTube.
a server-driven radio session and songs are added from Deezer or YouTube Music.
## Targets
@@ -22,8 +22,9 @@ a server-driven radio session and songs are added by searching YouTube.
- **Moods** are the only content model. Each user sees only their own moods.
- **Songs** belong to the mood's permanent collection. A mood needs at least one
song before it can play.
- **Search YouTube** from inside a mood or globally with a mood picker. Tracks
over 10 minutes are hidden. Results that are already downloaded are marked and
- **Search Deezer or YouTube Music** from inside a mood or globally with a mood
picker. Each mood has a **Download source** selector; search, recommendations
and downloads follow it. Tracks over 10 minutes are hidden. Results that are already downloaded are marked and
add instantly; other videos are queued for server-side download.
- **Paste a YouTube URL** to add a specific video.
- **Recommendations** are downloaded automatically and play in the radio without
@@ -39,10 +40,13 @@ a server-driven radio session and songs are added by searching YouTube.
- Two add-to-mood actions in the player:
- **Add to current mood** (the mood of the active radio session)
- **Choose another mood** (picker)
- A queue sheet from the player: the current track plus every upcoming track,
with move up/down and remove. Changes are persisted locally.
- A queue sheet from the player: the current track is pinned, upcoming tracks
can be reordered by **long-press and drag** or removed. Changes are persisted
locally.
- **Previous** from the player: after two seconds of playback it restarts the
current track; before that it restores the last played track.
- The bottom player keeps the cover and title/artist readable on narrow phones;
add-to-mood actions moved into the overflow menu.
- **Scrubbing**: the progress slider can be dragged on every platform. Android and
web seek natively; desktop restarts the decoder at the requested position.
- **Mood settings**: name, description, discovery hint, genres, collection share,
@@ -69,7 +73,8 @@ a server-driven radio session and songs are added by searching YouTube.
- **Moods** — grid with song and pick counts, create, global search.
- **Mood Detail** — songs, add music, recommendations, next batch, settings.
- **Search** — mood picker, YouTube search, paste URL, downloaded badges.
- **Search** — mood picker, source selector, catalog search, paste URL,
downloaded badges.
- **Downloads** — offline files and storage usage.
- **Settings** — account, server URL, offline storage, sign out.
@@ -191,7 +196,7 @@ Tagged builds (`v*`) publish to internal testing from CI. The Gitea secrets are:
| `ANDROID_KEY_PASSWORD` | key password |
| `PLAY_SERVICE_ACCOUNT_JSON` | contents of the service account JSON |
Then `git tag v0.2.0 && git push --tags` builds, signs and uploads the bundle.
Then `git tag v0.3.0 && git push --tags` builds, signs and uploads the bundle.
Gradle Play Publisher asks Play for the next free `versionCode`
(`ResolutionStrategy.AUTO`), so only the tag/version name needs to change.
@@ -204,7 +209,8 @@ it. It owns:
- **Mood sync** — GET `/moods` on login/refresh; details are fetched when a mood
is opened and cached.
- **Mood cache** — cached details power offline mood lists and downloads.
- **Search** — debounced remote YouTube search with the selected target mood.
- **Search** — debounced remote catalog search with the selected target mood and
its source.
- **Radio** — one session per mood, batches of 12, prefetch when the queue is
short, no repeats within a session.
- **Downloads** — stored under the platform app directory, keyed by the shared
@@ -264,6 +270,11 @@ scripts/build-ci-image.sh 3
streams and caches metadata.
- Downloads store the 320 px cover next to the MP3 (`<songId>.jpg`), so the
in-app cover and the Android notification artwork survive without the server.
- Search and downloads depend on `yt-dlp` on the server. YouTube bot checks can
fail a search (`502`) or leave a recommendation in `failed` with Retry.
- Search and downloads depend on the server's catalogs. YouTube bot checks can
fail a YouTube Music search (`502`) or leave a recommendation in `failed`
with Retry. Music search resolves every result for its artist/album/duration,
so a YouTube Music search takes roughly 10–15 seconds for ten results;
Deezer search is much faster.
- Deezer downloads need `DEEZER_ARL` on the server. A Free ARL is limited to
128 kbps; Premium enables 320 kbps. The client never stores the ARL.
- No iOS target yet. The shared module is ready for one.
+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.2.0"
?: "0.3.0"
kotlin {
androidTarget {
@@ -125,14 +125,22 @@ class ApiClient(private val http: HttpClient) {
suspend fun addSong(
moodId: String,
songId: String? = null,
videoId: String? = null,
source: String? = null,
externalId: String? = null,
url: String? = null,
): AddSongResponse =
parse(
http.post(url("/moods/$moodId/songs")) {
auth()
contentType(ContentType.Application.Json)
setBody(AddSongRequest(songId = songId, videoId = videoId, url = url))
setBody(
AddSongRequest(
songId = songId,
source = source,
externalId = externalId,
url = url,
),
)
},
)
@@ -155,23 +163,23 @@ class ApiClient(private val http: HttpClient) {
},
)
suspend fun addRecommendation(moodId: String, videoId: String): RecommendationDecision =
suspend fun addRecommendation(moodId: String, externalId: String): RecommendationDecision =
parse(
http.post(url("/moods/$moodId/recommendations/$videoId/add")) {
http.post(url("/moods/$moodId/recommendations/$externalId/add")) {
auth()
},
)
suspend fun rejectRecommendation(moodId: String, videoId: String): RecommendationDecision =
suspend fun rejectRecommendation(moodId: String, externalId: String): RecommendationDecision =
parse(
http.post(url("/moods/$moodId/recommendations/$videoId/reject")) {
http.post(url("/moods/$moodId/recommendations/$externalId/reject")) {
auth()
},
)
suspend fun retryRecommendation(moodId: String, videoId: String): MoodDetail =
suspend fun retryRecommendation(moodId: String, externalId: String): MoodDetail =
parse(
http.post(url("/moods/$moodId/recommendations/$videoId/retry")) {
http.post(url("/moods/$moodId/recommendations/$externalId/retry")) {
auth()
},
)
@@ -179,9 +187,25 @@ class ApiClient(private val http: HttpClient) {
suspend fun preview(moodId: String, limit: Int = 20): List<Song> =
get<TracksResponse>("/moods/$moodId/preview?limit=$limit").songs
suspend fun search(query: String, limit: Int = 20, moodId: String? = null): List<SearchResult> {
suspend fun search(
query: String,
limit: Int = 10,
source: String? = null,
moodId: String? = null,
): List<SearchResult> {
val sourceParam = source?.let { "&source=${it.encodeURLParameter()}" }.orEmpty()
val mood = moodId?.let { "&moodId=${it.encodeURLParameter()}" }.orEmpty()
return get<SearchResponse>("/search?q=${query.encodeURLParameter()}&limit=$limit$mood").results
return parse<SearchResponse>(
http.get(url("/search?q=${query.encodeURLParameter()}&limit=$limit$sourceParam$mood")) {
auth()
// yt-dlp resolves every YouTube Music hit to get artist, album
// and duration, so a search takes longer than a plain API call.
timeout {
requestTimeoutMillis = 60_000
socketTimeoutMillis = 60_000
}
},
).results
}
suspend fun startSession(moodId: String, limit: Int = 12): Session =
@@ -35,7 +35,8 @@ data class LoginResponse(
@Serializable
data class Song(
val id: String,
val videoId: String,
val source: String = "youtube",
val externalId: String,
val title: String,
val artist: String,
val album: String? = null,
@@ -55,6 +56,7 @@ data class Mood(
val description: String? = null,
val query: String? = null,
val genres: List<String> = emptyList(),
val source: String = "youtube",
val collectionPercent: Int = 50,
val recommendationPercent: Int = 50,
val recommendationCount: Int = 10,
@@ -86,7 +88,8 @@ data class Download(
@Serializable
data class Recommendation(
val videoId: String,
val source: String = "youtube",
val externalId: String,
val title: String,
val artist: String,
val album: String? = null,
@@ -121,7 +124,8 @@ data class RecommendationDecision(
@Serializable
data class SearchResult(
val videoId: String,
val source: String = "youtube",
val externalId: String,
val title: String,
val artist: String,
val album: String? = null,
@@ -180,7 +184,8 @@ data class AddToMoodResponse(val mood: Mood, val added: Boolean)
@Serializable
data class AddSongRequest(
val songId: String? = null,
val videoId: String? = null,
val source: String? = null,
val externalId: String? = null,
val url: String? = null,
)
@@ -197,6 +202,7 @@ data class CreateMoodRequest(
val description: String? = null,
val query: String? = null,
val genres: List<String> = emptyList(),
val source: String? = null,
val collectionPercent: Int = 50,
val recommendationCount: Int = 10,
val refreshHours: Int = 24,
@@ -210,6 +216,7 @@ data class UpdateMoodRequest(
val query: String? = null,
val clearQuery: Boolean = false,
val genres: List<String>? = null,
val source: String? = null,
val collectionPercent: Int? = null,
val recommendationCount: Int? = null,
val refreshHours: Int? = null,
@@ -16,8 +16,8 @@ data class SessionState(
)
/**
* Offline cache. Version 2 holds moods and their details only; the old
* mounted-library shape is discarded instead of silently mis-decoding.
* Offline cache. Version 3 adds the download source and the source-neutral
* external track id; older shapes are discarded instead of mis-decoding.
*/
@Serializable
data class CachedState(
@@ -28,7 +28,7 @@ data class CachedState(
val moodDetails: List<MoodDetail> = emptyList(),
) {
companion object {
const val CACHE_VERSION = 2
const val CACHE_VERSION = 3
}
}
@@ -363,7 +363,15 @@ class AppStore(
delay(SEARCH_DEBOUNCE_MS)
_state.update { it.copy(searching = true) }
try {
val results = api.search(query, 20, _state.value.searchTargetMoodId)
val target = _state.value.moods.firstOrNull {
it.id == _state.value.searchTargetMoodId
}
val results = api.search(
query,
SEARCH_LIMIT,
source = target?.source ?: DEFAULT_SOURCE,
moodId = _state.value.searchTargetMoodId,
)
_state.update { it.copy(searchResults = results) }
} catch (t: CancellationException) {
throw t
@@ -393,7 +401,11 @@ class AppStore(
val response = if (result.songId != null) {
api.addSong(target, songId = result.songId)
} else {
api.addSong(target, videoId = result.videoId)
api.addSong(
target,
source = result.source,
externalId = result.externalId,
)
}
applyMoodDetail(response.detail)
val title = response.detail.mood.name
@@ -451,6 +463,7 @@ class AppStore(
description: String?,
genres: List<String>,
query: String?,
source: String,
collectionPercent: Int,
recommendationCount: Int,
refreshHours: Int,
@@ -464,6 +477,7 @@ class AppStore(
description = description?.takeIf { it.isNotBlank() },
query = query?.takeIf { it.isNotBlank() },
genres = genres,
source = source,
collectionPercent = collectionPercent,
recommendationCount = recommendationCount,
refreshHours = refreshHours,
@@ -495,12 +509,42 @@ class AppStore(
}
}
/**
* Changes the mood's catalog. The server clears the active recommendation
* pool and refills it from the new source; permanent songs stay.
*/
fun setMoodSource(moodId: String, source: String) {
val current = _state.value.moods.firstOrNull { it.id == moodId } ?: return
if (current.source == source) return
scope.launch {
try {
val updated = api.updateMood(moodId, UpdateMoodRequest(source = source))
applyMoodDetail(updated)
_state.update {
it.copy(
message = "Download source changed to ${sourceLabel(source)}",
messageIsError = false,
messageId = it.messageId + 1,
)
}
if (_state.value.searchTargetMoodId == moodId &&
_state.value.searchQuery.isNotBlank()
) {
search(_state.value.searchQuery)
}
} catch (t: Throwable) {
message(t)
}
}
}
fun saveMood(
detail: MoodDetail,
name: String,
description: String?,
genres: List<String>,
query: String?,
source: String,
collectionPercent: Int,
recommendationCount: Int,
refreshHours: Int,
@@ -517,6 +561,7 @@ class AppStore(
query = query ?: "",
clearQuery = query.isNullOrBlank(),
genres = genres,
source = source,
collectionPercent = collectionPercent,
recommendationCount = recommendationCount,
refreshHours = refreshHours,
@@ -612,13 +657,13 @@ class AppStore(
}
}
fun addRecommendation(videoId: String) {
fun addRecommendation(externalId: String) {
val moodId = _state.value.selectedMood?.mood?.id ?: return
if (_state.value.discovering) return
scope.launch {
_state.update { it.copy(discovering = true) }
try {
val decision = api.addRecommendation(moodId, videoId)
val decision = api.addRecommendation(moodId, externalId)
applyMoodDetail(decision.detail)
if (decision.recommendation.song == null) {
pollUntilSongCount(decision.detail.mood.id, decision.detail.mood.songCount + 1)
@@ -642,13 +687,13 @@ class AppStore(
}
}
fun rejectRecommendation(videoId: String) {
fun rejectRecommendation(externalId: String) {
val moodId = _state.value.selectedMood?.mood?.id ?: return
if (_state.value.discovering) return
scope.launch {
_state.update { it.copy(discovering = true) }
try {
val decision = api.rejectRecommendation(moodId, videoId)
val decision = api.rejectRecommendation(moodId, externalId)
applyMoodDetail(decision.detail)
_state.update {
it.copy(
@@ -665,11 +710,11 @@ class AppStore(
}
}
fun retryRecommendation(videoId: String) {
fun retryRecommendation(externalId: String) {
val moodId = _state.value.selectedMood?.mood?.id ?: return
scope.launch {
try {
val detail = api.retryRecommendation(moodId, videoId)
val detail = api.retryRecommendation(moodId, externalId)
applyMoodDetail(detail)
_state.update {
it.copy(
@@ -1357,5 +1402,10 @@ private const val DOWNLOAD_ATTEMPTS = 3
private const val PROGRESS_POLL_TICKS = 12
private const val MAX_HISTORY = 50
private const val SEARCH_DEBOUNCE_MS = 300L
private const val SEARCH_LIMIT = 10
private const val DEFAULT_SOURCE = "deezer"
internal fun sourceLabel(source: String): String =
if (source == "deezer") "Deezer" else "YouTube Music"
private const val DOWNLOAD_POLL_MS = 4_000L
private const val DOWNLOAD_POLLS = 60
@@ -113,7 +113,8 @@ fun DownloadsScreen(state: AppState, store: AppStore) {
store.toggleDownload(
win.taptap.musicmanager.client.api.Song(
id = id,
videoId = id,
source = "youtube",
externalId = id,
title = id,
artist = "",
duration = 0,
@@ -1,6 +1,7 @@
package win.taptap.musicmanager.client.ui
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
@@ -24,11 +25,14 @@ 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.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.FilledTonalButton
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
@@ -50,6 +54,7 @@ import win.taptap.musicmanager.client.api.MoodSong
import win.taptap.musicmanager.client.api.Recommendation
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
import win.taptap.musicmanager.client.store.sourceLabel
@Composable
fun MoodDetailScreen(state: AppState, store: AppStore) {
@@ -76,6 +81,8 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
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 source by remember(mood.id) { mutableStateOf(mood.source) }
var sourceMenu by remember { mutableStateOf(false) }
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()) }
@@ -84,9 +91,12 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
detail.recommendations.count {
it.download?.state == "queued" || it.download?.state == "downloading"
}
LaunchedEffect(mood.id, inFlight) {
// A new mood gets its first batch from a background discovery run, which
// resolves the YouTube Music search. Keep refreshing until it lands.
val waitingForFirstBatch = mood.recommendationCount > 0 && detail.recommendations.isEmpty()
LaunchedEffect(mood.id, inFlight, waitingForFirstBatch) {
var polls = 0
while (inFlight > 0 && polls < 60) {
while ((inFlight > 0 || waitingForFirstBatch) && polls < 60) {
kotlinx.coroutines.delay(5_000)
store.refreshSelectedMood()
polls += 1
@@ -228,7 +238,7 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
)
}
} else {
items(detail.recommendations, key = { "rec-${it.videoId}" }) { recommendation ->
items(detail.recommendations, key = { "rec-${it.source}-${it.externalId}" }) { recommendation ->
RecommendationRow(recommendation, state.discovering, store)
}
}
@@ -268,6 +278,45 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f)) {
Text("Download source", style = MaterialTheme.typography.bodyMedium)
Text(
"Search, recommendations and downloads use this catalog.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Box {
OutlinedButton(onClick = { sourceMenu = true }) {
Text(sourceLabel(source))
}
DropdownMenu(
expanded = sourceMenu,
onDismissRequest = { sourceMenu = false },
) {
listOf("deezer", "youtube").forEach { option ->
DropdownMenuItem(
text = { Text(sourceLabel(option)) },
onClick = {
sourceMenu = false
source = option
},
)
}
}
}
}
if (source != mood.source) {
Text(
"Changing the source clears active recommendations and refills them.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.tertiary,
)
}
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(
"Collection share: ${collectionPercent.roundToInt()}% · ${100 - collectionPercent.roundToInt()}% recommendations",
@@ -318,6 +367,7 @@ 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() },
source = source,
collectionPercent = collectionPercent.roundToInt(),
recommendationCount = recommendations.roundToInt(),
refreshHours = hours.toIntOrNull() ?: mood.refreshHours,
@@ -415,21 +465,21 @@ private fun RecommendationRow(
}
if (failed) {
IconButton(
onClick = { store.retryRecommendation(recommendation.videoId) },
onClick = { store.retryRecommendation(recommendation.externalId) },
enabled = !busy,
) {
Icon(Icons.Rounded.Refresh, contentDescription = "Retry download")
}
} else {
IconButton(
onClick = { store.addRecommendation(recommendation.videoId) },
onClick = { store.addRecommendation(recommendation.externalId) },
enabled = !busy,
) {
Icon(Icons.Rounded.Add, contentDescription = "Add to mood")
}
}
IconButton(
onClick = { store.rejectRecommendation(recommendation.videoId) },
onClick = { store.rejectRecommendation(recommendation.externalId) },
enabled = !busy,
) {
Icon(Icons.Rounded.Close, contentDescription = "Not interested")
@@ -27,9 +27,12 @@ import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
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.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
@@ -50,6 +53,7 @@ import kotlin.math.roundToInt
import win.taptap.musicmanager.client.api.Mood
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
import win.taptap.musicmanager.client.store.sourceLabel
@Composable
fun MoodsScreen(state: AppState, store: AppStore) {
@@ -115,9 +119,18 @@ fun MoodsScreen(state: AppState, store: AppStore) {
CreateMoodDialog(
saving = state.saving,
onDismiss = { creating = false },
onCreate = { name, description, genres, query, collectionPercent, recommendations, hours ->
onCreate = { name, description, genres, query, source, collectionPercent, recommendations, hours ->
creating = false
store.createMood(name, description, genres, query, collectionPercent, recommendations, hours)
store.createMood(
name,
description,
genres,
query,
source,
collectionPercent,
recommendations,
hours,
)
},
)
}
@@ -165,6 +178,12 @@ private fun MoodCard(mood: Mood, onOpen: () -> Unit, onPlay: () -> Unit) {
color = Color.White.copy(alpha = 0.85f),
)
}
Spacer(Modifier.width(8.dp))
Text(
sourceLabel(mood.source),
style = MaterialTheme.typography.labelMedium,
color = Color.White.copy(alpha = 0.7f),
)
Spacer(Modifier.weight(1f))
FilledTonalButton(
onClick = onPlay,
@@ -187,12 +206,14 @@ private fun MoodCard(mood: Mood, onOpen: () -> Unit, onPlay: () -> Unit) {
private fun CreateMoodDialog(
saving: Boolean,
onDismiss: () -> Unit,
onCreate: (String, String?, List<String>, String?, Int, Int, Int) -> Unit,
onCreate: (String, String?, List<String>, 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 source by remember { mutableStateOf("deezer") }
var sourceMenu by remember { mutableStateOf(false) }
var collectionPercent by remember { mutableStateOf(50f) }
var recommendations by remember { mutableStateOf(10f) }
var hours by remember { mutableStateOf("24") }
@@ -229,6 +250,35 @@ private fun CreateMoodDialog(
label = { Text("Discovery hint") },
singleLine = true,
)
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
"Download source",
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.weight(1f),
)
Box {
OutlinedButton(onClick = { sourceMenu = true }) {
Text(sourceLabel(source))
}
DropdownMenu(
expanded = sourceMenu,
onDismissRequest = { sourceMenu = false },
) {
listOf("deezer", "youtube").forEach { option ->
DropdownMenuItem(
text = { Text(sourceLabel(option)) },
onClick = {
sourceMenu = false
source = option
},
)
}
}
}
}
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(
"Collection share: ${collectionPercent.roundToInt()}% · ${100 - collectionPercent.roundToInt()}% recommendations",
@@ -270,6 +320,7 @@ private fun CreateMoodDialog(
description.trim().takeIf { it.isNotEmpty() },
genres.split(',').map { it.trim() }.filter { it.isNotEmpty() },
query.trim().takeIf { it.isNotEmpty() },
source,
collectionPercent.roundToInt(),
recommendations.roundToInt(),
hours.toIntOrNull() ?: 24,
@@ -1,11 +1,15 @@
package win.taptap.musicmanager.client.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress
import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
@@ -13,13 +17,14 @@ import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.AddCircleOutline
import androidx.compose.material.icons.rounded.Bedtime
import androidx.compose.material.icons.rounded.Close
import androidx.compose.material.icons.rounded.KeyboardArrowDown
import androidx.compose.material.icons.rounded.KeyboardArrowUp
import androidx.compose.material.icons.rounded.DragHandle
import androidx.compose.material.icons.rounded.MoreVert
import androidx.compose.material.icons.rounded.Pause
import androidx.compose.material.icons.rounded.PlayArrow
import androidx.compose.material.icons.rounded.PlaylistAdd
@@ -37,23 +42,33 @@ import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.zIndex
import kotlinx.coroutines.delay
import kotlin.math.roundToInt
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
private val QUEUE_ROW_HEIGHT = 58.dp
@Composable
fun PlayerBar(state: AppState, store: AppStore) {
val song = state.current ?: return
var picker by remember { mutableStateOf(false) }
var sleepMenu by remember { mutableStateOf(false) }
var moreMenu by remember { mutableStateOf(false) }
var queueOpen by remember { mutableStateOf(false) }
var dragSeconds by remember(song.id) { mutableStateOf<Float?>(null) }
val sleepRemaining = state.sleepTimerRemainingSeconds
@@ -90,6 +105,36 @@ fun PlayerBar(state: AppState, store: AppStore) {
IconButton(onClick = { queueOpen = true }) {
Icon(Icons.Rounded.QueueMusic, contentDescription = "Queue")
}
Box {
IconButton(onClick = { moreMenu = true }) {
Icon(Icons.Rounded.MoreVert, contentDescription = "More actions")
}
DropdownMenu(
expanded = moreMenu,
onDismissRequest = { moreMenu = false },
) {
DropdownMenuItem(
text = { Text("Add to current mood") },
leadingIcon = {
Icon(Icons.Rounded.AddCircleOutline, contentDescription = null)
},
onClick = {
moreMenu = false
store.addCurrentToMood(null)
},
)
DropdownMenuItem(
text = { Text("Add to another mood") },
leadingIcon = {
Icon(Icons.Rounded.PlaylistAdd, contentDescription = null)
},
onClick = {
moreMenu = false
picker = true
},
)
}
}
Box {
IconButton(onClick = { sleepMenu = true }) {
Icon(
@@ -130,9 +175,11 @@ fun PlayerBar(state: AppState, store: AppStore) {
}
Row(
modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 8.dp, bottom = 8.dp),
modifier = Modifier
.fillMaxWidth()
.padding(start = 12.dp, end = 8.dp, bottom = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
horizontalArrangement = Arrangement.spacedBy(6.dp),
) {
Cover(store, song.id, Modifier.size(48.dp), size = 160)
Column(Modifier.weight(1f)) {
@@ -166,25 +213,36 @@ fun PlayerBar(state: AppState, store: AppStore) {
)
}
IconButton(onClick = { store.addCurrentToMood(null) }) {
Icon(Icons.Rounded.AddCircleOutline, contentDescription = "Add to current mood")
IconButton(
onClick = { store.previous() },
modifier = Modifier.size(40.dp),
) {
Icon(
Icons.Rounded.SkipPrevious,
contentDescription = "Previous",
modifier = Modifier.size(26.dp),
)
}
IconButton(onClick = { picker = true }) {
Icon(Icons.Rounded.PlaylistAdd, contentDescription = "Add to another mood")
}
IconButton(onClick = { store.previous() }) {
Icon(Icons.Rounded.SkipPrevious, contentDescription = "Previous")
}
IconButton(onClick = { store.skip() }) {
Icon(Icons.Rounded.SkipNext, contentDescription = "Skip")
}
IconButton(onClick = { store.togglePlayPause() }) {
IconButton(
onClick = { store.togglePlayPause() },
modifier = Modifier.size(48.dp),
) {
Icon(
if (state.playing) Icons.Rounded.Pause else Icons.Rounded.PlayArrow,
contentDescription = if (state.playing) "Pause" else "Play",
modifier = Modifier.size(30.dp),
)
}
IconButton(
onClick = { store.skip() },
modifier = Modifier.size(40.dp),
) {
Icon(
Icons.Rounded.SkipNext,
contentDescription = "Skip",
modifier = Modifier.size(26.dp),
)
}
}
}
}
@@ -208,12 +266,43 @@ fun PlayerBar(state: AppState, store: AppStore) {
@Composable
private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit) {
val listState = rememberLazyListState()
var draggingIndex by remember { mutableStateOf<Int?>(null) }
var dragPointerY by remember { mutableStateOf(0f) }
var grabOffset by remember { mutableStateOf(0f) }
val edgePx = with(LocalDensity.current) { 48.dp.toPx() }
fun queueIndexAt(y: Float): Int? =
listState.layoutInfo.visibleItemsInfo
.firstOrNull { y >= it.offset && y < it.offset + it.size }
?.index
LaunchedEffect(draggingIndex) {
while (draggingIndex != null) {
val y = dragPointerY
val edge = edgePx
val viewport = listState.layoutInfo.viewportEndOffset.toFloat()
if (y < edge) {
listState.scrollBy(-18f)
} else if (y > viewport - edge) {
listState.scrollBy(18f)
}
val from = draggingIndex
val to = queueIndexAt(y)
if (from != null && to != null && to != from) {
store.moveInQueue(from, to)
draggingIndex = to
}
delay(16)
}
}
Dialog(onDismissRequest = onDismiss) {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surface,
tonalElevation = 6.dp,
modifier = Modifier.fillMaxWidth().heightIn(max = 600.dp),
modifier = Modifier.fillMaxWidth().heightIn(max = 620.dp),
) {
Column {
Row(
@@ -223,7 +312,11 @@ private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit)
Column(Modifier.weight(1f)) {
Text("Queue", style = MaterialTheme.typography.titleMedium)
Text(
"${state.queue.size} upcoming",
if (state.queue.isEmpty()) {
"Nothing queued"
} else {
"${state.queue.size} upcoming · long-press and drag to reorder"
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
@@ -231,17 +324,23 @@ private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit)
TextButton(onClick = onDismiss) { Text("Close") }
}
HorizontalDivider()
LazyColumn(Modifier.fillMaxWidth().heightIn(max = 480.dp)) {
state.current?.let { song ->
item(key = "current") {
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 10.dp),
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
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(
song.title,
style = MaterialTheme.typography.bodyLarge,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
"Now playing",
style = MaterialTheme.typography.labelSmall,
@@ -249,29 +348,86 @@ private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit)
)
}
}
}
HorizontalDivider()
}
if (state.queue.isEmpty()) {
item {
Text(
"Nothing queued. Start a mood to build a radio queue.",
modifier = Modifier.padding(20.dp),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
} else {
Box(
modifier = Modifier
.fillMaxWidth()
.pointerInput(Unit) {
detectDragGesturesAfterLongPress(
onDragStart = { offset ->
val index = queueIndexAt(offset.y)
val info = listState.layoutInfo.visibleItemsInfo
.firstOrNull { it.index == index }
if (index != null && info != null) {
draggingIndex = index
dragPointerY = offset.y
grabOffset = offset.y - info.offset
}
},
onDrag = { change, _ ->
change.consume()
dragPointerY = change.position.y
val from = draggingIndex
val to = queueIndexAt(change.position.y)
if (from != null && to != null && to != from) {
store.moveInQueue(from, to)
draggingIndex = to
}
},
onDragEnd = { draggingIndex = null },
onDragCancel = { draggingIndex = null },
)
},
) {
LazyColumn(
state = listState,
modifier = Modifier.fillMaxWidth().heightIn(max = 500.dp),
) {
itemsIndexed(state.queue, key = { _, song -> song.id }) { index, song ->
val isDragging = index == draggingIndex
val rowInfo = if (isDragging) {
listState.layoutInfo.visibleItemsInfo
.firstOrNull { it.index == index }
} else {
null
}
val translation = if (rowInfo != null) {
dragPointerY - rowInfo.offset - grabOffset
} else {
0f
}
itemsIndexed(state.queue, key = { index, _ -> "queue-$index" }) { index, song ->
Row(
modifier = Modifier.fillMaxWidth().padding(start = 20.dp, end = 8.dp, top = 6.dp, bottom = 6.dp),
modifier = Modifier
.fillMaxWidth()
.height(QUEUE_ROW_HEIGHT)
.background(MaterialTheme.colorScheme.surface)
.zIndex(if (isDragging) 1f else 0f)
.graphicsLayer {
translationY = translation
shadowElevation = if (isDragging) 8.dp.toPx() else 0f
}
.padding(start = 20.dp, end = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
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(
song.title,
style = MaterialTheme.typography.bodyMedium,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
song.artist,
style = MaterialTheme.typography.labelSmall,
@@ -280,19 +436,19 @@ private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit)
overflow = TextOverflow.Ellipsis,
)
}
Icon(
Icons.Rounded.DragHandle,
contentDescription = "Drag to reorder",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(22.dp),
)
IconButton(
onClick = { store.moveInQueue(index, index - 1) },
enabled = index > 0,
onClick = {
val from = store.state.value.queue
.indexOfFirst { it.id == song.id }
if (from >= 0) store.removeFromQueue(from)
},
) {
Icon(Icons.Rounded.KeyboardArrowUp, contentDescription = "Move up")
}
IconButton(
onClick = { store.moveInQueue(index, index + 1) },
enabled = index < state.queue.lastIndex,
) {
Icon(Icons.Rounded.KeyboardArrowDown, contentDescription = "Move down")
}
IconButton(onClick = { store.removeFromQueue(index) }) {
Icon(Icons.Rounded.Close, contentDescription = "Remove from queue")
}
}
@@ -302,3 +458,5 @@ private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit)
}
}
}
}
}
@@ -47,6 +47,7 @@ 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
import win.taptap.musicmanager.client.store.sourceLabel
@Composable
fun SearchScreen(state: AppState, store: AppStore) {
@@ -61,6 +62,7 @@ fun SearchScreen(state: AppState, store: AppStore) {
var url by remember { mutableStateOf("") }
var moodMenu by remember { mutableStateOf(false) }
var sourceMenu by remember { mutableStateOf(false) }
val target = state.moods.firstOrNull { it.id == state.searchTargetMoodId } ?: state.moods.first()
LazyColumn(
@@ -95,11 +97,41 @@ fun SearchScreen(state: AppState, store: AppStore) {
}
}
item {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
Text("Download source", style = MaterialTheme.typography.bodyMedium)
Box {
OutlinedButton(onClick = { sourceMenu = true }) {
Text(sourceLabel(target.source))
Icon(Icons.Rounded.ArrowDropDown, contentDescription = null)
}
DropdownMenu(
expanded = sourceMenu,
onDismissRequest = { sourceMenu = false },
) {
listOf("deezer", "youtube").forEach { option ->
DropdownMenuItem(
text = { Text(sourceLabel(option)) },
onClick = {
sourceMenu = false
store.setMoodSource(target.id, option)
},
)
}
}
}
}
}
item {
OutlinedTextField(
value = state.searchQuery,
onValueChange = store::setSearchQuery,
label = { Text("Search YouTube") },
label = { Text("Search ${sourceLabel(target.source)}") },
singleLine = true,
leadingIcon = { Icon(Icons.Rounded.Search, contentDescription = null) },
modifier = Modifier.fillMaxWidth(),
@@ -115,7 +147,7 @@ fun SearchScreen(state: AppState, store: AppStore) {
OutlinedTextField(
value = url,
onValueChange = { url = it },
label = { Text("Paste a YouTube URL") },
label = { Text("Paste a YouTube or Deezer URL") },
singleLine = true,
leadingIcon = { Icon(Icons.Rounded.Link, contentDescription = null) },
modifier = Modifier.weight(1f),
@@ -137,7 +169,7 @@ fun SearchScreen(state: AppState, store: AppStore) {
Row(verticalAlignment = Alignment.CenterVertically) {
CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp)
Spacer(Modifier.width(10.dp))
Text("Searching YouTube…", style = MaterialTheme.typography.bodySmall)
Text("Searching YouTube Music…", style = MaterialTheme.typography.bodySmall)
}
}
}
@@ -152,7 +184,7 @@ fun SearchScreen(state: AppState, store: AppStore) {
}
}
items(state.searchResults, key = { it.videoId }) { result ->
items(state.searchResults, key = { "${it.source}-${it.externalId}" }) { result ->
SearchRow(result, store)
}
@@ -107,7 +107,7 @@ 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.2.0 · $platformName",
"AudioManager 0.3.0 · $platformName",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
@@ -38,7 +38,7 @@ class ApiClientTest {
)
"/api/v1/moods" -> respond(
"""
{"moods":[{"id":"mo-1","name":"Focus","collectionPercent":60,
{"moods":[{"id":"mo-1","name":"Focus","source":"deezer","collectionPercent":60,
"recommendationPercent":40,"recommendationCount":10,"refreshHours":24,
"createdAt":"now","changedAt":"now","songCount":2,"recommendationReady":3}]}
""".trimIndent(),
@@ -68,10 +68,10 @@ class ApiClientTest {
"/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}
{"source":"deezer","externalId":"v1","title":"Fresh","artist":"Artist",
"duration":180,"downloaded":false},
{"source":"deezer","externalId":"v2","title":"Old","artist":"Artist",
"duration":200,"songId":"sg-2","downloaded":true}
]}
""".trimIndent(),
HttpStatusCode.OK,
@@ -98,8 +98,9 @@ class ApiClientTest {
assertNull(results[0].songId)
assertEquals("sg-2", results[1].songId)
assertTrue(results[1].downloaded)
assertEquals("v2", results[1].externalId)
val added = client.addSong("mo-1", videoId = "v1")
val added = client.addSong("mo-1", source = "deezer", externalId = "v1")
assertTrue(added.downloading)
assertEquals(1, added.detail.mood.songCount)
}
@@ -112,8 +113,8 @@ class ApiClientTest {
"""
{"detail":{"mood":{"id":"mo-1","name":"Focus","createdAt":"now",
"changedAt":"now","songCount":2},"songs":[],"recommendations":[]},
"recommendation":{"videoId":"v1","title":"Pick","artist":"Artist",
"state":"added"}}
"recommendation":{"source":"deezer","externalId":"v1","title":"Pick",
"artist":"Artist","state":"added"}}
""".trimIndent(),
HttpStatusCode.OK,
jsonHeaders,
@@ -122,8 +123,8 @@ class ApiClientTest {
"""
{"detail":{"mood":{"id":"mo-1","name":"Focus","createdAt":"now",
"changedAt":"now","songCount":2},"songs":[],"recommendations":[]},
"recommendation":{"videoId":"v2","title":"Other","artist":"Artist",
"state":"rejected"}}
"recommendation":{"source":"deezer","externalId":"v2","title":"Other",
"artist":"Artist","state":"rejected"}}
""".trimIndent(),
HttpStatusCode.OK,
jsonHeaders,
@@ -223,6 +224,6 @@ class ApiClientTest {
storage.write("mood-cache.json", """{"version":1,"songs":[{"id":"old"}]}""")
val invalidated = cache.load()
assertTrue(invalidated.moods.isEmpty())
assertEquals(2, invalidated.version)
assertEquals(3, invalidated.version)
}
}
@@ -111,8 +111,8 @@ class AppStoreTest {
"/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}]}""",
"""{"results":[{"source":"youtube","externalId":"v1","title":"Fresh",
"artist":"Artist","duration":180,"downloaded":false}]}""",
HttpStatusCode.OK,
jsonHeaders,
)
@@ -133,7 +133,7 @@ class AppStoreTest {
advanceTimeBy(350)
runCurrent()
awaitState { store.state.value.searchResults.isNotEmpty() }
assertEquals("v1", store.state.value.searchResults.single().videoId)
assertEquals("v1", store.state.value.searchResults.single().externalId)
store.addSearchResult(store.state.value.searchResults.single())
awaitState { store.state.value.message != null }
@@ -180,6 +180,54 @@ class AppStoreTest {
store.release()
}
@Test
fun `changing the mood source re-runs the search against the new catalog`() = 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)
request.url.encodedPath == "/api/v1/moods" ->
respond("""{"moods":[${moodJson(0)}]}""", HttpStatusCode.OK, jsonHeaders)
request.method.value == "PATCH" && request.url.encodedPath == "/api/v1/moods/mo-1" ->
respond(detailJson(emptyList(), source = "deezer"), HttpStatusCode.OK, jsonHeaders)
request.url.encodedPath == "/api/v1/moods/mo-1" ->
respond(detailJson(emptyList()), HttpStatusCode.OK, jsonHeaders)
request.url.encodedPath == "/api/v1/moods/mo-1/preview" ->
respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
request.url.encodedPath == "/api/v1/search" -> {
val source = request.url.parameters["source"]
val body = if (source == "deezer") {
"""{"results":[{"source":"deezer","externalId":"67238732",
"title":"Instant Crush","artist":"Daft Punk","duration":337,
"downloaded":false}]}"""
} else {
"""{"results":[]}"""
}
respond(body, 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.openSearch("mo-1")
store.setSearchQuery("daft")
advanceTimeBy(350)
runCurrent()
store.setMoodSource("mo-1", "deezer")
awaitState { store.state.value.searchResults.any { it.source == "deezer" } }
assertEquals("deezer", store.state.value.moods.first { it.id == "mo-1" }.source)
assertEquals("67238732", store.state.value.searchResults.single().externalId)
store.release()
}
@Test
fun `sleep timer pauses playback when it expires`() = runTest {
val storage = MemoryStorage()
@@ -319,31 +367,38 @@ class AppStoreTest {
private val jsonHeaders = headersOf(HttpHeaders.ContentType, "application/json")
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"}
{"id":"$id","source":"youtube","externalId":"video-$id","title":"Song $id",
"artist":"Artist","album":"Album","duration":180,"bitRate":320,"size":1000,"suffix":"mp3"}
""".trimIndent()
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}
private fun moodJson(songCount: Int, source: String = "youtube") = """
{"id":"mo-1","name":"Focus","source":"$source","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 recommendationJson(state: String = "new", songId: String? = null) = """
{"videoId":"v1","title":"Pick","artist":"Artist","duration":180,"state":"$state",
{"source":"youtube","externalId":"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 detailJson(songs: List<String>, recommendation: String? = null) = """
{"mood":${moodJson(songs.size)},
private fun detailJson(
songs: List<String>,
recommendation: String? = null,
source: String = "youtube",
) = """
{"mood":${moodJson(songs.size, source)},
"songs":[${songs.joinToString(",") { """{"song":${songJson(it)},"origin":"search","addedAt":"now"}""" }}],
"recommendations":${recommendation?.let { "[$it]" } ?: "[]"}}
""".trimIndent()
private fun song(id: String, duration: Int = 180) = Song(
id = id,
videoId = "video-$id",
source = "youtube",
externalId = "video-$id",
title = "Song $id",
artist = "Artist",
album = "Album",
+4 -4
View File
@@ -10,7 +10,7 @@ Read that first. This file only records the client-side consequences.
## What the client becomes
- Moods are the only content model. No Library, no Longform, no mounted music.
- All music is downloaded on the server from YouTube; the client searches and
- All music is downloaded on the server from Deezer or YouTube Music; the client searches and
adds songs to a mood.
- A mood has **songs** (collection) and **recommendations** (auto-downloaded,
playable in radio, not permanent until added).
@@ -25,7 +25,7 @@ Read that first. This file only records the client-side consequences.
- **MoodDetail**: songs, add music, recommendations (Add / Not interested /
Retry), next batch, mood settings (query, genres, collectionPercent,
recommendationCount 0–30, refreshHours).
- **Search**: remote YouTube search, results over 10 minutes hidden, add to the
- **Search**: remote Deezer/YouTube Music search, results over 10 minutes hidden, add to the
current or a chosen mood, already-downloaded/in-mood badges, paste URL.
- **Downloads**: device-side offline files, delete/clear, storage usage.
- **Settings**: server/account/devices/logout (no scan UI).
@@ -59,10 +59,10 @@ Implemented. Concretely:
- `AppCache` (version 2) stores moods and details only; old cache shapes are
discarded. Session and playback snapshots are kept.
- `AppStore` has `Moods | MoodDetail | Search | Downloads | Settings`, remote
search with a target mood, add/remove song, recommendation actions, offline
Deezer/YouTube Music search with a target mood and a per-mood source, add/remove song, recommendation actions, offline
playback from device downloads, and no longform/library paths.
- The UI has a dedicated Search screen (mood picker, paste URL, downloaded
badges) and a Downloads screen. Mood Detail shows songs, add music,
recommendation states and the new options. The player keeps queue editing,
recommendation states and the new options. The player keeps drag-to-reorder queue editing,
previous/seek and the sleep timer.
- Device downloads store covers by song id (`<songId>.jpg`).