package win.taptap.musicmanager.api import io.ktor.client.HttpClient import io.ktor.client.request.delete import io.ktor.client.request.get import io.ktor.client.request.header import io.ktor.client.request.patch import io.ktor.client.request.post import io.ktor.client.request.setBody import io.ktor.client.statement.bodyAsBytes import io.ktor.client.statement.bodyAsText import io.ktor.http.ContentType import io.ktor.http.HttpHeaders import io.ktor.http.HttpStatusCode import io.ktor.http.contentType import io.ktor.serialization.kotlinx.json.json import io.ktor.server.application.install import io.ktor.server.plugins.contentnegotiation.ContentNegotiation import io.ktor.server.plugins.partialcontent.PartialContent import io.ktor.server.plugins.statuspages.StatusPages import io.ktor.server.response.respond import io.ktor.server.routing.routing import io.ktor.server.testing.ApplicationTestBuilder import io.ktor.server.testing.testApplication import java.nio.file.Files import java.nio.file.Path import java.time.Instant import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.int import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertTrue import org.junit.jupiter.api.io.TempDir import win.taptap.musicmanager.TestAudio import win.taptap.musicmanager.config.AppConfig import win.taptap.musicmanager.config.UserAccount import win.taptap.musicmanager.config.UsersConfig import win.taptap.musicmanager.db.ConfigRepository import win.taptap.musicmanager.db.DatabaseFactory import win.taptap.musicmanager.db.DatabaseHandle import win.taptap.musicmanager.db.DownloadRepository import win.taptap.musicmanager.db.MoodRepository import win.taptap.musicmanager.db.RecommendationUpsert import win.taptap.musicmanager.db.SongRecord import win.taptap.musicmanager.db.SongRepository import win.taptap.musicmanager.db.SongUpsert import win.taptap.musicmanager.discovery.DiscoveryService import win.taptap.musicmanager.discovery.TopUpService import win.taptap.musicmanager.discovery.YtCandidate import win.taptap.musicmanager.discovery.YtResolver import win.taptap.musicmanager.discovery.YtSearch import win.taptap.musicmanager.media.MediaGcService import win.taptap.musicmanager.media.MediaStore import win.taptap.musicmanager.radio.RadioService import win.taptap.musicmanager.scanner.CoverArtService import win.taptap.musicmanager.scanner.ScanStatus import win.taptap.musicmanager.transcoding.FfmpegTranscoder import win.taptap.musicmanager.util.IdGenerator class ApiRoutesTest { @TempDir lateinit var tempDir: Path @Test fun `login issues a bearer token and rejects bad credentials`() { seededContext().use { seed -> testApplication { setupApp(seed) val ok = parse(client.login("alice", "alice-pw").bodyAsText()) assertTrue(ok.string("token").isNotBlank()) assertEquals("alice", ok["user"]!!.jsonObject.string("name")) assertTrue(ok["user"]!!.jsonObject["admin"]!!.jsonPrimitive.content.toBoolean()) val bad = client.login("alice", "wrong") assertEquals(HttpStatusCode.Unauthorized, bad.status) assertEquals( "invalid_credentials", parse(bad.bodyAsText())["error"]!!.jsonObject.string("code"), ) assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/moods").status) val token = client.token("alice", "alice-pw") val me = parse(client.get("/api/v1/me") { bearer(token) }.bodyAsText()) assertEquals("alice", me.string("name")) val malformed = client.post("/api/v1/moods") { bearer(token) contentType(ContentType.Application.Json) setBody("not-json") } assertEquals(HttpStatusCode.BadRequest, malformed.status) } } } @Test fun `moods own their songs and are private`() { seededContext().use { seed -> testApplication { setupApp(seed) val token = client.token("alice", "alice-pw") val created = client.post("/api/v1/moods") { bearer(token) contentType(ContentType.Application.Json) setBody( """{"name":"Focus","genres":["Ambient"],"collectionPercent":70,"recommendationCount":0}""", ) } assertEquals(HttpStatusCode.Created, created.status) val body = parse(created.bodyAsText()) val moodId = body["mood"]!!.jsonObject.string("id") assertEquals(0, body["mood"]!!.jsonObject.int("songCount")) assertEquals(70, body["mood"]!!.jsonObject.int("collectionPercent")) assertEquals(30, body["mood"]!!.jsonObject.int("recommendationPercent")) val added = client.post("/api/v1/moods/$moodId/songs") { bearer(token) contentType(ContentType.Application.Json) setBody("""{"songId":"${seed.ambient1}"}""") } assertEquals(HttpStatusCode.OK, added.status) val addedBody = parse(added.bodyAsText()) assertTrue(addedBody["added"]!!.jsonPrimitive.content.toBoolean()) assertEquals(1, addedBody["detail"]!!.jsonObject["mood"]!!.jsonObject.int("songCount")) assertEquals( seed.ambient1, addedBody["detail"]!!.jsonObject["songs"]!!.jsonArray.single() .jsonObject["song"]!!.jsonObject.string("id"), ) val again = client.post("/api/v1/moods/$moodId/songs") { bearer(token) contentType(ContentType.Application.Json) setBody("""{"songId":"${seed.ambient1}"}""") } assertFalse( parse(again.bodyAsText())["added"]!!.jsonPrimitive.content.toBoolean(), ) val patched = client.patch("/api/v1/moods/$moodId") { bearer(token) contentType(ContentType.Application.Json) setBody("""{"name":"Deep Focus","collectionPercent":40}""") } val patchedMood = parse(patched.bodyAsText())["mood"]!!.jsonObject assertEquals("Deep Focus", patchedMood.string("name")) assertEquals(40, patchedMood.int("collectionPercent")) val list = parse(client.get("/api/v1/moods") { bearer(token) }.bodyAsText()) assertEquals(1, list["moods"]!!.jsonArray.size) val bob = client.token("bob", "bob-pw") assertEquals( HttpStatusCode.NotFound, client.get("/api/v1/moods/$moodId") { bearer(bob) }.status, ) val removed = client.delete("/api/v1/moods/$moodId/songs/${seed.ambient1}") { bearer(token) } assertEquals(HttpStatusCode.NoContent, removed.status) val detail = parse(client.get("/api/v1/moods/$moodId") { bearer(token) }.bodyAsText()) assertTrue(detail["songs"]!!.jsonArray.isEmpty()) assertEquals( HttpStatusCode.NoContent, client.delete("/api/v1/moods/$moodId") { bearer(token) }.status, ) } } } @Test fun `a mood needs a song before a session can start`() { seededContext().use { seed -> testApplication { setupApp(seed) val token = client.token("alice", "alice-pw") val moodId = client.createMood(token, """{"name":"Empty","recommendationCount":0}""") val rejected = client.post("/api/v1/moods/$moodId/sessions") { bearer(token) contentType(ContentType.Application.Json) setBody("""{"limit":5}""") } assertEquals(HttpStatusCode.BadRequest, rejected.status) assertEquals( "empty_mood", parse(rejected.bodyAsText())["error"]!!.jsonObject.string("code"), ) client.addSong(token, moodId, seed.ambient1) val started = client.post("/api/v1/moods/$moodId/sessions") { bearer(token) contentType(ContentType.Application.Json) setBody("""{"limit":8}""") } assertEquals(HttpStatusCode.Created, started.status) val session = parse(started.bodyAsText()) val sessionId = session.string("id") assertEquals(moodId, session.string("moodId")) assertTrue( session["queue"]!!.jsonArray.map { it.jsonObject.string("id") } .contains(seed.ambient1), ) val next = client.post("/api/v1/sessions/$sessionId/next") { bearer(token) contentType(ContentType.Application.Json) setBody("""{"limit":5}""") } assertEquals(HttpStatusCode.OK, next.status) val nextIds = parse(next.bodyAsText())["songs"]!!.jsonArray .map { it.jsonObject.string("id") } assertEquals(nextIds.size, nextIds.distinct().size) val event = client.post("/api/v1/sessions/$sessionId/events") { bearer(token) contentType(ContentType.Application.Json) setBody("""{"events":[{"songId":"${seed.ambient1}","type":"completed"}]}""") } assertEquals(1, parse(event.bodyAsText()).int("accepted")) val unknown = client.post("/api/v1/sessions/$sessionId/events") { bearer(token) contentType(ContentType.Application.Json) setBody("""{"events":[{"songId":"sg-missing","type":"completed"}]}""") } assertEquals(0, parse(unknown.bodyAsText()).int("accepted")) val added = client.post("/api/v1/sessions/$sessionId/add-to-mood") { bearer(token) contentType(ContentType.Application.Json) setBody("""{"songId":"${seed.ambient2}"}""") } assertEquals( 2, parse(added.bodyAsText())["mood"]!!.jsonObject.int("songCount"), ) assertEquals( HttpStatusCode.NoContent, client.delete("/api/v1/sessions/$sessionId") { bearer(token) }.status, ) } } } @Test fun `a session is scoped to its owner`() { seededContext().use { seed -> testApplication { setupApp(seed) val alice = client.token("alice", "alice-pw") val bob = client.token("bob", "bob-pw") val moodId = client.createMood(alice, """{"name":"Private","recommendationCount":0}""") client.addSong(alice, moodId, seed.ambient1) val started = client.post("/api/v1/moods/$moodId/sessions") { bearer(alice) contentType(ContentType.Application.Json) setBody("""{"limit":5}""") } val sessionId = parse(started.bodyAsText()).string("id") assertEquals( HttpStatusCode.NotFound, client.get("/api/v1/sessions/$sessionId") { bearer(bob) }.status, ) } } } @Test fun `search hides long tracks and marks downloaded songs`() { seededContext().use { seed -> val results = listOf( YtCandidate("vid-ambient-1", "Already Here", "Artist", duration = 180), YtCandidate("vid-new", "Fresh Track", "New Artist", duration = 200), YtCandidate("vid-long", "Late Night Set", "Some DJ", duration = 3_600), YtCandidate("vid-short", "Interlude", "Some DJ", duration = 20), ) testApplication { setupApp(seed, search = FakeYt(results)) val token = client.token("alice", "alice-pw") val moodId = client.createMood(token, """{"name":"Search Mood","recommendationCount":0}""") client.addSong(token, moodId, seed.ambient1) val body = parse( client.get("/api/v1/search?q=ambient&moodId=$moodId") { bearer(token) }.bodyAsText(), ) val found = body["results"]!!.jsonArray.map { it.jsonObject } assertEquals(2, found.size) assertFalse(found.any { it.string("videoId") == "vid-long" }) assertFalse(found.any { it.string("videoId") == "vid-short" }) val downloaded = found.first { it.string("videoId") == "vid-ambient-1" } assertTrue(downloaded["downloaded"]!!.jsonPrimitive.content.toBoolean()) assertTrue(downloaded["inMood"]!!.jsonPrimitive.content.toBoolean()) assertEquals(seed.ambient1, downloaded.string("songId")) assertFalse( found.first { it.string("videoId") == "vid-new" }["downloaded"]!! .jsonPrimitive.content.toBoolean(), ) } } } @Test fun `adding a search result downloads it and a URL is resolved`() { seededContext().use { seed -> val resolved = YtCandidate("vid-url", "From URL", "Artist", duration = 180) val search = FakeYt( results = emptyList(), resolved = mapOf( "https://youtu.be/vid-url" to resolved, "https://youtu.be/vid-long" to YtCandidate("vid-long", "Long", "Artist", duration = 3_600), ), ) testApplication { setupApp(seed, search = search) val token = client.token("alice", "alice-pw") val moodId = client.createMood(token, """{"name":"Adds","recommendationCount":0}""") val queued = client.post("/api/v1/moods/$moodId/songs") { bearer(token) contentType(ContentType.Application.Json) setBody("""{"videoId":"vid-new"}""") } assertEquals(HttpStatusCode.Accepted, queued.status) assertTrue( parse(queued.bodyAsText())["downloading"]!!.jsonPrimitive.content.toBoolean(), ) assertEquals( "queued", DownloadRepository.find(moodId, "vid-new", DownloadRepository.KIND_SONG)?.state, ) val byUrl = client.post("/api/v1/moods/$moodId/songs") { bearer(token) contentType(ContentType.Application.Json) setBody("""{"url":"https://youtu.be/vid-url"}""") } assertEquals(HttpStatusCode.Accepted, byUrl.status) assertEquals( "queued", DownloadRepository.find(moodId, "vid-url", DownloadRepository.KIND_SONG)?.state, ) val long = client.post("/api/v1/moods/$moodId/songs") { bearer(token) contentType(ContentType.Application.Json) setBody("""{"url":"https://youtu.be/vid-long"}""") } assertEquals(HttpStatusCode.BadRequest, long.status) } } } @Test fun `recommendations can be added rejected and retried`() { seededContext().use { seed -> val results = listOf( YtCandidate("vid-ready", "Ready Track", "Artist", duration = 180), YtCandidate("vid-reject", "Rejected Track", "Artist", duration = 180), YtCandidate("vid-failed", "Failed Track", "Artist", duration = 180), ) testApplication { setupApp(seed, search = FakeYt(results)) val token = client.token("alice", "alice-pw") val moodId = client.createMood(token, """{"name":"Radio","recommendationCount":3}""") client.addSong(token, moodId, seed.ambient1) val refreshed = client.post("/api/v1/moods/$moodId/recommendations/refresh") { bearer(token) } assertEquals(HttpStatusCode.OK, refreshed.status) val recommendations = parse(refreshed.bodyAsText())["recommendations"]!!.jsonArray .map { it.jsonObject } assertEquals(3, recommendations.size) assertTrue(recommendations.all { it.string("state") == "downloading" }) // Simulate a finished download for the first slot. val readySong = insertSong(seed, "vid-ready", "Ready Track") MoodRepository.completeDownload(moodId, "vid-ready", readySong) val detail = parse(client.get("/api/v1/moods/$moodId") { bearer(token) }.bodyAsText()) val ready = detail["recommendations"]!!.jsonArray.map { it.jsonObject } .first { it.string("videoId") == "vid-ready" } assertEquals("ready", ready.string("state")) assertEquals(readySong, ready["song"]!!.jsonObject.string("id")) val added = client.post("/api/v1/moods/$moodId/recommendations/vid-ready/add") { bearer(token) } assertEquals(HttpStatusCode.OK, added.status) val addedBody = parse(added.bodyAsText()) assertEquals( "added", addedBody["recommendation"]!!.jsonObject.string("state"), ) assertEquals( 2, addedBody["detail"]!!.jsonObject["mood"]!!.jsonObject.int("songCount"), ) assertFalse( addedBody["detail"]!!.jsonObject["recommendations"]!!.jsonArray .map { it.jsonObject.string("videoId") } .contains("vid-ready"), ) val rejected = client.post("/api/v1/moods/$moodId/recommendations/vid-reject/reject") { bearer(token) } assertEquals( "rejected", parse(rejected.bodyAsText())["recommendation"]!!.jsonObject.string("state"), ) // The third slot is visible but failed; it must be retried first. val remaining = MoodRepository.recommendations(moodId) assertEquals(1, remaining.size) assertEquals("vid-failed", remaining.single().videoId) MoodRepository.failRecommendation(moodId, "vid-failed", "boom", 3) val cannotAdd = client.post("/api/v1/moods/$moodId/recommendations/vid-failed/add") { bearer(token) } assertEquals(HttpStatusCode.Conflict, cannotAdd.status) val retried = client.post("/api/v1/moods/$moodId/recommendations/vid-failed/retry") { bearer(token) } assertEquals(HttpStatusCode.OK, retried.status) val retryBody = parse(retried.bodyAsText()) assertEquals( "downloading", retryBody["recommendations"]!!.jsonArray.map { it.jsonObject } .first { it.string("videoId") == "vid-failed" } .string("state"), ) assertEquals( "queued", DownloadRepository.find( moodId, "vid-failed", DownloadRepository.KIND_RECOMMENDATION, )?.state, ) } } } @Test fun `streaming and covers work with a query token`() { seededContext().use { seed -> testApplication { setupApp(seed) val token = client.token("alice", "alice-pw") val stream = client.get("/api/v1/songs/${seed.ambient1}/stream?token=$token") assertEquals(HttpStatusCode.OK, stream.status) assertTrue(stream.bodyAsBytes().isNotEmpty()) val ranged = client.get("/api/v1/songs/${seed.ambient1}/stream?token=$token") { header(HttpHeaders.Range, "bytes=0-3") } assertEquals(HttpStatusCode.PartialContent, ranged.status) assertEquals(4, ranged.bodyAsBytes().size) assertEquals( HttpStatusCode.NotFound, client.get("/api/v1/songs/sg-missing/stream?token=$token").status, ) val cover = client.get("/api/v1/songs/${seed.ambient1}/cover?size=16&token=$token") assertEquals(HttpStatusCode.OK, cover.status) assertTrue(cover.bodyAsBytes().isNotEmpty()) } } } private fun ApplicationTestBuilder.setupApp( seed: Seed, search: FakeYt = FakeYt(emptyList()), ) { val discovery = DiscoveryService(search) application { install(ContentNegotiation) { json(Json { ignoreUnknownKeys = true; encodeDefaults = true }) } install(PartialContent) install(StatusPages) { exception { call, cause -> call.respond( cause.status, apiErrorBody(cause.code, cause.message), ) } } routing { apiRoutes( users = seed.users, coverArtService = seed.coverArt, transcoder = FfmpegTranscoder("ffmpeg"), radioService = RadioService(), discoveryService = discovery, topUpService = TopUpService(discovery), ytSearch = search, ytResolver = search, mediaStore = seed.media, gc = seed.gc, startScan = { false }, scanStatus = { ScanStatus(false, 0) }, ) } } } private suspend fun HttpClient.token(user: String, password: String): String = parse(login(user, password).bodyAsText()).string("token") private suspend fun HttpClient.login(user: String, password: String) = post("/api/v1/auth/login") { contentType(ContentType.Application.Json) setBody("""{"username":"$user","password":"$password","deviceName":"test","platform":"test"}""") } private fun io.ktor.client.request.HttpRequestBuilder.bearer(token: String) { header(HttpHeaders.Authorization, "Bearer $token") } private suspend fun HttpClient.createMood(token: String, body: String): String { val created = post("/api/v1/moods") { bearer(token) contentType(ContentType.Application.Json) setBody(body) } assertEquals(HttpStatusCode.Created, created.status) return parse(created.bodyAsText())["mood"]!!.jsonObject.string("id") } private suspend fun HttpClient.addSong(token: String, moodId: String, songId: String) { val response = post("/api/v1/moods/$moodId/songs") { bearer(token) contentType(ContentType.Application.Json) setBody("""{"songId":"$songId"}""") } assertEquals(HttpStatusCode.OK, response.status) } private fun seededContext(): Seed { val users = UsersConfig( listOf( UserAccount("alice", "alice-pw", admin = true), UserAccount("bob", "bob-pw", admin = false), ), ) val db = DatabaseFactory.connect( AppConfig( port = 8080, dataDir = tempDir.resolve("data"), usersFile = tempDir.resolve("users.yaml"), ffmpegPath = "ffmpeg", ), ) ConfigRepository.sync(users) val media = MediaStore(Files.createDirectories(tempDir.resolve("media"))) val coverArt = CoverArtService(tempDir.resolve("data")) val seed = Seed( db = db, users = users, media = media, coverArt = coverArt, gc = MediaGcService(media, coverArt), ) seed.ambient1 = insertSong(seed, "vid-ambient-1", "Focus One", artist = "Alpha") seed.ambient2 = insertSong(seed, "vid-ambient-2", "Focus Two", artist = "Beta") seed.rock = insertSong(seed, "vid-rock", "Loud", artist = "Gamma") seed.bobSong = insertSong(seed, "vid-bob", "Bob Song", artist = "Bob") seed.coverArt.saveCover(seed.ambient1, pngBytes()) return seed } /** Seeds a shared song directly (normally the downloader does this). */ private fun insertSong(seed: Seed, videoId: String, title: String, artist: String = "Artist"): String { val file = seed.media.target(videoId, title) Files.createDirectories(file.parent) Files.write(file, "ID3-fake-audio".toByteArray()) return SongRepository.upsert( SongUpsert( videoId = videoId, title = title, artist = artist, album = "Album", duration = 180, bitRate = 128, size = Files.size(file), relativePath = seed.media.root.relativize(file).joinToString("/") { it.toString() }, fileMtime = Files.getLastModifiedTime(file).toMillis(), thumbnail = null, ), ).id } private fun pngBytes(): ByteArray { val cover = tempDir.resolve("cover.png") TestAudio.writePng(cover, 32, 32) return Files.readAllBytes(cover) } private fun parse(body: String): JsonObject = Json.parseToJsonElement(body).jsonObject private fun JsonObject.string(name: String): String = this[name]!!.jsonPrimitive.content private fun JsonObject.int(name: String): Int = this[name]!!.jsonPrimitive.int private class FakeYt( private val results: List, private val resolved: Map = emptyMap(), ) : YtSearch, YtResolver { override fun search(query: String, limit: Int): List = results override fun resolve(url: String): YtCandidate? = resolved[url] } private data class Seed( val db: DatabaseHandle, val users: UsersConfig, val media: MediaStore, val coverArt: CoverArtService, val gc: MediaGcService, ) : AutoCloseable { lateinit var ambient1: String lateinit var ambient2: String lateinit var rock: String lateinit var bobSong: String override fun close() = db.close() } }