- V8 wipe migration and the shared song store keyed by YouTube video id - media store, indexer, downloader, recommendation top-up and refcounted GC - mood songs plus the recommendation lifecycle and mixed radio pools - new search, song and recommendation API; remove library/longform/seed routes - chart PVC/media env, docs, Nix, README and an end-to-end smoke test
326 lines
13 KiB
Kotlin
326 lines
13 KiB
Kotlin
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 java.nio.file.Files
|
|
import kotlinx.coroutines.Dispatchers
|
|
import kotlinx.coroutines.withContext
|
|
import kotlinx.serialization.Serializable
|
|
import win.taptap.musicmanager.config.UserAccount
|
|
import win.taptap.musicmanager.config.UsersConfig
|
|
import win.taptap.musicmanager.db.DownloadRepository
|
|
import win.taptap.musicmanager.db.MoodRecord
|
|
import win.taptap.musicmanager.db.MoodRepository
|
|
import win.taptap.musicmanager.db.SongRecord
|
|
import win.taptap.musicmanager.db.SongRepository
|
|
import win.taptap.musicmanager.discovery.DiscoveryService
|
|
import win.taptap.musicmanager.discovery.TopUpService
|
|
import win.taptap.musicmanager.discovery.YtResolver
|
|
import win.taptap.musicmanager.discovery.isMusicLength
|
|
import win.taptap.musicmanager.media.MediaGcService
|
|
import win.taptap.musicmanager.media.MediaStore
|
|
import win.taptap.musicmanager.radio.RadioService
|
|
|
|
@Serializable
|
|
data class MoodsResponse(val moods: List<MoodDto>)
|
|
|
|
@Serializable
|
|
data class RecommendationsResponse(val recommendations: List<RecommendationDto>)
|
|
|
|
fun Route.moodRoutes(
|
|
users: UsersConfig,
|
|
radioService: RadioService,
|
|
discoveryService: DiscoveryService,
|
|
topUpService: TopUpService,
|
|
resolver: YtResolver,
|
|
mediaStore: MediaStore,
|
|
gc: MediaGcService,
|
|
) {
|
|
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 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,
|
|
collectionPercent = request.collectionPercent,
|
|
recommendationCount = request.recommendationCount,
|
|
refreshHours = request.refreshHours,
|
|
)
|
|
if (mood.recommendationCount > 0) topUpService.trigger(mood)
|
|
call.respond(HttpStatusCode.Created, detail(mood))
|
|
}
|
|
|
|
get("/moods/{id}") {
|
|
val user = call.requireApiUser(users)
|
|
val mood = ownedMood(call.parameters["id"], user)
|
|
call.respond(detail(mood))
|
|
}
|
|
|
|
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,
|
|
collectionPercent = request.collectionPercent ?: mood.collectionPercent,
|
|
recommendationCount = request.recommendationCount ?: mood.recommendationCount,
|
|
refreshHours = request.refreshHours ?: mood.refreshHours,
|
|
) ?: notFound("Mood")
|
|
|
|
topUpService.trigger(updated)
|
|
call.respond(detail(updated))
|
|
}
|
|
|
|
delete("/moods/{id}") {
|
|
val user = call.requireApiUser(users)
|
|
val mood = ownedMood(call.parameters["id"], user)
|
|
MoodRepository.delete(mood.id, user.name)
|
|
gc.collectGarbage()
|
|
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(TracksResponse(radioService.preview(mood, user, limit).map { it.toDto() }))
|
|
}
|
|
|
|
get("/moods/{id}/recommendations") {
|
|
val user = call.requireApiUser(users)
|
|
val mood = ownedMood(call.parameters["id"], user)
|
|
call.respond(RecommendationsResponse(recommendations(mood)))
|
|
}
|
|
|
|
/** Runs a discovery pass now, bypassing the mood's refresh interval. */
|
|
post("/moods/{id}/recommendations/refresh") {
|
|
val user = call.requireApiUser(users)
|
|
val mood = ownedMood(call.parameters["id"], user)
|
|
if (mood.recommendationCount <= 0) conflict("Recommendations are disabled for this mood")
|
|
|
|
val outcome = withContext(Dispatchers.IO) {
|
|
discoveryService.refresh(mood, force = true)
|
|
}
|
|
outcome.error?.let { message ->
|
|
throw ApiException(HttpStatusCode.BadGateway, "discovery_failed", message)
|
|
}
|
|
topUpService.topUp(mood, force = false)
|
|
val refreshed = MoodRepository.get(mood.id, user.name) ?: mood
|
|
call.respond(detail(refreshed))
|
|
}
|
|
|
|
post("/moods/{id}/recommendations/{videoId}/add") {
|
|
val user = call.requireApiUser(users)
|
|
val mood = ownedMood(call.parameters["id"], user)
|
|
val videoId = call.parameters["videoId"] ?: badRequest("Video id is required")
|
|
val recommendation = MoodRepository.recommendation(mood.id, videoId)
|
|
?: notFound("Recommendation")
|
|
if (recommendation.state == "failed") {
|
|
conflict("Retry the download before adding this track")
|
|
}
|
|
|
|
MoodRepository.markAdded(mood.id, videoId)
|
|
topUpService.trigger(mood)
|
|
val refreshed = MoodRepository.get(mood.id, user.name) ?: mood
|
|
call.respond(
|
|
RecommendationDecisionDto(
|
|
detail = detail(refreshed),
|
|
recommendation = MoodRepository.recommendation(mood.id, videoId)
|
|
?.toDto(song = recommendationSong(mood.id, videoId))
|
|
?: recommendation.toDto(song = recommendationSong(mood.id, videoId)),
|
|
),
|
|
)
|
|
}
|
|
|
|
post("/moods/{id}/recommendations/{videoId}/reject") {
|
|
val user = call.requireApiUser(users)
|
|
val mood = ownedMood(call.parameters["id"], user)
|
|
val videoId = call.parameters["videoId"] ?: badRequest("Video id is required")
|
|
val recommendation = MoodRepository.recommendation(mood.id, videoId)
|
|
?: notFound("Recommendation")
|
|
|
|
MoodRepository.markRejected(mood.id, videoId)
|
|
DownloadRepository.cancelForMoodVideo(mood.id, videoId, "Recommendation rejected")
|
|
recommendation.songId?.let(gc::collect)
|
|
topUpService.trigger(mood)
|
|
|
|
val refreshed = MoodRepository.get(mood.id, user.name) ?: mood
|
|
call.respond(
|
|
RecommendationDecisionDto(
|
|
detail = detail(refreshed),
|
|
recommendation = recommendation.copy(state = "rejected").toDto(),
|
|
),
|
|
)
|
|
}
|
|
|
|
post("/moods/{id}/recommendations/{videoId}/retry") {
|
|
val user = call.requireApiUser(users)
|
|
val mood = ownedMood(call.parameters["id"], user)
|
|
val videoId = call.parameters["videoId"] ?: badRequest("Video id is required")
|
|
val recommendation = MoodRepository.recommendation(mood.id, videoId)
|
|
?: notFound("Recommendation")
|
|
if (recommendation.state != "failed") conflict("Only failed downloads can be retried")
|
|
|
|
MoodRepository.markRecommendationDownloading(mood.id, videoId)
|
|
DownloadRepository.enqueue(
|
|
videoId = videoId,
|
|
moodId = mood.id,
|
|
kind = DownloadRepository.KIND_RECOMMENDATION,
|
|
)
|
|
val refreshed = MoodRepository.get(mood.id, user.name) ?: mood
|
|
call.respond(detail(refreshed))
|
|
}
|
|
|
|
post("/moods/{id}/songs") {
|
|
val user = call.requireApiUser(users)
|
|
val mood = ownedMood(call.parameters["id"], user)
|
|
val request = call.receiveJson<AddSongRequest>()
|
|
val normalized = normalizeAdd(request, resolver)
|
|
|
|
val bySongId = normalized.songId?.let(SongRepository::byId)
|
|
if (normalized.songId != null && bySongId == null) notFound("Song")
|
|
val existing = (bySongId ?: normalized.videoId?.let(SongRepository::byVideoId))
|
|
?.takeIf { mediaStore.file(it)?.let(Files::isRegularFile) == true }
|
|
if (existing != null) {
|
|
val added = MoodRepository.addSong(mood.id, existing.id, normalized.origin)
|
|
val refreshed = MoodRepository.get(mood.id, user.name) ?: mood
|
|
call.respond(
|
|
AddSongResponse(
|
|
detail = detail(refreshed),
|
|
added = added,
|
|
downloading = false,
|
|
),
|
|
)
|
|
return@post
|
|
}
|
|
|
|
val videoId = normalized.videoId ?: badRequest("No song or video id was supplied")
|
|
DownloadRepository.enqueue(
|
|
videoId = videoId,
|
|
moodId = mood.id,
|
|
kind = DownloadRepository.KIND_SONG,
|
|
)
|
|
val refreshed = MoodRepository.get(mood.id, user.name) ?: mood
|
|
call.respond(
|
|
HttpStatusCode.Accepted,
|
|
AddSongResponse(detail = detail(refreshed), added = false, downloading = true),
|
|
)
|
|
}
|
|
|
|
delete("/moods/{id}/songs/{songId}") {
|
|
val user = call.requireApiUser(users)
|
|
val mood = ownedMood(call.parameters["id"], user)
|
|
val songId = call.parameters["songId"] ?: badRequest("Song id is required")
|
|
MoodRepository.removeSong(mood.id, songId)
|
|
gc.collect(songId)
|
|
call.respond(HttpStatusCode.NoContent)
|
|
}
|
|
}
|
|
|
|
private data class NormalizedAdd(
|
|
val songId: String?,
|
|
val videoId: String?,
|
|
val origin: String,
|
|
)
|
|
|
|
private fun normalizeAdd(request: AddSongRequest, resolver: YtResolver): NormalizedAdd = when {
|
|
!request.songId.isNullOrBlank() -> NormalizedAdd(request.songId, null, "search")
|
|
!request.videoId.isNullOrBlank() -> NormalizedAdd(null, request.videoId.trim(), "search")
|
|
!request.url.isNullOrBlank() -> {
|
|
val candidate = runCatching { resolver.resolve(request.url) }
|
|
.getOrElse { error ->
|
|
throw ApiException(
|
|
HttpStatusCode.BadGateway,
|
|
"resolve_failed",
|
|
error.message ?: "Could not resolve the URL",
|
|
)
|
|
}
|
|
?: throw ApiException(
|
|
HttpStatusCode.BadGateway,
|
|
"resolve_failed",
|
|
"The URL did not resolve to a video",
|
|
)
|
|
if (!isMusicLength(candidate.duration)) {
|
|
badRequest("Only tracks up to 10 minutes can be added")
|
|
}
|
|
NormalizedAdd(null, candidate.videoId, "url")
|
|
}
|
|
else -> badRequest("Supply songId, videoId or url")
|
|
}
|
|
|
|
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 detail(mood: MoodRecord): MoodDetailDto {
|
|
val songRecords = MoodRepository.songRecords(mood.id).associateBy { it.id }
|
|
val songs = MoodRepository.songs(mood.id).mapNotNull { record ->
|
|
songRecords[record.songId]?.let { record.toDto(it) }
|
|
}
|
|
return MoodDetailDto(
|
|
mood = mood.toDto(),
|
|
songs = songs,
|
|
recommendations = recommendations(mood),
|
|
)
|
|
}
|
|
|
|
private fun recommendations(mood: MoodRecord): List<RecommendationDto> {
|
|
val records = MoodRepository.recommendations(mood.id)
|
|
val songs = SongRepository.byIds(records.mapNotNull { it.songId }).associateBy { it.id }
|
|
val jobs = DownloadRepository.forMood(mood.id)
|
|
.filter { it.kind == DownloadRepository.KIND_RECOMMENDATION }
|
|
.associateBy { it.videoId }
|
|
|
|
return records.map { record ->
|
|
record.toDto(
|
|
song = record.songId?.let { songs[it] },
|
|
download = jobs[record.videoId]?.let { job ->
|
|
DownloadDto(
|
|
state = job.state,
|
|
attempts = job.attempts,
|
|
error = job.error,
|
|
updatedAt = job.updatedAt,
|
|
)
|
|
},
|
|
)
|
|
}
|
|
}
|
|
|
|
private fun recommendationSong(moodId: String, videoId: String): SongRecord? =
|
|
MoodRepository.recommendation(moodId, videoId)?.songId?.let(SongRepository::byId)
|