diff --git a/.gitea/workflows/ci.yaml b/.gitea/workflows/ci.yaml index e5caa9d..6d1eb0a 100644 --- a/.gitea/workflows/ci.yaml +++ b/.gitea/workflows/ci.yaml @@ -22,6 +22,8 @@ jobs: image: gitea.tap-tap.win/taptap/audiomanager-client-ci:3 steps: - uses: actions/checkout@v4 + with: + persist-credentials: false - name: Test and build run: | diff --git a/README.md b/README.md index c6f3411..a50201d 100644 --- a/README.md +++ b/README.md @@ -143,9 +143,9 @@ 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. 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. +- Desktop playback supports seeking by reopening the decoder at the requested position (server `timeOffset` for remote streams, PCM skipping for local files). Longform resume works there too. 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 are downloaded by the server into `/AudioManager Imports`, with the YT thumbnail embedded as cover art, scanned and added as seeds. The server needs outbound network access for this. +- Accepted recommendations are downloaded by the server into `/AudioManager Imports///`, with the YT thumbnail embedded as cover art, scanned and added as seeds. The per-track folder keeps covers distinct. The server needs outbound network access for this. - Offline downloads also store the 320 px cover next to the MP3 (`<songId>.jpg`), so the in-app cover and the Android notification artwork survive without the server. Deleting a download removes both files. -- YT Music discovery runs server-side through `yt-dlp`; downloading accepted tracks that are not in the library is still roadmap. +- YT Music discovery and automatic downloads run server-side through `yt-dlp`. Accepted tracks that are not in the library are imported into `AudioManager Imports` with embedded cover art and promoted to seeds. - 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 27e5eb0..cab7be7 100644 --- a/composeApp/src/androidMain/kotlin/win/taptap/musicmanager/client/MediaControllerAudioPlayer.kt +++ b/composeApp/src/androidMain/kotlin/win/taptap/musicmanager/client/MediaControllerAudioPlayer.kt @@ -21,7 +21,7 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer { private val appContext = context.applicationContext private var controller: MediaController? = null - private var pending: ((MediaController) -> Unit)? = null + private val pending = ArrayDeque<(MediaController) -> Unit>() private var connected = false @Volatile private var finished = false @@ -45,8 +45,10 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer { controller = sessionController sessionController.addListener(listener) connected = true - pending?.invoke(sessionController) - pending = null + val queued = synchronized(pending) { + pending.toList().also { pending.clear() } + } + queued.forEach { action -> runCatching { action(sessionController) } } } }, ContextCompat.getMainExecutor(appContext), @@ -125,9 +127,14 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer { } 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 + val send: (MediaController) -> Boolean = { current -> + runCatching { current.sendCustomCommand(SLEEP_TIMER_COMMAND, args) }.isSuccess + } + val current = controller + if (current != null && connected) return send(current) + synchronized(pending) { pending.addLast { controller -> send(controller) } } + return true } override fun release() { @@ -135,7 +142,7 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer { MediaController.releaseFuture(future) controller = null connected = false - pending = null + synchronized(pending) { pending.clear() } } private fun withController(block: (MediaController) -> Unit) { @@ -143,7 +150,9 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer { if (current != null && connected) { block(current) } else { - pending = block + // The first playback request can be followed immediately by a seek + // (long-form resume). Keep every action, not only the last one. + synchronized(pending) { pending.addLast(block) } } } } diff --git a/composeApp/src/androidMain/kotlin/win/taptap/musicmanager/client/Platform.android.kt b/composeApp/src/androidMain/kotlin/win/taptap/musicmanager/client/Platform.android.kt index 57dd1d6..b1cbcd6 100644 --- a/composeApp/src/androidMain/kotlin/win/taptap/musicmanager/client/Platform.android.kt +++ b/composeApp/src/androidMain/kotlin/win/taptap/musicmanager/client/Platform.android.kt @@ -6,6 +6,7 @@ import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.asImageBitmap import io.ktor.client.engine.HttpClientEngine import io.ktor.client.engine.okhttp.OkHttp +import io.ktor.utils.io.readAvailable import java.io.File import win.taptap.musicmanager.client.data.AppStorage import win.taptap.musicmanager.client.playback.AudioPlayer @@ -32,7 +33,7 @@ class AndroidStorage(context: Context) : AppStorage { override fun write(name: String, text: String) { root.mkdirs() - File(root, name).writeText(text) + atomicWrite(File(root, name)) { it.writeText(text) } } override fun delete(name: String) { @@ -42,10 +43,39 @@ class AndroidStorage(context: Context) : AppStorage { override fun saveDownload(songId: String, bytes: ByteArray): String? { downloads.mkdirs() val file = File(downloads, "${safeName(songId)}.mp3") - file.writeBytes(bytes) + atomicWrite(file) { it.writeBytes(bytes) } return file.absolutePath } + override suspend fun saveDownloadStream( + songId: String, + source: io.ktor.utils.io.ByteReadChannel, + ): String? { + downloads.mkdirs() + val target = File(downloads, "${safeName(songId)}.mp3") + val temp = File(downloads, "${safeName(songId)}.mp3.part") + try { + temp.outputStream().use { output -> + val buffer = ByteArray(64 * 1024) + while (true) { + val read = source.readAvailable(buffer) + if (read < 0) break + if (read > 0) output.write(buffer, 0, read) + } + output.flush() + } + if (temp.length() == 0L) error("empty download") + if (!temp.renameTo(target)) { + temp.copyTo(target, overwrite = true) + temp.delete() + } + return target.absolutePath + } catch (t: Throwable) { + temp.delete() + throw t + } + } + override fun downloadPath(songId: String): String? = File(downloads, "${safeName(songId)}.mp3").takeIf { it.isFile }?.absolutePath @@ -53,7 +83,7 @@ class AndroidStorage(context: Context) : AppStorage { if (bytes.isEmpty()) return null downloads.mkdirs() val file = File(downloads, "${safeName(songId)}.jpg") - file.writeBytes(bytes) + atomicWrite(file) { it.writeBytes(bytes) } return file.absolutePath } @@ -74,6 +104,20 @@ class AndroidStorage(context: Context) : AppStorage { override fun storageUsedBytes(): Long = downloads.listFiles()?.sumOf { it.length() } ?: 0L + private fun atomicWrite(target: File, write: (File) -> Unit) { + val temp = File(target.parentFile, "${target.name}.part") + try { + write(temp) + if (!temp.renameTo(target)) { + temp.copyTo(target, overwrite = true) + temp.delete() + } + } catch (t: Throwable) { + temp.delete() + throw t + } + } + private fun safeName(songId: String): String = songId.map { if (it.isLetterOrDigit() || it == '-' || it == '_') it else '_' }.joinToString("") } 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 950a297..498c890 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 @@ -16,6 +16,7 @@ import io.ktor.client.request.put import io.ktor.client.request.setBody import io.ktor.client.statement.HttpResponse import io.ktor.client.statement.bodyAsBytes +import io.ktor.client.statement.bodyAsChannel import io.ktor.http.ContentType import io.ktor.http.HttpHeaders import io.ktor.http.HttpStatusCode @@ -23,6 +24,7 @@ import io.ktor.http.contentType import io.ktor.http.encodeURLParameter import io.ktor.http.isSuccess import io.ktor.serialization.kotlinx.json.json +import io.ktor.utils.io.ByteReadChannel import kotlinx.serialization.json.Json fun configuredHttpClient(engine: HttpClientEngine): HttpClient = HttpClient(engine) { @@ -85,6 +87,10 @@ class ApiClient(private val http: HttpClient) { imageCache.clear() } + fun close() { + http.close() + } + suspend fun me(): User = get("/me") suspend fun logout() { @@ -173,11 +179,13 @@ class ApiClient(private val http: HttpClient) { since: String? = null, limit: Int = 500, scope: String = "all", + revision: String? = null, ): LibraryPage { val query = buildString { append("?limit=$limit&scope=$scope") cursor?.let { append("&cursor=${it.encodeURLParameter()}") } since?.let { append("&since=${it.encodeURLParameter()}") } + revision?.let { append("&revision=${it.encodeURLParameter()}") } } return get("/library/songs$query") } @@ -266,25 +274,61 @@ class ApiClient(private val http: HttpClient) { } }.getOrNull() if (coverCache.size > MAX_CACHED_IMAGES) coverCache.clear() - coverCache[key] = result + // Do not cache failures: a cover can appear after the scanner indexes a + // newly downloaded track, and the UI should pick it up without a restart. + if (result != null) coverCache[key] = result return result } /** Remote artwork such as YT thumbnails, cached for the app's lifetime. */ suspend fun image(url: String): ByteArray? { if (imageCache.containsKey(url)) return imageCache[url] - val bytes = runCatching { http.get(url).bodyAsBytes() }.getOrNull() - val result = bytes?.takeIf { it.isNotEmpty() } + val result = runCatching { + val response = http.get(url) + if (response.status.isSuccess()) { + response.bodyAsBytes().takeIf { it.isNotEmpty() } + } else { + null + } + }.getOrNull() if (imageCache.size > MAX_CACHED_IMAGES) imageCache.clear() - imageCache[url] = result + if (result != null) imageCache[url] = result return result } - suspend fun download(songId: String): ByteArray = - http.get("$baseUrl/api/v1/songs/$songId/stream") { + suspend fun download(songId: String): ByteArray { + val response = downloadResponse(songId) + return response.bodyAsBytes().takeIf { it.isNotEmpty() } + ?: throw ApiException( + status = response.status.value, + code = "empty_download", + message = "The server returned an empty audio file", + ) + } + + /** Streams an audio download into [sink] instead of buffering it in RAM. */ + suspend fun downloadTo( + songId: String, + sink: suspend (ByteReadChannel) -> String?, + ): String? { + val response = downloadResponse(songId) + return sink(response.bodyAsChannel()) + } + + private suspend fun downloadResponse(songId: String): HttpResponse { + val response = http.get("$baseUrl/api/v1/songs/$songId/stream") { auth() url.parameters.append("download", "true") - }.bodyAsBytes() + // A long audiobook must not be cancelled by the default 30s total + // request timeout. + timeout { + requestTimeoutMillis = 6 * 60 * 60 * 1000 + socketTimeoutMillis = 60_000 + } + } + if (!response.status.isSuccess()) throw error(response) + return response + } fun streamUrl(songId: String): String = "$baseUrl/api/v1/songs/$songId/stream?token=${token.orEmpty().encodeURLParameter()}" diff --git a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/data/AppStorage.kt b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/data/AppStorage.kt index 42e1ff9..ada923b 100644 --- a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/data/AppStorage.kt +++ b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/data/AppStorage.kt @@ -10,6 +10,9 @@ interface AppStorage { fun saveDownload(songId: String, bytes: ByteArray): String? fun downloadPath(songId: String): String? + /** Streams a download to disk and returns the final playback path. */ + suspend fun saveDownloadStream(songId: String, source: io.ktor.utils.io.ByteReadChannel): String? = null + /** Stores the cover next to the audio file so offline playback keeps artwork. */ fun saveArtwork(songId: String, bytes: ByteArray): String? fun artworkBytes(songId: String): ByteArray? 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 2530165..e35d421 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 @@ -34,6 +34,7 @@ data class PlaybackSnapshot( val queue: List<Song> = emptyList(), val current: Song? = null, val history: List<Song> = emptyList(), + val positionSeconds: Double = 0.0, ) class LibraryCache(private val storage: AppStorage) { @@ -45,49 +46,59 @@ class LibraryCache(private val storage: AppStorage) { } fun loadSession(): SessionState? = - storage.read(SESSION_FILE)?.let { + read(SESSION_FILE)?.let { runCatching { json.decodeFromString<SessionState>(it) }.getOrNull() } fun saveSession(session: SessionState?) { - if (session == null) storage.delete(SESSION_FILE) else storage.write(SESSION_FILE, json.encodeToString(session)) + if (session == null) delete(SESSION_FILE) else write(SESSION_FILE, json.encodeToString(session)) } fun load(): CachedState = - storage.read(CACHE_FILE)?.let { + read(CACHE_FILE)?.let { runCatching { json.decodeFromString<CachedState>(it) }.getOrNull() } ?: CachedState() fun save(state: CachedState) { - storage.write(CACHE_FILE, json.encodeToString(state)) + write(CACHE_FILE, json.encodeToString(state)) } fun loadPlayback(): PlaybackSnapshot? = - storage.read(PLAYBACK_FILE)?.let { + read(PLAYBACK_FILE)?.let { runCatching { json.decodeFromString<PlaybackSnapshot>(it) }.getOrNull() } fun savePlayback(snapshot: PlaybackSnapshot?) { if (snapshot == null || (snapshot.current == null && snapshot.queue.isEmpty())) { - storage.delete(PLAYBACK_FILE) + delete(PLAYBACK_FILE) } else { - storage.write(PLAYBACK_FILE, json.encodeToString(snapshot)) + write(PLAYBACK_FILE, json.encodeToString(snapshot)) } } fun loadProgress(): List<LongformProgress> = - storage.read(PROGRESS_FILE)?.let { + read(PROGRESS_FILE)?.let { runCatching { json.decodeFromString<List<LongformProgress>>(it) }.getOrNull() } ?: emptyList() fun saveProgress(progress: List<LongformProgress>) { - storage.write(PROGRESS_FILE, json.encodeToString(progress)) + write(PROGRESS_FILE, json.encodeToString(progress)) } fun clear() { - storage.delete(CACHE_FILE) - storage.delete(PLAYBACK_FILE) - storage.delete(PROGRESS_FILE) + delete(CACHE_FILE) + delete(PLAYBACK_FILE) + delete(PROGRESS_FILE) + } + + // Web storage can be blocked (Safari private mode) or full. Cache failure + // must never prevent the app from reaching the login screen or playing. + private fun read(name: String): String? = runCatching { storage.read(name) }.getOrNull() + private fun write(name: String, text: String) { + runCatching { storage.write(name, text) } + } + private fun delete(name: String) { + runCatching { storage.delete(name) } } private companion object { 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 f8a9032..eac3e74 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 @@ -1,10 +1,13 @@ package win.taptap.musicmanager.client.store +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow @@ -60,7 +63,10 @@ data class AppState( val longform: List<Song> = emptyList(), val longformResults: List<Song> = emptyList(), val longformProgress: Map<String, LongformProgress> = emptyMap(), + /** Results for the mood seed picker. */ val searchResults: List<Song> = emptyList(), + /** Results for the Music library tab, kept separate from mood search. */ + val musicResults: List<Song> = emptyList(), val searching: Boolean = false, val loading: Boolean = false, val saving: Boolean = false, @@ -85,13 +91,21 @@ class AppStore( val state: StateFlow<AppState> = _state.asStateFlow() private var pollJob: Job? = null + private var refreshJob: Job? = null private var sleepJob: Job? = null + private var musicSearchJob: Job? = null + private var longformSearchJob: Job? = null private var reconnectJob: Job? = null private var playbackStarted = false private var advancing = false private var fetching = false private var finishing = false private var pollTicks = 0 + private var trackStartOffset = 0.0 + private var dataGeneration = 0 + private var moodRequestGeneration = 0 + private var loggingOut = false + private val progressSaveMutex = Mutex() init { bootstrap() @@ -103,6 +117,12 @@ class AppStore( val cached = cache.load() val playback = cache.loadPlayback() val progress = cache.loadProgress() + val progressById = progress.associateBy { entry -> entry.songId } + val restoredSong = playback?.current + val restoredPosition = playback?.positionSeconds?.takeIf { it > 0.0 } + ?: restoredSong?.let { progressById[it.id]?.positionSeconds?.toDouble() } + ?: 0.0 + trackStartOffset = restoredPosition _state.update { it.copy( booting = false, @@ -110,13 +130,14 @@ class AppStore( moods = cached.moods, library = cached.songs.sortedLibrary(), longform = cached.longform.sortedLibrary(), - longformProgress = progress.associateBy { entry -> entry.songId }, + longformProgress = progressById, selectedMood = cached.moodDetails.firstOrNull(), session = playback?.session, queue = playback?.queue.orEmpty(), - current = playback?.current, + current = restoredSong, history = playback?.history.orEmpty(), - durationSeconds = playback?.current?.duration?.toDouble() ?: 0.0, + positionSeconds = restoredPosition, + durationSeconds = restoredSong?.duration?.toDouble() ?: 0.0, ) } @@ -145,13 +166,18 @@ class AppStore( deviceName = "$platformName device", platform = platformName, ) - cache.saveSession(SessionState(api.baseUrl, response.token, response.user)) + dataGeneration += 1 + runCatching { + cache.saveSession(SessionState(api.baseUrl, response.token, response.user)) + } + loggingOut = false _state.update { it.copy( authenticated = true, user = response.user, serverUrl = api.baseUrl, loading = false, + message = null, ) } refreshAll() @@ -164,11 +190,17 @@ class AppStore( } fun logout() { + dataGeneration += 1 + loggingOut = true scope.launch { + musicSearchJob?.cancel() + longformSearchJob?.cancel() + refreshJob?.cancel() + stopPlayback() runCatching { api.logout() } + api.clear() cache.saveSession(null) cache.clear() - stopPlayback() _state.value = AppState( booting = false, serverUrl = _state.value.serverUrl, @@ -178,14 +210,31 @@ class AppStore( } fun refreshAll(silent: Boolean = false) { - scope.launch { refreshAllNow(silent) } + refreshJob?.cancel() + refreshJob = scope.launch { refreshAllNow(silent) } } private suspend fun refreshAllNow(silent: Boolean) { if (!silent) _state.update { it.copy(loading = true) } + val generation = dataGeneration try { + // Folder assignments can change server-side after login. Re-read the + // user so the music/longform split does not keep using stale folders. + val me = try { + api.me() + } catch (t: ApiException) { + if (t.status == 401) throw t + null + } + val currentUser = me ?: _state.value.user + if (me != null) { + cache.loadSession()?.let { session -> cache.saveSession(session.copy(user = me)) } + } val moods = api.moods() - val cached = cache.load() + val loaded = cache.load() + val cacheMatches = loaded.serverUrl == _state.value.serverUrl && + (loaded.userName.isEmpty() || loaded.userName == currentUser?.name.orEmpty()) + val cached = if (cacheMatches) loaded else CachedState() // Both halves of the cache must feed the delta sync; otherwise the // long-form list disappears as soon as the first delta arrives. var songs = (cached.songs + cached.longform) @@ -194,9 +243,18 @@ class AppStore( var revision = cached.revision if (revision == null) { + // Keep the first page's timestamp across the whole snapshot, so + // songs inserted between pages are fetched by the next delta. + var snapshotRevision: String? = null var cursor: String? = null do { - val page = api.library(cursor = cursor, since = null, limit = 500) + val page = api.library( + cursor = cursor, + since = null, + limit = 500, + revision = snapshotRevision, + ) + if (snapshotRevision == null) snapshotRevision = page.revision page.songs.forEach { songs[it.id] = it } cursor = page.nextCursor revision = page.revision @@ -213,37 +271,67 @@ class AppStore( } val details = cached.moodDetails.filter { detail -> moods.any { it.id == detail.mood.id } } - val longformFolders = longformFolders() + val longformFolders = currentUser?.longformFolders?.toSet().orEmpty() 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 = musicSongs, - longform = longformSongs, - moods = moods, - moodDetails = details, - ), - ) - serverProgress?.let { items -> - cache.saveProgress(items.map { it.toProgress() }) + if (generation != dataGeneration) return + runCatching { + cache.save( + CachedState( + serverUrl = _state.value.serverUrl, + userName = currentUser?.name.orEmpty(), + revision = revision, + songs = musicSongs, + longform = longformSongs, + moods = moods, + moodDetails = details, + ), + ) + } + // Progress saved while offline must not be replaced by a stale + // server copy. Keep whichever entry was updated last. + val localProgress = _state.value.longformProgress + val mergedProgress = localProgress.toMutableMap() + serverProgress?.forEach { item -> + val remote = item.toProgress() + val existing = mergedProgress[remote.songId] + if (existing == null || remote.updatedAt >= existing.updatedAt) { + mergedProgress[remote.songId] = remote + } + } + if (generation != dataGeneration) return + if (serverProgress != null) { + cache.saveProgress(mergedProgress.values.toList()) + // Replay local positions that are newer than the server copy + // (typically written while offline). + mergedProgress.forEach { (songId, local) -> + val remote = serverProgress.firstOrNull { it.song.id == songId } + if (remote == null || local.updatedAt > remote.updatedAt) { + runCatching { + api.saveLongformProgress( + songId, + local.positionSeconds, + local.durationSeconds, + local.completed, + ) + } + } + } } + if (generation != dataGeneration) return _state.update { it.copy( loading = false, offline = false, + user = currentUser, moods = moods, library = musicSongs.sortedLibrary(), longform = longformSongs.sortedLibrary(), - longformProgress = serverProgress - ?.associate { item -> item.song.id to item.toProgress() } - ?: it.longformProgress, + longformProgress = if (serverProgress != null) mergedProgress else it.longformProgress, ) } } catch (t: Throwable) { @@ -265,23 +353,37 @@ class AppStore( } fun openMoods() { + moodRequestGeneration += 1 _state.update { it.copy(screen = Screen.Moods) } } fun openMood(id: String) { scope.launch { - _state.update { it.copy(loading = true, screen = Screen.MoodDetail) } + val request = ++moodRequestGeneration + _state.update { + it.copy( + loading = true, + screen = Screen.MoodDetail, + selectedMood = null, + preview = emptyList(), + searchResults = emptyList(), + ) + } try { val detail = api.mood(id) val preview = runCatching { api.preview(id, 20) }.getOrDefault(emptyList()) + if (request != moodRequestGeneration) return@launch cacheDetail(detail) _state.update { it.copy(loading = false, selectedMood = detail, preview = preview) } } catch (t: Throwable) { + if (request != moodRequestGeneration) return@launch val cached = cache.load().moodDetails.firstOrNull { it.mood.id == id } _state.update { it.copy( loading = false, - selectedMood = cached ?: it.selectedMood, + // Never leave a different mood editable under the new title. + selectedMood = cached, + preview = emptyList(), message = if (cached == null) t.friendlyMessage() else "Showing cached mood", messageIsError = cached == null, messageId = it.messageId + 1, @@ -295,7 +397,9 @@ class AppStore( fun refreshSelectedMood() { val moodId = _state.value.selectedMood?.mood?.id ?: return scope.launch { - runCatching { api.mood(moodId) }.onSuccess { applyMoodDetail(it) } + runCatching { api.mood(moodId) }.onSuccess { detail -> + if (_state.value.selectedMood?.mood?.id == moodId) applyMoodDetail(detail) + } } } @@ -379,12 +483,10 @@ class AppStore( seedPercent = seedPercent, ), ) - cacheDetail(updated) + applyMoodDetail(updated) _state.update { it.copy( saving = false, - selectedMood = updated, - moods = it.moods.map { mood -> if (mood.id == updated.mood.id) updated.mood else mood }, message = "Saved", messageIsError = false, messageId = it.messageId + 1, @@ -421,11 +523,9 @@ class AppStore( try { api.addSeed(moodId, songId) val detail = api.mood(moodId) - cacheDetail(detail) + applyMoodDetail(detail) _state.update { it.copy( - selectedMood = detail, - moods = it.moods.map { mood -> if (mood.id == moodId) detail.mood else mood }, message = "Seed added", messageIsError = false, messageId = it.messageId + 1, @@ -442,11 +542,9 @@ class AppStore( try { api.removeSeed(moodId, songId) val detail = api.mood(moodId) - cacheDetail(detail) + applyMoodDetail(detail) _state.update { it.copy( - selectedMood = detail, - moods = it.moods.map { mood -> if (mood.id == moodId) detail.mood else mood }, message = "Seed removed", messageIsError = false, messageId = it.messageId + 1, @@ -475,19 +573,48 @@ class AppStore( } } + fun searchMusic(query: String) { + musicSearchJob?.cancel() + if (query.isBlank()) { + _state.update { it.copy(musicResults = emptyList()) } + return + } + musicSearchJob = scope.launch { + delay(SEARCH_DEBOUNCE_MS) + _state.update { it.copy(searching = true) } + try { + val songs = api.search(query, 60, scope = "music") + _state.update { it.copy(musicResults = songs) } + } catch (t: CancellationException) { + throw t + } catch (t: Throwable) { + _state.update { it.copy(musicResults = emptyList()) } + message(t) + } finally { + _state.update { it.copy(searching = false) } + } + } + } + fun searchLongform(query: String) { + longformSearchJob?.cancel() if (query.isBlank()) { _state.update { it.copy(longformResults = emptyList()) } return } - scope.launch { + longformSearchJob = scope.launch { + delay(SEARCH_DEBOUNCE_MS) _state.update { it.copy(searching = true) } try { val songs = api.search(query, 60, scope = "longform") - _state.update { it.copy(searching = false, longformResults = songs) } + _state.update { it.copy(longformResults = songs) } + } catch (t: CancellationException) { + throw t } catch (t: Throwable) { - _state.update { it.copy(searching = false, longformResults = emptyList()) } + _state.update { it.copy(longformResults = emptyList()) } message(t) + } finally { + _state.update { it.copy(searching = false) } } } } @@ -521,8 +648,10 @@ class AppStore( ) } playNext() + scheduleReconnect() } else { message(t) + scheduleReconnect() } } } @@ -530,6 +659,7 @@ class AppStore( fun playSong(song: Song) { scope.launch { + reportCurrentProgress(completed = false) _state.value.session?.let { api.closeSession(it.id) } _state.update { it.copy( @@ -595,9 +725,11 @@ class AppStore( } } - fun playLongformSong(song: Song, startAtSeconds: Double = 0.0) { + fun playLongformSong(song: Song, startAtSeconds: Double? = null) { scope.launch { + reportCurrentProgress(completed = false) _state.value.session?.let { runCatching { api.closeSession(it.id) } } + val startAt = startAtSeconds ?: savedPosition(song) _state.update { it.copy( session = null, @@ -605,20 +737,25 @@ class AppStore( current = song, history = pushHistory(it.history, it.current), playing = true, - positionSeconds = startAtSeconds, + positionSeconds = startAt, durationSeconds = song.duration.toDouble(), ) } persistPlayback() - startSong(song, startAtSeconds) + startSong(song, startAt) } } 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) + playLongformSong(song, savedPosition(song)) + } + + private fun savedPosition(song: Song): Double { + if (song.folderId !in longformFolders()) return 0.0 + val progress = _state.value.longformProgress[song.id] ?: return 0.0 + return if (progress.completed) 0.0 else progress.positionSeconds.toDouble().coerceAtLeast(0.0) } fun moveInQueue(fromIndex: Int, toIndex: Int) { @@ -675,6 +812,9 @@ class AppStore( if (!isActive) return@launch val wasPlaying = _state.value.playing player.pause() + pollJob?.cancel() + reportCurrentProgress(completed = false) + persistPlayback() _state.update { it.copy( playing = false, @@ -751,14 +891,26 @@ class AppStore( val song = state.current ?: return if (state.playing) { player.pause() + pollJob?.cancel() _state.update { it.copy(playing = false) } reportCurrentProgress(completed = false) + persistPlayback() } else if (!playbackStarted || player.isFinished()) { - // Restored queue or finished track: start it from the beginning. - _state.update { - it.copy(playing = true, positionSeconds = 0.0, durationSeconds = song.duration.toDouble()) + val finished = player.isFinished() + val duration = state.durationSeconds.takeIf { it > 0 } ?: song.duration.toDouble() + val startAt = if (finished || (duration > 0 && state.positionSeconds >= duration - 1.0)) { + 0.0 + } else { + state.positionSeconds.coerceAtLeast(0.0) } - startSong(song) + _state.update { + it.copy( + playing = true, + positionSeconds = startAt, + durationSeconds = duration, + ) + } + startSong(song, startAt) } else { player.resume() _state.update { it.copy(playing = true) } @@ -768,7 +920,7 @@ class AppStore( fun skip() { val state = _state.value - state.current?.let { report("skipped", it.id) } + state.current?.let { report("skipped", it.id, state.positionSeconds.toInt()) } playNext() } @@ -780,7 +932,8 @@ class AppStore( fun previous() { val state = _state.value val song = state.current ?: return - if (state.positionSeconds > 2.0) { + val elapsed = (state.positionSeconds - trackStartOffset).coerceAtLeast(0.0) + if (elapsed > 2.0) { restartCurrent(song) return } @@ -791,6 +944,7 @@ class AppStore( return } + val targetStart = savedPosition(target) reportCurrentProgress(completed = false) _state.update { it.copy( @@ -798,18 +952,20 @@ class AppStore( queue = listOf(song) + it.queue, current = target, playing = true, - positionSeconds = 0.0, + positionSeconds = targetStart, durationSeconds = target.duration.toDouble(), ) } persistPlayback() - startSong(target) - report("started", target.id) + startSong(target, targetStart) + report("started", target.id, 0) } private fun restartCurrent(song: Song) { + trackStartOffset = 0.0 if (player.canSeek) { - player.seekTo(0.0) + runCatching { player.seekTo(0.0) } + .onFailure { message(it) } _state.update { it.copy(positionSeconds = 0.0) } } else { _state.update { it.copy(playing = true, positionSeconds = 0.0) } @@ -821,9 +977,15 @@ class AppStore( fun seekTo(seconds: Double) { if (!player.canSeek) return - player.seekTo(seconds) - _state.update { it.copy(positionSeconds = seconds) } - reportCurrentProgress(completed = false) + val target = seconds.coerceAtLeast(0.0) + try { + player.seekTo(target) + _state.update { it.copy(positionSeconds = target) } + reportCurrentProgress(completed = false) + persistPlayback() + } catch (t: Throwable) { + message(t) + } } fun addCurrentToMood(targetMoodId: String?) { @@ -850,14 +1012,14 @@ class AppStore( val updatedMoods = state.moods.map { mood -> if (mood.id == response.mood.id) response.mood else mood } - val selected = state.selectedMood?.let { detail -> - if (detail.mood.id == response.mood.id) { - detail.copy(mood = response.mood) - } else { - detail - } - } _state.update { + val selected = it.selectedMood?.let { detail -> + if (detail.mood.id == response.mood.id) { + detail.copy(mood = response.mood) + } else { + detail + } + } it.copy( moods = updatedMoods, selectedMood = selected, @@ -870,7 +1032,7 @@ class AppStore( messageId = it.messageId + 1, ) } - if (selected != null) cacheDetail(selected) + _state.value.selectedMood?.let { cacheDetail(it) } } catch (t: Throwable) { message(t) } @@ -892,18 +1054,24 @@ class AppStore( return } + val generation = dataGeneration scope.launch { _state.update { it.copy(downloading = it.downloading + song.id) } var lastError: Throwable? = null repeat(DOWNLOAD_ATTEMPTS) { attempt -> try { - val bytes = api.download(song.id) - val path = storage.saveDownload(song.id, bytes) + val path = api.downloadTo(song.id) { channel -> + storage.saveDownloadStream(song.id, channel) + } if (path != null) { runCatching { api.cover(song.albumId, 320) } .getOrNull() ?.takeIf { it.isNotEmpty() } - ?.let { storage.saveArtwork(song.id, it) } + ?.let { artwork -> runCatching { storage.saveArtwork(song.id, artwork) } } + } + if (generation != dataGeneration) { + storage.deleteDownload(song.id) + return@launch } if (path == null) { _state.update { @@ -933,7 +1101,12 @@ class AppStore( } } } - _state.update { it.copy(downloading = it.downloading - song.id) } + _state.update { + it.copy( + downloading = it.downloading - song.id, + downloads = storage.listDownloads().keys, + ) + } message(lastError ?: IllegalStateException("Download failed")) } } @@ -983,9 +1156,13 @@ class AppStore( fun release() { persistPlayback() pollJob?.cancel() + refreshJob?.cancel() sleepJob?.cancel() reconnectJob?.cancel() + musicSearchJob?.cancel() + longformSearchJob?.cancel() player.release() + api.close() } private fun playNext() { @@ -998,22 +1175,28 @@ class AppStore( return } advancing = true + val sessionId = session.id scope.launch { try { - val more = api.nextTracks(session.id, 12) - _state.update { it.copy(queue = it.queue + more) } + val more = api.nextTracks(sessionId, 12) + if (_state.value.session?.id == sessionId) { + _state.update { it.copy(queue = it.queue + more) } + } } catch (t: Throwable) { message(t) } finally { advancing = false } + if (_state.value.session?.id != sessionId) return@launch if (_state.value.queue.isNotEmpty()) playNext() else _state.update { it.copy(playing = false) } } return } val song = state.queue.first() - reportCurrentProgress(completed = false) + // On natural completion the poll already saved completed=true for the + // outgoing track; do not immediately overwrite it with false. + if (!finishing) reportCurrentProgress(completed = false) _state.update { it.copy( queue = it.queue.drop(1), @@ -1026,7 +1209,7 @@ class AppStore( } persistPlayback() startSong(song) - report("started", song.id) + report("started", song.id, 0) if (_state.value.queue.size < 3) prefetch() } @@ -1034,10 +1217,13 @@ class AppStore( val session = _state.value.session ?: return if (fetching) return fetching = true + val sessionId = session.id scope.launch { try { - val more = api.nextTracks(session.id, 12) - _state.update { it.copy(queue = it.queue + more) } + val more = api.nextTracks(sessionId, 12) + if (_state.value.session?.id == sessionId) { + _state.update { it.copy(queue = it.queue + more) } + } } catch (_: Throwable) { // The queue still has tracks; a later request will retry. } finally { @@ -1050,6 +1236,7 @@ class AppStore( val localPath = storage.downloadPath(song.id) finishing = false pollTicks = 0 + trackStartOffset = startAtSeconds try { player.play( source = localPath ?: api.streamUrl(song.id), @@ -1094,14 +1281,16 @@ class AppStore( pollTicks += 1 if (pollTicks >= PROGRESS_POLL_TICKS) { pollTicks = 0 - reportCurrentProgress(completed = false) + // Pause/seek/track changes report explicitly; avoid + // rewriting the same position every few seconds while paused. + if (player.isPlaying()) reportCurrentProgress(completed = false) } if (player.isFinished()) { if (!finishing) { finishing = true reportCurrentProgress(completed = true) - report("completed", state.current?.id) + report("completed", state.current?.id, state.positionSeconds.toInt()) playNext() } break @@ -1111,7 +1300,7 @@ class AppStore( } } - private fun report(type: String, songId: String?) { + private fun report(type: String, songId: String?, positionSeconds: Int) { val session = _state.value.session ?: return if (songId == null) return scope.launch { @@ -1121,7 +1310,7 @@ class AppStore( PlaybackEvent( songId = songId, type = type, - positionSeconds = _state.value.positionSeconds.toInt(), + positionSeconds = positionSeconds, ), ), ) @@ -1151,16 +1340,22 @@ class AppStore( } private fun cacheDetail(detail: MoodDetail) { - val cached = cache.load() - val details = cached.moodDetails.filterNot { it.mood.id == detail.mood.id } + detail - cache.save(cached.copy(moodDetails = details, moods = cached.moods)) + runCatching { + val cached = cache.load() + val details = cached.moodDetails.filterNot { it.mood.id == detail.mood.id } + detail + cache.save(cached.copy(moodDetails = details, moods = cached.moods)) + } } private fun applyMoodDetail(detail: MoodDetail) { cacheDetail(detail) _state.update { state -> state.copy( - selectedMood = detail, + selectedMood = if (state.selectedMood?.mood?.id == detail.mood.id) { + detail + } else { + state.selectedMood + }, moods = state.moods.map { mood -> if (mood.id == detail.mood.id) detail.mood else mood }, ) } @@ -1168,14 +1363,17 @@ class AppStore( private fun persistPlayback() { val state = _state.value - cache.savePlayback( + runCatching { + cache.savePlayback( PlaybackSnapshot( session = state.session, queue = state.queue, current = state.current, history = state.history, + positionSeconds = state.positionSeconds, ), ) + } } /** Retries the library sync with exponential backoff while offline. */ @@ -1200,6 +1398,7 @@ class AppStore( _state.value.user?.longformFolders?.toSet().orEmpty() private fun reportCurrentProgress(completed: Boolean) { + if (loggingOut) return val state = _state.value val song = state.current ?: return if (song.folderId !in longformFolders()) return @@ -1225,7 +1424,9 @@ class AppStore( _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) } + progressSaveMutex.withLock { + runCatching { api.saveLongformProgress(songId, position, duration, completed) } + } } } @@ -1253,6 +1454,7 @@ private const val RECONNECT_MAX_MS = 300_000L private const val DOWNLOAD_ATTEMPTS = 3 private const val PROGRESS_POLL_TICKS = 12 private const val MAX_HISTORY = 50 +private const val SEARCH_DEBOUNCE_MS = 300L private fun LongformProgressItem.toProgress(): LongformProgress = LongformProgress( songId = song.id, diff --git a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/Components.kt b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/Components.kt index 3d6416c..fa0f8e4 100644 --- a/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/Components.kt +++ b/composeApp/src/commonMain/kotlin/win/taptap/musicmanager/client/ui/Components.kt @@ -215,7 +215,7 @@ fun MoodGradient(name: String): Brush { Color(0xFF1864AB) to Color(0xFF1098AD), Color(0xFF5F3DC4) to Color(0xFF862E9C), ) - val palette = palettes[abs(name.hashCode()) % palettes.size] + val palette = palettes[(name.hashCode() % palettes.size + palettes.size) % palettes.size] return Brush.linearGradient(listOf(palette.first, palette.second)) } 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 cf86d40..c410773 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 @@ -93,7 +93,10 @@ private fun MusicLibrary(state: AppState, store: AppStore) { item { OutlinedTextField( value = query, - onValueChange = { query = it }, + onValueChange = { + query = it + store.searchMusic(it) + }, singleLine = true, label = { Text("Search music") }, leadingIcon = { Icon(Icons.Rounded.Search, contentDescription = null) }, @@ -141,17 +144,17 @@ private fun MusicLibrary(state: AppState, store: AppStore) { } } - if (state.searchResults.isNotEmpty()) { + if (state.musicResults.isNotEmpty()) { item { SectionTitle("Search results") { Text( - "${state.searchResults.size}", + "${state.musicResults.size}", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) } } - items(state.searchResults, key = { "search-${it.id}" }) { song -> + items(state.musicResults, key = { "search-${it.id}" }) { song -> LibrarySongRow(song, state, store, supported) } item { HorizontalDivider(Modifier.padding(vertical = 14.dp)) } 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 2e5efc4..cf2709d 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 @@ -69,22 +69,24 @@ fun MoodDetailScreen(state: AppState, store: AppStore) { val mood = detail.mood var seedQuery by remember { mutableStateOf("") } - var name by remember(mood.id, mood.changedAt) { mutableStateOf(mood.name) } - var description by remember(mood.id, mood.changedAt) { mutableStateOf(mood.description.orEmpty()) } - var genres by remember(mood.id, mood.changedAt) { mutableStateOf(mood.genres.joinToString(", ")) } - var query by remember(mood.id, mood.changedAt) { mutableStateOf(mood.query.orEmpty()) } - var target by remember(mood.id, mood.changedAt) { mutableStateOf(mood.targetSize.toString()) } - var hours by remember(mood.id, mood.changedAt) { mutableStateOf(mood.refreshHours.toString()) } - var yt by remember(mood.id, mood.changedAt) { mutableStateOf(mood.ytEnabled) } - var seedPercent by remember(mood.id, mood.changedAt) { mutableStateOf(mood.seedPercent.toFloat()) } + var name by remember(mood.id) { mutableStateOf(mood.name) } + var description by remember(mood.id) { mutableStateOf(mood.description.orEmpty()) } + var genres by remember(mood.id) { mutableStateOf(mood.genres.joinToString(", ")) } + var query by remember(mood.id) { mutableStateOf(mood.query.orEmpty()) } + var target by remember(mood.id) { mutableStateOf(mood.targetSize.toString()) } + var hours by remember(mood.id) { mutableStateOf(mood.refreshHours.toString()) } + var yt by remember(mood.id) { mutableStateOf(mood.ytEnabled) } + var seedPercent by remember(mood.id) { mutableStateOf(mood.seedPercent.toFloat()) } val pendingDownloads = detail.recommendations.count { it.download?.state == "queued" || it.download?.state == "downloading" } LaunchedEffect(detail.mood.id, pendingDownloads) { - while (pendingDownloads > 0) { + var polls = 0 + while (pendingDownloads > 0 && polls < 60) { kotlinx.coroutines.delay(10_000) store.refreshSelectedMood() + polls += 1 } } 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 27b5c67..2a1415f 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 @@ -7,6 +7,7 @@ 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.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width @@ -56,10 +57,12 @@ fun PlayerBar(state: AppState, store: AppStore) { var queueOpen by remember { mutableStateOf(false) } var dragSeconds by remember(song.id) { mutableStateOf<Float?>(null) } val sleepRemaining = state.sleepTimerRemainingSeconds + val isLongform = state.user?.longformFolders?.contains(song.folderId) == true Surface( color = MaterialTheme.colorScheme.surfaceVariant, tonalElevation = 8.dp, + modifier = Modifier.navigationBarsPadding(), ) { Column(Modifier.fillMaxWidth()) { val progress = if (state.durationSeconds > 0) { @@ -164,11 +167,13 @@ fun PlayerBar(state: AppState, store: AppStore) { ) } - IconButton(onClick = { store.addCurrentToMood(null) }) { - Icon(Icons.Rounded.AddCircleOutline, contentDescription = "Add to current mood") - } - IconButton(onClick = { picker = true }) { - Icon(Icons.Rounded.PlaylistAdd, contentDescription = "Add to another mood") + if (!isLongform) { + IconButton(onClick = { store.addCurrentToMood(null) }) { + Icon(Icons.Rounded.AddCircleOutline, contentDescription = "Add to current mood") + } + IconButton(onClick = { picker = true }) { + Icon(Icons.Rounded.PlaylistAdd, contentDescription = "Add to another mood") + } } IconButton(onClick = { store.previous() }) { Icon(Icons.Rounded.SkipPrevious, contentDescription = "Previous") 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 469852d..68de268 100644 --- a/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/ApiClientTest.kt +++ b/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/ApiClientTest.kt @@ -6,6 +6,7 @@ import io.ktor.client.engine.mock.respondError import io.ktor.http.HttpHeaders import io.ktor.http.HttpStatusCode import io.ktor.http.headersOf +import io.ktor.utils.io.readAvailable import kotlinx.coroutines.test.runTest import kotlinx.serialization.json.Json import kotlin.test.Test @@ -73,6 +74,47 @@ class ApiClientTest { assertEquals("unauthorized", error.code) } + @Test + fun `failed downloads and images do not return error bodies`() = runTest { + val engine = MockEngine { + respond( + """{"error":{"code":"not_found","message":"Song not found"}}""", + HttpStatusCode.NotFound, + jsonHeaders, + ) + } + val client = ApiClient(configuredHttpClient(engine)) + client.restore("http://music", "token") + + val error = assertFailsWith<ApiException> { client.download("sg-missing") } + assertEquals(404, error.status) + assertNull(client.image("http://music/missing.jpg")) + } + + @Test + fun `downloadTo streams bytes into the storage sink`() = runTest { + val payload = ByteArray(100_000) { (it % 251).toByte() } + val engine = MockEngine { + respond(payload, HttpStatusCode.OK, headersOf(HttpHeaders.ContentType, "audio/mpeg")) + } + val client = ApiClient(configuredHttpClient(engine)) + client.restore("http://music", "token") + var received = 0 + + val path = client.downloadTo("sg-1") { channel -> + val buffer = ByteArray(8 * 1024) + while (true) { + val read = channel.readAvailable(buffer) + if (read < 0) break + received += read + } + "saved.mp3" + } + + assertEquals("saved.mp3", path) + assertEquals(payload.size, received) + } + @Test fun `cache round-trips songs and moods`() = runTest { val storage = MemoryStorage() 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 d7a7d4e..f59805c 100644 --- a/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/AppStoreTest.kt +++ b/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/AppStoreTest.kt @@ -244,6 +244,194 @@ class AppStoreTest { store.release() } + @Test + fun `restored playback resumes from the saved position`() = runTest { + val storage = MemoryStorage() + val cache = LibraryCache(storage) + cache.saveSession( + SessionState( + "http://music", + "token", + User("alice", admin = false, musicFolders = listOf(1), longformFolders = listOf(10)), + ), + ) + cache.save( + CachedState( + serverUrl = "http://music", + userName = "alice", + longform = listOf(song("l1", artist = "Book", folderId = 10, duration = 5400)), + ), + ) + cache.savePlayback( + PlaybackSnapshot( + current = song("l1", artist = "Book", folderId = 10, duration = 5400), + positionSeconds = 3600.0, + ), + ) + cache.saveProgress( + listOf( + win.taptap.musicmanager.client.api.LongformProgress( + songId = "l1", + positionSeconds = 3600, + durationSeconds = 5400, + completed = false, + updatedAt = "2026-01-01T00:00:00Z", + ), + ), + ) + val player = FakePlayer() + val store = store(storage, cache, player) + runCurrent() + awaitState { store.state.value.offline } + + assertEquals(3600.0, store.state.value.positionSeconds) + store.togglePlayPause() + runCurrent() + + assertEquals("l1", store.state.value.current?.id) + assertEquals(3600.0, player.seeks.last()) + store.release() + } + + @Test + fun `previous after resuming an audiobook goes back instead of restarting it`() = runTest { + val storage = MemoryStorage() + val cache = LibraryCache(storage) + cache.saveSession( + SessionState( + "http://music", + "token", + User("alice", admin = false, musicFolders = listOf(1), longformFolders = listOf(10)), + ), + ) + cache.save(CachedState(serverUrl = "http://music", userName = "alice")) + cache.savePlayback( + PlaybackSnapshot( + current = song("l1", artist = "Book", folderId = 10, duration = 5400), + history = listOf(song("a")), + positionSeconds = 3600.0, + ), + ) + val player = FakePlayer() + val store = store(storage, cache, player) + runCurrent() + awaitState { store.state.value.offline } + + store.previous() + runCurrent() + + assertEquals("a", store.state.value.current?.id) + assertEquals(listOf("l1"), store.state.value.queue.map { it.id }) + assertEquals("a", player.played.last()) + store.release() + } + + @Test + fun `finishing a longform track stays completed when the next track starts`() = runTest { + val storage = MemoryStorage() + val cache = LibraryCache(storage) + cache.saveSession( + SessionState( + "http://music", + "token", + User("alice", admin = false, musicFolders = listOf(1), longformFolders = listOf(10)), + ), + ) + cache.save( + CachedState( + serverUrl = "http://music", + userName = "alice", + longform = listOf( + song("l1", artist = "Book", folderId = 10, duration = 180), + song("l2", artist = "Book", folderId = 10, duration = 180), + ), + ), + ) + val player = FakePlayer() + val store = store(storage, cache, player) + runCurrent() + awaitState { store.state.value.offline } + + store.playLongformArtist("Book", shuffled = false) + runCurrent() + player.position = 180.0 + player.finish() + advanceTimeBy(600) + runCurrent() + + assertEquals(true, store.state.value.longformProgress["l1"]?.completed) + assertEquals("l2", store.state.value.current?.id) + store.release() + runCurrent() + } + + @Test + fun `logout removes progress and cached library`() = runTest { + val storage = MemoryStorage() + val cache = LibraryCache(storage) + cache.saveSession(SessionState("http://music", "token", User("alice", admin = false))) + cache.save(CachedState(serverUrl = "http://music", userName = "alice", songs = listOf(song("a")))) + cache.saveProgress( + listOf( + win.taptap.musicmanager.client.api.LongformProgress( + songId = "l1", + positionSeconds = 42, + durationSeconds = 180, + completed = false, + updatedAt = "2026-01-01T00:00:00Z", + ), + ), + ) + val store = store(storage, cache, FakePlayer()) + runCurrent() + + store.logout() + awaitState { !store.state.value.authenticated } + + assertTrue(cache.loadProgress().isEmpty()) + assertTrue(cache.load().songs.isEmpty()) + store.release() + } + + @Test + fun `music search is debounced and scoped to music`() = runTest { + val storage = MemoryStorage() + val cache = LibraryCache(storage) + var requestedScope: String? = null + val engine = MockEngine { request -> + when (request.url.encodedPath) { + "/api/v1/library/search" -> { + requestedScope = request.url.parameters["scope"] + respond( + """{"songs":[{"id":"m1","title":"Focus","artist":"Alpha","album":"Album", + "albumId":"al-1","duration":180,"bitRate":320,"size":1000,"suffix":"mp3", + "folderId":1,"relativePath":"m1.mp3","updatedAt":"now"}]}""", + HttpStatusCode.OK, + jsonHeaders, + ) + } + else -> respondError(HttpStatusCode.NotFound) + } + } + val store = AppStore( + scope = this, + api = ApiClient(configuredHttpClient(engine)), + storage = storage, + player = FakePlayer(), + cache = cache, + ) + runCurrent() + + store.searchMusic("focus") + advanceTimeBy(350) + runCurrent() + awaitState { store.state.value.musicResults.isNotEmpty() } + + assertEquals(listOf("m1"), store.state.value.musicResults.map { it.id }) + assertEquals("music", requestedScope) + store.release() + } + @Test fun `previous restarts after two seconds and restores the last track before it`() = runTest { val storage = MemoryStorage() @@ -427,13 +615,18 @@ class AppStoreTest { cache = cache, ) - private fun song(id: String, artist: String = "Artist", folderId: Int = 1) = Song( + private fun song( + id: String, + artist: String = "Artist", + folderId: Int = 1, + duration: Int = 180, + ) = Song( id = id, title = "Song $id", artist = artist, album = "Album", albumId = "al-1", - duration = 180, + duration = duration, bitRate = 320, size = 1_000, suffix = "mp3", @@ -448,7 +641,12 @@ class AppStoreTest { var paused = false private set private var playing = false - private var position = 0.0 + var position = 0.0 + private var finished = false + + fun finish() { + finished = true + } override fun play( source: String, @@ -461,6 +659,7 @@ class AppStoreTest { playing = true paused = false position = 0.0 + finished = false } override fun pause() { @@ -478,7 +677,7 @@ class AppStoreTest { } override fun isPlaying(): Boolean = playing - override fun isFinished(): Boolean = false + override fun isFinished(): Boolean = finished override fun positionSeconds(): Double = position override fun durationSeconds(): Double = 0.0 override val canSeek: Boolean = true diff --git a/composeApp/src/desktopMain/kotlin/win/taptap/musicmanager/client/DesktopAudioPlayer.kt b/composeApp/src/desktopMain/kotlin/win/taptap/musicmanager/client/DesktopAudioPlayer.kt index 9cd6764..c8815cf 100644 --- a/composeApp/src/desktopMain/kotlin/win/taptap/musicmanager/client/DesktopAudioPlayer.kt +++ b/composeApp/src/desktopMain/kotlin/win/taptap/musicmanager/client/DesktopAudioPlayer.kt @@ -76,7 +76,14 @@ class DesktopAudioPlayer : AudioPlayer { } else { source } - val raw = if (local) FileInputStream(File(requestSource)) else URI(requestSource).toURL().openStream() + val raw = if (local) { + FileInputStream(File(requestSource)) + } else { + val connection = URI(requestSource).toURL().openConnection() + connection.connectTimeout = 15_000 + connection.readTimeout = 30_000 + connection.getInputStream() + } val buffered = BufferedInputStream(raw, 128 * 1024) input = buffered val encoded = AudioSystem.getAudioInputStream(buffered) diff --git a/composeApp/src/desktopMain/kotlin/win/taptap/musicmanager/client/Platform.desktop.kt b/composeApp/src/desktopMain/kotlin/win/taptap/musicmanager/client/Platform.desktop.kt index 7c9b129..06b8f9a 100644 --- a/composeApp/src/desktopMain/kotlin/win/taptap/musicmanager/client/Platform.desktop.kt +++ b/composeApp/src/desktopMain/kotlin/win/taptap/musicmanager/client/Platform.desktop.kt @@ -4,6 +4,7 @@ import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.toComposeImageBitmap import io.ktor.client.engine.HttpClientEngine import io.ktor.client.engine.cio.CIO +import io.ktor.utils.io.readAvailable import java.io.File import win.taptap.musicmanager.client.data.AppStorage import win.taptap.musicmanager.client.playback.AudioPlayer @@ -32,7 +33,7 @@ class DesktopStorage : AppStorage { override fun write(name: String, text: String) { root.mkdirs() - File(root, name).writeText(text) + atomicWrite(File(root, name)) { it.writeText(text) } } override fun delete(name: String) { @@ -42,10 +43,39 @@ class DesktopStorage : AppStorage { override fun saveDownload(songId: String, bytes: ByteArray): String? { downloads.mkdirs() val file = File(downloads, "${safeName(songId)}.mp3") - file.writeBytes(bytes) + atomicWrite(file) { it.writeBytes(bytes) } return file.absolutePath } + override suspend fun saveDownloadStream( + songId: String, + source: io.ktor.utils.io.ByteReadChannel, + ): String? { + downloads.mkdirs() + val target = File(downloads, "${safeName(songId)}.mp3") + val temp = File(downloads, "${safeName(songId)}.mp3.part") + try { + temp.outputStream().use { output -> + val buffer = ByteArray(64 * 1024) + while (true) { + val read = source.readAvailable(buffer) + if (read < 0) break + if (read > 0) output.write(buffer, 0, read) + } + output.flush() + } + if (temp.length() == 0L) error("empty download") + if (!temp.renameTo(target)) { + temp.copyTo(target, overwrite = true) + temp.delete() + } + return target.absolutePath + } catch (t: Throwable) { + temp.delete() + throw t + } + } + override fun downloadPath(songId: String): String? = File(downloads, "${safeName(songId)}.mp3").takeIf { it.isFile }?.absolutePath @@ -53,7 +83,7 @@ class DesktopStorage : AppStorage { if (bytes.isEmpty()) return null downloads.mkdirs() val file = File(downloads, "${safeName(songId)}.jpg") - file.writeBytes(bytes) + atomicWrite(file) { it.writeBytes(bytes) } return file.absolutePath } @@ -74,6 +104,20 @@ class DesktopStorage : AppStorage { override fun storageUsedBytes(): Long = downloads.listFiles()?.sumOf { it.length() } ?: 0L + private fun atomicWrite(target: File, write: (File) -> Unit) { + val temp = File(target.parentFile, "${target.name}.part") + try { + write(temp) + if (!temp.renameTo(target)) { + temp.copyTo(target, overwrite = true) + temp.delete() + } + } catch (t: Throwable) { + temp.delete() + throw t + } + } + private fun safeName(songId: String): String = songId.map { if (it.isLetterOrDigit() || it == '-' || it == '_') it else '_' }.joinToString("") } diff --git a/composeApp/src/wasmJsMain/kotlin/win/taptap/musicmanager/client/Platform.wasm.kt b/composeApp/src/wasmJsMain/kotlin/win/taptap/musicmanager/client/Platform.wasm.kt index a3c411c..3a6c32f 100644 --- a/composeApp/src/wasmJsMain/kotlin/win/taptap/musicmanager/client/Platform.wasm.kt +++ b/composeApp/src/wasmJsMain/kotlin/win/taptap/musicmanager/client/Platform.wasm.kt @@ -29,6 +29,10 @@ class WebStorage : AppStorage { override fun saveDownload(songId: String, bytes: ByteArray): String? = null override fun downloadPath(songId: String): String? = null + override suspend fun saveDownloadStream( + songId: String, + source: io.ktor.utils.io.ByteReadChannel, + ): String? = null override fun saveArtwork(songId: String, bytes: ByteArray): String? = null override fun artworkBytes(songId: String): ByteArray? = null override fun listDownloads(): Map<String, Long> = emptyMap()