feat: add home feeds, interaction endpoints and playlists
- getAlbumList2/getAlbumList, getRandomSongs, getGenres, getSongsByGenre, getStarred2/getStarred, artist/album info and similar/top stubs - scrobble, star/unstar, setRating, bookmarks and lyrics - playlist create/get/update/delete with ownership and visibility rules - persist scanned lyrics via V3 migration - include last-played timestamps in song and album responses
This commit is contained in:
1 parent
43e726628e
commit
46266d8071
14 files changed
+1400
-9
No files matched your search
@@ -3,10 +3,12 @@ package win.taptap.musicmanager.db
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Path
|
||||
import org.jetbrains.exposed.sql.JoinType
|
||||
import org.jetbrains.exposed.sql.Op
|
||||
import org.jetbrains.exposed.sql.ResultRow
|
||||
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.selectAll
|
||||
import org.jetbrains.exposed.sql.transactions.transaction
|
||||
import org.jetbrains.exposed.sql.union
|
||||
@@ -19,10 +21,19 @@ data class UserItemState(val starredAt: String?, val rating: Int?)
|
||||
|
||||
data class UserSongState(
|
||||
val playCount: Int,
|
||||
val lastPlayedAt: String?,
|
||||
val starredAt: String?,
|
||||
val rating: Int?,
|
||||
)
|
||||
|
||||
data class GenreRecord(val value: String, val songCount: Int, val albumCount: Int)
|
||||
|
||||
data class StarredRecords(
|
||||
val artists: List<ArtistRecord>,
|
||||
val albums: List<AlbumRecord>,
|
||||
val songs: List<SongRecord>,
|
||||
)
|
||||
|
||||
data class ArtistRecord(
|
||||
val id: String,
|
||||
val name: String,
|
||||
@@ -42,6 +53,7 @@ data class AlbumRecord(
|
||||
val songCount: Int,
|
||||
val duration: Int,
|
||||
val playCount: Int,
|
||||
val lastPlayedAt: String?,
|
||||
val created: String,
|
||||
val starredAt: String?,
|
||||
val rating: Int?,
|
||||
@@ -71,6 +83,7 @@ data class SongRecord(
|
||||
val starredAt: String?,
|
||||
val rating: Int?,
|
||||
val playCount: Int,
|
||||
val lastPlayedAt: String?,
|
||||
val artists: List<ArtistRefRecord>,
|
||||
val genres: List<String>,
|
||||
)
|
||||
@@ -240,7 +253,210 @@ object LibraryRepository {
|
||||
enrichSongs(rows, userName)
|
||||
}
|
||||
|
||||
fun searchArtists( query: String,
|
||||
/**
|
||||
* Album feed used by getAlbumList2. Sorting happens after visibility filtering so
|
||||
* per-user play counts and stars are correct.
|
||||
*/
|
||||
fun albumList(
|
||||
type: String,
|
||||
size: Int,
|
||||
offset: Int,
|
||||
fromYear: Int?,
|
||||
toYear: Int?,
|
||||
genre: String?,
|
||||
folderIds: Set<Int>,
|
||||
userName: String,
|
||||
): List<AlbumRecord> = read {
|
||||
if (folderIds.isEmpty()) return@read emptyList()
|
||||
|
||||
val ids = AlbumsTable
|
||||
.select(AlbumsTable.id)
|
||||
.where { AlbumsTable.id inSubQuery visibleAlbums(folderIds) }
|
||||
.map { it[AlbumsTable.id] }
|
||||
|
||||
var albums = ids.mapNotNull { albumRecord(it, folderIds, userName) }
|
||||
if (fromYear != null) albums = albums.filter { (it.year ?: Int.MIN_VALUE) >= fromYear }
|
||||
if (toYear != null) albums = albums.filter { (it.year ?: Int.MAX_VALUE) <= toYear }
|
||||
if (!genre.isNullOrBlank()) {
|
||||
albums = albums.filter { album -> album.genres.any { it.equals(genre, ignoreCase = true) } }
|
||||
}
|
||||
|
||||
val sorted = when (type) {
|
||||
"newest" -> albums.sortedByDescending { it.created }
|
||||
"recent" -> albums.sortedWith(
|
||||
compareByDescending<AlbumRecord> { it.lastPlayedAt ?: "" }
|
||||
.thenByDescending { it.created },
|
||||
)
|
||||
"frequent" -> albums.sortedWith(
|
||||
compareByDescending<AlbumRecord> { it.playCount }
|
||||
.thenBy { IdGenerator.normalize(it.name) },
|
||||
)
|
||||
"random" -> albums.shuffled()
|
||||
"alphabeticalByName" -> albums.sortedBy { IdGenerator.normalize(it.name) }
|
||||
"alphabeticalByArtist" -> albums.sortedWith(
|
||||
compareBy(
|
||||
{ IdGenerator.normalize(it.artistName.orEmpty()) },
|
||||
{ IdGenerator.normalize(it.name) },
|
||||
),
|
||||
)
|
||||
"starred" -> albums
|
||||
.filter { it.starredAt != null }
|
||||
.sortedByDescending { it.starredAt }
|
||||
"byYear" -> albums.sortedWith(
|
||||
compareByDescending<AlbumRecord> { it.year ?: 0 }
|
||||
.thenBy { IdGenerator.normalize(it.name) },
|
||||
)
|
||||
"byGenre" -> albums.sortedBy { IdGenerator.normalize(it.name) }
|
||||
else -> albums.sortedBy { IdGenerator.normalize(it.name) }
|
||||
}
|
||||
|
||||
sorted.drop(offset).take(size)
|
||||
}
|
||||
|
||||
fun randomSongs(
|
||||
size: Int,
|
||||
genre: String?,
|
||||
fromYear: Int?,
|
||||
toYear: Int?,
|
||||
folderIds: Set<Int>,
|
||||
userName: String,
|
||||
): List<SongRecord> = read {
|
||||
if (folderIds.isEmpty()) return@read emptyList()
|
||||
|
||||
val rows = SongsTable.selectAll()
|
||||
.where {
|
||||
(SongsTable.folderId inList folderIds) and
|
||||
(fromYear?.let { SongsTable.year greaterEq it } ?: Op.TRUE) and
|
||||
(toYear?.let { SongsTable.year lessEq it } ?: Op.TRUE)
|
||||
}
|
||||
.toList()
|
||||
|
||||
var songs = enrichSongs(rows, userName)
|
||||
if (!genre.isNullOrBlank()) {
|
||||
songs = songs.filter { song -> song.genres.any { it.equals(genre, ignoreCase = true) } }
|
||||
}
|
||||
|
||||
songs.shuffled().take(size)
|
||||
}
|
||||
|
||||
fun genres(folderIds: Set<Int>): List<GenreRecord> = read {
|
||||
if (folderIds.isEmpty()) return@read emptyList()
|
||||
|
||||
val rows = SongGenresTable
|
||||
.join(SongsTable, JoinType.INNER, SongGenresTable.songId, SongsTable.id)
|
||||
.select(SongGenresTable.genre, SongsTable.id, SongsTable.albumId)
|
||||
.where { SongsTable.folderId inList folderIds }
|
||||
.toList()
|
||||
|
||||
rows.groupBy { it[SongGenresTable.genre] }
|
||||
.map { (genre, genreRows) ->
|
||||
GenreRecord(
|
||||
value = genre,
|
||||
songCount = genreRows.map { it[SongsTable.id] }.distinct().size,
|
||||
albumCount = genreRows.map { it[SongsTable.albumId] }.distinct().size,
|
||||
)
|
||||
}
|
||||
.sortedBy { IdGenerator.normalize(it.value) }
|
||||
}
|
||||
|
||||
fun songsByGenre(
|
||||
genre: String,
|
||||
size: Int,
|
||||
offset: Int,
|
||||
folderIds: Set<Int>,
|
||||
userName: String,
|
||||
): List<SongRecord> = read {
|
||||
if (folderIds.isEmpty()) return@read emptyList()
|
||||
|
||||
val songIds = SongGenresTable
|
||||
.select(SongGenresTable.songId)
|
||||
.where { SongGenresTable.genre.lowerCase() eq genre.lowercase() }
|
||||
|
||||
val rows = SongsTable.selectAll()
|
||||
.where {
|
||||
(SongsTable.id inSubQuery songIds) and
|
||||
(SongsTable.folderId inList folderIds)
|
||||
}
|
||||
.orderBy(SongsTable.title to SortOrder.ASC)
|
||||
.limit(size)
|
||||
.offset(offset.toLong())
|
||||
.toList()
|
||||
|
||||
enrichSongs(rows, userName)
|
||||
}
|
||||
|
||||
fun starred(userName: String, folderIds: Set<Int>): StarredRecords = read {
|
||||
if (folderIds.isEmpty()) {
|
||||
return@read StarredRecords(emptyList(), emptyList(), emptyList())
|
||||
}
|
||||
|
||||
val albumStates = itemStates(userName, "album")
|
||||
val albums = albumStates
|
||||
.filterValues { it.starredAt != null }
|
||||
.keys
|
||||
.mapNotNull { albumRecord(it, folderIds, userName) }
|
||||
.sortedByDescending { it.starredAt }
|
||||
|
||||
val artistStates = itemStates(userName, "artist")
|
||||
val artists = artistStates
|
||||
.filterValues { it.starredAt != null }
|
||||
.keys
|
||||
.mapNotNull { artist(it, folderIds, userName) }
|
||||
.sortedByDescending { it.starredAt }
|
||||
|
||||
val songStates = UserSongStateTable.selectAll()
|
||||
.where {
|
||||
(UserSongStateTable.userName eq userName) and
|
||||
UserSongStateTable.starredAt.isNotNull()
|
||||
}
|
||||
.toList()
|
||||
|
||||
val songRows = if (songStates.isEmpty()) {
|
||||
emptyList()
|
||||
} else {
|
||||
SongsTable.selectAll()
|
||||
.where {
|
||||
(SongsTable.id inList songStates.map { it[UserSongStateTable.songId] }) and
|
||||
(SongsTable.folderId inList folderIds)
|
||||
}
|
||||
.toList()
|
||||
}
|
||||
|
||||
val songs = enrichSongs(songRows, userName)
|
||||
.sortedByDescending { it.starredAt }
|
||||
|
||||
StarredRecords(artists, albums, songs)
|
||||
}
|
||||
|
||||
fun lyrics(songId: String, folderIds: Set<Int>): String? = read {
|
||||
if (folderIds.isEmpty()) return@read null
|
||||
|
||||
SongsTable
|
||||
.select(SongsTable.lyrics)
|
||||
.where {
|
||||
(SongsTable.id eq songId) and
|
||||
(SongsTable.folderId inList folderIds)
|
||||
}
|
||||
.singleOrNull()
|
||||
?.get(SongsTable.lyrics)
|
||||
}
|
||||
|
||||
fun songsByIds(ids: List<String>, folderIds: Set<Int>, userName: String): List<SongRecord> = read {
|
||||
if (ids.isEmpty() || folderIds.isEmpty()) return@read emptyList()
|
||||
|
||||
val rows = SongsTable.selectAll()
|
||||
.where {
|
||||
(SongsTable.id inList ids) and
|
||||
(SongsTable.folderId inList folderIds)
|
||||
}
|
||||
.toList()
|
||||
|
||||
val byId = enrichSongs(rows, userName).associateBy { it.id }
|
||||
ids.mapNotNull { byId[it] }
|
||||
}
|
||||
|
||||
fun searchArtists(
|
||||
query: String,
|
||||
limit: Int,
|
||||
offset: Int,
|
||||
folderIds: Set<Int>,
|
||||
@@ -368,9 +584,9 @@ object LibraryRepository {
|
||||
.orderBy(AlbumArtistsTable.position to SortOrder.ASC)
|
||||
.firstOrNull()
|
||||
|
||||
val playCount = songStates(userName, songs.map { it[SongsTable.id] })
|
||||
.values
|
||||
.sumOf { it.playCount }
|
||||
val states = songStates(userName, songs.map { it[SongsTable.id] })
|
||||
val playCount = states.values.sumOf { it.playCount }
|
||||
val lastPlayedAt = states.values.mapNotNull { it.lastPlayedAt }.maxOrNull()
|
||||
|
||||
val state = itemStates(userName, "album")[albumId]
|
||||
|
||||
@@ -384,6 +600,7 @@ object LibraryRepository {
|
||||
songCount = songs.size,
|
||||
duration = songs.sumOf { it[SongsTable.duration] },
|
||||
playCount = playCount,
|
||||
lastPlayedAt = lastPlayedAt,
|
||||
created = albumRow[AlbumsTable.createdAt],
|
||||
starredAt = state?.starredAt,
|
||||
rating = state?.rating,
|
||||
@@ -461,6 +678,7 @@ object LibraryRepository {
|
||||
starredAt = state?.starredAt,
|
||||
rating = state?.rating,
|
||||
playCount = state?.playCount ?: 0,
|
||||
lastPlayedAt = state?.lastPlayedAt,
|
||||
artists = songArtists[id].orEmpty(),
|
||||
genres = genres[id].orEmpty(),
|
||||
)
|
||||
@@ -486,7 +704,7 @@ object LibraryRepository {
|
||||
}
|
||||
.associate {
|
||||
it[UserStarsTable.itemId] to UserItemState(
|
||||
starredAt = it[UserStarsTable.starredAt],
|
||||
starredAt = it[UserStarsTable.starredAt].takeIf { value -> value.isNotBlank() },
|
||||
rating = it[UserStarsTable.rating],
|
||||
)
|
||||
}
|
||||
@@ -502,6 +720,7 @@ object LibraryRepository {
|
||||
.associate {
|
||||
it[UserSongStateTable.songId] to UserSongState(
|
||||
playCount = it[UserSongStateTable.playCount],
|
||||
lastPlayedAt = it[UserSongStateTable.lastPlayedAt],
|
||||
starredAt = it[UserSongStateTable.starredAt],
|
||||
rating = it[UserSongStateTable.rating],
|
||||
)
|
||||
|
||||
@@ -110,6 +110,7 @@ object MediaRepository {
|
||||
it[relativePath] = track.relativePath
|
||||
it[fileMtime] = track.fileMtime
|
||||
it[searchText] = track.searchText
|
||||
it[lyrics] = track.lyrics
|
||||
}
|
||||
} else {
|
||||
SongsTable.insert {
|
||||
@@ -131,6 +132,7 @@ object MediaRepository {
|
||||
it[fileMtime] = track.fileMtime
|
||||
it[createdAt] = now
|
||||
it[searchText] = track.searchText
|
||||
it[lyrics] = track.lyrics
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
package win.taptap.musicmanager.db
|
||||
|
||||
import java.time.Instant
|
||||
import org.jetbrains.exposed.sql.JoinType
|
||||
import org.jetbrains.exposed.sql.and
|
||||
import org.jetbrains.exposed.sql.deleteWhere
|
||||
import org.jetbrains.exposed.sql.insert
|
||||
import org.jetbrains.exposed.sql.or
|
||||
import org.jetbrains.exposed.sql.selectAll
|
||||
import org.jetbrains.exposed.sql.transactions.transaction
|
||||
import org.jetbrains.exposed.sql.update
|
||||
import win.taptap.musicmanager.util.IdGenerator
|
||||
|
||||
data class PlaylistRecord(
|
||||
val id: String,
|
||||
val name: String,
|
||||
val comment: String?,
|
||||
val owner: String,
|
||||
val isPublic: Boolean,
|
||||
val songCount: Int,
|
||||
val duration: Int,
|
||||
val created: String,
|
||||
val changed: String,
|
||||
)
|
||||
|
||||
/** Playlists are per user; public playlists are visible to everyone. */
|
||||
object PlaylistRepository {
|
||||
|
||||
fun visibleTo(userName: String): List<PlaylistRecord> = transaction {
|
||||
PlaylistsTable.selectAll()
|
||||
.where {
|
||||
(PlaylistsTable.owner eq userName) or (PlaylistsTable.isPublic eq true)
|
||||
}
|
||||
.orderBy(PlaylistsTable.changedAt to org.jetbrains.exposed.sql.SortOrder.DESC)
|
||||
.map { playlistRecord(it[PlaylistsTable.id], it) }
|
||||
}
|
||||
|
||||
fun get(playlistId: String, userName: String): PlaylistRecord? = transaction {
|
||||
val row = PlaylistsTable.selectAll()
|
||||
.where { PlaylistsTable.id eq playlistId }
|
||||
.singleOrNull() ?: return@transaction null
|
||||
|
||||
if (row[PlaylistsTable.owner] != userName && !row[PlaylistsTable.isPublic]) {
|
||||
return@transaction null
|
||||
}
|
||||
|
||||
playlistRecord(playlistId, row)
|
||||
}
|
||||
|
||||
fun songIds(playlistId: String): List<String> = transaction {
|
||||
PlaylistSongsTable.selectAll()
|
||||
.where { PlaylistSongsTable.playlistId eq playlistId }
|
||||
.orderBy(PlaylistSongsTable.position to org.jetbrains.exposed.sql.SortOrder.ASC)
|
||||
.map { it[PlaylistSongsTable.songId] }
|
||||
}
|
||||
|
||||
fun create(userName: String, name: String, songIds: List<String>): PlaylistRecord = transaction {
|
||||
val now = Instant.now().toString()
|
||||
val id = IdGenerator.playlistId(userName, name, now)
|
||||
|
||||
PlaylistsTable.insert {
|
||||
it[PlaylistsTable.id] = id
|
||||
it[owner] = userName
|
||||
it[PlaylistsTable.name] = name
|
||||
it[isPublic] = true
|
||||
it[createdAt] = now
|
||||
it[changedAt] = now
|
||||
}
|
||||
replaceSongsInternal(id, songIds)
|
||||
|
||||
playlistRecord(id, PlaylistsTable.selectAll().where { PlaylistsTable.id eq id }.single())
|
||||
}
|
||||
|
||||
fun replaceSongs(playlistId: String, songIds: List<String>, userName: String): Boolean = transaction {
|
||||
val row = PlaylistsTable.selectAll()
|
||||
.where { PlaylistsTable.id eq playlistId }
|
||||
.singleOrNull() ?: return@transaction false
|
||||
if (row[PlaylistsTable.owner] != userName) return@transaction false
|
||||
|
||||
val now = Instant.now().toString()
|
||||
replaceSongsInternal(playlistId, songIds)
|
||||
PlaylistsTable.update({ PlaylistsTable.id eq playlistId }) {
|
||||
it[changedAt] = now
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fun update(
|
||||
playlistId: String,
|
||||
userName: String,
|
||||
name: String?,
|
||||
comment: String?,
|
||||
isPublic: Boolean?,
|
||||
addSongIds: List<String>,
|
||||
removeIndices: List<Int>,
|
||||
): Boolean = transaction {
|
||||
val row = PlaylistsTable.selectAll()
|
||||
.where { PlaylistsTable.id eq playlistId }
|
||||
.singleOrNull() ?: return@transaction false
|
||||
if (row[PlaylistsTable.owner] != userName) return@transaction false
|
||||
|
||||
if (name != null || comment != null || isPublic != null) {
|
||||
PlaylistsTable.update({ PlaylistsTable.id eq playlistId }) {
|
||||
if (name != null) it[PlaylistsTable.name] = name
|
||||
if (comment != null) it[PlaylistsTable.comment] = comment
|
||||
if (isPublic != null) it[PlaylistsTable.isPublic] = isPublic
|
||||
}
|
||||
}
|
||||
|
||||
var songs = songIdsInternal(playlistId)
|
||||
if (removeIndices.isNotEmpty()) {
|
||||
val toRemove = removeIndices.filter { it in songs.indices }.toSortedSet(compareByDescending { it })
|
||||
toRemove.forEach { index ->
|
||||
if (index in songs.indices) songs = songs.filterIndexed { i, _ -> i != index }
|
||||
}
|
||||
}
|
||||
songs = songs + addSongIds
|
||||
|
||||
val now = Instant.now().toString()
|
||||
replaceSongsInternal(playlistId, songs)
|
||||
PlaylistsTable.update({ PlaylistsTable.id eq playlistId }) {
|
||||
it[changedAt] = now
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fun delete(playlistId: String, userName: String): Boolean = transaction {
|
||||
val row = PlaylistsTable.selectAll()
|
||||
.where { PlaylistsTable.id eq playlistId }
|
||||
.singleOrNull() ?: return@transaction false
|
||||
if (row[PlaylistsTable.owner] != userName) return@transaction false
|
||||
|
||||
PlaylistsTable.deleteWhere { it.run { PlaylistsTable.id eq playlistId } }
|
||||
true
|
||||
}
|
||||
|
||||
private fun songIdsInternal(playlistId: String): List<String> =
|
||||
PlaylistSongsTable.selectAll()
|
||||
.where { PlaylistSongsTable.playlistId eq playlistId }
|
||||
.orderBy(PlaylistSongsTable.position to org.jetbrains.exposed.sql.SortOrder.ASC)
|
||||
.map { it[PlaylistSongsTable.songId] }
|
||||
|
||||
private fun replaceSongsInternal(playlistId: String, songIds: List<String>) {
|
||||
PlaylistSongsTable.deleteWhere { it.run { PlaylistSongsTable.playlistId eq playlistId } }
|
||||
songIds.forEachIndexed { index, songId ->
|
||||
PlaylistSongsTable.insert {
|
||||
it[PlaylistSongsTable.playlistId] = playlistId
|
||||
it[PlaylistSongsTable.songId] = songId
|
||||
it[position] = index
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun playlistRecord(id: String, row: org.jetbrains.exposed.sql.ResultRow): PlaylistRecord {
|
||||
val songs = PlaylistSongsTable
|
||||
.join(SongsTable, JoinType.INNER, PlaylistSongsTable.songId, SongsTable.id)
|
||||
.select(SongsTable.duration)
|
||||
.where { PlaylistSongsTable.playlistId eq id }
|
||||
.toList()
|
||||
|
||||
return PlaylistRecord(
|
||||
id = id,
|
||||
name = row[PlaylistsTable.name],
|
||||
comment = row[PlaylistsTable.comment],
|
||||
owner = row[PlaylistsTable.owner],
|
||||
isPublic = row[PlaylistsTable.isPublic],
|
||||
songCount = songs.size,
|
||||
duration = songs.sumOf { it[SongsTable.duration] },
|
||||
created = row[PlaylistsTable.createdAt],
|
||||
changed = row[PlaylistsTable.changedAt],
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -69,6 +69,7 @@ object SongsTable : Table("songs") {
|
||||
val fileMtime = long("file_mtime")
|
||||
val createdAt = varchar("created_at", 40)
|
||||
val searchText = text("search_text")
|
||||
val lyrics = text("lyrics").nullable()
|
||||
|
||||
override val primaryKey = PrimaryKey(id)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
package win.taptap.musicmanager.db
|
||||
|
||||
import java.time.Instant
|
||||
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 BookmarkRecord(
|
||||
val songId: String,
|
||||
val positionMs: Long,
|
||||
val updatedAt: String,
|
||||
)
|
||||
|
||||
/** Per-user state: play counts, stars, ratings and bookmarks. */
|
||||
object UserStateRepository {
|
||||
|
||||
fun scrobble(userName: String, songId: String, submission: Boolean) {
|
||||
if (!submission) return
|
||||
val now = Instant.now().toString()
|
||||
|
||||
transaction {
|
||||
val existing = UserSongStateTable.selectAll()
|
||||
.where {
|
||||
(UserSongStateTable.userName eq userName) and
|
||||
(UserSongStateTable.songId eq songId)
|
||||
}
|
||||
.singleOrNull()
|
||||
|
||||
if (existing == null) {
|
||||
UserSongStateTable.insert {
|
||||
it[UserSongStateTable.userName] = userName
|
||||
it[UserSongStateTable.songId] = songId
|
||||
it[playCount] = 1
|
||||
it[lastPlayedAt] = now
|
||||
}
|
||||
} else {
|
||||
UserSongStateTable.update({
|
||||
(UserSongStateTable.userName eq userName) and
|
||||
(UserSongStateTable.songId eq songId)
|
||||
}) {
|
||||
it[playCount] = existing[UserSongStateTable.playCount] + 1
|
||||
it[lastPlayedAt] = now
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun setSongRating(userName: String, songId: String, rating: Int?) {
|
||||
transaction {
|
||||
val existing = UserSongStateTable.selectAll()
|
||||
.where {
|
||||
(UserSongStateTable.userName eq userName) and
|
||||
(UserSongStateTable.songId eq songId)
|
||||
}
|
||||
.singleOrNull()
|
||||
|
||||
if (existing == null) {
|
||||
UserSongStateTable.insert {
|
||||
it[UserSongStateTable.userName] = userName
|
||||
it[UserSongStateTable.songId] = songId
|
||||
it[UserSongStateTable.rating] = rating
|
||||
}
|
||||
} else {
|
||||
UserSongStateTable.update({
|
||||
(UserSongStateTable.userName eq userName) and
|
||||
(UserSongStateTable.songId eq songId)
|
||||
}) {
|
||||
it[UserSongStateTable.rating] = rating
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun setItemRating(userName: String, itemType: String, itemId: String, rating: Int?) {
|
||||
transaction {
|
||||
val existing = UserStarsTable.selectAll()
|
||||
.where {
|
||||
(UserStarsTable.userName eq userName) and
|
||||
(UserStarsTable.itemType eq itemType) and
|
||||
(UserStarsTable.itemId eq itemId)
|
||||
}
|
||||
.singleOrNull()
|
||||
|
||||
if (existing == null) {
|
||||
UserStarsTable.insert {
|
||||
it[UserStarsTable.userName] = userName
|
||||
it[UserStarsTable.itemType] = itemType
|
||||
it[UserStarsTable.itemId] = itemId
|
||||
it[starredAt] = ""
|
||||
it[UserStarsTable.rating] = rating
|
||||
}
|
||||
} else {
|
||||
UserStarsTable.update({
|
||||
(UserStarsTable.userName eq userName) and
|
||||
(UserStarsTable.itemType eq itemType) and
|
||||
(UserStarsTable.itemId eq itemId)
|
||||
}) {
|
||||
it[UserStarsTable.rating] = rating
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun starSong(userName: String, songId: String) {
|
||||
val now = Instant.now().toString()
|
||||
transaction {
|
||||
val existing = UserSongStateTable.selectAll()
|
||||
.where {
|
||||
(UserSongStateTable.userName eq userName) and
|
||||
(UserSongStateTable.songId eq songId)
|
||||
}
|
||||
.singleOrNull()
|
||||
|
||||
if (existing == null) {
|
||||
UserSongStateTable.insert {
|
||||
it[UserSongStateTable.userName] = userName
|
||||
it[UserSongStateTable.songId] = songId
|
||||
it[starredAt] = now
|
||||
}
|
||||
} else {
|
||||
UserSongStateTable.update({
|
||||
(UserSongStateTable.userName eq userName) and
|
||||
(UserSongStateTable.songId eq songId)
|
||||
}) {
|
||||
it[starredAt] = now
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun unstarSong(userName: String, songId: String) {
|
||||
transaction {
|
||||
UserSongStateTable.update({
|
||||
(UserSongStateTable.userName eq userName) and
|
||||
(UserSongStateTable.songId eq songId)
|
||||
}) {
|
||||
it[starredAt] = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun starItem(userName: String, itemType: String, itemId: String) {
|
||||
val now = Instant.now().toString()
|
||||
transaction {
|
||||
UserStarsTable.deleteWhere {
|
||||
it.run {
|
||||
(UserStarsTable.userName eq userName) and
|
||||
(UserStarsTable.itemType eq itemType) and
|
||||
(UserStarsTable.itemId eq itemId)
|
||||
}
|
||||
}
|
||||
UserStarsTable.insert {
|
||||
it[UserStarsTable.userName] = userName
|
||||
it[UserStarsTable.itemType] = itemType
|
||||
it[UserStarsTable.itemId] = itemId
|
||||
it[starredAt] = now
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun unstarItem(userName: String, itemType: String, itemId: String) {
|
||||
transaction {
|
||||
UserStarsTable.deleteWhere {
|
||||
it.run {
|
||||
(UserStarsTable.userName eq userName) and
|
||||
(UserStarsTable.itemType eq itemType) and
|
||||
(UserStarsTable.itemId eq itemId)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun createBookmark(userName: String, songId: String, positionMs: Long) {
|
||||
val now = Instant.now().toString()
|
||||
transaction {
|
||||
BookmarksTable.deleteWhere {
|
||||
it.run {
|
||||
(BookmarksTable.userName eq userName) and
|
||||
(BookmarksTable.songId eq songId)
|
||||
}
|
||||
}
|
||||
BookmarksTable.insert {
|
||||
it[BookmarksTable.userName] = userName
|
||||
it[BookmarksTable.songId] = songId
|
||||
it[BookmarksTable.positionMs] = positionMs
|
||||
it[updatedAt] = now
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteBookmark(userName: String, songId: String) {
|
||||
transaction {
|
||||
BookmarksTable.deleteWhere {
|
||||
it.run {
|
||||
(BookmarksTable.userName eq userName) and
|
||||
(BookmarksTable.songId eq songId)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun bookmarks(userName: String): List<BookmarkRecord> = transaction {
|
||||
BookmarksTable.selectAll()
|
||||
.where { BookmarksTable.userName eq userName }
|
||||
.orderBy(BookmarksTable.updatedAt to org.jetbrains.exposed.sql.SortOrder.DESC)
|
||||
.map {
|
||||
BookmarkRecord(
|
||||
songId = it[BookmarksTable.songId],
|
||||
positionMs = it[BookmarksTable.positionMs],
|
||||
updatedAt = it[BookmarksTable.updatedAt],
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,8 @@ import kotlinx.serialization.json.buildJsonObject
|
||||
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.PlaylistRecord
|
||||
import win.taptap.musicmanager.db.SongRecord
|
||||
import win.taptap.musicmanager.util.IdGenerator
|
||||
|
||||
@@ -39,6 +41,7 @@ fun songJson(song: SongRecord): JsonObject = buildJsonObject {
|
||||
put("discNumber", song.discNumber)
|
||||
put("created", song.created)
|
||||
put("playCount", song.playCount)
|
||||
song.lastPlayedAt?.let { put("played", it) }
|
||||
song.starredAt?.let { put("starred", it) }
|
||||
song.rating?.let { put("userRating", it) }
|
||||
put("artists", buildJsonArray {
|
||||
@@ -104,6 +107,28 @@ fun artistIndexArray(artists: List<ArtistRecord>): JsonArray {
|
||||
}
|
||||
}
|
||||
|
||||
fun playlistJson(playlist: PlaylistRecord, songs: List<SongRecord>? = null): JsonObject = buildJsonObject {
|
||||
put("id", playlist.id)
|
||||
put("name", playlist.name)
|
||||
playlist.comment?.let { put("comment", it) }
|
||||
put("owner", playlist.owner)
|
||||
put("public", playlist.isPublic)
|
||||
put("songCount", playlist.songCount)
|
||||
put("duration", playlist.duration)
|
||||
put("created", playlist.created)
|
||||
put("changed", playlist.changed)
|
||||
|
||||
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)
|
||||
put("albumCount", genre.albumCount)
|
||||
}
|
||||
|
||||
private fun indexLetter(sortName: String): String {
|
||||
val first = IdGenerator.normalize(sortName).firstOrNull() ?: return "#"
|
||||
return if (first.isLetter()) first.uppercaseChar().toString() else "#"
|
||||
|
||||
@@ -13,6 +13,7 @@ import win.taptap.musicmanager.subsonic.models.IGNORED_ARTICLES
|
||||
import win.taptap.musicmanager.subsonic.models.albumJson
|
||||
import win.taptap.musicmanager.subsonic.models.artistIndexArray
|
||||
import win.taptap.musicmanager.subsonic.models.artistJson
|
||||
import win.taptap.musicmanager.subsonic.models.genreJson
|
||||
import win.taptap.musicmanager.subsonic.models.songJson
|
||||
import win.taptap.musicmanager.subsonic.respondSubsonic
|
||||
import win.taptap.musicmanager.subsonic.respondSubsonicError
|
||||
@@ -117,10 +118,181 @@ fun Route.browsingRoutes(users: UsersConfig, library: LibraryConfig) {
|
||||
call.respondSubsonic(buildJsonObject { put("song", songJson(song)) })
|
||||
}
|
||||
|
||||
val albumListTypes = setOf(
|
||||
"newest",
|
||||
"recent",
|
||||
"frequent",
|
||||
"random",
|
||||
"alphabeticalByName",
|
||||
"alphabeticalByArtist",
|
||||
"starred",
|
||||
"byYear",
|
||||
"byGenre",
|
||||
)
|
||||
|
||||
for (endpoint in listOf("/getAlbumList2", "/getAlbumList")) {
|
||||
subsonicGet(users, endpoint) { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val type = parameters["type"] ?: "newest"
|
||||
if (type !in albumListTypes) {
|
||||
call.respondSubsonicError(10, "Invalid album list type: $type")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
val size = parameters.intParam("size", 10)
|
||||
val offset = parameters.intParam("offset", 0)
|
||||
val fromYear = parameters["fromYear"]?.toIntOrNull()
|
||||
val toYear = parameters["toYear"]?.toIntOrNull()
|
||||
val genre = parameters["genre"]
|
||||
|
||||
val albums = LibraryRepository.albumList(
|
||||
type = type,
|
||||
size = size,
|
||||
offset = offset,
|
||||
fromYear = fromYear,
|
||||
toYear = toYear,
|
||||
genre = genre,
|
||||
folderIds = user.effectiveFolderIds(library, parameters["musicFolderId"]),
|
||||
userName = user.name,
|
||||
)
|
||||
|
||||
val key = if (endpoint == "/getAlbumList2") "albumList2" else "albumList"
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put(key, buildJsonObject {
|
||||
put("album", buildJsonArray { albums.forEach { add(albumJson(it)) } })
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
subsonicGet(users, "/getRandomSongs") { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val songs = LibraryRepository.randomSongs(
|
||||
size = parameters.intParam("size", 10),
|
||||
genre = parameters["genre"],
|
||||
fromYear = parameters["fromYear"]?.toIntOrNull(),
|
||||
toYear = parameters["toYear"]?.toIntOrNull(),
|
||||
folderIds = user.effectiveFolderIds(library, parameters["musicFolderId"]),
|
||||
userName = user.name,
|
||||
)
|
||||
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put("randomSongs", buildJsonObject {
|
||||
put("song", buildJsonArray { songs.forEach { add(songJson(it)) } })
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
subsonicGet(users, "/getGenres") { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val genres = LibraryRepository.genres(
|
||||
user.effectiveFolderIds(library, parameters["musicFolderId"]),
|
||||
)
|
||||
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put("genres", buildJsonObject {
|
||||
put("genre", buildJsonArray { genres.forEach { add(genreJson(it)) } })
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
subsonicGet(users, "/getSongsByGenre") { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val genre = parameters["genre"]
|
||||
if (genre.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: genre")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
val songs = LibraryRepository.songsByGenre(
|
||||
genre = genre,
|
||||
size = parameters.intParam("count", 10),
|
||||
offset = parameters.intParam("offset", 0),
|
||||
folderIds = user.effectiveFolderIds(library, parameters["musicFolderId"]),
|
||||
userName = user.name,
|
||||
)
|
||||
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put("songsByGenre", buildJsonObject {
|
||||
put("song", buildJsonArray { songs.forEach { add(songJson(it)) } })
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
for (endpoint in listOf("/getStarred2", "/getStarred")) {
|
||||
subsonicGet(users, endpoint) { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val starred = LibraryRepository.starred(
|
||||
userName = user.name,
|
||||
folderIds = user.effectiveFolderIds(library, parameters["musicFolderId"]),
|
||||
)
|
||||
|
||||
val key = if (endpoint == "/getStarred2") "starred2" else "starred"
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put(key, buildJsonObject {
|
||||
put("artist", buildJsonArray { starred.artists.forEach { add(artistJson(it)) } })
|
||||
put("album", buildJsonArray { starred.albums.forEach { add(albumJson(it)) } })
|
||||
put("song", buildJsonArray { starred.songs.forEach { add(songJson(it)) } })
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// No external metadata provider yet, but clients expect a valid empty response.
|
||||
for (endpoint in listOf("/getArtistInfo2", "/getArtistInfo")) {
|
||||
subsonicGet(users, endpoint) { call, _ ->
|
||||
val key = if (endpoint == "/getArtistInfo2") "artistInfo2" else "artistInfo"
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put(key, buildJsonObject {
|
||||
put("biography", "")
|
||||
put("similarArtist", buildJsonArray { })
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
for (endpoint in listOf("/getAlbumInfo2", "/getAlbumInfo")) {
|
||||
subsonicGet(users, endpoint) { call, _ ->
|
||||
val key = if (endpoint == "/getAlbumInfo2") "albumInfo2" else "albumInfo"
|
||||
call.respondSubsonic(buildJsonObject { put(key, buildJsonObject { }) })
|
||||
}
|
||||
}
|
||||
|
||||
for (endpoint in listOf("/getSimilarSongs2", "/getSimilarSongs")) {
|
||||
subsonicGet(users, endpoint) { call, _ ->
|
||||
val key = if (endpoint == "/getSimilarSongs2") "similarSongs2" else "similarSongs"
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put(key, buildJsonObject { put("song", buildJsonArray { }) })
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
subsonicGet(users, "/getTopSongs") { call, _ ->
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put("topSongs", buildJsonObject { put("song", buildJsonArray { }) })
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
subsonicGet(users, "/search3") { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val query = parameters["query"].orEmpty()
|
||||
val folders = user.visibleFolderIds(library)
|
||||
val folders = user.effectiveFolderIds(library, parameters["musicFolderId"])
|
||||
val all = query.isBlank() || query == "*"
|
||||
|
||||
val artistCount = parameters.intParam("artistCount", 20)
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
package win.taptap.musicmanager.subsonic.routes
|
||||
|
||||
import io.ktor.server.routing.Route
|
||||
import kotlinx.serialization.json.add
|
||||
import kotlinx.serialization.json.buildJsonArray
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
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.UserStateRepository
|
||||
import win.taptap.musicmanager.subsonic.models.songJson
|
||||
import win.taptap.musicmanager.subsonic.respondSubsonic
|
||||
import win.taptap.musicmanager.subsonic.respondSubsonicError
|
||||
|
||||
/** Per-user interaction: scrobbling, stars, ratings, bookmarks and lyrics. */
|
||||
fun Route.interactionRoutes(users: UsersConfig, library: LibraryConfig) {
|
||||
|
||||
subsonicGet(users, "/scrobble") { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val ids = parameters.getAll("id").orEmpty().filter { it.isNotBlank() }
|
||||
if (ids.isEmpty()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
val submission = parameters["submission"]?.toBooleanStrictOrNull() ?: true
|
||||
val folders = user.effectiveFolderIds(library, parameters["musicFolderId"])
|
||||
|
||||
for (id in ids) {
|
||||
if (LibraryRepository.song(id, folders, user.name) == null) {
|
||||
call.respondSubsonicError(70, "Song not found")
|
||||
return@subsonicGet
|
||||
}
|
||||
UserStateRepository.scrobble(user.name, id, submission)
|
||||
}
|
||||
|
||||
call.respondSubsonic()
|
||||
}
|
||||
|
||||
subsonicGet(users, "/star") { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val folders = user.effectiveFolderIds(library, parameters["musicFolderId"])
|
||||
|
||||
val songIds = parameters.getAll("id").orEmpty().filter { it.isNotBlank() }
|
||||
val albumIds = parameters.getAll("albumId").orEmpty().filter { it.isNotBlank() }
|
||||
val artistIds = parameters.getAll("artistId").orEmpty().filter { it.isNotBlank() }
|
||||
|
||||
if (songIds.isEmpty() && albumIds.isEmpty() && artistIds.isEmpty()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: id, albumId or artistId")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
if (!validateVisible(songIds, albumIds, artistIds, folders, user.name)) {
|
||||
call.respondSubsonicError(70, "Item not found")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
songIds.forEach { UserStateRepository.starSong(user.name, it) }
|
||||
albumIds.forEach { UserStateRepository.starItem(user.name, "album", it) }
|
||||
artistIds.forEach { UserStateRepository.starItem(user.name, "artist", it) }
|
||||
|
||||
call.respondSubsonic()
|
||||
}
|
||||
|
||||
subsonicGet(users, "/unstar") { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val folders = user.effectiveFolderIds(library, parameters["musicFolderId"])
|
||||
|
||||
val songIds = parameters.getAll("id").orEmpty().filter { it.isNotBlank() }
|
||||
val albumIds = parameters.getAll("albumId").orEmpty().filter { it.isNotBlank() }
|
||||
val artistIds = parameters.getAll("artistId").orEmpty().filter { it.isNotBlank() }
|
||||
|
||||
if (songIds.isEmpty() && albumIds.isEmpty() && artistIds.isEmpty()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: id, albumId or artistId")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
if (!validateVisible(songIds, albumIds, artistIds, folders, user.name)) {
|
||||
call.respondSubsonicError(70, "Item not found")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
songIds.forEach { UserStateRepository.unstarSong(user.name, it) }
|
||||
albumIds.forEach { UserStateRepository.unstarItem(user.name, "album", it) }
|
||||
artistIds.forEach { UserStateRepository.unstarItem(user.name, "artist", it) }
|
||||
|
||||
call.respondSubsonic()
|
||||
}
|
||||
|
||||
subsonicGet(users, "/setRating") { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val id = parameters["id"]
|
||||
if (id.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
val rawRating = parameters["rating"]
|
||||
val rating = rawRating?.toIntOrNull()
|
||||
if (rating == null || rating !in 0..5) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing or invalid: rating")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
val folders = user.effectiveFolderIds(library, parameters["musicFolderId"])
|
||||
val storedRating = rating.takeIf { it > 0 }
|
||||
|
||||
when {
|
||||
id.startsWith("sg-") -> {
|
||||
if (LibraryRepository.song(id, folders, user.name) == null) {
|
||||
call.respondSubsonicError(70, "Song not found")
|
||||
return@subsonicGet
|
||||
}
|
||||
UserStateRepository.setSongRating(user.name, id, storedRating)
|
||||
}
|
||||
id.startsWith("al-") -> {
|
||||
if (LibraryRepository.album(id, folders, user.name) == null) {
|
||||
call.respondSubsonicError(70, "Album not found")
|
||||
return@subsonicGet
|
||||
}
|
||||
UserStateRepository.setItemRating(user.name, "album", id, storedRating)
|
||||
}
|
||||
id.startsWith("ar-") -> {
|
||||
if (LibraryRepository.artist(id, folders, user.name) == null) {
|
||||
call.respondSubsonicError(70, "Artist not found")
|
||||
return@subsonicGet
|
||||
}
|
||||
UserStateRepository.setItemRating(user.name, "artist", id, storedRating)
|
||||
}
|
||||
else -> {
|
||||
call.respondSubsonicError(70, "Item not found")
|
||||
return@subsonicGet
|
||||
}
|
||||
}
|
||||
|
||||
call.respondSubsonic()
|
||||
}
|
||||
|
||||
subsonicGet(users, "/getBookmarks") { call, user ->
|
||||
val folders = user.effectiveFolderIds(library, call.subsonicParams()["musicFolderId"])
|
||||
|
||||
val bookmarks = UserStateRepository.bookmarks(user.name).mapNotNull { bookmark ->
|
||||
val song = LibraryRepository.song(bookmark.songId, folders, user.name) ?: return@mapNotNull null
|
||||
buildJsonObject {
|
||||
put("position", bookmark.positionMs)
|
||||
put("username", user.name)
|
||||
put("created", bookmark.updatedAt)
|
||||
put("changed", bookmark.updatedAt)
|
||||
put("entry", songJson(song))
|
||||
}
|
||||
}
|
||||
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put("bookmarks", buildJsonObject {
|
||||
put("bookmark", buildJsonArray { bookmarks.forEach { add(it) } })
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
subsonicGet(users, "/createBookmark") { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val id = parameters["id"]
|
||||
if (id.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
val position = parameters["position"]?.toLongOrNull()
|
||||
if (position == null || position < 0) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing or invalid: position")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
if (LibraryRepository.song(id, user.effectiveFolderIds(library, parameters["musicFolderId"]), user.name) == null) {
|
||||
call.respondSubsonicError(70, "Song not found")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
UserStateRepository.createBookmark(user.name, id, position)
|
||||
call.respondSubsonic()
|
||||
}
|
||||
|
||||
subsonicGet(users, "/deleteBookmark") { call, user ->
|
||||
val id = call.subsonicParams()["id"]
|
||||
if (id.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
UserStateRepository.deleteBookmark(user.name, id)
|
||||
call.respondSubsonic()
|
||||
}
|
||||
|
||||
subsonicGet(users, "/getLyricsBySongId") { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val id = parameters["id"]
|
||||
if (id.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
val folders = user.effectiveFolderIds(library, parameters["musicFolderId"])
|
||||
val song = LibraryRepository.song(id, folders, user.name)
|
||||
if (song == null) {
|
||||
call.respondSubsonicError(70, "Song not found")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
val lyrics = LibraryRepository.lyrics(id, folders)
|
||||
val lines = lyrics.orEmpty()
|
||||
.lines()
|
||||
.map { it.trim() }
|
||||
.filter { it.isNotEmpty() }
|
||||
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
if (lines.isEmpty()) {
|
||||
put("lyricsList", buildJsonObject { })
|
||||
} else {
|
||||
put("lyricsList", buildJsonObject {
|
||||
put("structuredLyrics", buildJsonArray {
|
||||
add(buildJsonObject {
|
||||
put("displayArtist", song.displayArtist)
|
||||
put("displayTitle", song.title)
|
||||
put("lang", "")
|
||||
put("synced", false)
|
||||
put("line", buildJsonArray {
|
||||
lines.forEach { line ->
|
||||
add(buildJsonObject { put("value", line) })
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun validateVisible(
|
||||
songIds: List<String>,
|
||||
albumIds: List<String>,
|
||||
artistIds: List<String>,
|
||||
folderIds: Set<Int>,
|
||||
userName: String,
|
||||
): Boolean {
|
||||
if (songIds.any { LibraryRepository.song(it, folderIds, userName) == null }) return false
|
||||
if (albumIds.any { LibraryRepository.album(it, folderIds, userName) == null }) return false
|
||||
if (artistIds.any { LibraryRepository.artist(it, folderIds, userName) == null }) return false
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package win.taptap.musicmanager.subsonic.routes
|
||||
|
||||
import io.ktor.server.routing.Route
|
||||
import kotlinx.serialization.json.add
|
||||
import kotlinx.serialization.json.buildJsonArray
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
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.PlaylistRepository
|
||||
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) {
|
||||
|
||||
subsonicGet(users, "/getPlaylists") { call, user ->
|
||||
val playlists = PlaylistRepository.visibleTo(user.name)
|
||||
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put("playlists", buildJsonObject {
|
||||
put("playlist", buildJsonArray { playlists.forEach { add(playlistJson(it)) } })
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
subsonicGet(users, "/getPlaylist") { call, user ->
|
||||
val id = call.subsonicParams()["id"]
|
||||
if (id.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
val playlist = PlaylistRepository.get(id, user.name)
|
||||
if (playlist == null) {
|
||||
call.respondSubsonicError(70, "Playlist not found")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
val folders = user.visibleFolderIds(library)
|
||||
val songs = LibraryRepository.songsByIds(PlaylistRepository.songIds(id), folders, user.name)
|
||||
|
||||
call.respondSubsonic(buildJsonObject { put("playlist", playlistJson(playlist, songs)) })
|
||||
}
|
||||
|
||||
subsonicGet(users, "/createPlaylist") { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val folders = user.visibleFolderIds(library)
|
||||
val requestedSongs = parameters.getAll("songId").orEmpty()
|
||||
.filter { it.isNotBlank() }
|
||||
.filter { LibraryRepository.song(it, folders, user.name) != null }
|
||||
|
||||
val playlistId = parameters["playlistId"]
|
||||
if (!playlistId.isNullOrBlank()) {
|
||||
val existing = PlaylistRepository.get(playlistId, user.name)
|
||||
if (existing == null) {
|
||||
call.respondSubsonicError(70, "Playlist not found")
|
||||
return@subsonicGet
|
||||
}
|
||||
if (existing.owner != user.name) {
|
||||
call.respondSubsonicError(50, "Not authorized")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
val newName = parameters["name"]?.takeIf { it.isNotBlank() }
|
||||
PlaylistRepository.update(
|
||||
playlistId = playlistId,
|
||||
userName = user.name,
|
||||
name = newName,
|
||||
comment = null,
|
||||
isPublic = null,
|
||||
addSongIds = emptyList(),
|
||||
removeIndices = emptyList(),
|
||||
)
|
||||
PlaylistRepository.replaceSongs(playlistId, requestedSongs, user.name)
|
||||
|
||||
val updated = PlaylistRepository.get(playlistId, user.name)!!
|
||||
call.respondSubsonic(buildJsonObject { put("playlist", playlistJson(updated)) })
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
val name = parameters["name"]
|
||||
if (name.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: name")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
val playlist = PlaylistRepository.create(user.name, name.trim(), requestedSongs)
|
||||
call.respondSubsonic(buildJsonObject { put("playlist", playlistJson(playlist)) })
|
||||
}
|
||||
|
||||
subsonicGet(users, "/updatePlaylist") { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val playlistId = parameters["playlistId"]
|
||||
if (playlistId.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: playlistId")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
val existing = PlaylistRepository.get(playlistId, user.name)
|
||||
if (existing == null) {
|
||||
call.respondSubsonicError(70, "Playlist not found")
|
||||
return@subsonicGet
|
||||
}
|
||||
if (existing.owner != user.name) {
|
||||
call.respondSubsonicError(50, "Not authorized")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
val folders = user.visibleFolderIds(library)
|
||||
val addSongs = parameters.getAll("songIdToAdd").orEmpty()
|
||||
.filter { it.isNotBlank() }
|
||||
.filter { LibraryRepository.song(it, folders, user.name) != null }
|
||||
val removeIndices = parameters.getAll("songIndexToRemove").orEmpty()
|
||||
.mapNotNull { it.toIntOrNull() }
|
||||
.filter { it >= 0 }
|
||||
|
||||
val updated = PlaylistRepository.update(
|
||||
playlistId = playlistId,
|
||||
userName = user.name,
|
||||
name = parameters["name"]?.takeIf { it.isNotBlank() },
|
||||
comment = parameters["comment"],
|
||||
isPublic = parameters["public"]?.toBooleanStrictOrNull(),
|
||||
addSongIds = addSongs,
|
||||
removeIndices = removeIndices,
|
||||
)
|
||||
|
||||
if (!updated) {
|
||||
call.respondSubsonicError(50, "Not authorized")
|
||||
} else {
|
||||
call.respondSubsonic()
|
||||
}
|
||||
}
|
||||
|
||||
subsonicGet(users, "/deletePlaylist") { call, user ->
|
||||
val playlistId = call.subsonicParams()["id"]
|
||||
if (playlistId.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
val existing = PlaylistRepository.get(playlistId, user.name)
|
||||
if (existing == null) {
|
||||
call.respondSubsonicError(70, "Playlist not found")
|
||||
return@subsonicGet
|
||||
}
|
||||
if (existing.owner != user.name) {
|
||||
call.respondSubsonicError(50, "Not authorized")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
PlaylistRepository.delete(playlistId, user.name)
|
||||
call.respondSubsonic()
|
||||
}
|
||||
}
|
||||
@@ -8,11 +8,22 @@ 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.LibraryConfig
|
||||
import win.taptap.musicmanager.config.UserAccount
|
||||
|
||||
val CurrentUserKey = AttributeKey<UserAccount>("musicmanager.currentUser")
|
||||
val SubsonicParametersKey = AttributeKey<Parameters>("musicmanager.parameters")
|
||||
|
||||
/**
|
||||
* Visible folders, optionally narrowed to a client-supplied `musicFolderId`.
|
||||
* An unknown or invisible id yields an empty set, which all queries treat as "nothing".
|
||||
*/
|
||||
fun UserAccount.effectiveFolderIds(library: LibraryConfig, musicFolderId: String?): Set<Int> {
|
||||
val visible = visibleFolderIds(library)
|
||||
val requested = musicFolderId?.toIntOrNull() ?: return visible
|
||||
return if (requested in visible) setOf(requested) else emptySet()
|
||||
}
|
||||
|
||||
/** Parameters captured during authentication, so POST bodies are only read once. */
|
||||
fun ApplicationCall.subsonicParams(): Parameters =
|
||||
attributes.getOrNull(SubsonicParametersKey) ?: request.queryParameters
|
||||
|
||||
@@ -19,5 +19,7 @@ fun Route.subsonicRoutes(
|
||||
systemRoutes(users, library, startScan, scanStatus)
|
||||
browsingRoutes(users, library)
|
||||
mediaRoutes(users, library, coverArtService)
|
||||
interactionRoutes(users, library)
|
||||
playlistRoutes(users, library)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user