feat: move the client to searchable, downloadable moods
- new mood/song/search/recommendation models and API calls - AppCache v2 with moods and details only - Search and Downloads screens; remove Library and Longform - new mood detail with songs, add music and recommendation states - song-keyed covers and updated tests/docs
This commit is contained in:
1 parent
1bb23901eb
commit
dc270f863c
18 files changed
+1466
-1929
No files matched your search
@@ -8,17 +8,17 @@ 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
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFailsWith
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.test.assertTrue
|
||||
import win.taptap.musicmanager.client.api.ApiClient
|
||||
import win.taptap.musicmanager.client.api.ApiException
|
||||
import win.taptap.musicmanager.client.api.Mood
|
||||
import win.taptap.musicmanager.client.api.configuredHttpClient
|
||||
import win.taptap.musicmanager.client.data.AppStorage
|
||||
import win.taptap.musicmanager.client.data.AppCache
|
||||
import win.taptap.musicmanager.client.data.CachedState
|
||||
import win.taptap.musicmanager.client.data.LibraryCache
|
||||
|
||||
class ApiClientTest {
|
||||
|
||||
@@ -31,15 +31,16 @@ class ApiClientTest {
|
||||
"/api/v1/auth/login" -> respond(
|
||||
"""
|
||||
{"token":"abc123","expiresAt":"2027-01-01T00:00:00Z",
|
||||
"user":{"name":"alice","admin":true,"musicFolders":[1],"longformFolders":[10]}}
|
||||
"user":{"name":"alice","admin":true}}
|
||||
""".trimIndent(),
|
||||
HttpStatusCode.OK,
|
||||
jsonHeaders,
|
||||
)
|
||||
"/api/v1/moods" -> respond(
|
||||
"""
|
||||
{"moods":[{"id":"mo-1","name":"Focus","targetSize":30,"refreshHours":24,
|
||||
"ytEnabled":true,"createdAt":"now","changedAt":"now","seedCount":2}]}
|
||||
{"moods":[{"id":"mo-1","name":"Focus","collectionPercent":60,
|
||||
"recommendationPercent":40,"recommendationCount":10,"refreshHours":24,
|
||||
"createdAt":"now","changedAt":"now","songCount":2,"recommendationReady":3}]}
|
||||
""".trimIndent(),
|
||||
HttpStatusCode.OK,
|
||||
jsonHeaders,
|
||||
@@ -56,7 +57,86 @@ class ApiClientTest {
|
||||
val moods = client.moods()
|
||||
assertEquals(1, moods.size)
|
||||
assertEquals("Focus", moods.first().name)
|
||||
assertEquals(2, moods.first().seedCount)
|
||||
assertEquals(2, moods.first().songCount)
|
||||
assertEquals(3, moods.first().recommendationReady)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `search returns badges and adding a video queues a download`() = runTest {
|
||||
val engine = MockEngine { request ->
|
||||
when (request.url.encodedPath) {
|
||||
"/api/v1/search" -> respond(
|
||||
"""
|
||||
{"results":[
|
||||
{"videoId":"v1","title":"Fresh","artist":"Artist","duration":180,
|
||||
"downloaded":false},
|
||||
{"videoId":"v2","title":"Old","artist":"Artist","duration":200,
|
||||
"songId":"sg-2","downloaded":true}
|
||||
]}
|
||||
""".trimIndent(),
|
||||
HttpStatusCode.OK,
|
||||
jsonHeaders,
|
||||
)
|
||||
"/api/v1/moods/mo-1/songs" -> respond(
|
||||
"""
|
||||
{"detail":{"mood":{"id":"mo-1","name":"Focus","createdAt":"now",
|
||||
"changedAt":"now","songCount":1},"songs":[],"recommendations":[]},
|
||||
"added":false,"downloading":true}
|
||||
""".trimIndent(),
|
||||
HttpStatusCode.Accepted,
|
||||
jsonHeaders,
|
||||
)
|
||||
else -> respondError(HttpStatusCode.NotFound)
|
||||
}
|
||||
}
|
||||
|
||||
val client = ApiClient(configuredHttpClient(engine))
|
||||
client.restore("http://music", "token")
|
||||
|
||||
val results = client.search("fresh")
|
||||
assertEquals(2, results.size)
|
||||
assertNull(results[0].songId)
|
||||
assertEquals("sg-2", results[1].songId)
|
||||
assertTrue(results[1].downloaded)
|
||||
|
||||
val added = client.addSong("mo-1", videoId = "v1")
|
||||
assertTrue(added.downloading)
|
||||
assertEquals(1, added.detail.mood.songCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `adding and rejecting recommendations parse the decision`() = runTest {
|
||||
val engine = MockEngine { request ->
|
||||
when (request.url.encodedPath) {
|
||||
"/api/v1/moods/mo-1/recommendations/v1/add" -> respond(
|
||||
"""
|
||||
{"detail":{"mood":{"id":"mo-1","name":"Focus","createdAt":"now",
|
||||
"changedAt":"now","songCount":2},"songs":[],"recommendations":[]},
|
||||
"recommendation":{"videoId":"v1","title":"Pick","artist":"Artist",
|
||||
"state":"added"}}
|
||||
""".trimIndent(),
|
||||
HttpStatusCode.OK,
|
||||
jsonHeaders,
|
||||
)
|
||||
"/api/v1/moods/mo-1/recommendations/v2/reject" -> respond(
|
||||
"""
|
||||
{"detail":{"mood":{"id":"mo-1","name":"Focus","createdAt":"now",
|
||||
"changedAt":"now","songCount":2},"songs":[],"recommendations":[]},
|
||||
"recommendation":{"videoId":"v2","title":"Other","artist":"Artist",
|
||||
"state":"rejected"}}
|
||||
""".trimIndent(),
|
||||
HttpStatusCode.OK,
|
||||
jsonHeaders,
|
||||
)
|
||||
else -> respondError(HttpStatusCode.NotFound)
|
||||
}
|
||||
}
|
||||
|
||||
val client = ApiClient(configuredHttpClient(engine))
|
||||
client.restore("http://music", "token")
|
||||
|
||||
assertEquals("added", client.addRecommendation("mo-1", "v1").recommendation.state)
|
||||
assertEquals("rejected", client.rejectRecommendation("mo-1", "v2").recommendation.state)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -116,23 +196,33 @@ class ApiClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `cache round-trips songs and moods`() = runTest {
|
||||
fun `cache round-trips moods and discards the old cache version`() = runTest {
|
||||
val storage = MemoryStorage()
|
||||
val cache = LibraryCache(storage)
|
||||
val cache = AppCache(storage)
|
||||
assertNull(cache.loadSession())
|
||||
|
||||
val mood = Mood(
|
||||
id = "mo-1",
|
||||
name = "Focus",
|
||||
createdAt = "now",
|
||||
changedAt = "now",
|
||||
songCount = 2,
|
||||
)
|
||||
cache.save(
|
||||
CachedState(
|
||||
serverUrl = "http://localhost:8080",
|
||||
userName = "alice",
|
||||
revision = "2026-11-14T00:00:00Z",
|
||||
songs = emptyList(),
|
||||
moods = emptyList(),
|
||||
moods = listOf(mood),
|
||||
),
|
||||
)
|
||||
|
||||
val loaded = cache.load()
|
||||
assertEquals("2026-11-14T00:00:00Z", loaded.revision)
|
||||
assertEquals(listOf("mo-1"), loaded.moods.map { it.id })
|
||||
assertEquals("alice", loaded.userName)
|
||||
|
||||
storage.write("mood-cache.json", """{"version":1,"songs":[{"id":"old"}]}""")
|
||||
val invalidated = cache.load()
|
||||
assertTrue(invalidated.moods.isEmpty())
|
||||
assertEquals(2, invalidated.version)
|
||||
}
|
||||
}
|
||||
@@ -10,10 +10,10 @@ import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.test.TestScope
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.test.advanceTimeBy
|
||||
import kotlinx.coroutines.test.runCurrent
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFalse
|
||||
@@ -24,8 +24,8 @@ import win.taptap.musicmanager.client.api.ApiClient
|
||||
import win.taptap.musicmanager.client.api.Song
|
||||
import win.taptap.musicmanager.client.api.User
|
||||
import win.taptap.musicmanager.client.api.configuredHttpClient
|
||||
import win.taptap.musicmanager.client.data.AppCache
|
||||
import win.taptap.musicmanager.client.data.CachedState
|
||||
import win.taptap.musicmanager.client.data.LibraryCache
|
||||
import win.taptap.musicmanager.client.data.PlaybackSnapshot
|
||||
import win.taptap.musicmanager.client.data.SessionState
|
||||
import win.taptap.musicmanager.client.playback.AudioPlayer
|
||||
@@ -35,48 +35,155 @@ import win.taptap.musicmanager.client.store.AppStore
|
||||
class AppStoreTest {
|
||||
|
||||
@Test
|
||||
fun `play all queues the whole library and starts playback`() = runTest {
|
||||
fun `playing a mood starts the server session and the first track`() = runTest {
|
||||
val storage = MemoryStorage()
|
||||
val cache = LibraryCache(storage)
|
||||
val songs = listOf(song("a"), song("b"), song("c"))
|
||||
cache.save(CachedState(serverUrl = "http://music", songs = songs))
|
||||
val cache = AppCache(storage)
|
||||
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
|
||||
val player = FakePlayer()
|
||||
val store = store(storage, cache, player)
|
||||
val engine = MockEngine { request ->
|
||||
when (request.url.encodedPath) {
|
||||
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods" -> respond("""{"moods":[${moodJson(1)}]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods/mo-1" -> respond(detailJson(listOf("a")), HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods/mo-1/sessions" -> respond(
|
||||
"""{"id":"s1","moodId":"mo-1","moodName":"Focus","startedAt":"now",
|
||||
"queue":[${songJson("a")}]}""",
|
||||
HttpStatusCode.Created,
|
||||
jsonHeaders,
|
||||
)
|
||||
else -> respondError(HttpStatusCode.NotFound)
|
||||
}
|
||||
}
|
||||
val store = store(storage, cache, player, engine)
|
||||
runCurrent()
|
||||
store.openMood("mo-1")
|
||||
awaitState { store.state.value.selectedMood != null }
|
||||
|
||||
store.playAll()
|
||||
runCurrent()
|
||||
store.playMood("mo-1")
|
||||
awaitState { store.state.value.current != null }
|
||||
|
||||
val state = store.state.value
|
||||
val current = assertNotNull(state.current)
|
||||
assertEquals("a", state.current?.id)
|
||||
assertEquals("s1", state.session?.id)
|
||||
assertTrue(state.playing)
|
||||
assertEquals(listOf(current.id), player.played)
|
||||
assertEquals(2, state.queue.size)
|
||||
assertEquals(songs.map { it.id }.toSet(), (state.queue + current).map { it.id }.toSet())
|
||||
assertEquals(listOf("a"), player.played)
|
||||
store.release()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `play all reports an empty library instead of starting playback`() = runTest {
|
||||
fun `an empty mood is rejected before any request`() = runTest {
|
||||
val storage = MemoryStorage()
|
||||
val cache = LibraryCache(storage)
|
||||
val cache = AppCache(storage)
|
||||
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
|
||||
val player = FakePlayer()
|
||||
val store = store(storage, cache, player)
|
||||
val engine = MockEngine { request ->
|
||||
when (request.url.encodedPath) {
|
||||
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods" -> respond("""{"moods":[${moodJson(0)}]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods/mo-1" -> respond(detailJson(emptyList()), HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
else -> respondError(HttpStatusCode.NotFound)
|
||||
}
|
||||
}
|
||||
val store = store(storage, cache, player, engine)
|
||||
runCurrent()
|
||||
store.openMood("mo-1")
|
||||
awaitState { store.state.value.selectedMood != null }
|
||||
|
||||
store.playAll()
|
||||
runCurrent()
|
||||
store.playMood("mo-1")
|
||||
awaitState { store.state.value.message != null }
|
||||
|
||||
assertNull(store.state.value.current)
|
||||
assertTrue(player.played.isEmpty())
|
||||
assertTrue(store.state.value.messageIsError)
|
||||
assertTrue(store.state.value.message!!.contains("at least one song"))
|
||||
store.release()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `search is debounced and adding a result targets the chosen mood`() = runTest {
|
||||
val storage = MemoryStorage()
|
||||
val cache = AppCache(storage)
|
||||
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
|
||||
val engine = MockEngine { request ->
|
||||
when (request.url.encodedPath) {
|
||||
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods" -> respond("""{"moods":[${moodJson(0)}]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/search" -> respond(
|
||||
"""{"results":[{"videoId":"v1","title":"Fresh","artist":"Artist",
|
||||
"duration":180,"downloaded":false}]}""",
|
||||
HttpStatusCode.OK,
|
||||
jsonHeaders,
|
||||
)
|
||||
"/api/v1/moods/mo-1/songs" -> respond(
|
||||
"""{"detail":${detailJson(emptyList())},"added":false,"downloading":true}""",
|
||||
HttpStatusCode.Accepted,
|
||||
jsonHeaders,
|
||||
)
|
||||
else -> respondError(HttpStatusCode.NotFound)
|
||||
}
|
||||
}
|
||||
val store = store(storage, cache, FakePlayer(), engine)
|
||||
runCurrent()
|
||||
awaitState { store.state.value.moods.isNotEmpty() }
|
||||
|
||||
store.openSearch("mo-1")
|
||||
store.setSearchQuery("fresh")
|
||||
advanceTimeBy(350)
|
||||
runCurrent()
|
||||
awaitState { store.state.value.searchResults.isNotEmpty() }
|
||||
assertEquals("v1", store.state.value.searchResults.single().videoId)
|
||||
|
||||
store.addSearchResult(store.state.value.searchResults.single())
|
||||
awaitState { store.state.value.message != null }
|
||||
assertEquals("Downloading for Focus", store.state.value.message)
|
||||
store.release()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `adding a recommendation refreshes the selected mood`() = runTest {
|
||||
val storage = MemoryStorage()
|
||||
val cache = AppCache(storage)
|
||||
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
|
||||
val engine = MockEngine { request ->
|
||||
when (request.url.encodedPath) {
|
||||
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods" -> respond("""{"moods":[${moodJson(1)}]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods/mo-1" -> respond(
|
||||
detailJson(listOf("a"), recommendationJson()),
|
||||
HttpStatusCode.OK,
|
||||
jsonHeaders,
|
||||
)
|
||||
"/api/v1/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods/mo-1/recommendations/v1/add" -> respond(
|
||||
"""{"detail":${detailJson(listOf("a"))},
|
||||
"recommendation":${recommendationJson(state = "added", songId = "a")}}""",
|
||||
HttpStatusCode.OK,
|
||||
jsonHeaders,
|
||||
)
|
||||
else -> respondError(HttpStatusCode.NotFound)
|
||||
}
|
||||
}
|
||||
val store = store(storage, cache, FakePlayer(), engine)
|
||||
runCurrent()
|
||||
store.openMood("mo-1")
|
||||
awaitState { store.state.value.selectedMood != null }
|
||||
|
||||
store.addRecommendation("v1")
|
||||
awaitState { store.state.value.message != null }
|
||||
|
||||
val detail = assertNotNull(store.state.value.selectedMood)
|
||||
assertTrue(detail.recommendations.isEmpty())
|
||||
assertEquals(1, detail.mood.songCount)
|
||||
assertEquals("Added to Focus", store.state.value.message)
|
||||
store.release()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `sleep timer pauses playback when it expires`() = runTest {
|
||||
val storage = MemoryStorage()
|
||||
val cache = LibraryCache(storage)
|
||||
val cache = AppCache(storage)
|
||||
val player = FakePlayer()
|
||||
val store = store(storage, cache, player)
|
||||
runCurrent()
|
||||
@@ -91,54 +198,30 @@ class AppStoreTest {
|
||||
advanceTimeBy(60_000)
|
||||
runCurrent()
|
||||
|
||||
val state = store.state.value
|
||||
assertFalse(state.playing)
|
||||
assertNull(state.sleepTimerRemainingSeconds)
|
||||
assertFalse(store.state.value.playing)
|
||||
assertNull(store.state.value.sleepTimerRemainingSeconds)
|
||||
assertTrue(player.paused)
|
||||
store.release()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `turning the sleep timer off keeps playback running`() = runTest {
|
||||
fun `bootstrap restores the saved queue and resumes on play`() = runTest {
|
||||
val storage = MemoryStorage()
|
||||
val cache = LibraryCache(storage)
|
||||
val player = FakePlayer()
|
||||
val store = store(storage, cache, player)
|
||||
runCurrent()
|
||||
|
||||
store.playSong(song("a"))
|
||||
runCurrent()
|
||||
|
||||
store.setSleepTimer(30)
|
||||
assertEquals(1_800L, store.state.value.sleepTimerRemainingSeconds)
|
||||
store.setSleepTimer(null)
|
||||
assertNull(store.state.value.sleepTimerRemainingSeconds)
|
||||
|
||||
advanceTimeBy(120_000)
|
||||
runCurrent()
|
||||
assertTrue(store.state.value.playing)
|
||||
store.release()
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
fun `bootstrap restores the saved queue and starts it on play`() = runTest {
|
||||
val storage = MemoryStorage()
|
||||
val cache = LibraryCache(storage)
|
||||
val cache = AppCache(storage)
|
||||
cache.savePlayback(
|
||||
PlaybackSnapshot(
|
||||
queue = listOf(song("b")),
|
||||
current = song("a"),
|
||||
positionSeconds = 12.0,
|
||||
),
|
||||
)
|
||||
val player = FakePlayer()
|
||||
val store = store(storage, cache, player)
|
||||
runCurrent()
|
||||
|
||||
val restored = store.state.value
|
||||
assertEquals("a", restored.current?.id)
|
||||
assertEquals(listOf("b"), restored.queue.map { it.id })
|
||||
assertFalse(restored.playing)
|
||||
assertEquals("a", store.state.value.current?.id)
|
||||
assertEquals(listOf("b"), store.state.value.queue.map { it.id })
|
||||
assertEquals(12.0, store.state.value.positionSeconds)
|
||||
assertTrue(player.played.isEmpty())
|
||||
|
||||
store.togglePlayPause()
|
||||
@@ -146,93 +229,41 @@ class AppStoreTest {
|
||||
|
||||
assertTrue(store.state.value.playing)
|
||||
assertEquals(listOf("a"), player.played)
|
||||
assertEquals(12.0, player.seeks.last())
|
||||
store.release()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `accepting a recommendation replaces the selected mood`() = runTest {
|
||||
fun `queue reordering and removal persist in the snapshot`() = runTest {
|
||||
val storage = MemoryStorage()
|
||||
val cache = LibraryCache(storage)
|
||||
cache.saveSession(
|
||||
SessionState("http://music", "token", User("alice", admin = false)),
|
||||
)
|
||||
val player = FakePlayer()
|
||||
val detail = moodDetailJson(state = "new", seedCount = 1)
|
||||
val acceptedDetail = moodDetailJson(state = "accepted", seedCount = 2)
|
||||
val cache = AppCache(storage)
|
||||
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
|
||||
val engine = MockEngine { request ->
|
||||
when (request.url.encodedPath) {
|
||||
"/api/v1/moods" -> respond("""{"moods":[]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/library/songs" -> respond(
|
||||
"""{"songs":[],"revision":"r1"}""",
|
||||
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods" -> respond("""{"moods":[${moodJson(3)}]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods/mo-1" -> respond(
|
||||
detailJson(listOf("a", "b", "c")),
|
||||
HttpStatusCode.OK,
|
||||
jsonHeaders,
|
||||
)
|
||||
"/api/v1/moods/mo-1" -> respond(detail, HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods/mo-1/preview" -> respond(
|
||||
"""{"songs":[]}""",
|
||||
HttpStatusCode.OK,
|
||||
jsonHeaders,
|
||||
)
|
||||
"/api/v1/moods/mo-1/recommendations/v-1/accept" -> respond(
|
||||
"""{"detail":$acceptedDetail,"recommendation":${recommendationJson("accepted")},"seedAdded":true}""",
|
||||
HttpStatusCode.OK,
|
||||
jsonHeaders,
|
||||
)
|
||||
"/api/v1/moods/mo-1/recommendations/v-1/reject" -> respond(
|
||||
"""{"detail":$detail,"recommendation":${recommendationJson("rejected")},"seedAdded":false}""",
|
||||
HttpStatusCode.OK,
|
||||
"/api/v1/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods/mo-1/sessions" -> respond(
|
||||
"""{"id":"s1","moodId":"mo-1","moodName":"Focus","startedAt":"now",
|
||||
"queue":[${songJson("a")},${songJson("b")},${songJson("c")}]}""",
|
||||
HttpStatusCode.Created,
|
||||
jsonHeaders,
|
||||
)
|
||||
else -> respondError(HttpStatusCode.NotFound)
|
||||
}
|
||||
}
|
||||
val store = AppStore(
|
||||
scope = this,
|
||||
api = ApiClient(configuredHttpClient(engine)),
|
||||
storage = storage,
|
||||
player = player,
|
||||
cache = cache,
|
||||
)
|
||||
val store = store(storage, cache, FakePlayer(), engine)
|
||||
runCurrent()
|
||||
store.openMood("mo-1")
|
||||
awaitState { store.state.value.selectedMood != null || store.state.value.message != null }
|
||||
awaitState { store.state.value.selectedMood != null }
|
||||
|
||||
assertEquals(
|
||||
"new",
|
||||
store.state.value.selectedMood?.recommendations?.single()?.state,
|
||||
"message=" + store.state.value.message,
|
||||
)
|
||||
|
||||
store.acceptRecommendation("v-1")
|
||||
awaitState {
|
||||
store.state.value.selectedMood?.recommendations?.single()?.state == "accepted"
|
||||
}
|
||||
|
||||
val state = store.state.value
|
||||
assertEquals("accepted", state.selectedMood?.recommendations?.single()?.state)
|
||||
assertEquals(2, state.selectedMood?.mood?.seedCount)
|
||||
assertEquals("Added to Focus", state.message)
|
||||
assertFalse(state.messageIsError)
|
||||
store.release()
|
||||
}
|
||||
|
||||
/**
|
||||
* Ktor's mock engine responds on a real dispatcher, so queued test work has
|
||||
* to be run between short real waits.
|
||||
*/
|
||||
|
||||
@Test
|
||||
fun `queue reordering and removal persist`() = runTest {
|
||||
val storage = MemoryStorage()
|
||||
val cache = LibraryCache(storage)
|
||||
cache.save(CachedState(serverUrl = "http://music", songs = listOf(song("a"), song("b"), song("c"))))
|
||||
val player = FakePlayer()
|
||||
val store = store(storage, cache, player)
|
||||
runCurrent()
|
||||
|
||||
store.playAll(shuffled = false)
|
||||
runCurrent()
|
||||
assertEquals("a", store.state.value.current?.id)
|
||||
store.playMood("mo-1")
|
||||
awaitState { store.state.value.current?.id == "a" }
|
||||
assertEquals(listOf("b", "c"), store.state.value.queue.map { it.id })
|
||||
|
||||
store.moveInQueue(1, 0)
|
||||
@@ -245,333 +276,34 @@ class AppStoreTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `restored playback resumes from the saved position`() = runTest {
|
||||
fun `logout clears the session and the mood cache`() = 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)
|
||||
val cache = AppCache(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",
|
||||
),
|
||||
cache.save(
|
||||
CachedState(
|
||||
serverUrl = "http://music",
|
||||
userName = "alice",
|
||||
moods = emptyList(),
|
||||
),
|
||||
)
|
||||
val store = store(storage, cache, FakePlayer())
|
||||
val engine = MockEngine { request ->
|
||||
when (request.url.encodedPath) {
|
||||
"/api/v1/auth/logout" -> respond("", HttpStatusCode.NoContent)
|
||||
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods" -> respond("""{"moods":[]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
else -> respondError(HttpStatusCode.NotFound)
|
||||
}
|
||||
}
|
||||
val store = store(storage, cache, FakePlayer(), engine)
|
||||
runCurrent()
|
||||
awaitState { store.state.value.authenticated }
|
||||
|
||||
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()
|
||||
val cache = LibraryCache(storage)
|
||||
cache.save(CachedState(serverUrl = "http://music", songs = listOf(song("a"), song("b"), song("c"))))
|
||||
val player = FakePlayer()
|
||||
val store = store(storage, cache, player)
|
||||
runCurrent()
|
||||
|
||||
store.playAll(shuffled = false)
|
||||
runCurrent()
|
||||
store.skip()
|
||||
runCurrent()
|
||||
assertEquals("b", store.state.value.current?.id)
|
||||
assertEquals(listOf("a"), store.state.value.history.map { it.id })
|
||||
|
||||
store.seekTo(5.0)
|
||||
store.previous()
|
||||
assertEquals("b", store.state.value.current?.id)
|
||||
assertEquals(0.0, store.state.value.positionSeconds)
|
||||
assertEquals(0.0, player.seeks.last())
|
||||
|
||||
store.previous()
|
||||
runCurrent()
|
||||
assertEquals("a", store.state.value.current?.id)
|
||||
assertEquals(listOf("b", "c"), store.state.value.queue.map { it.id })
|
||||
assertTrue(store.state.value.history.isEmpty())
|
||||
assertEquals("a", player.played.last())
|
||||
assertTrue(cache.loadPlayback()?.history?.isEmpty() == true)
|
||||
store.release()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `delta refresh keeps cached longform songs`() = 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",
|
||||
revision = "r1",
|
||||
songs = listOf(song("m1")),
|
||||
longform = listOf(song("l1", artist = "Die drei ???", folderId = 10)),
|
||||
),
|
||||
)
|
||||
val engine = MockEngine { request ->
|
||||
when (request.url.encodedPath) {
|
||||
"/api/v1/moods" -> respond("""{"moods":[]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/library/songs" -> respond(
|
||||
"""{"songs":[],"revision":"r2"}""",
|
||||
HttpStatusCode.OK,
|
||||
jsonHeaders,
|
||||
)
|
||||
"/api/v1/longform/progress" -> respond(
|
||||
"""{"items":[]}""",
|
||||
HttpStatusCode.OK,
|
||||
jsonHeaders,
|
||||
)
|
||||
else -> respondError(HttpStatusCode.NotFound)
|
||||
}
|
||||
}
|
||||
val store = AppStore(
|
||||
scope = this,
|
||||
api = ApiClient(configuredHttpClient(engine)),
|
||||
storage = storage,
|
||||
player = FakePlayer(),
|
||||
cache = cache,
|
||||
)
|
||||
runCurrent()
|
||||
awaitState { cache.load()?.revision == "r2" }
|
||||
|
||||
assertEquals(listOf("m1"), store.state.value.library.map { it.id })
|
||||
assertEquals(listOf("l1"), store.state.value.longform.map { it.id })
|
||||
store.release()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `playing an artist queues only that longform artist`() = runTest {
|
||||
val storage = MemoryStorage()
|
||||
val cache = LibraryCache(storage)
|
||||
cache.save(
|
||||
CachedState(
|
||||
serverUrl = "http://music",
|
||||
longform = listOf(
|
||||
song("l1", artist = "Die drei ???", folderId = 10),
|
||||
song("l2", artist = "Die drei ???", folderId = 10),
|
||||
song("l3", artist = "Other", folderId = 10),
|
||||
),
|
||||
),
|
||||
)
|
||||
val player = FakePlayer()
|
||||
val store = store(storage, cache, player)
|
||||
runCurrent()
|
||||
|
||||
store.playLongformArtist("Die drei ???", shuffled = false)
|
||||
runCurrent()
|
||||
|
||||
val state = store.state.value
|
||||
assertEquals(setOf("l1", "l2"), (state.queue + listOfNotNull(state.current)).map { it.id }.toSet())
|
||||
assertTrue(player.played.single() in setOf("l1", "l2"))
|
||||
store.release()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `resuming a longform track starts it`() = runTest {
|
||||
val storage = MemoryStorage()
|
||||
val cache = LibraryCache(storage)
|
||||
cache.save(
|
||||
CachedState(
|
||||
serverUrl = "http://music",
|
||||
longform = listOf(song("l1", artist = "Die drei ???", folderId = 10)),
|
||||
),
|
||||
)
|
||||
cache.saveProgress(
|
||||
listOf(
|
||||
win.taptap.musicmanager.client.api.LongformProgress(
|
||||
songId = "l1",
|
||||
positionSeconds = 30,
|
||||
durationSeconds = 180,
|
||||
completed = false,
|
||||
updatedAt = "2026-01-01T00:00:00Z",
|
||||
),
|
||||
),
|
||||
)
|
||||
val player = FakePlayer()
|
||||
val store = store(storage, cache, player)
|
||||
runCurrent()
|
||||
|
||||
store.resumeLongform("l1")
|
||||
runCurrent()
|
||||
|
||||
assertEquals("l1", store.state.value.current?.id)
|
||||
assertEquals(listOf("l1"), player.played)
|
||||
assertEquals(30, store.state.value.longformProgress["l1"]?.positionSeconds)
|
||||
assertNull(cache.loadSession())
|
||||
assertTrue(cache.load().moods.isEmpty())
|
||||
store.release()
|
||||
}
|
||||
|
||||
@@ -586,56 +318,53 @@ class AppStoreTest {
|
||||
|
||||
private val jsonHeaders = headersOf(HttpHeaders.ContentType, "application/json")
|
||||
|
||||
private fun moodJson(seedCount: Int) = """
|
||||
{"id":"mo-1","name":"Focus","targetSize":30,"refreshHours":24,"ytEnabled":true,
|
||||
"createdAt":"2026-01-01T00:00:00Z","changedAt":"2026-01-01T00:00:00Z",
|
||||
"seedCount":$seedCount,"newRecommendations":1}
|
||||
private fun songJson(id: String) = """
|
||||
{"id":"$id","videoId":"video-$id","title":"Song $id","artist":"Artist",
|
||||
"album":"Album","duration":180,"bitRate":320,"size":1000,"suffix":"mp3"}
|
||||
""".trimIndent()
|
||||
|
||||
private fun recommendationJson(state: String) = """
|
||||
{"videoId":"v-1","title":"Soft Light","artist":"Beta","duration":180,
|
||||
"state":"$state","timesAdded":0,
|
||||
"firstSeen":"2026-01-01T00:00:00Z","lastSeen":"2026-01-01T00:00:00Z",
|
||||
"matchedSong":${song("a").let { """{"id":"${it.id}","title":"${it.title}","artist":"${it.artist}","album":"${it.album}","albumId":"${it.albumId}","duration":${it.duration},"bitRate":${it.bitRate},"size":${it.size},"suffix":"${it.suffix}","folderId":${it.folderId},"relativePath":"${it.relativePath}","updatedAt":"${it.updatedAt}"}""" }}}
|
||||
private fun moodJson(songCount: Int) = """
|
||||
{"id":"mo-1","name":"Focus","collectionPercent":50,"recommendationPercent":50,
|
||||
"recommendationCount":10,"refreshHours":24,"createdAt":"2026-01-01T00:00:00Z",
|
||||
"changedAt":"2026-01-01T00:00:00Z","songCount":$songCount}
|
||||
""".trimIndent()
|
||||
|
||||
private fun moodDetailJson(state: String, seedCount: Int) = """
|
||||
{"mood":${moodJson(seedCount)},"seeds":[],"recommendations":[${recommendationJson(state)}]}
|
||||
private fun recommendationJson(state: String = "new", songId: String? = null) = """
|
||||
{"videoId":"v1","title":"Pick","artist":"Artist","duration":180,"state":"$state",
|
||||
${songId?.let { "\"song\":${songJson(it)}," } ?: ""}
|
||||
"firstSeen":"2026-01-01T00:00:00Z","lastSeen":"2026-01-01T00:00:00Z"}
|
||||
""".trimIndent()
|
||||
|
||||
private fun kotlinx.coroutines.test.TestScope.store(
|
||||
storage: MemoryStorage,
|
||||
cache: LibraryCache,
|
||||
player: AudioPlayer,
|
||||
): AppStore = AppStore(
|
||||
// Background scope so leftover store jobs (reconnect loops, refreshes)
|
||||
// are cancelled by runTest instead of failing the next test with
|
||||
// UncompletedCoroutinesError.
|
||||
scope = backgroundScope,
|
||||
api = ApiClient(configuredHttpClient(MockEngine { respondError(HttpStatusCode.NotFound) })),
|
||||
storage = storage,
|
||||
player = player,
|
||||
cache = cache,
|
||||
)
|
||||
private fun detailJson(songs: List<String>, recommendation: String? = null) = """
|
||||
{"mood":${moodJson(songs.size)},
|
||||
"songs":[${songs.joinToString(",") { """{"song":${songJson(it)},"origin":"search","addedAt":"now"}""" }}],
|
||||
"recommendations":${recommendation?.let { "[$it]" } ?: "[]"}}
|
||||
""".trimIndent()
|
||||
|
||||
private fun song(
|
||||
id: String,
|
||||
artist: String = "Artist",
|
||||
folderId: Int = 1,
|
||||
duration: Int = 180,
|
||||
) = Song(
|
||||
private fun song(id: String, duration: Int = 180) = Song(
|
||||
id = id,
|
||||
videoId = "video-$id",
|
||||
title = "Song $id",
|
||||
artist = artist,
|
||||
artist = "Artist",
|
||||
album = "Album",
|
||||
albumId = "al-1",
|
||||
duration = duration,
|
||||
bitRate = 320,
|
||||
size = 1_000,
|
||||
suffix = "mp3",
|
||||
folderId = folderId,
|
||||
relativePath = "$id.mp3",
|
||||
updatedAt = "2026-01-01T00:00:00Z",
|
||||
)
|
||||
|
||||
private fun TestScope.store(
|
||||
storage: MemoryStorage,
|
||||
cache: AppCache,
|
||||
player: AudioPlayer,
|
||||
engine: MockEngine = MockEngine { respondError(HttpStatusCode.NotFound) },
|
||||
): AppStore = AppStore(
|
||||
// Background scope so leftover store jobs (reconnect loops, refreshes)
|
||||
// are cancelled by runTest instead of failing with UncompletedCoroutinesError.
|
||||
scope = backgroundScope,
|
||||
api = ApiClient(configuredHttpClient(engine)),
|
||||
storage = storage,
|
||||
player = player,
|
||||
cache = cache,
|
||||
)
|
||||
|
||||
private class FakePlayer : AudioPlayer {
|
||||
|
||||
Reference in new issue
Block a user