feat: bootstrap MusicManager with scanner and Subsonic auth
- Gradle/Kotlin/Ktor project on JVM 21 with ShadowJar - SQLite WAL, Flyway migrations and config-driven users/folders - deterministic IDs, MP3 tag extraction, cover cache and delta scanner - OpenSubsonic JSON envelope with token/password authentication - system endpoints: ping, license, extensions, scan status
This commit is contained in:
1 parent
961341b449
commit
e194badefb
45 files changed
+4079
-126
No files matched your search
@@ -0,0 +1,76 @@
|
||||
package win.taptap.musicmanager
|
||||
|
||||
import java.awt.Color
|
||||
import java.awt.image.BufferedImage
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Path
|
||||
import javax.imageio.ImageIO
|
||||
import org.junit.jupiter.api.Assumptions
|
||||
|
||||
/** Generates test audio locally; no audio files are committed to the repository. */
|
||||
object TestAudio {
|
||||
|
||||
private val ffmpegAvailable: Boolean by lazy {
|
||||
runCatching {
|
||||
val process = ProcessBuilder("ffmpeg", "-version")
|
||||
.redirectErrorStream(true)
|
||||
.start()
|
||||
process.inputStream.readBytes()
|
||||
process.waitFor() == 0
|
||||
}.getOrDefault(false)
|
||||
}
|
||||
|
||||
fun assumeFfmpeg() {
|
||||
Assumptions.assumeTrue(ffmpegAvailable, "ffmpeg is not available on this machine")
|
||||
}
|
||||
|
||||
fun createMp3(
|
||||
target: Path,
|
||||
metadata: Map<String, String> = emptyMap(),
|
||||
cover: Path? = null,
|
||||
seconds: Int = 1,
|
||||
) {
|
||||
Files.createDirectories(target.parent)
|
||||
|
||||
val command = mutableListOf(
|
||||
"ffmpeg", "-nostdin", "-hide_banner", "-loglevel", "error", "-y",
|
||||
"-f", "lavfi", "-i", "anullsrc=r=44100:cl=mono",
|
||||
)
|
||||
|
||||
if (cover != null) {
|
||||
command += listOf("-i", cover.toString(), "-map", "0:a", "-map", "1:v", "-c:v", "copy")
|
||||
} else {
|
||||
command += listOf("-map", "0:a")
|
||||
}
|
||||
|
||||
command += listOf("-c:a", "libmp3lame", "-b:a", "128k", "-t", seconds.toString())
|
||||
metadata.forEach { (key, value) -> command += listOf("-metadata", "$key=$value") }
|
||||
if (cover != null) {
|
||||
command += listOf(
|
||||
"-metadata:s:v", "title=Album cover",
|
||||
"-metadata:s:v", "comment=Cover (front)",
|
||||
)
|
||||
}
|
||||
command += listOf("-id3v2_version", "3", target.toString())
|
||||
|
||||
val process = ProcessBuilder(command)
|
||||
.redirectErrorStream(true)
|
||||
.start()
|
||||
val output = process.inputStream.bufferedReader().readText()
|
||||
val exit = process.waitFor()
|
||||
check(exit == 0) { "ffmpeg failed ($exit): $output" }
|
||||
}
|
||||
|
||||
fun writePng(target: Path, width: Int = 32, height: Int = 32, color: Color = Color.RED) {
|
||||
Files.createDirectories(target.parent)
|
||||
val image = BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)
|
||||
val graphics = image.createGraphics()
|
||||
try {
|
||||
graphics.color = color
|
||||
graphics.fillRect(0, 0, width, height)
|
||||
} finally {
|
||||
graphics.dispose()
|
||||
}
|
||||
ImageIO.write(image, "png", target.toFile())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package win.taptap.musicmanager.config
|
||||
|
||||
import java.nio.file.Path
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFailsWith
|
||||
|
||||
class AppConfigTest {
|
||||
|
||||
@Test
|
||||
fun `uses documented defaults`() {
|
||||
val config = AppConfig.fromEnv(emptyMap())
|
||||
|
||||
assertEquals(8080, config.port)
|
||||
assertEquals(Path.of("./data"), config.dataDir)
|
||||
assertEquals(Path.of("./config/library.yaml"), config.libraryConfigPath)
|
||||
assertEquals(Path.of("./config/users.yaml"), config.usersFile)
|
||||
assertEquals("ffmpeg", config.ffmpegPath)
|
||||
assertEquals(Path.of("./data/musicmanager.db"), config.databasePath)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `reads overrides from the environment`() {
|
||||
val config = AppConfig.fromEnv(
|
||||
mapOf(
|
||||
"PORT" to "9090",
|
||||
"DATA_DIR" to "/var/lib/musicmanager",
|
||||
"LIBRARY_CONFIG" to "/etc/musicmanager/library.yaml",
|
||||
"USERS_FILE" to "/run/secrets/users.yaml",
|
||||
"FFMPEG_PATH" to "/usr/bin/ffmpeg",
|
||||
),
|
||||
)
|
||||
|
||||
assertEquals(9090, config.port)
|
||||
assertEquals(Path.of("/var/lib/musicmanager"), config.dataDir)
|
||||
assertEquals(Path.of("/etc/musicmanager/library.yaml"), config.libraryConfigPath)
|
||||
assertEquals(Path.of("/run/secrets/users.yaml"), config.usersFile)
|
||||
assertEquals("/usr/bin/ffmpeg", config.ffmpegPath)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `rejects a malformed port`() {
|
||||
assertFailsWith<IllegalArgumentException> {
|
||||
AppConfig.fromEnv(mapOf("PORT" to "not-a-number"))
|
||||
}
|
||||
assertFailsWith<IllegalArgumentException> {
|
||||
AppConfig.fromEnv(mapOf("PORT" to "70000"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package win.taptap.musicmanager.config
|
||||
|
||||
import java.nio.file.Files
|
||||
import kotlin.io.path.createTempDirectory
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFailsWith
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
class LibraryConfigTest {
|
||||
|
||||
private val validYaml = """
|
||||
library:
|
||||
folders:
|
||||
- id: 1
|
||||
name: "Music"
|
||||
type: music
|
||||
path: "./media/music"
|
||||
- id: 10
|
||||
name: "Long-form"
|
||||
type: longform
|
||||
path: "./media/longform"
|
||||
""".trimIndent()
|
||||
|
||||
@Test
|
||||
fun `parses folders and resolves absolute paths`() {
|
||||
val config = LibraryConfig.parse(validYaml)
|
||||
|
||||
assertEquals(2, config.folders.size)
|
||||
assertEquals(setOf(10), config.longformFolderIds)
|
||||
assertEquals(FolderType.MUSIC, config.folders[0].type)
|
||||
assertEquals(FolderType.LONGFORM, config.folders[1].type)
|
||||
assertTrue(config.folders[0].path.isAbsolute)
|
||||
assertEquals(1, config.byId(1)?.id)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `rejects duplicate folder ids`() {
|
||||
val yaml = """
|
||||
library:
|
||||
folders:
|
||||
- id: 1
|
||||
name: A
|
||||
type: music
|
||||
path: /music/a
|
||||
- id: 1
|
||||
name: B
|
||||
type: music
|
||||
path: /music/b
|
||||
""".trimIndent()
|
||||
|
||||
assertFailsWith<IllegalArgumentException> { LibraryConfig.parse(yaml) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `rejects duplicate folder paths`() {
|
||||
val yaml = """
|
||||
library:
|
||||
folders:
|
||||
- id: 1
|
||||
name: A
|
||||
type: music
|
||||
path: /music/a
|
||||
- id: 2
|
||||
name: B
|
||||
type: music
|
||||
path: /music/a
|
||||
""".trimIndent()
|
||||
|
||||
assertFailsWith<IllegalArgumentException> { LibraryConfig.parse(yaml) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `rejects unknown folder types`() {
|
||||
val yaml = """
|
||||
library:
|
||||
folders:
|
||||
- id: 1
|
||||
name: A
|
||||
type: video
|
||||
path: /music/a
|
||||
""".trimIndent()
|
||||
|
||||
assertFailsWith<IllegalArgumentException> { LibraryConfig.parse(yaml) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `validatePaths fails for a missing root`() {
|
||||
val root = createTempDirectory("musicmanager-test")
|
||||
try {
|
||||
val yaml = """
|
||||
library:
|
||||
folders:
|
||||
- id: 1
|
||||
name: A
|
||||
type: music
|
||||
path: "${root.resolve("missing")}"
|
||||
""".trimIndent()
|
||||
|
||||
assertFailsWith<IllegalArgumentException> {
|
||||
LibraryConfig.parse(yaml).validatePaths()
|
||||
}
|
||||
} finally {
|
||||
root.toFile().deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `validatePaths accepts existing readable roots`() {
|
||||
val root = createTempDirectory("musicmanager-test")
|
||||
try {
|
||||
val music = Files.createDirectories(root.resolve("music"))
|
||||
val yaml = """
|
||||
library:
|
||||
folders:
|
||||
- id: 1
|
||||
name: A
|
||||
type: music
|
||||
path: "$music"
|
||||
""".trimIndent()
|
||||
|
||||
LibraryConfig.parse(yaml).validatePaths()
|
||||
} finally {
|
||||
root.toFile().deleteRecursively()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package win.taptap.musicmanager.config
|
||||
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFailsWith
|
||||
import kotlin.test.assertFalse
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
class UsersConfigTest {
|
||||
|
||||
private val library = LibraryConfig.parse(
|
||||
"""
|
||||
library:
|
||||
folders:
|
||||
- id: 1
|
||||
name: "Music A"
|
||||
type: music
|
||||
path: /music/a
|
||||
- id: 2
|
||||
name: "Music B"
|
||||
type: music
|
||||
path: /music/b
|
||||
- id: 10
|
||||
name: "Long-form"
|
||||
type: longform
|
||||
path: /longform
|
||||
""".trimIndent(),
|
||||
)
|
||||
|
||||
private val usersYaml = """
|
||||
users:
|
||||
- name: alice
|
||||
password: "secret-a"
|
||||
admin: true
|
||||
folders: [1]
|
||||
- name: bob
|
||||
password: "secret-b"
|
||||
folders: [1, 2]
|
||||
""".trimIndent()
|
||||
|
||||
@Test
|
||||
fun `parses users and shares long-form folders`() {
|
||||
val users = UsersConfig.parse(usersYaml)
|
||||
users.validateAgainst(library)
|
||||
|
||||
val alice = users.byName("alice")!!
|
||||
val bob = users.byName("bob")!!
|
||||
|
||||
assertTrue(alice.admin)
|
||||
assertFalse(bob.admin)
|
||||
assertEquals(setOf(1, 10), alice.visibleFolderIds(library))
|
||||
assertEquals(setOf(1, 2, 10), bob.visibleFolderIds(library))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `rejects missing passwords`() {
|
||||
val yaml = """
|
||||
users:
|
||||
- name: alice
|
||||
folders: [1]
|
||||
""".trimIndent()
|
||||
|
||||
assertFailsWith<IllegalArgumentException> { UsersConfig.parse(yaml) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `rejects duplicate names`() {
|
||||
val yaml = """
|
||||
users:
|
||||
- name: alice
|
||||
password: a
|
||||
folders: [1]
|
||||
- name: alice
|
||||
password: b
|
||||
folders: [2]
|
||||
""".trimIndent()
|
||||
|
||||
assertFailsWith<IllegalArgumentException> { UsersConfig.parse(yaml) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `rejects unknown folder references`() {
|
||||
val users = UsersConfig.parse(
|
||||
"""
|
||||
users:
|
||||
- name: alice
|
||||
password: a
|
||||
folders: [99]
|
||||
""".trimIndent(),
|
||||
)
|
||||
|
||||
assertFailsWith<IllegalArgumentException> { users.validateAgainst(library) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `rejects a user with no visible folders`() {
|
||||
val emptyLibrary = LibraryConfig.parse(
|
||||
"""
|
||||
library:
|
||||
folders:
|
||||
- id: 1
|
||||
name: "Music"
|
||||
type: music
|
||||
path: /music
|
||||
""".trimIndent(),
|
||||
)
|
||||
val users = UsersConfig.parse(
|
||||
"""
|
||||
users:
|
||||
- name: alice
|
||||
password: a
|
||||
folders: []
|
||||
""".trimIndent(),
|
||||
)
|
||||
|
||||
assertFailsWith<IllegalArgumentException> { users.validateAgainst(emptyLibrary) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `does not expose passwords in toString`() {
|
||||
val alice = UsersConfig.parse(usersYaml).byName("alice")!!
|
||||
|
||||
assertFalse(alice.toString().contains("secret-a"))
|
||||
assertTrue(alice.toString().contains("password=***"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package win.taptap.musicmanager.db
|
||||
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Path
|
||||
import java.time.Instant
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertTrue
|
||||
import org.jetbrains.exposed.sql.insert
|
||||
import org.jetbrains.exposed.sql.selectAll
|
||||
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
|
||||
|
||||
class DatabaseFactoryTest {
|
||||
|
||||
@TempDir
|
||||
lateinit var tempDir: Path
|
||||
|
||||
@Test
|
||||
fun `migrates the schema and configures sqlite`() {
|
||||
val db = DatabaseFactory.connect(appConfig())
|
||||
try {
|
||||
assertEquals("wal", pragma(db, "journal_mode"))
|
||||
assertEquals("1", pragma(db, "foreign_keys"))
|
||||
|
||||
val migrations = db.dataSource.connection.use { connection ->
|
||||
connection.createStatement().use { statement ->
|
||||
statement.executeQuery("SELECT COUNT(*) FROM flyway_schema_history").use { result ->
|
||||
result.next()
|
||||
result.getInt(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
assertEquals(1, migrations)
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `syncs folders and users idempotently`() {
|
||||
val db = DatabaseFactory.connect(appConfig())
|
||||
try {
|
||||
val library = library()
|
||||
val users = UsersConfig(
|
||||
listOf(
|
||||
UserAccount("alice", "pw", admin = true, folders = setOf(1)),
|
||||
UserAccount("bob", "pw", admin = false, folders = setOf(1)),
|
||||
),
|
||||
)
|
||||
|
||||
ConfigRepository.sync(library, users)
|
||||
ConfigRepository.sync(library, users)
|
||||
|
||||
transaction(db.database) {
|
||||
assertEquals(2L, MusicFoldersTable.selectAll().count())
|
||||
assertEquals(2L, UsersTable.selectAll().count())
|
||||
assertEquals(
|
||||
"longform",
|
||||
MusicFoldersTable.selectAll()
|
||||
.where { MusicFoldersTable.id eq 10 }
|
||||
.single()[MusicFoldersTable.type],
|
||||
)
|
||||
}
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `removing a user cascades their per-user state`() {
|
||||
val db = DatabaseFactory.connect(appConfig())
|
||||
try {
|
||||
val library = library()
|
||||
val aliceAndBob = UsersConfig(
|
||||
listOf(
|
||||
UserAccount("alice", "pw", admin = true, folders = setOf(1)),
|
||||
UserAccount("bob", "pw", admin = false, folders = setOf(1)),
|
||||
),
|
||||
)
|
||||
ConfigRepository.sync(library, aliceAndBob)
|
||||
insertSong(db, folderId = 1)
|
||||
|
||||
transaction(db.database) {
|
||||
UserSongStateTable.insert {
|
||||
it[userName] = "alice"
|
||||
it[songId] = "sg-1"
|
||||
it[playCount] = 3
|
||||
it[starredAt] = Instant.now().toString()
|
||||
}
|
||||
assertEquals(1L, UserSongStateTable.selectAll().count())
|
||||
}
|
||||
|
||||
ConfigRepository.sync(
|
||||
library,
|
||||
UsersConfig(listOf(UserAccount("bob", "pw", admin = false, folders = setOf(1)))),
|
||||
)
|
||||
|
||||
transaction(db.database) {
|
||||
assertEquals(0L, UserSongStateTable.selectAll().count())
|
||||
assertEquals(1L, UsersTable.selectAll().count())
|
||||
}
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `removing a folder cascades its songs`() {
|
||||
val db = DatabaseFactory.connect(appConfig())
|
||||
try {
|
||||
val library = library()
|
||||
val users = UsersConfig(listOf(UserAccount("alice", "pw", admin = true, folders = setOf(1))))
|
||||
ConfigRepository.sync(library, users)
|
||||
insertSong(db, folderId = 1)
|
||||
|
||||
transaction(db.database) {
|
||||
assertEquals(1L, SongsTable.selectAll().count())
|
||||
}
|
||||
|
||||
ConfigRepository.sync(
|
||||
LibraryConfig(library.folders.filter { it.id == 10 }),
|
||||
UsersConfig(listOf(UserAccount("alice", "pw", admin = true, folders = emptySet()))),
|
||||
)
|
||||
|
||||
transaction(db.database) {
|
||||
assertEquals(0L, SongsTable.selectAll().count())
|
||||
assertEquals(1L, MusicFoldersTable.selectAll().count())
|
||||
}
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
|
||||
private fun appConfig(): AppConfig = AppConfig(
|
||||
port = 8080,
|
||||
dataDir = tempDir.resolve("data"),
|
||||
libraryConfigPath = tempDir.resolve("library.yaml"),
|
||||
usersFile = tempDir.resolve("users.yaml"),
|
||||
ffmpegPath = "ffmpeg",
|
||||
)
|
||||
|
||||
private fun library(): LibraryConfig {
|
||||
val music = Files.createDirectories(tempDir.resolve("music"))
|
||||
val longform = Files.createDirectories(tempDir.resolve("longform"))
|
||||
return LibraryConfig(
|
||||
listOf(
|
||||
MusicFolder(1, "Music", FolderType.MUSIC, music),
|
||||
MusicFolder(10, "Long-form", FolderType.LONGFORM, longform),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
private fun insertSong(db: DatabaseHandle, folderId: Int) {
|
||||
val now = Instant.now().toString()
|
||||
transaction(db.database) {
|
||||
ArtistsTable.insert {
|
||||
it[id] = "ar-1"
|
||||
it[name] = "Artist"
|
||||
it[sortName] = "artist"
|
||||
it[searchText] = "artist"
|
||||
}
|
||||
AlbumsTable.insert {
|
||||
it[id] = "al-1"
|
||||
it[name] = "Album"
|
||||
it[createdAt] = now
|
||||
it[searchText] = "album"
|
||||
}
|
||||
SongsTable.insert {
|
||||
it[id] = "sg-1"
|
||||
it[albumId] = "al-1"
|
||||
it[this.folderId] = folderId
|
||||
it[title] = "Song"
|
||||
it[displayArtist] = "Artist"
|
||||
it[albumName] = "Album"
|
||||
it[duration] = 120
|
||||
it[bitRate] = 128
|
||||
it[size] = 1024
|
||||
it[suffix] = "mp3"
|
||||
it[contentType] = "audio/mpeg"
|
||||
it[relativePath] = "artist/album/song.mp3"
|
||||
it[fileMtime] = 0
|
||||
it[createdAt] = now
|
||||
it[searchText] = "song"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun pragma(db: DatabaseHandle, name: String): String =
|
||||
db.dataSource.connection.use { connection ->
|
||||
connection.createStatement().use { statement ->
|
||||
statement.executeQuery("PRAGMA $name").use { result ->
|
||||
assertTrue(result.next(), "PRAGMA $name returned no row")
|
||||
result.getString(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package win.taptap.musicmanager.scanner
|
||||
|
||||
import java.awt.Color
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Path
|
||||
import javax.imageio.ImageIO
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFalse
|
||||
import kotlin.test.assertNotNull
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.test.assertTrue
|
||||
import org.junit.jupiter.api.io.TempDir
|
||||
import win.taptap.musicmanager.TestAudio
|
||||
|
||||
class CoverArtServiceTest {
|
||||
|
||||
@TempDir
|
||||
lateinit var tempDir: Path
|
||||
|
||||
@Test
|
||||
fun `stores and resizes a cover`() {
|
||||
val service = CoverArtService(tempDir)
|
||||
val cover = tempDir.resolve("cover.png")
|
||||
TestAudio.writePng(cover, 64, 64)
|
||||
|
||||
assertTrue(service.saveCover(ALBUM_ID, Files.readAllBytes(cover)))
|
||||
|
||||
val stored = service.coverFile(ALBUM_ID)
|
||||
assertNotNull(stored)
|
||||
assertTrue(Files.size(stored) > 0)
|
||||
|
||||
val resized = service.resizedCover(ALBUM_ID, 24)
|
||||
assertNotNull(resized)
|
||||
val image = ImageIO.read(resized.toFile())
|
||||
assertEquals(24, image.width)
|
||||
assertEquals(24, image.height)
|
||||
|
||||
// Unchanged bytes are accepted without creating a new file.
|
||||
assertTrue(service.saveCover(ALBUM_ID, Files.readAllBytes(cover)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `invalid image data is rejected`() {
|
||||
val service = CoverArtService(tempDir)
|
||||
|
||||
assertFalse(service.saveCover(ALBUM_ID, "not an image".toByteArray()))
|
||||
assertFalse(service.saveCover(ALBUM_ID, ByteArray(0)))
|
||||
assertNull(service.coverFile(ALBUM_ID))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `changing the cover invalidates resized variants`() {
|
||||
val service = CoverArtService(tempDir)
|
||||
val red = tempDir.resolve("red.png")
|
||||
val blue = tempDir.resolve("blue.png")
|
||||
TestAudio.writePng(red, color = Color.RED)
|
||||
TestAudio.writePng(blue, color = Color.BLUE)
|
||||
|
||||
service.saveCover(ALBUM_ID, Files.readAllBytes(red))
|
||||
val resized = service.resizedCover(ALBUM_ID, 16)
|
||||
assertNotNull(resized)
|
||||
|
||||
service.saveCover(ALBUM_ID, Files.readAllBytes(blue))
|
||||
|
||||
assertFalse(Files.exists(resized), "Old resized variant should be removed")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `finds sidecar artwork next to the audio file`() {
|
||||
val service = CoverArtService(tempDir)
|
||||
val audio = tempDir.resolve("Artist/Album/song.mp3")
|
||||
Files.createDirectories(audio.parent)
|
||||
Files.writeString(audio, "audio")
|
||||
|
||||
assertNull(service.findSidecarCover(audio))
|
||||
|
||||
val cover = audio.parent.resolve("folder.jpg")
|
||||
TestAudio.writePng(cover)
|
||||
|
||||
assertEquals(cover, service.findSidecarCover(audio))
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val ALBUM_ID = "al-0123456789abcdef01234567"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
package win.taptap.musicmanager.scanner
|
||||
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Path
|
||||
import java.nio.file.attribute.FileTime
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNotNull
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.test.assertTrue
|
||||
import org.jetbrains.exposed.sql.insert
|
||||
import org.jetbrains.exposed.sql.selectAll
|
||||
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.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.SongGenresTable
|
||||
import win.taptap.musicmanager.db.SongsTable
|
||||
import win.taptap.musicmanager.db.UserSongStateTable
|
||||
import win.taptap.musicmanager.util.IdGenerator
|
||||
|
||||
class MediaScannerTest {
|
||||
|
||||
@TempDir
|
||||
lateinit var tempDir: Path
|
||||
|
||||
private lateinit var music: Path
|
||||
private lateinit var longform: Path
|
||||
|
||||
@Test
|
||||
fun `scans, caches covers and keeps user state across metadata updates`() {
|
||||
TestAudio.assumeFfmpeg()
|
||||
|
||||
val db = DatabaseFactory.connect(appConfig())
|
||||
try {
|
||||
val library = library()
|
||||
ConfigRepository.sync(library, users())
|
||||
|
||||
val albumDir = Files.createDirectories(music.resolve("Album Artist/Album"))
|
||||
TestAudio.writePng(albumDir.resolve("cover.jpg"))
|
||||
val one = albumDir.resolve("01 - One.mp3")
|
||||
val two = albumDir.resolve("02 - Two.mp3")
|
||||
TestAudio.createMp3(one, metadata = albumMetadata("One", "1/2"))
|
||||
TestAudio.createMp3(two, metadata = albumMetadata("Two", "2/2"))
|
||||
|
||||
val book = longform.resolve("Author/Book/01 - Chapter One.mp3")
|
||||
TestAudio.createMp3(
|
||||
book,
|
||||
metadata = mapOf(
|
||||
"title" to "Chapter One",
|
||||
"artist" to "Author",
|
||||
"album_artist" to "Author",
|
||||
"album" to "Book",
|
||||
),
|
||||
)
|
||||
Files.writeString(music.resolve("notes.txt"), "not audio")
|
||||
|
||||
val scanner = MediaScanner(library, CoverArtService(tempDir.resolve("data")))
|
||||
|
||||
val first = scanner.scanBlocking()
|
||||
assertNull(first.error)
|
||||
assertEquals(3L, first.count)
|
||||
assertEquals(3L, MediaRepository.countSongs())
|
||||
|
||||
val albumId = IdGenerator.albumId("Album Artist", "Album")
|
||||
val songId = IdGenerator.songId(1, "Album Artist/Album/01 - One.mp3")
|
||||
|
||||
transaction(db.database) {
|
||||
assertEquals(3L, SongsTable.selectAll().count())
|
||||
assertEquals(2L, AlbumsTable.selectAll().count())
|
||||
assertEquals(2L, ArtistsTable.selectAll().count())
|
||||
assertEquals(2L, SongGenresTable.selectAll().count())
|
||||
|
||||
val album = AlbumsTable.selectAll()
|
||||
.where { AlbumsTable.id eq albumId }
|
||||
.single()
|
||||
assertEquals(albumId, album[AlbumsTable.coverArt])
|
||||
|
||||
val song = SongsTable.selectAll()
|
||||
.where { SongsTable.id eq songId }
|
||||
.single()
|
||||
assertEquals(128, song[SongsTable.bitRate])
|
||||
assertEquals("mp3", song[SongsTable.suffix])
|
||||
assertEquals("audio/mpeg", song[SongsTable.contentType])
|
||||
assertEquals(Files.size(one), song[SongsTable.size])
|
||||
|
||||
UserSongStateTable.insert {
|
||||
it[userName] = "alice"
|
||||
it[this.songId] = songId
|
||||
it[playCount] = 7
|
||||
}
|
||||
}
|
||||
|
||||
assertTrue(Files.isRegularFile(tempDir.resolve("data/covers/$albumId.jpg")))
|
||||
|
||||
// Touching the file forces re-extraction; the play count must survive.
|
||||
Files.setLastModifiedTime(one, FileTime.fromMillis(System.currentTimeMillis() + 2_000))
|
||||
val second = scanner.scanBlocking()
|
||||
assertEquals(3L, second.count)
|
||||
assertEquals(3L, MediaRepository.countSongs())
|
||||
|
||||
transaction(db.database) {
|
||||
val state = UserSongStateTable.selectAll()
|
||||
.where { UserSongStateTable.songId eq songId }
|
||||
.single()
|
||||
assertEquals(7, state[UserSongStateTable.playCount])
|
||||
}
|
||||
|
||||
// Removing the whole album and the long-form book cleans up orphans.
|
||||
Files.delete(two)
|
||||
Files.delete(one)
|
||||
Files.delete(book)
|
||||
|
||||
val third = scanner.scanBlocking()
|
||||
assertNull(third.error)
|
||||
assertEquals(0L, third.count) // notes.txt is ignored, the three MP3s are gone
|
||||
assertEquals(0L, MediaRepository.countSongs())
|
||||
|
||||
transaction(db.database) {
|
||||
assertEquals(0L, SongsTable.selectAll().count())
|
||||
assertEquals(0L, AlbumsTable.selectAll().count())
|
||||
assertEquals(0L, ArtistsTable.selectAll().count())
|
||||
}
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unchanged files are skipped on a second scan`() {
|
||||
TestAudio.assumeFfmpeg()
|
||||
val db = DatabaseFactory.connect(appConfig())
|
||||
try {
|
||||
val library = library()
|
||||
ConfigRepository.sync(library, users())
|
||||
|
||||
val file = music.resolve("Artist/Album/song.mp3")
|
||||
TestAudio.createMp3(file)
|
||||
TestAudio.writePng(file.parent.resolve("cover.jpg"))
|
||||
|
||||
val scanner = MediaScanner(library, CoverArtService(tempDir.resolve("data")))
|
||||
scanner.scanBlocking()
|
||||
|
||||
val albumId = IdGenerator.albumId("Artist", "Album")
|
||||
transaction(db.database) {
|
||||
val album = AlbumsTable.selectAll()
|
||||
.where { AlbumsTable.id eq albumId }
|
||||
.single()
|
||||
assertEquals(albumId, album[AlbumsTable.coverArt])
|
||||
}
|
||||
assertTrue(Files.isRegularFile(tempDir.resolve("data/covers/$albumId.jpg")))
|
||||
|
||||
val before = transaction(db.database) {
|
||||
SongsTable.selectAll().single()[SongsTable.fileMtime]
|
||||
}
|
||||
val mtimeBefore = Files.getLastModifiedTime(file).toMillis()
|
||||
assertEquals(mtimeBefore, before)
|
||||
|
||||
val second = scanner.scanBlocking()
|
||||
assertEquals(1L, second.count)
|
||||
assertEquals(1L, MediaRepository.countSongs())
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
|
||||
private fun albumMetadata(title: String, track: String): Map<String, String> = mapOf(
|
||||
"title" to title,
|
||||
"artist" to "Album Artist",
|
||||
"album_artist" to "Album Artist",
|
||||
"album" to "Album",
|
||||
"track" to track,
|
||||
"genre" to "Rock",
|
||||
)
|
||||
|
||||
private fun appConfig(): AppConfig = AppConfig(
|
||||
port = 8080,
|
||||
dataDir = tempDir.resolve("data"),
|
||||
libraryConfigPath = tempDir.resolve("library.yaml"),
|
||||
usersFile = tempDir.resolve("users.yaml"),
|
||||
ffmpegPath = "ffmpeg",
|
||||
)
|
||||
|
||||
private fun library(): LibraryConfig {
|
||||
music = Files.createDirectories(tempDir.resolve("music"))
|
||||
longform = Files.createDirectories(tempDir.resolve("longform"))
|
||||
return LibraryConfig(
|
||||
listOf(
|
||||
MusicFolder(1, "Music", FolderType.MUSIC, music),
|
||||
MusicFolder(10, "Long-form", FolderType.LONGFORM, longform),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
private fun users(): UsersConfig = UsersConfig(
|
||||
listOf(UserAccount("alice", "pw", admin = true, folders = setOf(1))),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package win.taptap.musicmanager.scanner
|
||||
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Path
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNotNull
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.test.assertTrue
|
||||
import org.junit.jupiter.api.io.TempDir
|
||||
import win.taptap.musicmanager.TestAudio
|
||||
import win.taptap.musicmanager.util.IdGenerator
|
||||
|
||||
class Mp3TagExtractorTest {
|
||||
|
||||
@TempDir
|
||||
lateinit var tempDir: Path
|
||||
|
||||
@Test
|
||||
fun `reads ID3 tags and separates album artist from track artists`() {
|
||||
TestAudio.assumeFfmpeg()
|
||||
val root = Files.createDirectories(tempDir.resolve("music"))
|
||||
val file = root.resolve("Album Artist/Album/02 - Song.mp3")
|
||||
TestAudio.createMp3(
|
||||
file,
|
||||
metadata = mapOf(
|
||||
"title" to "Test Song",
|
||||
"artist" to "Track Artist",
|
||||
"album_artist" to "Album Artist",
|
||||
"album" to "Test Album",
|
||||
"track" to "2/10",
|
||||
"disc" to "1/2",
|
||||
"date" to "2021-05-01",
|
||||
"genre" to "Rock",
|
||||
),
|
||||
)
|
||||
|
||||
val track = assertNotNull(Mp3TagExtractor().extract(1, root, file))
|
||||
|
||||
assertEquals("Test Song", track.title)
|
||||
assertEquals("Album Artist/Album/02 - Song.mp3", track.relativePath)
|
||||
assertEquals("Test Album", track.albumTitle)
|
||||
assertEquals("Track Artist", track.displayArtist)
|
||||
assertEquals(listOf("Track Artist"), track.artists.map { it.name })
|
||||
assertEquals(listOf("Album Artist"), track.albumArtists.map { it.name })
|
||||
assertEquals("Album Artist", track.albumArtists.first().name)
|
||||
assertEquals(2, track.trackNumber)
|
||||
assertEquals(1, track.discNumber)
|
||||
assertEquals(2021, track.year)
|
||||
assertEquals(listOf("Rock"), track.genres)
|
||||
assertTrue(track.durationSeconds in 1..4)
|
||||
assertTrue(track.bitRate > 0)
|
||||
assertEquals(Files.size(file), track.size)
|
||||
assertEquals("mp3", track.suffix)
|
||||
assertEquals("audio/mpeg", track.contentType)
|
||||
|
||||
assertEquals(
|
||||
IdGenerator.songId(1, "Album Artist/Album/02 - Song.mp3"),
|
||||
track.songId,
|
||||
)
|
||||
assertEquals(
|
||||
IdGenerator.albumId("Album Artist", "Test Album"),
|
||||
track.albumId,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `falls back to the folder structure when tags are missing`() {
|
||||
TestAudio.assumeFfmpeg()
|
||||
val root = Files.createDirectories(tempDir.resolve("music"))
|
||||
val file = root.resolve("Artist/Album/song.mp3")
|
||||
TestAudio.createMp3(file)
|
||||
|
||||
val track = assertNotNull(Mp3TagExtractor().extract(1, root, file))
|
||||
|
||||
assertEquals("song", track.title)
|
||||
assertEquals("Album", track.albumTitle)
|
||||
assertEquals("Artist", track.displayArtist)
|
||||
assertEquals(listOf("Artist"), track.albumArtists.map { it.name })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `reads embedded artwork and sidecar lyrics`() {
|
||||
TestAudio.assumeFfmpeg()
|
||||
val root = Files.createDirectories(tempDir.resolve("music"))
|
||||
val cover = root.resolve("cover.png")
|
||||
TestAudio.writePng(cover)
|
||||
val file = root.resolve("Artist/Album/song.mp3")
|
||||
TestAudio.createMp3(
|
||||
file,
|
||||
metadata = mapOf("title" to "Covered"),
|
||||
cover = cover,
|
||||
)
|
||||
Files.writeString(file.resolveSibling("song.lrc"), "[00:00.00]Hello")
|
||||
|
||||
val track = assertNotNull(Mp3TagExtractor().extract(1, root, file))
|
||||
|
||||
assertNotNull(track.coverBytes)
|
||||
assertTrue(track.coverBytes!!.isNotEmpty())
|
||||
assertEquals("[00:00.00]Hello", track.lyrics)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `ignores non-mp3 files`() {
|
||||
val root = Files.createDirectories(tempDir.resolve("music"))
|
||||
val file = root.resolve("song.flac")
|
||||
Files.writeString(file, "not audio")
|
||||
|
||||
assertNull(Mp3TagExtractor().extract(1, root, file))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
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) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
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.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 win.taptap.musicmanager.config.UserAccount
|
||||
import win.taptap.musicmanager.config.UsersConfig
|
||||
import win.taptap.musicmanager.scanner.ScanStatus
|
||||
import win.taptap.musicmanager.subsonic.routes.subsonicRoutes
|
||||
|
||||
class SystemRoutesTest {
|
||||
|
||||
@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)
|
||||
}
|
||||
|
||||
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, 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)),
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package win.taptap.musicmanager.util
|
||||
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNotEquals
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
class IdGeneratorTest {
|
||||
|
||||
@Test
|
||||
fun `normalization is NFC, trimmed, collapsed and lowercase`() {
|
||||
val decomposed = "Cafe\u0301 The Artist"
|
||||
assertEquals("café the artist", IdGenerator.normalize(decomposed))
|
||||
assertEquals(IdGenerator.normalize(" THE Artist "), IdGenerator.normalize("the artist"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `IDs are deterministic, prefixed and 24 hex characters`() {
|
||||
val first = IdGenerator.artistId("The Beatles")
|
||||
val second = IdGenerator.artistId("the beatles")
|
||||
|
||||
assertEquals(first, second)
|
||||
assertTrue(first.startsWith("ar-"))
|
||||
assertEquals(27, first.length)
|
||||
|
||||
val album = IdGenerator.albumId("The Beatles", "Abbey Road")
|
||||
assertTrue(album.startsWith("al-"))
|
||||
assertEquals(27, album.length)
|
||||
|
||||
val song = IdGenerator.songId(1, "The Beatles/Abbey Road/01 - Come Together.mp3")
|
||||
assertTrue(song.startsWith("sg-"))
|
||||
assertEquals(27, song.length)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `path separators do not change the song ID`() {
|
||||
val unix = IdGenerator.songId(1, "Artist/Album/song.mp3")
|
||||
val windows = IdGenerator.songId(1, "Artist\\Album\\song.mp3")
|
||||
val prefixed = IdGenerator.songId(1, "./Artist/Album/song.mp3")
|
||||
|
||||
assertEquals(unix, windows)
|
||||
assertEquals(unix, prefixed)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `folder and album changes produce different IDs`() {
|
||||
assertNotEquals(
|
||||
IdGenerator.songId(1, "Artist/Album/song.mp3"),
|
||||
IdGenerator.songId(2, "Artist/Album/song.mp3"),
|
||||
)
|
||||
assertNotEquals(
|
||||
IdGenerator.albumId("Artist", "Album"),
|
||||
IdGenerator.albumId("Artist", "Other Album"),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package win.taptap.musicmanager.util
|
||||
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class SortNamesTest {
|
||||
|
||||
@Test
|
||||
fun `moves leading articles to the end`() {
|
||||
assertEquals("Beatles, The", SortNames.of("The Beatles"))
|
||||
assertEquals("Perfect Circle, A", SortNames.of("A Perfect Circle"))
|
||||
assertEquals("Toten Hosen, Die", SortNames.of("Die Toten Hosen"))
|
||||
assertEquals("Mond, Le", SortNames.of("Le Mond"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `leaves names without articles untouched`() {
|
||||
assertEquals("Radiohead", SortNames.of("Radiohead"))
|
||||
assertEquals("", SortNames.of(" "))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `handles names that are only an article`() {
|
||||
assertEquals("The", SortNames.of("The"))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user