feat!: replace OpenSubsonic with a native mood-first API
CI / chart (push) Successful in 3s
CI / chart-push (push) Successful in 3s
CI / test (push) Successful in 1m40s
CI / image (push) Successful in 3m12s

Remove the /rest compatibility layer and the playlist model. Moods are now
first-class private collections, and playback is driven by short-lived radio
sessions whose queues are generated by the server.

- Bearer device tokens (hashed) with revocable sessions.
- Library snapshot/delta sync with tombstones and per-folder scoping.
- Mood CRUD, seeds, preview and recommendations.
- Radio batches weighted by seeds, genres, artists, text and playback affinity.
- Playback events (started/completed/skipped) and explicit add-to-mood.
- Stream, download and cover endpoints with query-token support for browsers.
- V5 migration drops playlists and migrates existing moods; scanner writes
  tombstones and song update timestamps.
- Built-in UI rebuilt on the native API with a radio player.
- Native API integration tests and a rewritten smoke test (49 checks).
- Chart bumped to 0.2.0.

BREAKING CHANGE: the OpenSubsonic API and static playlists are gone.
This commit is contained in:
TapTap committed 2026-11-14 17:54:44 +00:00
1 parent 28bfdd9d00
commit b33eb076c1
46 files changed
+3472 -5823

No files matched your search

@@ -0,0 +1,188 @@
package win.taptap.musicmanager.api
import io.ktor.http.ContentType
import io.ktor.http.HttpHeaders
import io.ktor.http.HttpStatusCode
import io.ktor.server.response.respond
import io.ktor.server.response.header
import io.ktor.server.response.respondFile
import io.ktor.server.response.respondOutputStream
import io.ktor.server.routing.Route
import io.ktor.server.routing.get
import java.net.URLEncoder
import java.time.Instant
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.slf4j.LoggerFactory
import win.taptap.musicmanager.api.LibraryPage
import win.taptap.musicmanager.api.SearchResponse
import win.taptap.musicmanager.api.toDto
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.transcoding.FfmpegTranscoder
private val log = LoggerFactory.getLogger("win.taptap.musicmanager.api.LibraryRoutes")
fun Route.libraryRoutes(
users: UsersConfig,
library: LibraryConfig,
coverArtService: CoverArtService,
transcoder: FfmpegTranscoder,
) {
/**
* Snapshot sync (`cursor`) and delta sync (`since=revision`) in one endpoint.
* Deletions are returned explicitly so offline libraries can drop them.
*/
get("/library/songs") {
val user = call.requireApiUser(users)
val limit = (call.request.queryParameters["limit"]?.toIntOrNull() ?: 500).coerceIn(1, 1000)
val scope = call.request.queryParameters["scope"] ?: "all"
val folders = user.scopeFolders(library, scope)
val now = Instant.now().toString()
val since = call.request.queryParameters["since"]?.takeIf { it.isNotBlank() }
val cursor = call.request.queryParameters["cursor"]?.takeIf { it.isNotBlank() }
if (since != null) {
val changed = LibraryRepository.changedSongs(since, folders, limit, user.name)
val deleted = LibraryRepository.tombstones(since, limit).map { it.entityId }
val complete = changed.size < limit && deleted.size < limit
call.respond(
LibraryPage(
songs = changed.map { it.toDto() },
deletedSongIds = deleted,
revision = if (complete) now else changed.lastOrNull()?.updatedAt ?: now,
nextSince = if (changed.size == limit) changed.last().updatedAt else null,
),
)
return@get
}
val songs = LibraryRepository.syncSongs(folders, cursor.orEmpty(), limit, user.name)
call.respond(
LibraryPage(
songs = songs.map { it.toDto() },
revision = now,
nextCursor = if (songs.size == limit) songs.last().id else null,
),
)
}
get("/library/search") {
val user = call.requireApiUser(users)
val query = call.request.queryParameters["q"]?.trim().orEmpty()
if (query.isEmpty()) {
call.respond(SearchResponse(emptyList()))
return@get
}
val limit = (call.request.queryParameters["limit"]?.toIntOrNull() ?: 50).coerceIn(1, 200)
val folders = user.scopeFolders(library, call.request.queryParameters["scope"] ?: "all")
val songs = LibraryRepository.searchSongs(query, limit, 0, folders, user.name)
call.respond(SearchResponse(songs.map { it.toDto() }))
}
get("/songs/{id}/stream") {
val user = call.requireApiUser(users)
val id = call.parameters["id"] ?: badRequest("Song id is required")
val parameters = call.request.queryParameters
val rawMaxBitRate = parameters["maxBitRate"]
val maxBitRate = rawMaxBitRate?.toIntOrNull()
if (rawMaxBitRate != null && (maxBitRate == null || maxBitRate < 0)) {
badRequest("Invalid maxBitRate")
}
val rawOffset = parameters["timeOffset"]
val offset = rawOffset?.toIntOrNull()
if (rawOffset != null && (offset == null || offset < 0)) {
badRequest("Invalid timeOffset")
}
val resolved = LibraryRepository.resolveSong(
id,
user.visibleFolderIds(library),
user.name,
library,
) ?: notFound("Song")
if (!transcoder.shouldTranscode(
resolved.song.bitRate,
maxBitRate,
parameters["format"],
offset ?: 0,
)
) {
call.response.header(HttpHeaders.ContentType, resolved.song.contentType)
if (parameters["download"] == "true") {
call.response.header(
HttpHeaders.ContentDisposition,
contentDisposition(resolved.file.fileName.toString()),
)
}
call.respondFile(resolved.file.toFile())
return@get
}
val process = try {
transcoder.start(resolved.file, maxBitRate, offset ?: 0)
} catch (e: Exception) {
log.error("Failed to start ffmpeg for {}", resolved.file, e)
throw ApiException(HttpStatusCode.InternalServerError, "transcode_failed", "Transcoding failed")
}
try {
call.response.headers.append(HttpHeaders.CacheControl, "no-store")
call.respondOutputStream(ContentType.parse("audio/mpeg")) {
val output = this
withContext(Dispatchers.IO) {
process.inputStream.use { input -> input.copyTo(output) }
}
}
} finally {
transcoder.stop(process)
}
}
get("/covers/{id}") {
val user = call.requireApiUser(users)
val id = call.parameters["id"] ?: badRequest("Cover id is required")
val rawSize = call.request.queryParameters["size"]
val size = rawSize?.toIntOrNull()
if (rawSize != null && (size == null || size !in 1..2048)) {
badRequest("Cover size must be between 1 and 2048")
}
val folders = user.visibleFolderIds(library)
val albumId = when {
id.startsWith("sg-") -> LibraryRepository.albumIdForSong(id, folders)
LibraryRepository.album(id, folders, user.name) != null -> id
else -> null
} ?: notFound("Cover")
val cover = if (size == null) {
coverArtService.coverFile(albumId)
} else {
coverArtService.resizedCover(albumId, size)
} ?: notFound("Cover")
call.respondFile(cover.toFile())
}
}
private fun win.taptap.musicmanager.config.UserAccount.scopeFolders(
library: LibraryConfig,
scope: String,
): Set<Int> = when (scope) {
"music" -> musicFolderIds(library)
"longform" -> longformFolderIds(library)
else -> visibleFolderIds(library)
}
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"
}