From c7c1d59b7039ee8bd201f6c3a510abed3d97a564 Mon Sep 17 00:00:00 2001 From: TapTap Date: Sun, 15 Nov 2026 08:09:02 +0000 Subject: [PATCH] feat: shuffle the whole library and add a sleep timer Library screen: an "All music" card with Shuffle all, which builds a local queue from every cached song so playback does not need a mood session. Player bar: a sleep timer with 15/30/45/60/90 minute presets. The shared store shows the countdown and pauses playback; on Android the pause is also scheduled inside the media service through a custom session command, so it still fires when the app is backgrounded or the task is swiped away. Playback errors from the platform player now surface in the UI instead of failing silently (for example when no audio device is available). Tests cover shuffle-all, the empty library, timer expiry and cancelling it. --- README.md | 14 +- .../client/MediaControllerAudioPlayer.kt | 7 + .../musicmanager/client/PlaybackService.kt | 46 +++++ .../client/playback/AudioPlayer.kt | 8 + .../musicmanager/client/store/AppStore.kt | 105 ++++++++++- .../musicmanager/client/ui/LibraryScreen.kt | 41 ++++ .../musicmanager/client/ui/PlayerBar.kt | 81 ++++++-- .../musicmanager/client/ApiClientTest.kt | 18 -- .../musicmanager/client/AppStoreTest.kt | 176 ++++++++++++++++++ .../musicmanager/client/MemoryStorage.kt | 24 +++ 10 files changed, 478 insertions(+), 42 deletions(-) create mode 100644 composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/AppStoreTest.kt create mode 100644 composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/MemoryStorage.kt diff --git a/README.md b/README.md index ef2c0bf..6e3a36d 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ The client and server are designed together. There is no OpenSubsonic compatibil | Target | UI | Playback | Offline downloads | | --- | --- | --- | --- | | **Android** | Compose Multiplatform | Media3 / ExoPlayer | Yes | -| **Desktop (JVM)** | Compose Multiplatform | MP3SPI + `SourceDataLine` | Yes | +| **Desktop (JVM)** | Compose Multiplatform | MP3SPI, decoded to PCM + `SourceDataLine` | Yes | | **Web (Wasm)** | Compose Multiplatform | HTML5 `Audio` | Browser-managed cache only | The shared module contains the API client, session/cache storage, radio queue, app state and all screens. Platform code is limited to HTTP engines, storage, audio and back handling. @@ -24,7 +24,8 @@ The shared module contains the API client, session/cache storage, radio queue, a - Two add-to-mood actions in the player: - **Add to current mood** (the mood of the active radio session) - **Choose another mood** (picker) -- Library search and playback. +- Library search and playback, plus **Shuffle all** to queue the whole library without starting a mood. +- **Sleep timer** (15/30/45/60/90 minutes) that pauses playback. On Android the pause is scheduled inside the media service, so it still fires when the app is backgrounded or the task is swiped away. - Offline library cache: moods, songs and the last sync revision are stored locally. When the server is unreachable, downloaded tracks still play. - Original MP3 downloads with progress state, removal and storage usage. - Session persistence: the login survives app restarts until the token is revoked or expires. @@ -43,7 +44,8 @@ composeApp/ |-- src/androidMain/ # Activity, Media3 player, filesystem storage |-- src/desktopMain/ # Main window, MP3SPI player, filesystem storage |-- src/wasmJsMain/ # Compose viewport, HTML audio, localStorage -|-- src/commonTest/ # API parsing and cache tests +|-- src/commonTest/ # API, cache and store tests +|-- src/desktopTest/ # MP3 decoding and PCM conversion tests `-- ci/ # Android SDK CI image ``` @@ -113,7 +115,7 @@ Adding a song makes it a permanent seed, so it is always eligible in future radi ## CI and releases -`.gitea/workflows/ci.yaml` runs on Gitea Actions using `gitea.tap-tap.win/taptap/audiomanager-client-ci:2`. The image has the Android SDK installed and a warmed Gradle dependency cache, so jobs do not download either on every run. +`.gitea/workflows/ci.yaml` runs on Gitea Actions using `gitea.tap-tap.win/taptap/audiomanager-client-ci:3`. The image has the Android SDK, Node, Yarn and a warmed Gradle dependency cache, so jobs do not download them on every run. - **main / PR:** run `desktopTest`, build the Android APK and the *development* Wasm bundle. The optimized Wasm build is CPU-bound and reserved for releases. - **`v*` tag:** additionally build the desktop fat jar and the optimized Wasm bundle, then attach all three to the Gitea release. @@ -124,12 +126,12 @@ Rebuild the CI image after changing `ci/Dockerfile` or dependency versions: scripts/build-ci-image.sh 3 ``` -The image build performs one warm-up compile (`desktopTest`, `assembleDebug`, `compileKotlinWasmJs`) and then removes the sources, keeping only `/root/.gradle`. +The image build performs one warm-up compile (`kotlinNodeJsSetup`, `kotlinYarnSetup`, `desktopTest`, `assembleDebug`, `compileKotlinWasmJs`) and then removes the sources, keeping only `/root/.gradle`. ## Known limitations - The media notification exposes play/pause and seeking. Queue actions (skip, add to mood) stay in the app because the mood session and its events belong to the server. -- Desktop playback cannot seek (sequential decoder); pause/resume and skipping work. +- Desktop playback cannot seek (sequential decoder); pause/resume and skipping work. MP3s are decoded to 16-bit PCM before the line is opened, because Java Sound has no line for the compressed format. - Web downloads are disabled because the browser owns its storage; the app still streams and caches metadata. - YT Music recommendations are displayed when the server provides them; discovery and downloading are server-side roadmap items. - No iOS target yet. The shared module is ready for one. 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 ae44408..e761a80 100644 --- a/composeApp/src/androidMain/kotlin/win/taptap/musicmanager/client/MediaControllerAudioPlayer.kt +++ b/composeApp/src/androidMain/kotlin/win/taptap/musicmanager/client/MediaControllerAudioPlayer.kt @@ -3,6 +3,7 @@ package win.taptap.musicmanager.client import android.content.ComponentName import android.content.Context import android.net.Uri +import android.os.Bundle import androidx.core.content.ContextCompat import androidx.media3.common.MediaItem import androidx.media3.common.MediaMetadata @@ -108,6 +109,12 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer { withController { it.seekTo((seconds * 1000).toLong().coerceAtLeast(0L)) } } + override fun scheduleSleepTimer(seconds: Long?): Boolean { + val current = controller ?: return false + val args = Bundle().apply { putLong(SLEEP_TIMER_SECONDS, seconds ?: 0L) } + return runCatching { current.sendCustomCommand(SLEEP_TIMER_COMMAND, args) }.isSuccess + } + override fun release() { controller?.release() MediaController.releaseFuture(future) 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 bee825c..87340b8 100644 --- a/composeApp/src/androidMain/kotlin/win/taptap/musicmanager/client/PlaybackService.kt +++ b/composeApp/src/androidMain/kotlin/win/taptap/musicmanager/client/PlaybackService.kt @@ -2,11 +2,23 @@ package win.taptap.musicmanager.client import android.app.PendingIntent import android.content.Intent +import android.os.Bundle +import android.os.Handler +import android.os.Looper import androidx.media3.common.AudioAttributes import androidx.media3.common.C import androidx.media3.exoplayer.ExoPlayer import androidx.media3.session.MediaSession import androidx.media3.session.MediaSessionService +import androidx.media3.session.SessionCommand +import androidx.media3.session.SessionResult +import com.google.common.util.concurrent.Futures +import com.google.common.util.concurrent.ListenableFuture + +/** Custom session command used to arm or clear the sleep timer. */ +internal const val SLEEP_TIMER_ACTION = "win.taptap.musicmanager.client.SLEEP_TIMER" +internal const val SLEEP_TIMER_SECONDS = "seconds" +internal val SLEEP_TIMER_COMMAND = SessionCommand(SLEEP_TIMER_ACTION, Bundle.EMPTY) /** * Hosts playback in a foreground service so audio continues when the activity @@ -18,6 +30,8 @@ import androidx.media3.session.MediaSessionService class PlaybackService : MediaSessionService() { private var mediaSession: MediaSession? = null + private val handler = Handler(Looper.getMainLooper()) + private val sleepTimer = Runnable { mediaSession?.player?.pause() } override fun onCreate() { super.onCreate() @@ -45,6 +59,37 @@ class PlaybackService : MediaSessionService() { mediaSession = MediaSession.Builder(this, player) .setSessionActivity(sessionActivity) + .setCallback(object : MediaSession.Callback { + override fun onConnect( + session: MediaSession, + controller: MediaSession.ControllerInfo, + ): MediaSession.ConnectionResult { + val commands = MediaSession.ConnectionResult.DEFAULT_SESSION_AND_LIBRARY_COMMANDS + .buildUpon() + .add(SLEEP_TIMER_COMMAND) + .build() + return MediaSession.ConnectionResult.AcceptedResultBuilder(session) + .setAvailableSessionCommands(commands) + .build() + } + + override fun onCustomCommand( + session: MediaSession, + controller: MediaSession.ControllerInfo, + customCommand: SessionCommand, + args: Bundle, + ): ListenableFuture { + if (customCommand.customAction != SLEEP_TIMER_ACTION) { + return super.onCustomCommand(session, controller, customCommand, args) + } + handler.removeCallbacks(sleepTimer) + val seconds = args.getLong(SLEEP_TIMER_SECONDS, 0L) + if (seconds > 0) { + handler.postDelayed(sleepTimer, seconds * 1_000) + } + return Futures.immediateFuture(SessionResult(SessionResult.RESULT_SUCCESS)) + } + }) .build() } @@ -59,6 +104,7 @@ class PlaybackService : MediaSessionService() { } override fun onDestroy() { + handler.removeCallbacks(sleepTimer) mediaSession?.run { player.release() release() 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 242e76f..eb2d4be 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 @@ -20,5 +20,13 @@ interface AudioPlayer { val canSeek: Boolean fun seekTo(seconds: Double) fun release() + + /** + * Pauses playback after [seconds], or cancels a pending timer with null. + * Returns true when the platform scheduled the pause itself, so it still + * fires when the UI is gone (Android background playback). Callers keep + * their own countdown for the UI either way. + */ + fun scheduleSleepTimer(seconds: Long?): Boolean = false } 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 10ee18e..6ef1dd2 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 @@ -48,6 +48,7 @@ data class AppState( val playing: Boolean = false, val positionSeconds: Double = 0.0, val durationSeconds: Double = 0.0, + val sleepTimerRemainingSeconds: Long? = null, val downloads: Set = emptySet(), val downloading: Set = emptySet(), val library: List = emptyList(), @@ -75,6 +76,7 @@ class AppStore( val state: StateFlow = _state.asStateFlow() private var pollJob: Job? = null + private var sleepJob: Job? = null private var advancing = false private var fetching = false private var finishing = false @@ -471,6 +473,71 @@ class AppStore( } } + /** + * Builds a local queue from the whole library, so playback does not depend on + * a mood session. Shuffled by default because "play everything" is most + * useful as a mix. + */ + fun playAll(shuffled: Boolean = true) { + val state = _state.value + if (state.library.isEmpty()) { + _state.update { + it.copy( + message = "The library is empty. Scan a music folder first.", + messageIsError = true, + messageId = it.messageId + 1, + ) + } + return + } + scope.launch { + state.session?.let { runCatching { api.closeSession(it.id) } } + val queue = if (shuffled) state.library.shuffled(Random.Default) else state.library + _state.update { it.copy(session = null, queue = queue) } + playNext() + } + } + + /** + * Pauses playback after [minutes] so the app does not keep playing while + * falling asleep. Passing null turns the timer off. + */ + fun setSleepTimer(minutes: Int?) { + sleepJob?.cancel() + sleepJob = null + if (minutes == null || minutes <= 0) { + player.scheduleSleepTimer(null) + _state.update { it.copy(sleepTimerRemainingSeconds = null) } + return + } + + // Android hands the pause to the media service so it survives the UI + // being backgrounded or swiped away; the countdown below only drives + // the display and desktop/web playback. + player.scheduleSleepTimer(minutes * 60L) + var remaining = minutes * 60L + _state.update { it.copy(sleepTimerRemainingSeconds = remaining) } + sleepJob = scope.launch { + while (isActive && remaining > 0) { + delay(1_000) + remaining -= 1 + val seconds = remaining.coerceAtLeast(0) + _state.update { it.copy(sleepTimerRemainingSeconds = seconds.takeIf { value -> value > 0 }) } + } + if (!isActive) return@launch + val wasPlaying = _state.value.playing + player.pause() + _state.update { + it.copy( + playing = false, + sleepTimerRemainingSeconds = null, + message = if (wasPlaying) "Sleep timer: playback paused" else null, + messageId = if (wasPlaying) it.messageId + 1 else it.messageId, + ) + } + } + } + fun togglePlayPause() { val state = _state.value if (state.current == null) return @@ -635,6 +702,7 @@ class AppStore( fun release() { pollJob?.cancel() + sleepJob?.cancel() player.release() } @@ -696,12 +764,24 @@ class AppStore( private fun startSong(song: Song) { val localPath = storage.downloadPath(song.id) finishing = false - player.play( - source = localPath ?: api.streamUrl(song.id), - song = song, - local = localPath != null, - artworkUri = api.coverUrl(song.albumId), - ) + try { + player.play( + source = localPath ?: api.streamUrl(song.id), + song = song, + local = localPath != null, + artworkUri = api.coverUrl(song.albumId), + ) + } catch (t: Throwable) { + _state.update { + it.copy( + playing = false, + message = "Playback failed: ${t.message ?: "unknown error"}", + messageIsError = true, + messageId = it.messageId + 1, + ) + } + return + } startPolling() } @@ -752,8 +832,19 @@ class AppStore( private fun stopPlayback() { pollJob?.cancel() + sleepJob?.cancel() + sleepJob = null + player.scheduleSleepTimer(null) player.stop() - _state.update { it.copy(current = null, playing = false, queue = emptyList(), session = null) } + _state.update { + it.copy( + current = null, + playing = false, + queue = emptyList(), + session = null, + sleepTimerRemainingSeconds = null, + ) + } } private fun cacheDetail(detail: MoodDetail) { diff --git a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/LibraryScreen.kt b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/LibraryScreen.kt index 1933c1e..9113196 100644 --- a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/LibraryScreen.kt +++ b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/LibraryScreen.kt @@ -4,10 +4,13 @@ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.icons.Icons @@ -16,12 +19,15 @@ import androidx.compose.material.icons.rounded.DeleteOutline import androidx.compose.material.icons.rounded.Download import androidx.compose.material.icons.rounded.PlayArrow import androidx.compose.material.icons.rounded.Search +import androidx.compose.material.icons.rounded.Shuffle +import androidx.compose.material3.Button import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue @@ -64,6 +70,41 @@ fun LibraryScreen(state: AppState, store: AppStore) { ) } + item { + Surface( + shape = RoundedCornerShape(18.dp), + color = MaterialTheme.colorScheme.surfaceVariant, + modifier = Modifier.fillMaxWidth(), + ) { + Row( + modifier = Modifier.padding(16.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Column(Modifier.weight(1f)) { + Text("All music", style = MaterialTheme.typography.titleMedium) + Text( + if (state.library.isEmpty()) { + "Nothing in the library yet" + } else { + "${state.library.size} tracks, shuffled into a queue" + }, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + Button( + onClick = { store.playAll() }, + enabled = state.library.isNotEmpty(), + ) { + Icon(Icons.Rounded.Shuffle, contentDescription = null, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(6.dp)) + Text("Shuffle all") + } + } + } + } + if (state.searchResults.isNotEmpty()) { item { SectionTitle("Search results") { diff --git a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/PlayerBar.kt b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/PlayerBar.kt index 61beb17..64e764b 100644 --- a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/PlayerBar.kt +++ b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/PlayerBar.kt @@ -1,6 +1,7 @@ package win.taptap.musicmanager.client.ui import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer @@ -10,10 +11,14 @@ import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width 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.Pause import androidx.compose.material.icons.rounded.PlayArrow import androidx.compose.material.icons.rounded.PlaylistAdd import androidx.compose.material.icons.rounded.SkipNext +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme @@ -36,7 +41,9 @@ import win.taptap.musicmanager.client.store.AppStore fun PlayerBar(state: AppState, store: AppStore) { val song = state.current ?: return var picker by remember { mutableStateOf(false) } + var sleepMenu by remember { mutableStateOf(false) } var dragSeconds by remember(song.id) { mutableStateOf(null) } + val sleepRemaining = state.sleepTimerRemainingSeconds Surface( color = MaterialTheme.colorScheme.surfaceVariant, @@ -48,16 +55,58 @@ fun PlayerBar(state: AppState, store: AppStore) { } else { 0f } - Slider( - value = dragSeconds ?: progress, - onValueChange = { dragSeconds = it }, - onValueChangeFinished = { - dragSeconds?.let { store.seekTo(it * state.durationSeconds) } - dragSeconds = null - }, - enabled = store.canSeek(), - modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp), - ) + Row( + modifier = Modifier.fillMaxWidth().padding(start = 8.dp, end = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Slider( + value = dragSeconds ?: progress, + onValueChange = { dragSeconds = it }, + onValueChangeFinished = { + dragSeconds?.let { store.seekTo(it * state.durationSeconds) } + dragSeconds = null + }, + enabled = store.canSeek(), + modifier = Modifier.weight(1f), + ) + Box { + IconButton(onClick = { sleepMenu = true }) { + Icon( + Icons.Rounded.Bedtime, + contentDescription = "Sleep timer", + tint = if (sleepRemaining != null) { + MaterialTheme.colorScheme.primary + } else { + MaterialTheme.colorScheme.onSurfaceVariant + }, + ) + } + DropdownMenu( + expanded = sleepMenu, + onDismissRequest = { sleepMenu = false }, + ) { + listOf(15, 30, 45, 60, 90).forEach { minutes -> + DropdownMenuItem( + text = { Text("$minutes minutes") }, + onClick = { + sleepMenu = false + store.setSleepTimer(minutes) + }, + ) + } + if (sleepRemaining != null) { + HorizontalDivider() + DropdownMenuItem( + text = { Text("Turn off") }, + onClick = { + sleepMenu = false + store.setSleepTimer(null) + }, + ) + } + } + } + } Row( modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 8.dp, bottom = 8.dp), @@ -80,9 +129,19 @@ fun PlayerBar(state: AppState, store: AppStore) { overflow = TextOverflow.Ellipsis, ) Text( - "${formatDuration(state.positionSeconds.toInt())} / ${formatDuration(state.durationSeconds.toInt())}", + buildString { + append(formatDuration(state.positionSeconds.toInt())) + append(" / ") + append(formatDuration(state.durationSeconds.toInt())) + if (sleepRemaining != null) { + append(" ยท sleep ") + append(formatDuration(sleepRemaining.toInt())) + } + }, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, ) } diff --git a/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/ApiClientTest.kt b/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/ApiClientTest.kt index 1a5960a..469852d 100644 --- a/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/ApiClientTest.kt +++ b/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/ApiClientTest.kt @@ -93,22 +93,4 @@ class ApiClientTest { assertEquals("2026-11-14T00:00:00Z", loaded.revision) assertEquals("alice", loaded.userName) } - - private class MemoryStorage : AppStorage { - private val files = mutableMapOf() - override fun read(name: String): String? = files[name] - override fun write(name: String, text: String) { - files[name] = text - } - - override fun delete(name: String) { - files.remove(name) - } - - override fun saveDownload(songId: String, bytes: ByteArray): String? = null - override fun downloadPath(songId: String): String? = null - override fun listDownloads(): Map = emptyMap() - override fun deleteDownload(songId: String) = Unit - override fun storageUsedBytes(): Long = 0 - } } diff --git a/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/AppStoreTest.kt b/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/AppStoreTest.kt new file mode 100644 index 0000000..1e70d4c --- /dev/null +++ b/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/AppStoreTest.kt @@ -0,0 +1,176 @@ +package win.taptap.musicmanager.client + +import io.ktor.client.engine.mock.MockEngine +import io.ktor.client.engine.mock.respondError +import io.ktor.http.HttpStatusCode +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import win.taptap.musicmanager.client.api.ApiClient +import win.taptap.musicmanager.client.api.Song +import win.taptap.musicmanager.client.api.configuredHttpClient +import win.taptap.musicmanager.client.data.CachedState +import win.taptap.musicmanager.client.data.LibraryCache +import win.taptap.musicmanager.client.playback.AudioPlayer +import win.taptap.musicmanager.client.store.AppStore + +@OptIn(ExperimentalCoroutinesApi::class) +class AppStoreTest { + + @Test + fun `play all queues the whole library and starts playback`() = runTest { + val storage = MemoryStorage() + val cache = LibraryCache(storage) + val songs = listOf(song("a"), song("b"), song("c")) + cache.save(CachedState(serverUrl = "http://music", songs = songs)) + val player = FakePlayer() + val store = store(storage, cache, player) + runCurrent() + + store.playAll() + runCurrent() + + val state = store.state.value + val current = assertNotNull(state.current) + assertTrue(state.playing) + assertEquals(listOf(current.id), player.played) + assertEquals(2, state.queue.size) + assertEquals(songs.map { it.id }.toSet(), (state.queue + current).map { it.id }.toSet()) + store.release() + } + + @Test + fun `play all reports an empty library instead of starting playback`() = runTest { + val storage = MemoryStorage() + val cache = LibraryCache(storage) + val player = FakePlayer() + val store = store(storage, cache, player) + runCurrent() + + store.playAll() + runCurrent() + + assertNull(store.state.value.current) + assertTrue(player.played.isEmpty()) + assertTrue(store.state.value.messageIsError) + store.release() + } + + @Test + fun `sleep timer pauses playback when it expires`() = runTest { + val storage = MemoryStorage() + val cache = LibraryCache(storage) + val player = FakePlayer() + val store = store(storage, cache, player) + runCurrent() + + store.playSong(song("a")) + runCurrent() + assertTrue(store.state.value.playing) + + store.setSleepTimer(1) + assertEquals(60L, store.state.value.sleepTimerRemainingSeconds) + + advanceTimeBy(60_000) + runCurrent() + + val state = store.state.value + assertFalse(state.playing) + assertNull(state.sleepTimerRemainingSeconds) + assertTrue(player.paused) + store.release() + } + + @Test + fun `turning the sleep timer off keeps playback running`() = runTest { + val storage = MemoryStorage() + val cache = LibraryCache(storage) + val player = FakePlayer() + val store = store(storage, cache, player) + runCurrent() + + store.playSong(song("a")) + runCurrent() + + store.setSleepTimer(30) + assertEquals(1_800L, store.state.value.sleepTimerRemainingSeconds) + store.setSleepTimer(null) + assertNull(store.state.value.sleepTimerRemainingSeconds) + + advanceTimeBy(120_000) + runCurrent() + assertTrue(store.state.value.playing) + store.release() + } + + private fun kotlinx.coroutines.test.TestScope.store( + storage: MemoryStorage, + cache: LibraryCache, + player: AudioPlayer, + ): AppStore = AppStore( + scope = this, + api = ApiClient(configuredHttpClient(MockEngine { respondError(HttpStatusCode.NotFound) })), + storage = storage, + player = player, + cache = cache, + ) + + private fun song(id: String) = Song( + id = id, + title = "Song $id", + artist = "Artist", + album = "Album", + albumId = "al-1", + duration = 180, + bitRate = 320, + size = 1_000, + suffix = "mp3", + folderId = 1, + relativePath = "$id.mp3", + updatedAt = "2026-01-01T00:00:00Z", + ) + + private class FakePlayer : AudioPlayer { + val played = mutableListOf() + var paused = false + private set + private var playing = false + + override fun play(source: String, song: Song, local: Boolean, artworkUri: String?) { + played += song.id + playing = true + paused = false + } + + override fun pause() { + playing = false + paused = true + } + + override fun resume() { + playing = true + paused = false + } + + override fun stop() { + playing = false + } + + override fun isPlaying(): Boolean = playing + override fun isFinished(): Boolean = false + override fun positionSeconds(): Double = 0.0 + override fun durationSeconds(): Double = 0.0 + override val canSeek: Boolean = false + override fun seekTo(seconds: Double) = Unit + override fun release() { + playing = false + } + } +} diff --git a/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/MemoryStorage.kt b/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/MemoryStorage.kt new file mode 100644 index 0000000..13796df --- /dev/null +++ b/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/MemoryStorage.kt @@ -0,0 +1,24 @@ +package win.taptap.musicmanager.client + +import win.taptap.musicmanager.client.data.AppStorage + +/** In-memory [AppStorage] for store and cache tests. */ +internal class MemoryStorage : AppStorage { + private val files = mutableMapOf() + + override fun read(name: String): String? = files[name] + + override fun write(name: String, text: String) { + files[name] = text + } + + override fun delete(name: String) { + files.remove(name) + } + + override fun saveDownload(songId: String, bytes: ByteArray): String? = null + override fun downloadPath(songId: String): String? = null + override fun listDownloads(): Map = emptyMap() + override fun deleteDownload(songId: String) = Unit + override fun storageUsedBytes(): Long = 0 +}