From e194badefbf37669c6401ecfbf841a4e527ec396 Mon Sep 17 00:00:00 2001 From: TapTap Date: Fri, 13 Nov 2026 11:42:57 +0000 Subject: [PATCH] feat: bootstrap MusicManager with scanner and Subsonic auth - Gradle/Kotlin/Ktor project on JVM 21 with ShadowJar - SQLite WAL, Flyway migrations and config-driven users/folders - deterministic IDs, MP3 tag extraction, cover cache and delta scanner - OpenSubsonic JSON envelope with token/password authentication - system endpoints: ping, license, extensions, scan status --- .gitignore | 21 + README | 596 ++++++++++++++---- build.gradle.kts | 81 +++ config/library.example.yaml | 14 + config/users.example.yaml | 10 + gradle.properties | 4 + gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 43764 bytes gradle/wrapper/gradle-wrapper.properties | 7 + gradlew | 251 ++++++++ gradlew.bat | 94 +++ settings.gradle.kts | 1 + .../win/taptap/musicmanager/Application.kt | 109 ++++ .../taptap/musicmanager/config/AppConfig.kt | 39 ++ .../musicmanager/config/LibraryConfig.kt | 130 ++++ .../taptap/musicmanager/config/UsersConfig.kt | 96 +++ .../musicmanager/db/ConfigRepository.kt | 71 +++ .../taptap/musicmanager/db/DatabaseFactory.kt | 78 +++ .../taptap/musicmanager/db/MediaRepository.kt | 233 +++++++ .../win/taptap/musicmanager/db/Tables.kt | 152 +++++ .../musicmanager/scanner/CoverArtService.kt | 136 ++++ .../musicmanager/scanner/MediaScanner.kt | 125 ++++ .../musicmanager/scanner/Mp3TagExtractor.kt | 178 ++++++ .../taptap/musicmanager/scanner/ScanStatus.kt | 7 + .../musicmanager/subsonic/SubsonicAuth.kt | 57 ++ .../musicmanager/subsonic/SubsonicResponse.kt | 51 ++ .../subsonic/routes/RouteHelpers.kt | 31 + .../subsonic/routes/SubsonicGet.kt | 35 + .../subsonic/routes/SubsonicRoutes.kt | 17 + .../subsonic/routes/SystemRoutes.kt | 71 +++ .../taptap/musicmanager/util/IdGenerator.kt | 45 ++ .../win/taptap/musicmanager/util/SortNames.kt | 27 + src/main/resources/db/migration/V1__init.sql | 142 +++++ src/main/resources/logback.xml | 15 + .../win/taptap/musicmanager/TestAudio.kt | 76 +++ .../musicmanager/config/AppConfigTest.kt | 50 ++ .../musicmanager/config/LibraryConfigTest.kt | 127 ++++ .../musicmanager/config/UsersConfigTest.kt | 126 ++++ .../musicmanager/db/DatabaseFactoryTest.kt | 204 ++++++ .../scanner/CoverArtServiceTest.kt | 87 +++ .../musicmanager/scanner/MediaScannerTest.kt | 209 ++++++ .../scanner/Mp3TagExtractorTest.kt | 111 ++++ .../musicmanager/subsonic/SubsonicAuthTest.kt | 68 ++ .../musicmanager/subsonic/SystemRoutesTest.kt | 141 +++++ .../musicmanager/util/IdGeneratorTest.kt | 56 ++ .../taptap/musicmanager/util/SortNamesTest.kt | 26 + 45 files changed, 4079 insertions(+), 126 deletions(-) create mode 100644 .gitignore create mode 100644 build.gradle.kts create mode 100644 config/library.example.yaml create mode 100644 config/users.example.yaml create mode 100644 gradle.properties create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100755 gradlew create mode 100644 gradlew.bat create mode 100644 settings.gradle.kts create mode 100644 src/main/kotlin/win/taptap/musicmanager/Application.kt create mode 100644 src/main/kotlin/win/taptap/musicmanager/config/AppConfig.kt create mode 100644 src/main/kotlin/win/taptap/musicmanager/config/LibraryConfig.kt create mode 100644 src/main/kotlin/win/taptap/musicmanager/config/UsersConfig.kt create mode 100644 src/main/kotlin/win/taptap/musicmanager/db/ConfigRepository.kt create mode 100644 src/main/kotlin/win/taptap/musicmanager/db/DatabaseFactory.kt create mode 100644 src/main/kotlin/win/taptap/musicmanager/db/MediaRepository.kt create mode 100644 src/main/kotlin/win/taptap/musicmanager/db/Tables.kt create mode 100644 src/main/kotlin/win/taptap/musicmanager/scanner/CoverArtService.kt create mode 100644 src/main/kotlin/win/taptap/musicmanager/scanner/MediaScanner.kt create mode 100644 src/main/kotlin/win/taptap/musicmanager/scanner/Mp3TagExtractor.kt create mode 100644 src/main/kotlin/win/taptap/musicmanager/scanner/ScanStatus.kt create mode 100644 src/main/kotlin/win/taptap/musicmanager/subsonic/SubsonicAuth.kt create mode 100644 src/main/kotlin/win/taptap/musicmanager/subsonic/SubsonicResponse.kt create mode 100644 src/main/kotlin/win/taptap/musicmanager/subsonic/routes/RouteHelpers.kt create mode 100644 src/main/kotlin/win/taptap/musicmanager/subsonic/routes/SubsonicGet.kt create mode 100644 src/main/kotlin/win/taptap/musicmanager/subsonic/routes/SubsonicRoutes.kt create mode 100644 src/main/kotlin/win/taptap/musicmanager/subsonic/routes/SystemRoutes.kt create mode 100644 src/main/kotlin/win/taptap/musicmanager/util/IdGenerator.kt create mode 100644 src/main/kotlin/win/taptap/musicmanager/util/SortNames.kt create mode 100644 src/main/resources/db/migration/V1__init.sql create mode 100644 src/main/resources/logback.xml create mode 100644 src/test/kotlin/win/taptap/musicmanager/TestAudio.kt create mode 100644 src/test/kotlin/win/taptap/musicmanager/config/AppConfigTest.kt create mode 100644 src/test/kotlin/win/taptap/musicmanager/config/LibraryConfigTest.kt create mode 100644 src/test/kotlin/win/taptap/musicmanager/config/UsersConfigTest.kt create mode 100644 src/test/kotlin/win/taptap/musicmanager/db/DatabaseFactoryTest.kt create mode 100644 src/test/kotlin/win/taptap/musicmanager/scanner/CoverArtServiceTest.kt create mode 100644 src/test/kotlin/win/taptap/musicmanager/scanner/MediaScannerTest.kt create mode 100644 src/test/kotlin/win/taptap/musicmanager/scanner/Mp3TagExtractorTest.kt create mode 100644 src/test/kotlin/win/taptap/musicmanager/subsonic/SubsonicAuthTest.kt create mode 100644 src/test/kotlin/win/taptap/musicmanager/subsonic/SystemRoutesTest.kt create mode 100644 src/test/kotlin/win/taptap/musicmanager/util/IdGeneratorTest.kt create mode 100644 src/test/kotlin/win/taptap/musicmanager/util/SortNamesTest.kt diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..834b758 --- /dev/null +++ b/.gitignore @@ -0,0 +1,21 @@ +# Gradle +.gradle/ +build/ +!gradle/wrapper/gradle-wrapper.jar + +# IDE +.idea/ +*.iml +.vscode/ + +# Local runtime data +data/ +media/ +config/users.yaml +*.db +*.db-shm +*.db-wal +*.log + +# Test fixtures (generated locally, never committed) +test-media/ diff --git a/README b/README index 4d08431..d2a63c5 100644 --- a/README +++ b/README @@ -1,152 +1,310 @@ -# Implementation Plan: OpenSubsonic Music Server (Kotlin / Ktor) +# MusicManager — Self-hosted OpenSubsonic Server (Kotlin / Ktor) -## 1. Projektziel & Kontext -Entwickle einen leichtgewichtigen, selbstgehosteten **OpenSubsonic-kompatiblen Musik-Server** in **Kotlin**, der Plex für Musik-Streaming ablöst und speziell auf die Zusammenarbeit mit dem Android-Client **Symfonium** optimiert ist. +## 1. Goal & Context -### Kernanforderungen (MVP) -1. **Library-Indexing:** Einlesen eines lokalen Musik-Verzeichnisses (primär MP3, zusätzlich FLAC/OGG/M4A/OPUS), Auslesen der Metadaten (Tag-First mit Ordnerstruktur `Artist/Album/Track` als Fallback) und Persistierung in SQLite. -2. **Symfonium-Sync:** Vollständige Unterstützung der OpenSubsonic-Browsing-Endpunkte, damit Symfonium den gesamten Katalog sauber in seine lokale Offline-First-Datenbank synchronisiert. -3. **Streaming & Offline-Downloads:** Auslieferung der Audiodateien inkl. HTTP `Range`-Requests (`206 Partial Content`) sowie exakter Byte-Größen, damit Seeking und Symfoniums Offline-Download-Manager zuverlässig funktionieren. -4. **Bidirektionale Interaktion:** Scrobbling (Play-Counts), Favoriten (`star`/`unstar`), Bewertungen (`setRating`), Playlists und Startseiten-Feeds (`getAlbumList2`, `getRandomSongs`). -5. **Erweiterbarkeit:** Saubere Trennung zwischen Media-Scanner, Datenbank-Layer und HTTP-API, sodass später ein automatisierter Music-Downloader und eine Discovery-/Recommendation-Engine (z. B. über ListenBrainz/Last.fm oder Staging-Playlists) angedockt werden können. +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. **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). +- 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 +## 2. Tech Stack & Dependencies -* **Sprache & Runtime:** Kotlin 2.x auf JVM 21 (`eclipse-temurin:21-jre-alpine`) -* **Build-Tool:** Gradle (Kotlin DSL `build.gradle.kts`) mit `ShadowJar` Plugin (Fat-JAR) -* **Web-Framework:** **Ktor Server (Netty)** - * `ktor-server-core`, `ktor-server-netty` - * `ktor-server-content-negotiation` + `ktor-serialization-kotlinx-json` - * `ktor-server-partial-content` (Pflicht für HTTP `Range` / `206 Partial Content`) - * `ktor-server-status-pages`, `ktor-server-call-logging`, `ktor-server-auto-head-response` -* **Datenbank:** **SQLite** (im `WAL`-Mode) + **JetBrains Exposed** (`exposed-core`, `exposed-dao`, `exposed-jdbc`, `exposed-java-time`) + `sqlite-jdbc` + `HikariCP` -* **Audio-Metadaten & Cover:** - * `net.jthink:jaudiotagger` (Auslesen von ID3v1/v2, FLAC, Ogg, M4A, Dauer, Bitrate, Cover, Lyrics) - * `net.coobird:thumbnailator` (On-the-fly Resizing von Album-Covern für `getCoverArt?size=...`) -* **Logging:** `logback-classic` + `kotlin-logging-jvm` +- **Language & runtime:** Kotlin 2.x on JVM 21 (`eclipse-temurin:21-jre-alpine`) +- **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 image builds --- -## 3. Projektstruktur +## 3. Project Structure ```text -src/main/kotlin/com/musicserver/ -├── Application.kt # Ktor Einstiegspunkt, Plugins, Graceful Shutdown +src/main/kotlin/win/taptap/musicmanager/ +├── Application.kt # Ktor entry point, plugins, graceful shutdown ├── config/ -│ └── AppConfig.kt # Env-Vars (MUSIC_DIR, DATA_DIR, SUBSONIC_USER, SUBSONIC_PASS, PORT) +│ ├── 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, Schema-Migration -│ ├── Tables.kt # Exposed Table-Definitionen -│ └── Repositories.kt # CRUD- & Query-Logik für Artists, Albums, Songs, Playlists +│ ├── DatabaseFactory.kt # SQLite init, PRAGMA journal_mode=WAL, Flyway +│ ├── Tables.kt # Exposed table definitions +│ ├── Repositories.kt # CRUD & queries for artists, albums, songs, playlists +│ └── migrations/ # Flyway SQL (V1__init.sql, ...) ├── scanner/ -│ ├── MediaScanner.kt # Rekursiver Verzeichnis-Scan, Delta-Updates, Orphan-Cleanup -│ ├── TagExtractor.kt # jaudiotagger Wrapper (Tags, Fallback auf Pfad, Dauer, Bitrate) -│ └── CoverArtService.kt # Cover-Extraktion aus Tags/Ordnern, Disk-Cache & Resizing +│ ├── 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 ├── subsonic/ -│ ├── SubsonicAuth.kt # Ktor Plugin/Interceptor für Token-Auth (u, t, s) & Plaintext (p) -│ ├── SubsonicResponse.kt # Standardisierter JSON-Envelope ("subsonic-response") & Fehlercodes -│ ├── models/ # kotlinx.serialization DTOs für OpenSubsonic +│ ├── 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/ # Routing unter /rest/{endpoint} und /rest/{endpoint}.view -│ ├── SystemRoutes.kt # ping, getLicense, getOpenSubsonicExtensions, startScan, getScanStatus -│ ├── BrowsingRoutes.kt # getMusicFolders, getIndexes, getArtists, getArtist, getAlbum, getSong, search3, getAlbumList2, getRandomSongs -│ ├── MediaRoutes.kt # stream, download, getCoverArt, getLyricsBySongId -│ ├── InteractionRoutes.kt # scrobble, star, unstar, setRating -│ └── PlaylistRoutes.kt # getPlaylists, getPlaylist, createPlaylist, updatePlaylist, deletePlaylist +│ └── 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 +├── transcoding/ +│ └── FfmpegTranscoder.kt # MP3 transcoding with maxBitRate and timeOffset └── util/ - └── IdGenerator.kt # Deterministische SHA-256 ID-Generierung + └── IdGenerator.kt # Deterministic SHA-256 IDs ``` --- -## 4. Kritische Architektur-Regeln (Symfonium-Kompatibilität) +## 4. Architecture Rules -1. **Deterministische IDs (Extrem wichtig!):** - * IDs dürfen sich bei einem erneuten Library-Scan **niemals** ändern, sonst verliert Symfonium den Offline-Download-Status und Playlist-Zuordnungen. - * **Artist-ID:** `"ar-" + sha256(normalizedAlbumArtist).take(16)` - * **Album-ID:** `"al-" + sha256(normalizedAlbumArtist + "|" + normalizedAlbumTitle).take(16)` - * **Song-ID:** `"sg-" + sha256(relativeFilePathFromMusicDir).take(16)` - * **Cover-ID:** Identisch zur `Album-ID` (`"al-..."`) bzw. `Artist-ID` (`"ar-..."`). -2. **Album-Gruppierung über `AlbumArtist`:** - * Alben müssen primär über den `ALBUM_ARTIST`-Tag gruppiert werden (Fallback: `ARTIST`-Tag, Fallback: Elternordner). Andernfalls zerfallen Alben mit Featuring-Artists in einzelne Fragmente. -3. **Exakte Datei-Metadaten für Offline-Downloads:** - * Jedes Song-Objekt muss zwingend die exakte Dateigröße in Bytes (`size: Long`), die Spieldauer in Sekunden (`duration: Int`), `bitRate: Int`, `suffix: String` (z. B. `"mp3"`) und `contentType: String` (z. B. `"audio/mpeg"`) liefern. Symfonium prüft nach jedem Offline-Download, ob die heruntergeladenen Bytes exakt mit `size` übereinstimmen. -4. **Routing-Konvention & `formPost`:** - * Symfonium sendet Requests wahlweise an `/rest/getArtists` oder `/rest/getArtists.view` und nutzt bei langen Parameterlisten (z. B. `updatePlaylist`) `POST` mit `application/x-www-form-urlencoded`. - * Registriere alle Endpunkte für **beide** URL-Varianten (`/{method}` und `/{method}.view`) und lies Parameter vereinheitlicht aus `call.request.queryParameters` **und** `call.receiveParameters()` (bei POST). -5. **OpenSubsonic JSON-Envelope:** - * Jede Antwort (Standard `f=json`) muss in folgendes Root-Objekt verpackt sein: - ```json - { - "subsonic-response": { - "status": "ok", - "version": "1.16.1", - "type": "subsonic-kt", - "serverVersion": "0.1.0", - "openSubsonic": true - } - } - ``` +### 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. Datenbank-Schema (SQLite) +## 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, - starred_at TEXT + search_text TEXT NOT NULL ); CREATE TABLE albums ( id TEXT PRIMARY KEY, - artist_id TEXT NOT NULL REFERENCES artists(id) ON DELETE CASCADE, name TEXT NOT NULL, year INTEGER, - genre TEXT, cover_art TEXT, created_at TEXT NOT NULL, - starred_at TEXT, - user_rating INTEGER + 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, - artist_id TEXT NOT NULL REFERENCES artists(id) ON DELETE CASCADE, + folder_id INTEGER NOT NULL REFERENCES music_folders(id), title TEXT NOT NULL, - artist_name TEXT NOT NULL, + display_artist TEXT NOT NULL, album_name TEXT NOT NULL, track_number INTEGER, disc_number INTEGER DEFAULT 1, year INTEGER, - genre TEXT, 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 UNIQUE, + 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, - user_rating INTEGER + 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, - owner TEXT NOT NULL, is_public BOOLEAN NOT NULL DEFAULT 1, created_at TEXT NOT NULL, changed_at TEXT NOT NULL @@ -160,55 +318,241 @@ CREATE TABLE playlist_songs ( ); ``` ---- +Required indexes: -## 6. Spezifikation der MVP-Endpunkte +- `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)` -### Authentifizierung (`SubsonicAuth`) -* Prüfe bei jedem `/rest/*`-Call (außer optional Healthcheck): - * `u`: Muss mit `SUBSONIC_USER` übereinstimmen. - * Entweder Token-Auth: `t` und `s` vorhanden -> prüfe `t.equals(md5(SUBSONIC_PASS + s), ignoreCase = true)`. - * Oder Passwort-Auth: `p` vorhanden -> falls `p.startsWith("enc:")`, Hex-dekodieren, sonst direkt mit `SUBSONIC_PASS` vergleichen. - * Bei Fehler: HTTP 200 mit Subsonic-Error-JSON (`code = 40`, `message = "Wrong username or password"`). - -### Endpunkt-Liste -1. **System & Scan:** - * `ping`: Leeres `subsonic-response` mit `status: "ok"`. - * `getLicense`: `{"license": {"valid": true}}`. - * `getOpenSubsonicExtensions`: Deklariert `[{"name": "formPost", "versions": [1]}, {"name": "songLyrics", "versions": [1]}]`. - * `startScan` / `getScanStatus`: Startet asynchronen Coroutine-Scan und gibt `{"scanStatus": {"scanning": Boolean, "count": Long}}` zurück. -2. **Browsing & Suche:** - * `getMusicFolders`: Liefert `[{"id": 1, "name": "Music"}]`. - * `getIndexes`: Alphabetisch gruppierte Artists (`index: [{name: "A", artist: [...]}]`). - * `getArtists`: Identische Alphabet-Struktur für ID3-basiertes Browsing (`artists: {ignoredArticles: "The El La Los Las Le Les", index: [...]}`). - * `getArtist(id)`: Artist-Details inkl. Liste aller zugehörigen `album`-Objekte. - * `getAlbum(id)`: Album-Details inkl. aller `song`-Objekte (sortiert nach `discNumber`, `trackNumber`). - * `getSong(id)`: Einzelnes Song-Objekt. - * `search3(query, artistCount, artistOffset, albumCount, albumOffset, songCount, songOffset)`: SQL-`LIKE`-Suche über Artists, Alben und Songs (`query=""` darf leere oder paginierte Ergebnisse liefern). -3. **Home-Feeds:** - * `getAlbumList2(type, size, offset, fromYear, toYear, genre)`: Unterstützt `type` = `newest`, `recent`, `frequent`, `random`, `alphabeticalByName`, `alphabeticalByArtist`, `starred`, `byYear`, `byGenre`. - * `getRandomSongs(size, genre, fromYear, toYear)`: Zufällige Songs aus der DB. -4. **Media & Artwork:** - * `stream(id, maxBitRate, format)`: Liefert die Datei via `call.respondFile(file)` aus (Direct Play; `PartialContent`-Plugin übernimmt `Range`-Requests). Setzt `Content-Type` passend zur Datei. - * `download(id)`: Wie `stream`, zusätzlich mit `Content-Disposition: attachment; filename="..."`. - * `getCoverArt(id, size)`: Lädt das gecachte Cover aus `DATA_DIR/covers/{id}.jpg`. Falls `size` (Int) angegeben ist, skaliert `Thumbnailator` das Bild proportional auf `size x size` und cached die skalierte Variante (`{id}_{size}.jpg`). - * `getLyricsBySongId(id)`: Liest eingebettete Lyrics (`FieldKey.LYRICS`) oder eine gleichnamige `.lrc`-Datei neben der Audiodatei und gibt sie im OpenSubsonic-`lyricsList`-Format zurück. -5. **Interaktion & Playlists:** - * `scrobble(id, time, submission)`: Bei `submission=true` (Default) `play_count + 1` und `last_played_at` aktualisieren. - * `star(id, albumId, artistId)` / `unstar(id, albumId, artistId)`: Setzt bzw. löscht `starred_at`. - * `setRating(id, rating)`: Setzt `user_rating` (1–5; bei `0` auf `null`). - * `getPlaylists`, `getPlaylist(id)`, `createPlaylist(playlistId, name, songId)`, `updatePlaylist(playlistId, name, comment, public, songIdToAdd, songIndexToRemove)`, `deletePlaylist(playlistId)`. +All timestamps are ISO 8601 in UTC. --- -## 7. Schrittweise Implementierungs-Reihenfolge +## 6. Configuration -Setze das Projekt inkrementell in folgenden Schritten um und verifiziere jeden Schritt über `./gradlew test` bzw. `curl`: +### 6.1 `library.yaml` (ConfigMap) -1. **Setup & DB:** Erstelle `build.gradle.kts`, `AppConfig.kt`, `DatabaseFactory.kt` (inkl. SQLite WAL-Pragma) und `Tables.kt`. -2. **Scanner & Cover-Cache:** Implementiere `IdGenerator.kt`, `TagExtractor.kt` (`jaudiotagger`), `CoverArtService.kt` (`Thumbnailator`) und `MediaScanner.kt` (inkl. Entfernen gelöschter Dateien aus der DB). Führe beim Serverstart automatisch einen initialen Scan aus, falls die DB leer ist. -3. **Ktor Core & Auth:** Konfiguriere Ktor mit `PartialContent`, `ContentNegotiation` (`ignoreUnknownKeys = true`, `encodeDefaults = true`), `SubsonicAuth` und dem `SubsonicResponse`-Wrapper. -4. **Endpoints (Browsing + Media):** Implementiere System-, Browsing- und Media-Routes (`stream`, `download`, `getCoverArt`). -5. **Endpoints (Sync + Interaktion + Playlists):** Implementiere `getAlbumList2`, `search3`, `scrobble`, `star`/`unstar`, `setRating` und alle Playlist-Endpunkte. -6. **Containerisierung:** Erstelle ein Multi-Stage `Dockerfile` (Gradle Build -> `eclipse-temurin:21-jre-alpine` Runtime mit `-XX:+UseSerialGC -Xmx256m`) sowie eine `docker-compose.yml` mit Volumes für `/music:ro` und `/data`. -7. **Automatisierte Tests:** Schreibe Ktor-Integrationstests (`ktor-server-test-host`) für Auth-Hashing, deterministische IDs, `Range`-Header (`206 Partial Content`) beim Streaming und den kompletten Browsing-Flow (`getArtists` -> `getArtist` -> `getAlbum` -> `stream`). +```yaml +library: + folders: + - id: 1 + name: "Alice — Music" + type: music + path: /mnt/media/music/alice + - id: 2 + name: "Bob — Music" + type: music + path: /mnt/media/music/bob + - id: 10 + name: "Audiobooks & Podcasts" + type: longform + path: /mnt/media/longform +``` + +### 6.2 `users.yaml` (Vault-managed Secret) + +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. + +```yaml +users: + - name: alice + password: "" + admin: true + folders: [1] + - name: bob + password: "" + admin: false + folders: [2] +``` + +- 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). + +### 6.3 Environment variables + +| Variable | Default | Purpose | +| --- | --- | --- | +| `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 | + +### 6.4 Local development + +```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/* +./gradlew run +``` + +The database and covers are written to `./data`. `config/users.yaml` is git-ignored. + +--- + +## 7. MVP Endpoint Specification + +All endpoints live under `/rest/{endpoint}` and `/rest/{endpoint}.view`. + +### 7.1 Authentication (`SubsonicAuth`) + +For every `/rest/*` call (except an optional health check): + +- `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. + +### 7.2 System & scan + +- `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}}`. + +### 7.3 Browsing & search + +- `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. + +### 7.4 Home feeds + +- `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. + +### 7.5 Media & artwork + +- `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. + +### 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. + +No `createUser` / `updateUser` / `deleteUser` endpoints: config/Vault is the source of truth. + +--- + +## 8. Scanner + +- 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). + +Cover extraction order: embedded APIC frame → `cover.jpg`/`folder.jpg`/`front.jpg` next to the file → album directory → none. + +--- + +## 9. Deployment (k3s + Helm) + +### 9.1 Image + +- Multi-stage Dockerfile: Gradle build → `eclipse-temurin:21-jre-alpine` with `ffmpeg` installed. +- 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/tap-tap/audiomanager:` (registry paths must be lowercase). +- Gitea Actions builds and pushes on tags; `imagePullSecret` is provided by the cluster. + +### 9.2 Helm chart + +`charts/musicmanager` with values for: + +- image repository/tag, `imagePullSecrets` +- `library` config (folders) rendered into a ConfigMap +- `users.existingSecret` + key (Vault-managed; never put passwords in values) +- ingress host `subsonic.tap-tap.win`, ingress class, TLS via cluster issuer +- `/data` PVC (size, storage class) +- `hostPath` mounts: `/mnt/media/music` and `/mnt/media/longform`, read-only +- no node pinning: every schedulable node must expose the same mounts (documented) +- resource requests/limits, security context, liveness/readiness probes (`/health`) +- optional `nodeSelector`/`tolerations` for future use + +The server fails its readiness probe if a configured root path is missing or unreadable. + +### 9.3 Operations + +- 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. + +--- + +## 10. Testing + +- 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 + - transcoding: `maxBitRate` produces MP3, `timeOffset` seeks (skipped when `ffmpeg` is unavailable) + +--- + +## 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. +- [ ] 4. **Browsing & media:** system, browsing, genre and media routes (`stream`, `download`, `getCoverArt`). +- [ ] 5. **Transcoding:** `FfmpegTranscoder.kt`, `maxBitRate`/`format`/`timeOffset`, extension declaration. +- [ ] 6. **Interaction & playlists:** `getAlbumList2`, `getRandomSongs`, `getStarred2`, `search3`, `scrobble`, `star`/`unstar`, `setRating`, bookmarks, playlists. +- [ ] 7. **Packaging:** multi-stage Dockerfile (with ffmpeg), Helm chart, Gitea Actions workflow. +- [ ] 8. **Tests:** integration suite as described above, plus a `curl` smoke script. + +--- + +## 12. Open Items / Assumptions + +1. **Gitea registry path:** image assumed to be `gitea.tap-tap.win/tap-tap/audiomanager` (lowercased repo `TapTap/AudioManager`). +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. diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..de54396 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,81 @@ +import org.jetbrains.kotlin.gradle.dsl.JvmTarget + +plugins { + kotlin("jvm") version "2.1.20" + kotlin("plugin.serialization") version "2.1.20" + application + id("com.gradleup.shadow") version "8.3.6" +} + +group = "win.taptap" +version = "0.1.0" + +repositories { + mavenCentral() +} + +kotlin { + jvmToolchain(21) + compilerOptions { + jvmTarget.set(JvmTarget.JVM_21) + } +} + +application { + mainClass.set("win.taptap.musicmanager.ApplicationKt") +} + +dependencies { + // Ktor + implementation("io.ktor:ktor-server-core-jvm:3.1.2") + implementation("io.ktor:ktor-server-netty-jvm:3.1.2") + implementation("io.ktor:ktor-server-content-negotiation-jvm:3.1.2") + implementation("io.ktor:ktor-serialization-kotlinx-json-jvm:3.1.2") + implementation("io.ktor:ktor-server-partial-content-jvm:3.1.2") + implementation("io.ktor:ktor-server-status-pages-jvm:3.1.2") + implementation("io.ktor:ktor-server-call-logging-jvm:3.1.2") + implementation("io.ktor:ktor-server-auto-head-response-jvm:3.1.2") + + // Database + implementation("org.jetbrains.exposed:exposed-core:0.60.0") + implementation("org.jetbrains.exposed:exposed-jdbc:0.60.0") + implementation("org.jetbrains.exposed:exposed-java-time:0.60.0") + implementation("org.xerial:sqlite-jdbc:3.49.1.0") + implementation("com.zaxxer:HikariCP:6.2.1") + implementation("org.flywaydb:flyway-core:11.8.2") + + // Media + implementation("net.jthink:jaudiotagger:3.0.1") + implementation("net.coobird:thumbnailator:0.4.20") + + // Config & logging + implementation("org.yaml:snakeyaml:2.7") + implementation("ch.qos.logback:logback-classic:1.5.17") + implementation("io.github.oshai:kotlin-logging-jvm:7.0.0") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.1") + + // Tests + testImplementation("io.ktor:ktor-server-test-host-jvm:3.1.2") + testImplementation(kotlin("test-junit5")) + testImplementation("org.junit.jupiter:junit-jupiter:5.11.4") +} + +tasks.test { + useJUnitPlatform() + testLogging { + events("passed", "skipped", "failed") + } +} + +tasks.withType().configureEach { + options.encoding = "UTF-8" +} + +tasks.shadowJar { + archiveClassifier.set("all") + mergeServiceFiles() +} + +tasks.build { + dependsOn(tasks.shadowJar) +} diff --git a/config/library.example.yaml b/config/library.example.yaml new file mode 100644 index 0000000..182d566 --- /dev/null +++ b/config/library.example.yaml @@ -0,0 +1,14 @@ +# Example library configuration. Mount the real file as a ConfigMap. +# +# Folder IDs are stable identifiers used by songs and users. Never reuse an ID +# for a different path. +library: + folders: + - id: 1 + name: "Music" + type: music + path: /mnt/media/music + - id: 10 + name: "Audiobooks & Podcasts" + type: longform + path: /mnt/media/longform diff --git a/config/users.example.yaml b/config/users.example.yaml new file mode 100644 index 0000000..954a90b --- /dev/null +++ b/config/users.example.yaml @@ -0,0 +1,10 @@ +# Example users configuration. In the cluster this file comes from a +# Vault-managed Secret; never commit a real one. +# +# Long-form folders are shared automatically, so users only list their music +# folders here. +users: + - name: admin + password: "change-me" + admin: true + folders: [1] diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..a400b00 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,4 @@ +org.gradle.jvmargs=-Xmx1g -Dfile.encoding=UTF-8 +org.gradle.parallel=true +org.gradle.caching=true +kotlin.code.style=official diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..1b33c55baabb587c669f562ae36f953de2481846 GIT binary patch literal 43764 zcma&OWmKeVvL#I6?i3D%6z=Zs?ofE*?rw#G$eqJB ziT4y8-Y@s9rkH0Tz>ll(^xkcTl)CY?rS&9VNd66Yc)g^6)JcWaY(5$5gt z8gr3SBXUTN;~cBgz&})qX%#!Fxom2Yau_`&8)+6aSN7YY+pS410rRUU*>J}qL0TnJ zRxt*7QeUqTh8j)Q&iavh<}L+$Jqz))<`IfKussVk%%Ah-Ti?Eo0hQH!rK%K=#EAw0 zwq@@~XNUXRnv8$;zv<6rCRJ6fPD^hfrh;0K?n z=p!u^3xOgWZ%f3+?+>H)9+w^$Tn1e;?UpVMJb!!;f)`6f&4|8mr+g)^@x>_rvnL0< zvD0Hu_N>$(Li7|Jgu0mRh&MV+<}`~Wi*+avM01E)Jtg=)-vViQKax!GeDc!xv$^mL z{#OVBA$U{(Zr8~Xm|cP@odkHC*1R8z6hcLY#N@3E-A8XEvpt066+3t9L_6Zg6j@9Q zj$$%~yO-OS6PUVrM2s)(T4#6=JpI_@Uz+!6=GdyVU?`!F=d;8#ZB@(5g7$A0(`eqY z8_i@3w$0*es5mrSjhW*qzrl!_LQWs4?VfLmo1Sd@Ztt53+etwzAT^8ow_*7Jp`Y|l z*UgSEwvxq+FYO!O*aLf-PinZYne7Ib6ny3u>MjQz=((r3NTEeU4=-i0LBq3H-VJH< z^>1RE3_JwrclUn9vb7HcGUaFRA0QHcnE;6)hn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L16P)ERWQlY4%Y`-5aM9mZ{eKPUgI!~J3Z zkMd5A_p&v?V-o-6TUa8BndiX?ooviev(DKw=*bBVOW|=zps9=Yl|-R5@yJe*BPzN}a0mUsLn{4LfjB_oxpv(mwq# zSY*%E{iB)sNvWfzg-B!R!|+x(Q|b@>{-~cFvdDHA{F2sFGA5QGiIWy#3?P2JIpPKg6ncI^)dvqe`_|N=8 '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..5eed7ee --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..242bdf1 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "musicmanager" diff --git a/src/main/kotlin/win/taptap/musicmanager/Application.kt b/src/main/kotlin/win/taptap/musicmanager/Application.kt new file mode 100644 index 0000000..1389a16 --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/Application.kt @@ -0,0 +1,109 @@ +package win.taptap.musicmanager + +import io.ktor.http.HttpStatusCode +import io.ktor.serialization.kotlinx.json.json +import io.ktor.server.application.install +import io.ktor.server.engine.embeddedServer +import io.ktor.server.netty.Netty +import io.ktor.server.plugins.autohead.AutoHeadResponse +import io.ktor.server.plugins.calllogging.CallLogging +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.respondText +import io.ktor.server.routing.get +import io.ktor.server.routing.routing +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.job +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.json.Json +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.db.ConfigRepository +import win.taptap.musicmanager.db.DatabaseFactory +import win.taptap.musicmanager.db.MediaRepository +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 + +private val log = LoggerFactory.getLogger("win.taptap.musicmanager.Application") + +fun main() { + val config = AppConfig.fromEnv() + + val library = LibraryConfig.load(config.libraryConfigPath).also { it.validatePaths() } + val users = UsersConfig.load(config.usersFile).also { it.validateAgainst(library) } + + val db = DatabaseFactory.connect(config) + try { + ConfigRepository.sync(library, users) + + val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + val scanner = MediaScanner(library, CoverArtService(config.dataDir)) + if (MediaRepository.countSongs() == 0L) { + log.info("Song table is empty, starting initial library scan") + scanner.start(applicationScope) + } + + val server = embeddedServer(Netty, port = config.port, host = "0.0.0.0") { + install(ContentNegotiation) { + json( + Json { + ignoreUnknownKeys = true + encodeDefaults = true + explicitNulls = false + }, + ) + } + install(PartialContent) + install(AutoHeadResponse) + install(CallLogging) + install(StatusPages) { + exception { call, cause -> + log.error("Unhandled exception for ${call.request.path()}", cause) + if (call.request.path().startsWith("/rest/")) { + call.respondSubsonicError(0, "Internal server error") + } else { + call.respondText("Internal server error", status = HttpStatusCode.InternalServerError) + } + } + } + + routing { + get("/health") { call.respondText("ok") } + subsonicRoutes( + users = users, + startScan = { scanner.start(applicationScope) }, + scanStatus = { scanner.status() }, + ) + } + } + + val scopeJob = applicationScope.coroutineContext.job + Runtime.getRuntime().addShutdownHook( + Thread { + runBlocking { scopeJob.cancelAndJoin() } + runCatching { server.stop(1_000, 5_000) } + runCatching { db.close() } + }, + ) + + log.info( + "Starting MusicManager on port {} with {} library folders and {} users", + config.port, + library.folders.size, + users.users.size, + ) + server.start(wait = true) + } catch (t: Throwable) { + runCatching { db.close() } + throw t + } +} diff --git a/src/main/kotlin/win/taptap/musicmanager/config/AppConfig.kt b/src/main/kotlin/win/taptap/musicmanager/config/AppConfig.kt new file mode 100644 index 0000000..7f26911 --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/config/AppConfig.kt @@ -0,0 +1,39 @@ +package win.taptap.musicmanager.config + +import java.nio.file.Path + +/** + * Application-level configuration, sourced exclusively from environment variables. + * + * Library folders and users are not part of this class: they live in the YAML files + * referenced here so they can be managed by ConfigMaps/Vault. + */ +data class AppConfig( + val port: Int, + val dataDir: Path, + val libraryConfigPath: Path, + val usersFile: Path, + val ffmpegPath: String, +) { + val databasePath: Path get() = dataDir.resolve("musicmanager.db") + + companion object { + fun fromEnv(env: Map = System.getenv()): AppConfig { + fun value(key: String, default: String): String = + env[key]?.takeIf { it.isNotBlank() } ?: default + + val rawPort = value("PORT", "8080") + val port = rawPort.toIntOrNull() + ?: throw IllegalArgumentException("PORT must be an integer, got: $rawPort") + require(port in 1..65535) { "PORT must be between 1 and 65535, got: $port" } + + return AppConfig( + port = port, + dataDir = Path.of(value("DATA_DIR", "./data")), + libraryConfigPath = Path.of(value("LIBRARY_CONFIG", "./config/library.yaml")), + usersFile = Path.of(value("USERS_FILE", "./config/users.yaml")), + ffmpegPath = value("FFMPEG_PATH", "ffmpeg"), + ) + } + } +} diff --git a/src/main/kotlin/win/taptap/musicmanager/config/LibraryConfig.kt b/src/main/kotlin/win/taptap/musicmanager/config/LibraryConfig.kt new file mode 100644 index 0000000..1453999 --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/config/LibraryConfig.kt @@ -0,0 +1,130 @@ +package win.taptap.musicmanager.config + +import java.nio.file.Files +import java.nio.file.Path +import org.yaml.snakeyaml.LoaderOptions +import org.yaml.snakeyaml.Yaml +import org.yaml.snakeyaml.constructor.SafeConstructor + +enum class FolderType { + MUSIC, + LONGFORM, +} + +data class MusicFolder( + val id: Int, + val name: String, + val type: FolderType, + val path: Path, +) + +/** + * Library folders from `library.yaml`. Folder IDs are stable and referenced by songs, + * so they must never be reused for a different path. + */ +data class LibraryConfig(val folders: List) { + + val longformFolderIds: Set = folders + .filter { it.type == FolderType.LONGFORM } + .map { it.id } + .toSet() + + fun byId(id: Int): MusicFolder? = folders.firstOrNull { it.id == id } + + /** Fails fast at startup if a configured root is missing or unreadable. */ + fun validatePaths() { + folders.forEach { folder -> + require(Files.isDirectory(folder.path)) { + "Library folder ${folder.id} (${folder.name}) is not a directory: ${folder.path}" + } + require(Files.isReadable(folder.path)) { + "Library folder ${folder.id} (${folder.name}) is not readable: ${folder.path}" + } + } + } + + companion object { + fun load(path: Path): LibraryConfig { + require(Files.isRegularFile(path)) { "Library config not found: $path" } + val text = Files.readString(path) + return parse(text) + } + + fun parse(text: String): LibraryConfig { + val root = parseYaml(text) + val library = root["library"].asMapping("library") + val rawFolders = library["folders"].asList("library.folders") + + val folders = rawFolders.mapIndexed { index, raw -> + val item = raw.asMapping("library.folders[$index]") + val id = item["id"].asInt("library.folders[$index].id") + require(id > 0) { "library.folders[$index].id must be positive" } + + val name = item["name"].asString("library.folders[$index].name").trim() + require(name.isNotEmpty()) { "library.folders[$index].name must not be blank" } + + val rawType = item["type"].asString("library.folders[$index].type") + val type = runCatching { FolderType.valueOf(rawType.trim().uppercase()) } + .getOrElse { + throw IllegalArgumentException( + "library.folders[$index].type must be 'music' or 'longform', got: $rawType", + ) + } + + val rawPath = item["path"].asString("library.folders[$index].path") + val path = Path.of(rawPath).toAbsolutePath().normalize() + + MusicFolder(id = id, name = name, type = type, path = path) + } + + require(folders.isNotEmpty()) { "library.folders must not be empty" } + + folders.groupBy { it.id }.forEach { (id, duplicates) -> + require(duplicates.size == 1) { "Duplicate library folder id: $id" } + } + folders.groupBy { it.path }.forEach { (path, duplicates) -> + require(duplicates.size == 1) { "Duplicate library folder path: $path" } + } + + return LibraryConfig(folders) + } + + private fun parseYaml(text: String): Map { + val loaded = Yaml(SafeConstructor(LoaderOptions())).load(text) + ?: throw IllegalArgumentException("Config must not be empty") + @Suppress("UNCHECKED_CAST") + return loaded as? Map + ?: throw IllegalArgumentException("Config root must be a YAML mapping") + } + } +} + +internal fun Any?.asMapping(what: String): Map { + @Suppress("UNCHECKED_CAST") + return this as? Map + ?: throw IllegalArgumentException("$what must be a mapping") +} + +internal fun Any?.asList(what: String): List = + this as? List ?: throw IllegalArgumentException("$what must be a list") + +internal fun Any?.asString(what: String): String = + this as? String ?: throw IllegalArgumentException("$what must be a string") + +internal fun Any?.asInt(what: String): Int = when (this) { + is Int -> this + is Long -> toInt() + is String -> toIntOrNull() + ?: throw IllegalArgumentException("$what must be an integer") + else -> throw IllegalArgumentException("$what must be an integer") +} + +internal fun Any?.asBoolean(what: String): Boolean = when (this) { + is Boolean -> this + is String -> when (trim().lowercase()) { + "true", "yes", "1" -> true + "false", "no", "0" -> false + else -> throw IllegalArgumentException("$what must be a boolean") + } + else -> throw IllegalArgumentException("$what must be a boolean") +} diff --git a/src/main/kotlin/win/taptap/musicmanager/config/UsersConfig.kt b/src/main/kotlin/win/taptap/musicmanager/config/UsersConfig.kt new file mode 100644 index 0000000..1121b4e --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/config/UsersConfig.kt @@ -0,0 +1,96 @@ +package win.taptap.musicmanager.config + +import java.nio.file.Files +import java.nio.file.Path +import org.yaml.snakeyaml.LoaderOptions +import org.yaml.snakeyaml.Yaml +import org.yaml.snakeyaml.constructor.SafeConstructor + +/** + * User accounts. Passwords are supplied by a Vault-managed secret and are never + * persisted in SQLite. The `toString` implementation redacts the password so it + * cannot leak through logs or error messages. + */ +data class UserAccount( + val name: String, + val password: String, + val admin: Boolean, + val folders: Set, +) { + /** Music folders assigned to the user plus every shared long-form folder. */ + fun visibleFolderIds(library: LibraryConfig): Set = + folders + library.longformFolderIds + + override fun toString(): String = + "UserAccount(name=$name, admin=$admin, folders=$folders, password=***)" +} + +data class UsersConfig(val users: List) { + + init { + require(users.isNotEmpty()) { "users.yaml must define at least one user" } + users.groupBy { it.name }.forEach { (name, duplicates) -> + require(duplicates.size == 1) { "Duplicate user name: $name" } + } + } + + fun byName(name: String): UserAccount? = users.firstOrNull { it.name == name } + + fun validateAgainst(library: LibraryConfig) { + val knownFolderIds = library.folders.map { it.id }.toSet() + users.forEach { user -> + val unknown = user.folders - knownFolderIds + require(unknown.isEmpty()) { + "User '${user.name}' references unknown library folders: ${unknown.sorted()}" + } + require(user.visibleFolderIds(library).isNotEmpty()) { + "User '${user.name}' has no visible library folders" + } + } + } + + companion object { + private val NAME_PATTERN = Regex("[A-Za-z0-9._-]{1,64}") + + fun load(path: Path): UsersConfig { + require(Files.isRegularFile(path)) { "Users file not found: $path" } + val text = Files.readString(path) + return parse(text) + } + + fun parse(text: String): UsersConfig { + val loaded = Yaml(SafeConstructor(LoaderOptions())).load(text) + ?: throw IllegalArgumentException("Users config must not be empty") + @Suppress("UNCHECKED_CAST") + val root = loaded as? Map + ?: throw IllegalArgumentException("Users config root must be a YAML mapping") + + val rawUsers = root["users"].asList("users") + val users = rawUsers.mapIndexed { index, raw -> + val item = raw.asMapping("users[$index]") + val name = item["name"].asString("users[$index].name").trim() + require(NAME_PATTERN.matches(name)) { + "users[$index].name must match ${NAME_PATTERN.pattern}, got: $name" + } + + val password = item["password"].asString("users[$index].password") + require(password.isNotEmpty()) { "users[$index].password must not be empty" } + + val admin = item["admin"]?.asBoolean("users[$index].admin") ?: false + + val folders = when (val rawFolders = item["folders"]) { + null -> emptySet() + else -> rawFolders.asList("users[$index].folders") + .mapIndexed { folderIndex, value -> + value.asInt("users[$index].folders[$folderIndex]") + } + .toSet() + } + + UserAccount(name = name, password = password, admin = admin, folders = folders) + } + + return UsersConfig(users) + } + } +} diff --git a/src/main/kotlin/win/taptap/musicmanager/db/ConfigRepository.kt b/src/main/kotlin/win/taptap/musicmanager/db/ConfigRepository.kt new file mode 100644 index 0000000..d1b8771 --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/db/ConfigRepository.kt @@ -0,0 +1,71 @@ +package win.taptap.musicmanager.db + +import java.time.Instant +import org.jetbrains.exposed.sql.deleteWhere +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.config.LibraryConfig +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. + */ +object ConfigRepository { + + fun sync(library: LibraryConfig, users: UsersConfig) { + val now = Instant.now().toString() + + transaction { + val folderIds = library.folders.map { it.id }.toSet() + val obsoleteFolderIds = MusicFoldersTable.selectAll() + .map { it[MusicFoldersTable.id] } + .filterNot { it in folderIds } + obsoleteFolderIds.forEach { folderId -> + MusicFoldersTable.deleteWhere { + it.run { MusicFoldersTable.id eq folderId } + } + } + + library.folders.forEach { folder -> + MusicFoldersTable.insertIgnore { + it[id] = folder.id + it[name] = folder.name + it[type] = folder.type.name.lowercase() + it[rootPath] = folder.path.toString() + } + MusicFoldersTable.update({ MusicFoldersTable.id eq folder.id }) { + it[name] = folder.name + it[type] = folder.type.name.lowercase() + it[rootPath] = folder.path.toString() + } + } + + val userNames = users.users.map { it.name }.toSet() + val obsoleteUserNames = UsersTable.selectAll() + .map { it[UsersTable.name] } + .filterNot { it in userNames } + obsoleteUserNames.forEach { userName -> + UsersTable.deleteWhere { + it.run { UsersTable.name eq userName } + } + } + + users.users.forEach { user -> + UsersTable.insertIgnore { + it[name] = user.name + it[isAdmin] = user.admin + it[updatedAt] = now + } + UsersTable.update({ UsersTable.name eq user.name }) { + it[isAdmin] = user.admin + it[updatedAt] = now + } + } + } + } +} diff --git a/src/main/kotlin/win/taptap/musicmanager/db/DatabaseFactory.kt b/src/main/kotlin/win/taptap/musicmanager/db/DatabaseFactory.kt new file mode 100644 index 0000000..406c381 --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/db/DatabaseFactory.kt @@ -0,0 +1,78 @@ +package win.taptap.musicmanager.db + +import com.zaxxer.hikari.HikariConfig +import com.zaxxer.hikari.HikariDataSource +import java.nio.file.Files +import org.flywaydb.core.Flyway +import org.jetbrains.exposed.sql.Database +import org.jetbrains.exposed.sql.transactions.TransactionManager +import win.taptap.musicmanager.config.AppConfig + +/** + * Owns the SQLite connection pool and the Exposed database handle. + * + * WAL mode lets readers continue while the scanner writes. `busy_timeout` keeps + * concurrent writers from failing immediately, and `foreign_keys` is per SQLite + * connection, so it is set through the JDBC URL for every pooled connection. + */ +class DatabaseHandle( + val dataSource: HikariDataSource, + val database: Database, +) : AutoCloseable { + override fun close() { + TransactionManager.closeAndUnregister(database) + dataSource.close() + } +} + +object DatabaseFactory { + + fun connect(config: AppConfig): DatabaseHandle { + Files.createDirectories(config.dataDir) + + val dataSource = HikariDataSource( + HikariConfig().apply { + jdbcUrl = buildString { + append("jdbc:sqlite:") + append(config.databasePath.toAbsolutePath()) + append("?journal_mode=WAL") + append("&foreign_keys=on") + append("&busy_timeout=5000") + append("&synchronous=NORMAL") + } + driverClassName = "org.sqlite.JDBC" + maximumPoolSize = 4 + minimumIdle = 1 + poolName = "sqlite-pool" + isAutoCommit = true + }, + ) + + // journal_mode is persistent, but verify it so a misconfigured filesystem + // (for example a network mount without WAL support) fails loudly at startup. + dataSource.connection.use { connection -> + connection.createStatement().use { statement -> + statement.executeQuery("PRAGMA journal_mode").use { result -> + check(result.next()) { "Could not read SQLite journal_mode" } + val mode = result.getString(1) + check(mode.equals("wal", ignoreCase = true)) { + "SQLite is not in WAL mode (got: $mode). Check the data directory filesystem." + } + } + } + } + + val database = Database.connect(dataSource) + migrate(dataSource) + + return DatabaseHandle(dataSource, database) + } + + fun migrate(dataSource: HikariDataSource) { + Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration") + .load() + .migrate() + } +} diff --git a/src/main/kotlin/win/taptap/musicmanager/db/MediaRepository.kt b/src/main/kotlin/win/taptap/musicmanager/db/MediaRepository.kt new file mode 100644 index 0000000..9754ac8 --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/db/MediaRepository.kt @@ -0,0 +1,233 @@ +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.insertIgnore +import org.jetbrains.exposed.sql.selectAll +import org.jetbrains.exposed.sql.transactions.transaction +import org.jetbrains.exposed.sql.update +import win.taptap.musicmanager.scanner.ArtistRef +import win.taptap.musicmanager.scanner.ExtractedTrack +import win.taptap.musicmanager.util.IdGenerator +import win.taptap.musicmanager.util.SortNames + +data class ExistingSong( + val id: String, + val fileMtime: Long, + val size: Long, +) + +/** Persistence for the scanner. Per-user state is never touched when metadata is updated. */ +object MediaRepository { + + fun findExisting(folderId: Int, relativePath: String): ExistingSong? = transaction { + SongsTable.selectAll() + .where { + (SongsTable.folderId eq folderId) and (SongsTable.relativePath eq relativePath) + } + .singleOrNull() + ?.let { + ExistingSong( + id = it[SongsTable.id], + fileMtime = it[SongsTable.fileMtime], + size = it[SongsTable.size], + ) + } + } + + fun upsertTrack(track: ExtractedTrack) { + val now = Instant.now().toString() + + transaction { + (track.albumArtists + track.artists).distinctBy { it.id }.forEach(::upsertArtist) + + val albumSearch = IdGenerator.normalize( + "${track.albumTitle} ${track.albumArtists.joinToString(" ") { it.name }}", + ) + val albumExists = AlbumsTable.selectAll() + .where { AlbumsTable.id eq track.albumId } + .any() + + if (albumExists) { + AlbumsTable.update({ AlbumsTable.id eq track.albumId }) { + it[name] = track.albumTitle + if (track.year != null) it[year] = track.year + it[searchText] = albumSearch + } + } else { + AlbumsTable.insert { + it[id] = track.albumId + it[name] = track.albumTitle + it[year] = track.year + it[createdAt] = now + it[searchText] = albumSearch + } + } + + AlbumArtistsTable.deleteWhere { + it.run { AlbumArtistsTable.albumId eq track.albumId } + } + track.albumArtists.forEachIndexed { index, artist -> + AlbumArtistsTable.insertIgnore { + it[albumId] = track.albumId + it[artistId] = artist.id + it[position] = index + } + } + + val existingByPath = SongsTable.selectAll() + .where { + (SongsTable.folderId eq track.folderId) and + (SongsTable.relativePath eq track.relativePath) + } + .singleOrNull() + + val existingId = existingByPath?.get(SongsTable.id) + if (existingId != null && existingId != track.songId) { + SongsTable.deleteWhere { it.run { SongsTable.id eq existingId } } + } + + val songExists = existingId == track.songId || + SongsTable.selectAll().where { SongsTable.id eq track.songId }.any() + + if (songExists) { + SongsTable.update({ SongsTable.id eq track.songId }) { + it[albumId] = track.albumId + it[folderId] = track.folderId + it[title] = track.title + it[displayArtist] = track.displayArtist + it[albumName] = track.albumTitle + it[trackNumber] = track.trackNumber + it[discNumber] = track.discNumber + it[year] = track.year + it[duration] = track.durationSeconds + it[bitRate] = track.bitRate + it[size] = track.size + it[suffix] = track.suffix + it[contentType] = track.contentType + it[relativePath] = track.relativePath + it[fileMtime] = track.fileMtime + it[searchText] = track.searchText + } + } else { + SongsTable.insert { + it[id] = track.songId + it[albumId] = track.albumId + it[folderId] = track.folderId + it[title] = track.title + it[displayArtist] = track.displayArtist + it[albumName] = track.albumTitle + it[trackNumber] = track.trackNumber + it[discNumber] = track.discNumber + it[year] = track.year + it[duration] = track.durationSeconds + it[bitRate] = track.bitRate + it[size] = track.size + it[suffix] = track.suffix + it[contentType] = track.contentType + it[relativePath] = track.relativePath + it[fileMtime] = track.fileMtime + it[createdAt] = now + it[searchText] = track.searchText + } + } + + SongArtistsTable.deleteWhere { it.run { SongArtistsTable.songId eq track.songId } } + track.artists.forEachIndexed { index, artist -> + SongArtistsTable.insertIgnore { + it[songId] = track.songId + it[artistId] = artist.id + it[position] = index + } + } + + SongGenresTable.deleteWhere { it.run { SongGenresTable.songId eq track.songId } } + track.genres.forEach { genre -> + SongGenresTable.insertIgnore { + it[songId] = track.songId + it[this.genre] = genre + } + } + } + } + + fun setAlbumCover(albumId: String) { + transaction { + AlbumsTable.update({ AlbumsTable.id eq albumId }) { + it[coverArt] = albumId + } + } + } + + fun deleteSongsNotIn(seenSongIds: Set) { + transaction { + val obsolete = SongsTable.selectAll() + .map { it[SongsTable.id] } + .filterNot { it in seenSongIds } + + obsolete.forEach { songId -> + SongsTable.deleteWhere { it.run { SongsTable.id eq songId } } + } + + exec("DELETE FROM albums WHERE id NOT IN (SELECT DISTINCT album_id FROM songs)") + exec( + """ + DELETE FROM artists WHERE id NOT IN ( + SELECT artist_id FROM song_artists + UNION + SELECT artist_id FROM album_artists + ) + """.trimIndent(), + ) + } + } + + /** Recomputes album/artist genre aggregates from the song-level tags. */ + fun rebuildAggregates() { + transaction { + exec("DELETE FROM album_genres") + exec( + """ + INSERT INTO album_genres (album_id, genre) + SELECT DISTINCT s.album_id, sg.genre + FROM song_genres sg + JOIN songs s ON s.id = sg.song_id + """.trimIndent(), + ) + + exec("DELETE FROM artist_genres") + exec( + """ + INSERT INTO artist_genres (artist_id, genre) + SELECT DISTINCT sa.artist_id, sg.genre + FROM song_artists sa + JOIN song_genres sg ON sg.song_id = sa.song_id + UNION + SELECT DISTINCT aa.artist_id, ag.genre + FROM album_artists aa + JOIN album_genres ag ON ag.album_id = aa.album_id + """.trimIndent(), + ) + } + } + + fun countSongs(): Long = transaction { + SongsTable.selectAll().count() + } + + private fun upsertArtist(artist: ArtistRef) { + ArtistsTable.insertIgnore { + it[id] = artist.id + it[name] = artist.name + it[sortName] = SortNames.of(artist.name) + it[searchText] = IdGenerator.normalize(artist.name) + } + ArtistsTable.update({ ArtistsTable.id eq artist.id }) { + it[name] = artist.name + it[sortName] = SortNames.of(artist.name) + it[searchText] = IdGenerator.normalize(artist.name) + } + } +} diff --git a/src/main/kotlin/win/taptap/musicmanager/db/Tables.kt b/src/main/kotlin/win/taptap/musicmanager/db/Tables.kt new file mode 100644 index 0000000..9bdce7d --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/db/Tables.kt @@ -0,0 +1,152 @@ +package win.taptap.musicmanager.db + +import org.jetbrains.exposed.sql.ReferenceOption +import org.jetbrains.exposed.sql.Table + +/** Identity tables are reconciled from config/Vault at startup; passwords are never stored. */ +object UsersTable : Table("users") { + val name = varchar("name", 64) + val isAdmin = bool("is_admin").default(false) + val updatedAt = varchar("updated_at", 40) + + override val primaryKey = PrimaryKey(name) +} + +object MusicFoldersTable : Table("music_folders") { + val id = integer("id") + val name = varchar("name", 255) + val type = varchar("type", 16) + val rootPath = text("root_path") + + override val primaryKey = PrimaryKey(id) +} + +object ArtistsTable : Table("artists") { + val id = varchar("id", 32) + val name = text("name") + val sortName = text("sort_name") + val coverArt = varchar("cover_art", 32).nullable() + val searchText = text("search_text") + + override val primaryKey = PrimaryKey(id) +} + +object AlbumsTable : Table("albums") { + val id = varchar("id", 32) + val name = text("name") + val year = integer("year").nullable() + val coverArt = varchar("cover_art", 32).nullable() + val createdAt = varchar("created_at", 40) + val searchText = text("search_text") + + override val primaryKey = PrimaryKey(id) +} + +object AlbumArtistsTable : Table("album_artists") { + val albumId = reference("album_id", AlbumsTable.id, onDelete = ReferenceOption.CASCADE) + val artistId = reference("artist_id", ArtistsTable.id, onDelete = ReferenceOption.CASCADE) + val position = integer("position") + + override val primaryKey = PrimaryKey(albumId, position) +} + +object SongsTable : Table("songs") { + val id = varchar("id", 32) + val albumId = reference("album_id", AlbumsTable.id, onDelete = ReferenceOption.CASCADE) + val folderId = reference("folder_id", MusicFoldersTable.id, onDelete = ReferenceOption.CASCADE) + val title = text("title") + val displayArtist = text("display_artist") + val albumName = text("album_name") + val trackNumber = integer("track_number").nullable() + val discNumber = integer("disc_number").default(1) + val year = integer("year").nullable() + val duration = integer("duration") + val bitRate = integer("bit_rate") + val size = long("size") + val suffix = varchar("suffix", 16) + val contentType = varchar("content_type", 64) + val relativePath = text("relative_path") + val fileMtime = long("file_mtime") + val createdAt = varchar("created_at", 40) + val searchText = text("search_text") + + override val primaryKey = PrimaryKey(id) +} + +object SongArtistsTable : Table("song_artists") { + val songId = reference("song_id", SongsTable.id, onDelete = ReferenceOption.CASCADE) + val artistId = reference("artist_id", ArtistsTable.id, onDelete = ReferenceOption.CASCADE) + val position = integer("position") + + override val primaryKey = PrimaryKey(songId, position) +} + +object SongGenresTable : Table("song_genres") { + val songId = reference("song_id", SongsTable.id, onDelete = ReferenceOption.CASCADE) + val genre = varchar("genre", 255) + + override val primaryKey = PrimaryKey(songId, genre) +} + +object AlbumGenresTable : Table("album_genres") { + val albumId = reference("album_id", AlbumsTable.id, onDelete = ReferenceOption.CASCADE) + val genre = varchar("genre", 255) + + override val primaryKey = PrimaryKey(albumId, genre) +} + +object ArtistGenresTable : Table("artist_genres") { + val artistId = reference("artist_id", ArtistsTable.id, onDelete = ReferenceOption.CASCADE) + val genre = varchar("genre", 255) + + override val primaryKey = PrimaryKey(artistId, genre) +} + +object UserSongStateTable : Table("user_song_state") { + val userName = reference("user_name", UsersTable.name, onDelete = ReferenceOption.CASCADE) + val songId = reference("song_id", SongsTable.id, onDelete = ReferenceOption.CASCADE) + val playCount = integer("play_count").default(0) + val lastPlayedAt = varchar("last_played_at", 40).nullable() + val starredAt = varchar("starred_at", 40).nullable() + val rating = integer("rating").nullable() + + override val primaryKey = PrimaryKey(userName, songId) +} + +object UserStarsTable : Table("user_stars") { + val userName = reference("user_name", UsersTable.name, onDelete = ReferenceOption.CASCADE) + val itemType = varchar("item_type", 16) + val itemId = varchar("item_id", 32) + val starredAt = varchar("starred_at", 40) + + override val primaryKey = PrimaryKey(userName, itemType, itemId) +} + +object BookmarksTable : Table("bookmarks") { + val userName = reference("user_name", UsersTable.name, onDelete = ReferenceOption.CASCADE) + val songId = reference("song_id", SongsTable.id, onDelete = ReferenceOption.CASCADE) + val positionMs = long("position_ms") + val updatedAt = varchar("updated_at", 40) + + override val primaryKey = PrimaryKey(userName, songId) +} + +object PlaylistsTable : Table("playlists") { + 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 createdAt = varchar("created_at", 40) + val changedAt = varchar("changed_at", 40) + + 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) +} diff --git a/src/main/kotlin/win/taptap/musicmanager/scanner/CoverArtService.kt b/src/main/kotlin/win/taptap/musicmanager/scanner/CoverArtService.kt new file mode 100644 index 0000000..61d8d3a --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/scanner/CoverArtService.kt @@ -0,0 +1,136 @@ +package win.taptap.musicmanager.scanner + +import java.awt.image.BufferedImage +import java.io.ByteArrayInputStream +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.StandardCopyOption +import javax.imageio.ImageIO +import kotlin.io.path.name +import net.coobird.thumbnailator.Thumbnails +import org.slf4j.LoggerFactory + +/** + * Extracts, normalises and caches album covers under `DATA_DIR/covers`. + * + * Covers are always stored as JPEG. Original-size files are named `{albumId}.jpg`, + * resized variants `{albumId}_{size}.jpg`. When a cover changes, its variants are + * invalidated. + */ +class CoverArtService(dataDir: Path) { + + private val log = LoggerFactory.getLogger(CoverArtService::class.java) + private val coversDir: Path = dataDir.resolve("covers") + + init { + Files.createDirectories(coversDir) + } + + fun coverFile(albumId: String): Path? = + coversDir.resolve("$albumId.jpg").takeIf { Files.isRegularFile(it) } + + /** + * Stores [bytes] as the album cover. Returns true when a usable cover exists, + * including when the bytes were unchanged. + */ + @Synchronized + fun saveCover(albumId: String, bytes: ByteArray): Boolean { + if (bytes.isEmpty() || bytes.size > MAX_COVER_BYTES) return false + + val image = runCatching { + ImageIO.read(ByteArrayInputStream(bytes)) + }.getOrNull() ?: return false + + val target = coversDir.resolve("$albumId.jpg") + val temp = Files.createTempFile(coversDir, "$albumId-", ".jpg") + + return try { + writeJpeg(image, temp.toFile()) + + if (Files.isRegularFile(target) && Files.mismatch(target, temp) == -1L) { + return true + } + + moveReplacing(temp, target) + deleteVariants(albumId) + true + } catch (e: Exception) { + log.warn("Could not store cover for album {}: {}", albumId, e.message) + false + } finally { + Files.deleteIfExists(temp) + } + } + + /** Returns a cached `size x size` variant, generating it on first request. */ + @Synchronized + fun resizedCover(albumId: String, size: Int): Path? { + require(size in 1..MAX_RESIZE) { "Cover size must be between 1 and $MAX_RESIZE" } + + val base = coverFile(albumId) ?: return null + val target = coversDir.resolve("${albumId}_$size.jpg") + if (Files.isRegularFile(target)) return target + + val temp = Files.createTempFile(coversDir, "${albumId}_$size-", ".jpg") + return try { + Thumbnails.of(base.toFile()) + .size(size, size) + .keepAspectRatio(true) + .outputFormat("jpg") + .toFile(temp.toFile()) + + moveReplacing(temp, target) + target + } catch (e: Exception) { + log.warn("Could not resize cover for album {}: {}", albumId, e.message) + null + } finally { + Files.deleteIfExists(temp) + } + } + + fun findSidecarCover(audioFile: Path): Path? { + val directory = audioFile.parent ?: return null + return SIDECAR_NAMES + .asSequence() + .map { directory.resolve(it) } + .firstOrNull { Files.isRegularFile(it) && Files.size(it) > 0 } + } + + fun readCover(path: Path): ByteArray? = + runCatching { Files.readAllBytes(path) }.getOrNull() + + private fun writeJpeg(image: BufferedImage, target: java.io.File) { + Thumbnails.of(image) + .scale(1.0) + .outputFormat("jpg") + .outputQuality(0.92) + .toFile(target) + } + + private fun moveReplacing(source: Path, target: Path) { + try { + Files.move(source, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE) + } catch (_: java.nio.file.AtomicMoveNotSupportedException) { + Files.move(source, target, StandardCopyOption.REPLACE_EXISTING) + } + } + + private fun deleteVariants(albumId: String) { + Files.list(coversDir).use { stream -> + stream + .filter { it.name.startsWith("${albumId}_") && it.name.endsWith(".jpg") } + .forEach { runCatching { Files.deleteIfExists(it) } } + } + } + + private companion object { + const val MAX_COVER_BYTES = 20 * 1024 * 1024 + const val MAX_RESIZE = 2048 + val SIDECAR_NAMES = listOf( + "cover.jpg", "cover.jpeg", "cover.png", + "folder.jpg", "folder.jpeg", "folder.png", + "front.jpg", "front.jpeg", "front.png", + ) + } +} diff --git a/src/main/kotlin/win/taptap/musicmanager/scanner/MediaScanner.kt b/src/main/kotlin/win/taptap/musicmanager/scanner/MediaScanner.kt new file mode 100644 index 0000000..05e765d --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/scanner/MediaScanner.kt @@ -0,0 +1,125 @@ +package win.taptap.musicmanager.scanner + +import java.nio.file.Files +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicReference +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.launch +import org.slf4j.LoggerFactory +import win.taptap.musicmanager.config.LibraryConfig +import win.taptap.musicmanager.config.MusicFolder +import win.taptap.musicmanager.db.MediaRepository + +/** + * Recursive MP3 scanner with delta updates and orphan cleanup. + * + * Only one scan can run at a time. The file's `(mtime, size)` pair decides whether + * tags need to be re-read; unchanged files are skipped. + */ +class MediaScanner( + private val library: LibraryConfig, + private val coverArtService: CoverArtService, + private val tagExtractor: Mp3TagExtractor = Mp3TagExtractor(), + private val repository: MediaRepository = MediaRepository, +) { + + private val log = LoggerFactory.getLogger(MediaScanner::class.java) + private val running = AtomicBoolean(false) + private val status = AtomicReference(ScanStatus(scanning = false, count = 0)) + + fun status(): ScanStatus = status.get() + + /** Starts a scan in [scope]. Returns false when a scan is already running. */ + fun start(scope: CoroutineScope): Boolean { + if (!running.compareAndSet(false, true)) return false + status.set(ScanStatus(scanning = true, count = 0)) + scope.launch { runScan() } + return true + } + + /** Blocking variant for tests and the startup scan. */ + fun scanBlocking(): ScanStatus { + check(running.compareAndSet(false, true)) { "A scan is already running" } + status.set(ScanStatus(scanning = true, count = 0)) + return runScan() + } + + private fun runScan(): ScanStatus { + var count = 0L + val seenSongIds = mutableSetOf() + var error: String? = null + + try { + library.folders.forEach { folder -> + try { + scanFolder(folder, seenSongIds) { + count++ + status.set(ScanStatus(scanning = true, count = count)) + } + } catch (e: Exception) { + log.error("Could not scan folder ${folder.id} (${folder.path})", e) + } + } + + repository.deleteSongsNotIn(seenSongIds) + repository.rebuildAggregates() + } catch (t: Throwable) { + error = t.message ?: t::class.simpleName + log.error("Library scan failed after $count files", t) + } finally { + running.set(false) + } + + val finalStatus = ScanStatus(scanning = false, count = count, error = error) + status.set(finalStatus) + log.info("Library scan finished: {} files, error={}", count, error) + return finalStatus + } + + private fun scanFolder(folder: MusicFolder, seenSongIds: MutableSet, onFile: () -> Unit) { + Files.walk(folder.path).use { paths -> + paths.filter { Files.isRegularFile(it) }.forEach { file -> + if (!file.fileName.toString().endsWith(".mp3", ignoreCase = true)) { + log.debug("Skipping unsupported file: {}", file) + return@forEach + } + + onFile() + val relativePath = folder.path.relativize(file).joinToString("/") { it.toString() } + val existing = repository.findExisting(folder.id, relativePath) + + try { + val attributes = Files.readAttributes(file, java.nio.file.attribute.BasicFileAttributes::class.java) + val mtime = attributes.lastModifiedTime().toMillis() + val size = attributes.size() + + if (existing != null && existing.fileMtime == mtime && existing.size == size) { + seenSongIds += existing.id + return@forEach + } + + val track = tagExtractor.extract(folder.id, folder.path, file) + if (track == null) { + if (existing != null) seenSongIds += existing.id + log.warn("Could not read MP3 metadata: {}", file) + return@forEach + } + + val coverBytes = track.coverBytes + ?: coverArtService.findSidecarCover(file)?.let(coverArtService::readCover) + + repository.upsertTrack(track) + + if (coverBytes != null && coverArtService.saveCover(track.albumId, coverBytes)) { + repository.setAlbumCover(track.albumId) + } + + seenSongIds += track.songId + } catch (e: Exception) { + if (existing != null) seenSongIds += existing.id + log.warn("Could not index file: $file", e) + } + } + } + } +} diff --git a/src/main/kotlin/win/taptap/musicmanager/scanner/Mp3TagExtractor.kt b/src/main/kotlin/win/taptap/musicmanager/scanner/Mp3TagExtractor.kt new file mode 100644 index 0000000..a870064 --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/scanner/Mp3TagExtractor.kt @@ -0,0 +1,178 @@ +package win.taptap.musicmanager.scanner + +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.attribute.BasicFileAttributes +import java.util.logging.Level +import java.util.logging.Logger +import org.jaudiotagger.audio.AudioFileIO +import org.jaudiotagger.tag.FieldKey +import org.jaudiotagger.tag.Tag +import win.taptap.musicmanager.util.IdGenerator + +data class ArtistRef(val id: String, val name: String) + +data class ExtractedTrack( + val songId: String, + val albumId: String, + val albumArtistId: String, + val albumArtists: List, + val artists: List, + val title: String, + val displayArtist: String, + val albumTitle: String, + val folderId: Int, + val relativePath: String, + val trackNumber: Int?, + val discNumber: Int, + val year: Int?, + val genres: List, + val durationSeconds: Int, + val bitRate: Int, + val size: Long, + val suffix: String, + val contentType: String, + val fileMtime: Long, + val coverBytes: ByteArray?, + val lyrics: String?, +) { + val searchText: String = + IdGenerator.normalize("$title $displayArtist $albumTitle ${albumArtists.joinToString(" ") { it.name }}") +} + +/** + * Reads MP3 metadata with jaudiotagger and applies the documented fallbacks: + * album artist -> artist -> folder name, title -> file name. + */ +class Mp3TagExtractor { + + init { + listOf( + "org.jaudiotagger", + "org.jaudiotagger.audio", + "org.jaudiotagger.tag", + "org.jaudiotagger.tag.id3", + ).forEach { Logger.getLogger(it).level = Level.WARNING } + } + + fun extract(folderId: Int, root: Path, file: Path): ExtractedTrack? { + if (!file.fileName.toString().endsWith(".mp3", ignoreCase = true)) return null + + val attributes = Files.readAttributes(file, BasicFileAttributes::class.java) + val audioFile = try { + AudioFileIO.read(file.toFile()) + } catch (e: Exception) { + return null + } + + val tag = audioFile.tag + val header = audioFile.audioHeader + val relativePath = root.relativize(file).joinToString("/") { it.toString() } + + val fallbackArtist = file.parent + ?.takeIf { it != root } + ?.parent + ?.takeIf { it != root } + ?.fileName + ?.toString() + ?.takeIf { it.isNotBlank() } + ?: "Unknown Artist" + + val fallbackAlbum = file.parent + ?.takeIf { it != root } + ?.fileName + ?.toString() + ?.takeIf { it.isNotBlank() } + ?: "Unknown Album" + + val tagArtists = (tag.values(FieldKey.ARTIST) + tag.values(FieldKey.ARTISTS)).distinct() + val selectedArtists = tagArtists.ifEmpty { listOf(fallbackArtist) } + + val albumArtistNames = + (tag.values(FieldKey.ALBUM_ARTIST) + tag.values(FieldKey.ALBUM_ARTISTS)) + .ifEmpty { selectedArtists } + val albumArtist = albumArtistNames.first() + + val title = tag.values(FieldKey.TITLE).firstOrNull() + ?: file.fileName.toString().removeSuffix(".mp3").removeSuffix(".MP3") + + val albumTitle = tag.values(FieldKey.ALBUM).firstOrNull() ?: fallbackAlbum + + val year = (tag.values(FieldKey.YEAR) + tag.values(FieldKey.ALBUM_YEAR)) + .firstNotNullOfOrNull { YEAR_PATTERN.find(it)?.value?.toIntOrNull() } + + val trackNumber = tag.values(FieldKey.TRACK) + .firstOrNull() + ?.substringBefore('/') + ?.trim() + ?.toIntOrNull() + + val discNumber = tag.values(FieldKey.DISC_NO) + .firstOrNull() + ?.substringBefore('/') + ?.trim() + ?.toIntOrNull() + ?: 1 + + val genres = tag.values(FieldKey.GENRE) + + val duration = header.trackLength.takeIf { it > 0 } + ?: header.preciseTrackLength.toInt().coerceAtLeast(0) + val bitRate = header.bitRateAsNumber.toInt().takeIf { it > 0 } + ?: header.bitRate.filter(Char::isDigit).toIntOrNull() + ?: 0 + + val coverBytes = runCatching { tag?.firstArtwork?.binaryData } + .getOrNull() + ?.takeIf { it.isNotEmpty() } + + val lyrics = tag.values(FieldKey.LYRICS).firstOrNull() ?: readSidecarLyrics(file) + + val albumArtistRefs = albumArtistNames.map { ArtistRef(IdGenerator.artistId(it), it) } + val artistRefs = selectedArtists.map { ArtistRef(IdGenerator.artistId(it), it) } + + return ExtractedTrack( + songId = IdGenerator.songId(folderId, relativePath), + albumId = IdGenerator.albumId(albumArtist, albumTitle), + albumArtistId = IdGenerator.artistId(albumArtist), + albumArtists = albumArtistRefs, + artists = artistRefs, + title = title, + displayArtist = selectedArtists.joinToString(", "), + albumTitle = albumTitle, + folderId = folderId, + relativePath = relativePath, + trackNumber = trackNumber, + discNumber = discNumber, + year = year, + genres = genres, + durationSeconds = duration, + bitRate = bitRate, + size = attributes.size(), + suffix = "mp3", + contentType = "audio/mpeg", + fileMtime = attributes.lastModifiedTime().toMillis(), + coverBytes = coverBytes, + lyrics = lyrics, + ) + } + + private fun Tag?.values(key: FieldKey): List = + runCatching { this?.getAll(key) } + .getOrNull() + .orEmpty() + .map { it.trim() } + .filter { it.isNotEmpty() } + .distinct() + + private fun readSidecarLyrics(file: Path): String? { + val lrc = file.resolveSibling(file.fileName.toString().substringBeforeLast('.') + ".lrc") + return runCatching { + if (Files.isRegularFile(lrc)) Files.readString(lrc) else null + }.getOrNull() + } + + private companion object { + val YEAR_PATTERN = Regex("\\d{4}") + } +} diff --git a/src/main/kotlin/win/taptap/musicmanager/scanner/ScanStatus.kt b/src/main/kotlin/win/taptap/musicmanager/scanner/ScanStatus.kt new file mode 100644 index 0000000..92214ea --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/scanner/ScanStatus.kt @@ -0,0 +1,7 @@ +package win.taptap.musicmanager.scanner + +data class ScanStatus( + val scanning: Boolean, + val count: Long, + val error: String? = null, +) diff --git a/src/main/kotlin/win/taptap/musicmanager/subsonic/SubsonicAuth.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/SubsonicAuth.kt new file mode 100644 index 0000000..64a270c --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/subsonic/SubsonicAuth.kt @@ -0,0 +1,57 @@ +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 new file mode 100644 index 0000000..51b77cf --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/subsonic/SubsonicResponse.kt @@ -0,0 +1,51 @@ +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/routes/RouteHelpers.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/RouteHelpers.kt new file mode 100644 index 0000000..fa4a1ee --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/RouteHelpers.kt @@ -0,0 +1,31 @@ +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.UserAccount + +val CurrentUserKey = AttributeKey("musicmanager.currentUser") + +/** + * 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/SubsonicGet.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/SubsonicGet.kt new file mode 100644 index 0000000..47fdaba --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/SubsonicGet.kt @@ -0,0 +1,35 @@ +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 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 GET endpoint for both `/{path}` and `/{path}.view`. + * Authentication failures always return HTTP 200 with error code 40. + */ +internal fun Route.subsonicGet( + 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") + + paths.forEach { routePath -> + get(routePath) { + 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) + handler(call, user) + } + } + } +} diff --git a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/SubsonicRoutes.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/SubsonicRoutes.kt new file mode 100644 index 0000000..af0d067 --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/SubsonicRoutes.kt @@ -0,0 +1,17 @@ +package win.taptap.musicmanager.subsonic.routes + +import io.ktor.server.routing.Route +import io.ktor.server.routing.route +import win.taptap.musicmanager.config.UsersConfig +import win.taptap.musicmanager.scanner.ScanStatus + +/** Authenticated `/rest` subtree. */ +fun Route.subsonicRoutes( + users: UsersConfig, + startScan: () -> Boolean, + scanStatus: () -> ScanStatus, +) { + route("/rest") { + systemRoutes(users, startScan, scanStatus) + } +} diff --git a/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/SystemRoutes.kt b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/SystemRoutes.kt new file mode 100644 index 0000000..00b21ae --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/subsonic/routes/SystemRoutes.kt @@ -0,0 +1,71 @@ +package win.taptap.musicmanager.subsonic.routes + +import io.ktor.server.routing.Route +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.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, + startScan: () -> Boolean, + scanStatus: () -> ScanStatus, +) { + subsonicGet(users, "/ping") { call, _ -> + call.respondSubsonic() + } + + subsonicGet(users, "/getLicense") { call, _ -> + call.respondSubsonic( + buildJsonObject { + put("license", buildJsonObject { put("valid", true) }) + }, + ) + } + + subsonicGet(users, "/getOpenSubsonicExtensions") { call, _ -> + call.respondSubsonic( + buildJsonObject { + put( + "openSubsonicExtensions", + buildJsonArray { + add(extension("formPost", 1)) + add(extension("songLyrics", 1)) + add(extension("transcodeOffset", 1)) + }, + ) + }, + ) + } + + subsonicGet(users, "/startScan") { call, user -> + if (!user.admin) { + call.respondSubsonicError(50, "Not authorized") + } else { + startScan() + call.respondSubsonic() + } + } + + subsonicGet(users, "/getScanStatus") { call, _ -> + val status = scanStatus() + call.respondSubsonic( + buildJsonObject { + put("scanStatus", buildJsonObject { + put("scanning", status.scanning) + put("count", status.count) + }) + }, + ) + } +} + +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 new file mode 100644 index 0000000..77047ce --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/util/IdGenerator.kt @@ -0,0 +1,45 @@ +package win.taptap.musicmanager.util + +import java.security.MessageDigest +import java.text.Normalizer +import java.util.Locale + +/** + * Deterministic IDs for the Symfonium offline cache. + * + * Normalization is frozen: NFC, trimmed, collapsed whitespace, lowercase. Changing + * it changes every ID and forces clients to re-download their library. + */ +object IdGenerator { + + private const val HASH_LENGTH = 24 + + fun normalize(value: String): String = Normalizer.normalize(value, Normalizer.Form.NFC) + .trim() + .replace(WHITESPACE, " ") + .lowercase(Locale.ROOT) + + fun artistId(albumArtist: String): String = "ar-" + hash(normalize(albumArtist)) + + fun albumId(albumArtist: String, albumTitle: String): String = + "al-" + hash("${normalize(albumArtist)}|${normalize(albumTitle)}") + + 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") + + private fun normalizePath(path: String): String = path + .replace('\\', '/') + .removePrefix("./") + .trimStart('/') + + private fun hash(value: String): String { + val digest = MessageDigest.getInstance("SHA-256").digest(value.toByteArray(Charsets.UTF_8)) + val hex = digest.joinToString("") { "%02x".format(it) } + return hex.take(HASH_LENGTH) + } + + private val WHITESPACE = Regex("\\s+") +} diff --git a/src/main/kotlin/win/taptap/musicmanager/util/SortNames.kt b/src/main/kotlin/win/taptap/musicmanager/util/SortNames.kt new file mode 100644 index 0000000..22d07fc --- /dev/null +++ b/src/main/kotlin/win/taptap/musicmanager/util/SortNames.kt @@ -0,0 +1,27 @@ +package win.taptap.musicmanager.util + +import java.util.Locale + +/** Computes Subsonic sort names, moving leading articles to the end ("Beatles, The"). */ +object SortNames { + + private val ARTICLES = listOf( + "the ", "a ", "an ", + "die ", "der ", "das ", + "le ", "la ", "les ", + "el ", "los ", "las ", + ) + + fun of(name: String): String { + val trimmed = name.trim() + if (trimmed.isEmpty()) return trimmed + + val lower = trimmed.lowercase(Locale.ROOT) + val article = ARTICLES.firstOrNull { lower.startsWith(it) } ?: return trimmed + val rest = trimmed.substring(article.length).trim() + if (rest.isEmpty()) return trimmed + + val displayArticle = trimmed.take(article.length).trim() + return "$rest, $displayArticle" + } +} diff --git a/src/main/resources/db/migration/V1__init.sql b/src/main/resources/db/migration/V1__init.sql new file mode 100644 index 0000000..faf5a0c --- /dev/null +++ b/src/main/resources/db/migration/V1__init.sql @@ -0,0 +1,142 @@ +-- Identity and library roots are reconciled from config/Vault at startup. +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) ON DELETE CASCADE, + 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 are kept as text join tables; uniqueness is the primary key. +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. Passwords are never stored here. +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 CHECK (rating IS NULL OR rating BETWEEN 1 AND 5), + 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, + 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) +); + +CREATE INDEX idx_artists_search ON artists (search_text); +CREATE INDEX idx_albums_search ON albums (search_text); +CREATE INDEX idx_songs_search ON songs (search_text); +CREATE INDEX idx_songs_album ON songs (album_id); +CREATE INDEX idx_songs_folder ON songs (folder_id); +CREATE INDEX idx_songs_created ON songs (created_at); +CREATE INDEX idx_album_artists_artist ON album_artists (artist_id); +CREATE INDEX idx_song_artists_artist ON song_artists (artist_id); +CREATE INDEX idx_user_song_state_starred ON user_song_state (user_name, starred_at); +CREATE INDEX idx_user_stars_type ON user_stars (user_name, item_type); +CREATE INDEX idx_playlist_songs_song ON playlist_songs (song_id); +CREATE INDEX idx_playlists_owner ON playlists (owner); diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml new file mode 100644 index 0000000..ab5b9f5 --- /dev/null +++ b/src/main/resources/logback.xml @@ -0,0 +1,15 @@ + + + + %d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX} %-5level [%thread] %logger{36} - %msg%n + + + + + + + + + + + diff --git a/src/test/kotlin/win/taptap/musicmanager/TestAudio.kt b/src/test/kotlin/win/taptap/musicmanager/TestAudio.kt new file mode 100644 index 0000000..b2d2b29 --- /dev/null +++ b/src/test/kotlin/win/taptap/musicmanager/TestAudio.kt @@ -0,0 +1,76 @@ +package win.taptap.musicmanager + +import java.awt.Color +import java.awt.image.BufferedImage +import java.nio.file.Files +import java.nio.file.Path +import javax.imageio.ImageIO +import org.junit.jupiter.api.Assumptions + +/** Generates test audio locally; no audio files are committed to the repository. */ +object TestAudio { + + private val ffmpegAvailable: Boolean by lazy { + runCatching { + val process = ProcessBuilder("ffmpeg", "-version") + .redirectErrorStream(true) + .start() + process.inputStream.readBytes() + process.waitFor() == 0 + }.getOrDefault(false) + } + + fun assumeFfmpeg() { + Assumptions.assumeTrue(ffmpegAvailable, "ffmpeg is not available on this machine") + } + + fun createMp3( + target: Path, + metadata: Map = emptyMap(), + cover: Path? = null, + seconds: Int = 1, + ) { + Files.createDirectories(target.parent) + + val command = mutableListOf( + "ffmpeg", "-nostdin", "-hide_banner", "-loglevel", "error", "-y", + "-f", "lavfi", "-i", "anullsrc=r=44100:cl=mono", + ) + + if (cover != null) { + command += listOf("-i", cover.toString(), "-map", "0:a", "-map", "1:v", "-c:v", "copy") + } else { + command += listOf("-map", "0:a") + } + + command += listOf("-c:a", "libmp3lame", "-b:a", "128k", "-t", seconds.toString()) + metadata.forEach { (key, value) -> command += listOf("-metadata", "$key=$value") } + if (cover != null) { + command += listOf( + "-metadata:s:v", "title=Album cover", + "-metadata:s:v", "comment=Cover (front)", + ) + } + command += listOf("-id3v2_version", "3", target.toString()) + + val process = ProcessBuilder(command) + .redirectErrorStream(true) + .start() + val output = process.inputStream.bufferedReader().readText() + val exit = process.waitFor() + check(exit == 0) { "ffmpeg failed ($exit): $output" } + } + + fun writePng(target: Path, width: Int = 32, height: Int = 32, color: Color = Color.RED) { + Files.createDirectories(target.parent) + val image = BufferedImage(width, height, BufferedImage.TYPE_INT_RGB) + val graphics = image.createGraphics() + try { + graphics.color = color + graphics.fillRect(0, 0, width, height) + } finally { + graphics.dispose() + } + ImageIO.write(image, "png", target.toFile()) + } +} diff --git a/src/test/kotlin/win/taptap/musicmanager/config/AppConfigTest.kt b/src/test/kotlin/win/taptap/musicmanager/config/AppConfigTest.kt new file mode 100644 index 0000000..2b72bc4 --- /dev/null +++ b/src/test/kotlin/win/taptap/musicmanager/config/AppConfigTest.kt @@ -0,0 +1,50 @@ +package win.taptap.musicmanager.config + +import java.nio.file.Path +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith + +class AppConfigTest { + + @Test + fun `uses documented defaults`() { + val config = AppConfig.fromEnv(emptyMap()) + + assertEquals(8080, config.port) + assertEquals(Path.of("./data"), config.dataDir) + assertEquals(Path.of("./config/library.yaml"), config.libraryConfigPath) + assertEquals(Path.of("./config/users.yaml"), config.usersFile) + assertEquals("ffmpeg", config.ffmpegPath) + assertEquals(Path.of("./data/musicmanager.db"), config.databasePath) + } + + @Test + fun `reads overrides from the environment`() { + val config = AppConfig.fromEnv( + mapOf( + "PORT" to "9090", + "DATA_DIR" to "/var/lib/musicmanager", + "LIBRARY_CONFIG" to "/etc/musicmanager/library.yaml", + "USERS_FILE" to "/run/secrets/users.yaml", + "FFMPEG_PATH" to "/usr/bin/ffmpeg", + ), + ) + + assertEquals(9090, config.port) + assertEquals(Path.of("/var/lib/musicmanager"), config.dataDir) + assertEquals(Path.of("/etc/musicmanager/library.yaml"), config.libraryConfigPath) + assertEquals(Path.of("/run/secrets/users.yaml"), config.usersFile) + assertEquals("/usr/bin/ffmpeg", config.ffmpegPath) + } + + @Test + fun `rejects a malformed port`() { + assertFailsWith { + AppConfig.fromEnv(mapOf("PORT" to "not-a-number")) + } + assertFailsWith { + AppConfig.fromEnv(mapOf("PORT" to "70000")) + } + } +} diff --git a/src/test/kotlin/win/taptap/musicmanager/config/LibraryConfigTest.kt b/src/test/kotlin/win/taptap/musicmanager/config/LibraryConfigTest.kt new file mode 100644 index 0000000..dfd166c --- /dev/null +++ b/src/test/kotlin/win/taptap/musicmanager/config/LibraryConfigTest.kt @@ -0,0 +1,127 @@ +package win.taptap.musicmanager.config + +import java.nio.file.Files +import kotlin.io.path.createTempDirectory +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertTrue + +class LibraryConfigTest { + + private val validYaml = """ + library: + folders: + - id: 1 + name: "Music" + type: music + path: "./media/music" + - id: 10 + name: "Long-form" + type: longform + path: "./media/longform" + """.trimIndent() + + @Test + fun `parses folders and resolves absolute paths`() { + val config = LibraryConfig.parse(validYaml) + + assertEquals(2, config.folders.size) + assertEquals(setOf(10), config.longformFolderIds) + assertEquals(FolderType.MUSIC, config.folders[0].type) + assertEquals(FolderType.LONGFORM, config.folders[1].type) + assertTrue(config.folders[0].path.isAbsolute) + assertEquals(1, config.byId(1)?.id) + } + + @Test + fun `rejects duplicate folder ids`() { + val yaml = """ + library: + folders: + - id: 1 + name: A + type: music + path: /music/a + - id: 1 + name: B + type: music + path: /music/b + """.trimIndent() + + assertFailsWith { LibraryConfig.parse(yaml) } + } + + @Test + fun `rejects duplicate folder paths`() { + val yaml = """ + library: + folders: + - id: 1 + name: A + type: music + path: /music/a + - id: 2 + name: B + type: music + path: /music/a + """.trimIndent() + + assertFailsWith { LibraryConfig.parse(yaml) } + } + + @Test + fun `rejects unknown folder types`() { + val yaml = """ + library: + folders: + - id: 1 + name: A + type: video + path: /music/a + """.trimIndent() + + assertFailsWith { LibraryConfig.parse(yaml) } + } + + @Test + fun `validatePaths fails for a missing root`() { + val root = createTempDirectory("musicmanager-test") + try { + val yaml = """ + library: + folders: + - id: 1 + name: A + type: music + path: "${root.resolve("missing")}" + """.trimIndent() + + assertFailsWith { + LibraryConfig.parse(yaml).validatePaths() + } + } finally { + root.toFile().deleteRecursively() + } + } + + @Test + fun `validatePaths accepts existing readable roots`() { + val root = createTempDirectory("musicmanager-test") + try { + val music = Files.createDirectories(root.resolve("music")) + val yaml = """ + library: + folders: + - id: 1 + name: A + type: music + path: "$music" + """.trimIndent() + + LibraryConfig.parse(yaml).validatePaths() + } finally { + root.toFile().deleteRecursively() + } + } +} diff --git a/src/test/kotlin/win/taptap/musicmanager/config/UsersConfigTest.kt b/src/test/kotlin/win/taptap/musicmanager/config/UsersConfigTest.kt new file mode 100644 index 0000000..feab66c --- /dev/null +++ b/src/test/kotlin/win/taptap/musicmanager/config/UsersConfigTest.kt @@ -0,0 +1,126 @@ +package win.taptap.musicmanager.config + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class UsersConfigTest { + + private val library = LibraryConfig.parse( + """ + library: + folders: + - id: 1 + name: "Music A" + type: music + path: /music/a + - id: 2 + name: "Music B" + type: music + path: /music/b + - id: 10 + name: "Long-form" + type: longform + path: /longform + """.trimIndent(), + ) + + private val usersYaml = """ + users: + - name: alice + password: "secret-a" + admin: true + folders: [1] + - name: bob + password: "secret-b" + folders: [1, 2] + """.trimIndent() + + @Test + fun `parses users and shares long-form folders`() { + val users = UsersConfig.parse(usersYaml) + users.validateAgainst(library) + + val alice = users.byName("alice")!! + val bob = users.byName("bob")!! + + assertTrue(alice.admin) + assertFalse(bob.admin) + assertEquals(setOf(1, 10), alice.visibleFolderIds(library)) + assertEquals(setOf(1, 2, 10), bob.visibleFolderIds(library)) + } + + @Test + fun `rejects missing passwords`() { + val yaml = """ + users: + - name: alice + folders: [1] + """.trimIndent() + + assertFailsWith { UsersConfig.parse(yaml) } + } + + @Test + fun `rejects duplicate names`() { + val yaml = """ + users: + - name: alice + password: a + folders: [1] + - name: alice + password: b + folders: [2] + """.trimIndent() + + assertFailsWith { UsersConfig.parse(yaml) } + } + + @Test + fun `rejects unknown folder references`() { + val users = UsersConfig.parse( + """ + users: + - name: alice + password: a + folders: [99] + """.trimIndent(), + ) + + assertFailsWith { users.validateAgainst(library) } + } + + @Test + fun `rejects a user with no visible folders`() { + val emptyLibrary = LibraryConfig.parse( + """ + library: + folders: + - id: 1 + name: "Music" + type: music + path: /music + """.trimIndent(), + ) + val users = UsersConfig.parse( + """ + users: + - name: alice + password: a + folders: [] + """.trimIndent(), + ) + + assertFailsWith { users.validateAgainst(emptyLibrary) } + } + + @Test + fun `does not expose passwords in toString`() { + val alice = UsersConfig.parse(usersYaml).byName("alice")!! + + assertFalse(alice.toString().contains("secret-a")) + assertTrue(alice.toString().contains("password=***")) + } +} diff --git a/src/test/kotlin/win/taptap/musicmanager/db/DatabaseFactoryTest.kt b/src/test/kotlin/win/taptap/musicmanager/db/DatabaseFactoryTest.kt new file mode 100644 index 0000000..7c0c277 --- /dev/null +++ b/src/test/kotlin/win/taptap/musicmanager/db/DatabaseFactoryTest.kt @@ -0,0 +1,204 @@ +package win.taptap.musicmanager.db + +import java.nio.file.Files +import java.nio.file.Path +import java.time.Instant +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue +import org.jetbrains.exposed.sql.insert +import org.jetbrains.exposed.sql.selectAll +import org.jetbrains.exposed.sql.transactions.transaction +import org.junit.jupiter.api.io.TempDir +import win.taptap.musicmanager.config.AppConfig +import win.taptap.musicmanager.config.FolderType +import win.taptap.musicmanager.config.LibraryConfig +import win.taptap.musicmanager.config.MusicFolder +import win.taptap.musicmanager.config.UserAccount +import win.taptap.musicmanager.config.UsersConfig + +class DatabaseFactoryTest { + + @TempDir + lateinit var tempDir: Path + + @Test + fun `migrates the schema and configures sqlite`() { + val db = DatabaseFactory.connect(appConfig()) + try { + assertEquals("wal", pragma(db, "journal_mode")) + assertEquals("1", pragma(db, "foreign_keys")) + + val migrations = db.dataSource.connection.use { connection -> + connection.createStatement().use { statement -> + statement.executeQuery("SELECT COUNT(*) FROM flyway_schema_history").use { result -> + result.next() + result.getInt(1) + } + } + } + assertEquals(1, migrations) + } finally { + db.close() + } + } + + @Test + fun `syncs folders and users idempotently`() { + val db = DatabaseFactory.connect(appConfig()) + try { + val library = library() + val users = UsersConfig( + listOf( + UserAccount("alice", "pw", admin = true, folders = setOf(1)), + UserAccount("bob", "pw", admin = false, folders = setOf(1)), + ), + ) + + ConfigRepository.sync(library, users) + ConfigRepository.sync(library, users) + + transaction(db.database) { + assertEquals(2L, MusicFoldersTable.selectAll().count()) + assertEquals(2L, UsersTable.selectAll().count()) + assertEquals( + "longform", + MusicFoldersTable.selectAll() + .where { MusicFoldersTable.id eq 10 } + .single()[MusicFoldersTable.type], + ) + } + } finally { + db.close() + } + } + + @Test + fun `removing a user cascades their per-user state`() { + val db = DatabaseFactory.connect(appConfig()) + try { + val library = library() + val aliceAndBob = UsersConfig( + listOf( + UserAccount("alice", "pw", admin = true, folders = setOf(1)), + UserAccount("bob", "pw", admin = false, folders = setOf(1)), + ), + ) + ConfigRepository.sync(library, aliceAndBob) + insertSong(db, folderId = 1) + + transaction(db.database) { + UserSongStateTable.insert { + it[userName] = "alice" + it[songId] = "sg-1" + it[playCount] = 3 + it[starredAt] = Instant.now().toString() + } + assertEquals(1L, UserSongStateTable.selectAll().count()) + } + + ConfigRepository.sync( + library, + UsersConfig(listOf(UserAccount("bob", "pw", admin = false, folders = setOf(1)))), + ) + + transaction(db.database) { + assertEquals(0L, UserSongStateTable.selectAll().count()) + assertEquals(1L, UsersTable.selectAll().count()) + } + } finally { + db.close() + } + } + + @Test + fun `removing a folder cascades its songs`() { + val db = DatabaseFactory.connect(appConfig()) + try { + val library = library() + val users = UsersConfig(listOf(UserAccount("alice", "pw", admin = true, folders = setOf(1)))) + ConfigRepository.sync(library, users) + insertSong(db, folderId = 1) + + transaction(db.database) { + assertEquals(1L, SongsTable.selectAll().count()) + } + + ConfigRepository.sync( + LibraryConfig(library.folders.filter { it.id == 10 }), + UsersConfig(listOf(UserAccount("alice", "pw", admin = true, folders = emptySet()))), + ) + + transaction(db.database) { + assertEquals(0L, SongsTable.selectAll().count()) + assertEquals(1L, MusicFoldersTable.selectAll().count()) + } + } finally { + db.close() + } + } + + private fun appConfig(): AppConfig = AppConfig( + port = 8080, + dataDir = tempDir.resolve("data"), + libraryConfigPath = tempDir.resolve("library.yaml"), + usersFile = tempDir.resolve("users.yaml"), + ffmpegPath = "ffmpeg", + ) + + private fun library(): LibraryConfig { + val music = Files.createDirectories(tempDir.resolve("music")) + val longform = Files.createDirectories(tempDir.resolve("longform")) + return LibraryConfig( + listOf( + MusicFolder(1, "Music", FolderType.MUSIC, music), + MusicFolder(10, "Long-form", FolderType.LONGFORM, longform), + ), + ) + } + + private fun insertSong(db: DatabaseHandle, folderId: Int) { + val now = Instant.now().toString() + transaction(db.database) { + ArtistsTable.insert { + it[id] = "ar-1" + it[name] = "Artist" + it[sortName] = "artist" + it[searchText] = "artist" + } + AlbumsTable.insert { + it[id] = "al-1" + it[name] = "Album" + it[createdAt] = now + it[searchText] = "album" + } + SongsTable.insert { + it[id] = "sg-1" + it[albumId] = "al-1" + it[this.folderId] = folderId + it[title] = "Song" + it[displayArtist] = "Artist" + it[albumName] = "Album" + it[duration] = 120 + it[bitRate] = 128 + it[size] = 1024 + it[suffix] = "mp3" + it[contentType] = "audio/mpeg" + it[relativePath] = "artist/album/song.mp3" + it[fileMtime] = 0 + it[createdAt] = now + it[searchText] = "song" + } + } + } + + private fun pragma(db: DatabaseHandle, name: String): String = + db.dataSource.connection.use { connection -> + connection.createStatement().use { statement -> + statement.executeQuery("PRAGMA $name").use { result -> + assertTrue(result.next(), "PRAGMA $name returned no row") + result.getString(1) + } + } + } +} diff --git a/src/test/kotlin/win/taptap/musicmanager/scanner/CoverArtServiceTest.kt b/src/test/kotlin/win/taptap/musicmanager/scanner/CoverArtServiceTest.kt new file mode 100644 index 0000000..9e7ced7 --- /dev/null +++ b/src/test/kotlin/win/taptap/musicmanager/scanner/CoverArtServiceTest.kt @@ -0,0 +1,87 @@ +package win.taptap.musicmanager.scanner + +import java.awt.Color +import java.nio.file.Files +import java.nio.file.Path +import javax.imageio.ImageIO +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import org.junit.jupiter.api.io.TempDir +import win.taptap.musicmanager.TestAudio + +class CoverArtServiceTest { + + @TempDir + lateinit var tempDir: Path + + @Test + fun `stores and resizes a cover`() { + val service = CoverArtService(tempDir) + val cover = tempDir.resolve("cover.png") + TestAudio.writePng(cover, 64, 64) + + assertTrue(service.saveCover(ALBUM_ID, Files.readAllBytes(cover))) + + val stored = service.coverFile(ALBUM_ID) + assertNotNull(stored) + assertTrue(Files.size(stored) > 0) + + val resized = service.resizedCover(ALBUM_ID, 24) + assertNotNull(resized) + val image = ImageIO.read(resized.toFile()) + assertEquals(24, image.width) + assertEquals(24, image.height) + + // Unchanged bytes are accepted without creating a new file. + assertTrue(service.saveCover(ALBUM_ID, Files.readAllBytes(cover))) + } + + @Test + fun `invalid image data is rejected`() { + val service = CoverArtService(tempDir) + + assertFalse(service.saveCover(ALBUM_ID, "not an image".toByteArray())) + assertFalse(service.saveCover(ALBUM_ID, ByteArray(0))) + assertNull(service.coverFile(ALBUM_ID)) + } + + @Test + fun `changing the cover invalidates resized variants`() { + val service = CoverArtService(tempDir) + val red = tempDir.resolve("red.png") + val blue = tempDir.resolve("blue.png") + TestAudio.writePng(red, color = Color.RED) + TestAudio.writePng(blue, color = Color.BLUE) + + service.saveCover(ALBUM_ID, Files.readAllBytes(red)) + val resized = service.resizedCover(ALBUM_ID, 16) + assertNotNull(resized) + + service.saveCover(ALBUM_ID, Files.readAllBytes(blue)) + + assertFalse(Files.exists(resized), "Old resized variant should be removed") + } + + @Test + fun `finds sidecar artwork next to the audio file`() { + val service = CoverArtService(tempDir) + val audio = tempDir.resolve("Artist/Album/song.mp3") + Files.createDirectories(audio.parent) + Files.writeString(audio, "audio") + + assertNull(service.findSidecarCover(audio)) + + val cover = audio.parent.resolve("folder.jpg") + TestAudio.writePng(cover) + + assertEquals(cover, service.findSidecarCover(audio)) + } + + private companion object { + const val ALBUM_ID = "al-0123456789abcdef01234567" + } +} diff --git a/src/test/kotlin/win/taptap/musicmanager/scanner/MediaScannerTest.kt b/src/test/kotlin/win/taptap/musicmanager/scanner/MediaScannerTest.kt new file mode 100644 index 0000000..4b484d5 --- /dev/null +++ b/src/test/kotlin/win/taptap/musicmanager/scanner/MediaScannerTest.kt @@ -0,0 +1,209 @@ +package win.taptap.musicmanager.scanner + +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.attribute.FileTime +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import org.jetbrains.exposed.sql.insert +import org.jetbrains.exposed.sql.selectAll +import org.jetbrains.exposed.sql.transactions.transaction +import org.junit.jupiter.api.io.TempDir +import win.taptap.musicmanager.TestAudio +import win.taptap.musicmanager.config.AppConfig +import win.taptap.musicmanager.config.FolderType +import win.taptap.musicmanager.config.LibraryConfig +import win.taptap.musicmanager.config.MusicFolder +import win.taptap.musicmanager.config.UserAccount +import win.taptap.musicmanager.config.UsersConfig +import win.taptap.musicmanager.db.AlbumsTable +import win.taptap.musicmanager.db.ArtistsTable +import win.taptap.musicmanager.db.ConfigRepository +import win.taptap.musicmanager.db.DatabaseFactory +import win.taptap.musicmanager.db.DatabaseHandle +import win.taptap.musicmanager.db.MediaRepository +import win.taptap.musicmanager.db.SongGenresTable +import win.taptap.musicmanager.db.SongsTable +import win.taptap.musicmanager.db.UserSongStateTable +import win.taptap.musicmanager.util.IdGenerator + +class MediaScannerTest { + + @TempDir + lateinit var tempDir: Path + + private lateinit var music: Path + private lateinit var longform: Path + + @Test + fun `scans, caches covers and keeps user state across metadata updates`() { + TestAudio.assumeFfmpeg() + + val db = DatabaseFactory.connect(appConfig()) + try { + val library = library() + ConfigRepository.sync(library, users()) + + val albumDir = Files.createDirectories(music.resolve("Album Artist/Album")) + TestAudio.writePng(albumDir.resolve("cover.jpg")) + val one = albumDir.resolve("01 - One.mp3") + val two = albumDir.resolve("02 - Two.mp3") + TestAudio.createMp3(one, metadata = albumMetadata("One", "1/2")) + TestAudio.createMp3(two, metadata = albumMetadata("Two", "2/2")) + + val book = longform.resolve("Author/Book/01 - Chapter One.mp3") + TestAudio.createMp3( + book, + metadata = mapOf( + "title" to "Chapter One", + "artist" to "Author", + "album_artist" to "Author", + "album" to "Book", + ), + ) + Files.writeString(music.resolve("notes.txt"), "not audio") + + val scanner = MediaScanner(library, CoverArtService(tempDir.resolve("data"))) + + val first = scanner.scanBlocking() + assertNull(first.error) + assertEquals(3L, first.count) + assertEquals(3L, MediaRepository.countSongs()) + + val albumId = IdGenerator.albumId("Album Artist", "Album") + val songId = IdGenerator.songId(1, "Album Artist/Album/01 - One.mp3") + + transaction(db.database) { + assertEquals(3L, SongsTable.selectAll().count()) + assertEquals(2L, AlbumsTable.selectAll().count()) + assertEquals(2L, ArtistsTable.selectAll().count()) + assertEquals(2L, SongGenresTable.selectAll().count()) + + val album = AlbumsTable.selectAll() + .where { AlbumsTable.id eq albumId } + .single() + assertEquals(albumId, album[AlbumsTable.coverArt]) + + val song = SongsTable.selectAll() + .where { SongsTable.id eq songId } + .single() + assertEquals(128, song[SongsTable.bitRate]) + assertEquals("mp3", song[SongsTable.suffix]) + assertEquals("audio/mpeg", song[SongsTable.contentType]) + assertEquals(Files.size(one), song[SongsTable.size]) + + UserSongStateTable.insert { + it[userName] = "alice" + it[this.songId] = songId + it[playCount] = 7 + } + } + + assertTrue(Files.isRegularFile(tempDir.resolve("data/covers/$albumId.jpg"))) + + // Touching the file forces re-extraction; the play count must survive. + Files.setLastModifiedTime(one, FileTime.fromMillis(System.currentTimeMillis() + 2_000)) + val second = scanner.scanBlocking() + assertEquals(3L, second.count) + assertEquals(3L, MediaRepository.countSongs()) + + transaction(db.database) { + val state = UserSongStateTable.selectAll() + .where { UserSongStateTable.songId eq songId } + .single() + assertEquals(7, state[UserSongStateTable.playCount]) + } + + // Removing the whole album and the long-form book cleans up orphans. + Files.delete(two) + Files.delete(one) + Files.delete(book) + + val third = scanner.scanBlocking() + assertNull(third.error) + assertEquals(0L, third.count) // notes.txt is ignored, the three MP3s are gone + assertEquals(0L, MediaRepository.countSongs()) + + transaction(db.database) { + assertEquals(0L, SongsTable.selectAll().count()) + assertEquals(0L, AlbumsTable.selectAll().count()) + assertEquals(0L, ArtistsTable.selectAll().count()) + } + } finally { + db.close() + } + } + + @Test + fun `unchanged files are skipped on a second scan`() { + TestAudio.assumeFfmpeg() + val db = DatabaseFactory.connect(appConfig()) + try { + val library = library() + ConfigRepository.sync(library, users()) + + val file = music.resolve("Artist/Album/song.mp3") + TestAudio.createMp3(file) + TestAudio.writePng(file.parent.resolve("cover.jpg")) + + val scanner = MediaScanner(library, CoverArtService(tempDir.resolve("data"))) + scanner.scanBlocking() + + val albumId = IdGenerator.albumId("Artist", "Album") + transaction(db.database) { + val album = AlbumsTable.selectAll() + .where { AlbumsTable.id eq albumId } + .single() + assertEquals(albumId, album[AlbumsTable.coverArt]) + } + assertTrue(Files.isRegularFile(tempDir.resolve("data/covers/$albumId.jpg"))) + + val before = transaction(db.database) { + SongsTable.selectAll().single()[SongsTable.fileMtime] + } + val mtimeBefore = Files.getLastModifiedTime(file).toMillis() + assertEquals(mtimeBefore, before) + + val second = scanner.scanBlocking() + assertEquals(1L, second.count) + assertEquals(1L, MediaRepository.countSongs()) + } finally { + db.close() + } + } + + private fun albumMetadata(title: String, track: String): Map = mapOf( + "title" to title, + "artist" to "Album Artist", + "album_artist" to "Album Artist", + "album" to "Album", + "track" to track, + "genre" to "Rock", + ) + + private fun appConfig(): AppConfig = AppConfig( + port = 8080, + dataDir = tempDir.resolve("data"), + libraryConfigPath = tempDir.resolve("library.yaml"), + usersFile = tempDir.resolve("users.yaml"), + ffmpegPath = "ffmpeg", + ) + + private fun library(): LibraryConfig { + music = Files.createDirectories(tempDir.resolve("music")) + longform = Files.createDirectories(tempDir.resolve("longform")) + return LibraryConfig( + listOf( + MusicFolder(1, "Music", FolderType.MUSIC, music), + MusicFolder(10, "Long-form", FolderType.LONGFORM, longform), + ), + ) + } + + private fun users(): UsersConfig = UsersConfig( + listOf(UserAccount("alice", "pw", admin = true, folders = setOf(1))), + ) +} diff --git a/src/test/kotlin/win/taptap/musicmanager/scanner/Mp3TagExtractorTest.kt b/src/test/kotlin/win/taptap/musicmanager/scanner/Mp3TagExtractorTest.kt new file mode 100644 index 0000000..6a49abd --- /dev/null +++ b/src/test/kotlin/win/taptap/musicmanager/scanner/Mp3TagExtractorTest.kt @@ -0,0 +1,111 @@ +package win.taptap.musicmanager.scanner + +import java.nio.file.Files +import java.nio.file.Path +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import org.junit.jupiter.api.io.TempDir +import win.taptap.musicmanager.TestAudio +import win.taptap.musicmanager.util.IdGenerator + +class Mp3TagExtractorTest { + + @TempDir + lateinit var tempDir: Path + + @Test + fun `reads ID3 tags and separates album artist from track artists`() { + TestAudio.assumeFfmpeg() + val root = Files.createDirectories(tempDir.resolve("music")) + val file = root.resolve("Album Artist/Album/02 - Song.mp3") + TestAudio.createMp3( + file, + metadata = mapOf( + "title" to "Test Song", + "artist" to "Track Artist", + "album_artist" to "Album Artist", + "album" to "Test Album", + "track" to "2/10", + "disc" to "1/2", + "date" to "2021-05-01", + "genre" to "Rock", + ), + ) + + val track = assertNotNull(Mp3TagExtractor().extract(1, root, file)) + + assertEquals("Test Song", track.title) + assertEquals("Album Artist/Album/02 - Song.mp3", track.relativePath) + assertEquals("Test Album", track.albumTitle) + assertEquals("Track Artist", track.displayArtist) + assertEquals(listOf("Track Artist"), track.artists.map { it.name }) + assertEquals(listOf("Album Artist"), track.albumArtists.map { it.name }) + assertEquals("Album Artist", track.albumArtists.first().name) + assertEquals(2, track.trackNumber) + assertEquals(1, track.discNumber) + assertEquals(2021, track.year) + assertEquals(listOf("Rock"), track.genres) + assertTrue(track.durationSeconds in 1..4) + assertTrue(track.bitRate > 0) + assertEquals(Files.size(file), track.size) + assertEquals("mp3", track.suffix) + assertEquals("audio/mpeg", track.contentType) + + assertEquals( + IdGenerator.songId(1, "Album Artist/Album/02 - Song.mp3"), + track.songId, + ) + assertEquals( + IdGenerator.albumId("Album Artist", "Test Album"), + track.albumId, + ) + } + + @Test + fun `falls back to the folder structure when tags are missing`() { + TestAudio.assumeFfmpeg() + val root = Files.createDirectories(tempDir.resolve("music")) + val file = root.resolve("Artist/Album/song.mp3") + TestAudio.createMp3(file) + + val track = assertNotNull(Mp3TagExtractor().extract(1, root, file)) + + assertEquals("song", track.title) + assertEquals("Album", track.albumTitle) + assertEquals("Artist", track.displayArtist) + assertEquals(listOf("Artist"), track.albumArtists.map { it.name }) + } + + @Test + fun `reads embedded artwork and sidecar lyrics`() { + TestAudio.assumeFfmpeg() + val root = Files.createDirectories(tempDir.resolve("music")) + val cover = root.resolve("cover.png") + TestAudio.writePng(cover) + val file = root.resolve("Artist/Album/song.mp3") + TestAudio.createMp3( + file, + metadata = mapOf("title" to "Covered"), + cover = cover, + ) + Files.writeString(file.resolveSibling("song.lrc"), "[00:00.00]Hello") + + val track = assertNotNull(Mp3TagExtractor().extract(1, root, file)) + + assertNotNull(track.coverBytes) + assertTrue(track.coverBytes!!.isNotEmpty()) + assertEquals("[00:00.00]Hello", track.lyrics) + } + + @Test + fun `ignores non-mp3 files`() { + val root = Files.createDirectories(tempDir.resolve("music")) + val file = root.resolve("song.flac") + Files.writeString(file, "not audio") + + assertNull(Mp3TagExtractor().extract(1, root, file)) + } +} diff --git a/src/test/kotlin/win/taptap/musicmanager/subsonic/SubsonicAuthTest.kt b/src/test/kotlin/win/taptap/musicmanager/subsonic/SubsonicAuthTest.kt new file mode 100644 index 0000000..2aec754 --- /dev/null +++ b/src/test/kotlin/win/taptap/musicmanager/subsonic/SubsonicAuthTest.kt @@ -0,0 +1,68 @@ +package win.taptap.musicmanager.subsonic + +import io.ktor.http.Parameters +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import win.taptap.musicmanager.config.UserAccount +import win.taptap.musicmanager.config.UsersConfig + +class SubsonicAuthTest { + + private val users = UsersConfig( + listOf( + UserAccount("alice", "secret", admin = true, folders = setOf(1)), + UserAccount("bob", "hunter2", admin = false, folders = setOf(1)), + ), + ) + private val authenticator = SubsonicAuthenticator(users) + + @Test + fun `accepts token authentication`() { + val salt = "s4lt" + val token = SubsonicAuthenticator.md5Hex("secret$salt") + + val user = authenticator.authenticate(params("u" to "alice", "t" to token, "s" to salt)) + + assertEquals("alice", user?.name) + } + + @Test + fun `accepts plaintext password authentication`() { + assertEquals("bob", authenticator.authenticate(params("u" to "bob", "p" to "hunter2"))?.name) + } + + @Test + fun `accepts enc-prefixed hex password authentication`() { + val encoded = "enc:" + "secret".toByteArray().joinToString("") { "%02x".format(it) } + + assertEquals("alice", authenticator.authenticate(params("u" to "alice", "p" to encoded))?.name) + } + + @Test + fun `rejects wrong credentials and malformed requests`() { + val salt = "s4lt" + assertNull(authenticator.authenticate(params("u" to "alice", "t" to "wrong", "s" to salt))) + assertNull(authenticator.authenticate(params("u" to "alice", "p" to "wrong"))) + assertNull(authenticator.authenticate(params("u" to "nobody", "p" to "secret"))) + assertNull(authenticator.authenticate(params("p" to "secret"))) + assertNull(authenticator.authenticate(params("u" to "alice"))) + assertNull(authenticator.authenticate(params("u" to "alice", "p" to "enc:zz"))) + } + + @Test + fun `token takes precedence over password`() { + val salt = "s4lt" + val token = SubsonicAuthenticator.md5Hex("secret$salt") + + val user = authenticator.authenticate( + params("u" to "alice", "t" to token, "s" to salt, "p" to "wrong"), + ) + + assertEquals("alice", user?.name) + } + + private fun params(vararg pairs: Pair): Parameters = Parameters.build { + pairs.forEach { (key, value) -> append(key, value) } + } +} diff --git a/src/test/kotlin/win/taptap/musicmanager/subsonic/SystemRoutesTest.kt b/src/test/kotlin/win/taptap/musicmanager/subsonic/SystemRoutesTest.kt new file mode 100644 index 0000000..2bfc939 --- /dev/null +++ b/src/test/kotlin/win/taptap/musicmanager/subsonic/SystemRoutesTest.kt @@ -0,0 +1,141 @@ +package win.taptap.musicmanager.subsonic + +import io.ktor.client.request.get +import io.ktor.client.statement.bodyAsText +import io.ktor.http.HttpStatusCode +import io.ktor.serialization.kotlinx.json.json +import io.ktor.server.application.install +import io.ktor.server.plugins.contentnegotiation.ContentNegotiation +import io.ktor.server.routing.routing +import io.ktor.server.testing.ApplicationTestBuilder +import io.ktor.server.testing.testApplication +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.int +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue +import win.taptap.musicmanager.config.UserAccount +import win.taptap.musicmanager.config.UsersConfig +import win.taptap.musicmanager.scanner.ScanStatus +import win.taptap.musicmanager.subsonic.routes.subsonicRoutes + +class SystemRoutesTest { + + @Test + fun `ping returns the OpenSubsonic envelope for both route variants`() = testApplication { + setupApp() + + for (path in listOf("/rest/ping", "/rest/ping.view")) { + val response = client.get("$path?${credentials()}") + assertEquals(HttpStatusCode.OK, response.status) + + val body = parse(response.bodyAsText()) + assertEquals("ok", body.string("status")) + assertEquals("1.16.1", body.string("version")) + assertEquals("musicmanager", body.string("type")) + assertEquals("0.1.0", body.string("serverVersion")) + assertEquals("true", body.string("openSubsonic")) + } + } + + @Test + fun `wrong credentials return HTTP 200 with error code 40`() = testApplication { + setupApp() + + val response = client.get("/rest/ping?u=alice&p=wrong") + + assertEquals(HttpStatusCode.OK, response.status) + val body = parse(response.bodyAsText()) + assertEquals("failed", body.string("status")) + assertEquals(40, body["error"]!!.jsonObject["code"]!!.jsonPrimitive.int) + } + + @Test + fun `getLicense reports a valid license`() = testApplication { + setupApp() + + val body = parse(client.get("/rest/getLicense?${credentials()}").bodyAsText()) + + assertEquals("true", body["license"]!!.jsonObject["valid"]!!.jsonPrimitive.content) + } + + @Test + fun `getOpenSubsonicExtensions declares formPost songLyrics and transcodeOffset`() = testApplication { + setupApp() + + val body = parse(client.get("/rest/getOpenSubsonicExtensions?${credentials()}").bodyAsText()) + val extensions = body["openSubsonicExtensions"]!!.jsonArray + val names = extensions.map { it.jsonObject["name"]!!.jsonPrimitive.content } + + assertEquals(3, extensions.size) + assertTrue("formPost" in names) + assertTrue("songLyrics" in names) + assertTrue("transcodeOffset" in names) + } + + @Test + fun `startScan requires an admin user`() = testApplication { + var started = false + setupApp(startScan = { started = true; true }) + + val adminResponse = client.get("/rest/startScan?${credentials(user = "alice")}") + assertEquals("ok", parse(adminResponse.bodyAsText()).string("status")) + assertTrue(started) + + started = false + val userResponse = client.get("/rest/startScan?${credentials(user = "bob")}") + val body = parse(userResponse.bodyAsText()) + assertEquals("failed", body.string("status")) + assertEquals(50, body["error"]!!.jsonObject["code"]!!.jsonPrimitive.int) + assertFalse(started) + } + + @Test + fun `getScanStatus returns the scanner state`() = testApplication { + setupApp(scanStatus = { ScanStatus(scanning = true, count = 42) }) + + val body = parse(client.get("/rest/getScanStatus?${credentials()}").bodyAsText()) + val status = body["scanStatus"]!!.jsonObject + + assertEquals("true", status["scanning"]!!.jsonPrimitive.content) + assertEquals(42, status["count"]!!.jsonPrimitive.int) + } + + private fun ApplicationTestBuilder.setupApp( + startScan: () -> Boolean = { false }, + scanStatus: () -> ScanStatus = { ScanStatus(false, 0) }, + ) { + application { + install(ContentNegotiation) { + json(Json { ignoreUnknownKeys = true; encodeDefaults = true }) + } + routing { + subsonicRoutes(users = users, startScan = startScan, scanStatus = scanStatus) + } + } + } + + private fun credentials(user: String = "alice"): String { + val salt = "test-salt" + val password = if (user == "alice") "secret" else "hunter2" + val token = SubsonicAuthenticator.md5Hex(password + salt) + return "u=$user&t=$token&s=$salt" + } + + private fun parse(body: String): JsonObject = + Json.parseToJsonElement(body).jsonObject["subsonic-response"]!!.jsonObject + + private fun JsonObject.string(key: String): String = this[key]!!.jsonPrimitive.content + + private val users = UsersConfig( + listOf( + UserAccount("alice", "secret", admin = true, folders = setOf(1)), + UserAccount("bob", "hunter2", admin = false, folders = setOf(1)), + ), + ) +} diff --git a/src/test/kotlin/win/taptap/musicmanager/util/IdGeneratorTest.kt b/src/test/kotlin/win/taptap/musicmanager/util/IdGeneratorTest.kt new file mode 100644 index 0000000..9164a79 --- /dev/null +++ b/src/test/kotlin/win/taptap/musicmanager/util/IdGeneratorTest.kt @@ -0,0 +1,56 @@ +package win.taptap.musicmanager.util + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotEquals +import kotlin.test.assertTrue + +class IdGeneratorTest { + + @Test + fun `normalization is NFC, trimmed, collapsed and lowercase`() { + val decomposed = "Cafe\u0301 The Artist" + assertEquals("café the artist", IdGenerator.normalize(decomposed)) + assertEquals(IdGenerator.normalize(" THE Artist "), IdGenerator.normalize("the artist")) + } + + @Test + fun `IDs are deterministic, prefixed and 24 hex characters`() { + val first = IdGenerator.artistId("The Beatles") + val second = IdGenerator.artistId("the beatles") + + assertEquals(first, second) + assertTrue(first.startsWith("ar-")) + assertEquals(27, first.length) + + val album = IdGenerator.albumId("The Beatles", "Abbey Road") + assertTrue(album.startsWith("al-")) + assertEquals(27, album.length) + + val song = IdGenerator.songId(1, "The Beatles/Abbey Road/01 - Come Together.mp3") + assertTrue(song.startsWith("sg-")) + assertEquals(27, song.length) + } + + @Test + fun `path separators do not change the song ID`() { + val unix = IdGenerator.songId(1, "Artist/Album/song.mp3") + val windows = IdGenerator.songId(1, "Artist\\Album\\song.mp3") + val prefixed = IdGenerator.songId(1, "./Artist/Album/song.mp3") + + assertEquals(unix, windows) + assertEquals(unix, prefixed) + } + + @Test + fun `folder and album changes produce different IDs`() { + assertNotEquals( + IdGenerator.songId(1, "Artist/Album/song.mp3"), + IdGenerator.songId(2, "Artist/Album/song.mp3"), + ) + assertNotEquals( + IdGenerator.albumId("Artist", "Album"), + IdGenerator.albumId("Artist", "Other Album"), + ) + } +} diff --git a/src/test/kotlin/win/taptap/musicmanager/util/SortNamesTest.kt b/src/test/kotlin/win/taptap/musicmanager/util/SortNamesTest.kt new file mode 100644 index 0000000..696d90f --- /dev/null +++ b/src/test/kotlin/win/taptap/musicmanager/util/SortNamesTest.kt @@ -0,0 +1,26 @@ +package win.taptap.musicmanager.util + +import kotlin.test.Test +import kotlin.test.assertEquals + +class SortNamesTest { + + @Test + fun `moves leading articles to the end`() { + assertEquals("Beatles, The", SortNames.of("The Beatles")) + assertEquals("Perfect Circle, A", SortNames.of("A Perfect Circle")) + assertEquals("Toten Hosen, Die", SortNames.of("Die Toten Hosen")) + assertEquals("Mond, Le", SortNames.of("Le Mond")) + } + + @Test + fun `leaves names without articles untouched`() { + assertEquals("Radiohead", SortNames.of("Radiohead")) + assertEquals("", SortNames.of(" ")) + } + + @Test + fun `handles names that are only an article`() { + assertEquals("The", SortNames.of("The")) + } +}