diff --git a/README.md b/README.md index 433a0a6..5f22c8a 100644 --- a/README.md +++ b/README.md @@ -1,934 +1,322 @@ -# MusicManager - Self-hosted OpenSubsonic Server (Kotlin / Ktor) +# AudioManager -## How to use +A self-hosted, mood-first music server in Kotlin/Ktor, plus a Kotlin Multiplatform client. -This is the short version. The detailed design and endpoint reference follow in the sections below. +AudioManager replaces static playlists with **moods**: curated anchors plus a radio queue that is generated live by the server and learns from what you finish and skip. There is no like button and no OpenSubsonic layer — the native API and the native client are designed together around this model. -### 1. Prerequisites +## Contents -- JVM 21 (or `nix-shell` from this repository, which provides JDK 21, Gradle, ffmpeg and sqlite) -- `ffmpeg` on `PATH` (used for transcoding; direct play works without it) -- An MP3 library on disk, laid out as `Artist/Album/Track.mp3` if tags are missing +1. [Quick start](#quick-start) +2. [Configuration](#configuration) +3. [The mood model](#the-mood-model) +4. [Native API](#native-api) +5. [Architecture](#architecture) +6. [Database](#database) +7. [Scanner](#scanner) +8. [Deployment](#deployment) +9. [Client](#client) +10. [Testing](#testing) +11. [Roadmap](#roadmap) -### 2. Configure the library +--- -Create the local config and media directories: +## Quick start + +Requirements: JDK 21, ffmpeg, SQLite (bundled through JDBC). ```bash -./gradlew setupLocal -``` +# 1. Build +gradle shadowJar -This copies `config/library.example.yaml` to `config/library.yaml` (only when it does not exist), copies `config/users.example.yaml` to `config/users.yaml` and creates `media/music` plus `media/longform`. Both local config files are git-ignored, so `git pull` never touches them. - -`config/library.yaml` defines every root the server indexes: - -```yaml +# 2. Point the server at a library +mkdir -p data +cat > config/library.yaml <<'YAML' library: folders: - id: 1 - name: "Music" + name: Music type: music - path: ./media/music + path: /absolute/path/to/music - id: 10 - name: "Audiobooks & Podcasts" + name: Long-form type: longform - path: ./media/longform -``` + path: /absolute/path/to/longform +YAML -The example file already uses these relative paths, so no edit is needed for local development. Relative paths are resolved from the working directory (`./gradlew run` uses the project root). For deployment, replace them with absolute paths such as `/mnt/media/music/alice` (see Section 6.1). - -- `type: music` roots are assigned per user; `type: longform` roots are shared with every user. -- `id` must be stable and unique (integers). It is part of song IDs, so do not renumber it after a scan. -- Paths must exist and be readable, otherwise the server refuses to start with a clear error naming the folder. - -### 3. Configure users - -`./gradlew setupLocal` already created it. To recreate it manually: - -```bash -cp config/users.example.yaml config/users.yaml -``` - -```yaml +# 3. Define users (passwords stay outside SQLite) +cat > config/users.yaml <<'YAML' users: - name: alice - password: "change-me" + password: change-me admin: true folders: [1] +YAML + +# 4. Run +DATA_DIR=./data LIBRARY_CONFIG=./config/library.yaml USERS_FILE=./config/users.yaml \ + java -jar build/libs/musicmanager-*-all.jar ``` -- `folders` lists the *music* folder IDs the user may see; long-form folders are added automatically. -- At least one admin is needed to trigger scans. -- Passwords live only in this file and in memory. In production the file is provided by Vault (see Section 6.2); `config/users.yaml` is git-ignored. - -### 4. Start the server +Open `http://localhost:8080/ui`. The first start scans the library automatically because the database is empty. Later scans are manual: ```bash -nix-shell # optional: provides the toolchain -./gradlew run +curl -X POST -H "Authorization: Bearer $TOKEN" http://localhost:8080/api/v1/scan ``` -Or build and run the fat JAR: +The built-in UI is an admin/management surface: users, moods, seeds, library search, and a browser radio player. -```bash -./gradlew shadowJar -java -jar build/libs/musicmanager-0.1.0-all.jar -``` +## Configuration -The server listens on `http://localhost:8080`. Open `http://localhost:8080/ui` for the built-in test client (log in with a user from `users.yaml`). Override with `PORT`, `DATA_DIR`, `LIBRARY_CONFIG`, `USERS_FILE`, `FFMPEG_PATH` and `WEB_UI` (see Section 6.3). The SQLite database and cover cache are written to `./data`. - -On first start, the server scans automatically because the database is empty. After that, scans are manual. - -### 5. Trigger a scan - -Use an admin account. Token auth is what real clients use: - -```bash -SALT=abc123 -TOKEN=$(printf '%s%s' 'change-me' "$SALT" | md5sum | cut -d' ' -f1) - -curl -s "http://localhost:8080/rest/startScan?u=alice&t=$TOKEN&s=$SALT&v=1.16.1&c=curl&f=json" -curl -s "http://localhost:8080/rest/getScanStatus?u=alice&t=$TOKEN&s=$SALT&v=1.16.1&c=curl&f=json" -``` - -For quick manual testing you can pass the password in plaintext instead: `&p=change-me` (use `p=enc:` if it contains special characters). - -### 6. Connect a client (Symfonium) - -For a quick browser check, open `http://localhost:8080/ui` and log in with a user from `users.yaml`. It lists folders, albums and songs and can play streams; it is a debugging aid, not a full music client. - -For a real client: - -1. Add a new **Subsonic** server. -2. URL: `http://:8080` (or `https://subsonic.tap-tap.win` when deployed). -3. Username and password from `users.yaml`. -4. Let Symfonium sync. Music and long-form appear as separate **music folders** - select the one you want so the two content types never mix. - -### 7. Verify it works - -```bash -# health (no auth) -curl -s http://localhost:8080/health - -# list the folders this user can see -curl -s "http://localhost:8080/rest/getMusicFolders?u=alice&t=$TOKEN&s=$SALT&v=1.16.1&c=curl&f=json" - -# search and stream the first result -curl -s "http://localhost:8080/rest/search3?u=alice&t=$TOKEN&s=$SALT&v=1.16.1&c=curl&f=json&query=*&songCount=1" -curl -o track.mp3 "http://localhost:8080/rest/stream?u=alice&t=$TOKEN&s=$SALT&v=1.16.1&c=curl&f=json&id=" -``` - -All responses are JSON (no XML). Errors are returned as HTTP 200 with a Subsonic `error.code`; HTTP status codes are reserved for transport-level problems. - -### 8. Stop, back up, upgrade - -- Stop the process gracefully (`Ctrl+C` or `SIGTERM`); in-flight streams are allowed to finish. -- Back up `DATA_DIR` (SQLite database + `covers/`) while stopped, or use `sqlite3 data/musicmanager.db ".backup backup.db"`. -- The schema is migrated automatically by Flyway on startup. -- Re-running a scan only reads changed files (delta by mtime + size); IDs stay stable across scans. - ---- - -## 1. Goal & Context - -Build a lightweight, self-hosted **OpenSubsonic-compatible music server** in **Kotlin** that replaces Plex for audio streaming and is optimised for the Android client **Symfonium**. - -### Scope (MVP) - -1. **Library indexing:** index MP3 files only for now (other extensions are skipped and logged). Tags come first, with the folder layout `Artist/Album/Track` as fallback. Data is persisted in SQLite. -2. **Symfonium sync:** implement the OpenSubsonic browsing endpoints so Symfonium can sync the full catalog into its offline-first database. -3. **Streaming & offline downloads:** serve audio files with HTTP `Range` (`206 Partial Content`), exact byte sizes and correct metadata so seeking and Symfonium's offline download manager work reliably. -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. **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) - -- Audio formats other than MP3 (FLAC/OGG/M4A/Opus are future work). -- XML responses (JSON only). -- Podcast RSS ingestion, chapters or audiobook-specific metadata. -- Upload, sharing, social features. -- 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 - -- **Admin:** may trigger scans. -- **User:** regular library access. -- All users share the same long-form roots; each user has their own music roots. -- Per-user state: play counts, last played, stars, ratings, bookmarks, playlists. - ---- - -## 2. Tech Stack & Dependencies - -- **Language & runtime:** Kotlin 2.x on JVM 21 (`eclipse-temurin:21-jre-jammy`) -- **Build:** Gradle Kotlin DSL (`build.gradle.kts`), ShadowJar fat JAR -- **Web:** Ktor Server (Netty) - - `ktor-server-core`, `ktor-server-netty` - - `ktor-server-content-negotiation` + `ktor-serialization-kotlinx-json` - - `ktor-server-partial-content` (HTTP `Range` / `206`) - - `ktor-server-status-pages`, `ktor-server-call-logging`, `ktor-server-auto-head-response` -- **Database:** SQLite in `WAL` mode + JetBrains Exposed (`exposed-core`, `exposed-dao`, `exposed-jdbc`, `exposed-java-time`) + `sqlite-jdbc` + HikariCP -- **Migrations:** Flyway (`flyway-core`) with versioned SQL under `src/main/resources/db/migration` -- **Audio metadata:** `net.jthink:jaudiotagger` (MP3/ID3 only for the MVP) -- **Covers:** `net.coobird:thumbnailator` for on-the-fly resizing -- **Transcoding:** `ffmpeg` binary in the runtime image (libmp3lame), invoked as a subprocess -- **Logging:** `logback-classic` + `kotlin-logging-jvm` -- **Config:** YAML (`library.yaml`, `users.yaml`) with env-var overrides for paths and secrets -- **Deployment:** multi-stage Dockerfile, Helm chart for k3s, Gitea Actions for tests and artifact publishing, local release script for image pushes - ---- - -## 3. Project Structure - -```text -src/main/kotlin/win/taptap/musicmanager/ -|-- Application.kt # Ktor entry point, plugins, graceful shutdown -|-- config/ -| |-- AppConfig.kt # Port, data dir, ffmpeg path, env overrides -| |-- LibraryConfig.kt # Music folders and their type/path -| `-- UsersConfig.kt # Users, admins and folder assignments -|-- db/ -| |-- DatabaseFactory.kt # SQLite init, PRAGMA journal_mode=WAL, Flyway -| |-- Tables.kt # Exposed table definitions -| |-- 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 -| |-- models/ # kotlinx.serialization DTOs -| | |-- SystemModels.kt -| | |-- BrowsingModels.kt -| | |-- MediaModels.kt -| | `-- PlaylistModels.kt -| `-- routes/ # /rest/{endpoint} and /rest/{endpoint}.view -| |-- SystemRoutes.kt # ping, getLicense, extensions, startScan, getScanStatus -| |-- 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 -| `-- MoodRoutes.kt # custom mood management endpoints -|-- transcoding/ -| `-- FfmpegTranscoder.kt # MP3 transcoding with maxBitRate and timeOffset -`-- util/ - `-- IdGenerator.kt # Deterministic SHA-256 IDs -``` - ---- - -## 4. Architecture Rules - -### 4.1 Deterministic IDs (critical) - -IDs must never change on a re-scan; otherwise Symfonium loses offline download state and playlist assignments. - -- IDs use **24 hex characters** (96 bit). -- **Artist ID:** `"ar-" + sha256(normalizedAlbumArtist).take(24)` -- **Album ID:** `"al-" + sha256(normalizedAlbumArtist + "|" + normalizedAlbumTitle).take(24)` -- **Song ID:** `"sg-" + sha256(folderId + ":" + relativePathFromFolderRoot).take(24)` -- **Cover ID:** same as the album ID (`"al-..."`). Artist artwork is not served in the MVP. - -**Normalization is frozen** and must never change without a migration: - -1. Unicode NFC -2. Trim and collapse internal whitespace -3. Lowercase with `Locale.ROOT` - -Song IDs are path-based: renaming or moving a file creates a new ID. This is accepted. - -### 4.2 Album grouping via album artist - -Albums are grouped by the `ALBUM_ARTIST` tag. Fallbacks: `ARTIST` tag, then parent folder name. This prevents albums with featuring artists from fragmenting. - -- `albums` have one or more artists (`album_artists`), position 0 is the primary album artist. -- Songs additionally keep a display artist string and their full artist list (`song_artists`). -- `song.artist_id` in API responses means the **album artist**; track credits are exposed via `displayArtist` / `artists[]`. - -### 4.3 User-scoped library visibility - -- The catalog is global; users see only folders assigned to them. -- Every browsing and media query filters songs by the requesting user's visible folder IDs. -- Because album IDs are deterministic and roots can contain the same album for different users, an album may aggregate songs from several folders. Therefore: - - `getAlbum(id)` returns only songs from folders visible to the caller. - - An album/artist is returned only if it has at least one visible song. - - Album-level names, years and covers are global; per-user state is never global. -- `getMusicFolders` returns the caller's assigned music folders plus the shared long-form folders. -- Songs store `folder_id`; `music_folders` is synced from config on startup and referenced by foreign key. -- Long-form content uses the same artist/album/song model; separation is via folder type, not a separate API. - -### 4.4 Exact file metadata for offline downloads - -Every song object must include: - -- `size: Long` - exact byte size -- `duration: Int` - seconds -- `bitRate: Int` - kbps -- `suffix: String` - `"mp3"` -- `contentType: String` - `"audio/mpeg"` - -Symfonium verifies downloaded bytes against `size` after each offline download. - -### 4.5 Routing conventions & `formPost` - -- Register every endpoint for **both** `/{method}` and `/{method}.view`. -- Read parameters from `call.request.queryParameters` **and** `call.receiveParameters()` (POST `application/x-www-form-urlencoded`). -- Declare the `formPost` OpenSubsonic extension. -- Repeatable parameters (`songId`, `songIdToAdd`, `songIndexToRemove`) must be read as lists. - -### 4.6 JSON envelope - -Every response, including errors, uses `status: "ok"` or `status: "failed"` and HTTP 200: - -```json -{ - "subsonic-response": { - "status": "ok", - "version": "1.16.1", - "type": "musicmanager", - "serverVersion": "0.1.0", - "openSubsonic": true - } -} -``` - -Error codes: `0` generic, `10` missing parameter, `20` incompatible client, `30` incompatible server, `40` wrong credentials, `50` not authorized, `70` not found. - -### 4.7 Transcoding rules - -- `stream` accepts `maxBitRate` (kbps), `format` and `timeOffset` (seconds). -- Direct play when no transcode is requested or when the source bitrate is already `<= maxBitRate`. -- Transcoding target is always **MP3** (`libmp3lame`). A requested `format` other than `mp3` falls back to MP3. -- `timeOffset` is implemented with `ffmpeg -ss`, declared as the `transcodeOffset` OpenSubsonic extension. -- Transcoded responses are chunked and do **not** support byte `Range`. Seeking uses `timeOffset`. -- `download` always returns the original file, never a transcode. -- Direct-play responses support `Range` / `206` via the `PartialContent` plugin. - ---- - -## 5. Database Schema (SQLite) - -Identity and folder tables are synced from config at startup; passwords are never stored in SQLite. - -```sql -CREATE TABLE users ( - name TEXT PRIMARY KEY, - is_admin BOOLEAN NOT NULL DEFAULT 0, - updated_at TEXT NOT NULL -); - -CREATE TABLE music_folders ( - id INTEGER PRIMARY KEY, - name TEXT NOT NULL, - type TEXT NOT NULL CHECK (type IN ('music', 'longform')), - root_path TEXT NOT NULL -); - -CREATE TABLE artists ( - id TEXT PRIMARY KEY, - name TEXT NOT NULL, - sort_name TEXT NOT NULL, - cover_art TEXT, - search_text TEXT NOT NULL -); - -CREATE TABLE albums ( - id TEXT PRIMARY KEY, - name TEXT NOT NULL, - year INTEGER, - cover_art TEXT, - created_at TEXT NOT NULL, - search_text TEXT NOT NULL -); - -CREATE TABLE album_artists ( - album_id TEXT NOT NULL REFERENCES albums(id) ON DELETE CASCADE, - artist_id TEXT NOT NULL REFERENCES artists(id) ON DELETE CASCADE, - position INTEGER NOT NULL, - PRIMARY KEY (album_id, position) -); - -CREATE TABLE songs ( - id TEXT PRIMARY KEY, - album_id TEXT NOT NULL REFERENCES albums(id) ON DELETE CASCADE, - folder_id INTEGER NOT NULL REFERENCES music_folders(id), - title TEXT NOT NULL, - display_artist TEXT NOT NULL, - album_name TEXT NOT NULL, - track_number INTEGER, - disc_number INTEGER DEFAULT 1, - year INTEGER, - duration INTEGER NOT NULL, - bit_rate INTEGER NOT NULL, - size INTEGER NOT NULL, - suffix TEXT NOT NULL, - content_type TEXT NOT NULL, - relative_path TEXT NOT NULL, - file_mtime INTEGER NOT NULL, - created_at TEXT NOT NULL, - search_text TEXT NOT NULL, - UNIQUE (folder_id, relative_path) -); - -CREATE TABLE song_artists ( - song_id TEXT NOT NULL REFERENCES songs(id) ON DELETE CASCADE, - artist_id TEXT NOT NULL REFERENCES artists(id) ON DELETE CASCADE, - position INTEGER NOT NULL, - PRIMARY KEY (song_id, position) -); - --- Multi-value tags. Text keys keep the schema simple; uniqueness is enforced. -CREATE TABLE song_genres ( - song_id TEXT NOT NULL REFERENCES songs(id) ON DELETE CASCADE, - genre TEXT NOT NULL, - PRIMARY KEY (song_id, genre) -); - -CREATE TABLE album_genres ( - album_id TEXT NOT NULL REFERENCES albums(id) ON DELETE CASCADE, - genre TEXT NOT NULL, - PRIMARY KEY (album_id, genre) -); - -CREATE TABLE artist_genres ( - artist_id TEXT NOT NULL REFERENCES artists(id) ON DELETE CASCADE, - genre TEXT NOT NULL, - PRIMARY KEY (artist_id, genre) -); - --- Per-user state -CREATE TABLE user_song_state ( - user_name TEXT NOT NULL REFERENCES users(name) ON DELETE CASCADE, - song_id TEXT NOT NULL REFERENCES songs(id) ON DELETE CASCADE, - play_count INTEGER NOT NULL DEFAULT 0, - last_played_at TEXT, - starred_at TEXT, - rating INTEGER, - PRIMARY KEY (user_name, song_id) -); - -CREATE TABLE user_stars ( - user_name TEXT NOT NULL REFERENCES users(name) ON DELETE CASCADE, - item_type TEXT NOT NULL CHECK (item_type IN ('album', 'artist')), - item_id TEXT NOT NULL, - starred_at TEXT NOT NULL, - PRIMARY KEY (user_name, item_type, item_id) -); - -CREATE TABLE bookmarks ( - user_name TEXT NOT NULL REFERENCES users(name) ON DELETE CASCADE, - song_id TEXT NOT NULL REFERENCES songs(id) ON DELETE CASCADE, - position_ms INTEGER NOT NULL, - updated_at TEXT NOT NULL, - PRIMARY KEY (user_name, song_id) -); - -CREATE TABLE playlists ( - id TEXT PRIMARY KEY, - owner TEXT NOT NULL REFERENCES users(name) ON DELETE CASCADE, - 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 -); - -CREATE TABLE playlist_songs ( - playlist_id TEXT NOT NULL REFERENCES playlists(id) ON DELETE CASCADE, - song_id TEXT NOT NULL REFERENCES songs(id) ON DELETE CASCADE, - 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: - -- `albums(search_text)`, `artists(search_text)`, `songs(search_text)` -- `songs(album_id)`, `songs(folder_id)`, `songs(created_at)` -- `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. - ---- - -## 6. Configuration - -### 6.1 `library.yaml` (ConfigMap) +### `library.yaml` ```yaml library: folders: - id: 1 - name: "Alice - Music" + name: Music type: music - path: /mnt/media/music/alice - - id: 2 - name: "Bob - Music" - type: music - path: /mnt/media/music/bob + path: /mnt/media/music - id: 10 - name: "Audiobooks & Podcasts" + name: Long-form type: longform path: /mnt/media/longform ``` -### 6.2 `users.yaml` (Vault-managed Secret) +- `type` is either `music` or `longform`. They are never mixed in a mood. +- IDs are stable and referenced by songs; never reuse an ID for a different path. +- Long-form folders are shared with every user automatically. -Mounted from a HashiCorp Vault secret and read at startup. Passwords exist only in that secret and in memory - never in SQLite, logs or the Helm chart. +### `users.yaml` ```yaml users: - name: alice - password: "" + password: change-me admin: true folders: [1] - name: bob - password: "" + password: another-secret admin: false - folders: [2] + folders: [1] ``` -- Long-form folders are shared automatically; users only list their music folders. -- Env override: `USERS_FILE` (default `./config/users.yaml`; in the container `/etc/musicmanager/users.yaml`). -- Env override: `LIBRARY_CONFIG` (default `./config/library.yaml`; in the container `/etc/musicmanager/library.yaml`). -- `users` and `music_folders` tables are reconciled on startup; removed users/folders are deleted with their per-user state or orphaned songs. -- If `users.yaml` is missing or empty, the server refuses to start (fail closed). +Passwords are read into memory at startup and never written to SQLite. In production this file is a Vault-managed Secret. Restart the deployment after changing users. -### 6.3 Environment variables +### Environment -| Variable | Default | Purpose | +| Variable | Default | Meaning | | --- | --- | --- | -| `PORT` | `8080` | HTTP listen port | -| `DATA_DIR` | `./data` | SQLite DB and cover cache (`/data` in Kubernetes) | -| `LIBRARY_CONFIG` | `./config/library.yaml` | Library folder definitions | -| `USERS_FILE` | `./config/users.yaml` | Vault-managed users file | -| `FFMPEG_PATH` | `ffmpeg` | ffmpeg binary used for transcoding | -| `WEB_UI` | `true` | Serve the built-in test client at `/ui` | +| `PORT` | `8080` | HTTP port | +| `DATA_DIR` | `./data` | SQLite database and cover cache | +| `LIBRARY_CONFIG` | `./config/library.yaml` | Library folders | +| `USERS_FILE` | `./config/users.yaml` | Users and passwords | +| `FFMPEG_PATH` | `ffmpeg` | Transcoder binary | +| `WEB_UI` | `true` | Serve the built-in management UI | -### 6.4 Local development +## The mood model -See [How to use](#how-to-use) for the full setup. In short: +A mood is a private collection owned by one user: -```bash -cp config/library.example.yaml config/library.yaml -cp config/users.example.yaml config/users.yaml -mkdir -p media/music media/longform -# edit the paths in config/library.yaml to point at ./media/* -nix-shell # optional: JDK 21, Gradle, ffmpeg and sqlite -./gradlew run +- **Seeds** are permanent anchors. Every seed is always eligible for the radio. +- **Genres / free-text hint** widen the candidate pool. +- **Target size** is the desired batch and session size, not a hard playlist length. +- **Radio** is generated by the server for each playback session. It mixes seeds, related genres and artists, text matches, and the rest of the owner's music. +- **Signals** come from playback: completed tracks gain weight, skipped tracks lose weight. There are no likes. +- **Add to mood** is explicit. The client offers *add to current mood* and *choose another mood*, and the server turns the track into a manual seed. +- **Long-form is excluded** at seed validation and radio generation. + +A playback session belongs to one mood and one user. The server remembers queued tracks so a batch never repeats within the session, and a client can resume after a restart. + +## Native API + +All endpoints live under `/api/v1`. JSON in, JSON out, standard HTTP status codes. Errors use: + +```json +{ "error": { "code": "not_found", "message": "Mood not found" } } ``` -The database and covers are written to `./data`. `config/users.yaml` is git-ignored. +### Authentication ---- +```http +POST /api/v1/auth/login +Content-Type: application/json -## 7. MVP Endpoint Specification +{ "username": "alice", "password": "change-me", "deviceName": "Pixel", "platform": "android" } +``` -All endpoints live under `/rest/{endpoint}` and `/rest/{endpoint}.view`. +```json +{ + "token": "…", + "expiresAt": "2027-05-13T…", + "user": { "name": "alice", "admin": true, "musicFolders": [1], "longformFolders": [10] } +} +``` -### 7.1 Authentication (`SubsonicAuth`) +Send `Authorization: Bearer ` on every request. Tokens are stored as SHA-256 hashes and expire after 180 days. Media URLs may also use `?token=` because HTML audio and `` tags cannot set headers. -For every `/rest/*` call (except an optional health check): +- `POST /auth/logout` revokes the current token. +- `GET /auth/devices` lists devices; `DELETE /auth/devices/{id}` revokes one. +- `GET /me` returns the user and folder IDs. -- `u` must match a configured user. -- Token auth: `t` and `s` present -> verify `t.equals(md5(password + s), ignoreCase = true)`. -- Password auth: `p` present -> if `p` starts with `enc:`, hex-decode it; compare to the password. -- Comparisons use constant-time equality. -- On failure: HTTP 200 with a Subsonic error (`code = 40`). -- The authenticated user is attached to the call and used for all per-user filtering and state. +### Library sync -### 7.2 System & scan +- `GET /library/songs?cursor=&limit=500&scope=music|longform|all` — snapshot page, ordered by song ID. Loop while `nextCursor` is present. +- `GET /library/songs?since=` — delta with `songs` and `deletedSongIds`. Loop while `nextSince` is present. +- `GET /library/search?q=&limit=&scope=` — normalized substring search. +- `GET /songs/{id}/stream` — original MP3 with Range support. Optional `maxBitRate`, `timeOffset`, `format`, `download=true`. +- `GET /covers/{albumIdOrSongId}?size=320` — cached JPEG cover. -- `ping`: empty `subsonic-response` with `status: "ok"`. -- `getLicense`: `{"license": {"valid": true}}`. -- `getOpenSubsonicExtensions`: `[{formPost, [1]}, {songLyrics, [1]}, {transcodeOffset, [1]}]`. -- `startScan`: admin only; starts an async coroutine scan. -- `getScanStatus`: `{"scanStatus": {"scanning": Boolean, "count": Long}}`. -- `getUser(username)`: returns roles and visible folder IDs; users may only query themselves, admins may query anyone. -- `getUsers`: admin only; lists all configured users. +Song objects contain deterministic IDs (`sg-…`), album/artist names, duration, size, bitrate, genres, `folderId`, `relativePath`, and `updatedAt`, so a client can build an offline library without extra requests. -### 7.3 Browsing & search +### Moods -- `getMusicFolders`: the caller's music folders plus shared long-form folders. -- `getIndexes`: alphabetically grouped artists visible to the caller (`index: [{name, artist[]}]`), including `lastModified` and `ignoredArticles`. -- `getArtists`: ID3-based alphabet structure (`artists: {ignoredArticles, index[]}`), filtered by visibility. -- `getArtist(id)`: artist details plus all visible albums. -- `getAlbum(id)`: album details plus visible songs, sorted by `discNumber`, `trackNumber`. -- `getSong(id)`: single song, only if visible to the caller. -- `search3(query, ...Count, ...Offset)`: case-insensitive substring search over normalized `search_text` using `LIKE` with escaped wildcards. Empty `query` returns paginated results; `query="*"` returns everything visible. -- `getGenres`: distinct genres from visible songs. -- `getSongsByGenre(genre, count, offset)`: paginated visible songs in a genre. -- `getStarred2`: the caller's starred artists, albums and songs for the home screen. +- `GET /moods` +- `POST /moods` — `{ name, description?, query?, genres[], targetSize, refreshHours, ytEnabled, seedSongIds[] }` +- `GET /moods/{id}` — mood, seeds and recommendations. +- `PATCH /moods/{id}` — partial settings update; `clearDescription` / `clearQuery` clear fields. +- `DELETE /moods/{id}` +- `POST /moods/{id}/seeds` — `{ songId }` +- `DELETE /moods/{id}/seeds/{songId}` +- `GET /moods/{id}/preview?limit=20` — unpersisted radio preview. +- `GET /moods/{id}/recommendations` — YT Music candidates (see roadmap). -### 7.4 Home feeds +### Radio sessions -- `getAlbumList2(type, size, offset, fromYear, toYear, genre)`: `newest`, `recent`, `frequent`, `random`, `alphabeticalByName`, `alphabeticalByArtist`, `starred`, `byYear`, `byGenre`. All results are visibility- and user-scoped. -- `getRandomSongs(size, genre, fromYear, toYear)`: random visible songs. +- `POST /moods/{id}/sessions` — `{ limit?: 15 }` → session plus the first queue. +- `GET /sessions/{id}` — resume: session and queued tracks. +- `POST /sessions/{id}/next` — `{ limit?, excludeSongIds[] }` → the next batch. +- `POST /sessions/{id}/events` — `{ events: [{ songId, type: "started"|"completed"|"skipped", positionSeconds? }] }` +- `POST /sessions/{id}/add-to-mood` — `{ songId, moodId? }`. Without `moodId`, the session's mood is used. This is the replacement for likes. +- `DELETE /sessions/{id}` — close. -### 7.5 Media & artwork +### System -- `stream(id, maxBitRate, format, timeOffset)`: - - direct play via `call.respondFile` (PartialContent handles `Range`); - - otherwise stream ffmpeg MP3 output with chunked transfer; - - set `Content-Type` from the actual response. -- `download(id)`: original file with `Content-Disposition: attachment; filename*=UTF-8''...` (RFC 5987 for non-ASCII names). -- `getCoverArt(id, size)`: serve `DATA_DIR/covers/{albumId}.jpg`; if `size` is given, resize proportionally with Thumbnailator and cache as `{albumId}_{size}.jpg`. Validate `size` (`1..2048`). -- `getLyricsBySongId(id)`: read embedded ID3 lyrics or a sibling `.lrc` file; return the OpenSubsonic `lyricsList` format. +- `GET /scan` — `{ scanning, count, error }` +- `POST /scan` — admin only; 202 Accepted. +- `GET /health` — unauthenticated liveness probe. -### 7.6 Interaction, bookmarks & playlists - -- `scrobble(id, time, submission)`: per user; `submission=true` (default) increments `play_count` and sets `last_played_at`. -- `star(id, albumId, artistId)` / `unstar(...)`: per user. -- `setRating(id, rating)`: per user, 1-5; `0` clears. -- `getBookmarks` / `createBookmark(id, position)` / `deleteBookmark(id)`: per user; `position` is milliseconds. -- `getPlaylists`: the caller's playlists plus all public ones. -- `getPlaylist(id)`: if public or owned by the caller. -- `createPlaylist(playlistId, name, songId)`: owner is the caller. -- `updatePlaylist(playlistId, name, comment, public, songIdToAdd, songIndexToRemove)`: owner only; indices are applied in order. -- `deletePlaylist(playlistId)`: owner only. -- `getMusicDirectory(id)`: folder IDs return their albums as directories; album IDs return their songs. Used by folder-browsing clients. -- `savePlayQueue` / `getPlayQueue` (and the `*ByIndex` variants): per-user queue kept in memory. -- `jukeboxControl(action=status)` returns a stopped status; other jukebox actions report that jukebox is unsupported. -- `getInternetRadioStations` returns an empty list; radio mutation endpoints report that radio is unsupported. - -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: +## Architecture ```text -Action: app.symfonium.api.MEDIA_SYNC -Package: app.symfonik.music.player -Class: app.symfonium.remote.api.ApiReceiver -Extra: PROVIDER_ID = Providers> +src/main/kotlin/win/taptap/musicmanager/ +|-- Application.kt # Ktor entry point, plugins, graceful shutdown +|-- config/ +| |-- AppConfig.kt # Port, data dir, ffmpeg, env overrides +| |-- LibraryConfig.kt # Folder IDs, types and paths +| `-- UsersConfig.kt # Users, admins and folder assignments +|-- api/ +| |-- ApiRoutes.kt # /api/v1 wiring, auth and system endpoints +| |-- ApiModels.kt # Native DTOs +| |-- ApiSupport.kt # Token resolution, errors, folder scoping +| |-- LibraryApi.kt # Sync, search, stream, covers +| |-- MoodApi.kt # Mood CRUD, seeds, preview, recommendations +| `-- SessionApi.kt # Radio sessions, events, add-to-mood +|-- radio/ +| `-- RadioService.kt # Candidate pool, scoring, diversity, batches +|-- db/ +| |-- DatabaseFactory.kt # SQLite WAL + Flyway +| |-- Tables.kt # Exposed definitions +| |-- ApiTokenRepository.kt # Hashed bearer tokens +| |-- RadioRepository.kt # Sessions, events, affinity +| |-- MoodRepository.kt # Moods, seeds, recommendations +| |-- LibraryRepository.kt # Scoped browsing, sync, search +| `-- MediaRepository.kt # Scanner persistence and tombstones +|-- scanner/ # Recursive MP3 scan, tags, covers +|-- transcoding/ # ffmpeg MP3 transcoding +`-- util/ # Deterministic IDs, sort names ``` ---- +The old OpenSubsonic layer (`/rest`, `subsonic/`, playlist materialization) was removed in 0.2.0. The server and the KMP client are the two halves of the same product; there is no compatibility layer to preserve. -## 8. Scanner +## Database -- Scan all configured folder roots recursively; accept `.mp3` (case-insensitive) only, log every skipped file. -- Tag-first: title, artist, album artist, album, track/disc, year, genre(s), duration, bitrate, embedded cover, lyrics. -- Fallback: parent folder as album, grandparent as artist; filename as title. -- Delta scan by `(file_mtime, size)`; unchanged files are skipped. -- Orphan cleanup: delete songs (and their state) whose files disappeared. -- Initial scan on startup only when the `songs` table is empty; otherwise rely on `startScan`. -- One scan at a time; a second `startScan` returns the current status. -- All writes in a single transaction per batch; streaming reads continue under WAL. -- Album/artist rows are recomputed after each scan (aggregated genre lists, sort names, cover references). +SQLite in WAL mode, migrations through Flyway: -Cover extraction order: embedded APIC frame -> `cover.jpg`/`folder.jpg`/`front.jpg` next to the file -> album directory -> none. +- `V1__init.sql` — users, folders, artists, albums, songs, user state. +- `V2__user_item_ratings.sql`, `V3__song_lyrics.sql`. +- `V4__moods.sql` — the first playlist-based mood prototype. +- `V5__native_api.sql` — native moods, tokens, playback sessions, affinity, tombstones; drops playlists; adds `songs.updated_at`. ---- +Key invariants: -## 9. Deployment (k3s + Helm) +- IDs are deterministic (`ar-`, `al-`, `sg-`, `mo-`) with frozen normalization (NFC, trimmed, collapsed whitespace, lowercase). +- Albums are grouped by album artist, not by track artist. +- Deleted songs leave tombstones so offline clients can remove them. +- Passwords never appear in the database. -### 9.1 Image +## Scanner -- Multi-stage Dockerfile: Gradle build -> glibc-based `eclipse-temurin:21-jre-jammy` with `ffmpeg` installed (Alpine/musl is unsupported by sqlite-jdbc's bundled native library). -- Runtime flags: `-XX:+UseSerialGC -Xmx256m` (adjustable via Helm). -- Non-root user (UID 10001), read-only root filesystem, `/tmp` as `emptyDir`, `/data` as PVC. -- Image: `gitea.tap-tap.win/taptap/audiomanager:` (registry paths must be lowercase). -- Gitea Actions builds and pushes `:sha-` and `:latest` on `main`, and the tag name for `v*` tags; `imagePullSecret` is provided by the cluster. +- Indexes `.mp3` recursively; other extensions are skipped and logged. +- Tags first, `Artist/Album/Track` path fallback. +- Delta scan: unchanged file mtimes are skipped. +- Orphan cleanup writes song tombstones. +- The first start scans automatically when the songs table is empty. +- Manual scans come from `POST /api/v1/scan` or the UI. -The CI image job uses kaniko and keeps `DOCKER_CONFIG=/kaniko/.docker` for the -whole job. A multi-stage build replaces `/` with the last stage's root -filesystem, which deletes `$HOME/.docker/config.json`; without this setting -kaniko would push anonymously and Gitea would reject it with -`401 reqPackageAccess`. For the same reason the image job checks out the source -with plain `git` instead of a JavaScript action, whose post step would lose its -Node runtime after the build. +## Deployment -To build and push manually (or to deploy from a workstation): - -```bash -docker login gitea.tap-tap.win -scripts/release.sh # tag = git short SHA, pushes : and :latest -scripts/release.sh --tag v1.0.0 # explicit tag -scripts/release.sh --deploy # also apply the users secret and helm upgrade -``` - -### 9.2 Helm chart - -`charts/audiomanager` renders: - -- image repository/tag (defaults to `:latest` with `pullPolicy: Always`) and `imagePullSecrets` -- `library.folders` into a ConfigMap (`/etc/audiomanager/library.yaml`) -- `users.existingSecret` + key (Vault-managed; never put passwords in values) -- ingress host `subsonic.tap-tap.win`, ingress class, annotations and TLS secret; - cert-manager issues the certificate with the `letsencrypt-issuer` ClusterIssuer - by default -- `/data` PVC (size, storage class) -- `hostPath` mounts for music and long-form roots, both read-only -- resource requests/limits, non-root security context, probes on `/health` -- optional `nodeSelector`, `tolerations` and `affinity` - -The registry is private, so the cluster needs an image pull secret, and the users -secret must contain the Vault-managed file. `scripts/release.sh --deploy` creates -both from the local `~/.docker/config.json` and `config/users.yaml`, then runs -`helm upgrade --install`: - -```bash -docker login gitea.tap-tap.win -scripts/release.sh --tag latest --deploy -``` - -To deploy by hand: - -```bash -kubectl create namespace audiomanager - -kubectl -n audiomanager create secret generic audiomanager-users \ - --from-file=users.yaml=config/users.yaml - -kubectl -n audiomanager create secret generic audiomanager-registry \ - --type=kubernetes.io/dockerconfigjson \ - --from-file=.dockerconfigjson="$HOME/.docker/config.json" - -helm upgrade --install audiomanager charts/audiomanager \ - --namespace audiomanager \ - --set image.tag=latest \ - --set users.existingSecret=audiomanager-users \ - --set imagePullSecrets[0].name=audiomanager-registry -``` - -Pin a specific build with `--set image.tag=sha-`; CI publishes that tag for -every push to `main`. - -Adjust `library.folders`, `media.music.hostPath` and `media.longform.hostPath` for -the cluster. Every schedulable node must expose the same host paths; the chart -deliberately does not pin the pod to a node. The `/data` PVC must be writable by -UID 10001 (the chart sets `fsGroup: 10001`). - -The server exits at startup if a configured root path is missing or unreadable, so -the pod will not pass its readiness probe in that case. - -### 9.3 Chart repository - -The chart source lives in `charts/audiomanager` in this repository. CI packages -it and publishes the `.tgz` plus `index.yaml` to the public `TapTap/Charts` -repository: +Images and charts are published by Gitea Actions to `gitea.tap-tap.win`. ```text -https://gitea.tap-tap.win/TapTap/Charts/raw/branch/main +Image: gitea.tap-tap.win/taptap/audiomanager: +Chart: https://gitea.tap-tap.win/TapTap/Charts/raw/branch/main ``` -This is a classic Helm repository, so it supports both `helm repo add` and -Kustomize's `helmCharts` generator. The chart repository is public; the image -registry remains private. - -Versions published by CI: - -- `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: - -```bash -helm repo add taptap \ - https://gitea.tap-tap.win/TapTap/Charts/raw/branch/main -helm repo update -helm search repo taptap/audiomanager -``` - -Install a published chart: - -```bash -VERSION="0.1.4-sha." -helm upgrade --install audiomanager taptap/audiomanager \ - --version "$VERSION" \ - --namespace audiomanager \ - --set users.existingSecret=audiomanager-users \ - --set imagePullSecrets[0].name=audiomanager-registry -``` - -For Kustomize, use the same repository with `build --enable-helm`: +Kustomize example: ```yaml helmCharts: - name: audiomanager - releaseName: audiomanager - namespace: audiomanager repo: https://gitea.tap-tap.win/TapTap/Charts/raw/branch/main - version: 0.1.4-sha. + releaseName: audiomanager + version: 0.2.0-sha. + namespace: audiomanager valuesFile: values.yaml ``` -```bash -kustomize build --enable-helm deploy/overlays/prod | kubectl apply -f - -``` +The chart expects: -`kubectl apply -k` does not run the Helm inflator; render with `kustomize build ---enable-helm` (or `kubectl kustomize --enable-helm`) first. Kustomize's Helm -generator cannot authenticate, which is why `TapTap/Charts` is public. +- a `users.yaml` Secret (Vault-managed) referenced by `users.existingSecret`; +- a `library.yaml` ConfigMap; +- read-only hostPaths for music and long-form; +- a registry pull secret for the private image. -To publish from a workstation, either configure git credentials for -`TapTap/Charts` or pass a token explicitly: +Ingress host: `subsonic.tap-tap.win` (the historical name is kept, but the server no longer speaks the Subsonic protocol). ```bash -CHARTS_TOKEN= scripts/push-chart.sh -VERSION=0.2.0 CHARTS_TOKEN= scripts/push-chart.sh +kustomize build --enable-helm . | kubectl apply -f - +kubectl -n audiomanager rollout status deployment/audiomanager ``` -The CI job uses the `AUDIOMANAGER_CHARTS_TOKEN` repository secret. The script -clones the chart repository, adds the packaged chart, regenerates `index.yaml` -and pushes to `main`. +Flyway applies `V5__native_api.sql` automatically. Existing playlist-based moods are migrated to native moods; old playlists and user stars are dropped. -### 9.4 Operations +## Client -- Backups: documented manual copy of `DATA_DIR` (SQLite DB + covers) while the server is stopped, or via `sqlite3 .backup`. -- Logs to stdout (JSON optional), picked up by the cluster. -- Graceful shutdown: stop accepting requests, finish in-flight streams, close the DB pool. +The client lives in `TapTap/AudioManagerClient` and is built with Kotlin Multiplatform + Compose Multiplatform: ---- +- **Android**: Media3/ExoPlayer, background playback, offline downloads. +- **Desktop (JVM)**: shared Compose UI and a JVM audio backend. +- **Web (Wasm)**: the same Compose UI, HTML audio, tokenized stream URLs. -## 10. Testing +The shared module owns the API client, auth store, SQLDelight offline database, mood radio queue, and platform player abstractions. Downloads are original MP3s from `/stream?download=true`. Web is streaming-only (the browser owns its cache). -- No audio files are committed to the repository. A local script generates tiny silent MP3 fixtures (and `.lrc` files) under `build/test-media`; integration tests skip if fixtures are absent. -- Ktor integration tests (`ktor-server-test-host`): - - token and password auth, `enc:` decoding, wrong credentials -> code 40 - - deterministic IDs and normalization - - user visibility: user A cannot see or stream user B's music; both see long-form - - `Range` request -> `206 Partial Content` with exact bytes - - exact `size` / `duration` / `bitRate` / `suffix` / `contentType` fields - - browsing flow: `getArtists` -> `getArtist` -> `getAlbum` -> `stream` - - `search3` with Unicode and wildcards - - scrobble/star/rating/bookmark isolation between users - - playlist ownership and public visibility - - music directory browsing and server-side play queues - - transcoding: `maxBitRate` produces MP3, `timeOffset` seeks (skipped when `ffmpeg` is unavailable) - -### Compatibility smoke test - -`scripts/smoke.sh` generates a tagged MP3 with ffmpeg, starts the real server against a temporary library, and checks every endpoint a Subsonic client uses (browsing, feeds, search, stars, ratings, bookmarks, playlists, queues, stream with Range, download and covers). It prints PASS/FAIL per endpoint and exits non-zero on the first failure summary: +## Testing ```bash -nix-shell --run scripts/smoke.sh -# or, with ffmpeg/sqlite/curl installed: -scripts/smoke.sh +gradle test # unit + API integration tests +GRADLE=gradle scripts/smoke.sh # end-to-end server smoke test ``` -The work directory can be passed as the first argument; the server log is kept there for debugging. +The smoke test generates tagged MP3s, starts the server, and verifies login, sync, moods, radio, add-to-mood, streaming, transcoding, covers, scan and logout. ---- +## Roadmap -## 11. Implementation Order - -Verify each step with `./gradlew test` and/or `curl`: - -- [x] 1. **Setup & DB:** `build.gradle.kts`, `AppConfig.kt`, `LibraryConfig.kt`, `UsersConfig.kt`, `DatabaseFactory.kt` (WAL + Flyway), `Tables.kt`, `V1__init.sql`. -- [x] 2. **Scanner & covers:** `IdGenerator.kt`, `Mp3TagExtractor.kt`, `CoverArtService.kt`, `MediaScanner.kt` (delta + orphan cleanup + startup scan when empty). -- [x] 3. **Ktor core & auth:** `PartialContent`, content negotiation (`ignoreUnknownKeys`, `encodeDefaults`), `SubsonicAuth`, response wrapper, health endpoint. -- [x] 4. **Browsing & media:** system, browsing, genre and media routes (`stream`, `download`, `getCoverArt`). -- [x] 5. **Transcoding:** `FfmpegTranscoder.kt`, `maxBitRate`/`format`/`timeOffset`, extension declaration. -- [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. - ---- - -## 12. Open Items / Assumptions - -1. **Gitea registry path:** image is `gitea.tap-tap.win/taptap/audiomanager` (lowercased package owner `taptap`). -2. **Vault layout:** the chart expects a secret with a `users.yaml` key. Exact Vault path/agent template is deployment-side and not part of the app. -3. **Per-user music roots:** Vault/config must contain one folder entry per user root (e.g. `/mnt/media/music/`); there is no implicit path convention. -4. **hostPath without pinning:** requires `/mnt/media/music` and `/mnt/media/longform` to exist on every node that can schedule the pod. Add a `nodeSelector` later if that changes. -5. **Long-form modelling:** audiobooks/podcasts are albums/tracks in long-form folders; no RSS ingestion or chapter model. -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). +- [x] MP3 scanner, covers, deterministic IDs, SQLite + Flyway. +- [x] Native bearer-auth API, sync deltas, tombstones. +- [x] Mood CRUD, seeds, server-driven radio, playback events, add-to-mood. +- [x] Built-in management UI on the native API. +- [x] Kotlin Multiplatform client foundation (Android, desktop, web). +- [ ] Offline downloads and offline playback across clients. +- [ ] YT Music discovery through `yt-dlp`, recommendation list, accept/reject. +- [ ] Optional downloader that writes accepted tracks into an import folder and rescans. +- [ ] Home-screen widgets, Android Auto, and richer radio tuning. diff --git a/charts/audiomanager/Chart.yaml b/charts/audiomanager/Chart.yaml index 34276fd..bafa47b 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.4 +version: 0.2.0 appVersion: "0.1.0" diff --git a/scripts/smoke.sh b/scripts/smoke.sh index 09894e4..ce78ffb 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -1,9 +1,11 @@ #!/usr/bin/env bash # -# End-to-end smoke test: generates a tiny tagged MP3 library, starts the server -# against it, and exercises the endpoints a Subsonic client uses. +# End-to-end smoke test for the native mood-first API. # -# Requirements: ffmpeg, sqlite3, curl, md5sum, java (or use nix-shell). +# Generates a tiny tagged MP3 library, starts the server against it, and +# exercises auth, sync, moods, radio sessions, add-to-mood and streaming. +# +# Requirements: ffmpeg, sqlite3, curl, python3, java. # Usage: scripts/smoke.sh [work-dir] # set -euo pipefail @@ -15,9 +17,9 @@ PORT="${SMOKE_PORT:-18099}" USER="smoke" PASS="smoke-pass" BASE="http://127.0.0.1:${PORT}" -SALT="smoke-salt" -TOKEN="$(printf '%s%s' "$PASS" "$SALT" | md5sum | cut -d' ' -f1)" -AUTH="u=${USER}&t=${TOKEN}&s=${SALT}&v=1.16.1&c=smoke&f=json" +TOKEN="" +HTTP_STATUS="" +HTTP_BODY="" PASSED=0 FAILED=0 @@ -26,20 +28,30 @@ log() { printf '%s\n' "$*"; } pass() { PASSED=$((PASSED + 1)); log "PASS $1"; } fail() { FAILED=$((FAILED + 1)); log "FAIL $1: $2"; } -mkdir -p "$WORK/music/Smoke Artist/Smoke Album" "$WORK/longform" "$WORK/data" +json_field() { python3 -c 'import json,sys;d=json.load(sys.stdin);print(eval("d"+sys.argv[1]))' "$1"; } + +mkdir -p "$WORK/music/Smoke Artist/Smoke Album" "$WORK/music/Second Artist/Second Album" \ + "$WORK/longform/Long Narrator/Long Book" "$WORK/data" log "Generated test library in $WORK" ffmpeg -hide_banner -loglevel error -y \ -f lavfi -i "sine=frequency=440:duration=2" \ - -metadata title="Smoke Song" \ - -metadata artist="Smoke Artist" \ - -metadata album="Smoke Album" \ - -metadata album_artist="Smoke Artist" \ - -metadata genre="Rock" \ - -metadata track="1" \ - -metadata date="2026" \ + -metadata title="Smoke Song" -metadata artist="Smoke Artist" \ + -metadata album="Smoke Album" -metadata album_artist="Smoke Artist" \ + -metadata genre="Rock" -metadata track="1" -metadata date="2026" \ -b:a 192k "$WORK/music/Smoke Artist/Smoke Album/01 - Smoke Song.mp3" - +ffmpeg -hide_banner -loglevel error -y \ + -f lavfi -i "sine=frequency=550:duration=2" \ + -metadata title="Second Song" -metadata artist="Second Artist" \ + -metadata album="Second Album" -metadata album_artist="Second Artist" \ + -metadata genre="Ambient" -metadata track="1" -metadata date="2026" \ + -b:a 192k "$WORK/music/Second Artist/Second Album/01 - Second Song.mp3" +ffmpeg -hide_banner -loglevel error -y \ + -f lavfi -i "sine=frequency=660:duration=2" \ + -metadata title="Chapter One" -metadata artist="Long Narrator" \ + -metadata album="Long Book" -metadata album_artist="Long Narrator" \ + -metadata genre="Audiobook" -metadata track="1" -metadata date="2026" \ + -b:a 128k "$WORK/longform/Long Narrator/Long Book/01 - Chapter One.mp3" ffmpeg -hide_banner -loglevel error -y \ -f lavfi -i "color=c=red:s=64x64" -frames:v 1 \ "$WORK/music/Smoke Artist/Smoke Album/cover.jpg" @@ -80,182 +92,178 @@ SERVER_PID=$! trap 'kill $SERVER_PID 2>/dev/null || true' EXIT log "Waiting for the server and initial scan..." +SONGS=0 for _ in $(seq 1 120); do if curl -sf "$BASE/health" >/dev/null 2>&1; then SONGS="$(sqlite3 "$WORK/data/musicmanager.db" 'select count(*) from songs' 2>/dev/null || echo 0)" - [[ "$SONGS" -gt 0 ]] && break + [[ "$SONGS" -ge 3 ]] && break fi sleep 1 done -if [[ "${SONGS:-0}" -eq 0 ]]; then +if [[ "${SONGS:-0}" -lt 3 ]]; then log "Server did not scan the test library; see $WORK/server.log" tail -20 "$WORK/server.log" || true exit 1 fi -ALBUM_ID="$(sqlite3 "$WORK/data/musicmanager.db" 'select id from albums limit 1')" -ARTIST_ID="$(sqlite3 "$WORK/data/musicmanager.db" 'select id from artists limit 1')" -SONG_ID="$(sqlite3 "$WORK/data/musicmanager.db" 'select id from songs limit 1')" -log "Scanned: artist=$ARTIST_ID album=$ALBUM_ID song=$SONG_ID" +SONG_ID="$(sqlite3 "$WORK/data/musicmanager.db" "select id from songs where title='Smoke Song'")" +SONG2_ID="$(sqlite3 "$WORK/data/musicmanager.db" "select id from songs where title='Second Song'")" +LONG_ID="$(sqlite3 "$WORK/data/musicmanager.db" "select id from songs where title='Chapter One'")" +ALBUM_ID="$(sqlite3 "$WORK/data/musicmanager.db" "select album_id from songs where id='$SONG_ID'")" +log "Scanned: song=$SONG_ID second=$SONG2_ID longform=$LONG_ID" -# check [expected-status] -check() { - local name="$1" path="$2" expected="${3:-200}" body status - body="$(curl -s -w '\n%{http_code}' "$BASE$path")" - status="$(printf '%s' "$body" | tail -1)" - body="$(printf '%s' "$body" | sed '$d')" - - if [[ "$status" != "$expected" ]]; then - fail "$name" "HTTP $status (expected $expected): $(printf '%s' "$body" | head -c 200)" - return +# api [json-body] [token-override] +api() { + local method="$1" path="$2" body="${3:-}" auth="${4:-$TOKEN}" + local args=(-s -w '\n%{http_code}' -X "$method" "$BASE/api/v1$path") + [[ -n "$auth" ]] && args+=(-H "Authorization: Bearer $auth") + if [[ -n "$body" ]]; then + args+=(-H 'Content-Type: application/json' -d "$body") fi - if [[ "$expected" == "200" ]] && ! printf '%s' "$body" | grep -q '"status":"ok"'; then - fail "$name" "$(printf '%s' "$body" | head -c 200)" - return - fi - pass "$name" + local out + out="$(curl "${args[@]}")" + HTTP_STATUS="$(printf '%s' "$out" | tail -1)" + HTTP_BODY="$(printf '%s' "$out" | sed '$d')" } -# check_post -check_post() { - local name="$1" path="$2" extra="${3:-}" body status - body="$(curl -s -w '\n%{http_code}' -X POST \ - -H 'Content-Type: application/x-www-form-urlencoded' \ - --data "${AUTH}${extra}" "$BASE$path")" - status="$(printf '%s' "$body" | tail -1)" - body="$(printf '%s' "$body" | sed '$d')" - - if [[ "$status" != "200" ]]; then - fail "$name (POST)" "HTTP $status: $(printf '%s' "$body" | head -c 200)" - return +expect() { + local name="$1" expected="$2" method="$3" path="$4" body="${5:-}" + api "$method" "$path" "$body" + if [[ "$HTTP_STATUS" == "$expected" ]]; then + pass "$name" + else + fail "$name" "HTTP $HTTP_STATUS (expected $expected): ${HTTP_BODY:0:240}" fi - if ! printf '%s' "$body" | grep -q '"status":"ok"'; then - fail "$name (POST)" "$(printf '%s' "$body" | head -c 200)" - return - fi - pass "$name (POST)" } -check "ping" "/rest/ping.view?$AUTH" -check "getLicense" "/rest/getLicense.view?$AUTH" -check "getOpenSubsonicExtensions" "/rest/getOpenSubsonicExtensions.view?$AUTH" -check "getMusicFolders" "/rest/getMusicFolders.view?$AUTH" -check "getIndexes" "/rest/getIndexes.view?$AUTH" -check "getArtists" "/rest/getArtists.view?$AUTH" -check "getArtist" "/rest/getArtist.view?$AUTH&id=$ARTIST_ID" -check "getAlbum" "/rest/getAlbum.view?$AUTH&id=$ALBUM_ID" -check "getSong" "/rest/getSong.view?$AUTH&id=$SONG_ID" -check "search3" "/rest/search3.view?$AUTH&query=smoke" -check "getAlbumList2" "/rest/getAlbumList2.view?$AUTH&type=alphabeticalByName&size=10" -check "getAlbumList" "/rest/getAlbumList.view?$AUTH&type=newest&size=10" -check "getRandomSongs" "/rest/getRandomSongs.view?$AUTH&size=10" -check "getGenres" "/rest/getGenres.view?$AUTH" -check "getSongsByGenre" "/rest/getSongsByGenre.view?$AUTH&genre=Rock" -check "getMusicDirectory (folder)" "/rest/getMusicDirectory.view?$AUTH&id=1" -check "getMusicDirectory (album)" "/rest/getMusicDirectory.view?$AUTH&id=$ALBUM_ID" -check "getUser" "/rest/getUser.view?$AUTH&username=$USER" -check "getUsers" "/rest/getUsers.view?$AUTH" -check "getScanStatus" "/rest/getScanStatus.view?$AUTH" -check "getStarred2" "/rest/getStarred2.view?$AUTH" -check "getLyricsBySongId" "/rest/getLyricsBySongId.view?$AUTH&id=$SONG_ID" -check "getArtistInfo2" "/rest/getArtistInfo2.view?$AUTH&id=$ARTIST_ID" -check "getAlbumInfo2" "/rest/getAlbumInfo2.view?$AUTH&id=$ALBUM_ID" -check "getSimilarSongs2" "/rest/getSimilarSongs2.view?$AUTH&id=$ARTIST_ID" -check "getTopSongs" "/rest/getTopSongs.view?$AUTH&artist=Smoke%20Artist" -check "getInternetRadioStations" "/rest/getInternetRadioStations.view?$AUTH" -check "jukeboxControl" "/rest/jukeboxControl.view?$AUTH&action=status" +expect_eq() { + local name="$1" expected="$2" actual="$3" + if [[ "$actual" == "$expected" ]]; then + pass "$name" + else + fail "$name" "expected '$expected', got '$actual'" + fi +} -# The formPost extension means clients may use POST for every endpoint. -check_post "ping" "/rest/ping.view" -check_post "getAlbumList2" "/rest/getAlbumList2.view" "&type=alphabeticalByName&size=10" -check_post "getGenres" "/rest/getGenres.view" -check_post "getPlaylists" "/rest/getPlaylists.view" -check_post "getUser" "/rest/getUser.view" "&username=$USER" +log "" +log "Authentication" +LOGIN_STATUS="$(curl -s -o "$WORK/login.json" -w '%{http_code}' -X POST \ + -H 'Content-Type: application/json' \ + -d "{\"username\":\"$USER\",\"password\":\"$PASS\",\"deviceName\":\"smoke\",\"platform\":\"cli\"}" \ + "$BASE/api/v1/auth/login")" +expect_eq "login status" "200" "$LOGIN_STATUS" +TOKEN="$(json_field '["token"]' < "$WORK/login.json" 2>/dev/null || true)" +if [[ -n "$TOKEN" ]]; then pass "login token"; else fail "login token" "$(head -c 200 "$WORK/login.json")"; fi +expect_eq "login user" "$USER" "$(json_field '["user"]["name"]' < "$WORK/login.json" 2>/dev/null || true)" -check "scrobble" "/rest/scrobble.view?$AUTH&id=$SONG_ID" -check "star" "/rest/star.view?$AUTH&id=$SONG_ID&albumId=$ALBUM_ID&artistId=$ARTIST_ID" -check "getStarred2 after star" "/rest/getStarred2.view?$AUTH" -check "setRating" "/rest/setRating.view?$AUTH&id=$SONG_ID&rating=4" -check "unstar" "/rest/unstar.view?$AUTH&id=$SONG_ID&albumId=$ALBUM_ID&artistId=$ARTIST_ID" -check "createBookmark" "/rest/createBookmark.view?$AUTH&id=$SONG_ID&position=1000" -check "getBookmarks" "/rest/getBookmarks.view?$AUTH" -check "deleteBookmark" "/rest/deleteBookmark.view?$AUTH&id=$SONG_ID" +BAD_STATUS="$(curl -s -o /dev/null -w '%{http_code}' -X POST \ + -H 'Content-Type: application/json' -d '{"username":"smoke","password":"wrong"}' \ + "$BASE/api/v1/auth/login")" +expect_eq "login rejects bad password" "401" "$BAD_STATUS" +UNAUTH_STATUS="$(curl -s -o /dev/null -w '%{http_code}' "$BASE/api/v1/moods")" +expect_eq "unauthenticated request rejected" "401" "$UNAUTH_STATUS" -PLAYLIST_JSON="$(curl -s "$BASE/rest/createPlaylist.view?$AUTH&name=Smoke%20List&songId=$SONG_ID")" -PLAYLIST_ID="$(printf '%s' "$PLAYLIST_JSON" | python3 -c 'import json,sys; print(json.load(sys.stdin)["subsonic-response"]["playlist"]["id"])' 2>/dev/null || true)" -if [[ -z "$PLAYLIST_ID" ]]; then - fail "createPlaylist" "$(printf '%s' "$PLAYLIST_JSON" | head -c 300)" -else - pass "createPlaylist" - check "getPlaylists" "/rest/getPlaylists.view?$AUTH" - check "getPlaylist" "/rest/getPlaylist.view?$AUTH&id=$PLAYLIST_ID" - check "updatePlaylist" "/rest/updatePlaylist.view?$AUTH&playlistId=$PLAYLIST_ID&songIndexToRemove=0" - check "deletePlaylist" "/rest/deletePlaylist.view?$AUTH&id=$PLAYLIST_ID" -fi +expect "me" "200" "GET" "/me" +expect_eq "me name" "$USER" "$(printf '%s' "$HTTP_BODY" | json_field '["name"]')" -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 +log "" +log "Library sync" +expect "library snapshot (music)" "200" "GET" "/library/songs?scope=music" +MUSIC_COUNT="$(printf '%s' "$HTTP_BODY" | json_field '["songs"].__len__()' 2>/dev/null || echo 0)" +expect_eq "music snapshot has 2 songs" "2" "$MUSIC_COUNT" +expect_eq "snapshot contains smoke song" "1" "$(printf '%s' "$HTTP_BODY" | python3 -c 'import json,sys;print(sum(1 for s in json.load(sys.stdin)["songs"] if s["id"]=="'"$SONG_ID"'"))')" -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" -check "getPlayQueueByIndex" "/rest/getPlayQueueByIndex.view?$AUTH" +expect "library snapshot (longform)" "200" "GET" "/library/songs?scope=longform" +expect_eq "longform snapshot has 1 song" "1" "$(printf '%s' "$HTTP_BODY" | json_field '["songs"].__len__()')" +expect "search" "200" "GET" "/library/search?q=smoke&scope=music" +expect_eq "search finds one song" "1" "$(printf '%s' "$HTTP_BODY" | json_field '["songs"].__len__()')" -STREAM_STATUS="$(curl -s -o "$WORK/stream.mp3" -w '%{http_code}' "$BASE/rest/stream.view?$AUTH&id=$SONG_ID")" +log "" +log "Moods" +expect "create mood" "201" "POST" "/moods" \ + "{\"name\":\"Smoke Mood\",\"genres\":[\"Rock\"],\"targetSize\":10,\"seedSongIds\":[\"$SONG_ID\"]}" +MOOD_ID="$(printf '%s' "$HTTP_BODY" | json_field '["mood"]["id"]' 2>/dev/null || true)" +if [[ -n "$MOOD_ID" ]]; then pass "mood id"; else fail "mood id" "${HTTP_BODY:0:200}"; fi +expect_eq "mood seed count" "1" "$(printf '%s' "$HTTP_BODY" | json_field '["mood"]["seedCount"]')" +expect "list moods" "200" "GET" "/moods" +expect_eq "list contains mood" "1" "$(printf '%s' "$HTTP_BODY" | python3 -c 'import json,sys;print(sum(1 for m in json.load(sys.stdin)["moods"] if m["id"]=="'"$MOOD_ID"'"))')" +expect "get mood" "200" "GET" "/moods/$MOOD_ID" +expect "mood preview" "200" "GET" "/moods/$MOOD_ID/preview?limit=10" +expect_eq "preview is not empty" "yes" "$(printf '%s' "$HTTP_BODY" | python3 -c 'import json,sys;print("yes" if json.load(sys.stdin)["songs"] else "no")')" +expect "add seed" "200" "POST" "/moods/$MOOD_ID/seeds" "{\"songId\":\"$SONG2_ID\"}" +expect_eq "seed count after add" "2" "$(printf '%s' "$HTTP_BODY" | json_field '["mood"]["seedCount"]')" +expect "remove seed" "204" "DELETE" "/moods/$MOOD_ID/seeds/$SONG2_ID" +expect "get mood after seed removal" "200" "GET" "/moods/$MOOD_ID" +expect_eq "seed count after remove" "1" "$(printf '%s' "$HTTP_BODY" | json_field '["mood"]["seedCount"]')" + +log "" +log "Radio sessions" +expect "start session" "201" "POST" "/moods/$MOOD_ID/sessions" '{"limit":10}' +SESSION_ID="$(printf '%s' "$HTTP_BODY" | json_field '["id"]' 2>/dev/null || true)" +if [[ -n "$SESSION_ID" ]]; then pass "session id"; else fail "session id" "${HTTP_BODY:0:200}"; fi +expect_eq "queue contains seed" "yes" "$(printf '%s' "$HTTP_BODY" | python3 -c 'import json,sys;print("yes" if any(s["id"]=="'"$SONG_ID"'" for s in json.load(sys.stdin)["queue"]) else "no")')" +expect_eq "queue excludes longform" "yes" "$(printf '%s' "$HTTP_BODY" | python3 -c 'import json,sys;print("yes" if all(s["id"]!="'"$LONG_ID"'" for s in json.load(sys.stdin)["queue"]) else "no")')" +expect "next tracks" "200" "POST" "/sessions/$SESSION_ID/next" '{"limit":10}' +expect "playback event" "200" "POST" "/sessions/$SESSION_ID/events" \ + "{\"events\":[{\"songId\":\"$SONG_ID\",\"type\":\"completed\",\"positionSeconds\":2}]}" +expect_eq "accepted events" "1" "$(printf '%s' "$HTTP_BODY" | json_field '["accepted"]')" +expect "add playing track to current mood" "200" "POST" "/sessions/$SESSION_ID/add-to-mood" \ + "{\"songId\":\"$SONG2_ID\"}" +expect_eq "seed count after add-to-mood" "2" "$(printf '%s' "$HTTP_BODY" | json_field '["mood"]["seedCount"]')" +expect "resume session" "200" "GET" "/sessions/$SESSION_ID" +expect_eq "session mood" "$MOOD_ID" "$(printf '%s' "$HTTP_BODY" | json_field '["moodId"]')" +expect "close session" "204" "DELETE" "/sessions/$SESSION_ID" + +log "" +log "Media" +STREAM_STATUS="$(curl -s -o "$WORK/stream.mp3" -w '%{http_code}' \ + "$BASE/api/v1/songs/$SONG_ID/stream?token=$TOKEN")" if [[ "$STREAM_STATUS" == "200" && -s "$WORK/stream.mp3" ]]; then - pass "stream" + pass "stream with query token" else - fail "stream" "HTTP $STREAM_STATUS, $(wc -c < "$WORK/stream.mp3" 2>/dev/null || echo 0) bytes" + fail "stream with query token" "HTTP $STREAM_STATUS" fi -RANGE_STATUS="$(curl -s -o /dev/null -w '%{http_code}' -H 'Range: bytes=0-9' "$BASE/rest/stream.view?$AUTH&id=$SONG_ID")" -if [[ "$RANGE_STATUS" == "206" ]]; then pass "stream range"; else fail "stream range" "HTTP $RANGE_STATUS"; fi +RANGE_STATUS="$(curl -s -o /dev/null -w '%{http_code}' -H 'Range: bytes=0-9' \ + "$BASE/api/v1/songs/$SONG_ID/stream?token=$TOKEN")" +expect_eq "stream range" "206" "$RANGE_STATUS" -TRANSCODE_STATUS="$(curl -s -D "$WORK/transcode.headers" -o "$WORK/transcoded.mp3" -w '%{http_code}' "$BASE/rest/stream.view?$AUTH&id=$SONG_ID&maxBitRate=64")" +TRANSCODE_STATUS="$(curl -s -D "$WORK/transcode.headers" -o "$WORK/transcoded.mp3" -w '%{http_code}' \ + "$BASE/api/v1/songs/$SONG_ID/stream?token=$TOKEN&maxBitRate=64")" if [[ "$TRANSCODE_STATUS" == "200" && -s "$WORK/transcoded.mp3" ]] \ - && grep -qi '^content-type: audio/mpeg' "$WORK/transcode.headers" \ - && [[ $(wc -c < "$WORK/transcoded.mp3") -lt $(wc -c < "$WORK/stream.mp3") ]]; then - pass "stream transcode (maxBitRate)" + && grep -qi '^content-type: audio/mpeg' "$WORK/transcode.headers"; then + pass "stream transcode" else - fail "stream transcode (maxBitRate)" "HTTP $TRANSCODE_STATUS, $(wc -c < "$WORK/transcoded.mp3" 2>/dev/null || echo 0) bytes" + fail "stream transcode" "HTTP $TRANSCODE_STATUS" fi -OFFSET_STATUS="$(curl -s -o "$WORK/offset.mp3" -w '%{http_code}' "$BASE/rest/stream.view?$AUTH&id=$SONG_ID&timeOffset=1")" -if [[ "$OFFSET_STATUS" == "200" && -s "$WORK/offset.mp3" ]] \ - && [[ $(wc -c < "$WORK/offset.mp3") -lt $(wc -c < "$WORK/stream.mp3") ]]; then - pass "stream transcode (timeOffset)" +DOWNLOAD_STATUS="$(curl -s -o "$WORK/download.mp3" -w '%{http_code}' \ + "$BASE/api/v1/songs/$SONG_ID/stream?token=$TOKEN&download=true")" +if [[ "$DOWNLOAD_STATUS" == "200" && -s "$WORK/download.mp3" ]]; then + pass "download original" else - fail "stream transcode (timeOffset)" "HTTP $OFFSET_STATUS" + fail "download original" "HTTP $DOWNLOAD_STATUS" fi -FORMAT_STATUS="$(curl -s -o "$WORK/format.mp3" -w '%{http_code}' "$BASE/rest/stream.view?$AUTH&id=$SONG_ID&format=flac")" -if [[ "$FORMAT_STATUS" == "200" && -s "$WORK/format.mp3" ]]; then - pass "stream transcode (format fallback)" -else - fail "stream transcode (format fallback)" "HTTP $FORMAT_STATUS" -fi - -DOWNLOAD_STATUS="$(curl -s -o /dev/null -w '%{http_code}' "$BASE/rest/download.view?$AUTH&id=$SONG_ID")" -if [[ "$DOWNLOAD_STATUS" == "200" ]]; then pass "download"; else fail "download" "HTTP $DOWNLOAD_STATUS"; fi - -COVER_STATUS="$(curl -s -o "$WORK/cover.jpg" -w '%{http_code}' "$BASE/rest/getCoverArt.view?$AUTH&id=$ALBUM_ID&size=32")" +COVER_STATUS="$(curl -s -o "$WORK/cover.jpg" -w '%{http_code}' \ + "$BASE/api/v1/covers/$ALBUM_ID?size=32&token=$TOKEN")" if [[ "$COVER_STATUS" == "200" && -s "$WORK/cover.jpg" ]]; then - pass "getCoverArt" + pass "cover art" else - fail "getCoverArt" "HTTP $COVER_STATUS" + fail "cover art" "HTTP $COVER_STATUS" fi +expect "scan status" "200" "GET" "/scan" +expect "start scan" "202" "POST" "/scan" + +log "" +log "Cleanup" +expect "delete mood" "204" "DELETE" "/moods/$MOOD_ID" +expect "logout" "204" "POST" "/auth/logout" +api "GET" "/me" "" "$TOKEN" +expect_eq "token revoked after logout" "401" "$HTTP_STATUS" + log "" log "Smoke test finished: $PASSED passed, $FAILED failed" log "Server log: $WORK/server.log" diff --git a/src/main/kotlin/win/taptap/musicmanager/Application.kt b/src/main/kotlin/win/taptap/musicmanager/Application.kt index dc1a51e..0d1e2d8 100644 --- a/src/main/kotlin/win/taptap/musicmanager/Application.kt +++ b/src/main/kotlin/win/taptap/musicmanager/Application.kt @@ -12,6 +12,7 @@ import io.ktor.server.plugins.contentnegotiation.ContentNegotiation import io.ktor.server.plugins.partialcontent.PartialContent import io.ktor.server.plugins.statuspages.StatusPages import io.ktor.server.request.path +import io.ktor.server.response.respond import io.ktor.server.response.respondRedirect import io.ktor.server.response.respondText import io.ktor.server.routing.get @@ -27,15 +28,16 @@ import org.slf4j.LoggerFactory import win.taptap.musicmanager.config.AppConfig import win.taptap.musicmanager.config.LibraryConfig import win.taptap.musicmanager.config.UsersConfig +import win.taptap.musicmanager.api.ApiErrorBody +import win.taptap.musicmanager.api.ApiError +import win.taptap.musicmanager.api.ApiException +import win.taptap.musicmanager.api.apiRoutes 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.radio.RadioService import win.taptap.musicmanager.scanner.CoverArtService import win.taptap.musicmanager.scanner.MediaScanner -import win.taptap.musicmanager.subsonic.respondSubsonicError -import win.taptap.musicmanager.subsonic.routes.subsonicRoutes import win.taptap.musicmanager.transcoding.FfmpegTranscoder private val log = LoggerFactory.getLogger("win.taptap.musicmanager.Application") @@ -53,11 +55,10 @@ fun main() { val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) val coverArtService = CoverArtService(config.dataDir) val transcoder = FfmpegTranscoder(config.ffmpegPath) - val moodService = MoodService(applicationScope) + val radioService = RadioService() val scanner = MediaScanner( library = library, coverArtService = coverArtService, - onScanFinished = { MoodRepository.markAllStale() }, ) if (MediaRepository.countSongs() == 0L) { log.info("Song table is empty, starting initial library scan") @@ -84,10 +85,26 @@ fun main() { install(AutoHeadResponse) install(CallLogging) install(StatusPages) { + exception { call, cause -> + call.respond( + cause.status, + ApiErrorBody( + ApiError(cause.code, cause.message), + ), + ) + } exception { call, cause -> log.error("Unhandled exception for ${call.request.path()}", cause) - if (call.request.path().startsWith("/rest/")) { - call.respondSubsonicError(0, "Internal server error") + if (call.request.path().startsWith("/api/")) { + call.respond( + HttpStatusCode.InternalServerError, + ApiErrorBody( + ApiError( + "internal", + "Internal server error", + ), + ), + ) } else { call.respondText("Internal server error", status = HttpStatusCode.InternalServerError) } @@ -100,12 +117,12 @@ fun main() { get("/") { call.respondRedirect("/ui") } get("/ui") { call.respondText(webUiHtml, ContentType.Text.Html) } } - subsonicRoutes( + apiRoutes( users = users, library = library, coverArtService = coverArtService, transcoder = transcoder, - moodService = moodService, + radioService = radioService, startScan = { scanner.start(applicationScope) }, scanStatus = { scanner.status() }, ) diff --git a/src/main/kotlin/win/taptap/musicmanager/api/ApiModels.kt b/src/main/kotlin/win/taptap/musicmanager/api/ApiModels.kt new file mode 100644 index 0000000..05fc7d8 --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/api/ApiModels.kt @@ -0,0 +1,240 @@ +package win.taptap.musicmanager.api + +import kotlinx.serialization.Serializable +import win.taptap.musicmanager.db.MoodRecord +import win.taptap.musicmanager.db.MoodSeedRecord +import win.taptap.musicmanager.db.SongRecord + +@Serializable +data class ApiErrorBody(val error: ApiError) + +@Serializable +data class ApiError(val code: String, val message: String) + +@Serializable +data class LoginRequest( + val username: String, + val password: String, + val deviceName: String = "Unknown device", + val platform: String = "unknown", +) + +@Serializable +data class UserDto( + val name: String, + val admin: Boolean, + val musicFolders: List, + val longformFolders: List, +) + +@Serializable +data class LoginResponse( + val token: String, + val expiresAt: String, + val user: UserDto, +) + +@Serializable +data class DeviceDto( + val id: String, + val deviceName: String, + val platform: String, + val createdAt: String, + val lastUsedAt: String, + val expiresAt: String, + val current: Boolean, +) + +@Serializable +data class SongDto( + val id: String, + val title: String, + val artist: String, + val album: String, + val albumId: String, + val trackNumber: Int? = null, + val discNumber: Int = 1, + val year: Int? = null, + val duration: Int, + val bitRate: Int, + val size: Long, + val suffix: String, + val genres: List = emptyList(), + val folderId: Int, + val relativePath: String, + val updatedAt: String, +) + +fun SongRecord.toDto(): SongDto = SongDto( + id = id, + title = title, + artist = displayArtist, + album = albumName, + albumId = albumId, + trackNumber = trackNumber, + discNumber = discNumber, + year = year, + duration = duration, + bitRate = bitRate, + size = size, + suffix = suffix, + genres = genres, + folderId = folderId, + relativePath = relativePath, + updatedAt = updatedAt, +) + +@Serializable +data class SeedDto( + val song: SongDto, + val origin: String, + val addedAt: String, +) + +@Serializable +data class MoodDto( + val id: String, + val name: String, + val description: String? = null, + val query: String? = null, + val genres: List = emptyList(), + val targetSize: Int, + val refreshHours: Int, + val ytEnabled: Boolean, + val lastDiscoveryAt: String? = null, + val createdAt: String, + val changedAt: String, + val lastError: String? = null, + val seedCount: Int, + val newRecommendations: Int, +) + +fun MoodRecord.toDto(): MoodDto = MoodDto( + id = id, + name = name, + description = description, + query = query, + genres = genres, + targetSize = targetSize, + refreshHours = refreshHours, + ytEnabled = ytEnabled, + lastDiscoveryAt = lastDiscoveryAt, + createdAt = createdAt, + changedAt = changedAt, + lastError = lastError, + seedCount = seedCount, + newRecommendations = newRecommendations, +) + +@Serializable +data class MoodDetailDto( + val mood: MoodDto, + val seeds: List, + val recommendations: List = emptyList(), +) + +@Serializable +data class CreateMoodRequest( + val name: String, + val description: String? = null, + val query: String? = null, + val genres: List = emptyList(), + val targetSize: Int = 30, + val refreshHours: Int = 24, + val ytEnabled: Boolean = true, + val seedSongIds: List = emptyList(), +) + +@Serializable +data class UpdateMoodRequest( + val name: String? = null, + val description: String? = null, + val clearDescription: Boolean = false, + val query: String? = null, + val clearQuery: Boolean = false, + val genres: List? = null, + val targetSize: Int? = null, + val refreshHours: Int? = null, + val ytEnabled: Boolean? = null, +) + +@Serializable +data class AddSeedRequest(val songId: String, val origin: String = "manual") + +@Serializable +data class AddToMoodRequest(val songId: String, val moodId: String? = null) + +@Serializable +data class AddToMoodResponse( + val mood: MoodDto, + val added: Boolean, +) + +@Serializable +data class LibraryPage( + val songs: List, + val deletedSongIds: List = emptyList(), + val revision: String, + val nextCursor: String? = null, + val nextSince: String? = null, +) + +@Serializable +data class SearchResponse(val songs: List) + +@Serializable +data class StartSessionRequest(val limit: Int? = null) + +@Serializable +data class NextTracksRequest( + val limit: Int? = null, + val excludeSongIds: List = emptyList(), +) + +@Serializable +data class SessionDto( + val id: String, + val moodId: String, + val moodName: String, + val startedAt: String, + val closedAt: String? = null, + val queue: List = emptyList(), +) + +@Serializable +data class PlaybackEvent( + val songId: String, + val type: String, + val positionSeconds: Int? = null, +) + +@Serializable +data class PlaybackEventsRequest(val events: List) + +@Serializable +data class PlaybackEventsResponse(val accepted: Int) + +@Serializable +data class ScanStatusDto( + val scanning: Boolean, + val count: Long, + val error: String? = null, +) + +@Serializable +data class RecommendationDto( + val videoId: String, + val title: String, + val artist: String, + val album: String? = null, + val duration: Int? = null, + val thumbnail: String? = null, + val state: String, + val matchedSong: SongDto? = null, + val timesAdded: Int, + val firstSeen: String, + val lastSeen: String, +) + +fun seedDto(seed: MoodSeedRecord, song: SongRecord): SeedDto = + SeedDto(song = song.toDto(), origin = seed.origin, addedAt = seed.addedAt) diff --git a/src/main/kotlin/win/taptap/musicmanager/api/ApiRoutes.kt b/src/main/kotlin/win/taptap/musicmanager/api/ApiRoutes.kt new file mode 100644 index 0000000..9484336 --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/api/ApiRoutes.kt @@ -0,0 +1,137 @@ +package win.taptap.musicmanager.api + +import io.ktor.http.HttpStatusCode +import io.ktor.server.response.respond +import io.ktor.server.routing.Route +import io.ktor.server.routing.delete +import io.ktor.server.routing.get +import io.ktor.server.routing.post +import io.ktor.server.routing.route +import java.security.MessageDigest +import win.taptap.musicmanager.api.DeviceDto +import win.taptap.musicmanager.api.LoginRequest +import win.taptap.musicmanager.api.LoginResponse +import win.taptap.musicmanager.api.ScanStatusDto +import win.taptap.musicmanager.api.UserDto +import win.taptap.musicmanager.config.LibraryConfig +import win.taptap.musicmanager.config.UsersConfig +import win.taptap.musicmanager.db.ApiTokenRepository +import win.taptap.musicmanager.radio.RadioService +import win.taptap.musicmanager.scanner.CoverArtService +import win.taptap.musicmanager.scanner.ScanStatus +import win.taptap.musicmanager.transcoding.FfmpegTranscoder + +/** + * Routing for the native API. + * + * Every handler resolves the bearer token explicitly. Media URLs may also carry + * `?token=` because HTML audio and `` tags cannot set headers. + */ +fun Route.apiRoutes( + users: UsersConfig, + library: LibraryConfig, + coverArtService: CoverArtService, + transcoder: FfmpegTranscoder, + radioService: RadioService, + startScan: () -> Boolean, + scanStatus: () -> ScanStatus, +) { + route("/api/v1") { + post("/auth/login") { + val request = call.receiveJson() + val user = users.byName(request.username.trim()) + ?: throw ApiException( + HttpStatusCode.Unauthorized, + "invalid_credentials", + "Wrong username or password", + ) + if (!constantTimeEquals(request.password, user.password)) { + throw ApiException( + HttpStatusCode.Unauthorized, + "invalid_credentials", + "Wrong username or password", + ) + } + + val issued = ApiTokenRepository.create( + userName = user.name, + deviceName = request.deviceName.ifBlank { "Unknown device" }, + platform = request.platform.ifBlank { "unknown" }, + ) + call.respond( + HttpStatusCode.OK, + LoginResponse( + token = issued.raw, + expiresAt = issued.record.expiresAt, + user = user.toDto(library), + ), + ) + } + + get("/me") { + val user = call.requireApiUser(users) + call.respond(UserDto( + name = user.name, + admin = user.admin, + musicFolders = user.musicFolderIds(library).sorted(), + longformFolders = user.longformFolderIds(library).sorted(), + )) + } + + post("/auth/logout") { + val user = call.requireApiUser(users) + ApiTokenRepository.revokeRaw(call.bearerToken().orEmpty()) + call.respond(HttpStatusCode.NoContent) + } + + get("/auth/devices") { + val user = call.requireApiUser(users) + val current = call.apiToken() + val devices = ApiTokenRepository.list(user.name).map { record -> + DeviceDto( + id = record.id, + deviceName = record.deviceName, + platform = record.platform, + createdAt = record.createdAt, + lastUsedAt = record.lastUsedAt, + expiresAt = record.expiresAt, + current = record.id == current?.id, + ) + } + call.respond(devices) + } + + delete("/auth/devices/{id}") { + val user = call.requireApiUser(users) + val id = call.parameters["id"] ?: badRequest("Device id is required") + if (!ApiTokenRepository.revoke(id, user.name)) notFound("Device") + call.respond(HttpStatusCode.NoContent) + } + + get("/scan") { + call.requireApiUser(users) + val status = scanStatus() + call.respond(ScanStatusDto(status.scanning, status.count, status.error)) + } + + post("/scan") { + val user = call.requireApiUser(users) + if (!user.admin) forbidden("Only admins can start a scan") + val started = startScan() + call.respond( + HttpStatusCode.Accepted, + ScanStatusDto(scanning = started, count = scanStatus().count), + ) + } + + libraryRoutes(users, library, coverArtService, transcoder) + moodRoutes(users, library, radioService) + sessionRoutes(users, library, radioService) + } +} + +private fun constantTimeEquals(candidate: String, expected: String): Boolean = + MessageDigest.isEqual( + candidate.toByteArray(Charsets.UTF_8), + expected.toByteArray(Charsets.UTF_8), + ) diff --git a/src/main/kotlin/win/taptap/musicmanager/api/ApiSupport.kt b/src/main/kotlin/win/taptap/musicmanager/api/ApiSupport.kt new file mode 100644 index 0000000..3551a23 --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/api/ApiSupport.kt @@ -0,0 +1,111 @@ +package win.taptap.musicmanager.api + +import io.ktor.http.HttpHeaders +import io.ktor.http.HttpStatusCode +import io.ktor.server.application.ApplicationCall +import io.ktor.server.request.receive +import io.ktor.server.response.respond +import io.ktor.util.AttributeKey +import kotlinx.serialization.SerializationException +import win.taptap.musicmanager.api.ApiError +import win.taptap.musicmanager.api.ApiErrorBody +import win.taptap.musicmanager.api.UserDto +import win.taptap.musicmanager.config.FolderType +import win.taptap.musicmanager.config.LibraryConfig +import win.taptap.musicmanager.config.UserAccount +import win.taptap.musicmanager.config.UsersConfig +import win.taptap.musicmanager.db.ApiTokenRecord +import win.taptap.musicmanager.db.ApiTokenRepository + +/** HTTP-shaped error rendered by the global StatusPages handler. */ +class ApiException( + val status: HttpStatusCode, + val code: String, + override val message: String, +) : RuntimeException(message) + +val ApiUserKey = AttributeKey("musicmanager.api.user") +val ApiTokenKey = AttributeKey("musicmanager.api.token") + +fun UserAccount.musicFolderIds(library: LibraryConfig): Set = + library.folders + .asSequence() + .filter { it.type == FolderType.MUSIC && it.id in folders } + .map { it.id } + .toSet() + +fun UserAccount.longformFolderIds(library: LibraryConfig): Set = + library.folders + .asSequence() + .filter { it.type == FolderType.LONGFORM } + .map { it.id } + .toSet() + +fun UserAccount.toDto(library: LibraryConfig): UserDto = UserDto( + name = name, + admin = admin, + musicFolders = musicFolderIds(library).sorted(), + longformFolders = longformFolderIds(library).sorted(), +) + +fun ApplicationCall.apiUser(): UserAccount = + attributes.getOrNull(ApiUserKey) ?: throw ApiException( + HttpStatusCode.Unauthorized, + "unauthorized", + "Authentication required", + ) + +fun ApplicationCall.apiToken(): ApiTokenRecord? = attributes.getOrNull(ApiTokenKey) + +fun apiErrorBody(code: String, message: String): ApiErrorBody = + ApiErrorBody(ApiError(code, message)) + +/** Bearer header is the norm; `token` exists for browser audio and image URLs. */ +fun ApplicationCall.bearerToken(): String? { + val header = request.headers[HttpHeaders.Authorization] + if (!header.isNullOrBlank()) { + val value = header.trim() + if (value.startsWith("Bearer ", ignoreCase = true)) { + return value.substringAfter(' ').trim().takeIf { it.isNotEmpty() } + } + return value.takeIf { it.isNotEmpty() } + } + return request.queryParameters["token"]?.takeIf { it.isNotBlank() } +} + +/** + * Resolves the token and stores the user on the call. Returns null after sending + * a 401, so handlers can simply `?: return@get`. + */ +suspend fun ApplicationCall.requireApiUser(users: UsersConfig): UserAccount { + val raw = bearerToken() + val token = raw?.let { ApiTokenRepository.resolve(it) } + val user = token?.let { users.byName(it.userName) } + if (token == null || user == null) { + throw ApiException(HttpStatusCode.Unauthorized, "unauthorized", "Missing or invalid token") + } + attributes.put(ApiUserKey, user) + attributes.put(ApiTokenKey, token) + return user +} + +suspend inline fun ApplicationCall.receiveJson(): T = + try { + receive() + } catch (e: SerializationException) { + throw ApiException(HttpStatusCode.BadRequest, "invalid_body", "Invalid JSON body") + } catch (e: IllegalArgumentException) { + throw ApiException(HttpStatusCode.BadRequest, "invalid_body", e.message ?: "Invalid body") + } + +fun notFound(what: String): Nothing = + throw ApiException(HttpStatusCode.NotFound, "not_found", "$what not found") + +fun badRequest(message: String): Nothing = + throw ApiException(HttpStatusCode.BadRequest, "bad_request", message) + +fun forbidden(message: String): Nothing = + throw ApiException(HttpStatusCode.Forbidden, "forbidden", message) + +fun conflict(message: String): Nothing = + throw ApiException(HttpStatusCode.Conflict, "conflict", message) diff --git a/src/main/kotlin/win/taptap/musicmanager/api/LibraryApi.kt b/src/main/kotlin/win/taptap/musicmanager/api/LibraryApi.kt new file mode 100644 index 0000000..27221c7 --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/api/LibraryApi.kt @@ -0,0 +1,188 @@ +package win.taptap.musicmanager.api + +import io.ktor.http.ContentType +import io.ktor.http.HttpHeaders +import io.ktor.http.HttpStatusCode +import io.ktor.server.response.respond +import io.ktor.server.response.header +import io.ktor.server.response.respondFile +import io.ktor.server.response.respondOutputStream +import io.ktor.server.routing.Route +import io.ktor.server.routing.get +import java.net.URLEncoder +import java.time.Instant +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import org.slf4j.LoggerFactory +import win.taptap.musicmanager.api.LibraryPage +import win.taptap.musicmanager.api.SearchResponse +import win.taptap.musicmanager.api.toDto +import win.taptap.musicmanager.config.LibraryConfig +import win.taptap.musicmanager.config.UsersConfig +import win.taptap.musicmanager.db.LibraryRepository +import win.taptap.musicmanager.scanner.CoverArtService +import win.taptap.musicmanager.transcoding.FfmpegTranscoder + +private val log = LoggerFactory.getLogger("win.taptap.musicmanager.api.LibraryRoutes") + +fun Route.libraryRoutes( + users: UsersConfig, + library: LibraryConfig, + coverArtService: CoverArtService, + transcoder: FfmpegTranscoder, +) { + /** + * Snapshot sync (`cursor`) and delta sync (`since=revision`) in one endpoint. + * Deletions are returned explicitly so offline libraries can drop them. + */ + get("/library/songs") { + val user = call.requireApiUser(users) + val limit = (call.request.queryParameters["limit"]?.toIntOrNull() ?: 500).coerceIn(1, 1000) + val scope = call.request.queryParameters["scope"] ?: "all" + val folders = user.scopeFolders(library, scope) + val now = Instant.now().toString() + val since = call.request.queryParameters["since"]?.takeIf { it.isNotBlank() } + val cursor = call.request.queryParameters["cursor"]?.takeIf { it.isNotBlank() } + + if (since != null) { + val changed = LibraryRepository.changedSongs(since, folders, limit, user.name) + val deleted = LibraryRepository.tombstones(since, limit).map { it.entityId } + val complete = changed.size < limit && deleted.size < limit + call.respond( + LibraryPage( + songs = changed.map { it.toDto() }, + deletedSongIds = deleted, + revision = if (complete) now else changed.lastOrNull()?.updatedAt ?: now, + nextSince = if (changed.size == limit) changed.last().updatedAt else null, + ), + ) + return@get + } + + val songs = LibraryRepository.syncSongs(folders, cursor.orEmpty(), limit, user.name) + call.respond( + LibraryPage( + songs = songs.map { it.toDto() }, + revision = now, + nextCursor = if (songs.size == limit) songs.last().id else null, + ), + ) + } + + get("/library/search") { + val user = call.requireApiUser(users) + val query = call.request.queryParameters["q"]?.trim().orEmpty() + if (query.isEmpty()) { + call.respond(SearchResponse(emptyList())) + return@get + } + val limit = (call.request.queryParameters["limit"]?.toIntOrNull() ?: 50).coerceIn(1, 200) + val folders = user.scopeFolders(library, call.request.queryParameters["scope"] ?: "all") + val songs = LibraryRepository.searchSongs(query, limit, 0, folders, user.name) + call.respond(SearchResponse(songs.map { it.toDto() })) + } + + get("/songs/{id}/stream") { + val user = call.requireApiUser(users) + val id = call.parameters["id"] ?: badRequest("Song id is required") + val parameters = call.request.queryParameters + + val rawMaxBitRate = parameters["maxBitRate"] + val maxBitRate = rawMaxBitRate?.toIntOrNull() + if (rawMaxBitRate != null && (maxBitRate == null || maxBitRate < 0)) { + badRequest("Invalid maxBitRate") + } + val rawOffset = parameters["timeOffset"] + val offset = rawOffset?.toIntOrNull() + if (rawOffset != null && (offset == null || offset < 0)) { + badRequest("Invalid timeOffset") + } + + val resolved = LibraryRepository.resolveSong( + id, + user.visibleFolderIds(library), + user.name, + library, + ) ?: notFound("Song") + + if (!transcoder.shouldTranscode( + resolved.song.bitRate, + maxBitRate, + parameters["format"], + offset ?: 0, + ) + ) { + call.response.header(HttpHeaders.ContentType, resolved.song.contentType) + if (parameters["download"] == "true") { + call.response.header( + HttpHeaders.ContentDisposition, + contentDisposition(resolved.file.fileName.toString()), + ) + } + call.respondFile(resolved.file.toFile()) + return@get + } + + val process = try { + transcoder.start(resolved.file, maxBitRate, offset ?: 0) + } catch (e: Exception) { + log.error("Failed to start ffmpeg for {}", resolved.file, e) + throw ApiException(HttpStatusCode.InternalServerError, "transcode_failed", "Transcoding failed") + } + + try { + call.response.headers.append(HttpHeaders.CacheControl, "no-store") + call.respondOutputStream(ContentType.parse("audio/mpeg")) { + val output = this + withContext(Dispatchers.IO) { + process.inputStream.use { input -> input.copyTo(output) } + } + } + } finally { + transcoder.stop(process) + } + } + + get("/covers/{id}") { + val user = call.requireApiUser(users) + val id = call.parameters["id"] ?: badRequest("Cover id is required") + val rawSize = call.request.queryParameters["size"] + val size = rawSize?.toIntOrNull() + if (rawSize != null && (size == null || size !in 1..2048)) { + badRequest("Cover size must be between 1 and 2048") + } + + val folders = user.visibleFolderIds(library) + val albumId = when { + id.startsWith("sg-") -> LibraryRepository.albumIdForSong(id, folders) + LibraryRepository.album(id, folders, user.name) != null -> id + else -> null + } ?: notFound("Cover") + + val cover = if (size == null) { + coverArtService.coverFile(albumId) + } else { + coverArtService.resizedCover(albumId, size) + } ?: notFound("Cover") + + call.respondFile(cover.toFile()) + } +} + +private fun win.taptap.musicmanager.config.UserAccount.scopeFolders( + library: LibraryConfig, + scope: String, +): Set = when (scope) { + "music" -> musicFolderIds(library) + "longform" -> longformFolderIds(library) + else -> visibleFolderIds(library) +} + +private fun contentDisposition(fileName: String): String { + val encoded = URLEncoder.encode(fileName, Charsets.UTF_8).replace("+", "%20") + val ascii = fileName.map { character -> + if (character.code in 32..126 && character != '"' && character != '\\') character else '_' + }.joinToString("") + + return "attachment; filename=\"$ascii\"; filename*=UTF-8''$encoded" +} diff --git a/src/main/kotlin/win/taptap/musicmanager/api/MoodApi.kt b/src/main/kotlin/win/taptap/musicmanager/api/MoodApi.kt new file mode 100644 index 0000000..87a1376 --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/api/MoodApi.kt @@ -0,0 +1,209 @@ +package win.taptap.musicmanager.api + +import io.ktor.http.HttpStatusCode +import io.ktor.server.response.respond +import io.ktor.server.routing.Route +import io.ktor.server.routing.delete +import io.ktor.server.routing.get +import io.ktor.server.routing.patch +import io.ktor.server.routing.post +import kotlinx.serialization.Serializable +import win.taptap.musicmanager.api.AddSeedRequest +import win.taptap.musicmanager.api.AddToMoodResponse +import win.taptap.musicmanager.api.CreateMoodRequest +import win.taptap.musicmanager.api.MoodDetailDto +import win.taptap.musicmanager.api.MoodDto +import win.taptap.musicmanager.api.RecommendationDto +import win.taptap.musicmanager.api.SearchResponse +import win.taptap.musicmanager.api.UpdateMoodRequest +import win.taptap.musicmanager.api.seedDto +import win.taptap.musicmanager.api.toDto +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.radio.RadioService + +@Serializable +data class MoodsResponse(val moods: List) + +fun Route.moodRoutes( + users: UsersConfig, + library: LibraryConfig, + radioService: RadioService, +) { + get("/moods") { + val user = call.requireApiUser(users) + call.respond(MoodsResponse(MoodRepository.list(user.name).map { it.toDto() })) + } + + post("/moods") { + val user = call.requireApiUser(users) + val request = call.receiveJson() + val name = request.name.trim() + if (name.isEmpty()) badRequest("Mood name is required") + + val folders = user.musicFolderIds(library) + val seedIds = request.seedSongIds + .distinct() + .filter { LibraryRepository.song(it, folders, user.name) != null } + + val mood = MoodRepository.create( + owner = user.name, + name = name, + description = request.description?.trim()?.takeIf { it.isNotEmpty() }, + query = request.query?.trim()?.takeIf { it.isNotEmpty() }, + genres = request.genres, + targetSize = request.targetSize, + refreshHours = request.refreshHours, + ytEnabled = request.ytEnabled, + seedSongIds = seedIds, + ) + call.respond(HttpStatusCode.Created, detail(mood, user, library)) + } + + get("/moods/{id}") { + val user = call.requireApiUser(users) + val mood = ownedMood(call.parameters["id"], user) + call.respond(detail(mood, user, library)) + } + + patch("/moods/{id}") { + val user = call.requireApiUser(users) + val mood = ownedMood(call.parameters["id"], user) + val request = call.receiveJson() + + val description = when { + request.clearDescription -> null + request.description != null -> request.description.trim().takeIf { it.isNotEmpty() } + else -> mood.description + } + val query = when { + request.clearQuery -> null + request.query != null -> request.query.trim().takeIf { it.isNotEmpty() } + else -> mood.query + } + + val updated = MoodRepository.update( + id = mood.id, + owner = user.name, + name = request.name?.trim()?.takeIf { it.isNotEmpty() } ?: mood.name, + description = description, + query = query, + genres = request.genres ?: mood.genres, + targetSize = request.targetSize ?: mood.targetSize, + refreshHours = request.refreshHours ?: mood.refreshHours, + ytEnabled = request.ytEnabled ?: mood.ytEnabled, + ) ?: notFound("Mood") + + call.respond(detail(updated, user, library)) + } + + delete("/moods/{id}") { + val user = call.requireApiUser(users) + val mood = ownedMood(call.parameters["id"], user) + MoodRepository.delete(mood.id, user.name) + call.respond(HttpStatusCode.NoContent) + } + + post("/moods/{id}/seeds") { + val user = call.requireApiUser(users) + val mood = ownedMood(call.parameters["id"], user) + val request = call.receiveJson() + val song = requireMusicSong(request.songId, user, library) + val added = MoodRepository.addSeed( + id = mood.id, + owner = user.name, + songId = song.id, + origin = request.origin, + ) + val refreshed = MoodRepository.get(mood.id, user.name) ?: mood + call.respond( + HttpStatusCode.OK, + AddToMoodResponse(mood = refreshed.toDto(), added = added), + ) + } + + delete("/moods/{id}/seeds/{songId}") { + val user = call.requireApiUser(users) + val mood = ownedMood(call.parameters["id"], user) + val songId = call.parameters["songId"] ?: badRequest("Song id is required") + MoodRepository.removeSeed(mood.id, user.name, songId) + call.respond(HttpStatusCode.NoContent) + } + + /** A short, unpersisted radio preview for the mood detail screen. */ + get("/moods/{id}/preview") { + val user = call.requireApiUser(users) + val mood = ownedMood(call.parameters["id"], user) + val limit = (call.request.queryParameters["limit"]?.toIntOrNull() ?: 20).coerceIn(1, 50) + call.respond(SearchResponse(radioService.preview(mood, user, library, limit).map { it.toDto() })) + } + + get("/moods/{id}/recommendations") { + val user = call.requireApiUser(users) + val mood = ownedMood(call.parameters["id"], user) + call.respond(recommendations(mood, user, library)) + } +} + +private fun ownedMood(id: String?, user: UserAccount): MoodRecord { + if (id.isNullOrBlank()) badRequest("Mood id is required") + return MoodRepository.get(id, user.name) ?: notFound("Mood") +} + +private fun requireMusicSong(songId: String, user: UserAccount, library: LibraryConfig) = + LibraryRepository.song(songId, user.musicFolderIds(library), user.name) + ?: notFound("Song") + +private fun detail(mood: MoodRecord, user: UserAccount, library: LibraryConfig): MoodDetailDto { + val folders = user.musicFolderIds(library) + val seedRecords = MoodRepository.seeds(mood.id) + val seedSongs = LibraryRepository + .songsByIds(seedRecords.map { it.songId }, folders, user.name) + .associateBy { it.id } + val seeds = seedRecords.mapNotNull { seed -> + seedSongs[seed.songId]?.let { seedDto(seed, it) } + } + + return MoodDetailDto( + mood = mood.toDto(), + seeds = seeds, + recommendations = recommendations(mood, user, library).recommendations, + ) +} + +private fun recommendations( + mood: MoodRecord, + user: UserAccount, + library: LibraryConfig, +): RecommendationsResponse { + val records = MoodRepository.recommendations(mood.id) + val matchedIds = records.mapNotNull { it.matchedSongId } + val matchedSongs = LibraryRepository + .songsByIds(matchedIds, user.visibleFolderIds(library), user.name) + .associateBy { it.id } + + return RecommendationsResponse( + recommendations = records.map { record -> + RecommendationDto( + videoId = record.videoId, + title = record.title, + artist = record.artist, + album = record.album, + duration = record.duration, + thumbnail = record.thumbnail, + state = record.state, + matchedSong = record.matchedSongId?.let { matchedSongs[it] }?.toDto(), + timesAdded = record.timesAdded, + firstSeen = record.firstSeen, + lastSeen = record.lastSeen, + ) + }, + ) +} + +@Serializable +data class RecommendationsResponse(val recommendations: List) diff --git a/src/main/kotlin/win/taptap/musicmanager/api/SessionApi.kt b/src/main/kotlin/win/taptap/musicmanager/api/SessionApi.kt new file mode 100644 index 0000000..142837a --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/api/SessionApi.kt @@ -0,0 +1,154 @@ +package win.taptap.musicmanager.api + +import io.ktor.http.HttpStatusCode +import io.ktor.server.response.respond +import io.ktor.server.routing.Route +import io.ktor.server.routing.delete +import io.ktor.server.routing.get +import io.ktor.server.routing.post +import kotlinx.serialization.Serializable +import win.taptap.musicmanager.api.AddToMoodRequest +import win.taptap.musicmanager.api.AddToMoodResponse +import win.taptap.musicmanager.api.NextTracksRequest +import win.taptap.musicmanager.api.PlaybackEventsRequest +import win.taptap.musicmanager.api.PlaybackEventsResponse +import win.taptap.musicmanager.api.SessionDto +import win.taptap.musicmanager.api.SongDto +import win.taptap.musicmanager.api.StartSessionRequest +import win.taptap.musicmanager.api.toDto +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.PlaybackSessionRecord +import win.taptap.musicmanager.db.RadioRepository +import win.taptap.musicmanager.radio.RadioService + +@Serializable +data class TracksResponse(val songs: List) + +fun Route.sessionRoutes( + users: UsersConfig, + library: LibraryConfig, + radioService: RadioService, +) { + post("/moods/{id}/sessions") { + val user = call.requireApiUser(users) + val mood = ownedMoodFor(call.parameters["id"], user) + val request = runCatching { call.receiveJson() } + .getOrDefault(StartSessionRequest()) + val limit = request.limit ?: DEFAULT_BATCH + + val started = radioService.start(mood, user, library, limit) + call.respond( + HttpStatusCode.Created, + SessionDto( + id = started.session.id, + moodId = mood.id, + moodName = mood.name, + startedAt = started.session.createdAt, + queue = started.songs.map { it.toDto() }, + ), + ) + } + + get("/sessions/{id}") { + val user = call.requireApiUser(users) + val session = ownedSession(call.parameters["id"], user) + val mood = ownedMoodFor(session.moodId, user) + val folders = user.musicFolderIds(library) + val items = RadioRepository.items(session.id) + val songs = LibraryRepository + .songsByIds(items.map { it.songId }, folders, user.name) + .associateBy { it.id } + + call.respond( + SessionDto( + id = session.id, + moodId = session.moodId, + moodName = mood.name, + startedAt = session.createdAt, + closedAt = session.closedAt, + queue = items.mapNotNull { songs[it.songId]?.toDto() }, + ), + ) + } + + post("/sessions/{id}/next") { + val user = call.requireApiUser(users) + val session = ownedSession(call.parameters["id"], user) + if (session.closedAt != null) conflict("Session is closed") + val mood = ownedMoodFor(session.moodId, user) + val request = runCatching { call.receiveJson() } + .getOrDefault(NextTracksRequest()) + + val songs = radioService.next( + mood = mood, + user = user, + library = library, + sessionId = session.id, + excluded = request.excludeSongIds.toSet(), + limit = request.limit ?: DEFAULT_BATCH, + ) + call.respond(TracksResponse(songs.map { it.toDto() })) + } + + post("/sessions/{id}/events") { + val user = call.requireApiUser(users) + val session = ownedSession(call.parameters["id"], user) + val request = call.receiveJson() + val accepted = request.events.count { event -> + event.type in EVENT_TYPES && + event.songId.isNotBlank() && + RadioRepository.recordEvent(session.id, user.name, event.songId, event.type) + } + call.respond(PlaybackEventsResponse(accepted)) + } + + /** Explicitly adds the playing track to the session mood or another chosen mood. */ + post("/sessions/{id}/add-to-mood") { + val user = call.requireApiUser(users) + val session = ownedSession(call.parameters["id"], user) + val request = call.receiveJson() + val folders = user.musicFolderIds(library) + val song = LibraryRepository.song(request.songId, folders, user.name) + ?: notFound("Song") + + val target = if (request.moodId.isNullOrBlank()) { + ownedMoodFor(session.moodId, user) + } else { + ownedMoodFor(request.moodId, user) + } + + val added = MoodRepository.addSeed(target.id, user.name, song.id, "manual") + val refreshed = MoodRepository.get(target.id, user.name) ?: target + call.respond( + AddToMoodResponse( + mood = refreshed.toDto(), + added = added, + ), + ) + } + + delete("/sessions/{id}") { + val user = call.requireApiUser(users) + val session = ownedSession(call.parameters["id"], user) + RadioRepository.close(session.id, user.name) + call.respond(HttpStatusCode.NoContent) + } +} + +private fun ownedMoodFor(id: String?, user: UserAccount): MoodRecord { + if (id.isNullOrBlank()) badRequest("Mood id is required") + return MoodRepository.get(id, user.name) ?: notFound("Mood") +} + +private fun ownedSession(id: String?, user: UserAccount): PlaybackSessionRecord { + if (id.isNullOrBlank()) badRequest("Session id is required") + return RadioRepository.get(id, user.name) ?: notFound("Session") +} + +private const val DEFAULT_BATCH = 15 +private val EVENT_TYPES = setOf("started", "completed", "skipped") diff --git a/src/main/kotlin/win/taptap/musicmanager/db/ApiTokenRepository.kt b/src/main/kotlin/win/taptap/musicmanager/db/ApiTokenRepository.kt new file mode 100644 index 0000000..fb0562a --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/db/ApiTokenRepository.kt @@ -0,0 +1,153 @@ +package win.taptap.musicmanager.db + +import java.security.MessageDigest +import java.security.SecureRandom +import java.time.Duration +import java.time.Instant +import java.util.Base64 +import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq +import org.jetbrains.exposed.sql.SqlExpressionBuilder.greater +import org.jetbrains.exposed.sql.SqlExpressionBuilder.neq +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 IssuedToken(val raw: String, val record: ApiTokenRecord) + +data class ApiTokenRecord( + val id: String, + val userName: String, + val deviceName: String, + val platform: String, + val createdAt: String, + val lastUsedAt: String, + val expiresAt: String, +) + +/** + * Device sessions for the native API. Raw tokens never touch the database: only + * their SHA-256 hash is stored, so a database leak cannot be replayed. + */ +object ApiTokenRepository { + + private val random = SecureRandom() + private const val TOKEN_BYTES = 32 + private val TOUCH_INTERVAL: Duration = Duration.ofMinutes(1) + + fun create( + userName: String, + deviceName: String, + platform: String, + ttl: Duration = Duration.ofDays(180), + ): IssuedToken { + val raw = randomToken() + val now = Instant.now() + val record = ApiTokenRecord( + id = "tk-" + hash("$userName|$raw").take(24), + userName = userName, + deviceName = deviceName.take(120), + platform = platform.take(32), + createdAt = now.toString(), + lastUsedAt = now.toString(), + expiresAt = now.plus(ttl).toString(), + ) + + transaction { + ApiTokensTable.insert { + it[id] = record.id + it[this.userName] = record.userName + it[tokenHash] = hash(raw) + it[this.deviceName] = record.deviceName + it[this.platform] = record.platform + it[createdAt] = record.createdAt + it[lastUsedAt] = record.lastUsedAt + it[expiresAt] = record.expiresAt + } + } + + return IssuedToken(raw, record) + } + + /** Validates a raw token and refreshes `last_used_at` at most once a minute. */ + fun resolve(raw: String): ApiTokenRecord? = transaction { + val hashed = hash(raw) + val row = ApiTokensTable.selectAll() + .where { ApiTokensTable.tokenHash eq hashed } + .singleOrNull() ?: return@transaction null + + val expiresAt = row[ApiTokensTable.expiresAt] + if (Instant.parse(expiresAt).isBefore(Instant.now())) { + ApiTokensTable.deleteWhere { ApiTokensTable.id eq row[ApiTokensTable.id] } + return@transaction null + } + + val lastUsed = Instant.parse(row[ApiTokensTable.lastUsedAt]) + val now = Instant.now() + if (lastUsed.plus(TOUCH_INTERVAL).isBefore(now)) { + ApiTokensTable.update({ ApiTokensTable.id eq row[ApiTokensTable.id] }) { + it[lastUsedAt] = now.toString() + } + } + + ApiTokenRecord( + id = row[ApiTokensTable.id], + userName = row[ApiTokensTable.userName], + deviceName = row[ApiTokensTable.deviceName], + platform = row[ApiTokensTable.platform], + createdAt = row[ApiTokensTable.createdAt], + lastUsedAt = now.toString(), + expiresAt = expiresAt, + ) + } + + fun list(userName: String): List = transaction { + ApiTokensTable.selectAll() + .where { (ApiTokensTable.userName eq userName) and (ApiTokensTable.expiresAt greater Instant.now().toString()) } + .orderBy(ApiTokensTable.lastUsedAt to org.jetbrains.exposed.sql.SortOrder.DESC) + .map { + ApiTokenRecord( + id = it[ApiTokensTable.id], + userName = it[ApiTokensTable.userName], + deviceName = it[ApiTokensTable.deviceName], + platform = it[ApiTokensTable.platform], + createdAt = it[ApiTokensTable.createdAt], + lastUsedAt = it[ApiTokensTable.lastUsedAt], + expiresAt = it[ApiTokensTable.expiresAt], + ) + } + } + + fun revoke(id: String, userName: String): Boolean = transaction { + ApiTokensTable.deleteWhere { + (ApiTokensTable.id eq id) and (ApiTokensTable.userName eq userName) + } > 0 + } + + fun revokeRaw(raw: String): Boolean = transaction { + ApiTokensTable.deleteWhere { ApiTokensTable.tokenHash eq hash(raw) } > 0 + } + + fun revokeAll(userName: String, exceptId: String? = null): Int = transaction { + if (exceptId == null) { + ApiTokensTable.deleteWhere { ApiTokensTable.userName eq userName } + } else { + ApiTokensTable.deleteWhere { + (ApiTokensTable.userName eq userName) and (ApiTokensTable.id neq exceptId) + } + } + } + + fun hash(value: String): String = + MessageDigest.getInstance("SHA-256") + .digest(value.toByteArray(Charsets.UTF_8)) + .joinToString("") { "%02x".format(it) } + + private fun randomToken(): String { + val bytes = ByteArray(TOKEN_BYTES) + random.nextBytes(bytes) + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes) + } +} diff --git a/src/main/kotlin/win/taptap/musicmanager/db/ConfigRepository.kt b/src/main/kotlin/win/taptap/musicmanager/db/ConfigRepository.kt index d1b8771..aa12450 100644 --- a/src/main/kotlin/win/taptap/musicmanager/db/ConfigRepository.kt +++ b/src/main/kotlin/win/taptap/musicmanager/db/ConfigRepository.kt @@ -13,7 +13,7 @@ import win.taptap.musicmanager.config.UsersConfig * Reconciles the config/Vault-managed identity tables with SQLite. * * Removing a folder cascades to its songs; removing a user cascades to that - * user's stars, ratings, play counts, bookmarks and playlists. + * user's play history and mood ownership. */ object ConfigRepository { diff --git a/src/main/kotlin/win/taptap/musicmanager/db/LibraryRepository.kt b/src/main/kotlin/win/taptap/musicmanager/db/LibraryRepository.kt index 3b4506f..9fba2ff 100644 --- a/src/main/kotlin/win/taptap/musicmanager/db/LibraryRepository.kt +++ b/src/main/kotlin/win/taptap/musicmanager/db/LibraryRepository.kt @@ -4,6 +4,7 @@ import java.nio.file.Files import java.nio.file.Path import org.jetbrains.exposed.sql.JoinType import org.jetbrains.exposed.sql.Op +import org.jetbrains.exposed.sql.SqlExpressionBuilder.greater import org.jetbrains.exposed.sql.ResultRow import org.jetbrains.exposed.sql.SortOrder import org.jetbrains.exposed.sql.Transaction @@ -81,6 +82,7 @@ data class SongRecord( val folderId: Int, val relativePath: String, val created: String, + val updatedAt: String, val starredAt: String?, val rating: Int?, val playCount: Int, @@ -91,6 +93,8 @@ data class SongRecord( data class ResolvedSong(val song: SongRecord, val file: Path) +data class TombstoneRecord(val entityId: String, val deletedAt: String) + /** * Read-side queries for browsing and media. Every method takes the set of folder * IDs visible to the requesting user; an album or artist without a visible song @@ -241,6 +245,67 @@ object LibraryRepository { ids.mapNotNull { albumRecord(it, folderIds, userName) } } + /** Stable page of the library snapshot, ordered by song ID. */ + fun syncSongs( + folderIds: Set, + afterId: String, + limit: Int, + userName: String, + ): List = read { + if (folderIds.isEmpty()) return@read emptyList() + + val rows = SongsTable.selectAll() + .where { + (SongsTable.folderId inList folderIds) and + (SongsTable.id greater afterId) + } + .orderBy(SongsTable.id to SortOrder.ASC) + .limit(limit) + .toList() + + enrichSongs(rows, userName) + } + + /** Songs whose metadata changed after the client's last revision. */ + fun changedSongs( + since: String, + folderIds: Set, + limit: Int, + userName: String, + ): List = read { + if (folderIds.isEmpty()) return@read emptyList() + + val rows = SongsTable.selectAll() + .where { + (SongsTable.folderId inList folderIds) and + (SongsTable.updatedAt greater since) + } + .orderBy( + SongsTable.updatedAt to SortOrder.ASC, + SongsTable.id to SortOrder.ASC, + ) + .limit(limit) + .toList() + + enrichSongs(rows, userName) + } + + fun tombstones(since: String, limit: Int): List = read { + LibraryTombstonesTable.selectAll() + .where { + (LibraryTombstonesTable.entity eq "song") and + (LibraryTombstonesTable.deletedAt greater since) + } + .orderBy(LibraryTombstonesTable.deletedAt to SortOrder.ASC) + .limit(limit) + .map { + TombstoneRecord( + entityId = it[LibraryTombstonesTable.entityId], + deletedAt = it[LibraryTombstonesTable.deletedAt], + ) + } + } + fun allSongs(limit: Int, offset: Int, folderIds: Set, userName: String): List = read { if (folderIds.isEmpty()) return@read emptyList() @@ -748,6 +813,7 @@ object LibraryRepository { folderId = row[SongsTable.folderId], relativePath = row[SongsTable.relativePath], created = row[SongsTable.createdAt], + updatedAt = row[SongsTable.updatedAt].ifBlank { row[SongsTable.createdAt] }, starredAt = state?.starredAt, rating = state?.rating, playCount = state?.playCount ?: 0, diff --git a/src/main/kotlin/win/taptap/musicmanager/db/MediaRepository.kt b/src/main/kotlin/win/taptap/musicmanager/db/MediaRepository.kt index de6ed0d..1688c34 100644 --- a/src/main/kotlin/win/taptap/musicmanager/db/MediaRepository.kt +++ b/src/main/kotlin/win/taptap/musicmanager/db/MediaRepository.kt @@ -110,6 +110,7 @@ object MediaRepository { it[relativePath] = track.relativePath it[fileMtime] = track.fileMtime it[searchText] = track.searchText + it[updatedAt] = now it[lyrics] = track.lyrics } } else { @@ -132,6 +133,7 @@ object MediaRepository { it[fileMtime] = track.fileMtime it[createdAt] = now it[searchText] = track.searchText + it[updatedAt] = now it[lyrics] = track.lyrics } } @@ -169,7 +171,13 @@ object MediaRepository { .map { it[SongsTable.id] } .filterNot { it in seenSongIds } + val now = Instant.now().toString() obsolete.forEach { songId -> + LibraryTombstonesTable.insertIgnore { + it[entity] = "song" + it[entityId] = songId + it[deletedAt] = now + } SongsTable.deleteWhere { it.run { SongsTable.id eq songId } } } diff --git a/src/main/kotlin/win/taptap/musicmanager/db/MoodRepository.kt b/src/main/kotlin/win/taptap/musicmanager/db/MoodRepository.kt index a26b8f8..b7f5e69 100644 --- a/src/main/kotlin/win/taptap/musicmanager/db/MoodRepository.kt +++ b/src/main/kotlin/win/taptap/musicmanager/db/MoodRepository.kt @@ -4,37 +4,34 @@ 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.SqlExpressionBuilder.eq import org.jetbrains.exposed.sql.and import org.jetbrains.exposed.sql.deleteWhere import org.jetbrains.exposed.sql.insert +import org.jetbrains.exposed.sql.insertIgnore import org.jetbrains.exposed.sql.selectAll import org.jetbrains.exposed.sql.transactions.transaction import org.jetbrains.exposed.sql.update +import win.taptap.musicmanager.util.IdGenerator data class MoodRecord( - val playlistId: String, + val id: String, val owner: String, val name: String, - val comment: String?, + val description: 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 ytEnabled: Boolean, + val lastDiscoveryAt: String?, + val createdAt: String, + val changedAt: String, val lastError: String?, - val created: String, - val changed: String, - val songCount: Int, - val duration: Int, val seedCount: Int, + val newRecommendations: Int, ) data class MoodSeedRecord( @@ -43,190 +40,117 @@ data class MoodSeedRecord( val addedAt: String, ) +data class RecommendationRecord( + val videoId: String, + val title: String, + val artist: String, + val album: String?, + val duration: Int?, + val thumbnail: String?, + val state: String, + val matchedSongId: String?, + val timesAdded: Int, + val firstSeen: String, + val lastSeen: 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`. + * 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. */ 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) + fun list(owner: String): List = transaction { + MoodsTable.selectAll() + .where { MoodsTable.owner eq owner } + .orderBy(MoodsTable.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") - } + fun get(id: String, owner: String): MoodRecord? = transaction { + MoodsTable.selectAll() + .where { (MoodsTable.id eq id) and (MoodsTable.owner eq owner) } .singleOrNull() - - row?.let { moodRecord(it) } + ?.let { moodRecord(it) } } fun create( - userName: String, + owner: String, name: String, - comment: String?, + description: String?, query: String?, genres: List, targetSize: Int, - ytSlots: Int, - expandRelated: Boolean, refreshHours: Int, + ytEnabled: Boolean, seedSongIds: List, - ): MoodRecord { - val playlist = PlaylistRepository.create( - userName = userName, - name = name, - songIds = emptyList(), - isPublic = false, - kind = "mood", + ): MoodRecord = transaction { + val now = Instant.now().toString() + val id = IdGenerator.moodId(owner, name, now) + + MoodsTable.insert { + it[MoodsTable.id] = id + it[MoodsTable.owner] = owner + it[MoodsTable.name] = name.take(200) + 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.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(), ) - - 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, + id: String, + owner: String, name: String, - comment: String?, + description: 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") - } + ytEnabled: Boolean, + ): MoodRecord? = transaction { + val exists = MoodsTable.selectAll() + .where { (MoodsTable.id eq id) and (MoodsTable.owner eq owner) } .any() - if (!exists) return@transaction false + if (!exists) return@transaction null - PlaylistsTable.update({ PlaylistsTable.id eq playlistId }) { - it[PlaylistsTable.name] = name - it[PlaylistsTable.comment] = comment + MoodsTable.update({ MoodsTable.id eq id }) { + it[MoodsTable.name] = name.take(200) + 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.refreshHours] = refreshHours.coerceIn(1, 720) + it[MoodsTable.ytEnabled] = ytEnabled 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 + + moodRecord(MoodsTable.selectAll().where { MoodsTable.id eq id }.single()) } - 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 delete(id: String, owner: String): Boolean = transaction { + MoodsTable.deleteWhere { + (MoodsTable.id eq id) and (MoodsTable.owner eq owner) + } > 0 } - fun seeds(playlistId: String): List = transaction { + fun seeds(id: String): List = transaction { MoodSeedsTable.selectAll() - .where { MoodSeedsTable.playlistId eq playlistId } + .where { MoodSeedsTable.moodId eq id } .orderBy( MoodSeedsTable.addedAt to SortOrder.ASC, MoodSeedsTable.songId to SortOrder.ASC, @@ -240,165 +164,130 @@ object MoodRepository { } } - /** 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 + fun seedSongIds(id: String): List = seeds(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 val exists = MoodSeedsTable.selectAll() - .where { - (MoodSeedsTable.playlistId eq playlistId) and - (MoodSeedsTable.songId eq songId) - } + .where { (MoodSeedsTable.moodId eq id) and (MoodSeedsTable.songId eq songId) } .any() if (exists) return@transaction false - MoodSeedsTable.insert { - it[MoodSeedsTable.playlistId] = playlistId + val now = Instant.now().toString() + MoodSeedsTable.insertIgnore { + it[MoodSeedsTable.moodId] = id it[MoodSeedsTable.songId] = songId - it[MoodSeedsTable.origin] = origin - it[addedAt] = Instant.now().toString() + it[MoodSeedsTable.origin] = origin.takeIf { value -> value in ORIGINS } ?: "manual" + it[addedAt] = now + } + MoodsTable.update({ MoodsTable.id eq id }) { + it[changedAt] = now } true } - fun removeSeed( - playlistId: String, - userName: String, - songId: String, - origin: String? = null, - ): Boolean = transaction { - if (get(playlistId, userName) == null) return@transaction false + 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 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 + val removed = MoodSeedsTable.deleteWhere { + (MoodSeedsTable.moodId eq id) and (MoodSeedsTable.songId eq songId) + } > 0 + if (removed) { + MoodsTable.update({ MoodsTable.id eq id }) { + it[changedAt] = Instant.now().toString() } } + removed } - fun markStale(playlistId: String) { - transaction { - MoodsTable.update({ MoodsTable.playlistId eq playlistId }) { - it[generatedAt] = null + fun recommendations(id: String): List = transaction { + MoodRecommendationsTable.selectAll() + .where { MoodRecommendationsTable.moodId eq id } + .orderBy(MoodRecommendationsTable.lastSeen to SortOrder.DESC) + .map { + RecommendationRecord( + videoId = it[MoodRecommendationsTable.videoId], + title = it[MoodRecommendationsTable.title], + artist = it[MoodRecommendationsTable.artist], + album = it[MoodRecommendationsTable.album], + duration = it[MoodRecommendationsTable.duration], + thumbnail = it[MoodRecommendationsTable.thumbnail], + state = it[MoodRecommendationsTable.state], + matchedSongId = it[MoodRecommendationsTable.matchedSongId], + timesAdded = it[MoodRecommendationsTable.timesAdded], + firstSeen = it[MoodRecommendationsTable.firstSeen], + lastSeen = it[MoodRecommendationsTable.lastSeen], + ) } - } } - /** Records a failed generation without claiming the mood is fresh. */ - fun markError(playlistId: String, message: String) { + fun markError(id: String, message: String) { transaction { - MoodsTable.update({ MoodsTable.playlistId eq playlistId }) { + MoodsTable.update({ MoodsTable.id eq id }) { it[lastError] = message.take(1000) - it[generatedAt] = null } } } - fun markAllStale() { + fun markDiscovered(id: String) { transaction { - MoodsTable.update({ Op.TRUE }) { - it[generatedAt] = null + MoodsTable.update({ MoodsTable.id eq id }) { + it[lastDiscoveryAt] = Instant.now().toString() + it[lastError] = 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) { + private fun insertSeeds(id: 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 + MoodSeedsTable.insertIgnore { + it[moodId] = id + it[this.songId] = songId + it[this.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 } + 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") + } .count() .toInt() return MoodRecord( - playlistId = id, - owner = row[PlaylistsTable.owner], - name = row[PlaylistsTable.name], - comment = row[PlaylistsTable.comment], + id = id, + owner = row[MoodsTable.owner], + name = row[MoodsTable.name], + description = row[MoodsTable.description], 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], + ytEnabled = row[MoodsTable.ytEnabled], + lastDiscoveryAt = row[MoodsTable.lastDiscoveryAt], + createdAt = row[MoodsTable.createdAt], + changedAt = row[MoodsTable.changedAt], lastError = row[MoodsTable.lastError], - created = row[PlaylistsTable.createdAt], - changed = row[PlaylistsTable.changedAt], - songCount = songs.size, - duration = songs.sumOf { it[SongsTable.duration] }, seedCount = seedCount, + newRecommendations = newRecommendations, ) } @@ -410,4 +299,6 @@ object MoodRepository { private fun decodeGenres(value: String): List = runCatching { Json.decodeFromString(genreSerializer, value) }.getOrDefault(emptyList()) + + private val ORIGINS = setOf("manual", "recommendation", "yt") } diff --git a/src/main/kotlin/win/taptap/musicmanager/db/PlaylistRepository.kt b/src/main/kotlin/win/taptap/musicmanager/db/PlaylistRepository.kt deleted file mode 100644 index 847f36b..0000000 --- a/src/main/kotlin/win/taptap/musicmanager/db/PlaylistRepository.kt +++ /dev/null @@ -1,191 +0,0 @@ -package win.taptap.musicmanager.db - -import java.time.Instant -import org.jetbrains.exposed.sql.JoinType -import org.jetbrains.exposed.sql.and -import org.jetbrains.exposed.sql.deleteWhere -import org.jetbrains.exposed.sql.insert -import org.jetbrains.exposed.sql.or -import org.jetbrains.exposed.sql.selectAll -import org.jetbrains.exposed.sql.transactions.transaction -import org.jetbrains.exposed.sql.update -import win.taptap.musicmanager.util.IdGenerator - -data class PlaylistRecord( - val id: String, - val name: String, - val comment: String?, - val owner: String, - val isPublic: Boolean, - val kind: String, - val songCount: Int, - val duration: Int, - val created: String, - val changed: String, -) - -/** Playlists are per user; public playlists are visible to everyone. */ -object PlaylistRepository { - - fun visibleTo(userName: String): List = transaction { - PlaylistsTable.selectAll() - .where { - (PlaylistsTable.owner eq userName) or (PlaylistsTable.isPublic eq true) - } - .orderBy(PlaylistsTable.changedAt to org.jetbrains.exposed.sql.SortOrder.DESC) - .map { playlistRecord(it[PlaylistsTable.id], it) } - } - - fun get(playlistId: String, userName: String): PlaylistRecord? = transaction { - val row = PlaylistsTable.selectAll() - .where { PlaylistsTable.id eq playlistId } - .singleOrNull() ?: return@transaction null - - if (row[PlaylistsTable.owner] != userName && !row[PlaylistsTable.isPublic]) { - return@transaction null - } - - playlistRecord(playlistId, row) - } - - fun songIds(playlistId: String): List = transaction { - PlaylistSongsTable.selectAll() - .where { PlaylistSongsTable.playlistId eq playlistId } - .orderBy(PlaylistSongsTable.position to org.jetbrains.exposed.sql.SortOrder.ASC) - .map { it[PlaylistSongsTable.songId] } - } - - 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) - - PlaylistsTable.insert { - it[PlaylistsTable.id] = id - it[owner] = userName - it[PlaylistsTable.name] = name - it[PlaylistsTable.isPublic] = isPublic - it[PlaylistsTable.kind] = kind - it[createdAt] = now - it[changedAt] = now - } - replaceSongsInternal(id, songIds) - - 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 } - .singleOrNull() ?: return@transaction false - if (row[PlaylistsTable.owner] != userName) return@transaction false - - val now = Instant.now().toString() - replaceSongsInternal(playlistId, songIds) - PlaylistsTable.update({ PlaylistsTable.id eq playlistId }) { - it[changedAt] = now - } - true - } - - fun update( - playlistId: String, - userName: String, - name: String?, - comment: String?, - isPublic: Boolean?, - addSongIds: List, - removeIndices: List, - ): Boolean = transaction { - val row = PlaylistsTable.selectAll() - .where { PlaylistsTable.id eq playlistId } - .singleOrNull() ?: return@transaction false - if (row[PlaylistsTable.owner] != userName) return@transaction false - - if (name != null || comment != null || isPublic != null) { - PlaylistsTable.update({ PlaylistsTable.id eq playlistId }) { - if (name != null) it[PlaylistsTable.name] = name - if (comment != null) it[PlaylistsTable.comment] = comment - if (isPublic != null) it[PlaylistsTable.isPublic] = isPublic - } - } - - var songs = songIdsInternal(playlistId) - if (removeIndices.isNotEmpty()) { - val toRemove = removeIndices.filter { it in songs.indices }.toSortedSet(compareByDescending { it }) - toRemove.forEach { index -> - if (index in songs.indices) songs = songs.filterIndexed { i, _ -> i != index } - } - } - songs = songs + addSongIds - - val now = Instant.now().toString() - replaceSongsInternal(playlistId, songs) - PlaylistsTable.update({ PlaylistsTable.id eq playlistId }) { - it[changedAt] = now - } - true - } - - fun delete(playlistId: String, userName: String): Boolean = transaction { - val row = PlaylistsTable.selectAll() - .where { PlaylistsTable.id eq playlistId } - .singleOrNull() ?: return@transaction false - if (row[PlaylistsTable.owner] != userName) return@transaction false - - PlaylistsTable.deleteWhere { it.run { PlaylistsTable.id eq playlistId } } - true - } - - private fun songIdsInternal(playlistId: String): List = - PlaylistSongsTable.selectAll() - .where { PlaylistSongsTable.playlistId eq playlistId } - .orderBy(PlaylistSongsTable.position to org.jetbrains.exposed.sql.SortOrder.ASC) - .map { it[PlaylistSongsTable.songId] } - - private fun replaceSongsInternal(playlistId: String, songIds: List) { - PlaylistSongsTable.deleteWhere { it.run { PlaylistSongsTable.playlistId eq playlistId } } - songIds.forEachIndexed { index, songId -> - PlaylistSongsTable.insert { - it[PlaylistSongsTable.playlistId] = playlistId - it[PlaylistSongsTable.songId] = songId - it[position] = index - } - } - } - - private fun playlistRecord(id: String, row: org.jetbrains.exposed.sql.ResultRow): PlaylistRecord { - val songs = PlaylistSongsTable - .join(SongsTable, JoinType.INNER, PlaylistSongsTable.songId, SongsTable.id) - .select(SongsTable.duration) - .where { PlaylistSongsTable.playlistId eq id } - .toList() - - return PlaylistRecord( - id = id, - name = row[PlaylistsTable.name], - 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], - changed = row[PlaylistsTable.changedAt], - ) - } -} diff --git a/src/main/kotlin/win/taptap/musicmanager/db/RadioRepository.kt b/src/main/kotlin/win/taptap/musicmanager/db/RadioRepository.kt new file mode 100644 index 0000000..70518a2 --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/db/RadioRepository.kt @@ -0,0 +1,213 @@ +package win.taptap.musicmanager.db + +import java.time.Instant +import org.jetbrains.exposed.sql.SortOrder +import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq +import org.jetbrains.exposed.sql.and +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 PlaybackSessionRecord( + val id: String, + val userName: String, + val moodId: String, + val createdAt: String, + val lastSeenAt: String, + val closedAt: String?, +) + +data class SessionItemRecord( + val position: Int, + val songId: String, + val state: String, +) + +data class AffinityRecord(val completions: Int, val skips: Int) { + /** Skips weigh double so a mood stops serving rejected tracks quickly. */ + val score: Double get() = completions - skips * 2.0 +} + +/** + * Playback sessions make likes unnecessary: every play, skip and completion is + * attributed to the mood that produced the queue, and explicit "add to mood" + * actions replace stars. + */ +object RadioRepository { + + fun createSession(userName: String, moodId: String, sessionToken: String): PlaybackSessionRecord = transaction { + val now = Instant.now().toString() + val id = "ps-" + ApiTokenRepository.hash(sessionToken).take(24) + PlaybackSessionsTable.insert { + it[PlaybackSessionsTable.id] = id + it[PlaybackSessionsTable.userName] = userName + it[PlaybackSessionsTable.moodId] = moodId + it[createdAt] = now + it[lastSeenAt] = now + } + PlaybackSessionRecord(id, userName, moodId, now, now, null) + } + + fun get(id: String, userName: String): PlaybackSessionRecord? = transaction { + PlaybackSessionsTable.selectAll() + .where { + (PlaybackSessionsTable.id eq id) and + (PlaybackSessionsTable.userName eq userName) + } + .singleOrNull() + ?.toRecord() + } + + fun touch(id: String) { + transaction { + PlaybackSessionsTable.update({ PlaybackSessionsTable.id eq id }) { + it[lastSeenAt] = Instant.now().toString() + } + } + } + + fun close(id: String, userName: String): Boolean = transaction { + val now = Instant.now().toString() + PlaybackSessionsTable.update({ + (PlaybackSessionsTable.id eq id) and + (PlaybackSessionsTable.userName eq userName) and + (PlaybackSessionsTable.closedAt.isNull()) + }) { + it[closedAt] = now + it[lastSeenAt] = now + } > 0 + } + + fun items(id: String): List = transaction { + SessionItemsTable.selectAll() + .where { SessionItemsTable.sessionId eq id } + .orderBy(SessionItemsTable.position to SortOrder.ASC) + .map { + SessionItemRecord( + position = it[SessionItemsTable.position], + songId = it[SessionItemsTable.songId], + state = it[SessionItemsTable.state], + ) + } + } + + fun queuedSongIds(id: String): Set = items(id).map { it.songId }.toSet() + + /** Appends tracks and returns their positions in the session. */ + fun append(sessionId: String, songIds: List): List = transaction { + if (songIds.isEmpty()) return@transaction emptyList() + + val session = PlaybackSessionsTable.selectAll() + .where { PlaybackSessionsTable.id eq sessionId } + .single() + var position = session[PlaybackSessionsTable.nextPosition] + val now = Instant.now().toString() + val positions = mutableListOf() + + songIds.forEach { songId -> + SessionItemsTable.insert { + it[SessionItemsTable.sessionId] = sessionId + it[SessionItemsTable.position] = position + it[SessionItemsTable.songId] = songId + it[SessionItemsTable.state] = "queued" + it[queuedAt] = now + it[updatedAt] = now + } + positions += position + position += 1 + } + + PlaybackSessionsTable.update({ PlaybackSessionsTable.id eq sessionId }) { + it[nextPosition] = position + it[lastSeenAt] = now + } + positions + } + + /** + * Applies a client playback event. Unknown songs are still recorded in the + * affinity table so manual queueing can influence later radio batches. + */ + fun recordEvent( + sessionId: String, + userName: String, + songId: String, + state: String, + ): Boolean = transaction { + val session = PlaybackSessionsTable.selectAll() + .where { + (PlaybackSessionsTable.id eq sessionId) and + (PlaybackSessionsTable.userName eq userName) + } + .singleOrNull() ?: return@transaction false + + val now = Instant.now().toString() + SessionItemsTable.update({ + (SessionItemsTable.sessionId eq sessionId) and + (SessionItemsTable.songId eq songId) + }) { + it[SessionItemsTable.state] = state + it[updatedAt] = now + } + + if (state == "completed" || state == "skipped") { + val existing = SongAffinityTable.selectAll() + .where { + (SongAffinityTable.userName eq userName) and + (SongAffinityTable.songId eq songId) + } + .singleOrNull() + + if (existing == null) { + SongAffinityTable.insert { + it[SongAffinityTable.userName] = userName + it[SongAffinityTable.songId] = songId + it[completions] = if (state == "completed") 1 else 0 + it[skips] = if (state == "skipped") 1 else 0 + it[lastEventAt] = now + } + } else { + SongAffinityTable.update({ + (SongAffinityTable.userName eq userName) and + (SongAffinityTable.songId eq songId) + }) { + if (state == "completed") it[completions] = existing[SongAffinityTable.completions] + 1 + if (state == "skipped") it[skips] = existing[SongAffinityTable.skips] + 1 + it[lastEventAt] = now + } + } + } + + PlaybackSessionsTable.update({ PlaybackSessionsTable.id eq session[PlaybackSessionsTable.id] }) { + it[lastSeenAt] = now + } + true + } + + fun affinity(userName: String, songIds: Collection): Map { + if (songIds.isEmpty()) return emptyMap() + return transaction { + SongAffinityTable.selectAll() + .where { + (SongAffinityTable.userName eq userName) and + (SongAffinityTable.songId inList songIds.toList()) + } + .associate { + it[SongAffinityTable.songId] to AffinityRecord( + completions = it[SongAffinityTable.completions], + skips = it[SongAffinityTable.skips], + ) + } + } + } + + private fun org.jetbrains.exposed.sql.ResultRow.toRecord() = PlaybackSessionRecord( + id = this[PlaybackSessionsTable.id], + userName = this[PlaybackSessionsTable.userName], + moodId = this[PlaybackSessionsTable.moodId], + createdAt = this[PlaybackSessionsTable.createdAt], + lastSeenAt = this[PlaybackSessionsTable.lastSeenAt], + closedAt = this[PlaybackSessionsTable.closedAt], + ) +} diff --git a/src/main/kotlin/win/taptap/musicmanager/db/Tables.kt b/src/main/kotlin/win/taptap/musicmanager/db/Tables.kt index 193e7ab..071152b 100644 --- a/src/main/kotlin/win/taptap/musicmanager/db/Tables.kt +++ b/src/main/kotlin/win/taptap/musicmanager/db/Tables.kt @@ -68,6 +68,7 @@ object SongsTable : Table("songs") { val relativePath = text("relative_path") val fileMtime = long("file_mtime") val createdAt = varchar("created_at", 40) + val updatedAt = varchar("updated_at", 40).default("") val searchText = text("search_text") val lyrics = text("lyrics").nullable() @@ -133,57 +134,46 @@ object BookmarksTable : Table("bookmarks") { override val primaryKey = PrimaryKey(userName, songId) } -object PlaylistsTable : Table("playlists") { +/** + * Moods are the only collection type. A mood owns seeds (permanent anchors) and + * recommendations (YT Music candidates); playback queues are generated live and + * never materialized here. + */ +object MoodsTable : Table("moods") { val id = varchar("id", 32) val owner = reference("owner", UsersTable.name, onDelete = ReferenceOption.CASCADE) val name = text("name") - val comment = text("comment").nullable() - val isPublic = bool("is_public").default(true) - val kind = varchar("kind", 16).default("user") + val description = text("description").nullable() + val query = text("query").nullable() + val genres = text("genres").default("[]") + val targetSize = integer("target_size").default(30) + val refreshHours = integer("refresh_hours").default(24) + val ytEnabled = bool("yt_enabled").default(true) + val lastDiscoveryAt = varchar("last_discovery_at", 40).nullable() val createdAt = varchar("created_at", 40) val changedAt = varchar("changed_at", 40) + val lastError = text("last_error").nullable() override val primaryKey = PrimaryKey(id) } -object PlaylistSongsTable : Table("playlist_songs") { - val playlistId = reference("playlist_id", PlaylistsTable.id, onDelete = ReferenceOption.CASCADE) - val songId = reference("song_id", SongsTable.id, onDelete = ReferenceOption.CASCADE) - val position = integer("position") - - 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 moodId = reference("mood_id", MoodsTable.id, 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) + override val primaryKey = PrimaryKey(moodId, songId) } object MoodRecommendationsTable : Table("mood_recommendations") { - val playlistId = reference("playlist_id", MoodsTable.playlistId, onDelete = ReferenceOption.CASCADE) + val moodId = reference("mood_id", MoodsTable.id, onDelete = ReferenceOption.CASCADE) val videoId = varchar("video_id", 64) val title = text("title") val artist = text("artist") + val album = text("album").nullable() val duration = integer("duration").nullable() + val thumbnail = text("thumbnail").nullable() val state = varchar("state", 16).default("new") val matchedSongId = reference( "matched_song_id", @@ -194,5 +184,60 @@ object MoodRecommendationsTable : Table("mood_recommendations") { val firstSeen = varchar("first_seen", 40) val lastSeen = varchar("last_seen", 40) - override val primaryKey = PrimaryKey(playlistId, videoId) + override val primaryKey = PrimaryKey(moodId, videoId) +} + +/** Bearer tokens are stored as hashes; the raw value only exists on the device. */ +object ApiTokensTable : Table("api_tokens") { + val id = varchar("id", 32) + val userName = reference("user_name", UsersTable.name, onDelete = ReferenceOption.CASCADE) + val tokenHash = varchar("token_hash", 64) + val deviceName = varchar("device_name", 120) + val platform = varchar("platform", 32) + val createdAt = varchar("created_at", 40) + val lastUsedAt = varchar("last_used_at", 40) + val expiresAt = varchar("expires_at", 40) + + override val primaryKey = PrimaryKey(id) +} + +object PlaybackSessionsTable : Table("playback_sessions") { + val id = varchar("id", 32) + val userName = reference("user_name", UsersTable.name, onDelete = ReferenceOption.CASCADE) + val moodId = reference("mood_id", MoodsTable.id, onDelete = ReferenceOption.CASCADE) + val nextPosition = integer("next_position").default(0) + val createdAt = varchar("created_at", 40) + val lastSeenAt = varchar("last_seen_at", 40) + val closedAt = varchar("closed_at", 40).nullable() + + override val primaryKey = PrimaryKey(id) +} + +object SessionItemsTable : Table("playback_session_items") { + val sessionId = reference("session_id", PlaybackSessionsTable.id, onDelete = ReferenceOption.CASCADE) + val position = integer("position") + val songId = reference("song_id", SongsTable.id, onDelete = ReferenceOption.CASCADE) + val state = varchar("state", 16).default("queued") + val queuedAt = varchar("queued_at", 40) + val updatedAt = varchar("updated_at", 40) + + override val primaryKey = PrimaryKey(sessionId, position) +} + +object SongAffinityTable : Table("song_affinity") { + val userName = reference("user_name", UsersTable.name, onDelete = ReferenceOption.CASCADE) + val songId = reference("song_id", SongsTable.id, onDelete = ReferenceOption.CASCADE) + val completions = integer("completions").default(0) + val skips = integer("skips").default(0) + val lastEventAt = varchar("last_event_at", 40) + + override val primaryKey = PrimaryKey(userName, songId) +} + +object LibraryTombstonesTable : Table("library_tombstones") { + val entity = varchar("entity", 20) + val entityId = varchar("entity_id", 32) + val deletedAt = varchar("deleted_at", 40) + + override val primaryKey = PrimaryKey(entity, entityId) } diff --git a/src/main/kotlin/win/taptap/musicmanager/db/UserStateRepository.kt b/src/main/kotlin/win/taptap/musicmanager/db/UserStateRepository.kt deleted file mode 100644 index 40c6263..0000000 --- a/src/main/kotlin/win/taptap/musicmanager/db/UserStateRepository.kt +++ /dev/null @@ -1,217 +0,0 @@ -package win.taptap.musicmanager.db - -import java.time.Instant -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 BookmarkRecord( - val songId: String, - val positionMs: Long, - val updatedAt: String, -) - -/** Per-user state: play counts, stars, ratings and bookmarks. */ -object UserStateRepository { - - fun scrobble(userName: String, songId: String, submission: Boolean) { - if (!submission) return - val now = Instant.now().toString() - - transaction { - val existing = UserSongStateTable.selectAll() - .where { - (UserSongStateTable.userName eq userName) and - (UserSongStateTable.songId eq songId) - } - .singleOrNull() - - if (existing == null) { - UserSongStateTable.insert { - it[UserSongStateTable.userName] = userName - it[UserSongStateTable.songId] = songId - it[playCount] = 1 - it[lastPlayedAt] = now - } - } else { - UserSongStateTable.update({ - (UserSongStateTable.userName eq userName) and - (UserSongStateTable.songId eq songId) - }) { - it[playCount] = existing[UserSongStateTable.playCount] + 1 - it[lastPlayedAt] = now - } - } - } - } - - fun setSongRating(userName: String, songId: String, rating: Int?) { - transaction { - val existing = UserSongStateTable.selectAll() - .where { - (UserSongStateTable.userName eq userName) and - (UserSongStateTable.songId eq songId) - } - .singleOrNull() - - if (existing == null) { - UserSongStateTable.insert { - it[UserSongStateTable.userName] = userName - it[UserSongStateTable.songId] = songId - it[UserSongStateTable.rating] = rating - } - } else { - UserSongStateTable.update({ - (UserSongStateTable.userName eq userName) and - (UserSongStateTable.songId eq songId) - }) { - it[UserSongStateTable.rating] = rating - } - } - } - } - - fun setItemRating(userName: String, itemType: String, itemId: String, rating: Int?) { - transaction { - val existing = UserStarsTable.selectAll() - .where { - (UserStarsTable.userName eq userName) and - (UserStarsTable.itemType eq itemType) and - (UserStarsTable.itemId eq itemId) - } - .singleOrNull() - - if (existing == null) { - UserStarsTable.insert { - it[UserStarsTable.userName] = userName - it[UserStarsTable.itemType] = itemType - it[UserStarsTable.itemId] = itemId - it[starredAt] = "" - it[UserStarsTable.rating] = rating - } - } else { - UserStarsTable.update({ - (UserStarsTable.userName eq userName) and - (UserStarsTable.itemType eq itemType) and - (UserStarsTable.itemId eq itemId) - }) { - it[UserStarsTable.rating] = rating - } - } - } - } - - fun starSong(userName: String, songId: String) { - val now = Instant.now().toString() - transaction { - val existing = UserSongStateTable.selectAll() - .where { - (UserSongStateTable.userName eq userName) and - (UserSongStateTable.songId eq songId) - } - .singleOrNull() - - if (existing == null) { - UserSongStateTable.insert { - it[UserSongStateTable.userName] = userName - it[UserSongStateTable.songId] = songId - it[starredAt] = now - } - } else { - UserSongStateTable.update({ - (UserSongStateTable.userName eq userName) and - (UserSongStateTable.songId eq songId) - }) { - it[starredAt] = now - } - } - } - } - - fun unstarSong(userName: String, songId: String) { - transaction { - UserSongStateTable.update({ - (UserSongStateTable.userName eq userName) and - (UserSongStateTable.songId eq songId) - }) { - it[starredAt] = null - } - } - } - - fun starItem(userName: String, itemType: String, itemId: String) { - val now = Instant.now().toString() - transaction { - UserStarsTable.deleteWhere { - it.run { - (UserStarsTable.userName eq userName) and - (UserStarsTable.itemType eq itemType) and - (UserStarsTable.itemId eq itemId) - } - } - UserStarsTable.insert { - it[UserStarsTable.userName] = userName - it[UserStarsTable.itemType] = itemType - it[UserStarsTable.itemId] = itemId - it[starredAt] = now - } - } - } - - fun unstarItem(userName: String, itemType: String, itemId: String) { - transaction { - UserStarsTable.deleteWhere { - it.run { - (UserStarsTable.userName eq userName) and - (UserStarsTable.itemType eq itemType) and - (UserStarsTable.itemId eq itemId) - } - } - } - } - - fun createBookmark(userName: String, songId: String, positionMs: Long) { - val now = Instant.now().toString() - transaction { - BookmarksTable.deleteWhere { - it.run { - (BookmarksTable.userName eq userName) and - (BookmarksTable.songId eq songId) - } - } - BookmarksTable.insert { - it[BookmarksTable.userName] = userName - it[BookmarksTable.songId] = songId - it[BookmarksTable.positionMs] = positionMs - it[updatedAt] = now - } - } - } - - fun deleteBookmark(userName: String, songId: String) { - transaction { - BookmarksTable.deleteWhere { - it.run { - (BookmarksTable.userName eq userName) and - (BookmarksTable.songId eq songId) - } - } - } - } - - fun bookmarks(userName: String): List = transaction { - BookmarksTable.selectAll() - .where { BookmarksTable.userName eq userName } - .orderBy(BookmarksTable.updatedAt to org.jetbrains.exposed.sql.SortOrder.DESC) - .map { - BookmarkRecord( - songId = it[BookmarksTable.songId], - positionMs = it[BookmarksTable.positionMs], - updatedAt = it[BookmarksTable.updatedAt], - ) - } - } -} diff --git a/src/main/kotlin/win/taptap/musicmanager/mood/MoodMixService.kt b/src/main/kotlin/win/taptap/musicmanager/mood/MoodMixService.kt deleted file mode 100644 index 93d7e96..0000000 --- a/src/main/kotlin/win/taptap/musicmanager/mood/MoodMixService.kt +++ /dev/null @@ -1,145 +0,0 @@ -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 deleted file mode 100644 index eabba94..0000000 --- a/src/main/kotlin/win/taptap/musicmanager/mood/MoodPins.kt +++ /dev/null @@ -1,38 +0,0 @@ -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 deleted file mode 100644 index 9d9480c..0000000 --- a/src/main/kotlin/win/taptap/musicmanager/mood/MoodService.kt +++ /dev/null @@ -1,66 +0,0 @@ -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 deleted file mode 100644 index d3ebc5c..0000000 --- a/src/main/kotlin/win/taptap/musicmanager/mood/MoodSessionTracker.kt +++ /dev/null @@ -1,45 +0,0 @@ -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/radio/RadioService.kt b/src/main/kotlin/win/taptap/musicmanager/radio/RadioService.kt new file mode 100644 index 0000000..9c71cc8 --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/radio/RadioService.kt @@ -0,0 +1,208 @@ +package win.taptap.musicmanager.radio + +import java.util.UUID +import kotlin.math.max +import kotlin.random.Random +import org.slf4j.LoggerFactory +import win.taptap.musicmanager.api.musicFolderIds +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.PlaybackSessionRecord +import win.taptap.musicmanager.db.RadioRepository +import win.taptap.musicmanager.db.SongRecord + +data class StartedSession( + val session: PlaybackSessionRecord, + val songs: List, +) + +/** + * Server-driven mood radio. + * + * A batch is a weighted sample of the mood's world: seeds are guaranteed + * candidates, related genres/artists and free-text matches shape the pool, and + * per-user completions/skips nudge the ranking. Tracks already queued in the + * session are never repeated. The client asks for more whenever its buffer is + * low, so the queue is always generated with the latest signals. + */ +class RadioService { + + private val log = LoggerFactory.getLogger(RadioService::class.java) + private val random = Random.Default + + fun start( + mood: MoodRecord, + user: UserAccount, + library: LibraryConfig, + limit: Int, + ): StartedSession { + val session = RadioRepository.createSession(user.name, mood.id, UUID.randomUUID().toString()) + val songs = generate(mood, user, library, session.id, emptySet(), limit, persist = true) + log.info("Radio session {} started for mood {} with {} tracks", session.id, mood.name, songs.size) + return StartedSession(session, songs) + } + + fun next( + mood: MoodRecord, + user: UserAccount, + library: LibraryConfig, + sessionId: String, + excluded: Set, + limit: Int, + ): List = + generate(mood, user, library, sessionId, excluded, limit, persist = true) + + /** Queue preview for the mood screen; nothing is persisted. */ + fun preview( + mood: MoodRecord, + user: UserAccount, + library: LibraryConfig, + limit: Int, + ): List = + generate(mood, user, library, sessionId = null, excluded = emptySet(), limit, persist = false) + + private fun generate( + mood: MoodRecord, + user: UserAccount, + library: LibraryConfig, + sessionId: String?, + excluded: Set, + requestedLimit: Int, + persist: Boolean, + ): List { + val limit = requestedLimit.coerceIn(1, 50) + val folders = user.musicFolderIds(library) + if (folders.isEmpty()) return emptyList() + + val sessionSongs = if (sessionId != null && persist) { + RadioRepository.queuedSongIds(sessionId) + } else { + emptySet() + } + val skip = sessionSongs + excluded + + val seeds = LibraryRepository.songsByIds( + MoodRepository.seedSongIds(mood.id), + folders, + user.name, + ) + val seedIds = seeds.map { it.id }.toSet() + val seedGenres = (seeds.flatMap { it.genres } + mood.genres) + .map { it.trim() } + .filter { it.isNotEmpty() } + .distinctBy { it.lowercase() } + val seedArtistIds = seeds.mapNotNull { it.artistId }.distinct() + val query = mood.query?.trim()?.takeIf { it.isNotEmpty() } + + val candidates = LinkedHashMap() + seeds.forEach { candidates[it.id] = it } + if (seedGenres.isNotEmpty()) { + LibraryRepository.songsByGenres(seedGenres, POOL_LIMIT, folders, user.name) + .forEach { candidates[it.id] = it } + } + if (seedArtistIds.isNotEmpty()) { + LibraryRepository.songsByArtists(seedArtistIds, POOL_LIMIT, folders, user.name) + .forEach { candidates[it.id] = it } + } + if (query != null) { + LibraryRepository.searchSongs(query, POOL_LIMIT, 0, folders, user.name) + .forEach { candidates[it.id] = it } + } + // A mood with no seeds and no filters still needs a starting point. + LibraryRepository.randomSongs( + size = POOL_LIMIT, + genre = null, + fromYear = null, + toYear = null, + folderIds = folders, + userName = user.name, + ).forEach { candidates[it.id] = it } + + candidates.keys.removeAll(skip) + + // When a session has already heard the whole mood, allow controlled replay + // instead of ending with silence. + if (candidates.size < limit) { + LibraryRepository.randomSongs( + size = max(limit * 10, 200), + genre = null, + fromYear = null, + toYear = null, + folderIds = folders, + userName = user.name, + ).forEach { song -> + if (song.id !in skip || sessionSongs.size > 200) { + candidates.putIfAbsent(song.id, song) + } + } + } + + val affinity = RadioRepository.affinity(user.name, candidates.keys) + val scored = candidates.values.map { song -> + song to score( + song = song, + seedIds = seedIds, + seedGenres = seedGenres, + seedArtistIds = seedArtistIds, + query = query, + affinity = affinity[song.id]?.score ?: 0.0, + ) + } + + val picks = pickDiverse(scored, limit) + if (persist && sessionId != null && picks.isNotEmpty()) { + RadioRepository.append(sessionId, picks.map { it.id }) + } + return picks + } + + private fun score( + song: SongRecord, + seedIds: Set, + seedGenres: List, + seedArtistIds: List, + query: String?, + affinity: Double, + ): Double { + var score = random.nextDouble(0.0, 2.0) + if (song.id in seedIds) score += 10.0 + if (song.artistId != null && song.artistId in seedArtistIds) score += 3.0 + score += song.genres.count { candidate -> + seedGenres.any { it.equals(candidate, ignoreCase = true) } + } * 1.5 + if (query != null && song.title.contains(query, ignoreCase = true)) score += 2.0 + score += affinity.coerceIn(-6.0, 6.0) + return score + } + + /** + * Picks the best remaining candidate, preferring a different artist than the + * previous track so a batch does not become one album on repeat. + */ + private fun pickDiverse( + scored: List>, + limit: Int, + ): List { + val remaining = scored + .sortedWith(compareByDescending> { it.second }) + .toMutableList() + val picked = ArrayList(limit) + var lastArtist: String? = null + + while (picked.size < limit && remaining.isNotEmpty()) { + val different = remaining.indexOfFirst { it.first.displayArtist != lastArtist } + val index = if (different >= 0) different else 0 + val song = remaining.removeAt(index).first + picked += song + lastArtist = song.displayArtist + } + return picked + } + + private companion object { + const val POOL_LIMIT = 400 + } +} diff --git a/src/main/kotlin/win/taptap/musicmanager/subsonic/PlayQueueStore.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/PlayQueueStore.kt deleted file mode 100644 index ea56190..0000000 --- a/src/main/kotlin/win/taptap/musicmanager/subsonic/PlayQueueStore.kt +++ /dev/null @@ -1,33 +0,0 @@ -package win.taptap.musicmanager.subsonic - -import java.time.Instant -import java.util.concurrent.ConcurrentHashMap - -data class PlayQueueState( - val songIds: List, - val currentIndex: Int, - val positionMs: Long, - val changed: String, - val changedBy: String, -) - -/** - * Server-side play queue per user. Kept in memory: losing it on restart only means - * clients restore their local queue instead, which is acceptable for the MVP. - */ -object PlayQueueStore { - - private val queues = ConcurrentHashMap() - - fun save(userName: String, songIds: List, currentIndex: Int, positionMs: Long) { - queues[userName] = PlayQueueState( - songIds = songIds, - currentIndex = currentIndex.coerceIn(0, (songIds.size - 1).coerceAtLeast(0)), - positionMs = positionMs.coerceAtLeast(0), - changed = Instant.now().toString(), - changedBy = userName, - ) - } - - fun get(userName: String): PlayQueueState? = queues[userName] -} diff --git a/src/main/kotlin/win/taptap/musicmanager/subsonic/SubsonicAuth.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/SubsonicAuth.kt deleted file mode 100644 index 64a270c..0000000 --- a/src/main/kotlin/win/taptap/musicmanager/subsonic/SubsonicAuth.kt +++ /dev/null @@ -1,57 +0,0 @@ -package win.taptap.musicmanager.subsonic - -import io.ktor.http.Parameters -import java.security.MessageDigest -import win.taptap.musicmanager.config.UserAccount -import win.taptap.musicmanager.config.UsersConfig - -/** - * Subsonic authentication. - * - * Token auth is `md5(password + salt)`; password auth accepts plaintext or the - * `enc:` hex encoding. The server therefore needs the plaintext password in memory, - * but never persists it. - */ -class SubsonicAuthenticator(private val users: UsersConfig) { - - fun authenticate(parameters: Parameters): UserAccount? { - val userName = parameters["u"] ?: return null - val user = users.byName(userName) ?: return null - - val token = parameters["t"] - val salt = parameters["s"] - if (!token.isNullOrEmpty() && !salt.isNullOrEmpty()) { - return if (constantTimeEquals(token, md5Hex(user.password + salt))) user else null - } - - val password = parameters["p"] ?: return null - val candidate = if (password.startsWith("enc:")) { - hexToBytes(password.removePrefix("enc:"))?.toString(Charsets.UTF_8) ?: return null - } else { - password - } - - return if (constantTimeEquals(candidate, user.password)) user else null - } - - private fun constantTimeEquals(left: String, right: String): Boolean = - MessageDigest.isEqual(left.toByteArray(Charsets.UTF_8), right.toByteArray(Charsets.UTF_8)) - - private fun hexToBytes(hex: String): ByteArray? { - if (hex.length % 2 != 0) return null - return try { - ByteArray(hex.length / 2) { index -> - hex.substring(index * 2, index * 2 + 2).toInt(16).toByte() - } - } catch (_: NumberFormatException) { - null - } - } - - companion object { - fun md5Hex(value: String): String { - val digest = MessageDigest.getInstance("MD5").digest(value.toByteArray(Charsets.UTF_8)) - return digest.joinToString("") { "%02x".format(it) } - } - } -} diff --git a/src/main/kotlin/win/taptap/musicmanager/subsonic/SubsonicResponse.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/SubsonicResponse.kt deleted file mode 100644 index 51b77cf..0000000 --- a/src/main/kotlin/win/taptap/musicmanager/subsonic/SubsonicResponse.kt +++ /dev/null @@ -1,51 +0,0 @@ -package win.taptap.musicmanager.subsonic - -import io.ktor.server.application.ApplicationCall -import io.ktor.server.response.respond -import kotlinx.serialization.json.JsonObject -import kotlinx.serialization.json.buildJsonObject -import kotlinx.serialization.json.put - -/** - * The OpenSubsonic JSON envelope. Every endpoint, including errors, responds with - * HTTP 200 and this root object. - */ -object SubsonicEnvelope { - - const val API_VERSION = "1.16.1" - const val SERVER_TYPE = "musicmanager" - const val SERVER_VERSION = "0.1.0" - - fun ok(payload: JsonObject = JsonObject(emptyMap())): JsonObject = buildJsonObject { - put("subsonic-response", buildJsonObject { - put("status", "ok") - put("version", API_VERSION) - put("type", SERVER_TYPE) - put("serverVersion", SERVER_VERSION) - put("openSubsonic", true) - payload.forEach { (key, value) -> put(key, value) } - }) - } - - fun error(code: Int, message: String): JsonObject = buildJsonObject { - put("subsonic-response", buildJsonObject { - put("status", "failed") - put("version", API_VERSION) - put("type", SERVER_TYPE) - put("serverVersion", SERVER_VERSION) - put("openSubsonic", true) - put("error", buildJsonObject { - put("code", code) - put("message", message) - }) - }) - } -} - -suspend fun ApplicationCall.respondSubsonic(payload: JsonObject = JsonObject(emptyMap())) { - respond(SubsonicEnvelope.ok(payload)) -} - -suspend fun ApplicationCall.respondSubsonicError(code: Int, message: String) { - respond(SubsonicEnvelope.error(code, message)) -} diff --git a/src/main/kotlin/win/taptap/musicmanager/subsonic/models/JsonModels.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/models/JsonModels.kt deleted file mode 100644 index 0082b28..0000000 --- a/src/main/kotlin/win/taptap/musicmanager/subsonic/models/JsonModels.kt +++ /dev/null @@ -1,172 +0,0 @@ -package win.taptap.musicmanager.subsonic.models - -import kotlinx.serialization.json.JsonArray -import kotlinx.serialization.json.JsonObject -import kotlinx.serialization.json.JsonPrimitive -import kotlinx.serialization.json.add -import kotlinx.serialization.json.buildJsonArray -import kotlinx.serialization.json.buildJsonObject -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 - -const val IGNORED_ARTICLES = "The El La Los Las Le Les" - -fun songJson(song: SongRecord): JsonObject = buildJsonObject { - put("id", song.id) - put("parent", song.albumId) - put("isDir", false) - put("title", song.title) - put("album", song.albumName) - put("artist", song.artistName) - put("displayArtist", song.displayArtist) - song.trackNumber?.let { put("track", it) } - song.year?.let { put("year", it) } - song.genres.firstOrNull()?.let { put("genre", it) } - song.coverArt?.let { put("coverArt", it) } - put("size", song.size) - put("contentType", song.contentType) - put("suffix", song.suffix) - put("duration", song.duration) - put("bitRate", song.bitRate) - put("path", song.relativePath) - put("isVideo", false) - put("type", "music") - put("albumId", song.albumId) - song.artistId?.let { put("artistId", it) } - put("discNumber", song.discNumber) - put("created", song.created) - put("playCount", song.playCount) - song.lastPlayedAt?.let { put("played", it) } - song.starredAt?.let { put("starred", it) } - song.rating?.let { put("userRating", it) } - put("artists", buildJsonArray { - song.artists.forEach { artist -> - add(buildJsonObject { - put("id", artist.id) - put("name", artist.name) - }) - } - }) - put("genres", stringArray(song.genres)) -} - -fun albumJson(album: AlbumRecord, songs: List? = null): JsonObject = buildJsonObject { - put("id", album.id) - put("name", album.name) - album.artistName?.let { put("artist", it) } - album.artistId?.let { put("artistId", it) } - album.coverArt?.let { put("coverArt", it) } - put("songCount", album.songCount) - put("duration", album.duration) - put("playCount", album.playCount) - put("created", album.created) - album.year?.let { put("year", it) } - album.genres.firstOrNull()?.let { put("genre", it) } - album.starredAt?.let { put("starred", it) } - album.rating?.let { put("userRating", it) } - put("genres", stringArray(album.genres)) - - songs?.let { list -> - put("song", buildJsonArray { list.forEach { add(songJson(it)) } }) - } -} - -fun artistJson(artist: ArtistRecord, albums: List? = null): JsonObject = buildJsonObject { - put("id", artist.id) - put("name", artist.name) - put("albumCount", artist.albumCount) - put("sortName", artist.sortName) - artist.starredAt?.let { put("starred", it) } - artist.rating?.let { put("userRating", it) } - - albums?.let { list -> - put("album", buildJsonArray { list.forEach { add(albumJson(it)) } }) - } -} - -fun artistIndexArray(artists: List): JsonArray { - val groups = artists.groupBy { indexLetter(it.sortName) } - val keys = groups.keys.sortedWith(compareBy { if (it == "#") "\uFFFF" else it }) - - return buildJsonArray { - keys.forEach { key -> - add(buildJsonObject { - put("name", key) - put("artist", buildJsonArray { - groups.getValue(key) - .sortedBy { IdGenerator.normalize(it.sortName) } - .forEach { add(artistJson(it)) } - }) - }) - } - } -} - -fun playlistJson(playlist: PlaylistRecord, songs: List? = null): JsonObject = buildJsonObject { - put("id", playlist.id) - put("name", playlist.name) - playlist.comment?.let { put("comment", it) } - put("owner", playlist.owner) - put("public", playlist.isPublic) - put("songCount", playlist.songCount) - put("duration", playlist.duration) - put("created", playlist.created) - put("changed", playlist.changed) - - songs?.let { list -> - put("entry", buildJsonArray { list.forEach { add(songJson(it)) } }) - } -} - -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) - put("albumCount", genre.albumCount) -} - -private fun indexLetter(sortName: String): String { - val first = IdGenerator.normalize(sortName).firstOrNull() ?: return "#" - return if (first.isLetter()) first.uppercaseChar().toString() else "#" -} - -private fun stringArray(values: List): JsonArray = buildJsonArray { - values.forEach { add(JsonPrimitive(it)) } -} diff --git a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/BrowsingRoutes.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/BrowsingRoutes.kt deleted file mode 100644 index 338284e..0000000 --- a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/BrowsingRoutes.kt +++ /dev/null @@ -1,443 +0,0 @@ -package win.taptap.musicmanager.subsonic.routes - -import io.ktor.http.Parameters -import io.ktor.server.application.ApplicationCall -import io.ktor.server.routing.Route -import kotlinx.serialization.json.buildJsonArray -import kotlinx.serialization.json.buildJsonObject -import kotlinx.serialization.json.put -import win.taptap.musicmanager.config.LibraryConfig -import win.taptap.musicmanager.config.UsersConfig -import win.taptap.musicmanager.db.AlbumRecord -import win.taptap.musicmanager.db.LibraryRepository -import win.taptap.musicmanager.subsonic.models.IGNORED_ARTICLES -import win.taptap.musicmanager.subsonic.models.albumJson -import win.taptap.musicmanager.subsonic.models.artistIndexArray -import win.taptap.musicmanager.subsonic.models.artistJson -import win.taptap.musicmanager.subsonic.models.genreJson -import win.taptap.musicmanager.subsonic.models.songJson -import win.taptap.musicmanager.subsonic.respondSubsonic -import win.taptap.musicmanager.subsonic.respondSubsonicError - -fun Route.browsingRoutes(users: UsersConfig, library: LibraryConfig) { - - subsonicEndpoint(users, "/getMusicFolders") { call, user -> - val visible = user.visibleFolderIds(library) - call.respondSubsonic( - buildJsonObject { - put("musicFolders", buildJsonObject { - put("musicFolder", buildJsonArray { - library.folders - .filter { it.id in visible } - .sortedBy { it.id } - .forEach { folder -> - add(buildJsonObject { - put("id", folder.id) - put("name", folder.name) - }) - } - }) - }) - }, - ) - } - - subsonicEndpoint(users, "/getIndexes") { call, user -> - val artists = LibraryRepository.artists(user.visibleFolderIds(library), user.name) - call.respondSubsonic( - buildJsonObject { - put("indexes", buildJsonObject { - put("ignoredArticles", IGNORED_ARTICLES) - put("lastModified", 0) - put("index", artistIndexArray(artists)) - }) - }, - ) - } - - subsonicEndpoint(users, "/getArtists") { call, user -> - val artists = LibraryRepository.artists(user.visibleFolderIds(library), user.name) - call.respondSubsonic( - buildJsonObject { - put("artists", buildJsonObject { - put("ignoredArticles", IGNORED_ARTICLES) - put("index", artistIndexArray(artists)) - }) - }, - ) - } - - subsonicEndpoint(users, "/getArtist") { call, user -> - val id = call.subsonicParams()["id"] - if (id.isNullOrBlank()) { - call.respondSubsonicError(10, "Required parameter is missing: id") - return@subsonicEndpoint - } - - val folders = user.visibleFolderIds(library) - val artist = LibraryRepository.artist(id, folders, user.name) - if (artist == null) { - call.respondSubsonicError(70, "Artist not found") - return@subsonicEndpoint - } - - val albums = LibraryRepository.albumsForArtist(id, folders, user.name) - call.respondSubsonic(buildJsonObject { put("artist", artistJson(artist, albums)) }) - } - - subsonicEndpoint(users, "/getAlbum") { call, user -> - val id = call.subsonicParams()["id"] - if (id.isNullOrBlank()) { - call.respondSubsonicError(10, "Required parameter is missing: id") - return@subsonicEndpoint - } - - val folders = user.visibleFolderIds(library) - val album = LibraryRepository.album(id, folders, user.name) - if (album == null) { - call.respondSubsonicError(70, "Album not found") - return@subsonicEndpoint - } - - val songs = LibraryRepository.albumSongs(id, folders, user.name) - call.respondSubsonic(buildJsonObject { put("album", albumJson(album, songs)) }) - } - - subsonicEndpoint(users, "/getSong") { call, user -> - val id = call.subsonicParams()["id"] - if (id.isNullOrBlank()) { - call.respondSubsonicError(10, "Required parameter is missing: id") - return@subsonicEndpoint - } - - val song = LibraryRepository.song(id, user.visibleFolderIds(library), user.name) - if (song == null) { - call.respondSubsonicError(70, "Song not found") - return@subsonicEndpoint - } - - call.respondSubsonic(buildJsonObject { put("song", songJson(song)) }) - } - - subsonicEndpoint(users, "/getMusicDirectory") { call, user -> - val parameters = call.subsonicParams() - val id = parameters["id"] - if (id.isNullOrBlank()) { - call.respondSubsonicError(10, "Required parameter is missing: id") - return@subsonicEndpoint - } - - val folders = user.effectiveFolderIds(library, parameters["musicFolderId"]) - if (id.startsWith("ar-")) { - val artist = LibraryRepository.artist(id, folders, user.name) - if (artist == null) { - call.respondSubsonicError(70, "Artist not found") - return@subsonicEndpoint - } - - val albums = LibraryRepository.albumsForArtist(id, folders, user.name) - call.respondSubsonic( - buildJsonObject { - put("directory", buildJsonObject { - put("id", artist.id) - put("title", artist.name) - put("child", buildJsonArray { - albums.forEach { add(albumDirectoryJson(it, artist.id)) } - }) - }) - }, - ) - return@subsonicEndpoint - } - - if (id.startsWith("al-")) { - val album = LibraryRepository.album(id, folders, user.name) - if (album == null) { - call.respondSubsonicError(70, "Album not found") - return@subsonicEndpoint - } - - val songs = LibraryRepository.albumSongs(id, folders, user.name) - call.respondSubsonic( - buildJsonObject { - put("directory", buildJsonObject { - put("id", album.id) - put("title", album.name) - album.artistName?.let { put("artist", it) } - album.coverArt?.let { put("coverArt", it) } - put("child", buildJsonArray { songs.forEach { add(songJson(it)) } }) - }) - }, - ) - return@subsonicEndpoint - } - - val folderId = id.toIntOrNull() - if (folderId == null || folderId !in folders) { - call.respondSubsonicError(70, "Directory not found") - return@subsonicEndpoint - } - - val folder = library.byId(folderId) ?: run { - call.respondSubsonicError(70, "Directory not found") - return@subsonicEndpoint - } - val albums = LibraryRepository.albumList( - type = "alphabeticalByName", - size = 10_000, - offset = 0, - fromYear = null, - toYear = null, - genre = null, - folderIds = setOf(folderId), - userName = user.name, - ) - - call.respondSubsonic( - buildJsonObject { - put("directory", buildJsonObject { - put("id", folderId) - put("title", folder.name) - put("child", buildJsonArray { - albums.forEach { add(albumDirectoryJson(it, folderId.toString())) } - }) - }) - }, - ) - } - - val albumListTypes = setOf( - "newest", - "recent", - "frequent", - "random", - "alphabeticalByName", - "alphabeticalByArtist", - "starred", - "byYear", - "byGenre", - ) - - for (endpoint in listOf("/getAlbumList2", "/getAlbumList")) { - subsonicEndpoint(users, endpoint) { call, user -> - val parameters = call.subsonicParams() - val type = parameters["type"] ?: "newest" - if (type !in albumListTypes) { - call.respondSubsonicError(10, "Invalid album list type: $type") - return@subsonicEndpoint - } - - val size = parameters.intParam("size", 10) - val offset = parameters.intParam("offset", 0) - val fromYear = parameters["fromYear"]?.toIntOrNull() - val toYear = parameters["toYear"]?.toIntOrNull() - val genre = parameters["genre"] - - val albums = LibraryRepository.albumList( - type = type, - size = size, - offset = offset, - fromYear = fromYear, - toYear = toYear, - genre = genre, - folderIds = user.effectiveFolderIds(library, parameters["musicFolderId"]), - userName = user.name, - ) - - val key = if (endpoint == "/getAlbumList2") "albumList2" else "albumList" - call.respondSubsonic( - buildJsonObject { - put(key, buildJsonObject { - put("album", buildJsonArray { albums.forEach { add(albumJson(it)) } }) - }) - }, - ) - } - } - - subsonicEndpoint(users, "/getRandomSongs") { call, user -> - val parameters = call.subsonicParams() - val songs = LibraryRepository.randomSongs( - size = parameters.intParam("size", 10), - genre = parameters["genre"], - fromYear = parameters["fromYear"]?.toIntOrNull(), - toYear = parameters["toYear"]?.toIntOrNull(), - folderIds = user.effectiveFolderIds(library, parameters["musicFolderId"]), - userName = user.name, - ) - - call.respondSubsonic( - buildJsonObject { - put("randomSongs", buildJsonObject { - put("song", buildJsonArray { songs.forEach { add(songJson(it)) } }) - }) - }, - ) - } - - subsonicEndpoint(users, "/getGenres") { call, user -> - val parameters = call.subsonicParams() - val genres = LibraryRepository.genres( - user.effectiveFolderIds(library, parameters["musicFolderId"]), - ) - - call.respondSubsonic( - buildJsonObject { - put("genres", buildJsonObject { - put("genre", buildJsonArray { genres.forEach { add(genreJson(it)) } }) - }) - }, - ) - } - - subsonicEndpoint(users, "/getSongsByGenre") { call, user -> - val parameters = call.subsonicParams() - val genre = parameters["genre"] - if (genre.isNullOrBlank()) { - call.respondSubsonicError(10, "Required parameter is missing: genre") - return@subsonicEndpoint - } - - val songs = LibraryRepository.songsByGenre( - genre = genre, - size = parameters.intParam("count", 10), - offset = parameters.intParam("offset", 0), - folderIds = user.effectiveFolderIds(library, parameters["musicFolderId"]), - userName = user.name, - ) - - call.respondSubsonic( - buildJsonObject { - put("songsByGenre", buildJsonObject { - put("song", buildJsonArray { songs.forEach { add(songJson(it)) } }) - }) - }, - ) - } - - for (endpoint in listOf("/getStarred2", "/getStarred")) { - subsonicEndpoint(users, endpoint) { call, user -> - val parameters = call.subsonicParams() - val starred = LibraryRepository.starred( - userName = user.name, - folderIds = user.effectiveFolderIds(library, parameters["musicFolderId"]), - ) - - val key = if (endpoint == "/getStarred2") "starred2" else "starred" - call.respondSubsonic( - buildJsonObject { - put(key, buildJsonObject { - put("artist", buildJsonArray { starred.artists.forEach { add(artistJson(it)) } }) - put("album", buildJsonArray { starred.albums.forEach { add(albumJson(it)) } }) - put("song", buildJsonArray { starred.songs.forEach { add(songJson(it)) } }) - }) - }, - ) - } - } - - // No external metadata provider yet, but clients expect a valid empty response. - for (endpoint in listOf("/getArtistInfo2", "/getArtistInfo")) { - subsonicEndpoint(users, endpoint) { call, _ -> - val key = if (endpoint == "/getArtistInfo2") "artistInfo2" else "artistInfo" - call.respondSubsonic( - buildJsonObject { - put(key, buildJsonObject { - put("biography", "") - put("similarArtist", buildJsonArray { }) - }) - }, - ) - } - } - - for (endpoint in listOf("/getAlbumInfo2", "/getAlbumInfo")) { - subsonicEndpoint(users, endpoint) { call, _ -> - val key = if (endpoint == "/getAlbumInfo2") "albumInfo2" else "albumInfo" - call.respondSubsonic(buildJsonObject { put(key, buildJsonObject { }) }) - } - } - - for (endpoint in listOf("/getSimilarSongs2", "/getSimilarSongs")) { - subsonicEndpoint(users, endpoint) { call, _ -> - val key = if (endpoint == "/getSimilarSongs2") "similarSongs2" else "similarSongs" - call.respondSubsonic( - buildJsonObject { - put(key, buildJsonObject { put("song", buildJsonArray { }) }) - }, - ) - } - } - - subsonicEndpoint(users, "/getTopSongs") { call, _ -> - call.respondSubsonic( - buildJsonObject { - put("topSongs", buildJsonObject { put("song", buildJsonArray { }) }) - }, - ) - } - - subsonicEndpoint(users, "/search3") { call, user -> - val parameters = call.subsonicParams() - val query = parameters["query"].orEmpty() - val folders = user.effectiveFolderIds(library, parameters["musicFolderId"]) - val all = query.isBlank() || query == "*" - - val artistCount = parameters.intParam("artistCount", 20) - val artistOffset = parameters.intParam("artistOffset", 0, minimum = 0) - val albumCount = parameters.intParam("albumCount", 20) - val albumOffset = parameters.intParam("albumOffset", 0, minimum = 0) - val songCount = parameters.intParam("songCount", 20) - val songOffset = parameters.intParam("songOffset", 0, minimum = 0) - - val artists = if (all) { - LibraryRepository.artists(folders, user.name) - .drop(artistOffset) - .take(artistCount) - } else { - LibraryRepository.searchArtists(query, artistCount, artistOffset, folders, user.name) - } - val albums = if (all) { - LibraryRepository.allAlbums(albumCount, albumOffset, folders, user.name) - } else { - LibraryRepository.searchAlbums(query, albumCount, albumOffset, folders, user.name) - } - val songs = if (all) { - LibraryRepository.allSongs(songCount, songOffset, folders, user.name) - } else { - LibraryRepository.searchSongs(query, songCount, songOffset, folders, user.name) - } - - call.respondSubsonic( - buildJsonObject { - put("searchResult3", buildJsonObject { - put("artist", buildJsonArray { artists.forEach { add(artistJson(it)) } }) - put("album", buildJsonArray { albums.forEach { add(albumJson(it)) } }) - put("song", buildJsonArray { songs.forEach { add(songJson(it)) } }) - }) - }, - ) - } -} - -private fun albumDirectoryJson(album: AlbumRecord, parentId: String) = buildJsonObject { - put("id", album.id) - put("parent", parentId) - put("title", album.name) - put("isDir", true) - put("album", album.name) - album.artistName?.let { put("artist", it) } - album.artistId?.let { put("artistId", it) } - album.coverArt?.let { put("coverArt", it) } - put("songCount", album.songCount) - put("duration", album.duration) - put("created", album.created) - album.year?.let { put("year", it) } - album.genres.firstOrNull()?.let { put("genre", it) } -} - -private fun Parameters.intParam(name: String, default: Int, minimum: Int = 0): Int { - val raw = this[name] ?: return default - val parsed = raw.toIntOrNull() ?: return default - return parsed.coerceIn(minimum, 500) -} diff --git a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/InteractionRoutes.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/InteractionRoutes.kt deleted file mode 100644 index bfa3a12..0000000 --- a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/InteractionRoutes.kt +++ /dev/null @@ -1,264 +0,0 @@ -package win.taptap.musicmanager.subsonic.routes - -import io.ktor.server.routing.Route -import kotlinx.serialization.json.add -import kotlinx.serialization.json.buildJsonArray -import kotlinx.serialization.json.buildJsonObject -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.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 - -/** Per-user interaction: scrobbling, stars, ratings, bookmarks and lyrics. */ -fun Route.interactionRoutes(users: UsersConfig, library: LibraryConfig) { - - subsonicEndpoint(users, "/scrobble") { call, user -> - val parameters = call.subsonicParams() - val ids = parameters.getAll("id").orEmpty().filter { it.isNotBlank() } - if (ids.isEmpty()) { - call.respondSubsonicError(10, "Required parameter is missing: id") - return@subsonicEndpoint - } - - val submission = parameters["submission"]?.toBooleanStrictOrNull() ?: true - val folders = user.effectiveFolderIds(library, parameters["musicFolderId"]) - - for (id in ids) { - if (LibraryRepository.song(id, folders, user.name) == null) { - call.respondSubsonicError(70, "Song not found") - return@subsonicEndpoint - } - UserStateRepository.scrobble(user.name, id, submission) - } - MoodSessionTracker.touch(user.name) - - call.respondSubsonic() - } - - subsonicEndpoint(users, "/star") { call, user -> - val parameters = call.subsonicParams() - val folders = user.effectiveFolderIds(library, parameters["musicFolderId"]) - - val songIds = parameters.getAll("id").orEmpty().filter { it.isNotBlank() } - val albumIds = parameters.getAll("albumId").orEmpty().filter { it.isNotBlank() } - val artistIds = parameters.getAll("artistId").orEmpty().filter { it.isNotBlank() } - - if (songIds.isEmpty() && albumIds.isEmpty() && artistIds.isEmpty()) { - call.respondSubsonicError(10, "Required parameter is missing: id, albumId or artistId") - return@subsonicEndpoint - } - - if (!validateVisible(songIds, albumIds, artistIds, folders, user.name)) { - call.respondSubsonicError(70, "Item not found") - return@subsonicEndpoint - } - - 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) } - - call.respondSubsonic() - } - - subsonicEndpoint(users, "/unstar") { call, user -> - val parameters = call.subsonicParams() - val folders = user.effectiveFolderIds(library, parameters["musicFolderId"]) - - val songIds = parameters.getAll("id").orEmpty().filter { it.isNotBlank() } - val albumIds = parameters.getAll("albumId").orEmpty().filter { it.isNotBlank() } - val artistIds = parameters.getAll("artistId").orEmpty().filter { it.isNotBlank() } - - if (songIds.isEmpty() && albumIds.isEmpty() && artistIds.isEmpty()) { - call.respondSubsonicError(10, "Required parameter is missing: id, albumId or artistId") - return@subsonicEndpoint - } - - if (!validateVisible(songIds, albumIds, artistIds, folders, user.name)) { - call.respondSubsonicError(70, "Item not found") - return@subsonicEndpoint - } - - 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) } - - call.respondSubsonic() - } - - subsonicEndpoint(users, "/setRating") { call, user -> - val parameters = call.subsonicParams() - val id = parameters["id"] - if (id.isNullOrBlank()) { - call.respondSubsonicError(10, "Required parameter is missing: id") - return@subsonicEndpoint - } - - val rawRating = parameters["rating"] - val rating = rawRating?.toIntOrNull() - if (rating == null || rating !in 0..5) { - call.respondSubsonicError(10, "Required parameter is missing or invalid: rating") - return@subsonicEndpoint - } - - val folders = user.effectiveFolderIds(library, parameters["musicFolderId"]) - val storedRating = rating.takeIf { it > 0 } - - when { - id.startsWith("sg-") -> { - if (LibraryRepository.song(id, folders, user.name) == null) { - call.respondSubsonicError(70, "Song not found") - return@subsonicEndpoint - } - UserStateRepository.setSongRating(user.name, id, storedRating) - } - id.startsWith("al-") -> { - if (LibraryRepository.album(id, folders, user.name) == null) { - call.respondSubsonicError(70, "Album not found") - return@subsonicEndpoint - } - UserStateRepository.setItemRating(user.name, "album", id, storedRating) - } - id.startsWith("ar-") -> { - if (LibraryRepository.artist(id, folders, user.name) == null) { - call.respondSubsonicError(70, "Artist not found") - return@subsonicEndpoint - } - UserStateRepository.setItemRating(user.name, "artist", id, storedRating) - } - else -> { - call.respondSubsonicError(70, "Item not found") - return@subsonicEndpoint - } - } - - call.respondSubsonic() - } - - subsonicEndpoint(users, "/getBookmarks") { call, user -> - val folders = user.effectiveFolderIds(library, call.subsonicParams()["musicFolderId"]) - - val bookmarks = UserStateRepository.bookmarks(user.name).mapNotNull { bookmark -> - val song = LibraryRepository.song(bookmark.songId, folders, user.name) ?: return@mapNotNull null - buildJsonObject { - put("position", bookmark.positionMs) - put("username", user.name) - put("created", bookmark.updatedAt) - put("changed", bookmark.updatedAt) - put("entry", songJson(song)) - } - } - - call.respondSubsonic( - buildJsonObject { - put("bookmarks", buildJsonObject { - put("bookmark", buildJsonArray { bookmarks.forEach { add(it) } }) - }) - }, - ) - } - - subsonicEndpoint(users, "/createBookmark") { call, user -> - val parameters = call.subsonicParams() - val id = parameters["id"] - if (id.isNullOrBlank()) { - call.respondSubsonicError(10, "Required parameter is missing: id") - return@subsonicEndpoint - } - - val position = parameters["position"]?.toLongOrNull() - if (position == null || position < 0) { - call.respondSubsonicError(10, "Required parameter is missing or invalid: position") - return@subsonicEndpoint - } - - if (LibraryRepository.song(id, user.effectiveFolderIds(library, parameters["musicFolderId"]), user.name) == null) { - call.respondSubsonicError(70, "Song not found") - return@subsonicEndpoint - } - - UserStateRepository.createBookmark(user.name, id, position) - call.respondSubsonic() - } - - subsonicEndpoint(users, "/deleteBookmark") { call, user -> - val id = call.subsonicParams()["id"] - if (id.isNullOrBlank()) { - call.respondSubsonicError(10, "Required parameter is missing: id") - return@subsonicEndpoint - } - - UserStateRepository.deleteBookmark(user.name, id) - call.respondSubsonic() - } - - subsonicEndpoint(users, "/getLyricsBySongId") { call, user -> - val parameters = call.subsonicParams() - val id = parameters["id"] - if (id.isNullOrBlank()) { - call.respondSubsonicError(10, "Required parameter is missing: id") - return@subsonicEndpoint - } - - val folders = user.effectiveFolderIds(library, parameters["musicFolderId"]) - val song = LibraryRepository.song(id, folders, user.name) - if (song == null) { - call.respondSubsonicError(70, "Song not found") - return@subsonicEndpoint - } - - val lyrics = LibraryRepository.lyrics(id, folders) - val lines = lyrics.orEmpty() - .lines() - .map { it.trim() } - .filter { it.isNotEmpty() } - - call.respondSubsonic( - buildJsonObject { - if (lines.isEmpty()) { - put("lyricsList", buildJsonObject { }) - } else { - put("lyricsList", buildJsonObject { - put("structuredLyrics", buildJsonArray { - add(buildJsonObject { - put("displayArtist", song.displayArtist) - put("displayTitle", song.title) - put("lang", "") - put("synced", false) - put("line", buildJsonArray { - lines.forEach { line -> - add(buildJsonObject { put("value", line) }) - } - }) - }) - }) - }) - } - }, - ) - } -} - -private fun validateVisible( - songIds: List, - albumIds: List, - artistIds: List, - folderIds: Set, - userName: String, -): Boolean { - if (songIds.any { LibraryRepository.song(it, folderIds, userName) == null }) return false - if (albumIds.any { LibraryRepository.album(it, folderIds, userName) == null }) return false - if (artistIds.any { LibraryRepository.artist(it, folderIds, userName) == null }) return false - return true -} diff --git a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/MediaRoutes.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/MediaRoutes.kt deleted file mode 100644 index a383bc8..0000000 --- a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/MediaRoutes.kt +++ /dev/null @@ -1,168 +0,0 @@ -package win.taptap.musicmanager.subsonic.routes - -import io.ktor.http.ContentType -import io.ktor.http.HttpHeaders -import io.ktor.http.HttpStatusCode -import io.ktor.server.response.respond -import io.ktor.server.response.respondFile -import io.ktor.server.response.respondOutputStream -import io.ktor.server.routing.Route -import java.net.URLEncoder -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext -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 - -private val log = LoggerFactory.getLogger("win.taptap.musicmanager.MediaRoutes") - -fun Route.mediaRoutes( - users: UsersConfig, - library: LibraryConfig, - coverArtService: CoverArtService, - transcoder: FfmpegTranscoder, -) { - - subsonicEndpoint(users, "/stream") { call, user -> - val parameters = call.subsonicParams() - val id = parameters["id"] - if (id.isNullOrBlank()) { - call.respondSubsonicError(10, "Required parameter is missing: id") - return@subsonicEndpoint - } - - val rawMaxBitRate = parameters["maxBitRate"] - val maxBitRate = rawMaxBitRate?.toIntOrNull() - if (rawMaxBitRate != null && (maxBitRate == null || maxBitRate < 0)) { - call.respondSubsonicError(10, "Invalid maxBitRate") - return@subsonicEndpoint - } - - val rawTimeOffset = parameters["timeOffset"] - val timeOffset = rawTimeOffset?.toIntOrNull() - if (rawTimeOffset != null && (timeOffset == null || timeOffset < 0)) { - call.respondSubsonicError(10, "Invalid timeOffset") - return@subsonicEndpoint - } - val offset = timeOffset ?: 0 - val format = parameters["format"] - - val resolved = LibraryRepository.resolveSong( - id, - user.visibleFolderIds(library), - user.name, - library, - ) - if (resolved == null) { - 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()) - return@subsonicEndpoint - } - - val process = try { - transcoder.start(resolved.file, maxBitRate, offset) - } catch (e: Exception) { - log.error("Failed to start ffmpeg for {}", resolved.file, e) - call.respondSubsonicError(0, "Transcoding failed") - return@subsonicEndpoint - } - - try { - call.response.headers.append(HttpHeaders.CacheControl, "no-store") - call.respondOutputStream(ContentType.parse("audio/mpeg")) { - val output = this - withContext(Dispatchers.IO) { - process.inputStream.use { input -> input.copyTo(output) } - } - } - } finally { - transcoder.stop(process) - } - } - - subsonicEndpoint(users, "/download") { call, user -> - val id = call.subsonicParams()["id"] - if (id.isNullOrBlank()) { - call.respondSubsonicError(10, "Required parameter is missing: id") - return@subsonicEndpoint - } - - val resolved = LibraryRepository.resolveSong( - id, - user.visibleFolderIds(library), - user.name, - library, - ) - if (resolved == null) { - call.respondSubsonicError(70, "Song not found") - return@subsonicEndpoint - } - - call.response.headers.append( - HttpHeaders.ContentDisposition, - contentDisposition(resolved.file.fileName.toString()), - ) - call.respondFile(resolved.file.toFile()) - } - - subsonicEndpoint(users, "/getCoverArt") { call, user -> - val parameters = call.subsonicParams() - val id = parameters["id"] - if (id.isNullOrBlank()) { - call.respondSubsonicError(10, "Required parameter is missing: id") - return@subsonicEndpoint - } - - val requestedSize = parameters["size"] - val size = requestedSize?.toIntOrNull() - if (requestedSize != null && (size == null || size !in 1..2048)) { - call.respondSubsonicError(10, "Invalid cover size") - return@subsonicEndpoint - } - - val folders = user.visibleFolderIds(library) - val albumId = if (id.startsWith("sg-")) { - LibraryRepository.albumIdForSong(id, folders) - } else if (LibraryRepository.album(id, folders, user.name) != null) { - id - } else { - null - } - - if (albumId == null) { - call.respond(HttpStatusCode.NotFound) - return@subsonicEndpoint - } - - val cover = if (size == null) { - coverArtService.coverFile(albumId) - } else { - coverArtService.resizedCover(albumId, size) - } - - if (cover == null) { - call.respond(HttpStatusCode.NotFound) - } else { - call.respondFile(cover.toFile()) - } - } -} - -private fun contentDisposition(fileName: String): String { - val encoded = URLEncoder.encode(fileName, Charsets.UTF_8).replace("+", "%20") - val ascii = fileName.map { character -> - if (character.code in 32..126 && character != '"' && character != '\\') character else '_' - }.joinToString("") - - return "attachment; filename=\"$ascii\"; filename*=UTF-8''$encoded" -} diff --git a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/MoodRoutes.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/MoodRoutes.kt deleted file mode 100644 index 63e74ab..0000000 --- a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/MoodRoutes.kt +++ /dev/null @@ -1,265 +0,0 @@ -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/PlayQueueRoutes.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/PlayQueueRoutes.kt deleted file mode 100644 index 51299ff..0000000 --- a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/PlayQueueRoutes.kt +++ /dev/null @@ -1,67 +0,0 @@ -package win.taptap.musicmanager.subsonic.routes - -import io.ktor.server.routing.Route -import kotlinx.serialization.json.add -import kotlinx.serialization.json.buildJsonArray -import kotlinx.serialization.json.buildJsonObject -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.subsonic.PlayQueueStore -import win.taptap.musicmanager.subsonic.models.songJson -import win.taptap.musicmanager.subsonic.respondSubsonic - -/** Optional server-side queue used by clients that support queue hand-off. */ -fun Route.playQueueRoutes(users: UsersConfig, library: LibraryConfig) { - - for (endpoint in listOf("/savePlayQueue", "/savePlayQueueByIndex")) { - subsonicEndpoint(users, endpoint) { call, user -> - val parameters = call.subsonicParams() - val folders = user.visibleFolderIds(library) - - val requestedIds = parameters.getAll("id").orEmpty().filter { it.isNotBlank() } - val visible = requestedIds.filter { LibraryRepository.song(it, folders, user.name) != null } - - val currentId = parameters["current"] - val explicitIndex = parameters["currentIndex"]?.toIntOrNull() - val currentIndex = explicitIndex - ?: currentId?.let { visible.indexOf(it) }?.takeIf { it >= 0 } - ?: 0 - - val position = parameters["position"]?.toLongOrNull() ?: 0L - PlayQueueStore.save(user.name, visible, currentIndex, position) - - call.respondSubsonic() - } - } - - for (endpoint in listOf("/getPlayQueue", "/getPlayQueueByIndex")) { - subsonicEndpoint(users, endpoint) { call, user -> - val state = PlayQueueStore.get(user.name) - val folders = user.visibleFolderIds(library) - val songs = LibraryRepository.songsByIds(state?.songIds.orEmpty(), folders, user.name) - val byIndex = endpoint == "/getPlayQueueByIndex" - - val queue = buildJsonObject { - put("entry", buildJsonArray { songs.forEach { add(songJson(it)) } }) - put("position", state?.positionMs ?: 0L) - put("username", user.name) - put("changed", state?.changed.orEmpty()) - put("changedBy", state?.changedBy.orEmpty()) - - if (byIndex) { - put("currentIndex", state?.currentIndex ?: 0) - } else { - state?.songIds?.getOrNull(state.currentIndex)?.let { put("current", it) } - } - } - - call.respondSubsonic( - buildJsonObject { - put(if (byIndex) "playQueueByIndex" else "playQueue", queue) - }, - ) - } - } -} diff --git a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/PlaylistRoutes.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/PlaylistRoutes.kt deleted file mode 100644 index 8328369..0000000 --- a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/PlaylistRoutes.kt +++ /dev/null @@ -1,189 +0,0 @@ -package win.taptap.musicmanager.subsonic.routes - -import io.ktor.server.routing.Route -import kotlinx.serialization.json.add -import kotlinx.serialization.json.buildJsonArray -import kotlinx.serialization.json.buildJsonObject -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, moodService: MoodService) { - - subsonicEndpoint(users, "/getPlaylists") { call, user -> - val playlists = PlaylistRepository.visibleTo(user.name) - - call.respondSubsonic( - buildJsonObject { - put("playlists", buildJsonObject { - put("playlist", buildJsonArray { playlists.forEach { add(playlistJson(it)) } }) - }) - }, - ) - } - - subsonicEndpoint(users, "/getPlaylist") { call, user -> - val id = call.subsonicParams()["id"] - if (id.isNullOrBlank()) { - call.respondSubsonicError(10, "Required parameter is missing: id") - return@subsonicEndpoint - } - - val playlist = PlaylistRepository.get(id, user.name) - if (playlist == null) { - call.respondSubsonicError(70, "Playlist not found") - return@subsonicEndpoint - } - - 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)) }) - } - - subsonicEndpoint(users, "/createPlaylist") { call, user -> - val parameters = call.subsonicParams() - val folders = user.visibleFolderIds(library) - val requestedSongs = parameters.getAll("songId").orEmpty() - .filter { it.isNotBlank() } - .filter { LibraryRepository.song(it, folders, user.name) != null } - - val playlistId = parameters["playlistId"] - if (!playlistId.isNullOrBlank()) { - val existing = PlaylistRepository.get(playlistId, user.name) - if (existing == null) { - call.respondSubsonicError(70, "Playlist not found") - return@subsonicEndpoint - } - if (existing.owner != user.name) { - 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( - playlistId = playlistId, - userName = user.name, - name = newName, - comment = null, - isPublic = null, - addSongIds = emptyList(), - removeIndices = emptyList(), - ) - PlaylistRepository.replaceSongs(playlistId, requestedSongs, user.name) - - val updated = PlaylistRepository.get(playlistId, user.name)!! - call.respondSubsonic(buildJsonObject { put("playlist", playlistJson(updated)) }) - return@subsonicEndpoint - } - - val name = parameters["name"] - if (name.isNullOrBlank()) { - call.respondSubsonicError(10, "Required parameter is missing: name") - return@subsonicEndpoint - } - - val playlist = PlaylistRepository.create(user.name, name.trim(), requestedSongs) - call.respondSubsonic(buildJsonObject { put("playlist", playlistJson(playlist)) }) - } - - subsonicEndpoint(users, "/updatePlaylist") { call, user -> - val parameters = call.subsonicParams() - val playlistId = parameters["playlistId"] - if (playlistId.isNullOrBlank()) { - call.respondSubsonicError(10, "Required parameter is missing: playlistId") - return@subsonicEndpoint - } - - val existing = PlaylistRepository.get(playlistId, user.name) - if (existing == null) { - call.respondSubsonicError(70, "Playlist not found") - return@subsonicEndpoint - } - if (existing.owner != user.name) { - call.respondSubsonicError(50, "Not authorized") - return@subsonicEndpoint - } - - val folders = user.visibleFolderIds(library) - val addSongs = parameters.getAll("songIdToAdd").orEmpty() - .filter { it.isNotBlank() } - .filter { LibraryRepository.song(it, folders, user.name) != null } - val removeIndices = parameters.getAll("songIndexToRemove").orEmpty() - .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, - name = parameters["name"]?.takeIf { it.isNotBlank() }, - comment = parameters["comment"], - isPublic = parameters["public"]?.toBooleanStrictOrNull(), - addSongIds = addSongs, - removeIndices = removeIndices, - ) - - if (!updated) { - call.respondSubsonicError(50, "Not authorized") - } else { - call.respondSubsonic() - } - } - - subsonicEndpoint(users, "/deletePlaylist") { call, user -> - val playlistId = call.subsonicParams()["id"] - if (playlistId.isNullOrBlank()) { - call.respondSubsonicError(10, "Required parameter is missing: id") - return@subsonicEndpoint - } - - val existing = PlaylistRepository.get(playlistId, user.name) - if (existing == null) { - call.respondSubsonicError(70, "Playlist not found") - return@subsonicEndpoint - } - if (existing.owner != user.name) { - call.respondSubsonicError(50, "Not authorized") - return@subsonicEndpoint - } - - 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 deleted file mode 100644 index edb412d..0000000 --- a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/RouteHelpers.kt +++ /dev/null @@ -1,56 +0,0 @@ -package win.taptap.musicmanager.subsonic.routes - -import io.ktor.http.ContentType -import io.ktor.http.HttpMethod -import io.ktor.http.Parameters -import io.ktor.server.application.ApplicationCall -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 - -val CurrentUserKey = AttributeKey("musicmanager.currentUser") -val SubsonicParametersKey = AttributeKey("musicmanager.parameters") - -/** - * Visible folders, optionally narrowed to a client-supplied `musicFolderId`. - * An unknown or invisible id yields an empty set, which all queries treat as "nothing". - */ -fun UserAccount.effectiveFolderIds(library: LibraryConfig, musicFolderId: String?): Set { - val visible = visibleFolderIds(library) - val requested = musicFolderId?.toIntOrNull() ?: return visible - 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 - -/** - * Unified parameter access for Subsonic: query parameters plus URL-encoded form - * bodies (the `formPost` OpenSubsonic extension). - */ -suspend fun subsonicParameters(call: ApplicationCall): Parameters { - val query = call.request.queryParameters - if (call.request.httpMethod != HttpMethod.Post) return query - - val contentType = call.request.contentType() - if (!contentType.match(ContentType.Application.FormUrlEncoded)) return query - - val form = call.receiveParameters() - return Parameters.build { - query.forEach { name, values -> values.forEach { append(name, it) } } - form.forEach { name, values -> values.forEach { append(name, it) } } - } -} diff --git a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/SubsonicEndpoint.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/SubsonicEndpoint.kt deleted file mode 100644 index f8e7c9b..0000000 --- a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/SubsonicEndpoint.kt +++ /dev/null @@ -1,41 +0,0 @@ -package win.taptap.musicmanager.subsonic.routes - -import io.ktor.server.application.ApplicationCall -import io.ktor.server.routing.Route -import io.ktor.server.routing.get -import io.ktor.server.routing.post -import win.taptap.musicmanager.config.UserAccount -import win.taptap.musicmanager.config.UsersConfig -import win.taptap.musicmanager.subsonic.SubsonicAuthenticator -import win.taptap.musicmanager.subsonic.respondSubsonicError - -/** - * Registers a Subsonic endpoint for both `/{path}` and `/{path}.view`, and for both - * GET and POST form posts (the `formPost` OpenSubsonic extension). - * Authentication failures always return HTTP 200 with error code 40. - */ -internal fun Route.subsonicEndpoint( - users: UsersConfig, - path: String, - handler: suspend (ApplicationCall, UserAccount) -> Unit, -) { - val authenticator = SubsonicAuthenticator(users) - val paths = if (path.endsWith(".view")) listOf(path) else listOf(path, "$path.view") - - suspend fun handle(call: ApplicationCall) { - val parameters = subsonicParameters(call) - val user = authenticator.authenticate(parameters) - if (user == null) { - call.respondSubsonicError(40, "Wrong username or password") - } else { - call.attributes.put(CurrentUserKey, user) - call.attributes.put(SubsonicParametersKey, parameters) - handler(call, user) - } - } - - paths.forEach { routePath -> - get(routePath) { handle(call) } - post(routePath) { handle(call) } - } -} diff --git a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/SubsonicRoutes.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/SubsonicRoutes.kt deleted file mode 100644 index 0e3b7c1..0000000 --- a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/SubsonicRoutes.kt +++ /dev/null @@ -1,31 +0,0 @@ -package win.taptap.musicmanager.subsonic.routes - -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 - -/** Authenticated `/rest` subtree. */ -fun Route.subsonicRoutes( - users: UsersConfig, - library: LibraryConfig, - coverArtService: CoverArtService, - transcoder: FfmpegTranscoder, - moodService: MoodService, - startScan: () -> Boolean, - scanStatus: () -> ScanStatus, -) { - route("/rest") { - systemRoutes(users, library, startScan, scanStatus) - browsingRoutes(users, library) - mediaRoutes(users, library, coverArtService, transcoder) - interactionRoutes(users, library) - playlistRoutes(users, library, moodService) - moodRoutes(users, library, moodService) - playQueueRoutes(users, library) - } -} diff --git a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/SystemRoutes.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/SystemRoutes.kt deleted file mode 100644 index 2b29a9f..0000000 --- a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/SystemRoutes.kt +++ /dev/null @@ -1,174 +0,0 @@ -package win.taptap.musicmanager.subsonic.routes - -import io.ktor.server.routing.Route -import kotlinx.serialization.json.JsonArray -import kotlinx.serialization.json.JsonPrimitive -import kotlinx.serialization.json.add -import kotlinx.serialization.json.buildJsonArray -import kotlinx.serialization.json.buildJsonObject -import kotlinx.serialization.json.put -import win.taptap.musicmanager.config.LibraryConfig -import win.taptap.musicmanager.config.UserAccount -import win.taptap.musicmanager.config.UsersConfig -import win.taptap.musicmanager.scanner.ScanStatus -import win.taptap.musicmanager.subsonic.respondSubsonic -import win.taptap.musicmanager.subsonic.respondSubsonicError - -/** System endpoints from the MVP specification. */ -fun Route.systemRoutes( - users: UsersConfig, - library: LibraryConfig, - startScan: () -> Boolean, - scanStatus: () -> ScanStatus, -) { - subsonicEndpoint(users, "/ping") { call, _ -> - call.respondSubsonic() - } - - subsonicEndpoint(users, "/getLicense") { call, _ -> - call.respondSubsonic( - buildJsonObject { - put("license", buildJsonObject { put("valid", true) }) - }, - ) - } - - subsonicEndpoint(users, "/getOpenSubsonicExtensions") { call, _ -> - call.respondSubsonic( - buildJsonObject { - put( - "openSubsonicExtensions", - buildJsonArray { - add(extension("formPost", 1)) - add(extension("songLyrics", 1)) - add(extension("transcodeOffset", 1)) - }, - ) - }, - ) - } - - subsonicEndpoint(users, "/startScan") { call, user -> - if (!user.admin) { - call.respondSubsonicError(50, "Not authorized") - } else { - startScan() - call.respondSubsonic() - } - } - - subsonicEndpoint(users, "/getScanStatus") { call, _ -> - val status = scanStatus() - call.respondSubsonic( - buildJsonObject { - put("scanStatus", buildJsonObject { - put("scanning", status.scanning) - put("count", status.count) - }) - }, - ) - } - - subsonicEndpoint(users, "/getUser") { call, currentUser -> - val username = call.subsonicParams()["username"] - if (username.isNullOrBlank()) { - call.respondSubsonicError(10, "Required parameter is missing: username") - return@subsonicEndpoint - } - - if (username != currentUser.name && !currentUser.admin) { - call.respondSubsonicError(50, "Not authorized") - return@subsonicEndpoint - } - - val requested = users.byName(username) - if (requested == null) { - call.respondSubsonicError(70, "User not found") - return@subsonicEndpoint - } - - call.respondSubsonic(buildJsonObject { put("user", userJson(requested, library)) }) - } - - subsonicEndpoint(users, "/getInternetRadioStations") { call, _ -> - call.respondSubsonic( - buildJsonObject { - put("internetRadioStations", buildJsonObject { - put("internetRadioStation", buildJsonArray { }) - }) - }, - ) - } - - for (endpoint in listOf( - "/createInternetRadioStation", - "/updateInternetRadioStation", - "/deleteInternetRadioStation", - )) { - subsonicEndpoint(users, endpoint) { call, _ -> - call.respondSubsonicError(0, "Internet radio is not supported") - } - } - - subsonicEndpoint(users, "/jukeboxControl") { call, _ -> - if (call.subsonicParams()["action"] != "status") { - call.respondSubsonicError(0, "Jukebox is not supported") - return@subsonicEndpoint - } - - call.respondSubsonic( - buildJsonObject { - put("jukeboxStatus", buildJsonObject { - put("currentIndex", 0) - put("playing", false) - put("gain", 1.0) - put("position", 0) - }) - }, - ) - } - - subsonicEndpoint(users, "/getUsers") { call, currentUser -> - if (!currentUser.admin) { - call.respondSubsonicError(50, "Not authorized") - return@subsonicEndpoint - } - - call.respondSubsonic( - buildJsonObject { - put("users", buildJsonObject { - put("user", buildJsonArray { - users.users.forEach { add(userJson(it, library)) } - }) - }) - }, - ) - } -} - -private fun userJson(user: UserAccount, library: LibraryConfig) = buildJsonObject { - put("username", user.name) - put("scrobblingEnabled", true) - put("adminRole", user.admin) - put("settingsRole", user.admin) - put("downloadRole", true) - put("uploadRole", false) - put("playlistRole", true) - put("coverArtRole", true) - put("commentRole", false) - put("podcastRole", false) - put("streamRole", true) - put("jukeboxRole", false) - put("shareRole", false) - put("videoConversionRole", false) - put("folder", folderIds(user.visibleFolderIds(library))) -} - -private fun folderIds(ids: Set): JsonArray = buildJsonArray { - ids.sorted().forEach { add(JsonPrimitive(it)) } -} - -private fun extension(name: String, version: Int) = buildJsonObject { - put("name", name) - put("versions", buildJsonArray { add(kotlinx.serialization.json.JsonPrimitive(version)) }) -} diff --git a/src/main/kotlin/win/taptap/musicmanager/util/IdGenerator.kt b/src/main/kotlin/win/taptap/musicmanager/util/IdGenerator.kt index 77047ce..652e2a9 100644 --- a/src/main/kotlin/win/taptap/musicmanager/util/IdGenerator.kt +++ b/src/main/kotlin/win/taptap/musicmanager/util/IdGenerator.kt @@ -5,7 +5,7 @@ import java.text.Normalizer import java.util.Locale /** - * Deterministic IDs for the Symfonium offline cache. + * Deterministic IDs for clients' offline caches. * * Normalization is frozen: NFC, trimmed, collapsed whitespace, lowercase. Changing * it changes every ID and forces clients to re-download their library. @@ -27,8 +27,8 @@ object IdGenerator { fun songId(folderId: Int, relativePath: String): String = "sg-" + hash("$folderId:${normalizePath(relativePath)}") - fun playlistId(owner: String, name: String, createdAt: String): String = - "pl-" + hash("${normalize(owner)}|${normalize(name)}|$createdAt") + fun moodId(owner: String, name: String, createdAt: String): String = + "mo-" + hash("${normalize(owner)}|${normalize(name)}|$createdAt") private fun normalizePath(path: String): String = path .replace('\\', '/') diff --git a/src/main/resources/db/migration/V5__native_api.sql b/src/main/resources/db/migration/V5__native_api.sql new file mode 100644 index 0000000..817aacd --- /dev/null +++ b/src/main/resources/db/migration/V5__native_api.sql @@ -0,0 +1,164 @@ +-- Native mood-first API. +-- +-- The OpenSubsonic layer is gone, so moods no longer need to be materialized as +-- playlists. They become first-class rows, radio queues are generated per +-- playback session, and the old playlist tables are dropped. + +CREATE TABLE moods_v2 ( + id TEXT PRIMARY KEY, + owner TEXT NOT NULL REFERENCES users(name) ON DELETE CASCADE, + name TEXT NOT NULL, + description TEXT, + query TEXT, + genres TEXT NOT NULL DEFAULT '[]', + target_size INTEGER NOT NULL DEFAULT 30, + refresh_hours INTEGER NOT NULL DEFAULT 24, + yt_enabled BOOLEAN NOT NULL DEFAULT 1, + last_discovery_at TEXT, + created_at TEXT NOT NULL, + changed_at TEXT NOT NULL, + last_error TEXT +); + +INSERT INTO moods_v2 ( + id, owner, name, description, query, genres, target_size, + refresh_hours, yt_enabled, created_at, changed_at, last_error +) +SELECT + m.playlist_id, + p.owner, + p.name, + p.comment, + m.query, + m.genres, + m.target_size, + m.refresh_hours, + 1, + p.created_at, + p.changed_at, + m.last_error +FROM moods m +JOIN playlists p ON p.id = m.playlist_id; + +CREATE TABLE mood_seeds_v2 ( + mood_id TEXT NOT NULL REFERENCES moods_v2(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', 'recommendation', 'yt')), + added_at TEXT NOT NULL, + PRIMARY KEY (mood_id, song_id) +); + +-- Stars no longer exist. Songs liked under the old model become manual seeds. +INSERT INTO mood_seeds_v2 (mood_id, song_id, origin, added_at) +SELECT + playlist_id, + song_id, + CASE origin WHEN 'manual' THEN 'manual' ELSE 'manual' END, + added_at +FROM mood_seeds; + +CREATE TABLE mood_recommendations_v2 ( + mood_id TEXT NOT NULL REFERENCES moods_v2(id) ON DELETE CASCADE, + video_id TEXT NOT NULL, + title TEXT NOT NULL, + artist TEXT NOT NULL, + album TEXT, + duration INTEGER, + thumbnail TEXT, + state TEXT NOT NULL DEFAULT 'new' + CHECK (state IN ('new', 'accepted', 'rejected', 'unavailable')), + 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 (mood_id, video_id) +); + +INSERT INTO mood_recommendations_v2 ( + mood_id, video_id, title, artist, duration, state, + matched_song_id, times_added, first_seen, last_seen +) +SELECT + playlist_id, video_id, title, artist, duration, state, + matched_song_id, times_added, first_seen, last_seen +FROM mood_recommendations; + +DROP TABLE mood_recommendations; +DROP TABLE mood_seeds; +DROP TABLE moods; +DROP TABLE playlist_songs; +DROP TABLE playlists; + +ALTER TABLE moods_v2 RENAME TO moods; +ALTER TABLE mood_seeds_v2 RENAME TO mood_seeds; +ALTER TABLE mood_recommendations_v2 RENAME TO mood_recommendations; + +CREATE INDEX idx_moods_owner ON moods (owner); +CREATE INDEX idx_mood_seeds_song ON mood_seeds (song_id); +CREATE INDEX idx_mood_recommendations_song ON mood_recommendations (matched_song_id); + +-- Device sessions. Only the SHA-256 hash of the bearer token is stored. +CREATE TABLE api_tokens ( + id TEXT PRIMARY KEY, + user_name TEXT NOT NULL REFERENCES users(name) ON DELETE CASCADE, + token_hash TEXT NOT NULL UNIQUE, + device_name TEXT NOT NULL, + platform TEXT NOT NULL, + created_at TEXT NOT NULL, + last_used_at TEXT NOT NULL, + expires_at TEXT NOT NULL +); + +CREATE INDEX idx_api_tokens_user ON api_tokens (user_name); + +-- A playback session belongs to one mood. Queue items and events are kept so a +-- client can resume and so radio ranking learns from skips and completions. +CREATE TABLE playback_sessions ( + id TEXT PRIMARY KEY, + user_name TEXT NOT NULL REFERENCES users(name) ON DELETE CASCADE, + mood_id TEXT NOT NULL REFERENCES moods(id) ON DELETE CASCADE, + next_position INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, + last_seen_at TEXT NOT NULL, + closed_at TEXT +); + +CREATE INDEX idx_playback_sessions_user ON playback_sessions (user_name, last_seen_at); + +CREATE TABLE playback_session_items ( + session_id TEXT NOT NULL REFERENCES playback_sessions(id) ON DELETE CASCADE, + position INTEGER NOT NULL, + song_id TEXT NOT NULL REFERENCES songs(id) ON DELETE CASCADE, + state TEXT NOT NULL DEFAULT 'queued' + CHECK (state IN ('queued', 'started', 'completed', 'skipped')), + queued_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + PRIMARY KEY (session_id, position) +); + +CREATE INDEX idx_session_items_song ON playback_session_items (song_id); + +CREATE TABLE song_affinity ( + user_name TEXT NOT NULL REFERENCES users(name) ON DELETE CASCADE, + song_id TEXT NOT NULL REFERENCES songs(id) ON DELETE CASCADE, + completions INTEGER NOT NULL DEFAULT 0, + skips INTEGER NOT NULL DEFAULT 0, + last_event_at TEXT NOT NULL, + PRIMARY KEY (user_name, song_id) +); + +-- Clients sync by revision. Deletions are explicit so offline libraries can drop +-- removed files instead of keeping them forever. +CREATE TABLE library_tombstones ( + entity TEXT NOT NULL, + entity_id TEXT NOT NULL, + deleted_at TEXT NOT NULL, + PRIMARY KEY (entity, entity_id) +); + +CREATE INDEX idx_library_tombstones_deleted ON library_tombstones (deleted_at); + +-- Scanner deltas need a changed timestamp independent of the file mtime. +ALTER TABLE songs ADD COLUMN updated_at TEXT NOT NULL DEFAULT ''; +UPDATE songs SET updated_at = created_at WHERE updated_at = ''; diff --git a/src/main/resources/web/index.html b/src/main/resources/web/index.html index ffcce96..de75d0c 100644 --- a/src/main/resources/web/index.html +++ b/src/main/resources/web/index.html @@ -1,572 +1,614 @@ - + -MusicManager +AudioManager -
-

MusicManager test client

-

Sign in with a user from users.yaml.

- - - -
+

AudioManager

+

Mood-based streaming. Sign in to continue.

+
+
+
+
+ +
-
-
- - - -
-
-
+