From 28bfdd9d0021fa01eaa121ea32c1c3569123706f Mon Sep 17 00:00:00 2001 From: TapTap Date: Sat, 14 Nov 2026 12:52:25 +0000 Subject: [PATCH] feat: add per-user moods as generated playlists Add private server-managed playlist moods with curated seeds and related library fill. Moods are created or promoted from existing playlists in the web UI, refresh lazily after their TTL, and are marked stale after a scan. Symfonium stars pin the active mood: opening a mood restores its context, and a starred song becomes a permanent seed. Without an active session the song is pinned to every mood that already contains it. Includes the V4 migration, custom mood endpoints, management UI, tests and smoke coverage. Bump the chart to 0.1.4. --- README.md | 104 ++++- charts/audiomanager/Chart.yaml | 2 +- scripts/smoke.sh | 13 + .../win/taptap/musicmanager/Application.kt | 10 +- .../musicmanager/db/LibraryRepository.kt | 54 +++ .../taptap/musicmanager/db/MoodRepository.kt | 413 ++++++++++++++++++ .../musicmanager/db/PlaylistRepository.kt | 22 +- .../win/taptap/musicmanager/db/Tables.kt | 44 ++ .../musicmanager/mood/MoodMixService.kt | 145 ++++++ .../win/taptap/musicmanager/mood/MoodPins.kt | 38 ++ .../taptap/musicmanager/mood/MoodService.kt | 66 +++ .../musicmanager/mood/MoodSessionTracker.kt | 45 ++ .../musicmanager/scanner/MediaScanner.kt | 3 + .../subsonic/models/JsonModels.kt | 33 ++ .../subsonic/routes/InteractionRoutes.kt | 13 +- .../subsonic/routes/MediaRoutes.kt | 2 + .../subsonic/routes/MoodRoutes.kt | 265 +++++++++++ .../subsonic/routes/PlaylistRoutes.kt | 34 +- .../subsonic/routes/RouteHelpers.kt | 9 + .../subsonic/routes/SubsonicRoutes.kt | 5 +- src/main/resources/db/migration/V4__moods.sql | 47 ++ src/main/resources/web/index.html | 268 ++++++++++++ .../subsonic/BrowsingRoutesTest.kt | 4 + .../musicmanager/subsonic/MoodRoutesTest.kt | 410 +++++++++++++++++ .../musicmanager/subsonic/SystemRoutesTest.kt | 4 + 25 files changed, 2039 insertions(+), 14 deletions(-) create mode 100644 src/main/kotlin/win/taptap/musicmanager/db/MoodRepository.kt create mode 100644 src/main/kotlin/win/taptap/musicmanager/mood/MoodMixService.kt create mode 100644 src/main/kotlin/win/taptap/musicmanager/mood/MoodPins.kt create mode 100644 src/main/kotlin/win/taptap/musicmanager/mood/MoodService.kt create mode 100644 src/main/kotlin/win/taptap/musicmanager/mood/MoodSessionTracker.kt create mode 100644 src/main/kotlin/win/taptap/musicmanager/subsonic/routes/MoodRoutes.kt create mode 100644 src/main/resources/db/migration/V4__moods.sql create mode 100644 src/test/kotlin/win/taptap/musicmanager/subsonic/MoodRoutesTest.kt diff --git a/README.md b/README.md index 3d1d4a4..433a0a6 100644 --- a/README.md +++ b/README.md @@ -141,7 +141,8 @@ Build a lightweight, self-hosted **OpenSubsonic-compatible music server** in **K 4. **Two content types, never mixed:** *music* and *long-form* (audiobooks, podcasts, lectures) live in **separate music folders**. Clients see and select them independently. 5. **Multi-user:** users are defined outside the database (config + HashiCorp Vault). Music roots are assigned per user, long-form is shared. Stars, ratings, play counts, bookmarks and playlists are per user. 6. **Transcoding:** optional on-the-fly MP3 transcoding with `maxBitRate` and `timeOffset` support. -7. **Extensibility:** clean separation between scanner, database layer and HTTP API so a downloader and a discovery/recommendation engine can be added later. +7. **Moods:** per-user private playlists generated from curated seeds and related library music. Symfonium likes pin songs to the active mood. +8. **Extensibility:** clean separation between scanner, database layer and HTTP API so a downloader and a discovery/recommendation engine can be added later. ### Explicit non-goals (MVP) @@ -152,6 +153,7 @@ Build a lightweight, self-hosted **OpenSubsonic-compatible music server** in **K - User-management API (users come from config/Vault). - TLS inside the app (terminated by the k3s ingress). - Automatic filesystem watching (scans are manual or on boot when the DB is empty). +- Downloading or streaming YT Music inside the app (future phase; recommendations are metadata-only until then). - Backups (documented manual procedure only). ### Roles @@ -198,12 +200,18 @@ src/main/kotlin/win/taptap/musicmanager/ | |-- LibraryRepository.kt # Visibility-scoped browsing, feeds, genres, search | |-- UserStateRepository.kt # Play counts, stars, ratings, bookmarks | |-- PlaylistRepository.kt # Playlist CRUD and visibility +| |-- MoodRepository.kt # Mood settings, seeds, pinned recommendations | |-- MediaRepository.kt # Scanner persistence and aggregate rebuilds | `-- migrations/ # Flyway SQL (V1__init.sql, ...) |-- scanner/ | |-- MediaScanner.kt # Recursive scan, delta updates, orphan cleanup | |-- Mp3TagExtractor.kt # jaudiotagger wrapper (tags, path fallback, duration, bitrate) | `-- CoverArtService.kt # Cover extraction from tags/folders, disk cache, resizing +|-- mood/ +| |-- MoodMixService.kt # Seed + related-library mix generation +| |-- MoodService.kt # TTL refresh and per-mood generation locking +| |-- MoodSessionTracker.kt # Active mood for Symfonium star pinning +| `-- MoodPins.kt # star/unstar -> mood seed translation |-- subsonic/ | |-- SubsonicAuth.kt # Token (u, t, s) and password (p, enc:) auth | |-- SubsonicResponse.kt # JSON envelope & error codes @@ -217,7 +225,8 @@ src/main/kotlin/win/taptap/musicmanager/ | |-- BrowsingRoutes.kt # indexes, artists, album, song, search3, lists, genres | |-- MediaRoutes.kt # stream, download, getCoverArt, lyrics | |-- InteractionRoutes.kt # scrobble, star/unstar, setRating, getStarred2 -| `-- PlaylistRoutes.kt # playlists and playlist songs +| |-- PlaylistRoutes.kt # playlists and playlist songs +| `-- MoodRoutes.kt # custom mood management endpoints |-- transcoding/ | `-- FfmpegTranscoder.kt # MP3 transcoding with maxBitRate and timeOffset `-- util/ @@ -438,6 +447,7 @@ CREATE TABLE playlists ( name TEXT NOT NULL, comment TEXT, is_public BOOLEAN NOT NULL DEFAULT 1, + kind TEXT NOT NULL DEFAULT 'user' CHECK (kind IN ('user', 'mood')), created_at TEXT NOT NULL, changed_at TEXT NOT NULL ); @@ -448,6 +458,45 @@ CREATE TABLE playlist_songs ( position INTEGER NOT NULL, PRIMARY KEY (playlist_id, position) ); + +-- Moods are private playlists with generation settings. The current mix lives +-- in playlist_songs; these tables hold the anchors and future YT candidates. +CREATE TABLE moods ( + playlist_id TEXT PRIMARY KEY REFERENCES playlists(id) ON DELETE CASCADE, + query TEXT, + genres TEXT NOT NULL DEFAULT '[]', + target_size INTEGER NOT NULL DEFAULT 50, + yt_slots INTEGER NOT NULL DEFAULT 0, + expand_related BOOLEAN NOT NULL DEFAULT 1, + refresh_hours INTEGER NOT NULL DEFAULT 24, + generated_at TEXT, + generation INTEGER NOT NULL DEFAULT 0, + last_error TEXT +); + +CREATE TABLE mood_seeds ( + playlist_id TEXT NOT NULL REFERENCES moods(playlist_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', 'promoted', 'star', 'yt_like')), + added_at TEXT NOT NULL, + PRIMARY KEY (playlist_id, song_id) +); + +CREATE TABLE mood_recommendations ( + playlist_id TEXT NOT NULL REFERENCES moods(playlist_id) ON DELETE CASCADE, + video_id TEXT NOT NULL, + title TEXT NOT NULL, + artist TEXT NOT NULL, + duration INTEGER, + state TEXT NOT NULL DEFAULT 'new' + CHECK (state IN ('new', 'liked', 'rejected', 'downloaded')), + 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 (playlist_id, video_id) +); ``` Required indexes: @@ -457,6 +506,7 @@ Required indexes: - `album_artists(artist_id)`, `song_artists(artist_id)` - `user_song_state(user_name, starred_at)`, `user_stars(user_name, item_type)` - `playlist_songs(song_id)`, `playlists(owner)` +- `mood_seeds(song_id)`, `mood_recommendations(matched_song_id)` All timestamps are ISO 8601 in UTC. @@ -604,6 +654,46 @@ For every `/rest/*` call (except an optional health check): No `createUser` / `updateUser` / `deleteUser` endpoints: config/Vault is the source of truth. +### 7.7 Moods (custom, for Symfonium) + +OpenSubsonic has no mood entity, so a mood is a **private server-managed playlist**. The playlist ID and name stay stable, so Symfonium keeps its reference. Management lives in the built-in `/ui` page under **Moods**. + +Custom endpoints use the normal Subsonic auth and JSON envelope: + +- `getMoods`: list the caller's moods. +- `getMood(id)`: settings plus `seed` and `entry` song lists. +- `createMood(name, query, genre, songId, targetSize, ytSlots, expandRelated, refreshHours)`: creates a private playlist and generates the first mix. +- `updateMood(id, ...)`: updates settings, marks the mix stale and regenerates. +- `deleteMood(id)`: deletes the playlist and all mood data. +- `refreshMood(id)`: synchronous regeneration. +- `promotePlaylistToMood(playlistId, ...)`: keeps the same playlist ID and name; its current songs become `promoted` seeds. +- `addMoodSeed(id, songId)` / `removeMoodSeed(id, songId)`: manual anchors. + +Generation rules: + +- Only the owner's **music** folders are used. Shared long-form folders never enter a mood. +- Every seed is always included; if there are more seeds than `targetSize`, all seeds are kept. +- With `expandRelated`, remaining slots are filled from matching genres/artists and, if needed, other visible music. +- `ytSlots` is reserved for the YT Music recommendation phase. +- A scan marks all moods stale. `getPlaylist` regenerates stale moods in the background; `refreshMood` forces it immediately. + +Liking in Symfonium: + +- Symfonium's heart calls `star`. +- If a mood was opened within the last four hours, the starred song becomes a permanent `star` seed of that mood, even if it was not in the mix. +- Without an active mood, the song is pinned to every mood that already contains it. +- `unstar` removes only `star` seeds; manual and promoted seeds stay. +- `updatePlaylist` and `createPlaylist(playlistId=...)` reject song edits on mood playlists with error 50; renaming is still allowed. + +Symfonium has no built-in weekly sync interval. Automatic sync runs on app start and when it detects server changes. For a deterministic refresh, schedule the Symfonium broadcast API with Tasker/MacroDroid/Automate: + +```text +Action: app.symfonium.api.MEDIA_SYNC +Package: app.symfonik.music.player +Class: app.symfonium.remote.api.ApiReceiver +Extra: PROVIDER_ID = Providers> +``` + --- ## 8. Scanner @@ -720,7 +810,7 @@ registry remains private. Versions published by CI: -- `main`: `-sha.`, for example `0.1.3-sha.` +- `main`: `-sha.`, for example `0.1.4-sha.` - `v*` tag: the tag without the leading `v`, for example `v0.2.0` -> `0.2.0` Use it with Helm: @@ -735,7 +825,7 @@ helm search repo taptap/audiomanager Install a published chart: ```bash -VERSION="0.1.3-sha." +VERSION="0.1.4-sha." helm upgrade --install audiomanager taptap/audiomanager \ --version "$VERSION" \ --namespace audiomanager \ @@ -751,7 +841,7 @@ helmCharts: releaseName: audiomanager namespace: audiomanager repo: https://gitea.tap-tap.win/TapTap/Charts/raw/branch/main - version: 0.1.3-sha. + version: 0.1.4-sha. valuesFile: values.yaml ``` @@ -825,6 +915,8 @@ Verify each step with `./gradlew test` and/or `curl`: - [x] 6. **Interaction & playlists:** `getAlbumList2`, `getRandomSongs`, `getStarred2`, `search3`, `scrobble`, `star`/`unstar`, `setRating`, bookmarks, playlists. - [x] 7. **Packaging:** multi-stage Dockerfile (with ffmpeg), Helm chart, Gitea Actions workflow. - [x] 8. **Tests:** integration suite as described above, plus a `curl` smoke script. +- [x] 9. **Moods:** `V4__moods.sql`, `MoodRepository`, `MoodMixService`, `MoodService`, `MoodRoutes`, mood UI, Symfonium star pinning, and route tests. +- [ ] 10. **YT recommendations:** yt-dlp discovery, mood recommendation UI, liked/wishlist candidates, and the optional downloader. --- @@ -838,3 +930,5 @@ Verify each step with `./gradlew test` and/or `curl`: 6. **No XML:** clients that insist on XML are unsupported. 7. **No user-management API:** user changes are applied on restart after the Vault secret/config is updated. 8. **Backups** are manual and documented; no backup endpoint. +9. **YT Music recommendations** are the next phase. `mood_recommendations` and `yt_slots` are already in the schema; generation currently falls back to library music. +10. **Mood playlists are fixed queues in Symfonium.** For fresh contents, let the lazy TTL refresh run and sync the client (Tasker recipe above). diff --git a/charts/audiomanager/Chart.yaml b/charts/audiomanager/Chart.yaml index 363581e..34276fd 100644 --- a/charts/audiomanager/Chart.yaml +++ b/charts/audiomanager/Chart.yaml @@ -2,5 +2,5 @@ apiVersion: v2 name: audiomanager description: Self-hosted OpenSubsonic music server type: application -version: 0.1.3 +version: 0.1.4 appVersion: "0.1.0" diff --git a/scripts/smoke.sh b/scripts/smoke.sh index e719352..09894e4 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -194,6 +194,19 @@ else check "deletePlaylist" "/rest/deletePlaylist.view?$AUTH&id=$PLAYLIST_ID" fi +MOOD_JSON="$(curl -s "$BASE/rest/createMood.view?$AUTH&name=Smoke%20Mood&songId=$SONG_ID&targetSize=5")" +MOOD_ID="$(printf '%s' "$MOOD_JSON" | python3 -c 'import json,sys; print(json.load(sys.stdin)["subsonic-response"]["mood"]["id"])' 2>/dev/null || true)" +if [[ -z "$MOOD_ID" ]]; then + fail "createMood" "$(printf '%s' "$MOOD_JSON" | head -c 300)" +else + pass "createMood" + check "getMoods" "/rest/getMoods.view?$AUTH" + check "getMood" "/rest/getMood.view?$AUTH&id=$MOOD_ID" + check "getPlaylist (mood)" "/rest/getPlaylist.view?$AUTH&id=$MOOD_ID" + check "refreshMood" "/rest/refreshMood.view?$AUTH&id=$MOOD_ID" + check "deleteMood" "/rest/deleteMood.view?$AUTH&id=$MOOD_ID" +fi + check "savePlayQueue" "/rest/savePlayQueue.view?$AUTH&id=$SONG_ID&position=0" check "getPlayQueue" "/rest/getPlayQueue.view?$AUTH" check "savePlayQueueByIndex" "/rest/savePlayQueueByIndex.view?$AUTH&id=$SONG_ID¤tIndex=0&position=0" diff --git a/src/main/kotlin/win/taptap/musicmanager/Application.kt b/src/main/kotlin/win/taptap/musicmanager/Application.kt index ff9e382..dc1a51e 100644 --- a/src/main/kotlin/win/taptap/musicmanager/Application.kt +++ b/src/main/kotlin/win/taptap/musicmanager/Application.kt @@ -30,6 +30,8 @@ import win.taptap.musicmanager.config.UsersConfig 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.scanner.CoverArtService import win.taptap.musicmanager.scanner.MediaScanner import win.taptap.musicmanager.subsonic.respondSubsonicError @@ -51,7 +53,12 @@ fun main() { val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) val coverArtService = CoverArtService(config.dataDir) val transcoder = FfmpegTranscoder(config.ffmpegPath) - val scanner = MediaScanner(library, coverArtService) + val moodService = MoodService(applicationScope) + val scanner = MediaScanner( + library = library, + coverArtService = coverArtService, + onScanFinished = { MoodRepository.markAllStale() }, + ) if (MediaRepository.countSongs() == 0L) { log.info("Song table is empty, starting initial library scan") scanner.start(applicationScope) @@ -98,6 +105,7 @@ fun main() { library = library, coverArtService = coverArtService, transcoder = transcoder, + moodService = moodService, startScan = { scanner.start(applicationScope) }, scanStatus = { scanner.status() }, ) diff --git a/src/main/kotlin/win/taptap/musicmanager/db/LibraryRepository.kt b/src/main/kotlin/win/taptap/musicmanager/db/LibraryRepository.kt index c06446d..3b4506f 100644 --- a/src/main/kotlin/win/taptap/musicmanager/db/LibraryRepository.kt +++ b/src/main/kotlin/win/taptap/musicmanager/db/LibraryRepository.kt @@ -9,6 +9,7 @@ import org.jetbrains.exposed.sql.SortOrder import org.jetbrains.exposed.sql.Transaction import org.jetbrains.exposed.sql.and import org.jetbrains.exposed.sql.lowerCase +import org.jetbrains.exposed.sql.or import org.jetbrains.exposed.sql.selectAll import org.jetbrains.exposed.sql.transactions.transaction import org.jetbrains.exposed.sql.union @@ -404,6 +405,59 @@ object LibraryRepository { enrichSongs(rows, userName) } + /** Bulk genre lookup used by mood generation to avoid one query per seed genre. */ + fun songsByGenres( + genres: Collection, + limit: Int, + folderIds: Set, + userName: String, + ): List = read { + if (genres.isEmpty() || folderIds.isEmpty()) return@read emptyList() + + val normalized = genres.map { it.lowercase() }.distinct() + val songIds = SongGenresTable + .select(SongGenresTable.songId) + .where { SongGenresTable.genre.lowerCase() inList normalized } + + val rows = SongsTable.selectAll() + .where { + (SongsTable.id inSubQuery songIds) and + (SongsTable.folderId inList folderIds) + } + .limit(limit) + .toList() + + enrichSongs(rows, userName) + } + + /** Songs by track artist or album artist, used as related-mood candidates. */ + fun songsByArtists( + artistIds: Collection, + limit: Int, + folderIds: Set, + userName: String, + ): List = read { + if (artistIds.isEmpty() || folderIds.isEmpty()) return@read emptyList() + + val ids = artistIds.toList() + val songArtists = SongArtistsTable + .select(SongArtistsTable.songId) + .where { SongArtistsTable.artistId inList ids } + val albumArtists = AlbumArtistsTable + .select(AlbumArtistsTable.albumId) + .where { AlbumArtistsTable.artistId inList ids } + + val rows = SongsTable.selectAll() + .where { + (SongsTable.folderId inList folderIds) and + ((SongsTable.id inSubQuery songArtists) or (SongsTable.albumId inSubQuery albumArtists)) + } + .limit(limit) + .toList() + + enrichSongs(rows, userName) + } + fun starred(userName: String, folderIds: Set): StarredRecords = read { if (folderIds.isEmpty()) { return@read StarredRecords(emptyList(), emptyList(), emptyList()) diff --git a/src/main/kotlin/win/taptap/musicmanager/db/MoodRepository.kt b/src/main/kotlin/win/taptap/musicmanager/db/MoodRepository.kt new file mode 100644 index 0000000..a26b8f8 --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/db/MoodRepository.kt @@ -0,0 +1,413 @@ +package win.taptap.musicmanager.db + +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.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 MoodRecord( + val playlistId: String, + val owner: String, + val name: String, + val comment: String?, + val query: String?, + val genres: List, + val targetSize: Int, + val ytSlots: Int, + val expandRelated: Boolean, + val refreshHours: Int, + val generatedAt: String?, + val generation: Int, + val lastError: String?, + val created: String, + val changed: String, + val songCount: Int, + val duration: Int, + val seedCount: Int, +) + +data class MoodSeedRecord( + val songId: String, + val origin: String, + val addedAt: 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`. + */ +object MoodRepository { + + private val genreSerializer = ListSerializer(String.serializer()) + + fun list(userName: String): List = 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) + .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") + } + .singleOrNull() + + row?.let { moodRecord(it) } + } + + fun create( + userName: String, + name: String, + comment: String?, + query: String?, + genres: List, + targetSize: Int, + ytSlots: Int, + expandRelated: Boolean, + refreshHours: Int, + seedSongIds: List, + ): MoodRecord { + val playlist = PlaylistRepository.create( + userName = userName, + name = name, + songIds = emptyList(), + isPublic = false, + kind = "mood", + ) + + 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, + targetSize: Int, + ytSlots: Int, + expandRelated: Boolean, + refreshHours: Int, + musicFolderIds: Set, + ): 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, + name: String, + comment: String?, + query: String?, + genres: List, + 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") + } + .any() + if (!exists) return@transaction false + + PlaylistsTable.update({ PlaylistsTable.id eq playlistId }) { + it[PlaylistsTable.name] = name + it[PlaylistsTable.comment] = comment + 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 + } + + fun delete(playlistId: String, userName: String): Boolean = + PlaylistRepository.delete(playlistId, userName) + + fun seedSongIds(playlistId: String, origin: String? = null): List = 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 seeds(playlistId: String): List = transaction { + MoodSeedsTable.selectAll() + .where { MoodSeedsTable.playlistId eq playlistId } + .orderBy( + MoodSeedsTable.addedAt to SortOrder.ASC, + MoodSeedsTable.songId to SortOrder.ASC, + ) + .map { + MoodSeedRecord( + songId = it[MoodSeedsTable.songId], + origin = it[MoodSeedsTable.origin], + addedAt = it[MoodSeedsTable.addedAt], + ) + } + } + + /** 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 + + val exists = MoodSeedsTable.selectAll() + .where { + (MoodSeedsTable.playlistId eq playlistId) and + (MoodSeedsTable.songId eq songId) + } + .any() + if (exists) return@transaction false + + MoodSeedsTable.insert { + it[MoodSeedsTable.playlistId] = playlistId + it[MoodSeedsTable.songId] = songId + it[MoodSeedsTable.origin] = origin + it[addedAt] = Instant.now().toString() + } + true + } + + fun removeSeed( + playlistId: String, + userName: String, + songId: String, + origin: String? = null, + ): Boolean = transaction { + if (get(playlistId, userName) == null) 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 = 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 + } + } + } + + fun markStale(playlistId: String) { + transaction { + MoodsTable.update({ MoodsTable.playlistId eq playlistId }) { + it[generatedAt] = null + } + } + } + + /** Records a failed generation without claiming the mood is fresh. */ + fun markError(playlistId: String, message: String) { + transaction { + MoodsTable.update({ MoodsTable.playlistId eq playlistId }) { + it[lastError] = message.take(1000) + it[generatedAt] = null + } + } + } + + fun markAllStale() { + transaction { + MoodsTable.update({ Op.TRUE }) { + it[generatedAt] = null + } + } + } + + private fun insertSettings( + playlistId: String, + query: String?, + genres: List, + 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, 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 + 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 } + .count() + .toInt() + + return MoodRecord( + playlistId = id, + owner = row[PlaylistsTable.owner], + name = row[PlaylistsTable.name], + comment = row[PlaylistsTable.comment], + 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], + lastError = row[MoodsTable.lastError], + created = row[PlaylistsTable.createdAt], + changed = row[PlaylistsTable.changedAt], + songCount = songs.size, + duration = songs.sumOf { it[SongsTable.duration] }, + seedCount = seedCount, + ) + } + + private fun encodeGenres(genres: List): String = + Json.encodeToString( + genreSerializer, + genres.map { it.trim() }.filter { it.isNotEmpty() }.distinct().take(20), + ) + + private fun decodeGenres(value: String): List = + runCatching { Json.decodeFromString(genreSerializer, value) }.getOrDefault(emptyList()) +} diff --git a/src/main/kotlin/win/taptap/musicmanager/db/PlaylistRepository.kt b/src/main/kotlin/win/taptap/musicmanager/db/PlaylistRepository.kt index 8c6b3d8..847f36b 100644 --- a/src/main/kotlin/win/taptap/musicmanager/db/PlaylistRepository.kt +++ b/src/main/kotlin/win/taptap/musicmanager/db/PlaylistRepository.kt @@ -17,6 +17,7 @@ data class PlaylistRecord( val comment: String?, val owner: String, val isPublic: Boolean, + val kind: String, val songCount: Int, val duration: Int, val created: String, @@ -54,7 +55,13 @@ object PlaylistRepository { .map { it[PlaylistSongsTable.songId] } } - fun create(userName: String, name: String, songIds: List): PlaylistRecord = transaction { + fun create( + userName: String, + name: String, + songIds: List, + isPublic: Boolean = true, + kind: String = "user", + ): PlaylistRecord = transaction { val now = Instant.now().toString() val id = IdGenerator.playlistId(userName, name, now) @@ -62,7 +69,8 @@ object PlaylistRepository { it[PlaylistsTable.id] = id it[owner] = userName it[PlaylistsTable.name] = name - it[isPublic] = true + it[PlaylistsTable.isPublic] = isPublic + it[PlaylistsTable.kind] = kind it[createdAt] = now it[changedAt] = now } @@ -71,6 +79,15 @@ object PlaylistRepository { 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, userName: String): Boolean = transaction { val row = PlaylistsTable.selectAll() .where { PlaylistsTable.id eq playlistId } @@ -164,6 +181,7 @@ object PlaylistRepository { 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], diff --git a/src/main/kotlin/win/taptap/musicmanager/db/Tables.kt b/src/main/kotlin/win/taptap/musicmanager/db/Tables.kt index 45f8b0c..193e7ab 100644 --- a/src/main/kotlin/win/taptap/musicmanager/db/Tables.kt +++ b/src/main/kotlin/win/taptap/musicmanager/db/Tables.kt @@ -139,6 +139,7 @@ object PlaylistsTable : Table("playlists") { val name = text("name") val comment = text("comment").nullable() val isPublic = bool("is_public").default(true) + val kind = varchar("kind", 16).default("user") val createdAt = varchar("created_at", 40) val changedAt = varchar("changed_at", 40) @@ -152,3 +153,46 @@ object PlaylistSongsTable : Table("playlist_songs") { 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 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) +} + +object MoodRecommendationsTable : Table("mood_recommendations") { + val playlistId = reference("playlist_id", MoodsTable.playlistId, onDelete = ReferenceOption.CASCADE) + val videoId = varchar("video_id", 64) + val title = text("title") + val artist = text("artist") + val duration = integer("duration").nullable() + val state = varchar("state", 16).default("new") + val matchedSongId = reference( + "matched_song_id", + SongsTable.id, + onDelete = ReferenceOption.SET_NULL, + ).nullable() + val timesAdded = integer("times_added").default(0) + val firstSeen = varchar("first_seen", 40) + val lastSeen = varchar("last_seen", 40) + + override val primaryKey = PrimaryKey(playlistId, videoId) +} diff --git a/src/main/kotlin/win/taptap/musicmanager/mood/MoodMixService.kt b/src/main/kotlin/win/taptap/musicmanager/mood/MoodMixService.kt new file mode 100644 index 0000000..93d7e96 --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/mood/MoodMixService.kt @@ -0,0 +1,145 @@ +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() + 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() + 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, + seedArtistIds: List, + seedAlbumIds: Set, + 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 = + 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 + } +} diff --git a/src/main/kotlin/win/taptap/musicmanager/mood/MoodPins.kt b/src/main/kotlin/win/taptap/musicmanager/mood/MoodPins.kt new file mode 100644 index 0000000..eabba94 --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/mood/MoodPins.kt @@ -0,0 +1,38 @@ +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 { + val active = MoodSessionTracker.active(userName) + if (active != null && MoodRepository.get(active, userName) != null) { + return listOf(active) + } + return MoodRepository.moodsContainingSong(userName, songId) + } +} diff --git a/src/main/kotlin/win/taptap/musicmanager/mood/MoodService.kt b/src/main/kotlin/win/taptap/musicmanager/mood/MoodService.kt new file mode 100644 index 0000000..9d9480c --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/mood/MoodService.kt @@ -0,0 +1,66 @@ +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() + private val running = ConcurrentHashMap.newKeySet() + + 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 + } + } +} diff --git a/src/main/kotlin/win/taptap/musicmanager/mood/MoodSessionTracker.kt b/src/main/kotlin/win/taptap/musicmanager/mood/MoodSessionTracker.kt new file mode 100644 index 0000000..d3ebc5c --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/mood/MoodSessionTracker.kt @@ -0,0 +1,45 @@ +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() + + 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 + } +} diff --git a/src/main/kotlin/win/taptap/musicmanager/scanner/MediaScanner.kt b/src/main/kotlin/win/taptap/musicmanager/scanner/MediaScanner.kt index 05e765d..9387819 100644 --- a/src/main/kotlin/win/taptap/musicmanager/scanner/MediaScanner.kt +++ b/src/main/kotlin/win/taptap/musicmanager/scanner/MediaScanner.kt @@ -21,6 +21,7 @@ class MediaScanner( private val coverArtService: CoverArtService, private val tagExtractor: Mp3TagExtractor = Mp3TagExtractor(), private val repository: MediaRepository = MediaRepository, + private val onScanFinished: (ScanStatus) -> Unit = {}, ) { private val log = LoggerFactory.getLogger(MediaScanner::class.java) @@ -73,6 +74,8 @@ class MediaScanner( val finalStatus = ScanStatus(scanning = false, count = count, error = error) status.set(finalStatus) log.info("Library scan finished: {} files, error={}", count, error) + runCatching { onScanFinished(finalStatus) } + .onFailure { log.warn("Scan completion hook failed", it) } return finalStatus } diff --git a/src/main/kotlin/win/taptap/musicmanager/subsonic/models/JsonModels.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/models/JsonModels.kt index ab150ad..0082b28 100644 --- a/src/main/kotlin/win/taptap/musicmanager/subsonic/models/JsonModels.kt +++ b/src/main/kotlin/win/taptap/musicmanager/subsonic/models/JsonModels.kt @@ -10,6 +10,7 @@ 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 @@ -123,6 +124,38 @@ fun playlistJson(playlist: PlaylistRecord, songs: List? = null): Jso } } +fun moodJson( + mood: MoodRecord, + seeds: List? = null, + songs: List? = 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) diff --git a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/InteractionRoutes.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/InteractionRoutes.kt index c080619..bfa3a12 100644 --- a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/InteractionRoutes.kt +++ b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/InteractionRoutes.kt @@ -9,6 +9,8 @@ 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 @@ -34,6 +36,7 @@ fun Route.interactionRoutes(users: UsersConfig, library: LibraryConfig) { } UserStateRepository.scrobble(user.name, id, submission) } + MoodSessionTracker.touch(user.name) call.respondSubsonic() } @@ -56,7 +59,10 @@ fun Route.interactionRoutes(users: UsersConfig, library: LibraryConfig) { return@subsonicEndpoint } - songIds.forEach { UserStateRepository.starSong(user.name, it) } + 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) } @@ -81,7 +87,10 @@ fun Route.interactionRoutes(users: UsersConfig, library: LibraryConfig) { return@subsonicEndpoint } - songIds.forEach { UserStateRepository.unstarSong(user.name, it) } + 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) } diff --git a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/MediaRoutes.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/MediaRoutes.kt index c75cb42..a383bc8 100644 --- a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/MediaRoutes.kt +++ b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/MediaRoutes.kt @@ -14,6 +14,7 @@ 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 @@ -61,6 +62,7 @@ fun Route.mediaRoutes( 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()) diff --git a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/MoodRoutes.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/MoodRoutes.kt new file mode 100644 index 0000000..63e74ab --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/MoodRoutes.kt @@ -0,0 +1,265 @@ +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 = + (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 +} diff --git a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/PlaylistRoutes.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/PlaylistRoutes.kt index 6560378..8328369 100644 --- a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/PlaylistRoutes.kt +++ b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/PlaylistRoutes.kt @@ -8,13 +8,16 @@ 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) { +fun Route.playlistRoutes(users: UsersConfig, library: LibraryConfig, moodService: MoodService) { subsonicEndpoint(users, "/getPlaylists") { call, user -> val playlists = PlaylistRepository.visibleTo(user.name) @@ -41,7 +44,20 @@ fun Route.playlistRoutes(users: UsersConfig, library: LibraryConfig) { return@subsonicEndpoint } - val folders = user.visibleFolderIds(library) + 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)) }) @@ -65,6 +81,10 @@ fun Route.playlistRoutes(users: UsersConfig, library: LibraryConfig) { 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( @@ -119,6 +139,15 @@ fun Route.playlistRoutes(users: UsersConfig, library: LibraryConfig) { .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, @@ -154,6 +183,7 @@ fun Route.playlistRoutes(users: UsersConfig, library: LibraryConfig) { } PlaylistRepository.delete(playlistId, user.name) + MoodSessionTracker.clear(user.name) call.respondSubsonic() } } diff --git a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/RouteHelpers.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/RouteHelpers.kt index e8c7a86..edb412d 100644 --- a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/RouteHelpers.kt +++ b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/RouteHelpers.kt @@ -8,6 +8,7 @@ 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 @@ -24,6 +25,14 @@ fun UserAccount.effectiveFolderIds(library: LibraryConfig, musicFolderId: String 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 = + 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 diff --git a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/SubsonicRoutes.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/SubsonicRoutes.kt index 5cd99d0..0e3b7c1 100644 --- a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/SubsonicRoutes.kt +++ b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/SubsonicRoutes.kt @@ -4,6 +4,7 @@ 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 @@ -14,6 +15,7 @@ fun Route.subsonicRoutes( library: LibraryConfig, coverArtService: CoverArtService, transcoder: FfmpegTranscoder, + moodService: MoodService, startScan: () -> Boolean, scanStatus: () -> ScanStatus, ) { @@ -22,7 +24,8 @@ fun Route.subsonicRoutes( browsingRoutes(users, library) mediaRoutes(users, library, coverArtService, transcoder) interactionRoutes(users, library) - playlistRoutes(users, library) + playlistRoutes(users, library, moodService) + moodRoutes(users, library, moodService) playQueueRoutes(users, library) } } diff --git a/src/main/resources/db/migration/V4__moods.sql b/src/main/resources/db/migration/V4__moods.sql new file mode 100644 index 0000000..55fe510 --- /dev/null +++ b/src/main/resources/db/migration/V4__moods.sql @@ -0,0 +1,47 @@ +-- Moods are private, server-managed playlists. The playlist stays the +-- Symfonium-visible object; this table holds the generation settings. +ALTER TABLE playlists ADD COLUMN kind TEXT NOT NULL DEFAULT 'user' + CHECK (kind IN ('user', 'mood')); + +CREATE TABLE moods ( + playlist_id TEXT PRIMARY KEY REFERENCES playlists(id) ON DELETE CASCADE, + query TEXT, + genres TEXT NOT NULL DEFAULT '[]', + target_size INTEGER NOT NULL DEFAULT 50, + yt_slots INTEGER NOT NULL DEFAULT 0, + expand_related BOOLEAN NOT NULL DEFAULT 1, + refresh_hours INTEGER NOT NULL DEFAULT 24, + generated_at TEXT, + generation INTEGER NOT NULL DEFAULT 0, + last_error TEXT +); + +-- Manual, promoted and liked songs are permanent anchors for the mood. +CREATE TABLE mood_seeds ( + playlist_id TEXT NOT NULL REFERENCES moods(playlist_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', 'promoted', 'star', 'yt_like')), + added_at TEXT NOT NULL, + PRIMARY KEY (playlist_id, song_id) +); + +-- YT Music candidates. The downloader and recommendation UI land in a later +-- phase; the table is created now so generation does not need a migration. +CREATE TABLE mood_recommendations ( + playlist_id TEXT NOT NULL REFERENCES moods(playlist_id) ON DELETE CASCADE, + video_id TEXT NOT NULL, + title TEXT NOT NULL, + artist TEXT NOT NULL, + duration INTEGER, + state TEXT NOT NULL DEFAULT 'new' + CHECK (state IN ('new', 'liked', 'rejected', 'downloaded')), + 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 (playlist_id, video_id) +); + +CREATE INDEX idx_mood_seeds_song ON mood_seeds (song_id); +CREATE INDEX idx_mood_recommendations_song ON mood_recommendations (matched_song_id); diff --git a/src/main/resources/web/index.html b/src/main/resources/web/index.html index 5f255dc..ffcce96 100644 --- a/src/main/resources/web/index.html +++ b/src/main/resources/web/index.html @@ -44,12 +44,17 @@ #status.error { color:#ff7b72; } #crumb { cursor:pointer; color:var(--accent); } .hidden { display:none !important; } + form label { display:grid; gap:5px; font-size:13px; color:var(--muted); } + form label.row { display:flex; gap:8px; align-items:center; color:var(--text); } + form input[type=checkbox] { width:auto; } + .error { color:#ff7b72; }