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()
|
||||
}
|
||||
}
|
||||
@@ -1,649 +0,0 @@
|
||||
package win.taptap.musicmanager.subsonic
|
||||
|
||||
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.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.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
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.assertTrue
|
||||
import org.jetbrains.exposed.sql.insert
|
||||
import org.jetbrains.exposed.sql.transactions.transaction
|
||||
import org.junit.jupiter.api.io.TempDir
|
||||
import win.taptap.musicmanager.TestAudio
|
||||
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.AlbumGenresTable
|
||||
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.MediaRepository
|
||||
import win.taptap.musicmanager.db.SongArtistsTable
|
||||
import win.taptap.musicmanager.db.SongGenresTable
|
||||
import win.taptap.musicmanager.db.SongsTable
|
||||
import win.taptap.musicmanager.mood.MoodService
|
||||
import win.taptap.musicmanager.scanner.CoverArtService
|
||||
import win.taptap.musicmanager.scanner.ScanStatus
|
||||
import win.taptap.musicmanager.subsonic.routes.subsonicRoutes
|
||||
import win.taptap.musicmanager.transcoding.FfmpegTranscoder
|
||||
import win.taptap.musicmanager.util.IdGenerator
|
||||
|
||||
class BrowsingRoutesTest {
|
||||
|
||||
@TempDir
|
||||
lateinit var tempDir: Path
|
||||
|
||||
@Test
|
||||
fun `music folders are scoped to the user and long-form is shared`() {
|
||||
seededContext().use { seed ->
|
||||
testApplication {
|
||||
setupApp(seed)
|
||||
|
||||
val alice = parseBody(client.get("/rest/getMusicFolders?${credentials("alice", "alice-pw")}").bodyAsText())
|
||||
val aliceIds = folderIds(alice)
|
||||
assertEquals(listOf(1, 10), aliceIds)
|
||||
|
||||
val bob = parseBody(client.get("/rest/getMusicFolders?${credentials("bob", "bob-pw")}").bodyAsText())
|
||||
assertEquals(listOf(2, 10), folderIds(bob))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `artist and album browsing only exposes visible music`() {
|
||||
seededContext().use { seed ->
|
||||
testApplication {
|
||||
setupApp(seed)
|
||||
|
||||
val artists = parseBody(client.get("/rest/getArtists?${credentials("alice", "alice-pw")}").bodyAsText())
|
||||
val index = artists["artists"]!!.jsonObject["index"]!!.jsonArray
|
||||
val names = index.flatMap { it.jsonObject["artist"]!!.jsonArray }
|
||||
.map { it.jsonObject["name"]!!.jsonPrimitive.content }
|
||||
assertEquals(listOf("Alice Artist"), names)
|
||||
|
||||
val artist = parseBody(
|
||||
client.get("/rest/getArtist?${credentials("alice", "alice-pw")}&id=${seed.aliceArtistId}").bodyAsText(),
|
||||
)
|
||||
val albums = artist["artist"]!!.jsonObject["album"]!!.jsonArray
|
||||
assertEquals(1, albums.size)
|
||||
assertEquals(seed.aliceAlbumId, albums[0].jsonObject["id"]!!.jsonPrimitive.content)
|
||||
|
||||
val album = parseBody(
|
||||
client.get("/rest/getAlbum?${credentials("alice", "alice-pw")}&id=${seed.aliceAlbumId}").bodyAsText(),
|
||||
)
|
||||
val songs = album["album"]!!.jsonObject["song"]!!.jsonArray
|
||||
assertEquals(1, songs.size)
|
||||
assertEquals(seed.aliceSongId, songs[0].jsonObject["id"]!!.jsonPrimitive.content)
|
||||
assertEquals("mp3", songs[0].jsonObject["suffix"]!!.jsonPrimitive.content)
|
||||
assertEquals("audio/mpeg", songs[0].jsonObject["contentType"]!!.jsonPrimitive.content)
|
||||
|
||||
val hidden = parseBody(
|
||||
client.get("/rest/getSong?${credentials("alice", "alice-pw")}&id=${seed.bobSongId}").bodyAsText(),
|
||||
)
|
||||
assertEquals("failed", hidden["status"]!!.jsonPrimitive.content)
|
||||
assertEquals(70, hidden["error"]!!.jsonObject["code"]!!.jsonPrimitive.int)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `search3 filters by query and supports empty and wildcard queries`() {
|
||||
seededContext().use { seed ->
|
||||
testApplication {
|
||||
setupApp(seed)
|
||||
|
||||
val alice = parseSearch(
|
||||
client.get("/rest/search3?${credentials("alice", "alice-pw")}&query=alice").bodyAsText(),
|
||||
)
|
||||
assertEquals(1, alice["artist"]!!.jsonArray.size)
|
||||
assertEquals(1, alice["album"]!!.jsonArray.size)
|
||||
assertEquals(1, alice["song"]!!.jsonArray.size)
|
||||
|
||||
val none = parseSearch(
|
||||
client.get("/rest/search3?${credentials("alice", "alice-pw")}&query=nothing-matches").bodyAsText(),
|
||||
)
|
||||
assertEquals(0, none["artist"]!!.jsonArray.size)
|
||||
assertEquals(0, none["album"]!!.jsonArray.size)
|
||||
assertEquals(0, none["song"]!!.jsonArray.size)
|
||||
|
||||
val all = parseSearch(
|
||||
client.get("/rest/search3?${credentials("bob", "bob-pw")}&query=*").bodyAsText(),
|
||||
)
|
||||
assertEquals(1, all["song"]!!.jsonArray.size)
|
||||
assertEquals(seed.bobSongId, all["song"]!!.jsonArray[0].jsonObject["id"]!!.jsonPrimitive.content)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `streams and downloads the original file and serves covers`() {
|
||||
seededContext().use { seed ->
|
||||
testApplication {
|
||||
setupApp(seed)
|
||||
|
||||
val stream = client.get("/rest/stream?${credentials("alice", "alice-pw")}&id=${seed.aliceSongId}")
|
||||
assertEquals(HttpStatusCode.OK, stream.status)
|
||||
assertEquals(seed.aliceAudioBytes.toList(), stream.bodyAsBytes().toList())
|
||||
|
||||
val ranged = client.get("/rest/stream?${credentials("alice", "alice-pw")}&id=${seed.aliceSongId}") {
|
||||
header(HttpHeaders.Range, "bytes=0-3")
|
||||
}
|
||||
assertEquals(HttpStatusCode.PartialContent, ranged.status)
|
||||
assertEquals(seed.aliceAudioBytes.take(4), ranged.bodyAsBytes().toList())
|
||||
|
||||
val download = client.get("/rest/download?${credentials("alice", "alice-pw")}&id=${seed.aliceSongId}")
|
||||
assertEquals(HttpStatusCode.OK, download.status)
|
||||
assertTrue(
|
||||
download.headers["Content-Disposition"]!!
|
||||
.contains("filename*=UTF-8''song.mp3"),
|
||||
)
|
||||
|
||||
val cover = client.get(
|
||||
"/rest/getCoverArt?${credentials("alice", "alice-pw")}&id=${seed.aliceAlbumId}&size=16",
|
||||
)
|
||||
assertEquals(HttpStatusCode.OK, cover.status)
|
||||
assertTrue(cover.bodyAsBytes().isNotEmpty())
|
||||
|
||||
val otherUsersCover = client.get(
|
||||
"/rest/getCoverArt?${credentials("bob", "bob-pw")}&id=${seed.aliceAlbumId}",
|
||||
)
|
||||
assertEquals(HttpStatusCode.NotFound, otherUsersCover.status)
|
||||
|
||||
val otherUsersSong = parseBody(
|
||||
client.get("/rest/stream?${credentials("bob", "bob-pw")}&id=${seed.aliceSongId}").bodyAsText(),
|
||||
)
|
||||
assertEquals(70, otherUsersSong["error"]!!.jsonObject["code"]!!.jsonPrimitive.int)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `getSong returns the expected offline metadata`() {
|
||||
seededContext().use { seed ->
|
||||
testApplication {
|
||||
setupApp(seed)
|
||||
|
||||
val song = parseBody(
|
||||
client.get("/rest/getSong?${credentials("alice", "alice-pw")}&id=${seed.aliceSongId}").bodyAsText(),
|
||||
)["song"]!!.jsonObject
|
||||
|
||||
assertEquals(seed.aliceSongId, song["id"]!!.jsonPrimitive.content)
|
||||
assertEquals(seed.aliceAlbumId, song["albumId"]!!.jsonPrimitive.content)
|
||||
assertEquals(seed.aliceArtistId, song["artistId"]!!.jsonPrimitive.content)
|
||||
assertEquals(seed.aliceFileSize.toString(), song["size"]!!.jsonPrimitive.content)
|
||||
assertEquals("Rock", song["genre"]!!.jsonPrimitive.content)
|
||||
assertEquals(128, song["bitRate"]!!.jsonPrimitive.int)
|
||||
assertEquals("music", song["type"]!!.jsonPrimitive.content)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `album feeds genres and random songs are visibility scoped`() {
|
||||
seededContext().use { seed ->
|
||||
testApplication {
|
||||
setupApp(seed)
|
||||
val auth = credentials("alice", "alice-pw")
|
||||
|
||||
val albums = parseBody(
|
||||
client.get("/rest/getAlbumList2?$auth&type=alphabeticalByName&size=10").bodyAsText(),
|
||||
)["albumList2"]!!.jsonObject["album"]!!.jsonArray
|
||||
assertEquals(1, albums.size)
|
||||
assertEquals(seed.aliceAlbumId, albums[0].jsonObject["id"]!!.jsonPrimitive.content)
|
||||
|
||||
val recent = parseBody(
|
||||
client.get("/rest/getAlbumList2?$auth&type=recent&size=10").bodyAsText(),
|
||||
)["albumList2"]!!.jsonObject["album"]!!.jsonArray
|
||||
assertEquals(1, recent.size)
|
||||
|
||||
// Feishin sends an inverted range for descending by-year queries.
|
||||
val byYear = parseBody(
|
||||
client.get("/rest/getAlbumList2?$auth&type=byYear&fromYear=2026&toYear=0").bodyAsText(),
|
||||
)["albumList2"]!!.jsonObject["album"]!!.jsonArray
|
||||
assertEquals(1, byYear.size)
|
||||
|
||||
val genres = parseBody(client.get("/rest/getGenres?$auth").bodyAsText())["genres"]!!
|
||||
.jsonObject["genre"]!!.jsonArray
|
||||
assertEquals(listOf("Rock"), genres.map { it.jsonObject["value"]!!.jsonPrimitive.content })
|
||||
|
||||
val byGenre = parseBody(
|
||||
client.get("/rest/getSongsByGenre?$auth&genre=Rock&count=10").bodyAsText(),
|
||||
)["songsByGenre"]!!.jsonObject["song"]!!.jsonArray
|
||||
assertEquals(seed.aliceSongId, byGenre.single().jsonObject["id"]!!.jsonPrimitive.content)
|
||||
|
||||
val random = parseBody(
|
||||
client.get("/rest/getRandomSongs?$auth&size=10").bodyAsText(),
|
||||
)["randomSongs"]!!.jsonObject["song"]!!.jsonArray
|
||||
assertEquals(seed.aliceSongId, random.single().jsonObject["id"]!!.jsonPrimitive.content)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `scrobbling stars ratings and bookmarks are per user`() {
|
||||
seededContext().use { seed ->
|
||||
testApplication {
|
||||
setupApp(seed)
|
||||
val alice = credentials("alice", "alice-pw")
|
||||
val bob = credentials("bob", "bob-pw")
|
||||
|
||||
client.get("/rest/scrobble?$alice&id=${seed.aliceSongId}")
|
||||
val played = parseBody(
|
||||
client.get("/rest/getSong?$alice&id=${seed.aliceSongId}").bodyAsText(),
|
||||
)["song"]!!.jsonObject
|
||||
assertEquals(1, played["playCount"]!!.jsonPrimitive.int)
|
||||
|
||||
client.get("/rest/star?$alice&id=${seed.aliceSongId}&albumId=${seed.aliceAlbumId}")
|
||||
val starred = parseBody(client.get("/rest/getStarred2?$alice").bodyAsText())["starred2"]!!
|
||||
.jsonObject
|
||||
assertEquals(1, starred["song"]!!.jsonArray.size)
|
||||
assertEquals(1, starred["album"]!!.jsonArray.size)
|
||||
|
||||
val bobStarred = parseBody(client.get("/rest/getStarred2?$bob").bodyAsText())["starred2"]!!
|
||||
.jsonObject
|
||||
assertEquals(0, bobStarred["song"]!!.jsonArray.size)
|
||||
|
||||
client.get("/rest/setRating?$alice&id=${seed.aliceSongId}&rating=4")
|
||||
client.get("/rest/setRating?$alice&id=${seed.aliceAlbumId}&rating=5")
|
||||
|
||||
val ratedSong = parseBody(
|
||||
client.get("/rest/getSong?$alice&id=${seed.aliceSongId}").bodyAsText(),
|
||||
)["song"]!!.jsonObject
|
||||
assertEquals(4, ratedSong["userRating"]!!.jsonPrimitive.int)
|
||||
|
||||
val ratedAlbum = parseBody(
|
||||
client.get("/rest/getAlbum?$alice&id=${seed.aliceAlbumId}").bodyAsText(),
|
||||
)["album"]!!.jsonObject
|
||||
assertEquals(5, ratedAlbum["userRating"]!!.jsonPrimitive.int)
|
||||
|
||||
client.get("/rest/createBookmark?$alice&id=${seed.aliceSongId}&position=5000")
|
||||
val bookmarks = parseBody(client.get("/rest/getBookmarks?$alice").bodyAsText())["bookmarks"]!!
|
||||
.jsonObject["bookmark"]!!.jsonArray
|
||||
assertEquals(1, bookmarks.size)
|
||||
assertEquals(5000, bookmarks[0].jsonObject["position"]!!.jsonPrimitive.int)
|
||||
assertEquals(
|
||||
seed.aliceSongId,
|
||||
bookmarks[0].jsonObject["entry"]!!.jsonObject["id"]!!.jsonPrimitive.content,
|
||||
)
|
||||
|
||||
client.get("/rest/deleteBookmark?$alice&id=${seed.aliceSongId}")
|
||||
val empty = parseBody(client.get("/rest/getBookmarks?$alice").bodyAsText())["bookmarks"]!!
|
||||
.jsonObject["bookmark"]!!.jsonArray
|
||||
assertEquals(0, empty.size)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `playlists enforce ownership and filter entries by visibility`() {
|
||||
seededContext().use { seed ->
|
||||
testApplication {
|
||||
setupApp(seed)
|
||||
val alice = credentials("alice", "alice-pw")
|
||||
val bob = credentials("bob", "bob-pw")
|
||||
|
||||
val created = parseBody(
|
||||
client.get("/rest/createPlaylist?$alice&name=Alice List&songId=${seed.aliceSongId}").bodyAsText(),
|
||||
)["playlist"]!!.jsonObject
|
||||
val playlistId = created["id"]!!.jsonPrimitive.content
|
||||
assertEquals("Alice List", created["name"]!!.jsonPrimitive.content)
|
||||
assertEquals(1, created["songCount"]!!.jsonPrimitive.int)
|
||||
|
||||
val aliceList = parseBody(client.get("/rest/getPlaylists?$alice").bodyAsText())["playlists"]!!
|
||||
.jsonObject["playlist"]!!.jsonArray
|
||||
assertEquals(1, aliceList.size)
|
||||
|
||||
val bobDetail = parseBody(
|
||||
client.get("/rest/getPlaylist?$bob&id=$playlistId").bodyAsText(),
|
||||
)["playlist"]!!.jsonObject
|
||||
assertEquals(1, bobDetail["songCount"]!!.jsonPrimitive.int)
|
||||
assertEquals(0, bobDetail["entry"]!!.jsonArray.size)
|
||||
|
||||
val forbidden = parseBody(
|
||||
client.get("/rest/deletePlaylist?$bob&id=$playlistId").bodyAsText(),
|
||||
)
|
||||
assertEquals(50, forbidden["error"]!!.jsonObject["code"]!!.jsonPrimitive.int)
|
||||
|
||||
client.get("/rest/updatePlaylist?$alice&playlistId=$playlistId&songIndexToRemove=0")
|
||||
val emptied = parseBody(
|
||||
client.get("/rest/getPlaylist?$alice&id=$playlistId").bodyAsText(),
|
||||
)["playlist"]!!.jsonObject
|
||||
assertEquals(0, emptied["entry"]!!.jsonArray.size)
|
||||
|
||||
val deleted = parseBody(
|
||||
client.get("/rest/deletePlaylist?$alice&id=$playlistId").bodyAsText(),
|
||||
)
|
||||
assertEquals("ok", deleted["status"]!!.jsonPrimitive.content)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `form posts are accepted for client compatibility`() {
|
||||
seededContext().use { seed ->
|
||||
testApplication {
|
||||
setupApp(seed)
|
||||
|
||||
val response = client.post("/rest/getAlbumList2.view") {
|
||||
contentType(ContentType.Application.FormUrlEncoded)
|
||||
setBody("${credentials("alice", "alice-pw")}&type=alphabeticalByName&size=10")
|
||||
}
|
||||
|
||||
assertEquals(HttpStatusCode.OK, response.status)
|
||||
val albums = parseBody(response.bodyAsText())["albumList2"]!!
|
||||
.jsonObject["album"]!!.jsonArray
|
||||
assertEquals(seed.aliceAlbumId, albums[0].jsonObject["id"]!!.jsonPrimitive.content)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `music directory and play queue expose folders albums and songs`() {
|
||||
seededContext().use { seed ->
|
||||
testApplication {
|
||||
setupApp(seed)
|
||||
val auth = credentials("alice", "alice-pw")
|
||||
|
||||
val folder = parseBody(
|
||||
client.get("/rest/getMusicDirectory?$auth&id=1").bodyAsText(),
|
||||
)["directory"]!!.jsonObject
|
||||
val folderChildren = folder["child"]!!.jsonArray
|
||||
assertEquals(1, folderChildren.size)
|
||||
assertEquals(seed.aliceAlbumId, folderChildren[0].jsonObject["id"]!!.jsonPrimitive.content)
|
||||
assertEquals("true", folderChildren[0].jsonObject["isDir"]!!.jsonPrimitive.content)
|
||||
|
||||
val album = parseBody(
|
||||
client.get("/rest/getMusicDirectory?$auth&id=${seed.aliceAlbumId}").bodyAsText(),
|
||||
)["directory"]!!.jsonObject
|
||||
assertEquals(seed.aliceSongId, album["child"]!!.jsonArray[0].jsonObject["id"]!!.jsonPrimitive.content)
|
||||
|
||||
client.get("/rest/savePlayQueue?$auth&id=${seed.aliceSongId}&position=1000")
|
||||
val queue = parseBody(client.get("/rest/getPlayQueue?$auth").bodyAsText())["playQueue"]!!
|
||||
.jsonObject
|
||||
assertEquals(seed.aliceSongId, queue["entry"]!!.jsonArray[0].jsonObject["id"]!!.jsonPrimitive.content)
|
||||
assertEquals(1000, queue["position"]!!.jsonPrimitive.int)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `music directory exposes artist albums for folder browsing`() {
|
||||
seededContext().use { seed ->
|
||||
testApplication {
|
||||
setupApp(seed)
|
||||
val auth = credentials("alice", "alice-pw")
|
||||
|
||||
val artist = parseBody(
|
||||
client.get("/rest/getMusicDirectory?$auth&id=${seed.aliceArtistId}").bodyAsText(),
|
||||
)["directory"]!!.jsonObject
|
||||
assertEquals(seed.aliceArtistId, artist["id"]!!.jsonPrimitive.content)
|
||||
|
||||
val albums = artist["child"]!!.jsonArray
|
||||
assertEquals(1, albums.size)
|
||||
assertEquals(seed.aliceAlbumId, albums[0].jsonObject["id"]!!.jsonPrimitive.content)
|
||||
assertEquals(seed.aliceArtistId, albums[0].jsonObject["parent"]!!.jsonPrimitive.content)
|
||||
assertEquals("true", albums[0].jsonObject["isDir"]!!.jsonPrimitive.content)
|
||||
|
||||
val album = parseBody(
|
||||
client.get("/rest/getMusicDirectory?$auth&id=${seed.aliceAlbumId}").bodyAsText(),
|
||||
)["directory"]!!.jsonObject
|
||||
assertEquals(seed.aliceSongId, album["child"]!!.jsonArray[0].jsonObject["id"]!!.jsonPrimitive.content)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `lyrics endpoint returns an empty structure when the song has no lyrics`() {
|
||||
seededContext().use { seed ->
|
||||
testApplication {
|
||||
setupApp(seed)
|
||||
val auth = credentials("alice", "alice-pw")
|
||||
|
||||
val body = parseBody(
|
||||
client.get("/rest/getLyricsBySongId?$auth&id=${seed.aliceSongId}").bodyAsText(),
|
||||
)
|
||||
val lyricsList = body["lyricsList"]!!.jsonObject
|
||||
assertEquals(0, lyricsList["structuredLyrics"]?.jsonArray?.size ?: 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun ApplicationTestBuilder.setupApp(seed: Seed) {
|
||||
application {
|
||||
install(ContentNegotiation) {
|
||||
json(Json { ignoreUnknownKeys = true; encodeDefaults = true })
|
||||
}
|
||||
install(PartialContent)
|
||||
routing {
|
||||
subsonicRoutes(
|
||||
users = seed.users,
|
||||
library = seed.library,
|
||||
coverArtService = seed.coverArt,
|
||||
transcoder = FfmpegTranscoder("ffmpeg"),
|
||||
moodService = MoodService(CoroutineScope(Dispatchers.Unconfined)),
|
||||
startScan = { false },
|
||||
scanStatus = { ScanStatus(false, 0) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 aliceAudio = musicA.resolve("Alice Artist/Alice Album/song.mp3")
|
||||
Files.createDirectories(aliceAudio.parent)
|
||||
val audioBytes = "ID3-fake-audio-payload".toByteArray()
|
||||
Files.write(aliceAudio, audioBytes)
|
||||
|
||||
val bobAudio = musicB.resolve("Bob Artist/Bob Album/song.mp3")
|
||||
Files.createDirectories(bobAudio.parent)
|
||||
Files.write(bobAudio, "ID3-bob".toByteArray())
|
||||
|
||||
val alice = seedSong(
|
||||
db = db,
|
||||
folderId = 1,
|
||||
artistName = "Alice Artist",
|
||||
albumName = "Alice Album",
|
||||
title = "Alice Song",
|
||||
relativePath = "Alice Artist/Alice Album/song.mp3",
|
||||
genre = "Rock",
|
||||
fileSize = Files.size(aliceAudio),
|
||||
)
|
||||
val bob = seedSong(
|
||||
db = db,
|
||||
folderId = 2,
|
||||
artistName = "Bob Artist",
|
||||
albumName = "Bob Album",
|
||||
title = "Bob Song",
|
||||
relativePath = "Bob Artist/Bob Album/song.mp3",
|
||||
genre = "Jazz",
|
||||
fileSize = Files.size(bobAudio),
|
||||
)
|
||||
|
||||
val coverArt = CoverArtService(tempDir.resolve("data"))
|
||||
val coverPng = tempDir.resolve("cover.png")
|
||||
TestAudio.writePng(coverPng, 64, 64)
|
||||
coverArt.saveCover(alice.albumId, Files.readAllBytes(coverPng))
|
||||
MediaRepository.setAlbumCover(alice.albumId)
|
||||
|
||||
return Seed(
|
||||
db = db,
|
||||
library = library,
|
||||
users = users,
|
||||
coverArt = coverArt,
|
||||
aliceArtistId = alice.artistId,
|
||||
aliceAlbumId = alice.albumId,
|
||||
aliceSongId = alice.songId,
|
||||
bobArtistId = bob.artistId,
|
||||
bobAlbumId = bob.albumId,
|
||||
bobSongId = bob.songId,
|
||||
aliceAudioBytes = audioBytes,
|
||||
aliceFileSize = Files.size(aliceAudio),
|
||||
)
|
||||
}
|
||||
|
||||
private fun seedSong(
|
||||
db: DatabaseHandle,
|
||||
folderId: Int,
|
||||
artistName: String,
|
||||
albumName: String,
|
||||
title: String,
|
||||
relativePath: String,
|
||||
genre: String,
|
||||
fileSize: Long,
|
||||
): SeededSong {
|
||||
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.insert {
|
||||
it[id] = artistId
|
||||
it[name] = artistName
|
||||
it[sortName] = artistName
|
||||
it[searchText] = IdGenerator.normalize(artistName)
|
||||
}
|
||||
AlbumsTable.insert {
|
||||
it[id] = albumId
|
||||
it[name] = albumName
|
||||
it[year] = 2026
|
||||
it[createdAt] = now
|
||||
it[searchText] = IdGenerator.normalize("$albumName $artistName")
|
||||
}
|
||||
AlbumArtistsTable.insert {
|
||||
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] = fileSize
|
||||
it[suffix] = "mp3"
|
||||
it[contentType] = "audio/mpeg"
|
||||
it[this.relativePath] = relativePath
|
||||
it[fileMtime] = 0
|
||||
it[createdAt] = 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
|
||||
}
|
||||
AlbumGenresTable.insert {
|
||||
it[this.albumId] = albumId
|
||||
it[this.genre] = genre
|
||||
}
|
||||
}
|
||||
|
||||
return SeededSong(artistId, albumId, songId)
|
||||
}
|
||||
|
||||
private fun credentials(user: String, password: String): String {
|
||||
val salt = "test-salt"
|
||||
return "u=$user&t=${SubsonicAuthenticator.md5Hex(password + salt)}&s=$salt"
|
||||
}
|
||||
|
||||
private fun parseBody(body: String): JsonObject =
|
||||
Json.parseToJsonElement(body).jsonObject["subsonic-response"]!!.jsonObject
|
||||
|
||||
private fun parseSearch(body: String): JsonObject =
|
||||
parseBody(body)["searchResult3"]!!.jsonObject
|
||||
|
||||
private fun folderIds(body: JsonObject): List<Int> =
|
||||
body["musicFolders"]!!.jsonObject["musicFolder"]!!.jsonArray
|
||||
.map { it.jsonObject["id"]!!.jsonPrimitive.int }
|
||||
|
||||
private data class SeededSong(val artistId: String, val albumId: String, val songId: String)
|
||||
|
||||
private data class Seed(
|
||||
val db: DatabaseHandle,
|
||||
val library: LibraryConfig,
|
||||
val users: UsersConfig,
|
||||
val coverArt: CoverArtService,
|
||||
val aliceArtistId: String,
|
||||
val aliceAlbumId: String,
|
||||
val aliceSongId: String,
|
||||
val bobArtistId: String,
|
||||
val bobAlbumId: String,
|
||||
val bobSongId: String,
|
||||
val aliceAudioBytes: ByteArray,
|
||||
val aliceFileSize: Long,
|
||||
) : AutoCloseable {
|
||||
override fun close() = db.close()
|
||||
}
|
||||
}
|
||||
@@ -1,410 +0,0 @@
|
||||
package win.taptap.musicmanager.subsonic
|
||||
|
||||
import io.ktor.client.HttpClient
|
||||
import io.ktor.client.request.get
|
||||
import io.ktor.client.statement.bodyAsText
|
||||
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.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.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
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.mood.MoodService
|
||||
import win.taptap.musicmanager.mood.MoodSessionTracker
|
||||
import win.taptap.musicmanager.scanner.CoverArtService
|
||||
import win.taptap.musicmanager.scanner.ScanStatus
|
||||
import win.taptap.musicmanager.subsonic.routes.subsonicRoutes
|
||||
import win.taptap.musicmanager.transcoding.FfmpegTranscoder
|
||||
import win.taptap.musicmanager.util.IdGenerator
|
||||
|
||||
class MoodRoutesTest {
|
||||
|
||||
@TempDir
|
||||
lateinit var tempDir: Path
|
||||
|
||||
@Test
|
||||
fun `creating a mood generates a private music-only playlist`() {
|
||||
clearSessions()
|
||||
seededContext().use { seed ->
|
||||
testApplication {
|
||||
setupApp(seed)
|
||||
val auth = credentials("alice", "alice-pw")
|
||||
|
||||
val mood = client.createMood(auth, "Focus", listOf(seed.aliceAmbient1), target = 10)
|
||||
val id = mood.string("id")
|
||||
assertEquals(1, mood.int("seedCount"))
|
||||
assertTrue(mood.string("generatedAt").isNotBlank())
|
||||
|
||||
val entries = mood.ids("entry")
|
||||
assertTrue(seed.aliceAmbient1 in entries)
|
||||
assertTrue(seed.aliceAmbient2 in entries)
|
||||
assertFalse(seed.bobSong in entries)
|
||||
assertFalse(seed.longformSong in entries)
|
||||
|
||||
// A long-form song is not a valid mood seed and must not enter the mix.
|
||||
val bookish = client.createMood(auth, "Bookish", listOf(seed.longformSong), target = 5)
|
||||
assertEquals(0, bookish.int("seedCount"))
|
||||
assertEquals(0, bookish.ids("entry").size)
|
||||
|
||||
val playlist = parseBody(
|
||||
client.get("/rest/getPlaylist?$auth&id=$id").bodyAsText(),
|
||||
)["playlist"]!!.jsonObject
|
||||
assertEquals("Focus", playlist.string("name"))
|
||||
assertEquals(entries.size, playlist["entry"]!!.jsonArray.size)
|
||||
|
||||
val bobAuth = credentials("bob", "bob-pw")
|
||||
val bobMoods = parseBody(client.get("/rest/getMoods?$bobAuth").bodyAsText())["moods"]!!.jsonObject
|
||||
assertEquals(0, bobMoods["mood"]?.jsonArray?.size ?: 0)
|
||||
|
||||
val denied = parseBody(client.get("/rest/getPlaylist?$bobAuth&id=$id").bodyAsText())
|
||||
assertEquals(70, denied["error"]!!.jsonObject["code"]!!.jsonPrimitive.int)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `promoting a playlist keeps its id and rejects song edits`() {
|
||||
clearSessions()
|
||||
seededContext().use { seed ->
|
||||
testApplication {
|
||||
setupApp(seed)
|
||||
val auth = credentials("alice", "alice-pw")
|
||||
|
||||
val playlist = parseBody(
|
||||
client.get(
|
||||
"/rest/createPlaylist?$auth&name=Road&songId=${seed.aliceAmbient1}&songId=${seed.aliceAmbient2}",
|
||||
).bodyAsText(),
|
||||
)["playlist"]!!.jsonObject
|
||||
val id = playlist.string("id")
|
||||
|
||||
val promoted = parseBody(
|
||||
client.get("/rest/promotePlaylistToMood?$auth&playlistId=$id&targetSize=10").bodyAsText(),
|
||||
)["mood"]!!.jsonObject
|
||||
assertEquals(id, promoted.string("id"))
|
||||
assertEquals(2, promoted.int("seedCount"))
|
||||
assertEquals(2, promoted.ids("seed").size)
|
||||
assertTrue(seed.aliceAmbient1 in promoted.ids("entry"))
|
||||
|
||||
val edit = parseBody(
|
||||
client.get(
|
||||
"/rest/updatePlaylist?$auth&playlistId=$id&songIdToAdd=${seed.aliceRock}",
|
||||
).bodyAsText(),
|
||||
)
|
||||
assertEquals(50, edit["error"]!!.jsonObject["code"]!!.jsonPrimitive.int)
|
||||
|
||||
val bobAuth = credentials("bob", "bob-pw")
|
||||
val denied = parseBody(client.get("/rest/getPlaylist?$bobAuth&id=$id").bodyAsText())
|
||||
assertEquals(70, denied["error"]!!.jsonObject["code"]!!.jsonPrimitive.int)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `star pins to the active mood and unstar removes only star seeds`() {
|
||||
clearSessions()
|
||||
seededContext().use { seed ->
|
||||
testApplication {
|
||||
setupApp(seed)
|
||||
val auth = credentials("alice", "alice-pw")
|
||||
|
||||
val mood = client.createMood(
|
||||
auth,
|
||||
"Pinned",
|
||||
listOf(seed.aliceAmbient1),
|
||||
target = 10,
|
||||
expandRelated = false,
|
||||
)
|
||||
val id = mood.string("id")
|
||||
|
||||
// Opening the mood makes it active.
|
||||
client.get("/rest/getPlaylist?$auth&id=$id").bodyAsText()
|
||||
|
||||
val star = parseBody(client.get("/rest/star?$auth&id=${seed.aliceAmbient2}").bodyAsText())
|
||||
assertEquals("ok", star.string("status"))
|
||||
|
||||
val afterStar = parseBody(client.get("/rest/getMood?$auth&id=$id").bodyAsText())["mood"]!!.jsonObject
|
||||
assertEquals(2, afterStar.int("seedCount"))
|
||||
assertTrue(seed.aliceAmbient2 in afterStar.ids("seed"))
|
||||
assertTrue(seed.aliceAmbient1 in afterStar.ids("seed"))
|
||||
|
||||
val refreshed = parseBody(client.get("/rest/refreshMood?$auth&id=$id").bodyAsText())["mood"]!!.jsonObject
|
||||
assertTrue(seed.aliceAmbient2 in refreshed.ids("entry"))
|
||||
|
||||
parseBody(client.get("/rest/unstar?$auth&id=${seed.aliceAmbient2}").bodyAsText())
|
||||
val afterUnstar = parseBody(client.get("/rest/getMood?$auth&id=$id").bodyAsText())["mood"]!!.jsonObject
|
||||
assertEquals(1, afterUnstar.int("seedCount"))
|
||||
assertTrue(seed.aliceAmbient1 in afterUnstar.ids("seed"))
|
||||
assertFalse(seed.aliceAmbient2 in afterUnstar.ids("seed"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `star without a session pins moods that already contain the song`() {
|
||||
clearSessions()
|
||||
seededContext().use { seed ->
|
||||
testApplication {
|
||||
setupApp(seed)
|
||||
val auth = credentials("alice", "alice-pw")
|
||||
|
||||
val mood = client.createMood(auth, "Related", listOf(seed.aliceAmbient1), target = 10)
|
||||
val id = mood.string("id")
|
||||
assertTrue(seed.aliceAmbient2 in mood.ids("entry"))
|
||||
|
||||
// No getPlaylist call: there is no active mood session.
|
||||
parseBody(client.get("/rest/star?$auth&id=${seed.aliceAmbient2}").bodyAsText())
|
||||
|
||||
val afterStar = parseBody(client.get("/rest/getMood?$auth&id=$id").bodyAsText())["mood"]!!.jsonObject
|
||||
assertEquals(2, afterStar.int("seedCount"))
|
||||
assertTrue(seed.aliceAmbient2 in afterStar.ids("seed"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun ApplicationTestBuilder.setupApp(seed: Seed) {
|
||||
application {
|
||||
install(ContentNegotiation) {
|
||||
json(Json { ignoreUnknownKeys = true; encodeDefaults = true })
|
||||
}
|
||||
install(PartialContent)
|
||||
routing {
|
||||
subsonicRoutes(
|
||||
users = seed.users,
|
||||
library = seed.library,
|
||||
coverArtService = seed.coverArt,
|
||||
transcoder = FfmpegTranscoder("ffmpeg"),
|
||||
moodService = MoodService(CoroutineScope(Dispatchers.Unconfined)),
|
||||
startScan = { false },
|
||||
scanStatus = { ScanStatus(false, 0) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 aliceAmbient3 = seedSong(
|
||||
db, 1, "Alpha", "Focus One", "Second Wind",
|
||||
"Alpha/Focus One/02.mp3", "Ambient", 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,
|
||||
aliceAmbient3 = aliceAmbient3,
|
||||
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[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 suspend fun HttpClient.createMood(
|
||||
auth: String,
|
||||
name: String,
|
||||
seeds: List<String>,
|
||||
target: Int,
|
||||
expandRelated: Boolean = true,
|
||||
): JsonObject {
|
||||
val seedParams = seeds.joinToString("") { "&songId=$it" }
|
||||
val body = get(
|
||||
"/rest/createMood?$auth&name=$name$seedParams&targetSize=$target&expandRelated=$expandRelated",
|
||||
).bodyAsText()
|
||||
return parseBody(body)["mood"]!!.jsonObject
|
||||
}
|
||||
|
||||
private fun clearSessions() {
|
||||
MoodSessionTracker.clear("alice")
|
||||
MoodSessionTracker.clear("bob")
|
||||
}
|
||||
|
||||
private fun credentials(user: String, password: String): String {
|
||||
val salt = "test-salt"
|
||||
return "u=$user&t=${SubsonicAuthenticator.md5Hex(password + salt)}&s=$salt"
|
||||
}
|
||||
|
||||
private fun parseBody(body: String): JsonObject =
|
||||
Json.parseToJsonElement(body).jsonObject["subsonic-response"]!!.jsonObject
|
||||
|
||||
private fun JsonObject.string(name: String): String =
|
||||
this[name]!!.jsonPrimitive.content
|
||||
|
||||
private fun JsonObject.int(name: String): Int =
|
||||
this[name]!!.jsonPrimitive.int
|
||||
|
||||
private fun JsonObject.ids(name: String): List<String> =
|
||||
this[name]!!.jsonArray.map { it.jsonObject["id"]!!.jsonPrimitive.content }
|
||||
|
||||
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 aliceAmbient3: String,
|
||||
val bobSong: String,
|
||||
val longformSong: String,
|
||||
) : AutoCloseable {
|
||||
override fun close() = db.close()
|
||||
}
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
package win.taptap.musicmanager.subsonic
|
||||
|
||||
import io.ktor.http.Parameters
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNull
|
||||
import win.taptap.musicmanager.config.UserAccount
|
||||
import win.taptap.musicmanager.config.UsersConfig
|
||||
|
||||
class SubsonicAuthTest {
|
||||
|
||||
private val users = UsersConfig(
|
||||
listOf(
|
||||
UserAccount("alice", "secret", admin = true, folders = setOf(1)),
|
||||
UserAccount("bob", "hunter2", admin = false, folders = setOf(1)),
|
||||
),
|
||||
)
|
||||
private val authenticator = SubsonicAuthenticator(users)
|
||||
|
||||
@Test
|
||||
fun `accepts token authentication`() {
|
||||
val salt = "s4lt"
|
||||
val token = SubsonicAuthenticator.md5Hex("secret$salt")
|
||||
|
||||
val user = authenticator.authenticate(params("u" to "alice", "t" to token, "s" to salt))
|
||||
|
||||
assertEquals("alice", user?.name)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `accepts plaintext password authentication`() {
|
||||
assertEquals("bob", authenticator.authenticate(params("u" to "bob", "p" to "hunter2"))?.name)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `accepts enc-prefixed hex password authentication`() {
|
||||
val encoded = "enc:" + "secret".toByteArray().joinToString("") { "%02x".format(it) }
|
||||
|
||||
assertEquals("alice", authenticator.authenticate(params("u" to "alice", "p" to encoded))?.name)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `rejects wrong credentials and malformed requests`() {
|
||||
val salt = "s4lt"
|
||||
assertNull(authenticator.authenticate(params("u" to "alice", "t" to "wrong", "s" to salt)))
|
||||
assertNull(authenticator.authenticate(params("u" to "alice", "p" to "wrong")))
|
||||
assertNull(authenticator.authenticate(params("u" to "nobody", "p" to "secret")))
|
||||
assertNull(authenticator.authenticate(params("p" to "secret")))
|
||||
assertNull(authenticator.authenticate(params("u" to "alice")))
|
||||
assertNull(authenticator.authenticate(params("u" to "alice", "p" to "enc:zz")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `token takes precedence over password`() {
|
||||
val salt = "s4lt"
|
||||
val token = SubsonicAuthenticator.md5Hex("secret$salt")
|
||||
|
||||
val user = authenticator.authenticate(
|
||||
params("u" to "alice", "t" to token, "s" to salt, "p" to "wrong"),
|
||||
)
|
||||
|
||||
assertEquals("alice", user?.name)
|
||||
}
|
||||
|
||||
private fun params(vararg pairs: Pair<String, String>): Parameters = Parameters.build {
|
||||
pairs.forEach { (key, value) -> append(key, value) }
|
||||
}
|
||||
}
|
||||
@@ -1,212 +0,0 @@
|
||||
package win.taptap.musicmanager.subsonic
|
||||
|
||||
import io.ktor.client.request.get
|
||||
import io.ktor.client.statement.bodyAsText
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import io.ktor.serialization.kotlinx.json.json
|
||||
import io.ktor.server.application.install
|
||||
import io.ktor.server.plugins.contentnegotiation.ContentNegotiation
|
||||
import io.ktor.server.routing.routing
|
||||
import io.ktor.server.testing.ApplicationTestBuilder
|
||||
import io.ktor.server.testing.testApplication
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
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.junit.jupiter.api.io.TempDir
|
||||
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.mood.MoodService
|
||||
import win.taptap.musicmanager.scanner.CoverArtService
|
||||
import win.taptap.musicmanager.scanner.ScanStatus
|
||||
import win.taptap.musicmanager.subsonic.routes.subsonicRoutes
|
||||
import win.taptap.musicmanager.transcoding.FfmpegTranscoder
|
||||
|
||||
class SystemRoutesTest {
|
||||
|
||||
@TempDir
|
||||
lateinit var tempDir: java.nio.file.Path
|
||||
|
||||
@Test
|
||||
fun `ping returns the OpenSubsonic envelope for both route variants`() = testApplication {
|
||||
setupApp()
|
||||
|
||||
for (path in listOf("/rest/ping", "/rest/ping.view")) {
|
||||
val response = client.get("$path?${credentials()}")
|
||||
assertEquals(HttpStatusCode.OK, response.status)
|
||||
|
||||
val body = parse(response.bodyAsText())
|
||||
assertEquals("ok", body.string("status"))
|
||||
assertEquals("1.16.1", body.string("version"))
|
||||
assertEquals("musicmanager", body.string("type"))
|
||||
assertEquals("0.1.0", body.string("serverVersion"))
|
||||
assertEquals("true", body.string("openSubsonic"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `wrong credentials return HTTP 200 with error code 40`() = testApplication {
|
||||
setupApp()
|
||||
|
||||
val response = client.get("/rest/ping?u=alice&p=wrong")
|
||||
|
||||
assertEquals(HttpStatusCode.OK, response.status)
|
||||
val body = parse(response.bodyAsText())
|
||||
assertEquals("failed", body.string("status"))
|
||||
assertEquals(40, body["error"]!!.jsonObject["code"]!!.jsonPrimitive.int)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `getLicense reports a valid license`() = testApplication {
|
||||
setupApp()
|
||||
|
||||
val body = parse(client.get("/rest/getLicense?${credentials()}").bodyAsText())
|
||||
|
||||
assertEquals("true", body["license"]!!.jsonObject["valid"]!!.jsonPrimitive.content)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `getOpenSubsonicExtensions declares formPost songLyrics and transcodeOffset`() = testApplication {
|
||||
setupApp()
|
||||
|
||||
val body = parse(client.get("/rest/getOpenSubsonicExtensions?${credentials()}").bodyAsText())
|
||||
val extensions = body["openSubsonicExtensions"]!!.jsonArray
|
||||
val names = extensions.map { it.jsonObject["name"]!!.jsonPrimitive.content }
|
||||
|
||||
assertEquals(3, extensions.size)
|
||||
assertTrue("formPost" in names)
|
||||
assertTrue("songLyrics" in names)
|
||||
assertTrue("transcodeOffset" in names)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `startScan requires an admin user`() = testApplication {
|
||||
var started = false
|
||||
setupApp(startScan = { started = true; true })
|
||||
|
||||
val adminResponse = client.get("/rest/startScan?${credentials(user = "alice")}")
|
||||
assertEquals("ok", parse(adminResponse.bodyAsText()).string("status"))
|
||||
assertTrue(started)
|
||||
|
||||
started = false
|
||||
val userResponse = client.get("/rest/startScan?${credentials(user = "bob")}")
|
||||
val body = parse(userResponse.bodyAsText())
|
||||
assertEquals("failed", body.string("status"))
|
||||
assertEquals(50, body["error"]!!.jsonObject["code"]!!.jsonPrimitive.int)
|
||||
assertFalse(started)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `getScanStatus returns the scanner state`() = testApplication {
|
||||
setupApp(scanStatus = { ScanStatus(scanning = true, count = 42) })
|
||||
|
||||
val body = parse(client.get("/rest/getScanStatus?${credentials()}").bodyAsText())
|
||||
val status = body["scanStatus"]!!.jsonObject
|
||||
|
||||
assertEquals("true", status["scanning"]!!.jsonPrimitive.content)
|
||||
assertEquals(42, status["count"]!!.jsonPrimitive.int)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `getUser returns roles and folder ids with admin restrictions`() = testApplication {
|
||||
setupApp()
|
||||
|
||||
val own = parse(client.get("/rest/getUser?${credentials()}&username=alice").bodyAsText())
|
||||
val alice = own["user"]!!.jsonObject
|
||||
assertEquals("alice", alice.string("username"))
|
||||
assertEquals("true", alice["adminRole"]!!.jsonPrimitive.content)
|
||||
assertEquals("true", alice["downloadRole"]!!.jsonPrimitive.content)
|
||||
assertEquals(listOf(1), alice["folder"]!!.jsonArray.map { it.jsonPrimitive.int })
|
||||
|
||||
val other = parse(client.get("/rest/getUser?${credentials()}&username=bob").bodyAsText())
|
||||
assertEquals("bob", other["user"]!!.jsonObject.string("username"))
|
||||
|
||||
val forbidden = parse(client.get("/rest/getUser?${credentials(user = "bob")}&username=alice").bodyAsText())
|
||||
assertEquals("failed", forbidden.string("status"))
|
||||
assertEquals(50, forbidden["error"]!!.jsonObject["code"]!!.jsonPrimitive.int)
|
||||
|
||||
val missing = parse(client.get("/rest/getUser?${credentials()}").bodyAsText())
|
||||
assertEquals(10, missing["error"]!!.jsonObject["code"]!!.jsonPrimitive.int)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `jukebox and internet radio endpoints return valid empty responses`() = testApplication {
|
||||
setupApp()
|
||||
|
||||
val jukebox = parse(client.get("/rest/jukeboxControl?${credentials()}&action=status").bodyAsText())
|
||||
assertEquals("false", jukebox["jukeboxStatus"]!!.jsonObject["playing"]!!.jsonPrimitive.content)
|
||||
|
||||
val radio = parse(client.get("/rest/getInternetRadioStations?${credentials()}").bodyAsText())
|
||||
assertEquals(
|
||||
0,
|
||||
radio["internetRadioStations"]!!.jsonObject["internetRadioStation"]!!.jsonArray.size,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `getUsers is admin only`() = testApplication {
|
||||
setupApp()
|
||||
|
||||
val admin = parse(client.get("/rest/getUsers?${credentials()}").bodyAsText())
|
||||
val names = admin["users"]!!.jsonObject["user"]!!.jsonArray
|
||||
.map { it.jsonObject.string("username") }
|
||||
assertEquals(setOf("alice", "bob"), names.toSet())
|
||||
|
||||
val regular = parse(client.get("/rest/getUsers?${credentials(user = "bob")}").bodyAsText())
|
||||
assertEquals(50, regular["error"]!!.jsonObject["code"]!!.jsonPrimitive.int)
|
||||
}
|
||||
|
||||
private fun ApplicationTestBuilder.setupApp(
|
||||
startScan: () -> Boolean = { false },
|
||||
scanStatus: () -> ScanStatus = { ScanStatus(false, 0) },
|
||||
) {
|
||||
application {
|
||||
install(ContentNegotiation) {
|
||||
json(Json { ignoreUnknownKeys = true; encodeDefaults = true })
|
||||
}
|
||||
routing {
|
||||
subsonicRoutes(
|
||||
users = users,
|
||||
library = LibraryConfig(
|
||||
listOf(MusicFolder(1, "Music", FolderType.MUSIC, tempDir)),
|
||||
),
|
||||
coverArtService = CoverArtService(tempDir.resolve("data")),
|
||||
transcoder = FfmpegTranscoder("ffmpeg"),
|
||||
moodService = MoodService(CoroutineScope(Dispatchers.Unconfined)),
|
||||
startScan = startScan,
|
||||
scanStatus = scanStatus,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun credentials(user: String = "alice"): String {
|
||||
val salt = "test-salt"
|
||||
val password = if (user == "alice") "secret" else "hunter2"
|
||||
val token = SubsonicAuthenticator.md5Hex(password + salt)
|
||||
return "u=$user&t=$token&s=$salt"
|
||||
}
|
||||
|
||||
private fun parse(body: String): JsonObject =
|
||||
Json.parseToJsonElement(body).jsonObject["subsonic-response"]!!.jsonObject
|
||||
|
||||
private fun JsonObject.string(key: String): String = this[key]!!.jsonPrimitive.content
|
||||
|
||||
private val users = UsersConfig(
|
||||
listOf(
|
||||
UserAccount("alice", "secret", admin = true, folders = setOf(1)),
|
||||
UserAccount("bob", "hunter2", admin = false, folders = setOf(1)),
|
||||
),
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user