feat: rebuild AudioManager around downloadable moods
- V8 wipe migration and the shared song store keyed by YouTube video id - media store, indexer, downloader, recommendation top-up and refcounted GC - mood songs plus the recommendation lifecycle and mixed radio pools - new search, song and recommendation API; remove library/longform/seed routes - chart PVC/media env, docs, Nix, README and an end-to-end smoke test
This commit is contained in:
1 parent
50d8b6c580
commit
824eb36dd2
59 files changed
+3838
-5276
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -13,9 +13,11 @@ class AppConfigTest {
|
||||
|
||||
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("yt-dlp", config.ytDlpPath)
|
||||
assertEquals(Path.of("./data/media"), config.mediaDir)
|
||||
assertEquals(Path.of("./data/downloads"), config.downloadDir)
|
||||
assertEquals(Path.of("./data/musicmanager.db"), config.databasePath)
|
||||
}
|
||||
|
||||
@@ -25,17 +27,21 @@ class AppConfigTest {
|
||||
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",
|
||||
"YTDLP_PATH" to "/usr/local/bin/yt-dlp",
|
||||
"MEDIA_DIR" to "/mnt/media",
|
||||
"DOWNLOAD_DIR" to "/var/tmp/downloads",
|
||||
),
|
||||
)
|
||||
|
||||
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)
|
||||
assertEquals("/usr/local/bin/yt-dlp", config.ytDlpPath)
|
||||
assertEquals(Path.of("/mnt/media"), config.mediaDir)
|
||||
assertEquals(Path.of("/var/tmp/downloads"), config.downloadDir)
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -1,127 +0,0 @@
|
||||
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()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,48 +8,26 @@ 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)
|
||||
fun `parses users and ignores old folder assignments`() {
|
||||
val users = UsersConfig.parse(
|
||||
"""
|
||||
users:
|
||||
- name: alice
|
||||
password: "secret-a"
|
||||
admin: true
|
||||
folders: [1]
|
||||
- name: bob
|
||||
password: "secret-b"
|
||||
""".trimIndent(),
|
||||
)
|
||||
|
||||
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))
|
||||
assertEquals(2, users.users.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -57,7 +35,6 @@ class UsersConfigTest {
|
||||
val yaml = """
|
||||
users:
|
||||
- name: alice
|
||||
folders: [1]
|
||||
""".trimIndent()
|
||||
|
||||
assertFailsWith<IllegalArgumentException> { UsersConfig.parse(yaml) }
|
||||
@@ -69,56 +46,27 @@ class UsersConfigTest {
|
||||
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) }
|
||||
fun `rejects an empty user list`() {
|
||||
assertFailsWith<IllegalArgumentException> { UsersConfig.parse("users: []") }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `does not expose passwords in toString`() {
|
||||
val alice = UsersConfig.parse(usersYaml).byName("alice")!!
|
||||
val alice = UsersConfig.parse(
|
||||
"""
|
||||
users:
|
||||
- name: alice
|
||||
password: "secret-a"
|
||||
""".trimIndent(),
|
||||
).byName("alice")!!
|
||||
|
||||
assertFalse(alice.toString().contains("secret-a"))
|
||||
assertTrue(alice.toString().contains("password=***"))
|
||||
|
||||
@@ -3,20 +3,18 @@ package win.taptap.musicmanager.db
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Path
|
||||
import java.sql.DriverManager
|
||||
import org.flywaydb.core.Flyway
|
||||
import org.flywaydb.core.api.MigrationVersion
|
||||
import java.time.Instant
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFalse
|
||||
import kotlin.test.assertTrue
|
||||
import org.flywaydb.core.Flyway
|
||||
import org.flywaydb.core.api.MigrationVersion
|
||||
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
|
||||
|
||||
@@ -32,23 +30,24 @@ class DatabaseFactoryTest {
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
assertTrue(migrations >= 2, "Expected at least the V1 and V2 migrations")
|
||||
val migrations = queryInt(db, "SELECT COUNT(*) FROM flyway_schema_history")
|
||||
assertTrue(migrations >= 8, "Expected at least the V1..V8 migrations")
|
||||
|
||||
// The new schema exists and the mounted-library tables do not.
|
||||
assertTrue(tableExists(db, "songs"))
|
||||
assertTrue(tableExists(db, "mood_songs"))
|
||||
assertTrue(tableExists(db, "mood_recommendations"))
|
||||
assertTrue(tableExists(db, "download_jobs"))
|
||||
assertFalse(tableExists(db, "music_folders"))
|
||||
assertFalse(tableExists(db, "artists"))
|
||||
assertFalse(tableExists(db, "longform_progress"))
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
fun `upgrades legacy liked and downloaded recommendations`() {
|
||||
fun `V8 wipes content but keeps users and device tokens`() {
|
||||
val config = appConfig()
|
||||
Files.createDirectories(config.dataDir)
|
||||
val url = "jdbc:sqlite:${config.databasePath.toAbsolutePath()}"
|
||||
@@ -56,7 +55,7 @@ class DatabaseFactoryTest {
|
||||
Flyway.configure()
|
||||
.dataSource(url, null, null)
|
||||
.locations("classpath:db/migration")
|
||||
.target(MigrationVersion.fromVersion("4"))
|
||||
.target(MigrationVersion.fromVersion("7"))
|
||||
.load()
|
||||
.migrate()
|
||||
|
||||
@@ -66,62 +65,84 @@ class DatabaseFactoryTest {
|
||||
"INSERT INTO users (name, is_admin, updated_at) VALUES ('alice', 1, 'now')",
|
||||
)
|
||||
statement.executeUpdate(
|
||||
"INSERT INTO playlists (id, owner, name, created_at, changed_at) " +
|
||||
"VALUES ('pl-1', 'alice', 'Mood', 'now', 'now')",
|
||||
"INSERT INTO api_tokens " +
|
||||
"(id, user_name, token_hash, device_name, platform, created_at, last_used_at, expires_at) " +
|
||||
"VALUES ('tk-1', 'alice', 'hash', 'phone', 'android', 'now', 'now', 'later')",
|
||||
)
|
||||
statement.executeUpdate(
|
||||
"INSERT INTO moods (playlist_id) VALUES ('pl-1')",
|
||||
"INSERT INTO music_folders (id, name, type, root_path) VALUES (1, 'Music', 'music', '/m')",
|
||||
)
|
||||
statement.executeUpdate(
|
||||
"INSERT INTO mood_recommendations " +
|
||||
"(playlist_id, video_id, title, artist, state, first_seen, last_seen) " +
|
||||
"VALUES ('pl-1', 'v-1', 'Title', 'Artist', 'liked', 'now', 'now')",
|
||||
"INSERT INTO artists (id, name, sort_name, search_text) VALUES ('ar-1', 'Artist', 'artist', 'artist')",
|
||||
)
|
||||
statement.executeUpdate(
|
||||
"INSERT INTO albums (id, name, created_at, search_text) VALUES ('al-1', 'Album', 'now', 'album')",
|
||||
)
|
||||
statement.executeUpdate(
|
||||
"INSERT INTO songs " +
|
||||
"(id, album_id, folder_id, title, display_artist, album_name, duration, bit_rate, " +
|
||||
"size, suffix, content_type, relative_path, file_mtime, created_at, updated_at, search_text) " +
|
||||
"VALUES ('sg-1', 'al-1', 1, 'Song', 'Artist', 'Album', 120, 128, 10, 'mp3', " +
|
||||
"'audio/mpeg', 'a/b.mp3', 0, 'now', 'now', 'song')",
|
||||
)
|
||||
statement.executeUpdate(
|
||||
"INSERT INTO moods " +
|
||||
"(id, owner, name, genres, target_size, refresh_hours, yt_enabled, created_at, changed_at, seed_percent) " +
|
||||
"VALUES ('mo-1', 'alice', 'Focus', '[]', 30, 24, 1, 'now', 'now', 50)",
|
||||
)
|
||||
statement.executeUpdate(
|
||||
"INSERT INTO mood_seeds (mood_id, song_id, origin, added_at) VALUES ('mo-1', 'sg-1', 'manual', 'now')",
|
||||
)
|
||||
statement.executeUpdate(
|
||||
"INSERT INTO playback_sessions (id, user_name, mood_id, created_at, last_seen_at) " +
|
||||
"VALUES ('ps-1', 'alice', 'mo-1', 'now', 'now')",
|
||||
)
|
||||
statement.executeUpdate(
|
||||
"INSERT INTO playback_session_items " +
|
||||
"(session_id, position, song_id, state, queued_at, updated_at) " +
|
||||
"VALUES ('ps-1', 0, 'sg-1', 'queued', 'now', 'now')",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
val db = DatabaseFactory.connect(config)
|
||||
try {
|
||||
val state = db.dataSource.connection.use { connection ->
|
||||
connection.createStatement().use { statement ->
|
||||
statement.executeQuery(
|
||||
"SELECT state FROM mood_recommendations WHERE video_id = 'v-1'",
|
||||
).use { result ->
|
||||
result.next()
|
||||
result.getString(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
assertEquals("new", state)
|
||||
assertEquals(
|
||||
1,
|
||||
queryInt(db, "SELECT COUNT(*) FROM users WHERE name = 'alice'"),
|
||||
"Users must survive the wipe",
|
||||
)
|
||||
assertEquals(
|
||||
1,
|
||||
queryInt(db, "SELECT COUNT(*) FROM api_tokens WHERE id = 'tk-1'"),
|
||||
"Device tokens must survive the wipe",
|
||||
)
|
||||
assertEquals(0, queryInt(db, "SELECT COUNT(*) FROM songs"))
|
||||
assertEquals(0, queryInt(db, "SELECT COUNT(*) FROM moods"))
|
||||
assertEquals(0, queryInt(db, "SELECT COUNT(*) FROM playback_sessions"))
|
||||
assertTrue(tableExists(db, "mood_songs"))
|
||||
assertFalse(tableExists(db, "music_folders"))
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `syncs folders and users idempotently`() {
|
||||
fun `syncs 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)),
|
||||
UserAccount("alice", "pw", admin = true),
|
||||
UserAccount("bob", "pw", admin = false),
|
||||
),
|
||||
)
|
||||
|
||||
ConfigRepository.sync(library, users)
|
||||
ConfigRepository.sync(library, users)
|
||||
ConfigRepository.sync(users)
|
||||
ConfigRepository.sync(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()
|
||||
@@ -129,65 +150,69 @@ class DatabaseFactoryTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `removing a user cascades their per-user state`() {
|
||||
fun `removing a user cascades their moods and playback 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(
|
||||
UsersConfig(
|
||||
listOf(
|
||||
UserAccount("alice", "pw", admin = true),
|
||||
UserAccount("bob", "pw", admin = false),
|
||||
),
|
||||
),
|
||||
)
|
||||
ConfigRepository.sync(library, aliceAndBob)
|
||||
insertSong(db, folderId = 1)
|
||||
|
||||
val now = Instant.now().toString()
|
||||
val moodId = "mo-1"
|
||||
transaction(db.database) {
|
||||
UserSongStateTable.insert {
|
||||
SongsTable.insert {
|
||||
it[id] = "sg-1"
|
||||
it[videoId] = "video-1"
|
||||
it[title] = "Song"
|
||||
it[artist] = "Artist"
|
||||
it[relativePath] = "video-1/song.mp3"
|
||||
it[createdAt] = now
|
||||
it[updatedAt] = now
|
||||
}
|
||||
MoodsTable.insert {
|
||||
it[id] = moodId
|
||||
it[owner] = "alice"
|
||||
it[name] = "Focus"
|
||||
it[createdAt] = now
|
||||
it[changedAt] = now
|
||||
}
|
||||
MoodSongsTable.insert {
|
||||
it[this.moodId] = moodId
|
||||
it[songId] = "sg-1"
|
||||
it[addedAt] = now
|
||||
}
|
||||
PlaybackSessionsTable.insert {
|
||||
it[id] = "ps-1"
|
||||
it[userName] = "alice"
|
||||
it[this.moodId] = moodId
|
||||
it[createdAt] = now
|
||||
it[lastSeenAt] = now
|
||||
}
|
||||
SessionItemsTable.insert {
|
||||
it[sessionId] = "ps-1"
|
||||
it[position] = 0
|
||||
it[songId] = "sg-1"
|
||||
it[playCount] = 3
|
||||
it[starredAt] = Instant.now().toString()
|
||||
it[queuedAt] = now
|
||||
it[updatedAt] = now
|
||||
}
|
||||
assertEquals(1L, UserSongStateTable.selectAll().count())
|
||||
}
|
||||
|
||||
ConfigRepository.sync(
|
||||
library,
|
||||
UsersConfig(listOf(UserAccount("bob", "pw", admin = false, folders = setOf(1)))),
|
||||
UsersConfig(listOf(UserAccount("bob", "pw", admin = false))),
|
||||
)
|
||||
|
||||
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(0L, MoodsTable.selectAll().count())
|
||||
assertEquals(0L, MoodSongsTable.selectAll().count())
|
||||
assertEquals(0L, PlaybackSessionsTable.selectAll().count())
|
||||
// Songs are shared and have no owner, so they survive.
|
||||
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()
|
||||
}
|
||||
@@ -196,57 +221,10 @@ class DatabaseFactoryTest {
|
||||
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 ->
|
||||
@@ -256,4 +234,20 @@ class DatabaseFactoryTest {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun queryInt(db: DatabaseHandle, sql: String): Int =
|
||||
db.dataSource.connection.use { connection ->
|
||||
connection.createStatement().use { statement ->
|
||||
statement.executeQuery(sql).use { result ->
|
||||
assertTrue(result.next(), "$sql returned no row")
|
||||
result.getInt(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun tableExists(db: DatabaseHandle, name: String): Boolean =
|
||||
queryInt(
|
||||
db,
|
||||
"SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = '$name'",
|
||||
) > 0
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
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.assertFalse
|
||||
import kotlin.test.assertNotNull
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.test.assertTrue
|
||||
import org.junit.jupiter.api.io.TempDir
|
||||
import win.taptap.musicmanager.config.AppConfig
|
||||
import win.taptap.musicmanager.config.UserAccount
|
||||
import win.taptap.musicmanager.config.UsersConfig
|
||||
import win.taptap.musicmanager.media.MediaGcService
|
||||
import win.taptap.musicmanager.media.MediaStore
|
||||
import win.taptap.musicmanager.scanner.CoverArtService
|
||||
|
||||
class MoodRepositoryTest {
|
||||
|
||||
@TempDir
|
||||
lateinit var tempDir: Path
|
||||
|
||||
@Test
|
||||
fun `recommendation slots are promoted completed added and refilled`() {
|
||||
withDatabase { mediaStore, _ ->
|
||||
val mood = createMood(recommendationCount = 3)
|
||||
storeCandidates(mood.id, 5)
|
||||
|
||||
val promoted = MoodRepository.promoteCandidates(mood.id, 3)
|
||||
assertEquals(3, promoted.size)
|
||||
assertEquals(3, MoodRepository.activeCount(mood.id))
|
||||
assertEquals(
|
||||
2,
|
||||
MoodRepository.allRecommendations(mood.id).count { it.state == "new" },
|
||||
)
|
||||
|
||||
val first = promoted.first()
|
||||
val song = insertSong(mediaStore, "vid-${first.videoId}", "Track ${first.videoId}")
|
||||
assertEquals(
|
||||
RecommendationCompletion.READY,
|
||||
MoodRepository.completeDownload(mood.id, first.videoId, song.id),
|
||||
)
|
||||
assertEquals("ready", MoodRepository.recommendation(mood.id, first.videoId)?.state)
|
||||
|
||||
// Add turns the slot into a permanent mood song and frees it.
|
||||
assertEquals(
|
||||
RecommendationCompletion.ALREADY_ADDED,
|
||||
MoodRepository.markAdded(mood.id, first.videoId),
|
||||
)
|
||||
assertTrue(MoodRepository.songIds(mood.id).contains(song.id))
|
||||
assertEquals("added", MoodRepository.recommendation(mood.id, first.videoId)?.state)
|
||||
assertEquals(2, MoodRepository.activeCount(mood.id))
|
||||
|
||||
val refill = MoodRepository.promoteCandidates(mood.id, 1)
|
||||
assertEquals(1, refill.size)
|
||||
assertEquals(3, MoodRepository.activeCount(mood.id))
|
||||
|
||||
// Reject is permanent and frees the slot again.
|
||||
MoodRepository.markRejected(mood.id, refill.first().videoId)
|
||||
assertEquals(2, MoodRepository.activeCount(mood.id))
|
||||
assertEquals(
|
||||
"rejected",
|
||||
MoodRepository.recommendation(mood.id, refill.first().videoId)?.state,
|
||||
)
|
||||
assertTrue(MoodRepository.decidedVideoIds(mood.id).contains(refill.first().videoId))
|
||||
assertEquals(
|
||||
1,
|
||||
MoodRepository.allRecommendations(mood.id).count { it.state == "new" },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `decisions survive a discovery refresh`() {
|
||||
withDatabase { _, _ ->
|
||||
val mood = createMood(recommendationCount = 3)
|
||||
storeCandidates(mood.id, 3)
|
||||
val first = MoodRepository.promoteCandidates(mood.id, 1).single()
|
||||
MoodRepository.markRejected(mood.id, first.videoId)
|
||||
|
||||
// The same video must not come back as a hidden candidate.
|
||||
storeCandidates(mood.id, 3)
|
||||
assertEquals(
|
||||
"rejected",
|
||||
MoodRepository.recommendation(mood.id, first.videoId)?.state,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `download completion after a rejection does not attach the song`() {
|
||||
withDatabase { mediaStore, _ ->
|
||||
val mood = createMood(recommendationCount = 2)
|
||||
storeCandidates(mood.id, 2)
|
||||
val recommendation = MoodRepository.promoteCandidates(mood.id, 1).single()
|
||||
val song = insertSong(mediaStore, "vid-1", "One")
|
||||
|
||||
MoodRepository.markRejected(mood.id, recommendation.videoId)
|
||||
assertEquals(
|
||||
RecommendationCompletion.REJECTED,
|
||||
MoodRepository.completeDownload(mood.id, recommendation.videoId, song.id),
|
||||
)
|
||||
assertTrue(MoodRepository.songIds(mood.id).isEmpty())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `adding while downloading attaches exactly one mood song`() {
|
||||
withDatabase { mediaStore, _ ->
|
||||
val mood = createMood(recommendationCount = 2)
|
||||
storeCandidates(mood.id, 2)
|
||||
val recommendation = MoodRepository.promoteCandidates(mood.id, 1).single()
|
||||
val song = insertSong(mediaStore, "vid-1", "One")
|
||||
|
||||
// User presses Add while the download is still running.
|
||||
MoodRepository.markAdded(mood.id, recommendation.videoId)
|
||||
assertTrue(MoodRepository.songIds(mood.id).isEmpty())
|
||||
|
||||
assertEquals(
|
||||
RecommendationCompletion.ALREADY_ADDED,
|
||||
MoodRepository.completeDownload(mood.id, recommendation.videoId, song.id),
|
||||
)
|
||||
assertEquals(listOf(song.id), MoodRepository.songIds(mood.id))
|
||||
assertFalse(MoodRepository.addSong(mood.id, song.id, "recommendation"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `mood counts reflect songs and active recommendation states`() {
|
||||
withDatabase { mediaStore, _ ->
|
||||
val mood = createMood(recommendationCount = 3)
|
||||
val song = insertSong(mediaStore, "vid-1", "One")
|
||||
MoodRepository.addSong(mood.id, song.id, "search")
|
||||
storeCandidates(mood.id, 3)
|
||||
val promoted = MoodRepository.promoteCandidates(mood.id, 2)
|
||||
val ready = insertSong(mediaStore, "vid-ready", "Ready")
|
||||
MoodRepository.completeDownload(mood.id, promoted.first().videoId, ready.id)
|
||||
|
||||
val record = assertNotNull(MoodRepository.get(mood.id, "alice"))
|
||||
assertEquals(1, record.songCount)
|
||||
assertEquals(1, record.recommendationReady)
|
||||
assertEquals(1, record.recommendationDownloading)
|
||||
assertEquals(0, record.recommendationFailed)
|
||||
|
||||
MoodRepository.failRecommendation(mood.id, promoted.last().videoId, "boom", 3)
|
||||
val failed = assertNotNull(MoodRepository.get(mood.id, "alice"))
|
||||
assertEquals(0, failed.recommendationDownloading)
|
||||
assertEquals(1, failed.recommendationFailed)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `removing a song only detaches it`() {
|
||||
withDatabase { mediaStore, _ ->
|
||||
val mood = createMood(recommendationCount = 0)
|
||||
val song = insertSong(mediaStore, "vid-1", "One")
|
||||
MoodRepository.addSong(mood.id, song.id, "search")
|
||||
|
||||
assertTrue(MoodRepository.removeSong(mood.id, song.id))
|
||||
assertTrue(MoodRepository.songIds(mood.id).isEmpty())
|
||||
assertNotNull(SongRepository.byId(song.id))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `GC keeps shared or playing files and deletes unreferenced ones`() {
|
||||
withDatabase { mediaStore, gc ->
|
||||
val firstMood = createMood(recommendationCount = 0, name = "First")
|
||||
val secondMood = createMood(recommendationCount = 0, name = "Second")
|
||||
val song = insertSong(mediaStore, "vid-1", "One")
|
||||
val file = assertNotNull(mediaStore.file(song))
|
||||
assertTrue(Files.isRegularFile(file))
|
||||
|
||||
MoodRepository.addSong(firstMood.id, song.id, "search")
|
||||
MoodRepository.addSong(secondMood.id, song.id, "search")
|
||||
|
||||
MoodRepository.removeSong(firstMood.id, song.id)
|
||||
assertFalse(gc.collect(song.id), "The second mood still references the song")
|
||||
assertTrue(Files.isRegularFile(file))
|
||||
|
||||
// An open playback session protects the track even after detach.
|
||||
val now = Instant.now().toString()
|
||||
val session = RadioRepository.createSession("alice", secondMood.id, now)
|
||||
RadioRepository.append(session.id, listOf(song.id))
|
||||
MoodRepository.removeSong(secondMood.id, song.id)
|
||||
assertFalse(gc.collect(song.id), "An open session still references the song")
|
||||
|
||||
RadioRepository.close(session.id, "alice")
|
||||
assertTrue(gc.collect(song.id))
|
||||
assertNull(SongRepository.byId(song.id))
|
||||
assertFalse(Files.exists(mediaStore.root.resolve("vid-1")))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a ready recommendation protects its file`() {
|
||||
withDatabase { mediaStore, gc ->
|
||||
val mood = createMood(recommendationCount = 2)
|
||||
storeCandidates(mood.id, 2)
|
||||
val recommendation = MoodRepository.promoteCandidates(mood.id, 1).single()
|
||||
val song = insertSong(mediaStore, "vid-1", "One")
|
||||
MoodRepository.completeDownload(mood.id, recommendation.videoId, song.id)
|
||||
|
||||
assertFalse(gc.collect(song.id))
|
||||
MoodRepository.markRejected(mood.id, recommendation.videoId)
|
||||
assertTrue(gc.collect(song.id))
|
||||
}
|
||||
}
|
||||
|
||||
private fun withDatabase(block: (MediaStore, MediaGcService) -> Unit) {
|
||||
val handle = DatabaseFactory.connect(appConfig())
|
||||
try {
|
||||
ConfigRepository.sync(UsersConfig(listOf(UserAccount("alice", "pw", admin = true))))
|
||||
val store = MediaStore(Files.createDirectories(tempDir.resolve("media")))
|
||||
val gc = MediaGcService(store, CoverArtService(tempDir.resolve("data")))
|
||||
block(store, gc)
|
||||
} finally {
|
||||
handle.close()
|
||||
}
|
||||
}
|
||||
|
||||
private fun createMood(recommendationCount: Int, name: String = "Focus"): MoodRecord =
|
||||
MoodRepository.create(
|
||||
owner = "alice",
|
||||
name = name,
|
||||
description = null,
|
||||
query = null,
|
||||
genres = emptyList(),
|
||||
collectionPercent = 50,
|
||||
recommendationCount = recommendationCount,
|
||||
refreshHours = 24,
|
||||
)
|
||||
|
||||
private fun storeCandidates(moodId: String, count: Int) {
|
||||
MoodRepository.storeCandidates(
|
||||
moodId,
|
||||
(1..count).map { index ->
|
||||
RecommendationUpsert(
|
||||
videoId = "v-$index",
|
||||
title = "Track $index",
|
||||
artist = "Artist $index",
|
||||
album = null,
|
||||
duration = 180,
|
||||
thumbnail = null,
|
||||
)
|
||||
},
|
||||
Instant.now().toString(),
|
||||
)
|
||||
}
|
||||
|
||||
private fun insertSong(
|
||||
mediaStore: MediaStore,
|
||||
videoId: String,
|
||||
title: String,
|
||||
): SongRecord {
|
||||
val file = mediaStore.target(videoId, title)
|
||||
Files.createDirectories(file.parent)
|
||||
Files.write(file, "fake-mp3".toByteArray())
|
||||
return SongRepository.upsert(
|
||||
SongUpsert(
|
||||
videoId = videoId,
|
||||
title = title,
|
||||
artist = "Artist",
|
||||
album = null,
|
||||
duration = 180,
|
||||
bitRate = 128,
|
||||
size = Files.size(file),
|
||||
relativePath = mediaStore.root.relativize(file).joinToString("/") { it.toString() },
|
||||
fileMtime = Files.getLastModifiedTime(file).toMillis(),
|
||||
thumbnail = null,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
private fun appConfig(): AppConfig = AppConfig(
|
||||
port = 8080,
|
||||
dataDir = tempDir.resolve("data"),
|
||||
usersFile = tempDir.resolve("users.yaml"),
|
||||
ffmpegPath = "ffmpeg",
|
||||
)
|
||||
}
|
||||
@@ -31,19 +31,42 @@ class DiscoveryServiceTest {
|
||||
assertEquals(YtCandidate("c", "Loud", "Gamma", null, 90, null), parsed[2])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `parses a single resolved video`() {
|
||||
val json = """
|
||||
{"id":"dQw4w9WgXcQ","title":"Rick Astley - Never Gonna Give You Up (Official Video)",
|
||||
"channel":"Rick Astley","duration":213,"thumbnail":"http://t/x.jpg"}
|
||||
""".trimIndent()
|
||||
|
||||
assertEquals(
|
||||
YtCandidate(
|
||||
videoId = "dQw4w9WgXcQ",
|
||||
title = "Never Gonna Give You Up",
|
||||
artist = "Rick Astley",
|
||||
album = null,
|
||||
duration = 213,
|
||||
thumbnail = "http://t/x.jpg",
|
||||
),
|
||||
parseYtVideo(json),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `malformed search output yields no candidates`() {
|
||||
assertTrue(parseYtSearchOutput("").isEmpty())
|
||||
assertTrue(parseYtSearchOutput("not json").isEmpty())
|
||||
assertTrue(parseYtSearchOutput("""{"entries": "nope"}""").isEmpty())
|
||||
assertEquals(null, parseYtVideo("not json"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `music length keeps songs and unknown durations but drops long mixes`() {
|
||||
fun `music length keeps tracks between 30 seconds and 10 minutes`() {
|
||||
assertTrue(isMusicLength(null))
|
||||
assertTrue(isMusicLength(45))
|
||||
assertTrue(isMusicLength(30))
|
||||
assertTrue(isMusicLength(200))
|
||||
assertFalse(isMusicLength(30))
|
||||
assertTrue(isMusicLength(600))
|
||||
assertFalse(isMusicLength(29))
|
||||
assertFalse(isMusicLength(601))
|
||||
assertFalse(isMusicLength(21 * 60))
|
||||
}
|
||||
|
||||
@@ -67,7 +90,7 @@ class DiscoveryServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `queries combine text seed artists and genres`() {
|
||||
fun `queries combine text collection artists and genres`() {
|
||||
val mood = mood(query = "late night", genres = listOf("Ambient", "Jazz"))
|
||||
val queries = buildQueries(mood, listOf("Alpha", "Beta", "Alpha"))
|
||||
|
||||
@@ -80,15 +103,13 @@ class DiscoveryServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `seed artists and library matches score higher`() {
|
||||
fun `collection artists score higher`() {
|
||||
val candidate = YtCandidate("v", "Focus Two", "Beta", duration = 200)
|
||||
|
||||
val plain = scoreCandidate(candidate, listOf("Alpha"), "focus", matched = false)
|
||||
val seedArtist = scoreCandidate(candidate, listOf("Beta"), "focus", matched = false)
|
||||
val matched = scoreCandidate(candidate, listOf("Alpha"), "focus", matched = true)
|
||||
val plain = scoreCandidate(candidate, listOf("Alpha"), "focus")
|
||||
val seedArtist = scoreCandidate(candidate, listOf("Beta"), "focus")
|
||||
|
||||
assertTrue(seedArtist > plain)
|
||||
assertTrue(matched > plain)
|
||||
}
|
||||
|
||||
private fun mood(
|
||||
@@ -101,15 +122,16 @@ class DiscoveryServiceTest {
|
||||
description = null,
|
||||
query = query,
|
||||
genres = genres,
|
||||
targetSize = 30,
|
||||
seedPercent = 50,
|
||||
collectionPercent = 50,
|
||||
recommendationCount = 10,
|
||||
refreshHours = 24,
|
||||
ytEnabled = true,
|
||||
lastDiscoveryAt = null,
|
||||
createdAt = "2026-01-01T00:00:00Z",
|
||||
changedAt = "2026-01-01T00:00:00Z",
|
||||
lastError = null,
|
||||
seedCount = 0,
|
||||
newRecommendations = 0,
|
||||
songCount = 0,
|
||||
recommendationReady = 0,
|
||||
recommendationDownloading = 0,
|
||||
recommendationFailed = 0,
|
||||
)
|
||||
}
|
||||
@@ -6,35 +6,28 @@ import java.nio.file.Path
|
||||
import java.time.Instant
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNotEquals
|
||||
import kotlin.test.assertNotNull
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.test.assertTrue
|
||||
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
|
||||
import org.jetbrains.exposed.sql.insert
|
||||
import org.jetbrains.exposed.sql.insertIgnore
|
||||
import org.jetbrains.exposed.sql.update
|
||||
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.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.DownloadJobsTable
|
||||
import win.taptap.musicmanager.db.DownloadRepository
|
||||
import win.taptap.musicmanager.db.MoodRepository
|
||||
import win.taptap.musicmanager.db.MoodRecord
|
||||
import win.taptap.musicmanager.db.RecommendationUpsert
|
||||
import win.taptap.musicmanager.db.SongArtistsTable
|
||||
import win.taptap.musicmanager.db.SongGenresTable
|
||||
import win.taptap.musicmanager.db.SongsTable
|
||||
import win.taptap.musicmanager.util.IdGenerator
|
||||
import win.taptap.musicmanager.db.SongRepository
|
||||
import win.taptap.musicmanager.db.SongUpsert
|
||||
import win.taptap.musicmanager.media.MediaGcService
|
||||
import win.taptap.musicmanager.media.MediaStore
|
||||
import win.taptap.musicmanager.scanner.CoverArtService
|
||||
import win.taptap.musicmanager.scanner.Mp3TagExtractor
|
||||
import win.taptap.musicmanager.scanner.SongIndexer
|
||||
|
||||
class DownloadServiceTest {
|
||||
|
||||
@@ -42,377 +35,297 @@ class DownloadServiceTest {
|
||||
lateinit var tempDir: Path
|
||||
|
||||
@Test
|
||||
fun `downloaded tracks are promoted to recommendation matches and seeds`() {
|
||||
withDatabase { handle, library, users ->
|
||||
val mood = MoodRepository.create(
|
||||
owner = "alice",
|
||||
name = "Drei ???",
|
||||
description = null,
|
||||
query = null,
|
||||
genres = emptyList(),
|
||||
targetSize = 30,
|
||||
refreshHours = 24,
|
||||
ytEnabled = true,
|
||||
seedSongIds = emptyList(),
|
||||
)
|
||||
MoodRepository.storeRecommendations(
|
||||
mood.id,
|
||||
listOf(
|
||||
RecommendationUpsert(
|
||||
videoId = "v-1",
|
||||
title = "Neue Folge",
|
||||
artist = "Die drei ???",
|
||||
album = null,
|
||||
duration = 300,
|
||||
thumbnail = null,
|
||||
matchedSongId = null,
|
||||
),
|
||||
),
|
||||
"2026-01-01T00:00:00Z",
|
||||
)
|
||||
DownloadRepository.enqueue("alice", mood.id, "v-1", "Neue Folge", "Die drei ???")
|
||||
|
||||
var scanned = false
|
||||
val service = DownloadService(
|
||||
users = users,
|
||||
library = library,
|
||||
downloader = AudioDownloader { videoId, _, _, dir ->
|
||||
val file = dir.resolve("$videoId.mp3")
|
||||
Files.write(file, "fake-mp3".toByteArray())
|
||||
file
|
||||
},
|
||||
tempDir = tempDir.resolve("downloads"),
|
||||
startScan = {
|
||||
if (!scanned) {
|
||||
scanned = true
|
||||
insertSong(handle, "Die drei ???", "Neue Folge")
|
||||
}
|
||||
true
|
||||
},
|
||||
isScanning = { false },
|
||||
)
|
||||
fun `a manual download lands in the media store and attaches to the mood`() {
|
||||
TestAudio.assumeFfmpeg()
|
||||
withService { service, mediaStore, _ ->
|
||||
val mood = mood(recommendationCount = 0)
|
||||
DownloadRepository.enqueue("vid-manual", mood.id, DownloadRepository.KIND_SONG)
|
||||
|
||||
assertTrue(service.processOne())
|
||||
|
||||
val job = assertNotNull(DownloadRepository.forRecommendation("alice", mood.id, "v-1"))
|
||||
val job = assertNotNull(
|
||||
DownloadRepository.find(mood.id, "vid-manual", DownloadRepository.KIND_SONG),
|
||||
)
|
||||
assertEquals("done", job.state)
|
||||
val songId = assertNotNull(job.songId)
|
||||
assertEquals(listOf(songId), MoodRepository.songIds(mood.id))
|
||||
|
||||
val recommendation = assertNotNull(MoodRepository.recommendation(mood.id, "v-1"))
|
||||
assertEquals("accepted", recommendation.state)
|
||||
assertEquals(songId, recommendation.matchedSongId)
|
||||
assertTrue(MoodRepository.seedSongIds(mood.id).contains(songId))
|
||||
|
||||
val imports = library.folders.first().path.resolve("AudioManager Imports")
|
||||
val files = Files.walk(imports).use { stream ->
|
||||
stream.filter { Files.isRegularFile(it) }.toList()
|
||||
}
|
||||
assertEquals(1, files.size)
|
||||
assertEquals("Neue Folge.mp3", files.first().fileName.toString())
|
||||
assertEquals("Neue Folge", files.first().parent.fileName.toString())
|
||||
assertEquals("Die drei ___", files.first().parent.parent.fileName.toString())
|
||||
val song = assertNotNull(SongRepository.byId(songId))
|
||||
assertEquals("vid-manual", song.videoId)
|
||||
assertEquals("Song vid-manual", song.title)
|
||||
assertEquals("Artist", song.artist)
|
||||
assertEquals("vid-manual/Song vid-manual.mp3", song.relativePath)
|
||||
assertTrue(Files.isRegularFile(assertNotNull(mediaStore.file(song))))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an already downloaded song attaches without another download`() {
|
||||
withService(downloader = AudioDownloader { _, _ -> error("downloader must not run") }) { service, mediaStore, _ ->
|
||||
val mood = mood(recommendationCount = 0)
|
||||
val song = insertSong(mediaStore, "vid-existing")
|
||||
DownloadRepository.enqueue("vid-existing", mood.id, DownloadRepository.KIND_SONG)
|
||||
|
||||
assertTrue(service.processOne())
|
||||
|
||||
assertEquals(listOf(song.id), MoodRepository.songIds(mood.id))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `downloaded file is promoted instead of an older same-title song`() {
|
||||
withDatabase { handle, library, users ->
|
||||
val mood = MoodRepository.create(
|
||||
owner = "alice",
|
||||
name = "Drei ???",
|
||||
description = null,
|
||||
query = null,
|
||||
genres = emptyList(),
|
||||
targetSize = 30,
|
||||
refreshHours = 24,
|
||||
ytEnabled = true,
|
||||
seedSongIds = emptyList(),
|
||||
)
|
||||
MoodRepository.storeRecommendations(
|
||||
fun `the same video is downloaded once for two moods`() {
|
||||
TestAudio.assumeFfmpeg()
|
||||
var downloads = 0
|
||||
withService(downloader = AudioDownloader { videoId, dir -> downloads++; mp3(videoId, dir) }) { service, _, _ ->
|
||||
val first = mood(recommendationCount = 0, name = "First")
|
||||
val second = mood(recommendationCount = 0, name = "Second")
|
||||
DownloadRepository.enqueue("vid-shared", first.id, DownloadRepository.KIND_SONG)
|
||||
DownloadRepository.enqueue("vid-shared", second.id, DownloadRepository.KIND_SONG)
|
||||
|
||||
assertTrue(service.processOne())
|
||||
assertTrue(service.processOne())
|
||||
|
||||
assertEquals(1, downloads)
|
||||
assertEquals(1, SongRepository.count())
|
||||
assertEquals(MoodRepository.songIds(first.id), MoodRepository.songIds(second.id))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a recommendation download becomes ready but is not a mood song`() {
|
||||
TestAudio.assumeFfmpeg()
|
||||
withService { service, _, _ ->
|
||||
val mood = mood(recommendationCount = 1)
|
||||
storeRecommendation(mood.id, "vid-rec")
|
||||
val promoted = MoodRepository.promoteCandidates(mood.id, 1).single()
|
||||
DownloadRepository.enqueue(
|
||||
promoted.videoId,
|
||||
mood.id,
|
||||
listOf(
|
||||
RecommendationUpsert(
|
||||
videoId = "v-dup",
|
||||
title = "Neue Folge",
|
||||
artist = "Die drei ???",
|
||||
album = null,
|
||||
duration = 300,
|
||||
thumbnail = null,
|
||||
matchedSongId = null,
|
||||
),
|
||||
),
|
||||
"2026-01-01T00:00:00Z",
|
||||
)
|
||||
DownloadRepository.enqueue("alice", mood.id, "v-dup", "Neue Folge", "Die drei ???")
|
||||
|
||||
val oldId = insertSong(
|
||||
handle,
|
||||
"Die drei ???",
|
||||
"Neue Folge",
|
||||
"Old/Die drei ??? - Neue Folge.mp3",
|
||||
)
|
||||
var newId: String? = null
|
||||
val service = DownloadService(
|
||||
users = users,
|
||||
library = library,
|
||||
downloader = AudioDownloader { videoId, _, _, dir ->
|
||||
val file = dir.resolve("$videoId.mp3")
|
||||
Files.write(file, "fake-mp3".toByteArray())
|
||||
file
|
||||
},
|
||||
tempDir = tempDir.resolve("downloads"),
|
||||
startScan = {
|
||||
if (newId == null) {
|
||||
newId = insertSong(
|
||||
handle,
|
||||
"Die drei ???",
|
||||
"Neue Folge",
|
||||
"AudioManager Imports/Die drei ___/Neue Folge/Neue Folge.mp3",
|
||||
)
|
||||
}
|
||||
true
|
||||
},
|
||||
isScanning = { false },
|
||||
DownloadRepository.KIND_RECOMMENDATION,
|
||||
)
|
||||
|
||||
assertTrue(service.processOne())
|
||||
|
||||
val job = assertNotNull(DownloadRepository.forRecommendation("alice", mood.id, "v-dup"))
|
||||
assertEquals("done", job.state)
|
||||
assertEquals(newId, job.songId)
|
||||
assertNotEquals(oldId, job.songId)
|
||||
val recommendation = assertNotNull(
|
||||
MoodRepository.recommendation(mood.id, "vid-rec"),
|
||||
)
|
||||
assertEquals("ready", recommendation.state)
|
||||
assertNotNull(recommendation.songId)
|
||||
assertTrue(MoodRepository.songIds(mood.id).isEmpty())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `failed downloads retry and then fail`() {
|
||||
withDatabase { _, library, users ->
|
||||
val mood = MoodRepository.create(
|
||||
owner = "alice",
|
||||
name = "Broken",
|
||||
description = null,
|
||||
query = null,
|
||||
genres = emptyList(),
|
||||
targetSize = 30,
|
||||
refreshHours = 24,
|
||||
ytEnabled = true,
|
||||
seedSongIds = emptyList(),
|
||||
fun `adding while downloading attaches when the job finishes`() {
|
||||
TestAudio.assumeFfmpeg()
|
||||
withService { service, _, _ ->
|
||||
val mood = mood(recommendationCount = 1)
|
||||
storeRecommendation(mood.id, "vid-rec")
|
||||
MoodRepository.promoteCandidates(mood.id, 1)
|
||||
DownloadRepository.enqueue(
|
||||
"vid-rec",
|
||||
mood.id,
|
||||
DownloadRepository.KIND_RECOMMENDATION,
|
||||
)
|
||||
DownloadRepository.enqueue("alice", mood.id, "v-2", "Missing", "Nobody")
|
||||
val service = DownloadService(
|
||||
users = users,
|
||||
library = library,
|
||||
downloader = AudioDownloader { _, _, _, _ -> error("network down") },
|
||||
tempDir = tempDir.resolve("downloads"),
|
||||
startScan = { true },
|
||||
isScanning = { false },
|
||||
MoodRepository.markAdded(mood.id, "vid-rec")
|
||||
|
||||
assertTrue(service.processOne())
|
||||
|
||||
val recommendation = assertNotNull(MoodRepository.recommendation(mood.id, "vid-rec"))
|
||||
assertEquals("added", recommendation.state)
|
||||
assertEquals(listOf(assertNotNull(recommendation.songId)), MoodRepository.songIds(mood.id))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `rejecting while downloading leaves no mood song and collects the file`() {
|
||||
TestAudio.assumeFfmpeg()
|
||||
withService { service, mediaStore, _ ->
|
||||
val mood = mood(recommendationCount = 1)
|
||||
storeRecommendation(mood.id, "vid-rec")
|
||||
MoodRepository.promoteCandidates(mood.id, 1)
|
||||
DownloadRepository.enqueue(
|
||||
"vid-rec",
|
||||
mood.id,
|
||||
DownloadRepository.KIND_RECOMMENDATION,
|
||||
)
|
||||
MoodRepository.markRejected(mood.id, "vid-rec")
|
||||
|
||||
assertTrue(service.processOne())
|
||||
|
||||
assertTrue(MoodRepository.songIds(mood.id).isEmpty())
|
||||
assertNull(SongRepository.byVideoId("vid-rec"))
|
||||
assertTrue(Files.notExists(mediaStore.root.resolve("vid-rec")))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `failures retry three times and leave the recommendation failed`() {
|
||||
withService(downloader = AudioDownloader { _, _ -> error("network down") }) { service, _, _ ->
|
||||
val mood = mood(recommendationCount = 1)
|
||||
storeRecommendation(mood.id, "vid-broken")
|
||||
MoodRepository.promoteCandidates(mood.id, 1)
|
||||
DownloadRepository.enqueue(
|
||||
"vid-broken",
|
||||
mood.id,
|
||||
DownloadRepository.KIND_RECOMMENDATION,
|
||||
)
|
||||
|
||||
assertTrue(service.processOne())
|
||||
assertEquals("queued", DownloadRepository.forRecommendation("alice", mood.id, "v-2")?.state)
|
||||
assertTrue(service.processOne())
|
||||
assertEquals("queued", DownloadRepository.forRecommendation("alice", mood.id, "v-2")?.state)
|
||||
assertTrue(service.processOne())
|
||||
|
||||
val job = assertNotNull(DownloadRepository.forRecommendation("alice", mood.id, "v-2"))
|
||||
val job = assertNotNull(
|
||||
DownloadRepository.find(mood.id, "vid-broken", DownloadRepository.KIND_RECOMMENDATION),
|
||||
)
|
||||
assertEquals("failed", job.state)
|
||||
assertEquals(3, job.attempts)
|
||||
assertTrue(job.error?.contains("network down") == true)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Test
|
||||
fun `stale downloading jobs are recovered`() {
|
||||
withDatabase { handle, library, users ->
|
||||
val mood = MoodRepository.create(
|
||||
owner = "alice",
|
||||
name = "Recovery",
|
||||
description = null,
|
||||
query = null,
|
||||
genres = emptyList(),
|
||||
targetSize = 30,
|
||||
refreshHours = 24,
|
||||
ytEnabled = true,
|
||||
seedSongIds = emptyList(),
|
||||
)
|
||||
DownloadRepository.enqueue("alice", mood.id, "v-stale", "Stale", "Nobody")
|
||||
val job = assertNotNull(DownloadRepository.forRecommendation("alice", mood.id, "v-stale"))
|
||||
transaction(handle.database) {
|
||||
DownloadJobsTable.update({ DownloadJobsTable.id eq job.id }) {
|
||||
it[state] = "downloading"
|
||||
it[updatedAt] = Instant.now().minusSeconds(3600).toString()
|
||||
}
|
||||
}
|
||||
|
||||
val claimed = assertNotNull(DownloadRepository.claimNext())
|
||||
assertEquals(job.id, claimed.id)
|
||||
assertEquals("downloading", claimed.state)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `failed verification removes the promoted file instead of duplicating it`() {
|
||||
withDatabase { _, library, users ->
|
||||
val mood = MoodRepository.create(
|
||||
owner = "alice",
|
||||
name = "Broken match",
|
||||
description = null,
|
||||
query = null,
|
||||
genres = emptyList(),
|
||||
targetSize = 30,
|
||||
refreshHours = 24,
|
||||
ytEnabled = true,
|
||||
seedSongIds = emptyList(),
|
||||
)
|
||||
DownloadRepository.enqueue("alice", mood.id, "v-nomatch", "No Match", "Nobody")
|
||||
val service = DownloadService(
|
||||
users = users,
|
||||
library = library,
|
||||
downloader = AudioDownloader { videoId, _, _, dir ->
|
||||
val file = dir.resolve("$videoId.mp3")
|
||||
Files.write(file, "fake-mp3".toByteArray())
|
||||
file
|
||||
},
|
||||
tempDir = tempDir.resolve("downloads"),
|
||||
startScan = { true },
|
||||
isScanning = { false },
|
||||
)
|
||||
|
||||
repeat(3) { assertTrue(service.processOne()) }
|
||||
|
||||
val job = assertNotNull(DownloadRepository.forRecommendation("alice", mood.id, "v-nomatch"))
|
||||
assertEquals("failed", job.state)
|
||||
val imports = library.folders.first().path.resolve("AudioManager Imports")
|
||||
if (Files.isDirectory(imports)) {
|
||||
val files = Files.walk(imports).use { stream ->
|
||||
stream.filter { Files.isRegularFile(it) }.toList()
|
||||
}
|
||||
assertTrue(files.isEmpty(), "leftover promoted files: $files")
|
||||
}
|
||||
val recommendation = assertNotNull(MoodRepository.recommendation(mood.id, "vid-broken"))
|
||||
assertEquals("failed", recommendation.state)
|
||||
assertTrue(recommendation.error?.contains("network down") == true)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `permission errors fail without burning retries`() {
|
||||
withDatabase { _, library, users ->
|
||||
val mood = MoodRepository.create(
|
||||
owner = "alice",
|
||||
name = "Denied",
|
||||
description = null,
|
||||
query = null,
|
||||
genres = emptyList(),
|
||||
targetSize = 30,
|
||||
refreshHours = 24,
|
||||
ytEnabled = true,
|
||||
seedSongIds = emptyList(),
|
||||
)
|
||||
DownloadRepository.enqueue("alice", mood.id, "v-3", "Blocked", "Nobody")
|
||||
val service = DownloadService(
|
||||
users = users,
|
||||
library = library,
|
||||
downloader = AudioDownloader { _, _, _, _ ->
|
||||
throw AccessDeniedException("/mnt/media/music/AudioManager Imports")
|
||||
},
|
||||
tempDir = tempDir.resolve("downloads"),
|
||||
startScan = { true },
|
||||
isScanning = { false },
|
||||
)
|
||||
withService(
|
||||
downloader = AudioDownloader { _, _ -> throw AccessDeniedException("/data/media") },
|
||||
) { service, _, _ ->
|
||||
val mood = mood(recommendationCount = 0)
|
||||
DownloadRepository.enqueue("vid-denied", mood.id, DownloadRepository.KIND_SONG)
|
||||
|
||||
assertTrue(service.processOne())
|
||||
|
||||
val job = assertNotNull(DownloadRepository.forRecommendation("alice", mood.id, "v-3"))
|
||||
val job = assertNotNull(
|
||||
DownloadRepository.find(mood.id, "vid-denied", DownloadRepository.KIND_SONG),
|
||||
)
|
||||
assertEquals("failed", job.state)
|
||||
assertEquals(1, job.attempts)
|
||||
assertTrue(job.error?.contains("AccessDeniedException") == true)
|
||||
}
|
||||
}
|
||||
|
||||
private fun withDatabase(block: (DatabaseHandle, LibraryConfig, UsersConfig) -> Unit) {
|
||||
val musicDir = Files.createDirectories(tempDir.resolve("music"))
|
||||
val library = LibraryConfig(
|
||||
listOf(MusicFolder(1, "Music", FolderType.MUSIC, musicDir)),
|
||||
@Test
|
||||
fun `manual adds outrank recommendation downloads`() {
|
||||
withDatabase { _, _ ->
|
||||
val mood = mood(recommendationCount = 1)
|
||||
DownloadRepository.enqueue(
|
||||
"vid-rec",
|
||||
mood.id,
|
||||
DownloadRepository.KIND_RECOMMENDATION,
|
||||
)
|
||||
DownloadRepository.enqueue("vid-manual", mood.id, DownloadRepository.KIND_SONG)
|
||||
|
||||
val claimed = assertNotNull(DownloadRepository.claimNext())
|
||||
assertEquals("vid-manual", claimed.videoId)
|
||||
assertEquals(DownloadRepository.KIND_SONG, claimed.kind)
|
||||
}
|
||||
}
|
||||
|
||||
private fun mood(recommendationCount: Int, name: String = "Focus"): MoodRecord =
|
||||
MoodRepository.create(
|
||||
owner = "alice",
|
||||
name = name,
|
||||
description = null,
|
||||
query = null,
|
||||
genres = emptyList(),
|
||||
collectionPercent = 50,
|
||||
recommendationCount = recommendationCount,
|
||||
refreshHours = 24,
|
||||
)
|
||||
val users = UsersConfig(
|
||||
listOf(UserAccount("alice", "pw", admin = true, folders = setOf(1))),
|
||||
)
|
||||
val handle = DatabaseFactory.connect(
|
||||
AppConfig(
|
||||
port = 8080,
|
||||
dataDir = tempDir.resolve("data"),
|
||||
libraryConfigPath = tempDir.resolve("library.yaml"),
|
||||
usersFile = tempDir.resolve("users.yaml"),
|
||||
ffmpegPath = "ffmpeg",
|
||||
downloadDir = tempDir.resolve("downloads"),
|
||||
|
||||
private fun storeRecommendation(moodId: String, videoId: String) {
|
||||
MoodRepository.storeCandidates(
|
||||
moodId,
|
||||
listOf(
|
||||
RecommendationUpsert(
|
||||
videoId = videoId,
|
||||
title = "Recommended",
|
||||
artist = "Artist",
|
||||
album = null,
|
||||
duration = 180,
|
||||
thumbnail = null,
|
||||
),
|
||||
),
|
||||
Instant.now().toString(),
|
||||
)
|
||||
}
|
||||
|
||||
private fun withService(
|
||||
downloader: AudioDownloader = AudioDownloader { videoId, dir -> mp3(videoId, dir) },
|
||||
block: (DownloadService, MediaStore, MediaGcService) -> Unit,
|
||||
) {
|
||||
withDatabase { handle, store ->
|
||||
val coverArt = CoverArtService(tempDir.resolve("data"))
|
||||
val indexer = SongIndexer(store, coverArt)
|
||||
val gc = MediaGcService(store, coverArt)
|
||||
val service = DownloadService(
|
||||
downloader = downloader,
|
||||
mediaStore = store,
|
||||
indexer = indexer,
|
||||
gc = gc,
|
||||
tagExtractor = Mp3TagExtractor(),
|
||||
tempDir = tempDir.resolve("downloads"),
|
||||
)
|
||||
try {
|
||||
block(service, store, gc)
|
||||
} catch (t: Throwable) {
|
||||
throw t
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun withDatabase(block: (DatabaseHandle, MediaStore) -> Unit) {
|
||||
val handle = DatabaseFactory.connect(appConfig())
|
||||
try {
|
||||
ConfigRepository.sync(library, users)
|
||||
block(handle, library, users)
|
||||
ConfigRepository.sync(UsersConfig(listOf(UserAccount("alice", "pw", admin = true))))
|
||||
val store = MediaStore(Files.createDirectories(tempDir.resolve("media")))
|
||||
block(handle, store)
|
||||
} finally {
|
||||
handle.close()
|
||||
}
|
||||
}
|
||||
|
||||
private fun insertSong(
|
||||
handle: DatabaseHandle,
|
||||
artistName: String,
|
||||
title: String,
|
||||
relativePath: String = "AudioManager Imports/$artistName - $title.mp3",
|
||||
): String {
|
||||
val artistId = IdGenerator.artistId(artistName)
|
||||
val albumId = IdGenerator.albumId(artistName, "Downloads")
|
||||
val songId = IdGenerator.songId(1, relativePath)
|
||||
val now = Instant.now().toString()
|
||||
|
||||
transaction(handle.database) {
|
||||
ArtistsTable.insertIgnore {
|
||||
it[id] = artistId
|
||||
it[name] = artistName
|
||||
it[sortName] = artistName
|
||||
it[searchText] = IdGenerator.normalize(artistName)
|
||||
}
|
||||
AlbumsTable.insertIgnore {
|
||||
it[id] = albumId
|
||||
it[name] = "Downloads"
|
||||
it[createdAt] = now
|
||||
it[searchText] = IdGenerator.normalize("$title $artistName")
|
||||
}
|
||||
AlbumArtistsTable.insertIgnore {
|
||||
it[this.albumId] = albumId
|
||||
it[this.artistId] = artistId
|
||||
it[position] = 0
|
||||
}
|
||||
SongsTable.insert {
|
||||
it[id] = songId
|
||||
it[this.albumId] = albumId
|
||||
it[folderId] = 1
|
||||
it[this.title] = title
|
||||
it[displayArtist] = artistName
|
||||
it[albumName] = "Downloads"
|
||||
it[duration] = 300
|
||||
it[bitRate] = 128
|
||||
it[size] = 10
|
||||
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 Downloads $artistName")
|
||||
}
|
||||
SongArtistsTable.insert {
|
||||
it[this.songId] = songId
|
||||
it[this.artistId] = artistId
|
||||
it[position] = 0
|
||||
}
|
||||
SongGenresTable.insert {
|
||||
it[this.songId] = songId
|
||||
it[genre] = "Hörspiel"
|
||||
}
|
||||
}
|
||||
return songId
|
||||
private fun mp3(videoId: String, dir: Path): Path {
|
||||
val file = dir.resolve("$videoId.mp3")
|
||||
TestAudio.createMp3(
|
||||
file,
|
||||
metadata = mapOf(
|
||||
"title" to "Song $videoId",
|
||||
"artist" to "Artist",
|
||||
"album" to "Album",
|
||||
),
|
||||
)
|
||||
return file
|
||||
}
|
||||
|
||||
private fun insertSong(mediaStore: MediaStore, videoId: String): win.taptap.musicmanager.db.SongRecord {
|
||||
val file = mediaStore.target(videoId, "Existing")
|
||||
Files.createDirectories(file.parent)
|
||||
Files.write(file, "fake-mp3".toByteArray())
|
||||
return SongRepository.upsert(
|
||||
SongUpsert(
|
||||
videoId = videoId,
|
||||
title = "Existing",
|
||||
artist = "Artist",
|
||||
album = null,
|
||||
duration = 180,
|
||||
bitRate = 128,
|
||||
size = Files.size(file),
|
||||
relativePath = mediaStore.root.relativize(file).joinToString("/") { it.toString() },
|
||||
fileMtime = Files.getLastModifiedTime(file).toMillis(),
|
||||
thumbnail = null,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
private fun appConfig(): AppConfig = AppConfig(
|
||||
port = 8080,
|
||||
dataDir = tempDir.resolve("data"),
|
||||
usersFile = tempDir.resolve("users.yaml"),
|
||||
ffmpegPath = "ffmpeg",
|
||||
downloadDir = tempDir.resolve("downloads"),
|
||||
)
|
||||
}
|
||||
@@ -12,18 +12,21 @@ class RadioServiceTest {
|
||||
private val service = RadioService()
|
||||
|
||||
@Test
|
||||
fun `recently played songs are penalized`() {
|
||||
fun `recently played and already heard songs are penalized`() {
|
||||
val song = song("s-1")
|
||||
val fresh = service.scoreCandidate(
|
||||
song, emptySet(), emptyList(), emptyList(), null, affinity = 0.0, jitter = 0.0,
|
||||
)
|
||||
val recent = service.scoreCandidate(
|
||||
song, emptySet(), emptyList(), emptyList(), null, affinity = 0.0,
|
||||
recent = setOf("s-1"), jitter = 0.0,
|
||||
)
|
||||
|
||||
assertEquals(0.0, fresh)
|
||||
assertEquals(-6.0, recent)
|
||||
assertEquals(
|
||||
0.0,
|
||||
service.scoreCandidate(song, affinity = 0.0, recent = false, jitter = 0.0),
|
||||
)
|
||||
assertEquals(
|
||||
-6.0,
|
||||
service.scoreCandidate(song, affinity = 0.0, recent = true, jitter = 0.0),
|
||||
)
|
||||
assertEquals(
|
||||
-20.0,
|
||||
service.scoreCandidate(song, affinity = 0.0, recent = false, jitter = 0.0, heard = true),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -34,145 +37,103 @@ class RadioServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `seeds and matching genres are boosted`() {
|
||||
val seeded = service.scoreCandidate(
|
||||
song("s-1", genres = listOf("Ambient")),
|
||||
seedIds = setOf("s-1"),
|
||||
seedGenres = listOf("Ambient"),
|
||||
seedArtistIds = emptyList(),
|
||||
query = null,
|
||||
affinity = 0.0,
|
||||
jitter = 0.0,
|
||||
)
|
||||
val plain = service.scoreCandidate(
|
||||
song("s-2"),
|
||||
seedIds = setOf("s-1"),
|
||||
seedGenres = listOf("Ambient"),
|
||||
seedArtistIds = emptyList(),
|
||||
query = null,
|
||||
affinity = 0.0,
|
||||
jitter = 0.0,
|
||||
fun `higher scores are picked first`() {
|
||||
val scored = listOf(
|
||||
song("low", artist = "A") to 1.0,
|
||||
song("high", artist = "B") to 9.0,
|
||||
)
|
||||
|
||||
assertEquals(11.5, seeded)
|
||||
assertEquals(0.0, plain)
|
||||
val picked = service.pickMixed(scored, emptyList(), limit = 2, collectionPercent = 100)
|
||||
|
||||
assertEquals("high", picked.first().id)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `picks keep artists and albums apart`() {
|
||||
fun `picks keep artists and albums apart when possible`() {
|
||||
val scored = listOf(
|
||||
song("s1", artist = "A", albumId = "al1") to 0.0,
|
||||
song("s2", artist = "B", albumId = "al2") to 0.0,
|
||||
song("s3", artist = "C", albumId = "al3") to 0.0,
|
||||
song("s4", artist = "D", albumId = "al4") to 0.0,
|
||||
song("s5", artist = "A", albumId = "al5") to 0.0,
|
||||
song("s6", artist = "B", albumId = "al6") to 0.0,
|
||||
song("s1", artist = "A", album = "a1") to 0.0,
|
||||
song("s2", artist = "B", album = "a2") to 0.0,
|
||||
song("s3", artist = "C", album = "a3") to 0.0,
|
||||
song("s4", artist = "D", album = "a4") to 0.0,
|
||||
song("s5", artist = "A", album = "a5") to 0.0,
|
||||
song("s6", artist = "B", album = "a6") to 0.0,
|
||||
)
|
||||
|
||||
val picked = service.pickDiverse(scored, limit = 6)
|
||||
val picked = service.pickMixed(
|
||||
scored,
|
||||
emptyList(),
|
||||
limit = 6,
|
||||
collectionPercent = 100,
|
||||
artistSpacing = 2,
|
||||
albumSpacing = 3,
|
||||
)
|
||||
|
||||
assertEquals(6, picked.size)
|
||||
picked.indices.forEach { index ->
|
||||
val artists = picked.subList(index, minOf(index + 3, picked.size)).map { it.displayArtist }
|
||||
val artists = picked.subList(index, minOf(index + 3, picked.size)).map { it.artist }
|
||||
assertEquals(artists.size, artists.distinct().size, "artist spacing at $index")
|
||||
val albums = picked.subList(index, minOf(index + 4, picked.size)).map { it.albumId }
|
||||
assertEquals(albums.size, albums.distinct().size, "album spacing at $index")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `picks relax spacing when the pool is too small`() {
|
||||
val scored = listOf(
|
||||
song("s1", artist = "A", albumId = "al1") to 0.0,
|
||||
song("s2", artist = "A", albumId = "al1") to 0.0,
|
||||
)
|
||||
|
||||
val picked = service.pickDiverse(scored, limit = 2)
|
||||
|
||||
assertEquals(listOf("s1", "s2"), picked.map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `higher scores are picked first`() {
|
||||
val scored = listOf(
|
||||
song("low", artist = "A", albumId = "al1") to 1.0,
|
||||
song("high", artist = "B", albumId = "al2") to 9.0,
|
||||
)
|
||||
|
||||
assertTrue(service.pickDiverse(scored, limit = 2).first().id == "high")
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
fun `mood mix draws from seeds and recommendations in proportion`() {
|
||||
val seeds = (1..20).map { song("seed-$it", artist = "Seed $it") }
|
||||
fun `mood mix draws from collection and recommendations in proportion`() {
|
||||
val collection = (1..20).map { song("col-$it", artist = "Col $it") }
|
||||
val recommendations = (1..20).map { song("rec-$it", artist = "Rec $it") }
|
||||
val seedScored = seeds.mapIndexed { index, song -> song to (10.0 - index * 0.1) }
|
||||
val collectionScored = collection.mapIndexed { index, song -> song to (10.0 - index * 0.1) }
|
||||
val recommendationScored = recommendations.mapIndexed { index, song -> song to (9.0 - index * 0.1) }
|
||||
|
||||
val allSeeds = RadioService(Random(1)).pickMixed(
|
||||
seedScored, recommendationScored, limit = 10, seedPercent = 100,
|
||||
val allCollection = RadioService(Random(1)).pickMixed(
|
||||
collectionScored, recommendationScored, limit = 10, collectionPercent = 100,
|
||||
)
|
||||
assertTrue(allSeeds.all { it.id.startsWith("seed-") })
|
||||
assertTrue(allCollection.all { it.id.startsWith("col-") })
|
||||
|
||||
val allRecommendations = RadioService(Random(1)).pickMixed(
|
||||
seedScored, recommendationScored, limit = 10, seedPercent = 0,
|
||||
collectionScored, recommendationScored, limit = 10, collectionPercent = 0,
|
||||
)
|
||||
assertTrue(allRecommendations.all { it.id.startsWith("rec-") })
|
||||
|
||||
val mixed = RadioService(Random(7)).pickMixed(
|
||||
seedScored, recommendationScored, limit = 20, seedPercent = 50,
|
||||
collectionScored, recommendationScored, limit = 20, collectionPercent = 50,
|
||||
)
|
||||
assertEquals(20, mixed.size)
|
||||
assertEquals(20, mixed.map { it.id }.distinct().size)
|
||||
assertTrue(mixed.any { it.id.startsWith("seed-") })
|
||||
assertTrue(mixed.any { it.id.startsWith("col-") })
|
||||
assertTrue(mixed.any { it.id.startsWith("rec-") })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `mood mix falls back when one pool is empty`() {
|
||||
val seeds = listOf(song("only-seed"))
|
||||
val onlyCollection = listOf(song("only-collection"))
|
||||
|
||||
val picked = RadioService(Random(1)).pickMixed(
|
||||
seedScored = seeds.map { it to 1.0 },
|
||||
collectionScored = onlyCollection.map { it to 1.0 },
|
||||
recommendationScored = emptyList(),
|
||||
limit = 5,
|
||||
seedPercent = 0,
|
||||
collectionPercent = 0,
|
||||
)
|
||||
|
||||
assertEquals(listOf("only-seed"), picked.map { it.id })
|
||||
assertEquals(listOf("only-collection"), picked.map { it.id })
|
||||
}
|
||||
|
||||
private fun song(
|
||||
id: String,
|
||||
artist: String = "Artist $id",
|
||||
albumId: String = "album-$id",
|
||||
genres: List<String> = emptyList(),
|
||||
album: String? = "Album $id",
|
||||
) = SongRecord(
|
||||
id = id,
|
||||
albumId = albumId,
|
||||
albumName = "Album",
|
||||
artistId = "ar-$artist",
|
||||
artistName = artist,
|
||||
displayArtist = artist,
|
||||
videoId = "video-$id",
|
||||
title = "Title $id",
|
||||
trackNumber = 1,
|
||||
discNumber = 1,
|
||||
year = 2026,
|
||||
artist = artist,
|
||||
album = album,
|
||||
duration = 180,
|
||||
bitRate = 320,
|
||||
size = 1_000,
|
||||
suffix = "mp3",
|
||||
contentType = "audio/mpeg",
|
||||
coverArt = null,
|
||||
folderId = 1,
|
||||
relativePath = "$id.mp3",
|
||||
created = "2026-01-01T00:00:00Z",
|
||||
relativePath = "video-$id/$id.mp3",
|
||||
fileMtime = 0,
|
||||
thumbnail = null,
|
||||
createdAt = "2026-01-01T00:00:00Z",
|
||||
updatedAt = "2026-01-01T00:00:00Z",
|
||||
starredAt = null,
|
||||
rating = null,
|
||||
playCount = 0,
|
||||
lastPlayedAt = null,
|
||||
artists = emptyList(),
|
||||
genres = genres,
|
||||
)
|
||||
}
|
||||
@@ -2,33 +2,18 @@ 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.LibraryTombstonesTable
|
||||
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.db.SongRepository
|
||||
import win.taptap.musicmanager.media.MediaStore
|
||||
import win.taptap.musicmanager.util.IdGenerator
|
||||
|
||||
class MediaScannerTest {
|
||||
@@ -36,242 +21,101 @@ class MediaScannerTest {
|
||||
@TempDir
|
||||
lateinit var tempDir: Path
|
||||
|
||||
private lateinit var music: Path
|
||||
private lateinit var longform: Path
|
||||
private lateinit var media: Path
|
||||
|
||||
@Test
|
||||
fun `scans, caches covers and keeps user state across metadata updates`() {
|
||||
fun `indexes the media root by video id and caches covers`() {
|
||||
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")
|
||||
withScanner { scanner, coverArt ->
|
||||
val one = media.resolve("vid-one/One.mp3")
|
||||
val two = media.resolve("vid-two/Two.mp3")
|
||||
val cover = media.resolve("cover.png")
|
||||
TestAudio.writePng(cover)
|
||||
TestAudio.createMp3(
|
||||
book,
|
||||
one,
|
||||
metadata = mapOf(
|
||||
"title" to "Chapter One",
|
||||
"artist" to "Author",
|
||||
"album_artist" to "Author",
|
||||
"album" to "Book",
|
||||
"title" to "One",
|
||||
"artist" to "Alpha",
|
||||
"album" to "Album",
|
||||
"genre" to "Rock",
|
||||
),
|
||||
cover = cover,
|
||||
)
|
||||
Files.writeString(music.resolve("notes.txt"), "not audio")
|
||||
|
||||
val scanner = MediaScanner(library, CoverArtService(tempDir.resolve("data")))
|
||||
TestAudio.createMp3(two, metadata = mapOf("title" to "Two", "artist" to "Beta"))
|
||||
Files.writeString(media.resolve("notes.txt"), "not audio")
|
||||
Files.writeString(media.resolve("loose.mp3"), "not in a video folder")
|
||||
|
||||
val first = scanner.scanBlocking()
|
||||
assertNull(first.error)
|
||||
assertEquals(3L, first.count)
|
||||
assertEquals(3L, MediaRepository.countSongs())
|
||||
assertEquals(2L, first.count)
|
||||
assertEquals(2L, SongRepository.count())
|
||||
|
||||
val albumId = IdGenerator.albumId("Album Artist", "Album")
|
||||
val songId = IdGenerator.songId(1, "Album Artist/Album/01 - One.mp3")
|
||||
val song = assertNotNull(SongRepository.byVideoId("vid-one"))
|
||||
assertEquals(IdGenerator.songId("vid-one"), song.id)
|
||||
assertEquals("One", song.title)
|
||||
assertEquals("Alpha", song.artist)
|
||||
assertEquals("Album", song.album)
|
||||
assertEquals("vid-one/One.mp3", song.relativePath)
|
||||
assertEquals(128, song.bitRate)
|
||||
assertEquals("mp3", song.suffix)
|
||||
assertEquals("audio/mpeg", song.contentType)
|
||||
assertEquals(Files.size(one), song.size)
|
||||
|
||||
transaction(db.database) {
|
||||
assertEquals(3L, SongsTable.selectAll().count())
|
||||
assertEquals(2L, AlbumsTable.selectAll().count())
|
||||
assertEquals(2L, ArtistsTable.selectAll().count())
|
||||
assertEquals(2L, SongGenresTable.selectAll().count())
|
||||
assertTrue(Files.isRegularFile(coverArt.coverFile(song.id)))
|
||||
|
||||
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))
|
||||
// Unchanged files are skipped on a second scan.
|
||||
val second = scanner.scanBlocking()
|
||||
assertEquals(3L, second.count)
|
||||
assertEquals(3L, MediaRepository.countSongs())
|
||||
assertEquals(2L, second.count)
|
||||
assertEquals(2L, SongRepository.count())
|
||||
|
||||
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.
|
||||
// Deleting a file removes its row.
|
||||
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())
|
||||
assertEquals(1L, third.count)
|
||||
assertNull(SongRepository.byVideoId("vid-two"))
|
||||
|
||||
transaction(db.database) {
|
||||
assertEquals(0L, SongsTable.selectAll().count())
|
||||
assertEquals(0L, AlbumsTable.selectAll().count())
|
||||
assertEquals(0L, ArtistsTable.selectAll().count())
|
||||
}
|
||||
} finally {
|
||||
db.close()
|
||||
// Re-adding it indexes it again.
|
||||
TestAudio.createMp3(two, metadata = mapOf("title" to "Two", "artist" to "Beta"))
|
||||
val fourth = scanner.scanBlocking()
|
||||
assertEquals(2L, fourth.count)
|
||||
assertNotNull(SongRepository.byVideoId("vid-two"))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
fun `an unreadable folder does not delete its songs`() {
|
||||
fun `a missing media root does not delete its songs`() {
|
||||
TestAudio.assumeFfmpeg()
|
||||
val db = DatabaseFactory.connect(appConfig())
|
||||
try {
|
||||
val library = library()
|
||||
ConfigRepository.sync(library, users())
|
||||
|
||||
val file = music.resolve("Artist/Album/song.mp3")
|
||||
withScanner { scanner, _ ->
|
||||
val file = media.resolve("vid-one/One.mp3")
|
||||
TestAudio.createMp3(file)
|
||||
|
||||
val scanner = MediaScanner(library, CoverArtService(tempDir.resolve("data")))
|
||||
assertEquals(1L, scanner.scanBlocking().count)
|
||||
assertEquals(1L, MediaRepository.countSongs())
|
||||
|
||||
// Simulate an unmounted or temporarily unreadable folder.
|
||||
music.toFile().deleteRecursively()
|
||||
media.toFile().deleteRecursively()
|
||||
|
||||
val broken = scanner.scanBlocking()
|
||||
assertNotNull(broken.error)
|
||||
assertEquals(1L, MediaRepository.countSongs())
|
||||
} finally {
|
||||
db.close()
|
||||
assertEquals(1L, SongRepository.count())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
fun `re-adding a deleted file clears its tombstone`() {
|
||||
TestAudio.assumeFfmpeg()
|
||||
private fun withScanner(block: (MediaScanner, CoverArtService) -> Unit) {
|
||||
val db = DatabaseFactory.connect(appConfig())
|
||||
try {
|
||||
val library = library()
|
||||
ConfigRepository.sync(library, users())
|
||||
val file = music.resolve("Artist/Album/song.mp3")
|
||||
TestAudio.createMp3(file)
|
||||
val scanner = MediaScanner(library, CoverArtService(tempDir.resolve("data")))
|
||||
scanner.scanBlocking()
|
||||
val songId = IdGenerator.songId(1, "Artist/Album/song.mp3")
|
||||
|
||||
Files.delete(file)
|
||||
scanner.scanBlocking()
|
||||
transaction(db.database) {
|
||||
assertEquals(
|
||||
1L,
|
||||
LibraryTombstonesTable.selectAll()
|
||||
.where { LibraryTombstonesTable.entityId eq songId }
|
||||
.count(),
|
||||
)
|
||||
}
|
||||
|
||||
TestAudio.createMp3(file)
|
||||
scanner.scanBlocking()
|
||||
transaction(db.database) {
|
||||
assertEquals(
|
||||
0L,
|
||||
LibraryTombstonesTable.selectAll()
|
||||
.where { LibraryTombstonesTable.entityId eq songId }
|
||||
.count(),
|
||||
)
|
||||
}
|
||||
val store = MediaStore(Files.createDirectories(tempDir.resolve("media")))
|
||||
media = store.root
|
||||
val coverArt = CoverArtService(tempDir.resolve("data"))
|
||||
val scanner = MediaScanner(store, SongIndexer(store, coverArt))
|
||||
block(scanner, coverArt)
|
||||
} 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))),
|
||||
)
|
||||
}
|
||||
@@ -9,7 +9,6 @@ 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 {
|
||||
|
||||
@@ -17,95 +16,66 @@ class Mp3TagExtractorTest {
|
||||
lateinit var tempDir: Path
|
||||
|
||||
@Test
|
||||
fun `reads ID3 tags and separates album artist from track artists`() {
|
||||
fun `reads ID3 tags from a downloaded MP3`() {
|
||||
TestAudio.assumeFfmpeg()
|
||||
val root = Files.createDirectories(tempDir.resolve("music"))
|
||||
val file = root.resolve("Album Artist/Album/02 - Song.mp3")
|
||||
val file = tempDir.resolve("video-id/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))
|
||||
val song = assertNotNull(Mp3TagExtractor().extract(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,
|
||||
)
|
||||
assertEquals("Test Song", song.title)
|
||||
assertEquals("Track Artist", song.artist)
|
||||
assertEquals("Test Album", song.album)
|
||||
assertTrue(song.durationSeconds in 1..4)
|
||||
assertTrue(song.bitRate > 0)
|
||||
assertEquals(Files.size(file), song.size)
|
||||
assertEquals("mp3", song.suffix)
|
||||
assertEquals("audio/mpeg", song.contentType)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `falls back to the folder structure when tags are missing`() {
|
||||
fun `falls back to the file name and a generic artist`() {
|
||||
TestAudio.assumeFfmpeg()
|
||||
val root = Files.createDirectories(tempDir.resolve("music"))
|
||||
val file = root.resolve("Artist/Album/song.mp3")
|
||||
val file = tempDir.resolve("video-id/My Track.mp3")
|
||||
TestAudio.createMp3(file)
|
||||
|
||||
val track = assertNotNull(Mp3TagExtractor().extract(1, root, file))
|
||||
val song = assertNotNull(Mp3TagExtractor().extract(file))
|
||||
|
||||
assertEquals("song", track.title)
|
||||
assertEquals("Album", track.albumTitle)
|
||||
assertEquals("Artist", track.displayArtist)
|
||||
assertEquals(listOf("Artist"), track.albumArtists.map { it.name })
|
||||
assertEquals("My Track", song.title)
|
||||
assertEquals("Unknown artist", song.artist)
|
||||
assertNull(song.album)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `reads embedded artwork and sidecar lyrics`() {
|
||||
fun `reads embedded artwork`() {
|
||||
TestAudio.assumeFfmpeg()
|
||||
val root = Files.createDirectories(tempDir.resolve("music"))
|
||||
val cover = root.resolve("cover.png")
|
||||
val cover = tempDir.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 file = tempDir.resolve("video-id/covered.mp3")
|
||||
TestAudio.createMp3(file, metadata = mapOf("title" to "Covered"), cover = cover)
|
||||
|
||||
val track = assertNotNull(Mp3TagExtractor().extract(1, root, file))
|
||||
val song = assertNotNull(Mp3TagExtractor().extract(file))
|
||||
|
||||
assertNotNull(track.coverBytes)
|
||||
assertTrue(track.coverBytes!!.isNotEmpty())
|
||||
assertEquals("[00:00.00]Hello", track.lyrics)
|
||||
assertNotNull(song.coverBytes)
|
||||
assertTrue(song.coverBytes!!.isNotEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `ignores non-mp3 files`() {
|
||||
val root = Files.createDirectories(tempDir.resolve("music"))
|
||||
val file = root.resolve("song.flac")
|
||||
val file = tempDir.resolve("video-id/song.flac")
|
||||
Files.createDirectories(file.parent)
|
||||
Files.writeString(file, "not audio")
|
||||
|
||||
assertNull(Mp3TagExtractor().extract(1, root, file))
|
||||
assertNull(Mp3TagExtractor().extract(file))
|
||||
}
|
||||
}
|
||||
@@ -15,42 +15,29 @@ class IdGeneratorTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `IDs are deterministic, prefixed and 24 hex characters`() {
|
||||
val first = IdGenerator.artistId("The Beatles")
|
||||
val second = IdGenerator.artistId("the beatles")
|
||||
fun `song IDs are deterministic, prefixed and 24 hex characters`() {
|
||||
val first = IdGenerator.songId("dQw4w9WgXcQ")
|
||||
val second = IdGenerator.songId(" dQw4w9WgXcQ ")
|
||||
|
||||
assertEquals(first, second)
|
||||
assertTrue(first.startsWith("ar-"))
|
||||
assertTrue(first.startsWith("sg-"))
|
||||
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)
|
||||
fun `different videos produce different IDs`() {
|
||||
assertNotEquals(
|
||||
IdGenerator.songId("dQw4w9WgXcQ"),
|
||||
IdGenerator.songId("dQw4w9WgXcR"),
|
||||
)
|
||||
}
|
||||
|
||||
@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"),
|
||||
)
|
||||
fun `mood IDs are deterministic for the same inputs`() {
|
||||
val id = IdGenerator.moodId("Alice", "Focus", "2026-01-01T00:00:00Z")
|
||||
|
||||
assertTrue(id.startsWith("mo-"))
|
||||
assertEquals(id, IdGenerator.moodId("alice", " Focus ", "2026-01-01T00:00:00Z"))
|
||||
assertNotEquals(id, IdGenerator.moodId("Alice", "Focus", "2026-01-02T00:00:00Z"))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user