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
This commit is contained in:
1 parent
44b75c4d4d
commit
a3c5da559b
15 files changed
+507
-8
No files matched your search
@@ -46,6 +46,12 @@ keeps playing without a mounted music library.
|
||||
- **Add / Not interested are permanent.** Adding promotes a recommendation into
|
||||
the collection. Rejecting is remembered per mood. Both free a slot and the
|
||||
server refills it.
|
||||
- **Picks rotate after a few plays.** `recommendationRotationPlays` (0–100,
|
||||
default 3) retires an active recommendation once it has been started that many
|
||||
times and fills its slot from the hidden pool. `0` turns automatic rotation
|
||||
off. Retired tracks rest for 30 days, then may be offered again; this is a
|
||||
cooldown, not a rejection. The "All new" action retires every active pick at
|
||||
once, which is what you want when Refresh keeps returning the same songs.
|
||||
- **Playback mixes both pools.** Every queue slot rolls `collectionPercent`;
|
||||
the rest comes from ready recommendations. An empty pool falls back to the
|
||||
other one. Small pools replay least-recently-played tracks.
|
||||
@@ -176,7 +182,7 @@ Media URLs may use `?token=` because HTML audio and images cannot send headers.
|
||||
| Method | Path | Purpose |
|
||||
|---|---|---|
|
||||
| `GET` | `/moods` | List the user's moods |
|
||||
| `POST` | `/moods` | Create `{name,description,query,genres,source,collectionPercent,recommendationCount,refreshHours}` |
|
||||
| `POST` | `/moods` | Create `{name,description,query,genres,source,collectionPercent,recommendationCount,recommendationRotationPlays,refreshHours}` |
|
||||
| `GET` | `/moods/{id}` | Mood detail: songs, active recommendations, download status |
|
||||
| `PATCH` | `/moods/{id}` | Update options |
|
||||
| `DELETE` | `/moods/{id}` | Delete mood, detach songs and run GC |
|
||||
@@ -185,6 +191,7 @@ Media URLs may use `?token=` because HTML audio and images cannot send headers.
|
||||
| `DELETE` | `/moods/{id}/songs/{songId}` | Detach a song |
|
||||
| `GET` | `/moods/{id}/recommendations` | Active recommendation slots |
|
||||
| `POST` | `/moods/{id}/recommendations/refresh` | Force discovery + top-up |
|
||||
| `POST` | `/moods/{id}/recommendations/rotate` | Retire every active pick and fill the slots with different tracks |
|
||||
| `POST` | `/moods/{id}/recommendations/{externalId}/add` | Add to the collection |
|
||||
| `POST` | `/moods/{id}/recommendations/{externalId}/reject` | Hide permanently |
|
||||
| `POST` | `/moods/{id}/recommendations/{externalId}/retry` | Retry a failed download |
|
||||
@@ -270,8 +277,9 @@ album and cover art, so the indexer can derive the metadata from the file.
|
||||
|
||||
A file is deleted only when it has no references from `mood_songs`, an active
|
||||
recommendation (`downloading`, `ready`, `added`, `failed`), or an open playback
|
||||
session. GC runs after removals, after rejections, after mood deletion, and
|
||||
hourly.
|
||||
session. Rotated and rejected slots do not keep a file alive, so a retired pick
|
||||
disappears once no open session still queues it. GC runs after removals, after
|
||||
rejections, after mood deletion, and hourly.
|
||||
|
||||
## Database
|
||||
|
||||
@@ -285,6 +293,9 @@ SQLite in WAL mode. Migrations are Flyway scripts under
|
||||
- **V9 adds sources.** It renames `video_id` to `external_id` and adds a
|
||||
`source` column to songs, moods, recommendations and download jobs. Existing
|
||||
rows become `youtube`.
|
||||
- **V12 adds rotation.** It rebuilds `mood_recommendations` to allow the
|
||||
`rotated` state and adds `play_count`, `rotated_at` and the mood-level
|
||||
`recommendation_rotation_plays` (default 3).
|
||||
- There is no import from an old media directory. Back up externally and start
|
||||
with an empty `MEDIA_DIR`.
|
||||
|
||||
|
||||
@@ -2,5 +2,5 @@ apiVersion: v2
|
||||
name: audiomanager
|
||||
description: Mood-first self-hosted music server
|
||||
type: application
|
||||
version: 0.5.0
|
||||
version: 0.6.0
|
||||
appVersion: "0.1.0"
|
||||
@@ -760,7 +760,15 @@ Phases 1-8 are implemented in both repositories.
|
||||
Uncaught exceptions are stored on Android and desktop and uploaded on the next
|
||||
launch. Every response carries `X-Request-Id`, which the client includes in
|
||||
server-error diagnostics so a report can be matched to the server log.
|
||||
- Tests: 26 client tests; desktop, Android debug and Wasm compile.
|
||||
- **Rotation (V12)**: `mood_recommendations.play_count` counts plays (`started`
|
||||
events). At `moods.recommendation_rotation_plays` (0–100, default 3) the slot
|
||||
becomes `rotated` and TopUpService fills it from the hidden pool. Rotated rows
|
||||
are a 30-day cooldown, not a rejection: discovery revives them as `new`
|
||||
candidates after that. `POST /moods/{id}/recommendations/rotate` retires every
|
||||
active slot for the **All new** action; plain `refresh` still only discovers
|
||||
and tops up. The file follows the usual reference rules and is deleted by the
|
||||
GC once no mood or open session needs it.
|
||||
- Tests: 28 client tests; desktop, Android debug and Wasm compile.
|
||||
|
||||
|
||||
### Known follow-ups
|
||||
|
||||
@@ -154,6 +154,8 @@ data class MoodDto(
|
||||
val collectionPercent: Int,
|
||||
val recommendationPercent: Int,
|
||||
val recommendationCount: Int,
|
||||
/** Plays before a recommendation is replaced; 0 = never rotate. */
|
||||
val recommendationRotationPlays: Int,
|
||||
val refreshHours: Int,
|
||||
val lastDiscoveryAt: String? = null,
|
||||
val createdAt: String,
|
||||
@@ -175,6 +177,7 @@ fun MoodRecord.toDto(): MoodDto = MoodDto(
|
||||
collectionPercent = collectionPercent,
|
||||
recommendationPercent = 100 - collectionPercent,
|
||||
recommendationCount = recommendationCount,
|
||||
recommendationRotationPlays = recommendationRotationPlays,
|
||||
refreshHours = refreshHours,
|
||||
lastDiscoveryAt = lastDiscoveryAt,
|
||||
createdAt = createdAt,
|
||||
@@ -220,6 +223,8 @@ data class RecommendationDto(
|
||||
val error: String? = null,
|
||||
val firstSeen: String,
|
||||
val lastSeen: String,
|
||||
/** How often this active slot was played; rotation replaces it at the mood limit. */
|
||||
val playCount: Int = 0,
|
||||
)
|
||||
|
||||
fun RecommendationRecord.toDto(
|
||||
@@ -239,6 +244,7 @@ fun RecommendationRecord.toDto(
|
||||
error = error,
|
||||
firstSeen = firstSeen,
|
||||
lastSeen = lastSeen,
|
||||
playCount = playCount,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
@@ -275,6 +281,7 @@ data class CreateMoodRequest(
|
||||
val source: String? = null,
|
||||
val collectionPercent: Int = 50,
|
||||
val recommendationCount: Int = 10,
|
||||
val recommendationRotationPlays: Int = 3,
|
||||
val refreshHours: Int = 24,
|
||||
)
|
||||
|
||||
@@ -289,6 +296,7 @@ data class UpdateMoodRequest(
|
||||
val source: String? = null,
|
||||
val collectionPercent: Int? = null,
|
||||
val recommendationCount: Int? = null,
|
||||
val recommendationRotationPlays: Int? = null,
|
||||
val refreshHours: Int? = null,
|
||||
)
|
||||
|
||||
|
||||
@@ -152,7 +152,7 @@ fun Route.apiRoutes(
|
||||
gc = gc,
|
||||
defaultSource = defaultSource,
|
||||
)
|
||||
sessionRoutes(users, radioService, gc)
|
||||
sessionRoutes(users, radioService, topUpService, gc)
|
||||
logRoutes(users)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,6 +33,16 @@ data class MoodsResponse(val moods: List<MoodDto>)
|
||||
@Serializable
|
||||
data class RecommendationsResponse(val recommendations: List<RecommendationDto>)
|
||||
|
||||
@Serializable
|
||||
data class RecommendationRotationDto(
|
||||
val detail: MoodDetailDto,
|
||||
/** Active slots retired by this action. */
|
||||
val rotated: Int,
|
||||
/** Slots active afterwards (downloading, ready or failed). */
|
||||
val active: Int,
|
||||
val error: String? = null,
|
||||
)
|
||||
|
||||
fun Route.moodRoutes(
|
||||
users: UsersConfig,
|
||||
radioService: RadioService,
|
||||
@@ -67,6 +77,7 @@ fun Route.moodRoutes(
|
||||
source = source,
|
||||
collectionPercent = request.collectionPercent,
|
||||
recommendationCount = request.recommendationCount,
|
||||
recommendationRotationPlays = request.recommendationRotationPlays,
|
||||
refreshHours = request.refreshHours,
|
||||
)
|
||||
if (mood.recommendationCount > 0) topUpService.trigger(mood)
|
||||
@@ -109,6 +120,8 @@ fun Route.moodRoutes(
|
||||
source = source,
|
||||
collectionPercent = request.collectionPercent ?: mood.collectionPercent,
|
||||
recommendationCount = request.recommendationCount ?: mood.recommendationCount,
|
||||
recommendationRotationPlays = request.recommendationRotationPlays
|
||||
?: mood.recommendationRotationPlays,
|
||||
refreshHours = request.refreshHours ?: mood.refreshHours,
|
||||
) ?: notFound("Mood")
|
||||
|
||||
@@ -155,6 +168,41 @@ fun Route.moodRoutes(
|
||||
call.respond(detail(refreshed))
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces every active recommendation with different tracks. Unlike
|
||||
* `refresh`, which only runs discovery and tops up empty slots, this retires
|
||||
* the tracks the user already sees, so the mood must find new ones.
|
||||
*/
|
||||
post("/moods/{id}/recommendations/rotate") {
|
||||
val user = call.requireApiUser(users)
|
||||
val mood = ownedMood(call.parameters["id"], user)
|
||||
if (mood.recommendationCount <= 0) conflict("Recommendations are disabled for this mood")
|
||||
|
||||
val rotated = MoodRepository.rotateActive(mood.id)
|
||||
rotated.forEach { recommendation ->
|
||||
DownloadRepository.cancelForMoodTrack(
|
||||
mood.id,
|
||||
recommendation.externalId,
|
||||
"Recommendation rotated",
|
||||
)
|
||||
recommendation.songId?.let(gc::collect)
|
||||
}
|
||||
|
||||
val outcome = withContext(Dispatchers.IO) {
|
||||
discoveryService.refresh(mood, force = true)
|
||||
}
|
||||
topUpService.topUp(mood, force = false)
|
||||
val refreshed = MoodRepository.get(mood.id, user.name) ?: mood
|
||||
call.respond(
|
||||
RecommendationRotationDto(
|
||||
detail = detail(refreshed),
|
||||
rotated = rotated.size,
|
||||
active = MoodRepository.activeCount(mood.id),
|
||||
error = outcome.error,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
post("/moods/{id}/recommendations/{externalId}/add") {
|
||||
val user = call.requireApiUser(users)
|
||||
val mood = ownedMood(call.parameters["id"], user)
|
||||
|
||||
@@ -7,6 +7,8 @@ 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
|
||||
@@ -14,12 +16,14 @@ 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") {
|
||||
@@ -88,10 +92,30 @@ fun Route.sessionRoutes(
|
||||
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 ->
|
||||
event.type in EVENT_TYPES &&
|
||||
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))
|
||||
}
|
||||
@@ -138,5 +162,7 @@ private fun ownedSession(id: String?, user: UserAccount): PlaybackSessionRecord
|
||||
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")
|
||||
@@ -31,6 +31,8 @@ data class MoodRecord(
|
||||
val source: String,
|
||||
val collectionPercent: Int,
|
||||
val recommendationCount: Int,
|
||||
/** Plays before an active recommendation is replaced; 0 = never. */
|
||||
val recommendationRotationPlays: Int,
|
||||
val refreshHours: Int,
|
||||
val lastDiscoveryAt: String?,
|
||||
val createdAt: String,
|
||||
@@ -73,6 +75,15 @@ data class RecommendationRecord(
|
||||
val rank: Int,
|
||||
val firstSeen: String,
|
||||
val lastSeen: String,
|
||||
val playCount: Int,
|
||||
)
|
||||
|
||||
/** A recommendation slot retired by rotation, with its file when it has one. */
|
||||
data class RotatedRecommendation(
|
||||
val externalId: String,
|
||||
val songId: String?,
|
||||
/** The play that retired it (the mood's threshold), or 0 for a bulk rotate. */
|
||||
val plays: Int = 0,
|
||||
)
|
||||
|
||||
/** Result of applying a finished download to a recommendation. */
|
||||
@@ -134,6 +145,7 @@ object MoodRepository {
|
||||
source: String,
|
||||
collectionPercent: Int,
|
||||
recommendationCount: Int,
|
||||
recommendationRotationPlays: Int,
|
||||
refreshHours: Int,
|
||||
): MoodRecord = transaction {
|
||||
val now = Instant.now().toString()
|
||||
@@ -149,6 +161,8 @@ object MoodRepository {
|
||||
it[MoodsTable.musicSource] = source
|
||||
it[MoodsTable.collectionPercent] = collectionPercent.coerceIn(0, 100)
|
||||
it[MoodsTable.recommendationCount] = recommendationCount.coerceIn(0, 30)
|
||||
it[MoodsTable.recommendationRotationPlays] =
|
||||
recommendationRotationPlays.coerceIn(0, MAX_ROTATION_PLAYS)
|
||||
it[MoodsTable.refreshHours] = refreshHours.coerceIn(1, 720)
|
||||
it[createdAt] = now
|
||||
it[changedAt] = now
|
||||
@@ -167,6 +181,7 @@ object MoodRepository {
|
||||
source: String,
|
||||
collectionPercent: Int,
|
||||
recommendationCount: Int,
|
||||
recommendationRotationPlays: Int,
|
||||
refreshHours: Int,
|
||||
): MoodRecord? = transaction {
|
||||
val current = MoodsTable.selectAll()
|
||||
@@ -193,6 +208,8 @@ object MoodRepository {
|
||||
it[MoodsTable.musicSource] = source
|
||||
it[MoodsTable.collectionPercent] = collectionPercent.coerceIn(0, 100)
|
||||
it[MoodsTable.recommendationCount] = recommendationCount.coerceIn(0, 30)
|
||||
it[MoodsTable.recommendationRotationPlays] =
|
||||
recommendationRotationPlays.coerceIn(0, MAX_ROTATION_PLAYS)
|
||||
it[MoodsTable.refreshHours] = refreshHours.coerceIn(1, 720)
|
||||
it[MoodsTable.changedAt] = Instant.now().toString()
|
||||
if (sourceChanged) {
|
||||
@@ -520,7 +537,9 @@ object MoodRepository {
|
||||
?: return@transaction RecommendationCompletion.MISSING
|
||||
|
||||
when (row[MoodRecommendationsTable.state]) {
|
||||
"rejected" -> RecommendationCompletion.REJECTED
|
||||
// The user rejected it, or rotation retired it while the download
|
||||
// was still running. Either way the file is not a live slot.
|
||||
"rejected", "rotated" -> RecommendationCompletion.REJECTED
|
||||
"added" -> {
|
||||
insertRecommendationSong(moodId, songId)
|
||||
MoodRecommendationsTable.update({
|
||||
@@ -575,6 +594,115 @@ object MoodRepository {
|
||||
setRecommendationState(moodId, externalId, "rejected")
|
||||
}
|
||||
|
||||
/**
|
||||
* Counts a play of an active recommendation and retires it once the mood's
|
||||
* threshold is reached. Returns the retired slot so the caller can refill
|
||||
* the mood; the GC keeps the file while a session still queues it.
|
||||
*/
|
||||
fun recordPlay(
|
||||
moodId: String,
|
||||
songId: String,
|
||||
playedAt: Instant = Instant.now(),
|
||||
): RotatedRecommendation? = transaction {
|
||||
val limit = MoodsTable.select(MoodsTable.recommendationRotationPlays)
|
||||
.where { MoodsTable.id eq moodId }
|
||||
.singleOrNull()
|
||||
?.get(MoodsTable.recommendationRotationPlays)
|
||||
?: return@transaction null
|
||||
if (limit <= 0) return@transaction null
|
||||
|
||||
val row = MoodRecommendationsTable.selectAll()
|
||||
.where {
|
||||
(MoodRecommendationsTable.moodId eq moodId) and
|
||||
(MoodRecommendationsTable.songId eq songId) and
|
||||
(MoodRecommendationsTable.state eq "ready")
|
||||
}
|
||||
.singleOrNull()
|
||||
?: return@transaction null
|
||||
|
||||
val plays = row[MoodRecommendationsTable.playCount] + 1
|
||||
val retire = plays >= limit
|
||||
MoodRecommendationsTable.update({
|
||||
(MoodRecommendationsTable.moodId eq moodId) and
|
||||
(MoodRecommendationsTable.externalId eq row[MoodRecommendationsTable.externalId])
|
||||
}) {
|
||||
it[playCount] = plays
|
||||
if (retire) {
|
||||
it[state] = "rotated"
|
||||
it[rotatedAt] = playedAt.toString()
|
||||
}
|
||||
}
|
||||
if (!retire) {
|
||||
null
|
||||
} else {
|
||||
RotatedRecommendation(
|
||||
externalId = row[MoodRecommendationsTable.externalId],
|
||||
songId = row[MoodRecommendationsTable.songId],
|
||||
plays = plays,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retires every active slot, including queued downloads. The caller forces a
|
||||
* discovery pass and a top-up so the mood is refilled with different picks.
|
||||
*/
|
||||
fun rotateActive(
|
||||
moodId: String,
|
||||
rotatedAt: Instant = Instant.now(),
|
||||
): List<RotatedRecommendation> = transaction {
|
||||
val rows = MoodRecommendationsTable.selectAll()
|
||||
.where {
|
||||
(MoodRecommendationsTable.moodId eq moodId) and
|
||||
(MoodRecommendationsTable.state inList ACTIVE_STATES)
|
||||
}
|
||||
.toList()
|
||||
if (rows.isEmpty()) return@transaction emptyList()
|
||||
|
||||
MoodRecommendationsTable.update({
|
||||
(MoodRecommendationsTable.moodId eq moodId) and
|
||||
(MoodRecommendationsTable.state inList ACTIVE_STATES)
|
||||
}) {
|
||||
it[state] = "rotated"
|
||||
it[this.rotatedAt] = rotatedAt.toString()
|
||||
}
|
||||
rows.map {
|
||||
RotatedRecommendation(
|
||||
externalId = it[MoodRecommendationsTable.externalId],
|
||||
songId = it[MoodRecommendationsTable.songId],
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes slots retired before [before] eligible again. Rotation is a
|
||||
* cooldown, not a rejection: after enough time the same catalog can offer
|
||||
* the track to a long-lived mood again instead of running dry.
|
||||
*/
|
||||
fun reviveRotated(moodId: String, source: String, before: Instant): Int = transaction {
|
||||
val stale = MoodRecommendationsTable.selectAll()
|
||||
.where {
|
||||
(MoodRecommendationsTable.moodId eq moodId) and
|
||||
(MoodRecommendationsTable.musicSource eq source) and
|
||||
(MoodRecommendationsTable.state eq "rotated") and
|
||||
(MoodRecommendationsTable.rotatedAt less before.toString())
|
||||
}
|
||||
.map { it[MoodRecommendationsTable.externalId] }
|
||||
if (stale.isEmpty()) return@transaction 0
|
||||
|
||||
MoodRecommendationsTable.update({
|
||||
(MoodRecommendationsTable.moodId eq moodId) and
|
||||
(MoodRecommendationsTable.externalId inList stale)
|
||||
}) {
|
||||
it[state] = "new"
|
||||
it[playCount] = 0
|
||||
it[rotatedAt] = null
|
||||
// At the end of the pool so a fresh discovery result wins.
|
||||
it[rank] = CANDIDATE_POOL
|
||||
}
|
||||
stale.size
|
||||
}
|
||||
|
||||
fun readySongs(moodId: String): List<SongRecord> = transaction {
|
||||
val songIds = MoodRecommendationsTable
|
||||
.select(MoodRecommendationsTable.songId)
|
||||
@@ -677,6 +805,7 @@ object MoodRepository {
|
||||
rank = this[MoodRecommendationsTable.rank],
|
||||
firstSeen = this[MoodRecommendationsTable.firstSeen],
|
||||
lastSeen = this[MoodRecommendationsTable.lastSeen],
|
||||
playCount = this[MoodRecommendationsTable.playCount],
|
||||
)
|
||||
|
||||
private fun ResultRow.toSongRecord() = SongRecord(
|
||||
@@ -718,6 +847,7 @@ object MoodRepository {
|
||||
source = row[MoodsTable.musicSource],
|
||||
collectionPercent = row[MoodsTable.collectionPercent],
|
||||
recommendationCount = row[MoodsTable.recommendationCount],
|
||||
recommendationRotationPlays = row[MoodsTable.recommendationRotationPlays],
|
||||
refreshHours = row[MoodsTable.refreshHours],
|
||||
lastDiscoveryAt = row[MoodsTable.lastDiscoveryAt],
|
||||
createdAt = row[MoodsTable.createdAt],
|
||||
@@ -750,4 +880,5 @@ object MoodRepository {
|
||||
|
||||
private val ORIGINS = setOf("search", "recommendation", "url")
|
||||
private const val CANDIDATE_POOL = 60
|
||||
private const val MAX_ROTATION_PLAYS = 100
|
||||
}
|
||||
@@ -58,6 +58,9 @@ object MoodsTable : Table("moods") {
|
||||
val musicSource = varchar("source", 16).default(MusicSource.YOUTUBE)
|
||||
val collectionPercent = integer("collection_percent").default(50)
|
||||
val recommendationCount = integer("recommendation_count").default(10)
|
||||
|
||||
/** Plays before an active recommendation is replaced; 0 disables rotation. */
|
||||
val recommendationRotationPlays = integer("recommendation_rotation_plays").default(3)
|
||||
val refreshHours = integer("refresh_hours").default(24)
|
||||
val lastDiscoveryAt = varchar("last_discovery_at", 40).nullable()
|
||||
val createdAt = varchar("created_at", 40)
|
||||
@@ -97,6 +100,12 @@ object MoodRecommendationsTable : Table("mood_recommendations") {
|
||||
val firstSeen = varchar("first_seen", 40)
|
||||
val lastSeen = varchar("last_seen", 40)
|
||||
|
||||
/** How many times the user played this active slot; reset when it revives. */
|
||||
val playCount = integer("play_count").default(0)
|
||||
|
||||
/** When the slot was retired, so discovery can exclude it for a cooldown. */
|
||||
val rotatedAt = varchar("rotated_at", 40).nullable()
|
||||
|
||||
override val primaryKey = PrimaryKey(moodId, externalId)
|
||||
}
|
||||
|
||||
|
||||
@@ -38,6 +38,17 @@ class DiscoveryService(
|
||||
return DiscoveryOutcome(0, skipped = true)
|
||||
}
|
||||
|
||||
// Rotation is a cooldown, not a rejection: tracks retired a while ago
|
||||
// may be offered again instead of draining the catalog forever.
|
||||
val revived = MoodRepository.reviveRotated(
|
||||
mood.id,
|
||||
mood.source,
|
||||
now.minus(ROTATION_COOLDOWN_DAYS, ChronoUnit.DAYS),
|
||||
)
|
||||
if (revived > 0) {
|
||||
log.info("Revived {} rotated recommendations for mood {}", revived, mood.name)
|
||||
}
|
||||
|
||||
val catalog = catalogs.forSource(mood.source)
|
||||
val collection = MoodRepository.songRecords(mood.id)
|
||||
val artists = artistsByFrequency(collection)
|
||||
@@ -180,6 +191,7 @@ class DiscoveryService(
|
||||
const val DISCOVERY_LIMIT = 200
|
||||
const val RADIO_SEEDS = 2
|
||||
const val CANDIDATE_POOL = 60
|
||||
const val ROTATION_COOLDOWN_DAYS = 30L
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
-- Recommendation rotation.
|
||||
--
|
||||
-- A recommendation is not permanent: after the user has played it a few times
|
||||
-- the server retires it and fills the slot with a different pick. The threshold
|
||||
-- lives on the mood (`0` disables rotation) and the count lives on the slot.
|
||||
--
|
||||
-- Retiring needs a new `rotated` state, and SQLite cannot widen a CHECK
|
||||
-- constraint in place, so the table is rebuilt. Rotated rows are kept (not
|
||||
-- deleted) so discovery can exclude them for a cooldown window; afterwards
|
||||
-- [MoodRepository.reviveRotated] turns them back into candidates. That avoids
|
||||
-- exhausting the catalog of a long-lived mood.
|
||||
CREATE TABLE mood_recommendations_new (
|
||||
mood_id TEXT NOT NULL REFERENCES moods(id) ON DELETE CASCADE,
|
||||
source TEXT NOT NULL DEFAULT 'youtube'
|
||||
CHECK (source IN ('youtube', 'deezer')),
|
||||
external_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', 'downloading', 'ready', 'failed', 'added', 'rejected', 'rotated')),
|
||||
song_id TEXT REFERENCES songs(id) ON DELETE SET NULL,
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
error TEXT,
|
||||
rank INTEGER NOT NULL DEFAULT 0,
|
||||
first_seen TEXT NOT NULL,
|
||||
last_seen TEXT NOT NULL,
|
||||
play_count INTEGER NOT NULL DEFAULT 0,
|
||||
rotated_at TEXT,
|
||||
PRIMARY KEY (mood_id, external_id)
|
||||
);
|
||||
|
||||
INSERT INTO mood_recommendations_new (
|
||||
mood_id, source, external_id, title, artist, album, duration, thumbnail,
|
||||
state, song_id, attempts, error, rank, first_seen, last_seen
|
||||
)
|
||||
SELECT
|
||||
mood_id, source, external_id, title, artist, album, duration, thumbnail,
|
||||
state, song_id, attempts, error, rank, first_seen, last_seen
|
||||
FROM mood_recommendations;
|
||||
|
||||
DROP TABLE mood_recommendations;
|
||||
ALTER TABLE mood_recommendations_new RENAME TO mood_recommendations;
|
||||
|
||||
CREATE INDEX idx_mood_recommendations_state ON mood_recommendations (mood_id, state);
|
||||
CREATE INDEX idx_mood_recommendations_song ON mood_recommendations (song_id);
|
||||
|
||||
-- 0 = never rotate automatically; the Settings screen defaults to 3.
|
||||
ALTER TABLE moods ADD COLUMN recommendation_rotation_plays INTEGER NOT NULL DEFAULT 3
|
||||
CHECK (recommendation_rotation_plays BETWEEN 0 AND 100);
|
||||
@@ -34,6 +34,7 @@ import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFalse
|
||||
import kotlin.test.assertNotNull
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.test.assertTrue
|
||||
import org.junit.jupiter.api.io.TempDir
|
||||
import win.taptap.musicmanager.TestAudio
|
||||
@@ -647,6 +648,130 @@ class ApiRoutesTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `playing a recommendation rotates it at the mood limit`() {
|
||||
seededContext().use { seed ->
|
||||
val results = listOf(
|
||||
yt("vid-rotate", "Rotate Me", "Artist", 180),
|
||||
yt("vid-next", "Next Pick", "Artist", 180),
|
||||
)
|
||||
testApplication {
|
||||
setupApp(seed, youtubeResults = results)
|
||||
val token = client.token("alice", "alice-pw")
|
||||
val moodId = client.createMood(
|
||||
token,
|
||||
"""{"name":"Rotate","source":"youtube","recommendationCount":1,
|
||||
"recommendationRotationPlays":2}""",
|
||||
)
|
||||
client.addSong(token, moodId, seed.ambient1)
|
||||
|
||||
val created = parse(
|
||||
client.get("/api/v1/moods/$moodId") { bearer(token) }.bodyAsText(),
|
||||
)
|
||||
assertEquals(2, created["mood"]!!.jsonObject.int("recommendationRotationPlays"))
|
||||
|
||||
client.post("/api/v1/moods/$moodId/recommendations/refresh") { bearer(token) }
|
||||
val slot = MoodRepository.recommendations(moodId).single()
|
||||
val songId = insertSong(seed, MusicSource.YOUTUBE, slot.externalId, "Rotate Me")
|
||||
MoodRepository.completeDownload(
|
||||
moodId,
|
||||
MusicSource.YOUTUBE,
|
||||
slot.externalId,
|
||||
songId,
|
||||
)
|
||||
|
||||
val session = parse(
|
||||
client.post("/api/v1/moods/$moodId/sessions") {
|
||||
bearer(token)
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody("""{"limit":10}""")
|
||||
}.bodyAsText(),
|
||||
)
|
||||
val sessionId = session["id"]!!.jsonPrimitive.content
|
||||
assertTrue(
|
||||
session["queue"]!!.jsonArray.any {
|
||||
it.jsonObject.string("id") == songId
|
||||
},
|
||||
)
|
||||
|
||||
repeat(2) {
|
||||
val event = client.post("/api/v1/sessions/$sessionId/events") {
|
||||
bearer(token)
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody("""{"events":[{"songId":"$songId","type":"started"}]}""")
|
||||
}
|
||||
assertEquals(1, parse(event.bodyAsText()).int("accepted"))
|
||||
}
|
||||
|
||||
val retired = assertNotNull(
|
||||
MoodRepository.recommendation(moodId, slot.externalId),
|
||||
)
|
||||
assertEquals("rotated", retired.state)
|
||||
assertEquals(2, retired.playCount)
|
||||
val detail = parse(
|
||||
client.get("/api/v1/moods/$moodId") { bearer(token) }.bodyAsText(),
|
||||
)
|
||||
assertTrue(
|
||||
detail["recommendations"]!!.jsonArray.none {
|
||||
it.jsonObject.string("externalId") == slot.externalId
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `rotating picks retires every active slot and refills the mood`() {
|
||||
seededContext().use { seed ->
|
||||
val results = (1..5).map { yt("vid-$it", "Pick $it", "Artist $it", 180) }
|
||||
testApplication {
|
||||
setupApp(seed, youtubeResults = results)
|
||||
val token = client.token("alice", "alice-pw")
|
||||
val moodId = client.createMood(
|
||||
token,
|
||||
"""{"name":"Swap","source":"youtube","recommendationCount":2}""",
|
||||
)
|
||||
client.addSong(token, moodId, seed.ambient1)
|
||||
client.post("/api/v1/moods/$moodId/recommendations/refresh") { bearer(token) }
|
||||
|
||||
val before = MoodRepository.recommendations(moodId)
|
||||
assertEquals(2, before.size)
|
||||
before.forEach { slot ->
|
||||
val songId = insertSong(seed, MusicSource.YOUTUBE, slot.externalId, slot.title)
|
||||
MoodRepository.completeDownload(
|
||||
moodId,
|
||||
MusicSource.YOUTUBE,
|
||||
slot.externalId,
|
||||
songId,
|
||||
)
|
||||
}
|
||||
|
||||
val rotated = client.post("/api/v1/moods/$moodId/recommendations/rotate") {
|
||||
bearer(token)
|
||||
}
|
||||
assertEquals(HttpStatusCode.OK, rotated.status)
|
||||
val body = parse(rotated.bodyAsText())
|
||||
assertEquals(2, body.int("rotated"))
|
||||
assertEquals(2, body.int("active"))
|
||||
|
||||
val replaced = body["detail"]!!.jsonObject["recommendations"]!!.jsonArray
|
||||
.map { it.jsonObject.string("externalId") }
|
||||
assertEquals(2, replaced.size)
|
||||
assertTrue(replaced.none { it in before.map { slot -> slot.externalId } })
|
||||
assertTrue(
|
||||
body["detail"]!!.jsonObject["recommendations"]!!.jsonArray
|
||||
.all { it.jsonObject.int("playCount") == 0 },
|
||||
)
|
||||
before.forEach { slot ->
|
||||
assertEquals(
|
||||
"rotated",
|
||||
MoodRepository.recommendation(moodId, slot.externalId)?.state,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `streaming and covers work with a query token`() {
|
||||
seededContext().use { seed ->
|
||||
|
||||
@@ -163,6 +163,7 @@ class MoodRepositoryTest {
|
||||
source = MusicSource.DEEZER,
|
||||
collectionPercent = mood.collectionPercent,
|
||||
recommendationCount = mood.recommendationCount,
|
||||
recommendationRotationPlays = mood.recommendationRotationPlays,
|
||||
refreshHours = mood.refreshHours,
|
||||
),
|
||||
)
|
||||
@@ -364,10 +365,75 @@ class MoodRepositoryTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `plays retire a recommendation at the mood limit`() {
|
||||
withDatabase { mediaStore, _ ->
|
||||
val mood = createMood(recommendationCount = 1, rotationPlays = 2)
|
||||
storeCandidates(mood.id, 2)
|
||||
val promoted = MoodRepository.promoteCandidates(mood.id, MusicSource.YOUTUBE, 1).single()
|
||||
val song = insertSong(
|
||||
mediaStore,
|
||||
MusicSource.YOUTUBE,
|
||||
"vid-${promoted.externalId}",
|
||||
"Track ${promoted.externalId}",
|
||||
)
|
||||
MoodRepository.completeDownload(
|
||||
mood.id,
|
||||
MusicSource.YOUTUBE,
|
||||
promoted.externalId,
|
||||
song.id,
|
||||
)
|
||||
|
||||
assertNull(MoodRepository.recordPlay(mood.id, song.id))
|
||||
assertEquals(1, MoodRepository.recommendation(mood.id, promoted.externalId)?.playCount)
|
||||
|
||||
val rotated = assertNotNull(MoodRepository.recordPlay(mood.id, song.id))
|
||||
assertEquals(2, rotated.plays)
|
||||
val retired = assertNotNull(MoodRepository.recommendation(mood.id, promoted.externalId))
|
||||
assertEquals("rotated", retired.state)
|
||||
// A retired slot is not counted again, even if the client re-sends
|
||||
// the event or the track replays from an old queue.
|
||||
assertNull(MoodRepository.recordPlay(mood.id, song.id))
|
||||
|
||||
// After the cooldown the same catalog may offer it again.
|
||||
assertEquals(
|
||||
1,
|
||||
MoodRepository.reviveRotated(
|
||||
mood.id,
|
||||
MusicSource.YOUTUBE,
|
||||
Instant.now().plusSeconds(60),
|
||||
),
|
||||
)
|
||||
val revived = assertNotNull(MoodRepository.recommendation(mood.id, promoted.externalId))
|
||||
assertEquals("new", revived.state)
|
||||
assertEquals(0, revived.playCount)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `bulk rotation retires every active slot`() {
|
||||
withDatabase { _, _ ->
|
||||
val mood = createMood(recommendationCount = 2)
|
||||
storeCandidates(mood.id, 4)
|
||||
assertEquals(2, MoodRepository.promoteCandidates(mood.id, MusicSource.YOUTUBE, 2).size)
|
||||
|
||||
val rotated = MoodRepository.rotateActive(mood.id)
|
||||
assertEquals(2, rotated.size)
|
||||
assertEquals(0, MoodRepository.activeCount(mood.id))
|
||||
assertTrue(
|
||||
MoodRepository.allRecommendations(mood.id)
|
||||
.filter { it.externalId in rotated.map { slot -> slot.externalId } }
|
||||
.all { it.state == "rotated" },
|
||||
)
|
||||
assertTrue(MoodRepository.rotateActive(mood.id).isEmpty())
|
||||
}
|
||||
}
|
||||
|
||||
private fun createMood(
|
||||
recommendationCount: Int,
|
||||
name: String = "Focus",
|
||||
source: String = MusicSource.YOUTUBE,
|
||||
rotationPlays: Int = 3,
|
||||
): MoodRecord = MoodRepository.create(
|
||||
owner = "alice",
|
||||
name = name,
|
||||
@@ -377,6 +443,7 @@ class MoodRepositoryTest {
|
||||
source = source,
|
||||
collectionPercent = 50,
|
||||
recommendationCount = recommendationCount,
|
||||
recommendationRotationPlays = rotationPlays,
|
||||
refreshHours = 24,
|
||||
)
|
||||
|
||||
|
||||
@@ -450,6 +450,7 @@ class DiscoveryServiceTest {
|
||||
source = MusicSource.DEEZER,
|
||||
collectionPercent = 50,
|
||||
recommendationCount = 10,
|
||||
recommendationRotationPlays = 3,
|
||||
refreshHours = 24,
|
||||
lastDiscoveryAt = null,
|
||||
createdAt = "2026-01-01T00:00:00Z",
|
||||
|
||||
@@ -336,6 +336,7 @@ class DownloadServiceTest {
|
||||
source = source,
|
||||
collectionPercent = 50,
|
||||
recommendationCount = recommendationCount,
|
||||
recommendationRotationPlays = 3,
|
||||
refreshHours = 24,
|
||||
)
|
||||
|
||||
|
||||
Reference in new issue
Block a user