feat: add browsing and media endpoints
- user-scoped getMusicFolders, getIndexes, getArtists, getArtist, getAlbum and getSong - search3 with pagination, literal matching and empty/wildcard queries - stream and download with Range support and RFC 5987 filenames - getCoverArt with cached size variants and visibility checks - V2 migration for per-user album and artist ratings
This commit is contained in:
1 parent
1f73d901d5
commit
643ee42f09
14 files changed
+1364
-4
No files matched your search
@@ -46,7 +46,8 @@ fun main() {
|
||||
ConfigRepository.sync(library, users)
|
||||
|
||||
val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
val scanner = MediaScanner(library, CoverArtService(config.dataDir))
|
||||
val coverArtService = CoverArtService(config.dataDir)
|
||||
val scanner = MediaScanner(library, coverArtService)
|
||||
if (MediaRepository.countSongs() == 0L) {
|
||||
log.info("Song table is empty, starting initial library scan")
|
||||
scanner.start(applicationScope)
|
||||
@@ -80,6 +81,8 @@ fun main() {
|
||||
get("/health") { call.respondText("ok") }
|
||||
subsonicRoutes(
|
||||
users = users,
|
||||
library = library,
|
||||
coverArtService = coverArtService,
|
||||
startScan = { scanner.start(applicationScope) },
|
||||
scanStatus = { scanner.status() },
|
||||
)
|
||||
|
||||
@@ -0,0 +1,518 @@
|
||||
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.ResultRow
|
||||
import org.jetbrains.exposed.sql.SortOrder
|
||||
import org.jetbrains.exposed.sql.Transaction
|
||||
import org.jetbrains.exposed.sql.and
|
||||
import org.jetbrains.exposed.sql.selectAll
|
||||
import org.jetbrains.exposed.sql.transactions.transaction
|
||||
import org.jetbrains.exposed.sql.union
|
||||
import win.taptap.musicmanager.config.LibraryConfig
|
||||
import win.taptap.musicmanager.util.IdGenerator
|
||||
|
||||
data class ArtistRefRecord(val id: String, val name: String)
|
||||
|
||||
data class UserItemState(val starredAt: String?, val rating: Int?)
|
||||
|
||||
data class UserSongState(
|
||||
val playCount: Int,
|
||||
val starredAt: String?,
|
||||
val rating: Int?,
|
||||
)
|
||||
|
||||
data class ArtistRecord(
|
||||
val id: String,
|
||||
val name: String,
|
||||
val sortName: String,
|
||||
val albumCount: Int,
|
||||
val starredAt: String?,
|
||||
val rating: Int?,
|
||||
)
|
||||
|
||||
data class AlbumRecord(
|
||||
val id: String,
|
||||
val name: String,
|
||||
val artistId: String?,
|
||||
val artistName: String?,
|
||||
val year: Int?,
|
||||
val coverArt: String?,
|
||||
val songCount: Int,
|
||||
val duration: Int,
|
||||
val playCount: Int,
|
||||
val created: String,
|
||||
val starredAt: String?,
|
||||
val rating: Int?,
|
||||
val genres: List<String>,
|
||||
)
|
||||
|
||||
data class SongRecord(
|
||||
val id: String,
|
||||
val albumId: String,
|
||||
val albumName: String,
|
||||
val artistId: String?,
|
||||
val artistName: String,
|
||||
val displayArtist: String,
|
||||
val title: String,
|
||||
val trackNumber: Int?,
|
||||
val discNumber: Int,
|
||||
val year: Int?,
|
||||
val duration: Int,
|
||||
val bitRate: Int,
|
||||
val size: Long,
|
||||
val suffix: String,
|
||||
val contentType: String,
|
||||
val coverArt: String?,
|
||||
val folderId: Int,
|
||||
val relativePath: String,
|
||||
val created: String,
|
||||
val starredAt: String?,
|
||||
val rating: Int?,
|
||||
val playCount: Int,
|
||||
val artists: List<ArtistRefRecord>,
|
||||
val genres: List<String>,
|
||||
)
|
||||
|
||||
data class ResolvedSong(val song: SongRecord, val file: Path)
|
||||
|
||||
/**
|
||||
* Read-side queries for browsing and media. Every method takes the set of folder
|
||||
* IDs visible to the requesting user; an album or artist without a visible song
|
||||
* is never returned.
|
||||
*/
|
||||
object LibraryRepository {
|
||||
|
||||
fun artists(folderIds: Set<Int>, userName: String): List<ArtistRecord> = read {
|
||||
if (folderIds.isEmpty()) return@read emptyList()
|
||||
|
||||
val visibleSongs = visibleSongs(folderIds)
|
||||
val visibleAlbums = visibleAlbums(folderIds)
|
||||
|
||||
val trackArtists = SongArtistsTable
|
||||
.select(SongArtistsTable.artistId)
|
||||
.where { SongArtistsTable.songId inSubQuery visibleSongs }
|
||||
val albumArtists = AlbumArtistsTable
|
||||
.select(AlbumArtistsTable.artistId)
|
||||
.where { AlbumArtistsTable.albumId inSubQuery visibleAlbums }
|
||||
|
||||
val albumCounts = AlbumArtistsTable
|
||||
.select(AlbumArtistsTable.artistId, AlbumArtistsTable.albumId)
|
||||
.withDistinct()
|
||||
.where { AlbumArtistsTable.albumId inSubQuery visibleAlbums }
|
||||
.groupingBy { it[AlbumArtistsTable.artistId] }
|
||||
.eachCount()
|
||||
|
||||
val states = itemStates(userName, "artist")
|
||||
|
||||
return@read ArtistsTable
|
||||
.selectAll()
|
||||
.where { ArtistsTable.id inSubQuery trackArtists.union(albumArtists) }
|
||||
.map { row ->
|
||||
val id = row[ArtistsTable.id]
|
||||
val state = states[id]
|
||||
ArtistRecord(
|
||||
id = id,
|
||||
name = row[ArtistsTable.name],
|
||||
sortName = row[ArtistsTable.sortName],
|
||||
albumCount = albumCounts[id] ?: 0,
|
||||
starredAt = state?.starredAt,
|
||||
rating = state?.rating,
|
||||
)
|
||||
}
|
||||
.sortedBy { IdGenerator.normalize(it.sortName) }
|
||||
}
|
||||
|
||||
fun artist(artistId: String, folderIds: Set<Int>, userName: String): ArtistRecord? = read {
|
||||
if (folderIds.isEmpty()) return@read null
|
||||
|
||||
val row = ArtistsTable.selectAll()
|
||||
.where { ArtistsTable.id eq artistId }
|
||||
.singleOrNull() ?: return@read null
|
||||
|
||||
val albumCount = AlbumArtistsTable
|
||||
.select(AlbumArtistsTable.albumId)
|
||||
.withDistinct()
|
||||
.where {
|
||||
(AlbumArtistsTable.artistId eq artistId) and
|
||||
(AlbumArtistsTable.albumId inSubQuery visibleAlbums(folderIds))
|
||||
}
|
||||
.count()
|
||||
.toInt()
|
||||
|
||||
val hasVisibleSong = SongArtistsTable
|
||||
.select(SongArtistsTable.songId)
|
||||
.where {
|
||||
(SongArtistsTable.artistId eq artistId) and
|
||||
(SongArtistsTable.songId inSubQuery visibleSongs(folderIds))
|
||||
}
|
||||
.any()
|
||||
|
||||
if (albumCount == 0 && !hasVisibleSong) return@read null
|
||||
|
||||
val state = itemStates(userName, "artist")[artistId]
|
||||
ArtistRecord(
|
||||
id = artistId,
|
||||
name = row[ArtistsTable.name],
|
||||
sortName = row[ArtistsTable.sortName],
|
||||
albumCount = albumCount,
|
||||
starredAt = state?.starredAt,
|
||||
rating = state?.rating,
|
||||
)
|
||||
}
|
||||
|
||||
fun albumsForArtist(artistId: String, folderIds: Set<Int>, userName: String): List<AlbumRecord> = read {
|
||||
if (folderIds.isEmpty()) return@read emptyList()
|
||||
|
||||
val albumIds = AlbumArtistsTable
|
||||
.select(AlbumArtistsTable.albumId)
|
||||
.withDistinct()
|
||||
.where {
|
||||
(AlbumArtistsTable.artistId eq artistId) and
|
||||
(AlbumArtistsTable.albumId inSubQuery visibleAlbums(folderIds))
|
||||
}
|
||||
.map { it[AlbumArtistsTable.albumId] }
|
||||
|
||||
albumIds.mapNotNull { albumRecord(it, folderIds, userName) }
|
||||
.sortedBy { it.name.lowercase() }
|
||||
}
|
||||
|
||||
fun album(albumId: String, folderIds: Set<Int>, userName: String): AlbumRecord? = read {
|
||||
albumRecord(albumId, folderIds, userName)
|
||||
}
|
||||
|
||||
fun albumSongs(albumId: String, folderIds: Set<Int>, userName: String): List<SongRecord> = read {
|
||||
if (folderIds.isEmpty()) return@read emptyList()
|
||||
|
||||
val rows = SongsTable.selectAll()
|
||||
.where {
|
||||
(SongsTable.albumId eq albumId) and
|
||||
(SongsTable.folderId inList folderIds)
|
||||
}
|
||||
.orderBy(
|
||||
SongsTable.discNumber to SortOrder.ASC,
|
||||
SongsTable.trackNumber to SortOrder.ASC,
|
||||
SongsTable.title to SortOrder.ASC,
|
||||
)
|
||||
.toList()
|
||||
|
||||
enrichSongs(rows, userName)
|
||||
}
|
||||
|
||||
fun song(songId: String, folderIds: Set<Int>, userName: String): SongRecord? = read {
|
||||
if (folderIds.isEmpty()) return@read null
|
||||
|
||||
val row = SongsTable.selectAll()
|
||||
.where {
|
||||
(SongsTable.id eq songId) and
|
||||
(SongsTable.folderId inList folderIds)
|
||||
}
|
||||
.singleOrNull() ?: return@read null
|
||||
|
||||
enrichSongs(listOf(row), userName).single()
|
||||
}
|
||||
|
||||
fun allAlbums(limit: Int, offset: Int, 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) }
|
||||
.orderBy(AlbumsTable.name to SortOrder.ASC)
|
||||
.limit(limit)
|
||||
.offset(offset.toLong())
|
||||
.map { it[AlbumsTable.id] }
|
||||
|
||||
ids.mapNotNull { albumRecord(it, folderIds, userName) }
|
||||
}
|
||||
|
||||
fun allSongs(limit: Int, offset: Int, folderIds: Set<Int>, userName: String): List<SongRecord> = read {
|
||||
if (folderIds.isEmpty()) return@read emptyList()
|
||||
|
||||
val rows = SongsTable.selectAll()
|
||||
.where { SongsTable.folderId inList folderIds }
|
||||
.orderBy(SongsTable.title to SortOrder.ASC)
|
||||
.limit(limit)
|
||||
.offset(offset.toLong())
|
||||
.toList()
|
||||
|
||||
enrichSongs(rows, userName)
|
||||
}
|
||||
|
||||
fun searchArtists( query: String,
|
||||
limit: Int,
|
||||
offset: Int,
|
||||
folderIds: Set<Int>,
|
||||
userName: String,
|
||||
): List<ArtistRecord> = read {
|
||||
if (folderIds.isEmpty()) return@read emptyList()
|
||||
|
||||
val pattern = likePattern(query)
|
||||
val visibleSongs = visibleSongs(folderIds)
|
||||
val visibleAlbums = visibleAlbums(folderIds)
|
||||
val trackArtists = SongArtistsTable.select(SongArtistsTable.artistId)
|
||||
.where { SongArtistsTable.songId inSubQuery visibleSongs }
|
||||
val albumArtists = AlbumArtistsTable.select(AlbumArtistsTable.artistId)
|
||||
.where { AlbumArtistsTable.albumId inSubQuery visibleAlbums }
|
||||
|
||||
val ids = ArtistsTable
|
||||
.select(ArtistsTable.id)
|
||||
.where {
|
||||
(ArtistsTable.searchText like pattern) and
|
||||
(ArtistsTable.id inSubQuery trackArtists.union(albumArtists))
|
||||
}
|
||||
.orderBy(ArtistsTable.sortName to SortOrder.ASC)
|
||||
.limit(limit)
|
||||
.offset(offset.toLong())
|
||||
.map { it[ArtistsTable.id] }
|
||||
|
||||
ids.mapNotNull { artist(it, folderIds, userName) }
|
||||
}
|
||||
|
||||
fun searchAlbums(
|
||||
query: String,
|
||||
limit: Int,
|
||||
offset: Int,
|
||||
folderIds: Set<Int>,
|
||||
userName: String,
|
||||
): List<AlbumRecord> = read {
|
||||
if (folderIds.isEmpty()) return@read emptyList()
|
||||
|
||||
val pattern = likePattern(query)
|
||||
val ids = AlbumsTable
|
||||
.select(AlbumsTable.id)
|
||||
.where {
|
||||
(AlbumsTable.searchText like pattern) and
|
||||
(AlbumsTable.id inSubQuery visibleAlbums(folderIds))
|
||||
}
|
||||
.orderBy(AlbumsTable.name to SortOrder.ASC)
|
||||
.limit(limit)
|
||||
.offset(offset.toLong())
|
||||
.map { it[AlbumsTable.id] }
|
||||
|
||||
ids.mapNotNull { albumRecord(it, folderIds, userName) }
|
||||
}
|
||||
|
||||
fun searchSongs(
|
||||
query: String,
|
||||
limit: Int,
|
||||
offset: Int,
|
||||
folderIds: Set<Int>,
|
||||
userName: String,
|
||||
): List<SongRecord> = read {
|
||||
if (folderIds.isEmpty()) return@read emptyList()
|
||||
|
||||
val pattern = likePattern(query)
|
||||
val rows = SongsTable.selectAll()
|
||||
.where {
|
||||
(SongsTable.searchText like pattern) and
|
||||
(SongsTable.folderId inList folderIds)
|
||||
}
|
||||
.orderBy(SongsTable.title to SortOrder.ASC)
|
||||
.limit(limit)
|
||||
.offset(offset.toLong())
|
||||
.toList()
|
||||
|
||||
enrichSongs(rows, userName)
|
||||
}
|
||||
|
||||
fun resolveSong(
|
||||
songId: String,
|
||||
folderIds: Set<Int>,
|
||||
userName: String,
|
||||
library: LibraryConfig,
|
||||
): ResolvedSong? {
|
||||
val song = song(songId, folderIds, userName) ?: return null
|
||||
val folder = library.byId(song.folderId) ?: return null
|
||||
val file = folder.path.resolve(song.relativePath).normalize()
|
||||
|
||||
if (!file.startsWith(folder.path)) return null
|
||||
if (!Files.isRegularFile(file)) return null
|
||||
|
||||
return ResolvedSong(song, file)
|
||||
}
|
||||
|
||||
fun albumIdForSong(songId: String, folderIds: Set<Int>): String? = read {
|
||||
if (folderIds.isEmpty()) return@read null
|
||||
|
||||
SongsTable
|
||||
.select(SongsTable.albumId)
|
||||
.where {
|
||||
(SongsTable.id eq songId) and
|
||||
(SongsTable.folderId inList folderIds)
|
||||
}
|
||||
.singleOrNull()
|
||||
?.get(SongsTable.albumId)
|
||||
}
|
||||
|
||||
private fun albumRecord(albumId: String, folderIds: Set<Int>, userName: String): AlbumRecord? {
|
||||
if (folderIds.isEmpty()) return null
|
||||
|
||||
val albumRow = AlbumsTable.selectAll()
|
||||
.where { AlbumsTable.id eq albumId }
|
||||
.singleOrNull() ?: return null
|
||||
|
||||
val songs = SongsTable.selectAll()
|
||||
.where {
|
||||
(SongsTable.albumId eq albumId) and
|
||||
(SongsTable.folderId inList folderIds)
|
||||
}
|
||||
.toList()
|
||||
if (songs.isEmpty()) return null
|
||||
|
||||
val primaryArtist = AlbumArtistsTable
|
||||
.join(ArtistsTable, JoinType.INNER, AlbumArtistsTable.artistId, ArtistsTable.id)
|
||||
.select(AlbumArtistsTable.albumId, ArtistsTable.id, ArtistsTable.name, AlbumArtistsTable.position)
|
||||
.where { AlbumArtistsTable.albumId eq albumId }
|
||||
.orderBy(AlbumArtistsTable.position to SortOrder.ASC)
|
||||
.firstOrNull()
|
||||
|
||||
val playCount = songStates(userName, songs.map { it[SongsTable.id] })
|
||||
.values
|
||||
.sumOf { it.playCount }
|
||||
|
||||
val state = itemStates(userName, "album")[albumId]
|
||||
|
||||
return AlbumRecord(
|
||||
id = albumId,
|
||||
name = albumRow[AlbumsTable.name],
|
||||
artistId = primaryArtist?.get(ArtistsTable.id),
|
||||
artistName = primaryArtist?.get(ArtistsTable.name),
|
||||
year = albumRow[AlbumsTable.year],
|
||||
coverArt = albumRow[AlbumsTable.coverArt],
|
||||
songCount = songs.size,
|
||||
duration = songs.sumOf { it[SongsTable.duration] },
|
||||
playCount = playCount,
|
||||
created = albumRow[AlbumsTable.createdAt],
|
||||
starredAt = state?.starredAt,
|
||||
rating = state?.rating,
|
||||
genres = AlbumGenresTable
|
||||
.select(AlbumGenresTable.genre)
|
||||
.where { AlbumGenresTable.albumId eq albumId }
|
||||
.map { it[AlbumGenresTable.genre] }
|
||||
.sorted(),
|
||||
)
|
||||
}
|
||||
|
||||
private fun enrichSongs(rows: List<ResultRow>, userName: String): List<SongRecord> {
|
||||
if (rows.isEmpty()) return emptyList()
|
||||
|
||||
val songIds = rows.map { it[SongsTable.id] }
|
||||
val albumIds = rows.map { it[SongsTable.albumId] }.distinct()
|
||||
|
||||
val songArtists = SongArtistsTable
|
||||
.join(ArtistsTable, JoinType.INNER, SongArtistsTable.artistId, ArtistsTable.id)
|
||||
.select(SongArtistsTable.songId, ArtistsTable.id, ArtistsTable.name, SongArtistsTable.position)
|
||||
.where { SongArtistsTable.songId inList songIds }
|
||||
.orderBy(SongArtistsTable.position to SortOrder.ASC)
|
||||
.groupBy { it[SongArtistsTable.songId] }
|
||||
.mapValues { (_, artistRows) ->
|
||||
artistRows.map { ArtistRefRecord(it[ArtistsTable.id], it[ArtistsTable.name]) }
|
||||
}
|
||||
|
||||
val albumArtists = AlbumArtistsTable
|
||||
.join(ArtistsTable, JoinType.INNER, AlbumArtistsTable.artistId, ArtistsTable.id)
|
||||
.select(AlbumArtistsTable.albumId, ArtistsTable.id, ArtistsTable.name, AlbumArtistsTable.position)
|
||||
.where { AlbumArtistsTable.albumId inList albumIds }
|
||||
.orderBy(AlbumArtistsTable.position to SortOrder.ASC)
|
||||
.groupBy { it[AlbumArtistsTable.albumId] }
|
||||
.mapValues { (_, artistRows) ->
|
||||
ArtistRefRecord(artistRows.first()[ArtistsTable.id], artistRows.first()[ArtistsTable.name])
|
||||
}
|
||||
|
||||
val covers = AlbumsTable.selectAll()
|
||||
.where { AlbumsTable.id inList albumIds }
|
||||
.associate { it[AlbumsTable.id] to it[AlbumsTable.coverArt] }
|
||||
|
||||
val genres = SongGenresTable.selectAll()
|
||||
.where { SongGenresTable.songId inList songIds }
|
||||
.groupBy { it[SongGenresTable.songId] }
|
||||
.mapValues { (_, genreRows) -> genreRows.map { it[SongGenresTable.genre] }.sorted() }
|
||||
|
||||
val states = songStates(userName, songIds)
|
||||
|
||||
return rows.map { row ->
|
||||
val id = row[SongsTable.id]
|
||||
val albumId = row[SongsTable.albumId]
|
||||
val primaryArtist = albumArtists[albumId]
|
||||
val state = states[id]
|
||||
|
||||
SongRecord(
|
||||
id = id,
|
||||
albumId = albumId,
|
||||
albumName = row[SongsTable.albumName],
|
||||
artistId = primaryArtist?.id,
|
||||
artistName = row[SongsTable.displayArtist],
|
||||
displayArtist = row[SongsTable.displayArtist],
|
||||
title = row[SongsTable.title],
|
||||
trackNumber = row[SongsTable.trackNumber],
|
||||
discNumber = row[SongsTable.discNumber],
|
||||
year = row[SongsTable.year],
|
||||
duration = row[SongsTable.duration],
|
||||
bitRate = row[SongsTable.bitRate],
|
||||
size = row[SongsTable.size],
|
||||
suffix = row[SongsTable.suffix],
|
||||
contentType = row[SongsTable.contentType],
|
||||
coverArt = covers[albumId],
|
||||
folderId = row[SongsTable.folderId],
|
||||
relativePath = row[SongsTable.relativePath],
|
||||
created = row[SongsTable.createdAt],
|
||||
starredAt = state?.starredAt,
|
||||
rating = state?.rating,
|
||||
playCount = state?.playCount ?: 0,
|
||||
artists = songArtists[id].orEmpty(),
|
||||
genres = genres[id].orEmpty(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun visibleSongs(folderIds: Set<Int>) =
|
||||
SongsTable
|
||||
.select(SongsTable.id)
|
||||
.where { SongsTable.folderId inList folderIds }
|
||||
|
||||
private fun visibleAlbums(folderIds: Set<Int>) =
|
||||
SongsTable
|
||||
.select(SongsTable.albumId)
|
||||
.withDistinct()
|
||||
.where { SongsTable.folderId inList folderIds }
|
||||
|
||||
private fun itemStates(userName: String, itemType: String): Map<String, UserItemState> =
|
||||
UserStarsTable.selectAll()
|
||||
.where {
|
||||
(UserStarsTable.userName eq userName) and
|
||||
(UserStarsTable.itemType eq itemType)
|
||||
}
|
||||
.associate {
|
||||
it[UserStarsTable.itemId] to UserItemState(
|
||||
starredAt = it[UserStarsTable.starredAt],
|
||||
rating = it[UserStarsTable.rating],
|
||||
)
|
||||
}
|
||||
|
||||
private fun songStates(userName: String, songIds: Collection<String>): Map<String, UserSongState> {
|
||||
if (songIds.isEmpty()) return emptyMap()
|
||||
|
||||
return UserSongStateTable.selectAll()
|
||||
.where {
|
||||
(UserSongStateTable.userName eq userName) and
|
||||
(UserSongStateTable.songId inList songIds.toList())
|
||||
}
|
||||
.associate {
|
||||
it[UserSongStateTable.songId] to UserSongState(
|
||||
playCount = it[UserSongStateTable.playCount],
|
||||
starredAt = it[UserSongStateTable.starredAt],
|
||||
rating = it[UserSongStateTable.rating],
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Literal substring matching; `%` and `_` are removed instead of acting as wildcards. */
|
||||
private fun likePattern(query: String): String {
|
||||
val needle = IdGenerator.normalize(query).replace("%", "").replace("_", "")
|
||||
return "%$needle%"
|
||||
}
|
||||
|
||||
private fun <T> read(block: Transaction.() -> T): T = transaction { block() }
|
||||
}
|
||||
@@ -118,6 +118,7 @@ object UserStarsTable : Table("user_stars") {
|
||||
val itemType = varchar("item_type", 16)
|
||||
val itemId = varchar("item_id", 32)
|
||||
val starredAt = varchar("starred_at", 40)
|
||||
val rating = integer("rating").nullable()
|
||||
|
||||
override val primaryKey = PrimaryKey(userName, itemType, itemId)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
package win.taptap.musicmanager.subsonic.models
|
||||
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.add
|
||||
import kotlinx.serialization.json.buildJsonArray
|
||||
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.SongRecord
|
||||
import win.taptap.musicmanager.util.IdGenerator
|
||||
|
||||
const val IGNORED_ARTICLES = "The El La Los Las Le Les"
|
||||
|
||||
fun songJson(song: SongRecord): JsonObject = buildJsonObject {
|
||||
put("id", song.id)
|
||||
put("parent", song.albumId)
|
||||
put("isDir", false)
|
||||
put("title", song.title)
|
||||
put("album", song.albumName)
|
||||
put("artist", song.artistName)
|
||||
put("displayArtist", song.displayArtist)
|
||||
song.trackNumber?.let { put("track", it) }
|
||||
song.year?.let { put("year", it) }
|
||||
song.genres.firstOrNull()?.let { put("genre", it) }
|
||||
song.coverArt?.let { put("coverArt", it) }
|
||||
put("size", song.size)
|
||||
put("contentType", song.contentType)
|
||||
put("suffix", song.suffix)
|
||||
put("duration", song.duration)
|
||||
put("bitRate", song.bitRate)
|
||||
put("path", song.relativePath)
|
||||
put("isVideo", false)
|
||||
put("type", "music")
|
||||
put("albumId", song.albumId)
|
||||
song.artistId?.let { put("artistId", it) }
|
||||
put("discNumber", song.discNumber)
|
||||
put("created", song.created)
|
||||
put("playCount", song.playCount)
|
||||
song.starredAt?.let { put("starred", it) }
|
||||
song.rating?.let { put("userRating", it) }
|
||||
put("artists", buildJsonArray {
|
||||
song.artists.forEach { artist ->
|
||||
add(buildJsonObject {
|
||||
put("id", artist.id)
|
||||
put("name", artist.name)
|
||||
})
|
||||
}
|
||||
})
|
||||
put("genres", stringArray(song.genres))
|
||||
}
|
||||
|
||||
fun albumJson(album: AlbumRecord, songs: List<SongRecord>? = null): JsonObject = buildJsonObject {
|
||||
put("id", album.id)
|
||||
put("name", album.name)
|
||||
album.artistName?.let { put("artist", it) }
|
||||
album.artistId?.let { put("artistId", it) }
|
||||
album.coverArt?.let { put("coverArt", it) }
|
||||
put("songCount", album.songCount)
|
||||
put("duration", album.duration)
|
||||
put("playCount", album.playCount)
|
||||
put("created", album.created)
|
||||
album.year?.let { put("year", it) }
|
||||
album.genres.firstOrNull()?.let { put("genre", it) }
|
||||
album.starredAt?.let { put("starred", it) }
|
||||
album.rating?.let { put("userRating", it) }
|
||||
put("genres", stringArray(album.genres))
|
||||
|
||||
songs?.let { list ->
|
||||
put("song", buildJsonArray { list.forEach { add(songJson(it)) } })
|
||||
}
|
||||
}
|
||||
|
||||
fun artistJson(artist: ArtistRecord, albums: List<AlbumRecord>? = null): JsonObject = buildJsonObject {
|
||||
put("id", artist.id)
|
||||
put("name", artist.name)
|
||||
put("albumCount", artist.albumCount)
|
||||
put("sortName", artist.sortName)
|
||||
artist.starredAt?.let { put("starred", it) }
|
||||
artist.rating?.let { put("userRating", it) }
|
||||
|
||||
albums?.let { list ->
|
||||
put("album", buildJsonArray { list.forEach { add(albumJson(it)) } })
|
||||
}
|
||||
}
|
||||
|
||||
fun artistIndexArray(artists: List<ArtistRecord>): JsonArray {
|
||||
val groups = artists.groupBy { indexLetter(it.sortName) }
|
||||
val keys = groups.keys.sortedWith(compareBy { if (it == "#") "\uFFFF" else it })
|
||||
|
||||
return buildJsonArray {
|
||||
keys.forEach { key ->
|
||||
add(buildJsonObject {
|
||||
put("name", key)
|
||||
put("artist", buildJsonArray {
|
||||
groups.getValue(key)
|
||||
.sortedBy { IdGenerator.normalize(it.sortName) }
|
||||
.forEach { add(artistJson(it)) }
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun indexLetter(sortName: String): String {
|
||||
val first = IdGenerator.normalize(sortName).firstOrNull() ?: return "#"
|
||||
return if (first.isLetter()) first.uppercaseChar().toString() else "#"
|
||||
}
|
||||
|
||||
private fun stringArray(values: List<String>): JsonArray = buildJsonArray {
|
||||
values.forEach { add(JsonPrimitive(it)) }
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package win.taptap.musicmanager.subsonic.routes
|
||||
|
||||
import io.ktor.http.Parameters
|
||||
import io.ktor.server.application.ApplicationCall
|
||||
import io.ktor.server.routing.Route
|
||||
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.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.songJson
|
||||
import win.taptap.musicmanager.subsonic.respondSubsonic
|
||||
import win.taptap.musicmanager.subsonic.respondSubsonicError
|
||||
|
||||
fun Route.browsingRoutes(users: UsersConfig, library: LibraryConfig) {
|
||||
|
||||
subsonicGet(users, "/getMusicFolders") { call, user ->
|
||||
val visible = user.visibleFolderIds(library)
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put("musicFolders", buildJsonObject {
|
||||
put("musicFolder", buildJsonArray {
|
||||
library.folders
|
||||
.filter { it.id in visible }
|
||||
.sortedBy { it.id }
|
||||
.forEach { folder ->
|
||||
add(buildJsonObject {
|
||||
put("id", folder.id)
|
||||
put("name", folder.name)
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
subsonicGet(users, "/getIndexes") { call, user ->
|
||||
val artists = LibraryRepository.artists(user.visibleFolderIds(library), user.name)
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put("indexes", buildJsonObject {
|
||||
put("ignoredArticles", IGNORED_ARTICLES)
|
||||
put("lastModified", 0)
|
||||
put("index", artistIndexArray(artists))
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
subsonicGet(users, "/getArtists") { call, user ->
|
||||
val artists = LibraryRepository.artists(user.visibleFolderIds(library), user.name)
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put("artists", buildJsonObject {
|
||||
put("ignoredArticles", IGNORED_ARTICLES)
|
||||
put("index", artistIndexArray(artists))
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
subsonicGet(users, "/getArtist") { call, user ->
|
||||
val id = call.subsonicParams()["id"]
|
||||
if (id.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
val folders = user.visibleFolderIds(library)
|
||||
val artist = LibraryRepository.artist(id, folders, user.name)
|
||||
if (artist == null) {
|
||||
call.respondSubsonicError(70, "Artist not found")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
val albums = LibraryRepository.albumsForArtist(id, folders, user.name)
|
||||
call.respondSubsonic(buildJsonObject { put("artist", artistJson(artist, albums)) })
|
||||
}
|
||||
|
||||
subsonicGet(users, "/getAlbum") { call, user ->
|
||||
val id = call.subsonicParams()["id"]
|
||||
if (id.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
val folders = user.visibleFolderIds(library)
|
||||
val album = LibraryRepository.album(id, folders, user.name)
|
||||
if (album == null) {
|
||||
call.respondSubsonicError(70, "Album not found")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
val songs = LibraryRepository.albumSongs(id, folders, user.name)
|
||||
call.respondSubsonic(buildJsonObject { put("album", albumJson(album, songs)) })
|
||||
}
|
||||
|
||||
subsonicGet(users, "/getSong") { call, user ->
|
||||
val id = call.subsonicParams()["id"]
|
||||
if (id.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
val song = LibraryRepository.song(id, user.visibleFolderIds(library), user.name)
|
||||
if (song == null) {
|
||||
call.respondSubsonicError(70, "Song not found")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
call.respondSubsonic(buildJsonObject { put("song", songJson(song)) })
|
||||
}
|
||||
|
||||
subsonicGet(users, "/search3") { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val query = parameters["query"].orEmpty()
|
||||
val folders = user.visibleFolderIds(library)
|
||||
val all = query.isBlank() || query == "*"
|
||||
|
||||
val artistCount = parameters.intParam("artistCount", 20)
|
||||
val artistOffset = parameters.intParam("artistOffset", 0, minimum = 0)
|
||||
val albumCount = parameters.intParam("albumCount", 20)
|
||||
val albumOffset = parameters.intParam("albumOffset", 0, minimum = 0)
|
||||
val songCount = parameters.intParam("songCount", 20)
|
||||
val songOffset = parameters.intParam("songOffset", 0, minimum = 0)
|
||||
|
||||
val artists = if (all) {
|
||||
LibraryRepository.artists(folders, user.name)
|
||||
.drop(artistOffset)
|
||||
.take(artistCount)
|
||||
} else {
|
||||
LibraryRepository.searchArtists(query, artistCount, artistOffset, folders, user.name)
|
||||
}
|
||||
val albums = if (all) {
|
||||
LibraryRepository.allAlbums(albumCount, albumOffset, folders, user.name)
|
||||
} else {
|
||||
LibraryRepository.searchAlbums(query, albumCount, albumOffset, folders, user.name)
|
||||
}
|
||||
val songs = if (all) {
|
||||
LibraryRepository.allSongs(songCount, songOffset, folders, user.name)
|
||||
} else {
|
||||
LibraryRepository.searchSongs(query, songCount, songOffset, folders, user.name)
|
||||
}
|
||||
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put("searchResult3", buildJsonObject {
|
||||
put("artist", buildJsonArray { artists.forEach { add(artistJson(it)) } })
|
||||
put("album", buildJsonArray { albums.forEach { add(albumJson(it)) } })
|
||||
put("song", buildJsonArray { songs.forEach { add(songJson(it)) } })
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun Parameters.intParam(name: String, default: Int, minimum: Int = 0): Int {
|
||||
val raw = this[name] ?: return default
|
||||
val parsed = raw.toIntOrNull() ?: return default
|
||||
return parsed.coerceIn(minimum, 500)
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package win.taptap.musicmanager.subsonic.routes
|
||||
|
||||
import io.ktor.http.HttpHeaders
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import io.ktor.server.response.respond
|
||||
import io.ktor.server.response.respondFile
|
||||
import io.ktor.server.routing.Route
|
||||
import java.net.URLEncoder
|
||||
import win.taptap.musicmanager.config.LibraryConfig
|
||||
import win.taptap.musicmanager.config.UsersConfig
|
||||
import win.taptap.musicmanager.db.LibraryRepository
|
||||
import win.taptap.musicmanager.scanner.CoverArtService
|
||||
import win.taptap.musicmanager.subsonic.respondSubsonicError
|
||||
|
||||
fun Route.mediaRoutes(
|
||||
users: UsersConfig,
|
||||
library: LibraryConfig,
|
||||
coverArtService: CoverArtService,
|
||||
) {
|
||||
|
||||
subsonicGet(users, "/stream") { call, user ->
|
||||
val id = call.subsonicParams()["id"]
|
||||
if (id.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
val resolved = LibraryRepository.resolveSong(
|
||||
id,
|
||||
user.visibleFolderIds(library),
|
||||
user.name,
|
||||
library,
|
||||
)
|
||||
if (resolved == null) {
|
||||
call.respondSubsonicError(70, "Song not found")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
call.respondFile(resolved.file.toFile())
|
||||
}
|
||||
|
||||
subsonicGet(users, "/download") { call, user ->
|
||||
val id = call.subsonicParams()["id"]
|
||||
if (id.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
val resolved = LibraryRepository.resolveSong(
|
||||
id,
|
||||
user.visibleFolderIds(library),
|
||||
user.name,
|
||||
library,
|
||||
)
|
||||
if (resolved == null) {
|
||||
call.respondSubsonicError(70, "Song not found")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
call.response.headers.append(
|
||||
HttpHeaders.ContentDisposition,
|
||||
contentDisposition(resolved.file.fileName.toString()),
|
||||
)
|
||||
call.respondFile(resolved.file.toFile())
|
||||
}
|
||||
|
||||
subsonicGet(users, "/getCoverArt") { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val id = parameters["id"]
|
||||
if (id.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
val requestedSize = parameters["size"]
|
||||
val size = requestedSize?.toIntOrNull()
|
||||
if (requestedSize != null && (size == null || size !in 1..2048)) {
|
||||
call.respondSubsonicError(10, "Invalid cover size")
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
val folders = user.visibleFolderIds(library)
|
||||
val albumId = if (id.startsWith("sg-")) {
|
||||
LibraryRepository.albumIdForSong(id, folders)
|
||||
} else if (LibraryRepository.album(id, folders, user.name) != null) {
|
||||
id
|
||||
} else {
|
||||
null
|
||||
}
|
||||
|
||||
if (albumId == null) {
|
||||
call.respond(HttpStatusCode.NotFound)
|
||||
return@subsonicGet
|
||||
}
|
||||
|
||||
val cover = if (size == null) {
|
||||
coverArtService.coverFile(albumId)
|
||||
} else {
|
||||
coverArtService.resizedCover(albumId, size)
|
||||
}
|
||||
|
||||
if (cover == null) {
|
||||
call.respond(HttpStatusCode.NotFound)
|
||||
} else {
|
||||
call.respondFile(cover.toFile())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun contentDisposition(fileName: String): String {
|
||||
val encoded = URLEncoder.encode(fileName, Charsets.UTF_8).replace("+", "%20")
|
||||
val ascii = fileName.map { character ->
|
||||
if (character.code in 32..126 && character != '"' && character != '\\') character else '_'
|
||||
}.joinToString("")
|
||||
|
||||
return "attachment; filename=\"$ascii\"; filename*=UTF-8''$encoded"
|
||||
}
|
||||
@@ -11,6 +11,11 @@ import io.ktor.util.AttributeKey
|
||||
import win.taptap.musicmanager.config.UserAccount
|
||||
|
||||
val CurrentUserKey = AttributeKey<UserAccount>("musicmanager.currentUser")
|
||||
val SubsonicParametersKey = AttributeKey<Parameters>("musicmanager.parameters")
|
||||
|
||||
/** Parameters captured during authentication, so POST bodies are only read once. */
|
||||
fun ApplicationCall.subsonicParams(): Parameters =
|
||||
attributes.getOrNull(SubsonicParametersKey) ?: request.queryParameters
|
||||
|
||||
/**
|
||||
* Unified parameter access for Subsonic: query parameters plus URL-encoded form
|
||||
|
||||
@@ -28,6 +28,7 @@ internal fun Route.subsonicGet(
|
||||
call.respondSubsonicError(40, "Wrong username or password")
|
||||
} else {
|
||||
call.attributes.put(CurrentUserKey, user)
|
||||
call.attributes.put(SubsonicParametersKey, parameters)
|
||||
handler(call, user)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,16 +2,22 @@ package win.taptap.musicmanager.subsonic.routes
|
||||
|
||||
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.scanner.CoverArtService
|
||||
import win.taptap.musicmanager.scanner.ScanStatus
|
||||
|
||||
/** Authenticated `/rest` subtree. */
|
||||
fun Route.subsonicRoutes(
|
||||
users: UsersConfig,
|
||||
library: LibraryConfig,
|
||||
coverArtService: CoverArtService,
|
||||
startScan: () -> Boolean,
|
||||
scanStatus: () -> ScanStatus,
|
||||
) {
|
||||
route("/rest") {
|
||||
systemRoutes(users, startScan, scanStatus)
|
||||
browsingRoutes(users, library)
|
||||
mediaRoutes(users, library, coverArtService)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user