feat: add per-user moods as generated playlists
Add private server-managed playlist moods with curated seeds and related library fill. Moods are created or promoted from existing playlists in the web UI, refresh lazily after their TTL, and are marked stale after a scan. Symfonium stars pin the active mood: opening a mood restores its context, and a starred song becomes a permanent seed. Without an active session the song is pinned to every mood that already contains it. Includes the V4 migration, custom mood endpoints, management UI, tests and smoke coverage. Bump the chart to 0.1.4.
This commit is contained in:
1 parent
e08d993e35
commit
28bfdd9d00
25 files changed
+2039
-14
No files matched your search
@@ -30,6 +30,8 @@ import win.taptap.musicmanager.config.UsersConfig
|
||||
import win.taptap.musicmanager.db.ConfigRepository
|
||||
import win.taptap.musicmanager.db.DatabaseFactory
|
||||
import win.taptap.musicmanager.db.MediaRepository
|
||||
import win.taptap.musicmanager.db.MoodRepository
|
||||
import win.taptap.musicmanager.mood.MoodService
|
||||
import win.taptap.musicmanager.scanner.CoverArtService
|
||||
import win.taptap.musicmanager.scanner.MediaScanner
|
||||
import win.taptap.musicmanager.subsonic.respondSubsonicError
|
||||
@@ -51,7 +53,12 @@ fun main() {
|
||||
val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
val coverArtService = CoverArtService(config.dataDir)
|
||||
val transcoder = FfmpegTranscoder(config.ffmpegPath)
|
||||
val scanner = MediaScanner(library, coverArtService)
|
||||
val moodService = MoodService(applicationScope)
|
||||
val scanner = MediaScanner(
|
||||
library = library,
|
||||
coverArtService = coverArtService,
|
||||
onScanFinished = { MoodRepository.markAllStale() },
|
||||
)
|
||||
if (MediaRepository.countSongs() == 0L) {
|
||||
log.info("Song table is empty, starting initial library scan")
|
||||
scanner.start(applicationScope)
|
||||
@@ -98,6 +105,7 @@ fun main() {
|
||||
library = library,
|
||||
coverArtService = coverArtService,
|
||||
transcoder = transcoder,
|
||||
moodService = moodService,
|
||||
startScan = { scanner.start(applicationScope) },
|
||||
scanStatus = { scanner.status() },
|
||||
)
|
||||
|
||||
@@ -9,6 +9,7 @@ import org.jetbrains.exposed.sql.SortOrder
|
||||
import org.jetbrains.exposed.sql.Transaction
|
||||
import org.jetbrains.exposed.sql.and
|
||||
import org.jetbrains.exposed.sql.lowerCase
|
||||
import org.jetbrains.exposed.sql.or
|
||||
import org.jetbrains.exposed.sql.selectAll
|
||||
import org.jetbrains.exposed.sql.transactions.transaction
|
||||
import org.jetbrains.exposed.sql.union
|
||||
@@ -404,6 +405,59 @@ object LibraryRepository {
|
||||
enrichSongs(rows, userName)
|
||||
}
|
||||
|
||||
/** Bulk genre lookup used by mood generation to avoid one query per seed genre. */
|
||||
fun songsByGenres(
|
||||
genres: Collection<String>,
|
||||
limit: Int,
|
||||
folderIds: Set<Int>,
|
||||
userName: String,
|
||||
): List<SongRecord> = read {
|
||||
if (genres.isEmpty() || folderIds.isEmpty()) return@read emptyList()
|
||||
|
||||
val normalized = genres.map { it.lowercase() }.distinct()
|
||||
val songIds = SongGenresTable
|
||||
.select(SongGenresTable.songId)
|
||||
.where { SongGenresTable.genre.lowerCase() inList normalized }
|
||||
|
||||
val rows = SongsTable.selectAll()
|
||||
.where {
|
||||
(SongsTable.id inSubQuery songIds) and
|
||||
(SongsTable.folderId inList folderIds)
|
||||
}
|
||||
.limit(limit)
|
||||
.toList()
|
||||
|
||||
enrichSongs(rows, userName)
|
||||
}
|
||||
|
||||
/** Songs by track artist or album artist, used as related-mood candidates. */
|
||||
fun songsByArtists(
|
||||
artistIds: Collection<String>,
|
||||
limit: Int,
|
||||
folderIds: Set<Int>,
|
||||
userName: String,
|
||||
): List<SongRecord> = read {
|
||||
if (artistIds.isEmpty() || folderIds.isEmpty()) return@read emptyList()
|
||||
|
||||
val ids = artistIds.toList()
|
||||
val songArtists = SongArtistsTable
|
||||
.select(SongArtistsTable.songId)
|
||||
.where { SongArtistsTable.artistId inList ids }
|
||||
val albumArtists = AlbumArtistsTable
|
||||
.select(AlbumArtistsTable.albumId)
|
||||
.where { AlbumArtistsTable.artistId inList ids }
|
||||
|
||||
val rows = SongsTable.selectAll()
|
||||
.where {
|
||||
(SongsTable.folderId inList folderIds) and
|
||||
((SongsTable.id inSubQuery songArtists) or (SongsTable.albumId inSubQuery albumArtists))
|
||||
}
|
||||
.limit(limit)
|
||||
.toList()
|
||||
|
||||
enrichSongs(rows, userName)
|
||||
}
|
||||
|
||||
fun starred(userName: String, folderIds: Set<Int>): StarredRecords = read {
|
||||
if (folderIds.isEmpty()) {
|
||||
return@read StarredRecords(emptyList(), emptyList(), emptyList())
|
||||
|
||||
@@ -0,0 +1,413 @@
|
||||
package win.taptap.musicmanager.db
|
||||
|
||||
import java.time.Instant
|
||||
import kotlinx.serialization.builtins.ListSerializer
|
||||
import kotlinx.serialization.builtins.serializer
|
||||
import kotlinx.serialization.json.Json
|
||||
import org.jetbrains.exposed.sql.JoinType
|
||||
import org.jetbrains.exposed.sql.Op
|
||||
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
|
||||
import org.jetbrains.exposed.sql.ResultRow
|
||||
import org.jetbrains.exposed.sql.SortOrder
|
||||
import org.jetbrains.exposed.sql.and
|
||||
import org.jetbrains.exposed.sql.deleteWhere
|
||||
import org.jetbrains.exposed.sql.insert
|
||||
import org.jetbrains.exposed.sql.selectAll
|
||||
import org.jetbrains.exposed.sql.transactions.transaction
|
||||
import org.jetbrains.exposed.sql.update
|
||||
|
||||
data class MoodRecord(
|
||||
val playlistId: String,
|
||||
val owner: String,
|
||||
val name: String,
|
||||
val comment: String?,
|
||||
val query: String?,
|
||||
val genres: List<String>,
|
||||
val targetSize: Int,
|
||||
val ytSlots: Int,
|
||||
val expandRelated: Boolean,
|
||||
val refreshHours: Int,
|
||||
val generatedAt: String?,
|
||||
val generation: Int,
|
||||
val lastError: String?,
|
||||
val created: String,
|
||||
val changed: String,
|
||||
val songCount: Int,
|
||||
val duration: Int,
|
||||
val seedCount: Int,
|
||||
)
|
||||
|
||||
data class MoodSeedRecord(
|
||||
val songId: String,
|
||||
val origin: String,
|
||||
val addedAt: String,
|
||||
)
|
||||
|
||||
/**
|
||||
* Moods are private playlists with generation settings. The playlist row remains
|
||||
* the client-visible object; this repository owns the settings, seeds and the
|
||||
* materialized mix in `playlist_songs`.
|
||||
*/
|
||||
object MoodRepository {
|
||||
|
||||
private val genreSerializer = ListSerializer(String.serializer())
|
||||
|
||||
fun list(userName: String): List<MoodRecord> = transaction {
|
||||
PlaylistsTable
|
||||
.join(MoodsTable, JoinType.INNER, PlaylistsTable.id, MoodsTable.playlistId)
|
||||
.selectAll()
|
||||
.where {
|
||||
(PlaylistsTable.owner eq userName) and
|
||||
(PlaylistsTable.kind eq "mood")
|
||||
}
|
||||
.orderBy(PlaylistsTable.changedAt to SortOrder.DESC)
|
||||
.map { moodRecord(it) }
|
||||
}
|
||||
|
||||
fun get(playlistId: String, userName: String): MoodRecord? = transaction {
|
||||
val row = PlaylistsTable
|
||||
.join(MoodsTable, JoinType.INNER, PlaylistsTable.id, MoodsTable.playlistId)
|
||||
.selectAll()
|
||||
.where {
|
||||
(PlaylistsTable.id eq playlistId) and
|
||||
(PlaylistsTable.owner eq userName) and
|
||||
(PlaylistsTable.kind eq "mood")
|
||||
}
|
||||
.singleOrNull()
|
||||
|
||||
row?.let { moodRecord(it) }
|
||||
}
|
||||
|
||||
fun create(
|
||||
userName: String,
|
||||
name: String,
|
||||
comment: String?,
|
||||
query: String?,
|
||||
genres: List<String>,
|
||||
targetSize: Int,
|
||||
ytSlots: Int,
|
||||
expandRelated: Boolean,
|
||||
refreshHours: Int,
|
||||
seedSongIds: List<String>,
|
||||
): MoodRecord {
|
||||
val playlist = PlaylistRepository.create(
|
||||
userName = userName,
|
||||
name = name,
|
||||
songIds = emptyList(),
|
||||
isPublic = false,
|
||||
kind = "mood",
|
||||
)
|
||||
|
||||
try {
|
||||
transaction {
|
||||
insertSettings(
|
||||
playlistId = playlist.id,
|
||||
query = query,
|
||||
genres = genres,
|
||||
targetSize = targetSize,
|
||||
ytSlots = ytSlots,
|
||||
expandRelated = expandRelated,
|
||||
refreshHours = refreshHours,
|
||||
)
|
||||
insertSeeds(playlist.id, seedSongIds, "manual")
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
PlaylistRepository.delete(playlist.id, userName)
|
||||
throw t
|
||||
}
|
||||
|
||||
return get(playlist.id, userName)
|
||||
?: error("Mood ${playlist.id} was not persisted")
|
||||
}
|
||||
|
||||
/** Converts an existing owned playlist into a mood while keeping its ID. */
|
||||
fun promote(
|
||||
userName: String,
|
||||
playlistId: String,
|
||||
query: String?,
|
||||
genres: List<String>,
|
||||
targetSize: Int,
|
||||
ytSlots: Int,
|
||||
expandRelated: Boolean,
|
||||
refreshHours: Int,
|
||||
musicFolderIds: Set<Int>,
|
||||
): MoodRecord? {
|
||||
val playlist = PlaylistRepository.get(playlistId, userName) ?: return null
|
||||
if (playlist.owner != userName || playlist.kind != "user") return null
|
||||
|
||||
val seedIds = transaction {
|
||||
PlaylistRepository.songIds(playlistId).filter { songId ->
|
||||
SongsTable
|
||||
.select(SongsTable.folderId)
|
||||
.where { SongsTable.id eq songId }
|
||||
.singleOrNull()
|
||||
?.get(SongsTable.folderId) in musicFolderIds
|
||||
}
|
||||
}
|
||||
PlaylistRepository.setKind(playlistId, "mood", false)
|
||||
|
||||
try {
|
||||
transaction {
|
||||
insertSettings(
|
||||
playlistId = playlistId,
|
||||
query = query,
|
||||
genres = genres,
|
||||
targetSize = targetSize,
|
||||
ytSlots = ytSlots,
|
||||
expandRelated = expandRelated,
|
||||
refreshHours = refreshHours,
|
||||
)
|
||||
insertSeeds(playlistId, seedIds, "promoted")
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
PlaylistRepository.setKind(playlistId, "user", playlist.isPublic)
|
||||
throw t
|
||||
}
|
||||
|
||||
return get(playlistId, userName)
|
||||
}
|
||||
|
||||
fun update(
|
||||
playlistId: String,
|
||||
userName: String,
|
||||
name: String,
|
||||
comment: String?,
|
||||
query: String?,
|
||||
genres: List<String>,
|
||||
targetSize: Int,
|
||||
ytSlots: Int,
|
||||
expandRelated: Boolean,
|
||||
refreshHours: Int,
|
||||
): Boolean = transaction {
|
||||
val exists = PlaylistsTable.selectAll()
|
||||
.where {
|
||||
(PlaylistsTable.id eq playlistId) and
|
||||
(PlaylistsTable.owner eq userName) and
|
||||
(PlaylistsTable.kind eq "mood")
|
||||
}
|
||||
.any()
|
||||
if (!exists) return@transaction false
|
||||
|
||||
PlaylistsTable.update({ PlaylistsTable.id eq playlistId }) {
|
||||
it[PlaylistsTable.name] = name
|
||||
it[PlaylistsTable.comment] = comment
|
||||
it[changedAt] = Instant.now().toString()
|
||||
}
|
||||
MoodsTable.update({ MoodsTable.playlistId eq playlistId }) {
|
||||
it[MoodsTable.query] = query
|
||||
it[MoodsTable.genres] = encodeGenres(genres)
|
||||
it[MoodsTable.targetSize] = targetSize.coerceIn(1, 500)
|
||||
it[MoodsTable.ytSlots] = ytSlots.coerceIn(0, 500)
|
||||
it[MoodsTable.expandRelated] = expandRelated
|
||||
it[MoodsTable.refreshHours] = refreshHours.coerceIn(1, 720)
|
||||
it[generatedAt] = null
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fun delete(playlistId: String, userName: String): Boolean =
|
||||
PlaylistRepository.delete(playlistId, userName)
|
||||
|
||||
fun seedSongIds(playlistId: String, origin: String? = null): List<String> = transaction {
|
||||
val condition = if (origin == null) {
|
||||
MoodSeedsTable.playlistId eq playlistId
|
||||
} else {
|
||||
(MoodSeedsTable.playlistId eq playlistId) and (MoodSeedsTable.origin eq origin)
|
||||
}
|
||||
|
||||
MoodSeedsTable.selectAll()
|
||||
.where(condition)
|
||||
.orderBy(
|
||||
MoodSeedsTable.addedAt to SortOrder.ASC,
|
||||
MoodSeedsTable.songId to SortOrder.ASC,
|
||||
)
|
||||
.map { it[MoodSeedsTable.songId] }
|
||||
}
|
||||
|
||||
fun seeds(playlistId: String): List<MoodSeedRecord> = transaction {
|
||||
MoodSeedsTable.selectAll()
|
||||
.where { MoodSeedsTable.playlistId eq playlistId }
|
||||
.orderBy(
|
||||
MoodSeedsTable.addedAt to SortOrder.ASC,
|
||||
MoodSeedsTable.songId to SortOrder.ASC,
|
||||
)
|
||||
.map {
|
||||
MoodSeedRecord(
|
||||
songId = it[MoodSeedsTable.songId],
|
||||
origin = it[MoodSeedsTable.origin],
|
||||
addedAt = it[MoodSeedsTable.addedAt],
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns true when the seed was newly inserted. */
|
||||
fun addSeed(
|
||||
playlistId: String,
|
||||
userName: String,
|
||||
songId: String,
|
||||
origin: String,
|
||||
): Boolean = transaction {
|
||||
if (get(playlistId, userName) == null) return@transaction false
|
||||
|
||||
val exists = MoodSeedsTable.selectAll()
|
||||
.where {
|
||||
(MoodSeedsTable.playlistId eq playlistId) and
|
||||
(MoodSeedsTable.songId eq songId)
|
||||
}
|
||||
.any()
|
||||
if (exists) return@transaction false
|
||||
|
||||
MoodSeedsTable.insert {
|
||||
it[MoodSeedsTable.playlistId] = playlistId
|
||||
it[MoodSeedsTable.songId] = songId
|
||||
it[MoodSeedsTable.origin] = origin
|
||||
it[addedAt] = Instant.now().toString()
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fun removeSeed(
|
||||
playlistId: String,
|
||||
userName: String,
|
||||
songId: String,
|
||||
origin: String? = null,
|
||||
): Boolean = transaction {
|
||||
if (get(playlistId, userName) == null) return@transaction false
|
||||
|
||||
val condition = if (origin == null) {
|
||||
(MoodSeedsTable.playlistId eq playlistId) and (MoodSeedsTable.songId eq songId)
|
||||
} else {
|
||||
(MoodSeedsTable.playlistId eq playlistId) and
|
||||
(MoodSeedsTable.songId eq songId) and
|
||||
(MoodSeedsTable.origin eq origin)
|
||||
}
|
||||
MoodSeedsTable.deleteWhere { condition } > 0
|
||||
}
|
||||
|
||||
/** Mood playlists that currently contain [songId], for context-free star pinning. */
|
||||
fun moodsContainingSong(userName: String, songId: String): List<String> = transaction {
|
||||
PlaylistsTable
|
||||
.join(MoodsTable, JoinType.INNER, PlaylistsTable.id, MoodsTable.playlistId)
|
||||
.join(PlaylistSongsTable, JoinType.INNER, PlaylistsTable.id, PlaylistSongsTable.playlistId)
|
||||
.select(PlaylistsTable.id)
|
||||
.where {
|
||||
(PlaylistsTable.owner eq userName) and
|
||||
(PlaylistsTable.kind eq "mood") and
|
||||
(PlaylistSongsTable.songId eq songId)
|
||||
}
|
||||
.map { it[PlaylistsTable.id] }
|
||||
.distinct()
|
||||
}
|
||||
|
||||
fun markGenerated(playlistId: String, generation: Int, error: String?) {
|
||||
transaction {
|
||||
MoodsTable.update({ MoodsTable.playlistId eq playlistId }) {
|
||||
it[generatedAt] = Instant.now().toString()
|
||||
it[MoodsTable.generation] = generation
|
||||
it[lastError] = error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun markStale(playlistId: String) {
|
||||
transaction {
|
||||
MoodsTable.update({ MoodsTable.playlistId eq playlistId }) {
|
||||
it[generatedAt] = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Records a failed generation without claiming the mood is fresh. */
|
||||
fun markError(playlistId: String, message: String) {
|
||||
transaction {
|
||||
MoodsTable.update({ MoodsTable.playlistId eq playlistId }) {
|
||||
it[lastError] = message.take(1000)
|
||||
it[generatedAt] = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun markAllStale() {
|
||||
transaction {
|
||||
MoodsTable.update({ Op.TRUE }) {
|
||||
it[generatedAt] = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun insertSettings(
|
||||
playlistId: String,
|
||||
query: String?,
|
||||
genres: List<String>,
|
||||
targetSize: Int,
|
||||
ytSlots: Int,
|
||||
expandRelated: Boolean,
|
||||
refreshHours: Int,
|
||||
) {
|
||||
MoodsTable.insert {
|
||||
it[MoodsTable.playlistId] = playlistId
|
||||
it[MoodsTable.query] = query?.trim()?.takeIf(String::isNotEmpty)
|
||||
it[MoodsTable.genres] = encodeGenres(genres)
|
||||
it[MoodsTable.targetSize] = targetSize.coerceIn(1, 500)
|
||||
it[MoodsTable.ytSlots] = ytSlots.coerceIn(0, 500)
|
||||
it[MoodsTable.expandRelated] = expandRelated
|
||||
it[MoodsTable.refreshHours] = refreshHours.coerceIn(1, 720)
|
||||
}
|
||||
}
|
||||
|
||||
private fun insertSeeds(playlistId: String, songIds: List<String>, origin: String) {
|
||||
val now = Instant.now().toString()
|
||||
songIds.distinct().forEach { songId ->
|
||||
MoodSeedsTable.insert {
|
||||
it[MoodSeedsTable.playlistId] = playlistId
|
||||
it[MoodSeedsTable.songId] = songId
|
||||
it[MoodSeedsTable.origin] = origin
|
||||
it[addedAt] = now
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun moodRecord(row: ResultRow): MoodRecord {
|
||||
val id = row[PlaylistsTable.id]
|
||||
val songs = PlaylistSongsTable
|
||||
.join(SongsTable, JoinType.INNER, PlaylistSongsTable.songId, SongsTable.id)
|
||||
.select(SongsTable.duration)
|
||||
.where { PlaylistSongsTable.playlistId eq id }
|
||||
.toList()
|
||||
val seedCount = MoodSeedsTable
|
||||
.selectAll()
|
||||
.where { MoodSeedsTable.playlistId eq id }
|
||||
.count()
|
||||
.toInt()
|
||||
|
||||
return MoodRecord(
|
||||
playlistId = id,
|
||||
owner = row[PlaylistsTable.owner],
|
||||
name = row[PlaylistsTable.name],
|
||||
comment = row[PlaylistsTable.comment],
|
||||
query = row[MoodsTable.query],
|
||||
genres = decodeGenres(row[MoodsTable.genres]),
|
||||
targetSize = row[MoodsTable.targetSize],
|
||||
ytSlots = row[MoodsTable.ytSlots],
|
||||
expandRelated = row[MoodsTable.expandRelated],
|
||||
refreshHours = row[MoodsTable.refreshHours],
|
||||
generatedAt = row[MoodsTable.generatedAt],
|
||||
generation = row[MoodsTable.generation],
|
||||
lastError = row[MoodsTable.lastError],
|
||||
created = row[PlaylistsTable.createdAt],
|
||||
changed = row[PlaylistsTable.changedAt],
|
||||
songCount = songs.size,
|
||||
duration = songs.sumOf { it[SongsTable.duration] },
|
||||
seedCount = seedCount,
|
||||
)
|
||||
}
|
||||
|
||||
private fun encodeGenres(genres: List<String>): String =
|
||||
Json.encodeToString(
|
||||
genreSerializer,
|
||||
genres.map { it.trim() }.filter { it.isNotEmpty() }.distinct().take(20),
|
||||
)
|
||||
|
||||
private fun decodeGenres(value: String): List<String> =
|
||||
runCatching { Json.decodeFromString(genreSerializer, value) }.getOrDefault(emptyList())
|
||||
}
|
||||
@@ -17,6 +17,7 @@ data class PlaylistRecord(
|
||||
val comment: String?,
|
||||
val owner: String,
|
||||
val isPublic: Boolean,
|
||||
val kind: String,
|
||||
val songCount: Int,
|
||||
val duration: Int,
|
||||
val created: String,
|
||||
@@ -54,7 +55,13 @@ object PlaylistRepository {
|
||||
.map { it[PlaylistSongsTable.songId] }
|
||||
}
|
||||
|
||||
fun create(userName: String, name: String, songIds: List<String>): PlaylistRecord = transaction {
|
||||
fun create(
|
||||
userName: String,
|
||||
name: String,
|
||||
songIds: List<String>,
|
||||
isPublic: Boolean = true,
|
||||
kind: String = "user",
|
||||
): PlaylistRecord = transaction {
|
||||
val now = Instant.now().toString()
|
||||
val id = IdGenerator.playlistId(userName, name, now)
|
||||
|
||||
@@ -62,7 +69,8 @@ object PlaylistRepository {
|
||||
it[PlaylistsTable.id] = id
|
||||
it[owner] = userName
|
||||
it[PlaylistsTable.name] = name
|
||||
it[isPublic] = true
|
||||
it[PlaylistsTable.isPublic] = isPublic
|
||||
it[PlaylistsTable.kind] = kind
|
||||
it[createdAt] = now
|
||||
it[changedAt] = now
|
||||
}
|
||||
@@ -71,6 +79,15 @@ object PlaylistRepository {
|
||||
playlistRecord(id, PlaylistsTable.selectAll().where { PlaylistsTable.id eq id }.single())
|
||||
}
|
||||
|
||||
/** Promotion keeps the playlist ID stable so Symfonium keeps its reference. */
|
||||
fun setKind(playlistId: String, kind: String, isPublic: Boolean): Boolean = transaction {
|
||||
PlaylistsTable.update({ PlaylistsTable.id eq playlistId }) {
|
||||
it[PlaylistsTable.kind] = kind
|
||||
it[PlaylistsTable.isPublic] = isPublic
|
||||
it[changedAt] = Instant.now().toString()
|
||||
} > 0
|
||||
}
|
||||
|
||||
fun replaceSongs(playlistId: String, songIds: List<String>, userName: String): Boolean = transaction {
|
||||
val row = PlaylistsTable.selectAll()
|
||||
.where { PlaylistsTable.id eq playlistId }
|
||||
@@ -164,6 +181,7 @@ object PlaylistRepository {
|
||||
comment = row[PlaylistsTable.comment],
|
||||
owner = row[PlaylistsTable.owner],
|
||||
isPublic = row[PlaylistsTable.isPublic],
|
||||
kind = row[PlaylistsTable.kind],
|
||||
songCount = songs.size,
|
||||
duration = songs.sumOf { it[SongsTable.duration] },
|
||||
created = row[PlaylistsTable.createdAt],
|
||||
|
||||
@@ -139,6 +139,7 @@ object PlaylistsTable : Table("playlists") {
|
||||
val name = text("name")
|
||||
val comment = text("comment").nullable()
|
||||
val isPublic = bool("is_public").default(true)
|
||||
val kind = varchar("kind", 16).default("user")
|
||||
val createdAt = varchar("created_at", 40)
|
||||
val changedAt = varchar("changed_at", 40)
|
||||
|
||||
@@ -152,3 +153,46 @@ object PlaylistSongsTable : Table("playlist_songs") {
|
||||
|
||||
override val primaryKey = PrimaryKey(playlistId, position)
|
||||
}
|
||||
|
||||
object MoodsTable : Table("moods") {
|
||||
val playlistId = reference("playlist_id", PlaylistsTable.id, onDelete = ReferenceOption.CASCADE)
|
||||
val query = text("query").nullable()
|
||||
val genres = text("genres").default("[]")
|
||||
val targetSize = integer("target_size").default(50)
|
||||
val ytSlots = integer("yt_slots").default(0)
|
||||
val expandRelated = bool("expand_related").default(true)
|
||||
val refreshHours = integer("refresh_hours").default(24)
|
||||
val generatedAt = varchar("generated_at", 40).nullable()
|
||||
val generation = integer("generation").default(0)
|
||||
val lastError = text("last_error").nullable()
|
||||
|
||||
override val primaryKey = PrimaryKey(playlistId)
|
||||
}
|
||||
|
||||
object MoodSeedsTable : Table("mood_seeds") {
|
||||
val playlistId = reference("playlist_id", MoodsTable.playlistId, onDelete = ReferenceOption.CASCADE)
|
||||
val songId = reference("song_id", SongsTable.id, onDelete = ReferenceOption.CASCADE)
|
||||
val origin = varchar("origin", 16).default("manual")
|
||||
val addedAt = varchar("added_at", 40)
|
||||
|
||||
override val primaryKey = PrimaryKey(playlistId, songId)
|
||||
}
|
||||
|
||||
object MoodRecommendationsTable : Table("mood_recommendations") {
|
||||
val playlistId = reference("playlist_id", MoodsTable.playlistId, onDelete = ReferenceOption.CASCADE)
|
||||
val videoId = varchar("video_id", 64)
|
||||
val title = text("title")
|
||||
val artist = text("artist")
|
||||
val duration = integer("duration").nullable()
|
||||
val state = varchar("state", 16).default("new")
|
||||
val matchedSongId = reference(
|
||||
"matched_song_id",
|
||||
SongsTable.id,
|
||||
onDelete = ReferenceOption.SET_NULL,
|
||||
).nullable()
|
||||
val timesAdded = integer("times_added").default(0)
|
||||
val firstSeen = varchar("first_seen", 40)
|
||||
val lastSeen = varchar("last_seen", 40)
|
||||
|
||||
override val primaryKey = PrimaryKey(playlistId, videoId)
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package win.taptap.musicmanager.mood
|
||||
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.random.Random
|
||||
import org.slf4j.LoggerFactory
|
||||
import win.taptap.musicmanager.config.FolderType
|
||||
import win.taptap.musicmanager.config.LibraryConfig
|
||||
import win.taptap.musicmanager.config.UserAccount
|
||||
import win.taptap.musicmanager.db.LibraryRepository
|
||||
import win.taptap.musicmanager.db.MoodRecord
|
||||
import win.taptap.musicmanager.db.MoodRepository
|
||||
import win.taptap.musicmanager.db.PlaylistRepository
|
||||
import win.taptap.musicmanager.db.SongRecord
|
||||
|
||||
data class MoodGenerationStats(
|
||||
val seedCount: Int,
|
||||
val relatedCount: Int,
|
||||
val totalCount: Int,
|
||||
val targetSize: Int,
|
||||
)
|
||||
|
||||
/**
|
||||
* Builds the materialized mood playlist.
|
||||
*
|
||||
* Phase 1 has no YT source: the mix is the curated seeds plus related music from
|
||||
* the owner's own music folders. `yt_slots` is stored but only used once the
|
||||
* recommendation phase lands.
|
||||
*/
|
||||
class MoodMixService {
|
||||
|
||||
private val log = LoggerFactory.getLogger(MoodMixService::class.java)
|
||||
|
||||
fun generate(mood: MoodRecord, user: UserAccount, library: LibraryConfig): MoodGenerationStats {
|
||||
val folders = musicFolderIds(user, library)
|
||||
val seedIds = MoodRepository.seedSongIds(mood.playlistId)
|
||||
val seeds = LibraryRepository.songsByIds(seedIds, folders, user.name)
|
||||
|
||||
val seedGenres = (seeds.flatMap { it.genres } + mood.genres)
|
||||
.distinctBy { it.lowercase() }
|
||||
val seedArtistIds = seeds.mapNotNull { it.artistId }.distinct()
|
||||
val seedAlbumIds = seeds.map { it.albumId }.toSet()
|
||||
val query = mood.query?.trim()?.takeIf { it.isNotEmpty() }
|
||||
|
||||
val related = LinkedHashMap<String, SongRecord>()
|
||||
if (mood.expandRelated) {
|
||||
if (seedGenres.isNotEmpty()) {
|
||||
LibraryRepository.songsByGenres(seedGenres, RELATED_LIMIT, folders, user.name)
|
||||
.forEach { related[it.id] = it }
|
||||
}
|
||||
if (seedArtistIds.isNotEmpty()) {
|
||||
LibraryRepository.songsByArtists(seedArtistIds, RELATED_LIMIT, folders, user.name)
|
||||
.forEach { related[it.id] = it }
|
||||
}
|
||||
if (query != null) {
|
||||
LibraryRepository.searchSongs(query, RELATED_LIMIT, 0, folders, user.name)
|
||||
.forEach { related[it.id] = it }
|
||||
}
|
||||
}
|
||||
|
||||
val seedIdSet = seeds.map { it.id }.toSet()
|
||||
related.keys.removeAll(seedIdSet)
|
||||
|
||||
val random = Random(mood.playlistId.hashCode().toLong() * 31 + mood.generation)
|
||||
val ranked = related.values
|
||||
.shuffled(random)
|
||||
.sortedByDescending { song ->
|
||||
score(song, seedGenres, seedArtistIds, seedAlbumIds, query)
|
||||
}
|
||||
|
||||
val target = max(mood.targetSize, seeds.size).coerceIn(1, MAX_TARGET)
|
||||
val selected = LinkedHashMap<String, SongRecord>()
|
||||
seeds.forEach { selected[it.id] = it }
|
||||
ranked.forEach { song ->
|
||||
if (selected.size < target) selected[song.id] = song
|
||||
}
|
||||
|
||||
// Keep the playlist useful when a mood has only a few seeds or a narrow genre.
|
||||
val hasSignal = seeds.isNotEmpty() || seedGenres.isNotEmpty() || query != null
|
||||
if (mood.expandRelated && hasSignal && selected.size < target) {
|
||||
val fillers = LibraryRepository.randomSongs(
|
||||
size = (target - selected.size) * 3,
|
||||
genre = null,
|
||||
fromYear = null,
|
||||
toYear = null,
|
||||
folderIds = folders,
|
||||
userName = user.name,
|
||||
)
|
||||
fillers.forEach { song ->
|
||||
if (selected.size < target) selected.putIfAbsent(song.id, song)
|
||||
}
|
||||
}
|
||||
|
||||
PlaylistRepository.replaceSongs(mood.playlistId, selected.keys.toList(), user.name)
|
||||
MoodRepository.markGenerated(mood.playlistId, mood.generation + 1, null)
|
||||
|
||||
val stats = MoodGenerationStats(
|
||||
seedCount = seeds.size,
|
||||
relatedCount = selected.size - seeds.size,
|
||||
totalCount = selected.size,
|
||||
targetSize = target,
|
||||
)
|
||||
log.info(
|
||||
"Mood {} generated: {} seeds, {} related, {} total (target {})",
|
||||
mood.name,
|
||||
stats.seedCount,
|
||||
stats.relatedCount,
|
||||
stats.totalCount,
|
||||
stats.targetSize,
|
||||
)
|
||||
return stats
|
||||
}
|
||||
|
||||
private fun score(
|
||||
song: SongRecord,
|
||||
seedGenres: List<String>,
|
||||
seedArtistIds: List<String>,
|
||||
seedAlbumIds: Set<String>,
|
||||
query: String?,
|
||||
): Double {
|
||||
var score = 0.0
|
||||
if (song.artistId != null && song.artistId in seedArtistIds) score += 6.0
|
||||
if (song.albumId in seedAlbumIds) score += 3.0
|
||||
score += song.genres.count { candidate ->
|
||||
seedGenres.any { it.equals(candidate, ignoreCase = true) }
|
||||
} * 2.0
|
||||
if (song.starredAt != null) score += 1.0
|
||||
score += min(song.playCount, 20) * 0.05
|
||||
if (query != null && song.title.contains(query, ignoreCase = true)) score += 2.0
|
||||
return score
|
||||
}
|
||||
|
||||
/** Long-form folders are deliberately excluded, even when the user can see them. */
|
||||
private fun musicFolderIds(user: UserAccount, library: LibraryConfig): Set<Int> =
|
||||
library.folders
|
||||
.asSequence()
|
||||
.filter { it.type == FolderType.MUSIC && it.id in user.folders }
|
||||
.map { it.id }
|
||||
.toSet()
|
||||
|
||||
private companion object {
|
||||
const val RELATED_LIMIT = 500
|
||||
const val MAX_TARGET = 500
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package win.taptap.musicmanager.mood
|
||||
|
||||
import win.taptap.musicmanager.db.MoodRepository
|
||||
|
||||
/**
|
||||
* Translates a Symfonium star into a permanent mood seed.
|
||||
*
|
||||
* If a mood session is active, the like belongs to that mood, even when the song
|
||||
* is not in the current mix. Otherwise the song is pinned to every mood that
|
||||
* already contains it, which is a no-op for rotation except that it becomes an
|
||||
* anchor. Manual and promoted seeds are never removed by an unstar.
|
||||
*/
|
||||
object MoodPins {
|
||||
|
||||
fun onStar(userName: String, songId: String) {
|
||||
targets(userName, songId).forEach { playlistId ->
|
||||
if (MoodRepository.addSeed(playlistId, userName, songId, "star")) {
|
||||
MoodRepository.markStale(playlistId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun onUnstar(userName: String, songId: String) {
|
||||
targets(userName, songId).forEach { playlistId ->
|
||||
if (MoodRepository.removeSeed(playlistId, userName, songId, origin = "star")) {
|
||||
MoodRepository.markStale(playlistId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun targets(userName: String, songId: String): List<String> {
|
||||
val active = MoodSessionTracker.active(userName)
|
||||
if (active != null && MoodRepository.get(active, userName) != null) {
|
||||
return listOf(active)
|
||||
}
|
||||
return MoodRepository.moodsContainingSong(userName, songId)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package win.taptap.musicmanager.mood
|
||||
|
||||
import java.time.Instant
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.launch
|
||||
import org.slf4j.LoggerFactory
|
||||
import win.taptap.musicmanager.config.LibraryConfig
|
||||
import win.taptap.musicmanager.config.UserAccount
|
||||
import win.taptap.musicmanager.db.MoodRecord
|
||||
import win.taptap.musicmanager.db.MoodRepository
|
||||
|
||||
/**
|
||||
* Owns stale checks and serializes generation per mood. Background refreshes keep
|
||||
* `getPlaylist` fast; an explicit refresh is synchronous for the management UI.
|
||||
*/
|
||||
class MoodService(
|
||||
private val scope: CoroutineScope,
|
||||
private val mixService: MoodMixService = MoodMixService(),
|
||||
) {
|
||||
|
||||
private val log = LoggerFactory.getLogger(MoodService::class.java)
|
||||
private val locks = ConcurrentHashMap<String, Any>()
|
||||
private val running = ConcurrentHashMap.newKeySet<String>()
|
||||
|
||||
fun isStale(mood: MoodRecord): Boolean {
|
||||
val generated = mood.generatedAt?.let { runCatching { Instant.parse(it) }.getOrNull() }
|
||||
?: return true
|
||||
return generated.plusSeconds(mood.refreshHours * 3600L).isBefore(Instant.now())
|
||||
}
|
||||
|
||||
/** Starts one background generation when the mix is older than its TTL. */
|
||||
fun refreshIfStale(mood: MoodRecord, user: UserAccount, library: LibraryConfig) {
|
||||
if (!isStale(mood)) return
|
||||
if (!running.add(mood.playlistId)) return
|
||||
scope.launch {
|
||||
try {
|
||||
generateLocked(mood.playlistId, user, library)
|
||||
} catch (t: Throwable) {
|
||||
log.error("Background mood refresh failed for ${mood.name}", t)
|
||||
} finally {
|
||||
running.remove(mood.playlistId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Synchronous generation used by create, update, seed changes and refreshMood. */
|
||||
fun refreshNow(mood: MoodRecord, user: UserAccount, library: LibraryConfig): MoodGenerationStats =
|
||||
generateLocked(mood.playlistId, user, library)
|
||||
|
||||
private fun generateLocked(
|
||||
playlistId: String,
|
||||
user: UserAccount,
|
||||
library: LibraryConfig,
|
||||
): MoodGenerationStats = synchronized(locks.computeIfAbsent(playlistId) { Any() }) {
|
||||
val mood = MoodRepository.get(playlistId, user.name)
|
||||
?: error("Mood not found: $playlistId")
|
||||
|
||||
try {
|
||||
mixService.generate(mood, user, library)
|
||||
} catch (t: Throwable) {
|
||||
MoodRepository.markError(playlistId, t.message ?: t::class.simpleName.orEmpty())
|
||||
throw t
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package win.taptap.musicmanager.mood
|
||||
|
||||
import java.time.Duration
|
||||
import java.time.Instant
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
/**
|
||||
* Symfonium's star request does not carry the playlist it was invoked from.
|
||||
* Opening a mood marks it active, so a like can be attributed to that mood.
|
||||
* The fallback in [MoodPins] handles queued/offline stars without a session.
|
||||
*/
|
||||
object MoodSessionTracker {
|
||||
|
||||
private val ttl: Duration = Duration.ofHours(4)
|
||||
private val sessions = ConcurrentHashMap<String, Session>()
|
||||
|
||||
private data class Session(val playlistId: String, val seenAt: Instant)
|
||||
|
||||
fun activate(userName: String, playlistId: String) {
|
||||
sessions[userName] = Session(playlistId, Instant.now())
|
||||
}
|
||||
|
||||
fun clear(userName: String) {
|
||||
sessions.remove(userName)
|
||||
}
|
||||
|
||||
fun touch(userName: String) {
|
||||
sessions.computeIfPresent(userName) { _, session ->
|
||||
if (session.seenAt.plus(ttl).isBefore(Instant.now())) {
|
||||
null
|
||||
} else {
|
||||
session.copy(seenAt = Instant.now())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun active(userName: String): String? {
|
||||
val session = sessions[userName] ?: return null
|
||||
if (session.seenAt.plus(ttl).isBefore(Instant.now())) {
|
||||
sessions.remove(userName)
|
||||
return null
|
||||
}
|
||||
return session.playlistId
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ class MediaScanner(
|
||||
private val coverArtService: CoverArtService,
|
||||
private val tagExtractor: Mp3TagExtractor = Mp3TagExtractor(),
|
||||
private val repository: MediaRepository = MediaRepository,
|
||||
private val onScanFinished: (ScanStatus) -> Unit = {},
|
||||
) {
|
||||
|
||||
private val log = LoggerFactory.getLogger(MediaScanner::class.java)
|
||||
@@ -73,6 +74,8 @@ class MediaScanner(
|
||||
val finalStatus = ScanStatus(scanning = false, count = count, error = error)
|
||||
status.set(finalStatus)
|
||||
log.info("Library scan finished: {} files, error={}", count, error)
|
||||
runCatching { onScanFinished(finalStatus) }
|
||||
.onFailure { log.warn("Scan completion hook failed", it) }
|
||||
return finalStatus
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import kotlinx.serialization.json.put
|
||||
import win.taptap.musicmanager.db.AlbumRecord
|
||||
import win.taptap.musicmanager.db.ArtistRecord
|
||||
import win.taptap.musicmanager.db.GenreRecord
|
||||
import win.taptap.musicmanager.db.MoodRecord
|
||||
import win.taptap.musicmanager.db.PlaylistRecord
|
||||
import win.taptap.musicmanager.db.SongRecord
|
||||
import win.taptap.musicmanager.util.IdGenerator
|
||||
@@ -123,6 +124,38 @@ fun playlistJson(playlist: PlaylistRecord, songs: List<SongRecord>? = null): Jso
|
||||
}
|
||||
}
|
||||
|
||||
fun moodJson(
|
||||
mood: MoodRecord,
|
||||
seeds: List<SongRecord>? = null,
|
||||
songs: List<SongRecord>? = null,
|
||||
): JsonObject = buildJsonObject {
|
||||
put("id", mood.playlistId)
|
||||
put("name", mood.name)
|
||||
mood.comment?.let { put("comment", it) }
|
||||
mood.query?.let { put("query", it) }
|
||||
put("genres", stringArray(mood.genres))
|
||||
put("targetSize", mood.targetSize)
|
||||
put("ytSlots", mood.ytSlots)
|
||||
put("expandRelated", mood.expandRelated)
|
||||
put("refreshHours", mood.refreshHours)
|
||||
mood.generatedAt?.let { put("generatedAt", it) }
|
||||
put("generation", mood.generation)
|
||||
mood.lastError?.let { put("lastError", it) }
|
||||
put("seedCount", mood.seedCount)
|
||||
put("songCount", mood.songCount)
|
||||
put("duration", mood.duration)
|
||||
put("created", mood.created)
|
||||
put("changed", mood.changed)
|
||||
put("owner", mood.owner)
|
||||
|
||||
seeds?.let { list ->
|
||||
put("seed", buildJsonArray { list.forEach { add(songJson(it)) } })
|
||||
}
|
||||
songs?.let { list ->
|
||||
put("entry", buildJsonArray { list.forEach { add(songJson(it)) } })
|
||||
}
|
||||
}
|
||||
|
||||
fun genreJson(genre: GenreRecord): JsonObject = buildJsonObject {
|
||||
put("value", genre.value)
|
||||
put("songCount", genre.songCount)
|
||||
|
||||
@@ -9,6 +9,8 @@ import win.taptap.musicmanager.config.LibraryConfig
|
||||
import win.taptap.musicmanager.config.UsersConfig
|
||||
import win.taptap.musicmanager.db.LibraryRepository
|
||||
import win.taptap.musicmanager.db.UserStateRepository
|
||||
import win.taptap.musicmanager.mood.MoodPins
|
||||
import win.taptap.musicmanager.mood.MoodSessionTracker
|
||||
import win.taptap.musicmanager.subsonic.models.songJson
|
||||
import win.taptap.musicmanager.subsonic.respondSubsonic
|
||||
import win.taptap.musicmanager.subsonic.respondSubsonicError
|
||||
@@ -34,6 +36,7 @@ fun Route.interactionRoutes(users: UsersConfig, library: LibraryConfig) {
|
||||
}
|
||||
UserStateRepository.scrobble(user.name, id, submission)
|
||||
}
|
||||
MoodSessionTracker.touch(user.name)
|
||||
|
||||
call.respondSubsonic()
|
||||
}
|
||||
@@ -56,7 +59,10 @@ fun Route.interactionRoutes(users: UsersConfig, library: LibraryConfig) {
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
songIds.forEach { UserStateRepository.starSong(user.name, it) }
|
||||
songIds.forEach { songId ->
|
||||
UserStateRepository.starSong(user.name, songId)
|
||||
if (songId.startsWith("sg-")) MoodPins.onStar(user.name, songId)
|
||||
}
|
||||
albumIds.forEach { UserStateRepository.starItem(user.name, "album", it) }
|
||||
artistIds.forEach { UserStateRepository.starItem(user.name, "artist", it) }
|
||||
|
||||
@@ -81,7 +87,10 @@ fun Route.interactionRoutes(users: UsersConfig, library: LibraryConfig) {
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
songIds.forEach { UserStateRepository.unstarSong(user.name, it) }
|
||||
songIds.forEach { songId ->
|
||||
UserStateRepository.unstarSong(user.name, songId)
|
||||
if (songId.startsWith("sg-")) MoodPins.onUnstar(user.name, songId)
|
||||
}
|
||||
albumIds.forEach { UserStateRepository.unstarItem(user.name, "album", it) }
|
||||
artistIds.forEach { UserStateRepository.unstarItem(user.name, "artist", it) }
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import org.slf4j.LoggerFactory
|
||||
import win.taptap.musicmanager.config.LibraryConfig
|
||||
import win.taptap.musicmanager.config.UsersConfig
|
||||
import win.taptap.musicmanager.db.LibraryRepository
|
||||
import win.taptap.musicmanager.mood.MoodSessionTracker
|
||||
import win.taptap.musicmanager.scanner.CoverArtService
|
||||
import win.taptap.musicmanager.subsonic.respondSubsonicError
|
||||
import win.taptap.musicmanager.transcoding.FfmpegTranscoder
|
||||
@@ -61,6 +62,7 @@ fun Route.mediaRoutes(
|
||||
call.respondSubsonicError(70, "Song not found")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
MoodSessionTracker.touch(user.name)
|
||||
|
||||
if (!transcoder.shouldTranscode(resolved.song.bitRate, maxBitRate, format, offset)) {
|
||||
call.respondFile(resolved.file.toFile())
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
package win.taptap.musicmanager.subsonic.routes
|
||||
|
||||
import io.ktor.server.application.ApplicationCall
|
||||
import io.ktor.server.routing.Route
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.add
|
||||
import kotlinx.serialization.json.buildJsonArray
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.put
|
||||
import org.slf4j.LoggerFactory
|
||||
import win.taptap.musicmanager.config.LibraryConfig
|
||||
import win.taptap.musicmanager.config.UserAccount
|
||||
import win.taptap.musicmanager.config.UsersConfig
|
||||
import win.taptap.musicmanager.db.LibraryRepository
|
||||
import win.taptap.musicmanager.db.MoodRecord
|
||||
import win.taptap.musicmanager.db.MoodRepository
|
||||
import win.taptap.musicmanager.db.PlaylistRepository
|
||||
import win.taptap.musicmanager.mood.MoodService
|
||||
import win.taptap.musicmanager.subsonic.models.moodJson
|
||||
import win.taptap.musicmanager.subsonic.respondSubsonic
|
||||
import win.taptap.musicmanager.subsonic.respondSubsonicError
|
||||
|
||||
private val log = LoggerFactory.getLogger("win.taptap.musicmanager.MoodRoutes")
|
||||
|
||||
/**
|
||||
* Mood management endpoints. These are custom OpenSubsonic endpoints used by the
|
||||
* built-in web UI; Symfonium only sees the resulting playlists.
|
||||
*/
|
||||
fun Route.moodRoutes(
|
||||
users: UsersConfig,
|
||||
library: LibraryConfig,
|
||||
moodService: MoodService,
|
||||
) {
|
||||
subsonicEndpoint(users, "/getMoods") { call, user ->
|
||||
val moods = MoodRepository.list(user.name)
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put("moods", buildJsonObject {
|
||||
put("mood", buildJsonArray { moods.forEach { add(moodJson(it)) } })
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/getMood") { call, user ->
|
||||
val mood = call.requireMood(user) ?: return@subsonicEndpoint
|
||||
call.respondSubsonic(buildJsonObject { put("mood", detail(mood, user, library)) })
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/createMood") { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val name = parameters["name"]?.trim()?.takeIf { it.isNotEmpty() }
|
||||
if (name == null) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: name")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val folders = user.musicFolderIds(library)
|
||||
val seedIds = parameters.getAll("songId").orEmpty()
|
||||
.filter { it.isNotBlank() }
|
||||
.filter { LibraryRepository.song(it, folders, user.name) != null }
|
||||
.distinct()
|
||||
|
||||
val mood = MoodRepository.create(
|
||||
userName = user.name,
|
||||
name = name.take(200),
|
||||
comment = parameters["comment"]?.trim()?.takeIf { it.isNotEmpty() },
|
||||
query = parameters["query"]?.trim()?.takeIf { it.isNotEmpty() },
|
||||
genres = genres(parameters),
|
||||
targetSize = intParam(parameters["targetSize"], 50, 1, 500),
|
||||
ytSlots = intParam(parameters["ytSlots"], 0, 0, 500),
|
||||
expandRelated = boolParam(parameters["expandRelated"], true),
|
||||
refreshHours = intParam(parameters["refreshHours"], 24, 1, 720),
|
||||
seedSongIds = seedIds,
|
||||
)
|
||||
|
||||
regenerate(moodService, mood, user, library)
|
||||
call.respondSubsonic(buildJsonObject { put("mood", detail(refreshed(mood), user, library)) })
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/updateMood") { call, user ->
|
||||
val mood = call.requireMood(user) ?: return@subsonicEndpoint
|
||||
val parameters = call.subsonicParams()
|
||||
|
||||
val name = parameters["name"]?.trim()?.takeIf { it.isNotEmpty() } ?: mood.name
|
||||
val comment = if (parameters.contains("comment")) {
|
||||
parameters["comment"]?.trim()?.takeIf { it.isNotEmpty() }
|
||||
} else {
|
||||
mood.comment
|
||||
}
|
||||
val query = if (parameters.contains("query")) {
|
||||
parameters["query"]?.trim()?.takeIf { it.isNotEmpty() }
|
||||
} else {
|
||||
mood.query
|
||||
}
|
||||
val genres = if (parameters.contains("genre") || parameters.contains("genres")) {
|
||||
genres(parameters)
|
||||
} else {
|
||||
mood.genres
|
||||
}
|
||||
|
||||
val updated = MoodRepository.update(
|
||||
playlistId = mood.playlistId,
|
||||
userName = user.name,
|
||||
name = name.take(200),
|
||||
comment = comment,
|
||||
query = query,
|
||||
genres = genres,
|
||||
targetSize = intParam(parameters["targetSize"], mood.targetSize, 1, 500),
|
||||
ytSlots = intParam(parameters["ytSlots"], mood.ytSlots, 0, 500),
|
||||
expandRelated = boolParam(parameters["expandRelated"], mood.expandRelated),
|
||||
refreshHours = intParam(parameters["refreshHours"], mood.refreshHours, 1, 720),
|
||||
)
|
||||
|
||||
if (!updated) {
|
||||
call.respondSubsonicError(70, "Mood not found")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val refreshedMood = MoodRepository.get(mood.playlistId, user.name) ?: mood
|
||||
regenerate(moodService, refreshedMood, user, library)
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put("mood", detail(refreshed(refreshedMood), user, library))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/deleteMood") { call, user ->
|
||||
val mood = call.requireMood(user) ?: return@subsonicEndpoint
|
||||
MoodRepository.delete(mood.playlistId, user.name)
|
||||
call.respondSubsonic()
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/refreshMood") { call, user ->
|
||||
val mood = call.requireMood(user) ?: return@subsonicEndpoint
|
||||
regenerate(moodService, mood, user, library)
|
||||
call.respondSubsonic(buildJsonObject { put("mood", detail(refreshed(mood), user, library)) })
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/promotePlaylistToMood") { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val playlistId = parameters["playlistId"]
|
||||
if (playlistId.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: playlistId")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val mood = MoodRepository.promote(
|
||||
userName = user.name,
|
||||
playlistId = playlistId,
|
||||
query = parameters["query"]?.trim()?.takeIf { it.isNotEmpty() },
|
||||
genres = genres(parameters),
|
||||
targetSize = intParam(parameters["targetSize"], 50, 1, 500),
|
||||
ytSlots = intParam(parameters["ytSlots"], 0, 0, 500),
|
||||
expandRelated = boolParam(parameters["expandRelated"], true),
|
||||
refreshHours = intParam(parameters["refreshHours"], 24, 1, 720),
|
||||
musicFolderIds = user.musicFolderIds(library),
|
||||
)
|
||||
|
||||
if (mood == null) {
|
||||
call.respondSubsonicError(70, "Playlist not found")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
regenerate(moodService, mood, user, library)
|
||||
call.respondSubsonic(buildJsonObject { put("mood", detail(refreshed(mood), user, library)) })
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/addMoodSeed") { call, user ->
|
||||
val mood = call.requireMood(user) ?: return@subsonicEndpoint
|
||||
val parameters = call.subsonicParams()
|
||||
val songId = parameters["songId"]
|
||||
if (songId.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: songId")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val folders = user.musicFolderIds(library)
|
||||
if (LibraryRepository.song(songId, folders, user.name) == null) {
|
||||
call.respondSubsonicError(70, "Song not found")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
MoodRepository.addSeed(mood.playlistId, user.name, songId, "manual")
|
||||
regenerate(moodService, mood, user, library)
|
||||
call.respondSubsonic(buildJsonObject { put("mood", detail(refreshed(mood), user, library)) })
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/removeMoodSeed") { call, user ->
|
||||
val mood = call.requireMood(user) ?: return@subsonicEndpoint
|
||||
val songId = call.subsonicParams()["songId"]
|
||||
if (songId.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: songId")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
MoodRepository.removeSeed(mood.playlistId, user.name, songId)
|
||||
regenerate(moodService, mood, user, library)
|
||||
call.respondSubsonic(buildJsonObject { put("mood", detail(refreshed(mood), user, library)) })
|
||||
}
|
||||
}
|
||||
|
||||
private fun ApplicationCall.moodId(): String? = subsonicParams()["id"]?.takeIf { it.isNotBlank() }
|
||||
|
||||
private suspend fun ApplicationCall.requireMood(
|
||||
user: UserAccount,
|
||||
): MoodRecord? {
|
||||
val id = moodId()
|
||||
if (id == null) {
|
||||
respondSubsonicError(10, "Required parameter is missing: id")
|
||||
return null
|
||||
}
|
||||
|
||||
val mood = MoodRepository.get(id, user.name)
|
||||
if (mood == null) {
|
||||
respondSubsonicError(70, "Mood not found")
|
||||
return null
|
||||
}
|
||||
return mood
|
||||
}
|
||||
|
||||
private fun detail(mood: MoodRecord, user: UserAccount, library: LibraryConfig): JsonObject {
|
||||
val folders = user.musicFolderIds(library)
|
||||
val seedIds = MoodRepository.seedSongIds(mood.playlistId)
|
||||
val seeds = LibraryRepository.songsByIds(seedIds, folders, user.name)
|
||||
val entryIds = PlaylistRepository.songIds(mood.playlistId)
|
||||
val entries = LibraryRepository.songsByIds(entryIds, folders, user.name)
|
||||
return moodJson(mood, seeds = seeds, songs = entries)
|
||||
}
|
||||
|
||||
private fun refreshed(mood: MoodRecord): MoodRecord =
|
||||
MoodRepository.get(mood.playlistId, mood.owner) ?: mood
|
||||
|
||||
private fun regenerate(
|
||||
moodService: MoodService,
|
||||
mood: MoodRecord,
|
||||
user: UserAccount,
|
||||
library: LibraryConfig,
|
||||
) {
|
||||
// A generation failure is recorded on the mood; management actions still succeed.
|
||||
runCatching {
|
||||
moodService.refreshNow(mood, user, library)
|
||||
}.onFailure {
|
||||
log.warn("Mood generation failed for ${mood.name}", it)
|
||||
}
|
||||
}
|
||||
|
||||
private fun genres(parameters: io.ktor.http.Parameters): List<String> =
|
||||
(parameters.getAll("genre").orEmpty() +
|
||||
parameters["genres"].orEmpty().split(','))
|
||||
.map { it.trim() }
|
||||
.filter { it.isNotEmpty() }
|
||||
.distinct()
|
||||
.take(20)
|
||||
|
||||
private fun intParam(raw: String?, default: Int, minimum: Int, maximum: Int): Int =
|
||||
(raw?.toIntOrNull() ?: default).coerceIn(minimum, maximum)
|
||||
|
||||
private fun boolParam(raw: String?, default: Boolean): Boolean = when (raw?.lowercase()) {
|
||||
null -> default
|
||||
"true", "1", "yes", "on" -> true
|
||||
"false", "0", "no", "off" -> false
|
||||
else -> default
|
||||
}
|
||||
@@ -8,13 +8,16 @@ import kotlinx.serialization.json.put
|
||||
import win.taptap.musicmanager.config.LibraryConfig
|
||||
import win.taptap.musicmanager.config.UsersConfig
|
||||
import win.taptap.musicmanager.db.LibraryRepository
|
||||
import win.taptap.musicmanager.db.MoodRepository
|
||||
import win.taptap.musicmanager.db.PlaylistRepository
|
||||
import win.taptap.musicmanager.mood.MoodService
|
||||
import win.taptap.musicmanager.mood.MoodSessionTracker
|
||||
import win.taptap.musicmanager.subsonic.models.playlistJson
|
||||
import win.taptap.musicmanager.subsonic.respondSubsonic
|
||||
import win.taptap.musicmanager.subsonic.respondSubsonicError
|
||||
|
||||
/** Playlist CRUD. Visibility: owned playlists plus all public playlists. */
|
||||
fun Route.playlistRoutes(users: UsersConfig, library: LibraryConfig) {
|
||||
fun Route.playlistRoutes(users: UsersConfig, library: LibraryConfig, moodService: MoodService) {
|
||||
|
||||
subsonicEndpoint(users, "/getPlaylists") { call, user ->
|
||||
val playlists = PlaylistRepository.visibleTo(user.name)
|
||||
@@ -41,7 +44,20 @@ fun Route.playlistRoutes(users: UsersConfig, library: LibraryConfig) {
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val folders = user.visibleFolderIds(library)
|
||||
if (playlist.kind == "mood") {
|
||||
MoodSessionTracker.activate(user.name, playlist.id)
|
||||
MoodRepository.get(playlist.id, user.name)?.let { mood ->
|
||||
moodService.refreshIfStale(mood, user, library)
|
||||
}
|
||||
} else {
|
||||
MoodSessionTracker.clear(user.name)
|
||||
}
|
||||
|
||||
val folders = if (playlist.kind == "mood") {
|
||||
user.musicFolderIds(library)
|
||||
} else {
|
||||
user.visibleFolderIds(library)
|
||||
}
|
||||
val songs = LibraryRepository.songsByIds(PlaylistRepository.songIds(id), folders, user.name)
|
||||
|
||||
call.respondSubsonic(buildJsonObject { put("playlist", playlistJson(playlist, songs)) })
|
||||
@@ -65,6 +81,10 @@ fun Route.playlistRoutes(users: UsersConfig, library: LibraryConfig) {
|
||||
call.respondSubsonicError(50, "Not authorized")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
if (existing.kind == "mood") {
|
||||
call.respondSubsonicError(50, "Mood playlists are generated by the server")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val newName = parameters["name"]?.takeIf { it.isNotBlank() }
|
||||
PlaylistRepository.update(
|
||||
@@ -119,6 +139,15 @@ fun Route.playlistRoutes(users: UsersConfig, library: LibraryConfig) {
|
||||
.mapNotNull { it.toIntOrNull() }
|
||||
.filter { it >= 0 }
|
||||
|
||||
if (existing.kind == "mood" &&
|
||||
(parameters.getAll("songIdToAdd").orEmpty().any { it.isNotBlank() } ||
|
||||
removeIndices.isNotEmpty() ||
|
||||
parameters.contains("public"))
|
||||
) {
|
||||
call.respondSubsonicError(50, "Mood playlists are generated by the server")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val updated = PlaylistRepository.update(
|
||||
playlistId = playlistId,
|
||||
userName = user.name,
|
||||
@@ -154,6 +183,7 @@ fun Route.playlistRoutes(users: UsersConfig, library: LibraryConfig) {
|
||||
}
|
||||
|
||||
PlaylistRepository.delete(playlistId, user.name)
|
||||
MoodSessionTracker.clear(user.name)
|
||||
call.respondSubsonic()
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import io.ktor.server.request.contentType
|
||||
import io.ktor.server.request.httpMethod
|
||||
import io.ktor.server.request.receiveParameters
|
||||
import io.ktor.util.AttributeKey
|
||||
import win.taptap.musicmanager.config.FolderType
|
||||
import win.taptap.musicmanager.config.LibraryConfig
|
||||
import win.taptap.musicmanager.config.UserAccount
|
||||
|
||||
@@ -24,6 +25,14 @@ fun UserAccount.effectiveFolderIds(library: LibraryConfig, musicFolderId: String
|
||||
return if (requested in visible) setOf(requested) else emptySet()
|
||||
}
|
||||
|
||||
/** Music-only roots. Moods never draw from shared long-form folders. */
|
||||
fun UserAccount.musicFolderIds(library: LibraryConfig): Set<Int> =
|
||||
library.folders
|
||||
.asSequence()
|
||||
.filter { it.type == FolderType.MUSIC && it.id in folders }
|
||||
.map { it.id }
|
||||
.toSet()
|
||||
|
||||
/** Parameters captured during authentication, so POST bodies are only read once. */
|
||||
fun ApplicationCall.subsonicParams(): Parameters =
|
||||
attributes.getOrNull(SubsonicParametersKey) ?: request.queryParameters
|
||||
|
||||
@@ -4,6 +4,7 @@ import io.ktor.server.routing.Route
|
||||
import io.ktor.server.routing.route
|
||||
import win.taptap.musicmanager.config.LibraryConfig
|
||||
import win.taptap.musicmanager.config.UsersConfig
|
||||
import win.taptap.musicmanager.mood.MoodService
|
||||
import win.taptap.musicmanager.scanner.CoverArtService
|
||||
import win.taptap.musicmanager.scanner.ScanStatus
|
||||
import win.taptap.musicmanager.transcoding.FfmpegTranscoder
|
||||
@@ -14,6 +15,7 @@ fun Route.subsonicRoutes(
|
||||
library: LibraryConfig,
|
||||
coverArtService: CoverArtService,
|
||||
transcoder: FfmpegTranscoder,
|
||||
moodService: MoodService,
|
||||
startScan: () -> Boolean,
|
||||
scanStatus: () -> ScanStatus,
|
||||
) {
|
||||
@@ -22,7 +24,8 @@ fun Route.subsonicRoutes(
|
||||
browsingRoutes(users, library)
|
||||
mediaRoutes(users, library, coverArtService, transcoder)
|
||||
interactionRoutes(users, library)
|
||||
playlistRoutes(users, library)
|
||||
playlistRoutes(users, library, moodService)
|
||||
moodRoutes(users, library, moodService)
|
||||
playQueueRoutes(users, library)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
-- Moods are private, server-managed playlists. The playlist stays the
|
||||
-- Symfonium-visible object; this table holds the generation settings.
|
||||
ALTER TABLE playlists ADD COLUMN kind TEXT NOT NULL DEFAULT 'user'
|
||||
CHECK (kind IN ('user', 'mood'));
|
||||
|
||||
CREATE TABLE moods (
|
||||
playlist_id TEXT PRIMARY KEY REFERENCES playlists(id) ON DELETE CASCADE,
|
||||
query TEXT,
|
||||
genres TEXT NOT NULL DEFAULT '[]',
|
||||
target_size INTEGER NOT NULL DEFAULT 50,
|
||||
yt_slots INTEGER NOT NULL DEFAULT 0,
|
||||
expand_related BOOLEAN NOT NULL DEFAULT 1,
|
||||
refresh_hours INTEGER NOT NULL DEFAULT 24,
|
||||
generated_at TEXT,
|
||||
generation INTEGER NOT NULL DEFAULT 0,
|
||||
last_error TEXT
|
||||
);
|
||||
|
||||
-- Manual, promoted and liked songs are permanent anchors for the mood.
|
||||
CREATE TABLE mood_seeds (
|
||||
playlist_id TEXT NOT NULL REFERENCES moods(playlist_id) ON DELETE CASCADE,
|
||||
song_id TEXT NOT NULL REFERENCES songs(id) ON DELETE CASCADE,
|
||||
origin TEXT NOT NULL DEFAULT 'manual'
|
||||
CHECK (origin IN ('manual', 'promoted', 'star', 'yt_like')),
|
||||
added_at TEXT NOT NULL,
|
||||
PRIMARY KEY (playlist_id, song_id)
|
||||
);
|
||||
|
||||
-- YT Music candidates. The downloader and recommendation UI land in a later
|
||||
-- phase; the table is created now so generation does not need a migration.
|
||||
CREATE TABLE mood_recommendations (
|
||||
playlist_id TEXT NOT NULL REFERENCES moods(playlist_id) ON DELETE CASCADE,
|
||||
video_id TEXT NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
artist TEXT NOT NULL,
|
||||
duration INTEGER,
|
||||
state TEXT NOT NULL DEFAULT 'new'
|
||||
CHECK (state IN ('new', 'liked', 'rejected', 'downloaded')),
|
||||
matched_song_id TEXT REFERENCES songs(id) ON DELETE SET NULL,
|
||||
times_added INTEGER NOT NULL DEFAULT 0,
|
||||
first_seen TEXT NOT NULL,
|
||||
last_seen TEXT NOT NULL,
|
||||
PRIMARY KEY (playlist_id, video_id)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_mood_seeds_song ON mood_seeds (song_id);
|
||||
CREATE INDEX idx_mood_recommendations_song ON mood_recommendations (matched_song_id);
|
||||
@@ -44,12 +44,17 @@
|
||||
#status.error { color:#ff7b72; }
|
||||
#crumb { cursor:pointer; color:var(--accent); }
|
||||
.hidden { display:none !important; }
|
||||
form label { display:grid; gap:5px; font-size:13px; color:var(--muted); }
|
||||
form label.row { display:flex; gap:8px; align-items:center; color:var(--text); }
|
||||
form input[type=checkbox] { width:auto; }
|
||||
.error { color:#ff7b72; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header id="topbar" class="hidden">
|
||||
<h1>MusicManager</h1>
|
||||
<button class="ghost" id="homeBtn">Albums</button>
|
||||
<button class="ghost" id="moodsBtn">Moods</button>
|
||||
<input id="search" placeholder="Search" style="width:220px">
|
||||
<select id="folder"></select>
|
||||
<span class="spacer"></span>
|
||||
@@ -261,6 +266,268 @@ async function search() {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function formatWhen(value) {
|
||||
if (!value) return 'never';
|
||||
const date = new Date(value);
|
||||
return Number.isNaN(date.getTime()) ? value : date.toLocaleString();
|
||||
}
|
||||
|
||||
async function showMoods() {
|
||||
$('app').dataset.moodId = '';
|
||||
setStatus('Loading moods...');
|
||||
try {
|
||||
const moods = (await api('getMoods')).moods?.mood || [];
|
||||
$('title').textContent = 'Moods';
|
||||
$('content').innerHTML = `
|
||||
<div class="row" style="margin-top:12px">
|
||||
<button class="primary" id="newMoodBtn">New mood</button>
|
||||
<button id="promoteMoodBtn">Promote playlist</button>
|
||||
</div>
|
||||
${moods.length ? `<table>
|
||||
<thead><tr><th>Name</th><th>Seeds</th><th>Songs</th><th>Refreshed</th><th></th></tr></thead>
|
||||
<tbody>${moods.map(moodRow).join('')}</tbody>
|
||||
</table>` : '<p class="muted">No moods yet. Create one or promote an existing playlist.</p>'}`;
|
||||
$('newMoodBtn').onclick = showCreateMood;
|
||||
$('promoteMoodBtn').onclick = showPromoteMood;
|
||||
setStatus(`${moods.length} moods`);
|
||||
} catch (error) {
|
||||
setStatus(error.message, true);
|
||||
}
|
||||
}
|
||||
|
||||
function moodRow(mood) {
|
||||
return `<tr>
|
||||
<td><strong>${esc(mood.name)}</strong>${mood.lastError ? ' <span class="error">(generation error)</span>' : ''}</td>
|
||||
<td>${esc(mood.seedCount)}</td>
|
||||
<td>${esc(mood.songCount)}</td>
|
||||
<td class="muted">${esc(formatWhen(mood.generatedAt))}</td>
|
||||
<td class="row" style="justify-content:flex-end">
|
||||
<button data-mood-open="${esc(mood.id)}">Open</button>
|
||||
<button data-mood-refresh="${esc(mood.id)}">Refresh</button>
|
||||
<button data-mood-delete="${esc(mood.id)}">Delete</button>
|
||||
</td>
|
||||
</tr>`;
|
||||
}
|
||||
|
||||
function showCreateMood() {
|
||||
$('app').dataset.moodId = '';
|
||||
$('title').innerHTML = '<span id="crumb">Moods</span> / New mood';
|
||||
$('content').innerHTML = `
|
||||
<form id="moodForm" style="max-width:560px;margin-top:14px;display:grid;gap:10px">
|
||||
<label>Name<input name="name" required placeholder="Focus"></label>
|
||||
<label>Query (optional)<input name="query" placeholder="ambient focus"></label>
|
||||
<label>Genres (comma separated)<input name="genres" placeholder="Ambient, Electronic"></label>
|
||||
<label>Target size<input name="targetSize" type="number" min="1" max="500" value="50"></label>
|
||||
<label>Refresh hours<input name="refreshHours" type="number" min="1" max="720" value="24"></label>
|
||||
<label class="row"><input name="expandRelated" type="checkbox" checked> Fill with related library songs</label>
|
||||
<div class="row"><button class="primary" type="submit">Create mood</button></div>
|
||||
</form>`;
|
||||
$('crumb').onclick = showMoods;
|
||||
$('moodForm').onsubmit = async (event) => {
|
||||
event.preventDefault();
|
||||
const form = new FormData(event.target);
|
||||
try {
|
||||
const mood = (await api('createMood', {
|
||||
name: form.get('name'),
|
||||
query: form.get('query') || '',
|
||||
genres: form.get('genres') || '',
|
||||
targetSize: form.get('targetSize'),
|
||||
refreshHours: form.get('refreshHours'),
|
||||
expandRelated: form.get('expandRelated') ? 'true' : 'false',
|
||||
})).mood;
|
||||
await showMood(mood.id);
|
||||
} catch (error) {
|
||||
setStatus(error.message, true);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async function showPromoteMood() {
|
||||
setStatus('Loading playlists...');
|
||||
try {
|
||||
const [playlistsPayload, moodsPayload] = await Promise.all([api('getPlaylists'), api('getMoods')]);
|
||||
const playlists = playlistsPayload.playlists?.playlist || [];
|
||||
const moodIds = new Set((moodsPayload.moods?.mood || []).map((mood) => mood.id));
|
||||
const owned = playlists.filter((playlist) => playlist.owner === state.user && !moodIds.has(playlist.id));
|
||||
$('title').innerHTML = '<span id="crumb">Moods</span> / Promote playlist';
|
||||
$('content').innerHTML = owned.length ? `
|
||||
<p class="muted">The playlist ID and name stay the same. Its current songs become permanent seeds.</p>
|
||||
<form id="promoteForm" style="max-width:560px;display:grid;gap:10px">
|
||||
<label>Playlist<select name="playlistId">${owned.map((playlist) =>
|
||||
`<option value="${esc(playlist.id)}">${esc(playlist.name)} (${esc(playlist.songCount)})</option>`).join('')}</select></label>
|
||||
<label>Query (optional)<input name="query"></label>
|
||||
<label>Target size<input name="targetSize" type="number" min="1" max="500" value="50"></label>
|
||||
<label>Refresh hours<input name="refreshHours" type="number" min="1" max="720" value="24"></label>
|
||||
<label class="row"><input name="expandRelated" type="checkbox" checked> Fill with related library songs</label>
|
||||
<div class="row"><button class="primary" type="submit">Promote</button></div>
|
||||
</form>` : '<p class="muted">No owned playlists found.</p>';
|
||||
if ($('crumb')) $('crumb').onclick = showMoods;
|
||||
if ($('promoteForm')) $('promoteForm').onsubmit = async (event) => {
|
||||
event.preventDefault();
|
||||
const form = new FormData(event.target);
|
||||
try {
|
||||
const mood = (await api('promotePlaylistToMood', {
|
||||
playlistId: form.get('playlistId'),
|
||||
query: form.get('query') || '',
|
||||
targetSize: form.get('targetSize'),
|
||||
refreshHours: form.get('refreshHours'),
|
||||
expandRelated: form.get('expandRelated') ? 'true' : 'false',
|
||||
})).mood;
|
||||
await showMood(mood.id);
|
||||
} catch (error) {
|
||||
setStatus(error.message, true);
|
||||
}
|
||||
};
|
||||
setStatus(`${owned.length} playlists`);
|
||||
} catch (error) {
|
||||
setStatus(error.message, true);
|
||||
}
|
||||
}
|
||||
|
||||
async function showMood(id) {
|
||||
setStatus('Loading mood...');
|
||||
try {
|
||||
const mood = (await api('getMood', { id })).mood;
|
||||
const seeds = mood.seed || [];
|
||||
const entries = mood.entry || [];
|
||||
$('title').innerHTML = `<span id="crumb">Moods</span> / ${esc(mood.name)}`;
|
||||
$('content').innerHTML = `
|
||||
<div class="row" style="margin-top:12px">
|
||||
<span class="muted">${esc(mood.seedCount)} seeds · ${esc(mood.songCount)} songs · refreshed ${esc(formatWhen(mood.generatedAt))}</span>
|
||||
<span class="spacer" style="flex:1"></span>
|
||||
<button id="moodRefresh">Refresh now</button>
|
||||
<button id="moodDelete">Delete mood</button>
|
||||
</div>
|
||||
${mood.lastError ? `<p class="error">${esc(mood.lastError)}</p>` : ''}
|
||||
<form id="moodSettings" style="max-width:560px;margin-top:14px;display:grid;gap:10px">
|
||||
<label>Name<input name="name" required value="${esc(mood.name)}"></label>
|
||||
<label>Query (optional)<input name="query" value="${esc(mood.query || '')}"></label>
|
||||
<label>Genres (comma separated)<input name="genres" value="${esc((mood.genres || []).join(', '))}"></label>
|
||||
<label>Target size<input name="targetSize" type="number" min="1" max="500" value="${esc(mood.targetSize)}"></label>
|
||||
<label>YT slots (reserved)<input name="ytSlots" type="number" min="0" max="500" value="${esc(mood.ytSlots)}"></label>
|
||||
<label>Refresh hours<input name="refreshHours" type="number" min="1" max="720" value="${esc(mood.refreshHours)}"></label>
|
||||
<label class="row"><input name="expandRelated" type="checkbox" ${mood.expandRelated ? 'checked' : ''}> Fill with related library songs</label>
|
||||
<div class="row"><button class="primary" type="submit">Save settings</button></div>
|
||||
</form>
|
||||
<h3>Seeds</h3>
|
||||
${seeds.length ? `<table><tbody>${seeds.map((song) => `
|
||||
<tr><td>${esc(song.title)}</td><td class="muted">${esc(song.artist || '')}</td>
|
||||
<td style="text-align:right"><button data-seed-remove="${esc(song.id)}">Remove</button></td></tr>`).join('')}</tbody></table>`
|
||||
: '<p class="muted">No seeds yet. Add songs below or promote a playlist.</p>'}
|
||||
<h3>Add seed</h3>
|
||||
<div class="row">
|
||||
<input id="seedSearch" placeholder="Search library" style="min-width:260px">
|
||||
<button id="seedSearchBtn">Search</button>
|
||||
</div>
|
||||
<div id="seedResults"></div>
|
||||
<h3>Current mix</h3>
|
||||
${entries.length ? `<table><tbody>${entries.map(songRow).join('')}</tbody></table>` : '<p class="muted">The mix is empty.</p>'}`;
|
||||
|
||||
$('app').dataset.moodId = id;
|
||||
$('crumb').onclick = showMoods;
|
||||
$('moodRefresh').onclick = async () => {
|
||||
try {
|
||||
await api('refreshMood', { id });
|
||||
await showMood(id);
|
||||
} catch (error) { setStatus(error.message, true); }
|
||||
};
|
||||
$('moodDelete').onclick = async () => {
|
||||
if (!confirm(`Delete mood "${mood.name}"?`)) return;
|
||||
try {
|
||||
await api('deleteMood', { id });
|
||||
await showMoods();
|
||||
} catch (error) { setStatus(error.message, true); }
|
||||
};
|
||||
$('moodSettings').onsubmit = async (event) => {
|
||||
event.preventDefault();
|
||||
const form = new FormData(event.target);
|
||||
try {
|
||||
await api('updateMood', {
|
||||
id,
|
||||
name: form.get('name'),
|
||||
query: form.get('query') || '',
|
||||
genres: form.get('genres') || '',
|
||||
targetSize: form.get('targetSize'),
|
||||
ytSlots: form.get('ytSlots'),
|
||||
refreshHours: form.get('refreshHours'),
|
||||
expandRelated: form.get('expandRelated') ? 'true' : 'false',
|
||||
});
|
||||
await showMood(id);
|
||||
} catch (error) { setStatus(error.message, true); }
|
||||
};
|
||||
$('seedSearchBtn').onclick = () => searchSeeds(id, seeds);
|
||||
$('seedSearch').addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Enter') { event.preventDefault(); searchSeeds(id, seeds); }
|
||||
});
|
||||
|
||||
setStatus(`${seeds.length} seeds, ${entries.length} songs`);
|
||||
} catch (error) {
|
||||
setStatus(error.message, true);
|
||||
}
|
||||
}
|
||||
|
||||
async function searchSeeds(moodId, seeds) {
|
||||
const query = $('seedSearch').value.trim();
|
||||
if (!query) return;
|
||||
setStatus('Searching...');
|
||||
try {
|
||||
const result = (await api('search3', { query, songCount: '30', albumCount: '0', artistCount: '0' })).searchResult3 || {};
|
||||
const seedIds = new Set(seeds.map((song) => song.id));
|
||||
const songs = (result.song || []).filter((song) => !seedIds.has(song.id));
|
||||
$('seedResults').innerHTML = songs.length
|
||||
? `<table><tbody>${songs.map((song) => `
|
||||
<tr><td>${esc(song.title)}</td><td class="muted">${esc(song.artist || '')}</td>
|
||||
<td style="text-align:right"><button data-seed-add="${esc(song.id)}">Add</button></td></tr>`).join('')}</tbody></table>`
|
||||
: '<p class="muted">No matching songs, or all are already seeds.</p>';
|
||||
setStatus(`${songs.length} results`);
|
||||
} catch (error) {
|
||||
setStatus(error.message, true);
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('click', (event) => {
|
||||
const open = event.target.closest('[data-mood-open]');
|
||||
if (open) { showMood(open.dataset.moodOpen); return; }
|
||||
|
||||
const refresh = event.target.closest('[data-mood-refresh]');
|
||||
if (refresh) {
|
||||
api('refreshMood', { id: refresh.dataset.moodRefresh })
|
||||
.then(() => showMoods())
|
||||
.catch((error) => setStatus(error.message, true));
|
||||
return;
|
||||
}
|
||||
|
||||
const remove = event.target.closest('[data-mood-delete]');
|
||||
if (remove) {
|
||||
const id = remove.dataset.moodDelete;
|
||||
if (!confirm('Delete this mood?')) return;
|
||||
api('deleteMood', { id })
|
||||
.then(() => showMoods())
|
||||
.catch((error) => setStatus(error.message, true));
|
||||
return;
|
||||
}
|
||||
|
||||
const addSeed = event.target.closest('[data-seed-add]');
|
||||
if (addSeed) {
|
||||
const moodId = addSeed.closest('main').dataset.moodId;
|
||||
if (!moodId) return;
|
||||
api('addMoodSeed', { id: moodId, songId: addSeed.dataset.seedAdd })
|
||||
.then(() => showMood(moodId))
|
||||
.catch((error) => setStatus(error.message, true));
|
||||
return;
|
||||
}
|
||||
|
||||
const removeSeed = event.target.closest('[data-seed-remove]');
|
||||
if (removeSeed) {
|
||||
const moodId = removeSeed.closest('main').dataset.moodId;
|
||||
if (!moodId) return;
|
||||
api('removeMoodSeed', { id: moodId, songId: removeSeed.dataset.seedRemove })
|
||||
.then(() => showMood(moodId))
|
||||
.catch((error) => setStatus(error.message, true));
|
||||
}
|
||||
});
|
||||
|
||||
function formatDuration(seconds) {
|
||||
const total = Math.max(0, Math.floor(seconds || 0));
|
||||
return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`;
|
||||
@@ -291,6 +558,7 @@ document.addEventListener('click', (event) => {
|
||||
$('loginBtn').onclick = login;
|
||||
$('password').addEventListener('keydown', (event) => { if (event.key === 'Enter') login(); });
|
||||
$('homeBtn').onclick = showAlbums;
|
||||
$('moodsBtn').onclick = showMoods;
|
||||
$('logout').onclick = logout;
|
||||
$('search').addEventListener('keydown', (event) => { if (event.key === 'Enter') search(); });
|
||||
$('folder').onchange = () => { state.folderId = $('folder').value; showAlbums(); };
|
||||
|
||||
@@ -20,6 +20,8 @@ import io.ktor.server.testing.testApplication
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Path
|
||||
import java.time.Instant
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.int
|
||||
@@ -50,6 +52,7 @@ import win.taptap.musicmanager.db.MediaRepository
|
||||
import win.taptap.musicmanager.db.SongArtistsTable
|
||||
import win.taptap.musicmanager.db.SongGenresTable
|
||||
import win.taptap.musicmanager.db.SongsTable
|
||||
import win.taptap.musicmanager.mood.MoodService
|
||||
import win.taptap.musicmanager.scanner.CoverArtService
|
||||
import win.taptap.musicmanager.scanner.ScanStatus
|
||||
import win.taptap.musicmanager.subsonic.routes.subsonicRoutes
|
||||
@@ -448,6 +451,7 @@ class BrowsingRoutesTest {
|
||||
library = seed.library,
|
||||
coverArtService = seed.coverArt,
|
||||
transcoder = FfmpegTranscoder("ffmpeg"),
|
||||
moodService = MoodService(CoroutineScope(Dispatchers.Unconfined)),
|
||||
startScan = { false },
|
||||
scanStatus = { ScanStatus(false, 0) },
|
||||
)
|
||||
|
||||
@@ -0,0 +1,410 @@
|
||||
package win.taptap.musicmanager.subsonic
|
||||
|
||||
import io.ktor.client.HttpClient
|
||||
import io.ktor.client.request.get
|
||||
import io.ktor.client.statement.bodyAsText
|
||||
import io.ktor.serialization.kotlinx.json.json
|
||||
import io.ktor.server.application.install
|
||||
import io.ktor.server.plugins.contentnegotiation.ContentNegotiation
|
||||
import io.ktor.server.plugins.partialcontent.PartialContent
|
||||
import io.ktor.server.routing.routing
|
||||
import io.ktor.server.testing.ApplicationTestBuilder
|
||||
import io.ktor.server.testing.testApplication
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Path
|
||||
import java.time.Instant
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.int
|
||||
import kotlinx.serialization.json.jsonArray
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFalse
|
||||
import kotlin.test.assertTrue
|
||||
import org.jetbrains.exposed.sql.insert
|
||||
import org.jetbrains.exposed.sql.insertIgnore
|
||||
import org.jetbrains.exposed.sql.transactions.transaction
|
||||
import org.junit.jupiter.api.io.TempDir
|
||||
import win.taptap.musicmanager.config.AppConfig
|
||||
import win.taptap.musicmanager.config.FolderType
|
||||
import win.taptap.musicmanager.config.LibraryConfig
|
||||
import win.taptap.musicmanager.config.MusicFolder
|
||||
import win.taptap.musicmanager.config.UserAccount
|
||||
import win.taptap.musicmanager.config.UsersConfig
|
||||
import win.taptap.musicmanager.db.AlbumArtistsTable
|
||||
import win.taptap.musicmanager.db.AlbumsTable
|
||||
import win.taptap.musicmanager.db.ArtistsTable
|
||||
import win.taptap.musicmanager.db.ConfigRepository
|
||||
import win.taptap.musicmanager.db.DatabaseFactory
|
||||
import win.taptap.musicmanager.db.DatabaseHandle
|
||||
import win.taptap.musicmanager.db.SongArtistsTable
|
||||
import win.taptap.musicmanager.db.SongGenresTable
|
||||
import win.taptap.musicmanager.db.SongsTable
|
||||
import win.taptap.musicmanager.mood.MoodService
|
||||
import win.taptap.musicmanager.mood.MoodSessionTracker
|
||||
import win.taptap.musicmanager.scanner.CoverArtService
|
||||
import win.taptap.musicmanager.scanner.ScanStatus
|
||||
import win.taptap.musicmanager.subsonic.routes.subsonicRoutes
|
||||
import win.taptap.musicmanager.transcoding.FfmpegTranscoder
|
||||
import win.taptap.musicmanager.util.IdGenerator
|
||||
|
||||
class MoodRoutesTest {
|
||||
|
||||
@TempDir
|
||||
lateinit var tempDir: Path
|
||||
|
||||
@Test
|
||||
fun `creating a mood generates a private music-only playlist`() {
|
||||
clearSessions()
|
||||
seededContext().use { seed ->
|
||||
testApplication {
|
||||
setupApp(seed)
|
||||
val auth = credentials("alice", "alice-pw")
|
||||
|
||||
val mood = client.createMood(auth, "Focus", listOf(seed.aliceAmbient1), target = 10)
|
||||
val id = mood.string("id")
|
||||
assertEquals(1, mood.int("seedCount"))
|
||||
assertTrue(mood.string("generatedAt").isNotBlank())
|
||||
|
||||
val entries = mood.ids("entry")
|
||||
assertTrue(seed.aliceAmbient1 in entries)
|
||||
assertTrue(seed.aliceAmbient2 in entries)
|
||||
assertFalse(seed.bobSong in entries)
|
||||
assertFalse(seed.longformSong in entries)
|
||||
|
||||
// A long-form song is not a valid mood seed and must not enter the mix.
|
||||
val bookish = client.createMood(auth, "Bookish", listOf(seed.longformSong), target = 5)
|
||||
assertEquals(0, bookish.int("seedCount"))
|
||||
assertEquals(0, bookish.ids("entry").size)
|
||||
|
||||
val playlist = parseBody(
|
||||
client.get("/rest/getPlaylist?$auth&id=$id").bodyAsText(),
|
||||
)["playlist"]!!.jsonObject
|
||||
assertEquals("Focus", playlist.string("name"))
|
||||
assertEquals(entries.size, playlist["entry"]!!.jsonArray.size)
|
||||
|
||||
val bobAuth = credentials("bob", "bob-pw")
|
||||
val bobMoods = parseBody(client.get("/rest/getMoods?$bobAuth").bodyAsText())["moods"]!!.jsonObject
|
||||
assertEquals(0, bobMoods["mood"]?.jsonArray?.size ?: 0)
|
||||
|
||||
val denied = parseBody(client.get("/rest/getPlaylist?$bobAuth&id=$id").bodyAsText())
|
||||
assertEquals(70, denied["error"]!!.jsonObject["code"]!!.jsonPrimitive.int)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `promoting a playlist keeps its id and rejects song edits`() {
|
||||
clearSessions()
|
||||
seededContext().use { seed ->
|
||||
testApplication {
|
||||
setupApp(seed)
|
||||
val auth = credentials("alice", "alice-pw")
|
||||
|
||||
val playlist = parseBody(
|
||||
client.get(
|
||||
"/rest/createPlaylist?$auth&name=Road&songId=${seed.aliceAmbient1}&songId=${seed.aliceAmbient2}",
|
||||
).bodyAsText(),
|
||||
)["playlist"]!!.jsonObject
|
||||
val id = playlist.string("id")
|
||||
|
||||
val promoted = parseBody(
|
||||
client.get("/rest/promotePlaylistToMood?$auth&playlistId=$id&targetSize=10").bodyAsText(),
|
||||
)["mood"]!!.jsonObject
|
||||
assertEquals(id, promoted.string("id"))
|
||||
assertEquals(2, promoted.int("seedCount"))
|
||||
assertEquals(2, promoted.ids("seed").size)
|
||||
assertTrue(seed.aliceAmbient1 in promoted.ids("entry"))
|
||||
|
||||
val edit = parseBody(
|
||||
client.get(
|
||||
"/rest/updatePlaylist?$auth&playlistId=$id&songIdToAdd=${seed.aliceRock}",
|
||||
).bodyAsText(),
|
||||
)
|
||||
assertEquals(50, edit["error"]!!.jsonObject["code"]!!.jsonPrimitive.int)
|
||||
|
||||
val bobAuth = credentials("bob", "bob-pw")
|
||||
val denied = parseBody(client.get("/rest/getPlaylist?$bobAuth&id=$id").bodyAsText())
|
||||
assertEquals(70, denied["error"]!!.jsonObject["code"]!!.jsonPrimitive.int)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `star pins to the active mood and unstar removes only star seeds`() {
|
||||
clearSessions()
|
||||
seededContext().use { seed ->
|
||||
testApplication {
|
||||
setupApp(seed)
|
||||
val auth = credentials("alice", "alice-pw")
|
||||
|
||||
val mood = client.createMood(
|
||||
auth,
|
||||
"Pinned",
|
||||
listOf(seed.aliceAmbient1),
|
||||
target = 10,
|
||||
expandRelated = false,
|
||||
)
|
||||
val id = mood.string("id")
|
||||
|
||||
// Opening the mood makes it active.
|
||||
client.get("/rest/getPlaylist?$auth&id=$id").bodyAsText()
|
||||
|
||||
val star = parseBody(client.get("/rest/star?$auth&id=${seed.aliceAmbient2}").bodyAsText())
|
||||
assertEquals("ok", star.string("status"))
|
||||
|
||||
val afterStar = parseBody(client.get("/rest/getMood?$auth&id=$id").bodyAsText())["mood"]!!.jsonObject
|
||||
assertEquals(2, afterStar.int("seedCount"))
|
||||
assertTrue(seed.aliceAmbient2 in afterStar.ids("seed"))
|
||||
assertTrue(seed.aliceAmbient1 in afterStar.ids("seed"))
|
||||
|
||||
val refreshed = parseBody(client.get("/rest/refreshMood?$auth&id=$id").bodyAsText())["mood"]!!.jsonObject
|
||||
assertTrue(seed.aliceAmbient2 in refreshed.ids("entry"))
|
||||
|
||||
parseBody(client.get("/rest/unstar?$auth&id=${seed.aliceAmbient2}").bodyAsText())
|
||||
val afterUnstar = parseBody(client.get("/rest/getMood?$auth&id=$id").bodyAsText())["mood"]!!.jsonObject
|
||||
assertEquals(1, afterUnstar.int("seedCount"))
|
||||
assertTrue(seed.aliceAmbient1 in afterUnstar.ids("seed"))
|
||||
assertFalse(seed.aliceAmbient2 in afterUnstar.ids("seed"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `star without a session pins moods that already contain the song`() {
|
||||
clearSessions()
|
||||
seededContext().use { seed ->
|
||||
testApplication {
|
||||
setupApp(seed)
|
||||
val auth = credentials("alice", "alice-pw")
|
||||
|
||||
val mood = client.createMood(auth, "Related", listOf(seed.aliceAmbient1), target = 10)
|
||||
val id = mood.string("id")
|
||||
assertTrue(seed.aliceAmbient2 in mood.ids("entry"))
|
||||
|
||||
// No getPlaylist call: there is no active mood session.
|
||||
parseBody(client.get("/rest/star?$auth&id=${seed.aliceAmbient2}").bodyAsText())
|
||||
|
||||
val afterStar = parseBody(client.get("/rest/getMood?$auth&id=$id").bodyAsText())["mood"]!!.jsonObject
|
||||
assertEquals(2, afterStar.int("seedCount"))
|
||||
assertTrue(seed.aliceAmbient2 in afterStar.ids("seed"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun ApplicationTestBuilder.setupApp(seed: Seed) {
|
||||
application {
|
||||
install(ContentNegotiation) {
|
||||
json(Json { ignoreUnknownKeys = true; encodeDefaults = true })
|
||||
}
|
||||
install(PartialContent)
|
||||
routing {
|
||||
subsonicRoutes(
|
||||
users = seed.users,
|
||||
library = seed.library,
|
||||
coverArtService = seed.coverArt,
|
||||
transcoder = FfmpegTranscoder("ffmpeg"),
|
||||
moodService = MoodService(CoroutineScope(Dispatchers.Unconfined)),
|
||||
startScan = { false },
|
||||
scanStatus = { ScanStatus(false, 0) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun seededContext(): Seed {
|
||||
val musicA = Files.createDirectories(tempDir.resolve("music-a"))
|
||||
val musicB = Files.createDirectories(tempDir.resolve("music-b"))
|
||||
val longform = Files.createDirectories(tempDir.resolve("longform"))
|
||||
|
||||
val library = LibraryConfig(
|
||||
listOf(
|
||||
MusicFolder(1, "Alice Music", FolderType.MUSIC, musicA),
|
||||
MusicFolder(2, "Bob Music", FolderType.MUSIC, musicB),
|
||||
MusicFolder(10, "Long-form", FolderType.LONGFORM, longform),
|
||||
),
|
||||
)
|
||||
val users = UsersConfig(
|
||||
listOf(
|
||||
UserAccount("alice", "alice-pw", admin = true, folders = setOf(1)),
|
||||
UserAccount("bob", "bob-pw", admin = false, folders = setOf(2)),
|
||||
),
|
||||
)
|
||||
|
||||
val db = DatabaseFactory.connect(
|
||||
AppConfig(
|
||||
port = 8080,
|
||||
dataDir = tempDir.resolve("data"),
|
||||
libraryConfigPath = tempDir.resolve("library.yaml"),
|
||||
usersFile = tempDir.resolve("users.yaml"),
|
||||
ffmpegPath = "ffmpeg",
|
||||
),
|
||||
)
|
||||
ConfigRepository.sync(library, users)
|
||||
|
||||
val aliceAmbient1 = seedSong(
|
||||
db, 1, "Alpha", "Focus One", "Deep Work",
|
||||
"Alpha/Focus One/01.mp3", "Ambient", musicA,
|
||||
)
|
||||
val aliceAmbient2 = seedSong(
|
||||
db, 1, "Beta", "Focus Two", "Soft Light",
|
||||
"Beta/Focus Two/01.mp3", "Ambient", musicA,
|
||||
)
|
||||
val aliceRock = seedSong(
|
||||
db, 1, "Gamma", "Loud", "Noise",
|
||||
"Gamma/Loud/01.mp3", "Rock", musicA,
|
||||
)
|
||||
val aliceAmbient3 = seedSong(
|
||||
db, 1, "Alpha", "Focus One", "Second Wind",
|
||||
"Alpha/Focus One/02.mp3", "Ambient", musicA,
|
||||
)
|
||||
val bobSong = seedSong(
|
||||
db, 2, "Bob Artist", "Bob Album", "Bob Song",
|
||||
"Bob Artist/Bob Album/01.mp3", "Ambient", musicB,
|
||||
)
|
||||
val longformSong = seedSong(
|
||||
db, 10, "Long Narrator", "Long Book", "Chapter One",
|
||||
"Long Narrator/Long Book/01.mp3", "Ambient", longform,
|
||||
)
|
||||
|
||||
return Seed(
|
||||
db = db,
|
||||
library = library,
|
||||
users = users,
|
||||
coverArt = CoverArtService(tempDir.resolve("data")),
|
||||
aliceAmbient1 = aliceAmbient1,
|
||||
aliceAmbient2 = aliceAmbient2,
|
||||
aliceRock = aliceRock,
|
||||
aliceAmbient3 = aliceAmbient3,
|
||||
bobSong = bobSong,
|
||||
longformSong = longformSong,
|
||||
)
|
||||
}
|
||||
|
||||
private fun seedSong(
|
||||
db: DatabaseHandle,
|
||||
folderId: Int,
|
||||
artistName: String,
|
||||
albumName: String,
|
||||
title: String,
|
||||
relativePath: String,
|
||||
genre: String,
|
||||
root: Path,
|
||||
): String {
|
||||
val file = root.resolve(relativePath)
|
||||
Files.createDirectories(file.parent)
|
||||
Files.write(file, "ID3-fake-audio".toByteArray())
|
||||
|
||||
val artistId = IdGenerator.artistId(artistName)
|
||||
val albumId = IdGenerator.albumId(artistName, albumName)
|
||||
val songId = IdGenerator.songId(folderId, relativePath)
|
||||
val now = Instant.now().toString()
|
||||
|
||||
transaction(db.database) {
|
||||
ArtistsTable.insertIgnore {
|
||||
it[id] = artistId
|
||||
it[name] = artistName
|
||||
it[sortName] = artistName
|
||||
it[searchText] = IdGenerator.normalize(artistName)
|
||||
}
|
||||
AlbumsTable.insertIgnore {
|
||||
it[id] = albumId
|
||||
it[name] = albumName
|
||||
it[year] = 2026
|
||||
it[createdAt] = now
|
||||
it[searchText] = IdGenerator.normalize("$albumName $artistName")
|
||||
}
|
||||
AlbumArtistsTable.insertIgnore {
|
||||
it[this.albumId] = albumId
|
||||
it[this.artistId] = artistId
|
||||
it[position] = 0
|
||||
}
|
||||
SongsTable.insert {
|
||||
it[id] = songId
|
||||
it[this.albumId] = albumId
|
||||
it[this.folderId] = folderId
|
||||
it[this.title] = title
|
||||
it[displayArtist] = artistName
|
||||
it[this.albumName] = albumName
|
||||
it[trackNumber] = 1
|
||||
it[discNumber] = 1
|
||||
it[year] = 2026
|
||||
it[duration] = 120
|
||||
it[bitRate] = 128
|
||||
it[size] = Files.size(file)
|
||||
it[suffix] = "mp3"
|
||||
it[contentType] = "audio/mpeg"
|
||||
it[this.relativePath] = relativePath
|
||||
it[fileMtime] = 0
|
||||
it[createdAt] = now
|
||||
it[searchText] = IdGenerator.normalize("$title $artistName $albumName $artistName")
|
||||
}
|
||||
SongArtistsTable.insert {
|
||||
it[this.songId] = songId
|
||||
it[this.artistId] = artistId
|
||||
it[position] = 0
|
||||
}
|
||||
SongGenresTable.insert {
|
||||
it[this.songId] = songId
|
||||
it[this.genre] = genre
|
||||
}
|
||||
}
|
||||
|
||||
return songId
|
||||
}
|
||||
|
||||
private suspend fun HttpClient.createMood(
|
||||
auth: String,
|
||||
name: String,
|
||||
seeds: List<String>,
|
||||
target: Int,
|
||||
expandRelated: Boolean = true,
|
||||
): JsonObject {
|
||||
val seedParams = seeds.joinToString("") { "&songId=$it" }
|
||||
val body = get(
|
||||
"/rest/createMood?$auth&name=$name$seedParams&targetSize=$target&expandRelated=$expandRelated",
|
||||
).bodyAsText()
|
||||
return parseBody(body)["mood"]!!.jsonObject
|
||||
}
|
||||
|
||||
private fun clearSessions() {
|
||||
MoodSessionTracker.clear("alice")
|
||||
MoodSessionTracker.clear("bob")
|
||||
}
|
||||
|
||||
private fun credentials(user: String, password: String): String {
|
||||
val salt = "test-salt"
|
||||
return "u=$user&t=${SubsonicAuthenticator.md5Hex(password + salt)}&s=$salt"
|
||||
}
|
||||
|
||||
private fun parseBody(body: String): JsonObject =
|
||||
Json.parseToJsonElement(body).jsonObject["subsonic-response"]!!.jsonObject
|
||||
|
||||
private fun JsonObject.string(name: String): String =
|
||||
this[name]!!.jsonPrimitive.content
|
||||
|
||||
private fun JsonObject.int(name: String): Int =
|
||||
this[name]!!.jsonPrimitive.int
|
||||
|
||||
private fun JsonObject.ids(name: String): List<String> =
|
||||
this[name]!!.jsonArray.map { it.jsonObject["id"]!!.jsonPrimitive.content }
|
||||
|
||||
private data class Seed(
|
||||
val db: DatabaseHandle,
|
||||
val library: LibraryConfig,
|
||||
val users: UsersConfig,
|
||||
val coverArt: CoverArtService,
|
||||
val aliceAmbient1: String,
|
||||
val aliceAmbient2: String,
|
||||
val aliceRock: String,
|
||||
val aliceAmbient3: String,
|
||||
val bobSong: String,
|
||||
val longformSong: String,
|
||||
) : AutoCloseable {
|
||||
override fun close() = db.close()
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,8 @@ import io.ktor.server.plugins.contentnegotiation.ContentNegotiation
|
||||
import io.ktor.server.routing.routing
|
||||
import io.ktor.server.testing.ApplicationTestBuilder
|
||||
import io.ktor.server.testing.testApplication
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.int
|
||||
@@ -25,6 +27,7 @@ import win.taptap.musicmanager.config.LibraryConfig
|
||||
import win.taptap.musicmanager.config.MusicFolder
|
||||
import win.taptap.musicmanager.config.UserAccount
|
||||
import win.taptap.musicmanager.config.UsersConfig
|
||||
import win.taptap.musicmanager.mood.MoodService
|
||||
import win.taptap.musicmanager.scanner.CoverArtService
|
||||
import win.taptap.musicmanager.scanner.ScanStatus
|
||||
import win.taptap.musicmanager.subsonic.routes.subsonicRoutes
|
||||
@@ -180,6 +183,7 @@ class SystemRoutesTest {
|
||||
),
|
||||
coverArtService = CoverArtService(tempDir.resolve("data")),
|
||||
transcoder = FfmpegTranscoder("ffmpeg"),
|
||||
moodService = MoodService(CoroutineScope(Dispatchers.Unconfined)),
|
||||
startScan = startScan,
|
||||
scanStatus = scanStatus,
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user