5 Commits
Author SHA1 Message Date
TapTap 2478505dba test: make the search download status assertion timing independent
CI / build (push) Successful in 13m58s
CI / play (push) Successful in 3m18s
2026-11-17 16:57:07 +00:00
TapTap 957ee3eb4b feat: inline search download status and headset transport
CI / build (push) Successful in 5m35s
CI / play (push) Skipped
- mood detail carries the server's download jobs
- search rows show Downloading… / Added / Failed, so the keyboard cannot hide it
- headset and Bluetooth next/previous drive the app queue; previous keeps the
  after-two-seconds restart rule
- 'Next batch' now explains what the preview is
- version 0.3.1
2026-11-17 16:43:21 +00:00
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
19 changed files with 873 additions and 129 deletions

No files matched your search

+24 -13
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 Music.
a server-driven radio session and songs are added from Deezer or YouTube Music.
## Targets
@@ -22,9 +22,9 @@ a server-driven radio session and songs are added by searching YouTube Music.
- **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 Music** from inside a mood or globally with a mood picker.
Results are canonical songs with artist, album and duration; 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
@@ -40,10 +40,15 @@ a server-driven radio session and songs are added by searching YouTube Music.
- 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.
- **Headset/Bluetooth next and previous** use the same queue rules as the
buttons; they no longer seek inside the single ExoPlayer item.
- 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,
@@ -70,7 +75,9 @@ a server-driven radio session and songs are added by searching YouTube Music.
- **Moods** — grid with song and pick counts, create, global search.
- **Mood Detail** — songs, add music, recommendations, next batch, settings.
- **Search** — mood picker, YouTube Music search, paste URL, downloaded badges.
- **Search** — mood picker, source selector, catalog search, paste URL,
downloaded badges and an inline Downloading… / Added / Failed status per
result, so the keyboard never hides the feedback.
- **Downloads** — offline files and storage usage.
- **Settings** — account, server URL, offline storage, sign out.
@@ -192,7 +199,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.1 && 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.
@@ -205,7 +212,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 Music 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
@@ -265,8 +273,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.
Music search resolves every result for its artist/album/duration, so a search
takes roughly 10–15 seconds for ten results.
- 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.1"
kotlin {
androidTarget {
@@ -126,6 +126,11 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
withController { it.seekTo((seconds * 1000).toLong().coerceAtLeast(0L)) }
}
override fun setSkipCallbacks(onNext: (() -> Unit)?, onPrevious: (() -> Unit)?) {
PlaybackCommands.onNext = onNext
PlaybackCommands.onPrevious = onPrevious
}
override fun scheduleSleepTimer(seconds: Long?): Boolean {
val args = Bundle().apply { putLong(SLEEP_TIMER_SECONDS, seconds ?: 0L) }
val send: (MediaController) -> Boolean = { current ->
@@ -0,0 +1,27 @@
package win.taptap.musicmanager.client
/**
* Bridge between the media session in [PlaybackService] and the queue that
* lives in the app's store. Media3 sends headset/Bluetooth next and previous
* here instead of seeking the single-item ExoPlayer.
*/
internal object PlaybackCommands {
@Volatile
var onNext: (() -> Unit)? = null
@Volatile
var onPrevious: (() -> Unit)? = null
/** Returns false when no store is attached, so the default handling applies. */
fun next(): Boolean {
val handler = onNext ?: return false
handler()
return true
}
fun previous(): Boolean {
val handler = onPrevious ?: return false
handler()
return true
}
}
@@ -5,6 +5,8 @@ import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.KeyEvent
import androidx.core.content.IntentCompat
import androidx.media3.common.AudioAttributes
import androidx.media3.common.C
import androidx.media3.exoplayer.ExoPlayer
@@ -73,6 +75,38 @@ class PlaybackService : MediaSessionService() {
.build()
}
/**
* A headset skip must move the app's queue, not seek the one
* item ExoPlayer holds. Returning true consumes the event.
*/
override fun onMediaButtonEvent(
session: MediaSession,
controllerInfo: MediaSession.ControllerInfo,
intent: Intent,
): Boolean {
if (intent.action != Intent.ACTION_MEDIA_BUTTON) return false
val event = IntentCompat.getParcelableExtra(
intent,
Intent.EXTRA_KEY_EVENT,
KeyEvent::class.java,
) ?: return false
return when (event.keyCode) {
KeyEvent.KEYCODE_MEDIA_NEXT -> when (event.action) {
KeyEvent.ACTION_DOWN -> PlaybackCommands.next()
KeyEvent.ACTION_UP -> true
else -> false
}
KeyEvent.KEYCODE_MEDIA_PREVIOUS -> when (event.action) {
KeyEvent.ACTION_DOWN -> PlaybackCommands.previous()
KeyEvent.ACTION_UP -> true
else -> false
}
else -> false
}
}
override fun onCustomCommand(
session: MediaSession,
controller: MediaSession.ControllerInfo,
@@ -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,10 +187,16 @@ 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 = 10, 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 parse<SearchResponse>(
http.get(url("/search?q=${query.encodeURLParameter()}&limit=$limit$mood")) {
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.
@@ -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,
@@ -105,8 +108,22 @@ data class MoodDetail(
val mood: Mood,
val songs: List<MoodSong> = emptyList(),
val recommendations: List<Recommendation> = emptyList(),
val downloads: List<DownloadStatus> = emptyList(),
)
/** Server-side download state for one track, keyed by source and external id. */
@Serializable
data class DownloadStatus(
val source: String = "youtube",
val externalId: String,
val state: String,
val attempts: Int = 0,
val error: String? = null,
val songId: String? = null,
) {
val active: Boolean get() = state == "queued" || state == "downloading"
}
@Serializable
data class MoodsResponse(val moods: List<Mood> = emptyList())
@@ -121,7 +138,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 +198,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 +216,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 +230,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
}
}
@@ -34,5 +34,12 @@ interface AudioPlayer {
* their own countdown for the UI either way.
*/
fun scheduleSleepTimer(seconds: Long?): Boolean = false
/**
* Routes hardware transport buttons (headset/Bluetooth next and previous)
* to the app's own queue. Android wires this to its MediaSession; other
* platforms ignore it. Null clears the handlers.
*/
fun setSkipCallbacks(onNext: (() -> Unit)?, onPrevious: (() -> Unit)?) = Unit
}
@@ -14,6 +14,7 @@ import kotlin.random.Random
import win.taptap.musicmanager.client.api.ApiClient
import win.taptap.musicmanager.client.api.ApiException
import win.taptap.musicmanager.client.api.CreateMoodRequest
import win.taptap.musicmanager.client.api.DownloadStatus
import win.taptap.musicmanager.client.api.Mood
import win.taptap.musicmanager.client.api.MoodDetail
import win.taptap.musicmanager.client.api.PlaybackEvent
@@ -60,6 +61,8 @@ data class AppState(
val searchQuery: String = "",
val searchResults: List<SearchResult> = emptyList(),
val searchTargetMoodId: String? = null,
/** Download state of the search target mood, keyed by [downloadKey]. */
val searchDownloads: Map<String, DownloadStatus> = emptyMap(),
val searching: Boolean = false,
val loading: Boolean = false,
val saving: Boolean = false,
@@ -96,9 +99,13 @@ class AppStore(
private var trackStartOffset = 0.0
private var dataGeneration = 0
private var moodRequestGeneration = 0
private var searchTargetGeneration = 0
private var loggingOut = false
init {
// Headset/Bluetooth next and previous must use the app queue rules,
// not ExoPlayer's single-item seek-to-start.
player.setSkipCallbacks(onNext = ::skip, onPrevious = ::previous)
bootstrap()
}
@@ -333,6 +340,7 @@ class AppStore(
searchQuery = "",
)
}
_state.value.searchTargetMoodId?.let(::loadSearchTarget)
}
fun openDownloads() {
@@ -345,9 +353,22 @@ class AppStore(
fun selectSearchMood(moodId: String) {
_state.update { it.copy(searchTargetMoodId = moodId) }
loadSearchTarget(moodId)
if (_state.value.searchQuery.isNotBlank()) search(_state.value.searchQuery)
}
/**
* Loads the target mood once so in-flight downloads show their status. The
* generation guards against an older response overwriting a newer add.
*/
private fun loadSearchTarget(moodId: String) {
val generation = ++searchTargetGeneration
scope.launch {
val detail = runCatching { api.mood(moodId) }.getOrNull() ?: return@launch
if (generation == searchTargetGeneration) applyMoodDetail(detail)
}
}
fun setSearchQuery(query: String) {
_state.update { it.copy(searchQuery = query) }
search(query)
@@ -363,7 +384,15 @@ class AppStore(
delay(SEARCH_DEBOUNCE_MS)
_state.update { it.copy(searching = true) }
try {
val results = api.search(query, SEARCH_LIMIT, _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,12 +422,20 @@ 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,
)
}
searchTargetGeneration++
applyMoodDetail(response.detail)
val title = response.detail.mood.name
if (response.downloading) {
pollUntilSongCount(response.detail.mood.id, response.detail.mood.songCount + 1)
pollDownload(
response.detail.mood.id,
downloadKey(result.source, result.externalId),
)
}
_state.update {
it.copy(
@@ -451,6 +488,7 @@ class AppStore(
description: String?,
genres: List<String>,
query: String?,
source: String,
collectionPercent: Int,
recommendationCount: Int,
refreshHours: Int,
@@ -464,6 +502,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 +534,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 +586,7 @@ class AppStore(
query = query ?: "",
clearQuery = query.isNullOrBlank(),
genres = genres,
source = source,
collectionPercent = collectionPercent,
recommendationCount = recommendationCount,
refreshHours = refreshHours,
@@ -612,13 +682,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 +712,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 +735,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(
@@ -1062,6 +1132,7 @@ class AppStore(
}
fun release() {
player.setSkipCallbacks(onNext = null, onPrevious = null)
persistPlayback()
pollJob?.cancel()
refreshJob?.cancel()
@@ -1267,6 +1338,11 @@ class AppStore(
},
moods = state.moods.map { mood -> if (mood.id == detail.mood.id) detail.mood else mood },
knownSongs = state.knownSongs + detail.songMap(),
searchDownloads = if (state.searchTargetMoodId == detail.mood.id) {
detail.downloads.associateBy { downloadKey(it.source, it.externalId) }
} else {
state.searchDownloads
},
)
}
}
@@ -1280,6 +1356,24 @@ class AppStore(
* A song added while its download is still running is not in the detail
* response yet. Poll briefly so the new row appears without a manual refresh.
*/
/**
* Follows one queued track until the server finishes or fails it, so the
* search row can show Downloading… / Added / Failed without a snackbar.
*/
private fun pollDownload(moodId: String, key: String) {
scope.launch {
repeat(DOWNLOAD_POLLS) {
delay(DOWNLOAD_POLL_MS)
val detail = runCatching { api.mood(moodId) }.getOrNull() ?: return@launch
applyMoodDetail(detail)
val status = detail.downloads.firstOrNull {
downloadKey(it.source, it.externalId) == key
}
if (status == null || !status.active) return@launch
}
}
}
private fun pollUntilSongCount(moodId: String, expectedAtLeast: Int) {
scope.launch {
repeat(DOWNLOAD_POLLS) {
@@ -1358,5 +1452,11 @@ 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"
internal fun downloadKey(source: String, externalId: String): String = "$source|$externalId"
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,10 +1,12 @@
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
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
@@ -24,11 +26,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 +55,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 +82,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()) }
@@ -182,6 +190,13 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
item {
HorizontalDivider(Modifier.padding(vertical = 12.dp))
SectionTitle("Next batch")
Text(
"What the radio would play next, mixed from this mood and its ready picks. " +
"Nothing here is downloaded or saved.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.height(4.dp))
}
items(state.preview, key = { "preview-${it.id}" }) { song ->
SongRow(store, song, onPlay = { store.playSong(song) }) {
@@ -231,7 +246,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)
}
}
@@ -271,6 +286,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",
@@ -321,6 +375,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,
@@ -418,21 +473,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")
}
}
@@ -301,4 +457,6 @@ private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit)
}
}
}
}
}
}
@@ -44,9 +44,12 @@ 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.DownloadStatus
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.downloadKey
import win.taptap.musicmanager.client.store.sourceLabel
@Composable
fun SearchScreen(state: AppState, store: AppStore) {
@@ -61,6 +64,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 +99,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 Music") },
label = { Text("Search ${sourceLabel(target.source)}") },
singleLine = true,
leadingIcon = { Icon(Icons.Rounded.Search, contentDescription = null) },
modifier = Modifier.fillMaxWidth(),
@@ -115,7 +149,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),
@@ -152,8 +186,12 @@ fun SearchScreen(state: AppState, store: AppStore) {
}
}
items(state.searchResults, key = { it.videoId }) { result ->
SearchRow(result, store)
items(state.searchResults, key = { "${it.source}-${it.externalId}" }) { result ->
SearchRow(
result,
store,
download = state.searchDownloads[downloadKey(result.source, result.externalId)],
)
}
item { Spacer(Modifier.size(24.dp)) }
@@ -161,7 +199,9 @@ fun SearchScreen(state: AppState, store: AppStore) {
}
@Composable
private fun SearchRow(result: SearchResult, store: AppStore) {
private fun SearchRow(result: SearchResult, store: AppStore, download: DownloadStatus?) {
val pending = download?.active == true
val added = download?.state == "done"
Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically,
@@ -186,8 +226,43 @@ private fun SearchRow(result: SearchResult, store: AppStore) {
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
if (result.inMood) {
Row(verticalAlignment = Alignment.CenterVertically) {
when {
pending -> Row(verticalAlignment = Alignment.CenterVertically) {
CircularProgressIndicator(Modifier.size(12.dp), strokeWidth = 2.dp)
Spacer(Modifier.width(6.dp))
Text(
"Downloading…",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
)
}
added -> Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
Icons.Rounded.Check,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(14.dp),
)
Spacer(Modifier.width(4.dp))
Text(
"Added to this mood",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
)
}
download?.state == "failed" -> Text(
"Download failed" +
(download.error?.takeIf { it.isNotBlank() }?.let { " — ${it}" } ?: "") +
". Tap + to retry.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.error,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
result.inMood -> Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
Icons.Rounded.Check,
contentDescription = null,
@@ -201,8 +276,8 @@ private fun SearchRow(result: SearchResult, store: AppStore) {
color = MaterialTheme.colorScheme.primary,
)
}
} else if (result.downloaded) {
Row(verticalAlignment = Alignment.CenterVertically) {
result.downloaded -> Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
Icons.Rounded.DownloadDone,
contentDescription = null,
@@ -220,12 +295,16 @@ private fun SearchRow(result: SearchResult, store: AppStore) {
}
IconButton(
onClick = { store.addSearchResult(result) },
enabled = !result.inMood,
enabled = !result.inMood && !pending && !added,
) {
if (pending) {
CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp)
} else {
Icon(
Icons.Rounded.Add,
contentDescription = "Add to ${result.title}",
)
}
}
}
}
@@ -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.1 · $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 }
@@ -141,6 +141,56 @@ class AppStoreTest {
store.release()
}
@Test
fun `search shows the queued download status for a result`() = 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)
// Any detail the app may race with reports the job as active.
"/api/v1/moods/mo-1" -> respond(
detailJson(emptyList(), downloads = listOf(downloadJson("downloading"))),
HttpStatusCode.OK,
jsonHeaders,
)
"/api/v1/search" -> respond(
"""{"results":[{"source":"youtube","externalId":"v1","title":"Fresh",
"artist":"Artist","duration":180,"downloaded":false}]}""",
HttpStatusCode.OK,
jsonHeaders,
)
"/api/v1/moods/mo-1/songs" -> respond(
"""{"detail":${detailJson(emptyList(), downloads = listOf(downloadJson("queued")) )},
"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("search results") { store.state.value.searchResults.isNotEmpty() }
store.addSearchResult(store.state.value.searchResults.single())
awaitState("queued download") {
store.state.value.searchDownloads["youtube|v1"]?.active == true
}
val status = store.state.value.searchDownloads.getValue("youtube|v1")
assertTrue(status.state == "queued" || status.state == "downloading")
assertTrue(status.active)
store.release()
}
@Test
fun `adding a recommendation refreshes the selected mood`() = runTest {
val storage = MemoryStorage()
@@ -180,6 +230,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()
@@ -275,6 +373,53 @@ class AppStoreTest {
store.release()
}
@Test
fun `headset next and previous follow the queue instead of seeking`() = runTest {
val storage = MemoryStorage()
val cache = AppCache(storage)
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
val player = FakePlayer()
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(3)}]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1" -> respond(detailJson(listOf("a", "b", "c")), 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")},${songJson("b")},${songJson("c")}]}""",
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.playMood("mo-1")
awaitState { store.state.value.current?.id == "a" }
// A headset next moves the app queue: a -> b, not a seek inside one item.
player.pressNext()
awaitState { store.state.value.current?.id == "b" }
assertEquals("b", store.state.value.current?.id)
// Within two seconds, previous restores the track that just finished.
player.pressPrevious()
awaitState { store.state.value.current?.id == "a" }
assertEquals("a", store.state.value.current?.id)
// After two seconds it restarts the current track instead.
store.seekTo(5.0)
player.pressPrevious()
runCurrent()
assertEquals("a", store.state.value.current?.id)
assertEquals(0.0, player.seeks.last())
store.release()
}
@Test
fun `logout clears the session and the mood cache`() = runTest {
val storage = MemoryStorage()
@@ -307,43 +452,62 @@ class AppStoreTest {
store.release()
}
private suspend fun TestScope.awaitState(predicate: () -> Boolean) {
private suspend fun TestScope.awaitState(predicate: () -> Boolean) =
awaitState("state", predicate)
private suspend fun TestScope.awaitState(label: String, predicate: () -> Boolean) {
repeat(500) {
runCurrent()
if (predicate()) return
withContext(Dispatchers.Default) { delay(10) }
}
throw AssertionError("state did not settle")
throw AssertionError("$label did not settle")
}
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",
downloads: List<String> = emptyList(),
) = """
{"mood":${moodJson(songs.size, source)},
"songs":[${songs.joinToString(",") { """{"song":${songJson(it)},"origin":"search","addedAt":"now"}""" }}],
"recommendations":${recommendation?.let { "[$it]" } ?: "[]"}}
"recommendations":${recommendation?.let { "[$it]" } ?: "[]"},
"downloads":[${downloads.joinToString(",")}]}
""".trimIndent()
private fun downloadJson(
state: String,
source: String = "youtube",
externalId: String = "v1",
) = """{"source":"$source","externalId":"$externalId","state":"$state",
"attempts":1,"songId":null}""".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",
@@ -368,6 +532,22 @@ class AppStoreTest {
)
private class FakePlayer : AudioPlayer {
private var onNext: (() -> Unit)? = null
private var onPrevious: (() -> Unit)? = null
fun pressNext() {
onNext?.invoke()
}
fun pressPrevious() {
onPrevious?.invoke()
}
override fun setSkipCallbacks(onNext: (() -> Unit)?, onPrevious: (() -> Unit)?) {
this.onNext = onNext
this.onPrevious = onPrevious
}
val played = mutableListOf<String>()
val seeks = mutableListOf<Double>()
var paused = false
+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 Music; 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 Music 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
YouTube Music 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`).