Files
AudioManager/README.md
T
TapTap b33eb076c1
CI / chart (push) Successful in 3s
CI / chart-push (push) Successful in 3s
CI / test (push) Successful in 1m40s
CI / image (push) Successful in 3m12s
feat!: replace OpenSubsonic with a native mood-first API
Remove the /rest compatibility layer and the playlist model. Moods are now
first-class private collections, and playback is driven by short-lived radio
sessions whose queues are generated by the server.

- Bearer device tokens (hashed) with revocable sessions.
- Library snapshot/delta sync with tombstones and per-folder scoping.
- Mood CRUD, seeds, preview and recommendations.
- Radio batches weighted by seeds, genres, artists, text and playback affinity.
- Playback events (started/completed/skipped) and explicit add-to-mood.
- Stream, download and cover endpoints with query-token support for browsers.
- V5 migration drops playlists and migrates existing moods; scanner writes
  tombstones and song update timestamps.
- Built-in UI rebuilt on the native API with a radio player.
- Native API integration tests and a rewritten smoke test (49 checks).
- Chart bumped to 0.2.0.

BREAKING CHANGE: the OpenSubsonic API and static playlists are gone.
2026-11-14 17:54:44 +00:00

323 lines
12 KiB
Markdown

# AudioManager
A self-hosted, mood-first music server in Kotlin/Ktor, plus a Kotlin Multiplatform client.
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.
## Contents
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)
---
## Quick start
Requirements: JDK 21, ffmpeg, SQLite (bundled through JDBC).
```bash
# 1. Build
gradle shadowJar
# 2. Point the server at a library
mkdir -p data
cat > config/library.yaml <<'YAML'
library:
folders:
- id: 1
name: Music
type: music
path: /absolute/path/to/music
- id: 10
name: Long-form
type: longform
path: /absolute/path/to/longform
YAML
# 3. Define users (passwords stay outside SQLite)
cat > config/users.yaml <<'YAML'
users:
- name: alice
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
```
Open `http://localhost:8080/ui`. The first start scans the library automatically because the database is empty. Later scans are manual:
```bash
curl -X POST -H "Authorization: Bearer $TOKEN" http://localhost:8080/api/v1/scan
```
The built-in UI is an admin/management surface: users, moods, seeds, library search, and a browser radio player.
## Configuration
### `library.yaml`
```yaml
library:
folders:
- id: 1
name: Music
type: music
path: /mnt/media/music
- id: 10
name: Long-form
type: longform
path: /mnt/media/longform
```
- `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.
### `users.yaml`
```yaml
users:
- name: alice
password: change-me
admin: true
folders: [1]
- name: bob
password: another-secret
admin: false
folders: [1]
```
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.
### Environment
| Variable | Default | Meaning |
| --- | --- | --- |
| `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 |
## The mood model
A mood is a private collection owned by one user:
- **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" } }
```
### Authentication
```http
POST /api/v1/auth/login
Content-Type: application/json
{ "username": "alice", "password": "change-me", "deviceName": "Pixel", "platform": "android" }
```
```json
{
"token": "…",
"expiresAt": "2027-05-13T…",
"user": { "name": "alice", "admin": true, "musicFolders": [1], "longformFolders": [10] }
}
```
Send `Authorization: Bearer <token>` 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 `<img>` tags cannot set headers.
- `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.
### Library sync
- `GET /library/songs?cursor=<id>&limit=500&scope=music|longform|all` — snapshot page, ordered by song ID. Loop while `nextCursor` is present.
- `GET /library/songs?since=<revision>` — 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.
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.
### Moods
- `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).
### Radio sessions
- `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.
### System
- `GET /scan` — `{ scanning, count, error }`
- `POST /scan` — admin only; 202 Accepted.
- `GET /health` — unauthenticated liveness probe.
## Architecture
```text
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.
## Database
SQLite in WAL mode, migrations through Flyway:
- `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:
- 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.
## Scanner
- 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.
## Deployment
Images and charts are published by Gitea Actions to `gitea.tap-tap.win`.
```text
Image: gitea.tap-tap.win/taptap/audiomanager:<tag>
Chart: https://gitea.tap-tap.win/TapTap/Charts/raw/branch/main
```
Kustomize example:
```yaml
helmCharts:
- name: audiomanager
repo: https://gitea.tap-tap.win/TapTap/Charts/raw/branch/main
releaseName: audiomanager
version: 0.2.0-sha.<commit>
namespace: audiomanager
valuesFile: values.yaml
```
The chart expects:
- 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.
Ingress host: `subsonic.tap-tap.win` (the historical name is kept, but the server no longer speaks the Subsonic protocol).
```bash
kustomize build --enable-helm . | kubectl apply -f -
kubectl -n audiomanager rollout status deployment/audiomanager
```
Flyway applies `V5__native_api.sql` automatically. Existing playlist-based moods are migrated to native moods; old playlists and user stars are dropped.
## Client
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.
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).
## Testing
```bash
gradle test # unit + API integration tests
GRADLE=gradle scripts/smoke.sh # end-to-end server smoke test
```
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
- [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.