Files
AudioManager/src/main/kotlin/win/taptap/musicmanager/api/SessionApi.kt
T
TapTap a3c5da559b
CI / chart (push) Successful in 3s
CI / test (push) Successful in 2m4s
CI / chart-push (push) Successful in 3s
CI / image (push) Failing after 6m21s
feat: rotate recommendations after a few plays
- V12 rebuilds mood_recommendations with a rotated state, play_count and
  rotated_at, plus a per-mood recommendation_rotation_plays (default 3)
- count a play when a session reports started; retire the slot at the limit
  and let TopUpService refill it, with discovery only when the pool is empty
- add POST /moods/{id}/recommendations/rotate for the All new action, which
  retires every active slot and forces discovery
- turned a rotated slot's late download completion into REJECTED so it cannot
  reappear as ready
- revive rotated slots after a 30-day cooldown to avoid draining the catalog
- expose playCount and recommendationRotationPlays in the API, chart 0.6.0
2026-11-22 17:31:28 +00:00

169 lines
6.3 KiB
Kotlin

package win.taptap.musicmanager.api
import io.ktor.http.HttpStatusCode
import io.ktor.server.request.receiveNullable
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 java.time.Instant
import org.slf4j.LoggerFactory
import win.taptap.musicmanager.config.UserAccount
import win.taptap.musicmanager.config.UsersConfig
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.SongRepository
import win.taptap.musicmanager.discovery.TopUpService
import win.taptap.musicmanager.media.MediaGcService
import win.taptap.musicmanager.radio.RadioService
fun Route.sessionRoutes(
users: UsersConfig,
radioService: RadioService,
topUpService: TopUpService,
gc: MediaGcService,
) {
post("/moods/{id}/sessions") {
val user = call.requireApiUser(users)
val mood = ownedMoodFor(call.parameters["id"], user)
if (MoodRepository.songIds(mood.id).isEmpty()) {
throw ApiException(
HttpStatusCode.BadRequest,
"empty_mood",
"Add at least one song before playing this mood",
)
}
val request = call.receiveNullable<StartSessionRequest>() ?: StartSessionRequest()
val limit = request.limit ?: DEFAULT_BATCH
val started = radioService.start(mood, user, 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 items = RadioRepository.items(session.id)
val songs = SongRepository.byIds(items.map { it.songId }).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 = call.receiveNullable<NextTracksRequest>() ?: NextTracksRequest()
val songs = radioService.next(
mood = mood,
user = user,
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 playedAt = Instant.now()
val retired = mutableListOf<String>()
val accepted = request.events.count { event ->
val recorded = event.type in EVENT_TYPES &&
event.songId.isNotBlank() &&
RadioRepository.recordEvent(session.id, user.name, event.songId, event.type)
// A play is counted when it starts, so a crash or an offline finish
// cannot make the counter lag behind what the user actually heard.
if (recorded && event.type == "started") {
MoodRepository.recordPlay(session.moodId, event.songId, playedAt)?.let {
retired += it.externalId
log.info(
"Rotated recommendation {} in mood {} after {} plays",
it.externalId,
session.moodId,
it.plays,
)
}
}
recorded
}
if (retired.isNotEmpty()) {
// Refill in the background; the response must not wait for a search.
topUpService.trigger(session.moodId)
}
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 song = SongRepository.byId(request.songId) ?: notFound("Song")
val target = if (request.moodId.isNullOrBlank()) {
ownedMoodFor(session.moodId, user)
} else {
ownedMoodFor(request.moodId, user)
}
val added = MoodRepository.addSong(target.id, song.id, "search")
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)
gc.collectGarbage()
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 val log = LoggerFactory.getLogger("win.taptap.musicmanager.api.Sessions")
private const val DEFAULT_BATCH = 15
private val EVENT_TYPES = setOf("started", "completed", "skipped")