From 957ee3eb4b18a488b7ccdac1325f91d770792c80 Mon Sep 17 00:00:00 2001 From: TapTap Date: Tue, 17 Nov 2026 16:43:21 +0000 Subject: [PATCH] feat: inline search download status and headset transport MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- README.md | 7 +- composeApp/build.gradle.kts | 2 +- .../client/MediaControllerAudioPlayer.kt | 5 + .../musicmanager/client/PlaybackCommands.kt | 27 ++++ .../musicmanager/client/PlaybackService.kt | 36 +++++ .../taptap/musicmanager/client/api/Models.kt | 14 ++ .../client/playback/AudioPlayer.kt | 7 + .../musicmanager/client/store/AppStore.kt | 53 +++++- .../client/ui/MoodDetailScreen.kt | 8 + .../musicmanager/client/ui/SearchScreen.kt | 69 ++++++-- .../musicmanager/client/ui/SettingsScreen.kt | 2 +- .../musicmanager/client/AppStoreTest.kt | 151 +++++++++++++++++- 12 files changed, 362 insertions(+), 19 deletions(-) create mode 100644 composeApp/src/androidMain/kotlin/win/taptap/musicmanager/client/PlaybackCommands.kt diff --git a/README.md b/README.md index a029c35..93b7818 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,8 @@ a server-driven radio session and songs are added from Deezer or YouTube Music. 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 @@ -74,7 +76,8 @@ a server-driven radio session and songs are added from Deezer or YouTube Music. - **Moods** — grid with song and pick counts, create, global search. - **Mood Detail** — songs, add music, recommendations, next batch, settings. - **Search** — mood picker, source selector, catalog search, paste URL, - downloaded badges. + 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. @@ -196,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.3.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. diff --git a/composeApp/build.gradle.kts b/composeApp/build.gradle.kts index 38f6831..a5fb559 100644 --- a/composeApp/build.gradle.kts +++ b/composeApp/build.gradle.kts @@ -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.3.0" + ?: "0.3.1" kotlin { androidTarget { diff --git a/composeApp/src/androidMain/kotlin/win/taptap/musicmanager/client/MediaControllerAudioPlayer.kt b/composeApp/src/androidMain/kotlin/win/taptap/musicmanager/client/MediaControllerAudioPlayer.kt index cab7be7..bf9d618 100644 --- a/composeApp/src/androidMain/kotlin/win/taptap/musicmanager/client/MediaControllerAudioPlayer.kt +++ b/composeApp/src/androidMain/kotlin/win/taptap/musicmanager/client/MediaControllerAudioPlayer.kt @@ -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 -> diff --git a/composeApp/src/androidMain/kotlin/win/taptap/musicmanager/client/PlaybackCommands.kt b/composeApp/src/androidMain/kotlin/win/taptap/musicmanager/client/PlaybackCommands.kt new file mode 100644 index 0000000..b154181 --- /dev/null +++ b/composeApp/src/androidMain/kotlin/win/taptap/musicmanager/client/PlaybackCommands.kt @@ -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 + } +} diff --git a/composeApp/src/androidMain/kotlin/win/taptap/musicmanager/client/PlaybackService.kt b/composeApp/src/androidMain/kotlin/win/taptap/musicmanager/client/PlaybackService.kt index 87340b8..e4410da 100644 --- a/composeApp/src/androidMain/kotlin/win/taptap/musicmanager/client/PlaybackService.kt +++ b/composeApp/src/androidMain/kotlin/win/taptap/musicmanager/client/PlaybackService.kt @@ -5,8 +5,11 @@ 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.common.util.UnstableApi import androidx.media3.exoplayer.ExoPlayer import androidx.media3.session.MediaSession import androidx.media3.session.MediaSessionService @@ -73,6 +76,39 @@ 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. + */ + @OptIn(UnstableApi::class) + 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, diff --git a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/api/Models.kt b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/api/Models.kt index a7b6884..b6ee545 100644 --- a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/api/Models.kt +++ b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/api/Models.kt @@ -108,8 +108,22 @@ data class MoodDetail( val mood: Mood, val songs: List = emptyList(), val recommendations: List = emptyList(), + val downloads: List = 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 = emptyList()) diff --git a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/playback/AudioPlayer.kt b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/playback/AudioPlayer.kt index 75e74bf..81fa93c 100644 --- a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/playback/AudioPlayer.kt +++ b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/playback/AudioPlayer.kt @@ -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 } diff --git a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/store/AppStore.kt b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/store/AppStore.kt index 60ba457..2795f63 100644 --- a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/store/AppStore.kt +++ b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/store/AppStore.kt @@ -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 = emptyList(), val searchTargetMoodId: String? = null, + /** Download state of the search target mood, keyed by [downloadKey]. */ + val searchDownloads: Map = 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) @@ -407,10 +428,14 @@ class AppStore( 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( @@ -1107,6 +1132,7 @@ class AppStore( } fun release() { + player.setSkipCallbacks(onNext = null, onPrevious = null) persistPlayback() pollJob?.cancel() refreshJob?.cancel() @@ -1312,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 + }, ) } } @@ -1325,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) { @@ -1407,5 +1456,7 @@ 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 diff --git a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/MoodDetailScreen.kt b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/MoodDetailScreen.kt index 23c2853..414a79a 100644 --- a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/MoodDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/MoodDetailScreen.kt @@ -6,6 +6,7 @@ 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 @@ -189,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) }) { diff --git a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/SearchScreen.kt b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/SearchScreen.kt index 2a4afba..1e91550 100644 --- a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/SearchScreen.kt +++ b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/SearchScreen.kt @@ -44,9 +44,11 @@ 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 @@ -185,7 +187,11 @@ fun SearchScreen(state: AppState, store: AppStore) { } items(state.searchResults, key = { "${it.source}-${it.externalId}" }) { result -> - SearchRow(result, store) + SearchRow( + result, + store, + download = state.searchDownloads[downloadKey(result.source, result.externalId)], + ) } item { Spacer(Modifier.size(24.dp)) } @@ -193,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, @@ -218,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, @@ -233,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, @@ -252,12 +295,16 @@ private fun SearchRow(result: SearchResult, store: AppStore) { } IconButton( onClick = { store.addSearchResult(result) }, - enabled = !result.inMood, + enabled = !result.inMood && !pending && !added, ) { - Icon( - Icons.Rounded.Add, - contentDescription = "Add to ${result.title}", - ) + if (pending) { + CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp) + } else { + Icon( + Icons.Rounded.Add, + contentDescription = "Add to ${result.title}", + ) + } } } } diff --git a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/SettingsScreen.kt b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/SettingsScreen.kt index dddfb35..dbafe50 100644 --- a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/SettingsScreen.kt +++ b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/SettingsScreen.kt @@ -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.3.0 · $platformName", + "AudioManager 0.3.1 · $platformName", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) diff --git a/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/AppStoreTest.kt b/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/AppStoreTest.kt index 205d07c..46467c4 100644 --- a/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/AppStoreTest.kt +++ b/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/AppStoreTest.kt @@ -141,6 +141,76 @@ class AppStoreTest { store.release() } + @Test + fun `search shows the download status and clears it when the job finishes`() = runTest { + val storage = MemoryStorage() + val cache = AppCache(storage) + cache.saveSession(SessionState("http://music", "token", User("alice", admin = false))) + var finished = false + val engine = MockEngine { request -> + when (request.url.encodedPath) { + "/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders) + "/api/v1/moods" -> respond("""{"moods":[${moodJson(0)}]}""", HttpStatusCode.OK, jsonHeaders) + "/api/v1/moods/mo-1" -> respond( + detailJson( + emptyList(), + downloads = if (finished) listOf(downloadJson("done")) else emptyList(), + ), + 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" -> { + finished = true + 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 + } + assertEquals("queued", store.state.value.searchDownloads["youtube|v1"]?.state) + + // Each poll interval re-reads the detail. Advance until the finished job + // lands; repeating also covers a coroutine that registered late. + var ended = false + repeat(10) { + runCurrent() + advanceTimeBy(4_100) + // MockEngine answers off the test dispatcher, so give it real time. + withContext(Dispatchers.Default) { delay(15) } + runCurrent() + if (store.state.value.searchDownloads["youtube|v1"]?.state == "done") { + ended = true + return@repeat + } + } + assertTrue(ended, "downloads=${store.state.value.searchDownloads}") + store.release() + } + @Test fun `adding a recommendation refreshes the selected mood`() = runTest { val storage = MemoryStorage() @@ -323,6 +393,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() @@ -355,13 +472,16 @@ 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") @@ -389,12 +509,21 @@ class AppStoreTest { songs: List, recommendation: String? = null, source: String = "youtube", + downloads: List = 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, source = "youtube", @@ -423,6 +552,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() val seeks = mutableListOf() var paused = false