feat!: replace OpenSubsonic with a native mood-first API
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:
1 parent
28bfdd9d00
commit
b33eb076c1
46 files changed
+3472
-5823
No files matched your search
@@ -12,6 +12,7 @@ import io.ktor.server.plugins.contentnegotiation.ContentNegotiation
|
||||
import io.ktor.server.plugins.partialcontent.PartialContent
|
||||
import io.ktor.server.plugins.statuspages.StatusPages
|
||||
import io.ktor.server.request.path
|
||||
import io.ktor.server.response.respond
|
||||
import io.ktor.server.response.respondRedirect
|
||||
import io.ktor.server.response.respondText
|
||||
import io.ktor.server.routing.get
|
||||
@@ -27,15 +28,16 @@ import org.slf4j.LoggerFactory
|
||||
import win.taptap.musicmanager.config.AppConfig
|
||||
import win.taptap.musicmanager.config.LibraryConfig
|
||||
import win.taptap.musicmanager.config.UsersConfig
|
||||
import win.taptap.musicmanager.api.ApiErrorBody
|
||||
import win.taptap.musicmanager.api.ApiError
|
||||
import win.taptap.musicmanager.api.ApiException
|
||||
import win.taptap.musicmanager.api.apiRoutes
|
||||
import win.taptap.musicmanager.db.ConfigRepository
|
||||
import win.taptap.musicmanager.db.DatabaseFactory
|
||||
import win.taptap.musicmanager.db.MediaRepository
|
||||
import win.taptap.musicmanager.db.MoodRepository
|
||||
import win.taptap.musicmanager.mood.MoodService
|
||||
import win.taptap.musicmanager.radio.RadioService
|
||||
import win.taptap.musicmanager.scanner.CoverArtService
|
||||
import win.taptap.musicmanager.scanner.MediaScanner
|
||||
import win.taptap.musicmanager.subsonic.respondSubsonicError
|
||||
import win.taptap.musicmanager.subsonic.routes.subsonicRoutes
|
||||
import win.taptap.musicmanager.transcoding.FfmpegTranscoder
|
||||
|
||||
private val log = LoggerFactory.getLogger("win.taptap.musicmanager.Application")
|
||||
@@ -53,11 +55,10 @@ fun main() {
|
||||
val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
val coverArtService = CoverArtService(config.dataDir)
|
||||
val transcoder = FfmpegTranscoder(config.ffmpegPath)
|
||||
val moodService = MoodService(applicationScope)
|
||||
val radioService = RadioService()
|
||||
val scanner = MediaScanner(
|
||||
library = library,
|
||||
coverArtService = coverArtService,
|
||||
onScanFinished = { MoodRepository.markAllStale() },
|
||||
)
|
||||
if (MediaRepository.countSongs() == 0L) {
|
||||
log.info("Song table is empty, starting initial library scan")
|
||||
@@ -84,10 +85,26 @@ fun main() {
|
||||
install(AutoHeadResponse)
|
||||
install(CallLogging)
|
||||
install(StatusPages) {
|
||||
exception<ApiException> { call, cause ->
|
||||
call.respond(
|
||||
cause.status,
|
||||
ApiErrorBody(
|
||||
ApiError(cause.code, cause.message),
|
||||
),
|
||||
)
|
||||
}
|
||||
exception<Throwable> { call, cause ->
|
||||
log.error("Unhandled exception for ${call.request.path()}", cause)
|
||||
if (call.request.path().startsWith("/rest/")) {
|
||||
call.respondSubsonicError(0, "Internal server error")
|
||||
if (call.request.path().startsWith("/api/")) {
|
||||
call.respond(
|
||||
HttpStatusCode.InternalServerError,
|
||||
ApiErrorBody(
|
||||
ApiError(
|
||||
"internal",
|
||||
"Internal server error",
|
||||
),
|
||||
),
|
||||
)
|
||||
} else {
|
||||
call.respondText("Internal server error", status = HttpStatusCode.InternalServerError)
|
||||
}
|
||||
@@ -100,12 +117,12 @@ fun main() {
|
||||
get("/") { call.respondRedirect("/ui") }
|
||||
get("/ui") { call.respondText(webUiHtml, ContentType.Text.Html) }
|
||||
}
|
||||
subsonicRoutes(
|
||||
apiRoutes(
|
||||
users = users,
|
||||
library = library,
|
||||
coverArtService = coverArtService,
|
||||
transcoder = transcoder,
|
||||
moodService = moodService,
|
||||
radioService = radioService,
|
||||
startScan = { scanner.start(applicationScope) },
|
||||
scanStatus = { scanner.status() },
|
||||
)
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
package win.taptap.musicmanager.api
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
import win.taptap.musicmanager.db.MoodRecord
|
||||
import win.taptap.musicmanager.db.MoodSeedRecord
|
||||
import win.taptap.musicmanager.db.SongRecord
|
||||
|
||||
@Serializable
|
||||
data class ApiErrorBody(val error: ApiError)
|
||||
|
||||
@Serializable
|
||||
data class ApiError(val code: String, val message: String)
|
||||
|
||||
@Serializable
|
||||
data class LoginRequest(
|
||||
val username: String,
|
||||
val password: String,
|
||||
val deviceName: String = "Unknown device",
|
||||
val platform: String = "unknown",
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class UserDto(
|
||||
val name: String,
|
||||
val admin: Boolean,
|
||||
val musicFolders: List<Int>,
|
||||
val longformFolders: List<Int>,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class LoginResponse(
|
||||
val token: String,
|
||||
val expiresAt: String,
|
||||
val user: UserDto,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class DeviceDto(
|
||||
val id: String,
|
||||
val deviceName: String,
|
||||
val platform: String,
|
||||
val createdAt: String,
|
||||
val lastUsedAt: String,
|
||||
val expiresAt: String,
|
||||
val current: Boolean,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class SongDto(
|
||||
val id: String,
|
||||
val title: String,
|
||||
val artist: String,
|
||||
val album: String,
|
||||
val albumId: String,
|
||||
val trackNumber: Int? = null,
|
||||
val discNumber: Int = 1,
|
||||
val year: Int? = null,
|
||||
val duration: Int,
|
||||
val bitRate: Int,
|
||||
val size: Long,
|
||||
val suffix: String,
|
||||
val genres: List<String> = emptyList(),
|
||||
val folderId: Int,
|
||||
val relativePath: String,
|
||||
val updatedAt: String,
|
||||
)
|
||||
|
||||
fun SongRecord.toDto(): SongDto = SongDto(
|
||||
id = id,
|
||||
title = title,
|
||||
artist = displayArtist,
|
||||
album = albumName,
|
||||
albumId = albumId,
|
||||
trackNumber = trackNumber,
|
||||
discNumber = discNumber,
|
||||
year = year,
|
||||
duration = duration,
|
||||
bitRate = bitRate,
|
||||
size = size,
|
||||
suffix = suffix,
|
||||
genres = genres,
|
||||
folderId = folderId,
|
||||
relativePath = relativePath,
|
||||
updatedAt = updatedAt,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class SeedDto(
|
||||
val song: SongDto,
|
||||
val origin: String,
|
||||
val addedAt: String,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class MoodDto(
|
||||
val id: String,
|
||||
val name: String,
|
||||
val description: String? = null,
|
||||
val query: String? = null,
|
||||
val genres: List<String> = emptyList(),
|
||||
val targetSize: Int,
|
||||
val refreshHours: Int,
|
||||
val ytEnabled: Boolean,
|
||||
val lastDiscoveryAt: String? = null,
|
||||
val createdAt: String,
|
||||
val changedAt: String,
|
||||
val lastError: String? = null,
|
||||
val seedCount: Int,
|
||||
val newRecommendations: Int,
|
||||
)
|
||||
|
||||
fun MoodRecord.toDto(): MoodDto = MoodDto(
|
||||
id = id,
|
||||
name = name,
|
||||
description = description,
|
||||
query = query,
|
||||
genres = genres,
|
||||
targetSize = targetSize,
|
||||
refreshHours = refreshHours,
|
||||
ytEnabled = ytEnabled,
|
||||
lastDiscoveryAt = lastDiscoveryAt,
|
||||
createdAt = createdAt,
|
||||
changedAt = changedAt,
|
||||
lastError = lastError,
|
||||
seedCount = seedCount,
|
||||
newRecommendations = newRecommendations,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class MoodDetailDto(
|
||||
val mood: MoodDto,
|
||||
val seeds: List<SeedDto>,
|
||||
val recommendations: List<RecommendationDto> = emptyList(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class CreateMoodRequest(
|
||||
val name: String,
|
||||
val description: String? = null,
|
||||
val query: String? = null,
|
||||
val genres: List<String> = emptyList(),
|
||||
val targetSize: Int = 30,
|
||||
val refreshHours: Int = 24,
|
||||
val ytEnabled: Boolean = true,
|
||||
val seedSongIds: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class UpdateMoodRequest(
|
||||
val name: String? = null,
|
||||
val description: String? = null,
|
||||
val clearDescription: Boolean = false,
|
||||
val query: String? = null,
|
||||
val clearQuery: Boolean = false,
|
||||
val genres: List<String>? = null,
|
||||
val targetSize: Int? = null,
|
||||
val refreshHours: Int? = null,
|
||||
val ytEnabled: Boolean? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class AddSeedRequest(val songId: String, val origin: String = "manual")
|
||||
|
||||
@Serializable
|
||||
data class AddToMoodRequest(val songId: String, val moodId: String? = null)
|
||||
|
||||
@Serializable
|
||||
data class AddToMoodResponse(
|
||||
val mood: MoodDto,
|
||||
val added: Boolean,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class LibraryPage(
|
||||
val songs: List<SongDto>,
|
||||
val deletedSongIds: List<String> = emptyList(),
|
||||
val revision: String,
|
||||
val nextCursor: String? = null,
|
||||
val nextSince: String? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class SearchResponse(val songs: List<SongDto>)
|
||||
|
||||
@Serializable
|
||||
data class StartSessionRequest(val limit: Int? = null)
|
||||
|
||||
@Serializable
|
||||
data class NextTracksRequest(
|
||||
val limit: Int? = null,
|
||||
val excludeSongIds: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class SessionDto(
|
||||
val id: String,
|
||||
val moodId: String,
|
||||
val moodName: String,
|
||||
val startedAt: String,
|
||||
val closedAt: String? = null,
|
||||
val queue: List<SongDto> = emptyList(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class PlaybackEvent(
|
||||
val songId: String,
|
||||
val type: String,
|
||||
val positionSeconds: Int? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class PlaybackEventsRequest(val events: List<PlaybackEvent>)
|
||||
|
||||
@Serializable
|
||||
data class PlaybackEventsResponse(val accepted: Int)
|
||||
|
||||
@Serializable
|
||||
data class ScanStatusDto(
|
||||
val scanning: Boolean,
|
||||
val count: Long,
|
||||
val error: String? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class RecommendationDto(
|
||||
val videoId: String,
|
||||
val title: String,
|
||||
val artist: String,
|
||||
val album: String? = null,
|
||||
val duration: Int? = null,
|
||||
val thumbnail: String? = null,
|
||||
val state: String,
|
||||
val matchedSong: SongDto? = null,
|
||||
val timesAdded: Int,
|
||||
val firstSeen: String,
|
||||
val lastSeen: String,
|
||||
)
|
||||
|
||||
fun seedDto(seed: MoodSeedRecord, song: SongRecord): SeedDto =
|
||||
SeedDto(song = song.toDto(), origin = seed.origin, addedAt = seed.addedAt)
|
||||
@@ -0,0 +1,137 @@
|
||||
package win.taptap.musicmanager.api
|
||||
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import io.ktor.server.response.respond
|
||||
import io.ktor.server.routing.Route
|
||||
import io.ktor.server.routing.delete
|
||||
import io.ktor.server.routing.get
|
||||
import io.ktor.server.routing.post
|
||||
import io.ktor.server.routing.route
|
||||
import java.security.MessageDigest
|
||||
import win.taptap.musicmanager.api.DeviceDto
|
||||
import win.taptap.musicmanager.api.LoginRequest
|
||||
import win.taptap.musicmanager.api.LoginResponse
|
||||
import win.taptap.musicmanager.api.ScanStatusDto
|
||||
import win.taptap.musicmanager.api.UserDto
|
||||
import win.taptap.musicmanager.config.LibraryConfig
|
||||
import win.taptap.musicmanager.config.UsersConfig
|
||||
import win.taptap.musicmanager.db.ApiTokenRepository
|
||||
import win.taptap.musicmanager.radio.RadioService
|
||||
import win.taptap.musicmanager.scanner.CoverArtService
|
||||
import win.taptap.musicmanager.scanner.ScanStatus
|
||||
import win.taptap.musicmanager.transcoding.FfmpegTranscoder
|
||||
|
||||
/**
|
||||
* Routing for the native API.
|
||||
*
|
||||
* Every handler resolves the bearer token explicitly. Media URLs may also carry
|
||||
* `?token=` because HTML audio and `<img>` tags cannot set headers.
|
||||
*/
|
||||
fun Route.apiRoutes(
|
||||
users: UsersConfig,
|
||||
library: LibraryConfig,
|
||||
coverArtService: CoverArtService,
|
||||
transcoder: FfmpegTranscoder,
|
||||
radioService: RadioService,
|
||||
startScan: () -> Boolean,
|
||||
scanStatus: () -> ScanStatus,
|
||||
) {
|
||||
route("/api/v1") {
|
||||
post("/auth/login") {
|
||||
val request = call.receiveJson<LoginRequest>()
|
||||
val user = users.byName(request.username.trim())
|
||||
?: throw ApiException(
|
||||
HttpStatusCode.Unauthorized,
|
||||
"invalid_credentials",
|
||||
"Wrong username or password",
|
||||
)
|
||||
if (!constantTimeEquals(request.password, user.password)) {
|
||||
throw ApiException(
|
||||
HttpStatusCode.Unauthorized,
|
||||
"invalid_credentials",
|
||||
"Wrong username or password",
|
||||
)
|
||||
}
|
||||
|
||||
val issued = ApiTokenRepository.create(
|
||||
userName = user.name,
|
||||
deviceName = request.deviceName.ifBlank { "Unknown device" },
|
||||
platform = request.platform.ifBlank { "unknown" },
|
||||
)
|
||||
call.respond(
|
||||
HttpStatusCode.OK,
|
||||
LoginResponse(
|
||||
token = issued.raw,
|
||||
expiresAt = issued.record.expiresAt,
|
||||
user = user.toDto(library),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
get("/me") {
|
||||
val user = call.requireApiUser(users)
|
||||
call.respond(UserDto(
|
||||
name = user.name,
|
||||
admin = user.admin,
|
||||
musicFolders = user.musicFolderIds(library).sorted(),
|
||||
longformFolders = user.longformFolderIds(library).sorted(),
|
||||
))
|
||||
}
|
||||
|
||||
post("/auth/logout") {
|
||||
val user = call.requireApiUser(users)
|
||||
ApiTokenRepository.revokeRaw(call.bearerToken().orEmpty())
|
||||
call.respond(HttpStatusCode.NoContent)
|
||||
}
|
||||
|
||||
get("/auth/devices") {
|
||||
val user = call.requireApiUser(users)
|
||||
val current = call.apiToken()
|
||||
val devices = ApiTokenRepository.list(user.name).map { record ->
|
||||
DeviceDto(
|
||||
id = record.id,
|
||||
deviceName = record.deviceName,
|
||||
platform = record.platform,
|
||||
createdAt = record.createdAt,
|
||||
lastUsedAt = record.lastUsedAt,
|
||||
expiresAt = record.expiresAt,
|
||||
current = record.id == current?.id,
|
||||
)
|
||||
}
|
||||
call.respond(devices)
|
||||
}
|
||||
|
||||
delete("/auth/devices/{id}") {
|
||||
val user = call.requireApiUser(users)
|
||||
val id = call.parameters["id"] ?: badRequest("Device id is required")
|
||||
if (!ApiTokenRepository.revoke(id, user.name)) notFound("Device")
|
||||
call.respond(HttpStatusCode.NoContent)
|
||||
}
|
||||
|
||||
get("/scan") {
|
||||
call.requireApiUser(users)
|
||||
val status = scanStatus()
|
||||
call.respond(ScanStatusDto(status.scanning, status.count, status.error))
|
||||
}
|
||||
|
||||
post("/scan") {
|
||||
val user = call.requireApiUser(users)
|
||||
if (!user.admin) forbidden("Only admins can start a scan")
|
||||
val started = startScan()
|
||||
call.respond(
|
||||
HttpStatusCode.Accepted,
|
||||
ScanStatusDto(scanning = started, count = scanStatus().count),
|
||||
)
|
||||
}
|
||||
|
||||
libraryRoutes(users, library, coverArtService, transcoder)
|
||||
moodRoutes(users, library, radioService)
|
||||
sessionRoutes(users, library, radioService)
|
||||
}
|
||||
}
|
||||
|
||||
private fun constantTimeEquals(candidate: String, expected: String): Boolean =
|
||||
MessageDigest.isEqual(
|
||||
candidate.toByteArray(Charsets.UTF_8),
|
||||
expected.toByteArray(Charsets.UTF_8),
|
||||
)
|
||||
@@ -0,0 +1,111 @@
|
||||
package win.taptap.musicmanager.api
|
||||
|
||||
import io.ktor.http.HttpHeaders
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import io.ktor.server.application.ApplicationCall
|
||||
import io.ktor.server.request.receive
|
||||
import io.ktor.server.response.respond
|
||||
import io.ktor.util.AttributeKey
|
||||
import kotlinx.serialization.SerializationException
|
||||
import win.taptap.musicmanager.api.ApiError
|
||||
import win.taptap.musicmanager.api.ApiErrorBody
|
||||
import win.taptap.musicmanager.api.UserDto
|
||||
import win.taptap.musicmanager.config.FolderType
|
||||
import win.taptap.musicmanager.config.LibraryConfig
|
||||
import win.taptap.musicmanager.config.UserAccount
|
||||
import win.taptap.musicmanager.config.UsersConfig
|
||||
import win.taptap.musicmanager.db.ApiTokenRecord
|
||||
import win.taptap.musicmanager.db.ApiTokenRepository
|
||||
|
||||
/** HTTP-shaped error rendered by the global StatusPages handler. */
|
||||
class ApiException(
|
||||
val status: HttpStatusCode,
|
||||
val code: String,
|
||||
override val message: String,
|
||||
) : RuntimeException(message)
|
||||
|
||||
val ApiUserKey = AttributeKey<UserAccount>("musicmanager.api.user")
|
||||
val ApiTokenKey = AttributeKey<ApiTokenRecord>("musicmanager.api.token")
|
||||
|
||||
fun UserAccount.musicFolderIds(library: LibraryConfig): Set<Int> =
|
||||
library.folders
|
||||
.asSequence()
|
||||
.filter { it.type == FolderType.MUSIC && it.id in folders }
|
||||
.map { it.id }
|
||||
.toSet()
|
||||
|
||||
fun UserAccount.longformFolderIds(library: LibraryConfig): Set<Int> =
|
||||
library.folders
|
||||
.asSequence()
|
||||
.filter { it.type == FolderType.LONGFORM }
|
||||
.map { it.id }
|
||||
.toSet()
|
||||
|
||||
fun UserAccount.toDto(library: LibraryConfig): UserDto = UserDto(
|
||||
name = name,
|
||||
admin = admin,
|
||||
musicFolders = musicFolderIds(library).sorted(),
|
||||
longformFolders = longformFolderIds(library).sorted(),
|
||||
)
|
||||
|
||||
fun ApplicationCall.apiUser(): UserAccount =
|
||||
attributes.getOrNull(ApiUserKey) ?: throw ApiException(
|
||||
HttpStatusCode.Unauthorized,
|
||||
"unauthorized",
|
||||
"Authentication required",
|
||||
)
|
||||
|
||||
fun ApplicationCall.apiToken(): ApiTokenRecord? = attributes.getOrNull(ApiTokenKey)
|
||||
|
||||
fun apiErrorBody(code: String, message: String): ApiErrorBody =
|
||||
ApiErrorBody(ApiError(code, message))
|
||||
|
||||
/** Bearer header is the norm; `token` exists for browser audio and image URLs. */
|
||||
fun ApplicationCall.bearerToken(): String? {
|
||||
val header = request.headers[HttpHeaders.Authorization]
|
||||
if (!header.isNullOrBlank()) {
|
||||
val value = header.trim()
|
||||
if (value.startsWith("Bearer ", ignoreCase = true)) {
|
||||
return value.substringAfter(' ').trim().takeIf { it.isNotEmpty() }
|
||||
}
|
||||
return value.takeIf { it.isNotEmpty() }
|
||||
}
|
||||
return request.queryParameters["token"]?.takeIf { it.isNotBlank() }
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the token and stores the user on the call. Returns null after sending
|
||||
* a 401, so handlers can simply `?: return@get`.
|
||||
*/
|
||||
suspend fun ApplicationCall.requireApiUser(users: UsersConfig): UserAccount {
|
||||
val raw = bearerToken()
|
||||
val token = raw?.let { ApiTokenRepository.resolve(it) }
|
||||
val user = token?.let { users.byName(it.userName) }
|
||||
if (token == null || user == null) {
|
||||
throw ApiException(HttpStatusCode.Unauthorized, "unauthorized", "Missing or invalid token")
|
||||
}
|
||||
attributes.put(ApiUserKey, user)
|
||||
attributes.put(ApiTokenKey, token)
|
||||
return user
|
||||
}
|
||||
|
||||
suspend inline fun <reified T : Any> ApplicationCall.receiveJson(): T =
|
||||
try {
|
||||
receive<T>()
|
||||
} catch (e: SerializationException) {
|
||||
throw ApiException(HttpStatusCode.BadRequest, "invalid_body", "Invalid JSON body")
|
||||
} catch (e: IllegalArgumentException) {
|
||||
throw ApiException(HttpStatusCode.BadRequest, "invalid_body", e.message ?: "Invalid body")
|
||||
}
|
||||
|
||||
fun notFound(what: String): Nothing =
|
||||
throw ApiException(HttpStatusCode.NotFound, "not_found", "$what not found")
|
||||
|
||||
fun badRequest(message: String): Nothing =
|
||||
throw ApiException(HttpStatusCode.BadRequest, "bad_request", message)
|
||||
|
||||
fun forbidden(message: String): Nothing =
|
||||
throw ApiException(HttpStatusCode.Forbidden, "forbidden", message)
|
||||
|
||||
fun conflict(message: String): Nothing =
|
||||
throw ApiException(HttpStatusCode.Conflict, "conflict", message)
|
||||
@@ -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"
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
package win.taptap.musicmanager.api
|
||||
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import io.ktor.server.response.respond
|
||||
import io.ktor.server.routing.Route
|
||||
import io.ktor.server.routing.delete
|
||||
import io.ktor.server.routing.get
|
||||
import io.ktor.server.routing.patch
|
||||
import io.ktor.server.routing.post
|
||||
import kotlinx.serialization.Serializable
|
||||
import win.taptap.musicmanager.api.AddSeedRequest
|
||||
import win.taptap.musicmanager.api.AddToMoodResponse
|
||||
import win.taptap.musicmanager.api.CreateMoodRequest
|
||||
import win.taptap.musicmanager.api.MoodDetailDto
|
||||
import win.taptap.musicmanager.api.MoodDto
|
||||
import win.taptap.musicmanager.api.RecommendationDto
|
||||
import win.taptap.musicmanager.api.SearchResponse
|
||||
import win.taptap.musicmanager.api.UpdateMoodRequest
|
||||
import win.taptap.musicmanager.api.seedDto
|
||||
import win.taptap.musicmanager.api.toDto
|
||||
import win.taptap.musicmanager.config.LibraryConfig
|
||||
import win.taptap.musicmanager.config.UserAccount
|
||||
import win.taptap.musicmanager.config.UsersConfig
|
||||
import win.taptap.musicmanager.db.LibraryRepository
|
||||
import win.taptap.musicmanager.db.MoodRecord
|
||||
import win.taptap.musicmanager.db.MoodRepository
|
||||
import win.taptap.musicmanager.radio.RadioService
|
||||
|
||||
@Serializable
|
||||
data class MoodsResponse(val moods: List<MoodDto>)
|
||||
|
||||
fun Route.moodRoutes(
|
||||
users: UsersConfig,
|
||||
library: LibraryConfig,
|
||||
radioService: RadioService,
|
||||
) {
|
||||
get("/moods") {
|
||||
val user = call.requireApiUser(users)
|
||||
call.respond(MoodsResponse(MoodRepository.list(user.name).map { it.toDto() }))
|
||||
}
|
||||
|
||||
post("/moods") {
|
||||
val user = call.requireApiUser(users)
|
||||
val request = call.receiveJson<CreateMoodRequest>()
|
||||
val name = request.name.trim()
|
||||
if (name.isEmpty()) badRequest("Mood name is required")
|
||||
|
||||
val folders = user.musicFolderIds(library)
|
||||
val seedIds = request.seedSongIds
|
||||
.distinct()
|
||||
.filter { LibraryRepository.song(it, folders, user.name) != null }
|
||||
|
||||
val mood = MoodRepository.create(
|
||||
owner = user.name,
|
||||
name = name,
|
||||
description = request.description?.trim()?.takeIf { it.isNotEmpty() },
|
||||
query = request.query?.trim()?.takeIf { it.isNotEmpty() },
|
||||
genres = request.genres,
|
||||
targetSize = request.targetSize,
|
||||
refreshHours = request.refreshHours,
|
||||
ytEnabled = request.ytEnabled,
|
||||
seedSongIds = seedIds,
|
||||
)
|
||||
call.respond(HttpStatusCode.Created, detail(mood, user, library))
|
||||
}
|
||||
|
||||
get("/moods/{id}") {
|
||||
val user = call.requireApiUser(users)
|
||||
val mood = ownedMood(call.parameters["id"], user)
|
||||
call.respond(detail(mood, user, library))
|
||||
}
|
||||
|
||||
patch("/moods/{id}") {
|
||||
val user = call.requireApiUser(users)
|
||||
val mood = ownedMood(call.parameters["id"], user)
|
||||
val request = call.receiveJson<UpdateMoodRequest>()
|
||||
|
||||
val description = when {
|
||||
request.clearDescription -> null
|
||||
request.description != null -> request.description.trim().takeIf { it.isNotEmpty() }
|
||||
else -> mood.description
|
||||
}
|
||||
val query = when {
|
||||
request.clearQuery -> null
|
||||
request.query != null -> request.query.trim().takeIf { it.isNotEmpty() }
|
||||
else -> mood.query
|
||||
}
|
||||
|
||||
val updated = MoodRepository.update(
|
||||
id = mood.id,
|
||||
owner = user.name,
|
||||
name = request.name?.trim()?.takeIf { it.isNotEmpty() } ?: mood.name,
|
||||
description = description,
|
||||
query = query,
|
||||
genres = request.genres ?: mood.genres,
|
||||
targetSize = request.targetSize ?: mood.targetSize,
|
||||
refreshHours = request.refreshHours ?: mood.refreshHours,
|
||||
ytEnabled = request.ytEnabled ?: mood.ytEnabled,
|
||||
) ?: notFound("Mood")
|
||||
|
||||
call.respond(detail(updated, user, library))
|
||||
}
|
||||
|
||||
delete("/moods/{id}") {
|
||||
val user = call.requireApiUser(users)
|
||||
val mood = ownedMood(call.parameters["id"], user)
|
||||
MoodRepository.delete(mood.id, user.name)
|
||||
call.respond(HttpStatusCode.NoContent)
|
||||
}
|
||||
|
||||
post("/moods/{id}/seeds") {
|
||||
val user = call.requireApiUser(users)
|
||||
val mood = ownedMood(call.parameters["id"], user)
|
||||
val request = call.receiveJson<AddSeedRequest>()
|
||||
val song = requireMusicSong(request.songId, user, library)
|
||||
val added = MoodRepository.addSeed(
|
||||
id = mood.id,
|
||||
owner = user.name,
|
||||
songId = song.id,
|
||||
origin = request.origin,
|
||||
)
|
||||
val refreshed = MoodRepository.get(mood.id, user.name) ?: mood
|
||||
call.respond(
|
||||
HttpStatusCode.OK,
|
||||
AddToMoodResponse(mood = refreshed.toDto(), added = added),
|
||||
)
|
||||
}
|
||||
|
||||
delete("/moods/{id}/seeds/{songId}") {
|
||||
val user = call.requireApiUser(users)
|
||||
val mood = ownedMood(call.parameters["id"], user)
|
||||
val songId = call.parameters["songId"] ?: badRequest("Song id is required")
|
||||
MoodRepository.removeSeed(mood.id, user.name, songId)
|
||||
call.respond(HttpStatusCode.NoContent)
|
||||
}
|
||||
|
||||
/** A short, unpersisted radio preview for the mood detail screen. */
|
||||
get("/moods/{id}/preview") {
|
||||
val user = call.requireApiUser(users)
|
||||
val mood = ownedMood(call.parameters["id"], user)
|
||||
val limit = (call.request.queryParameters["limit"]?.toIntOrNull() ?: 20).coerceIn(1, 50)
|
||||
call.respond(SearchResponse(radioService.preview(mood, user, library, limit).map { it.toDto() }))
|
||||
}
|
||||
|
||||
get("/moods/{id}/recommendations") {
|
||||
val user = call.requireApiUser(users)
|
||||
val mood = ownedMood(call.parameters["id"], user)
|
||||
call.respond(recommendations(mood, user, library))
|
||||
}
|
||||
}
|
||||
|
||||
private fun ownedMood(id: String?, user: UserAccount): MoodRecord {
|
||||
if (id.isNullOrBlank()) badRequest("Mood id is required")
|
||||
return MoodRepository.get(id, user.name) ?: notFound("Mood")
|
||||
}
|
||||
|
||||
private fun requireMusicSong(songId: String, user: UserAccount, library: LibraryConfig) =
|
||||
LibraryRepository.song(songId, user.musicFolderIds(library), user.name)
|
||||
?: notFound("Song")
|
||||
|
||||
private fun detail(mood: MoodRecord, user: UserAccount, library: LibraryConfig): MoodDetailDto {
|
||||
val folders = user.musicFolderIds(library)
|
||||
val seedRecords = MoodRepository.seeds(mood.id)
|
||||
val seedSongs = LibraryRepository
|
||||
.songsByIds(seedRecords.map { it.songId }, folders, user.name)
|
||||
.associateBy { it.id }
|
||||
val seeds = seedRecords.mapNotNull { seed ->
|
||||
seedSongs[seed.songId]?.let { seedDto(seed, it) }
|
||||
}
|
||||
|
||||
return MoodDetailDto(
|
||||
mood = mood.toDto(),
|
||||
seeds = seeds,
|
||||
recommendations = recommendations(mood, user, library).recommendations,
|
||||
)
|
||||
}
|
||||
|
||||
private fun recommendations(
|
||||
mood: MoodRecord,
|
||||
user: UserAccount,
|
||||
library: LibraryConfig,
|
||||
): RecommendationsResponse {
|
||||
val records = MoodRepository.recommendations(mood.id)
|
||||
val matchedIds = records.mapNotNull { it.matchedSongId }
|
||||
val matchedSongs = LibraryRepository
|
||||
.songsByIds(matchedIds, user.visibleFolderIds(library), user.name)
|
||||
.associateBy { it.id }
|
||||
|
||||
return RecommendationsResponse(
|
||||
recommendations = records.map { record ->
|
||||
RecommendationDto(
|
||||
videoId = record.videoId,
|
||||
title = record.title,
|
||||
artist = record.artist,
|
||||
album = record.album,
|
||||
duration = record.duration,
|
||||
thumbnail = record.thumbnail,
|
||||
state = record.state,
|
||||
matchedSong = record.matchedSongId?.let { matchedSongs[it] }?.toDto(),
|
||||
timesAdded = record.timesAdded,
|
||||
firstSeen = record.firstSeen,
|
||||
lastSeen = record.lastSeen,
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class RecommendationsResponse(val recommendations: List<RecommendationDto>)
|
||||
@@ -0,0 +1,154 @@
|
||||
package win.taptap.musicmanager.api
|
||||
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import io.ktor.server.response.respond
|
||||
import io.ktor.server.routing.Route
|
||||
import io.ktor.server.routing.delete
|
||||
import io.ktor.server.routing.get
|
||||
import io.ktor.server.routing.post
|
||||
import kotlinx.serialization.Serializable
|
||||
import win.taptap.musicmanager.api.AddToMoodRequest
|
||||
import win.taptap.musicmanager.api.AddToMoodResponse
|
||||
import win.taptap.musicmanager.api.NextTracksRequest
|
||||
import win.taptap.musicmanager.api.PlaybackEventsRequest
|
||||
import win.taptap.musicmanager.api.PlaybackEventsResponse
|
||||
import win.taptap.musicmanager.api.SessionDto
|
||||
import win.taptap.musicmanager.api.SongDto
|
||||
import win.taptap.musicmanager.api.StartSessionRequest
|
||||
import win.taptap.musicmanager.api.toDto
|
||||
import win.taptap.musicmanager.config.LibraryConfig
|
||||
import win.taptap.musicmanager.config.UserAccount
|
||||
import win.taptap.musicmanager.config.UsersConfig
|
||||
import win.taptap.musicmanager.db.LibraryRepository
|
||||
import win.taptap.musicmanager.db.MoodRecord
|
||||
import win.taptap.musicmanager.db.MoodRepository
|
||||
import win.taptap.musicmanager.db.PlaybackSessionRecord
|
||||
import win.taptap.musicmanager.db.RadioRepository
|
||||
import win.taptap.musicmanager.radio.RadioService
|
||||
|
||||
@Serializable
|
||||
data class TracksResponse(val songs: List<SongDto>)
|
||||
|
||||
fun Route.sessionRoutes(
|
||||
users: UsersConfig,
|
||||
library: LibraryConfig,
|
||||
radioService: RadioService,
|
||||
) {
|
||||
post("/moods/{id}/sessions") {
|
||||
val user = call.requireApiUser(users)
|
||||
val mood = ownedMoodFor(call.parameters["id"], user)
|
||||
val request = runCatching { call.receiveJson<StartSessionRequest>() }
|
||||
.getOrDefault(StartSessionRequest())
|
||||
val limit = request.limit ?: DEFAULT_BATCH
|
||||
|
||||
val started = radioService.start(mood, user, library, limit)
|
||||
call.respond(
|
||||
HttpStatusCode.Created,
|
||||
SessionDto(
|
||||
id = started.session.id,
|
||||
moodId = mood.id,
|
||||
moodName = mood.name,
|
||||
startedAt = started.session.createdAt,
|
||||
queue = started.songs.map { it.toDto() },
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
get("/sessions/{id}") {
|
||||
val user = call.requireApiUser(users)
|
||||
val session = ownedSession(call.parameters["id"], user)
|
||||
val mood = ownedMoodFor(session.moodId, user)
|
||||
val folders = user.musicFolderIds(library)
|
||||
val items = RadioRepository.items(session.id)
|
||||
val songs = LibraryRepository
|
||||
.songsByIds(items.map { it.songId }, folders, user.name)
|
||||
.associateBy { it.id }
|
||||
|
||||
call.respond(
|
||||
SessionDto(
|
||||
id = session.id,
|
||||
moodId = session.moodId,
|
||||
moodName = mood.name,
|
||||
startedAt = session.createdAt,
|
||||
closedAt = session.closedAt,
|
||||
queue = items.mapNotNull { songs[it.songId]?.toDto() },
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
post("/sessions/{id}/next") {
|
||||
val user = call.requireApiUser(users)
|
||||
val session = ownedSession(call.parameters["id"], user)
|
||||
if (session.closedAt != null) conflict("Session is closed")
|
||||
val mood = ownedMoodFor(session.moodId, user)
|
||||
val request = runCatching { call.receiveJson<NextTracksRequest>() }
|
||||
.getOrDefault(NextTracksRequest())
|
||||
|
||||
val songs = radioService.next(
|
||||
mood = mood,
|
||||
user = user,
|
||||
library = library,
|
||||
sessionId = session.id,
|
||||
excluded = request.excludeSongIds.toSet(),
|
||||
limit = request.limit ?: DEFAULT_BATCH,
|
||||
)
|
||||
call.respond(TracksResponse(songs.map { it.toDto() }))
|
||||
}
|
||||
|
||||
post("/sessions/{id}/events") {
|
||||
val user = call.requireApiUser(users)
|
||||
val session = ownedSession(call.parameters["id"], user)
|
||||
val request = call.receiveJson<PlaybackEventsRequest>()
|
||||
val accepted = request.events.count { event ->
|
||||
event.type in EVENT_TYPES &&
|
||||
event.songId.isNotBlank() &&
|
||||
RadioRepository.recordEvent(session.id, user.name, event.songId, event.type)
|
||||
}
|
||||
call.respond(PlaybackEventsResponse(accepted))
|
||||
}
|
||||
|
||||
/** Explicitly adds the playing track to the session mood or another chosen mood. */
|
||||
post("/sessions/{id}/add-to-mood") {
|
||||
val user = call.requireApiUser(users)
|
||||
val session = ownedSession(call.parameters["id"], user)
|
||||
val request = call.receiveJson<AddToMoodRequest>()
|
||||
val folders = user.musicFolderIds(library)
|
||||
val song = LibraryRepository.song(request.songId, folders, user.name)
|
||||
?: notFound("Song")
|
||||
|
||||
val target = if (request.moodId.isNullOrBlank()) {
|
||||
ownedMoodFor(session.moodId, user)
|
||||
} else {
|
||||
ownedMoodFor(request.moodId, user)
|
||||
}
|
||||
|
||||
val added = MoodRepository.addSeed(target.id, user.name, song.id, "manual")
|
||||
val refreshed = MoodRepository.get(target.id, user.name) ?: target
|
||||
call.respond(
|
||||
AddToMoodResponse(
|
||||
mood = refreshed.toDto(),
|
||||
added = added,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
delete("/sessions/{id}") {
|
||||
val user = call.requireApiUser(users)
|
||||
val session = ownedSession(call.parameters["id"], user)
|
||||
RadioRepository.close(session.id, user.name)
|
||||
call.respond(HttpStatusCode.NoContent)
|
||||
}
|
||||
}
|
||||
|
||||
private fun ownedMoodFor(id: String?, user: UserAccount): MoodRecord {
|
||||
if (id.isNullOrBlank()) badRequest("Mood id is required")
|
||||
return MoodRepository.get(id, user.name) ?: notFound("Mood")
|
||||
}
|
||||
|
||||
private fun ownedSession(id: String?, user: UserAccount): PlaybackSessionRecord {
|
||||
if (id.isNullOrBlank()) badRequest("Session id is required")
|
||||
return RadioRepository.get(id, user.name) ?: notFound("Session")
|
||||
}
|
||||
|
||||
private const val DEFAULT_BATCH = 15
|
||||
private val EVENT_TYPES = setOf("started", "completed", "skipped")
|
||||
@@ -0,0 +1,153 @@
|
||||
package win.taptap.musicmanager.db
|
||||
|
||||
import java.security.MessageDigest
|
||||
import java.security.SecureRandom
|
||||
import java.time.Duration
|
||||
import java.time.Instant
|
||||
import java.util.Base64
|
||||
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
|
||||
import org.jetbrains.exposed.sql.SqlExpressionBuilder.greater
|
||||
import org.jetbrains.exposed.sql.SqlExpressionBuilder.neq
|
||||
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 IssuedToken(val raw: String, val record: ApiTokenRecord)
|
||||
|
||||
data class ApiTokenRecord(
|
||||
val id: String,
|
||||
val userName: String,
|
||||
val deviceName: String,
|
||||
val platform: String,
|
||||
val createdAt: String,
|
||||
val lastUsedAt: String,
|
||||
val expiresAt: String,
|
||||
)
|
||||
|
||||
/**
|
||||
* Device sessions for the native API. Raw tokens never touch the database: only
|
||||
* their SHA-256 hash is stored, so a database leak cannot be replayed.
|
||||
*/
|
||||
object ApiTokenRepository {
|
||||
|
||||
private val random = SecureRandom()
|
||||
private const val TOKEN_BYTES = 32
|
||||
private val TOUCH_INTERVAL: Duration = Duration.ofMinutes(1)
|
||||
|
||||
fun create(
|
||||
userName: String,
|
||||
deviceName: String,
|
||||
platform: String,
|
||||
ttl: Duration = Duration.ofDays(180),
|
||||
): IssuedToken {
|
||||
val raw = randomToken()
|
||||
val now = Instant.now()
|
||||
val record = ApiTokenRecord(
|
||||
id = "tk-" + hash("$userName|$raw").take(24),
|
||||
userName = userName,
|
||||
deviceName = deviceName.take(120),
|
||||
platform = platform.take(32),
|
||||
createdAt = now.toString(),
|
||||
lastUsedAt = now.toString(),
|
||||
expiresAt = now.plus(ttl).toString(),
|
||||
)
|
||||
|
||||
transaction {
|
||||
ApiTokensTable.insert {
|
||||
it[id] = record.id
|
||||
it[this.userName] = record.userName
|
||||
it[tokenHash] = hash(raw)
|
||||
it[this.deviceName] = record.deviceName
|
||||
it[this.platform] = record.platform
|
||||
it[createdAt] = record.createdAt
|
||||
it[lastUsedAt] = record.lastUsedAt
|
||||
it[expiresAt] = record.expiresAt
|
||||
}
|
||||
}
|
||||
|
||||
return IssuedToken(raw, record)
|
||||
}
|
||||
|
||||
/** Validates a raw token and refreshes `last_used_at` at most once a minute. */
|
||||
fun resolve(raw: String): ApiTokenRecord? = transaction {
|
||||
val hashed = hash(raw)
|
||||
val row = ApiTokensTable.selectAll()
|
||||
.where { ApiTokensTable.tokenHash eq hashed }
|
||||
.singleOrNull() ?: return@transaction null
|
||||
|
||||
val expiresAt = row[ApiTokensTable.expiresAt]
|
||||
if (Instant.parse(expiresAt).isBefore(Instant.now())) {
|
||||
ApiTokensTable.deleteWhere { ApiTokensTable.id eq row[ApiTokensTable.id] }
|
||||
return@transaction null
|
||||
}
|
||||
|
||||
val lastUsed = Instant.parse(row[ApiTokensTable.lastUsedAt])
|
||||
val now = Instant.now()
|
||||
if (lastUsed.plus(TOUCH_INTERVAL).isBefore(now)) {
|
||||
ApiTokensTable.update({ ApiTokensTable.id eq row[ApiTokensTable.id] }) {
|
||||
it[lastUsedAt] = now.toString()
|
||||
}
|
||||
}
|
||||
|
||||
ApiTokenRecord(
|
||||
id = row[ApiTokensTable.id],
|
||||
userName = row[ApiTokensTable.userName],
|
||||
deviceName = row[ApiTokensTable.deviceName],
|
||||
platform = row[ApiTokensTable.platform],
|
||||
createdAt = row[ApiTokensTable.createdAt],
|
||||
lastUsedAt = now.toString(),
|
||||
expiresAt = expiresAt,
|
||||
)
|
||||
}
|
||||
|
||||
fun list(userName: String): List<ApiTokenRecord> = transaction {
|
||||
ApiTokensTable.selectAll()
|
||||
.where { (ApiTokensTable.userName eq userName) and (ApiTokensTable.expiresAt greater Instant.now().toString()) }
|
||||
.orderBy(ApiTokensTable.lastUsedAt to org.jetbrains.exposed.sql.SortOrder.DESC)
|
||||
.map {
|
||||
ApiTokenRecord(
|
||||
id = it[ApiTokensTable.id],
|
||||
userName = it[ApiTokensTable.userName],
|
||||
deviceName = it[ApiTokensTable.deviceName],
|
||||
platform = it[ApiTokensTable.platform],
|
||||
createdAt = it[ApiTokensTable.createdAt],
|
||||
lastUsedAt = it[ApiTokensTable.lastUsedAt],
|
||||
expiresAt = it[ApiTokensTable.expiresAt],
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun revoke(id: String, userName: String): Boolean = transaction {
|
||||
ApiTokensTable.deleteWhere {
|
||||
(ApiTokensTable.id eq id) and (ApiTokensTable.userName eq userName)
|
||||
} > 0
|
||||
}
|
||||
|
||||
fun revokeRaw(raw: String): Boolean = transaction {
|
||||
ApiTokensTable.deleteWhere { ApiTokensTable.tokenHash eq hash(raw) } > 0
|
||||
}
|
||||
|
||||
fun revokeAll(userName: String, exceptId: String? = null): Int = transaction {
|
||||
if (exceptId == null) {
|
||||
ApiTokensTable.deleteWhere { ApiTokensTable.userName eq userName }
|
||||
} else {
|
||||
ApiTokensTable.deleteWhere {
|
||||
(ApiTokensTable.userName eq userName) and (ApiTokensTable.id neq exceptId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun hash(value: String): String =
|
||||
MessageDigest.getInstance("SHA-256")
|
||||
.digest(value.toByteArray(Charsets.UTF_8))
|
||||
.joinToString("") { "%02x".format(it) }
|
||||
|
||||
private fun randomToken(): String {
|
||||
val bytes = ByteArray(TOKEN_BYTES)
|
||||
random.nextBytes(bytes)
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import win.taptap.musicmanager.config.UsersConfig
|
||||
* Reconciles the config/Vault-managed identity tables with SQLite.
|
||||
*
|
||||
* Removing a folder cascades to its songs; removing a user cascades to that
|
||||
* user's stars, ratings, play counts, bookmarks and playlists.
|
||||
* user's play history and mood ownership.
|
||||
*/
|
||||
object ConfigRepository {
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ 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.SqlExpressionBuilder.greater
|
||||
import org.jetbrains.exposed.sql.ResultRow
|
||||
import org.jetbrains.exposed.sql.SortOrder
|
||||
import org.jetbrains.exposed.sql.Transaction
|
||||
@@ -81,6 +82,7 @@ data class SongRecord(
|
||||
val folderId: Int,
|
||||
val relativePath: String,
|
||||
val created: String,
|
||||
val updatedAt: String,
|
||||
val starredAt: String?,
|
||||
val rating: Int?,
|
||||
val playCount: Int,
|
||||
@@ -91,6 +93,8 @@ data class SongRecord(
|
||||
|
||||
data class ResolvedSong(val song: SongRecord, val file: Path)
|
||||
|
||||
data class TombstoneRecord(val entityId: String, val deletedAt: String)
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -241,6 +245,67 @@ object LibraryRepository {
|
||||
ids.mapNotNull { albumRecord(it, folderIds, userName) }
|
||||
}
|
||||
|
||||
/** Stable page of the library snapshot, ordered by song ID. */
|
||||
fun syncSongs(
|
||||
folderIds: Set<Int>,
|
||||
afterId: String,
|
||||
limit: Int,
|
||||
userName: String,
|
||||
): List<SongRecord> = read {
|
||||
if (folderIds.isEmpty()) return@read emptyList()
|
||||
|
||||
val rows = SongsTable.selectAll()
|
||||
.where {
|
||||
(SongsTable.folderId inList folderIds) and
|
||||
(SongsTable.id greater afterId)
|
||||
}
|
||||
.orderBy(SongsTable.id to SortOrder.ASC)
|
||||
.limit(limit)
|
||||
.toList()
|
||||
|
||||
enrichSongs(rows, userName)
|
||||
}
|
||||
|
||||
/** Songs whose metadata changed after the client's last revision. */
|
||||
fun changedSongs(
|
||||
since: String,
|
||||
folderIds: Set<Int>,
|
||||
limit: Int,
|
||||
userName: String,
|
||||
): List<SongRecord> = read {
|
||||
if (folderIds.isEmpty()) return@read emptyList()
|
||||
|
||||
val rows = SongsTable.selectAll()
|
||||
.where {
|
||||
(SongsTable.folderId inList folderIds) and
|
||||
(SongsTable.updatedAt greater since)
|
||||
}
|
||||
.orderBy(
|
||||
SongsTable.updatedAt to SortOrder.ASC,
|
||||
SongsTable.id to SortOrder.ASC,
|
||||
)
|
||||
.limit(limit)
|
||||
.toList()
|
||||
|
||||
enrichSongs(rows, userName)
|
||||
}
|
||||
|
||||
fun tombstones(since: String, limit: Int): List<TombstoneRecord> = read {
|
||||
LibraryTombstonesTable.selectAll()
|
||||
.where {
|
||||
(LibraryTombstonesTable.entity eq "song") and
|
||||
(LibraryTombstonesTable.deletedAt greater since)
|
||||
}
|
||||
.orderBy(LibraryTombstonesTable.deletedAt to SortOrder.ASC)
|
||||
.limit(limit)
|
||||
.map {
|
||||
TombstoneRecord(
|
||||
entityId = it[LibraryTombstonesTable.entityId],
|
||||
deletedAt = it[LibraryTombstonesTable.deletedAt],
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun allSongs(limit: Int, offset: Int, folderIds: Set<Int>, userName: String): List<SongRecord> = read {
|
||||
if (folderIds.isEmpty()) return@read emptyList()
|
||||
|
||||
@@ -748,6 +813,7 @@ object LibraryRepository {
|
||||
folderId = row[SongsTable.folderId],
|
||||
relativePath = row[SongsTable.relativePath],
|
||||
created = row[SongsTable.createdAt],
|
||||
updatedAt = row[SongsTable.updatedAt].ifBlank { row[SongsTable.createdAt] },
|
||||
starredAt = state?.starredAt,
|
||||
rating = state?.rating,
|
||||
playCount = state?.playCount ?: 0,
|
||||
|
||||
@@ -110,6 +110,7 @@ object MediaRepository {
|
||||
it[relativePath] = track.relativePath
|
||||
it[fileMtime] = track.fileMtime
|
||||
it[searchText] = track.searchText
|
||||
it[updatedAt] = now
|
||||
it[lyrics] = track.lyrics
|
||||
}
|
||||
} else {
|
||||
@@ -132,6 +133,7 @@ object MediaRepository {
|
||||
it[fileMtime] = track.fileMtime
|
||||
it[createdAt] = now
|
||||
it[searchText] = track.searchText
|
||||
it[updatedAt] = now
|
||||
it[lyrics] = track.lyrics
|
||||
}
|
||||
}
|
||||
@@ -169,7 +171,13 @@ object MediaRepository {
|
||||
.map { it[SongsTable.id] }
|
||||
.filterNot { it in seenSongIds }
|
||||
|
||||
val now = Instant.now().toString()
|
||||
obsolete.forEach { songId ->
|
||||
LibraryTombstonesTable.insertIgnore {
|
||||
it[entity] = "song"
|
||||
it[entityId] = songId
|
||||
it[deletedAt] = now
|
||||
}
|
||||
SongsTable.deleteWhere { it.run { SongsTable.id eq songId } }
|
||||
}
|
||||
|
||||
|
||||
@@ -4,37 +4,34 @@ import java.time.Instant
|
||||
import kotlinx.serialization.builtins.ListSerializer
|
||||
import kotlinx.serialization.builtins.serializer
|
||||
import kotlinx.serialization.json.Json
|
||||
import org.jetbrains.exposed.sql.JoinType
|
||||
import org.jetbrains.exposed.sql.Op
|
||||
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
|
||||
import org.jetbrains.exposed.sql.ResultRow
|
||||
import org.jetbrains.exposed.sql.SortOrder
|
||||
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
|
||||
import org.jetbrains.exposed.sql.and
|
||||
import org.jetbrains.exposed.sql.deleteWhere
|
||||
import org.jetbrains.exposed.sql.insert
|
||||
import org.jetbrains.exposed.sql.insertIgnore
|
||||
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 MoodRecord(
|
||||
val playlistId: String,
|
||||
val id: String,
|
||||
val owner: String,
|
||||
val name: String,
|
||||
val comment: String?,
|
||||
val description: String?,
|
||||
val query: String?,
|
||||
val genres: List<String>,
|
||||
val targetSize: Int,
|
||||
val ytSlots: Int,
|
||||
val expandRelated: Boolean,
|
||||
val refreshHours: Int,
|
||||
val generatedAt: String?,
|
||||
val generation: Int,
|
||||
val ytEnabled: Boolean,
|
||||
val lastDiscoveryAt: String?,
|
||||
val createdAt: String,
|
||||
val changedAt: String,
|
||||
val lastError: String?,
|
||||
val created: String,
|
||||
val changed: String,
|
||||
val songCount: Int,
|
||||
val duration: Int,
|
||||
val seedCount: Int,
|
||||
val newRecommendations: Int,
|
||||
)
|
||||
|
||||
data class MoodSeedRecord(
|
||||
@@ -43,190 +40,117 @@ data class MoodSeedRecord(
|
||||
val addedAt: String,
|
||||
)
|
||||
|
||||
data class RecommendationRecord(
|
||||
val videoId: String,
|
||||
val title: String,
|
||||
val artist: String,
|
||||
val album: String?,
|
||||
val duration: Int?,
|
||||
val thumbnail: String?,
|
||||
val state: String,
|
||||
val matchedSongId: String?,
|
||||
val timesAdded: Int,
|
||||
val firstSeen: String,
|
||||
val lastSeen: String,
|
||||
)
|
||||
|
||||
/**
|
||||
* Moods are private playlists with generation settings. The playlist row remains
|
||||
* the client-visible object; this repository owns the settings, seeds and the
|
||||
* materialized mix in `playlist_songs`.
|
||||
* Moods are the product's only collection. Seeds are permanent anchors; the
|
||||
* play queue is generated by [win.taptap.musicmanager.radio.RadioService] for
|
||||
* every playback session instead of being stored as a playlist.
|
||||
*/
|
||||
object MoodRepository {
|
||||
|
||||
private val genreSerializer = ListSerializer(String.serializer())
|
||||
|
||||
fun list(userName: String): List<MoodRecord> = transaction {
|
||||
PlaylistsTable
|
||||
.join(MoodsTable, JoinType.INNER, PlaylistsTable.id, MoodsTable.playlistId)
|
||||
.selectAll()
|
||||
.where {
|
||||
(PlaylistsTable.owner eq userName) and
|
||||
(PlaylistsTable.kind eq "mood")
|
||||
}
|
||||
.orderBy(PlaylistsTable.changedAt to SortOrder.DESC)
|
||||
fun list(owner: String): List<MoodRecord> = transaction {
|
||||
MoodsTable.selectAll()
|
||||
.where { MoodsTable.owner eq owner }
|
||||
.orderBy(MoodsTable.changedAt to SortOrder.DESC)
|
||||
.map { moodRecord(it) }
|
||||
}
|
||||
|
||||
fun get(playlistId: String, userName: String): MoodRecord? = transaction {
|
||||
val row = PlaylistsTable
|
||||
.join(MoodsTable, JoinType.INNER, PlaylistsTable.id, MoodsTable.playlistId)
|
||||
.selectAll()
|
||||
.where {
|
||||
(PlaylistsTable.id eq playlistId) and
|
||||
(PlaylistsTable.owner eq userName) and
|
||||
(PlaylistsTable.kind eq "mood")
|
||||
}
|
||||
fun get(id: String, owner: String): MoodRecord? = transaction {
|
||||
MoodsTable.selectAll()
|
||||
.where { (MoodsTable.id eq id) and (MoodsTable.owner eq owner) }
|
||||
.singleOrNull()
|
||||
|
||||
row?.let { moodRecord(it) }
|
||||
?.let { moodRecord(it) }
|
||||
}
|
||||
|
||||
fun create(
|
||||
userName: String,
|
||||
owner: String,
|
||||
name: String,
|
||||
comment: String?,
|
||||
description: String?,
|
||||
query: String?,
|
||||
genres: List<String>,
|
||||
targetSize: Int,
|
||||
ytSlots: Int,
|
||||
expandRelated: Boolean,
|
||||
refreshHours: Int,
|
||||
ytEnabled: Boolean,
|
||||
seedSongIds: List<String>,
|
||||
): MoodRecord {
|
||||
val playlist = PlaylistRepository.create(
|
||||
userName = userName,
|
||||
name = name,
|
||||
songIds = emptyList(),
|
||||
isPublic = false,
|
||||
kind = "mood",
|
||||
): MoodRecord = transaction {
|
||||
val now = Instant.now().toString()
|
||||
val id = IdGenerator.moodId(owner, name, now)
|
||||
|
||||
MoodsTable.insert {
|
||||
it[MoodsTable.id] = id
|
||||
it[MoodsTable.owner] = owner
|
||||
it[MoodsTable.name] = name.take(200)
|
||||
it[MoodsTable.description] = description?.take(2000)
|
||||
it[MoodsTable.query] = query?.trim()?.takeIf(String::isNotEmpty)
|
||||
it[MoodsTable.genres] = encodeGenres(genres)
|
||||
it[MoodsTable.targetSize] = targetSize.coerceIn(5, 500)
|
||||
it[MoodsTable.refreshHours] = refreshHours.coerceIn(1, 720)
|
||||
it[MoodsTable.ytEnabled] = ytEnabled
|
||||
it[createdAt] = now
|
||||
it[changedAt] = now
|
||||
}
|
||||
|
||||
insertSeeds(id, seedSongIds, "manual")
|
||||
|
||||
moodRecord(
|
||||
MoodsTable.selectAll().where { MoodsTable.id eq id }.single(),
|
||||
)
|
||||
|
||||
try {
|
||||
transaction {
|
||||
insertSettings(
|
||||
playlistId = playlist.id,
|
||||
query = query,
|
||||
genres = genres,
|
||||
targetSize = targetSize,
|
||||
ytSlots = ytSlots,
|
||||
expandRelated = expandRelated,
|
||||
refreshHours = refreshHours,
|
||||
)
|
||||
insertSeeds(playlist.id, seedSongIds, "manual")
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
PlaylistRepository.delete(playlist.id, userName)
|
||||
throw t
|
||||
}
|
||||
|
||||
return get(playlist.id, userName)
|
||||
?: error("Mood ${playlist.id} was not persisted")
|
||||
}
|
||||
|
||||
/** Converts an existing owned playlist into a mood while keeping its ID. */
|
||||
fun promote(
|
||||
userName: String,
|
||||
playlistId: String,
|
||||
query: String?,
|
||||
genres: List<String>,
|
||||
targetSize: Int,
|
||||
ytSlots: Int,
|
||||
expandRelated: Boolean,
|
||||
refreshHours: Int,
|
||||
musicFolderIds: Set<Int>,
|
||||
): MoodRecord? {
|
||||
val playlist = PlaylistRepository.get(playlistId, userName) ?: return null
|
||||
if (playlist.owner != userName || playlist.kind != "user") return null
|
||||
|
||||
val seedIds = transaction {
|
||||
PlaylistRepository.songIds(playlistId).filter { songId ->
|
||||
SongsTable
|
||||
.select(SongsTable.folderId)
|
||||
.where { SongsTable.id eq songId }
|
||||
.singleOrNull()
|
||||
?.get(SongsTable.folderId) in musicFolderIds
|
||||
}
|
||||
}
|
||||
PlaylistRepository.setKind(playlistId, "mood", false)
|
||||
|
||||
try {
|
||||
transaction {
|
||||
insertSettings(
|
||||
playlistId = playlistId,
|
||||
query = query,
|
||||
genres = genres,
|
||||
targetSize = targetSize,
|
||||
ytSlots = ytSlots,
|
||||
expandRelated = expandRelated,
|
||||
refreshHours = refreshHours,
|
||||
)
|
||||
insertSeeds(playlistId, seedIds, "promoted")
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
PlaylistRepository.setKind(playlistId, "user", playlist.isPublic)
|
||||
throw t
|
||||
}
|
||||
|
||||
return get(playlistId, userName)
|
||||
}
|
||||
|
||||
fun update(
|
||||
playlistId: String,
|
||||
userName: String,
|
||||
id: String,
|
||||
owner: String,
|
||||
name: String,
|
||||
comment: String?,
|
||||
description: String?,
|
||||
query: String?,
|
||||
genres: List<String>,
|
||||
targetSize: Int,
|
||||
ytSlots: Int,
|
||||
expandRelated: Boolean,
|
||||
refreshHours: Int,
|
||||
): Boolean = transaction {
|
||||
val exists = PlaylistsTable.selectAll()
|
||||
.where {
|
||||
(PlaylistsTable.id eq playlistId) and
|
||||
(PlaylistsTable.owner eq userName) and
|
||||
(PlaylistsTable.kind eq "mood")
|
||||
}
|
||||
ytEnabled: Boolean,
|
||||
): MoodRecord? = transaction {
|
||||
val exists = MoodsTable.selectAll()
|
||||
.where { (MoodsTable.id eq id) and (MoodsTable.owner eq owner) }
|
||||
.any()
|
||||
if (!exists) return@transaction false
|
||||
if (!exists) return@transaction null
|
||||
|
||||
PlaylistsTable.update({ PlaylistsTable.id eq playlistId }) {
|
||||
it[PlaylistsTable.name] = name
|
||||
it[PlaylistsTable.comment] = comment
|
||||
MoodsTable.update({ MoodsTable.id eq id }) {
|
||||
it[MoodsTable.name] = name.take(200)
|
||||
it[MoodsTable.description] = description?.take(2000)
|
||||
it[MoodsTable.query] = query?.trim()?.takeIf(String::isNotEmpty)
|
||||
it[MoodsTable.genres] = encodeGenres(genres)
|
||||
it[MoodsTable.targetSize] = targetSize.coerceIn(5, 500)
|
||||
it[MoodsTable.refreshHours] = refreshHours.coerceIn(1, 720)
|
||||
it[MoodsTable.ytEnabled] = ytEnabled
|
||||
it[changedAt] = Instant.now().toString()
|
||||
}
|
||||
MoodsTable.update({ MoodsTable.playlistId eq playlistId }) {
|
||||
it[MoodsTable.query] = query
|
||||
it[MoodsTable.genres] = encodeGenres(genres)
|
||||
it[MoodsTable.targetSize] = targetSize.coerceIn(1, 500)
|
||||
it[MoodsTable.ytSlots] = ytSlots.coerceIn(0, 500)
|
||||
it[MoodsTable.expandRelated] = expandRelated
|
||||
it[MoodsTable.refreshHours] = refreshHours.coerceIn(1, 720)
|
||||
it[generatedAt] = null
|
||||
}
|
||||
true
|
||||
|
||||
moodRecord(MoodsTable.selectAll().where { MoodsTable.id eq id }.single())
|
||||
}
|
||||
|
||||
fun delete(playlistId: String, userName: String): Boolean =
|
||||
PlaylistRepository.delete(playlistId, userName)
|
||||
|
||||
fun seedSongIds(playlistId: String, origin: String? = null): List<String> = transaction {
|
||||
val condition = if (origin == null) {
|
||||
MoodSeedsTable.playlistId eq playlistId
|
||||
} else {
|
||||
(MoodSeedsTable.playlistId eq playlistId) and (MoodSeedsTable.origin eq origin)
|
||||
}
|
||||
|
||||
MoodSeedsTable.selectAll()
|
||||
.where(condition)
|
||||
.orderBy(
|
||||
MoodSeedsTable.addedAt to SortOrder.ASC,
|
||||
MoodSeedsTable.songId to SortOrder.ASC,
|
||||
)
|
||||
.map { it[MoodSeedsTable.songId] }
|
||||
fun delete(id: String, owner: String): Boolean = transaction {
|
||||
MoodsTable.deleteWhere {
|
||||
(MoodsTable.id eq id) and (MoodsTable.owner eq owner)
|
||||
} > 0
|
||||
}
|
||||
|
||||
fun seeds(playlistId: String): List<MoodSeedRecord> = transaction {
|
||||
fun seeds(id: String): List<MoodSeedRecord> = transaction {
|
||||
MoodSeedsTable.selectAll()
|
||||
.where { MoodSeedsTable.playlistId eq playlistId }
|
||||
.where { MoodSeedsTable.moodId eq id }
|
||||
.orderBy(
|
||||
MoodSeedsTable.addedAt to SortOrder.ASC,
|
||||
MoodSeedsTable.songId to SortOrder.ASC,
|
||||
@@ -240,165 +164,130 @@ object MoodRepository {
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns true when the seed was newly inserted. */
|
||||
fun addSeed(
|
||||
playlistId: String,
|
||||
userName: String,
|
||||
songId: String,
|
||||
origin: String,
|
||||
): Boolean = transaction {
|
||||
if (get(playlistId, userName) == null) return@transaction false
|
||||
fun seedSongIds(id: String): List<String> = seeds(id).map { it.songId }
|
||||
|
||||
/** Returns false when the song is already a seed or the mood is not owned. */
|
||||
fun addSeed(id: String, owner: String, songId: String, origin: String): Boolean = transaction {
|
||||
val owned = MoodsTable.selectAll()
|
||||
.where { (MoodsTable.id eq id) and (MoodsTable.owner eq owner) }
|
||||
.any()
|
||||
if (!owned) return@transaction false
|
||||
|
||||
val exists = MoodSeedsTable.selectAll()
|
||||
.where {
|
||||
(MoodSeedsTable.playlistId eq playlistId) and
|
||||
(MoodSeedsTable.songId eq songId)
|
||||
}
|
||||
.where { (MoodSeedsTable.moodId eq id) and (MoodSeedsTable.songId eq songId) }
|
||||
.any()
|
||||
if (exists) return@transaction false
|
||||
|
||||
MoodSeedsTable.insert {
|
||||
it[MoodSeedsTable.playlistId] = playlistId
|
||||
val now = Instant.now().toString()
|
||||
MoodSeedsTable.insertIgnore {
|
||||
it[MoodSeedsTable.moodId] = id
|
||||
it[MoodSeedsTable.songId] = songId
|
||||
it[MoodSeedsTable.origin] = origin
|
||||
it[addedAt] = Instant.now().toString()
|
||||
it[MoodSeedsTable.origin] = origin.takeIf { value -> value in ORIGINS } ?: "manual"
|
||||
it[addedAt] = now
|
||||
}
|
||||
MoodsTable.update({ MoodsTable.id eq id }) {
|
||||
it[changedAt] = now
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fun removeSeed(
|
||||
playlistId: String,
|
||||
userName: String,
|
||||
songId: String,
|
||||
origin: String? = null,
|
||||
): Boolean = transaction {
|
||||
if (get(playlistId, userName) == null) return@transaction false
|
||||
fun removeSeed(id: String, owner: String, songId: String): Boolean = transaction {
|
||||
val owned = MoodsTable.selectAll()
|
||||
.where { (MoodsTable.id eq id) and (MoodsTable.owner eq owner) }
|
||||
.any()
|
||||
if (!owned) return@transaction false
|
||||
|
||||
val condition = if (origin == null) {
|
||||
(MoodSeedsTable.playlistId eq playlistId) and (MoodSeedsTable.songId eq songId)
|
||||
} else {
|
||||
(MoodSeedsTable.playlistId eq playlistId) and
|
||||
(MoodSeedsTable.songId eq songId) and
|
||||
(MoodSeedsTable.origin eq origin)
|
||||
}
|
||||
MoodSeedsTable.deleteWhere { condition } > 0
|
||||
}
|
||||
|
||||
/** Mood playlists that currently contain [songId], for context-free star pinning. */
|
||||
fun moodsContainingSong(userName: String, songId: String): List<String> = transaction {
|
||||
PlaylistsTable
|
||||
.join(MoodsTable, JoinType.INNER, PlaylistsTable.id, MoodsTable.playlistId)
|
||||
.join(PlaylistSongsTable, JoinType.INNER, PlaylistsTable.id, PlaylistSongsTable.playlistId)
|
||||
.select(PlaylistsTable.id)
|
||||
.where {
|
||||
(PlaylistsTable.owner eq userName) and
|
||||
(PlaylistsTable.kind eq "mood") and
|
||||
(PlaylistSongsTable.songId eq songId)
|
||||
}
|
||||
.map { it[PlaylistsTable.id] }
|
||||
.distinct()
|
||||
}
|
||||
|
||||
fun markGenerated(playlistId: String, generation: Int, error: String?) {
|
||||
transaction {
|
||||
MoodsTable.update({ MoodsTable.playlistId eq playlistId }) {
|
||||
it[generatedAt] = Instant.now().toString()
|
||||
it[MoodsTable.generation] = generation
|
||||
it[lastError] = error
|
||||
val removed = MoodSeedsTable.deleteWhere {
|
||||
(MoodSeedsTable.moodId eq id) and (MoodSeedsTable.songId eq songId)
|
||||
} > 0
|
||||
if (removed) {
|
||||
MoodsTable.update({ MoodsTable.id eq id }) {
|
||||
it[changedAt] = Instant.now().toString()
|
||||
}
|
||||
}
|
||||
removed
|
||||
}
|
||||
|
||||
fun markStale(playlistId: String) {
|
||||
transaction {
|
||||
MoodsTable.update({ MoodsTable.playlistId eq playlistId }) {
|
||||
it[generatedAt] = null
|
||||
fun recommendations(id: String): List<RecommendationRecord> = transaction {
|
||||
MoodRecommendationsTable.selectAll()
|
||||
.where { MoodRecommendationsTable.moodId eq id }
|
||||
.orderBy(MoodRecommendationsTable.lastSeen to SortOrder.DESC)
|
||||
.map {
|
||||
RecommendationRecord(
|
||||
videoId = it[MoodRecommendationsTable.videoId],
|
||||
title = it[MoodRecommendationsTable.title],
|
||||
artist = it[MoodRecommendationsTable.artist],
|
||||
album = it[MoodRecommendationsTable.album],
|
||||
duration = it[MoodRecommendationsTable.duration],
|
||||
thumbnail = it[MoodRecommendationsTable.thumbnail],
|
||||
state = it[MoodRecommendationsTable.state],
|
||||
matchedSongId = it[MoodRecommendationsTable.matchedSongId],
|
||||
timesAdded = it[MoodRecommendationsTable.timesAdded],
|
||||
firstSeen = it[MoodRecommendationsTable.firstSeen],
|
||||
lastSeen = it[MoodRecommendationsTable.lastSeen],
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Records a failed generation without claiming the mood is fresh. */
|
||||
fun markError(playlistId: String, message: String) {
|
||||
fun markError(id: String, message: String) {
|
||||
transaction {
|
||||
MoodsTable.update({ MoodsTable.playlistId eq playlistId }) {
|
||||
MoodsTable.update({ MoodsTable.id eq id }) {
|
||||
it[lastError] = message.take(1000)
|
||||
it[generatedAt] = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun markAllStale() {
|
||||
fun markDiscovered(id: String) {
|
||||
transaction {
|
||||
MoodsTable.update({ Op.TRUE }) {
|
||||
it[generatedAt] = null
|
||||
MoodsTable.update({ MoodsTable.id eq id }) {
|
||||
it[lastDiscoveryAt] = Instant.now().toString()
|
||||
it[lastError] = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun insertSettings(
|
||||
playlistId: String,
|
||||
query: String?,
|
||||
genres: List<String>,
|
||||
targetSize: Int,
|
||||
ytSlots: Int,
|
||||
expandRelated: Boolean,
|
||||
refreshHours: Int,
|
||||
) {
|
||||
MoodsTable.insert {
|
||||
it[MoodsTable.playlistId] = playlistId
|
||||
it[MoodsTable.query] = query?.trim()?.takeIf(String::isNotEmpty)
|
||||
it[MoodsTable.genres] = encodeGenres(genres)
|
||||
it[MoodsTable.targetSize] = targetSize.coerceIn(1, 500)
|
||||
it[MoodsTable.ytSlots] = ytSlots.coerceIn(0, 500)
|
||||
it[MoodsTable.expandRelated] = expandRelated
|
||||
it[MoodsTable.refreshHours] = refreshHours.coerceIn(1, 720)
|
||||
}
|
||||
}
|
||||
|
||||
private fun insertSeeds(playlistId: String, songIds: List<String>, origin: String) {
|
||||
private fun insertSeeds(id: String, songIds: List<String>, origin: String) {
|
||||
val now = Instant.now().toString()
|
||||
songIds.distinct().forEach { songId ->
|
||||
MoodSeedsTable.insert {
|
||||
it[MoodSeedsTable.playlistId] = playlistId
|
||||
it[MoodSeedsTable.songId] = songId
|
||||
it[MoodSeedsTable.origin] = origin
|
||||
MoodSeedsTable.insertIgnore {
|
||||
it[moodId] = id
|
||||
it[this.songId] = songId
|
||||
it[this.origin] = origin
|
||||
it[addedAt] = now
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun moodRecord(row: ResultRow): MoodRecord {
|
||||
val id = row[PlaylistsTable.id]
|
||||
val songs = PlaylistSongsTable
|
||||
.join(SongsTable, JoinType.INNER, PlaylistSongsTable.songId, SongsTable.id)
|
||||
.select(SongsTable.duration)
|
||||
.where { PlaylistSongsTable.playlistId eq id }
|
||||
.toList()
|
||||
val seedCount = MoodSeedsTable
|
||||
.selectAll()
|
||||
.where { MoodSeedsTable.playlistId eq id }
|
||||
val id = row[MoodsTable.id]
|
||||
val seedCount = MoodSeedsTable.selectAll()
|
||||
.where { MoodSeedsTable.moodId eq id }
|
||||
.count()
|
||||
.toInt()
|
||||
val newRecommendations = MoodRecommendationsTable.selectAll()
|
||||
.where {
|
||||
(MoodRecommendationsTable.moodId eq id) and
|
||||
(MoodRecommendationsTable.state eq "new")
|
||||
}
|
||||
.count()
|
||||
.toInt()
|
||||
|
||||
return MoodRecord(
|
||||
playlistId = id,
|
||||
owner = row[PlaylistsTable.owner],
|
||||
name = row[PlaylistsTable.name],
|
||||
comment = row[PlaylistsTable.comment],
|
||||
id = id,
|
||||
owner = row[MoodsTable.owner],
|
||||
name = row[MoodsTable.name],
|
||||
description = row[MoodsTable.description],
|
||||
query = row[MoodsTable.query],
|
||||
genres = decodeGenres(row[MoodsTable.genres]),
|
||||
targetSize = row[MoodsTable.targetSize],
|
||||
ytSlots = row[MoodsTable.ytSlots],
|
||||
expandRelated = row[MoodsTable.expandRelated],
|
||||
refreshHours = row[MoodsTable.refreshHours],
|
||||
generatedAt = row[MoodsTable.generatedAt],
|
||||
generation = row[MoodsTable.generation],
|
||||
ytEnabled = row[MoodsTable.ytEnabled],
|
||||
lastDiscoveryAt = row[MoodsTable.lastDiscoveryAt],
|
||||
createdAt = row[MoodsTable.createdAt],
|
||||
changedAt = row[MoodsTable.changedAt],
|
||||
lastError = row[MoodsTable.lastError],
|
||||
created = row[PlaylistsTable.createdAt],
|
||||
changed = row[PlaylistsTable.changedAt],
|
||||
songCount = songs.size,
|
||||
duration = songs.sumOf { it[SongsTable.duration] },
|
||||
seedCount = seedCount,
|
||||
newRecommendations = newRecommendations,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -410,4 +299,6 @@ object MoodRepository {
|
||||
|
||||
private fun decodeGenres(value: String): List<String> =
|
||||
runCatching { Json.decodeFromString(genreSerializer, value) }.getOrDefault(emptyList())
|
||||
|
||||
private val ORIGINS = setOf("manual", "recommendation", "yt")
|
||||
}
|
||||
@@ -1,191 +0,0 @@
|
||||
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 kind: String,
|
||||
val songCount: Int,
|
||||
val duration: Int,
|
||||
val created: String,
|
||||
val changed: String,
|
||||
)
|
||||
|
||||
/** Playlists are per user; public playlists are visible to everyone. */
|
||||
object PlaylistRepository {
|
||||
|
||||
fun visibleTo(userName: String): List<PlaylistRecord> = transaction {
|
||||
PlaylistsTable.selectAll()
|
||||
.where {
|
||||
(PlaylistsTable.owner eq userName) or (PlaylistsTable.isPublic eq true)
|
||||
}
|
||||
.orderBy(PlaylistsTable.changedAt to org.jetbrains.exposed.sql.SortOrder.DESC)
|
||||
.map { playlistRecord(it[PlaylistsTable.id], it) }
|
||||
}
|
||||
|
||||
fun get(playlistId: String, userName: String): PlaylistRecord? = transaction {
|
||||
val row = PlaylistsTable.selectAll()
|
||||
.where { PlaylistsTable.id eq playlistId }
|
||||
.singleOrNull() ?: return@transaction null
|
||||
|
||||
if (row[PlaylistsTable.owner] != userName && !row[PlaylistsTable.isPublic]) {
|
||||
return@transaction null
|
||||
}
|
||||
|
||||
playlistRecord(playlistId, row)
|
||||
}
|
||||
|
||||
fun songIds(playlistId: String): List<String> = transaction {
|
||||
PlaylistSongsTable.selectAll()
|
||||
.where { PlaylistSongsTable.playlistId eq playlistId }
|
||||
.orderBy(PlaylistSongsTable.position to org.jetbrains.exposed.sql.SortOrder.ASC)
|
||||
.map { it[PlaylistSongsTable.songId] }
|
||||
}
|
||||
|
||||
fun create(
|
||||
userName: String,
|
||||
name: String,
|
||||
songIds: List<String>,
|
||||
isPublic: Boolean = true,
|
||||
kind: String = "user",
|
||||
): 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[PlaylistsTable.isPublic] = isPublic
|
||||
it[PlaylistsTable.kind] = kind
|
||||
it[createdAt] = now
|
||||
it[changedAt] = now
|
||||
}
|
||||
replaceSongsInternal(id, songIds)
|
||||
|
||||
playlistRecord(id, PlaylistsTable.selectAll().where { PlaylistsTable.id eq id }.single())
|
||||
}
|
||||
|
||||
/** Promotion keeps the playlist ID stable so Symfonium keeps its reference. */
|
||||
fun setKind(playlistId: String, kind: String, isPublic: Boolean): Boolean = transaction {
|
||||
PlaylistsTable.update({ PlaylistsTable.id eq playlistId }) {
|
||||
it[PlaylistsTable.kind] = kind
|
||||
it[PlaylistsTable.isPublic] = isPublic
|
||||
it[changedAt] = Instant.now().toString()
|
||||
} > 0
|
||||
}
|
||||
|
||||
fun replaceSongs(playlistId: String, songIds: List<String>, userName: String): Boolean = transaction {
|
||||
val row = PlaylistsTable.selectAll()
|
||||
.where { PlaylistsTable.id eq playlistId }
|
||||
.singleOrNull() ?: return@transaction false
|
||||
if (row[PlaylistsTable.owner] != userName) return@transaction false
|
||||
|
||||
val now = Instant.now().toString()
|
||||
replaceSongsInternal(playlistId, songIds)
|
||||
PlaylistsTable.update({ PlaylistsTable.id eq playlistId }) {
|
||||
it[changedAt] = now
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fun update(
|
||||
playlistId: String,
|
||||
userName: String,
|
||||
name: String?,
|
||||
comment: String?,
|
||||
isPublic: Boolean?,
|
||||
addSongIds: List<String>,
|
||||
removeIndices: List<Int>,
|
||||
): Boolean = transaction {
|
||||
val row = PlaylistsTable.selectAll()
|
||||
.where { PlaylistsTable.id eq playlistId }
|
||||
.singleOrNull() ?: return@transaction false
|
||||
if (row[PlaylistsTable.owner] != userName) return@transaction false
|
||||
|
||||
if (name != null || comment != null || isPublic != null) {
|
||||
PlaylistsTable.update({ PlaylistsTable.id eq playlistId }) {
|
||||
if (name != null) it[PlaylistsTable.name] = name
|
||||
if (comment != null) it[PlaylistsTable.comment] = comment
|
||||
if (isPublic != null) it[PlaylistsTable.isPublic] = isPublic
|
||||
}
|
||||
}
|
||||
|
||||
var songs = songIdsInternal(playlistId)
|
||||
if (removeIndices.isNotEmpty()) {
|
||||
val toRemove = removeIndices.filter { it in songs.indices }.toSortedSet(compareByDescending { it })
|
||||
toRemove.forEach { index ->
|
||||
if (index in songs.indices) songs = songs.filterIndexed { i, _ -> i != index }
|
||||
}
|
||||
}
|
||||
songs = songs + addSongIds
|
||||
|
||||
val now = Instant.now().toString()
|
||||
replaceSongsInternal(playlistId, songs)
|
||||
PlaylistsTable.update({ PlaylistsTable.id eq playlistId }) {
|
||||
it[changedAt] = now
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fun delete(playlistId: String, userName: String): Boolean = transaction {
|
||||
val row = PlaylistsTable.selectAll()
|
||||
.where { PlaylistsTable.id eq playlistId }
|
||||
.singleOrNull() ?: return@transaction false
|
||||
if (row[PlaylistsTable.owner] != userName) return@transaction false
|
||||
|
||||
PlaylistsTable.deleteWhere { it.run { PlaylistsTable.id eq playlistId } }
|
||||
true
|
||||
}
|
||||
|
||||
private fun songIdsInternal(playlistId: String): List<String> =
|
||||
PlaylistSongsTable.selectAll()
|
||||
.where { PlaylistSongsTable.playlistId eq playlistId }
|
||||
.orderBy(PlaylistSongsTable.position to org.jetbrains.exposed.sql.SortOrder.ASC)
|
||||
.map { it[PlaylistSongsTable.songId] }
|
||||
|
||||
private fun replaceSongsInternal(playlistId: String, songIds: List<String>) {
|
||||
PlaylistSongsTable.deleteWhere { it.run { PlaylistSongsTable.playlistId eq playlistId } }
|
||||
songIds.forEachIndexed { index, songId ->
|
||||
PlaylistSongsTable.insert {
|
||||
it[PlaylistSongsTable.playlistId] = playlistId
|
||||
it[PlaylistSongsTable.songId] = songId
|
||||
it[position] = index
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun playlistRecord(id: String, row: org.jetbrains.exposed.sql.ResultRow): PlaylistRecord {
|
||||
val songs = PlaylistSongsTable
|
||||
.join(SongsTable, JoinType.INNER, PlaylistSongsTable.songId, SongsTable.id)
|
||||
.select(SongsTable.duration)
|
||||
.where { PlaylistSongsTable.playlistId eq id }
|
||||
.toList()
|
||||
|
||||
return PlaylistRecord(
|
||||
id = id,
|
||||
name = row[PlaylistsTable.name],
|
||||
comment = row[PlaylistsTable.comment],
|
||||
owner = row[PlaylistsTable.owner],
|
||||
isPublic = row[PlaylistsTable.isPublic],
|
||||
kind = row[PlaylistsTable.kind],
|
||||
songCount = songs.size,
|
||||
duration = songs.sumOf { it[SongsTable.duration] },
|
||||
created = row[PlaylistsTable.createdAt],
|
||||
changed = row[PlaylistsTable.changedAt],
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
package win.taptap.musicmanager.db
|
||||
|
||||
import java.time.Instant
|
||||
import org.jetbrains.exposed.sql.SortOrder
|
||||
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
|
||||
import org.jetbrains.exposed.sql.and
|
||||
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 PlaybackSessionRecord(
|
||||
val id: String,
|
||||
val userName: String,
|
||||
val moodId: String,
|
||||
val createdAt: String,
|
||||
val lastSeenAt: String,
|
||||
val closedAt: String?,
|
||||
)
|
||||
|
||||
data class SessionItemRecord(
|
||||
val position: Int,
|
||||
val songId: String,
|
||||
val state: String,
|
||||
)
|
||||
|
||||
data class AffinityRecord(val completions: Int, val skips: Int) {
|
||||
/** Skips weigh double so a mood stops serving rejected tracks quickly. */
|
||||
val score: Double get() = completions - skips * 2.0
|
||||
}
|
||||
|
||||
/**
|
||||
* Playback sessions make likes unnecessary: every play, skip and completion is
|
||||
* attributed to the mood that produced the queue, and explicit "add to mood"
|
||||
* actions replace stars.
|
||||
*/
|
||||
object RadioRepository {
|
||||
|
||||
fun createSession(userName: String, moodId: String, sessionToken: String): PlaybackSessionRecord = transaction {
|
||||
val now = Instant.now().toString()
|
||||
val id = "ps-" + ApiTokenRepository.hash(sessionToken).take(24)
|
||||
PlaybackSessionsTable.insert {
|
||||
it[PlaybackSessionsTable.id] = id
|
||||
it[PlaybackSessionsTable.userName] = userName
|
||||
it[PlaybackSessionsTable.moodId] = moodId
|
||||
it[createdAt] = now
|
||||
it[lastSeenAt] = now
|
||||
}
|
||||
PlaybackSessionRecord(id, userName, moodId, now, now, null)
|
||||
}
|
||||
|
||||
fun get(id: String, userName: String): PlaybackSessionRecord? = transaction {
|
||||
PlaybackSessionsTable.selectAll()
|
||||
.where {
|
||||
(PlaybackSessionsTable.id eq id) and
|
||||
(PlaybackSessionsTable.userName eq userName)
|
||||
}
|
||||
.singleOrNull()
|
||||
?.toRecord()
|
||||
}
|
||||
|
||||
fun touch(id: String) {
|
||||
transaction {
|
||||
PlaybackSessionsTable.update({ PlaybackSessionsTable.id eq id }) {
|
||||
it[lastSeenAt] = Instant.now().toString()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun close(id: String, userName: String): Boolean = transaction {
|
||||
val now = Instant.now().toString()
|
||||
PlaybackSessionsTable.update({
|
||||
(PlaybackSessionsTable.id eq id) and
|
||||
(PlaybackSessionsTable.userName eq userName) and
|
||||
(PlaybackSessionsTable.closedAt.isNull())
|
||||
}) {
|
||||
it[closedAt] = now
|
||||
it[lastSeenAt] = now
|
||||
} > 0
|
||||
}
|
||||
|
||||
fun items(id: String): List<SessionItemRecord> = transaction {
|
||||
SessionItemsTable.selectAll()
|
||||
.where { SessionItemsTable.sessionId eq id }
|
||||
.orderBy(SessionItemsTable.position to SortOrder.ASC)
|
||||
.map {
|
||||
SessionItemRecord(
|
||||
position = it[SessionItemsTable.position],
|
||||
songId = it[SessionItemsTable.songId],
|
||||
state = it[SessionItemsTable.state],
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun queuedSongIds(id: String): Set<String> = items(id).map { it.songId }.toSet()
|
||||
|
||||
/** Appends tracks and returns their positions in the session. */
|
||||
fun append(sessionId: String, songIds: List<String>): List<Int> = transaction {
|
||||
if (songIds.isEmpty()) return@transaction emptyList()
|
||||
|
||||
val session = PlaybackSessionsTable.selectAll()
|
||||
.where { PlaybackSessionsTable.id eq sessionId }
|
||||
.single()
|
||||
var position = session[PlaybackSessionsTable.nextPosition]
|
||||
val now = Instant.now().toString()
|
||||
val positions = mutableListOf<Int>()
|
||||
|
||||
songIds.forEach { songId ->
|
||||
SessionItemsTable.insert {
|
||||
it[SessionItemsTable.sessionId] = sessionId
|
||||
it[SessionItemsTable.position] = position
|
||||
it[SessionItemsTable.songId] = songId
|
||||
it[SessionItemsTable.state] = "queued"
|
||||
it[queuedAt] = now
|
||||
it[updatedAt] = now
|
||||
}
|
||||
positions += position
|
||||
position += 1
|
||||
}
|
||||
|
||||
PlaybackSessionsTable.update({ PlaybackSessionsTable.id eq sessionId }) {
|
||||
it[nextPosition] = position
|
||||
it[lastSeenAt] = now
|
||||
}
|
||||
positions
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a client playback event. Unknown songs are still recorded in the
|
||||
* affinity table so manual queueing can influence later radio batches.
|
||||
*/
|
||||
fun recordEvent(
|
||||
sessionId: String,
|
||||
userName: String,
|
||||
songId: String,
|
||||
state: String,
|
||||
): Boolean = transaction {
|
||||
val session = PlaybackSessionsTable.selectAll()
|
||||
.where {
|
||||
(PlaybackSessionsTable.id eq sessionId) and
|
||||
(PlaybackSessionsTable.userName eq userName)
|
||||
}
|
||||
.singleOrNull() ?: return@transaction false
|
||||
|
||||
val now = Instant.now().toString()
|
||||
SessionItemsTable.update({
|
||||
(SessionItemsTable.sessionId eq sessionId) and
|
||||
(SessionItemsTable.songId eq songId)
|
||||
}) {
|
||||
it[SessionItemsTable.state] = state
|
||||
it[updatedAt] = now
|
||||
}
|
||||
|
||||
if (state == "completed" || state == "skipped") {
|
||||
val existing = SongAffinityTable.selectAll()
|
||||
.where {
|
||||
(SongAffinityTable.userName eq userName) and
|
||||
(SongAffinityTable.songId eq songId)
|
||||
}
|
||||
.singleOrNull()
|
||||
|
||||
if (existing == null) {
|
||||
SongAffinityTable.insert {
|
||||
it[SongAffinityTable.userName] = userName
|
||||
it[SongAffinityTable.songId] = songId
|
||||
it[completions] = if (state == "completed") 1 else 0
|
||||
it[skips] = if (state == "skipped") 1 else 0
|
||||
it[lastEventAt] = now
|
||||
}
|
||||
} else {
|
||||
SongAffinityTable.update({
|
||||
(SongAffinityTable.userName eq userName) and
|
||||
(SongAffinityTable.songId eq songId)
|
||||
}) {
|
||||
if (state == "completed") it[completions] = existing[SongAffinityTable.completions] + 1
|
||||
if (state == "skipped") it[skips] = existing[SongAffinityTable.skips] + 1
|
||||
it[lastEventAt] = now
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
PlaybackSessionsTable.update({ PlaybackSessionsTable.id eq session[PlaybackSessionsTable.id] }) {
|
||||
it[lastSeenAt] = now
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fun affinity(userName: String, songIds: Collection<String>): Map<String, AffinityRecord> {
|
||||
if (songIds.isEmpty()) return emptyMap()
|
||||
return transaction {
|
||||
SongAffinityTable.selectAll()
|
||||
.where {
|
||||
(SongAffinityTable.userName eq userName) and
|
||||
(SongAffinityTable.songId inList songIds.toList())
|
||||
}
|
||||
.associate {
|
||||
it[SongAffinityTable.songId] to AffinityRecord(
|
||||
completions = it[SongAffinityTable.completions],
|
||||
skips = it[SongAffinityTable.skips],
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun org.jetbrains.exposed.sql.ResultRow.toRecord() = PlaybackSessionRecord(
|
||||
id = this[PlaybackSessionsTable.id],
|
||||
userName = this[PlaybackSessionsTable.userName],
|
||||
moodId = this[PlaybackSessionsTable.moodId],
|
||||
createdAt = this[PlaybackSessionsTable.createdAt],
|
||||
lastSeenAt = this[PlaybackSessionsTable.lastSeenAt],
|
||||
closedAt = this[PlaybackSessionsTable.closedAt],
|
||||
)
|
||||
}
|
||||
@@ -68,6 +68,7 @@ object SongsTable : Table("songs") {
|
||||
val relativePath = text("relative_path")
|
||||
val fileMtime = long("file_mtime")
|
||||
val createdAt = varchar("created_at", 40)
|
||||
val updatedAt = varchar("updated_at", 40).default("")
|
||||
val searchText = text("search_text")
|
||||
val lyrics = text("lyrics").nullable()
|
||||
|
||||
@@ -133,57 +134,46 @@ object BookmarksTable : Table("bookmarks") {
|
||||
override val primaryKey = PrimaryKey(userName, songId)
|
||||
}
|
||||
|
||||
object PlaylistsTable : Table("playlists") {
|
||||
/**
|
||||
* Moods are the only collection type. A mood owns seeds (permanent anchors) and
|
||||
* recommendations (YT Music candidates); playback queues are generated live and
|
||||
* never materialized here.
|
||||
*/
|
||||
object MoodsTable : Table("moods") {
|
||||
val id = varchar("id", 32)
|
||||
val owner = reference("owner", UsersTable.name, onDelete = ReferenceOption.CASCADE)
|
||||
val name = text("name")
|
||||
val comment = text("comment").nullable()
|
||||
val isPublic = bool("is_public").default(true)
|
||||
val kind = varchar("kind", 16).default("user")
|
||||
val description = text("description").nullable()
|
||||
val query = text("query").nullable()
|
||||
val genres = text("genres").default("[]")
|
||||
val targetSize = integer("target_size").default(30)
|
||||
val refreshHours = integer("refresh_hours").default(24)
|
||||
val ytEnabled = bool("yt_enabled").default(true)
|
||||
val lastDiscoveryAt = varchar("last_discovery_at", 40).nullable()
|
||||
val createdAt = varchar("created_at", 40)
|
||||
val changedAt = varchar("changed_at", 40)
|
||||
val lastError = text("last_error").nullable()
|
||||
|
||||
override val primaryKey = PrimaryKey(id)
|
||||
}
|
||||
|
||||
object PlaylistSongsTable : Table("playlist_songs") {
|
||||
val playlistId = reference("playlist_id", PlaylistsTable.id, onDelete = ReferenceOption.CASCADE)
|
||||
val songId = reference("song_id", SongsTable.id, onDelete = ReferenceOption.CASCADE)
|
||||
val position = integer("position")
|
||||
|
||||
override val primaryKey = PrimaryKey(playlistId, position)
|
||||
}
|
||||
|
||||
object MoodsTable : Table("moods") {
|
||||
val playlistId = reference("playlist_id", PlaylistsTable.id, onDelete = ReferenceOption.CASCADE)
|
||||
val query = text("query").nullable()
|
||||
val genres = text("genres").default("[]")
|
||||
val targetSize = integer("target_size").default(50)
|
||||
val ytSlots = integer("yt_slots").default(0)
|
||||
val expandRelated = bool("expand_related").default(true)
|
||||
val refreshHours = integer("refresh_hours").default(24)
|
||||
val generatedAt = varchar("generated_at", 40).nullable()
|
||||
val generation = integer("generation").default(0)
|
||||
val lastError = text("last_error").nullable()
|
||||
|
||||
override val primaryKey = PrimaryKey(playlistId)
|
||||
}
|
||||
|
||||
object MoodSeedsTable : Table("mood_seeds") {
|
||||
val playlistId = reference("playlist_id", MoodsTable.playlistId, onDelete = ReferenceOption.CASCADE)
|
||||
val moodId = reference("mood_id", MoodsTable.id, onDelete = ReferenceOption.CASCADE)
|
||||
val songId = reference("song_id", SongsTable.id, onDelete = ReferenceOption.CASCADE)
|
||||
val origin = varchar("origin", 16).default("manual")
|
||||
val addedAt = varchar("added_at", 40)
|
||||
|
||||
override val primaryKey = PrimaryKey(playlistId, songId)
|
||||
override val primaryKey = PrimaryKey(moodId, songId)
|
||||
}
|
||||
|
||||
object MoodRecommendationsTable : Table("mood_recommendations") {
|
||||
val playlistId = reference("playlist_id", MoodsTable.playlistId, onDelete = ReferenceOption.CASCADE)
|
||||
val moodId = reference("mood_id", MoodsTable.id, onDelete = ReferenceOption.CASCADE)
|
||||
val videoId = varchar("video_id", 64)
|
||||
val title = text("title")
|
||||
val artist = text("artist")
|
||||
val album = text("album").nullable()
|
||||
val duration = integer("duration").nullable()
|
||||
val thumbnail = text("thumbnail").nullable()
|
||||
val state = varchar("state", 16).default("new")
|
||||
val matchedSongId = reference(
|
||||
"matched_song_id",
|
||||
@@ -194,5 +184,60 @@ object MoodRecommendationsTable : Table("mood_recommendations") {
|
||||
val firstSeen = varchar("first_seen", 40)
|
||||
val lastSeen = varchar("last_seen", 40)
|
||||
|
||||
override val primaryKey = PrimaryKey(playlistId, videoId)
|
||||
override val primaryKey = PrimaryKey(moodId, videoId)
|
||||
}
|
||||
|
||||
/** Bearer tokens are stored as hashes; the raw value only exists on the device. */
|
||||
object ApiTokensTable : Table("api_tokens") {
|
||||
val id = varchar("id", 32)
|
||||
val userName = reference("user_name", UsersTable.name, onDelete = ReferenceOption.CASCADE)
|
||||
val tokenHash = varchar("token_hash", 64)
|
||||
val deviceName = varchar("device_name", 120)
|
||||
val platform = varchar("platform", 32)
|
||||
val createdAt = varchar("created_at", 40)
|
||||
val lastUsedAt = varchar("last_used_at", 40)
|
||||
val expiresAt = varchar("expires_at", 40)
|
||||
|
||||
override val primaryKey = PrimaryKey(id)
|
||||
}
|
||||
|
||||
object PlaybackSessionsTable : Table("playback_sessions") {
|
||||
val id = varchar("id", 32)
|
||||
val userName = reference("user_name", UsersTable.name, onDelete = ReferenceOption.CASCADE)
|
||||
val moodId = reference("mood_id", MoodsTable.id, onDelete = ReferenceOption.CASCADE)
|
||||
val nextPosition = integer("next_position").default(0)
|
||||
val createdAt = varchar("created_at", 40)
|
||||
val lastSeenAt = varchar("last_seen_at", 40)
|
||||
val closedAt = varchar("closed_at", 40).nullable()
|
||||
|
||||
override val primaryKey = PrimaryKey(id)
|
||||
}
|
||||
|
||||
object SessionItemsTable : Table("playback_session_items") {
|
||||
val sessionId = reference("session_id", PlaybackSessionsTable.id, onDelete = ReferenceOption.CASCADE)
|
||||
val position = integer("position")
|
||||
val songId = reference("song_id", SongsTable.id, onDelete = ReferenceOption.CASCADE)
|
||||
val state = varchar("state", 16).default("queued")
|
||||
val queuedAt = varchar("queued_at", 40)
|
||||
val updatedAt = varchar("updated_at", 40)
|
||||
|
||||
override val primaryKey = PrimaryKey(sessionId, position)
|
||||
}
|
||||
|
||||
object SongAffinityTable : Table("song_affinity") {
|
||||
val userName = reference("user_name", UsersTable.name, onDelete = ReferenceOption.CASCADE)
|
||||
val songId = reference("song_id", SongsTable.id, onDelete = ReferenceOption.CASCADE)
|
||||
val completions = integer("completions").default(0)
|
||||
val skips = integer("skips").default(0)
|
||||
val lastEventAt = varchar("last_event_at", 40)
|
||||
|
||||
override val primaryKey = PrimaryKey(userName, songId)
|
||||
}
|
||||
|
||||
object LibraryTombstonesTable : Table("library_tombstones") {
|
||||
val entity = varchar("entity", 20)
|
||||
val entityId = varchar("entity_id", 32)
|
||||
val deletedAt = varchar("deleted_at", 40)
|
||||
|
||||
override val primaryKey = PrimaryKey(entity, entityId)
|
||||
}
|
||||
@@ -1,217 +0,0 @@
|
||||
package win.taptap.musicmanager.db
|
||||
|
||||
import java.time.Instant
|
||||
import org.jetbrains.exposed.sql.and
|
||||
import org.jetbrains.exposed.sql.deleteWhere
|
||||
import org.jetbrains.exposed.sql.insert
|
||||
import org.jetbrains.exposed.sql.selectAll
|
||||
import org.jetbrains.exposed.sql.transactions.transaction
|
||||
import org.jetbrains.exposed.sql.update
|
||||
|
||||
data class BookmarkRecord(
|
||||
val songId: String,
|
||||
val positionMs: Long,
|
||||
val updatedAt: String,
|
||||
)
|
||||
|
||||
/** Per-user state: play counts, stars, ratings and bookmarks. */
|
||||
object UserStateRepository {
|
||||
|
||||
fun scrobble(userName: String, songId: String, submission: Boolean) {
|
||||
if (!submission) return
|
||||
val now = Instant.now().toString()
|
||||
|
||||
transaction {
|
||||
val existing = UserSongStateTable.selectAll()
|
||||
.where {
|
||||
(UserSongStateTable.userName eq userName) and
|
||||
(UserSongStateTable.songId eq songId)
|
||||
}
|
||||
.singleOrNull()
|
||||
|
||||
if (existing == null) {
|
||||
UserSongStateTable.insert {
|
||||
it[UserSongStateTable.userName] = userName
|
||||
it[UserSongStateTable.songId] = songId
|
||||
it[playCount] = 1
|
||||
it[lastPlayedAt] = now
|
||||
}
|
||||
} else {
|
||||
UserSongStateTable.update({
|
||||
(UserSongStateTable.userName eq userName) and
|
||||
(UserSongStateTable.songId eq songId)
|
||||
}) {
|
||||
it[playCount] = existing[UserSongStateTable.playCount] + 1
|
||||
it[lastPlayedAt] = now
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun setSongRating(userName: String, songId: String, rating: Int?) {
|
||||
transaction {
|
||||
val existing = UserSongStateTable.selectAll()
|
||||
.where {
|
||||
(UserSongStateTable.userName eq userName) and
|
||||
(UserSongStateTable.songId eq songId)
|
||||
}
|
||||
.singleOrNull()
|
||||
|
||||
if (existing == null) {
|
||||
UserSongStateTable.insert {
|
||||
it[UserSongStateTable.userName] = userName
|
||||
it[UserSongStateTable.songId] = songId
|
||||
it[UserSongStateTable.rating] = rating
|
||||
}
|
||||
} else {
|
||||
UserSongStateTable.update({
|
||||
(UserSongStateTable.userName eq userName) and
|
||||
(UserSongStateTable.songId eq songId)
|
||||
}) {
|
||||
it[UserSongStateTable.rating] = rating
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun setItemRating(userName: String, itemType: String, itemId: String, rating: Int?) {
|
||||
transaction {
|
||||
val existing = UserStarsTable.selectAll()
|
||||
.where {
|
||||
(UserStarsTable.userName eq userName) and
|
||||
(UserStarsTable.itemType eq itemType) and
|
||||
(UserStarsTable.itemId eq itemId)
|
||||
}
|
||||
.singleOrNull()
|
||||
|
||||
if (existing == null) {
|
||||
UserStarsTable.insert {
|
||||
it[UserStarsTable.userName] = userName
|
||||
it[UserStarsTable.itemType] = itemType
|
||||
it[UserStarsTable.itemId] = itemId
|
||||
it[starredAt] = ""
|
||||
it[UserStarsTable.rating] = rating
|
||||
}
|
||||
} else {
|
||||
UserStarsTable.update({
|
||||
(UserStarsTable.userName eq userName) and
|
||||
(UserStarsTable.itemType eq itemType) and
|
||||
(UserStarsTable.itemId eq itemId)
|
||||
}) {
|
||||
it[UserStarsTable.rating] = rating
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun starSong(userName: String, songId: String) {
|
||||
val now = Instant.now().toString()
|
||||
transaction {
|
||||
val existing = UserSongStateTable.selectAll()
|
||||
.where {
|
||||
(UserSongStateTable.userName eq userName) and
|
||||
(UserSongStateTable.songId eq songId)
|
||||
}
|
||||
.singleOrNull()
|
||||
|
||||
if (existing == null) {
|
||||
UserSongStateTable.insert {
|
||||
it[UserSongStateTable.userName] = userName
|
||||
it[UserSongStateTable.songId] = songId
|
||||
it[starredAt] = now
|
||||
}
|
||||
} else {
|
||||
UserSongStateTable.update({
|
||||
(UserSongStateTable.userName eq userName) and
|
||||
(UserSongStateTable.songId eq songId)
|
||||
}) {
|
||||
it[starredAt] = now
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun unstarSong(userName: String, songId: String) {
|
||||
transaction {
|
||||
UserSongStateTable.update({
|
||||
(UserSongStateTable.userName eq userName) and
|
||||
(UserSongStateTable.songId eq songId)
|
||||
}) {
|
||||
it[starredAt] = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun starItem(userName: String, itemType: String, itemId: String) {
|
||||
val now = Instant.now().toString()
|
||||
transaction {
|
||||
UserStarsTable.deleteWhere {
|
||||
it.run {
|
||||
(UserStarsTable.userName eq userName) and
|
||||
(UserStarsTable.itemType eq itemType) and
|
||||
(UserStarsTable.itemId eq itemId)
|
||||
}
|
||||
}
|
||||
UserStarsTable.insert {
|
||||
it[UserStarsTable.userName] = userName
|
||||
it[UserStarsTable.itemType] = itemType
|
||||
it[UserStarsTable.itemId] = itemId
|
||||
it[starredAt] = now
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun unstarItem(userName: String, itemType: String, itemId: String) {
|
||||
transaction {
|
||||
UserStarsTable.deleteWhere {
|
||||
it.run {
|
||||
(UserStarsTable.userName eq userName) and
|
||||
(UserStarsTable.itemType eq itemType) and
|
||||
(UserStarsTable.itemId eq itemId)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun createBookmark(userName: String, songId: String, positionMs: Long) {
|
||||
val now = Instant.now().toString()
|
||||
transaction {
|
||||
BookmarksTable.deleteWhere {
|
||||
it.run {
|
||||
(BookmarksTable.userName eq userName) and
|
||||
(BookmarksTable.songId eq songId)
|
||||
}
|
||||
}
|
||||
BookmarksTable.insert {
|
||||
it[BookmarksTable.userName] = userName
|
||||
it[BookmarksTable.songId] = songId
|
||||
it[BookmarksTable.positionMs] = positionMs
|
||||
it[updatedAt] = now
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteBookmark(userName: String, songId: String) {
|
||||
transaction {
|
||||
BookmarksTable.deleteWhere {
|
||||
it.run {
|
||||
(BookmarksTable.userName eq userName) and
|
||||
(BookmarksTable.songId eq songId)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun bookmarks(userName: String): List<BookmarkRecord> = transaction {
|
||||
BookmarksTable.selectAll()
|
||||
.where { BookmarksTable.userName eq userName }
|
||||
.orderBy(BookmarksTable.updatedAt to org.jetbrains.exposed.sql.SortOrder.DESC)
|
||||
.map {
|
||||
BookmarkRecord(
|
||||
songId = it[BookmarksTable.songId],
|
||||
positionMs = it[BookmarksTable.positionMs],
|
||||
updatedAt = it[BookmarksTable.updatedAt],
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,145 +0,0 @@
|
||||
package win.taptap.musicmanager.mood
|
||||
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.random.Random
|
||||
import org.slf4j.LoggerFactory
|
||||
import win.taptap.musicmanager.config.FolderType
|
||||
import win.taptap.musicmanager.config.LibraryConfig
|
||||
import win.taptap.musicmanager.config.UserAccount
|
||||
import win.taptap.musicmanager.db.LibraryRepository
|
||||
import win.taptap.musicmanager.db.MoodRecord
|
||||
import win.taptap.musicmanager.db.MoodRepository
|
||||
import win.taptap.musicmanager.db.PlaylistRepository
|
||||
import win.taptap.musicmanager.db.SongRecord
|
||||
|
||||
data class MoodGenerationStats(
|
||||
val seedCount: Int,
|
||||
val relatedCount: Int,
|
||||
val totalCount: Int,
|
||||
val targetSize: Int,
|
||||
)
|
||||
|
||||
/**
|
||||
* Builds the materialized mood playlist.
|
||||
*
|
||||
* Phase 1 has no YT source: the mix is the curated seeds plus related music from
|
||||
* the owner's own music folders. `yt_slots` is stored but only used once the
|
||||
* recommendation phase lands.
|
||||
*/
|
||||
class MoodMixService {
|
||||
|
||||
private val log = LoggerFactory.getLogger(MoodMixService::class.java)
|
||||
|
||||
fun generate(mood: MoodRecord, user: UserAccount, library: LibraryConfig): MoodGenerationStats {
|
||||
val folders = musicFolderIds(user, library)
|
||||
val seedIds = MoodRepository.seedSongIds(mood.playlistId)
|
||||
val seeds = LibraryRepository.songsByIds(seedIds, folders, user.name)
|
||||
|
||||
val seedGenres = (seeds.flatMap { it.genres } + mood.genres)
|
||||
.distinctBy { it.lowercase() }
|
||||
val seedArtistIds = seeds.mapNotNull { it.artistId }.distinct()
|
||||
val seedAlbumIds = seeds.map { it.albumId }.toSet()
|
||||
val query = mood.query?.trim()?.takeIf { it.isNotEmpty() }
|
||||
|
||||
val related = LinkedHashMap<String, SongRecord>()
|
||||
if (mood.expandRelated) {
|
||||
if (seedGenres.isNotEmpty()) {
|
||||
LibraryRepository.songsByGenres(seedGenres, RELATED_LIMIT, folders, user.name)
|
||||
.forEach { related[it.id] = it }
|
||||
}
|
||||
if (seedArtistIds.isNotEmpty()) {
|
||||
LibraryRepository.songsByArtists(seedArtistIds, RELATED_LIMIT, folders, user.name)
|
||||
.forEach { related[it.id] = it }
|
||||
}
|
||||
if (query != null) {
|
||||
LibraryRepository.searchSongs(query, RELATED_LIMIT, 0, folders, user.name)
|
||||
.forEach { related[it.id] = it }
|
||||
}
|
||||
}
|
||||
|
||||
val seedIdSet = seeds.map { it.id }.toSet()
|
||||
related.keys.removeAll(seedIdSet)
|
||||
|
||||
val random = Random(mood.playlistId.hashCode().toLong() * 31 + mood.generation)
|
||||
val ranked = related.values
|
||||
.shuffled(random)
|
||||
.sortedByDescending { song ->
|
||||
score(song, seedGenres, seedArtistIds, seedAlbumIds, query)
|
||||
}
|
||||
|
||||
val target = max(mood.targetSize, seeds.size).coerceIn(1, MAX_TARGET)
|
||||
val selected = LinkedHashMap<String, SongRecord>()
|
||||
seeds.forEach { selected[it.id] = it }
|
||||
ranked.forEach { song ->
|
||||
if (selected.size < target) selected[song.id] = song
|
||||
}
|
||||
|
||||
// Keep the playlist useful when a mood has only a few seeds or a narrow genre.
|
||||
val hasSignal = seeds.isNotEmpty() || seedGenres.isNotEmpty() || query != null
|
||||
if (mood.expandRelated && hasSignal && selected.size < target) {
|
||||
val fillers = LibraryRepository.randomSongs(
|
||||
size = (target - selected.size) * 3,
|
||||
genre = null,
|
||||
fromYear = null,
|
||||
toYear = null,
|
||||
folderIds = folders,
|
||||
userName = user.name,
|
||||
)
|
||||
fillers.forEach { song ->
|
||||
if (selected.size < target) selected.putIfAbsent(song.id, song)
|
||||
}
|
||||
}
|
||||
|
||||
PlaylistRepository.replaceSongs(mood.playlistId, selected.keys.toList(), user.name)
|
||||
MoodRepository.markGenerated(mood.playlistId, mood.generation + 1, null)
|
||||
|
||||
val stats = MoodGenerationStats(
|
||||
seedCount = seeds.size,
|
||||
relatedCount = selected.size - seeds.size,
|
||||
totalCount = selected.size,
|
||||
targetSize = target,
|
||||
)
|
||||
log.info(
|
||||
"Mood {} generated: {} seeds, {} related, {} total (target {})",
|
||||
mood.name,
|
||||
stats.seedCount,
|
||||
stats.relatedCount,
|
||||
stats.totalCount,
|
||||
stats.targetSize,
|
||||
)
|
||||
return stats
|
||||
}
|
||||
|
||||
private fun score(
|
||||
song: SongRecord,
|
||||
seedGenres: List<String>,
|
||||
seedArtistIds: List<String>,
|
||||
seedAlbumIds: Set<String>,
|
||||
query: String?,
|
||||
): Double {
|
||||
var score = 0.0
|
||||
if (song.artistId != null && song.artistId in seedArtistIds) score += 6.0
|
||||
if (song.albumId in seedAlbumIds) score += 3.0
|
||||
score += song.genres.count { candidate ->
|
||||
seedGenres.any { it.equals(candidate, ignoreCase = true) }
|
||||
} * 2.0
|
||||
if (song.starredAt != null) score += 1.0
|
||||
score += min(song.playCount, 20) * 0.05
|
||||
if (query != null && song.title.contains(query, ignoreCase = true)) score += 2.0
|
||||
return score
|
||||
}
|
||||
|
||||
/** Long-form folders are deliberately excluded, even when the user can see them. */
|
||||
private fun musicFolderIds(user: UserAccount, library: LibraryConfig): Set<Int> =
|
||||
library.folders
|
||||
.asSequence()
|
||||
.filter { it.type == FolderType.MUSIC && it.id in user.folders }
|
||||
.map { it.id }
|
||||
.toSet()
|
||||
|
||||
private companion object {
|
||||
const val RELATED_LIMIT = 500
|
||||
const val MAX_TARGET = 500
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
package win.taptap.musicmanager.mood
|
||||
|
||||
import win.taptap.musicmanager.db.MoodRepository
|
||||
|
||||
/**
|
||||
* Translates a Symfonium star into a permanent mood seed.
|
||||
*
|
||||
* If a mood session is active, the like belongs to that mood, even when the song
|
||||
* is not in the current mix. Otherwise the song is pinned to every mood that
|
||||
* already contains it, which is a no-op for rotation except that it becomes an
|
||||
* anchor. Manual and promoted seeds are never removed by an unstar.
|
||||
*/
|
||||
object MoodPins {
|
||||
|
||||
fun onStar(userName: String, songId: String) {
|
||||
targets(userName, songId).forEach { playlistId ->
|
||||
if (MoodRepository.addSeed(playlistId, userName, songId, "star")) {
|
||||
MoodRepository.markStale(playlistId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun onUnstar(userName: String, songId: String) {
|
||||
targets(userName, songId).forEach { playlistId ->
|
||||
if (MoodRepository.removeSeed(playlistId, userName, songId, origin = "star")) {
|
||||
MoodRepository.markStale(playlistId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun targets(userName: String, songId: String): List<String> {
|
||||
val active = MoodSessionTracker.active(userName)
|
||||
if (active != null && MoodRepository.get(active, userName) != null) {
|
||||
return listOf(active)
|
||||
}
|
||||
return MoodRepository.moodsContainingSong(userName, songId)
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
package win.taptap.musicmanager.mood
|
||||
|
||||
import java.time.Instant
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.launch
|
||||
import org.slf4j.LoggerFactory
|
||||
import win.taptap.musicmanager.config.LibraryConfig
|
||||
import win.taptap.musicmanager.config.UserAccount
|
||||
import win.taptap.musicmanager.db.MoodRecord
|
||||
import win.taptap.musicmanager.db.MoodRepository
|
||||
|
||||
/**
|
||||
* Owns stale checks and serializes generation per mood. Background refreshes keep
|
||||
* `getPlaylist` fast; an explicit refresh is synchronous for the management UI.
|
||||
*/
|
||||
class MoodService(
|
||||
private val scope: CoroutineScope,
|
||||
private val mixService: MoodMixService = MoodMixService(),
|
||||
) {
|
||||
|
||||
private val log = LoggerFactory.getLogger(MoodService::class.java)
|
||||
private val locks = ConcurrentHashMap<String, Any>()
|
||||
private val running = ConcurrentHashMap.newKeySet<String>()
|
||||
|
||||
fun isStale(mood: MoodRecord): Boolean {
|
||||
val generated = mood.generatedAt?.let { runCatching { Instant.parse(it) }.getOrNull() }
|
||||
?: return true
|
||||
return generated.plusSeconds(mood.refreshHours * 3600L).isBefore(Instant.now())
|
||||
}
|
||||
|
||||
/** Starts one background generation when the mix is older than its TTL. */
|
||||
fun refreshIfStale(mood: MoodRecord, user: UserAccount, library: LibraryConfig) {
|
||||
if (!isStale(mood)) return
|
||||
if (!running.add(mood.playlistId)) return
|
||||
scope.launch {
|
||||
try {
|
||||
generateLocked(mood.playlistId, user, library)
|
||||
} catch (t: Throwable) {
|
||||
log.error("Background mood refresh failed for ${mood.name}", t)
|
||||
} finally {
|
||||
running.remove(mood.playlistId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Synchronous generation used by create, update, seed changes and refreshMood. */
|
||||
fun refreshNow(mood: MoodRecord, user: UserAccount, library: LibraryConfig): MoodGenerationStats =
|
||||
generateLocked(mood.playlistId, user, library)
|
||||
|
||||
private fun generateLocked(
|
||||
playlistId: String,
|
||||
user: UserAccount,
|
||||
library: LibraryConfig,
|
||||
): MoodGenerationStats = synchronized(locks.computeIfAbsent(playlistId) { Any() }) {
|
||||
val mood = MoodRepository.get(playlistId, user.name)
|
||||
?: error("Mood not found: $playlistId")
|
||||
|
||||
try {
|
||||
mixService.generate(mood, user, library)
|
||||
} catch (t: Throwable) {
|
||||
MoodRepository.markError(playlistId, t.message ?: t::class.simpleName.orEmpty())
|
||||
throw t
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
package win.taptap.musicmanager.mood
|
||||
|
||||
import java.time.Duration
|
||||
import java.time.Instant
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
/**
|
||||
* Symfonium's star request does not carry the playlist it was invoked from.
|
||||
* Opening a mood marks it active, so a like can be attributed to that mood.
|
||||
* The fallback in [MoodPins] handles queued/offline stars without a session.
|
||||
*/
|
||||
object MoodSessionTracker {
|
||||
|
||||
private val ttl: Duration = Duration.ofHours(4)
|
||||
private val sessions = ConcurrentHashMap<String, Session>()
|
||||
|
||||
private data class Session(val playlistId: String, val seenAt: Instant)
|
||||
|
||||
fun activate(userName: String, playlistId: String) {
|
||||
sessions[userName] = Session(playlistId, Instant.now())
|
||||
}
|
||||
|
||||
fun clear(userName: String) {
|
||||
sessions.remove(userName)
|
||||
}
|
||||
|
||||
fun touch(userName: String) {
|
||||
sessions.computeIfPresent(userName) { _, session ->
|
||||
if (session.seenAt.plus(ttl).isBefore(Instant.now())) {
|
||||
null
|
||||
} else {
|
||||
session.copy(seenAt = Instant.now())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun active(userName: String): String? {
|
||||
val session = sessions[userName] ?: return null
|
||||
if (session.seenAt.plus(ttl).isBefore(Instant.now())) {
|
||||
sessions.remove(userName)
|
||||
return null
|
||||
}
|
||||
return session.playlistId
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package win.taptap.musicmanager.radio
|
||||
|
||||
import java.util.UUID
|
||||
import kotlin.math.max
|
||||
import kotlin.random.Random
|
||||
import org.slf4j.LoggerFactory
|
||||
import win.taptap.musicmanager.api.musicFolderIds
|
||||
import win.taptap.musicmanager.config.LibraryConfig
|
||||
import win.taptap.musicmanager.config.UserAccount
|
||||
import win.taptap.musicmanager.db.LibraryRepository
|
||||
import win.taptap.musicmanager.db.MoodRecord
|
||||
import win.taptap.musicmanager.db.MoodRepository
|
||||
import win.taptap.musicmanager.db.PlaybackSessionRecord
|
||||
import win.taptap.musicmanager.db.RadioRepository
|
||||
import win.taptap.musicmanager.db.SongRecord
|
||||
|
||||
data class StartedSession(
|
||||
val session: PlaybackSessionRecord,
|
||||
val songs: List<SongRecord>,
|
||||
)
|
||||
|
||||
/**
|
||||
* Server-driven mood radio.
|
||||
*
|
||||
* A batch is a weighted sample of the mood's world: seeds are guaranteed
|
||||
* candidates, related genres/artists and free-text matches shape the pool, and
|
||||
* per-user completions/skips nudge the ranking. Tracks already queued in the
|
||||
* session are never repeated. The client asks for more whenever its buffer is
|
||||
* low, so the queue is always generated with the latest signals.
|
||||
*/
|
||||
class RadioService {
|
||||
|
||||
private val log = LoggerFactory.getLogger(RadioService::class.java)
|
||||
private val random = Random.Default
|
||||
|
||||
fun start(
|
||||
mood: MoodRecord,
|
||||
user: UserAccount,
|
||||
library: LibraryConfig,
|
||||
limit: Int,
|
||||
): StartedSession {
|
||||
val session = RadioRepository.createSession(user.name, mood.id, UUID.randomUUID().toString())
|
||||
val songs = generate(mood, user, library, session.id, emptySet(), limit, persist = true)
|
||||
log.info("Radio session {} started for mood {} with {} tracks", session.id, mood.name, songs.size)
|
||||
return StartedSession(session, songs)
|
||||
}
|
||||
|
||||
fun next(
|
||||
mood: MoodRecord,
|
||||
user: UserAccount,
|
||||
library: LibraryConfig,
|
||||
sessionId: String,
|
||||
excluded: Set<String>,
|
||||
limit: Int,
|
||||
): List<SongRecord> =
|
||||
generate(mood, user, library, sessionId, excluded, limit, persist = true)
|
||||
|
||||
/** Queue preview for the mood screen; nothing is persisted. */
|
||||
fun preview(
|
||||
mood: MoodRecord,
|
||||
user: UserAccount,
|
||||
library: LibraryConfig,
|
||||
limit: Int,
|
||||
): List<SongRecord> =
|
||||
generate(mood, user, library, sessionId = null, excluded = emptySet(), limit, persist = false)
|
||||
|
||||
private fun generate(
|
||||
mood: MoodRecord,
|
||||
user: UserAccount,
|
||||
library: LibraryConfig,
|
||||
sessionId: String?,
|
||||
excluded: Set<String>,
|
||||
requestedLimit: Int,
|
||||
persist: Boolean,
|
||||
): List<SongRecord> {
|
||||
val limit = requestedLimit.coerceIn(1, 50)
|
||||
val folders = user.musicFolderIds(library)
|
||||
if (folders.isEmpty()) return emptyList()
|
||||
|
||||
val sessionSongs = if (sessionId != null && persist) {
|
||||
RadioRepository.queuedSongIds(sessionId)
|
||||
} else {
|
||||
emptySet()
|
||||
}
|
||||
val skip = sessionSongs + excluded
|
||||
|
||||
val seeds = LibraryRepository.songsByIds(
|
||||
MoodRepository.seedSongIds(mood.id),
|
||||
folders,
|
||||
user.name,
|
||||
)
|
||||
val seedIds = seeds.map { it.id }.toSet()
|
||||
val seedGenres = (seeds.flatMap { it.genres } + mood.genres)
|
||||
.map { it.trim() }
|
||||
.filter { it.isNotEmpty() }
|
||||
.distinctBy { it.lowercase() }
|
||||
val seedArtistIds = seeds.mapNotNull { it.artistId }.distinct()
|
||||
val query = mood.query?.trim()?.takeIf { it.isNotEmpty() }
|
||||
|
||||
val candidates = LinkedHashMap<String, SongRecord>()
|
||||
seeds.forEach { candidates[it.id] = it }
|
||||
if (seedGenres.isNotEmpty()) {
|
||||
LibraryRepository.songsByGenres(seedGenres, POOL_LIMIT, folders, user.name)
|
||||
.forEach { candidates[it.id] = it }
|
||||
}
|
||||
if (seedArtistIds.isNotEmpty()) {
|
||||
LibraryRepository.songsByArtists(seedArtistIds, POOL_LIMIT, folders, user.name)
|
||||
.forEach { candidates[it.id] = it }
|
||||
}
|
||||
if (query != null) {
|
||||
LibraryRepository.searchSongs(query, POOL_LIMIT, 0, folders, user.name)
|
||||
.forEach { candidates[it.id] = it }
|
||||
}
|
||||
// A mood with no seeds and no filters still needs a starting point.
|
||||
LibraryRepository.randomSongs(
|
||||
size = POOL_LIMIT,
|
||||
genre = null,
|
||||
fromYear = null,
|
||||
toYear = null,
|
||||
folderIds = folders,
|
||||
userName = user.name,
|
||||
).forEach { candidates[it.id] = it }
|
||||
|
||||
candidates.keys.removeAll(skip)
|
||||
|
||||
// When a session has already heard the whole mood, allow controlled replay
|
||||
// instead of ending with silence.
|
||||
if (candidates.size < limit) {
|
||||
LibraryRepository.randomSongs(
|
||||
size = max(limit * 10, 200),
|
||||
genre = null,
|
||||
fromYear = null,
|
||||
toYear = null,
|
||||
folderIds = folders,
|
||||
userName = user.name,
|
||||
).forEach { song ->
|
||||
if (song.id !in skip || sessionSongs.size > 200) {
|
||||
candidates.putIfAbsent(song.id, song)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val affinity = RadioRepository.affinity(user.name, candidates.keys)
|
||||
val scored = candidates.values.map { song ->
|
||||
song to score(
|
||||
song = song,
|
||||
seedIds = seedIds,
|
||||
seedGenres = seedGenres,
|
||||
seedArtistIds = seedArtistIds,
|
||||
query = query,
|
||||
affinity = affinity[song.id]?.score ?: 0.0,
|
||||
)
|
||||
}
|
||||
|
||||
val picks = pickDiverse(scored, limit)
|
||||
if (persist && sessionId != null && picks.isNotEmpty()) {
|
||||
RadioRepository.append(sessionId, picks.map { it.id })
|
||||
}
|
||||
return picks
|
||||
}
|
||||
|
||||
private fun score(
|
||||
song: SongRecord,
|
||||
seedIds: Set<String>,
|
||||
seedGenres: List<String>,
|
||||
seedArtistIds: List<String>,
|
||||
query: String?,
|
||||
affinity: Double,
|
||||
): Double {
|
||||
var score = random.nextDouble(0.0, 2.0)
|
||||
if (song.id in seedIds) score += 10.0
|
||||
if (song.artistId != null && song.artistId in seedArtistIds) score += 3.0
|
||||
score += song.genres.count { candidate ->
|
||||
seedGenres.any { it.equals(candidate, ignoreCase = true) }
|
||||
} * 1.5
|
||||
if (query != null && song.title.contains(query, ignoreCase = true)) score += 2.0
|
||||
score += affinity.coerceIn(-6.0, 6.0)
|
||||
return score
|
||||
}
|
||||
|
||||
/**
|
||||
* Picks the best remaining candidate, preferring a different artist than the
|
||||
* previous track so a batch does not become one album on repeat.
|
||||
*/
|
||||
private fun pickDiverse(
|
||||
scored: List<Pair<SongRecord, Double>>,
|
||||
limit: Int,
|
||||
): List<SongRecord> {
|
||||
val remaining = scored
|
||||
.sortedWith(compareByDescending<Pair<SongRecord, Double>> { it.second })
|
||||
.toMutableList()
|
||||
val picked = ArrayList<SongRecord>(limit)
|
||||
var lastArtist: String? = null
|
||||
|
||||
while (picked.size < limit && remaining.isNotEmpty()) {
|
||||
val different = remaining.indexOfFirst { it.first.displayArtist != lastArtist }
|
||||
val index = if (different >= 0) different else 0
|
||||
val song = remaining.removeAt(index).first
|
||||
picked += song
|
||||
lastArtist = song.displayArtist
|
||||
}
|
||||
return picked
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val POOL_LIMIT = 400
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
package win.taptap.musicmanager.subsonic
|
||||
|
||||
import java.time.Instant
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
data class PlayQueueState(
|
||||
val songIds: List<String>,
|
||||
val currentIndex: Int,
|
||||
val positionMs: Long,
|
||||
val changed: String,
|
||||
val changedBy: String,
|
||||
)
|
||||
|
||||
/**
|
||||
* Server-side play queue per user. Kept in memory: losing it on restart only means
|
||||
* clients restore their local queue instead, which is acceptable for the MVP.
|
||||
*/
|
||||
object PlayQueueStore {
|
||||
|
||||
private val queues = ConcurrentHashMap<String, PlayQueueState>()
|
||||
|
||||
fun save(userName: String, songIds: List<String>, currentIndex: Int, positionMs: Long) {
|
||||
queues[userName] = PlayQueueState(
|
||||
songIds = songIds,
|
||||
currentIndex = currentIndex.coerceIn(0, (songIds.size - 1).coerceAtLeast(0)),
|
||||
positionMs = positionMs.coerceAtLeast(0),
|
||||
changed = Instant.now().toString(),
|
||||
changedBy = userName,
|
||||
)
|
||||
}
|
||||
|
||||
fun get(userName: String): PlayQueueState? = queues[userName]
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
package win.taptap.musicmanager.subsonic
|
||||
|
||||
import io.ktor.http.Parameters
|
||||
import java.security.MessageDigest
|
||||
import win.taptap.musicmanager.config.UserAccount
|
||||
import win.taptap.musicmanager.config.UsersConfig
|
||||
|
||||
/**
|
||||
* Subsonic authentication.
|
||||
*
|
||||
* Token auth is `md5(password + salt)`; password auth accepts plaintext or the
|
||||
* `enc:` hex encoding. The server therefore needs the plaintext password in memory,
|
||||
* but never persists it.
|
||||
*/
|
||||
class SubsonicAuthenticator(private val users: UsersConfig) {
|
||||
|
||||
fun authenticate(parameters: Parameters): UserAccount? {
|
||||
val userName = parameters["u"] ?: return null
|
||||
val user = users.byName(userName) ?: return null
|
||||
|
||||
val token = parameters["t"]
|
||||
val salt = parameters["s"]
|
||||
if (!token.isNullOrEmpty() && !salt.isNullOrEmpty()) {
|
||||
return if (constantTimeEquals(token, md5Hex(user.password + salt))) user else null
|
||||
}
|
||||
|
||||
val password = parameters["p"] ?: return null
|
||||
val candidate = if (password.startsWith("enc:")) {
|
||||
hexToBytes(password.removePrefix("enc:"))?.toString(Charsets.UTF_8) ?: return null
|
||||
} else {
|
||||
password
|
||||
}
|
||||
|
||||
return if (constantTimeEquals(candidate, user.password)) user else null
|
||||
}
|
||||
|
||||
private fun constantTimeEquals(left: String, right: String): Boolean =
|
||||
MessageDigest.isEqual(left.toByteArray(Charsets.UTF_8), right.toByteArray(Charsets.UTF_8))
|
||||
|
||||
private fun hexToBytes(hex: String): ByteArray? {
|
||||
if (hex.length % 2 != 0) return null
|
||||
return try {
|
||||
ByteArray(hex.length / 2) { index ->
|
||||
hex.substring(index * 2, index * 2 + 2).toInt(16).toByte()
|
||||
}
|
||||
} catch (_: NumberFormatException) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun md5Hex(value: String): String {
|
||||
val digest = MessageDigest.getInstance("MD5").digest(value.toByteArray(Charsets.UTF_8))
|
||||
return digest.joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
package win.taptap.musicmanager.subsonic
|
||||
|
||||
import io.ktor.server.application.ApplicationCall
|
||||
import io.ktor.server.response.respond
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.put
|
||||
|
||||
/**
|
||||
* The OpenSubsonic JSON envelope. Every endpoint, including errors, responds with
|
||||
* HTTP 200 and this root object.
|
||||
*/
|
||||
object SubsonicEnvelope {
|
||||
|
||||
const val API_VERSION = "1.16.1"
|
||||
const val SERVER_TYPE = "musicmanager"
|
||||
const val SERVER_VERSION = "0.1.0"
|
||||
|
||||
fun ok(payload: JsonObject = JsonObject(emptyMap())): JsonObject = buildJsonObject {
|
||||
put("subsonic-response", buildJsonObject {
|
||||
put("status", "ok")
|
||||
put("version", API_VERSION)
|
||||
put("type", SERVER_TYPE)
|
||||
put("serverVersion", SERVER_VERSION)
|
||||
put("openSubsonic", true)
|
||||
payload.forEach { (key, value) -> put(key, value) }
|
||||
})
|
||||
}
|
||||
|
||||
fun error(code: Int, message: String): JsonObject = buildJsonObject {
|
||||
put("subsonic-response", buildJsonObject {
|
||||
put("status", "failed")
|
||||
put("version", API_VERSION)
|
||||
put("type", SERVER_TYPE)
|
||||
put("serverVersion", SERVER_VERSION)
|
||||
put("openSubsonic", true)
|
||||
put("error", buildJsonObject {
|
||||
put("code", code)
|
||||
put("message", message)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun ApplicationCall.respondSubsonic(payload: JsonObject = JsonObject(emptyMap())) {
|
||||
respond(SubsonicEnvelope.ok(payload))
|
||||
}
|
||||
|
||||
suspend fun ApplicationCall.respondSubsonicError(code: Int, message: String) {
|
||||
respond(SubsonicEnvelope.error(code, message))
|
||||
}
|
||||
@@ -1,172 +0,0 @@
|
||||
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.GenreRecord
|
||||
import win.taptap.musicmanager.db.MoodRecord
|
||||
import win.taptap.musicmanager.db.PlaylistRecord
|
||||
import win.taptap.musicmanager.db.SongRecord
|
||||
import win.taptap.musicmanager.util.IdGenerator
|
||||
|
||||
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.lastPlayedAt?.let { put("played", it) }
|
||||
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)) }
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun playlistJson(playlist: PlaylistRecord, songs: List<SongRecord>? = null): JsonObject = buildJsonObject {
|
||||
put("id", playlist.id)
|
||||
put("name", playlist.name)
|
||||
playlist.comment?.let { put("comment", it) }
|
||||
put("owner", playlist.owner)
|
||||
put("public", playlist.isPublic)
|
||||
put("songCount", playlist.songCount)
|
||||
put("duration", playlist.duration)
|
||||
put("created", playlist.created)
|
||||
put("changed", playlist.changed)
|
||||
|
||||
songs?.let { list ->
|
||||
put("entry", buildJsonArray { list.forEach { add(songJson(it)) } })
|
||||
}
|
||||
}
|
||||
|
||||
fun moodJson(
|
||||
mood: MoodRecord,
|
||||
seeds: List<SongRecord>? = null,
|
||||
songs: List<SongRecord>? = null,
|
||||
): JsonObject = buildJsonObject {
|
||||
put("id", mood.playlistId)
|
||||
put("name", mood.name)
|
||||
mood.comment?.let { put("comment", it) }
|
||||
mood.query?.let { put("query", it) }
|
||||
put("genres", stringArray(mood.genres))
|
||||
put("targetSize", mood.targetSize)
|
||||
put("ytSlots", mood.ytSlots)
|
||||
put("expandRelated", mood.expandRelated)
|
||||
put("refreshHours", mood.refreshHours)
|
||||
mood.generatedAt?.let { put("generatedAt", it) }
|
||||
put("generation", mood.generation)
|
||||
mood.lastError?.let { put("lastError", it) }
|
||||
put("seedCount", mood.seedCount)
|
||||
put("songCount", mood.songCount)
|
||||
put("duration", mood.duration)
|
||||
put("created", mood.created)
|
||||
put("changed", mood.changed)
|
||||
put("owner", mood.owner)
|
||||
|
||||
seeds?.let { list ->
|
||||
put("seed", buildJsonArray { list.forEach { add(songJson(it)) } })
|
||||
}
|
||||
songs?.let { list ->
|
||||
put("entry", buildJsonArray { list.forEach { add(songJson(it)) } })
|
||||
}
|
||||
}
|
||||
|
||||
fun genreJson(genre: GenreRecord): JsonObject = buildJsonObject {
|
||||
put("value", genre.value)
|
||||
put("songCount", genre.songCount)
|
||||
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 "#"
|
||||
}
|
||||
|
||||
private fun stringArray(values: List<String>): JsonArray = buildJsonArray {
|
||||
values.forEach { add(JsonPrimitive(it)) }
|
||||
}
|
||||
@@ -1,443 +0,0 @@
|
||||
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.AlbumRecord
|
||||
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.genreJson
|
||||
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) {
|
||||
|
||||
subsonicEndpoint(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)
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
subsonicEndpoint(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))
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
subsonicEndpoint(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))
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/getArtist") { call, user ->
|
||||
val id = call.subsonicParams()["id"]
|
||||
if (id.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val folders = user.visibleFolderIds(library)
|
||||
val artist = LibraryRepository.artist(id, folders, user.name)
|
||||
if (artist == null) {
|
||||
call.respondSubsonicError(70, "Artist not found")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val albums = LibraryRepository.albumsForArtist(id, folders, user.name)
|
||||
call.respondSubsonic(buildJsonObject { put("artist", artistJson(artist, albums)) })
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/getAlbum") { call, user ->
|
||||
val id = call.subsonicParams()["id"]
|
||||
if (id.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val folders = user.visibleFolderIds(library)
|
||||
val album = LibraryRepository.album(id, folders, user.name)
|
||||
if (album == null) {
|
||||
call.respondSubsonicError(70, "Album not found")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val songs = LibraryRepository.albumSongs(id, folders, user.name)
|
||||
call.respondSubsonic(buildJsonObject { put("album", albumJson(album, songs)) })
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/getSong") { call, user ->
|
||||
val id = call.subsonicParams()["id"]
|
||||
if (id.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val song = LibraryRepository.song(id, user.visibleFolderIds(library), user.name)
|
||||
if (song == null) {
|
||||
call.respondSubsonicError(70, "Song not found")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
call.respondSubsonic(buildJsonObject { put("song", songJson(song)) })
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/getMusicDirectory") { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val id = parameters["id"]
|
||||
if (id.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val folders = user.effectiveFolderIds(library, parameters["musicFolderId"])
|
||||
if (id.startsWith("ar-")) {
|
||||
val artist = LibraryRepository.artist(id, folders, user.name)
|
||||
if (artist == null) {
|
||||
call.respondSubsonicError(70, "Artist not found")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val albums = LibraryRepository.albumsForArtist(id, folders, user.name)
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put("directory", buildJsonObject {
|
||||
put("id", artist.id)
|
||||
put("title", artist.name)
|
||||
put("child", buildJsonArray {
|
||||
albums.forEach { add(albumDirectoryJson(it, artist.id)) }
|
||||
})
|
||||
})
|
||||
},
|
||||
)
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
if (id.startsWith("al-")) {
|
||||
val album = LibraryRepository.album(id, folders, user.name)
|
||||
if (album == null) {
|
||||
call.respondSubsonicError(70, "Album not found")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val songs = LibraryRepository.albumSongs(id, folders, user.name)
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put("directory", buildJsonObject {
|
||||
put("id", album.id)
|
||||
put("title", album.name)
|
||||
album.artistName?.let { put("artist", it) }
|
||||
album.coverArt?.let { put("coverArt", it) }
|
||||
put("child", buildJsonArray { songs.forEach { add(songJson(it)) } })
|
||||
})
|
||||
},
|
||||
)
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val folderId = id.toIntOrNull()
|
||||
if (folderId == null || folderId !in folders) {
|
||||
call.respondSubsonicError(70, "Directory not found")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val folder = library.byId(folderId) ?: run {
|
||||
call.respondSubsonicError(70, "Directory not found")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
val albums = LibraryRepository.albumList(
|
||||
type = "alphabeticalByName",
|
||||
size = 10_000,
|
||||
offset = 0,
|
||||
fromYear = null,
|
||||
toYear = null,
|
||||
genre = null,
|
||||
folderIds = setOf(folderId),
|
||||
userName = user.name,
|
||||
)
|
||||
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put("directory", buildJsonObject {
|
||||
put("id", folderId)
|
||||
put("title", folder.name)
|
||||
put("child", buildJsonArray {
|
||||
albums.forEach { add(albumDirectoryJson(it, folderId.toString())) }
|
||||
})
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
val albumListTypes = setOf(
|
||||
"newest",
|
||||
"recent",
|
||||
"frequent",
|
||||
"random",
|
||||
"alphabeticalByName",
|
||||
"alphabeticalByArtist",
|
||||
"starred",
|
||||
"byYear",
|
||||
"byGenre",
|
||||
)
|
||||
|
||||
for (endpoint in listOf("/getAlbumList2", "/getAlbumList")) {
|
||||
subsonicEndpoint(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@subsonicEndpoint
|
||||
}
|
||||
|
||||
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)) } })
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
subsonicEndpoint(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)) } })
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
subsonicEndpoint(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)) } })
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/getSongsByGenre") { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val genre = parameters["genre"]
|
||||
if (genre.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: genre")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
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")) {
|
||||
subsonicEndpoint(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")) {
|
||||
subsonicEndpoint(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")) {
|
||||
subsonicEndpoint(users, endpoint) { call, _ ->
|
||||
val key = if (endpoint == "/getAlbumInfo2") "albumInfo2" else "albumInfo"
|
||||
call.respondSubsonic(buildJsonObject { put(key, buildJsonObject { }) })
|
||||
}
|
||||
}
|
||||
|
||||
for (endpoint in listOf("/getSimilarSongs2", "/getSimilarSongs")) {
|
||||
subsonicEndpoint(users, endpoint) { call, _ ->
|
||||
val key = if (endpoint == "/getSimilarSongs2") "similarSongs2" else "similarSongs"
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put(key, buildJsonObject { put("song", buildJsonArray { }) })
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/getTopSongs") { call, _ ->
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put("topSongs", buildJsonObject { put("song", buildJsonArray { }) })
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/search3") { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val query = parameters["query"].orEmpty()
|
||||
val folders = user.effectiveFolderIds(library, parameters["musicFolderId"])
|
||||
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 albumDirectoryJson(album: AlbumRecord, parentId: String) = buildJsonObject {
|
||||
put("id", album.id)
|
||||
put("parent", parentId)
|
||||
put("title", album.name)
|
||||
put("isDir", true)
|
||||
put("album", 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("created", album.created)
|
||||
album.year?.let { put("year", it) }
|
||||
album.genres.firstOrNull()?.let { put("genre", 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)
|
||||
}
|
||||
@@ -1,264 +0,0 @@
|
||||
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.mood.MoodPins
|
||||
import win.taptap.musicmanager.mood.MoodSessionTracker
|
||||
import win.taptap.musicmanager.subsonic.models.songJson
|
||||
import win.taptap.musicmanager.subsonic.respondSubsonic
|
||||
import win.taptap.musicmanager.subsonic.respondSubsonicError
|
||||
|
||||
/** Per-user interaction: scrobbling, stars, ratings, bookmarks and lyrics. */
|
||||
fun Route.interactionRoutes(users: UsersConfig, library: LibraryConfig) {
|
||||
|
||||
subsonicEndpoint(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@subsonicEndpoint
|
||||
}
|
||||
|
||||
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@subsonicEndpoint
|
||||
}
|
||||
UserStateRepository.scrobble(user.name, id, submission)
|
||||
}
|
||||
MoodSessionTracker.touch(user.name)
|
||||
|
||||
call.respondSubsonic()
|
||||
}
|
||||
|
||||
subsonicEndpoint(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@subsonicEndpoint
|
||||
}
|
||||
|
||||
if (!validateVisible(songIds, albumIds, artistIds, folders, user.name)) {
|
||||
call.respondSubsonicError(70, "Item not found")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
songIds.forEach { songId ->
|
||||
UserStateRepository.starSong(user.name, songId)
|
||||
if (songId.startsWith("sg-")) MoodPins.onStar(user.name, songId)
|
||||
}
|
||||
albumIds.forEach { UserStateRepository.starItem(user.name, "album", it) }
|
||||
artistIds.forEach { UserStateRepository.starItem(user.name, "artist", it) }
|
||||
|
||||
call.respondSubsonic()
|
||||
}
|
||||
|
||||
subsonicEndpoint(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@subsonicEndpoint
|
||||
}
|
||||
|
||||
if (!validateVisible(songIds, albumIds, artistIds, folders, user.name)) {
|
||||
call.respondSubsonicError(70, "Item not found")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
songIds.forEach { songId ->
|
||||
UserStateRepository.unstarSong(user.name, songId)
|
||||
if (songId.startsWith("sg-")) MoodPins.onUnstar(user.name, songId)
|
||||
}
|
||||
albumIds.forEach { UserStateRepository.unstarItem(user.name, "album", it) }
|
||||
artistIds.forEach { UserStateRepository.unstarItem(user.name, "artist", it) }
|
||||
|
||||
call.respondSubsonic()
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/setRating") { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val id = parameters["id"]
|
||||
if (id.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
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@subsonicEndpoint
|
||||
}
|
||||
|
||||
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@subsonicEndpoint
|
||||
}
|
||||
UserStateRepository.setSongRating(user.name, id, storedRating)
|
||||
}
|
||||
id.startsWith("al-") -> {
|
||||
if (LibraryRepository.album(id, folders, user.name) == null) {
|
||||
call.respondSubsonicError(70, "Album not found")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
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@subsonicEndpoint
|
||||
}
|
||||
UserStateRepository.setItemRating(user.name, "artist", id, storedRating)
|
||||
}
|
||||
else -> {
|
||||
call.respondSubsonicError(70, "Item not found")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
}
|
||||
|
||||
call.respondSubsonic()
|
||||
}
|
||||
|
||||
subsonicEndpoint(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) } })
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/createBookmark") { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val id = parameters["id"]
|
||||
if (id.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val position = parameters["position"]?.toLongOrNull()
|
||||
if (position == null || position < 0) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing or invalid: position")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
if (LibraryRepository.song(id, user.effectiveFolderIds(library, parameters["musicFolderId"]), user.name) == null) {
|
||||
call.respondSubsonicError(70, "Song not found")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
UserStateRepository.createBookmark(user.name, id, position)
|
||||
call.respondSubsonic()
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/deleteBookmark") { call, user ->
|
||||
val id = call.subsonicParams()["id"]
|
||||
if (id.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
UserStateRepository.deleteBookmark(user.name, id)
|
||||
call.respondSubsonic()
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/getLyricsBySongId") { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val id = parameters["id"]
|
||||
if (id.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
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@subsonicEndpoint
|
||||
}
|
||||
|
||||
val lyrics = LibraryRepository.lyrics(id, folders)
|
||||
val lines = lyrics.orEmpty()
|
||||
.lines()
|
||||
.map { it.trim() }
|
||||
.filter { it.isNotEmpty() }
|
||||
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
if (lines.isEmpty()) {
|
||||
put("lyricsList", buildJsonObject { })
|
||||
} else {
|
||||
put("lyricsList", buildJsonObject {
|
||||
put("structuredLyrics", buildJsonArray {
|
||||
add(buildJsonObject {
|
||||
put("displayArtist", song.displayArtist)
|
||||
put("displayTitle", song.title)
|
||||
put("lang", "")
|
||||
put("synced", false)
|
||||
put("line", buildJsonArray {
|
||||
lines.forEach { line ->
|
||||
add(buildJsonObject { put("value", line) })
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun validateVisible(
|
||||
songIds: List<String>,
|
||||
albumIds: List<String>,
|
||||
artistIds: List<String>,
|
||||
folderIds: Set<Int>,
|
||||
userName: String,
|
||||
): Boolean {
|
||||
if (songIds.any { LibraryRepository.song(it, folderIds, userName) == null }) return false
|
||||
if (albumIds.any { LibraryRepository.album(it, folderIds, userName) == null }) return false
|
||||
if (artistIds.any { LibraryRepository.artist(it, folderIds, userName) == null }) return false
|
||||
return true
|
||||
}
|
||||
@@ -1,168 +0,0 @@
|
||||
package win.taptap.musicmanager.subsonic.routes
|
||||
|
||||
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.respondFile
|
||||
import io.ktor.server.response.respondOutputStream
|
||||
import io.ktor.server.routing.Route
|
||||
import java.net.URLEncoder
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.slf4j.LoggerFactory
|
||||
import win.taptap.musicmanager.config.LibraryConfig
|
||||
import win.taptap.musicmanager.config.UsersConfig
|
||||
import win.taptap.musicmanager.db.LibraryRepository
|
||||
import win.taptap.musicmanager.mood.MoodSessionTracker
|
||||
import win.taptap.musicmanager.scanner.CoverArtService
|
||||
import win.taptap.musicmanager.subsonic.respondSubsonicError
|
||||
import win.taptap.musicmanager.transcoding.FfmpegTranscoder
|
||||
|
||||
private val log = LoggerFactory.getLogger("win.taptap.musicmanager.MediaRoutes")
|
||||
|
||||
fun Route.mediaRoutes(
|
||||
users: UsersConfig,
|
||||
library: LibraryConfig,
|
||||
coverArtService: CoverArtService,
|
||||
transcoder: FfmpegTranscoder,
|
||||
) {
|
||||
|
||||
subsonicEndpoint(users, "/stream") { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val id = parameters["id"]
|
||||
if (id.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val rawMaxBitRate = parameters["maxBitRate"]
|
||||
val maxBitRate = rawMaxBitRate?.toIntOrNull()
|
||||
if (rawMaxBitRate != null && (maxBitRate == null || maxBitRate < 0)) {
|
||||
call.respondSubsonicError(10, "Invalid maxBitRate")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val rawTimeOffset = parameters["timeOffset"]
|
||||
val timeOffset = rawTimeOffset?.toIntOrNull()
|
||||
if (rawTimeOffset != null && (timeOffset == null || timeOffset < 0)) {
|
||||
call.respondSubsonicError(10, "Invalid timeOffset")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
val offset = timeOffset ?: 0
|
||||
val format = parameters["format"]
|
||||
|
||||
val resolved = LibraryRepository.resolveSong(
|
||||
id,
|
||||
user.visibleFolderIds(library),
|
||||
user.name,
|
||||
library,
|
||||
)
|
||||
if (resolved == null) {
|
||||
call.respondSubsonicError(70, "Song not found")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
MoodSessionTracker.touch(user.name)
|
||||
|
||||
if (!transcoder.shouldTranscode(resolved.song.bitRate, maxBitRate, format, offset)) {
|
||||
call.respondFile(resolved.file.toFile())
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val process = try {
|
||||
transcoder.start(resolved.file, maxBitRate, offset)
|
||||
} catch (e: Exception) {
|
||||
log.error("Failed to start ffmpeg for {}", resolved.file, e)
|
||||
call.respondSubsonicError(0, "Transcoding failed")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/download") { call, user ->
|
||||
val id = call.subsonicParams()["id"]
|
||||
if (id.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val resolved = LibraryRepository.resolveSong(
|
||||
id,
|
||||
user.visibleFolderIds(library),
|
||||
user.name,
|
||||
library,
|
||||
)
|
||||
if (resolved == null) {
|
||||
call.respondSubsonicError(70, "Song not found")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
call.response.headers.append(
|
||||
HttpHeaders.ContentDisposition,
|
||||
contentDisposition(resolved.file.fileName.toString()),
|
||||
)
|
||||
call.respondFile(resolved.file.toFile())
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/getCoverArt") { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val id = parameters["id"]
|
||||
if (id.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val requestedSize = parameters["size"]
|
||||
val size = requestedSize?.toIntOrNull()
|
||||
if (requestedSize != null && (size == null || size !in 1..2048)) {
|
||||
call.respondSubsonicError(10, "Invalid cover size")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
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@subsonicEndpoint
|
||||
}
|
||||
|
||||
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"
|
||||
}
|
||||
@@ -1,265 +0,0 @@
|
||||
package win.taptap.musicmanager.subsonic.routes
|
||||
|
||||
import io.ktor.server.application.ApplicationCall
|
||||
import io.ktor.server.routing.Route
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.add
|
||||
import kotlinx.serialization.json.buildJsonArray
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.put
|
||||
import org.slf4j.LoggerFactory
|
||||
import win.taptap.musicmanager.config.LibraryConfig
|
||||
import win.taptap.musicmanager.config.UserAccount
|
||||
import win.taptap.musicmanager.config.UsersConfig
|
||||
import win.taptap.musicmanager.db.LibraryRepository
|
||||
import win.taptap.musicmanager.db.MoodRecord
|
||||
import win.taptap.musicmanager.db.MoodRepository
|
||||
import win.taptap.musicmanager.db.PlaylistRepository
|
||||
import win.taptap.musicmanager.mood.MoodService
|
||||
import win.taptap.musicmanager.subsonic.models.moodJson
|
||||
import win.taptap.musicmanager.subsonic.respondSubsonic
|
||||
import win.taptap.musicmanager.subsonic.respondSubsonicError
|
||||
|
||||
private val log = LoggerFactory.getLogger("win.taptap.musicmanager.MoodRoutes")
|
||||
|
||||
/**
|
||||
* Mood management endpoints. These are custom OpenSubsonic endpoints used by the
|
||||
* built-in web UI; Symfonium only sees the resulting playlists.
|
||||
*/
|
||||
fun Route.moodRoutes(
|
||||
users: UsersConfig,
|
||||
library: LibraryConfig,
|
||||
moodService: MoodService,
|
||||
) {
|
||||
subsonicEndpoint(users, "/getMoods") { call, user ->
|
||||
val moods = MoodRepository.list(user.name)
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put("moods", buildJsonObject {
|
||||
put("mood", buildJsonArray { moods.forEach { add(moodJson(it)) } })
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/getMood") { call, user ->
|
||||
val mood = call.requireMood(user) ?: return@subsonicEndpoint
|
||||
call.respondSubsonic(buildJsonObject { put("mood", detail(mood, user, library)) })
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/createMood") { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val name = parameters["name"]?.trim()?.takeIf { it.isNotEmpty() }
|
||||
if (name == null) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: name")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val folders = user.musicFolderIds(library)
|
||||
val seedIds = parameters.getAll("songId").orEmpty()
|
||||
.filter { it.isNotBlank() }
|
||||
.filter { LibraryRepository.song(it, folders, user.name) != null }
|
||||
.distinct()
|
||||
|
||||
val mood = MoodRepository.create(
|
||||
userName = user.name,
|
||||
name = name.take(200),
|
||||
comment = parameters["comment"]?.trim()?.takeIf { it.isNotEmpty() },
|
||||
query = parameters["query"]?.trim()?.takeIf { it.isNotEmpty() },
|
||||
genres = genres(parameters),
|
||||
targetSize = intParam(parameters["targetSize"], 50, 1, 500),
|
||||
ytSlots = intParam(parameters["ytSlots"], 0, 0, 500),
|
||||
expandRelated = boolParam(parameters["expandRelated"], true),
|
||||
refreshHours = intParam(parameters["refreshHours"], 24, 1, 720),
|
||||
seedSongIds = seedIds,
|
||||
)
|
||||
|
||||
regenerate(moodService, mood, user, library)
|
||||
call.respondSubsonic(buildJsonObject { put("mood", detail(refreshed(mood), user, library)) })
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/updateMood") { call, user ->
|
||||
val mood = call.requireMood(user) ?: return@subsonicEndpoint
|
||||
val parameters = call.subsonicParams()
|
||||
|
||||
val name = parameters["name"]?.trim()?.takeIf { it.isNotEmpty() } ?: mood.name
|
||||
val comment = if (parameters.contains("comment")) {
|
||||
parameters["comment"]?.trim()?.takeIf { it.isNotEmpty() }
|
||||
} else {
|
||||
mood.comment
|
||||
}
|
||||
val query = if (parameters.contains("query")) {
|
||||
parameters["query"]?.trim()?.takeIf { it.isNotEmpty() }
|
||||
} else {
|
||||
mood.query
|
||||
}
|
||||
val genres = if (parameters.contains("genre") || parameters.contains("genres")) {
|
||||
genres(parameters)
|
||||
} else {
|
||||
mood.genres
|
||||
}
|
||||
|
||||
val updated = MoodRepository.update(
|
||||
playlistId = mood.playlistId,
|
||||
userName = user.name,
|
||||
name = name.take(200),
|
||||
comment = comment,
|
||||
query = query,
|
||||
genres = genres,
|
||||
targetSize = intParam(parameters["targetSize"], mood.targetSize, 1, 500),
|
||||
ytSlots = intParam(parameters["ytSlots"], mood.ytSlots, 0, 500),
|
||||
expandRelated = boolParam(parameters["expandRelated"], mood.expandRelated),
|
||||
refreshHours = intParam(parameters["refreshHours"], mood.refreshHours, 1, 720),
|
||||
)
|
||||
|
||||
if (!updated) {
|
||||
call.respondSubsonicError(70, "Mood not found")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val refreshedMood = MoodRepository.get(mood.playlistId, user.name) ?: mood
|
||||
regenerate(moodService, refreshedMood, user, library)
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put("mood", detail(refreshed(refreshedMood), user, library))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/deleteMood") { call, user ->
|
||||
val mood = call.requireMood(user) ?: return@subsonicEndpoint
|
||||
MoodRepository.delete(mood.playlistId, user.name)
|
||||
call.respondSubsonic()
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/refreshMood") { call, user ->
|
||||
val mood = call.requireMood(user) ?: return@subsonicEndpoint
|
||||
regenerate(moodService, mood, user, library)
|
||||
call.respondSubsonic(buildJsonObject { put("mood", detail(refreshed(mood), user, library)) })
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/promotePlaylistToMood") { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val playlistId = parameters["playlistId"]
|
||||
if (playlistId.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: playlistId")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val mood = MoodRepository.promote(
|
||||
userName = user.name,
|
||||
playlistId = playlistId,
|
||||
query = parameters["query"]?.trim()?.takeIf { it.isNotEmpty() },
|
||||
genres = genres(parameters),
|
||||
targetSize = intParam(parameters["targetSize"], 50, 1, 500),
|
||||
ytSlots = intParam(parameters["ytSlots"], 0, 0, 500),
|
||||
expandRelated = boolParam(parameters["expandRelated"], true),
|
||||
refreshHours = intParam(parameters["refreshHours"], 24, 1, 720),
|
||||
musicFolderIds = user.musicFolderIds(library),
|
||||
)
|
||||
|
||||
if (mood == null) {
|
||||
call.respondSubsonicError(70, "Playlist not found")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
regenerate(moodService, mood, user, library)
|
||||
call.respondSubsonic(buildJsonObject { put("mood", detail(refreshed(mood), user, library)) })
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/addMoodSeed") { call, user ->
|
||||
val mood = call.requireMood(user) ?: return@subsonicEndpoint
|
||||
val parameters = call.subsonicParams()
|
||||
val songId = parameters["songId"]
|
||||
if (songId.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: songId")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val folders = user.musicFolderIds(library)
|
||||
if (LibraryRepository.song(songId, folders, user.name) == null) {
|
||||
call.respondSubsonicError(70, "Song not found")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
MoodRepository.addSeed(mood.playlistId, user.name, songId, "manual")
|
||||
regenerate(moodService, mood, user, library)
|
||||
call.respondSubsonic(buildJsonObject { put("mood", detail(refreshed(mood), user, library)) })
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/removeMoodSeed") { call, user ->
|
||||
val mood = call.requireMood(user) ?: return@subsonicEndpoint
|
||||
val songId = call.subsonicParams()["songId"]
|
||||
if (songId.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: songId")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
MoodRepository.removeSeed(mood.playlistId, user.name, songId)
|
||||
regenerate(moodService, mood, user, library)
|
||||
call.respondSubsonic(buildJsonObject { put("mood", detail(refreshed(mood), user, library)) })
|
||||
}
|
||||
}
|
||||
|
||||
private fun ApplicationCall.moodId(): String? = subsonicParams()["id"]?.takeIf { it.isNotBlank() }
|
||||
|
||||
private suspend fun ApplicationCall.requireMood(
|
||||
user: UserAccount,
|
||||
): MoodRecord? {
|
||||
val id = moodId()
|
||||
if (id == null) {
|
||||
respondSubsonicError(10, "Required parameter is missing: id")
|
||||
return null
|
||||
}
|
||||
|
||||
val mood = MoodRepository.get(id, user.name)
|
||||
if (mood == null) {
|
||||
respondSubsonicError(70, "Mood not found")
|
||||
return null
|
||||
}
|
||||
return mood
|
||||
}
|
||||
|
||||
private fun detail(mood: MoodRecord, user: UserAccount, library: LibraryConfig): JsonObject {
|
||||
val folders = user.musicFolderIds(library)
|
||||
val seedIds = MoodRepository.seedSongIds(mood.playlistId)
|
||||
val seeds = LibraryRepository.songsByIds(seedIds, folders, user.name)
|
||||
val entryIds = PlaylistRepository.songIds(mood.playlistId)
|
||||
val entries = LibraryRepository.songsByIds(entryIds, folders, user.name)
|
||||
return moodJson(mood, seeds = seeds, songs = entries)
|
||||
}
|
||||
|
||||
private fun refreshed(mood: MoodRecord): MoodRecord =
|
||||
MoodRepository.get(mood.playlistId, mood.owner) ?: mood
|
||||
|
||||
private fun regenerate(
|
||||
moodService: MoodService,
|
||||
mood: MoodRecord,
|
||||
user: UserAccount,
|
||||
library: LibraryConfig,
|
||||
) {
|
||||
// A generation failure is recorded on the mood; management actions still succeed.
|
||||
runCatching {
|
||||
moodService.refreshNow(mood, user, library)
|
||||
}.onFailure {
|
||||
log.warn("Mood generation failed for ${mood.name}", it)
|
||||
}
|
||||
}
|
||||
|
||||
private fun genres(parameters: io.ktor.http.Parameters): List<String> =
|
||||
(parameters.getAll("genre").orEmpty() +
|
||||
parameters["genres"].orEmpty().split(','))
|
||||
.map { it.trim() }
|
||||
.filter { it.isNotEmpty() }
|
||||
.distinct()
|
||||
.take(20)
|
||||
|
||||
private fun intParam(raw: String?, default: Int, minimum: Int, maximum: Int): Int =
|
||||
(raw?.toIntOrNull() ?: default).coerceIn(minimum, maximum)
|
||||
|
||||
private fun boolParam(raw: String?, default: Boolean): Boolean = when (raw?.lowercase()) {
|
||||
null -> default
|
||||
"true", "1", "yes", "on" -> true
|
||||
"false", "0", "no", "off" -> false
|
||||
else -> default
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
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.subsonic.PlayQueueStore
|
||||
import win.taptap.musicmanager.subsonic.models.songJson
|
||||
import win.taptap.musicmanager.subsonic.respondSubsonic
|
||||
|
||||
/** Optional server-side queue used by clients that support queue hand-off. */
|
||||
fun Route.playQueueRoutes(users: UsersConfig, library: LibraryConfig) {
|
||||
|
||||
for (endpoint in listOf("/savePlayQueue", "/savePlayQueueByIndex")) {
|
||||
subsonicEndpoint(users, endpoint) { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val folders = user.visibleFolderIds(library)
|
||||
|
||||
val requestedIds = parameters.getAll("id").orEmpty().filter { it.isNotBlank() }
|
||||
val visible = requestedIds.filter { LibraryRepository.song(it, folders, user.name) != null }
|
||||
|
||||
val currentId = parameters["current"]
|
||||
val explicitIndex = parameters["currentIndex"]?.toIntOrNull()
|
||||
val currentIndex = explicitIndex
|
||||
?: currentId?.let { visible.indexOf(it) }?.takeIf { it >= 0 }
|
||||
?: 0
|
||||
|
||||
val position = parameters["position"]?.toLongOrNull() ?: 0L
|
||||
PlayQueueStore.save(user.name, visible, currentIndex, position)
|
||||
|
||||
call.respondSubsonic()
|
||||
}
|
||||
}
|
||||
|
||||
for (endpoint in listOf("/getPlayQueue", "/getPlayQueueByIndex")) {
|
||||
subsonicEndpoint(users, endpoint) { call, user ->
|
||||
val state = PlayQueueStore.get(user.name)
|
||||
val folders = user.visibleFolderIds(library)
|
||||
val songs = LibraryRepository.songsByIds(state?.songIds.orEmpty(), folders, user.name)
|
||||
val byIndex = endpoint == "/getPlayQueueByIndex"
|
||||
|
||||
val queue = buildJsonObject {
|
||||
put("entry", buildJsonArray { songs.forEach { add(songJson(it)) } })
|
||||
put("position", state?.positionMs ?: 0L)
|
||||
put("username", user.name)
|
||||
put("changed", state?.changed.orEmpty())
|
||||
put("changedBy", state?.changedBy.orEmpty())
|
||||
|
||||
if (byIndex) {
|
||||
put("currentIndex", state?.currentIndex ?: 0)
|
||||
} else {
|
||||
state?.songIds?.getOrNull(state.currentIndex)?.let { put("current", it) }
|
||||
}
|
||||
}
|
||||
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put(if (byIndex) "playQueueByIndex" else "playQueue", queue)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,189 +0,0 @@
|
||||
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.MoodRepository
|
||||
import win.taptap.musicmanager.db.PlaylistRepository
|
||||
import win.taptap.musicmanager.mood.MoodService
|
||||
import win.taptap.musicmanager.mood.MoodSessionTracker
|
||||
import win.taptap.musicmanager.subsonic.models.playlistJson
|
||||
import win.taptap.musicmanager.subsonic.respondSubsonic
|
||||
import win.taptap.musicmanager.subsonic.respondSubsonicError
|
||||
|
||||
/** Playlist CRUD. Visibility: owned playlists plus all public playlists. */
|
||||
fun Route.playlistRoutes(users: UsersConfig, library: LibraryConfig, moodService: MoodService) {
|
||||
|
||||
subsonicEndpoint(users, "/getPlaylists") { call, user ->
|
||||
val playlists = PlaylistRepository.visibleTo(user.name)
|
||||
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put("playlists", buildJsonObject {
|
||||
put("playlist", buildJsonArray { playlists.forEach { add(playlistJson(it)) } })
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/getPlaylist") { call, user ->
|
||||
val id = call.subsonicParams()["id"]
|
||||
if (id.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val playlist = PlaylistRepository.get(id, user.name)
|
||||
if (playlist == null) {
|
||||
call.respondSubsonicError(70, "Playlist not found")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
if (playlist.kind == "mood") {
|
||||
MoodSessionTracker.activate(user.name, playlist.id)
|
||||
MoodRepository.get(playlist.id, user.name)?.let { mood ->
|
||||
moodService.refreshIfStale(mood, user, library)
|
||||
}
|
||||
} else {
|
||||
MoodSessionTracker.clear(user.name)
|
||||
}
|
||||
|
||||
val folders = if (playlist.kind == "mood") {
|
||||
user.musicFolderIds(library)
|
||||
} else {
|
||||
user.visibleFolderIds(library)
|
||||
}
|
||||
val songs = LibraryRepository.songsByIds(PlaylistRepository.songIds(id), folders, user.name)
|
||||
|
||||
call.respondSubsonic(buildJsonObject { put("playlist", playlistJson(playlist, songs)) })
|
||||
}
|
||||
|
||||
subsonicEndpoint(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@subsonicEndpoint
|
||||
}
|
||||
if (existing.owner != user.name) {
|
||||
call.respondSubsonicError(50, "Not authorized")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
if (existing.kind == "mood") {
|
||||
call.respondSubsonicError(50, "Mood playlists are generated by the server")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val newName = parameters["name"]?.takeIf { it.isNotBlank() }
|
||||
PlaylistRepository.update(
|
||||
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@subsonicEndpoint
|
||||
}
|
||||
|
||||
val name = parameters["name"]
|
||||
if (name.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: name")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val playlist = PlaylistRepository.create(user.name, name.trim(), requestedSongs)
|
||||
call.respondSubsonic(buildJsonObject { put("playlist", playlistJson(playlist)) })
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/updatePlaylist") { call, user ->
|
||||
val parameters = call.subsonicParams()
|
||||
val playlistId = parameters["playlistId"]
|
||||
if (playlistId.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: playlistId")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val existing = PlaylistRepository.get(playlistId, user.name)
|
||||
if (existing == null) {
|
||||
call.respondSubsonicError(70, "Playlist not found")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
if (existing.owner != user.name) {
|
||||
call.respondSubsonicError(50, "Not authorized")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
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 }
|
||||
|
||||
if (existing.kind == "mood" &&
|
||||
(parameters.getAll("songIdToAdd").orEmpty().any { it.isNotBlank() } ||
|
||||
removeIndices.isNotEmpty() ||
|
||||
parameters.contains("public"))
|
||||
) {
|
||||
call.respondSubsonicError(50, "Mood playlists are generated by the server")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val updated = PlaylistRepository.update(
|
||||
playlistId = playlistId,
|
||||
userName = user.name,
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/deletePlaylist") { call, user ->
|
||||
val playlistId = call.subsonicParams()["id"]
|
||||
if (playlistId.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val existing = PlaylistRepository.get(playlistId, user.name)
|
||||
if (existing == null) {
|
||||
call.respondSubsonicError(70, "Playlist not found")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
if (existing.owner != user.name) {
|
||||
call.respondSubsonicError(50, "Not authorized")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
PlaylistRepository.delete(playlistId, user.name)
|
||||
MoodSessionTracker.clear(user.name)
|
||||
call.respondSubsonic()
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
package win.taptap.musicmanager.subsonic.routes
|
||||
|
||||
import io.ktor.http.ContentType
|
||||
import io.ktor.http.HttpMethod
|
||||
import io.ktor.http.Parameters
|
||||
import io.ktor.server.application.ApplicationCall
|
||||
import io.ktor.server.request.contentType
|
||||
import io.ktor.server.request.httpMethod
|
||||
import io.ktor.server.request.receiveParameters
|
||||
import io.ktor.util.AttributeKey
|
||||
import win.taptap.musicmanager.config.FolderType
|
||||
import win.taptap.musicmanager.config.LibraryConfig
|
||||
import win.taptap.musicmanager.config.UserAccount
|
||||
|
||||
val CurrentUserKey = AttributeKey<UserAccount>("musicmanager.currentUser")
|
||||
val SubsonicParametersKey = AttributeKey<Parameters>("musicmanager.parameters")
|
||||
|
||||
/**
|
||||
* Visible folders, optionally narrowed to a client-supplied `musicFolderId`.
|
||||
* An unknown or invisible id yields an empty set, which all queries treat as "nothing".
|
||||
*/
|
||||
fun UserAccount.effectiveFolderIds(library: LibraryConfig, musicFolderId: String?): Set<Int> {
|
||||
val visible = visibleFolderIds(library)
|
||||
val requested = musicFolderId?.toIntOrNull() ?: return visible
|
||||
return if (requested in visible) setOf(requested) else emptySet()
|
||||
}
|
||||
|
||||
/** Music-only roots. Moods never draw from shared long-form folders. */
|
||||
fun UserAccount.musicFolderIds(library: LibraryConfig): Set<Int> =
|
||||
library.folders
|
||||
.asSequence()
|
||||
.filter { it.type == FolderType.MUSIC && it.id in folders }
|
||||
.map { it.id }
|
||||
.toSet()
|
||||
|
||||
/** Parameters captured during authentication, so POST bodies are only read once. */
|
||||
fun ApplicationCall.subsonicParams(): Parameters =
|
||||
attributes.getOrNull(SubsonicParametersKey) ?: request.queryParameters
|
||||
|
||||
/**
|
||||
* Unified parameter access for Subsonic: query parameters plus URL-encoded form
|
||||
* bodies (the `formPost` OpenSubsonic extension).
|
||||
*/
|
||||
suspend fun subsonicParameters(call: ApplicationCall): Parameters {
|
||||
val query = call.request.queryParameters
|
||||
if (call.request.httpMethod != HttpMethod.Post) return query
|
||||
|
||||
val contentType = call.request.contentType()
|
||||
if (!contentType.match(ContentType.Application.FormUrlEncoded)) return query
|
||||
|
||||
val form = call.receiveParameters()
|
||||
return Parameters.build {
|
||||
query.forEach { name, values -> values.forEach { append(name, it) } }
|
||||
form.forEach { name, values -> values.forEach { append(name, it) } }
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package win.taptap.musicmanager.subsonic.routes
|
||||
|
||||
import io.ktor.server.application.ApplicationCall
|
||||
import io.ktor.server.routing.Route
|
||||
import io.ktor.server.routing.get
|
||||
import io.ktor.server.routing.post
|
||||
import win.taptap.musicmanager.config.UserAccount
|
||||
import win.taptap.musicmanager.config.UsersConfig
|
||||
import win.taptap.musicmanager.subsonic.SubsonicAuthenticator
|
||||
import win.taptap.musicmanager.subsonic.respondSubsonicError
|
||||
|
||||
/**
|
||||
* Registers a Subsonic endpoint for both `/{path}` and `/{path}.view`, and for both
|
||||
* GET and POST form posts (the `formPost` OpenSubsonic extension).
|
||||
* Authentication failures always return HTTP 200 with error code 40.
|
||||
*/
|
||||
internal fun Route.subsonicEndpoint(
|
||||
users: UsersConfig,
|
||||
path: String,
|
||||
handler: suspend (ApplicationCall, UserAccount) -> Unit,
|
||||
) {
|
||||
val authenticator = SubsonicAuthenticator(users)
|
||||
val paths = if (path.endsWith(".view")) listOf(path) else listOf(path, "$path.view")
|
||||
|
||||
suspend fun handle(call: ApplicationCall) {
|
||||
val parameters = subsonicParameters(call)
|
||||
val user = authenticator.authenticate(parameters)
|
||||
if (user == null) {
|
||||
call.respondSubsonicError(40, "Wrong username or password")
|
||||
} else {
|
||||
call.attributes.put(CurrentUserKey, user)
|
||||
call.attributes.put(SubsonicParametersKey, parameters)
|
||||
handler(call, user)
|
||||
}
|
||||
}
|
||||
|
||||
paths.forEach { routePath ->
|
||||
get(routePath) { handle(call) }
|
||||
post(routePath) { handle(call) }
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
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.mood.MoodService
|
||||
import win.taptap.musicmanager.scanner.CoverArtService
|
||||
import win.taptap.musicmanager.scanner.ScanStatus
|
||||
import win.taptap.musicmanager.transcoding.FfmpegTranscoder
|
||||
|
||||
/** Authenticated `/rest` subtree. */
|
||||
fun Route.subsonicRoutes(
|
||||
users: UsersConfig,
|
||||
library: LibraryConfig,
|
||||
coverArtService: CoverArtService,
|
||||
transcoder: FfmpegTranscoder,
|
||||
moodService: MoodService,
|
||||
startScan: () -> Boolean,
|
||||
scanStatus: () -> ScanStatus,
|
||||
) {
|
||||
route("/rest") {
|
||||
systemRoutes(users, library, startScan, scanStatus)
|
||||
browsingRoutes(users, library)
|
||||
mediaRoutes(users, library, coverArtService, transcoder)
|
||||
interactionRoutes(users, library)
|
||||
playlistRoutes(users, library, moodService)
|
||||
moodRoutes(users, library, moodService)
|
||||
playQueueRoutes(users, library)
|
||||
}
|
||||
}
|
||||
@@ -1,174 +0,0 @@
|
||||
package win.taptap.musicmanager.subsonic.routes
|
||||
|
||||
import io.ktor.server.routing.Route
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
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.config.LibraryConfig
|
||||
import win.taptap.musicmanager.config.UserAccount
|
||||
import win.taptap.musicmanager.config.UsersConfig
|
||||
import win.taptap.musicmanager.scanner.ScanStatus
|
||||
import win.taptap.musicmanager.subsonic.respondSubsonic
|
||||
import win.taptap.musicmanager.subsonic.respondSubsonicError
|
||||
|
||||
/** System endpoints from the MVP specification. */
|
||||
fun Route.systemRoutes(
|
||||
users: UsersConfig,
|
||||
library: LibraryConfig,
|
||||
startScan: () -> Boolean,
|
||||
scanStatus: () -> ScanStatus,
|
||||
) {
|
||||
subsonicEndpoint(users, "/ping") { call, _ ->
|
||||
call.respondSubsonic()
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/getLicense") { call, _ ->
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put("license", buildJsonObject { put("valid", true) })
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/getOpenSubsonicExtensions") { call, _ ->
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put(
|
||||
"openSubsonicExtensions",
|
||||
buildJsonArray {
|
||||
add(extension("formPost", 1))
|
||||
add(extension("songLyrics", 1))
|
||||
add(extension("transcodeOffset", 1))
|
||||
},
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/startScan") { call, user ->
|
||||
if (!user.admin) {
|
||||
call.respondSubsonicError(50, "Not authorized")
|
||||
} else {
|
||||
startScan()
|
||||
call.respondSubsonic()
|
||||
}
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/getScanStatus") { call, _ ->
|
||||
val status = scanStatus()
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put("scanStatus", buildJsonObject {
|
||||
put("scanning", status.scanning)
|
||||
put("count", status.count)
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/getUser") { call, currentUser ->
|
||||
val username = call.subsonicParams()["username"]
|
||||
if (username.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: username")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
if (username != currentUser.name && !currentUser.admin) {
|
||||
call.respondSubsonicError(50, "Not authorized")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val requested = users.byName(username)
|
||||
if (requested == null) {
|
||||
call.respondSubsonicError(70, "User not found")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
call.respondSubsonic(buildJsonObject { put("user", userJson(requested, library)) })
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/getInternetRadioStations") { call, _ ->
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put("internetRadioStations", buildJsonObject {
|
||||
put("internetRadioStation", buildJsonArray { })
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
for (endpoint in listOf(
|
||||
"/createInternetRadioStation",
|
||||
"/updateInternetRadioStation",
|
||||
"/deleteInternetRadioStation",
|
||||
)) {
|
||||
subsonicEndpoint(users, endpoint) { call, _ ->
|
||||
call.respondSubsonicError(0, "Internet radio is not supported")
|
||||
}
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/jukeboxControl") { call, _ ->
|
||||
if (call.subsonicParams()["action"] != "status") {
|
||||
call.respondSubsonicError(0, "Jukebox is not supported")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put("jukeboxStatus", buildJsonObject {
|
||||
put("currentIndex", 0)
|
||||
put("playing", false)
|
||||
put("gain", 1.0)
|
||||
put("position", 0)
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/getUsers") { call, currentUser ->
|
||||
if (!currentUser.admin) {
|
||||
call.respondSubsonicError(50, "Not authorized")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
call.respondSubsonic(
|
||||
buildJsonObject {
|
||||
put("users", buildJsonObject {
|
||||
put("user", buildJsonArray {
|
||||
users.users.forEach { add(userJson(it, library)) }
|
||||
})
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun userJson(user: UserAccount, library: LibraryConfig) = buildJsonObject {
|
||||
put("username", user.name)
|
||||
put("scrobblingEnabled", true)
|
||||
put("adminRole", user.admin)
|
||||
put("settingsRole", user.admin)
|
||||
put("downloadRole", true)
|
||||
put("uploadRole", false)
|
||||
put("playlistRole", true)
|
||||
put("coverArtRole", true)
|
||||
put("commentRole", false)
|
||||
put("podcastRole", false)
|
||||
put("streamRole", true)
|
||||
put("jukeboxRole", false)
|
||||
put("shareRole", false)
|
||||
put("videoConversionRole", false)
|
||||
put("folder", folderIds(user.visibleFolderIds(library)))
|
||||
}
|
||||
|
||||
private fun folderIds(ids: Set<Int>): JsonArray = buildJsonArray {
|
||||
ids.sorted().forEach { add(JsonPrimitive(it)) }
|
||||
}
|
||||
|
||||
private fun extension(name: String, version: Int) = buildJsonObject {
|
||||
put("name", name)
|
||||
put("versions", buildJsonArray { add(kotlinx.serialization.json.JsonPrimitive(version)) })
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import java.text.Normalizer
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* Deterministic IDs for the Symfonium offline cache.
|
||||
* Deterministic IDs for clients' offline caches.
|
||||
*
|
||||
* Normalization is frozen: NFC, trimmed, collapsed whitespace, lowercase. Changing
|
||||
* it changes every ID and forces clients to re-download their library.
|
||||
@@ -27,8 +27,8 @@ object IdGenerator {
|
||||
fun songId(folderId: Int, relativePath: String): String =
|
||||
"sg-" + hash("$folderId:${normalizePath(relativePath)}")
|
||||
|
||||
fun playlistId(owner: String, name: String, createdAt: String): String =
|
||||
"pl-" + hash("${normalize(owner)}|${normalize(name)}|$createdAt")
|
||||
fun moodId(owner: String, name: String, createdAt: String): String =
|
||||
"mo-" + hash("${normalize(owner)}|${normalize(name)}|$createdAt")
|
||||
|
||||
private fun normalizePath(path: String): String = path
|
||||
.replace('\\', '/')
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
-- Native mood-first API.
|
||||
--
|
||||
-- The OpenSubsonic layer is gone, so moods no longer need to be materialized as
|
||||
-- playlists. They become first-class rows, radio queues are generated per
|
||||
-- playback session, and the old playlist tables are dropped.
|
||||
|
||||
CREATE TABLE moods_v2 (
|
||||
id TEXT PRIMARY KEY,
|
||||
owner TEXT NOT NULL REFERENCES users(name) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
query TEXT,
|
||||
genres TEXT NOT NULL DEFAULT '[]',
|
||||
target_size INTEGER NOT NULL DEFAULT 30,
|
||||
refresh_hours INTEGER NOT NULL DEFAULT 24,
|
||||
yt_enabled BOOLEAN NOT NULL DEFAULT 1,
|
||||
last_discovery_at TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
changed_at TEXT NOT NULL,
|
||||
last_error TEXT
|
||||
);
|
||||
|
||||
INSERT INTO moods_v2 (
|
||||
id, owner, name, description, query, genres, target_size,
|
||||
refresh_hours, yt_enabled, created_at, changed_at, last_error
|
||||
)
|
||||
SELECT
|
||||
m.playlist_id,
|
||||
p.owner,
|
||||
p.name,
|
||||
p.comment,
|
||||
m.query,
|
||||
m.genres,
|
||||
m.target_size,
|
||||
m.refresh_hours,
|
||||
1,
|
||||
p.created_at,
|
||||
p.changed_at,
|
||||
m.last_error
|
||||
FROM moods m
|
||||
JOIN playlists p ON p.id = m.playlist_id;
|
||||
|
||||
CREATE TABLE mood_seeds_v2 (
|
||||
mood_id TEXT NOT NULL REFERENCES moods_v2(id) ON DELETE CASCADE,
|
||||
song_id TEXT NOT NULL REFERENCES songs(id) ON DELETE CASCADE,
|
||||
origin TEXT NOT NULL DEFAULT 'manual'
|
||||
CHECK (origin IN ('manual', 'recommendation', 'yt')),
|
||||
added_at TEXT NOT NULL,
|
||||
PRIMARY KEY (mood_id, song_id)
|
||||
);
|
||||
|
||||
-- Stars no longer exist. Songs liked under the old model become manual seeds.
|
||||
INSERT INTO mood_seeds_v2 (mood_id, song_id, origin, added_at)
|
||||
SELECT
|
||||
playlist_id,
|
||||
song_id,
|
||||
CASE origin WHEN 'manual' THEN 'manual' ELSE 'manual' END,
|
||||
added_at
|
||||
FROM mood_seeds;
|
||||
|
||||
CREATE TABLE mood_recommendations_v2 (
|
||||
mood_id TEXT NOT NULL REFERENCES moods_v2(id) ON DELETE CASCADE,
|
||||
video_id TEXT NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
artist TEXT NOT NULL,
|
||||
album TEXT,
|
||||
duration INTEGER,
|
||||
thumbnail TEXT,
|
||||
state TEXT NOT NULL DEFAULT 'new'
|
||||
CHECK (state IN ('new', 'accepted', 'rejected', 'unavailable')),
|
||||
matched_song_id TEXT REFERENCES songs(id) ON DELETE SET NULL,
|
||||
times_added INTEGER NOT NULL DEFAULT 0,
|
||||
first_seen TEXT NOT NULL,
|
||||
last_seen TEXT NOT NULL,
|
||||
PRIMARY KEY (mood_id, video_id)
|
||||
);
|
||||
|
||||
INSERT INTO mood_recommendations_v2 (
|
||||
mood_id, video_id, title, artist, duration, state,
|
||||
matched_song_id, times_added, first_seen, last_seen
|
||||
)
|
||||
SELECT
|
||||
playlist_id, video_id, title, artist, duration, state,
|
||||
matched_song_id, times_added, first_seen, last_seen
|
||||
FROM mood_recommendations;
|
||||
|
||||
DROP TABLE mood_recommendations;
|
||||
DROP TABLE mood_seeds;
|
||||
DROP TABLE moods;
|
||||
DROP TABLE playlist_songs;
|
||||
DROP TABLE playlists;
|
||||
|
||||
ALTER TABLE moods_v2 RENAME TO moods;
|
||||
ALTER TABLE mood_seeds_v2 RENAME TO mood_seeds;
|
||||
ALTER TABLE mood_recommendations_v2 RENAME TO mood_recommendations;
|
||||
|
||||
CREATE INDEX idx_moods_owner ON moods (owner);
|
||||
CREATE INDEX idx_mood_seeds_song ON mood_seeds (song_id);
|
||||
CREATE INDEX idx_mood_recommendations_song ON mood_recommendations (matched_song_id);
|
||||
|
||||
-- Device sessions. Only the SHA-256 hash of the bearer token is stored.
|
||||
CREATE TABLE api_tokens (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_name TEXT NOT NULL REFERENCES users(name) ON DELETE CASCADE,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
device_name TEXT NOT NULL,
|
||||
platform TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
last_used_at TEXT NOT NULL,
|
||||
expires_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX idx_api_tokens_user ON api_tokens (user_name);
|
||||
|
||||
-- A playback session belongs to one mood. Queue items and events are kept so a
|
||||
-- client can resume and so radio ranking learns from skips and completions.
|
||||
CREATE TABLE playback_sessions (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_name TEXT NOT NULL REFERENCES users(name) ON DELETE CASCADE,
|
||||
mood_id TEXT NOT NULL REFERENCES moods(id) ON DELETE CASCADE,
|
||||
next_position INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL,
|
||||
last_seen_at TEXT NOT NULL,
|
||||
closed_at TEXT
|
||||
);
|
||||
|
||||
CREATE INDEX idx_playback_sessions_user ON playback_sessions (user_name, last_seen_at);
|
||||
|
||||
CREATE TABLE playback_session_items (
|
||||
session_id TEXT NOT NULL REFERENCES playback_sessions(id) ON DELETE CASCADE,
|
||||
position INTEGER NOT NULL,
|
||||
song_id TEXT NOT NULL REFERENCES songs(id) ON DELETE CASCADE,
|
||||
state TEXT NOT NULL DEFAULT 'queued'
|
||||
CHECK (state IN ('queued', 'started', 'completed', 'skipped')),
|
||||
queued_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL,
|
||||
PRIMARY KEY (session_id, position)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_session_items_song ON playback_session_items (song_id);
|
||||
|
||||
CREATE TABLE song_affinity (
|
||||
user_name TEXT NOT NULL REFERENCES users(name) ON DELETE CASCADE,
|
||||
song_id TEXT NOT NULL REFERENCES songs(id) ON DELETE CASCADE,
|
||||
completions INTEGER NOT NULL DEFAULT 0,
|
||||
skips INTEGER NOT NULL DEFAULT 0,
|
||||
last_event_at TEXT NOT NULL,
|
||||
PRIMARY KEY (user_name, song_id)
|
||||
);
|
||||
|
||||
-- Clients sync by revision. Deletions are explicit so offline libraries can drop
|
||||
-- removed files instead of keeping them forever.
|
||||
CREATE TABLE library_tombstones (
|
||||
entity TEXT NOT NULL,
|
||||
entity_id TEXT NOT NULL,
|
||||
deleted_at TEXT NOT NULL,
|
||||
PRIMARY KEY (entity, entity_id)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_library_tombstones_deleted ON library_tombstones (deleted_at);
|
||||
|
||||
-- Scanner deltas need a changed timestamp independent of the file mtime.
|
||||
ALTER TABLE songs ADD COLUMN updated_at TEXT NOT NULL DEFAULT '';
|
||||
UPDATE songs SET updated_at = created_at WHERE updated_at = '';
|
||||
+526
-484
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user