diff --git a/README.md b/README.md index d99614c..17b9ab9 100644 --- a/README.md +++ b/README.md @@ -24,8 +24,10 @@ 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) -- YT Music recommendations in the mood editor: refresh on demand, accept or reject candidates, thumbnails, and a clear state for library matches (`Seed added`), accepted-for-download tracks and new picks. Accepting a track the library already has adds it as a seed immediately. +- YT Music recommendations in the mood editor: refresh on demand, accept or reject candidates, thumbnails, and a clear state for library matches (`Seed added`), accepted-for-download tracks (`Queued`, `Downloading`, `Download failed` with retry) and new picks. Accepting a track the library already has adds it as a seed immediately; the rest are downloaded by the server and promoted automatically. - Library search and playback, plus **Shuffle all** to queue the whole library without starting a mood. +- A queue sheet from the player: the current track plus every upcoming track, with move up/down and remove. Changes are persisted locally. +- **Longform tab** for audiobooks and podcasts: per-artist read-only playlists, “Shuffle artist” for random episodes, a resume list with progress, and a separate search scope. Long-form never enters music search, Shuffle all, moods or radio. - **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. - The play queue and current track are saved locally, so a restart reopens the player paused and resumes on the next tap. @@ -95,11 +97,12 @@ Android cleartext HTTP is enabled for local development. Use HTTPS in production `AppStore` is a plain Kotlin class with a `StateFlow`; Compose observes it. It owns: - **Auth** — restore token, refresh token, logout. -- **Library sync** — first launch pages through `/library/songs`; later launches use the `since` delta and tombstones. +- **Library sync** — first launch pages through `/library/songs`; later launches use the `since` delta and tombstones. Songs are split into music and longform using the folders assigned at login, so the two never mix client-side. - **Mood cache** — mood details are stored so the app can open them offline. - **Radio** — one session per mood, batches of 12, prefetch when the queue is short, no repeats within a session. - **Downloads** — stored under the platform app directory, keyed by deterministic song ID. - **Playback snapshot** — the session, upcoming queue and current track are persisted on every queue change and restored on the next launch. +- **Longform progress** — position is saved locally and to `/longform/progress` while playing, on pause and on track changes; the resume list is fed from the server when online. - **Offline retry** — a background loop retries the library sync until the server responds again. On startup the app is usable before the network call completes: cached moods and library render immediately, then refresh in the background. @@ -137,8 +140,8 @@ The image build performs one warm-up compile (`kotlinNodeJsSetup`, `kotlinYarnSe ## 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. MP3s are decoded to 16-bit PCM before the line is opened, because Java Sound has no line for the compressed format. +- Desktop playback cannot seek (sequential decoder); pause/resume and skipping work. Longform resume therefore starts from the beginning on desktop. 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. -- Accepted recommendations that are not in the library wait for the server-side downloader before they can be played. +- Accepted recommendations are downloaded by the server into `/AudioManager Imports`, scanned and added as seeds. The server needs outbound network access for this. - YT Music discovery runs server-side through `yt-dlp`; downloading accepted tracks that are not in the library is still roadmap. - No iOS target yet. The shared module is ready for one. diff --git a/composeApp/build.gradle.kts b/composeApp/build.gradle.kts index 55c4645..943c71f 100644 --- a/composeApp/build.gradle.kts +++ b/composeApp/build.gradle.kts @@ -47,6 +47,7 @@ kotlin { implementation("io.ktor:ktor-serialization-kotlinx-json:3.1.2") implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.1") implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.8.0") + implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.6.2") } commonTest.dependencies { diff --git a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/api/ApiClient.kt b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/api/ApiClient.kt index 5a0cca7..0925539 100644 --- a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/api/ApiClient.kt +++ b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/api/ApiClient.kt @@ -12,6 +12,7 @@ import io.ktor.client.request.get import io.ktor.client.request.header import io.ktor.client.request.patch import io.ktor.client.request.post +import io.ktor.client.request.put import io.ktor.client.request.setBody import io.ktor.client.statement.HttpResponse import io.ktor.client.statement.bodyAsBytes @@ -162,8 +163,10 @@ class ApiClient(private val http: HttpClient) { suspend fun preview(moodId: String, limit: Int = 20): List = get("/moods/$moodId/preview?limit=$limit").songs - suspend fun search(query: String, limit: Int = 50): List = - get("/library/search?q=${query.encodeURLParameter()}&limit=$limit").songs + suspend fun search(query: String, limit: Int = 50, scope: String = "music"): List = + get( + "/library/search?q=${query.encodeURLParameter()}&limit=$limit&scope=$scope", + ).songs suspend fun library( cursor: String? = null, @@ -221,6 +224,23 @@ class ApiClient(private val http: HttpClient) { runCatching { requestNoContent { http.delete(url("/sessions/$id")) { auth() } } } } + suspend fun longformProgress(): List = + get("/longform/progress").items + + suspend fun saveLongformProgress( + songId: String, + positionSeconds: Int, + durationSeconds: Int, + completed: Boolean, + ) { + val response = http.put(url("/longform/progress/$songId")) { + auth() + contentType(ContentType.Application.Json) + setBody(SaveLongformProgressRequest(positionSeconds, durationSeconds, completed)) + } + if (!response.status.isSuccess()) throw error(response) + } + suspend fun devices(): List = get("/auth/devices") suspend fun scanStatus(): ScanStatus = get("/scan") 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 3cf3cab..ff21df5 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 @@ -79,6 +79,14 @@ data class Seed( val addedAt: String, ) +@Serializable +data class Download( + val state: String, + val attempts: Int = 0, + val error: String? = null, + val updatedAt: String, +) + @Serializable data class Recommendation( val videoId: String, @@ -92,6 +100,35 @@ data class Recommendation( val timesAdded: Int = 0, val firstSeen: String, val lastSeen: String, + val download: Download? = null, +) + +@Serializable +data class LongformProgressItem( + val song: Song, + val positionSeconds: Int, + val durationSeconds: Int, + val completed: Boolean, + val updatedAt: String, +) + +@Serializable +data class LongformProgressResponse(val items: List = emptyList()) + +@Serializable +data class SaveLongformProgressRequest( + val positionSeconds: Int, + val durationSeconds: Int? = null, + val completed: Boolean = false, +) + +@Serializable +data class LongformProgress( + val songId: String, + val positionSeconds: Int, + val durationSeconds: Int, + val completed: Boolean, + val updatedAt: String, ) @Serializable diff --git a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/data/LibraryCache.kt b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/data/LibraryCache.kt index 88cf250..b95fc3a 100644 --- a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/data/LibraryCache.kt +++ b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/data/LibraryCache.kt @@ -2,6 +2,7 @@ package win.taptap.musicmanager.client.data import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json +import win.taptap.musicmanager.client.api.LongformProgress import win.taptap.musicmanager.client.api.Mood import win.taptap.musicmanager.client.api.MoodDetail import win.taptap.musicmanager.client.api.Session @@ -21,6 +22,7 @@ data class CachedState( val userName: String = "", val revision: String? = null, val songs: List = emptyList(), + val longform: List = emptyList(), val moods: List = emptyList(), val moodDetails: List = emptyList(), ) @@ -72,14 +74,25 @@ class LibraryCache(private val storage: AppStorage) { } } + fun loadProgress(): List = + storage.read(PROGRESS_FILE)?.let { + runCatching { json.decodeFromString>(it) }.getOrNull() + } ?: emptyList() + + fun saveProgress(progress: List) { + storage.write(PROGRESS_FILE, json.encodeToString(progress)) + } + fun clear() { storage.delete(CACHE_FILE) storage.delete(PLAYBACK_FILE) + storage.delete(PROGRESS_FILE) } private companion object { const val SESSION_FILE = "session.json" const val CACHE_FILE = "library.json" const val PLAYBACK_FILE = "playback.json" + const val PROGRESS_FILE = "longform-progress.json" } } 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 38800a4..51f077c 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 @@ -9,6 +9,7 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update +import kotlinx.datetime.Clock import kotlin.random.Random import win.taptap.musicmanager.client.api.ApiClient import win.taptap.musicmanager.client.createAudioPlayer @@ -17,6 +18,8 @@ import win.taptap.musicmanager.client.platformName import win.taptap.musicmanager.client.platformStorage import win.taptap.musicmanager.client.api.ApiException import win.taptap.musicmanager.client.api.CreateMoodRequest +import win.taptap.musicmanager.client.api.LongformProgress +import win.taptap.musicmanager.client.api.LongformProgressItem import win.taptap.musicmanager.client.api.Mood import win.taptap.musicmanager.client.api.MoodDetail import win.taptap.musicmanager.client.api.PlaybackEvent @@ -53,6 +56,9 @@ data class AppState( val downloads: Set = emptySet(), val downloading: Set = emptySet(), val library: List = emptyList(), + val longform: List = emptyList(), + val longformResults: List = emptyList(), + val longformProgress: Map = emptyMap(), val searchResults: List = emptyList(), val searching: Boolean = false, val loading: Boolean = false, @@ -84,6 +90,7 @@ class AppStore( private var advancing = false private var fetching = false private var finishing = false + private var pollTicks = 0 init { bootstrap() @@ -94,12 +101,15 @@ class AppStore( val session = cache.loadSession() val cached = cache.load() val playback = cache.loadPlayback() + val progress = cache.loadProgress() _state.update { it.copy( booting = false, downloads = storage.listDownloads().keys, moods = cached.moods, library = cached.songs.sortedLibrary(), + longform = cached.longform.sortedLibrary(), + longformProgress = progress.associateBy { entry -> entry.songId }, selectedMood = cached.moodDetails.firstOrNull(), session = playback?.session, queue = playback?.queue.orEmpty(), @@ -197,23 +207,37 @@ class AppStore( } val details = cached.moodDetails.filter { detail -> moods.any { it.id == detail.mood.id } } + val longformFolders = longformFolders() + val allSongs = songs.values.toList() + val longformSongs = allSongs.filter { it.folderId in longformFolders } + val musicSongs = allSongs.filterNot { it.folderId in longformFolders } + val serverProgress = runCatching { api.longformProgress() }.getOrNull() + cache.save( CachedState( serverUrl = _state.value.serverUrl, userName = _state.value.user?.name.orEmpty(), revision = revision, - songs = songs.values.toList(), + songs = musicSongs, + longform = longformSongs, moods = moods, moodDetails = details, ), ) + serverProgress?.let { items -> + cache.saveProgress(items.map { it.toProgress() }) + } _state.update { it.copy( loading = false, offline = false, moods = moods, - library = songs.values.sortedLibrary(), + library = musicSongs.sortedLibrary(), + longform = longformSongs.sortedLibrary(), + longformProgress = serverProgress + ?.associate { item -> item.song.id to item.toProgress() } + ?: it.longformProgress, ) } } catch (t: Throwable) { @@ -261,6 +285,14 @@ class AppStore( } } + /** Refreshes the open mood, used while downloads are still running. */ + fun refreshSelectedMood() { + val moodId = _state.value.selectedMood?.mood?.id ?: return + scope.launch { + runCatching { api.mood(moodId) }.onSuccess { applyMoodDetail(it) } + } + } + fun openLibrary() { _state.update { it.copy(screen = Screen.Library) } } @@ -433,6 +465,23 @@ class AppStore( } } + fun searchLongform(query: String) { + if (query.isBlank()) { + _state.update { it.copy(longformResults = emptyList()) } + return + } + scope.launch { + _state.update { it.copy(searching = true) } + try { + val songs = api.search(query, 60, scope = "longform") + _state.update { it.copy(searching = false, longformResults = songs) } + } catch (t: Throwable) { + _state.update { it.copy(searching = false, longformResults = emptyList()) } + message(t) + } + } + } + fun playMood(moodId: String) { scope.launch { val state = _state.value @@ -522,6 +571,69 @@ class AppStore( } } + /** Queues every long-form track of one artist, shuffled by default. */ + fun playLongformArtist(artist: String, shuffled: Boolean = true) { + val songs = _state.value.longform.filter { it.artist == artist } + if (songs.isEmpty()) return + scope.launch { + _state.value.session?.let { runCatching { api.closeSession(it.id) } } + val queue = if (shuffled) songs.shuffled(Random.Default) else songs + _state.update { it.copy(session = null, queue = queue) } + playNext() + persistPlayback() + } + } + + fun playLongformSong(song: Song, startAtSeconds: Double = 0.0) { + scope.launch { + _state.value.session?.let { runCatching { api.closeSession(it.id) } } + _state.update { + it.copy( + session = null, + queue = emptyList(), + current = song, + playing = true, + positionSeconds = startAtSeconds, + durationSeconds = song.duration.toDouble(), + ) + } + persistPlayback() + startSong(song, startAtSeconds) + } + } + + fun resumeLongform(songId: String) { + val state = _state.value + val song = state.longform.firstOrNull { it.id == songId } ?: return + val startAt = state.longformProgress[songId]?.positionSeconds?.toDouble() ?: 0.0 + playLongformSong(song, startAt) + } + + fun moveInQueue(fromIndex: Int, toIndex: Int) { + _state.update { state -> + if (fromIndex !in state.queue.indices || toIndex !in state.queue.indices || fromIndex == toIndex) { + state + } else { + val queue = state.queue.toMutableList() + val item = queue.removeAt(fromIndex) + queue.add(toIndex, item) + state.copy(queue = queue) + } + } + persistPlayback() + } + + fun removeFromQueue(index: Int) { + _state.update { state -> + if (index !in state.queue.indices) { + state + } else { + state.copy(queue = state.queue.filterIndexed { i, _ -> i != index }) + } + } + persistPlayback() + } + /** * Pauses playback after [minutes] so the app does not keep playing while * falling asleep. Passing null turns the timer off. @@ -628,6 +740,7 @@ class AppStore( if (state.playing) { player.pause() _state.update { it.copy(playing = false) } + reportCurrentProgress(completed = false) } else if (!playbackStarted || player.isFinished()) { // Restored queue or finished track: start it from the beginning. _state.update { @@ -651,6 +764,7 @@ class AppStore( if (!player.canSeek) return player.seekTo(seconds) _state.update { it.copy(positionSeconds = seconds) } + reportCurrentProgress(completed = false) } fun addCurrentToMood(targetMoodId: String?) { @@ -834,6 +948,7 @@ class AppStore( } val song = state.queue.first() + reportCurrentProgress(completed = false) _state.update { it.copy( queue = it.queue.drop(1), @@ -865,9 +980,10 @@ class AppStore( } } - private fun startSong(song: Song) { + private fun startSong(song: Song, startAtSeconds: Double = 0.0) { val localPath = storage.downloadPath(song.id) finishing = false + pollTicks = 0 try { player.play( source = localPath ?: api.streamUrl(song.id), @@ -875,6 +991,9 @@ class AppStore( local = localPath != null, artworkUri = api.coverUrl(song.albumId), ) + if (startAtSeconds > 0 && player.canSeek) { + player.seekTo(startAtSeconds) + } } catch (t: Throwable) { _state.update { it.copy( @@ -905,9 +1024,16 @@ class AppStore( playing = player.isPlaying(), ) } + pollTicks += 1 + if (pollTicks >= PROGRESS_POLL_TICKS) { + pollTicks = 0 + reportCurrentProgress(completed = false) + } + if (player.isFinished()) { if (!finishing) { finishing = true + reportCurrentProgress(completed = true) report("completed", state.current?.id) playNext() } @@ -936,6 +1062,7 @@ class AppStore( } private fun stopPlayback() { + reportCurrentProgress(completed = false) pollJob?.cancel() sleepJob?.cancel() sleepJob = null @@ -996,6 +1123,39 @@ class AppStore( } } + private fun longformFolders(): Set = + _state.value.user?.longformFolders?.toSet().orEmpty() + + private fun reportCurrentProgress(completed: Boolean) { + val state = _state.value + val song = state.current ?: return + if (song.folderId !in longformFolders()) return + val duration = if (state.durationSeconds > 0) state.durationSeconds else song.duration.toDouble() + reportLongformProgress(song.id, state.positionSeconds, duration, completed) + } + + private fun reportLongformProgress( + songId: String, + positionSeconds: Double, + durationSeconds: Double, + completed: Boolean, + ) { + val position = positionSeconds.toInt().coerceAtLeast(0) + val duration = durationSeconds.toInt().coerceAtLeast(0) + val entry = LongformProgress( + songId = songId, + positionSeconds = position, + durationSeconds = duration, + completed = completed, + updatedAt = Clock.System.now().toString(), + ) + _state.update { it.copy(longformProgress = it.longformProgress + (songId to entry)) } + cache.saveProgress(_state.value.longformProgress.values.toList()) + scope.launch { + runCatching { api.saveLongformProgress(songId, position, duration, completed) } + } + } + private fun message(t: Throwable) { _state.update { it.copy( @@ -1018,3 +1178,12 @@ private fun Collection.sortedLibrary(): List = private const val RECONNECT_INITIAL_MS = 15_000L private const val RECONNECT_MAX_MS = 300_000L private const val DOWNLOAD_ATTEMPTS = 3 +private const val PROGRESS_POLL_TICKS = 12 + +private fun LongformProgressItem.toProgress(): LongformProgress = LongformProgress( + songId = song.id, + positionSeconds = positionSeconds, + durationSeconds = durationSeconds, + completed = completed, + updatedAt = updatedAt, +) 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 9113196..cf86d40 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 @@ -1,22 +1,28 @@ package win.taptap.musicmanager.client.ui +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn 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.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.CheckCircle import androidx.compose.material.icons.rounded.DeleteOutline import androidx.compose.material.icons.rounded.Download +import androidx.compose.material.icons.rounded.List import androidx.compose.material.icons.rounded.PlayArrow import androidx.compose.material.icons.rounded.Search import androidx.compose.material.icons.rounded.Shuffle @@ -28,7 +34,10 @@ import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Surface +import androidx.compose.material3.Tab +import androidx.compose.material3.TabRow import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -36,8 +45,11 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.draw.clip +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Dialog +import win.taptap.musicmanager.client.api.LongformProgress import win.taptap.musicmanager.client.api.Song import win.taptap.musicmanager.client.platformName import win.taptap.musicmanager.client.store.AppState @@ -45,6 +57,30 @@ import win.taptap.musicmanager.client.store.AppStore @Composable fun LibraryScreen(state: AppState, store: AppStore) { + var tab by remember { mutableStateOf(0) } + + Column(Modifier.fillMaxSize()) { + TabRow(selectedTabIndex = tab) { + Tab( + selected = tab == 0, + onClick = { tab = 0 }, + text = { Text("Music") }, + ) + Tab( + selected = tab == 1, + onClick = { tab = 1 }, + text = { Text("Longform") }, + ) + } + when (tab) { + 0 -> MusicLibrary(state, store) + else -> LongformLibrary(state, store) + } + } +} + +@Composable +private fun MusicLibrary(state: AppState, store: AppStore) { var query by remember { mutableStateOf("") } val supported = platformName != "web" val downloadedSongs = state.library.filter { it.id in state.downloads } @@ -59,7 +95,7 @@ fun LibraryScreen(state: AppState, store: AppStore) { value = query, onValueChange = { query = it }, singleLine = true, - label = { Text("Search library") }, + label = { Text("Search music") }, leadingIcon = { Icon(Icons.Rounded.Search, contentDescription = null) }, trailingIcon = { if (state.searching) { @@ -164,23 +200,266 @@ fun LibraryScreen(state: AppState, store: AppStore) { } @Composable -private fun LibrarySongRow(song: Song, state: AppState, store: AppStore, supported: Boolean) { - SongRow(store = store, song = song, onPlay = { store.playSong(song) }) { - if (supported) { - when { - song.id in state.downloading -> CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp) - song.id in state.downloads -> { - IconButton(onClick = { store.toggleDownload(song) }) { - Icon(Icons.Rounded.DeleteOutline, contentDescription = "Delete download") +private fun LongformLibrary(state: AppState, store: AppStore) { + var query by remember { mutableStateOf("") } + var artistDialog by remember { mutableStateOf(null) } + val supported = platformName != "web" + + val byArtist = state.longform.groupBy { it.artist } + val artistNames = byArtist.keys.sortedBy { it.lowercase() } + val continueListening = state.longformProgress.values + .asSequence() + .filterNot { it.completed } + .sortedByDescending { it.updatedAt } + .mapNotNull { progress -> + state.longform.firstOrNull { it.id == progress.songId }?.let { it to progress } + } + .take(5) + .toList() + + LazyColumn( + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues(20.dp), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + item { + OutlinedTextField( + value = query, + onValueChange = { + query = it + store.searchLongform(it) + }, + singleLine = true, + label = { Text("Search audiobooks and podcasts") }, + leadingIcon = { Icon(Icons.Rounded.Search, contentDescription = null) }, + trailingIcon = { + if (state.searching) { + CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp) + } + }, + modifier = Modifier.fillMaxWidth(), + ) + } + + if (state.longformResults.isNotEmpty()) { + item { SectionTitle("Search results") } + items(state.longformResults, key = { "lf-search-${it.id}" }) { song -> + LongformSongRow(song, state, store, supported) { store.playLongformSong(song) } + } + item { HorizontalDivider(Modifier.padding(vertical = 14.dp)) } + } + + if (continueListening.isNotEmpty()) { + item { SectionTitle("Continue listening") } + items(continueListening, key = { "continue-${it.first.id}" }) { (song, progress) -> + ContinueRow(song, progress, store) + } + item { HorizontalDivider(Modifier.padding(vertical = 14.dp)) } + } + + item { + SectionTitle("Artists") { + Text( + "${artistNames.size}", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + + if (artistNames.isEmpty()) { + item { + EmptyState( + "No long-form content", + "Add audiobooks or podcasts to a folder of type longform in library.yaml.", + ) + } + } else { + items(artistNames, key = { "artist-$it" }) { artist -> + val songs = byArtist[artist].orEmpty() + ArtistRow( + name = artist, + count = songs.size, + onShuffle = { store.playLongformArtist(artist) }, + onOpen = { artistDialog = artist }, + ) + } + } + } + + artistDialog?.let { artist -> + LongformArtistDialog( + artist = artist, + songs = byArtist[artist].orEmpty(), + state = state, + store = store, + supported = supported, + onDismiss = { artistDialog = null }, + ) + } +} + +@Composable +private fun ContinueRow(song: Song, progress: LongformProgress, store: AppStore) { + val duration = progress.durationSeconds.takeIf { it > 0 } ?: song.duration + val fraction = if (duration > 0) { + (progress.positionSeconds.toFloat() / duration).coerceIn(0f, 1f) + } else { + 0f + } + + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { store.resumeLongform(song.id) } + .padding(vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Cover(store, song.albumId, Modifier.size(44.dp), size = 96) + Column(Modifier.weight(1f)) { + Text(song.title, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text( + song.artist, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Box( + Modifier + .fillMaxWidth() + .padding(top = 4.dp) + .height(3.dp) + .clip(RoundedCornerShape(2.dp)) + .background(MaterialTheme.colorScheme.surfaceVariant), + ) { + Box( + Modifier + .fillMaxWidth(fraction) + .height(3.dp) + .background(MaterialTheme.colorScheme.primary), + ) + } + Text( + "${formatDuration(progress.positionSeconds)} / ${formatDuration(duration)}", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + IconButton(onClick = { store.resumeLongform(song.id) }) { + Icon(Icons.Rounded.PlayArrow, contentDescription = "Resume") + } + } +} + +@Composable +private fun ArtistRow( + name: String, + count: Int, + onShuffle: () -> Unit, + onOpen: () -> Unit, +) { + Row( + modifier = Modifier.fillMaxWidth().clickable(onClick = onOpen).padding(vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Column(Modifier.weight(1f)) { + Text(name, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text( + "$count tracks", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + IconButton(onClick = onShuffle) { + Icon(Icons.Rounded.Shuffle, contentDescription = "Play $name shuffled") + } + IconButton(onClick = onOpen) { + Icon(Icons.Rounded.List, contentDescription = "Show tracks") + } + } +} + +@Composable +private fun LongformArtistDialog( + artist: String, + songs: List, + state: AppState, + store: AppStore, + supported: Boolean, + onDismiss: () -> Unit, +) { + Dialog(onDismissRequest = onDismiss) { + Surface( + shape = RoundedCornerShape(18.dp), + color = MaterialTheme.colorScheme.surface, + tonalElevation = 6.dp, + modifier = Modifier.fillMaxWidth().heightIn(max = 600.dp), + ) { + Column { + Row( + modifier = Modifier.padding(20.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text(artist, style = MaterialTheme.typography.titleMedium, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text( + "${songs.size} tracks · read-only playlist", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + TextButton(onClick = onDismiss) { Text("Close") } + } + Row(modifier = Modifier.padding(horizontal = 20.dp)) { + Button( + onClick = { + store.playLongformArtist(artist) + onDismiss() + }, + enabled = songs.isNotEmpty(), + ) { + Icon(Icons.Rounded.Shuffle, contentDescription = null, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(6.dp)) + Text("Shuffle artist") } } - else -> { - IconButton(onClick = { store.toggleDownload(song) }) { - Icon(Icons.Rounded.Download, contentDescription = "Download") + HorizontalDivider(Modifier.padding(vertical = 12.dp)) + LazyColumn(Modifier.fillMaxWidth().heightIn(max = 460.dp)) { + items(songs, key = { "artist-song-${it.id}" }) { song -> + LongformSongRow(song, state, store, supported) { + store.playLongformSong(song) + onDismiss() + } } } } } + } +} + +@Composable +private fun LongformSongRow( + song: Song, + state: AppState, + store: AppStore, + supported: Boolean, + onPlay: () -> Unit, +) { + SongRow(store = store, song = song, onPlay = onPlay) { + DownloadAction(song, state, store, supported) + IconButton(onClick = onPlay) { + Icon(Icons.Rounded.PlayArrow, contentDescription = "Play") + } + } +} + +@Composable +private fun LibrarySongRow(song: Song, state: AppState, store: AppStore, supported: Boolean) { + SongRow(store = store, song = song, onPlay = { store.playSong(song) }) { + DownloadAction(song, state, store, supported) if (song.id in state.downloads) { Icon( Icons.Rounded.CheckCircle, @@ -194,3 +473,21 @@ private fun LibrarySongRow(song: Song, state: AppState, store: AppStore, support } } } + +@Composable +private fun DownloadAction(song: Song, state: AppState, store: AppStore, supported: Boolean) { + if (!supported) return + when { + song.id in state.downloading -> CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp) + song.id in state.downloads -> { + IconButton(onClick = { store.toggleDownload(song) }) { + Icon(Icons.Rounded.DeleteOutline, contentDescription = "Delete download") + } + } + else -> { + IconButton(onClick = { store.toggleDownload(song) }) { + Icon(Icons.Rounded.Download, contentDescription = "Download") + } + } + } +} 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 853e58d..cd5301e 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 @@ -34,6 +34,7 @@ import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -74,6 +75,16 @@ fun MoodDetailScreen(state: AppState, store: AppStore) { var hours by remember(mood.id, mood.changedAt) { mutableStateOf(mood.refreshHours.toString()) } var yt by remember(mood.id, mood.changedAt) { mutableStateOf(mood.ytEnabled) } + val pendingDownloads = detail.recommendations.count { + it.download?.state == "queued" || it.download?.state == "downloading" + } + LaunchedEffect(detail.mood.id, pendingDownloads) { + while (pendingDownloads > 0) { + kotlinx.coroutines.delay(10_000) + store.refreshSelectedMood() + } + } + val seedIds = detail.seeds.map { it.song.id }.toSet() val searchResults = state.searchResults.filterNot { it.id in seedIds } @@ -343,22 +354,36 @@ private fun RecommendationRow( maxLines = 1, overflow = TextOverflow.Ellipsis, ) + val download = recommendation.download Text( when { recommendation.state == "accepted" && recommendation.matchedSong != null -> "Seed added" + download?.state == "downloading" -> "Downloading..." + download?.state == "failed" -> "Download failed — tap ✓ to retry" + download?.state == "queued" -> "Download queued" recommendation.state == "accepted" -> "Queued for download" recommendation.matchedSong != null -> "In your library" else -> "New" }, style = MaterialTheme.typography.labelSmall, - color = if (recommendation.state == "accepted") { - MaterialTheme.colorScheme.primary - } else { - MaterialTheme.colorScheme.onSurfaceVariant + color = when { + download?.state == "failed" -> MaterialTheme.colorScheme.error + recommendation.state == "accepted" || download != null -> + MaterialTheme.colorScheme.primary + else -> MaterialTheme.colorScheme.onSurfaceVariant }, ) + if (download?.state == "failed" && download.error != null) { + Text( + download.error, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.error, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } } - if (recommendation.state == "accepted") { + if (recommendation.state == "accepted" && recommendation.download?.state != "failed") { Icon( Icons.Rounded.Check, contentDescription = "Accepted", 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 64e764b..d8cbcc5 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 @@ -6,15 +6,23 @@ import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.AddCircleOutline import androidx.compose.material.icons.rounded.Bedtime +import androidx.compose.material.icons.rounded.Close +import androidx.compose.material.icons.rounded.KeyboardArrowDown +import androidx.compose.material.icons.rounded.KeyboardArrowUp import androidx.compose.material.icons.rounded.Pause import androidx.compose.material.icons.rounded.PlayArrow import androidx.compose.material.icons.rounded.PlaylistAdd +import androidx.compose.material.icons.rounded.QueueMusic import androidx.compose.material.icons.rounded.SkipNext import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem @@ -25,6 +33,7 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Slider import androidx.compose.material3.Surface import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -34,6 +43,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Dialog import win.taptap.musicmanager.client.store.AppState import win.taptap.musicmanager.client.store.AppStore @@ -42,6 +52,7 @@ fun PlayerBar(state: AppState, store: AppStore) { val song = state.current ?: return var picker by remember { mutableStateOf(false) } var sleepMenu by remember { mutableStateOf(false) } + var queueOpen by remember { mutableStateOf(false) } var dragSeconds by remember(song.id) { mutableStateOf(null) } val sleepRemaining = state.sleepTimerRemainingSeconds @@ -69,6 +80,9 @@ fun PlayerBar(state: AppState, store: AppStore) { enabled = store.canSeek(), modifier = Modifier.weight(1f), ) + IconButton(onClick = { queueOpen = true }) { + Icon(Icons.Rounded.QueueMusic, contentDescription = "Queue") + } Box { IconButton(onClick = { sleepMenu = true }) { Icon( @@ -165,6 +179,10 @@ fun PlayerBar(state: AppState, store: AppStore) { } } + if (queueOpen) { + QueueDialog(state, store) { queueOpen = false } + } + if (picker) { MoodPickerDialog( moods = state.moods, @@ -177,3 +195,100 @@ fun PlayerBar(state: AppState, store: AppStore) { ) } } + +@Composable +private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit) { + Dialog(onDismissRequest = onDismiss) { + Surface( + shape = RoundedCornerShape(18.dp), + color = MaterialTheme.colorScheme.surface, + tonalElevation = 6.dp, + modifier = Modifier.fillMaxWidth().heightIn(max = 600.dp), + ) { + Column { + Row( + modifier = Modifier.padding(20.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text("Queue", style = MaterialTheme.typography.titleMedium) + Text( + "${state.queue.size} upcoming", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + TextButton(onClick = onDismiss) { Text("Close") } + } + HorizontalDivider() + LazyColumn(Modifier.fillMaxWidth().heightIn(max = 480.dp)) { + state.current?.let { song -> + item(key = "current") { + Row( + modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Cover(store, song.albumId, Modifier.size(40.dp), size = 96) + Column(Modifier.weight(1f)) { + Text(song.title, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text( + "Now playing", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.primary, + ) + } + } + } + } + + if (state.queue.isEmpty()) { + item { + Text( + "Nothing queued. Start a mood, shuffle all or an artist.", + modifier = Modifier.padding(20.dp), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + + itemsIndexed(state.queue, key = { index, _ -> "queue-$index" }) { index, song -> + Row( + modifier = Modifier.fillMaxWidth().padding(start = 20.dp, end = 8.dp, top = 6.dp, bottom = 6.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + Cover(store, song.albumId, Modifier.size(36.dp), size = 96) + Column(Modifier.weight(1f)) { + Text(song.title, style = MaterialTheme.typography.bodyMedium, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text( + song.artist, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + IconButton( + onClick = { store.moveInQueue(index, index - 1) }, + enabled = index > 0, + ) { + Icon(Icons.Rounded.KeyboardArrowUp, contentDescription = "Move up") + } + IconButton( + onClick = { store.moveInQueue(index, index + 1) }, + enabled = index < state.queue.lastIndex, + ) { + Icon(Icons.Rounded.KeyboardArrowDown, contentDescription = "Move down") + } + IconButton(onClick = { store.removeFromQueue(index) }) { + Icon(Icons.Rounded.Close, contentDescription = "Remove from queue") + } + } + } + } + } + } + } +} 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 e8e5865..473b42c 100644 --- a/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/AppStoreTest.kt +++ b/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/AppStoreTest.kt @@ -220,6 +220,91 @@ class AppStoreTest { * Ktor's mock engine responds on a real dispatcher, so queued test work has * to be run between short real waits. */ + + @Test + fun `queue reordering and removal persist`() = runTest { + val storage = MemoryStorage() + val cache = LibraryCache(storage) + cache.save(CachedState(serverUrl = "http://music", songs = listOf(song("a"), song("b"), song("c")))) + val player = FakePlayer() + val store = store(storage, cache, player) + runCurrent() + + store.playAll(shuffled = false) + runCurrent() + assertEquals("a", store.state.value.current?.id) + assertEquals(listOf("b", "c"), store.state.value.queue.map { it.id }) + + store.moveInQueue(1, 0) + assertEquals(listOf("c", "b"), store.state.value.queue.map { it.id }) + + store.removeFromQueue(0) + assertEquals(listOf("b"), store.state.value.queue.map { it.id }) + assertEquals(listOf("b"), cache.loadPlayback()?.queue?.map { it.id }) + store.release() + } + + @Test + fun `playing an artist queues only that longform artist`() = runTest { + val storage = MemoryStorage() + val cache = LibraryCache(storage) + cache.save( + CachedState( + serverUrl = "http://music", + longform = listOf( + song("l1", artist = "Die drei ???", folderId = 10), + song("l2", artist = "Die drei ???", folderId = 10), + song("l3", artist = "Other", folderId = 10), + ), + ), + ) + val player = FakePlayer() + val store = store(storage, cache, player) + runCurrent() + + store.playLongformArtist("Die drei ???", shuffled = false) + runCurrent() + + val state = store.state.value + assertEquals(setOf("l1", "l2"), (state.queue + listOfNotNull(state.current)).map { it.id }.toSet()) + assertTrue(player.played.single() in setOf("l1", "l2")) + store.release() + } + + @Test + fun `resuming a longform track starts it`() = runTest { + val storage = MemoryStorage() + val cache = LibraryCache(storage) + cache.save( + CachedState( + serverUrl = "http://music", + longform = listOf(song("l1", artist = "Die drei ???", folderId = 10)), + ), + ) + cache.saveProgress( + listOf( + win.taptap.musicmanager.client.api.LongformProgress( + songId = "l1", + positionSeconds = 30, + durationSeconds = 180, + completed = false, + updatedAt = "2026-01-01T00:00:00Z", + ), + ), + ) + val player = FakePlayer() + val store = store(storage, cache, player) + runCurrent() + + store.resumeLongform("l1") + runCurrent() + + assertEquals("l1", store.state.value.current?.id) + assertEquals(listOf("l1"), player.played) + assertEquals(30, store.state.value.longformProgress["l1"]?.positionSeconds) + store.release() + } + private suspend fun TestScope.awaitState(predicate: () -> Boolean) { repeat(500) { runCurrent() @@ -260,17 +345,17 @@ class AppStoreTest { cache = cache, ) - private fun song(id: String) = Song( + private fun song(id: String, artist: String = "Artist", folderId: Int = 1) = Song( id = id, title = "Song $id", - artist = "Artist", + artist = artist, album = "Album", albumId = "al-1", duration = 180, bitRate = 320, size = 1_000, suffix = "mp3", - folderId = 1, + folderId = folderId, relativePath = "$id.mp3", updatedAt = "2026-01-01T00:00:00Z", )