fix: harden playback, sync, downloads and mood state
CI / build (push) Successful in 2m1s

Playback:
- Persist the playhead in the playback snapshot and resume from it; restored
  longform progress is no longer overwritten with 0 on first play.
- Previous compares elapsed playtime since the track start, so resuming at
  1:00:00 and pressing previous goes back instead of restarting the book.
- Auto-advance no longer overwrites completed=true with false, longform PUTs
  are serialized, and playing rows/search results resume saved positions.
- Pause cancels the 400 ms poll; seek errors are reported instead of crashing.

Sync and state:
- First-sync snapshots keep the first page revision; cached revisions are only
  trusted for the same server/user.
- Refresh re-reads /me, merges local and server longform progress by timestamp,
  replays newer local positions, and keeps cached longform after deltas.
- Logout cancels refresh jobs, suppresses late progress writes, clears after
  playback teardown, and closes the HTTP client on release.
- Failed/racing mood opens clear the previous mood; stale responses cannot
  replace a newer selection. Mood drafts survive background refreshes.

Downloads and storage:
- Stream downloads to a .part file and atomically rename on Android/desktop,
  with a download-specific timeout and no whole-file buffering.
- Cache writes are best-effort and atomic; blocked/full web storage no longer
  leaves the app on the splash screen or blocks playback.
- Artwork failures do not fail audio downloads; failed downloads refresh the
  download index.
- Android queues sleep-timer commands before the controller connects.

UI:
- Music search is wired, debounced and kept separate from mood search.
- Player bar respects navigation-bar insets and hides music-only mood actions
  for longform. Mood gradient handles Int.MIN_VALUE.
This commit is contained in:
TapTap committed 2026-11-15 18:18:30 +00:00
1 parent 14bebced10
commit 43bd9629d3
17 files changed
+766 -145

No files matched your search

