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

@@ -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()
@@ -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