feat: add browsing and media endpoints
- user-scoped getMusicFolders, getIndexes, getArtists, getArtist, getAlbum and getSong - search3 with pagination, literal matching and empty/wildcard queries - stream and download with Range support and RFC 5987 filenames - getCoverArt with cached size variants and visibility checks - V2 migration for per-user album and artist ratings
This commit is contained in:
1 parent
1f73d901d5
commit
643ee42f09
14 files changed
+1364
-4
No files matched your search
@@ -37,7 +37,7 @@ class DatabaseFactoryTest {
|
||||
}
|
||||
}
|
||||
}
|
||||
assertEquals(1, migrations)
|
||||
assertTrue(migrations >= 2, "Expected at least the V1 and V2 migrations")
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,409 @@
|
||||
package win.taptap.musicmanager.subsonic
|
||||
|
||||
import io.ktor.client.request.get
|
||||
import io.ktor.client.request.header
|
||||
import io.ktor.client.statement.bodyAsBytes
|
||||
import io.ktor.client.statement.bodyAsText
|
||||
import io.ktor.http.HttpHeaders
|
||||
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.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.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.assertNotNull
|
||||
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.scanner.CoverArtService
|
||||
import win.taptap.musicmanager.scanner.ScanStatus
|
||||
import win.taptap.musicmanager.subsonic.routes.subsonicRoutes
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
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[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()
|
||||
}
|
||||
}
|
||||
@@ -19,13 +19,21 @@ 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.scanner.CoverArtService
|
||||
import win.taptap.musicmanager.scanner.ScanStatus
|
||||
import win.taptap.musicmanager.subsonic.routes.subsonicRoutes
|
||||
|
||||
class SystemRoutesTest {
|
||||
|
||||
@TempDir
|
||||
lateinit var tempDir: java.nio.file.Path
|
||||
|
||||
@Test
|
||||
fun `ping returns the OpenSubsonic envelope for both route variants`() = testApplication {
|
||||
setupApp()
|
||||
@@ -115,7 +123,15 @@ class SystemRoutesTest {
|
||||
json(Json { ignoreUnknownKeys = true; encodeDefaults = true })
|
||||
}
|
||||
routing {
|
||||
subsonicRoutes(users = users, startScan = startScan, scanStatus = scanStatus)
|
||||
subsonicRoutes(
|
||||
users = users,
|
||||
library = LibraryConfig(
|
||||
listOf(MusicFolder(1, "Music", FolderType.MUSIC, tempDir)),
|
||||
),
|
||||
coverArtService = CoverArtService(tempDir.resolve("data")),
|
||||
startScan = startScan,
|
||||
scanStatus = scanStatus,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user