6 Commits
Author SHA1 Message Date
TapTap 8d7f6a0ccb fix: re-run search immediately when the mood source changes
CI / build (push) Successful in 3m54s
CI / play (push) Successful in 3m29s
The explicit source switch cancelled the debounced search and then waited
another 300 ms for no reason. It now searches right away, which also makes the
test deterministic.
2026-11-18 19:48:09 +00:00
TapTap 4048262fc5 feat: remove the Up next preview section
CI / build (push) Successful in 2m22s
CI / play (push) Skipped
The preview duplicated what the radio does and is not the real queue. Mood
detail now only loads songs and recommendations, so opening a mood makes one
fewer request.

Also drop the Wasm warm-up from the CI image recipe: the target is local-only.
Version 0.3.3.
2026-11-18 19:39:51 +00:00
TapTap 14e5b9d982 ci: drop the Wasm build from the pipeline
CI / build (push) Successful in 2m57s
CI / play (push) Skipped
It is CPU-bound and dominates the runtime. The target stays available for
local builds with :composeApp:wasmJsBrowserDistribution.
2026-11-18 19:26:04 +00:00
TapTap e28e95fa2b fix: notification skip/back drive the app queue
CI / build (push) Successful in 14m12s
CI / play (push) Successful in 3m20s
- advertise next/previous on a ForwardingPlayer so the notification and
  Android Auto show the buttons, and route them to the mood queue
- rename the preview section to 'Up next' with a clearer subtitle
- version 0.3.2
2026-11-18 19:14:05 +00:00
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
15 changed files with 396 additions and 65 deletions

No files matched your search

