feat: rebuild AudioManager around downloadable moods
CI / chart (push) Successful in 3s
CI / test (push) Successful in 2m2s
CI / chart-push (push) Successful in 4s
CI / image (push) Successful in 3m20s

- 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
This commit is contained in:
TapTap committed 2026-11-15 21:37:39 +00:00
1 parent 50d8b6c580
commit 824eb36dd2
59 files changed
+3838 -5276

No files matched your search

@@ -9,6 +9,8 @@ import org.jetbrains.exposed.sql.ResultRow
import org.jetbrains.exposed.sql.SortOrder
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
import org.jetbrains.exposed.sql.SqlExpressionBuilder.inList
import org.jetbrains.exposed.sql.SqlExpressionBuilder.inSubQuery
import org.jetbrains.exposed.sql.SqlExpressionBuilder.notInList
import org.jetbrains.exposed.sql.and
import org.jetbrains.exposed.sql.deleteWhere
import org.jetbrains.exposed.sql.insert
@@ -25,19 +27,20 @@ data class MoodRecord(
val description: String?,
val query: String?,
val genres: List<String>,
val targetSize: Int,
val seedPercent: Int = 50,
val collectionPercent: Int,
val recommendationCount: Int,
val refreshHours: Int,
val ytEnabled: Boolean,
val lastDiscoveryAt: String?,
val createdAt: String,
val changedAt: String,
val lastError: String?,
val seedCount: Int,
val newRecommendations: Int,
val songCount: Int,
val recommendationReady: Int,
val recommendationDownloading: Int,
val recommendationFailed: Int,
)
data class MoodSeedRecord(
data class MoodSongRecord(
val songId: String,
val origin: String,
val addedAt: String,
@@ -50,7 +53,6 @@ data class RecommendationUpsert(
val album: String?,
val duration: Int?,
val thumbnail: String?,
val matchedSongId: String?,
)
data class RecommendationRecord(
@@ -61,21 +63,31 @@ data class RecommendationRecord(
val duration: Int?,
val thumbnail: String?,
val state: String,
val matchedSongId: String?,
val timesAdded: Int,
val songId: String?,
val attempts: Int,
val error: String?,
val rank: Int,
val firstSeen: String,
val lastSeen: String,
)
/** Result of applying a finished download to a recommendation. */
enum class RecommendationCompletion { READY, ALREADY_ADDED, REJECTED, MISSING }
/**
* 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.
* Moods are the product's only collection. Songs are permanent entries; the
* recommendation table also holds hidden `new` candidates and the lifecycle of
* the active slots. 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())
private val ACTIVE_STATES = listOf("downloading", "ready", "failed")
private val VISIBLE_STATES = ACTIVE_STATES
private val HIDDEN_DECISIONS = listOf("added", "rejected")
fun list(owner: String): List<MoodRecord> = transaction {
MoodsTable.selectAll()
.where { MoodsTable.owner eq owner }
@@ -83,6 +95,12 @@ object MoodRepository {
.map { moodRecord(it) }
}
fun all(): List<MoodRecord> = transaction {
MoodsTable.selectAll()
.orderBy(MoodsTable.changedAt to SortOrder.DESC)
.map { moodRecord(it) }
}
fun get(id: String, owner: String): MoodRecord? = transaction {
MoodsTable.selectAll()
.where { (MoodsTable.id eq id) and (MoodsTable.owner eq owner) }
@@ -96,11 +114,9 @@ object MoodRepository {
description: String?,
query: String?,
genres: List<String>,
targetSize: Int,
collectionPercent: Int,
recommendationCount: Int,
refreshHours: Int,
ytEnabled: Boolean,
seedSongIds: List<String>,
seedPercent: Int = 50,
): MoodRecord = transaction {
val now = Instant.now().toString()
val id = IdGenerator.moodId(owner, name, now)
@@ -112,19 +128,14 @@ object MoodRepository {
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.seedPercent] = seedPercent.coerceIn(0, 100)
it[MoodsTable.collectionPercent] = collectionPercent.coerceIn(0, 100)
it[MoodsTable.recommendationCount] = recommendationCount.coerceIn(0, 30)
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(),
)
moodRecord(MoodsTable.selectAll().where { MoodsTable.id eq id }.single())
}
fun update(
@@ -134,10 +145,9 @@ object MoodRepository {
description: String?,
query: String?,
genres: List<String>,
targetSize: Int,
collectionPercent: Int,
recommendationCount: Int,
refreshHours: Int,
ytEnabled: Boolean,
seedPercent: Int,
): MoodRecord? = transaction {
val exists = MoodsTable.selectAll()
.where { (MoodsTable.id eq id) and (MoodsTable.owner eq owner) }
@@ -149,11 +159,10 @@ object MoodRepository {
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.seedPercent] = seedPercent.coerceIn(0, 100)
it[MoodsTable.collectionPercent] = collectionPercent.coerceIn(0, 100)
it[MoodsTable.recommendationCount] = recommendationCount.coerceIn(0, 30)
it[MoodsTable.refreshHours] = refreshHours.coerceIn(1, 720)
it[MoodsTable.ytEnabled] = ytEnabled
it[changedAt] = Instant.now().toString()
it[MoodsTable.changedAt] = Instant.now().toString()
}
moodRecord(MoodsTable.selectAll().where { MoodsTable.id eq id }.single())
@@ -165,70 +174,117 @@ object MoodRepository {
} > 0
}
fun seeds(id: String): List<MoodSeedRecord> = transaction {
MoodSeedsTable.selectAll()
.where { MoodSeedsTable.moodId eq id }
// ---------------------------------------------------------------- songs
fun songs(id: String): List<MoodSongRecord> = transaction {
MoodSongsTable.selectAll()
.where { MoodSongsTable.moodId eq id }
.orderBy(
MoodSeedsTable.addedAt to SortOrder.ASC,
MoodSeedsTable.songId to SortOrder.ASC,
MoodSongsTable.addedAt to SortOrder.ASC,
MoodSongsTable.songId to SortOrder.ASC,
)
.map {
MoodSeedRecord(
songId = it[MoodSeedsTable.songId],
origin = it[MoodSeedsTable.origin],
addedAt = it[MoodSeedsTable.addedAt],
MoodSongRecord(
songId = it[MoodSongsTable.songId],
origin = it[MoodSongsTable.origin],
addedAt = it[MoodSongsTable.addedAt],
)
}
}
fun seedSongIds(id: String): List<String> = seeds(id).map { it.songId }
fun songIds(id: String): List<String> = songs(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
fun songRecords(id: String): List<SongRecord> {
val ids = songIds(id)
return SongRepository.byIds(ids)
}
val exists = MoodSeedsTable.selectAll()
.where { (MoodSeedsTable.moodId eq id) and (MoodSeedsTable.songId eq songId) }
/** Returns false when the song is already in the mood or the mood does not exist. */
fun addSong(id: String, songId: String, origin: String): Boolean = transaction {
val exists = MoodSongsTable.selectAll()
.where { (MoodSongsTable.moodId eq id) and (MoodSongsTable.songId eq songId) }
.any()
if (exists) return@transaction false
val moodExists = MoodsTable.selectAll().where { MoodsTable.id eq id }.any()
if (!moodExists) return@transaction false
val now = Instant.now().toString()
MoodSeedsTable.insertIgnore {
it[MoodSeedsTable.moodId] = id
it[MoodSeedsTable.songId] = songId
it[MoodSeedsTable.origin] = origin.takeIf { value -> value in ORIGINS } ?: "manual"
MoodSongsTable.insertIgnore {
it[moodId] = id
it[this.songId] = songId
it[this.origin] = origin.takeIf { value -> value in ORIGINS } ?: "search"
it[addedAt] = now
}
MoodsTable.update({ MoodsTable.id eq id }) {
it[changedAt] = now
}
// A track that is now permanently in the mood must not also linger as a
// hidden candidate or an active recommendation slot.
val videoId = SongsTable.select(SongsTable.videoId)
.where { SongsTable.id eq songId }
.singleOrNull()
?.get(SongsTable.videoId)
if (videoId != null) {
MoodRecommendationsTable.deleteWhere {
(MoodRecommendationsTable.moodId eq id) and
(MoodRecommendationsTable.videoId eq videoId) and
(MoodRecommendationsTable.state eq "new")
}
MoodRecommendationsTable.update({
(MoodRecommendationsTable.moodId eq id) and
(MoodRecommendationsTable.videoId eq videoId) and
(MoodRecommendationsTable.state inList listOf("downloading", "ready", "failed"))
}) {
it[state] = "added"
it[this.songId] = songId
}
}
true
}
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 removed = MoodSeedsTable.deleteWhere {
(MoodSeedsTable.moodId eq id) and (MoodSeedsTable.songId eq songId)
fun removeSong(id: String, songId: String): Boolean = transaction {
val removed = MoodSongsTable.deleteWhere {
(MoodSongsTable.moodId eq id) and (MoodSongsTable.songId eq songId)
} > 0
if (removed) {
MoodsTable.update({ MoodsTable.id eq id }) {
it[changedAt] = Instant.now().toString()
}
// Detaching must not keep a permanent `added` decision pinned to the
// file, otherwise the GC could never delete it.
MoodRecommendationsTable.update({
(MoodRecommendationsTable.moodId eq id) and
(MoodRecommendationsTable.songId eq songId) and
(MoodRecommendationsTable.state eq "added")
}) {
it[MoodRecommendationsTable.songId] = null
}
}
removed
}
// ------------------------------------------------------ recommendations
/** Active recommendations, i.e. the rows the client is allowed to see. */
fun recommendations(id: String): List<RecommendationRecord> = transaction {
MoodRecommendationsTable.selectAll()
.where {
(MoodRecommendationsTable.moodId eq id) and
(MoodRecommendationsTable.state inList VISIBLE_STATES)
}
.orderBy(
MoodRecommendationsTable.rank to SortOrder.ASC,
MoodRecommendationsTable.firstSeen to SortOrder.ASC,
)
.map { it.toRecommendationRecord() }
}
fun allRecommendations(id: String): List<RecommendationRecord> = transaction {
MoodRecommendationsTable.selectAll()
.where { MoodRecommendationsTable.moodId eq id }
.orderBy(MoodRecommendationsTable.lastSeen to SortOrder.DESC)
.orderBy(MoodRecommendationsTable.rank to SortOrder.ASC)
.map { it.toRecommendationRecord() }
}
@@ -242,22 +298,51 @@ object MoodRepository {
?.toRecommendationRecord()
}
fun activeCount(moodId: String): Int = transaction {
MoodRecommendationsTable.selectAll()
.where {
(MoodRecommendationsTable.moodId eq moodId) and
(MoodRecommendationsTable.state inList ACTIVE_STATES)
}
.count()
.toInt()
}
fun videoIdsInMood(moodId: String): Set<String> = transaction {
val songs = MoodSongsTable.select(MoodSongsTable.songId)
.where { MoodSongsTable.moodId eq moodId }
SongsTable.select(SongsTable.videoId)
.where { SongsTable.id inSubQuery songs }
.map { it[SongsTable.videoId] }
.toSet()
}
fun decidedVideoIds(moodId: String): Set<String> = transaction {
MoodRecommendationsTable.selectAll()
.where {
(MoodRecommendationsTable.moodId eq moodId) and
(MoodRecommendationsTable.state inList HIDDEN_DECISIONS)
}
.map { it[MoodRecommendationsTable.videoId] }
.toSet()
}
/**
* Inserts new candidates and refreshes the metadata of known ones. Decisions
* (accepted/rejected) and the add counter survive a refresh; stale undecided
* candidates are removed so the review list does not grow without bound.
* Stores a sorted discovery batch as hidden `new` candidates. Existing rows
* keep their state: active slots and decisions must survive a refresh.
*/
fun storeRecommendations(
fun storeCandidates(
moodId: String,
items: List<RecommendationUpsert>,
seenAt: String,
poolLimit: Int = CANDIDATE_POOL,
): Int = transaction {
val existing = MoodRecommendationsTable.selectAll()
.where { MoodRecommendationsTable.moodId eq moodId }
.associateBy { it[MoodRecommendationsTable.videoId] }
var stored = 0
items.forEach { item ->
items.take(poolLimit.coerceAtLeast(1)).forEachIndexed { index, item ->
val row = existing[item.videoId]
if (row == null) {
MoodRecommendationsTable.insert {
@@ -269,12 +354,11 @@ object MoodRepository {
it[duration] = item.duration
it[thumbnail] = item.thumbnail?.take(500)
it[state] = "new"
it[matchedSongId] = item.matchedSongId
it[timesAdded] = 0
it[rank] = index
it[firstSeen] = seenAt
it[lastSeen] = seenAt
}
} else {
} else if (row[MoodRecommendationsTable.state] == "new") {
MoodRecommendationsTable.update({
(MoodRecommendationsTable.moodId eq moodId) and
(MoodRecommendationsTable.videoId eq item.videoId)
@@ -284,61 +368,201 @@ object MoodRepository {
it[album] = item.album?.take(300)
it[duration] = item.duration
it[thumbnail] = item.thumbnail?.take(500)
it[matchedSongId] = item.matchedSongId
?: row[MoodRecommendationsTable.matchedSongId]
it[rank] = index
it[lastSeen] = seenAt
}
}
stored += 1
}
val keep = items.map { it.videoId }.toSet()
val stale = existing.keys - keep
if (stale.isNotEmpty()) {
// Candidates that were not returned again are no longer useful.
val keep = items.take(poolLimit.coerceAtLeast(1)).map { it.videoId }.toSet()
if (keep.isNotEmpty()) {
MoodRecommendationsTable.deleteWhere {
(MoodRecommendationsTable.moodId eq moodId) and
(MoodRecommendationsTable.videoId inList stale.toList()) and
(MoodRecommendationsTable.state eq "new")
(MoodRecommendationsTable.state eq "new") and
(MoodRecommendationsTable.videoId notInList keep.toList())
}
}
stored
}
fun setRecommendationState(moodId: String, videoId: String, state: String): Boolean = transaction {
MoodRecommendationsTable.update({
(MoodRecommendationsTable.moodId eq moodId) and
(MoodRecommendationsTable.videoId eq videoId)
}) {
it[MoodRecommendationsTable.state] = state
} > 0
/** Moves up to [limit] hidden candidates into the downloading state. */
fun promoteCandidates(moodId: String, limit: Int): List<RecommendationRecord> = transaction {
if (limit <= 0) return@transaction emptyList()
val rows = MoodRecommendationsTable.selectAll()
.where {
(MoodRecommendationsTable.moodId eq moodId) and
(MoodRecommendationsTable.state eq "new")
}
.orderBy(
MoodRecommendationsTable.rank to SortOrder.ASC,
MoodRecommendationsTable.firstSeen to SortOrder.ASC,
)
.limit(limit)
.toList()
rows.forEach { row ->
MoodRecommendationsTable.update({
(MoodRecommendationsTable.moodId eq moodId) and
(MoodRecommendationsTable.videoId eq row[MoodRecommendationsTable.videoId])
}) {
it[state] = "downloading"
it[error] = null
}
}
rows.map { it.toRecommendationRecord().copy(state = "downloading", error = null) }
}
fun incrementRecommendationAdds(moodId: String, videoId: String) {
fun setRecommendationState(moodId: String, videoId: String, state: String, error: String? = null) {
transaction {
val current = MoodRecommendationsTable.selectAll()
MoodRecommendationsTable.update({
(MoodRecommendationsTable.moodId eq moodId) and
(MoodRecommendationsTable.videoId eq videoId)
}) {
it[this.state] = state
it[this.error] = error?.take(1000)
}
}
}
fun markRecommendationDownloading(moodId: String, videoId: String) {
transaction {
MoodRecommendationsTable.update({
(MoodRecommendationsTable.moodId eq moodId) and
(MoodRecommendationsTable.videoId eq videoId)
}) {
it[state] = "downloading"
it[attempts] = 0
it[error] = null
}
}
}
fun failRecommendation(moodId: String, videoId: String, error: String, attempts: Int) {
transaction {
MoodRecommendationsTable.update({
(MoodRecommendationsTable.moodId eq moodId) and
(MoodRecommendationsTable.videoId eq videoId) and
(MoodRecommendationsTable.state eq "downloading")
}) {
it[state] = "failed"
it[this.error] = error.take(1000)
it[this.attempts] = attempts
}
}
}
/**
* Applies a finished download. A rejection that happened while the download
* was running wins: the file is left for the GC to delete.
*/
fun completeDownload(moodId: String, videoId: String, songId: String): RecommendationCompletion =
transaction {
val row = MoodRecommendationsTable.selectAll()
.where {
(MoodRecommendationsTable.moodId eq moodId) and
(MoodRecommendationsTable.videoId eq videoId)
}
.singleOrNull()
?.get(MoodRecommendationsTable.timesAdded)
?: return@transaction
MoodRecommendationsTable.update({
(MoodRecommendationsTable.moodId eq moodId) and
(MoodRecommendationsTable.videoId eq videoId)
}) {
it[timesAdded] = current + 1
?: return@transaction RecommendationCompletion.MISSING
when (row[MoodRecommendationsTable.state]) {
"rejected" -> RecommendationCompletion.REJECTED
"added" -> {
insertRecommendationSong(moodId, songId)
MoodRecommendationsTable.update({
(MoodRecommendationsTable.moodId eq moodId) and
(MoodRecommendationsTable.videoId eq videoId)
}) {
it[this.songId] = songId
it[state] = "added"
}
RecommendationCompletion.ALREADY_ADDED
}
else -> {
MoodRecommendationsTable.update({
(MoodRecommendationsTable.moodId eq moodId) and
(MoodRecommendationsTable.videoId eq videoId)
}) {
it[this.songId] = songId
it[state] = "ready"
it[error] = null
it[lastSeen] = Instant.now().toString()
}
RecommendationCompletion.READY
}
}
}
/** Called when the user presses Add. Marks the row and attaches a ready song. */
fun markAdded(moodId: String, videoId: String): RecommendationCompletion = transaction {
val row = MoodRecommendationsTable.selectAll()
.where {
(MoodRecommendationsTable.moodId eq moodId) and
(MoodRecommendationsTable.videoId eq videoId)
}
.singleOrNull()
?: return@transaction RecommendationCompletion.MISSING
val songId = row[MoodRecommendationsTable.songId]
MoodRecommendationsTable.update({
(MoodRecommendationsTable.moodId eq moodId) and
(MoodRecommendationsTable.videoId eq videoId)
}) {
it[state] = "added"
}
if (songId != null && row[MoodRecommendationsTable.state] != "added") {
insertRecommendationSong(moodId, songId)
return@transaction RecommendationCompletion.ALREADY_ADDED
}
RecommendationCompletion.READY
}
/** Moods whose YT discovery is due, oldest first. */
fun markRejected(moodId: String, videoId: String) {
setRecommendationState(moodId, videoId, "rejected")
}
fun readySongs(moodId: String): List<SongRecord> = transaction {
val songIds = MoodRecommendationsTable
.select(MoodRecommendationsTable.songId)
.where {
(MoodRecommendationsTable.moodId eq moodId) and
(MoodRecommendationsTable.state eq "ready")
}
.mapNotNull { it[MoodRecommendationsTable.songId] }
if (songIds.isEmpty()) emptyList()
else SongsTable.selectAll()
.where { SongsTable.id inList songIds }
.map {
SongRecord(
id = it[SongsTable.id],
videoId = it[SongsTable.videoId],
title = it[SongsTable.title],
artist = it[SongsTable.artist],
album = it[SongsTable.album],
duration = it[SongsTable.duration],
bitRate = it[SongsTable.bitRate],
size = it[SongsTable.size],
suffix = it[SongsTable.suffix],
contentType = it[SongsTable.contentType],
relativePath = it[SongsTable.relativePath],
fileMtime = it[SongsTable.fileMtime],
thumbnail = it[SongsTable.thumbnail],
createdAt = it[SongsTable.createdAt],
updatedAt = it[SongsTable.updatedAt],
)
}
}
// ---------------------------------------------------------- discovery
/** Moods whose automatic discovery is due, oldest first. */
fun staleDiscovery(now: Instant, limit: Int): List<MoodRecord> = transaction {
MoodsTable.selectAll()
.where { MoodsTable.ytEnabled eq true }
.orderBy(MoodsTable.lastDiscoveryAt to SortOrder.ASC)
.map { moodRecord(it) }
.filter { mood -> isStale(mood.lastDiscoveryAt, mood.refreshHours, now) }
.filter { mood -> mood.recommendationCount > 0 && isStale(mood.lastDiscoveryAt, mood.refreshHours, now) }
.take(limit.coerceAtLeast(1))
}
@@ -350,31 +574,6 @@ object MoodRepository {
}
}
/** Links a downloaded recommendation to the scanned song and accepts it. */
fun attachDownloadedSong(moodId: String, videoId: String, songId: String): Boolean = transaction {
val row = MoodRecommendationsTable.selectAll()
.where {
(MoodRecommendationsTable.moodId eq moodId) and
(MoodRecommendationsTable.videoId eq videoId)
}
.singleOrNull()
?: return@transaction false
// The user may have rejected the track while it was downloading.
if (row[MoodRecommendationsTable.state] == "rejected") {
return@transaction false
}
MoodRecommendationsTable.update({
(MoodRecommendationsTable.moodId eq moodId) and
(MoodRecommendationsTable.videoId eq videoId)
}) {
it[matchedSongId] = songId
it[state] = "accepted"
it[timesAdded] = row[MoodRecommendationsTable.timesAdded] + 1
it[lastSeen] = Instant.now().toString()
}
true
}
fun markDiscovered(id: String) {
transaction {
MoodsTable.update({ MoodsTable.id eq id }) {
@@ -384,15 +583,20 @@ object MoodRepository {
}
}
private fun insertSeeds(id: String, songIds: List<String>, origin: String) {
val now = Instant.now().toString()
songIds.distinct().forEach { songId ->
MoodSeedsTable.insertIgnore {
it[moodId] = id
it[this.songId] = songId
it[this.origin] = origin
it[addedAt] = now
}
fun isDiscoveryDue(mood: MoodRecord, now: Instant = Instant.now()): Boolean =
isStale(mood.lastDiscoveryAt, mood.refreshHours, now)
// ------------------------------------------------------------ internal
private fun insertRecommendationSong(moodId: String, songId: String) {
MoodSongsTable.insertIgnore {
it[this.moodId] = moodId
it[this.songId] = songId
it[origin] = "recommendation"
it[addedAt] = Instant.now().toString()
}
MoodsTable.update({ MoodsTable.id eq moodId }) {
it[changedAt] = Instant.now().toString()
}
}
@@ -410,25 +614,23 @@ object MoodRepository {
duration = this[MoodRecommendationsTable.duration],
thumbnail = this[MoodRecommendationsTable.thumbnail],
state = this[MoodRecommendationsTable.state],
matchedSongId = this[MoodRecommendationsTable.matchedSongId],
timesAdded = this[MoodRecommendationsTable.timesAdded],
songId = this[MoodRecommendationsTable.songId],
attempts = this[MoodRecommendationsTable.attempts],
error = this[MoodRecommendationsTable.error],
rank = this[MoodRecommendationsTable.rank],
firstSeen = this[MoodRecommendationsTable.firstSeen],
lastSeen = this[MoodRecommendationsTable.lastSeen],
)
private fun moodRecord(row: ResultRow): MoodRecord {
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")
}
val songCount = MoodSongsTable.selectAll()
.where { MoodSongsTable.moodId eq id }
.count()
.toInt()
val ready = countState(id, "ready")
val downloading = countState(id, "downloading")
val failed = countState(id, "failed")
return MoodRecord(
id = id,
@@ -437,19 +639,29 @@ object MoodRepository {
description = row[MoodsTable.description],
query = row[MoodsTable.query],
genres = decodeGenres(row[MoodsTable.genres]),
targetSize = row[MoodsTable.targetSize],
seedPercent = row[MoodsTable.seedPercent],
collectionPercent = row[MoodsTable.collectionPercent],
recommendationCount = row[MoodsTable.recommendationCount],
refreshHours = row[MoodsTable.refreshHours],
ytEnabled = row[MoodsTable.ytEnabled],
lastDiscoveryAt = row[MoodsTable.lastDiscoveryAt],
createdAt = row[MoodsTable.createdAt],
changedAt = row[MoodsTable.changedAt],
lastError = row[MoodsTable.lastError],
seedCount = seedCount,
newRecommendations = newRecommendations,
songCount = songCount,
recommendationReady = ready,
recommendationDownloading = downloading,
recommendationFailed = failed,
)
}
private fun countState(moodId: String, state: String): Int =
MoodRecommendationsTable.selectAll()
.where {
(MoodRecommendationsTable.moodId eq moodId) and
(MoodRecommendationsTable.state eq state)
}
.count()
.toInt()
private fun encodeGenres(genres: List<String>): String =
Json.encodeToString(
genreSerializer,
@@ -459,5 +671,6 @@ object MoodRepository {
private fun decodeGenres(value: String): List<String> =
runCatching { Json.decodeFromString(genreSerializer, value) }.getOrDefault(emptyList())
private val ORIGINS = setOf("manual", "recommendation", "yt")
private val ORIGINS = setOf("search", "recommendation", "url")
private const val CANDIDATE_POOL = 60
}