From 46266d80714e3f685fd237098260c548e53590cc Mon Sep 17 00:00:00 2001 From: TapTap Date: Fri, 13 Nov 2026 12:33:10 +0000 Subject: [PATCH] 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 --- README.md | 7 +- .../musicmanager/db/LibraryRepository.kt | 229 +++++++++++++++- .../taptap/musicmanager/db/MediaRepository.kt | 2 + .../musicmanager/db/PlaylistRepository.kt | 173 ++++++++++++ .../win/taptap/musicmanager/db/Tables.kt | 1 + .../musicmanager/db/UserStateRepository.kt | 217 +++++++++++++++ .../subsonic/models/JsonModels.kt | 25 ++ .../subsonic/routes/BrowsingRoutes.kt | 174 +++++++++++- .../subsonic/routes/InteractionRoutes.kt | 255 ++++++++++++++++++ .../subsonic/routes/PlaylistRoutes.kt | 159 +++++++++++ .../subsonic/routes/RouteHelpers.kt | 11 + .../subsonic/routes/SubsonicRoutes.kt | 2 + .../db/migration/V3__song_lyrics.sql | 3 + .../subsonic/BrowsingRoutesTest.kt | 151 ++++++++++- 14 files changed, 1400 insertions(+), 9 deletions(-) create mode 100644 src/main/kotlin/win/taptap/musicmanager/db/PlaylistRepository.kt create mode 100644 src/main/kotlin/win/taptap/musicmanager/db/UserStateRepository.kt create mode 100644 src/main/kotlin/win/taptap/musicmanager/subsonic/routes/InteractionRoutes.kt create mode 100644 src/main/kotlin/win/taptap/musicmanager/subsonic/routes/PlaylistRoutes.kt create mode 100644 src/main/resources/db/migration/V3__song_lyrics.sql diff --git a/README.md b/README.md index dd95cba..b98dd1a 100644 --- a/README.md +++ b/README.md @@ -191,7 +191,10 @@ src/main/kotlin/win/taptap/musicmanager/ |-- db/ | |-- DatabaseFactory.kt # SQLite init, PRAGMA journal_mode=WAL, Flyway | |-- Tables.kt # Exposed table definitions -| |-- Repositories.kt # CRUD & queries for artists, albums, songs, playlists +| |-- LibraryRepository.kt # Visibility-scoped browsing, feeds, genres, search +| |-- UserStateRepository.kt # Play counts, stars, ratings, bookmarks +| |-- PlaylistRepository.kt # Playlist CRUD and visibility +| |-- MediaRepository.kt # Scanner persistence and aggregate rebuilds | `-- migrations/ # Flyway SQL (V1__init.sql, ...) |-- scanner/ | |-- MediaScanner.kt # Recursive scan, delta updates, orphan cleanup @@ -670,7 +673,7 @@ Verify each step with `./gradlew test` and/or `curl`: - [x] 3. **Ktor core & auth:** `PartialContent`, content negotiation (`ignoreUnknownKeys`, `encodeDefaults`), `SubsonicAuth`, response wrapper, health endpoint. - [x] 4. **Browsing & media:** system, browsing, genre and media routes (`stream`, `download`, `getCoverArt`). - [ ] 5. **Transcoding:** `FfmpegTranscoder.kt`, `maxBitRate`/`format`/`timeOffset`, extension declaration. -- [ ] 6. **Interaction & playlists:** `getAlbumList2`, `getRandomSongs`, `getStarred2`, `search3`, `scrobble`, `star`/`unstar`, `setRating`, bookmarks, playlists. +- [x] 6. **Interaction & playlists:** `getAlbumList2`, `getRandomSongs`, `getStarred2`, `search3`, `scrobble`, `star`/`unstar`, `setRating`, bookmarks, playlists. - [ ] 7. **Packaging:** multi-stage Dockerfile (with ffmpeg), Helm chart, Gitea Actions workflow. - [ ] 8. **Tests:** integration suite as described above, plus a `curl` smoke script. diff --git a/src/main/kotlin/win/taptap/musicmanager/db/LibraryRepository.kt b/src/main/kotlin/win/taptap/musicmanager/db/LibraryRepository.kt index 520c7de..8592f90 100644 --- a/src/main/kotlin/win/taptap/musicmanager/db/LibraryRepository.kt +++ b/src/main/kotlin/win/taptap/musicmanager/db/LibraryRepository.kt @@ -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, + val albums: List, + val songs: List, +) + 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, val genres: List, ) @@ -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, + userName: String, + ): List = 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 { it.lastPlayedAt ?: "" } + .thenByDescending { it.created }, + ) + "frequent" -> albums.sortedWith( + compareByDescending { 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 { 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, + userName: String, + ): List = 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): List = 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, + userName: String, + ): List = 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): 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): 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, folderIds: Set, userName: String): List = 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, @@ -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], ) diff --git a/src/main/kotlin/win/taptap/musicmanager/db/MediaRepository.kt b/src/main/kotlin/win/taptap/musicmanager/db/MediaRepository.kt index 9754ac8..de6ed0d 100644 --- a/src/main/kotlin/win/taptap/musicmanager/db/MediaRepository.kt +++ b/src/main/kotlin/win/taptap/musicmanager/db/MediaRepository.kt @@ -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 } } diff --git a/src/main/kotlin/win/taptap/musicmanager/db/PlaylistRepository.kt b/src/main/kotlin/win/taptap/musicmanager/db/PlaylistRepository.kt new file mode 100644 index 0000000..8c6b3d8 --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/db/PlaylistRepository.kt @@ -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 = 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 = 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): 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, 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, + removeIndices: List, + ): 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 = + 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) { + 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], + ) + } +} diff --git a/src/main/kotlin/win/taptap/musicmanager/db/Tables.kt b/src/main/kotlin/win/taptap/musicmanager/db/Tables.kt index b900d13..45f8b0c 100644 --- a/src/main/kotlin/win/taptap/musicmanager/db/Tables.kt +++ b/src/main/kotlin/win/taptap/musicmanager/db/Tables.kt @@ -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) } diff --git a/src/main/kotlin/win/taptap/musicmanager/db/UserStateRepository.kt b/src/main/kotlin/win/taptap/musicmanager/db/UserStateRepository.kt new file mode 100644 index 0000000..40c6263 --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/db/UserStateRepository.kt @@ -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 = 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], + ) + } + } +} diff --git a/src/main/kotlin/win/taptap/musicmanager/subsonic/models/JsonModels.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/models/JsonModels.kt index 0574e4e..ab150ad 100644 --- a/src/main/kotlin/win/taptap/musicmanager/subsonic/models/JsonModels.kt +++ b/src/main/kotlin/win/taptap/musicmanager/subsonic/models/JsonModels.kt @@ -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): JsonArray { } } +fun playlistJson(playlist: PlaylistRecord, songs: List? = 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 "#" diff --git a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/BrowsingRoutes.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/BrowsingRoutes.kt index ca7c741..0c6feba 100644 --- a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/BrowsingRoutes.kt +++ b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/BrowsingRoutes.kt @@ -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) diff --git a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/InteractionRoutes.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/InteractionRoutes.kt new file mode 100644 index 0000000..27b9c61 --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/InteractionRoutes.kt @@ -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, + albumIds: List, + artistIds: List, + folderIds: Set, + 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 +} diff --git a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/PlaylistRoutes.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/PlaylistRoutes.kt new file mode 100644 index 0000000..062d28b --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/PlaylistRoutes.kt @@ -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() + } +} diff --git a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/RouteHelpers.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/RouteHelpers.kt index 51d831c..e8c7a86 100644 --- a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/RouteHelpers.kt +++ b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/RouteHelpers.kt @@ -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("musicmanager.currentUser") val SubsonicParametersKey = AttributeKey("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 { + 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 diff --git a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/SubsonicRoutes.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/SubsonicRoutes.kt index 902b50e..db6ec1d 100644 --- a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/SubsonicRoutes.kt +++ b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/SubsonicRoutes.kt @@ -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) } } diff --git a/src/main/resources/db/migration/V3__song_lyrics.sql b/src/main/resources/db/migration/V3__song_lyrics.sql new file mode 100644 index 0000000..499e4dd --- /dev/null +++ b/src/main/resources/db/migration/V3__song_lyrics.sql @@ -0,0 +1,3 @@ +-- Lyrics are extracted from ID3 tags or sibling .lrc files during scanning and +-- served through the OpenSubsonic songLyrics endpoint. +ALTER TABLE songs ADD COLUMN lyrics TEXT; diff --git a/src/test/kotlin/win/taptap/musicmanager/subsonic/BrowsingRoutesTest.kt b/src/test/kotlin/win/taptap/musicmanager/subsonic/BrowsingRoutesTest.kt index 00e7621..4cc17bf 100644 --- a/src/test/kotlin/win/taptap/musicmanager/subsonic/BrowsingRoutesTest.kt +++ b/src/test/kotlin/win/taptap/musicmanager/subsonic/BrowsingRoutesTest.kt @@ -24,7 +24,6 @@ import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import kotlin.test.Test import kotlin.test.assertEquals -import kotlin.test.assertNotNull import kotlin.test.assertTrue import org.jetbrains.exposed.sql.insert import org.jetbrains.exposed.sql.transactions.transaction @@ -202,6 +201,156 @@ class BrowsingRoutesTest { } } + @Test + fun `album feeds genres and random songs are visibility scoped`() { + seededContext().use { seed -> + testApplication { + setupApp(seed) + val auth = credentials("alice", "alice-pw") + + val albums = parseBody( + client.get("/rest/getAlbumList2?$auth&type=alphabeticalByName&size=10").bodyAsText(), + )["albumList2"]!!.jsonObject["album"]!!.jsonArray + assertEquals(1, albums.size) + assertEquals(seed.aliceAlbumId, albums[0].jsonObject["id"]!!.jsonPrimitive.content) + + val recent = parseBody( + client.get("/rest/getAlbumList2?$auth&type=recent&size=10").bodyAsText(), + )["albumList2"]!!.jsonObject["album"]!!.jsonArray + assertEquals(1, recent.size) + + val genres = parseBody(client.get("/rest/getGenres?$auth").bodyAsText())["genres"]!! + .jsonObject["genre"]!!.jsonArray + assertEquals(listOf("Rock"), genres.map { it.jsonObject["value"]!!.jsonPrimitive.content }) + + val byGenre = parseBody( + client.get("/rest/getSongsByGenre?$auth&genre=Rock&count=10").bodyAsText(), + )["songsByGenre"]!!.jsonObject["song"]!!.jsonArray + assertEquals(seed.aliceSongId, byGenre.single().jsonObject["id"]!!.jsonPrimitive.content) + + val random = parseBody( + client.get("/rest/getRandomSongs?$auth&size=10").bodyAsText(), + )["randomSongs"]!!.jsonObject["song"]!!.jsonArray + assertEquals(seed.aliceSongId, random.single().jsonObject["id"]!!.jsonPrimitive.content) + } + } + } + + @Test + fun `scrobbling stars ratings and bookmarks are per user`() { + seededContext().use { seed -> + testApplication { + setupApp(seed) + val alice = credentials("alice", "alice-pw") + val bob = credentials("bob", "bob-pw") + + client.get("/rest/scrobble?$alice&id=${seed.aliceSongId}") + val played = parseBody( + client.get("/rest/getSong?$alice&id=${seed.aliceSongId}").bodyAsText(), + )["song"]!!.jsonObject + assertEquals(1, played["playCount"]!!.jsonPrimitive.int) + + client.get("/rest/star?$alice&id=${seed.aliceSongId}&albumId=${seed.aliceAlbumId}") + val starred = parseBody(client.get("/rest/getStarred2?$alice").bodyAsText())["starred2"]!! + .jsonObject + assertEquals(1, starred["song"]!!.jsonArray.size) + assertEquals(1, starred["album"]!!.jsonArray.size) + + val bobStarred = parseBody(client.get("/rest/getStarred2?$bob").bodyAsText())["starred2"]!! + .jsonObject + assertEquals(0, bobStarred["song"]!!.jsonArray.size) + + client.get("/rest/setRating?$alice&id=${seed.aliceSongId}&rating=4") + client.get("/rest/setRating?$alice&id=${seed.aliceAlbumId}&rating=5") + + val ratedSong = parseBody( + client.get("/rest/getSong?$alice&id=${seed.aliceSongId}").bodyAsText(), + )["song"]!!.jsonObject + assertEquals(4, ratedSong["userRating"]!!.jsonPrimitive.int) + + val ratedAlbum = parseBody( + client.get("/rest/getAlbum?$alice&id=${seed.aliceAlbumId}").bodyAsText(), + )["album"]!!.jsonObject + assertEquals(5, ratedAlbum["userRating"]!!.jsonPrimitive.int) + + client.get("/rest/createBookmark?$alice&id=${seed.aliceSongId}&position=5000") + val bookmarks = parseBody(client.get("/rest/getBookmarks?$alice").bodyAsText())["bookmarks"]!! + .jsonObject["bookmark"]!!.jsonArray + assertEquals(1, bookmarks.size) + assertEquals(5000, bookmarks[0].jsonObject["position"]!!.jsonPrimitive.int) + assertEquals( + seed.aliceSongId, + bookmarks[0].jsonObject["entry"]!!.jsonObject["id"]!!.jsonPrimitive.content, + ) + + client.get("/rest/deleteBookmark?$alice&id=${seed.aliceSongId}") + val empty = parseBody(client.get("/rest/getBookmarks?$alice").bodyAsText())["bookmarks"]!! + .jsonObject["bookmark"]!!.jsonArray + assertEquals(0, empty.size) + } + } + } + + @Test + fun `playlists enforce ownership and filter entries by visibility`() { + seededContext().use { seed -> + testApplication { + setupApp(seed) + val alice = credentials("alice", "alice-pw") + val bob = credentials("bob", "bob-pw") + + val created = parseBody( + client.get("/rest/createPlaylist?$alice&name=Alice List&songId=${seed.aliceSongId}").bodyAsText(), + )["playlist"]!!.jsonObject + val playlistId = created["id"]!!.jsonPrimitive.content + assertEquals("Alice List", created["name"]!!.jsonPrimitive.content) + assertEquals(1, created["songCount"]!!.jsonPrimitive.int) + + val aliceList = parseBody(client.get("/rest/getPlaylists?$alice").bodyAsText())["playlists"]!! + .jsonObject["playlist"]!!.jsonArray + assertEquals(1, aliceList.size) + + val bobDetail = parseBody( + client.get("/rest/getPlaylist?$bob&id=$playlistId").bodyAsText(), + )["playlist"]!!.jsonObject + assertEquals(1, bobDetail["songCount"]!!.jsonPrimitive.int) + assertEquals(0, bobDetail["entry"]!!.jsonArray.size) + + val forbidden = parseBody( + client.get("/rest/deletePlaylist?$bob&id=$playlistId").bodyAsText(), + ) + assertEquals(50, forbidden["error"]!!.jsonObject["code"]!!.jsonPrimitive.int) + + client.get("/rest/updatePlaylist?$alice&playlistId=$playlistId&songIndexToRemove=0") + val emptied = parseBody( + client.get("/rest/getPlaylist?$alice&id=$playlistId").bodyAsText(), + )["playlist"]!!.jsonObject + assertEquals(0, emptied["entry"]!!.jsonArray.size) + + val deleted = parseBody( + client.get("/rest/deletePlaylist?$alice&id=$playlistId").bodyAsText(), + ) + assertEquals("ok", deleted["status"]!!.jsonPrimitive.content) + } + } + } + + @Test + fun `lyrics endpoint returns an empty structure when the song has no lyrics`() { + seededContext().use { seed -> + testApplication { + setupApp(seed) + val auth = credentials("alice", "alice-pw") + + val body = parseBody( + client.get("/rest/getLyricsBySongId?$auth&id=${seed.aliceSongId}").bodyAsText(), + ) + val lyricsList = body["lyricsList"]!!.jsonObject + assertEquals(0, lyricsList["structuredLyrics"]?.jsonArray?.size ?: 0) + } + } + } + private fun ApplicationTestBuilder.setupApp(seed: Seed) { application { install(ContentNegotiation) {