+2 -5
View File
@@ -45,15 +45,13 @@ jobs:
:composeApp:desktopTest \ :composeApp:desktopTest \
:composeApp:assembleDebug \ :composeApp:assembleDebug \
:composeApp:packageUberJarForCurrentOS \ :composeApp:packageUberJarForCurrentOS \
:composeApp:wasmJsBrowserDistribution \
--console=plain --console=plain
else else
# The optimized Wasm build is CPU-bound and slow; main/PR builds # The Wasm target is kept for local builds but is not part of CI:
# only need to prove the web target compiles and bundles. # it is CPU-bound and dominates the pipeline runtime.
gradle \ gradle \
:composeApp:desktopTest \ :composeApp:desktopTest \
:composeApp:assembleDebug \ :composeApp:assembleDebug \
:composeApp:wasmJsBrowserDevelopmentExecutableDistribution \
--console=plain --console=plain
fi fi
@@ -64,7 +62,6 @@ jobs:
cp composeApp/build/outputs/apk/debug/composeApp-debug.apk dist/AudioManager.apk cp composeApp/build/outputs/apk/debug/composeApp-debug.apk dist/AudioManager.apk
if [[ "$GITHUB_REF" == refs/tags/* ]]; then if [[ "$GITHUB_REF" == refs/tags/* ]]; then
cp composeApp/build/compose/jars/*.jar dist/AudioManager-desktop.jar cp composeApp/build/compose/jars/*.jar dist/AudioManager-desktop.jar
(cd composeApp/build/dist/wasmJs/productionExecutable && zip -qr "$GITHUB_WORKSPACE/dist/AudioManager-web.zip" .)
fi fi
- name: Publish release assets - name: Publish release assets
+12 -8
View File
@@ -45,6 +45,9 @@ a server-driven radio session and songs are added from Deezer or YouTube Music.
locally. locally.
- **Previous** from the player: after two seconds of playback it restarts the - **Previous** from the player: after two seconds of playback it restarts the
current track; before that it restores the last played track. current track; before that it restores the last played track.
- **Headset/Bluetooth next and previous** and the media notification's skip /
back buttons use the same queue rules as the in-app controls; they no longer
seek inside the single ExoPlayer item.
- The bottom player keeps the cover and title/artist readable on narrow phones; - The bottom player keeps the cover and title/artist readable on narrow phones;
add-to-mood actions moved into the overflow menu. add-to-mood actions moved into the overflow menu.
- **Scrubbing**: the progress slider can be dragged on every platform. Android and - **Scrubbing**: the progress slider can be dragged on every platform. Android and
@@ -74,7 +77,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. - **Moods** — grid with song and pick counts, create, global search.
- **Mood Detail** — songs, add music, recommendations, next batch, settings. - **Mood Detail** — songs, add music, recommendations, next batch, settings.
- **Search** — mood picker, source selector, catalog search, paste URL, - **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. - **Downloads** — offline files and storage usage.
- **Settings** — account, server URL, offline storage, sign out. - **Settings** — account, server URL, offline storage, sign out.
@@ -129,7 +133,7 @@ gradle :composeApp:run
# Desktop fat jar # Desktop fat jar
gradle :composeApp:packageUberJarForCurrentOS gradle :composeApp:packageUberJarForCurrentOS
# Web bundle # Web bundle (local only, not built by CI)
gradle :composeApp:wasmJsBrowserDistribution gradle :composeApp:wasmJsBrowserDistribution
# composeApp/build/dist/wasmJs/productionExecutable # composeApp/build/dist/wasmJs/productionExecutable
``` ```
@@ -196,7 +200,7 @@ Tagged builds (`v*`) publish to internal testing from CI. The Gitea secrets are:
| `ANDROID_KEY_PASSWORD` | key password | | `ANDROID_KEY_PASSWORD` | key password |
| `PLAY_SERVICE_ACCOUNT_JSON` | contents of the service account JSON | | `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.3 && git push --tags` builds, signs and uploads the bundle.
Gradle Play Publisher asks Play for the next free `versionCode` Gradle Play Publisher asks Play for the next free `versionCode`
(`ResolutionStrategy.AUTO`), so only the tag/version name needs to change. (`ResolutionStrategy.AUTO`), so only the tag/version name needs to change.
@@ -246,11 +250,11 @@ radio and visible in the song list.
`gitea.tap-tap.win/taptap/audiomanager-client-ci:3`. The image has the Android `gitea.tap-tap.win/taptap/audiomanager-client-ci:3`. The image has the Android
SDK, Node, Yarn and a warmed Gradle dependency cache. SDK, Node, Yarn and a warmed Gradle dependency cache.
- **main / PR:** run `desktopTest`, build the Android APK and the *development* - **main / PR:** run `desktopTest` and build the Android APK.
Wasm bundle. - **`v*` tag:** additionally build the desktop fat jar, attach the artifacts to
- **`v*` tag:** additionally build the desktop fat jar and the optimized Wasm the Gitea release, and publish the AAB to Play internal testing.
bundle, attach the artifacts to the Gitea release, and publish the AAB to Play - The Wasm target stays in the project for local builds but is **not** part of
internal testing. CI; compiling it dominates the pipeline runtime.
Rebuild the CI image after changing `ci/Dockerfile` or dependency versions: Rebuild the CI image after changing `ci/Dockerfile` or dependency versions:
+4 -9
View File
@@ -43,21 +43,16 @@ RUN mkdir -p "$ANDROID_HOME/cmdline-tools" \
"build-tools;36.0.0" \ "build-tools;36.0.0" \
&& rm -rf "$ANDROID_HOME/.temp" "$ANDROID_HOME/.downloadIntermediates" && rm -rf "$ANDROID_HOME/.temp" "$ANDROID_HOME/.downloadIntermediates"
# Warm the Gradle dependency cache and the Kotlin/Wasm (node, yarn, binaryen) # Warm the Gradle dependency cache and the common/Android/desktop compilers so
# toolchain so CI jobs do not download them on every run. Rebuild this image # CI jobs do not download them on every run. The Wasm toolchain is intentionally
# when dependencies change. # not warmed: Wasm is not part of the pipeline. Rebuild this image when
# dependencies change.
COPY . /warmup COPY . /warmup
WORKDIR /warmup WORKDIR /warmup
# Warm dependencies and the common/Android/desktop compilers here. The Wasm
# executable build is memory hungry and stays in the web job, but node and yarn
# are cached: Kotlin downloads them from GitHub, which has been flaky during CI.
RUN sed -i 's/kotlin.daemon.jvmargs=-Xmx3g/kotlin.daemon.jvmargs=-Xmx2g/' gradle.properties \ RUN sed -i 's/kotlin.daemon.jvmargs=-Xmx3g/kotlin.daemon.jvmargs=-Xmx2g/' gradle.properties \
&& gradle --no-daemon --max-workers=2 \ && gradle --no-daemon --max-workers=2 \
:kotlinNodeJsSetup \
:kotlinYarnSetup \
:composeApp:desktopTest \ :composeApp:desktopTest \
:composeApp:assembleDebug \ :composeApp:assembleDebug \
:composeApp:compileKotlinWasmJs \
--console=plain \ --console=plain \
&& rm -rf /warmup && rm -rf /warmup
+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 appVersionCode = (System.getenv("VERSION_CODE") ?: localProperties.getProperty("VERSION_CODE") ?: "1").toInt()
val appVersionName = System.getenv("VERSION_NAME") val appVersionName = System.getenv("VERSION_NAME")
?: localProperties.getProperty("VERSION_NAME") ?: localProperties.getProperty("VERSION_NAME")
?: "0.3.0" ?: "0.3.3"
kotlin { kotlin {
androidTarget { androidTarget {
@@ -126,6 +126,11 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
withController { it.seekTo((seconds * 1000).toLong().coerceAtLeast(0L)) } 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 { override fun scheduleSleepTimer(seconds: Long?): Boolean {
val args = Bundle().apply { putLong(SLEEP_TIMER_SECONDS, seconds ?: 0L) } val args = Bundle().apply { putLong(SLEEP_TIMER_SECONDS, seconds ?: 0L) }
val send: (MediaController) -> Boolean = { current -> 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,8 +5,12 @@ import android.content.Intent
import android.os.Bundle import android.os.Bundle
import android.os.Handler import android.os.Handler
import android.os.Looper import android.os.Looper
import android.view.KeyEvent
import androidx.core.content.IntentCompat
import androidx.media3.common.AudioAttributes import androidx.media3.common.AudioAttributes
import androidx.media3.common.C import androidx.media3.common.C
import androidx.media3.common.ForwardingPlayer
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.session.MediaSession import androidx.media3.session.MediaSession
import androidx.media3.session.MediaSessionService import androidx.media3.session.MediaSessionService
@@ -36,7 +40,7 @@ class PlaybackService : MediaSessionService() {
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
val player = ExoPlayer.Builder(this) val exoPlayer = ExoPlayer.Builder(this)
.setAudioAttributes( .setAudioAttributes(
AudioAttributes.Builder() AudioAttributes.Builder()
.setUsage(C.USAGE_MEDIA) .setUsage(C.USAGE_MEDIA)
@@ -50,6 +54,44 @@ class PlaybackService : MediaSessionService() {
setWakeMode(C.WAKE_MODE_NETWORK) setWakeMode(C.WAKE_MODE_NETWORK)
} }
// ExoPlayer holds one item at a time; the queue lives in the app. Advertise
// next/previous so the notification and Android Auto show the buttons and
// route them to the queue instead of seeking inside the single item.
val player = object : ForwardingPlayer(exoPlayer) {
override fun getAvailableCommands(): Player.Commands =
super.getAvailableCommands().buildUpon()
.addAll(
Player.COMMAND_SEEK_TO_NEXT,
Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM,
Player.COMMAND_SEEK_TO_PREVIOUS,
Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM,
)
.build()
override fun isCommandAvailable(command: Int): Boolean =
command == Player.COMMAND_SEEK_TO_NEXT ||
command == Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM ||
command == Player.COMMAND_SEEK_TO_PREVIOUS ||
command == Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM ||
super.isCommandAvailable(command)
override fun seekToNext() {
if (!PlaybackCommands.next()) super.seekToNext()
}
override fun seekToNextMediaItem() {
if (!PlaybackCommands.next()) super.seekToNextMediaItem()
}
override fun seekToPrevious() {
if (!PlaybackCommands.previous()) super.seekToPrevious()
}
override fun seekToPreviousMediaItem() {
if (!PlaybackCommands.previous()) super.seekToPreviousMediaItem()
}
}
val sessionActivity = PendingIntent.getActivity( val sessionActivity = PendingIntent.getActivity(
this, this,
0, 0,
@@ -73,6 +115,38 @@ class PlaybackService : MediaSessionService() {
.build() .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( override fun onCustomCommand(
session: MediaSession, session: MediaSession,
controller: MediaSession.ControllerInfo, controller: MediaSession.ControllerInfo,
@@ -184,9 +184,6 @@ 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( suspend fun search(
query: String, query: String,
limit: Int = 10, limit: Int = 10,
@@ -108,8 +108,22 @@ data class MoodDetail(
val mood: Mood, val mood: Mood,
val songs: List<MoodSong> = emptyList(), val songs: List<MoodSong> = emptyList(),
val recommendations: List<Recommendation> = 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 @Serializable
data class MoodsResponse(val moods: List<Mood> = emptyList()) data class MoodsResponse(val moods: List<Mood> = emptyList())
@@ -34,5 +34,12 @@ interface AudioPlayer {
* their own countdown for the UI either way. * their own countdown for the UI either way.
*/ */
fun scheduleSleepTimer(seconds: Long?): Boolean = false 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.ApiClient
import win.taptap.musicmanager.client.api.ApiException import win.taptap.musicmanager.client.api.ApiException
import win.taptap.musicmanager.client.api.CreateMoodRequest 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.Mood
import win.taptap.musicmanager.client.api.MoodDetail import win.taptap.musicmanager.client.api.MoodDetail
import win.taptap.musicmanager.client.api.PlaybackEvent import win.taptap.musicmanager.client.api.PlaybackEvent
@@ -44,7 +45,6 @@ data class AppState(
val screen: Screen = Screen.Moods, val screen: Screen = Screen.Moods,
val moods: List<Mood> = emptyList(), val moods: List<Mood> = emptyList(),
val selectedMood: MoodDetail? = null, val selectedMood: MoodDetail? = null,
val preview: List<Song> = emptyList(),
val session: Session? = null, val session: Session? = null,
val queue: List<Song> = emptyList(), val queue: List<Song> = emptyList(),
val current: Song? = null, val current: Song? = null,
@@ -60,6 +60,8 @@ data class AppState(
val searchQuery: String = "", val searchQuery: String = "",
val searchResults: List<SearchResult> = emptyList(), val searchResults: List<SearchResult> = emptyList(),
val searchTargetMoodId: String? = null, 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 searching: Boolean = false,
val loading: Boolean = false, val loading: Boolean = false,
val saving: Boolean = false, val saving: Boolean = false,
@@ -96,9 +98,13 @@ class AppStore(
private var trackStartOffset = 0.0 private var trackStartOffset = 0.0
private var dataGeneration = 0 private var dataGeneration = 0
private var moodRequestGeneration = 0 private var moodRequestGeneration = 0
private var searchTargetGeneration = 0
private var loggingOut = false private var loggingOut = false
init { 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() bootstrap()
} }
@@ -275,23 +281,19 @@ class AppStore(
loading = true, loading = true,
screen = Screen.MoodDetail, screen = Screen.MoodDetail,
selectedMood = null, selectedMood = null,
preview = emptyList(),
) )
} }
try { try {
val detail = api.mood(id) val detail = api.mood(id)
val preview = runCatching { api.preview(id, 20) }.getOrDefault(emptyList())
if (request != moodRequestGeneration) return@launch if (request != moodRequestGeneration) return@launch
cacheDetail(detail) cacheDetail(detail)
_state.update { _state.update {
it.copy( it.copy(
loading = false, loading = false,
selectedMood = detail, selectedMood = detail,
preview = preview,
knownSongs = it.knownSongs + detail.songMap(), knownSongs = it.knownSongs + detail.songMap(),
) )
} }
mergeSongs(preview)
} catch (t: Throwable) { } catch (t: Throwable) {
if (request != moodRequestGeneration) return@launch if (request != moodRequestGeneration) return@launch
val cached = cache.load().moodDetails.firstOrNull { it.mood.id == id } val cached = cache.load().moodDetails.firstOrNull { it.mood.id == id }
@@ -300,7 +302,6 @@ class AppStore(
loading = false, loading = false,
// Never leave a different mood editable under the new title. // Never leave a different mood editable under the new title.
selectedMood = cached, selectedMood = cached,
preview = emptyList(),
knownSongs = it.knownSongs + (cached?.songMap() ?: emptyMap()), knownSongs = it.knownSongs + (cached?.songMap() ?: emptyMap()),
message = if (cached == null) t.friendlyMessage() else "Showing cached mood", message = if (cached == null) t.friendlyMessage() else "Showing cached mood",
messageIsError = cached == null, messageIsError = cached == null,
@@ -333,6 +334,7 @@ class AppStore(
searchQuery = "", searchQuery = "",
) )
} }
_state.value.searchTargetMoodId?.let(::loadSearchTarget)
} }
fun openDownloads() { fun openDownloads() {
@@ -345,22 +347,43 @@ class AppStore(
fun selectSearchMood(moodId: String) { fun selectSearchMood(moodId: String) {
_state.update { it.copy(searchTargetMoodId = moodId) } _state.update { it.copy(searchTargetMoodId = moodId) }
loadSearchTarget(moodId)
if (_state.value.searchQuery.isNotBlank()) search(_state.value.searchQuery) 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) { fun setSearchQuery(query: String) {
_state.update { it.copy(searchQuery = query) } _state.update { it.copy(searchQuery = query) }
search(query) search(query)
} }
fun search(query: String) { fun search(query: String) {
runSearch(query, debounce = true)
}
/**
* A source change is explicit, so it re-runs the query immediately instead
* of waiting for the keystroke debounce.
*/
private fun runSearch(query: String, debounce: Boolean) {
searchJob?.cancel() searchJob?.cancel()
if (query.isBlank()) { if (query.isBlank()) {
_state.update { it.copy(searchResults = emptyList(), searching = false) } _state.update { it.copy(searchResults = emptyList(), searching = false) }
return return
} }
searchJob = scope.launch { searchJob = scope.launch {
delay(SEARCH_DEBOUNCE_MS) if (debounce) delay(SEARCH_DEBOUNCE_MS)
_state.update { it.copy(searching = true) } _state.update { it.copy(searching = true) }
try { try {
val target = _state.value.moods.firstOrNull { val target = _state.value.moods.firstOrNull {
@@ -407,10 +430,14 @@ class AppStore(
externalId = result.externalId, externalId = result.externalId,
) )
} }
searchTargetGeneration++
applyMoodDetail(response.detail) applyMoodDetail(response.detail)
val title = response.detail.mood.name val title = response.detail.mood.name
if (response.downloading) { 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 { _state.update {
it.copy( it.copy(
@@ -530,7 +557,7 @@ class AppStore(
if (_state.value.searchTargetMoodId == moodId && if (_state.value.searchTargetMoodId == moodId &&
_state.value.searchQuery.isNotBlank() _state.value.searchQuery.isNotBlank()
) { ) {
search(_state.value.searchQuery) runSearch(_state.value.searchQuery, debounce = false)
} }
} catch (t: Throwable) { } catch (t: Throwable) {
message(t) message(t)
@@ -1107,6 +1134,7 @@ class AppStore(
} }
fun release() { fun release() {
player.setSkipCallbacks(onNext = null, onPrevious = null)
persistPlayback() persistPlayback()
pollJob?.cancel() pollJob?.cancel()
refreshJob?.cancel() refreshJob?.cancel()
@@ -1312,6 +1340,11 @@ class AppStore(
}, },
moods = state.moods.map { mood -> if (mood.id == detail.mood.id) detail.mood else mood }, moods = state.moods.map { mood -> if (mood.id == detail.mood.id) detail.mood else mood },
knownSongs = state.knownSongs + detail.songMap(), 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 +1358,24 @@ class AppStore(
* A song added while its download is still running is not in the detail * 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. * 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) { private fun pollUntilSongCount(moodId: String, expectedAtLeast: Int) {
scope.launch { scope.launch {
repeat(DOWNLOAD_POLLS) { repeat(DOWNLOAD_POLLS) {
@@ -1407,5 +1458,7 @@ private const val DEFAULT_SOURCE = "deezer"
internal fun sourceLabel(source: String): String = internal fun sourceLabel(source: String): String =
if (source == "deezer") "Deezer" else "YouTube Music" 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_POLL_MS = 4_000L
private const val DOWNLOAD_POLLS = 60 private const val DOWNLOAD_POLLS = 60
@@ -6,6 +6,7 @@ import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
@@ -185,18 +186,6 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
} }
} }
if (state.preview.isNotEmpty()) {
item {
HorizontalDivider(Modifier.padding(vertical = 12.dp))
SectionTitle("Next batch")
}
items(state.preview, key = { "preview-${it.id}" }) { song ->
SongRow(store, song, onPlay = { store.playSong(song) }) {
Text(formatDuration(song.duration), style = MaterialTheme.typography.labelSmall)
}
}
}
item { item {
HorizontalDivider(Modifier.padding(vertical = 12.dp)) HorizontalDivider(Modifier.padding(vertical = 12.dp))
SectionTitle("Recommendations") { SectionTitle("Recommendations") {
@@ -44,9 +44,11 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import win.taptap.musicmanager.client.api.DownloadStatus
import win.taptap.musicmanager.client.api.SearchResult import win.taptap.musicmanager.client.api.SearchResult
import win.taptap.musicmanager.client.store.AppState import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore import win.taptap.musicmanager.client.store.AppStore
import win.taptap.musicmanager.client.store.downloadKey
import win.taptap.musicmanager.client.store.sourceLabel import win.taptap.musicmanager.client.store.sourceLabel
@Composable @Composable
@@ -185,7 +187,11 @@ fun SearchScreen(state: AppState, store: AppStore) {
} }
items(state.searchResults, key = { "${it.source}-${it.externalId}" }) { result -> 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)) } item { Spacer(Modifier.size(24.dp)) }
@@ -193,7 +199,9 @@ fun SearchScreen(state: AppState, store: AppStore) {
} }
@Composable @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( Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp), modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
@@ -218,8 +226,43 @@ private fun SearchRow(result: SearchResult, store: AppStore) {
maxLines = 1, maxLines = 1,
overflow = TextOverflow.Ellipsis, overflow = TextOverflow.Ellipsis,
) )
if (result.inMood) { when {
Row(verticalAlignment = Alignment.CenterVertically) { 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( Icon(
Icons.Rounded.Check, Icons.Rounded.Check,
contentDescription = null, contentDescription = null,
@@ -233,8 +276,8 @@ private fun SearchRow(result: SearchResult, store: AppStore) {
color = MaterialTheme.colorScheme.primary, color = MaterialTheme.colorScheme.primary,
) )
} }
} else if (result.downloaded) {
Row(verticalAlignment = Alignment.CenterVertically) { result.downloaded -> Row(verticalAlignment = Alignment.CenterVertically) {
Icon( Icon(
Icons.Rounded.DownloadDone, Icons.Rounded.DownloadDone,
contentDescription = null, contentDescription = null,
@@ -252,12 +295,16 @@ private fun SearchRow(result: SearchResult, store: AppStore) {
} }
IconButton( IconButton(
onClick = { store.addSearchResult(result) }, onClick = { store.addSearchResult(result) },
enabled = !result.inMood, enabled = !result.inMood && !pending && !added,
) { ) {
if (pending) {
CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp)
} else {
Icon( Icon(
Icons.Rounded.Add, Icons.Rounded.Add,
contentDescription = "Add to ${result.title}", 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)) { Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text("About", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Text("About", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
Text( Text(
"AudioManager 0.3.0 · $platformName", "AudioManager 0.3.3 · $platformName",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
@@ -45,7 +45,6 @@ class AppStoreTest {
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders) "/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods" -> respond("""{"moods":[${moodJson(1)}]}""", HttpStatusCode.OK, jsonHeaders) "/api/v1/moods" -> respond("""{"moods":[${moodJson(1)}]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1" -> respond(detailJson(listOf("a")), HttpStatusCode.OK, jsonHeaders) "/api/v1/moods/mo-1" -> respond(detailJson(listOf("a")), HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1/sessions" -> respond( "/api/v1/moods/mo-1/sessions" -> respond(
"""{"id":"s1","moodId":"mo-1","moodName":"Focus","startedAt":"now", """{"id":"s1","moodId":"mo-1","moodName":"Focus","startedAt":"now",
"queue":[${songJson("a")}]}""", "queue":[${songJson("a")}]}""",
@@ -82,7 +81,6 @@ class AppStoreTest {
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders) "/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods" -> respond("""{"moods":[${moodJson(0)}]}""", HttpStatusCode.OK, jsonHeaders) "/api/v1/moods" -> respond("""{"moods":[${moodJson(0)}]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1" -> respond(detailJson(emptyList()), HttpStatusCode.OK, jsonHeaders) "/api/v1/moods/mo-1" -> respond(detailJson(emptyList()), HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
else -> respondError(HttpStatusCode.NotFound) else -> respondError(HttpStatusCode.NotFound)
} }
} }
@@ -141,6 +139,56 @@ class AppStoreTest {
store.release() 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 @Test
fun `adding a recommendation refreshes the selected mood`() = runTest { fun `adding a recommendation refreshes the selected mood`() = runTest {
val storage = MemoryStorage() val storage = MemoryStorage()
@@ -155,7 +203,6 @@ class AppStoreTest {
HttpStatusCode.OK, HttpStatusCode.OK,
jsonHeaders, jsonHeaders,
) )
"/api/v1/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1/recommendations/v1/add" -> respond( "/api/v1/moods/mo-1/recommendations/v1/add" -> respond(
"""{"detail":${detailJson(listOf("a"))}, """{"detail":${detailJson(listOf("a"))},
"recommendation":${recommendationJson(state = "added", songId = "a")}}""", "recommendation":${recommendationJson(state = "added", songId = "a")}}""",
@@ -195,8 +242,6 @@ class AppStoreTest {
respond(detailJson(emptyList(), source = "deezer"), HttpStatusCode.OK, jsonHeaders) respond(detailJson(emptyList(), source = "deezer"), HttpStatusCode.OK, jsonHeaders)
request.url.encodedPath == "/api/v1/moods/mo-1" -> request.url.encodedPath == "/api/v1/moods/mo-1" ->
respond(detailJson(emptyList()), HttpStatusCode.OK, jsonHeaders) 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" -> { request.url.encodedPath == "/api/v1/search" -> {
val source = request.url.parameters["source"] val source = request.url.parameters["source"]
val body = if (source == "deezer") { val body = if (source == "deezer") {
@@ -221,6 +266,10 @@ class AppStoreTest {
runCurrent() runCurrent()
store.setMoodSource("mo-1", "deezer") store.setMoodSource("mo-1", "deezer")
awaitState("mood source updated") {
store.state.value.moods.first { it.id == "mo-1" }.source == "deezer"
}
// The source change re-runs the search immediately, without debounce.
awaitState { store.state.value.searchResults.any { it.source == "deezer" } } awaitState { store.state.value.searchResults.any { it.source == "deezer" } }
assertEquals("deezer", store.state.value.moods.first { it.id == "mo-1" }.source) assertEquals("deezer", store.state.value.moods.first { it.id == "mo-1" }.source)
@@ -295,7 +344,6 @@ class AppStoreTest {
HttpStatusCode.OK, HttpStatusCode.OK,
jsonHeaders, jsonHeaders,
) )
"/api/v1/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1/sessions" -> respond( "/api/v1/moods/mo-1/sessions" -> respond(
"""{"id":"s1","moodId":"mo-1","moodName":"Focus","startedAt":"now", """{"id":"s1","moodId":"mo-1","moodName":"Focus","startedAt":"now",
"queue":[${songJson("a")},${songJson("b")},${songJson("c")}]}""", "queue":[${songJson("a")},${songJson("b")},${songJson("c")}]}""",
@@ -323,6 +371,52 @@ class AppStoreTest {
store.release() 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/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 @Test
fun `logout clears the session and the mood cache`() = runTest { fun `logout clears the session and the mood cache`() = runTest {
val storage = MemoryStorage() val storage = MemoryStorage()
@@ -355,13 +449,16 @@ class AppStoreTest {
store.release() 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) { repeat(500) {
runCurrent() runCurrent()
if (predicate()) return if (predicate()) return
withContext(Dispatchers.Default) { delay(10) } 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 val jsonHeaders = headersOf(HttpHeaders.ContentType, "application/json")
@@ -389,12 +486,21 @@ class AppStoreTest {
songs: List<String>, songs: List<String>,
recommendation: String? = null, recommendation: String? = null,
source: String = "youtube", source: String = "youtube",
downloads: List<String> = emptyList(),
) = """ ) = """
{"mood":${moodJson(songs.size, source)}, {"mood":${moodJson(songs.size, source)},
"songs":[${songs.joinToString(",") { """{"song":${songJson(it)},"origin":"search","addedAt":"now"}""" }}], "songs":[${songs.joinToString(",") { """{"song":${songJson(it)},"origin":"search","addedAt":"now"}""" }}],
"recommendations":${recommendation?.let { "[$it]" } ?: "[]"}} "recommendations":${recommendation?.let { "[$it]" } ?: "[]"},
"downloads":[${downloads.joinToString(",")}]}
""".trimIndent() """.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( private fun song(id: String, duration: Int = 180) = Song(
id = id, id = id,
source = "youtube", source = "youtube",
@@ -423,6 +529,22 @@ class AppStoreTest {
) )
private class FakePlayer : AudioPlayer { 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 played = mutableListOf<String>()
val seeks = mutableListOf<Double>() val seeks = mutableListOf<Double>()
var paused = false var paused = false