+2
View File
@@ -22,6 +22,8 @@ jobs:
image: gitea.tap-tap.win/taptap/audiomanager-client-ci:3 image: gitea.tap-tap.win/taptap/audiomanager-client-ci:3
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with:
persist-credentials: false
- name: Test and build - name: Test and build
run: | run: |
+3 -3
View File
@@ -143,9 +143,9 @@ The image build performs one warm-up compile (`kotlinNodeJsSetup`, `kotlinYarnSe
## Known limitations ## 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. - 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. - 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 `<music>/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 `<music>/AudioManager Imports/<artist>/<title>/`, 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. - 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. - No iOS target yet. The shared module is ready for one.
@@ -21,7 +21,7 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
private val appContext = context.applicationContext private val appContext = context.applicationContext
private var controller: MediaController? = null private var controller: MediaController? = null
private var pending: ((MediaController) -> Unit)? = null private val pending = ArrayDeque<(MediaController) -> Unit>()
private var connected = false private var connected = false
@Volatile private var finished = false @Volatile private var finished = false
@@ -45,8 +45,10 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
controller = sessionController controller = sessionController
sessionController.addListener(listener) sessionController.addListener(listener)
connected = true connected = true
pending?.invoke(sessionController) val queued = synchronized(pending) {
pending = null pending.toList().also { pending.clear() }
}
queued.forEach { action -> runCatching { action(sessionController) } }
} }
}, },
ContextCompat.getMainExecutor(appContext), ContextCompat.getMainExecutor(appContext),
@@ -125,9 +127,14 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
} }
override fun scheduleSleepTimer(seconds: Long?): Boolean { override fun scheduleSleepTimer(seconds: Long?): Boolean {
val current = controller ?: return false
val args = Bundle().apply { putLong(SLEEP_TIMER_SECONDS, seconds ?: 0L) } 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() { override fun release() {
@@ -135,7 +142,7 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
MediaController.releaseFuture(future) MediaController.releaseFuture(future)
controller = null controller = null
connected = false connected = false
pending = null synchronized(pending) { pending.clear() }
} }
private fun withController(block: (MediaController) -> Unit) { private fun withController(block: (MediaController) -> Unit) {
@@ -143,7 +150,9 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
if (current != null && connected) { if (current != null && connected) {
block(current) block(current)
} else { } 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) }
} }
} }
} }
@@ -6,6 +6,7 @@ import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.asImageBitmap
import io.ktor.client.engine.HttpClientEngine import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.engine.okhttp.OkHttp import io.ktor.client.engine.okhttp.OkHttp
import io.ktor.utils.io.readAvailable
import java.io.File import java.io.File
import win.taptap.musicmanager.client.data.AppStorage import win.taptap.musicmanager.client.data.AppStorage
import win.taptap.musicmanager.client.playback.AudioPlayer import win.taptap.musicmanager.client.playback.AudioPlayer
@@ -32,7 +33,7 @@ class AndroidStorage(context: Context) : AppStorage {
override fun write(name: String, text: String) { override fun write(name: String, text: String) {
root.mkdirs() root.mkdirs()
File(root, name).writeText(text) atomicWrite(File(root, name)) { it.writeText(text) }
} }
override fun delete(name: String) { override fun delete(name: String) {
@@ -42,10 +43,39 @@ class AndroidStorage(context: Context) : AppStorage {
override fun saveDownload(songId: String, bytes: ByteArray): String? { override fun saveDownload(songId: String, bytes: ByteArray): String? {
downloads.mkdirs() downloads.mkdirs()
val file = File(downloads, "${safeName(songId)}.mp3") val file = File(downloads, "${safeName(songId)}.mp3")
file.writeBytes(bytes) atomicWrite(file) { it.writeBytes(bytes) }
return file.absolutePath 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? = override fun downloadPath(songId: String): String? =
File(downloads, "${safeName(songId)}.mp3").takeIf { it.isFile }?.absolutePath File(downloads, "${safeName(songId)}.mp3").takeIf { it.isFile }?.absolutePath
@@ -53,7 +83,7 @@ class AndroidStorage(context: Context) : AppStorage {
if (bytes.isEmpty()) return null if (bytes.isEmpty()) return null
downloads.mkdirs() downloads.mkdirs()
val file = File(downloads, "${safeName(songId)}.jpg") val file = File(downloads, "${safeName(songId)}.jpg")
file.writeBytes(bytes) atomicWrite(file) { it.writeBytes(bytes) }
return file.absolutePath return file.absolutePath
} }
@@ -74,6 +104,20 @@ class AndroidStorage(context: Context) : AppStorage {
override fun storageUsedBytes(): Long = override fun storageUsedBytes(): Long =
downloads.listFiles()?.sumOf { it.length() } ?: 0L 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 = private fun safeName(songId: String): String =
songId.map { if (it.isLetterOrDigit() || it == '-' || it == '_') it else '_' }.joinToString("") songId.map { if (it.isLetterOrDigit() || it == '-' || it == '_') it else '_' }.joinToString("")
} }
@@ -16,6 +16,7 @@ import io.ktor.client.request.put
import io.ktor.client.request.setBody import io.ktor.client.request.setBody
import io.ktor.client.statement.HttpResponse import io.ktor.client.statement.HttpResponse
import io.ktor.client.statement.bodyAsBytes import io.ktor.client.statement.bodyAsBytes
import io.ktor.client.statement.bodyAsChannel
import io.ktor.http.ContentType import io.ktor.http.ContentType
import io.ktor.http.HttpHeaders import io.ktor.http.HttpHeaders
import io.ktor.http.HttpStatusCode import io.ktor.http.HttpStatusCode
@@ -23,6 +24,7 @@ import io.ktor.http.contentType
import io.ktor.http.encodeURLParameter import io.ktor.http.encodeURLParameter
import io.ktor.http.isSuccess import io.ktor.http.isSuccess
import io.ktor.serialization.kotlinx.json.json import io.ktor.serialization.kotlinx.json.json
import io.ktor.utils.io.ByteReadChannel
import kotlinx.serialization.json.Json import kotlinx.serialization.json.Json
fun configuredHttpClient(engine: HttpClientEngine): HttpClient = HttpClient(engine) { fun configuredHttpClient(engine: HttpClientEngine): HttpClient = HttpClient(engine) {
@@ -85,6 +87,10 @@ class ApiClient(private val http: HttpClient) {
imageCache.clear() imageCache.clear()
} }
fun close() {
http.close()
}
suspend fun me(): User = get("/me") suspend fun me(): User = get("/me")
suspend fun logout() { suspend fun logout() {
@@ -173,11 +179,13 @@ class ApiClient(private val http: HttpClient) {
since: String? = null, since: String? = null,
limit: Int = 500, limit: Int = 500,
scope: String = "all", scope: String = "all",
revision: String? = null,
): LibraryPage { ): LibraryPage {
val query = buildString { val query = buildString {
append("?limit=$limit&scope=$scope") append("?limit=$limit&scope=$scope")
cursor?.let { append("&cursor=${it.encodeURLParameter()}") } cursor?.let { append("&cursor=${it.encodeURLParameter()}") }
since?.let { append("&since=${it.encodeURLParameter()}") } since?.let { append("&since=${it.encodeURLParameter()}") }
revision?.let { append("&revision=${it.encodeURLParameter()}") }
} }
return get("/library/songs$query") return get("/library/songs$query")
} }
@@ -266,25 +274,61 @@ class ApiClient(private val http: HttpClient) {
} }
}.getOrNull() }.getOrNull()
if (coverCache.size > MAX_CACHED_IMAGES) coverCache.clear() 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 return result
} }
/** Remote artwork such as YT thumbnails, cached for the app's lifetime. */ /** Remote artwork such as YT thumbnails, cached for the app's lifetime. */
suspend fun image(url: String): ByteArray? { suspend fun image(url: String): ByteArray? {
if (imageCache.containsKey(url)) return imageCache[url] if (imageCache.containsKey(url)) return imageCache[url]
val bytes = runCatching { http.get(url).bodyAsBytes() }.getOrNull() val result = runCatching {
val result = bytes?.takeIf { it.isNotEmpty() } 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() if (imageCache.size > MAX_CACHED_IMAGES) imageCache.clear()
imageCache[url] = result if (result != null) imageCache[url] = result
return result return result
} }
suspend fun download(songId: String): ByteArray = suspend fun download(songId: String): ByteArray {
http.get("$baseUrl/api/v1/songs/$songId/stream") { 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() auth()
url.parameters.append("download", "true") 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 = fun streamUrl(songId: String): String =
"$baseUrl/api/v1/songs/$songId/stream?token=${token.orEmpty().encodeURLParameter()}" "$baseUrl/api/v1/songs/$songId/stream?token=${token.orEmpty().encodeURLParameter()}"
@@ -10,6 +10,9 @@ interface AppStorage {
fun saveDownload(songId: String, bytes: ByteArray): String? fun saveDownload(songId: String, bytes: ByteArray): String?
fun downloadPath(songId: String): 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. */ /** Stores the cover next to the audio file so offline playback keeps artwork. */
fun saveArtwork(songId: String, bytes: ByteArray): String? fun saveArtwork(songId: String, bytes: ByteArray): String?
fun artworkBytes(songId: String): ByteArray? fun artworkBytes(songId: String): ByteArray?
@@ -34,6 +34,7 @@ data class PlaybackSnapshot(
val queue: List<Song> = emptyList(), val queue: List<Song> = emptyList(),
val current: Song? = null, val current: Song? = null,
val history: List<Song> = emptyList(), val history: List<Song> = emptyList(),
val positionSeconds: Double = 0.0,
) )
class LibraryCache(private val storage: AppStorage) { class LibraryCache(private val storage: AppStorage) {
@@ -45,49 +46,59 @@ class LibraryCache(private val storage: AppStorage) {
} }
fun loadSession(): SessionState? = fun loadSession(): SessionState? =
storage.read(SESSION_FILE)?.let { read(SESSION_FILE)?.let {
runCatching { json.decodeFromString<SessionState>(it) }.getOrNull() runCatching { json.decodeFromString<SessionState>(it) }.getOrNull()
} }
fun saveSession(session: SessionState?) { 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 = fun load(): CachedState =
storage.read(CACHE_FILE)?.let { read(CACHE_FILE)?.let {
runCatching { json.decodeFromString<CachedState>(it) }.getOrNull() runCatching { json.decodeFromString<CachedState>(it) }.getOrNull()
} ?: CachedState() } ?: CachedState()
fun save(state: CachedState) { fun save(state: CachedState) {
storage.write(CACHE_FILE, json.encodeToString(state)) write(CACHE_FILE, json.encodeToString(state))
} }
fun loadPlayback(): PlaybackSnapshot? = fun loadPlayback(): PlaybackSnapshot? =
storage.read(PLAYBACK_FILE)?.let { read(PLAYBACK_FILE)?.let {
runCatching { json.decodeFromString<PlaybackSnapshot>(it) }.getOrNull() runCatching { json.decodeFromString<PlaybackSnapshot>(it) }.getOrNull()
} }
fun savePlayback(snapshot: PlaybackSnapshot?) { fun savePlayback(snapshot: PlaybackSnapshot?) {
if (snapshot == null || (snapshot.current == null && snapshot.queue.isEmpty())) { if (snapshot == null || (snapshot.current == null && snapshot.queue.isEmpty())) {
storage.delete(PLAYBACK_FILE) delete(PLAYBACK_FILE)
} else { } else {
storage.write(PLAYBACK_FILE, json.encodeToString(snapshot)) write(PLAYBACK_FILE, json.encodeToString(snapshot))
} }
} }
fun loadProgress(): List<LongformProgress> = fun loadProgress(): List<LongformProgress> =
storage.read(PROGRESS_FILE)?.let { read(PROGRESS_FILE)?.let {
runCatching { json.decodeFromString<List<LongformProgress>>(it) }.getOrNull() runCatching { json.decodeFromString<List<LongformProgress>>(it) }.getOrNull()
} ?: emptyList() } ?: emptyList()
fun saveProgress(progress: List<LongformProgress>) { fun saveProgress(progress: List<LongformProgress>) {
storage.write(PROGRESS_FILE, json.encodeToString(progress)) write(PROGRESS_FILE, json.encodeToString(progress))
} }
fun clear() { fun clear() {
storage.delete(CACHE_FILE) delete(CACHE_FILE)
storage.delete(PLAYBACK_FILE) delete(PLAYBACK_FILE)
storage.delete(PROGRESS_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 { private companion object {
@@ -1,10 +1,13 @@
package win.taptap.musicmanager.client.store package win.taptap.musicmanager.client.store
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job import kotlinx.coroutines.Job
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.asStateFlow
@@ -60,7 +63,10 @@ data class AppState(
val longform: List<Song> = emptyList(), val longform: List<Song> = emptyList(),
val longformResults: List<Song> = emptyList(), val longformResults: List<Song> = emptyList(),
val longformProgress: Map<String, LongformProgress> = emptyMap(), val longformProgress: Map<String, LongformProgress> = emptyMap(),
/** Results for the mood seed picker. */
val searchResults: List<Song> = emptyList(), 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 searching: Boolean = false,
val loading: Boolean = false, val loading: Boolean = false,
val saving: Boolean = false, val saving: Boolean = false,
@@ -85,13 +91,21 @@ class AppStore(
val state: StateFlow<AppState> = _state.asStateFlow() val state: StateFlow<AppState> = _state.asStateFlow()
private var pollJob: Job? = null private var pollJob: Job? = null
private var refreshJob: Job? = null
private var sleepJob: Job? = null private var sleepJob: Job? = null
private var musicSearchJob: Job? = null
private var longformSearchJob: Job? = null
private var reconnectJob: Job? = null private var reconnectJob: Job? = null
private var playbackStarted = false private var playbackStarted = false
private var advancing = false private var advancing = false
private var fetching = false private var fetching = false
private var finishing = false private var finishing = false
private var pollTicks = 0 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 { init {
bootstrap() bootstrap()
@@ -103,6 +117,12 @@ class AppStore(
val cached = cache.load() val cached = cache.load()
val playback = cache.loadPlayback() val playback = cache.loadPlayback()
val progress = cache.loadProgress() 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 { _state.update {
it.copy( it.copy(
booting = false, booting = false,
@@ -110,13 +130,14 @@ class AppStore(
moods = cached.moods, moods = cached.moods,
library = cached.songs.sortedLibrary(), library = cached.songs.sortedLibrary(),
longform = cached.longform.sortedLibrary(), longform = cached.longform.sortedLibrary(),
longformProgress = progress.associateBy { entry -> entry.songId }, longformProgress = progressById,
selectedMood = cached.moodDetails.firstOrNull(), selectedMood = cached.moodDetails.firstOrNull(),
session = playback?.session, session = playback?.session,
queue = playback?.queue.orEmpty(), queue = playback?.queue.orEmpty(),
current = playback?.current, current = restoredSong,
history = playback?.history.orEmpty(), 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", deviceName = "$platformName device",
platform = platformName, 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 { _state.update {
it.copy( it.copy(
authenticated = true, authenticated = true,
user = response.user, user = response.user,
serverUrl = api.baseUrl, serverUrl = api.baseUrl,
loading = false, loading = false,
message = null,
) )
} }
refreshAll() refreshAll()
@@ -164,11 +190,17 @@ class AppStore(
} }
fun logout() { fun logout() {
dataGeneration += 1
loggingOut = true
scope.launch { scope.launch {
musicSearchJob?.cancel()
longformSearchJob?.cancel()
refreshJob?.cancel()
stopPlayback()
runCatching { api.logout() } runCatching { api.logout() }
api.clear()
cache.saveSession(null) cache.saveSession(null)
cache.clear() cache.clear()
stopPlayback()
_state.value = AppState( _state.value = AppState(
booting = false, booting = false,
serverUrl = _state.value.serverUrl, serverUrl = _state.value.serverUrl,
@@ -178,14 +210,31 @@ class AppStore(
} }
fun refreshAll(silent: Boolean = false) { fun refreshAll(silent: Boolean = false) {
scope.launch { refreshAllNow(silent) } refreshJob?.cancel()
refreshJob = scope.launch { refreshAllNow(silent) }
} }
private suspend fun refreshAllNow(silent: Boolean) { private suspend fun refreshAllNow(silent: Boolean) {
if (!silent) _state.update { it.copy(loading = true) } if (!silent) _state.update { it.copy(loading = true) }
val generation = dataGeneration
try { 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 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 // Both halves of the cache must feed the delta sync; otherwise the
// long-form list disappears as soon as the first delta arrives. // long-form list disappears as soon as the first delta arrives.
var songs = (cached.songs + cached.longform) var songs = (cached.songs + cached.longform)
@@ -194,9 +243,18 @@ class AppStore(
var revision = cached.revision var revision = cached.revision
if (revision == null) { 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 var cursor: String? = null
do { 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 } page.songs.forEach { songs[it.id] = it }
cursor = page.nextCursor cursor = page.nextCursor
revision = page.revision revision = page.revision
@@ -213,37 +271,67 @@ class AppStore(
} }
val details = cached.moodDetails.filter { detail -> moods.any { it.id == detail.mood.id } } 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 allSongs = songs.values.toList()
val longformSongs = allSongs.filter { it.folderId in longformFolders } val longformSongs = allSongs.filter { it.folderId in longformFolders }
val musicSongs = allSongs.filterNot { it.folderId in longformFolders } val musicSongs = allSongs.filterNot { it.folderId in longformFolders }
val serverProgress = runCatching { api.longformProgress() }.getOrNull() val serverProgress = runCatching { api.longformProgress() }.getOrNull()
cache.save( if (generation != dataGeneration) return
CachedState( runCatching {
serverUrl = _state.value.serverUrl, cache.save(
userName = _state.value.user?.name.orEmpty(), CachedState(
revision = revision, serverUrl = _state.value.serverUrl,
songs = musicSongs, userName = currentUser?.name.orEmpty(),
longform = longformSongs, revision = revision,
moods = moods, songs = musicSongs,
moodDetails = details, longform = longformSongs,
), moods = moods,
) moodDetails = details,
serverProgress?.let { items -> ),
cache.saveProgress(items.map { it.toProgress() }) )
}
// 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 { _state.update {
it.copy( it.copy(
loading = false, loading = false,
offline = false, offline = false,
user = currentUser,
moods = moods, moods = moods,
library = musicSongs.sortedLibrary(), library = musicSongs.sortedLibrary(),
longform = longformSongs.sortedLibrary(), longform = longformSongs.sortedLibrary(),
longformProgress = serverProgress longformProgress = if (serverProgress != null) mergedProgress else it.longformProgress,
?.associate { item -> item.song.id to item.toProgress() }
?: it.longformProgress,
) )
} }
} catch (t: Throwable) { } catch (t: Throwable) {
@@ -265,23 +353,37 @@ class AppStore(
} }
fun openMoods() { fun openMoods() {
moodRequestGeneration += 1
_state.update { it.copy(screen = Screen.Moods) } _state.update { it.copy(screen = Screen.Moods) }
} }
fun openMood(id: String) { fun openMood(id: String) {
scope.launch { 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 { try {
val detail = api.mood(id) val detail = api.mood(id)
val preview = runCatching { api.preview(id, 20) }.getOrDefault(emptyList()) val preview = runCatching { api.preview(id, 20) }.getOrDefault(emptyList())
if (request != moodRequestGeneration) return@launch
cacheDetail(detail) cacheDetail(detail)
_state.update { it.copy(loading = false, selectedMood = detail, preview = preview) } _state.update { it.copy(loading = false, selectedMood = detail, preview = preview) }
} catch (t: Throwable) { } catch (t: Throwable) {
if (request != moodRequestGeneration) return@launch
val cached = cache.load().moodDetails.firstOrNull { it.mood.id == id } val cached = cache.load().moodDetails.firstOrNull { it.mood.id == id }
_state.update { _state.update {
it.copy( it.copy(
loading = false, 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", message = if (cached == null) t.friendlyMessage() else "Showing cached mood",
messageIsError = cached == null, messageIsError = cached == null,
messageId = it.messageId + 1, messageId = it.messageId + 1,
@@ -295,7 +397,9 @@ class AppStore(
fun refreshSelectedMood() { fun refreshSelectedMood() {
val moodId = _state.value.selectedMood?.mood?.id ?: return val moodId = _state.value.selectedMood?.mood?.id ?: return
scope.launch { 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, seedPercent = seedPercent,
), ),
) )
cacheDetail(updated) applyMoodDetail(updated)
_state.update { _state.update {
it.copy( it.copy(
saving = false, saving = false,
selectedMood = updated,
moods = it.moods.map { mood -> if (mood.id == updated.mood.id) updated.mood else mood },
message = "Saved", message = "Saved",
messageIsError = false, messageIsError = false,
messageId = it.messageId + 1, messageId = it.messageId + 1,
@@ -421,11 +523,9 @@ class AppStore(
try { try {
api.addSeed(moodId, songId) api.addSeed(moodId, songId)
val detail = api.mood(moodId) val detail = api.mood(moodId)
cacheDetail(detail) applyMoodDetail(detail)
_state.update { _state.update {
it.copy( it.copy(
selectedMood = detail,
moods = it.moods.map { mood -> if (mood.id == moodId) detail.mood else mood },
message = "Seed added", message = "Seed added",
messageIsError = false, messageIsError = false,
messageId = it.messageId + 1, messageId = it.messageId + 1,
@@ -442,11 +542,9 @@ class AppStore(
try { try {
api.removeSeed(moodId, songId) api.removeSeed(moodId, songId)
val detail = api.mood(moodId) val detail = api.mood(moodId)
cacheDetail(detail) applyMoodDetail(detail)
_state.update { _state.update {
it.copy( it.copy(
selectedMood = detail,
moods = it.moods.map { mood -> if (mood.id == moodId) detail.mood else mood },
message = "Seed removed", message = "Seed removed",
messageIsError = false, messageIsError = false,
messageId = it.messageId + 1, 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) { fun searchLongform(query: String) {
longformSearchJob?.cancel()
if (query.isBlank()) { if (query.isBlank()) {
_state.update { it.copy(longformResults = emptyList()) } _state.update { it.copy(longformResults = emptyList()) }
return return
} }
scope.launch { longformSearchJob = scope.launch {
delay(SEARCH_DEBOUNCE_MS)
_state.update { it.copy(searching = true) } _state.update { it.copy(searching = true) }
try { try {
val songs = api.search(query, 60, scope = "longform") 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) { } catch (t: Throwable) {
_state.update { it.copy(searching = false, longformResults = emptyList()) } _state.update { it.copy(longformResults = emptyList()) }
message(t) message(t)
} finally {
_state.update { it.copy(searching = false) }
} }
} }
} }
@@ -521,8 +648,10 @@ class AppStore(
) )
} }
playNext() playNext()
scheduleReconnect()
} else { } else {
message(t) message(t)
scheduleReconnect()
} }
} }
} }
@@ -530,6 +659,7 @@ class AppStore(
fun playSong(song: Song) { fun playSong(song: Song) {
scope.launch { scope.launch {
reportCurrentProgress(completed = false)
_state.value.session?.let { api.closeSession(it.id) } _state.value.session?.let { api.closeSession(it.id) }
_state.update { _state.update {
it.copy( 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 { scope.launch {
reportCurrentProgress(completed = false)
_state.value.session?.let { runCatching { api.closeSession(it.id) } } _state.value.session?.let { runCatching { api.closeSession(it.id) } }
val startAt = startAtSeconds ?: savedPosition(song)
_state.update { _state.update {
it.copy( it.copy(
session = null, session = null,
@@ -605,20 +737,25 @@ class AppStore(
current = song, current = song,
history = pushHistory(it.history, it.current), history = pushHistory(it.history, it.current),
playing = true, playing = true,
positionSeconds = startAtSeconds, positionSeconds = startAt,
durationSeconds = song.duration.toDouble(), durationSeconds = song.duration.toDouble(),
) )
} }
persistPlayback() persistPlayback()
startSong(song, startAtSeconds) startSong(song, startAt)
} }
} }
fun resumeLongform(songId: String) { fun resumeLongform(songId: String) {
val state = _state.value val state = _state.value
val song = state.longform.firstOrNull { it.id == songId } ?: return val song = state.longform.firstOrNull { it.id == songId } ?: return
val startAt = state.longformProgress[songId]?.positionSeconds?.toDouble() ?: 0.0 playLongformSong(song, savedPosition(song))
playLongformSong(song, startAt) }
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) { fun moveInQueue(fromIndex: Int, toIndex: Int) {
@@ -675,6 +812,9 @@ class AppStore(
if (!isActive) return@launch if (!isActive) return@launch
val wasPlaying = _state.value.playing val wasPlaying = _state.value.playing
player.pause() player.pause()
pollJob?.cancel()
reportCurrentProgress(completed = false)
persistPlayback()
_state.update { _state.update {
it.copy( it.copy(
playing = false, playing = false,
@@ -751,14 +891,26 @@ class AppStore(
val song = state.current ?: return val song = state.current ?: return
if (state.playing) { if (state.playing) {
player.pause() player.pause()
pollJob?.cancel()
_state.update { it.copy(playing = false) } _state.update { it.copy(playing = false) }
reportCurrentProgress(completed = false) reportCurrentProgress(completed = false)
persistPlayback()
} else if (!playbackStarted || player.isFinished()) { } else if (!playbackStarted || player.isFinished()) {
// Restored queue or finished track: start it from the beginning. val finished = player.isFinished()
_state.update { val duration = state.durationSeconds.takeIf { it > 0 } ?: song.duration.toDouble()
it.copy(playing = true, positionSeconds = 0.0, durationSeconds = 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 { } else {
player.resume() player.resume()
_state.update { it.copy(playing = true) } _state.update { it.copy(playing = true) }
@@ -768,7 +920,7 @@ class AppStore(
fun skip() { fun skip() {
val state = _state.value val state = _state.value
state.current?.let { report("skipped", it.id) } state.current?.let { report("skipped", it.id, state.positionSeconds.toInt()) }
playNext() playNext()
} }
@@ -780,7 +932,8 @@ class AppStore(
fun previous() { fun previous() {
val state = _state.value val state = _state.value
val song = state.current ?: return val song = state.current ?: return
if (state.positionSeconds > 2.0) { val elapsed = (state.positionSeconds - trackStartOffset).coerceAtLeast(0.0)
if (elapsed > 2.0) {
restartCurrent(song) restartCurrent(song)
return return
} }
@@ -791,6 +944,7 @@ class AppStore(
return return
} }
val targetStart = savedPosition(target)
reportCurrentProgress(completed = false) reportCurrentProgress(completed = false)
_state.update { _state.update {
it.copy( it.copy(
@@ -798,18 +952,20 @@ class AppStore(
queue = listOf(song) + it.queue, queue = listOf(song) + it.queue,
current = target, current = target,
playing = true, playing = true,
positionSeconds = 0.0, positionSeconds = targetStart,
durationSeconds = target.duration.toDouble(), durationSeconds = target.duration.toDouble(),
) )
} }
persistPlayback() persistPlayback()
startSong(target) startSong(target, targetStart)
report("started", target.id) report("started", target.id, 0)
} }
private fun restartCurrent(song: Song) { private fun restartCurrent(song: Song) {
trackStartOffset = 0.0
if (player.canSeek) { if (player.canSeek) {
player.seekTo(0.0) runCatching { player.seekTo(0.0) }
.onFailure { message(it) }
_state.update { it.copy(positionSeconds = 0.0) } _state.update { it.copy(positionSeconds = 0.0) }
} else { } else {
_state.update { it.copy(playing = true, positionSeconds = 0.0) } _state.update { it.copy(playing = true, positionSeconds = 0.0) }
@@ -821,9 +977,15 @@ class AppStore(
fun seekTo(seconds: Double) { fun seekTo(seconds: Double) {
if (!player.canSeek) return if (!player.canSeek) return
player.seekTo(seconds) val target = seconds.coerceAtLeast(0.0)
_state.update { it.copy(positionSeconds = seconds) } try {
reportCurrentProgress(completed = false) player.seekTo(target)
_state.update { it.copy(positionSeconds = target) }
reportCurrentProgress(completed = false)
persistPlayback()
} catch (t: Throwable) {
message(t)
}
} }
fun addCurrentToMood(targetMoodId: String?) { fun addCurrentToMood(targetMoodId: String?) {
@@ -850,14 +1012,14 @@ class AppStore(
val updatedMoods = state.moods.map { mood -> val updatedMoods = state.moods.map { mood ->
if (mood.id == response.mood.id) response.mood else 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 { _state.update {
val selected = it.selectedMood?.let { detail ->
if (detail.mood.id == response.mood.id) {
detail.copy(mood = response.mood)
} else {
detail
}
}
it.copy( it.copy(
moods = updatedMoods, moods = updatedMoods,
selectedMood = selected, selectedMood = selected,
@@ -870,7 +1032,7 @@ class AppStore(
messageId = it.messageId + 1, messageId = it.messageId + 1,
) )
} }
if (selected != null) cacheDetail(selected) _state.value.selectedMood?.let { cacheDetail(it) }
} catch (t: Throwable) { } catch (t: Throwable) {
message(t) message(t)
} }
@@ -892,18 +1054,24 @@ class AppStore(
return return
} }
val generation = dataGeneration
scope.launch { scope.launch {
_state.update { it.copy(downloading = it.downloading + song.id) } _state.update { it.copy(downloading = it.downloading + song.id) }
var lastError: Throwable? = null var lastError: Throwable? = null
repeat(DOWNLOAD_ATTEMPTS) { attempt -> repeat(DOWNLOAD_ATTEMPTS) { attempt ->
try { try {
val bytes = api.download(song.id) val path = api.downloadTo(song.id) { channel ->
val path = storage.saveDownload(song.id, bytes) storage.saveDownloadStream(song.id, channel)
}
if (path != null) { if (path != null) {
runCatching { api.cover(song.albumId, 320) } runCatching { api.cover(song.albumId, 320) }
.getOrNull() .getOrNull()
?.takeIf { it.isNotEmpty() } ?.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) { if (path == null) {
_state.update { _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")) message(lastError ?: IllegalStateException("Download failed"))
} }
} }
@@ -983,9 +1156,13 @@ class AppStore(
fun release() { fun release() {
persistPlayback() persistPlayback()
pollJob?.cancel() pollJob?.cancel()
refreshJob?.cancel()
sleepJob?.cancel() sleepJob?.cancel()
reconnectJob?.cancel() reconnectJob?.cancel()
musicSearchJob?.cancel()
longformSearchJob?.cancel()
player.release() player.release()
api.close()
} }
private fun playNext() { private fun playNext() {
@@ -998,22 +1175,28 @@ class AppStore(
return return
} }
advancing = true advancing = true
val sessionId = session.id
scope.launch { scope.launch {
try { try {
val more = api.nextTracks(session.id, 12) val more = api.nextTracks(sessionId, 12)
_state.update { it.copy(queue = it.queue + more) } if (_state.value.session?.id == sessionId) {
_state.update { it.copy(queue = it.queue + more) }
}
} catch (t: Throwable) { } catch (t: Throwable) {
message(t) message(t)
} finally { } finally {
advancing = false advancing = false
} }
if (_state.value.session?.id != sessionId) return@launch
if (_state.value.queue.isNotEmpty()) playNext() else _state.update { it.copy(playing = false) } if (_state.value.queue.isNotEmpty()) playNext() else _state.update { it.copy(playing = false) }
} }
return return
} }
val song = state.queue.first() 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 { _state.update {
it.copy( it.copy(
queue = it.queue.drop(1), queue = it.queue.drop(1),
@@ -1026,7 +1209,7 @@ class AppStore(
} }
persistPlayback() persistPlayback()
startSong(song) startSong(song)
report("started", song.id) report("started", song.id, 0)
if (_state.value.queue.size < 3) prefetch() if (_state.value.queue.size < 3) prefetch()
} }
@@ -1034,10 +1217,13 @@ class AppStore(
val session = _state.value.session ?: return val session = _state.value.session ?: return
if (fetching) return if (fetching) return
fetching = true fetching = true
val sessionId = session.id
scope.launch { scope.launch {
try { try {
val more = api.nextTracks(session.id, 12) val more = api.nextTracks(sessionId, 12)
_state.update { it.copy(queue = it.queue + more) } if (_state.value.session?.id == sessionId) {
_state.update { it.copy(queue = it.queue + more) }
}
} catch (_: Throwable) { } catch (_: Throwable) {
// The queue still has tracks; a later request will retry. // The queue still has tracks; a later request will retry.
} finally { } finally {
@@ -1050,6 +1236,7 @@ class AppStore(
val localPath = storage.downloadPath(song.id) val localPath = storage.downloadPath(song.id)
finishing = false finishing = false
pollTicks = 0 pollTicks = 0
trackStartOffset = startAtSeconds
try { try {
player.play( player.play(
source = localPath ?: api.streamUrl(song.id), source = localPath ?: api.streamUrl(song.id),
@@ -1094,14 +1281,16 @@ class AppStore(
pollTicks += 1 pollTicks += 1
if (pollTicks >= PROGRESS_POLL_TICKS) { if (pollTicks >= PROGRESS_POLL_TICKS) {
pollTicks = 0 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 (player.isFinished()) {
if (!finishing) { if (!finishing) {
finishing = true finishing = true
reportCurrentProgress(completed = true) reportCurrentProgress(completed = true)
report("completed", state.current?.id) report("completed", state.current?.id, state.positionSeconds.toInt())
playNext() playNext()
} }
break 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 val session = _state.value.session ?: return
if (songId == null) return if (songId == null) return
scope.launch { scope.launch {
@@ -1121,7 +1310,7 @@ class AppStore(
PlaybackEvent( PlaybackEvent(
songId = songId, songId = songId,
type = type, type = type,
positionSeconds = _state.value.positionSeconds.toInt(), positionSeconds = positionSeconds,
), ),
), ),
) )
@@ -1151,16 +1340,22 @@ class AppStore(
} }
private fun cacheDetail(detail: MoodDetail) { private fun cacheDetail(detail: MoodDetail) {
val cached = cache.load() runCatching {
val details = cached.moodDetails.filterNot { it.mood.id == detail.mood.id } + detail val cached = cache.load()
cache.save(cached.copy(moodDetails = details, moods = cached.moods)) 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) { private fun applyMoodDetail(detail: MoodDetail) {
cacheDetail(detail) cacheDetail(detail)
_state.update { state -> _state.update { state ->
state.copy( 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 }, moods = state.moods.map { mood -> if (mood.id == detail.mood.id) detail.mood else mood },
) )
} }
@@ -1168,14 +1363,17 @@ class AppStore(
private fun persistPlayback() { private fun persistPlayback() {
val state = _state.value val state = _state.value
cache.savePlayback( runCatching {
cache.savePlayback(
PlaybackSnapshot( PlaybackSnapshot(
session = state.session, session = state.session,
queue = state.queue, queue = state.queue,
current = state.current, current = state.current,
history = state.history, history = state.history,
positionSeconds = state.positionSeconds,
), ),
) )
}
} }
/** Retries the library sync with exponential backoff while offline. */ /** Retries the library sync with exponential backoff while offline. */
@@ -1200,6 +1398,7 @@ class AppStore(
_state.value.user?.longformFolders?.toSet().orEmpty() _state.value.user?.longformFolders?.toSet().orEmpty()
private fun reportCurrentProgress(completed: Boolean) { private fun reportCurrentProgress(completed: Boolean) {
if (loggingOut) return
val state = _state.value val state = _state.value
val song = state.current ?: return val song = state.current ?: return
if (song.folderId !in longformFolders()) return if (song.folderId !in longformFolders()) return
@@ -1225,7 +1424,9 @@ class AppStore(
_state.update { it.copy(longformProgress = it.longformProgress + (songId to entry)) } _state.update { it.copy(longformProgress = it.longformProgress + (songId to entry)) }
cache.saveProgress(_state.value.longformProgress.values.toList()) cache.saveProgress(_state.value.longformProgress.values.toList())
scope.launch { 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 DOWNLOAD_ATTEMPTS = 3
private const val PROGRESS_POLL_TICKS = 12 private const val PROGRESS_POLL_TICKS = 12
private const val MAX_HISTORY = 50 private const val MAX_HISTORY = 50
private const val SEARCH_DEBOUNCE_MS = 300L
private fun LongformProgressItem.toProgress(): LongformProgress = LongformProgress( private fun LongformProgressItem.toProgress(): LongformProgress = LongformProgress(
songId = song.id, songId = song.id,
@@ -215,7 +215,7 @@ fun MoodGradient(name: String): Brush {
Color(0xFF1864AB) to Color(0xFF1098AD), Color(0xFF1864AB) to Color(0xFF1098AD),
Color(0xFF5F3DC4) to Color(0xFF862E9C), 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)) return Brush.linearGradient(listOf(palette.first, palette.second))
} }
@@ -93,7 +93,10 @@ private fun MusicLibrary(state: AppState, store: AppStore) {
item { item {
OutlinedTextField( OutlinedTextField(
value = query, value = query,
onValueChange = { query = it }, onValueChange = {
query = it
store.searchMusic(it)
},
singleLine = true, singleLine = true,
label = { Text("Search music") }, label = { Text("Search music") },
leadingIcon = { Icon(Icons.Rounded.Search, contentDescription = null) }, 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 { item {
SectionTitle("Search results") { SectionTitle("Search results") {
Text( Text(
"${state.searchResults.size}", "${state.musicResults.size}",
style = MaterialTheme.typography.labelSmall, style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, 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) LibrarySongRow(song, state, store, supported)
} }
item { HorizontalDivider(Modifier.padding(vertical = 14.dp)) } item { HorizontalDivider(Modifier.padding(vertical = 14.dp)) }
@@ -69,22 +69,24 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
val mood = detail.mood val mood = detail.mood
var seedQuery by remember { mutableStateOf("") } var seedQuery by remember { mutableStateOf("") }
var name by remember(mood.id, mood.changedAt) { mutableStateOf(mood.name) } var name by remember(mood.id) { mutableStateOf(mood.name) }
var description by remember(mood.id, mood.changedAt) { mutableStateOf(mood.description.orEmpty()) } var description by remember(mood.id) { mutableStateOf(mood.description.orEmpty()) }
var genres by remember(mood.id, mood.changedAt) { mutableStateOf(mood.genres.joinToString(", ")) } var genres by remember(mood.id) { mutableStateOf(mood.genres.joinToString(", ")) }
var query by remember(mood.id, mood.changedAt) { mutableStateOf(mood.query.orEmpty()) } var query by remember(mood.id) { mutableStateOf(mood.query.orEmpty()) }
var target by remember(mood.id, mood.changedAt) { mutableStateOf(mood.targetSize.toString()) } var target by remember(mood.id) { mutableStateOf(mood.targetSize.toString()) }
var hours by remember(mood.id, mood.changedAt) { mutableStateOf(mood.refreshHours.toString()) } var hours by remember(mood.id) { mutableStateOf(mood.refreshHours.toString()) }
var yt by remember(mood.id, mood.changedAt) { mutableStateOf(mood.ytEnabled) } var yt by remember(mood.id) { mutableStateOf(mood.ytEnabled) }
var seedPercent by remember(mood.id, mood.changedAt) { mutableStateOf(mood.seedPercent.toFloat()) } var seedPercent by remember(mood.id) { mutableStateOf(mood.seedPercent.toFloat()) }
val pendingDownloads = detail.recommendations.count { val pendingDownloads = detail.recommendations.count {
it.download?.state == "queued" || it.download?.state == "downloading" it.download?.state == "queued" || it.download?.state == "downloading"
} }
LaunchedEffect(detail.mood.id, pendingDownloads) { LaunchedEffect(detail.mood.id, pendingDownloads) {
while (pendingDownloads > 0) { var polls = 0
while (pendingDownloads > 0 && polls < 60) {
kotlinx.coroutines.delay(10_000) kotlinx.coroutines.delay(10_000)
store.refreshSelectedMood() store.refreshSelectedMood()
polls += 1
} }
} }
@@ -7,6 +7,7 @@ import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.width
@@ -56,10 +57,12 @@ fun PlayerBar(state: AppState, store: AppStore) {
var queueOpen by remember { mutableStateOf(false) } var queueOpen by remember { mutableStateOf(false) }
var dragSeconds by remember(song.id) { mutableStateOf<Float?>(null) } var dragSeconds by remember(song.id) { mutableStateOf<Float?>(null) }
val sleepRemaining = state.sleepTimerRemainingSeconds val sleepRemaining = state.sleepTimerRemainingSeconds
val isLongform = state.user?.longformFolders?.contains(song.folderId) == true
Surface( Surface(
color = MaterialTheme.colorScheme.surfaceVariant, color = MaterialTheme.colorScheme.surfaceVariant,
tonalElevation = 8.dp, tonalElevation = 8.dp,
modifier = Modifier.navigationBarsPadding(),
) { ) {
Column(Modifier.fillMaxWidth()) { Column(Modifier.fillMaxWidth()) {
val progress = if (state.durationSeconds > 0) { val progress = if (state.durationSeconds > 0) {
@@ -164,11 +167,13 @@ fun PlayerBar(state: AppState, store: AppStore) {
) )
} }
IconButton(onClick = { store.addCurrentToMood(null) }) { if (!isLongform) {
Icon(Icons.Rounded.AddCircleOutline, contentDescription = "Add to current mood") 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 = { picker = true }) {
Icon(Icons.Rounded.PlaylistAdd, contentDescription = "Add to another mood")
}
} }
IconButton(onClick = { store.previous() }) { IconButton(onClick = { store.previous() }) {
Icon(Icons.Rounded.SkipPrevious, contentDescription = "Previous") Icon(Icons.Rounded.SkipPrevious, contentDescription = "Previous")
@@ -6,6 +6,7 @@ import io.ktor.client.engine.mock.respondError
import io.ktor.http.HttpHeaders import io.ktor.http.HttpHeaders
import io.ktor.http.HttpStatusCode import io.ktor.http.HttpStatusCode
import io.ktor.http.headersOf import io.ktor.http.headersOf
import io.ktor.utils.io.readAvailable
import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json import kotlinx.serialization.json.Json
import kotlin.test.Test import kotlin.test.Test
@@ -73,6 +74,47 @@ class ApiClientTest {
assertEquals("unauthorized", error.code) 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 @Test
fun `cache round-trips songs and moods`() = runTest { fun `cache round-trips songs and moods`() = runTest {
val storage = MemoryStorage() val storage = MemoryStorage()
@@ -244,6 +244,194 @@ class AppStoreTest {
store.release() 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 @Test
fun `previous restarts after two seconds and restores the last track before it`() = runTest { fun `previous restarts after two seconds and restores the last track before it`() = runTest {
val storage = MemoryStorage() val storage = MemoryStorage()
@@ -427,13 +615,18 @@ class AppStoreTest {
cache = cache, 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, id = id,
title = "Song $id", title = "Song $id",
artist = artist, artist = artist,
album = "Album", album = "Album",
albumId = "al-1", albumId = "al-1",
duration = 180, duration = duration,
bitRate = 320, bitRate = 320,
size = 1_000, size = 1_000,
suffix = "mp3", suffix = "mp3",
@@ -448,7 +641,12 @@ class AppStoreTest {
var paused = false var paused = false
private set private set
private var playing = false private var playing = false
private var position = 0.0 var position = 0.0
private var finished = false
fun finish() {
finished = true
}
override fun play( override fun play(
source: String, source: String,
@@ -461,6 +659,7 @@ class AppStoreTest {
playing = true playing = true
paused = false paused = false
position = 0.0 position = 0.0
finished = false
} }
override fun pause() { override fun pause() {
@@ -478,7 +677,7 @@ class AppStoreTest {
} }
override fun isPlaying(): Boolean = playing override fun isPlaying(): Boolean = playing
override fun isFinished(): Boolean = false override fun isFinished(): Boolean = finished
override fun positionSeconds(): Double = position override fun positionSeconds(): Double = position
override fun durationSeconds(): Double = 0.0 override fun durationSeconds(): Double = 0.0
override val canSeek: Boolean = true override val canSeek: Boolean = true
@@ -76,7 +76,14 @@ class DesktopAudioPlayer : AudioPlayer {
} else { } else {
source 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) val buffered = BufferedInputStream(raw, 128 * 1024)
input = buffered input = buffered
val encoded = AudioSystem.getAudioInputStream(buffered) val encoded = AudioSystem.getAudioInputStream(buffered)
@@ -4,6 +4,7 @@ import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.toComposeImageBitmap import androidx.compose.ui.graphics.toComposeImageBitmap
import io.ktor.client.engine.HttpClientEngine import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.engine.cio.CIO import io.ktor.client.engine.cio.CIO
import io.ktor.utils.io.readAvailable
import java.io.File import java.io.File
import win.taptap.musicmanager.client.data.AppStorage import win.taptap.musicmanager.client.data.AppStorage
import win.taptap.musicmanager.client.playback.AudioPlayer import win.taptap.musicmanager.client.playback.AudioPlayer
@@ -32,7 +33,7 @@ class DesktopStorage : AppStorage {
override fun write(name: String, text: String) { override fun write(name: String, text: String) {
root.mkdirs() root.mkdirs()
File(root, name).writeText(text) atomicWrite(File(root, name)) { it.writeText(text) }
} }
override fun delete(name: String) { override fun delete(name: String) {
@@ -42,10 +43,39 @@ class DesktopStorage : AppStorage {
override fun saveDownload(songId: String, bytes: ByteArray): String? { override fun saveDownload(songId: String, bytes: ByteArray): String? {
downloads.mkdirs() downloads.mkdirs()
val file = File(downloads, "${safeName(songId)}.mp3") val file = File(downloads, "${safeName(songId)}.mp3")
file.writeBytes(bytes) atomicWrite(file) { it.writeBytes(bytes) }
return file.absolutePath 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? = override fun downloadPath(songId: String): String? =
File(downloads, "${safeName(songId)}.mp3").takeIf { it.isFile }?.absolutePath File(downloads, "${safeName(songId)}.mp3").takeIf { it.isFile }?.absolutePath
@@ -53,7 +83,7 @@ class DesktopStorage : AppStorage {
if (bytes.isEmpty()) return null if (bytes.isEmpty()) return null
downloads.mkdirs() downloads.mkdirs()
val file = File(downloads, "${safeName(songId)}.jpg") val file = File(downloads, "${safeName(songId)}.jpg")
file.writeBytes(bytes) atomicWrite(file) { it.writeBytes(bytes) }
return file.absolutePath return file.absolutePath
} }
@@ -74,6 +104,20 @@ class DesktopStorage : AppStorage {
override fun storageUsedBytes(): Long = override fun storageUsedBytes(): Long =
downloads.listFiles()?.sumOf { it.length() } ?: 0L 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 = private fun safeName(songId: String): String =
songId.map { if (it.isLetterOrDigit() || it == '-' || it == '_') it else '_' }.joinToString("") songId.map { if (it.isLetterOrDigit() || it == '-' || it == '_') it else '_' }.joinToString("")
} }
@@ -29,6 +29,10 @@ class WebStorage : AppStorage {
override fun saveDownload(songId: String, bytes: ByteArray): String? = null override fun saveDownload(songId: String, bytes: ByteArray): String? = null
override fun downloadPath(songId: String): 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 saveArtwork(songId: String, bytes: ByteArray): String? = null
override fun artworkBytes(songId: String): ByteArray? = null override fun artworkBytes(songId: String): ByteArray? = null
override fun listDownloads(): Map<String, Long> = emptyMap() override fun listDownloads(): Map<String, Long> = emptyMap()