feat!: replace OpenSubsonic with a native mood-first API
Remove the /rest compatibility layer and the playlist model. Moods are now first-class private collections, and playback is driven by short-lived radio sessions whose queues are generated by the server. - Bearer device tokens (hashed) with revocable sessions. - Library snapshot/delta sync with tombstones and per-folder scoping. - Mood CRUD, seeds, preview and recommendations. - Radio batches weighted by seeds, genres, artists, text and playback affinity. - Playback events (started/completed/skipped) and explicit add-to-mood. - Stream, download and cover endpoints with query-token support for browsers. - V5 migration drops playlists and migrates existing moods; scanner writes tombstones and song update timestamps. - Built-in UI rebuilt on the native API with a radio player. - Native API integration tests and a rewritten smoke test (49 checks). - Chart bumped to 0.2.0. BREAKING CHANGE: the OpenSubsonic API and static playlists are gone.
This commit is contained in:
1 parent
28bfdd9d00
commit
b33eb076c1
46 files changed
+3472
-5823
No files matched your search
@@ -0,0 +1,459 @@
|
||||
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.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.assertTrue
|
||||
import org.jetbrains.exposed.sql.insert
|
||||
import org.jetbrains.exposed.sql.insertIgnore
|
||||
import org.jetbrains.exposed.sql.transactions.transaction
|
||||
import org.junit.jupiter.api.io.TempDir
|
||||
import win.taptap.musicmanager.config.AppConfig
|
||||
import win.taptap.musicmanager.config.FolderType
|
||||
import win.taptap.musicmanager.config.LibraryConfig
|
||||
import win.taptap.musicmanager.config.MusicFolder
|
||||
import win.taptap.musicmanager.config.UserAccount
|
||||
import win.taptap.musicmanager.config.UsersConfig
|
||||
import win.taptap.musicmanager.db.AlbumArtistsTable
|
||||
import win.taptap.musicmanager.db.AlbumsTable
|
||||
import win.taptap.musicmanager.db.ArtistsTable
|
||||
import win.taptap.musicmanager.db.ConfigRepository
|
||||
import win.taptap.musicmanager.db.DatabaseFactory
|
||||
import win.taptap.musicmanager.db.DatabaseHandle
|
||||
import win.taptap.musicmanager.db.SongArtistsTable
|
||||
import win.taptap.musicmanager.db.SongGenresTable
|
||||
import win.taptap.musicmanager.db.SongsTable
|
||||
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"))
|
||||
assertEquals(listOf(1), ok["user"]!!.jsonObject["musicFolders"]!!.jsonArray.map { it.jsonPrimitive.int })
|
||||
|
||||
val bad = client.login("alice", "wrong")
|
||||
assertEquals(HttpStatusCode.Unauthorized, bad.status)
|
||||
assertEquals("invalid_credentials", parse(bad.bodyAsText())["error"]!!.jsonObject.string("code"))
|
||||
|
||||
val unauth = client.get("/api/v1/moods")
|
||||
assertEquals(HttpStatusCode.Unauthorized, unauth.status)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `library sync is folder scoped and stream accepts a query token`() {
|
||||
seededContext().use { seed ->
|
||||
testApplication {
|
||||
setupApp(seed)
|
||||
val token = client.token("alice", "alice-pw")
|
||||
|
||||
val page = parseBody(
|
||||
client.get("/api/v1/library/songs?scope=music") {
|
||||
bearer(token)
|
||||
}.bodyAsText(),
|
||||
)
|
||||
val ids = page["songs"]!!.jsonArray.map { it.jsonObject.string("id") }
|
||||
assertTrue(seed.aliceAmbient1 in ids)
|
||||
assertTrue(seed.aliceRock in ids)
|
||||
assertFalse(seed.longformSong in ids)
|
||||
assertFalse(seed.bobSong in ids)
|
||||
assertTrue(page.string("revision").isNotBlank())
|
||||
|
||||
val longform = parseBody(
|
||||
client.get("/api/v1/library/songs?scope=longform") {
|
||||
bearer(token)
|
||||
}.bodyAsText(),
|
||||
)
|
||||
val longformIds = longform["songs"]!!.jsonArray.map { it.jsonObject.string("id") }
|
||||
assertEquals(listOf(seed.longformSong), longformIds)
|
||||
|
||||
// HTML audio cannot set headers, so media endpoints accept ?token=.
|
||||
val stream = client.get("/api/v1/songs/${seed.aliceAmbient1}/stream?token=$token")
|
||||
assertEquals(HttpStatusCode.OK, stream.status)
|
||||
assertTrue(stream.bodyAsBytes().isNotEmpty())
|
||||
|
||||
val ranged = client.get("/api/v1/songs/${seed.aliceAmbient1}/stream?token=$token") {
|
||||
header(HttpHeaders.Range, "bytes=0-3")
|
||||
}
|
||||
assertEquals(HttpStatusCode.PartialContent, ranged.status)
|
||||
assertEquals(4, ranged.bodyAsBytes().size)
|
||||
|
||||
val forbidden = client.get("/api/v1/songs/${seed.bobSong}/stream?token=$token")
|
||||
assertEquals(HttpStatusCode.NotFound, forbidden.status)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `moods generate radio queues and add-to-mood replaces likes`() {
|
||||
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"],"targetSize":10,"seedSongIds":["${seed.aliceAmbient1}"]}""",
|
||||
)
|
||||
}
|
||||
assertEquals(HttpStatusCode.Created, created.status)
|
||||
val mood = parse(created.bodyAsText())
|
||||
val moodId = mood["mood"]!!.jsonObject.string("id")
|
||||
assertEquals(1, mood["mood"]!!.jsonObject.int("seedCount"))
|
||||
assertTrue(mood["seeds"]!!.jsonArray.isNotEmpty())
|
||||
|
||||
// Long-form can never be a mood seed.
|
||||
val withLongform = client.post("/api/v1/moods") {
|
||||
bearer(token)
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody("""{"name":"Book","seedSongIds":["${seed.longformSong}"]}""")
|
||||
}
|
||||
val bookMood = parse(withLongform.bodyAsText())
|
||||
assertEquals(0, bookMood["mood"]!!.jsonObject.int("seedCount"))
|
||||
|
||||
val started = client.post("/api/v1/moods/$moodId/sessions") {
|
||||
bearer(token)
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody("""{"limit":10}""")
|
||||
}
|
||||
assertEquals(HttpStatusCode.Created, started.status)
|
||||
val session = parse(started.bodyAsText())
|
||||
val sessionId = session.string("id")
|
||||
val queue = session["queue"]!!.jsonArray.map { it.jsonObject }
|
||||
assertTrue(queue.any { it.string("id") == seed.aliceAmbient1 })
|
||||
assertFalse(queue.any { it.string("id") == seed.longformSong })
|
||||
assertFalse(queue.any { it.string("id") == seed.bobSong })
|
||||
assertTrue(queue.all { it.string("folderId") == "1" })
|
||||
|
||||
val second = client.post("/api/v1/sessions/$sessionId/next") {
|
||||
bearer(token)
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody("""{"limit":10}""")
|
||||
}
|
||||
assertEquals(HttpStatusCode.OK, second.status)
|
||||
val nextIds = parse(second.bodyAsText())["songs"]!!.jsonArray
|
||||
.map { it.jsonObject.string("id") }
|
||||
assertTrue(nextIds.none { it in queue.map { song -> song.string("id") } })
|
||||
|
||||
val completed = client.post("/api/v1/sessions/$sessionId/events") {
|
||||
bearer(token)
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody("""{"events":[{"songId":"${seed.aliceAmbient1}","type":"completed"}]}""")
|
||||
}
|
||||
assertEquals(1, parse(completed.bodyAsText()).int("accepted"))
|
||||
|
||||
// Add to the current mood.
|
||||
val added = client.post("/api/v1/sessions/$sessionId/add-to-mood") {
|
||||
bearer(token)
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody("""{"songId":"${seed.aliceAmbient2}"}""")
|
||||
}
|
||||
val addedBody = parse(added.bodyAsText())
|
||||
assertTrue(addedBody["added"]!!.jsonPrimitive.content.toBoolean())
|
||||
assertEquals(2, addedBody["mood"]!!.jsonObject.int("seedCount"))
|
||||
|
||||
// Add to another mood through the chooser.
|
||||
val other = client.post("/api/v1/moods") {
|
||||
bearer(token)
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody("""{"name":"Evening"}""")
|
||||
}
|
||||
val otherId = parse(other.bodyAsText())["mood"]!!.jsonObject.string("id")
|
||||
val switched = client.post("/api/v1/sessions/$sessionId/add-to-mood") {
|
||||
bearer(token)
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody("""{"songId":"${seed.aliceAmbient2}","moodId":"$otherId"}""")
|
||||
}
|
||||
assertEquals(1, parse(switched.bodyAsText())["mood"]!!.jsonObject.int("seedCount"))
|
||||
|
||||
val removed = client.post("/api/v1/sessions/$sessionId/add-to-mood") {
|
||||
bearer(token)
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody("""{"songId":"${seed.aliceAmbient2}"}""")
|
||||
}
|
||||
assertEquals(2, parse(removed.bodyAsText())["mood"]!!.jsonObject.int("seedCount"))
|
||||
|
||||
val preview = parseBody(
|
||||
client.get("/api/v1/moods/$moodId/preview?limit=5") { bearer(token) }.bodyAsText(),
|
||||
)
|
||||
assertTrue(preview["songs"]!!.jsonArray.isNotEmpty())
|
||||
|
||||
val bobToken = client.token("bob", "bob-pw")
|
||||
val denied = client.get("/api/v1/moods/$moodId") { bearer(bobToken) }
|
||||
assertEquals(HttpStatusCode.NotFound, denied.status)
|
||||
|
||||
val deleted = client.deleteMood(token, moodId)
|
||||
assertEquals(HttpStatusCode.NoContent, deleted.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 mood = client.post("/api/v1/moods") {
|
||||
bearer(alice)
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody("""{"name":"Private"}""")
|
||||
}
|
||||
val moodId = parse(mood.bodyAsText())["mood"]!!.jsonObject.string("id")
|
||||
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")
|
||||
|
||||
val denied = client.get("/api/v1/sessions/$sessionId") { bearer(bob) }
|
||||
assertEquals(HttpStatusCode.NotFound, denied.status)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun ApplicationTestBuilder.setupApp(seed: Seed) {
|
||||
application {
|
||||
install(ContentNegotiation) {
|
||||
json(Json { ignoreUnknownKeys = true; encodeDefaults = true })
|
||||
}
|
||||
install(PartialContent)
|
||||
install(StatusPages) {
|
||||
exception<ApiException> { call, cause ->
|
||||
call.respond(
|
||||
cause.status,
|
||||
apiErrorBody(cause.code, cause.message),
|
||||
)
|
||||
}
|
||||
}
|
||||
routing {
|
||||
apiRoutes(
|
||||
users = seed.users,
|
||||
library = seed.library,
|
||||
coverArtService = seed.coverArt,
|
||||
transcoder = FfmpegTranscoder("ffmpeg"),
|
||||
radioService = RadioService(),
|
||||
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.deleteMood(token: String, id: String) =
|
||||
delete("/api/v1/moods/$id") {
|
||||
bearer(token)
|
||||
}
|
||||
|
||||
private fun seededContext(): Seed {
|
||||
val musicA = Files.createDirectories(tempDir.resolve("music-a"))
|
||||
val musicB = Files.createDirectories(tempDir.resolve("music-b"))
|
||||
val longform = Files.createDirectories(tempDir.resolve("longform"))
|
||||
|
||||
val library = LibraryConfig(
|
||||
listOf(
|
||||
MusicFolder(1, "Alice Music", FolderType.MUSIC, musicA),
|
||||
MusicFolder(2, "Bob Music", FolderType.MUSIC, musicB),
|
||||
MusicFolder(10, "Long-form", FolderType.LONGFORM, longform),
|
||||
),
|
||||
)
|
||||
val users = UsersConfig(
|
||||
listOf(
|
||||
UserAccount("alice", "alice-pw", admin = true, folders = setOf(1)),
|
||||
UserAccount("bob", "bob-pw", admin = false, folders = setOf(2)),
|
||||
),
|
||||
)
|
||||
|
||||
val db = DatabaseFactory.connect(
|
||||
AppConfig(
|
||||
port = 8080,
|
||||
dataDir = tempDir.resolve("data"),
|
||||
libraryConfigPath = tempDir.resolve("library.yaml"),
|
||||
usersFile = tempDir.resolve("users.yaml"),
|
||||
ffmpegPath = "ffmpeg",
|
||||
),
|
||||
)
|
||||
ConfigRepository.sync(library, users)
|
||||
|
||||
val aliceAmbient1 = seedSong(db, 1, "Alpha", "Focus One", "Deep Work", "Alpha/Focus One/01.mp3", "Ambient", musicA)
|
||||
val aliceAmbient2 = seedSong(db, 1, "Beta", "Focus Two", "Soft Light", "Beta/Focus Two/01.mp3", "Ambient", musicA)
|
||||
val aliceRock = seedSong(db, 1, "Gamma", "Loud", "Noise", "Gamma/Loud/01.mp3", "Rock", musicA)
|
||||
val bobSong = seedSong(db, 2, "Bob Artist", "Bob Album", "Bob Song", "Bob Artist/Bob Album/01.mp3", "Ambient", musicB)
|
||||
val longformSong = seedSong(
|
||||
db, 10, "Long Narrator", "Long Book", "Chapter One",
|
||||
"Long Narrator/Long Book/01.mp3", "Ambient", longform,
|
||||
)
|
||||
|
||||
return Seed(
|
||||
db = db,
|
||||
library = library,
|
||||
users = users,
|
||||
coverArt = CoverArtService(tempDir.resolve("data")),
|
||||
aliceAmbient1 = aliceAmbient1,
|
||||
aliceAmbient2 = aliceAmbient2,
|
||||
aliceRock = aliceRock,
|
||||
bobSong = bobSong,
|
||||
longformSong = longformSong,
|
||||
)
|
||||
}
|
||||
|
||||
private fun seedSong(
|
||||
db: DatabaseHandle,
|
||||
folderId: Int,
|
||||
artistName: String,
|
||||
albumName: String,
|
||||
title: String,
|
||||
relativePath: String,
|
||||
genre: String,
|
||||
root: Path,
|
||||
): String {
|
||||
val file = root.resolve(relativePath)
|
||||
Files.createDirectories(file.parent)
|
||||
Files.write(file, "ID3-fake-audio".toByteArray())
|
||||
|
||||
val artistId = IdGenerator.artistId(artistName)
|
||||
val albumId = IdGenerator.albumId(artistName, albumName)
|
||||
val songId = IdGenerator.songId(folderId, relativePath)
|
||||
val now = Instant.now().toString()
|
||||
|
||||
transaction(db.database) {
|
||||
ArtistsTable.insertIgnore {
|
||||
it[id] = artistId
|
||||
it[name] = artistName
|
||||
it[sortName] = artistName
|
||||
it[searchText] = IdGenerator.normalize(artistName)
|
||||
}
|
||||
AlbumsTable.insertIgnore {
|
||||
it[id] = albumId
|
||||
it[name] = albumName
|
||||
it[year] = 2026
|
||||
it[createdAt] = now
|
||||
it[searchText] = IdGenerator.normalize("$albumName $artistName")
|
||||
}
|
||||
AlbumArtistsTable.insertIgnore {
|
||||
it[this.albumId] = albumId
|
||||
it[this.artistId] = artistId
|
||||
it[position] = 0
|
||||
}
|
||||
SongsTable.insert {
|
||||
it[id] = songId
|
||||
it[this.albumId] = albumId
|
||||
it[this.folderId] = folderId
|
||||
it[this.title] = title
|
||||
it[displayArtist] = artistName
|
||||
it[this.albumName] = albumName
|
||||
it[trackNumber] = 1
|
||||
it[discNumber] = 1
|
||||
it[year] = 2026
|
||||
it[duration] = 120
|
||||
it[bitRate] = 128
|
||||
it[size] = Files.size(file)
|
||||
it[suffix] = "mp3"
|
||||
it[contentType] = "audio/mpeg"
|
||||
it[this.relativePath] = relativePath
|
||||
it[fileMtime] = 0
|
||||
it[createdAt] = now
|
||||
it[updatedAt] = now
|
||||
it[searchText] = IdGenerator.normalize("$title $artistName $albumName $artistName")
|
||||
}
|
||||
SongArtistsTable.insert {
|
||||
it[this.songId] = songId
|
||||
it[this.artistId] = artistId
|
||||
it[position] = 0
|
||||
}
|
||||
SongGenresTable.insert {
|
||||
it[this.songId] = songId
|
||||
it[this.genre] = genre
|
||||
}
|
||||
}
|
||||
|
||||
return songId
|
||||
}
|
||||
|
||||
private fun parseBody(body: String): JsonObject =
|
||||
Json.parseToJsonElement(body).jsonObject
|
||||
|
||||
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 data class Seed(
|
||||
val db: DatabaseHandle,
|
||||
val library: LibraryConfig,
|
||||
val users: UsersConfig,
|
||||
val coverArt: CoverArtService,
|
||||
val aliceAmbient1: String,
|
||||
val aliceAmbient2: String,
|
||||
val aliceRock: String,
|
||||
val bobSong: String,
|
||||
val longformSong: String,
|
||||
) : AutoCloseable {
|
||||
override fun close() = db.close()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user