feat!: replace OpenSubsonic with a native mood-first API
Remove the /rest compatibility layer and the playlist model. Moods are now first-class private collections, and playback is driven by short-lived radio sessions whose queues are generated by the server. - Bearer device tokens (hashed) with revocable sessions. - Library snapshot/delta sync with tombstones and per-folder scoping. - Mood CRUD, seeds, preview and recommendations. - Radio batches weighted by seeds, genres, artists, text and playback affinity. - Playback events (started/completed/skipped) and explicit add-to-mood. - Stream, download and cover endpoints with query-token support for browsers. - V5 migration drops playlists and migrates existing moods; scanner writes tombstones and song update timestamps. - Built-in UI rebuilt on the native API with a radio player. - Native API integration tests and a rewritten smoke test (49 checks). - Chart bumped to 0.2.0. BREAKING CHANGE: the OpenSubsonic API and static playlists are gone.
This commit is contained in:
1 parent
28bfdd9d00
commit
b33eb076c1
46 files changed
+3467
-5818
No files matched your search
@@ -2,5 +2,5 @@ apiVersion: v2
|
|||||||
name: audiomanager
|
name: audiomanager
|
||||||
description: Self-hosted OpenSubsonic music server
|
description: Self-hosted OpenSubsonic music server
|
||||||
type: application
|
type: application
|
||||||
version: 0.1.4
|
version: 0.2.0
|
||||||
appVersion: "0.1.0"
|
appVersion: "0.1.0"
|
||||||
+157
-149
@@ -1,9 +1,11 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
#
|
#
|
||||||
# End-to-end smoke test: generates a tiny tagged MP3 library, starts the server
|
# End-to-end smoke test for the native mood-first API.
|
||||||
# against it, and exercises the endpoints a Subsonic client uses.
|
|
||||||
#
|
#
|
||||||
# Requirements: ffmpeg, sqlite3, curl, md5sum, java (or use nix-shell).
|
# Generates a tiny tagged MP3 library, starts the server against it, and
|
||||||
|
# exercises auth, sync, moods, radio sessions, add-to-mood and streaming.
|
||||||
|
#
|
||||||
|
# Requirements: ffmpeg, sqlite3, curl, python3, java.
|
||||||
# Usage: scripts/smoke.sh [work-dir]
|
# Usage: scripts/smoke.sh [work-dir]
|
||||||
#
|
#
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
@@ -15,9 +17,9 @@ PORT="${SMOKE_PORT:-18099}"
|
|||||||
USER="smoke"
|
USER="smoke"
|
||||||
PASS="smoke-pass"
|
PASS="smoke-pass"
|
||||||
BASE="http://127.0.0.1:${PORT}"
|
BASE="http://127.0.0.1:${PORT}"
|
||||||
SALT="smoke-salt"
|
TOKEN=""
|
||||||
TOKEN="$(printf '%s%s' "$PASS" "$SALT" | md5sum | cut -d' ' -f1)"
|
HTTP_STATUS=""
|
||||||
AUTH="u=${USER}&t=${TOKEN}&s=${SALT}&v=1.16.1&c=smoke&f=json"
|
HTTP_BODY=""
|
||||||
|
|
||||||
PASSED=0
|
PASSED=0
|
||||||
FAILED=0
|
FAILED=0
|
||||||
@@ -26,20 +28,30 @@ log() { printf '%s\n' "$*"; }
|
|||||||
pass() { PASSED=$((PASSED + 1)); log "PASS $1"; }
|
pass() { PASSED=$((PASSED + 1)); log "PASS $1"; }
|
||||||
fail() { FAILED=$((FAILED + 1)); log "FAIL $1: $2"; }
|
fail() { FAILED=$((FAILED + 1)); log "FAIL $1: $2"; }
|
||||||
|
|
||||||
mkdir -p "$WORK/music/Smoke Artist/Smoke Album" "$WORK/longform" "$WORK/data"
|
json_field() { python3 -c 'import json,sys;d=json.load(sys.stdin);print(eval("d"+sys.argv[1]))' "$1"; }
|
||||||
|
|
||||||
|
mkdir -p "$WORK/music/Smoke Artist/Smoke Album" "$WORK/music/Second Artist/Second Album" \
|
||||||
|
"$WORK/longform/Long Narrator/Long Book" "$WORK/data"
|
||||||
|
|
||||||
log "Generated test library in $WORK"
|
log "Generated test library in $WORK"
|
||||||
ffmpeg -hide_banner -loglevel error -y \
|
ffmpeg -hide_banner -loglevel error -y \
|
||||||
-f lavfi -i "sine=frequency=440:duration=2" \
|
-f lavfi -i "sine=frequency=440:duration=2" \
|
||||||
-metadata title="Smoke Song" \
|
-metadata title="Smoke Song" -metadata artist="Smoke Artist" \
|
||||||
-metadata artist="Smoke Artist" \
|
-metadata album="Smoke Album" -metadata album_artist="Smoke Artist" \
|
||||||
-metadata album="Smoke Album" \
|
-metadata genre="Rock" -metadata track="1" -metadata date="2026" \
|
||||||
-metadata album_artist="Smoke Artist" \
|
|
||||||
-metadata genre="Rock" \
|
|
||||||
-metadata track="1" \
|
|
||||||
-metadata date="2026" \
|
|
||||||
-b:a 192k "$WORK/music/Smoke Artist/Smoke Album/01 - Smoke Song.mp3"
|
-b:a 192k "$WORK/music/Smoke Artist/Smoke Album/01 - Smoke Song.mp3"
|
||||||
|
ffmpeg -hide_banner -loglevel error -y \
|
||||||
|
-f lavfi -i "sine=frequency=550:duration=2" \
|
||||||
|
-metadata title="Second Song" -metadata artist="Second Artist" \
|
||||||
|
-metadata album="Second Album" -metadata album_artist="Second Artist" \
|
||||||
|
-metadata genre="Ambient" -metadata track="1" -metadata date="2026" \
|
||||||
|
-b:a 192k "$WORK/music/Second Artist/Second Album/01 - Second Song.mp3"
|
||||||
|
ffmpeg -hide_banner -loglevel error -y \
|
||||||
|
-f lavfi -i "sine=frequency=660:duration=2" \
|
||||||
|
-metadata title="Chapter One" -metadata artist="Long Narrator" \
|
||||||
|
-metadata album="Long Book" -metadata album_artist="Long Narrator" \
|
||||||
|
-metadata genre="Audiobook" -metadata track="1" -metadata date="2026" \
|
||||||
|
-b:a 128k "$WORK/longform/Long Narrator/Long Book/01 - Chapter One.mp3"
|
||||||
ffmpeg -hide_banner -loglevel error -y \
|
ffmpeg -hide_banner -loglevel error -y \
|
||||||
-f lavfi -i "color=c=red:s=64x64" -frames:v 1 \
|
-f lavfi -i "color=c=red:s=64x64" -frames:v 1 \
|
||||||
"$WORK/music/Smoke Artist/Smoke Album/cover.jpg"
|
"$WORK/music/Smoke Artist/Smoke Album/cover.jpg"
|
||||||
@@ -80,182 +92,178 @@ SERVER_PID=$!
|
|||||||
trap 'kill $SERVER_PID 2>/dev/null || true' EXIT
|
trap 'kill $SERVER_PID 2>/dev/null || true' EXIT
|
||||||
|
|
||||||
log "Waiting for the server and initial scan..."
|
log "Waiting for the server and initial scan..."
|
||||||
|
SONGS=0
|
||||||
for _ in $(seq 1 120); do
|
for _ in $(seq 1 120); do
|
||||||
if curl -sf "$BASE/health" >/dev/null 2>&1; then
|
if curl -sf "$BASE/health" >/dev/null 2>&1; then
|
||||||
SONGS="$(sqlite3 "$WORK/data/musicmanager.db" 'select count(*) from songs' 2>/dev/null || echo 0)"
|
SONGS="$(sqlite3 "$WORK/data/musicmanager.db" 'select count(*) from songs' 2>/dev/null || echo 0)"
|
||||||
[[ "$SONGS" -gt 0 ]] && break
|
[[ "$SONGS" -ge 3 ]] && break
|
||||||
fi
|
fi
|
||||||
sleep 1
|
sleep 1
|
||||||
done
|
done
|
||||||
|
|
||||||
if [[ "${SONGS:-0}" -eq 0 ]]; then
|
if [[ "${SONGS:-0}" -lt 3 ]]; then
|
||||||
log "Server did not scan the test library; see $WORK/server.log"
|
log "Server did not scan the test library; see $WORK/server.log"
|
||||||
tail -20 "$WORK/server.log" || true
|
tail -20 "$WORK/server.log" || true
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
ALBUM_ID="$(sqlite3 "$WORK/data/musicmanager.db" 'select id from albums limit 1')"
|
SONG_ID="$(sqlite3 "$WORK/data/musicmanager.db" "select id from songs where title='Smoke Song'")"
|
||||||
ARTIST_ID="$(sqlite3 "$WORK/data/musicmanager.db" 'select id from artists limit 1')"
|
SONG2_ID="$(sqlite3 "$WORK/data/musicmanager.db" "select id from songs where title='Second Song'")"
|
||||||
SONG_ID="$(sqlite3 "$WORK/data/musicmanager.db" 'select id from songs limit 1')"
|
LONG_ID="$(sqlite3 "$WORK/data/musicmanager.db" "select id from songs where title='Chapter One'")"
|
||||||
log "Scanned: artist=$ARTIST_ID album=$ALBUM_ID song=$SONG_ID"
|
ALBUM_ID="$(sqlite3 "$WORK/data/musicmanager.db" "select album_id from songs where id='$SONG_ID'")"
|
||||||
|
log "Scanned: song=$SONG_ID second=$SONG2_ID longform=$LONG_ID"
|
||||||
|
|
||||||
# check <name> <path-with-query> [expected-status]
|
# api <method> <path> [json-body] [token-override]
|
||||||
check() {
|
api() {
|
||||||
local name="$1" path="$2" expected="${3:-200}" body status
|
local method="$1" path="$2" body="${3:-}" auth="${4:-$TOKEN}"
|
||||||
body="$(curl -s -w '\n%{http_code}' "$BASE$path")"
|
local args=(-s -w '\n%{http_code}' -X "$method" "$BASE/api/v1$path")
|
||||||
status="$(printf '%s' "$body" | tail -1)"
|
[[ -n "$auth" ]] && args+=(-H "Authorization: Bearer $auth")
|
||||||
body="$(printf '%s' "$body" | sed '$d')"
|
if [[ -n "$body" ]]; then
|
||||||
|
args+=(-H 'Content-Type: application/json' -d "$body")
|
||||||
|
fi
|
||||||
|
local out
|
||||||
|
out="$(curl "${args[@]}")"
|
||||||
|
HTTP_STATUS="$(printf '%s' "$out" | tail -1)"
|
||||||
|
HTTP_BODY="$(printf '%s' "$out" | sed '$d')"
|
||||||
|
}
|
||||||
|
|
||||||
if [[ "$status" != "$expected" ]]; then
|
expect() {
|
||||||
fail "$name" "HTTP $status (expected $expected): $(printf '%s' "$body" | head -c 200)"
|
local name="$1" expected="$2" method="$3" path="$4" body="${5:-}"
|
||||||
return
|
api "$method" "$path" "$body"
|
||||||
fi
|
if [[ "$HTTP_STATUS" == "$expected" ]]; then
|
||||||
if [[ "$expected" == "200" ]] && ! printf '%s' "$body" | grep -q '"status":"ok"'; then
|
|
||||||
fail "$name" "$(printf '%s' "$body" | head -c 200)"
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
pass "$name"
|
pass "$name"
|
||||||
|
else
|
||||||
|
fail "$name" "HTTP $HTTP_STATUS (expected $expected): ${HTTP_BODY:0:240}"
|
||||||
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
# check_post <name> <path> <extra-form-data>
|
expect_eq() {
|
||||||
check_post() {
|
local name="$1" expected="$2" actual="$3"
|
||||||
local name="$1" path="$2" extra="${3:-}" body status
|
if [[ "$actual" == "$expected" ]]; then
|
||||||
body="$(curl -s -w '\n%{http_code}' -X POST \
|
pass "$name"
|
||||||
-H 'Content-Type: application/x-www-form-urlencoded' \
|
else
|
||||||
--data "${AUTH}${extra}" "$BASE$path")"
|
fail "$name" "expected '$expected', got '$actual'"
|
||||||
status="$(printf '%s' "$body" | tail -1)"
|
|
||||||
body="$(printf '%s' "$body" | sed '$d')"
|
|
||||||
|
|
||||||
if [[ "$status" != "200" ]]; then
|
|
||||||
fail "$name (POST)" "HTTP $status: $(printf '%s' "$body" | head -c 200)"
|
|
||||||
return
|
|
||||||
fi
|
fi
|
||||||
if ! printf '%s' "$body" | grep -q '"status":"ok"'; then
|
|
||||||
fail "$name (POST)" "$(printf '%s' "$body" | head -c 200)"
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
pass "$name (POST)"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
check "ping" "/rest/ping.view?$AUTH"
|
log ""
|
||||||
check "getLicense" "/rest/getLicense.view?$AUTH"
|
log "Authentication"
|
||||||
check "getOpenSubsonicExtensions" "/rest/getOpenSubsonicExtensions.view?$AUTH"
|
LOGIN_STATUS="$(curl -s -o "$WORK/login.json" -w '%{http_code}' -X POST \
|
||||||
check "getMusicFolders" "/rest/getMusicFolders.view?$AUTH"
|
-H 'Content-Type: application/json' \
|
||||||
check "getIndexes" "/rest/getIndexes.view?$AUTH"
|
-d "{\"username\":\"$USER\",\"password\":\"$PASS\",\"deviceName\":\"smoke\",\"platform\":\"cli\"}" \
|
||||||
check "getArtists" "/rest/getArtists.view?$AUTH"
|
"$BASE/api/v1/auth/login")"
|
||||||
check "getArtist" "/rest/getArtist.view?$AUTH&id=$ARTIST_ID"
|
expect_eq "login status" "200" "$LOGIN_STATUS"
|
||||||
check "getAlbum" "/rest/getAlbum.view?$AUTH&id=$ALBUM_ID"
|
TOKEN="$(json_field '["token"]' < "$WORK/login.json" 2>/dev/null || true)"
|
||||||
check "getSong" "/rest/getSong.view?$AUTH&id=$SONG_ID"
|
if [[ -n "$TOKEN" ]]; then pass "login token"; else fail "login token" "$(head -c 200 "$WORK/login.json")"; fi
|
||||||
check "search3" "/rest/search3.view?$AUTH&query=smoke"
|
expect_eq "login user" "$USER" "$(json_field '["user"]["name"]' < "$WORK/login.json" 2>/dev/null || true)"
|
||||||
check "getAlbumList2" "/rest/getAlbumList2.view?$AUTH&type=alphabeticalByName&size=10"
|
|
||||||
check "getAlbumList" "/rest/getAlbumList.view?$AUTH&type=newest&size=10"
|
|
||||||
check "getRandomSongs" "/rest/getRandomSongs.view?$AUTH&size=10"
|
|
||||||
check "getGenres" "/rest/getGenres.view?$AUTH"
|
|
||||||
check "getSongsByGenre" "/rest/getSongsByGenre.view?$AUTH&genre=Rock"
|
|
||||||
check "getMusicDirectory (folder)" "/rest/getMusicDirectory.view?$AUTH&id=1"
|
|
||||||
check "getMusicDirectory (album)" "/rest/getMusicDirectory.view?$AUTH&id=$ALBUM_ID"
|
|
||||||
check "getUser" "/rest/getUser.view?$AUTH&username=$USER"
|
|
||||||
check "getUsers" "/rest/getUsers.view?$AUTH"
|
|
||||||
check "getScanStatus" "/rest/getScanStatus.view?$AUTH"
|
|
||||||
check "getStarred2" "/rest/getStarred2.view?$AUTH"
|
|
||||||
check "getLyricsBySongId" "/rest/getLyricsBySongId.view?$AUTH&id=$SONG_ID"
|
|
||||||
check "getArtistInfo2" "/rest/getArtistInfo2.view?$AUTH&id=$ARTIST_ID"
|
|
||||||
check "getAlbumInfo2" "/rest/getAlbumInfo2.view?$AUTH&id=$ALBUM_ID"
|
|
||||||
check "getSimilarSongs2" "/rest/getSimilarSongs2.view?$AUTH&id=$ARTIST_ID"
|
|
||||||
check "getTopSongs" "/rest/getTopSongs.view?$AUTH&artist=Smoke%20Artist"
|
|
||||||
check "getInternetRadioStations" "/rest/getInternetRadioStations.view?$AUTH"
|
|
||||||
check "jukeboxControl" "/rest/jukeboxControl.view?$AUTH&action=status"
|
|
||||||
|
|
||||||
# The formPost extension means clients may use POST for every endpoint.
|
BAD_STATUS="$(curl -s -o /dev/null -w '%{http_code}' -X POST \
|
||||||
check_post "ping" "/rest/ping.view"
|
-H 'Content-Type: application/json' -d '{"username":"smoke","password":"wrong"}' \
|
||||||
check_post "getAlbumList2" "/rest/getAlbumList2.view" "&type=alphabeticalByName&size=10"
|
"$BASE/api/v1/auth/login")"
|
||||||
check_post "getGenres" "/rest/getGenres.view"
|
expect_eq "login rejects bad password" "401" "$BAD_STATUS"
|
||||||
check_post "getPlaylists" "/rest/getPlaylists.view"
|
UNAUTH_STATUS="$(curl -s -o /dev/null -w '%{http_code}' "$BASE/api/v1/moods")"
|
||||||
check_post "getUser" "/rest/getUser.view" "&username=$USER"
|
expect_eq "unauthenticated request rejected" "401" "$UNAUTH_STATUS"
|
||||||
|
|
||||||
check "scrobble" "/rest/scrobble.view?$AUTH&id=$SONG_ID"
|
expect "me" "200" "GET" "/me"
|
||||||
check "star" "/rest/star.view?$AUTH&id=$SONG_ID&albumId=$ALBUM_ID&artistId=$ARTIST_ID"
|
expect_eq "me name" "$USER" "$(printf '%s' "$HTTP_BODY" | json_field '["name"]')"
|
||||||
check "getStarred2 after star" "/rest/getStarred2.view?$AUTH"
|
|
||||||
check "setRating" "/rest/setRating.view?$AUTH&id=$SONG_ID&rating=4"
|
|
||||||
check "unstar" "/rest/unstar.view?$AUTH&id=$SONG_ID&albumId=$ALBUM_ID&artistId=$ARTIST_ID"
|
|
||||||
check "createBookmark" "/rest/createBookmark.view?$AUTH&id=$SONG_ID&position=1000"
|
|
||||||
check "getBookmarks" "/rest/getBookmarks.view?$AUTH"
|
|
||||||
check "deleteBookmark" "/rest/deleteBookmark.view?$AUTH&id=$SONG_ID"
|
|
||||||
|
|
||||||
PLAYLIST_JSON="$(curl -s "$BASE/rest/createPlaylist.view?$AUTH&name=Smoke%20List&songId=$SONG_ID")"
|
log ""
|
||||||
PLAYLIST_ID="$(printf '%s' "$PLAYLIST_JSON" | python3 -c 'import json,sys; print(json.load(sys.stdin)["subsonic-response"]["playlist"]["id"])' 2>/dev/null || true)"
|
log "Library sync"
|
||||||
if [[ -z "$PLAYLIST_ID" ]]; then
|
expect "library snapshot (music)" "200" "GET" "/library/songs?scope=music"
|
||||||
fail "createPlaylist" "$(printf '%s' "$PLAYLIST_JSON" | head -c 300)"
|
MUSIC_COUNT="$(printf '%s' "$HTTP_BODY" | json_field '["songs"].__len__()' 2>/dev/null || echo 0)"
|
||||||
else
|
expect_eq "music snapshot has 2 songs" "2" "$MUSIC_COUNT"
|
||||||
pass "createPlaylist"
|
expect_eq "snapshot contains smoke song" "1" "$(printf '%s' "$HTTP_BODY" | python3 -c 'import json,sys;print(sum(1 for s in json.load(sys.stdin)["songs"] if s["id"]=="'"$SONG_ID"'"))')"
|
||||||
check "getPlaylists" "/rest/getPlaylists.view?$AUTH"
|
|
||||||
check "getPlaylist" "/rest/getPlaylist.view?$AUTH&id=$PLAYLIST_ID"
|
|
||||||
check "updatePlaylist" "/rest/updatePlaylist.view?$AUTH&playlistId=$PLAYLIST_ID&songIndexToRemove=0"
|
|
||||||
check "deletePlaylist" "/rest/deletePlaylist.view?$AUTH&id=$PLAYLIST_ID"
|
|
||||||
fi
|
|
||||||
|
|
||||||
MOOD_JSON="$(curl -s "$BASE/rest/createMood.view?$AUTH&name=Smoke%20Mood&songId=$SONG_ID&targetSize=5")"
|
expect "library snapshot (longform)" "200" "GET" "/library/songs?scope=longform"
|
||||||
MOOD_ID="$(printf '%s' "$MOOD_JSON" | python3 -c 'import json,sys; print(json.load(sys.stdin)["subsonic-response"]["mood"]["id"])' 2>/dev/null || true)"
|
expect_eq "longform snapshot has 1 song" "1" "$(printf '%s' "$HTTP_BODY" | json_field '["songs"].__len__()')"
|
||||||
if [[ -z "$MOOD_ID" ]]; then
|
expect "search" "200" "GET" "/library/search?q=smoke&scope=music"
|
||||||
fail "createMood" "$(printf '%s' "$MOOD_JSON" | head -c 300)"
|
expect_eq "search finds one song" "1" "$(printf '%s' "$HTTP_BODY" | json_field '["songs"].__len__()')"
|
||||||
else
|
|
||||||
pass "createMood"
|
|
||||||
check "getMoods" "/rest/getMoods.view?$AUTH"
|
|
||||||
check "getMood" "/rest/getMood.view?$AUTH&id=$MOOD_ID"
|
|
||||||
check "getPlaylist (mood)" "/rest/getPlaylist.view?$AUTH&id=$MOOD_ID"
|
|
||||||
check "refreshMood" "/rest/refreshMood.view?$AUTH&id=$MOOD_ID"
|
|
||||||
check "deleteMood" "/rest/deleteMood.view?$AUTH&id=$MOOD_ID"
|
|
||||||
fi
|
|
||||||
|
|
||||||
check "savePlayQueue" "/rest/savePlayQueue.view?$AUTH&id=$SONG_ID&position=0"
|
log ""
|
||||||
check "getPlayQueue" "/rest/getPlayQueue.view?$AUTH"
|
log "Moods"
|
||||||
check "savePlayQueueByIndex" "/rest/savePlayQueueByIndex.view?$AUTH&id=$SONG_ID¤tIndex=0&position=0"
|
expect "create mood" "201" "POST" "/moods" \
|
||||||
check "getPlayQueueByIndex" "/rest/getPlayQueueByIndex.view?$AUTH"
|
"{\"name\":\"Smoke Mood\",\"genres\":[\"Rock\"],\"targetSize\":10,\"seedSongIds\":[\"$SONG_ID\"]}"
|
||||||
|
MOOD_ID="$(printf '%s' "$HTTP_BODY" | json_field '["mood"]["id"]' 2>/dev/null || true)"
|
||||||
|
if [[ -n "$MOOD_ID" ]]; then pass "mood id"; else fail "mood id" "${HTTP_BODY:0:200}"; fi
|
||||||
|
expect_eq "mood seed count" "1" "$(printf '%s' "$HTTP_BODY" | json_field '["mood"]["seedCount"]')"
|
||||||
|
expect "list moods" "200" "GET" "/moods"
|
||||||
|
expect_eq "list contains mood" "1" "$(printf '%s' "$HTTP_BODY" | python3 -c 'import json,sys;print(sum(1 for m in json.load(sys.stdin)["moods"] if m["id"]=="'"$MOOD_ID"'"))')"
|
||||||
|
expect "get mood" "200" "GET" "/moods/$MOOD_ID"
|
||||||
|
expect "mood preview" "200" "GET" "/moods/$MOOD_ID/preview?limit=10"
|
||||||
|
expect_eq "preview is not empty" "yes" "$(printf '%s' "$HTTP_BODY" | python3 -c 'import json,sys;print("yes" if json.load(sys.stdin)["songs"] else "no")')"
|
||||||
|
expect "add seed" "200" "POST" "/moods/$MOOD_ID/seeds" "{\"songId\":\"$SONG2_ID\"}"
|
||||||
|
expect_eq "seed count after add" "2" "$(printf '%s' "$HTTP_BODY" | json_field '["mood"]["seedCount"]')"
|
||||||
|
expect "remove seed" "204" "DELETE" "/moods/$MOOD_ID/seeds/$SONG2_ID"
|
||||||
|
expect "get mood after seed removal" "200" "GET" "/moods/$MOOD_ID"
|
||||||
|
expect_eq "seed count after remove" "1" "$(printf '%s' "$HTTP_BODY" | json_field '["mood"]["seedCount"]')"
|
||||||
|
|
||||||
STREAM_STATUS="$(curl -s -o "$WORK/stream.mp3" -w '%{http_code}' "$BASE/rest/stream.view?$AUTH&id=$SONG_ID")"
|
log ""
|
||||||
|
log "Radio sessions"
|
||||||
|
expect "start session" "201" "POST" "/moods/$MOOD_ID/sessions" '{"limit":10}'
|
||||||
|
SESSION_ID="$(printf '%s' "$HTTP_BODY" | json_field '["id"]' 2>/dev/null || true)"
|
||||||
|
if [[ -n "$SESSION_ID" ]]; then pass "session id"; else fail "session id" "${HTTP_BODY:0:200}"; fi
|
||||||
|
expect_eq "queue contains seed" "yes" "$(printf '%s' "$HTTP_BODY" | python3 -c 'import json,sys;print("yes" if any(s["id"]=="'"$SONG_ID"'" for s in json.load(sys.stdin)["queue"]) else "no")')"
|
||||||
|
expect_eq "queue excludes longform" "yes" "$(printf '%s' "$HTTP_BODY" | python3 -c 'import json,sys;print("yes" if all(s["id"]!="'"$LONG_ID"'" for s in json.load(sys.stdin)["queue"]) else "no")')"
|
||||||
|
expect "next tracks" "200" "POST" "/sessions/$SESSION_ID/next" '{"limit":10}'
|
||||||
|
expect "playback event" "200" "POST" "/sessions/$SESSION_ID/events" \
|
||||||
|
"{\"events\":[{\"songId\":\"$SONG_ID\",\"type\":\"completed\",\"positionSeconds\":2}]}"
|
||||||
|
expect_eq "accepted events" "1" "$(printf '%s' "$HTTP_BODY" | json_field '["accepted"]')"
|
||||||
|
expect "add playing track to current mood" "200" "POST" "/sessions/$SESSION_ID/add-to-mood" \
|
||||||
|
"{\"songId\":\"$SONG2_ID\"}"
|
||||||
|
expect_eq "seed count after add-to-mood" "2" "$(printf '%s' "$HTTP_BODY" | json_field '["mood"]["seedCount"]')"
|
||||||
|
expect "resume session" "200" "GET" "/sessions/$SESSION_ID"
|
||||||
|
expect_eq "session mood" "$MOOD_ID" "$(printf '%s' "$HTTP_BODY" | json_field '["moodId"]')"
|
||||||
|
expect "close session" "204" "DELETE" "/sessions/$SESSION_ID"
|
||||||
|
|
||||||
|
log ""
|
||||||
|
log "Media"
|
||||||
|
STREAM_STATUS="$(curl -s -o "$WORK/stream.mp3" -w '%{http_code}' \
|
||||||
|
"$BASE/api/v1/songs/$SONG_ID/stream?token=$TOKEN")"
|
||||||
if [[ "$STREAM_STATUS" == "200" && -s "$WORK/stream.mp3" ]]; then
|
if [[ "$STREAM_STATUS" == "200" && -s "$WORK/stream.mp3" ]]; then
|
||||||
pass "stream"
|
pass "stream with query token"
|
||||||
else
|
else
|
||||||
fail "stream" "HTTP $STREAM_STATUS, $(wc -c < "$WORK/stream.mp3" 2>/dev/null || echo 0) bytes"
|
fail "stream with query token" "HTTP $STREAM_STATUS"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
RANGE_STATUS="$(curl -s -o /dev/null -w '%{http_code}' -H 'Range: bytes=0-9' "$BASE/rest/stream.view?$AUTH&id=$SONG_ID")"
|
RANGE_STATUS="$(curl -s -o /dev/null -w '%{http_code}' -H 'Range: bytes=0-9' \
|
||||||
if [[ "$RANGE_STATUS" == "206" ]]; then pass "stream range"; else fail "stream range" "HTTP $RANGE_STATUS"; fi
|
"$BASE/api/v1/songs/$SONG_ID/stream?token=$TOKEN")"
|
||||||
|
expect_eq "stream range" "206" "$RANGE_STATUS"
|
||||||
|
|
||||||
TRANSCODE_STATUS="$(curl -s -D "$WORK/transcode.headers" -o "$WORK/transcoded.mp3" -w '%{http_code}' "$BASE/rest/stream.view?$AUTH&id=$SONG_ID&maxBitRate=64")"
|
TRANSCODE_STATUS="$(curl -s -D "$WORK/transcode.headers" -o "$WORK/transcoded.mp3" -w '%{http_code}' \
|
||||||
|
"$BASE/api/v1/songs/$SONG_ID/stream?token=$TOKEN&maxBitRate=64")"
|
||||||
if [[ "$TRANSCODE_STATUS" == "200" && -s "$WORK/transcoded.mp3" ]] \
|
if [[ "$TRANSCODE_STATUS" == "200" && -s "$WORK/transcoded.mp3" ]] \
|
||||||
&& grep -qi '^content-type: audio/mpeg' "$WORK/transcode.headers" \
|
&& grep -qi '^content-type: audio/mpeg' "$WORK/transcode.headers"; then
|
||||||
&& [[ $(wc -c < "$WORK/transcoded.mp3") -lt $(wc -c < "$WORK/stream.mp3") ]]; then
|
pass "stream transcode"
|
||||||
pass "stream transcode (maxBitRate)"
|
|
||||||
else
|
else
|
||||||
fail "stream transcode (maxBitRate)" "HTTP $TRANSCODE_STATUS, $(wc -c < "$WORK/transcoded.mp3" 2>/dev/null || echo 0) bytes"
|
fail "stream transcode" "HTTP $TRANSCODE_STATUS"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
OFFSET_STATUS="$(curl -s -o "$WORK/offset.mp3" -w '%{http_code}' "$BASE/rest/stream.view?$AUTH&id=$SONG_ID&timeOffset=1")"
|
DOWNLOAD_STATUS="$(curl -s -o "$WORK/download.mp3" -w '%{http_code}' \
|
||||||
if [[ "$OFFSET_STATUS" == "200" && -s "$WORK/offset.mp3" ]] \
|
"$BASE/api/v1/songs/$SONG_ID/stream?token=$TOKEN&download=true")"
|
||||||
&& [[ $(wc -c < "$WORK/offset.mp3") -lt $(wc -c < "$WORK/stream.mp3") ]]; then
|
if [[ "$DOWNLOAD_STATUS" == "200" && -s "$WORK/download.mp3" ]]; then
|
||||||
pass "stream transcode (timeOffset)"
|
pass "download original"
|
||||||
else
|
else
|
||||||
fail "stream transcode (timeOffset)" "HTTP $OFFSET_STATUS"
|
fail "download original" "HTTP $DOWNLOAD_STATUS"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
FORMAT_STATUS="$(curl -s -o "$WORK/format.mp3" -w '%{http_code}' "$BASE/rest/stream.view?$AUTH&id=$SONG_ID&format=flac")"
|
COVER_STATUS="$(curl -s -o "$WORK/cover.jpg" -w '%{http_code}' \
|
||||||
if [[ "$FORMAT_STATUS" == "200" && -s "$WORK/format.mp3" ]]; then
|
"$BASE/api/v1/covers/$ALBUM_ID?size=32&token=$TOKEN")"
|
||||||
pass "stream transcode (format fallback)"
|
|
||||||
else
|
|
||||||
fail "stream transcode (format fallback)" "HTTP $FORMAT_STATUS"
|
|
||||||
fi
|
|
||||||
|
|
||||||
DOWNLOAD_STATUS="$(curl -s -o /dev/null -w '%{http_code}' "$BASE/rest/download.view?$AUTH&id=$SONG_ID")"
|
|
||||||
if [[ "$DOWNLOAD_STATUS" == "200" ]]; then pass "download"; else fail "download" "HTTP $DOWNLOAD_STATUS"; fi
|
|
||||||
|
|
||||||
COVER_STATUS="$(curl -s -o "$WORK/cover.jpg" -w '%{http_code}' "$BASE/rest/getCoverArt.view?$AUTH&id=$ALBUM_ID&size=32")"
|
|
||||||
if [[ "$COVER_STATUS" == "200" && -s "$WORK/cover.jpg" ]]; then
|
if [[ "$COVER_STATUS" == "200" && -s "$WORK/cover.jpg" ]]; then
|
||||||
pass "getCoverArt"
|
pass "cover art"
|
||||||
else
|
else
|
||||||
fail "getCoverArt" "HTTP $COVER_STATUS"
|
fail "cover art" "HTTP $COVER_STATUS"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
expect "scan status" "200" "GET" "/scan"
|
||||||
|
expect "start scan" "202" "POST" "/scan"
|
||||||
|
|
||||||
|
log ""
|
||||||
|
log "Cleanup"
|
||||||
|
expect "delete mood" "204" "DELETE" "/moods/$MOOD_ID"
|
||||||
|
expect "logout" "204" "POST" "/auth/logout"
|
||||||
|
api "GET" "/me" "" "$TOKEN"
|
||||||
|
expect_eq "token revoked after logout" "401" "$HTTP_STATUS"
|
||||||
|
|
||||||
log ""
|
log ""
|
||||||
log "Smoke test finished: $PASSED passed, $FAILED failed"
|
log "Smoke test finished: $PASSED passed, $FAILED failed"
|
||||||
log "Server log: $WORK/server.log"
|
log "Server log: $WORK/server.log"
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import io.ktor.server.plugins.contentnegotiation.ContentNegotiation
|
|||||||
import io.ktor.server.plugins.partialcontent.PartialContent
|
import io.ktor.server.plugins.partialcontent.PartialContent
|
||||||
import io.ktor.server.plugins.statuspages.StatusPages
|
import io.ktor.server.plugins.statuspages.StatusPages
|
||||||
import io.ktor.server.request.path
|
import io.ktor.server.request.path
|
||||||
|
import io.ktor.server.response.respond
|
||||||
import io.ktor.server.response.respondRedirect
|
import io.ktor.server.response.respondRedirect
|
||||||
import io.ktor.server.response.respondText
|
import io.ktor.server.response.respondText
|
||||||
import io.ktor.server.routing.get
|
import io.ktor.server.routing.get
|
||||||
@@ -27,15 +28,16 @@ import org.slf4j.LoggerFactory
|
|||||||
import win.taptap.musicmanager.config.AppConfig
|
import win.taptap.musicmanager.config.AppConfig
|
||||||
import win.taptap.musicmanager.config.LibraryConfig
|
import win.taptap.musicmanager.config.LibraryConfig
|
||||||
import win.taptap.musicmanager.config.UsersConfig
|
import win.taptap.musicmanager.config.UsersConfig
|
||||||
|
import win.taptap.musicmanager.api.ApiErrorBody
|
||||||
|
import win.taptap.musicmanager.api.ApiError
|
||||||
|
import win.taptap.musicmanager.api.ApiException
|
||||||
|
import win.taptap.musicmanager.api.apiRoutes
|
||||||
import win.taptap.musicmanager.db.ConfigRepository
|
import win.taptap.musicmanager.db.ConfigRepository
|
||||||
import win.taptap.musicmanager.db.DatabaseFactory
|
import win.taptap.musicmanager.db.DatabaseFactory
|
||||||
import win.taptap.musicmanager.db.MediaRepository
|
import win.taptap.musicmanager.db.MediaRepository
|
||||||
import win.taptap.musicmanager.db.MoodRepository
|
import win.taptap.musicmanager.radio.RadioService
|
||||||
import win.taptap.musicmanager.mood.MoodService
|
|
||||||
import win.taptap.musicmanager.scanner.CoverArtService
|
import win.taptap.musicmanager.scanner.CoverArtService
|
||||||
import win.taptap.musicmanager.scanner.MediaScanner
|
import win.taptap.musicmanager.scanner.MediaScanner
|
||||||
import win.taptap.musicmanager.subsonic.respondSubsonicError
|
|
||||||
import win.taptap.musicmanager.subsonic.routes.subsonicRoutes
|
|
||||||
import win.taptap.musicmanager.transcoding.FfmpegTranscoder
|
import win.taptap.musicmanager.transcoding.FfmpegTranscoder
|
||||||
|
|
||||||
private val log = LoggerFactory.getLogger("win.taptap.musicmanager.Application")
|
private val log = LoggerFactory.getLogger("win.taptap.musicmanager.Application")
|
||||||
@@ -53,11 +55,10 @@ fun main() {
|
|||||||
val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||||
val coverArtService = CoverArtService(config.dataDir)
|
val coverArtService = CoverArtService(config.dataDir)
|
||||||
val transcoder = FfmpegTranscoder(config.ffmpegPath)
|
val transcoder = FfmpegTranscoder(config.ffmpegPath)
|
||||||
val moodService = MoodService(applicationScope)
|
val radioService = RadioService()
|
||||||
val scanner = MediaScanner(
|
val scanner = MediaScanner(
|
||||||
library = library,
|
library = library,
|
||||||
coverArtService = coverArtService,
|
coverArtService = coverArtService,
|
||||||
onScanFinished = { MoodRepository.markAllStale() },
|
|
||||||
)
|
)
|
||||||
if (MediaRepository.countSongs() == 0L) {
|
if (MediaRepository.countSongs() == 0L) {
|
||||||
log.info("Song table is empty, starting initial library scan")
|
log.info("Song table is empty, starting initial library scan")
|
||||||
@@ -84,10 +85,26 @@ fun main() {
|
|||||||
install(AutoHeadResponse)
|
install(AutoHeadResponse)
|
||||||
install(CallLogging)
|
install(CallLogging)
|
||||||
install(StatusPages) {
|
install(StatusPages) {
|
||||||
|
exception<ApiException> { call, cause ->
|
||||||
|
call.respond(
|
||||||
|
cause.status,
|
||||||
|
ApiErrorBody(
|
||||||
|
ApiError(cause.code, cause.message),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
exception<Throwable> { call, cause ->
|
exception<Throwable> { call, cause ->
|
||||||
log.error("Unhandled exception for ${call.request.path()}", cause)
|
log.error("Unhandled exception for ${call.request.path()}", cause)
|
||||||
if (call.request.path().startsWith("/rest/")) {
|
if (call.request.path().startsWith("/api/")) {
|
||||||
call.respondSubsonicError(0, "Internal server error")
|
call.respond(
|
||||||
|
HttpStatusCode.InternalServerError,
|
||||||
|
ApiErrorBody(
|
||||||
|
ApiError(
|
||||||
|
"internal",
|
||||||
|
"Internal server error",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
} else {
|
} else {
|
||||||
call.respondText("Internal server error", status = HttpStatusCode.InternalServerError)
|
call.respondText("Internal server error", status = HttpStatusCode.InternalServerError)
|
||||||
}
|
}
|
||||||
@@ -100,12 +117,12 @@ fun main() {
|
|||||||
get("/") { call.respondRedirect("/ui") }
|
get("/") { call.respondRedirect("/ui") }
|
||||||
get("/ui") { call.respondText(webUiHtml, ContentType.Text.Html) }
|
get("/ui") { call.respondText(webUiHtml, ContentType.Text.Html) }
|
||||||
}
|
}
|
||||||
subsonicRoutes(
|
apiRoutes(
|
||||||
users = users,
|
users = users,
|
||||||
library = library,
|
library = library,
|
||||||
coverArtService = coverArtService,
|
coverArtService = coverArtService,
|
||||||
transcoder = transcoder,
|
transcoder = transcoder,
|
||||||
moodService = moodService,
|
radioService = radioService,
|
||||||
startScan = { scanner.start(applicationScope) },
|
startScan = { scanner.start(applicationScope) },
|
||||||
scanStatus = { scanner.status() },
|
scanStatus = { scanner.status() },
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,240 @@
|
|||||||
|
package win.taptap.musicmanager.api
|
||||||
|
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
import win.taptap.musicmanager.db.MoodRecord
|
||||||
|
import win.taptap.musicmanager.db.MoodSeedRecord
|
||||||
|
import win.taptap.musicmanager.db.SongRecord
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class ApiErrorBody(val error: ApiError)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class ApiError(val code: String, val message: String)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class LoginRequest(
|
||||||
|
val username: String,
|
||||||
|
val password: String,
|
||||||
|
val deviceName: String = "Unknown device",
|
||||||
|
val platform: String = "unknown",
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class UserDto(
|
||||||
|
val name: String,
|
||||||
|
val admin: Boolean,
|
||||||
|
val musicFolders: List<Int>,
|
||||||
|
val longformFolders: List<Int>,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class LoginResponse(
|
||||||
|
val token: String,
|
||||||
|
val expiresAt: String,
|
||||||
|
val user: UserDto,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class DeviceDto(
|
||||||
|
val id: String,
|
||||||
|
val deviceName: String,
|
||||||
|
val platform: String,
|
||||||
|
val createdAt: String,
|
||||||
|
val lastUsedAt: String,
|
||||||
|
val expiresAt: String,
|
||||||
|
val current: Boolean,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class SongDto(
|
||||||
|
val id: String,
|
||||||
|
val title: String,
|
||||||
|
val artist: String,
|
||||||
|
val album: String,
|
||||||
|
val albumId: String,
|
||||||
|
val trackNumber: Int? = null,
|
||||||
|
val discNumber: Int = 1,
|
||||||
|
val year: Int? = null,
|
||||||
|
val duration: Int,
|
||||||
|
val bitRate: Int,
|
||||||
|
val size: Long,
|
||||||
|
val suffix: String,
|
||||||
|
val genres: List<String> = emptyList(),
|
||||||
|
val folderId: Int,
|
||||||
|
val relativePath: String,
|
||||||
|
val updatedAt: String,
|
||||||
|
)
|
||||||
|
|
||||||
|
fun SongRecord.toDto(): SongDto = SongDto(
|
||||||
|
id = id,
|
||||||
|
title = title,
|
||||||
|
artist = displayArtist,
|
||||||
|
album = albumName,
|
||||||
|
albumId = albumId,
|
||||||
|
trackNumber = trackNumber,
|
||||||
|
discNumber = discNumber,
|
||||||
|
year = year,
|
||||||
|
duration = duration,
|
||||||
|
bitRate = bitRate,
|
||||||
|
size = size,
|
||||||
|
suffix = suffix,
|
||||||
|
genres = genres,
|
||||||
|
folderId = folderId,
|
||||||
|
relativePath = relativePath,
|
||||||
|
updatedAt = updatedAt,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class SeedDto(
|
||||||
|
val song: SongDto,
|
||||||
|
val origin: String,
|
||||||
|
val addedAt: String,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class MoodDto(
|
||||||
|
val id: String,
|
||||||
|
val name: String,
|
||||||
|
val description: String? = null,
|
||||||
|
val query: String? = null,
|
||||||
|
val genres: List<String> = emptyList(),
|
||||||
|
val targetSize: Int,
|
||||||
|
val refreshHours: Int,
|
||||||
|
val ytEnabled: Boolean,
|
||||||
|
val lastDiscoveryAt: String? = null,
|
||||||
|
val createdAt: String,
|
||||||
|
val changedAt: String,
|
||||||
|
val lastError: String? = null,
|
||||||
|
val seedCount: Int,
|
||||||
|
val newRecommendations: Int,
|
||||||
|
)
|
||||||
|
|
||||||
|
fun MoodRecord.toDto(): MoodDto = MoodDto(
|
||||||
|
id = id,
|
||||||
|
name = name,
|
||||||
|
description = description,
|
||||||
|
query = query,
|
||||||
|
genres = genres,
|
||||||
|
targetSize = targetSize,
|
||||||
|
refreshHours = refreshHours,
|
||||||
|
ytEnabled = ytEnabled,
|
||||||
|
lastDiscoveryAt = lastDiscoveryAt,
|
||||||
|
createdAt = createdAt,
|
||||||
|
changedAt = changedAt,
|
||||||
|
lastError = lastError,
|
||||||
|
seedCount = seedCount,
|
||||||
|
newRecommendations = newRecommendations,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class MoodDetailDto(
|
||||||
|
val mood: MoodDto,
|
||||||
|
val seeds: List<SeedDto>,
|
||||||
|
val recommendations: List<RecommendationDto> = emptyList(),
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class CreateMoodRequest(
|
||||||
|
val name: String,
|
||||||
|
val description: String? = null,
|
||||||
|
val query: String? = null,
|
||||||
|
val genres: List<String> = emptyList(),
|
||||||
|
val targetSize: Int = 30,
|
||||||
|
val refreshHours: Int = 24,
|
||||||
|
val ytEnabled: Boolean = true,
|
||||||
|
val seedSongIds: List<String> = emptyList(),
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class UpdateMoodRequest(
|
||||||
|
val name: String? = null,
|
||||||
|
val description: String? = null,
|
||||||
|
val clearDescription: Boolean = false,
|
||||||
|
val query: String? = null,
|
||||||
|
val clearQuery: Boolean = false,
|
||||||
|
val genres: List<String>? = null,
|
||||||
|
val targetSize: Int? = null,
|
||||||
|
val refreshHours: Int? = null,
|
||||||
|
val ytEnabled: Boolean? = null,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class AddSeedRequest(val songId: String, val origin: String = "manual")
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class AddToMoodRequest(val songId: String, val moodId: String? = null)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class AddToMoodResponse(
|
||||||
|
val mood: MoodDto,
|
||||||
|
val added: Boolean,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class LibraryPage(
|
||||||
|
val songs: List<SongDto>,
|
||||||
|
val deletedSongIds: List<String> = emptyList(),
|
||||||
|
val revision: String,
|
||||||
|
val nextCursor: String? = null,
|
||||||
|
val nextSince: String? = null,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class SearchResponse(val songs: List<SongDto>)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class StartSessionRequest(val limit: Int? = null)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class NextTracksRequest(
|
||||||
|
val limit: Int? = null,
|
||||||
|
val excludeSongIds: List<String> = emptyList(),
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class SessionDto(
|
||||||
|
val id: String,
|
||||||
|
val moodId: String,
|
||||||
|
val moodName: String,
|
||||||
|
val startedAt: String,
|
||||||
|
val closedAt: String? = null,
|
||||||
|
val queue: List<SongDto> = emptyList(),
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class PlaybackEvent(
|
||||||
|
val songId: String,
|
||||||
|
val type: String,
|
||||||
|
val positionSeconds: Int? = null,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class PlaybackEventsRequest(val events: List<PlaybackEvent>)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class PlaybackEventsResponse(val accepted: Int)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class ScanStatusDto(
|
||||||
|
val scanning: Boolean,
|
||||||
|
val count: Long,
|
||||||
|
val error: String? = null,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class RecommendationDto(
|
||||||
|
val videoId: String,
|
||||||
|
val title: String,
|
||||||
|
val artist: String,
|
||||||
|
val album: String? = null,
|
||||||
|
val duration: Int? = null,
|
||||||
|
val thumbnail: String? = null,
|
||||||
|
val state: String,
|
||||||
|
val matchedSong: SongDto? = null,
|
||||||
|
val timesAdded: Int,
|
||||||
|
val firstSeen: String,
|
||||||
|
val lastSeen: String,
|
||||||
|
)
|
||||||
|
|
||||||
|
fun seedDto(seed: MoodSeedRecord, song: SongRecord): SeedDto =
|
||||||
|
SeedDto(song = song.toDto(), origin = seed.origin, addedAt = seed.addedAt)
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
package win.taptap.musicmanager.api
|
||||||
|
|
||||||
|
import io.ktor.http.HttpStatusCode
|
||||||
|
import io.ktor.server.response.respond
|
||||||
|
import io.ktor.server.routing.Route
|
||||||
|
import io.ktor.server.routing.delete
|
||||||
|
import io.ktor.server.routing.get
|
||||||
|
import io.ktor.server.routing.post
|
||||||
|
import io.ktor.server.routing.route
|
||||||
|
import java.security.MessageDigest
|
||||||
|
import win.taptap.musicmanager.api.DeviceDto
|
||||||
|
import win.taptap.musicmanager.api.LoginRequest
|
||||||
|
import win.taptap.musicmanager.api.LoginResponse
|
||||||
|
import win.taptap.musicmanager.api.ScanStatusDto
|
||||||
|
import win.taptap.musicmanager.api.UserDto
|
||||||
|
import win.taptap.musicmanager.config.LibraryConfig
|
||||||
|
import win.taptap.musicmanager.config.UsersConfig
|
||||||
|
import win.taptap.musicmanager.db.ApiTokenRepository
|
||||||
|
import win.taptap.musicmanager.radio.RadioService
|
||||||
|
import win.taptap.musicmanager.scanner.CoverArtService
|
||||||
|
import win.taptap.musicmanager.scanner.ScanStatus
|
||||||
|
import win.taptap.musicmanager.transcoding.FfmpegTranscoder
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Routing for the native API.
|
||||||
|
*
|
||||||
|
* Every handler resolves the bearer token explicitly. Media URLs may also carry
|
||||||
|
* `?token=` because HTML audio and `<img>` tags cannot set headers.
|
||||||
|
*/
|
||||||
|
fun Route.apiRoutes(
|
||||||
|
users: UsersConfig,
|
||||||
|
library: LibraryConfig,
|
||||||
|
coverArtService: CoverArtService,
|
||||||
|
transcoder: FfmpegTranscoder,
|
||||||
|
radioService: RadioService,
|
||||||
|
startScan: () -> Boolean,
|
||||||
|
scanStatus: () -> ScanStatus,
|
||||||
|
) {
|
||||||
|
route("/api/v1") {
|
||||||
|
post("/auth/login") {
|
||||||
|
val request = call.receiveJson<LoginRequest>()
|
||||||
|
val user = users.byName(request.username.trim())
|
||||||
|
?: throw ApiException(
|
||||||
|
HttpStatusCode.Unauthorized,
|
||||||
|
"invalid_credentials",
|
||||||
|
"Wrong username or password",
|
||||||
|
)
|
||||||
|
if (!constantTimeEquals(request.password, user.password)) {
|
||||||
|
throw ApiException(
|
||||||
|
HttpStatusCode.Unauthorized,
|
||||||
|
"invalid_credentials",
|
||||||
|
"Wrong username or password",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
val issued = ApiTokenRepository.create(
|
||||||
|
userName = user.name,
|
||||||
|
deviceName = request.deviceName.ifBlank { "Unknown device" },
|
||||||
|
platform = request.platform.ifBlank { "unknown" },
|
||||||
|
)
|
||||||
|
call.respond(
|
||||||
|
HttpStatusCode.OK,
|
||||||
|
LoginResponse(
|
||||||
|
token = issued.raw,
|
||||||
|
expiresAt = issued.record.expiresAt,
|
||||||
|
user = user.toDto(library),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
get("/me") {
|
||||||
|
val user = call.requireApiUser(users)
|
||||||
|
call.respond(UserDto(
|
||||||
|
name = user.name,
|
||||||
|
admin = user.admin,
|
||||||
|
musicFolders = user.musicFolderIds(library).sorted(),
|
||||||
|
longformFolders = user.longformFolderIds(library).sorted(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
post("/auth/logout") {
|
||||||
|
val user = call.requireApiUser(users)
|
||||||
|
ApiTokenRepository.revokeRaw(call.bearerToken().orEmpty())
|
||||||
|
call.respond(HttpStatusCode.NoContent)
|
||||||
|
}
|
||||||
|
|
||||||
|
get("/auth/devices") {
|
||||||
|
val user = call.requireApiUser(users)
|
||||||
|
val current = call.apiToken()
|
||||||
|
val devices = ApiTokenRepository.list(user.name).map { record ->
|
||||||
|
DeviceDto(
|
||||||
|
id = record.id,
|
||||||
|
deviceName = record.deviceName,
|
||||||
|
platform = record.platform,
|
||||||
|
createdAt = record.createdAt,
|
||||||
|
lastUsedAt = record.lastUsedAt,
|
||||||
|
expiresAt = record.expiresAt,
|
||||||
|
current = record.id == current?.id,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
call.respond(devices)
|
||||||
|
}
|
||||||
|
|
||||||
|
delete("/auth/devices/{id}") {
|
||||||
|
val user = call.requireApiUser(users)
|
||||||
|
val id = call.parameters["id"] ?: badRequest("Device id is required")
|
||||||
|
if (!ApiTokenRepository.revoke(id, user.name)) notFound("Device")
|
||||||
|
call.respond(HttpStatusCode.NoContent)
|
||||||
|
}
|
||||||
|
|
||||||
|
get("/scan") {
|
||||||
|
call.requireApiUser(users)
|
||||||
|
val status = scanStatus()
|
||||||
|
call.respond(ScanStatusDto(status.scanning, status.count, status.error))
|
||||||
|
}
|
||||||
|
|
||||||
|
post("/scan") {
|
||||||
|
val user = call.requireApiUser(users)
|
||||||
|
if (!user.admin) forbidden("Only admins can start a scan")
|
||||||
|
val started = startScan()
|
||||||
|
call.respond(
|
||||||
|
HttpStatusCode.Accepted,
|
||||||
|
ScanStatusDto(scanning = started, count = scanStatus().count),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
libraryRoutes(users, library, coverArtService, transcoder)
|
||||||
|
moodRoutes(users, library, radioService)
|
||||||
|
sessionRoutes(users, library, radioService)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun constantTimeEquals(candidate: String, expected: String): Boolean =
|
||||||
|
MessageDigest.isEqual(
|
||||||
|
candidate.toByteArray(Charsets.UTF_8),
|
||||||
|
expected.toByteArray(Charsets.UTF_8),
|
||||||
|
)
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
package win.taptap.musicmanager.api
|
||||||
|
|
||||||
|
import io.ktor.http.HttpHeaders
|
||||||
|
import io.ktor.http.HttpStatusCode
|
||||||
|
import io.ktor.server.application.ApplicationCall
|
||||||
|
import io.ktor.server.request.receive
|
||||||
|
import io.ktor.server.response.respond
|
||||||
|
import io.ktor.util.AttributeKey
|
||||||
|
import kotlinx.serialization.SerializationException
|
||||||
|
import win.taptap.musicmanager.api.ApiError
|
||||||
|
import win.taptap.musicmanager.api.ApiErrorBody
|
||||||
|
import win.taptap.musicmanager.api.UserDto
|
||||||
|
import win.taptap.musicmanager.config.FolderType
|
||||||
|
import win.taptap.musicmanager.config.LibraryConfig
|
||||||
|
import win.taptap.musicmanager.config.UserAccount
|
||||||
|
import win.taptap.musicmanager.config.UsersConfig
|
||||||
|
import win.taptap.musicmanager.db.ApiTokenRecord
|
||||||
|
import win.taptap.musicmanager.db.ApiTokenRepository
|
||||||
|
|
||||||
|
/** HTTP-shaped error rendered by the global StatusPages handler. */
|
||||||
|
class ApiException(
|
||||||
|
val status: HttpStatusCode,
|
||||||
|
val code: String,
|
||||||
|
override val message: String,
|
||||||
|
) : RuntimeException(message)
|
||||||
|
|
||||||
|
val ApiUserKey = AttributeKey<UserAccount>("musicmanager.api.user")
|
||||||
|
val ApiTokenKey = AttributeKey<ApiTokenRecord>("musicmanager.api.token")
|
||||||
|
|
||||||
|
fun UserAccount.musicFolderIds(library: LibraryConfig): Set<Int> =
|
||||||
|
library.folders
|
||||||
|
.asSequence()
|
||||||
|
.filter { it.type == FolderType.MUSIC && it.id in folders }
|
||||||
|
.map { it.id }
|
||||||
|
.toSet()
|
||||||
|
|
||||||
|
fun UserAccount.longformFolderIds(library: LibraryConfig): Set<Int> =
|
||||||
|
library.folders
|
||||||
|
.asSequence()
|
||||||
|
.filter { it.type == FolderType.LONGFORM }
|
||||||
|
.map { it.id }
|
||||||
|
.toSet()
|
||||||
|
|
||||||
|
fun UserAccount.toDto(library: LibraryConfig): UserDto = UserDto(
|
||||||
|
name = name,
|
||||||
|
admin = admin,
|
||||||
|
musicFolders = musicFolderIds(library).sorted(),
|
||||||
|
longformFolders = longformFolderIds(library).sorted(),
|
||||||
|
)
|
||||||
|
|
||||||
|
fun ApplicationCall.apiUser(): UserAccount =
|
||||||
|
attributes.getOrNull(ApiUserKey) ?: throw ApiException(
|
||||||
|
HttpStatusCode.Unauthorized,
|
||||||
|
"unauthorized",
|
||||||
|
"Authentication required",
|
||||||
|
)
|
||||||
|
|
||||||
|
fun ApplicationCall.apiToken(): ApiTokenRecord? = attributes.getOrNull(ApiTokenKey)
|
||||||
|
|
||||||
|
fun apiErrorBody(code: String, message: String): ApiErrorBody =
|
||||||
|
ApiErrorBody(ApiError(code, message))
|
||||||
|
|
||||||
|
/** Bearer header is the norm; `token` exists for browser audio and image URLs. */
|
||||||
|
fun ApplicationCall.bearerToken(): String? {
|
||||||
|
val header = request.headers[HttpHeaders.Authorization]
|
||||||
|
if (!header.isNullOrBlank()) {
|
||||||
|
val value = header.trim()
|
||||||
|
if (value.startsWith("Bearer ", ignoreCase = true)) {
|
||||||
|
return value.substringAfter(' ').trim().takeIf { it.isNotEmpty() }
|
||||||
|
}
|
||||||
|
return value.takeIf { it.isNotEmpty() }
|
||||||
|
}
|
||||||
|
return request.queryParameters["token"]?.takeIf { it.isNotBlank() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves the token and stores the user on the call. Returns null after sending
|
||||||
|
* a 401, so handlers can simply `?: return@get`.
|
||||||
|
*/
|
||||||
|
suspend fun ApplicationCall.requireApiUser(users: UsersConfig): UserAccount {
|
||||||
|
val raw = bearerToken()
|
||||||
|
val token = raw?.let { ApiTokenRepository.resolve(it) }
|
||||||
|
val user = token?.let { users.byName(it.userName) }
|
||||||
|
if (token == null || user == null) {
|
||||||
|
throw ApiException(HttpStatusCode.Unauthorized, "unauthorized", "Missing or invalid token")
|
||||||
|
}
|
||||||
|
attributes.put(ApiUserKey, user)
|
||||||
|
attributes.put(ApiTokenKey, token)
|
||||||
|
return user
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend inline fun <reified T : Any> ApplicationCall.receiveJson(): T =
|
||||||
|
try {
|
||||||
|
receive<T>()
|
||||||
|
} catch (e: SerializationException) {
|
||||||
|
throw ApiException(HttpStatusCode.BadRequest, "invalid_body", "Invalid JSON body")
|
||||||
|
} catch (e: IllegalArgumentException) {
|
||||||
|
throw ApiException(HttpStatusCode.BadRequest, "invalid_body", e.message ?: "Invalid body")
|
||||||
|
}
|
||||||
|
|
||||||
|
fun notFound(what: String): Nothing =
|
||||||
|
throw ApiException(HttpStatusCode.NotFound, "not_found", "$what not found")
|
||||||
|
|
||||||
|
fun badRequest(message: String): Nothing =
|
||||||
|
throw ApiException(HttpStatusCode.BadRequest, "bad_request", message)
|
||||||
|
|
||||||
|
fun forbidden(message: String): Nothing =
|
||||||
|
throw ApiException(HttpStatusCode.Forbidden, "forbidden", message)
|
||||||
|
|
||||||
|
fun conflict(message: String): Nothing =
|
||||||
|
throw ApiException(HttpStatusCode.Conflict, "conflict", message)
|
||||||
@@ -0,0 +1,188 @@
|
|||||||
|
package win.taptap.musicmanager.api
|
||||||
|
|
||||||
|
import io.ktor.http.ContentType
|
||||||
|
import io.ktor.http.HttpHeaders
|
||||||
|
import io.ktor.http.HttpStatusCode
|
||||||
|
import io.ktor.server.response.respond
|
||||||
|
import io.ktor.server.response.header
|
||||||
|
import io.ktor.server.response.respondFile
|
||||||
|
import io.ktor.server.response.respondOutputStream
|
||||||
|
import io.ktor.server.routing.Route
|
||||||
|
import io.ktor.server.routing.get
|
||||||
|
import java.net.URLEncoder
|
||||||
|
import java.time.Instant
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import org.slf4j.LoggerFactory
|
||||||
|
import win.taptap.musicmanager.api.LibraryPage
|
||||||
|
import win.taptap.musicmanager.api.SearchResponse
|
||||||
|
import win.taptap.musicmanager.api.toDto
|
||||||
|
import win.taptap.musicmanager.config.LibraryConfig
|
||||||
|
import win.taptap.musicmanager.config.UsersConfig
|
||||||
|
import win.taptap.musicmanager.db.LibraryRepository
|
||||||
|
import win.taptap.musicmanager.scanner.CoverArtService
|
||||||
|
import win.taptap.musicmanager.transcoding.FfmpegTranscoder
|
||||||
|
|
||||||
|
private val log = LoggerFactory.getLogger("win.taptap.musicmanager.api.LibraryRoutes")
|
||||||
|
|
||||||
|
fun Route.libraryRoutes(
|
||||||
|
users: UsersConfig,
|
||||||
|
library: LibraryConfig,
|
||||||
|
coverArtService: CoverArtService,
|
||||||
|
transcoder: FfmpegTranscoder,
|
||||||
|
) {
|
||||||
|
/**
|
||||||
|
* Snapshot sync (`cursor`) and delta sync (`since=revision`) in one endpoint.
|
||||||
|
* Deletions are returned explicitly so offline libraries can drop them.
|
||||||
|
*/
|
||||||
|
get("/library/songs") {
|
||||||
|
val user = call.requireApiUser(users)
|
||||||
|
val limit = (call.request.queryParameters["limit"]?.toIntOrNull() ?: 500).coerceIn(1, 1000)
|
||||||
|
val scope = call.request.queryParameters["scope"] ?: "all"
|
||||||
|
val folders = user.scopeFolders(library, scope)
|
||||||
|
val now = Instant.now().toString()
|
||||||
|
val since = call.request.queryParameters["since"]?.takeIf { it.isNotBlank() }
|
||||||
|
val cursor = call.request.queryParameters["cursor"]?.takeIf { it.isNotBlank() }
|
||||||
|
|
||||||
|
if (since != null) {
|
||||||
|
val changed = LibraryRepository.changedSongs(since, folders, limit, user.name)
|
||||||
|
val deleted = LibraryRepository.tombstones(since, limit).map { it.entityId }
|
||||||
|
val complete = changed.size < limit && deleted.size < limit
|
||||||
|
call.respond(
|
||||||
|
LibraryPage(
|
||||||
|
songs = changed.map { it.toDto() },
|
||||||
|
deletedSongIds = deleted,
|
||||||
|
revision = if (complete) now else changed.lastOrNull()?.updatedAt ?: now,
|
||||||
|
nextSince = if (changed.size == limit) changed.last().updatedAt else null,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
return@get
|
||||||
|
}
|
||||||
|
|
||||||
|
val songs = LibraryRepository.syncSongs(folders, cursor.orEmpty(), limit, user.name)
|
||||||
|
call.respond(
|
||||||
|
LibraryPage(
|
||||||
|
songs = songs.map { it.toDto() },
|
||||||
|
revision = now,
|
||||||
|
nextCursor = if (songs.size == limit) songs.last().id else null,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
get("/library/search") {
|
||||||
|
val user = call.requireApiUser(users)
|
||||||
|
val query = call.request.queryParameters["q"]?.trim().orEmpty()
|
||||||
|
if (query.isEmpty()) {
|
||||||
|
call.respond(SearchResponse(emptyList()))
|
||||||
|
return@get
|
||||||
|
}
|
||||||
|
val limit = (call.request.queryParameters["limit"]?.toIntOrNull() ?: 50).coerceIn(1, 200)
|
||||||
|
val folders = user.scopeFolders(library, call.request.queryParameters["scope"] ?: "all")
|
||||||
|
val songs = LibraryRepository.searchSongs(query, limit, 0, folders, user.name)
|
||||||
|
call.respond(SearchResponse(songs.map { it.toDto() }))
|
||||||
|
}
|
||||||
|
|
||||||
|
get("/songs/{id}/stream") {
|
||||||
|
val user = call.requireApiUser(users)
|
||||||
|
val id = call.parameters["id"] ?: badRequest("Song id is required")
|
||||||
|
val parameters = call.request.queryParameters
|
||||||
|
|
||||||
|
val rawMaxBitRate = parameters["maxBitRate"]
|
||||||
|
val maxBitRate = rawMaxBitRate?.toIntOrNull()
|
||||||
|
if (rawMaxBitRate != null && (maxBitRate == null || maxBitRate < 0)) {
|
||||||
|
badRequest("Invalid maxBitRate")
|
||||||
|
}
|
||||||
|
val rawOffset = parameters["timeOffset"]
|
||||||
|
val offset = rawOffset?.toIntOrNull()
|
||||||
|
if (rawOffset != null && (offset == null || offset < 0)) {
|
||||||
|
badRequest("Invalid timeOffset")
|
||||||
|
}
|
||||||
|
|
||||||
|
val resolved = LibraryRepository.resolveSong(
|
||||||
|
id,
|
||||||
|
user.visibleFolderIds(library),
|
||||||
|
user.name,
|
||||||
|
library,
|
||||||
|
) ?: notFound("Song")
|
||||||
|
|
||||||
|
if (!transcoder.shouldTranscode(
|
||||||
|
resolved.song.bitRate,
|
||||||
|
maxBitRate,
|
||||||
|
parameters["format"],
|
||||||
|
offset ?: 0,
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
call.response.header(HttpHeaders.ContentType, resolved.song.contentType)
|
||||||
|
if (parameters["download"] == "true") {
|
||||||
|
call.response.header(
|
||||||
|
HttpHeaders.ContentDisposition,
|
||||||
|
contentDisposition(resolved.file.fileName.toString()),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
call.respondFile(resolved.file.toFile())
|
||||||
|
return@get
|
||||||
|
}
|
||||||
|
|
||||||
|
val process = try {
|
||||||
|
transcoder.start(resolved.file, maxBitRate, offset ?: 0)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
log.error("Failed to start ffmpeg for {}", resolved.file, e)
|
||||||
|
throw ApiException(HttpStatusCode.InternalServerError, "transcode_failed", "Transcoding failed")
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
call.response.headers.append(HttpHeaders.CacheControl, "no-store")
|
||||||
|
call.respondOutputStream(ContentType.parse("audio/mpeg")) {
|
||||||
|
val output = this
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
process.inputStream.use { input -> input.copyTo(output) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
transcoder.stop(process)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
get("/covers/{id}") {
|
||||||
|
val user = call.requireApiUser(users)
|
||||||
|
val id = call.parameters["id"] ?: badRequest("Cover id is required")
|
||||||
|
val rawSize = call.request.queryParameters["size"]
|
||||||
|
val size = rawSize?.toIntOrNull()
|
||||||
|
if (rawSize != null && (size == null || size !in 1..2048)) {
|
||||||
|
badRequest("Cover size must be between 1 and 2048")
|
||||||
|
}
|
||||||
|
|
||||||
|
val folders = user.visibleFolderIds(library)
|
||||||
|
val albumId = when {
|
||||||
|
id.startsWith("sg-") -> LibraryRepository.albumIdForSong(id, folders)
|
||||||
|
LibraryRepository.album(id, folders, user.name) != null -> id
|
||||||
|
else -> null
|
||||||
|
} ?: notFound("Cover")
|
||||||
|
|
||||||
|
val cover = if (size == null) {
|
||||||
|
coverArtService.coverFile(albumId)
|
||||||
|
} else {
|
||||||
|
coverArtService.resizedCover(albumId, size)
|
||||||
|
} ?: notFound("Cover")
|
||||||
|
|
||||||
|
call.respondFile(cover.toFile())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun win.taptap.musicmanager.config.UserAccount.scopeFolders(
|
||||||
|
library: LibraryConfig,
|
||||||
|
scope: String,
|
||||||
|
): Set<Int> = when (scope) {
|
||||||
|
"music" -> musicFolderIds(library)
|
||||||
|
"longform" -> longformFolderIds(library)
|
||||||
|
else -> visibleFolderIds(library)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun contentDisposition(fileName: String): String {
|
||||||
|
val encoded = URLEncoder.encode(fileName, Charsets.UTF_8).replace("+", "%20")
|
||||||
|
val ascii = fileName.map { character ->
|
||||||
|
if (character.code in 32..126 && character != '"' && character != '\\') character else '_'
|
||||||
|
}.joinToString("")
|
||||||
|
|
||||||
|
return "attachment; filename=\"$ascii\"; filename*=UTF-8''$encoded"
|
||||||
|
}
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
package win.taptap.musicmanager.api
|
||||||
|
|
||||||
|
import io.ktor.http.HttpStatusCode
|
||||||
|
import io.ktor.server.response.respond
|
||||||
|
import io.ktor.server.routing.Route
|
||||||
|
import io.ktor.server.routing.delete
|
||||||
|
import io.ktor.server.routing.get
|
||||||
|
import io.ktor.server.routing.patch
|
||||||
|
import io.ktor.server.routing.post
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
import win.taptap.musicmanager.api.AddSeedRequest
|
||||||
|
import win.taptap.musicmanager.api.AddToMoodResponse
|
||||||
|
import win.taptap.musicmanager.api.CreateMoodRequest
|
||||||
|
import win.taptap.musicmanager.api.MoodDetailDto
|
||||||
|
import win.taptap.musicmanager.api.MoodDto
|
||||||
|
import win.taptap.musicmanager.api.RecommendationDto
|
||||||
|
import win.taptap.musicmanager.api.SearchResponse
|
||||||
|
import win.taptap.musicmanager.api.UpdateMoodRequest
|
||||||
|
import win.taptap.musicmanager.api.seedDto
|
||||||
|
import win.taptap.musicmanager.api.toDto
|
||||||
|
import win.taptap.musicmanager.config.LibraryConfig
|
||||||
|
import win.taptap.musicmanager.config.UserAccount
|
||||||
|
import win.taptap.musicmanager.config.UsersConfig
|
||||||
|
import win.taptap.musicmanager.db.LibraryRepository
|
||||||
|
import win.taptap.musicmanager.db.MoodRecord
|
||||||
|
import win.taptap.musicmanager.db.MoodRepository
|
||||||
|
import win.taptap.musicmanager.radio.RadioService
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class MoodsResponse(val moods: List<MoodDto>)
|
||||||
|
|
||||||
|
fun Route.moodRoutes(
|
||||||
|
users: UsersConfig,
|
||||||
|
library: LibraryConfig,
|
||||||
|
radioService: RadioService,
|
||||||
|
) {
|
||||||
|
get("/moods") {
|
||||||
|
val user = call.requireApiUser(users)
|
||||||
|
call.respond(MoodsResponse(MoodRepository.list(user.name).map { it.toDto() }))
|
||||||
|
}
|
||||||
|
|
||||||
|
post("/moods") {
|
||||||
|
val user = call.requireApiUser(users)
|
||||||
|
val request = call.receiveJson<CreateMoodRequest>()
|
||||||
|
val name = request.name.trim()
|
||||||
|
if (name.isEmpty()) badRequest("Mood name is required")
|
||||||
|
|
||||||
|
val folders = user.musicFolderIds(library)
|
||||||
|
val seedIds = request.seedSongIds
|
||||||
|
.distinct()
|
||||||
|
.filter { LibraryRepository.song(it, folders, user.name) != null }
|
||||||
|
|
||||||
|
val mood = MoodRepository.create(
|
||||||
|
owner = user.name,
|
||||||
|
name = name,
|
||||||
|
description = request.description?.trim()?.takeIf { it.isNotEmpty() },
|
||||||
|
query = request.query?.trim()?.takeIf { it.isNotEmpty() },
|
||||||
|
genres = request.genres,
|
||||||
|
targetSize = request.targetSize,
|
||||||
|
refreshHours = request.refreshHours,
|
||||||
|
ytEnabled = request.ytEnabled,
|
||||||
|
seedSongIds = seedIds,
|
||||||
|
)
|
||||||
|
call.respond(HttpStatusCode.Created, detail(mood, user, library))
|
||||||
|
}
|
||||||
|
|
||||||
|
get("/moods/{id}") {
|
||||||
|
val user = call.requireApiUser(users)
|
||||||
|
val mood = ownedMood(call.parameters["id"], user)
|
||||||
|
call.respond(detail(mood, user, library))
|
||||||
|
}
|
||||||
|
|
||||||
|
patch("/moods/{id}") {
|
||||||
|
val user = call.requireApiUser(users)
|
||||||
|
val mood = ownedMood(call.parameters["id"], user)
|
||||||
|
val request = call.receiveJson<UpdateMoodRequest>()
|
||||||
|
|
||||||
|
val description = when {
|
||||||
|
request.clearDescription -> null
|
||||||
|
request.description != null -> request.description.trim().takeIf { it.isNotEmpty() }
|
||||||
|
else -> mood.description
|
||||||
|
}
|
||||||
|
val query = when {
|
||||||
|
request.clearQuery -> null
|
||||||
|
request.query != null -> request.query.trim().takeIf { it.isNotEmpty() }
|
||||||
|
else -> mood.query
|
||||||
|
}
|
||||||
|
|
||||||
|
val updated = MoodRepository.update(
|
||||||
|
id = mood.id,
|
||||||
|
owner = user.name,
|
||||||
|
name = request.name?.trim()?.takeIf { it.isNotEmpty() } ?: mood.name,
|
||||||
|
description = description,
|
||||||
|
query = query,
|
||||||
|
genres = request.genres ?: mood.genres,
|
||||||
|
targetSize = request.targetSize ?: mood.targetSize,
|
||||||
|
refreshHours = request.refreshHours ?: mood.refreshHours,
|
||||||
|
ytEnabled = request.ytEnabled ?: mood.ytEnabled,
|
||||||
|
) ?: notFound("Mood")
|
||||||
|
|
||||||
|
call.respond(detail(updated, user, library))
|
||||||
|
}
|
||||||
|
|
||||||
|
delete("/moods/{id}") {
|
||||||
|
val user = call.requireApiUser(users)
|
||||||
|
val mood = ownedMood(call.parameters["id"], user)
|
||||||
|
MoodRepository.delete(mood.id, user.name)
|
||||||
|
call.respond(HttpStatusCode.NoContent)
|
||||||
|
}
|
||||||
|
|
||||||
|
post("/moods/{id}/seeds") {
|
||||||
|
val user = call.requireApiUser(users)
|
||||||
|
val mood = ownedMood(call.parameters["id"], user)
|
||||||
|
val request = call.receiveJson<AddSeedRequest>()
|
||||||
|
val song = requireMusicSong(request.songId, user, library)
|
||||||
|
val added = MoodRepository.addSeed(
|
||||||
|
id = mood.id,
|
||||||
|
owner = user.name,
|
||||||
|
songId = song.id,
|
||||||
|
origin = request.origin,
|
||||||
|
)
|
||||||
|
val refreshed = MoodRepository.get(mood.id, user.name) ?: mood
|
||||||
|
call.respond(
|
||||||
|
HttpStatusCode.OK,
|
||||||
|
AddToMoodResponse(mood = refreshed.toDto(), added = added),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
delete("/moods/{id}/seeds/{songId}") {
|
||||||
|
val user = call.requireApiUser(users)
|
||||||
|
val mood = ownedMood(call.parameters["id"], user)
|
||||||
|
val songId = call.parameters["songId"] ?: badRequest("Song id is required")
|
||||||
|
MoodRepository.removeSeed(mood.id, user.name, songId)
|
||||||
|
call.respond(HttpStatusCode.NoContent)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A short, unpersisted radio preview for the mood detail screen. */
|
||||||
|
get("/moods/{id}/preview") {
|
||||||
|
val user = call.requireApiUser(users)
|
||||||
|
val mood = ownedMood(call.parameters["id"], user)
|
||||||
|
val limit = (call.request.queryParameters["limit"]?.toIntOrNull() ?: 20).coerceIn(1, 50)
|
||||||
|
call.respond(SearchResponse(radioService.preview(mood, user, library, limit).map { it.toDto() }))
|
||||||
|
}
|
||||||
|
|
||||||
|
get("/moods/{id}/recommendations") {
|
||||||
|
val user = call.requireApiUser(users)
|
||||||
|
val mood = ownedMood(call.parameters["id"], user)
|
||||||
|
call.respond(recommendations(mood, user, library))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ownedMood(id: String?, user: UserAccount): MoodRecord {
|
||||||
|
if (id.isNullOrBlank()) badRequest("Mood id is required")
|
||||||
|
return MoodRepository.get(id, user.name) ?: notFound("Mood")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun requireMusicSong(songId: String, user: UserAccount, library: LibraryConfig) =
|
||||||
|
LibraryRepository.song(songId, user.musicFolderIds(library), user.name)
|
||||||
|
?: notFound("Song")
|
||||||
|
|
||||||
|
private fun detail(mood: MoodRecord, user: UserAccount, library: LibraryConfig): MoodDetailDto {
|
||||||
|
val folders = user.musicFolderIds(library)
|
||||||
|
val seedRecords = MoodRepository.seeds(mood.id)
|
||||||
|
val seedSongs = LibraryRepository
|
||||||
|
.songsByIds(seedRecords.map { it.songId }, folders, user.name)
|
||||||
|
.associateBy { it.id }
|
||||||
|
val seeds = seedRecords.mapNotNull { seed ->
|
||||||
|
seedSongs[seed.songId]?.let { seedDto(seed, it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
return MoodDetailDto(
|
||||||
|
mood = mood.toDto(),
|
||||||
|
seeds = seeds,
|
||||||
|
recommendations = recommendations(mood, user, library).recommendations,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun recommendations(
|
||||||
|
mood: MoodRecord,
|
||||||
|
user: UserAccount,
|
||||||
|
library: LibraryConfig,
|
||||||
|
): RecommendationsResponse {
|
||||||
|
val records = MoodRepository.recommendations(mood.id)
|
||||||
|
val matchedIds = records.mapNotNull { it.matchedSongId }
|
||||||
|
val matchedSongs = LibraryRepository
|
||||||
|
.songsByIds(matchedIds, user.visibleFolderIds(library), user.name)
|
||||||
|
.associateBy { it.id }
|
||||||
|
|
||||||
|
return RecommendationsResponse(
|
||||||
|
recommendations = records.map { record ->
|
||||||
|
RecommendationDto(
|
||||||
|
videoId = record.videoId,
|
||||||
|
title = record.title,
|
||||||
|
artist = record.artist,
|
||||||
|
album = record.album,
|
||||||
|
duration = record.duration,
|
||||||
|
thumbnail = record.thumbnail,
|
||||||
|
state = record.state,
|
||||||
|
matchedSong = record.matchedSongId?.let { matchedSongs[it] }?.toDto(),
|
||||||
|
timesAdded = record.timesAdded,
|
||||||
|
firstSeen = record.firstSeen,
|
||||||
|
lastSeen = record.lastSeen,
|
||||||
|
)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class RecommendationsResponse(val recommendations: List<RecommendationDto>)
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
package win.taptap.musicmanager.api
|
||||||
|
|
||||||
|
import io.ktor.http.HttpStatusCode
|
||||||
|
import io.ktor.server.response.respond
|
||||||
|
import io.ktor.server.routing.Route
|
||||||
|
import io.ktor.server.routing.delete
|
||||||
|
import io.ktor.server.routing.get
|
||||||
|
import io.ktor.server.routing.post
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
import win.taptap.musicmanager.api.AddToMoodRequest
|
||||||
|
import win.taptap.musicmanager.api.AddToMoodResponse
|
||||||
|
import win.taptap.musicmanager.api.NextTracksRequest
|
||||||
|
import win.taptap.musicmanager.api.PlaybackEventsRequest
|
||||||
|
import win.taptap.musicmanager.api.PlaybackEventsResponse
|
||||||
|
import win.taptap.musicmanager.api.SessionDto
|
||||||
|
import win.taptap.musicmanager.api.SongDto
|
||||||
|
import win.taptap.musicmanager.api.StartSessionRequest
|
||||||
|
import win.taptap.musicmanager.api.toDto
|
||||||
|
import win.taptap.musicmanager.config.LibraryConfig
|
||||||
|
import win.taptap.musicmanager.config.UserAccount
|
||||||
|
import win.taptap.musicmanager.config.UsersConfig
|
||||||
|
import win.taptap.musicmanager.db.LibraryRepository
|
||||||
|
import win.taptap.musicmanager.db.MoodRecord
|
||||||
|
import win.taptap.musicmanager.db.MoodRepository
|
||||||
|
import win.taptap.musicmanager.db.PlaybackSessionRecord
|
||||||
|
import win.taptap.musicmanager.db.RadioRepository
|
||||||
|
import win.taptap.musicmanager.radio.RadioService
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class TracksResponse(val songs: List<SongDto>)
|
||||||
|
|
||||||
|
fun Route.sessionRoutes(
|
||||||
|
users: UsersConfig,
|
||||||
|
library: LibraryConfig,
|
||||||
|
radioService: RadioService,
|
||||||
|
) {
|
||||||
|
post("/moods/{id}/sessions") {
|
||||||
|
val user = call.requireApiUser(users)
|
||||||
|
val mood = ownedMoodFor(call.parameters["id"], user)
|
||||||
|
val request = runCatching { call.receiveJson<StartSessionRequest>() }
|
||||||
|
.getOrDefault(StartSessionRequest())
|
||||||
|
val limit = request.limit ?: DEFAULT_BATCH
|
||||||
|
|
||||||
|
val started = radioService.start(mood, user, library, limit)
|
||||||
|
call.respond(
|
||||||
|
HttpStatusCode.Created,
|
||||||
|
SessionDto(
|
||||||
|
id = started.session.id,
|
||||||
|
moodId = mood.id,
|
||||||
|
moodName = mood.name,
|
||||||
|
startedAt = started.session.createdAt,
|
||||||
|
queue = started.songs.map { it.toDto() },
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
get("/sessions/{id}") {
|
||||||
|
val user = call.requireApiUser(users)
|
||||||
|
val session = ownedSession(call.parameters["id"], user)
|
||||||
|
val mood = ownedMoodFor(session.moodId, user)
|
||||||
|
val folders = user.musicFolderIds(library)
|
||||||
|
val items = RadioRepository.items(session.id)
|
||||||
|
val songs = LibraryRepository
|
||||||
|
.songsByIds(items.map { it.songId }, folders, user.name)
|
||||||
|
.associateBy { it.id }
|
||||||
|
|
||||||
|
call.respond(
|
||||||
|
SessionDto(
|
||||||
|
id = session.id,
|
||||||
|
moodId = session.moodId,
|
||||||
|
moodName = mood.name,
|
||||||
|
startedAt = session.createdAt,
|
||||||
|
closedAt = session.closedAt,
|
||||||
|
queue = items.mapNotNull { songs[it.songId]?.toDto() },
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
post("/sessions/{id}/next") {
|
||||||
|
val user = call.requireApiUser(users)
|
||||||
|
val session = ownedSession(call.parameters["id"], user)
|
||||||
|
if (session.closedAt != null) conflict("Session is closed")
|
||||||
|
val mood = ownedMoodFor(session.moodId, user)
|
||||||
|
val request = runCatching { call.receiveJson<NextTracksRequest>() }
|
||||||
|
.getOrDefault(NextTracksRequest())
|
||||||
|
|
||||||
|
val songs = radioService.next(
|
||||||
|
mood = mood,
|
||||||
|
user = user,
|
||||||
|
library = library,
|
||||||
|
sessionId = session.id,
|
||||||
|
excluded = request.excludeSongIds.toSet(),
|
||||||
|
limit = request.limit ?: DEFAULT_BATCH,
|
||||||
|
)
|
||||||
|
call.respond(TracksResponse(songs.map { it.toDto() }))
|
||||||
|
}
|
||||||
|
|
||||||
|
post("/sessions/{id}/events") {
|
||||||
|
val user = call.requireApiUser(users)
|
||||||
|
val session = ownedSession(call.parameters["id"], user)
|
||||||
|
val request = call.receiveJson<PlaybackEventsRequest>()
|
||||||
|
val accepted = request.events.count { event ->
|
||||||
|
event.type in EVENT_TYPES &&
|
||||||
|
event.songId.isNotBlank() &&
|
||||||
|
RadioRepository.recordEvent(session.id, user.name, event.songId, event.type)
|
||||||
|
}
|
||||||
|
call.respond(PlaybackEventsResponse(accepted))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Explicitly adds the playing track to the session mood or another chosen mood. */
|
||||||
|
post("/sessions/{id}/add-to-mood") {
|
||||||
|
val user = call.requireApiUser(users)
|
||||||
|
val session = ownedSession(call.parameters["id"], user)
|
||||||
|
val request = call.receiveJson<AddToMoodRequest>()
|
||||||
|
val folders = user.musicFolderIds(library)
|
||||||
|
val song = LibraryRepository.song(request.songId, folders, user.name)
|
||||||
|
?: notFound("Song")
|
||||||
|
|
||||||
|
val target = if (request.moodId.isNullOrBlank()) {
|
||||||
|
ownedMoodFor(session.moodId, user)
|
||||||
|
} else {
|
||||||
|
ownedMoodFor(request.moodId, user)
|
||||||
|
}
|
||||||
|
|
||||||
|
val added = MoodRepository.addSeed(target.id, user.name, song.id, "manual")
|
||||||
|
val refreshed = MoodRepository.get(target.id, user.name) ?: target
|
||||||
|
call.respond(
|
||||||
|
AddToMoodResponse(
|
||||||
|
mood = refreshed.toDto(),
|
||||||
|
added = added,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
delete("/sessions/{id}") {
|
||||||
|
val user = call.requireApiUser(users)
|
||||||
|
val session = ownedSession(call.parameters["id"], user)
|
||||||
|
RadioRepository.close(session.id, user.name)
|
||||||
|
call.respond(HttpStatusCode.NoContent)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ownedMoodFor(id: String?, user: UserAccount): MoodRecord {
|
||||||
|
if (id.isNullOrBlank()) badRequest("Mood id is required")
|
||||||
|
return MoodRepository.get(id, user.name) ?: notFound("Mood")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ownedSession(id: String?, user: UserAccount): PlaybackSessionRecord {
|
||||||
|
if (id.isNullOrBlank()) badRequest("Session id is required")
|
||||||
|
return RadioRepository.get(id, user.name) ?: notFound("Session")
|
||||||
|
}
|
||||||
|
|
||||||
|
private const val DEFAULT_BATCH = 15
|
||||||
|
private val EVENT_TYPES = setOf("started", "completed", "skipped")
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
package win.taptap.musicmanager.db
|
||||||
|
|
||||||
|
import java.security.MessageDigest
|
||||||
|
import java.security.SecureRandom
|
||||||
|
import java.time.Duration
|
||||||
|
import java.time.Instant
|
||||||
|
import java.util.Base64
|
||||||
|
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
|
||||||
|
import org.jetbrains.exposed.sql.SqlExpressionBuilder.greater
|
||||||
|
import org.jetbrains.exposed.sql.SqlExpressionBuilder.neq
|
||||||
|
import org.jetbrains.exposed.sql.and
|
||||||
|
import org.jetbrains.exposed.sql.deleteWhere
|
||||||
|
import org.jetbrains.exposed.sql.insert
|
||||||
|
import org.jetbrains.exposed.sql.selectAll
|
||||||
|
import org.jetbrains.exposed.sql.transactions.transaction
|
||||||
|
import org.jetbrains.exposed.sql.update
|
||||||
|
|
||||||
|
data class IssuedToken(val raw: String, val record: ApiTokenRecord)
|
||||||
|
|
||||||
|
data class ApiTokenRecord(
|
||||||
|
val id: String,
|
||||||
|
val userName: String,
|
||||||
|
val deviceName: String,
|
||||||
|
val platform: String,
|
||||||
|
val createdAt: String,
|
||||||
|
val lastUsedAt: String,
|
||||||
|
val expiresAt: String,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Device sessions for the native API. Raw tokens never touch the database: only
|
||||||
|
* their SHA-256 hash is stored, so a database leak cannot be replayed.
|
||||||
|
*/
|
||||||
|
object ApiTokenRepository {
|
||||||
|
|
||||||
|
private val random = SecureRandom()
|
||||||
|
private const val TOKEN_BYTES = 32
|
||||||
|
private val TOUCH_INTERVAL: Duration = Duration.ofMinutes(1)
|
||||||
|
|
||||||
|
fun create(
|
||||||
|
userName: String,
|
||||||
|
deviceName: String,
|
||||||
|
platform: String,
|
||||||
|
ttl: Duration = Duration.ofDays(180),
|
||||||
|
): IssuedToken {
|
||||||
|
val raw = randomToken()
|
||||||
|
val now = Instant.now()
|
||||||
|
val record = ApiTokenRecord(
|
||||||
|
id = "tk-" + hash("$userName|$raw").take(24),
|
||||||
|
userName = userName,
|
||||||
|
deviceName = deviceName.take(120),
|
||||||
|
platform = platform.take(32),
|
||||||
|
createdAt = now.toString(),
|
||||||
|
lastUsedAt = now.toString(),
|
||||||
|
expiresAt = now.plus(ttl).toString(),
|
||||||
|
)
|
||||||
|
|
||||||
|
transaction {
|
||||||
|
ApiTokensTable.insert {
|
||||||
|
it[id] = record.id
|
||||||
|
it[this.userName] = record.userName
|
||||||
|
it[tokenHash] = hash(raw)
|
||||||
|
it[this.deviceName] = record.deviceName
|
||||||
|
it[this.platform] = record.platform
|
||||||
|
it[createdAt] = record.createdAt
|
||||||
|
it[lastUsedAt] = record.lastUsedAt
|
||||||
|
it[expiresAt] = record.expiresAt
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return IssuedToken(raw, record)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Validates a raw token and refreshes `last_used_at` at most once a minute. */
|
||||||
|
fun resolve(raw: String): ApiTokenRecord? = transaction {
|
||||||
|
val hashed = hash(raw)
|
||||||
|
val row = ApiTokensTable.selectAll()
|
||||||
|
.where { ApiTokensTable.tokenHash eq hashed }
|
||||||
|
.singleOrNull() ?: return@transaction null
|
||||||
|
|
||||||
|
val expiresAt = row[ApiTokensTable.expiresAt]
|
||||||
|
if (Instant.parse(expiresAt).isBefore(Instant.now())) {
|
||||||
|
ApiTokensTable.deleteWhere { ApiTokensTable.id eq row[ApiTokensTable.id] }
|
||||||
|
return@transaction null
|
||||||
|
}
|
||||||
|
|
||||||
|
val lastUsed = Instant.parse(row[ApiTokensTable.lastUsedAt])
|
||||||
|
val now = Instant.now()
|
||||||
|
if (lastUsed.plus(TOUCH_INTERVAL).isBefore(now)) {
|
||||||
|
ApiTokensTable.update({ ApiTokensTable.id eq row[ApiTokensTable.id] }) {
|
||||||
|
it[lastUsedAt] = now.toString()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ApiTokenRecord(
|
||||||
|
id = row[ApiTokensTable.id],
|
||||||
|
userName = row[ApiTokensTable.userName],
|
||||||
|
deviceName = row[ApiTokensTable.deviceName],
|
||||||
|
platform = row[ApiTokensTable.platform],
|
||||||
|
createdAt = row[ApiTokensTable.createdAt],
|
||||||
|
lastUsedAt = now.toString(),
|
||||||
|
expiresAt = expiresAt,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun list(userName: String): List<ApiTokenRecord> = transaction {
|
||||||
|
ApiTokensTable.selectAll()
|
||||||
|
.where { (ApiTokensTable.userName eq userName) and (ApiTokensTable.expiresAt greater Instant.now().toString()) }
|
||||||
|
.orderBy(ApiTokensTable.lastUsedAt to org.jetbrains.exposed.sql.SortOrder.DESC)
|
||||||
|
.map {
|
||||||
|
ApiTokenRecord(
|
||||||
|
id = it[ApiTokensTable.id],
|
||||||
|
userName = it[ApiTokensTable.userName],
|
||||||
|
deviceName = it[ApiTokensTable.deviceName],
|
||||||
|
platform = it[ApiTokensTable.platform],
|
||||||
|
createdAt = it[ApiTokensTable.createdAt],
|
||||||
|
lastUsedAt = it[ApiTokensTable.lastUsedAt],
|
||||||
|
expiresAt = it[ApiTokensTable.expiresAt],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun revoke(id: String, userName: String): Boolean = transaction {
|
||||||
|
ApiTokensTable.deleteWhere {
|
||||||
|
(ApiTokensTable.id eq id) and (ApiTokensTable.userName eq userName)
|
||||||
|
} > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
fun revokeRaw(raw: String): Boolean = transaction {
|
||||||
|
ApiTokensTable.deleteWhere { ApiTokensTable.tokenHash eq hash(raw) } > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
fun revokeAll(userName: String, exceptId: String? = null): Int = transaction {
|
||||||
|
if (exceptId == null) {
|
||||||
|
ApiTokensTable.deleteWhere { ApiTokensTable.userName eq userName }
|
||||||
|
} else {
|
||||||
|
ApiTokensTable.deleteWhere {
|
||||||
|
(ApiTokensTable.userName eq userName) and (ApiTokensTable.id neq exceptId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun hash(value: String): String =
|
||||||
|
MessageDigest.getInstance("SHA-256")
|
||||||
|
.digest(value.toByteArray(Charsets.UTF_8))
|
||||||
|
.joinToString("") { "%02x".format(it) }
|
||||||
|
|
||||||
|
private fun randomToken(): String {
|
||||||
|
val bytes = ByteArray(TOKEN_BYTES)
|
||||||
|
random.nextBytes(bytes)
|
||||||
|
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,7 +13,7 @@ import win.taptap.musicmanager.config.UsersConfig
|
|||||||
* Reconciles the config/Vault-managed identity tables with SQLite.
|
* Reconciles the config/Vault-managed identity tables with SQLite.
|
||||||
*
|
*
|
||||||
* Removing a folder cascades to its songs; removing a user cascades to that
|
* Removing a folder cascades to its songs; removing a user cascades to that
|
||||||
* user's stars, ratings, play counts, bookmarks and playlists.
|
* user's play history and mood ownership.
|
||||||
*/
|
*/
|
||||||
object ConfigRepository {
|
object ConfigRepository {
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import java.nio.file.Files
|
|||||||
import java.nio.file.Path
|
import java.nio.file.Path
|
||||||
import org.jetbrains.exposed.sql.JoinType
|
import org.jetbrains.exposed.sql.JoinType
|
||||||
import org.jetbrains.exposed.sql.Op
|
import org.jetbrains.exposed.sql.Op
|
||||||
|
import org.jetbrains.exposed.sql.SqlExpressionBuilder.greater
|
||||||
import org.jetbrains.exposed.sql.ResultRow
|
import org.jetbrains.exposed.sql.ResultRow
|
||||||
import org.jetbrains.exposed.sql.SortOrder
|
import org.jetbrains.exposed.sql.SortOrder
|
||||||
import org.jetbrains.exposed.sql.Transaction
|
import org.jetbrains.exposed.sql.Transaction
|
||||||
@@ -81,6 +82,7 @@ data class SongRecord(
|
|||||||
val folderId: Int,
|
val folderId: Int,
|
||||||
val relativePath: String,
|
val relativePath: String,
|
||||||
val created: String,
|
val created: String,
|
||||||
|
val updatedAt: String,
|
||||||
val starredAt: String?,
|
val starredAt: String?,
|
||||||
val rating: Int?,
|
val rating: Int?,
|
||||||
val playCount: Int,
|
val playCount: Int,
|
||||||
@@ -91,6 +93,8 @@ data class SongRecord(
|
|||||||
|
|
||||||
data class ResolvedSong(val song: SongRecord, val file: Path)
|
data class ResolvedSong(val song: SongRecord, val file: Path)
|
||||||
|
|
||||||
|
data class TombstoneRecord(val entityId: String, val deletedAt: String)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Read-side queries for browsing and media. Every method takes the set of folder
|
* Read-side queries for browsing and media. Every method takes the set of folder
|
||||||
* IDs visible to the requesting user; an album or artist without a visible song
|
* IDs visible to the requesting user; an album or artist without a visible song
|
||||||
@@ -241,6 +245,67 @@ object LibraryRepository {
|
|||||||
ids.mapNotNull { albumRecord(it, folderIds, userName) }
|
ids.mapNotNull { albumRecord(it, folderIds, userName) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Stable page of the library snapshot, ordered by song ID. */
|
||||||
|
fun syncSongs(
|
||||||
|
folderIds: Set<Int>,
|
||||||
|
afterId: String,
|
||||||
|
limit: Int,
|
||||||
|
userName: String,
|
||||||
|
): List<SongRecord> = read {
|
||||||
|
if (folderIds.isEmpty()) return@read emptyList()
|
||||||
|
|
||||||
|
val rows = SongsTable.selectAll()
|
||||||
|
.where {
|
||||||
|
(SongsTable.folderId inList folderIds) and
|
||||||
|
(SongsTable.id greater afterId)
|
||||||
|
}
|
||||||
|
.orderBy(SongsTable.id to SortOrder.ASC)
|
||||||
|
.limit(limit)
|
||||||
|
.toList()
|
||||||
|
|
||||||
|
enrichSongs(rows, userName)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Songs whose metadata changed after the client's last revision. */
|
||||||
|
fun changedSongs(
|
||||||
|
since: String,
|
||||||
|
folderIds: Set<Int>,
|
||||||
|
limit: Int,
|
||||||
|
userName: String,
|
||||||
|
): List<SongRecord> = read {
|
||||||
|
if (folderIds.isEmpty()) return@read emptyList()
|
||||||
|
|
||||||
|
val rows = SongsTable.selectAll()
|
||||||
|
.where {
|
||||||
|
(SongsTable.folderId inList folderIds) and
|
||||||
|
(SongsTable.updatedAt greater since)
|
||||||
|
}
|
||||||
|
.orderBy(
|
||||||
|
SongsTable.updatedAt to SortOrder.ASC,
|
||||||
|
SongsTable.id to SortOrder.ASC,
|
||||||
|
)
|
||||||
|
.limit(limit)
|
||||||
|
.toList()
|
||||||
|
|
||||||
|
enrichSongs(rows, userName)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun tombstones(since: String, limit: Int): List<TombstoneRecord> = read {
|
||||||
|
LibraryTombstonesTable.selectAll()
|
||||||
|
.where {
|
||||||
|
(LibraryTombstonesTable.entity eq "song") and
|
||||||
|
(LibraryTombstonesTable.deletedAt greater since)
|
||||||
|
}
|
||||||
|
.orderBy(LibraryTombstonesTable.deletedAt to SortOrder.ASC)
|
||||||
|
.limit(limit)
|
||||||
|
.map {
|
||||||
|
TombstoneRecord(
|
||||||
|
entityId = it[LibraryTombstonesTable.entityId],
|
||||||
|
deletedAt = it[LibraryTombstonesTable.deletedAt],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fun allSongs(limit: Int, offset: Int, folderIds: Set<Int>, userName: String): List<SongRecord> = read {
|
fun allSongs(limit: Int, offset: Int, folderIds: Set<Int>, userName: String): List<SongRecord> = read {
|
||||||
if (folderIds.isEmpty()) return@read emptyList()
|
if (folderIds.isEmpty()) return@read emptyList()
|
||||||
|
|
||||||
@@ -748,6 +813,7 @@ object LibraryRepository {
|
|||||||
folderId = row[SongsTable.folderId],
|
folderId = row[SongsTable.folderId],
|
||||||
relativePath = row[SongsTable.relativePath],
|
relativePath = row[SongsTable.relativePath],
|
||||||
created = row[SongsTable.createdAt],
|
created = row[SongsTable.createdAt],
|
||||||
|
updatedAt = row[SongsTable.updatedAt].ifBlank { row[SongsTable.createdAt] },
|
||||||
starredAt = state?.starredAt,
|
starredAt = state?.starredAt,
|
||||||
rating = state?.rating,
|
rating = state?.rating,
|
||||||
playCount = state?.playCount ?: 0,
|
playCount = state?.playCount ?: 0,
|
||||||
|
|||||||
@@ -110,6 +110,7 @@ object MediaRepository {
|
|||||||
it[relativePath] = track.relativePath
|
it[relativePath] = track.relativePath
|
||||||
it[fileMtime] = track.fileMtime
|
it[fileMtime] = track.fileMtime
|
||||||
it[searchText] = track.searchText
|
it[searchText] = track.searchText
|
||||||
|
it[updatedAt] = now
|
||||||
it[lyrics] = track.lyrics
|
it[lyrics] = track.lyrics
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -132,6 +133,7 @@ object MediaRepository {
|
|||||||
it[fileMtime] = track.fileMtime
|
it[fileMtime] = track.fileMtime
|
||||||
it[createdAt] = now
|
it[createdAt] = now
|
||||||
it[searchText] = track.searchText
|
it[searchText] = track.searchText
|
||||||
|
it[updatedAt] = now
|
||||||
it[lyrics] = track.lyrics
|
it[lyrics] = track.lyrics
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -169,7 +171,13 @@ object MediaRepository {
|
|||||||
.map { it[SongsTable.id] }
|
.map { it[SongsTable.id] }
|
||||||
.filterNot { it in seenSongIds }
|
.filterNot { it in seenSongIds }
|
||||||
|
|
||||||
|
val now = Instant.now().toString()
|
||||||
obsolete.forEach { songId ->
|
obsolete.forEach { songId ->
|
||||||
|
LibraryTombstonesTable.insertIgnore {
|
||||||
|
it[entity] = "song"
|
||||||
|
it[entityId] = songId
|
||||||
|
it[deletedAt] = now
|
||||||
|
}
|
||||||
SongsTable.deleteWhere { it.run { SongsTable.id eq songId } }
|
SongsTable.deleteWhere { it.run { SongsTable.id eq songId } }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,37 +4,34 @@ import java.time.Instant
|
|||||||
import kotlinx.serialization.builtins.ListSerializer
|
import kotlinx.serialization.builtins.ListSerializer
|
||||||
import kotlinx.serialization.builtins.serializer
|
import kotlinx.serialization.builtins.serializer
|
||||||
import kotlinx.serialization.json.Json
|
import kotlinx.serialization.json.Json
|
||||||
import org.jetbrains.exposed.sql.JoinType
|
|
||||||
import org.jetbrains.exposed.sql.Op
|
|
||||||
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
|
|
||||||
import org.jetbrains.exposed.sql.ResultRow
|
import org.jetbrains.exposed.sql.ResultRow
|
||||||
import org.jetbrains.exposed.sql.SortOrder
|
import org.jetbrains.exposed.sql.SortOrder
|
||||||
|
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
|
||||||
import org.jetbrains.exposed.sql.and
|
import org.jetbrains.exposed.sql.and
|
||||||
import org.jetbrains.exposed.sql.deleteWhere
|
import org.jetbrains.exposed.sql.deleteWhere
|
||||||
import org.jetbrains.exposed.sql.insert
|
import org.jetbrains.exposed.sql.insert
|
||||||
|
import org.jetbrains.exposed.sql.insertIgnore
|
||||||
import org.jetbrains.exposed.sql.selectAll
|
import org.jetbrains.exposed.sql.selectAll
|
||||||
import org.jetbrains.exposed.sql.transactions.transaction
|
import org.jetbrains.exposed.sql.transactions.transaction
|
||||||
import org.jetbrains.exposed.sql.update
|
import org.jetbrains.exposed.sql.update
|
||||||
|
import win.taptap.musicmanager.util.IdGenerator
|
||||||
|
|
||||||
data class MoodRecord(
|
data class MoodRecord(
|
||||||
val playlistId: String,
|
val id: String,
|
||||||
val owner: String,
|
val owner: String,
|
||||||
val name: String,
|
val name: String,
|
||||||
val comment: String?,
|
val description: String?,
|
||||||
val query: String?,
|
val query: String?,
|
||||||
val genres: List<String>,
|
val genres: List<String>,
|
||||||
val targetSize: Int,
|
val targetSize: Int,
|
||||||
val ytSlots: Int,
|
|
||||||
val expandRelated: Boolean,
|
|
||||||
val refreshHours: Int,
|
val refreshHours: Int,
|
||||||
val generatedAt: String?,
|
val ytEnabled: Boolean,
|
||||||
val generation: Int,
|
val lastDiscoveryAt: String?,
|
||||||
|
val createdAt: String,
|
||||||
|
val changedAt: String,
|
||||||
val lastError: String?,
|
val lastError: String?,
|
||||||
val created: String,
|
|
||||||
val changed: String,
|
|
||||||
val songCount: Int,
|
|
||||||
val duration: Int,
|
|
||||||
val seedCount: Int,
|
val seedCount: Int,
|
||||||
|
val newRecommendations: Int,
|
||||||
)
|
)
|
||||||
|
|
||||||
data class MoodSeedRecord(
|
data class MoodSeedRecord(
|
||||||
@@ -43,190 +40,117 @@ data class MoodSeedRecord(
|
|||||||
val addedAt: String,
|
val addedAt: String,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
data class RecommendationRecord(
|
||||||
|
val videoId: String,
|
||||||
|
val title: String,
|
||||||
|
val artist: String,
|
||||||
|
val album: String?,
|
||||||
|
val duration: Int?,
|
||||||
|
val thumbnail: String?,
|
||||||
|
val state: String,
|
||||||
|
val matchedSongId: String?,
|
||||||
|
val timesAdded: Int,
|
||||||
|
val firstSeen: String,
|
||||||
|
val lastSeen: String,
|
||||||
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Moods are private playlists with generation settings. The playlist row remains
|
* Moods are the product's only collection. Seeds are permanent anchors; the
|
||||||
* the client-visible object; this repository owns the settings, seeds and the
|
* play queue is generated by [win.taptap.musicmanager.radio.RadioService] for
|
||||||
* materialized mix in `playlist_songs`.
|
* every playback session instead of being stored as a playlist.
|
||||||
*/
|
*/
|
||||||
object MoodRepository {
|
object MoodRepository {
|
||||||
|
|
||||||
private val genreSerializer = ListSerializer(String.serializer())
|
private val genreSerializer = ListSerializer(String.serializer())
|
||||||
|
|
||||||
fun list(userName: String): List<MoodRecord> = transaction {
|
fun list(owner: String): List<MoodRecord> = transaction {
|
||||||
PlaylistsTable
|
MoodsTable.selectAll()
|
||||||
.join(MoodsTable, JoinType.INNER, PlaylistsTable.id, MoodsTable.playlistId)
|
.where { MoodsTable.owner eq owner }
|
||||||
.selectAll()
|
.orderBy(MoodsTable.changedAt to SortOrder.DESC)
|
||||||
.where {
|
|
||||||
(PlaylistsTable.owner eq userName) and
|
|
||||||
(PlaylistsTable.kind eq "mood")
|
|
||||||
}
|
|
||||||
.orderBy(PlaylistsTable.changedAt to SortOrder.DESC)
|
|
||||||
.map { moodRecord(it) }
|
.map { moodRecord(it) }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun get(playlistId: String, userName: String): MoodRecord? = transaction {
|
fun get(id: String, owner: String): MoodRecord? = transaction {
|
||||||
val row = PlaylistsTable
|
MoodsTable.selectAll()
|
||||||
.join(MoodsTable, JoinType.INNER, PlaylistsTable.id, MoodsTable.playlistId)
|
.where { (MoodsTable.id eq id) and (MoodsTable.owner eq owner) }
|
||||||
.selectAll()
|
|
||||||
.where {
|
|
||||||
(PlaylistsTable.id eq playlistId) and
|
|
||||||
(PlaylistsTable.owner eq userName) and
|
|
||||||
(PlaylistsTable.kind eq "mood")
|
|
||||||
}
|
|
||||||
.singleOrNull()
|
.singleOrNull()
|
||||||
|
?.let { moodRecord(it) }
|
||||||
row?.let { moodRecord(it) }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun create(
|
fun create(
|
||||||
userName: String,
|
owner: String,
|
||||||
name: String,
|
name: String,
|
||||||
comment: String?,
|
description: String?,
|
||||||
query: String?,
|
query: String?,
|
||||||
genres: List<String>,
|
genres: List<String>,
|
||||||
targetSize: Int,
|
targetSize: Int,
|
||||||
ytSlots: Int,
|
|
||||||
expandRelated: Boolean,
|
|
||||||
refreshHours: Int,
|
refreshHours: Int,
|
||||||
|
ytEnabled: Boolean,
|
||||||
seedSongIds: List<String>,
|
seedSongIds: List<String>,
|
||||||
): MoodRecord {
|
): MoodRecord = transaction {
|
||||||
val playlist = PlaylistRepository.create(
|
val now = Instant.now().toString()
|
||||||
userName = userName,
|
val id = IdGenerator.moodId(owner, name, now)
|
||||||
name = name,
|
|
||||||
songIds = emptyList(),
|
MoodsTable.insert {
|
||||||
isPublic = false,
|
it[MoodsTable.id] = id
|
||||||
kind = "mood",
|
it[MoodsTable.owner] = owner
|
||||||
|
it[MoodsTable.name] = name.take(200)
|
||||||
|
it[MoodsTable.description] = description?.take(2000)
|
||||||
|
it[MoodsTable.query] = query?.trim()?.takeIf(String::isNotEmpty)
|
||||||
|
it[MoodsTable.genres] = encodeGenres(genres)
|
||||||
|
it[MoodsTable.targetSize] = targetSize.coerceIn(5, 500)
|
||||||
|
it[MoodsTable.refreshHours] = refreshHours.coerceIn(1, 720)
|
||||||
|
it[MoodsTable.ytEnabled] = ytEnabled
|
||||||
|
it[createdAt] = now
|
||||||
|
it[changedAt] = now
|
||||||
|
}
|
||||||
|
|
||||||
|
insertSeeds(id, seedSongIds, "manual")
|
||||||
|
|
||||||
|
moodRecord(
|
||||||
|
MoodsTable.selectAll().where { MoodsTable.id eq id }.single(),
|
||||||
)
|
)
|
||||||
|
|
||||||
try {
|
|
||||||
transaction {
|
|
||||||
insertSettings(
|
|
||||||
playlistId = playlist.id,
|
|
||||||
query = query,
|
|
||||||
genres = genres,
|
|
||||||
targetSize = targetSize,
|
|
||||||
ytSlots = ytSlots,
|
|
||||||
expandRelated = expandRelated,
|
|
||||||
refreshHours = refreshHours,
|
|
||||||
)
|
|
||||||
insertSeeds(playlist.id, seedSongIds, "manual")
|
|
||||||
}
|
|
||||||
} catch (t: Throwable) {
|
|
||||||
PlaylistRepository.delete(playlist.id, userName)
|
|
||||||
throw t
|
|
||||||
}
|
|
||||||
|
|
||||||
return get(playlist.id, userName)
|
|
||||||
?: error("Mood ${playlist.id} was not persisted")
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Converts an existing owned playlist into a mood while keeping its ID. */
|
|
||||||
fun promote(
|
|
||||||
userName: String,
|
|
||||||
playlistId: String,
|
|
||||||
query: String?,
|
|
||||||
genres: List<String>,
|
|
||||||
targetSize: Int,
|
|
||||||
ytSlots: Int,
|
|
||||||
expandRelated: Boolean,
|
|
||||||
refreshHours: Int,
|
|
||||||
musicFolderIds: Set<Int>,
|
|
||||||
): MoodRecord? {
|
|
||||||
val playlist = PlaylistRepository.get(playlistId, userName) ?: return null
|
|
||||||
if (playlist.owner != userName || playlist.kind != "user") return null
|
|
||||||
|
|
||||||
val seedIds = transaction {
|
|
||||||
PlaylistRepository.songIds(playlistId).filter { songId ->
|
|
||||||
SongsTable
|
|
||||||
.select(SongsTable.folderId)
|
|
||||||
.where { SongsTable.id eq songId }
|
|
||||||
.singleOrNull()
|
|
||||||
?.get(SongsTable.folderId) in musicFolderIds
|
|
||||||
}
|
|
||||||
}
|
|
||||||
PlaylistRepository.setKind(playlistId, "mood", false)
|
|
||||||
|
|
||||||
try {
|
|
||||||
transaction {
|
|
||||||
insertSettings(
|
|
||||||
playlistId = playlistId,
|
|
||||||
query = query,
|
|
||||||
genres = genres,
|
|
||||||
targetSize = targetSize,
|
|
||||||
ytSlots = ytSlots,
|
|
||||||
expandRelated = expandRelated,
|
|
||||||
refreshHours = refreshHours,
|
|
||||||
)
|
|
||||||
insertSeeds(playlistId, seedIds, "promoted")
|
|
||||||
}
|
|
||||||
} catch (t: Throwable) {
|
|
||||||
PlaylistRepository.setKind(playlistId, "user", playlist.isPublic)
|
|
||||||
throw t
|
|
||||||
}
|
|
||||||
|
|
||||||
return get(playlistId, userName)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun update(
|
fun update(
|
||||||
playlistId: String,
|
id: String,
|
||||||
userName: String,
|
owner: String,
|
||||||
name: String,
|
name: String,
|
||||||
comment: String?,
|
description: String?,
|
||||||
query: String?,
|
query: String?,
|
||||||
genres: List<String>,
|
genres: List<String>,
|
||||||
targetSize: Int,
|
targetSize: Int,
|
||||||
ytSlots: Int,
|
|
||||||
expandRelated: Boolean,
|
|
||||||
refreshHours: Int,
|
refreshHours: Int,
|
||||||
): Boolean = transaction {
|
ytEnabled: Boolean,
|
||||||
val exists = PlaylistsTable.selectAll()
|
): MoodRecord? = transaction {
|
||||||
.where {
|
val exists = MoodsTable.selectAll()
|
||||||
(PlaylistsTable.id eq playlistId) and
|
.where { (MoodsTable.id eq id) and (MoodsTable.owner eq owner) }
|
||||||
(PlaylistsTable.owner eq userName) and
|
|
||||||
(PlaylistsTable.kind eq "mood")
|
|
||||||
}
|
|
||||||
.any()
|
.any()
|
||||||
if (!exists) return@transaction false
|
if (!exists) return@transaction null
|
||||||
|
|
||||||
PlaylistsTable.update({ PlaylistsTable.id eq playlistId }) {
|
MoodsTable.update({ MoodsTable.id eq id }) {
|
||||||
it[PlaylistsTable.name] = name
|
it[MoodsTable.name] = name.take(200)
|
||||||
it[PlaylistsTable.comment] = comment
|
it[MoodsTable.description] = description?.take(2000)
|
||||||
|
it[MoodsTable.query] = query?.trim()?.takeIf(String::isNotEmpty)
|
||||||
|
it[MoodsTable.genres] = encodeGenres(genres)
|
||||||
|
it[MoodsTable.targetSize] = targetSize.coerceIn(5, 500)
|
||||||
|
it[MoodsTable.refreshHours] = refreshHours.coerceIn(1, 720)
|
||||||
|
it[MoodsTable.ytEnabled] = ytEnabled
|
||||||
it[changedAt] = Instant.now().toString()
|
it[changedAt] = Instant.now().toString()
|
||||||
}
|
}
|
||||||
MoodsTable.update({ MoodsTable.playlistId eq playlistId }) {
|
|
||||||
it[MoodsTable.query] = query
|
moodRecord(MoodsTable.selectAll().where { MoodsTable.id eq id }.single())
|
||||||
it[MoodsTable.genres] = encodeGenres(genres)
|
|
||||||
it[MoodsTable.targetSize] = targetSize.coerceIn(1, 500)
|
|
||||||
it[MoodsTable.ytSlots] = ytSlots.coerceIn(0, 500)
|
|
||||||
it[MoodsTable.expandRelated] = expandRelated
|
|
||||||
it[MoodsTable.refreshHours] = refreshHours.coerceIn(1, 720)
|
|
||||||
it[generatedAt] = null
|
|
||||||
}
|
|
||||||
true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun delete(playlistId: String, userName: String): Boolean =
|
fun delete(id: String, owner: String): Boolean = transaction {
|
||||||
PlaylistRepository.delete(playlistId, userName)
|
MoodsTable.deleteWhere {
|
||||||
|
(MoodsTable.id eq id) and (MoodsTable.owner eq owner)
|
||||||
fun seedSongIds(playlistId: String, origin: String? = null): List<String> = transaction {
|
} > 0
|
||||||
val condition = if (origin == null) {
|
|
||||||
MoodSeedsTable.playlistId eq playlistId
|
|
||||||
} else {
|
|
||||||
(MoodSeedsTable.playlistId eq playlistId) and (MoodSeedsTable.origin eq origin)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun seeds(id: String): List<MoodSeedRecord> = transaction {
|
||||||
MoodSeedsTable.selectAll()
|
MoodSeedsTable.selectAll()
|
||||||
.where(condition)
|
.where { MoodSeedsTable.moodId eq id }
|
||||||
.orderBy(
|
|
||||||
MoodSeedsTable.addedAt to SortOrder.ASC,
|
|
||||||
MoodSeedsTable.songId to SortOrder.ASC,
|
|
||||||
)
|
|
||||||
.map { it[MoodSeedsTable.songId] }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun seeds(playlistId: String): List<MoodSeedRecord> = transaction {
|
|
||||||
MoodSeedsTable.selectAll()
|
|
||||||
.where { MoodSeedsTable.playlistId eq playlistId }
|
|
||||||
.orderBy(
|
.orderBy(
|
||||||
MoodSeedsTable.addedAt to SortOrder.ASC,
|
MoodSeedsTable.addedAt to SortOrder.ASC,
|
||||||
MoodSeedsTable.songId to SortOrder.ASC,
|
MoodSeedsTable.songId to SortOrder.ASC,
|
||||||
@@ -240,165 +164,130 @@ object MoodRepository {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Returns true when the seed was newly inserted. */
|
fun seedSongIds(id: String): List<String> = seeds(id).map { it.songId }
|
||||||
fun addSeed(
|
|
||||||
playlistId: String,
|
/** Returns false when the song is already a seed or the mood is not owned. */
|
||||||
userName: String,
|
fun addSeed(id: String, owner: String, songId: String, origin: String): Boolean = transaction {
|
||||||
songId: String,
|
val owned = MoodsTable.selectAll()
|
||||||
origin: String,
|
.where { (MoodsTable.id eq id) and (MoodsTable.owner eq owner) }
|
||||||
): Boolean = transaction {
|
.any()
|
||||||
if (get(playlistId, userName) == null) return@transaction false
|
if (!owned) return@transaction false
|
||||||
|
|
||||||
val exists = MoodSeedsTable.selectAll()
|
val exists = MoodSeedsTable.selectAll()
|
||||||
.where {
|
.where { (MoodSeedsTable.moodId eq id) and (MoodSeedsTable.songId eq songId) }
|
||||||
(MoodSeedsTable.playlistId eq playlistId) and
|
|
||||||
(MoodSeedsTable.songId eq songId)
|
|
||||||
}
|
|
||||||
.any()
|
.any()
|
||||||
if (exists) return@transaction false
|
if (exists) return@transaction false
|
||||||
|
|
||||||
MoodSeedsTable.insert {
|
val now = Instant.now().toString()
|
||||||
it[MoodSeedsTable.playlistId] = playlistId
|
MoodSeedsTable.insertIgnore {
|
||||||
|
it[MoodSeedsTable.moodId] = id
|
||||||
it[MoodSeedsTable.songId] = songId
|
it[MoodSeedsTable.songId] = songId
|
||||||
it[MoodSeedsTable.origin] = origin
|
it[MoodSeedsTable.origin] = origin.takeIf { value -> value in ORIGINS } ?: "manual"
|
||||||
it[addedAt] = Instant.now().toString()
|
it[addedAt] = now
|
||||||
|
}
|
||||||
|
MoodsTable.update({ MoodsTable.id eq id }) {
|
||||||
|
it[changedAt] = now
|
||||||
}
|
}
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
fun removeSeed(
|
fun removeSeed(id: String, owner: String, songId: String): Boolean = transaction {
|
||||||
playlistId: String,
|
val owned = MoodsTable.selectAll()
|
||||||
userName: String,
|
.where { (MoodsTable.id eq id) and (MoodsTable.owner eq owner) }
|
||||||
songId: String,
|
.any()
|
||||||
origin: String? = null,
|
if (!owned) return@transaction false
|
||||||
): Boolean = transaction {
|
|
||||||
if (get(playlistId, userName) == null) return@transaction false
|
|
||||||
|
|
||||||
val condition = if (origin == null) {
|
val removed = MoodSeedsTable.deleteWhere {
|
||||||
(MoodSeedsTable.playlistId eq playlistId) and (MoodSeedsTable.songId eq songId)
|
(MoodSeedsTable.moodId eq id) and (MoodSeedsTable.songId eq songId)
|
||||||
} else {
|
} > 0
|
||||||
(MoodSeedsTable.playlistId eq playlistId) and
|
if (removed) {
|
||||||
(MoodSeedsTable.songId eq songId) and
|
MoodsTable.update({ MoodsTable.id eq id }) {
|
||||||
(MoodSeedsTable.origin eq origin)
|
it[changedAt] = Instant.now().toString()
|
||||||
}
|
}
|
||||||
MoodSeedsTable.deleteWhere { condition } > 0
|
}
|
||||||
|
removed
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Mood playlists that currently contain [songId], for context-free star pinning. */
|
fun recommendations(id: String): List<RecommendationRecord> = transaction {
|
||||||
fun moodsContainingSong(userName: String, songId: String): List<String> = transaction {
|
MoodRecommendationsTable.selectAll()
|
||||||
PlaylistsTable
|
.where { MoodRecommendationsTable.moodId eq id }
|
||||||
.join(MoodsTable, JoinType.INNER, PlaylistsTable.id, MoodsTable.playlistId)
|
.orderBy(MoodRecommendationsTable.lastSeen to SortOrder.DESC)
|
||||||
.join(PlaylistSongsTable, JoinType.INNER, PlaylistsTable.id, PlaylistSongsTable.playlistId)
|
.map {
|
||||||
.select(PlaylistsTable.id)
|
RecommendationRecord(
|
||||||
.where {
|
videoId = it[MoodRecommendationsTable.videoId],
|
||||||
(PlaylistsTable.owner eq userName) and
|
title = it[MoodRecommendationsTable.title],
|
||||||
(PlaylistsTable.kind eq "mood") and
|
artist = it[MoodRecommendationsTable.artist],
|
||||||
(PlaylistSongsTable.songId eq songId)
|
album = it[MoodRecommendationsTable.album],
|
||||||
|
duration = it[MoodRecommendationsTable.duration],
|
||||||
|
thumbnail = it[MoodRecommendationsTable.thumbnail],
|
||||||
|
state = it[MoodRecommendationsTable.state],
|
||||||
|
matchedSongId = it[MoodRecommendationsTable.matchedSongId],
|
||||||
|
timesAdded = it[MoodRecommendationsTable.timesAdded],
|
||||||
|
firstSeen = it[MoodRecommendationsTable.firstSeen],
|
||||||
|
lastSeen = it[MoodRecommendationsTable.lastSeen],
|
||||||
|
)
|
||||||
}
|
}
|
||||||
.map { it[PlaylistsTable.id] }
|
|
||||||
.distinct()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun markGenerated(playlistId: String, generation: Int, error: String?) {
|
fun markError(id: String, message: String) {
|
||||||
transaction {
|
transaction {
|
||||||
MoodsTable.update({ MoodsTable.playlistId eq playlistId }) {
|
MoodsTable.update({ MoodsTable.id eq id }) {
|
||||||
it[generatedAt] = Instant.now().toString()
|
|
||||||
it[MoodsTable.generation] = generation
|
|
||||||
it[lastError] = error
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun markStale(playlistId: String) {
|
|
||||||
transaction {
|
|
||||||
MoodsTable.update({ MoodsTable.playlistId eq playlistId }) {
|
|
||||||
it[generatedAt] = null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Records a failed generation without claiming the mood is fresh. */
|
|
||||||
fun markError(playlistId: String, message: String) {
|
|
||||||
transaction {
|
|
||||||
MoodsTable.update({ MoodsTable.playlistId eq playlistId }) {
|
|
||||||
it[lastError] = message.take(1000)
|
it[lastError] = message.take(1000)
|
||||||
it[generatedAt] = null
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun markAllStale() {
|
fun markDiscovered(id: String) {
|
||||||
transaction {
|
transaction {
|
||||||
MoodsTable.update({ Op.TRUE }) {
|
MoodsTable.update({ MoodsTable.id eq id }) {
|
||||||
it[generatedAt] = null
|
it[lastDiscoveryAt] = Instant.now().toString()
|
||||||
|
it[lastError] = null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun insertSettings(
|
private fun insertSeeds(id: String, songIds: List<String>, origin: String) {
|
||||||
playlistId: String,
|
|
||||||
query: String?,
|
|
||||||
genres: List<String>,
|
|
||||||
targetSize: Int,
|
|
||||||
ytSlots: Int,
|
|
||||||
expandRelated: Boolean,
|
|
||||||
refreshHours: Int,
|
|
||||||
) {
|
|
||||||
MoodsTable.insert {
|
|
||||||
it[MoodsTable.playlistId] = playlistId
|
|
||||||
it[MoodsTable.query] = query?.trim()?.takeIf(String::isNotEmpty)
|
|
||||||
it[MoodsTable.genres] = encodeGenres(genres)
|
|
||||||
it[MoodsTable.targetSize] = targetSize.coerceIn(1, 500)
|
|
||||||
it[MoodsTable.ytSlots] = ytSlots.coerceIn(0, 500)
|
|
||||||
it[MoodsTable.expandRelated] = expandRelated
|
|
||||||
it[MoodsTable.refreshHours] = refreshHours.coerceIn(1, 720)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun insertSeeds(playlistId: String, songIds: List<String>, origin: String) {
|
|
||||||
val now = Instant.now().toString()
|
val now = Instant.now().toString()
|
||||||
songIds.distinct().forEach { songId ->
|
songIds.distinct().forEach { songId ->
|
||||||
MoodSeedsTable.insert {
|
MoodSeedsTable.insertIgnore {
|
||||||
it[MoodSeedsTable.playlistId] = playlistId
|
it[moodId] = id
|
||||||
it[MoodSeedsTable.songId] = songId
|
it[this.songId] = songId
|
||||||
it[MoodSeedsTable.origin] = origin
|
it[this.origin] = origin
|
||||||
it[addedAt] = now
|
it[addedAt] = now
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun moodRecord(row: ResultRow): MoodRecord {
|
private fun moodRecord(row: ResultRow): MoodRecord {
|
||||||
val id = row[PlaylistsTable.id]
|
val id = row[MoodsTable.id]
|
||||||
val songs = PlaylistSongsTable
|
val seedCount = MoodSeedsTable.selectAll()
|
||||||
.join(SongsTable, JoinType.INNER, PlaylistSongsTable.songId, SongsTable.id)
|
.where { MoodSeedsTable.moodId eq id }
|
||||||
.select(SongsTable.duration)
|
.count()
|
||||||
.where { PlaylistSongsTable.playlistId eq id }
|
.toInt()
|
||||||
.toList()
|
val newRecommendations = MoodRecommendationsTable.selectAll()
|
||||||
val seedCount = MoodSeedsTable
|
.where {
|
||||||
.selectAll()
|
(MoodRecommendationsTable.moodId eq id) and
|
||||||
.where { MoodSeedsTable.playlistId eq id }
|
(MoodRecommendationsTable.state eq "new")
|
||||||
|
}
|
||||||
.count()
|
.count()
|
||||||
.toInt()
|
.toInt()
|
||||||
|
|
||||||
return MoodRecord(
|
return MoodRecord(
|
||||||
playlistId = id,
|
id = id,
|
||||||
owner = row[PlaylistsTable.owner],
|
owner = row[MoodsTable.owner],
|
||||||
name = row[PlaylistsTable.name],
|
name = row[MoodsTable.name],
|
||||||
comment = row[PlaylistsTable.comment],
|
description = row[MoodsTable.description],
|
||||||
query = row[MoodsTable.query],
|
query = row[MoodsTable.query],
|
||||||
genres = decodeGenres(row[MoodsTable.genres]),
|
genres = decodeGenres(row[MoodsTable.genres]),
|
||||||
targetSize = row[MoodsTable.targetSize],
|
targetSize = row[MoodsTable.targetSize],
|
||||||
ytSlots = row[MoodsTable.ytSlots],
|
|
||||||
expandRelated = row[MoodsTable.expandRelated],
|
|
||||||
refreshHours = row[MoodsTable.refreshHours],
|
refreshHours = row[MoodsTable.refreshHours],
|
||||||
generatedAt = row[MoodsTable.generatedAt],
|
ytEnabled = row[MoodsTable.ytEnabled],
|
||||||
generation = row[MoodsTable.generation],
|
lastDiscoveryAt = row[MoodsTable.lastDiscoveryAt],
|
||||||
|
createdAt = row[MoodsTable.createdAt],
|
||||||
|
changedAt = row[MoodsTable.changedAt],
|
||||||
lastError = row[MoodsTable.lastError],
|
lastError = row[MoodsTable.lastError],
|
||||||
created = row[PlaylistsTable.createdAt],
|
|
||||||
changed = row[PlaylistsTable.changedAt],
|
|
||||||
songCount = songs.size,
|
|
||||||
duration = songs.sumOf { it[SongsTable.duration] },
|
|
||||||
seedCount = seedCount,
|
seedCount = seedCount,
|
||||||
|
newRecommendations = newRecommendations,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -410,4 +299,6 @@ object MoodRepository {
|
|||||||
|
|
||||||
private fun decodeGenres(value: String): List<String> =
|
private fun decodeGenres(value: String): List<String> =
|
||||||
runCatching { Json.decodeFromString(genreSerializer, value) }.getOrDefault(emptyList())
|
runCatching { Json.decodeFromString(genreSerializer, value) }.getOrDefault(emptyList())
|
||||||
|
|
||||||
|
private val ORIGINS = setOf("manual", "recommendation", "yt")
|
||||||
}
|
}
|
||||||
@@ -1,191 +0,0 @@
|
|||||||
package win.taptap.musicmanager.db
|
|
||||||
|
|
||||||
import java.time.Instant
|
|
||||||
import org.jetbrains.exposed.sql.JoinType
|
|
||||||
import org.jetbrains.exposed.sql.and
|
|
||||||
import org.jetbrains.exposed.sql.deleteWhere
|
|
||||||
import org.jetbrains.exposed.sql.insert
|
|
||||||
import org.jetbrains.exposed.sql.or
|
|
||||||
import org.jetbrains.exposed.sql.selectAll
|
|
||||||
import org.jetbrains.exposed.sql.transactions.transaction
|
|
||||||
import org.jetbrains.exposed.sql.update
|
|
||||||
import win.taptap.musicmanager.util.IdGenerator
|
|
||||||
|
|
||||||
data class PlaylistRecord(
|
|
||||||
val id: String,
|
|
||||||
val name: String,
|
|
||||||
val comment: String?,
|
|
||||||
val owner: String,
|
|
||||||
val isPublic: Boolean,
|
|
||||||
val kind: String,
|
|
||||||
val songCount: Int,
|
|
||||||
val duration: Int,
|
|
||||||
val created: String,
|
|
||||||
val changed: String,
|
|
||||||
)
|
|
||||||
|
|
||||||
/** Playlists are per user; public playlists are visible to everyone. */
|
|
||||||
object PlaylistRepository {
|
|
||||||
|
|
||||||
fun visibleTo(userName: String): List<PlaylistRecord> = transaction {
|
|
||||||
PlaylistsTable.selectAll()
|
|
||||||
.where {
|
|
||||||
(PlaylistsTable.owner eq userName) or (PlaylistsTable.isPublic eq true)
|
|
||||||
}
|
|
||||||
.orderBy(PlaylistsTable.changedAt to org.jetbrains.exposed.sql.SortOrder.DESC)
|
|
||||||
.map { playlistRecord(it[PlaylistsTable.id], it) }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun get(playlistId: String, userName: String): PlaylistRecord? = transaction {
|
|
||||||
val row = PlaylistsTable.selectAll()
|
|
||||||
.where { PlaylistsTable.id eq playlistId }
|
|
||||||
.singleOrNull() ?: return@transaction null
|
|
||||||
|
|
||||||
if (row[PlaylistsTable.owner] != userName && !row[PlaylistsTable.isPublic]) {
|
|
||||||
return@transaction null
|
|
||||||
}
|
|
||||||
|
|
||||||
playlistRecord(playlistId, row)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun songIds(playlistId: String): List<String> = transaction {
|
|
||||||
PlaylistSongsTable.selectAll()
|
|
||||||
.where { PlaylistSongsTable.playlistId eq playlistId }
|
|
||||||
.orderBy(PlaylistSongsTable.position to org.jetbrains.exposed.sql.SortOrder.ASC)
|
|
||||||
.map { it[PlaylistSongsTable.songId] }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun create(
|
|
||||||
userName: String,
|
|
||||||
name: String,
|
|
||||||
songIds: List<String>,
|
|
||||||
isPublic: Boolean = true,
|
|
||||||
kind: String = "user",
|
|
||||||
): PlaylistRecord = transaction {
|
|
||||||
val now = Instant.now().toString()
|
|
||||||
val id = IdGenerator.playlistId(userName, name, now)
|
|
||||||
|
|
||||||
PlaylistsTable.insert {
|
|
||||||
it[PlaylistsTable.id] = id
|
|
||||||
it[owner] = userName
|
|
||||||
it[PlaylistsTable.name] = name
|
|
||||||
it[PlaylistsTable.isPublic] = isPublic
|
|
||||||
it[PlaylistsTable.kind] = kind
|
|
||||||
it[createdAt] = now
|
|
||||||
it[changedAt] = now
|
|
||||||
}
|
|
||||||
replaceSongsInternal(id, songIds)
|
|
||||||
|
|
||||||
playlistRecord(id, PlaylistsTable.selectAll().where { PlaylistsTable.id eq id }.single())
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Promotion keeps the playlist ID stable so Symfonium keeps its reference. */
|
|
||||||
fun setKind(playlistId: String, kind: String, isPublic: Boolean): Boolean = transaction {
|
|
||||||
PlaylistsTable.update({ PlaylistsTable.id eq playlistId }) {
|
|
||||||
it[PlaylistsTable.kind] = kind
|
|
||||||
it[PlaylistsTable.isPublic] = isPublic
|
|
||||||
it[changedAt] = Instant.now().toString()
|
|
||||||
} > 0
|
|
||||||
}
|
|
||||||
|
|
||||||
fun replaceSongs(playlistId: String, songIds: List<String>, userName: String): Boolean = transaction {
|
|
||||||
val row = PlaylistsTable.selectAll()
|
|
||||||
.where { PlaylistsTable.id eq playlistId }
|
|
||||||
.singleOrNull() ?: return@transaction false
|
|
||||||
if (row[PlaylistsTable.owner] != userName) return@transaction false
|
|
||||||
|
|
||||||
val now = Instant.now().toString()
|
|
||||||
replaceSongsInternal(playlistId, songIds)
|
|
||||||
PlaylistsTable.update({ PlaylistsTable.id eq playlistId }) {
|
|
||||||
it[changedAt] = now
|
|
||||||
}
|
|
||||||
true
|
|
||||||
}
|
|
||||||
|
|
||||||
fun update(
|
|
||||||
playlistId: String,
|
|
||||||
userName: String,
|
|
||||||
name: String?,
|
|
||||||
comment: String?,
|
|
||||||
isPublic: Boolean?,
|
|
||||||
addSongIds: List<String>,
|
|
||||||
removeIndices: List<Int>,
|
|
||||||
): Boolean = transaction {
|
|
||||||
val row = PlaylistsTable.selectAll()
|
|
||||||
.where { PlaylistsTable.id eq playlistId }
|
|
||||||
.singleOrNull() ?: return@transaction false
|
|
||||||
if (row[PlaylistsTable.owner] != userName) return@transaction false
|
|
||||||
|
|
||||||
if (name != null || comment != null || isPublic != null) {
|
|
||||||
PlaylistsTable.update({ PlaylistsTable.id eq playlistId }) {
|
|
||||||
if (name != null) it[PlaylistsTable.name] = name
|
|
||||||
if (comment != null) it[PlaylistsTable.comment] = comment
|
|
||||||
if (isPublic != null) it[PlaylistsTable.isPublic] = isPublic
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var songs = songIdsInternal(playlistId)
|
|
||||||
if (removeIndices.isNotEmpty()) {
|
|
||||||
val toRemove = removeIndices.filter { it in songs.indices }.toSortedSet(compareByDescending { it })
|
|
||||||
toRemove.forEach { index ->
|
|
||||||
if (index in songs.indices) songs = songs.filterIndexed { i, _ -> i != index }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
songs = songs + addSongIds
|
|
||||||
|
|
||||||
val now = Instant.now().toString()
|
|
||||||
replaceSongsInternal(playlistId, songs)
|
|
||||||
PlaylistsTable.update({ PlaylistsTable.id eq playlistId }) {
|
|
||||||
it[changedAt] = now
|
|
||||||
}
|
|
||||||
true
|
|
||||||
}
|
|
||||||
|
|
||||||
fun delete(playlistId: String, userName: String): Boolean = transaction {
|
|
||||||
val row = PlaylistsTable.selectAll()
|
|
||||||
.where { PlaylistsTable.id eq playlistId }
|
|
||||||
.singleOrNull() ?: return@transaction false
|
|
||||||
if (row[PlaylistsTable.owner] != userName) return@transaction false
|
|
||||||
|
|
||||||
PlaylistsTable.deleteWhere { it.run { PlaylistsTable.id eq playlistId } }
|
|
||||||
true
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun songIdsInternal(playlistId: String): List<String> =
|
|
||||||
PlaylistSongsTable.selectAll()
|
|
||||||
.where { PlaylistSongsTable.playlistId eq playlistId }
|
|
||||||
.orderBy(PlaylistSongsTable.position to org.jetbrains.exposed.sql.SortOrder.ASC)
|
|
||||||
.map { it[PlaylistSongsTable.songId] }
|
|
||||||
|
|
||||||
private fun replaceSongsInternal(playlistId: String, songIds: List<String>) {
|
|
||||||
PlaylistSongsTable.deleteWhere { it.run { PlaylistSongsTable.playlistId eq playlistId } }
|
|
||||||
songIds.forEachIndexed { index, songId ->
|
|
||||||
PlaylistSongsTable.insert {
|
|
||||||
it[PlaylistSongsTable.playlistId] = playlistId
|
|
||||||
it[PlaylistSongsTable.songId] = songId
|
|
||||||
it[position] = index
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun playlistRecord(id: String, row: org.jetbrains.exposed.sql.ResultRow): PlaylistRecord {
|
|
||||||
val songs = PlaylistSongsTable
|
|
||||||
.join(SongsTable, JoinType.INNER, PlaylistSongsTable.songId, SongsTable.id)
|
|
||||||
.select(SongsTable.duration)
|
|
||||||
.where { PlaylistSongsTable.playlistId eq id }
|
|
||||||
.toList()
|
|
||||||
|
|
||||||
return PlaylistRecord(
|
|
||||||
id = id,
|
|
||||||
name = row[PlaylistsTable.name],
|
|
||||||
comment = row[PlaylistsTable.comment],
|
|
||||||
owner = row[PlaylistsTable.owner],
|
|
||||||
isPublic = row[PlaylistsTable.isPublic],
|
|
||||||
kind = row[PlaylistsTable.kind],
|
|
||||||
songCount = songs.size,
|
|
||||||
duration = songs.sumOf { it[SongsTable.duration] },
|
|
||||||
created = row[PlaylistsTable.createdAt],
|
|
||||||
changed = row[PlaylistsTable.changedAt],
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
package win.taptap.musicmanager.db
|
||||||
|
|
||||||
|
import java.time.Instant
|
||||||
|
import org.jetbrains.exposed.sql.SortOrder
|
||||||
|
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
|
||||||
|
import org.jetbrains.exposed.sql.and
|
||||||
|
import org.jetbrains.exposed.sql.insert
|
||||||
|
import org.jetbrains.exposed.sql.selectAll
|
||||||
|
import org.jetbrains.exposed.sql.transactions.transaction
|
||||||
|
import org.jetbrains.exposed.sql.update
|
||||||
|
|
||||||
|
data class PlaybackSessionRecord(
|
||||||
|
val id: String,
|
||||||
|
val userName: String,
|
||||||
|
val moodId: String,
|
||||||
|
val createdAt: String,
|
||||||
|
val lastSeenAt: String,
|
||||||
|
val closedAt: String?,
|
||||||
|
)
|
||||||
|
|
||||||
|
data class SessionItemRecord(
|
||||||
|
val position: Int,
|
||||||
|
val songId: String,
|
||||||
|
val state: String,
|
||||||
|
)
|
||||||
|
|
||||||
|
data class AffinityRecord(val completions: Int, val skips: Int) {
|
||||||
|
/** Skips weigh double so a mood stops serving rejected tracks quickly. */
|
||||||
|
val score: Double get() = completions - skips * 2.0
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Playback sessions make likes unnecessary: every play, skip and completion is
|
||||||
|
* attributed to the mood that produced the queue, and explicit "add to mood"
|
||||||
|
* actions replace stars.
|
||||||
|
*/
|
||||||
|
object RadioRepository {
|
||||||
|
|
||||||
|
fun createSession(userName: String, moodId: String, sessionToken: String): PlaybackSessionRecord = transaction {
|
||||||
|
val now = Instant.now().toString()
|
||||||
|
val id = "ps-" + ApiTokenRepository.hash(sessionToken).take(24)
|
||||||
|
PlaybackSessionsTable.insert {
|
||||||
|
it[PlaybackSessionsTable.id] = id
|
||||||
|
it[PlaybackSessionsTable.userName] = userName
|
||||||
|
it[PlaybackSessionsTable.moodId] = moodId
|
||||||
|
it[createdAt] = now
|
||||||
|
it[lastSeenAt] = now
|
||||||
|
}
|
||||||
|
PlaybackSessionRecord(id, userName, moodId, now, now, null)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun get(id: String, userName: String): PlaybackSessionRecord? = transaction {
|
||||||
|
PlaybackSessionsTable.selectAll()
|
||||||
|
.where {
|
||||||
|
(PlaybackSessionsTable.id eq id) and
|
||||||
|
(PlaybackSessionsTable.userName eq userName)
|
||||||
|
}
|
||||||
|
.singleOrNull()
|
||||||
|
?.toRecord()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun touch(id: String) {
|
||||||
|
transaction {
|
||||||
|
PlaybackSessionsTable.update({ PlaybackSessionsTable.id eq id }) {
|
||||||
|
it[lastSeenAt] = Instant.now().toString()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun close(id: String, userName: String): Boolean = transaction {
|
||||||
|
val now = Instant.now().toString()
|
||||||
|
PlaybackSessionsTable.update({
|
||||||
|
(PlaybackSessionsTable.id eq id) and
|
||||||
|
(PlaybackSessionsTable.userName eq userName) and
|
||||||
|
(PlaybackSessionsTable.closedAt.isNull())
|
||||||
|
}) {
|
||||||
|
it[closedAt] = now
|
||||||
|
it[lastSeenAt] = now
|
||||||
|
} > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
fun items(id: String): List<SessionItemRecord> = transaction {
|
||||||
|
SessionItemsTable.selectAll()
|
||||||
|
.where { SessionItemsTable.sessionId eq id }
|
||||||
|
.orderBy(SessionItemsTable.position to SortOrder.ASC)
|
||||||
|
.map {
|
||||||
|
SessionItemRecord(
|
||||||
|
position = it[SessionItemsTable.position],
|
||||||
|
songId = it[SessionItemsTable.songId],
|
||||||
|
state = it[SessionItemsTable.state],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun queuedSongIds(id: String): Set<String> = items(id).map { it.songId }.toSet()
|
||||||
|
|
||||||
|
/** Appends tracks and returns their positions in the session. */
|
||||||
|
fun append(sessionId: String, songIds: List<String>): List<Int> = transaction {
|
||||||
|
if (songIds.isEmpty()) return@transaction emptyList()
|
||||||
|
|
||||||
|
val session = PlaybackSessionsTable.selectAll()
|
||||||
|
.where { PlaybackSessionsTable.id eq sessionId }
|
||||||
|
.single()
|
||||||
|
var position = session[PlaybackSessionsTable.nextPosition]
|
||||||
|
val now = Instant.now().toString()
|
||||||
|
val positions = mutableListOf<Int>()
|
||||||
|
|
||||||
|
songIds.forEach { songId ->
|
||||||
|
SessionItemsTable.insert {
|
||||||
|
it[SessionItemsTable.sessionId] = sessionId
|
||||||
|
it[SessionItemsTable.position] = position
|
||||||
|
it[SessionItemsTable.songId] = songId
|
||||||
|
it[SessionItemsTable.state] = "queued"
|
||||||
|
it[queuedAt] = now
|
||||||
|
it[updatedAt] = now
|
||||||
|
}
|
||||||
|
positions += position
|
||||||
|
position += 1
|
||||||
|
}
|
||||||
|
|
||||||
|
PlaybackSessionsTable.update({ PlaybackSessionsTable.id eq sessionId }) {
|
||||||
|
it[nextPosition] = position
|
||||||
|
it[lastSeenAt] = now
|
||||||
|
}
|
||||||
|
positions
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Applies a client playback event. Unknown songs are still recorded in the
|
||||||
|
* affinity table so manual queueing can influence later radio batches.
|
||||||
|
*/
|
||||||
|
fun recordEvent(
|
||||||
|
sessionId: String,
|
||||||
|
userName: String,
|
||||||
|
songId: String,
|
||||||
|
state: String,
|
||||||
|
): Boolean = transaction {
|
||||||
|
val session = PlaybackSessionsTable.selectAll()
|
||||||
|
.where {
|
||||||
|
(PlaybackSessionsTable.id eq sessionId) and
|
||||||
|
(PlaybackSessionsTable.userName eq userName)
|
||||||
|
}
|
||||||
|
.singleOrNull() ?: return@transaction false
|
||||||
|
|
||||||
|
val now = Instant.now().toString()
|
||||||
|
SessionItemsTable.update({
|
||||||
|
(SessionItemsTable.sessionId eq sessionId) and
|
||||||
|
(SessionItemsTable.songId eq songId)
|
||||||
|
}) {
|
||||||
|
it[SessionItemsTable.state] = state
|
||||||
|
it[updatedAt] = now
|
||||||
|
}
|
||||||
|
|
||||||
|
if (state == "completed" || state == "skipped") {
|
||||||
|
val existing = SongAffinityTable.selectAll()
|
||||||
|
.where {
|
||||||
|
(SongAffinityTable.userName eq userName) and
|
||||||
|
(SongAffinityTable.songId eq songId)
|
||||||
|
}
|
||||||
|
.singleOrNull()
|
||||||
|
|
||||||
|
if (existing == null) {
|
||||||
|
SongAffinityTable.insert {
|
||||||
|
it[SongAffinityTable.userName] = userName
|
||||||
|
it[SongAffinityTable.songId] = songId
|
||||||
|
it[completions] = if (state == "completed") 1 else 0
|
||||||
|
it[skips] = if (state == "skipped") 1 else 0
|
||||||
|
it[lastEventAt] = now
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
SongAffinityTable.update({
|
||||||
|
(SongAffinityTable.userName eq userName) and
|
||||||
|
(SongAffinityTable.songId eq songId)
|
||||||
|
}) {
|
||||||
|
if (state == "completed") it[completions] = existing[SongAffinityTable.completions] + 1
|
||||||
|
if (state == "skipped") it[skips] = existing[SongAffinityTable.skips] + 1
|
||||||
|
it[lastEventAt] = now
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
PlaybackSessionsTable.update({ PlaybackSessionsTable.id eq session[PlaybackSessionsTable.id] }) {
|
||||||
|
it[lastSeenAt] = now
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun affinity(userName: String, songIds: Collection<String>): Map<String, AffinityRecord> {
|
||||||
|
if (songIds.isEmpty()) return emptyMap()
|
||||||
|
return transaction {
|
||||||
|
SongAffinityTable.selectAll()
|
||||||
|
.where {
|
||||||
|
(SongAffinityTable.userName eq userName) and
|
||||||
|
(SongAffinityTable.songId inList songIds.toList())
|
||||||
|
}
|
||||||
|
.associate {
|
||||||
|
it[SongAffinityTable.songId] to AffinityRecord(
|
||||||
|
completions = it[SongAffinityTable.completions],
|
||||||
|
skips = it[SongAffinityTable.skips],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun org.jetbrains.exposed.sql.ResultRow.toRecord() = PlaybackSessionRecord(
|
||||||
|
id = this[PlaybackSessionsTable.id],
|
||||||
|
userName = this[PlaybackSessionsTable.userName],
|
||||||
|
moodId = this[PlaybackSessionsTable.moodId],
|
||||||
|
createdAt = this[PlaybackSessionsTable.createdAt],
|
||||||
|
lastSeenAt = this[PlaybackSessionsTable.lastSeenAt],
|
||||||
|
closedAt = this[PlaybackSessionsTable.closedAt],
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -68,6 +68,7 @@ object SongsTable : Table("songs") {
|
|||||||
val relativePath = text("relative_path")
|
val relativePath = text("relative_path")
|
||||||
val fileMtime = long("file_mtime")
|
val fileMtime = long("file_mtime")
|
||||||
val createdAt = varchar("created_at", 40)
|
val createdAt = varchar("created_at", 40)
|
||||||
|
val updatedAt = varchar("updated_at", 40).default("")
|
||||||
val searchText = text("search_text")
|
val searchText = text("search_text")
|
||||||
val lyrics = text("lyrics").nullable()
|
val lyrics = text("lyrics").nullable()
|
||||||
|
|
||||||
@@ -133,57 +134,46 @@ object BookmarksTable : Table("bookmarks") {
|
|||||||
override val primaryKey = PrimaryKey(userName, songId)
|
override val primaryKey = PrimaryKey(userName, songId)
|
||||||
}
|
}
|
||||||
|
|
||||||
object PlaylistsTable : Table("playlists") {
|
/**
|
||||||
|
* Moods are the only collection type. A mood owns seeds (permanent anchors) and
|
||||||
|
* recommendations (YT Music candidates); playback queues are generated live and
|
||||||
|
* never materialized here.
|
||||||
|
*/
|
||||||
|
object MoodsTable : Table("moods") {
|
||||||
val id = varchar("id", 32)
|
val id = varchar("id", 32)
|
||||||
val owner = reference("owner", UsersTable.name, onDelete = ReferenceOption.CASCADE)
|
val owner = reference("owner", UsersTable.name, onDelete = ReferenceOption.CASCADE)
|
||||||
val name = text("name")
|
val name = text("name")
|
||||||
val comment = text("comment").nullable()
|
val description = text("description").nullable()
|
||||||
val isPublic = bool("is_public").default(true)
|
val query = text("query").nullable()
|
||||||
val kind = varchar("kind", 16).default("user")
|
val genres = text("genres").default("[]")
|
||||||
|
val targetSize = integer("target_size").default(30)
|
||||||
|
val refreshHours = integer("refresh_hours").default(24)
|
||||||
|
val ytEnabled = bool("yt_enabled").default(true)
|
||||||
|
val lastDiscoveryAt = varchar("last_discovery_at", 40).nullable()
|
||||||
val createdAt = varchar("created_at", 40)
|
val createdAt = varchar("created_at", 40)
|
||||||
val changedAt = varchar("changed_at", 40)
|
val changedAt = varchar("changed_at", 40)
|
||||||
|
val lastError = text("last_error").nullable()
|
||||||
|
|
||||||
override val primaryKey = PrimaryKey(id)
|
override val primaryKey = PrimaryKey(id)
|
||||||
}
|
}
|
||||||
|
|
||||||
object PlaylistSongsTable : Table("playlist_songs") {
|
|
||||||
val playlistId = reference("playlist_id", PlaylistsTable.id, onDelete = ReferenceOption.CASCADE)
|
|
||||||
val songId = reference("song_id", SongsTable.id, onDelete = ReferenceOption.CASCADE)
|
|
||||||
val position = integer("position")
|
|
||||||
|
|
||||||
override val primaryKey = PrimaryKey(playlistId, position)
|
|
||||||
}
|
|
||||||
|
|
||||||
object MoodsTable : Table("moods") {
|
|
||||||
val playlistId = reference("playlist_id", PlaylistsTable.id, onDelete = ReferenceOption.CASCADE)
|
|
||||||
val query = text("query").nullable()
|
|
||||||
val genres = text("genres").default("[]")
|
|
||||||
val targetSize = integer("target_size").default(50)
|
|
||||||
val ytSlots = integer("yt_slots").default(0)
|
|
||||||
val expandRelated = bool("expand_related").default(true)
|
|
||||||
val refreshHours = integer("refresh_hours").default(24)
|
|
||||||
val generatedAt = varchar("generated_at", 40).nullable()
|
|
||||||
val generation = integer("generation").default(0)
|
|
||||||
val lastError = text("last_error").nullable()
|
|
||||||
|
|
||||||
override val primaryKey = PrimaryKey(playlistId)
|
|
||||||
}
|
|
||||||
|
|
||||||
object MoodSeedsTable : Table("mood_seeds") {
|
object MoodSeedsTable : Table("mood_seeds") {
|
||||||
val playlistId = reference("playlist_id", MoodsTable.playlistId, onDelete = ReferenceOption.CASCADE)
|
val moodId = reference("mood_id", MoodsTable.id, onDelete = ReferenceOption.CASCADE)
|
||||||
val songId = reference("song_id", SongsTable.id, onDelete = ReferenceOption.CASCADE)
|
val songId = reference("song_id", SongsTable.id, onDelete = ReferenceOption.CASCADE)
|
||||||
val origin = varchar("origin", 16).default("manual")
|
val origin = varchar("origin", 16).default("manual")
|
||||||
val addedAt = varchar("added_at", 40)
|
val addedAt = varchar("added_at", 40)
|
||||||
|
|
||||||
override val primaryKey = PrimaryKey(playlistId, songId)
|
override val primaryKey = PrimaryKey(moodId, songId)
|
||||||
}
|
}
|
||||||
|
|
||||||
object MoodRecommendationsTable : Table("mood_recommendations") {
|
object MoodRecommendationsTable : Table("mood_recommendations") {
|
||||||
val playlistId = reference("playlist_id", MoodsTable.playlistId, onDelete = ReferenceOption.CASCADE)
|
val moodId = reference("mood_id", MoodsTable.id, onDelete = ReferenceOption.CASCADE)
|
||||||
val videoId = varchar("video_id", 64)
|
val videoId = varchar("video_id", 64)
|
||||||
val title = text("title")
|
val title = text("title")
|
||||||
val artist = text("artist")
|
val artist = text("artist")
|
||||||
|
val album = text("album").nullable()
|
||||||
val duration = integer("duration").nullable()
|
val duration = integer("duration").nullable()
|
||||||
|
val thumbnail = text("thumbnail").nullable()
|
||||||
val state = varchar("state", 16).default("new")
|
val state = varchar("state", 16).default("new")
|
||||||
val matchedSongId = reference(
|
val matchedSongId = reference(
|
||||||
"matched_song_id",
|
"matched_song_id",
|
||||||
@@ -194,5 +184,60 @@ object MoodRecommendationsTable : Table("mood_recommendations") {
|
|||||||
val firstSeen = varchar("first_seen", 40)
|
val firstSeen = varchar("first_seen", 40)
|
||||||
val lastSeen = varchar("last_seen", 40)
|
val lastSeen = varchar("last_seen", 40)
|
||||||
|
|
||||||
override val primaryKey = PrimaryKey(playlistId, videoId)
|
override val primaryKey = PrimaryKey(moodId, videoId)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Bearer tokens are stored as hashes; the raw value only exists on the device. */
|
||||||
|
object ApiTokensTable : Table("api_tokens") {
|
||||||
|
val id = varchar("id", 32)
|
||||||
|
val userName = reference("user_name", UsersTable.name, onDelete = ReferenceOption.CASCADE)
|
||||||
|
val tokenHash = varchar("token_hash", 64)
|
||||||
|
val deviceName = varchar("device_name", 120)
|
||||||
|
val platform = varchar("platform", 32)
|
||||||
|
val createdAt = varchar("created_at", 40)
|
||||||
|
val lastUsedAt = varchar("last_used_at", 40)
|
||||||
|
val expiresAt = varchar("expires_at", 40)
|
||||||
|
|
||||||
|
override val primaryKey = PrimaryKey(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
object PlaybackSessionsTable : Table("playback_sessions") {
|
||||||
|
val id = varchar("id", 32)
|
||||||
|
val userName = reference("user_name", UsersTable.name, onDelete = ReferenceOption.CASCADE)
|
||||||
|
val moodId = reference("mood_id", MoodsTable.id, onDelete = ReferenceOption.CASCADE)
|
||||||
|
val nextPosition = integer("next_position").default(0)
|
||||||
|
val createdAt = varchar("created_at", 40)
|
||||||
|
val lastSeenAt = varchar("last_seen_at", 40)
|
||||||
|
val closedAt = varchar("closed_at", 40).nullable()
|
||||||
|
|
||||||
|
override val primaryKey = PrimaryKey(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
object SessionItemsTable : Table("playback_session_items") {
|
||||||
|
val sessionId = reference("session_id", PlaybackSessionsTable.id, onDelete = ReferenceOption.CASCADE)
|
||||||
|
val position = integer("position")
|
||||||
|
val songId = reference("song_id", SongsTable.id, onDelete = ReferenceOption.CASCADE)
|
||||||
|
val state = varchar("state", 16).default("queued")
|
||||||
|
val queuedAt = varchar("queued_at", 40)
|
||||||
|
val updatedAt = varchar("updated_at", 40)
|
||||||
|
|
||||||
|
override val primaryKey = PrimaryKey(sessionId, position)
|
||||||
|
}
|
||||||
|
|
||||||
|
object SongAffinityTable : Table("song_affinity") {
|
||||||
|
val userName = reference("user_name", UsersTable.name, onDelete = ReferenceOption.CASCADE)
|
||||||
|
val songId = reference("song_id", SongsTable.id, onDelete = ReferenceOption.CASCADE)
|
||||||
|
val completions = integer("completions").default(0)
|
||||||
|
val skips = integer("skips").default(0)
|
||||||
|
val lastEventAt = varchar("last_event_at", 40)
|
||||||
|
|
||||||
|
override val primaryKey = PrimaryKey(userName, songId)
|
||||||
|
}
|
||||||
|
|
||||||
|
object LibraryTombstonesTable : Table("library_tombstones") {
|
||||||
|
val entity = varchar("entity", 20)
|
||||||
|
val entityId = varchar("entity_id", 32)
|
||||||
|
val deletedAt = varchar("deleted_at", 40)
|
||||||
|
|
||||||
|
override val primaryKey = PrimaryKey(entity, entityId)
|
||||||
}
|
}
|
||||||
@@ -1,217 +0,0 @@
|
|||||||
package win.taptap.musicmanager.db
|
|
||||||
|
|
||||||
import java.time.Instant
|
|
||||||
import org.jetbrains.exposed.sql.and
|
|
||||||
import org.jetbrains.exposed.sql.deleteWhere
|
|
||||||
import org.jetbrains.exposed.sql.insert
|
|
||||||
import org.jetbrains.exposed.sql.selectAll
|
|
||||||
import org.jetbrains.exposed.sql.transactions.transaction
|
|
||||||
import org.jetbrains.exposed.sql.update
|
|
||||||
|
|
||||||
data class BookmarkRecord(
|
|
||||||
val songId: String,
|
|
||||||
val positionMs: Long,
|
|
||||||
val updatedAt: String,
|
|
||||||
)
|
|
||||||
|
|
||||||
/** Per-user state: play counts, stars, ratings and bookmarks. */
|
|
||||||
object UserStateRepository {
|
|
||||||
|
|
||||||
fun scrobble(userName: String, songId: String, submission: Boolean) {
|
|
||||||
if (!submission) return
|
|
||||||
val now = Instant.now().toString()
|
|
||||||
|
|
||||||
transaction {
|
|
||||||
val existing = UserSongStateTable.selectAll()
|
|
||||||
.where {
|
|
||||||
(UserSongStateTable.userName eq userName) and
|
|
||||||
(UserSongStateTable.songId eq songId)
|
|
||||||
}
|
|
||||||
.singleOrNull()
|
|
||||||
|
|
||||||
if (existing == null) {
|
|
||||||
UserSongStateTable.insert {
|
|
||||||
it[UserSongStateTable.userName] = userName
|
|
||||||
it[UserSongStateTable.songId] = songId
|
|
||||||
it[playCount] = 1
|
|
||||||
it[lastPlayedAt] = now
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
UserSongStateTable.update({
|
|
||||||
(UserSongStateTable.userName eq userName) and
|
|
||||||
(UserSongStateTable.songId eq songId)
|
|
||||||
}) {
|
|
||||||
it[playCount] = existing[UserSongStateTable.playCount] + 1
|
|
||||||
it[lastPlayedAt] = now
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun setSongRating(userName: String, songId: String, rating: Int?) {
|
|
||||||
transaction {
|
|
||||||
val existing = UserSongStateTable.selectAll()
|
|
||||||
.where {
|
|
||||||
(UserSongStateTable.userName eq userName) and
|
|
||||||
(UserSongStateTable.songId eq songId)
|
|
||||||
}
|
|
||||||
.singleOrNull()
|
|
||||||
|
|
||||||
if (existing == null) {
|
|
||||||
UserSongStateTable.insert {
|
|
||||||
it[UserSongStateTable.userName] = userName
|
|
||||||
it[UserSongStateTable.songId] = songId
|
|
||||||
it[UserSongStateTable.rating] = rating
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
UserSongStateTable.update({
|
|
||||||
(UserSongStateTable.userName eq userName) and
|
|
||||||
(UserSongStateTable.songId eq songId)
|
|
||||||
}) {
|
|
||||||
it[UserSongStateTable.rating] = rating
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun setItemRating(userName: String, itemType: String, itemId: String, rating: Int?) {
|
|
||||||
transaction {
|
|
||||||
val existing = UserStarsTable.selectAll()
|
|
||||||
.where {
|
|
||||||
(UserStarsTable.userName eq userName) and
|
|
||||||
(UserStarsTable.itemType eq itemType) and
|
|
||||||
(UserStarsTable.itemId eq itemId)
|
|
||||||
}
|
|
||||||
.singleOrNull()
|
|
||||||
|
|
||||||
if (existing == null) {
|
|
||||||
UserStarsTable.insert {
|
|
||||||
it[UserStarsTable.userName] = userName
|
|
||||||
it[UserStarsTable.itemType] = itemType
|
|
||||||
it[UserStarsTable.itemId] = itemId
|
|
||||||
it[starredAt] = ""
|
|
||||||
it[UserStarsTable.rating] = rating
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
UserStarsTable.update({
|
|
||||||
(UserStarsTable.userName eq userName) and
|
|
||||||
(UserStarsTable.itemType eq itemType) and
|
|
||||||
(UserStarsTable.itemId eq itemId)
|
|
||||||
}) {
|
|
||||||
it[UserStarsTable.rating] = rating
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun starSong(userName: String, songId: String) {
|
|
||||||
val now = Instant.now().toString()
|
|
||||||
transaction {
|
|
||||||
val existing = UserSongStateTable.selectAll()
|
|
||||||
.where {
|
|
||||||
(UserSongStateTable.userName eq userName) and
|
|
||||||
(UserSongStateTable.songId eq songId)
|
|
||||||
}
|
|
||||||
.singleOrNull()
|
|
||||||
|
|
||||||
if (existing == null) {
|
|
||||||
UserSongStateTable.insert {
|
|
||||||
it[UserSongStateTable.userName] = userName
|
|
||||||
it[UserSongStateTable.songId] = songId
|
|
||||||
it[starredAt] = now
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
UserSongStateTable.update({
|
|
||||||
(UserSongStateTable.userName eq userName) and
|
|
||||||
(UserSongStateTable.songId eq songId)
|
|
||||||
}) {
|
|
||||||
it[starredAt] = now
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun unstarSong(userName: String, songId: String) {
|
|
||||||
transaction {
|
|
||||||
UserSongStateTable.update({
|
|
||||||
(UserSongStateTable.userName eq userName) and
|
|
||||||
(UserSongStateTable.songId eq songId)
|
|
||||||
}) {
|
|
||||||
it[starredAt] = null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun starItem(userName: String, itemType: String, itemId: String) {
|
|
||||||
val now = Instant.now().toString()
|
|
||||||
transaction {
|
|
||||||
UserStarsTable.deleteWhere {
|
|
||||||
it.run {
|
|
||||||
(UserStarsTable.userName eq userName) and
|
|
||||||
(UserStarsTable.itemType eq itemType) and
|
|
||||||
(UserStarsTable.itemId eq itemId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
UserStarsTable.insert {
|
|
||||||
it[UserStarsTable.userName] = userName
|
|
||||||
it[UserStarsTable.itemType] = itemType
|
|
||||||
it[UserStarsTable.itemId] = itemId
|
|
||||||
it[starredAt] = now
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun unstarItem(userName: String, itemType: String, itemId: String) {
|
|
||||||
transaction {
|
|
||||||
UserStarsTable.deleteWhere {
|
|
||||||
it.run {
|
|
||||||
(UserStarsTable.userName eq userName) and
|
|
||||||
(UserStarsTable.itemType eq itemType) and
|
|
||||||
(UserStarsTable.itemId eq itemId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun createBookmark(userName: String, songId: String, positionMs: Long) {
|
|
||||||
val now = Instant.now().toString()
|
|
||||||
transaction {
|
|
||||||
BookmarksTable.deleteWhere {
|
|
||||||
it.run {
|
|
||||||
(BookmarksTable.userName eq userName) and
|
|
||||||
(BookmarksTable.songId eq songId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
BookmarksTable.insert {
|
|
||||||
it[BookmarksTable.userName] = userName
|
|
||||||
it[BookmarksTable.songId] = songId
|
|
||||||
it[BookmarksTable.positionMs] = positionMs
|
|
||||||
it[updatedAt] = now
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun deleteBookmark(userName: String, songId: String) {
|
|
||||||
transaction {
|
|
||||||
BookmarksTable.deleteWhere {
|
|
||||||
it.run {
|
|
||||||
(BookmarksTable.userName eq userName) and
|
|
||||||
(BookmarksTable.songId eq songId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun bookmarks(userName: String): List<BookmarkRecord> = transaction {
|
|
||||||
BookmarksTable.selectAll()
|
|
||||||
.where { BookmarksTable.userName eq userName }
|
|
||||||
.orderBy(BookmarksTable.updatedAt to org.jetbrains.exposed.sql.SortOrder.DESC)
|
|
||||||
.map {
|
|
||||||
BookmarkRecord(
|
|
||||||
songId = it[BookmarksTable.songId],
|
|
||||||
positionMs = it[BookmarksTable.positionMs],
|
|
||||||
updatedAt = it[BookmarksTable.updatedAt],
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,145 +0,0 @@
|
|||||||
package win.taptap.musicmanager.mood
|
|
||||||
|
|
||||||
import kotlin.math.max
|
|
||||||
import kotlin.math.min
|
|
||||||
import kotlin.random.Random
|
|
||||||
import org.slf4j.LoggerFactory
|
|
||||||
import win.taptap.musicmanager.config.FolderType
|
|
||||||
import win.taptap.musicmanager.config.LibraryConfig
|
|
||||||
import win.taptap.musicmanager.config.UserAccount
|
|
||||||
import win.taptap.musicmanager.db.LibraryRepository
|
|
||||||
import win.taptap.musicmanager.db.MoodRecord
|
|
||||||
import win.taptap.musicmanager.db.MoodRepository
|
|
||||||
import win.taptap.musicmanager.db.PlaylistRepository
|
|
||||||
import win.taptap.musicmanager.db.SongRecord
|
|
||||||
|
|
||||||
data class MoodGenerationStats(
|
|
||||||
val seedCount: Int,
|
|
||||||
val relatedCount: Int,
|
|
||||||
val totalCount: Int,
|
|
||||||
val targetSize: Int,
|
|
||||||
)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Builds the materialized mood playlist.
|
|
||||||
*
|
|
||||||
* Phase 1 has no YT source: the mix is the curated seeds plus related music from
|
|
||||||
* the owner's own music folders. `yt_slots` is stored but only used once the
|
|
||||||
* recommendation phase lands.
|
|
||||||
*/
|
|
||||||
class MoodMixService {
|
|
||||||
|
|
||||||
private val log = LoggerFactory.getLogger(MoodMixService::class.java)
|
|
||||||
|
|
||||||
fun generate(mood: MoodRecord, user: UserAccount, library: LibraryConfig): MoodGenerationStats {
|
|
||||||
val folders = musicFolderIds(user, library)
|
|
||||||
val seedIds = MoodRepository.seedSongIds(mood.playlistId)
|
|
||||||
val seeds = LibraryRepository.songsByIds(seedIds, folders, user.name)
|
|
||||||
|
|
||||||
val seedGenres = (seeds.flatMap { it.genres } + mood.genres)
|
|
||||||
.distinctBy { it.lowercase() }
|
|
||||||
val seedArtistIds = seeds.mapNotNull { it.artistId }.distinct()
|
|
||||||
val seedAlbumIds = seeds.map { it.albumId }.toSet()
|
|
||||||
val query = mood.query?.trim()?.takeIf { it.isNotEmpty() }
|
|
||||||
|
|
||||||
val related = LinkedHashMap<String, SongRecord>()
|
|
||||||
if (mood.expandRelated) {
|
|
||||||
if (seedGenres.isNotEmpty()) {
|
|
||||||
LibraryRepository.songsByGenres(seedGenres, RELATED_LIMIT, folders, user.name)
|
|
||||||
.forEach { related[it.id] = it }
|
|
||||||
}
|
|
||||||
if (seedArtistIds.isNotEmpty()) {
|
|
||||||
LibraryRepository.songsByArtists(seedArtistIds, RELATED_LIMIT, folders, user.name)
|
|
||||||
.forEach { related[it.id] = it }
|
|
||||||
}
|
|
||||||
if (query != null) {
|
|
||||||
LibraryRepository.searchSongs(query, RELATED_LIMIT, 0, folders, user.name)
|
|
||||||
.forEach { related[it.id] = it }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
val seedIdSet = seeds.map { it.id }.toSet()
|
|
||||||
related.keys.removeAll(seedIdSet)
|
|
||||||
|
|
||||||
val random = Random(mood.playlistId.hashCode().toLong() * 31 + mood.generation)
|
|
||||||
val ranked = related.values
|
|
||||||
.shuffled(random)
|
|
||||||
.sortedByDescending { song ->
|
|
||||||
score(song, seedGenres, seedArtistIds, seedAlbumIds, query)
|
|
||||||
}
|
|
||||||
|
|
||||||
val target = max(mood.targetSize, seeds.size).coerceIn(1, MAX_TARGET)
|
|
||||||
val selected = LinkedHashMap<String, SongRecord>()
|
|
||||||
seeds.forEach { selected[it.id] = it }
|
|
||||||
ranked.forEach { song ->
|
|
||||||
if (selected.size < target) selected[song.id] = song
|
|
||||||
}
|
|
||||||
|
|
||||||
// Keep the playlist useful when a mood has only a few seeds or a narrow genre.
|
|
||||||
val hasSignal = seeds.isNotEmpty() || seedGenres.isNotEmpty() || query != null
|
|
||||||
if (mood.expandRelated && hasSignal && selected.size < target) {
|
|
||||||
val fillers = LibraryRepository.randomSongs(
|
|
||||||
size = (target - selected.size) * 3,
|
|
||||||
genre = null,
|
|
||||||
fromYear = null,
|
|
||||||
toYear = null,
|
|
||||||
folderIds = folders,
|
|
||||||
userName = user.name,
|
|
||||||
)
|
|
||||||
fillers.forEach { song ->
|
|
||||||
if (selected.size < target) selected.putIfAbsent(song.id, song)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
PlaylistRepository.replaceSongs(mood.playlistId, selected.keys.toList(), user.name)
|
|
||||||
MoodRepository.markGenerated(mood.playlistId, mood.generation + 1, null)
|
|
||||||
|
|
||||||
val stats = MoodGenerationStats(
|
|
||||||
seedCount = seeds.size,
|
|
||||||
relatedCount = selected.size - seeds.size,
|
|
||||||
totalCount = selected.size,
|
|
||||||
targetSize = target,
|
|
||||||
)
|
|
||||||
log.info(
|
|
||||||
"Mood {} generated: {} seeds, {} related, {} total (target {})",
|
|
||||||
mood.name,
|
|
||||||
stats.seedCount,
|
|
||||||
stats.relatedCount,
|
|
||||||
stats.totalCount,
|
|
||||||
stats.targetSize,
|
|
||||||
)
|
|
||||||
return stats
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun score(
|
|
||||||
song: SongRecord,
|
|
||||||
seedGenres: List<String>,
|
|
||||||
seedArtistIds: List<String>,
|
|
||||||
seedAlbumIds: Set<String>,
|
|
||||||
query: String?,
|
|
||||||
): Double {
|
|
||||||
var score = 0.0
|
|
||||||
if (song.artistId != null && song.artistId in seedArtistIds) score += 6.0
|
|
||||||
if (song.albumId in seedAlbumIds) score += 3.0
|
|
||||||
score += song.genres.count { candidate ->
|
|
||||||
seedGenres.any { it.equals(candidate, ignoreCase = true) }
|
|
||||||
} * 2.0
|
|
||||||
if (song.starredAt != null) score += 1.0
|
|
||||||
score += min(song.playCount, 20) * 0.05
|
|
||||||
if (query != null && song.title.contains(query, ignoreCase = true)) score += 2.0
|
|
||||||
return score
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Long-form folders are deliberately excluded, even when the user can see them. */
|
|
||||||
private fun musicFolderIds(user: UserAccount, library: LibraryConfig): Set<Int> =
|
|
||||||
library.folders
|
|
||||||
.asSequence()
|
|
||||||
.filter { it.type == FolderType.MUSIC && it.id in user.folders }
|
|
||||||
.map { it.id }
|
|
||||||
.toSet()
|
|
||||||
|
|
||||||
private companion object {
|
|
||||||
const val RELATED_LIMIT = 500
|
|
||||||
const val MAX_TARGET = 500
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
package win.taptap.musicmanager.mood
|
|
||||||
|
|
||||||
import win.taptap.musicmanager.db.MoodRepository
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Translates a Symfonium star into a permanent mood seed.
|
|
||||||
*
|
|
||||||
* If a mood session is active, the like belongs to that mood, even when the song
|
|
||||||
* is not in the current mix. Otherwise the song is pinned to every mood that
|
|
||||||
* already contains it, which is a no-op for rotation except that it becomes an
|
|
||||||
* anchor. Manual and promoted seeds are never removed by an unstar.
|
|
||||||
*/
|
|
||||||
object MoodPins {
|
|
||||||
|
|
||||||
fun onStar(userName: String, songId: String) {
|
|
||||||
targets(userName, songId).forEach { playlistId ->
|
|
||||||
if (MoodRepository.addSeed(playlistId, userName, songId, "star")) {
|
|
||||||
MoodRepository.markStale(playlistId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onUnstar(userName: String, songId: String) {
|
|
||||||
targets(userName, songId).forEach { playlistId ->
|
|
||||||
if (MoodRepository.removeSeed(playlistId, userName, songId, origin = "star")) {
|
|
||||||
MoodRepository.markStale(playlistId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun targets(userName: String, songId: String): List<String> {
|
|
||||||
val active = MoodSessionTracker.active(userName)
|
|
||||||
if (active != null && MoodRepository.get(active, userName) != null) {
|
|
||||||
return listOf(active)
|
|
||||||
}
|
|
||||||
return MoodRepository.moodsContainingSong(userName, songId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
package win.taptap.musicmanager.mood
|
|
||||||
|
|
||||||
import java.time.Instant
|
|
||||||
import java.util.concurrent.ConcurrentHashMap
|
|
||||||
import kotlinx.coroutines.CoroutineScope
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import org.slf4j.LoggerFactory
|
|
||||||
import win.taptap.musicmanager.config.LibraryConfig
|
|
||||||
import win.taptap.musicmanager.config.UserAccount
|
|
||||||
import win.taptap.musicmanager.db.MoodRecord
|
|
||||||
import win.taptap.musicmanager.db.MoodRepository
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Owns stale checks and serializes generation per mood. Background refreshes keep
|
|
||||||
* `getPlaylist` fast; an explicit refresh is synchronous for the management UI.
|
|
||||||
*/
|
|
||||||
class MoodService(
|
|
||||||
private val scope: CoroutineScope,
|
|
||||||
private val mixService: MoodMixService = MoodMixService(),
|
|
||||||
) {
|
|
||||||
|
|
||||||
private val log = LoggerFactory.getLogger(MoodService::class.java)
|
|
||||||
private val locks = ConcurrentHashMap<String, Any>()
|
|
||||||
private val running = ConcurrentHashMap.newKeySet<String>()
|
|
||||||
|
|
||||||
fun isStale(mood: MoodRecord): Boolean {
|
|
||||||
val generated = mood.generatedAt?.let { runCatching { Instant.parse(it) }.getOrNull() }
|
|
||||||
?: return true
|
|
||||||
return generated.plusSeconds(mood.refreshHours * 3600L).isBefore(Instant.now())
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Starts one background generation when the mix is older than its TTL. */
|
|
||||||
fun refreshIfStale(mood: MoodRecord, user: UserAccount, library: LibraryConfig) {
|
|
||||||
if (!isStale(mood)) return
|
|
||||||
if (!running.add(mood.playlistId)) return
|
|
||||||
scope.launch {
|
|
||||||
try {
|
|
||||||
generateLocked(mood.playlistId, user, library)
|
|
||||||
} catch (t: Throwable) {
|
|
||||||
log.error("Background mood refresh failed for ${mood.name}", t)
|
|
||||||
} finally {
|
|
||||||
running.remove(mood.playlistId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Synchronous generation used by create, update, seed changes and refreshMood. */
|
|
||||||
fun refreshNow(mood: MoodRecord, user: UserAccount, library: LibraryConfig): MoodGenerationStats =
|
|
||||||
generateLocked(mood.playlistId, user, library)
|
|
||||||
|
|
||||||
private fun generateLocked(
|
|
||||||
playlistId: String,
|
|
||||||
user: UserAccount,
|
|
||||||
library: LibraryConfig,
|
|
||||||
): MoodGenerationStats = synchronized(locks.computeIfAbsent(playlistId) { Any() }) {
|
|
||||||
val mood = MoodRepository.get(playlistId, user.name)
|
|
||||||
?: error("Mood not found: $playlistId")
|
|
||||||
|
|
||||||
try {
|
|
||||||
mixService.generate(mood, user, library)
|
|
||||||
} catch (t: Throwable) {
|
|
||||||
MoodRepository.markError(playlistId, t.message ?: t::class.simpleName.orEmpty())
|
|
||||||
throw t
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
package win.taptap.musicmanager.mood
|
|
||||||
|
|
||||||
import java.time.Duration
|
|
||||||
import java.time.Instant
|
|
||||||
import java.util.concurrent.ConcurrentHashMap
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Symfonium's star request does not carry the playlist it was invoked from.
|
|
||||||
* Opening a mood marks it active, so a like can be attributed to that mood.
|
|
||||||
* The fallback in [MoodPins] handles queued/offline stars without a session.
|
|
||||||
*/
|
|
||||||
object MoodSessionTracker {
|
|
||||||
|
|
||||||
private val ttl: Duration = Duration.ofHours(4)
|
|
||||||
private val sessions = ConcurrentHashMap<String, Session>()
|
|
||||||
|
|
||||||
private data class Session(val playlistId: String, val seenAt: Instant)
|
|
||||||
|
|
||||||
fun activate(userName: String, playlistId: String) {
|
|
||||||
sessions[userName] = Session(playlistId, Instant.now())
|
|
||||||
}
|
|
||||||
|
|
||||||
fun clear(userName: String) {
|
|
||||||
sessions.remove(userName)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun touch(userName: String) {
|
|
||||||
sessions.computeIfPresent(userName) { _, session ->
|
|
||||||
if (session.seenAt.plus(ttl).isBefore(Instant.now())) {
|
|
||||||
null
|
|
||||||
} else {
|
|
||||||
session.copy(seenAt = Instant.now())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun active(userName: String): String? {
|
|
||||||
val session = sessions[userName] ?: return null
|
|
||||||
if (session.seenAt.plus(ttl).isBefore(Instant.now())) {
|
|
||||||
sessions.remove(userName)
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
return session.playlistId
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
package win.taptap.musicmanager.radio
|
||||||
|
|
||||||
|
import java.util.UUID
|
||||||
|
import kotlin.math.max
|
||||||
|
import kotlin.random.Random
|
||||||
|
import org.slf4j.LoggerFactory
|
||||||
|
import win.taptap.musicmanager.api.musicFolderIds
|
||||||
|
import win.taptap.musicmanager.config.LibraryConfig
|
||||||
|
import win.taptap.musicmanager.config.UserAccount
|
||||||
|
import win.taptap.musicmanager.db.LibraryRepository
|
||||||
|
import win.taptap.musicmanager.db.MoodRecord
|
||||||
|
import win.taptap.musicmanager.db.MoodRepository
|
||||||
|
import win.taptap.musicmanager.db.PlaybackSessionRecord
|
||||||
|
import win.taptap.musicmanager.db.RadioRepository
|
||||||
|
import win.taptap.musicmanager.db.SongRecord
|
||||||
|
|
||||||
|
data class StartedSession(
|
||||||
|
val session: PlaybackSessionRecord,
|
||||||
|
val songs: List<SongRecord>,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Server-driven mood radio.
|
||||||
|
*
|
||||||
|
* A batch is a weighted sample of the mood's world: seeds are guaranteed
|
||||||
|
* candidates, related genres/artists and free-text matches shape the pool, and
|
||||||
|
* per-user completions/skips nudge the ranking. Tracks already queued in the
|
||||||
|
* session are never repeated. The client asks for more whenever its buffer is
|
||||||
|
* low, so the queue is always generated with the latest signals.
|
||||||
|
*/
|
||||||
|
class RadioService {
|
||||||
|
|
||||||
|
private val log = LoggerFactory.getLogger(RadioService::class.java)
|
||||||
|
private val random = Random.Default
|
||||||
|
|
||||||
|
fun start(
|
||||||
|
mood: MoodRecord,
|
||||||
|
user: UserAccount,
|
||||||
|
library: LibraryConfig,
|
||||||
|
limit: Int,
|
||||||
|
): StartedSession {
|
||||||
|
val session = RadioRepository.createSession(user.name, mood.id, UUID.randomUUID().toString())
|
||||||
|
val songs = generate(mood, user, library, session.id, emptySet(), limit, persist = true)
|
||||||
|
log.info("Radio session {} started for mood {} with {} tracks", session.id, mood.name, songs.size)
|
||||||
|
return StartedSession(session, songs)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun next(
|
||||||
|
mood: MoodRecord,
|
||||||
|
user: UserAccount,
|
||||||
|
library: LibraryConfig,
|
||||||
|
sessionId: String,
|
||||||
|
excluded: Set<String>,
|
||||||
|
limit: Int,
|
||||||
|
): List<SongRecord> =
|
||||||
|
generate(mood, user, library, sessionId, excluded, limit, persist = true)
|
||||||
|
|
||||||
|
/** Queue preview for the mood screen; nothing is persisted. */
|
||||||
|
fun preview(
|
||||||
|
mood: MoodRecord,
|
||||||
|
user: UserAccount,
|
||||||
|
library: LibraryConfig,
|
||||||
|
limit: Int,
|
||||||
|
): List<SongRecord> =
|
||||||
|
generate(mood, user, library, sessionId = null, excluded = emptySet(), limit, persist = false)
|
||||||
|
|
||||||
|
private fun generate(
|
||||||
|
mood: MoodRecord,
|
||||||
|
user: UserAccount,
|
||||||
|
library: LibraryConfig,
|
||||||
|
sessionId: String?,
|
||||||
|
excluded: Set<String>,
|
||||||
|
requestedLimit: Int,
|
||||||
|
persist: Boolean,
|
||||||
|
): List<SongRecord> {
|
||||||
|
val limit = requestedLimit.coerceIn(1, 50)
|
||||||
|
val folders = user.musicFolderIds(library)
|
||||||
|
if (folders.isEmpty()) return emptyList()
|
||||||
|
|
||||||
|
val sessionSongs = if (sessionId != null && persist) {
|
||||||
|
RadioRepository.queuedSongIds(sessionId)
|
||||||
|
} else {
|
||||||
|
emptySet()
|
||||||
|
}
|
||||||
|
val skip = sessionSongs + excluded
|
||||||
|
|
||||||
|
val seeds = LibraryRepository.songsByIds(
|
||||||
|
MoodRepository.seedSongIds(mood.id),
|
||||||
|
folders,
|
||||||
|
user.name,
|
||||||
|
)
|
||||||
|
val seedIds = seeds.map { it.id }.toSet()
|
||||||
|
val seedGenres = (seeds.flatMap { it.genres } + mood.genres)
|
||||||
|
.map { it.trim() }
|
||||||
|
.filter { it.isNotEmpty() }
|
||||||
|
.distinctBy { it.lowercase() }
|
||||||
|
val seedArtistIds = seeds.mapNotNull { it.artistId }.distinct()
|
||||||
|
val query = mood.query?.trim()?.takeIf { it.isNotEmpty() }
|
||||||
|
|
||||||
|
val candidates = LinkedHashMap<String, SongRecord>()
|
||||||
|
seeds.forEach { candidates[it.id] = it }
|
||||||
|
if (seedGenres.isNotEmpty()) {
|
||||||
|
LibraryRepository.songsByGenres(seedGenres, POOL_LIMIT, folders, user.name)
|
||||||
|
.forEach { candidates[it.id] = it }
|
||||||
|
}
|
||||||
|
if (seedArtistIds.isNotEmpty()) {
|
||||||
|
LibraryRepository.songsByArtists(seedArtistIds, POOL_LIMIT, folders, user.name)
|
||||||
|
.forEach { candidates[it.id] = it }
|
||||||
|
}
|
||||||
|
if (query != null) {
|
||||||
|
LibraryRepository.searchSongs(query, POOL_LIMIT, 0, folders, user.name)
|
||||||
|
.forEach { candidates[it.id] = it }
|
||||||
|
}
|
||||||
|
// A mood with no seeds and no filters still needs a starting point.
|
||||||
|
LibraryRepository.randomSongs(
|
||||||
|
size = POOL_LIMIT,
|
||||||
|
genre = null,
|
||||||
|
fromYear = null,
|
||||||
|
toYear = null,
|
||||||
|
folderIds = folders,
|
||||||
|
userName = user.name,
|
||||||
|
).forEach { candidates[it.id] = it }
|
||||||
|
|
||||||
|
candidates.keys.removeAll(skip)
|
||||||
|
|
||||||
|
// When a session has already heard the whole mood, allow controlled replay
|
||||||
|
// instead of ending with silence.
|
||||||
|
if (candidates.size < limit) {
|
||||||
|
LibraryRepository.randomSongs(
|
||||||
|
size = max(limit * 10, 200),
|
||||||
|
genre = null,
|
||||||
|
fromYear = null,
|
||||||
|
toYear = null,
|
||||||
|
folderIds = folders,
|
||||||
|
userName = user.name,
|
||||||
|
).forEach { song ->
|
||||||
|
if (song.id !in skip || sessionSongs.size > 200) {
|
||||||
|
candidates.putIfAbsent(song.id, song)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val affinity = RadioRepository.affinity(user.name, candidates.keys)
|
||||||
|
val scored = candidates.values.map { song ->
|
||||||
|
song to score(
|
||||||
|
song = song,
|
||||||
|
seedIds = seedIds,
|
||||||
|
seedGenres = seedGenres,
|
||||||
|
seedArtistIds = seedArtistIds,
|
||||||
|
query = query,
|
||||||
|
affinity = affinity[song.id]?.score ?: 0.0,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
val picks = pickDiverse(scored, limit)
|
||||||
|
if (persist && sessionId != null && picks.isNotEmpty()) {
|
||||||
|
RadioRepository.append(sessionId, picks.map { it.id })
|
||||||
|
}
|
||||||
|
return picks
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun score(
|
||||||
|
song: SongRecord,
|
||||||
|
seedIds: Set<String>,
|
||||||
|
seedGenres: List<String>,
|
||||||
|
seedArtistIds: List<String>,
|
||||||
|
query: String?,
|
||||||
|
affinity: Double,
|
||||||
|
): Double {
|
||||||
|
var score = random.nextDouble(0.0, 2.0)
|
||||||
|
if (song.id in seedIds) score += 10.0
|
||||||
|
if (song.artistId != null && song.artistId in seedArtistIds) score += 3.0
|
||||||
|
score += song.genres.count { candidate ->
|
||||||
|
seedGenres.any { it.equals(candidate, ignoreCase = true) }
|
||||||
|
} * 1.5
|
||||||
|
if (query != null && song.title.contains(query, ignoreCase = true)) score += 2.0
|
||||||
|
score += affinity.coerceIn(-6.0, 6.0)
|
||||||
|
return score
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Picks the best remaining candidate, preferring a different artist than the
|
||||||
|
* previous track so a batch does not become one album on repeat.
|
||||||
|
*/
|
||||||
|
private fun pickDiverse(
|
||||||
|
scored: List<Pair<SongRecord, Double>>,
|
||||||
|
limit: Int,
|
||||||
|
): List<SongRecord> {
|
||||||
|
val remaining = scored
|
||||||
|
.sortedWith(compareByDescending<Pair<SongRecord, Double>> { it.second })
|
||||||
|
.toMutableList()
|
||||||
|
val picked = ArrayList<SongRecord>(limit)
|
||||||
|
var lastArtist: String? = null
|
||||||
|
|
||||||
|
while (picked.size < limit && remaining.isNotEmpty()) {
|
||||||
|
val different = remaining.indexOfFirst { it.first.displayArtist != lastArtist }
|
||||||
|
val index = if (different >= 0) different else 0
|
||||||
|
val song = remaining.removeAt(index).first
|
||||||
|
picked += song
|
||||||
|
lastArtist = song.displayArtist
|
||||||
|
}
|
||||||
|
return picked
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val POOL_LIMIT = 400
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
package win.taptap.musicmanager.subsonic
|
|
||||||
|
|
||||||
import java.time.Instant
|
|
||||||
import java.util.concurrent.ConcurrentHashMap
|
|
||||||
|
|
||||||
data class PlayQueueState(
|
|
||||||
val songIds: List<String>,
|
|
||||||
val currentIndex: Int,
|
|
||||||
val positionMs: Long,
|
|
||||||
val changed: String,
|
|
||||||
val changedBy: String,
|
|
||||||
)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Server-side play queue per user. Kept in memory: losing it on restart only means
|
|
||||||
* clients restore their local queue instead, which is acceptable for the MVP.
|
|
||||||
*/
|
|
||||||
object PlayQueueStore {
|
|
||||||
|
|
||||||
private val queues = ConcurrentHashMap<String, PlayQueueState>()
|
|
||||||
|
|
||||||
fun save(userName: String, songIds: List<String>, currentIndex: Int, positionMs: Long) {
|
|
||||||
queues[userName] = PlayQueueState(
|
|
||||||
songIds = songIds,
|
|
||||||
currentIndex = currentIndex.coerceIn(0, (songIds.size - 1).coerceAtLeast(0)),
|
|
||||||
positionMs = positionMs.coerceAtLeast(0),
|
|
||||||
changed = Instant.now().toString(),
|
|
||||||
changedBy = userName,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun get(userName: String): PlayQueueState? = queues[userName]
|
|
||||||
}
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
package win.taptap.musicmanager.subsonic
|
|
||||||
|
|
||||||
import io.ktor.http.Parameters
|
|
||||||
import java.security.MessageDigest
|
|
||||||
import win.taptap.musicmanager.config.UserAccount
|
|
||||||
import win.taptap.musicmanager.config.UsersConfig
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Subsonic authentication.
|
|
||||||
*
|
|
||||||
* Token auth is `md5(password + salt)`; password auth accepts plaintext or the
|
|
||||||
* `enc:` hex encoding. The server therefore needs the plaintext password in memory,
|
|
||||||
* but never persists it.
|
|
||||||
*/
|
|
||||||
class SubsonicAuthenticator(private val users: UsersConfig) {
|
|
||||||
|
|
||||||
fun authenticate(parameters: Parameters): UserAccount? {
|
|
||||||
val userName = parameters["u"] ?: return null
|
|
||||||
val user = users.byName(userName) ?: return null
|
|
||||||
|
|
||||||
val token = parameters["t"]
|
|
||||||
val salt = parameters["s"]
|
|
||||||
if (!token.isNullOrEmpty() && !salt.isNullOrEmpty()) {
|
|
||||||
return if (constantTimeEquals(token, md5Hex(user.password + salt))) user else null
|
|
||||||
}
|
|
||||||
|
|
||||||
val password = parameters["p"] ?: return null
|
|
||||||
val candidate = if (password.startsWith("enc:")) {
|
|
||||||
hexToBytes(password.removePrefix("enc:"))?.toString(Charsets.UTF_8) ?: return null
|
|
||||||
} else {
|
|
||||||
password
|
|
||||||
}
|
|
||||||
|
|
||||||
return if (constantTimeEquals(candidate, user.password)) user else null
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun constantTimeEquals(left: String, right: String): Boolean =
|
|
||||||
MessageDigest.isEqual(left.toByteArray(Charsets.UTF_8), right.toByteArray(Charsets.UTF_8))
|
|
||||||
|
|
||||||
private fun hexToBytes(hex: String): ByteArray? {
|
|
||||||
if (hex.length % 2 != 0) return null
|
|
||||||
return try {
|
|
||||||
ByteArray(hex.length / 2) { index ->
|
|
||||||
hex.substring(index * 2, index * 2 + 2).toInt(16).toByte()
|
|
||||||
}
|
|
||||||
} catch (_: NumberFormatException) {
|
|
||||||
null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
fun md5Hex(value: String): String {
|
|
||||||
val digest = MessageDigest.getInstance("MD5").digest(value.toByteArray(Charsets.UTF_8))
|
|
||||||
return digest.joinToString("") { "%02x".format(it) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
package win.taptap.musicmanager.subsonic
|
|
||||||
|
|
||||||
import io.ktor.server.application.ApplicationCall
|
|
||||||
import io.ktor.server.response.respond
|
|
||||||
import kotlinx.serialization.json.JsonObject
|
|
||||||
import kotlinx.serialization.json.buildJsonObject
|
|
||||||
import kotlinx.serialization.json.put
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The OpenSubsonic JSON envelope. Every endpoint, including errors, responds with
|
|
||||||
* HTTP 200 and this root object.
|
|
||||||
*/
|
|
||||||
object SubsonicEnvelope {
|
|
||||||
|
|
||||||
const val API_VERSION = "1.16.1"
|
|
||||||
const val SERVER_TYPE = "musicmanager"
|
|
||||||
const val SERVER_VERSION = "0.1.0"
|
|
||||||
|
|
||||||
fun ok(payload: JsonObject = JsonObject(emptyMap())): JsonObject = buildJsonObject {
|
|
||||||
put("subsonic-response", buildJsonObject {
|
|
||||||
put("status", "ok")
|
|
||||||
put("version", API_VERSION)
|
|
||||||
put("type", SERVER_TYPE)
|
|
||||||
put("serverVersion", SERVER_VERSION)
|
|
||||||
put("openSubsonic", true)
|
|
||||||
payload.forEach { (key, value) -> put(key, value) }
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fun error(code: Int, message: String): JsonObject = buildJsonObject {
|
|
||||||
put("subsonic-response", buildJsonObject {
|
|
||||||
put("status", "failed")
|
|
||||||
put("version", API_VERSION)
|
|
||||||
put("type", SERVER_TYPE)
|
|
||||||
put("serverVersion", SERVER_VERSION)
|
|
||||||
put("openSubsonic", true)
|
|
||||||
put("error", buildJsonObject {
|
|
||||||
put("code", code)
|
|
||||||
put("message", message)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
suspend fun ApplicationCall.respondSubsonic(payload: JsonObject = JsonObject(emptyMap())) {
|
|
||||||
respond(SubsonicEnvelope.ok(payload))
|
|
||||||
}
|
|
||||||
|
|
||||||
suspend fun ApplicationCall.respondSubsonicError(code: Int, message: String) {
|
|
||||||
respond(SubsonicEnvelope.error(code, message))
|
|
||||||
}
|
|
||||||
@@ -1,172 +0,0 @@
|
|||||||
package win.taptap.musicmanager.subsonic.models
|
|
||||||
|
|
||||||
import kotlinx.serialization.json.JsonArray
|
|
||||||
import kotlinx.serialization.json.JsonObject
|
|
||||||
import kotlinx.serialization.json.JsonPrimitive
|
|
||||||
import kotlinx.serialization.json.add
|
|
||||||
import kotlinx.serialization.json.buildJsonArray
|
|
||||||
import kotlinx.serialization.json.buildJsonObject
|
|
||||||
import kotlinx.serialization.json.put
|
|
||||||
import win.taptap.musicmanager.db.AlbumRecord
|
|
||||||
import win.taptap.musicmanager.db.ArtistRecord
|
|
||||||
import win.taptap.musicmanager.db.GenreRecord
|
|
||||||
import win.taptap.musicmanager.db.MoodRecord
|
|
||||||
import win.taptap.musicmanager.db.PlaylistRecord
|
|
||||||
import win.taptap.musicmanager.db.SongRecord
|
|
||||||
import win.taptap.musicmanager.util.IdGenerator
|
|
||||||
|
|
||||||
const val IGNORED_ARTICLES = "The El La Los Las Le Les"
|
|
||||||
|
|
||||||
fun songJson(song: SongRecord): JsonObject = buildJsonObject {
|
|
||||||
put("id", song.id)
|
|
||||||
put("parent", song.albumId)
|
|
||||||
put("isDir", false)
|
|
||||||
put("title", song.title)
|
|
||||||
put("album", song.albumName)
|
|
||||||
put("artist", song.artistName)
|
|
||||||
put("displayArtist", song.displayArtist)
|
|
||||||
song.trackNumber?.let { put("track", it) }
|
|
||||||
song.year?.let { put("year", it) }
|
|
||||||
song.genres.firstOrNull()?.let { put("genre", it) }
|
|
||||||
song.coverArt?.let { put("coverArt", it) }
|
|
||||||
put("size", song.size)
|
|
||||||
put("contentType", song.contentType)
|
|
||||||
put("suffix", song.suffix)
|
|
||||||
put("duration", song.duration)
|
|
||||||
put("bitRate", song.bitRate)
|
|
||||||
put("path", song.relativePath)
|
|
||||||
put("isVideo", false)
|
|
||||||
put("type", "music")
|
|
||||||
put("albumId", song.albumId)
|
|
||||||
song.artistId?.let { put("artistId", it) }
|
|
||||||
put("discNumber", song.discNumber)
|
|
||||||
put("created", song.created)
|
|
||||||
put("playCount", song.playCount)
|
|
||||||
song.lastPlayedAt?.let { put("played", it) }
|
|
||||||
song.starredAt?.let { put("starred", it) }
|
|
||||||
song.rating?.let { put("userRating", it) }
|
|
||||||
put("artists", buildJsonArray {
|
|
||||||
song.artists.forEach { artist ->
|
|
||||||
add(buildJsonObject {
|
|
||||||
put("id", artist.id)
|
|
||||||
put("name", artist.name)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
})
|
|
||||||
put("genres", stringArray(song.genres))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun albumJson(album: AlbumRecord, songs: List<SongRecord>? = null): JsonObject = buildJsonObject {
|
|
||||||
put("id", album.id)
|
|
||||||
put("name", album.name)
|
|
||||||
album.artistName?.let { put("artist", it) }
|
|
||||||
album.artistId?.let { put("artistId", it) }
|
|
||||||
album.coverArt?.let { put("coverArt", it) }
|
|
||||||
put("songCount", album.songCount)
|
|
||||||
put("duration", album.duration)
|
|
||||||
put("playCount", album.playCount)
|
|
||||||
put("created", album.created)
|
|
||||||
album.year?.let { put("year", it) }
|
|
||||||
album.genres.firstOrNull()?.let { put("genre", it) }
|
|
||||||
album.starredAt?.let { put("starred", it) }
|
|
||||||
album.rating?.let { put("userRating", it) }
|
|
||||||
put("genres", stringArray(album.genres))
|
|
||||||
|
|
||||||
songs?.let { list ->
|
|
||||||
put("song", buildJsonArray { list.forEach { add(songJson(it)) } })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun artistJson(artist: ArtistRecord, albums: List<AlbumRecord>? = null): JsonObject = buildJsonObject {
|
|
||||||
put("id", artist.id)
|
|
||||||
put("name", artist.name)
|
|
||||||
put("albumCount", artist.albumCount)
|
|
||||||
put("sortName", artist.sortName)
|
|
||||||
artist.starredAt?.let { put("starred", it) }
|
|
||||||
artist.rating?.let { put("userRating", it) }
|
|
||||||
|
|
||||||
albums?.let { list ->
|
|
||||||
put("album", buildJsonArray { list.forEach { add(albumJson(it)) } })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun artistIndexArray(artists: List<ArtistRecord>): JsonArray {
|
|
||||||
val groups = artists.groupBy { indexLetter(it.sortName) }
|
|
||||||
val keys = groups.keys.sortedWith(compareBy { if (it == "#") "\uFFFF" else it })
|
|
||||||
|
|
||||||
return buildJsonArray {
|
|
||||||
keys.forEach { key ->
|
|
||||||
add(buildJsonObject {
|
|
||||||
put("name", key)
|
|
||||||
put("artist", buildJsonArray {
|
|
||||||
groups.getValue(key)
|
|
||||||
.sortedBy { IdGenerator.normalize(it.sortName) }
|
|
||||||
.forEach { add(artistJson(it)) }
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun playlistJson(playlist: PlaylistRecord, songs: List<SongRecord>? = null): JsonObject = buildJsonObject {
|
|
||||||
put("id", playlist.id)
|
|
||||||
put("name", playlist.name)
|
|
||||||
playlist.comment?.let { put("comment", it) }
|
|
||||||
put("owner", playlist.owner)
|
|
||||||
put("public", playlist.isPublic)
|
|
||||||
put("songCount", playlist.songCount)
|
|
||||||
put("duration", playlist.duration)
|
|
||||||
put("created", playlist.created)
|
|
||||||
put("changed", playlist.changed)
|
|
||||||
|
|
||||||
songs?.let { list ->
|
|
||||||
put("entry", buildJsonArray { list.forEach { add(songJson(it)) } })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun moodJson(
|
|
||||||
mood: MoodRecord,
|
|
||||||
seeds: List<SongRecord>? = null,
|
|
||||||
songs: List<SongRecord>? = null,
|
|
||||||
): JsonObject = buildJsonObject {
|
|
||||||
put("id", mood.playlistId)
|
|
||||||
put("name", mood.name)
|
|
||||||
mood.comment?.let { put("comment", it) }
|
|
||||||
mood.query?.let { put("query", it) }
|
|
||||||
put("genres", stringArray(mood.genres))
|
|
||||||
put("targetSize", mood.targetSize)
|
|
||||||
put("ytSlots", mood.ytSlots)
|
|
||||||
put("expandRelated", mood.expandRelated)
|
|
||||||
put("refreshHours", mood.refreshHours)
|
|
||||||
mood.generatedAt?.let { put("generatedAt", it) }
|
|
||||||
put("generation", mood.generation)
|
|
||||||
mood.lastError?.let { put("lastError", it) }
|
|
||||||
put("seedCount", mood.seedCount)
|
|
||||||
put("songCount", mood.songCount)
|
|
||||||
put("duration", mood.duration)
|
|
||||||
put("created", mood.created)
|
|
||||||
put("changed", mood.changed)
|
|
||||||
put("owner", mood.owner)
|
|
||||||
|
|
||||||
seeds?.let { list ->
|
|
||||||
put("seed", buildJsonArray { list.forEach { add(songJson(it)) } })
|
|
||||||
}
|
|
||||||
songs?.let { list ->
|
|
||||||
put("entry", buildJsonArray { list.forEach { add(songJson(it)) } })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun genreJson(genre: GenreRecord): JsonObject = buildJsonObject {
|
|
||||||
put("value", genre.value)
|
|
||||||
put("songCount", genre.songCount)
|
|
||||||
put("albumCount", genre.albumCount)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun indexLetter(sortName: String): String {
|
|
||||||
val first = IdGenerator.normalize(sortName).firstOrNull() ?: return "#"
|
|
||||||
return if (first.isLetter()) first.uppercaseChar().toString() else "#"
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun stringArray(values: List<String>): JsonArray = buildJsonArray {
|
|
||||||
values.forEach { add(JsonPrimitive(it)) }
|
|
||||||
}
|
|
||||||
@@ -1,443 +0,0 @@
|
|||||||
package win.taptap.musicmanager.subsonic.routes
|
|
||||||
|
|
||||||
import io.ktor.http.Parameters
|
|
||||||
import io.ktor.server.application.ApplicationCall
|
|
||||||
import io.ktor.server.routing.Route
|
|
||||||
import kotlinx.serialization.json.buildJsonArray
|
|
||||||
import kotlinx.serialization.json.buildJsonObject
|
|
||||||
import kotlinx.serialization.json.put
|
|
||||||
import win.taptap.musicmanager.config.LibraryConfig
|
|
||||||
import win.taptap.musicmanager.config.UsersConfig
|
|
||||||
import win.taptap.musicmanager.db.AlbumRecord
|
|
||||||
import win.taptap.musicmanager.db.LibraryRepository
|
|
||||||
import win.taptap.musicmanager.subsonic.models.IGNORED_ARTICLES
|
|
||||||
import win.taptap.musicmanager.subsonic.models.albumJson
|
|
||||||
import win.taptap.musicmanager.subsonic.models.artistIndexArray
|
|
||||||
import win.taptap.musicmanager.subsonic.models.artistJson
|
|
||||||
import win.taptap.musicmanager.subsonic.models.genreJson
|
|
||||||
import win.taptap.musicmanager.subsonic.models.songJson
|
|
||||||
import win.taptap.musicmanager.subsonic.respondSubsonic
|
|
||||||
import win.taptap.musicmanager.subsonic.respondSubsonicError
|
|
||||||
|
|
||||||
fun Route.browsingRoutes(users: UsersConfig, library: LibraryConfig) {
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/getMusicFolders") { call, user ->
|
|
||||||
val visible = user.visibleFolderIds(library)
|
|
||||||
call.respondSubsonic(
|
|
||||||
buildJsonObject {
|
|
||||||
put("musicFolders", buildJsonObject {
|
|
||||||
put("musicFolder", buildJsonArray {
|
|
||||||
library.folders
|
|
||||||
.filter { it.id in visible }
|
|
||||||
.sortedBy { it.id }
|
|
||||||
.forEach { folder ->
|
|
||||||
add(buildJsonObject {
|
|
||||||
put("id", folder.id)
|
|
||||||
put("name", folder.name)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/getIndexes") { call, user ->
|
|
||||||
val artists = LibraryRepository.artists(user.visibleFolderIds(library), user.name)
|
|
||||||
call.respondSubsonic(
|
|
||||||
buildJsonObject {
|
|
||||||
put("indexes", buildJsonObject {
|
|
||||||
put("ignoredArticles", IGNORED_ARTICLES)
|
|
||||||
put("lastModified", 0)
|
|
||||||
put("index", artistIndexArray(artists))
|
|
||||||
})
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/getArtists") { call, user ->
|
|
||||||
val artists = LibraryRepository.artists(user.visibleFolderIds(library), user.name)
|
|
||||||
call.respondSubsonic(
|
|
||||||
buildJsonObject {
|
|
||||||
put("artists", buildJsonObject {
|
|
||||||
put("ignoredArticles", IGNORED_ARTICLES)
|
|
||||||
put("index", artistIndexArray(artists))
|
|
||||||
})
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/getArtist") { call, user ->
|
|
||||||
val id = call.subsonicParams()["id"]
|
|
||||||
if (id.isNullOrBlank()) {
|
|
||||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val folders = user.visibleFolderIds(library)
|
|
||||||
val artist = LibraryRepository.artist(id, folders, user.name)
|
|
||||||
if (artist == null) {
|
|
||||||
call.respondSubsonicError(70, "Artist not found")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val albums = LibraryRepository.albumsForArtist(id, folders, user.name)
|
|
||||||
call.respondSubsonic(buildJsonObject { put("artist", artistJson(artist, albums)) })
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/getAlbum") { call, user ->
|
|
||||||
val id = call.subsonicParams()["id"]
|
|
||||||
if (id.isNullOrBlank()) {
|
|
||||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val folders = user.visibleFolderIds(library)
|
|
||||||
val album = LibraryRepository.album(id, folders, user.name)
|
|
||||||
if (album == null) {
|
|
||||||
call.respondSubsonicError(70, "Album not found")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val songs = LibraryRepository.albumSongs(id, folders, user.name)
|
|
||||||
call.respondSubsonic(buildJsonObject { put("album", albumJson(album, songs)) })
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/getSong") { call, user ->
|
|
||||||
val id = call.subsonicParams()["id"]
|
|
||||||
if (id.isNullOrBlank()) {
|
|
||||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val song = LibraryRepository.song(id, user.visibleFolderIds(library), user.name)
|
|
||||||
if (song == null) {
|
|
||||||
call.respondSubsonicError(70, "Song not found")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
call.respondSubsonic(buildJsonObject { put("song", songJson(song)) })
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/getMusicDirectory") { call, user ->
|
|
||||||
val parameters = call.subsonicParams()
|
|
||||||
val id = parameters["id"]
|
|
||||||
if (id.isNullOrBlank()) {
|
|
||||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val folders = user.effectiveFolderIds(library, parameters["musicFolderId"])
|
|
||||||
if (id.startsWith("ar-")) {
|
|
||||||
val artist = LibraryRepository.artist(id, folders, user.name)
|
|
||||||
if (artist == null) {
|
|
||||||
call.respondSubsonicError(70, "Artist not found")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val albums = LibraryRepository.albumsForArtist(id, folders, user.name)
|
|
||||||
call.respondSubsonic(
|
|
||||||
buildJsonObject {
|
|
||||||
put("directory", buildJsonObject {
|
|
||||||
put("id", artist.id)
|
|
||||||
put("title", artist.name)
|
|
||||||
put("child", buildJsonArray {
|
|
||||||
albums.forEach { add(albumDirectoryJson(it, artist.id)) }
|
|
||||||
})
|
|
||||||
})
|
|
||||||
},
|
|
||||||
)
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
if (id.startsWith("al-")) {
|
|
||||||
val album = LibraryRepository.album(id, folders, user.name)
|
|
||||||
if (album == null) {
|
|
||||||
call.respondSubsonicError(70, "Album not found")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val songs = LibraryRepository.albumSongs(id, folders, user.name)
|
|
||||||
call.respondSubsonic(
|
|
||||||
buildJsonObject {
|
|
||||||
put("directory", buildJsonObject {
|
|
||||||
put("id", album.id)
|
|
||||||
put("title", album.name)
|
|
||||||
album.artistName?.let { put("artist", it) }
|
|
||||||
album.coverArt?.let { put("coverArt", it) }
|
|
||||||
put("child", buildJsonArray { songs.forEach { add(songJson(it)) } })
|
|
||||||
})
|
|
||||||
},
|
|
||||||
)
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val folderId = id.toIntOrNull()
|
|
||||||
if (folderId == null || folderId !in folders) {
|
|
||||||
call.respondSubsonicError(70, "Directory not found")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val folder = library.byId(folderId) ?: run {
|
|
||||||
call.respondSubsonicError(70, "Directory not found")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
val albums = LibraryRepository.albumList(
|
|
||||||
type = "alphabeticalByName",
|
|
||||||
size = 10_000,
|
|
||||||
offset = 0,
|
|
||||||
fromYear = null,
|
|
||||||
toYear = null,
|
|
||||||
genre = null,
|
|
||||||
folderIds = setOf(folderId),
|
|
||||||
userName = user.name,
|
|
||||||
)
|
|
||||||
|
|
||||||
call.respondSubsonic(
|
|
||||||
buildJsonObject {
|
|
||||||
put("directory", buildJsonObject {
|
|
||||||
put("id", folderId)
|
|
||||||
put("title", folder.name)
|
|
||||||
put("child", buildJsonArray {
|
|
||||||
albums.forEach { add(albumDirectoryJson(it, folderId.toString())) }
|
|
||||||
})
|
|
||||||
})
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
val albumListTypes = setOf(
|
|
||||||
"newest",
|
|
||||||
"recent",
|
|
||||||
"frequent",
|
|
||||||
"random",
|
|
||||||
"alphabeticalByName",
|
|
||||||
"alphabeticalByArtist",
|
|
||||||
"starred",
|
|
||||||
"byYear",
|
|
||||||
"byGenre",
|
|
||||||
)
|
|
||||||
|
|
||||||
for (endpoint in listOf("/getAlbumList2", "/getAlbumList")) {
|
|
||||||
subsonicEndpoint(users, endpoint) { call, user ->
|
|
||||||
val parameters = call.subsonicParams()
|
|
||||||
val type = parameters["type"] ?: "newest"
|
|
||||||
if (type !in albumListTypes) {
|
|
||||||
call.respondSubsonicError(10, "Invalid album list type: $type")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val size = parameters.intParam("size", 10)
|
|
||||||
val offset = parameters.intParam("offset", 0)
|
|
||||||
val fromYear = parameters["fromYear"]?.toIntOrNull()
|
|
||||||
val toYear = parameters["toYear"]?.toIntOrNull()
|
|
||||||
val genre = parameters["genre"]
|
|
||||||
|
|
||||||
val albums = LibraryRepository.albumList(
|
|
||||||
type = type,
|
|
||||||
size = size,
|
|
||||||
offset = offset,
|
|
||||||
fromYear = fromYear,
|
|
||||||
toYear = toYear,
|
|
||||||
genre = genre,
|
|
||||||
folderIds = user.effectiveFolderIds(library, parameters["musicFolderId"]),
|
|
||||||
userName = user.name,
|
|
||||||
)
|
|
||||||
|
|
||||||
val key = if (endpoint == "/getAlbumList2") "albumList2" else "albumList"
|
|
||||||
call.respondSubsonic(
|
|
||||||
buildJsonObject {
|
|
||||||
put(key, buildJsonObject {
|
|
||||||
put("album", buildJsonArray { albums.forEach { add(albumJson(it)) } })
|
|
||||||
})
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/getRandomSongs") { call, user ->
|
|
||||||
val parameters = call.subsonicParams()
|
|
||||||
val songs = LibraryRepository.randomSongs(
|
|
||||||
size = parameters.intParam("size", 10),
|
|
||||||
genre = parameters["genre"],
|
|
||||||
fromYear = parameters["fromYear"]?.toIntOrNull(),
|
|
||||||
toYear = parameters["toYear"]?.toIntOrNull(),
|
|
||||||
folderIds = user.effectiveFolderIds(library, parameters["musicFolderId"]),
|
|
||||||
userName = user.name,
|
|
||||||
)
|
|
||||||
|
|
||||||
call.respondSubsonic(
|
|
||||||
buildJsonObject {
|
|
||||||
put("randomSongs", buildJsonObject {
|
|
||||||
put("song", buildJsonArray { songs.forEach { add(songJson(it)) } })
|
|
||||||
})
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/getGenres") { call, user ->
|
|
||||||
val parameters = call.subsonicParams()
|
|
||||||
val genres = LibraryRepository.genres(
|
|
||||||
user.effectiveFolderIds(library, parameters["musicFolderId"]),
|
|
||||||
)
|
|
||||||
|
|
||||||
call.respondSubsonic(
|
|
||||||
buildJsonObject {
|
|
||||||
put("genres", buildJsonObject {
|
|
||||||
put("genre", buildJsonArray { genres.forEach { add(genreJson(it)) } })
|
|
||||||
})
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/getSongsByGenre") { call, user ->
|
|
||||||
val parameters = call.subsonicParams()
|
|
||||||
val genre = parameters["genre"]
|
|
||||||
if (genre.isNullOrBlank()) {
|
|
||||||
call.respondSubsonicError(10, "Required parameter is missing: genre")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val songs = LibraryRepository.songsByGenre(
|
|
||||||
genre = genre,
|
|
||||||
size = parameters.intParam("count", 10),
|
|
||||||
offset = parameters.intParam("offset", 0),
|
|
||||||
folderIds = user.effectiveFolderIds(library, parameters["musicFolderId"]),
|
|
||||||
userName = user.name,
|
|
||||||
)
|
|
||||||
|
|
||||||
call.respondSubsonic(
|
|
||||||
buildJsonObject {
|
|
||||||
put("songsByGenre", buildJsonObject {
|
|
||||||
put("song", buildJsonArray { songs.forEach { add(songJson(it)) } })
|
|
||||||
})
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
for (endpoint in listOf("/getStarred2", "/getStarred")) {
|
|
||||||
subsonicEndpoint(users, endpoint) { call, user ->
|
|
||||||
val parameters = call.subsonicParams()
|
|
||||||
val starred = LibraryRepository.starred(
|
|
||||||
userName = user.name,
|
|
||||||
folderIds = user.effectiveFolderIds(library, parameters["musicFolderId"]),
|
|
||||||
)
|
|
||||||
|
|
||||||
val key = if (endpoint == "/getStarred2") "starred2" else "starred"
|
|
||||||
call.respondSubsonic(
|
|
||||||
buildJsonObject {
|
|
||||||
put(key, buildJsonObject {
|
|
||||||
put("artist", buildJsonArray { starred.artists.forEach { add(artistJson(it)) } })
|
|
||||||
put("album", buildJsonArray { starred.albums.forEach { add(albumJson(it)) } })
|
|
||||||
put("song", buildJsonArray { starred.songs.forEach { add(songJson(it)) } })
|
|
||||||
})
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// No external metadata provider yet, but clients expect a valid empty response.
|
|
||||||
for (endpoint in listOf("/getArtistInfo2", "/getArtistInfo")) {
|
|
||||||
subsonicEndpoint(users, endpoint) { call, _ ->
|
|
||||||
val key = if (endpoint == "/getArtistInfo2") "artistInfo2" else "artistInfo"
|
|
||||||
call.respondSubsonic(
|
|
||||||
buildJsonObject {
|
|
||||||
put(key, buildJsonObject {
|
|
||||||
put("biography", "")
|
|
||||||
put("similarArtist", buildJsonArray { })
|
|
||||||
})
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (endpoint in listOf("/getAlbumInfo2", "/getAlbumInfo")) {
|
|
||||||
subsonicEndpoint(users, endpoint) { call, _ ->
|
|
||||||
val key = if (endpoint == "/getAlbumInfo2") "albumInfo2" else "albumInfo"
|
|
||||||
call.respondSubsonic(buildJsonObject { put(key, buildJsonObject { }) })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (endpoint in listOf("/getSimilarSongs2", "/getSimilarSongs")) {
|
|
||||||
subsonicEndpoint(users, endpoint) { call, _ ->
|
|
||||||
val key = if (endpoint == "/getSimilarSongs2") "similarSongs2" else "similarSongs"
|
|
||||||
call.respondSubsonic(
|
|
||||||
buildJsonObject {
|
|
||||||
put(key, buildJsonObject { put("song", buildJsonArray { }) })
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/getTopSongs") { call, _ ->
|
|
||||||
call.respondSubsonic(
|
|
||||||
buildJsonObject {
|
|
||||||
put("topSongs", buildJsonObject { put("song", buildJsonArray { }) })
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/search3") { call, user ->
|
|
||||||
val parameters = call.subsonicParams()
|
|
||||||
val query = parameters["query"].orEmpty()
|
|
||||||
val folders = user.effectiveFolderIds(library, parameters["musicFolderId"])
|
|
||||||
val all = query.isBlank() || query == "*"
|
|
||||||
|
|
||||||
val artistCount = parameters.intParam("artistCount", 20)
|
|
||||||
val artistOffset = parameters.intParam("artistOffset", 0, minimum = 0)
|
|
||||||
val albumCount = parameters.intParam("albumCount", 20)
|
|
||||||
val albumOffset = parameters.intParam("albumOffset", 0, minimum = 0)
|
|
||||||
val songCount = parameters.intParam("songCount", 20)
|
|
||||||
val songOffset = parameters.intParam("songOffset", 0, minimum = 0)
|
|
||||||
|
|
||||||
val artists = if (all) {
|
|
||||||
LibraryRepository.artists(folders, user.name)
|
|
||||||
.drop(artistOffset)
|
|
||||||
.take(artistCount)
|
|
||||||
} else {
|
|
||||||
LibraryRepository.searchArtists(query, artistCount, artistOffset, folders, user.name)
|
|
||||||
}
|
|
||||||
val albums = if (all) {
|
|
||||||
LibraryRepository.allAlbums(albumCount, albumOffset, folders, user.name)
|
|
||||||
} else {
|
|
||||||
LibraryRepository.searchAlbums(query, albumCount, albumOffset, folders, user.name)
|
|
||||||
}
|
|
||||||
val songs = if (all) {
|
|
||||||
LibraryRepository.allSongs(songCount, songOffset, folders, user.name)
|
|
||||||
} else {
|
|
||||||
LibraryRepository.searchSongs(query, songCount, songOffset, folders, user.name)
|
|
||||||
}
|
|
||||||
|
|
||||||
call.respondSubsonic(
|
|
||||||
buildJsonObject {
|
|
||||||
put("searchResult3", buildJsonObject {
|
|
||||||
put("artist", buildJsonArray { artists.forEach { add(artistJson(it)) } })
|
|
||||||
put("album", buildJsonArray { albums.forEach { add(albumJson(it)) } })
|
|
||||||
put("song", buildJsonArray { songs.forEach { add(songJson(it)) } })
|
|
||||||
})
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun albumDirectoryJson(album: AlbumRecord, parentId: String) = buildJsonObject {
|
|
||||||
put("id", album.id)
|
|
||||||
put("parent", parentId)
|
|
||||||
put("title", album.name)
|
|
||||||
put("isDir", true)
|
|
||||||
put("album", album.name)
|
|
||||||
album.artistName?.let { put("artist", it) }
|
|
||||||
album.artistId?.let { put("artistId", it) }
|
|
||||||
album.coverArt?.let { put("coverArt", it) }
|
|
||||||
put("songCount", album.songCount)
|
|
||||||
put("duration", album.duration)
|
|
||||||
put("created", album.created)
|
|
||||||
album.year?.let { put("year", it) }
|
|
||||||
album.genres.firstOrNull()?.let { put("genre", it) }
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun Parameters.intParam(name: String, default: Int, minimum: Int = 0): Int {
|
|
||||||
val raw = this[name] ?: return default
|
|
||||||
val parsed = raw.toIntOrNull() ?: return default
|
|
||||||
return parsed.coerceIn(minimum, 500)
|
|
||||||
}
|
|
||||||
@@ -1,264 +0,0 @@
|
|||||||
package win.taptap.musicmanager.subsonic.routes
|
|
||||||
|
|
||||||
import io.ktor.server.routing.Route
|
|
||||||
import kotlinx.serialization.json.add
|
|
||||||
import kotlinx.serialization.json.buildJsonArray
|
|
||||||
import kotlinx.serialization.json.buildJsonObject
|
|
||||||
import kotlinx.serialization.json.put
|
|
||||||
import win.taptap.musicmanager.config.LibraryConfig
|
|
||||||
import win.taptap.musicmanager.config.UsersConfig
|
|
||||||
import win.taptap.musicmanager.db.LibraryRepository
|
|
||||||
import win.taptap.musicmanager.db.UserStateRepository
|
|
||||||
import win.taptap.musicmanager.mood.MoodPins
|
|
||||||
import win.taptap.musicmanager.mood.MoodSessionTracker
|
|
||||||
import win.taptap.musicmanager.subsonic.models.songJson
|
|
||||||
import win.taptap.musicmanager.subsonic.respondSubsonic
|
|
||||||
import win.taptap.musicmanager.subsonic.respondSubsonicError
|
|
||||||
|
|
||||||
/** Per-user interaction: scrobbling, stars, ratings, bookmarks and lyrics. */
|
|
||||||
fun Route.interactionRoutes(users: UsersConfig, library: LibraryConfig) {
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/scrobble") { call, user ->
|
|
||||||
val parameters = call.subsonicParams()
|
|
||||||
val ids = parameters.getAll("id").orEmpty().filter { it.isNotBlank() }
|
|
||||||
if (ids.isEmpty()) {
|
|
||||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val submission = parameters["submission"]?.toBooleanStrictOrNull() ?: true
|
|
||||||
val folders = user.effectiveFolderIds(library, parameters["musicFolderId"])
|
|
||||||
|
|
||||||
for (id in ids) {
|
|
||||||
if (LibraryRepository.song(id, folders, user.name) == null) {
|
|
||||||
call.respondSubsonicError(70, "Song not found")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
UserStateRepository.scrobble(user.name, id, submission)
|
|
||||||
}
|
|
||||||
MoodSessionTracker.touch(user.name)
|
|
||||||
|
|
||||||
call.respondSubsonic()
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/star") { call, user ->
|
|
||||||
val parameters = call.subsonicParams()
|
|
||||||
val folders = user.effectiveFolderIds(library, parameters["musicFolderId"])
|
|
||||||
|
|
||||||
val songIds = parameters.getAll("id").orEmpty().filter { it.isNotBlank() }
|
|
||||||
val albumIds = parameters.getAll("albumId").orEmpty().filter { it.isNotBlank() }
|
|
||||||
val artistIds = parameters.getAll("artistId").orEmpty().filter { it.isNotBlank() }
|
|
||||||
|
|
||||||
if (songIds.isEmpty() && albumIds.isEmpty() && artistIds.isEmpty()) {
|
|
||||||
call.respondSubsonicError(10, "Required parameter is missing: id, albumId or artistId")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!validateVisible(songIds, albumIds, artistIds, folders, user.name)) {
|
|
||||||
call.respondSubsonicError(70, "Item not found")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
songIds.forEach { songId ->
|
|
||||||
UserStateRepository.starSong(user.name, songId)
|
|
||||||
if (songId.startsWith("sg-")) MoodPins.onStar(user.name, songId)
|
|
||||||
}
|
|
||||||
albumIds.forEach { UserStateRepository.starItem(user.name, "album", it) }
|
|
||||||
artistIds.forEach { UserStateRepository.starItem(user.name, "artist", it) }
|
|
||||||
|
|
||||||
call.respondSubsonic()
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/unstar") { call, user ->
|
|
||||||
val parameters = call.subsonicParams()
|
|
||||||
val folders = user.effectiveFolderIds(library, parameters["musicFolderId"])
|
|
||||||
|
|
||||||
val songIds = parameters.getAll("id").orEmpty().filter { it.isNotBlank() }
|
|
||||||
val albumIds = parameters.getAll("albumId").orEmpty().filter { it.isNotBlank() }
|
|
||||||
val artistIds = parameters.getAll("artistId").orEmpty().filter { it.isNotBlank() }
|
|
||||||
|
|
||||||
if (songIds.isEmpty() && albumIds.isEmpty() && artistIds.isEmpty()) {
|
|
||||||
call.respondSubsonicError(10, "Required parameter is missing: id, albumId or artistId")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!validateVisible(songIds, albumIds, artistIds, folders, user.name)) {
|
|
||||||
call.respondSubsonicError(70, "Item not found")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
songIds.forEach { songId ->
|
|
||||||
UserStateRepository.unstarSong(user.name, songId)
|
|
||||||
if (songId.startsWith("sg-")) MoodPins.onUnstar(user.name, songId)
|
|
||||||
}
|
|
||||||
albumIds.forEach { UserStateRepository.unstarItem(user.name, "album", it) }
|
|
||||||
artistIds.forEach { UserStateRepository.unstarItem(user.name, "artist", it) }
|
|
||||||
|
|
||||||
call.respondSubsonic()
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/setRating") { call, user ->
|
|
||||||
val parameters = call.subsonicParams()
|
|
||||||
val id = parameters["id"]
|
|
||||||
if (id.isNullOrBlank()) {
|
|
||||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val rawRating = parameters["rating"]
|
|
||||||
val rating = rawRating?.toIntOrNull()
|
|
||||||
if (rating == null || rating !in 0..5) {
|
|
||||||
call.respondSubsonicError(10, "Required parameter is missing or invalid: rating")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val folders = user.effectiveFolderIds(library, parameters["musicFolderId"])
|
|
||||||
val storedRating = rating.takeIf { it > 0 }
|
|
||||||
|
|
||||||
when {
|
|
||||||
id.startsWith("sg-") -> {
|
|
||||||
if (LibraryRepository.song(id, folders, user.name) == null) {
|
|
||||||
call.respondSubsonicError(70, "Song not found")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
UserStateRepository.setSongRating(user.name, id, storedRating)
|
|
||||||
}
|
|
||||||
id.startsWith("al-") -> {
|
|
||||||
if (LibraryRepository.album(id, folders, user.name) == null) {
|
|
||||||
call.respondSubsonicError(70, "Album not found")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
UserStateRepository.setItemRating(user.name, "album", id, storedRating)
|
|
||||||
}
|
|
||||||
id.startsWith("ar-") -> {
|
|
||||||
if (LibraryRepository.artist(id, folders, user.name) == null) {
|
|
||||||
call.respondSubsonicError(70, "Artist not found")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
UserStateRepository.setItemRating(user.name, "artist", id, storedRating)
|
|
||||||
}
|
|
||||||
else -> {
|
|
||||||
call.respondSubsonicError(70, "Item not found")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
call.respondSubsonic()
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/getBookmarks") { call, user ->
|
|
||||||
val folders = user.effectiveFolderIds(library, call.subsonicParams()["musicFolderId"])
|
|
||||||
|
|
||||||
val bookmarks = UserStateRepository.bookmarks(user.name).mapNotNull { bookmark ->
|
|
||||||
val song = LibraryRepository.song(bookmark.songId, folders, user.name) ?: return@mapNotNull null
|
|
||||||
buildJsonObject {
|
|
||||||
put("position", bookmark.positionMs)
|
|
||||||
put("username", user.name)
|
|
||||||
put("created", bookmark.updatedAt)
|
|
||||||
put("changed", bookmark.updatedAt)
|
|
||||||
put("entry", songJson(song))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
call.respondSubsonic(
|
|
||||||
buildJsonObject {
|
|
||||||
put("bookmarks", buildJsonObject {
|
|
||||||
put("bookmark", buildJsonArray { bookmarks.forEach { add(it) } })
|
|
||||||
})
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/createBookmark") { call, user ->
|
|
||||||
val parameters = call.subsonicParams()
|
|
||||||
val id = parameters["id"]
|
|
||||||
if (id.isNullOrBlank()) {
|
|
||||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val position = parameters["position"]?.toLongOrNull()
|
|
||||||
if (position == null || position < 0) {
|
|
||||||
call.respondSubsonicError(10, "Required parameter is missing or invalid: position")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
if (LibraryRepository.song(id, user.effectiveFolderIds(library, parameters["musicFolderId"]), user.name) == null) {
|
|
||||||
call.respondSubsonicError(70, "Song not found")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
UserStateRepository.createBookmark(user.name, id, position)
|
|
||||||
call.respondSubsonic()
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/deleteBookmark") { call, user ->
|
|
||||||
val id = call.subsonicParams()["id"]
|
|
||||||
if (id.isNullOrBlank()) {
|
|
||||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
UserStateRepository.deleteBookmark(user.name, id)
|
|
||||||
call.respondSubsonic()
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/getLyricsBySongId") { call, user ->
|
|
||||||
val parameters = call.subsonicParams()
|
|
||||||
val id = parameters["id"]
|
|
||||||
if (id.isNullOrBlank()) {
|
|
||||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val folders = user.effectiveFolderIds(library, parameters["musicFolderId"])
|
|
||||||
val song = LibraryRepository.song(id, folders, user.name)
|
|
||||||
if (song == null) {
|
|
||||||
call.respondSubsonicError(70, "Song not found")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val lyrics = LibraryRepository.lyrics(id, folders)
|
|
||||||
val lines = lyrics.orEmpty()
|
|
||||||
.lines()
|
|
||||||
.map { it.trim() }
|
|
||||||
.filter { it.isNotEmpty() }
|
|
||||||
|
|
||||||
call.respondSubsonic(
|
|
||||||
buildJsonObject {
|
|
||||||
if (lines.isEmpty()) {
|
|
||||||
put("lyricsList", buildJsonObject { })
|
|
||||||
} else {
|
|
||||||
put("lyricsList", buildJsonObject {
|
|
||||||
put("structuredLyrics", buildJsonArray {
|
|
||||||
add(buildJsonObject {
|
|
||||||
put("displayArtist", song.displayArtist)
|
|
||||||
put("displayTitle", song.title)
|
|
||||||
put("lang", "")
|
|
||||||
put("synced", false)
|
|
||||||
put("line", buildJsonArray {
|
|
||||||
lines.forEach { line ->
|
|
||||||
add(buildJsonObject { put("value", line) })
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun validateVisible(
|
|
||||||
songIds: List<String>,
|
|
||||||
albumIds: List<String>,
|
|
||||||
artistIds: List<String>,
|
|
||||||
folderIds: Set<Int>,
|
|
||||||
userName: String,
|
|
||||||
): Boolean {
|
|
||||||
if (songIds.any { LibraryRepository.song(it, folderIds, userName) == null }) return false
|
|
||||||
if (albumIds.any { LibraryRepository.album(it, folderIds, userName) == null }) return false
|
|
||||||
if (artistIds.any { LibraryRepository.artist(it, folderIds, userName) == null }) return false
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
@@ -1,168 +0,0 @@
|
|||||||
package win.taptap.musicmanager.subsonic.routes
|
|
||||||
|
|
||||||
import io.ktor.http.ContentType
|
|
||||||
import io.ktor.http.HttpHeaders
|
|
||||||
import io.ktor.http.HttpStatusCode
|
|
||||||
import io.ktor.server.response.respond
|
|
||||||
import io.ktor.server.response.respondFile
|
|
||||||
import io.ktor.server.response.respondOutputStream
|
|
||||||
import io.ktor.server.routing.Route
|
|
||||||
import java.net.URLEncoder
|
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
import kotlinx.coroutines.withContext
|
|
||||||
import org.slf4j.LoggerFactory
|
|
||||||
import win.taptap.musicmanager.config.LibraryConfig
|
|
||||||
import win.taptap.musicmanager.config.UsersConfig
|
|
||||||
import win.taptap.musicmanager.db.LibraryRepository
|
|
||||||
import win.taptap.musicmanager.mood.MoodSessionTracker
|
|
||||||
import win.taptap.musicmanager.scanner.CoverArtService
|
|
||||||
import win.taptap.musicmanager.subsonic.respondSubsonicError
|
|
||||||
import win.taptap.musicmanager.transcoding.FfmpegTranscoder
|
|
||||||
|
|
||||||
private val log = LoggerFactory.getLogger("win.taptap.musicmanager.MediaRoutes")
|
|
||||||
|
|
||||||
fun Route.mediaRoutes(
|
|
||||||
users: UsersConfig,
|
|
||||||
library: LibraryConfig,
|
|
||||||
coverArtService: CoverArtService,
|
|
||||||
transcoder: FfmpegTranscoder,
|
|
||||||
) {
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/stream") { call, user ->
|
|
||||||
val parameters = call.subsonicParams()
|
|
||||||
val id = parameters["id"]
|
|
||||||
if (id.isNullOrBlank()) {
|
|
||||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val rawMaxBitRate = parameters["maxBitRate"]
|
|
||||||
val maxBitRate = rawMaxBitRate?.toIntOrNull()
|
|
||||||
if (rawMaxBitRate != null && (maxBitRate == null || maxBitRate < 0)) {
|
|
||||||
call.respondSubsonicError(10, "Invalid maxBitRate")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val rawTimeOffset = parameters["timeOffset"]
|
|
||||||
val timeOffset = rawTimeOffset?.toIntOrNull()
|
|
||||||
if (rawTimeOffset != null && (timeOffset == null || timeOffset < 0)) {
|
|
||||||
call.respondSubsonicError(10, "Invalid timeOffset")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
val offset = timeOffset ?: 0
|
|
||||||
val format = parameters["format"]
|
|
||||||
|
|
||||||
val resolved = LibraryRepository.resolveSong(
|
|
||||||
id,
|
|
||||||
user.visibleFolderIds(library),
|
|
||||||
user.name,
|
|
||||||
library,
|
|
||||||
)
|
|
||||||
if (resolved == null) {
|
|
||||||
call.respondSubsonicError(70, "Song not found")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
MoodSessionTracker.touch(user.name)
|
|
||||||
|
|
||||||
if (!transcoder.shouldTranscode(resolved.song.bitRate, maxBitRate, format, offset)) {
|
|
||||||
call.respondFile(resolved.file.toFile())
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val process = try {
|
|
||||||
transcoder.start(resolved.file, maxBitRate, offset)
|
|
||||||
} catch (e: Exception) {
|
|
||||||
log.error("Failed to start ffmpeg for {}", resolved.file, e)
|
|
||||||
call.respondSubsonicError(0, "Transcoding failed")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
call.response.headers.append(HttpHeaders.CacheControl, "no-store")
|
|
||||||
call.respondOutputStream(ContentType.parse("audio/mpeg")) {
|
|
||||||
val output = this
|
|
||||||
withContext(Dispatchers.IO) {
|
|
||||||
process.inputStream.use { input -> input.copyTo(output) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
transcoder.stop(process)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/download") { call, user ->
|
|
||||||
val id = call.subsonicParams()["id"]
|
|
||||||
if (id.isNullOrBlank()) {
|
|
||||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val resolved = LibraryRepository.resolveSong(
|
|
||||||
id,
|
|
||||||
user.visibleFolderIds(library),
|
|
||||||
user.name,
|
|
||||||
library,
|
|
||||||
)
|
|
||||||
if (resolved == null) {
|
|
||||||
call.respondSubsonicError(70, "Song not found")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
call.response.headers.append(
|
|
||||||
HttpHeaders.ContentDisposition,
|
|
||||||
contentDisposition(resolved.file.fileName.toString()),
|
|
||||||
)
|
|
||||||
call.respondFile(resolved.file.toFile())
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/getCoverArt") { call, user ->
|
|
||||||
val parameters = call.subsonicParams()
|
|
||||||
val id = parameters["id"]
|
|
||||||
if (id.isNullOrBlank()) {
|
|
||||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val requestedSize = parameters["size"]
|
|
||||||
val size = requestedSize?.toIntOrNull()
|
|
||||||
if (requestedSize != null && (size == null || size !in 1..2048)) {
|
|
||||||
call.respondSubsonicError(10, "Invalid cover size")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val folders = user.visibleFolderIds(library)
|
|
||||||
val albumId = if (id.startsWith("sg-")) {
|
|
||||||
LibraryRepository.albumIdForSong(id, folders)
|
|
||||||
} else if (LibraryRepository.album(id, folders, user.name) != null) {
|
|
||||||
id
|
|
||||||
} else {
|
|
||||||
null
|
|
||||||
}
|
|
||||||
|
|
||||||
if (albumId == null) {
|
|
||||||
call.respond(HttpStatusCode.NotFound)
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val cover = if (size == null) {
|
|
||||||
coverArtService.coverFile(albumId)
|
|
||||||
} else {
|
|
||||||
coverArtService.resizedCover(albumId, size)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (cover == null) {
|
|
||||||
call.respond(HttpStatusCode.NotFound)
|
|
||||||
} else {
|
|
||||||
call.respondFile(cover.toFile())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun contentDisposition(fileName: String): String {
|
|
||||||
val encoded = URLEncoder.encode(fileName, Charsets.UTF_8).replace("+", "%20")
|
|
||||||
val ascii = fileName.map { character ->
|
|
||||||
if (character.code in 32..126 && character != '"' && character != '\\') character else '_'
|
|
||||||
}.joinToString("")
|
|
||||||
|
|
||||||
return "attachment; filename=\"$ascii\"; filename*=UTF-8''$encoded"
|
|
||||||
}
|
|
||||||
@@ -1,265 +0,0 @@
|
|||||||
package win.taptap.musicmanager.subsonic.routes
|
|
||||||
|
|
||||||
import io.ktor.server.application.ApplicationCall
|
|
||||||
import io.ktor.server.routing.Route
|
|
||||||
import kotlinx.serialization.json.JsonObject
|
|
||||||
import kotlinx.serialization.json.add
|
|
||||||
import kotlinx.serialization.json.buildJsonArray
|
|
||||||
import kotlinx.serialization.json.buildJsonObject
|
|
||||||
import kotlinx.serialization.json.put
|
|
||||||
import org.slf4j.LoggerFactory
|
|
||||||
import win.taptap.musicmanager.config.LibraryConfig
|
|
||||||
import win.taptap.musicmanager.config.UserAccount
|
|
||||||
import win.taptap.musicmanager.config.UsersConfig
|
|
||||||
import win.taptap.musicmanager.db.LibraryRepository
|
|
||||||
import win.taptap.musicmanager.db.MoodRecord
|
|
||||||
import win.taptap.musicmanager.db.MoodRepository
|
|
||||||
import win.taptap.musicmanager.db.PlaylistRepository
|
|
||||||
import win.taptap.musicmanager.mood.MoodService
|
|
||||||
import win.taptap.musicmanager.subsonic.models.moodJson
|
|
||||||
import win.taptap.musicmanager.subsonic.respondSubsonic
|
|
||||||
import win.taptap.musicmanager.subsonic.respondSubsonicError
|
|
||||||
|
|
||||||
private val log = LoggerFactory.getLogger("win.taptap.musicmanager.MoodRoutes")
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Mood management endpoints. These are custom OpenSubsonic endpoints used by the
|
|
||||||
* built-in web UI; Symfonium only sees the resulting playlists.
|
|
||||||
*/
|
|
||||||
fun Route.moodRoutes(
|
|
||||||
users: UsersConfig,
|
|
||||||
library: LibraryConfig,
|
|
||||||
moodService: MoodService,
|
|
||||||
) {
|
|
||||||
subsonicEndpoint(users, "/getMoods") { call, user ->
|
|
||||||
val moods = MoodRepository.list(user.name)
|
|
||||||
call.respondSubsonic(
|
|
||||||
buildJsonObject {
|
|
||||||
put("moods", buildJsonObject {
|
|
||||||
put("mood", buildJsonArray { moods.forEach { add(moodJson(it)) } })
|
|
||||||
})
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/getMood") { call, user ->
|
|
||||||
val mood = call.requireMood(user) ?: return@subsonicEndpoint
|
|
||||||
call.respondSubsonic(buildJsonObject { put("mood", detail(mood, user, library)) })
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/createMood") { call, user ->
|
|
||||||
val parameters = call.subsonicParams()
|
|
||||||
val name = parameters["name"]?.trim()?.takeIf { it.isNotEmpty() }
|
|
||||||
if (name == null) {
|
|
||||||
call.respondSubsonicError(10, "Required parameter is missing: name")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val folders = user.musicFolderIds(library)
|
|
||||||
val seedIds = parameters.getAll("songId").orEmpty()
|
|
||||||
.filter { it.isNotBlank() }
|
|
||||||
.filter { LibraryRepository.song(it, folders, user.name) != null }
|
|
||||||
.distinct()
|
|
||||||
|
|
||||||
val mood = MoodRepository.create(
|
|
||||||
userName = user.name,
|
|
||||||
name = name.take(200),
|
|
||||||
comment = parameters["comment"]?.trim()?.takeIf { it.isNotEmpty() },
|
|
||||||
query = parameters["query"]?.trim()?.takeIf { it.isNotEmpty() },
|
|
||||||
genres = genres(parameters),
|
|
||||||
targetSize = intParam(parameters["targetSize"], 50, 1, 500),
|
|
||||||
ytSlots = intParam(parameters["ytSlots"], 0, 0, 500),
|
|
||||||
expandRelated = boolParam(parameters["expandRelated"], true),
|
|
||||||
refreshHours = intParam(parameters["refreshHours"], 24, 1, 720),
|
|
||||||
seedSongIds = seedIds,
|
|
||||||
)
|
|
||||||
|
|
||||||
regenerate(moodService, mood, user, library)
|
|
||||||
call.respondSubsonic(buildJsonObject { put("mood", detail(refreshed(mood), user, library)) })
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/updateMood") { call, user ->
|
|
||||||
val mood = call.requireMood(user) ?: return@subsonicEndpoint
|
|
||||||
val parameters = call.subsonicParams()
|
|
||||||
|
|
||||||
val name = parameters["name"]?.trim()?.takeIf { it.isNotEmpty() } ?: mood.name
|
|
||||||
val comment = if (parameters.contains("comment")) {
|
|
||||||
parameters["comment"]?.trim()?.takeIf { it.isNotEmpty() }
|
|
||||||
} else {
|
|
||||||
mood.comment
|
|
||||||
}
|
|
||||||
val query = if (parameters.contains("query")) {
|
|
||||||
parameters["query"]?.trim()?.takeIf { it.isNotEmpty() }
|
|
||||||
} else {
|
|
||||||
mood.query
|
|
||||||
}
|
|
||||||
val genres = if (parameters.contains("genre") || parameters.contains("genres")) {
|
|
||||||
genres(parameters)
|
|
||||||
} else {
|
|
||||||
mood.genres
|
|
||||||
}
|
|
||||||
|
|
||||||
val updated = MoodRepository.update(
|
|
||||||
playlistId = mood.playlistId,
|
|
||||||
userName = user.name,
|
|
||||||
name = name.take(200),
|
|
||||||
comment = comment,
|
|
||||||
query = query,
|
|
||||||
genres = genres,
|
|
||||||
targetSize = intParam(parameters["targetSize"], mood.targetSize, 1, 500),
|
|
||||||
ytSlots = intParam(parameters["ytSlots"], mood.ytSlots, 0, 500),
|
|
||||||
expandRelated = boolParam(parameters["expandRelated"], mood.expandRelated),
|
|
||||||
refreshHours = intParam(parameters["refreshHours"], mood.refreshHours, 1, 720),
|
|
||||||
)
|
|
||||||
|
|
||||||
if (!updated) {
|
|
||||||
call.respondSubsonicError(70, "Mood not found")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val refreshedMood = MoodRepository.get(mood.playlistId, user.name) ?: mood
|
|
||||||
regenerate(moodService, refreshedMood, user, library)
|
|
||||||
call.respondSubsonic(
|
|
||||||
buildJsonObject {
|
|
||||||
put("mood", detail(refreshed(refreshedMood), user, library))
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/deleteMood") { call, user ->
|
|
||||||
val mood = call.requireMood(user) ?: return@subsonicEndpoint
|
|
||||||
MoodRepository.delete(mood.playlistId, user.name)
|
|
||||||
call.respondSubsonic()
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/refreshMood") { call, user ->
|
|
||||||
val mood = call.requireMood(user) ?: return@subsonicEndpoint
|
|
||||||
regenerate(moodService, mood, user, library)
|
|
||||||
call.respondSubsonic(buildJsonObject { put("mood", detail(refreshed(mood), user, library)) })
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/promotePlaylistToMood") { call, user ->
|
|
||||||
val parameters = call.subsonicParams()
|
|
||||||
val playlistId = parameters["playlistId"]
|
|
||||||
if (playlistId.isNullOrBlank()) {
|
|
||||||
call.respondSubsonicError(10, "Required parameter is missing: playlistId")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val mood = MoodRepository.promote(
|
|
||||||
userName = user.name,
|
|
||||||
playlistId = playlistId,
|
|
||||||
query = parameters["query"]?.trim()?.takeIf { it.isNotEmpty() },
|
|
||||||
genres = genres(parameters),
|
|
||||||
targetSize = intParam(parameters["targetSize"], 50, 1, 500),
|
|
||||||
ytSlots = intParam(parameters["ytSlots"], 0, 0, 500),
|
|
||||||
expandRelated = boolParam(parameters["expandRelated"], true),
|
|
||||||
refreshHours = intParam(parameters["refreshHours"], 24, 1, 720),
|
|
||||||
musicFolderIds = user.musicFolderIds(library),
|
|
||||||
)
|
|
||||||
|
|
||||||
if (mood == null) {
|
|
||||||
call.respondSubsonicError(70, "Playlist not found")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
regenerate(moodService, mood, user, library)
|
|
||||||
call.respondSubsonic(buildJsonObject { put("mood", detail(refreshed(mood), user, library)) })
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/addMoodSeed") { call, user ->
|
|
||||||
val mood = call.requireMood(user) ?: return@subsonicEndpoint
|
|
||||||
val parameters = call.subsonicParams()
|
|
||||||
val songId = parameters["songId"]
|
|
||||||
if (songId.isNullOrBlank()) {
|
|
||||||
call.respondSubsonicError(10, "Required parameter is missing: songId")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val folders = user.musicFolderIds(library)
|
|
||||||
if (LibraryRepository.song(songId, folders, user.name) == null) {
|
|
||||||
call.respondSubsonicError(70, "Song not found")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
MoodRepository.addSeed(mood.playlistId, user.name, songId, "manual")
|
|
||||||
regenerate(moodService, mood, user, library)
|
|
||||||
call.respondSubsonic(buildJsonObject { put("mood", detail(refreshed(mood), user, library)) })
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/removeMoodSeed") { call, user ->
|
|
||||||
val mood = call.requireMood(user) ?: return@subsonicEndpoint
|
|
||||||
val songId = call.subsonicParams()["songId"]
|
|
||||||
if (songId.isNullOrBlank()) {
|
|
||||||
call.respondSubsonicError(10, "Required parameter is missing: songId")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
MoodRepository.removeSeed(mood.playlistId, user.name, songId)
|
|
||||||
regenerate(moodService, mood, user, library)
|
|
||||||
call.respondSubsonic(buildJsonObject { put("mood", detail(refreshed(mood), user, library)) })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun ApplicationCall.moodId(): String? = subsonicParams()["id"]?.takeIf { it.isNotBlank() }
|
|
||||||
|
|
||||||
private suspend fun ApplicationCall.requireMood(
|
|
||||||
user: UserAccount,
|
|
||||||
): MoodRecord? {
|
|
||||||
val id = moodId()
|
|
||||||
if (id == null) {
|
|
||||||
respondSubsonicError(10, "Required parameter is missing: id")
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
val mood = MoodRepository.get(id, user.name)
|
|
||||||
if (mood == null) {
|
|
||||||
respondSubsonicError(70, "Mood not found")
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
return mood
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun detail(mood: MoodRecord, user: UserAccount, library: LibraryConfig): JsonObject {
|
|
||||||
val folders = user.musicFolderIds(library)
|
|
||||||
val seedIds = MoodRepository.seedSongIds(mood.playlistId)
|
|
||||||
val seeds = LibraryRepository.songsByIds(seedIds, folders, user.name)
|
|
||||||
val entryIds = PlaylistRepository.songIds(mood.playlistId)
|
|
||||||
val entries = LibraryRepository.songsByIds(entryIds, folders, user.name)
|
|
||||||
return moodJson(mood, seeds = seeds, songs = entries)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun refreshed(mood: MoodRecord): MoodRecord =
|
|
||||||
MoodRepository.get(mood.playlistId, mood.owner) ?: mood
|
|
||||||
|
|
||||||
private fun regenerate(
|
|
||||||
moodService: MoodService,
|
|
||||||
mood: MoodRecord,
|
|
||||||
user: UserAccount,
|
|
||||||
library: LibraryConfig,
|
|
||||||
) {
|
|
||||||
// A generation failure is recorded on the mood; management actions still succeed.
|
|
||||||
runCatching {
|
|
||||||
moodService.refreshNow(mood, user, library)
|
|
||||||
}.onFailure {
|
|
||||||
log.warn("Mood generation failed for ${mood.name}", it)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun genres(parameters: io.ktor.http.Parameters): List<String> =
|
|
||||||
(parameters.getAll("genre").orEmpty() +
|
|
||||||
parameters["genres"].orEmpty().split(','))
|
|
||||||
.map { it.trim() }
|
|
||||||
.filter { it.isNotEmpty() }
|
|
||||||
.distinct()
|
|
||||||
.take(20)
|
|
||||||
|
|
||||||
private fun intParam(raw: String?, default: Int, minimum: Int, maximum: Int): Int =
|
|
||||||
(raw?.toIntOrNull() ?: default).coerceIn(minimum, maximum)
|
|
||||||
|
|
||||||
private fun boolParam(raw: String?, default: Boolean): Boolean = when (raw?.lowercase()) {
|
|
||||||
null -> default
|
|
||||||
"true", "1", "yes", "on" -> true
|
|
||||||
"false", "0", "no", "off" -> false
|
|
||||||
else -> default
|
|
||||||
}
|
|
||||||
@@ -1,67 +0,0 @@
|
|||||||
package win.taptap.musicmanager.subsonic.routes
|
|
||||||
|
|
||||||
import io.ktor.server.routing.Route
|
|
||||||
import kotlinx.serialization.json.add
|
|
||||||
import kotlinx.serialization.json.buildJsonArray
|
|
||||||
import kotlinx.serialization.json.buildJsonObject
|
|
||||||
import kotlinx.serialization.json.put
|
|
||||||
import win.taptap.musicmanager.config.LibraryConfig
|
|
||||||
import win.taptap.musicmanager.config.UsersConfig
|
|
||||||
import win.taptap.musicmanager.db.LibraryRepository
|
|
||||||
import win.taptap.musicmanager.subsonic.PlayQueueStore
|
|
||||||
import win.taptap.musicmanager.subsonic.models.songJson
|
|
||||||
import win.taptap.musicmanager.subsonic.respondSubsonic
|
|
||||||
|
|
||||||
/** Optional server-side queue used by clients that support queue hand-off. */
|
|
||||||
fun Route.playQueueRoutes(users: UsersConfig, library: LibraryConfig) {
|
|
||||||
|
|
||||||
for (endpoint in listOf("/savePlayQueue", "/savePlayQueueByIndex")) {
|
|
||||||
subsonicEndpoint(users, endpoint) { call, user ->
|
|
||||||
val parameters = call.subsonicParams()
|
|
||||||
val folders = user.visibleFolderIds(library)
|
|
||||||
|
|
||||||
val requestedIds = parameters.getAll("id").orEmpty().filter { it.isNotBlank() }
|
|
||||||
val visible = requestedIds.filter { LibraryRepository.song(it, folders, user.name) != null }
|
|
||||||
|
|
||||||
val currentId = parameters["current"]
|
|
||||||
val explicitIndex = parameters["currentIndex"]?.toIntOrNull()
|
|
||||||
val currentIndex = explicitIndex
|
|
||||||
?: currentId?.let { visible.indexOf(it) }?.takeIf { it >= 0 }
|
|
||||||
?: 0
|
|
||||||
|
|
||||||
val position = parameters["position"]?.toLongOrNull() ?: 0L
|
|
||||||
PlayQueueStore.save(user.name, visible, currentIndex, position)
|
|
||||||
|
|
||||||
call.respondSubsonic()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (endpoint in listOf("/getPlayQueue", "/getPlayQueueByIndex")) {
|
|
||||||
subsonicEndpoint(users, endpoint) { call, user ->
|
|
||||||
val state = PlayQueueStore.get(user.name)
|
|
||||||
val folders = user.visibleFolderIds(library)
|
|
||||||
val songs = LibraryRepository.songsByIds(state?.songIds.orEmpty(), folders, user.name)
|
|
||||||
val byIndex = endpoint == "/getPlayQueueByIndex"
|
|
||||||
|
|
||||||
val queue = buildJsonObject {
|
|
||||||
put("entry", buildJsonArray { songs.forEach { add(songJson(it)) } })
|
|
||||||
put("position", state?.positionMs ?: 0L)
|
|
||||||
put("username", user.name)
|
|
||||||
put("changed", state?.changed.orEmpty())
|
|
||||||
put("changedBy", state?.changedBy.orEmpty())
|
|
||||||
|
|
||||||
if (byIndex) {
|
|
||||||
put("currentIndex", state?.currentIndex ?: 0)
|
|
||||||
} else {
|
|
||||||
state?.songIds?.getOrNull(state.currentIndex)?.let { put("current", it) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
call.respondSubsonic(
|
|
||||||
buildJsonObject {
|
|
||||||
put(if (byIndex) "playQueueByIndex" else "playQueue", queue)
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,189 +0,0 @@
|
|||||||
package win.taptap.musicmanager.subsonic.routes
|
|
||||||
|
|
||||||
import io.ktor.server.routing.Route
|
|
||||||
import kotlinx.serialization.json.add
|
|
||||||
import kotlinx.serialization.json.buildJsonArray
|
|
||||||
import kotlinx.serialization.json.buildJsonObject
|
|
||||||
import kotlinx.serialization.json.put
|
|
||||||
import win.taptap.musicmanager.config.LibraryConfig
|
|
||||||
import win.taptap.musicmanager.config.UsersConfig
|
|
||||||
import win.taptap.musicmanager.db.LibraryRepository
|
|
||||||
import win.taptap.musicmanager.db.MoodRepository
|
|
||||||
import win.taptap.musicmanager.db.PlaylistRepository
|
|
||||||
import win.taptap.musicmanager.mood.MoodService
|
|
||||||
import win.taptap.musicmanager.mood.MoodSessionTracker
|
|
||||||
import win.taptap.musicmanager.subsonic.models.playlistJson
|
|
||||||
import win.taptap.musicmanager.subsonic.respondSubsonic
|
|
||||||
import win.taptap.musicmanager.subsonic.respondSubsonicError
|
|
||||||
|
|
||||||
/** Playlist CRUD. Visibility: owned playlists plus all public playlists. */
|
|
||||||
fun Route.playlistRoutes(users: UsersConfig, library: LibraryConfig, moodService: MoodService) {
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/getPlaylists") { call, user ->
|
|
||||||
val playlists = PlaylistRepository.visibleTo(user.name)
|
|
||||||
|
|
||||||
call.respondSubsonic(
|
|
||||||
buildJsonObject {
|
|
||||||
put("playlists", buildJsonObject {
|
|
||||||
put("playlist", buildJsonArray { playlists.forEach { add(playlistJson(it)) } })
|
|
||||||
})
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/getPlaylist") { call, user ->
|
|
||||||
val id = call.subsonicParams()["id"]
|
|
||||||
if (id.isNullOrBlank()) {
|
|
||||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val playlist = PlaylistRepository.get(id, user.name)
|
|
||||||
if (playlist == null) {
|
|
||||||
call.respondSubsonicError(70, "Playlist not found")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
if (playlist.kind == "mood") {
|
|
||||||
MoodSessionTracker.activate(user.name, playlist.id)
|
|
||||||
MoodRepository.get(playlist.id, user.name)?.let { mood ->
|
|
||||||
moodService.refreshIfStale(mood, user, library)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
MoodSessionTracker.clear(user.name)
|
|
||||||
}
|
|
||||||
|
|
||||||
val folders = if (playlist.kind == "mood") {
|
|
||||||
user.musicFolderIds(library)
|
|
||||||
} else {
|
|
||||||
user.visibleFolderIds(library)
|
|
||||||
}
|
|
||||||
val songs = LibraryRepository.songsByIds(PlaylistRepository.songIds(id), folders, user.name)
|
|
||||||
|
|
||||||
call.respondSubsonic(buildJsonObject { put("playlist", playlistJson(playlist, songs)) })
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/createPlaylist") { call, user ->
|
|
||||||
val parameters = call.subsonicParams()
|
|
||||||
val folders = user.visibleFolderIds(library)
|
|
||||||
val requestedSongs = parameters.getAll("songId").orEmpty()
|
|
||||||
.filter { it.isNotBlank() }
|
|
||||||
.filter { LibraryRepository.song(it, folders, user.name) != null }
|
|
||||||
|
|
||||||
val playlistId = parameters["playlistId"]
|
|
||||||
if (!playlistId.isNullOrBlank()) {
|
|
||||||
val existing = PlaylistRepository.get(playlistId, user.name)
|
|
||||||
if (existing == null) {
|
|
||||||
call.respondSubsonicError(70, "Playlist not found")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
if (existing.owner != user.name) {
|
|
||||||
call.respondSubsonicError(50, "Not authorized")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
if (existing.kind == "mood") {
|
|
||||||
call.respondSubsonicError(50, "Mood playlists are generated by the server")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val newName = parameters["name"]?.takeIf { it.isNotBlank() }
|
|
||||||
PlaylistRepository.update(
|
|
||||||
playlistId = playlistId,
|
|
||||||
userName = user.name,
|
|
||||||
name = newName,
|
|
||||||
comment = null,
|
|
||||||
isPublic = null,
|
|
||||||
addSongIds = emptyList(),
|
|
||||||
removeIndices = emptyList(),
|
|
||||||
)
|
|
||||||
PlaylistRepository.replaceSongs(playlistId, requestedSongs, user.name)
|
|
||||||
|
|
||||||
val updated = PlaylistRepository.get(playlistId, user.name)!!
|
|
||||||
call.respondSubsonic(buildJsonObject { put("playlist", playlistJson(updated)) })
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val name = parameters["name"]
|
|
||||||
if (name.isNullOrBlank()) {
|
|
||||||
call.respondSubsonicError(10, "Required parameter is missing: name")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val playlist = PlaylistRepository.create(user.name, name.trim(), requestedSongs)
|
|
||||||
call.respondSubsonic(buildJsonObject { put("playlist", playlistJson(playlist)) })
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/updatePlaylist") { call, user ->
|
|
||||||
val parameters = call.subsonicParams()
|
|
||||||
val playlistId = parameters["playlistId"]
|
|
||||||
if (playlistId.isNullOrBlank()) {
|
|
||||||
call.respondSubsonicError(10, "Required parameter is missing: playlistId")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val existing = PlaylistRepository.get(playlistId, user.name)
|
|
||||||
if (existing == null) {
|
|
||||||
call.respondSubsonicError(70, "Playlist not found")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
if (existing.owner != user.name) {
|
|
||||||
call.respondSubsonicError(50, "Not authorized")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val folders = user.visibleFolderIds(library)
|
|
||||||
val addSongs = parameters.getAll("songIdToAdd").orEmpty()
|
|
||||||
.filter { it.isNotBlank() }
|
|
||||||
.filter { LibraryRepository.song(it, folders, user.name) != null }
|
|
||||||
val removeIndices = parameters.getAll("songIndexToRemove").orEmpty()
|
|
||||||
.mapNotNull { it.toIntOrNull() }
|
|
||||||
.filter { it >= 0 }
|
|
||||||
|
|
||||||
if (existing.kind == "mood" &&
|
|
||||||
(parameters.getAll("songIdToAdd").orEmpty().any { it.isNotBlank() } ||
|
|
||||||
removeIndices.isNotEmpty() ||
|
|
||||||
parameters.contains("public"))
|
|
||||||
) {
|
|
||||||
call.respondSubsonicError(50, "Mood playlists are generated by the server")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val updated = PlaylistRepository.update(
|
|
||||||
playlistId = playlistId,
|
|
||||||
userName = user.name,
|
|
||||||
name = parameters["name"]?.takeIf { it.isNotBlank() },
|
|
||||||
comment = parameters["comment"],
|
|
||||||
isPublic = parameters["public"]?.toBooleanStrictOrNull(),
|
|
||||||
addSongIds = addSongs,
|
|
||||||
removeIndices = removeIndices,
|
|
||||||
)
|
|
||||||
|
|
||||||
if (!updated) {
|
|
||||||
call.respondSubsonicError(50, "Not authorized")
|
|
||||||
} else {
|
|
||||||
call.respondSubsonic()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/deletePlaylist") { call, user ->
|
|
||||||
val playlistId = call.subsonicParams()["id"]
|
|
||||||
if (playlistId.isNullOrBlank()) {
|
|
||||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val existing = PlaylistRepository.get(playlistId, user.name)
|
|
||||||
if (existing == null) {
|
|
||||||
call.respondSubsonicError(70, "Playlist not found")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
if (existing.owner != user.name) {
|
|
||||||
call.respondSubsonicError(50, "Not authorized")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
PlaylistRepository.delete(playlistId, user.name)
|
|
||||||
MoodSessionTracker.clear(user.name)
|
|
||||||
call.respondSubsonic()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
package win.taptap.musicmanager.subsonic.routes
|
|
||||||
|
|
||||||
import io.ktor.http.ContentType
|
|
||||||
import io.ktor.http.HttpMethod
|
|
||||||
import io.ktor.http.Parameters
|
|
||||||
import io.ktor.server.application.ApplicationCall
|
|
||||||
import io.ktor.server.request.contentType
|
|
||||||
import io.ktor.server.request.httpMethod
|
|
||||||
import io.ktor.server.request.receiveParameters
|
|
||||||
import io.ktor.util.AttributeKey
|
|
||||||
import win.taptap.musicmanager.config.FolderType
|
|
||||||
import win.taptap.musicmanager.config.LibraryConfig
|
|
||||||
import win.taptap.musicmanager.config.UserAccount
|
|
||||||
|
|
||||||
val CurrentUserKey = AttributeKey<UserAccount>("musicmanager.currentUser")
|
|
||||||
val SubsonicParametersKey = AttributeKey<Parameters>("musicmanager.parameters")
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Visible folders, optionally narrowed to a client-supplied `musicFolderId`.
|
|
||||||
* An unknown or invisible id yields an empty set, which all queries treat as "nothing".
|
|
||||||
*/
|
|
||||||
fun UserAccount.effectiveFolderIds(library: LibraryConfig, musicFolderId: String?): Set<Int> {
|
|
||||||
val visible = visibleFolderIds(library)
|
|
||||||
val requested = musicFolderId?.toIntOrNull() ?: return visible
|
|
||||||
return if (requested in visible) setOf(requested) else emptySet()
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Music-only roots. Moods never draw from shared long-form folders. */
|
|
||||||
fun UserAccount.musicFolderIds(library: LibraryConfig): Set<Int> =
|
|
||||||
library.folders
|
|
||||||
.asSequence()
|
|
||||||
.filter { it.type == FolderType.MUSIC && it.id in folders }
|
|
||||||
.map { it.id }
|
|
||||||
.toSet()
|
|
||||||
|
|
||||||
/** Parameters captured during authentication, so POST bodies are only read once. */
|
|
||||||
fun ApplicationCall.subsonicParams(): Parameters =
|
|
||||||
attributes.getOrNull(SubsonicParametersKey) ?: request.queryParameters
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Unified parameter access for Subsonic: query parameters plus URL-encoded form
|
|
||||||
* bodies (the `formPost` OpenSubsonic extension).
|
|
||||||
*/
|
|
||||||
suspend fun subsonicParameters(call: ApplicationCall): Parameters {
|
|
||||||
val query = call.request.queryParameters
|
|
||||||
if (call.request.httpMethod != HttpMethod.Post) return query
|
|
||||||
|
|
||||||
val contentType = call.request.contentType()
|
|
||||||
if (!contentType.match(ContentType.Application.FormUrlEncoded)) return query
|
|
||||||
|
|
||||||
val form = call.receiveParameters()
|
|
||||||
return Parameters.build {
|
|
||||||
query.forEach { name, values -> values.forEach { append(name, it) } }
|
|
||||||
form.forEach { name, values -> values.forEach { append(name, it) } }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
package win.taptap.musicmanager.subsonic.routes
|
|
||||||
|
|
||||||
import io.ktor.server.application.ApplicationCall
|
|
||||||
import io.ktor.server.routing.Route
|
|
||||||
import io.ktor.server.routing.get
|
|
||||||
import io.ktor.server.routing.post
|
|
||||||
import win.taptap.musicmanager.config.UserAccount
|
|
||||||
import win.taptap.musicmanager.config.UsersConfig
|
|
||||||
import win.taptap.musicmanager.subsonic.SubsonicAuthenticator
|
|
||||||
import win.taptap.musicmanager.subsonic.respondSubsonicError
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Registers a Subsonic endpoint for both `/{path}` and `/{path}.view`, and for both
|
|
||||||
* GET and POST form posts (the `formPost` OpenSubsonic extension).
|
|
||||||
* Authentication failures always return HTTP 200 with error code 40.
|
|
||||||
*/
|
|
||||||
internal fun Route.subsonicEndpoint(
|
|
||||||
users: UsersConfig,
|
|
||||||
path: String,
|
|
||||||
handler: suspend (ApplicationCall, UserAccount) -> Unit,
|
|
||||||
) {
|
|
||||||
val authenticator = SubsonicAuthenticator(users)
|
|
||||||
val paths = if (path.endsWith(".view")) listOf(path) else listOf(path, "$path.view")
|
|
||||||
|
|
||||||
suspend fun handle(call: ApplicationCall) {
|
|
||||||
val parameters = subsonicParameters(call)
|
|
||||||
val user = authenticator.authenticate(parameters)
|
|
||||||
if (user == null) {
|
|
||||||
call.respondSubsonicError(40, "Wrong username or password")
|
|
||||||
} else {
|
|
||||||
call.attributes.put(CurrentUserKey, user)
|
|
||||||
call.attributes.put(SubsonicParametersKey, parameters)
|
|
||||||
handler(call, user)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
paths.forEach { routePath ->
|
|
||||||
get(routePath) { handle(call) }
|
|
||||||
post(routePath) { handle(call) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
package win.taptap.musicmanager.subsonic.routes
|
|
||||||
|
|
||||||
import io.ktor.server.routing.Route
|
|
||||||
import io.ktor.server.routing.route
|
|
||||||
import win.taptap.musicmanager.config.LibraryConfig
|
|
||||||
import win.taptap.musicmanager.config.UsersConfig
|
|
||||||
import win.taptap.musicmanager.mood.MoodService
|
|
||||||
import win.taptap.musicmanager.scanner.CoverArtService
|
|
||||||
import win.taptap.musicmanager.scanner.ScanStatus
|
|
||||||
import win.taptap.musicmanager.transcoding.FfmpegTranscoder
|
|
||||||
|
|
||||||
/** Authenticated `/rest` subtree. */
|
|
||||||
fun Route.subsonicRoutes(
|
|
||||||
users: UsersConfig,
|
|
||||||
library: LibraryConfig,
|
|
||||||
coverArtService: CoverArtService,
|
|
||||||
transcoder: FfmpegTranscoder,
|
|
||||||
moodService: MoodService,
|
|
||||||
startScan: () -> Boolean,
|
|
||||||
scanStatus: () -> ScanStatus,
|
|
||||||
) {
|
|
||||||
route("/rest") {
|
|
||||||
systemRoutes(users, library, startScan, scanStatus)
|
|
||||||
browsingRoutes(users, library)
|
|
||||||
mediaRoutes(users, library, coverArtService, transcoder)
|
|
||||||
interactionRoutes(users, library)
|
|
||||||
playlistRoutes(users, library, moodService)
|
|
||||||
moodRoutes(users, library, moodService)
|
|
||||||
playQueueRoutes(users, library)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,174 +0,0 @@
|
|||||||
package win.taptap.musicmanager.subsonic.routes
|
|
||||||
|
|
||||||
import io.ktor.server.routing.Route
|
|
||||||
import kotlinx.serialization.json.JsonArray
|
|
||||||
import kotlinx.serialization.json.JsonPrimitive
|
|
||||||
import kotlinx.serialization.json.add
|
|
||||||
import kotlinx.serialization.json.buildJsonArray
|
|
||||||
import kotlinx.serialization.json.buildJsonObject
|
|
||||||
import kotlinx.serialization.json.put
|
|
||||||
import win.taptap.musicmanager.config.LibraryConfig
|
|
||||||
import win.taptap.musicmanager.config.UserAccount
|
|
||||||
import win.taptap.musicmanager.config.UsersConfig
|
|
||||||
import win.taptap.musicmanager.scanner.ScanStatus
|
|
||||||
import win.taptap.musicmanager.subsonic.respondSubsonic
|
|
||||||
import win.taptap.musicmanager.subsonic.respondSubsonicError
|
|
||||||
|
|
||||||
/** System endpoints from the MVP specification. */
|
|
||||||
fun Route.systemRoutes(
|
|
||||||
users: UsersConfig,
|
|
||||||
library: LibraryConfig,
|
|
||||||
startScan: () -> Boolean,
|
|
||||||
scanStatus: () -> ScanStatus,
|
|
||||||
) {
|
|
||||||
subsonicEndpoint(users, "/ping") { call, _ ->
|
|
||||||
call.respondSubsonic()
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/getLicense") { call, _ ->
|
|
||||||
call.respondSubsonic(
|
|
||||||
buildJsonObject {
|
|
||||||
put("license", buildJsonObject { put("valid", true) })
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/getOpenSubsonicExtensions") { call, _ ->
|
|
||||||
call.respondSubsonic(
|
|
||||||
buildJsonObject {
|
|
||||||
put(
|
|
||||||
"openSubsonicExtensions",
|
|
||||||
buildJsonArray {
|
|
||||||
add(extension("formPost", 1))
|
|
||||||
add(extension("songLyrics", 1))
|
|
||||||
add(extension("transcodeOffset", 1))
|
|
||||||
},
|
|
||||||
)
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/startScan") { call, user ->
|
|
||||||
if (!user.admin) {
|
|
||||||
call.respondSubsonicError(50, "Not authorized")
|
|
||||||
} else {
|
|
||||||
startScan()
|
|
||||||
call.respondSubsonic()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/getScanStatus") { call, _ ->
|
|
||||||
val status = scanStatus()
|
|
||||||
call.respondSubsonic(
|
|
||||||
buildJsonObject {
|
|
||||||
put("scanStatus", buildJsonObject {
|
|
||||||
put("scanning", status.scanning)
|
|
||||||
put("count", status.count)
|
|
||||||
})
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/getUser") { call, currentUser ->
|
|
||||||
val username = call.subsonicParams()["username"]
|
|
||||||
if (username.isNullOrBlank()) {
|
|
||||||
call.respondSubsonicError(10, "Required parameter is missing: username")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
if (username != currentUser.name && !currentUser.admin) {
|
|
||||||
call.respondSubsonicError(50, "Not authorized")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
val requested = users.byName(username)
|
|
||||||
if (requested == null) {
|
|
||||||
call.respondSubsonicError(70, "User not found")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
call.respondSubsonic(buildJsonObject { put("user", userJson(requested, library)) })
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/getInternetRadioStations") { call, _ ->
|
|
||||||
call.respondSubsonic(
|
|
||||||
buildJsonObject {
|
|
||||||
put("internetRadioStations", buildJsonObject {
|
|
||||||
put("internetRadioStation", buildJsonArray { })
|
|
||||||
})
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
for (endpoint in listOf(
|
|
||||||
"/createInternetRadioStation",
|
|
||||||
"/updateInternetRadioStation",
|
|
||||||
"/deleteInternetRadioStation",
|
|
||||||
)) {
|
|
||||||
subsonicEndpoint(users, endpoint) { call, _ ->
|
|
||||||
call.respondSubsonicError(0, "Internet radio is not supported")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/jukeboxControl") { call, _ ->
|
|
||||||
if (call.subsonicParams()["action"] != "status") {
|
|
||||||
call.respondSubsonicError(0, "Jukebox is not supported")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
call.respondSubsonic(
|
|
||||||
buildJsonObject {
|
|
||||||
put("jukeboxStatus", buildJsonObject {
|
|
||||||
put("currentIndex", 0)
|
|
||||||
put("playing", false)
|
|
||||||
put("gain", 1.0)
|
|
||||||
put("position", 0)
|
|
||||||
})
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
subsonicEndpoint(users, "/getUsers") { call, currentUser ->
|
|
||||||
if (!currentUser.admin) {
|
|
||||||
call.respondSubsonicError(50, "Not authorized")
|
|
||||||
return@subsonicEndpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
call.respondSubsonic(
|
|
||||||
buildJsonObject {
|
|
||||||
put("users", buildJsonObject {
|
|
||||||
put("user", buildJsonArray {
|
|
||||||
users.users.forEach { add(userJson(it, library)) }
|
|
||||||
})
|
|
||||||
})
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun userJson(user: UserAccount, library: LibraryConfig) = buildJsonObject {
|
|
||||||
put("username", user.name)
|
|
||||||
put("scrobblingEnabled", true)
|
|
||||||
put("adminRole", user.admin)
|
|
||||||
put("settingsRole", user.admin)
|
|
||||||
put("downloadRole", true)
|
|
||||||
put("uploadRole", false)
|
|
||||||
put("playlistRole", true)
|
|
||||||
put("coverArtRole", true)
|
|
||||||
put("commentRole", false)
|
|
||||||
put("podcastRole", false)
|
|
||||||
put("streamRole", true)
|
|
||||||
put("jukeboxRole", false)
|
|
||||||
put("shareRole", false)
|
|
||||||
put("videoConversionRole", false)
|
|
||||||
put("folder", folderIds(user.visibleFolderIds(library)))
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun folderIds(ids: Set<Int>): JsonArray = buildJsonArray {
|
|
||||||
ids.sorted().forEach { add(JsonPrimitive(it)) }
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun extension(name: String, version: Int) = buildJsonObject {
|
|
||||||
put("name", name)
|
|
||||||
put("versions", buildJsonArray { add(kotlinx.serialization.json.JsonPrimitive(version)) })
|
|
||||||
}
|
|
||||||
@@ -5,7 +5,7 @@ import java.text.Normalizer
|
|||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Deterministic IDs for the Symfonium offline cache.
|
* Deterministic IDs for clients' offline caches.
|
||||||
*
|
*
|
||||||
* Normalization is frozen: NFC, trimmed, collapsed whitespace, lowercase. Changing
|
* Normalization is frozen: NFC, trimmed, collapsed whitespace, lowercase. Changing
|
||||||
* it changes every ID and forces clients to re-download their library.
|
* it changes every ID and forces clients to re-download their library.
|
||||||
@@ -27,8 +27,8 @@ object IdGenerator {
|
|||||||
fun songId(folderId: Int, relativePath: String): String =
|
fun songId(folderId: Int, relativePath: String): String =
|
||||||
"sg-" + hash("$folderId:${normalizePath(relativePath)}")
|
"sg-" + hash("$folderId:${normalizePath(relativePath)}")
|
||||||
|
|
||||||
fun playlistId(owner: String, name: String, createdAt: String): String =
|
fun moodId(owner: String, name: String, createdAt: String): String =
|
||||||
"pl-" + hash("${normalize(owner)}|${normalize(name)}|$createdAt")
|
"mo-" + hash("${normalize(owner)}|${normalize(name)}|$createdAt")
|
||||||
|
|
||||||
private fun normalizePath(path: String): String = path
|
private fun normalizePath(path: String): String = path
|
||||||
.replace('\\', '/')
|
.replace('\\', '/')
|
||||||
|
|||||||
@@ -0,0 +1,164 @@
|
|||||||
|
-- Native mood-first API.
|
||||||
|
--
|
||||||
|
-- The OpenSubsonic layer is gone, so moods no longer need to be materialized as
|
||||||
|
-- playlists. They become first-class rows, radio queues are generated per
|
||||||
|
-- playback session, and the old playlist tables are dropped.
|
||||||
|
|
||||||
|
CREATE TABLE moods_v2 (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
owner TEXT NOT NULL REFERENCES users(name) ON DELETE CASCADE,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
description TEXT,
|
||||||
|
query TEXT,
|
||||||
|
genres TEXT NOT NULL DEFAULT '[]',
|
||||||
|
target_size INTEGER NOT NULL DEFAULT 30,
|
||||||
|
refresh_hours INTEGER NOT NULL DEFAULT 24,
|
||||||
|
yt_enabled BOOLEAN NOT NULL DEFAULT 1,
|
||||||
|
last_discovery_at TEXT,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
changed_at TEXT NOT NULL,
|
||||||
|
last_error TEXT
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO moods_v2 (
|
||||||
|
id, owner, name, description, query, genres, target_size,
|
||||||
|
refresh_hours, yt_enabled, created_at, changed_at, last_error
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
m.playlist_id,
|
||||||
|
p.owner,
|
||||||
|
p.name,
|
||||||
|
p.comment,
|
||||||
|
m.query,
|
||||||
|
m.genres,
|
||||||
|
m.target_size,
|
||||||
|
m.refresh_hours,
|
||||||
|
1,
|
||||||
|
p.created_at,
|
||||||
|
p.changed_at,
|
||||||
|
m.last_error
|
||||||
|
FROM moods m
|
||||||
|
JOIN playlists p ON p.id = m.playlist_id;
|
||||||
|
|
||||||
|
CREATE TABLE mood_seeds_v2 (
|
||||||
|
mood_id TEXT NOT NULL REFERENCES moods_v2(id) ON DELETE CASCADE,
|
||||||
|
song_id TEXT NOT NULL REFERENCES songs(id) ON DELETE CASCADE,
|
||||||
|
origin TEXT NOT NULL DEFAULT 'manual'
|
||||||
|
CHECK (origin IN ('manual', 'recommendation', 'yt')),
|
||||||
|
added_at TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (mood_id, song_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Stars no longer exist. Songs liked under the old model become manual seeds.
|
||||||
|
INSERT INTO mood_seeds_v2 (mood_id, song_id, origin, added_at)
|
||||||
|
SELECT
|
||||||
|
playlist_id,
|
||||||
|
song_id,
|
||||||
|
CASE origin WHEN 'manual' THEN 'manual' ELSE 'manual' END,
|
||||||
|
added_at
|
||||||
|
FROM mood_seeds;
|
||||||
|
|
||||||
|
CREATE TABLE mood_recommendations_v2 (
|
||||||
|
mood_id TEXT NOT NULL REFERENCES moods_v2(id) ON DELETE CASCADE,
|
||||||
|
video_id TEXT NOT NULL,
|
||||||
|
title TEXT NOT NULL,
|
||||||
|
artist TEXT NOT NULL,
|
||||||
|
album TEXT,
|
||||||
|
duration INTEGER,
|
||||||
|
thumbnail TEXT,
|
||||||
|
state TEXT NOT NULL DEFAULT 'new'
|
||||||
|
CHECK (state IN ('new', 'accepted', 'rejected', 'unavailable')),
|
||||||
|
matched_song_id TEXT REFERENCES songs(id) ON DELETE SET NULL,
|
||||||
|
times_added INTEGER NOT NULL DEFAULT 0,
|
||||||
|
first_seen TEXT NOT NULL,
|
||||||
|
last_seen TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (mood_id, video_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO mood_recommendations_v2 (
|
||||||
|
mood_id, video_id, title, artist, duration, state,
|
||||||
|
matched_song_id, times_added, first_seen, last_seen
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
playlist_id, video_id, title, artist, duration, state,
|
||||||
|
matched_song_id, times_added, first_seen, last_seen
|
||||||
|
FROM mood_recommendations;
|
||||||
|
|
||||||
|
DROP TABLE mood_recommendations;
|
||||||
|
DROP TABLE mood_seeds;
|
||||||
|
DROP TABLE moods;
|
||||||
|
DROP TABLE playlist_songs;
|
||||||
|
DROP TABLE playlists;
|
||||||
|
|
||||||
|
ALTER TABLE moods_v2 RENAME TO moods;
|
||||||
|
ALTER TABLE mood_seeds_v2 RENAME TO mood_seeds;
|
||||||
|
ALTER TABLE mood_recommendations_v2 RENAME TO mood_recommendations;
|
||||||
|
|
||||||
|
CREATE INDEX idx_moods_owner ON moods (owner);
|
||||||
|
CREATE INDEX idx_mood_seeds_song ON mood_seeds (song_id);
|
||||||
|
CREATE INDEX idx_mood_recommendations_song ON mood_recommendations (matched_song_id);
|
||||||
|
|
||||||
|
-- Device sessions. Only the SHA-256 hash of the bearer token is stored.
|
||||||
|
CREATE TABLE api_tokens (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
user_name TEXT NOT NULL REFERENCES users(name) ON DELETE CASCADE,
|
||||||
|
token_hash TEXT NOT NULL UNIQUE,
|
||||||
|
device_name TEXT NOT NULL,
|
||||||
|
platform TEXT NOT NULL,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
last_used_at TEXT NOT NULL,
|
||||||
|
expires_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_api_tokens_user ON api_tokens (user_name);
|
||||||
|
|
||||||
|
-- A playback session belongs to one mood. Queue items and events are kept so a
|
||||||
|
-- client can resume and so radio ranking learns from skips and completions.
|
||||||
|
CREATE TABLE playback_sessions (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
user_name TEXT NOT NULL REFERENCES users(name) ON DELETE CASCADE,
|
||||||
|
mood_id TEXT NOT NULL REFERENCES moods(id) ON DELETE CASCADE,
|
||||||
|
next_position INTEGER NOT NULL DEFAULT 0,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
last_seen_at TEXT NOT NULL,
|
||||||
|
closed_at TEXT
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_playback_sessions_user ON playback_sessions (user_name, last_seen_at);
|
||||||
|
|
||||||
|
CREATE TABLE playback_session_items (
|
||||||
|
session_id TEXT NOT NULL REFERENCES playback_sessions(id) ON DELETE CASCADE,
|
||||||
|
position INTEGER NOT NULL,
|
||||||
|
song_id TEXT NOT NULL REFERENCES songs(id) ON DELETE CASCADE,
|
||||||
|
state TEXT NOT NULL DEFAULT 'queued'
|
||||||
|
CHECK (state IN ('queued', 'started', 'completed', 'skipped')),
|
||||||
|
queued_at TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (session_id, position)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_session_items_song ON playback_session_items (song_id);
|
||||||
|
|
||||||
|
CREATE TABLE song_affinity (
|
||||||
|
user_name TEXT NOT NULL REFERENCES users(name) ON DELETE CASCADE,
|
||||||
|
song_id TEXT NOT NULL REFERENCES songs(id) ON DELETE CASCADE,
|
||||||
|
completions INTEGER NOT NULL DEFAULT 0,
|
||||||
|
skips INTEGER NOT NULL DEFAULT 0,
|
||||||
|
last_event_at TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (user_name, song_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Clients sync by revision. Deletions are explicit so offline libraries can drop
|
||||||
|
-- removed files instead of keeping them forever.
|
||||||
|
CREATE TABLE library_tombstones (
|
||||||
|
entity TEXT NOT NULL,
|
||||||
|
entity_id TEXT NOT NULL,
|
||||||
|
deleted_at TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (entity, entity_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_library_tombstones_deleted ON library_tombstones (deleted_at);
|
||||||
|
|
||||||
|
-- Scanner deltas need a changed timestamp independent of the file mtime.
|
||||||
|
ALTER TABLE songs ADD COLUMN updated_at TEXT NOT NULL DEFAULT '';
|
||||||
|
UPDATE songs SET updated_at = created_at WHERE updated_at = '';
|
||||||
+503
-461
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,459 @@
|
|||||||
|
package win.taptap.musicmanager.api
|
||||||
|
|
||||||
|
import io.ktor.client.HttpClient
|
||||||
|
import io.ktor.client.request.delete
|
||||||
|
import io.ktor.client.request.get
|
||||||
|
import io.ktor.client.request.header
|
||||||
|
import io.ktor.client.request.post
|
||||||
|
import io.ktor.client.request.setBody
|
||||||
|
import io.ktor.client.statement.bodyAsBytes
|
||||||
|
import io.ktor.client.statement.bodyAsText
|
||||||
|
import io.ktor.http.ContentType
|
||||||
|
import io.ktor.http.HttpHeaders
|
||||||
|
import io.ktor.http.HttpStatusCode
|
||||||
|
import io.ktor.http.contentType
|
||||||
|
import io.ktor.serialization.kotlinx.json.json
|
||||||
|
import io.ktor.server.application.install
|
||||||
|
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.response.respond
|
||||||
|
import io.ktor.server.routing.routing
|
||||||
|
import io.ktor.server.testing.ApplicationTestBuilder
|
||||||
|
import io.ktor.server.testing.testApplication
|
||||||
|
import java.nio.file.Files
|
||||||
|
import java.nio.file.Path
|
||||||
|
import java.time.Instant
|
||||||
|
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 org.jetbrains.exposed.sql.insert
|
||||||
|
import org.jetbrains.exposed.sql.insertIgnore
|
||||||
|
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
|
||||||
|
import win.taptap.musicmanager.db.AlbumArtistsTable
|
||||||
|
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.SongArtistsTable
|
||||||
|
import win.taptap.musicmanager.db.SongGenresTable
|
||||||
|
import win.taptap.musicmanager.db.SongsTable
|
||||||
|
import win.taptap.musicmanager.radio.RadioService
|
||||||
|
import win.taptap.musicmanager.scanner.CoverArtService
|
||||||
|
import win.taptap.musicmanager.scanner.ScanStatus
|
||||||
|
import win.taptap.musicmanager.transcoding.FfmpegTranscoder
|
||||||
|
import win.taptap.musicmanager.util.IdGenerator
|
||||||
|
|
||||||
|
class ApiRoutesTest {
|
||||||
|
|
||||||
|
@TempDir
|
||||||
|
lateinit var tempDir: Path
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `login issues a bearer token and rejects bad credentials`() {
|
||||||
|
seededContext().use { seed ->
|
||||||
|
testApplication {
|
||||||
|
setupApp(seed)
|
||||||
|
|
||||||
|
val ok = parse(client.login("alice", "alice-pw").bodyAsText())
|
||||||
|
assertTrue(ok.string("token").isNotBlank())
|
||||||
|
assertEquals("alice", ok["user"]!!.jsonObject.string("name"))
|
||||||
|
assertEquals(listOf(1), ok["user"]!!.jsonObject["musicFolders"]!!.jsonArray.map { it.jsonPrimitive.int })
|
||||||
|
|
||||||
|
val bad = client.login("alice", "wrong")
|
||||||
|
assertEquals(HttpStatusCode.Unauthorized, bad.status)
|
||||||
|
assertEquals("invalid_credentials", parse(bad.bodyAsText())["error"]!!.jsonObject.string("code"))
|
||||||
|
|
||||||
|
val unauth = client.get("/api/v1/moods")
|
||||||
|
assertEquals(HttpStatusCode.Unauthorized, unauth.status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `library sync is folder scoped and stream accepts a query token`() {
|
||||||
|
seededContext().use { seed ->
|
||||||
|
testApplication {
|
||||||
|
setupApp(seed)
|
||||||
|
val token = client.token("alice", "alice-pw")
|
||||||
|
|
||||||
|
val page = parseBody(
|
||||||
|
client.get("/api/v1/library/songs?scope=music") {
|
||||||
|
bearer(token)
|
||||||
|
}.bodyAsText(),
|
||||||
|
)
|
||||||
|
val ids = page["songs"]!!.jsonArray.map { it.jsonObject.string("id") }
|
||||||
|
assertTrue(seed.aliceAmbient1 in ids)
|
||||||
|
assertTrue(seed.aliceRock in ids)
|
||||||
|
assertFalse(seed.longformSong in ids)
|
||||||
|
assertFalse(seed.bobSong in ids)
|
||||||
|
assertTrue(page.string("revision").isNotBlank())
|
||||||
|
|
||||||
|
val longform = parseBody(
|
||||||
|
client.get("/api/v1/library/songs?scope=longform") {
|
||||||
|
bearer(token)
|
||||||
|
}.bodyAsText(),
|
||||||
|
)
|
||||||
|
val longformIds = longform["songs"]!!.jsonArray.map { it.jsonObject.string("id") }
|
||||||
|
assertEquals(listOf(seed.longformSong), longformIds)
|
||||||
|
|
||||||
|
// HTML audio cannot set headers, so media endpoints accept ?token=.
|
||||||
|
val stream = client.get("/api/v1/songs/${seed.aliceAmbient1}/stream?token=$token")
|
||||||
|
assertEquals(HttpStatusCode.OK, stream.status)
|
||||||
|
assertTrue(stream.bodyAsBytes().isNotEmpty())
|
||||||
|
|
||||||
|
val ranged = client.get("/api/v1/songs/${seed.aliceAmbient1}/stream?token=$token") {
|
||||||
|
header(HttpHeaders.Range, "bytes=0-3")
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.PartialContent, ranged.status)
|
||||||
|
assertEquals(4, ranged.bodyAsBytes().size)
|
||||||
|
|
||||||
|
val forbidden = client.get("/api/v1/songs/${seed.bobSong}/stream?token=$token")
|
||||||
|
assertEquals(HttpStatusCode.NotFound, forbidden.status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `moods generate radio queues and add-to-mood replaces likes`() {
|
||||||
|
seededContext().use { seed ->
|
||||||
|
testApplication {
|
||||||
|
setupApp(seed)
|
||||||
|
val token = client.token("alice", "alice-pw")
|
||||||
|
|
||||||
|
val created = client.post("/api/v1/moods") {
|
||||||
|
bearer(token)
|
||||||
|
contentType(ContentType.Application.Json)
|
||||||
|
setBody(
|
||||||
|
"""{"name":"Focus","genres":["Ambient"],"targetSize":10,"seedSongIds":["${seed.aliceAmbient1}"]}""",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.Created, created.status)
|
||||||
|
val mood = parse(created.bodyAsText())
|
||||||
|
val moodId = mood["mood"]!!.jsonObject.string("id")
|
||||||
|
assertEquals(1, mood["mood"]!!.jsonObject.int("seedCount"))
|
||||||
|
assertTrue(mood["seeds"]!!.jsonArray.isNotEmpty())
|
||||||
|
|
||||||
|
// Long-form can never be a mood seed.
|
||||||
|
val withLongform = client.post("/api/v1/moods") {
|
||||||
|
bearer(token)
|
||||||
|
contentType(ContentType.Application.Json)
|
||||||
|
setBody("""{"name":"Book","seedSongIds":["${seed.longformSong}"]}""")
|
||||||
|
}
|
||||||
|
val bookMood = parse(withLongform.bodyAsText())
|
||||||
|
assertEquals(0, bookMood["mood"]!!.jsonObject.int("seedCount"))
|
||||||
|
|
||||||
|
val started = client.post("/api/v1/moods/$moodId/sessions") {
|
||||||
|
bearer(token)
|
||||||
|
contentType(ContentType.Application.Json)
|
||||||
|
setBody("""{"limit":10}""")
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.Created, started.status)
|
||||||
|
val session = parse(started.bodyAsText())
|
||||||
|
val sessionId = session.string("id")
|
||||||
|
val queue = session["queue"]!!.jsonArray.map { it.jsonObject }
|
||||||
|
assertTrue(queue.any { it.string("id") == seed.aliceAmbient1 })
|
||||||
|
assertFalse(queue.any { it.string("id") == seed.longformSong })
|
||||||
|
assertFalse(queue.any { it.string("id") == seed.bobSong })
|
||||||
|
assertTrue(queue.all { it.string("folderId") == "1" })
|
||||||
|
|
||||||
|
val second = client.post("/api/v1/sessions/$sessionId/next") {
|
||||||
|
bearer(token)
|
||||||
|
contentType(ContentType.Application.Json)
|
||||||
|
setBody("""{"limit":10}""")
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.OK, second.status)
|
||||||
|
val nextIds = parse(second.bodyAsText())["songs"]!!.jsonArray
|
||||||
|
.map { it.jsonObject.string("id") }
|
||||||
|
assertTrue(nextIds.none { it in queue.map { song -> song.string("id") } })
|
||||||
|
|
||||||
|
val completed = client.post("/api/v1/sessions/$sessionId/events") {
|
||||||
|
bearer(token)
|
||||||
|
contentType(ContentType.Application.Json)
|
||||||
|
setBody("""{"events":[{"songId":"${seed.aliceAmbient1}","type":"completed"}]}""")
|
||||||
|
}
|
||||||
|
assertEquals(1, parse(completed.bodyAsText()).int("accepted"))
|
||||||
|
|
||||||
|
// Add to the current mood.
|
||||||
|
val added = client.post("/api/v1/sessions/$sessionId/add-to-mood") {
|
||||||
|
bearer(token)
|
||||||
|
contentType(ContentType.Application.Json)
|
||||||
|
setBody("""{"songId":"${seed.aliceAmbient2}"}""")
|
||||||
|
}
|
||||||
|
val addedBody = parse(added.bodyAsText())
|
||||||
|
assertTrue(addedBody["added"]!!.jsonPrimitive.content.toBoolean())
|
||||||
|
assertEquals(2, addedBody["mood"]!!.jsonObject.int("seedCount"))
|
||||||
|
|
||||||
|
// Add to another mood through the chooser.
|
||||||
|
val other = client.post("/api/v1/moods") {
|
||||||
|
bearer(token)
|
||||||
|
contentType(ContentType.Application.Json)
|
||||||
|
setBody("""{"name":"Evening"}""")
|
||||||
|
}
|
||||||
|
val otherId = parse(other.bodyAsText())["mood"]!!.jsonObject.string("id")
|
||||||
|
val switched = client.post("/api/v1/sessions/$sessionId/add-to-mood") {
|
||||||
|
bearer(token)
|
||||||
|
contentType(ContentType.Application.Json)
|
||||||
|
setBody("""{"songId":"${seed.aliceAmbient2}","moodId":"$otherId"}""")
|
||||||
|
}
|
||||||
|
assertEquals(1, parse(switched.bodyAsText())["mood"]!!.jsonObject.int("seedCount"))
|
||||||
|
|
||||||
|
val removed = client.post("/api/v1/sessions/$sessionId/add-to-mood") {
|
||||||
|
bearer(token)
|
||||||
|
contentType(ContentType.Application.Json)
|
||||||
|
setBody("""{"songId":"${seed.aliceAmbient2}"}""")
|
||||||
|
}
|
||||||
|
assertEquals(2, parse(removed.bodyAsText())["mood"]!!.jsonObject.int("seedCount"))
|
||||||
|
|
||||||
|
val preview = parseBody(
|
||||||
|
client.get("/api/v1/moods/$moodId/preview?limit=5") { bearer(token) }.bodyAsText(),
|
||||||
|
)
|
||||||
|
assertTrue(preview["songs"]!!.jsonArray.isNotEmpty())
|
||||||
|
|
||||||
|
val bobToken = client.token("bob", "bob-pw")
|
||||||
|
val denied = client.get("/api/v1/moods/$moodId") { bearer(bobToken) }
|
||||||
|
assertEquals(HttpStatusCode.NotFound, denied.status)
|
||||||
|
|
||||||
|
val deleted = client.deleteMood(token, moodId)
|
||||||
|
assertEquals(HttpStatusCode.NoContent, deleted.status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `a session is scoped to its owner`() {
|
||||||
|
seededContext().use { seed ->
|
||||||
|
testApplication {
|
||||||
|
setupApp(seed)
|
||||||
|
val alice = client.token("alice", "alice-pw")
|
||||||
|
val bob = client.token("bob", "bob-pw")
|
||||||
|
|
||||||
|
val mood = client.post("/api/v1/moods") {
|
||||||
|
bearer(alice)
|
||||||
|
contentType(ContentType.Application.Json)
|
||||||
|
setBody("""{"name":"Private"}""")
|
||||||
|
}
|
||||||
|
val moodId = parse(mood.bodyAsText())["mood"]!!.jsonObject.string("id")
|
||||||
|
val started = client.post("/api/v1/moods/$moodId/sessions") {
|
||||||
|
bearer(alice)
|
||||||
|
contentType(ContentType.Application.Json)
|
||||||
|
setBody("""{"limit":5}""")
|
||||||
|
}
|
||||||
|
val sessionId = parse(started.bodyAsText()).string("id")
|
||||||
|
|
||||||
|
val denied = client.get("/api/v1/sessions/$sessionId") { bearer(bob) }
|
||||||
|
assertEquals(HttpStatusCode.NotFound, denied.status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ApplicationTestBuilder.setupApp(seed: Seed) {
|
||||||
|
application {
|
||||||
|
install(ContentNegotiation) {
|
||||||
|
json(Json { ignoreUnknownKeys = true; encodeDefaults = true })
|
||||||
|
}
|
||||||
|
install(PartialContent)
|
||||||
|
install(StatusPages) {
|
||||||
|
exception<ApiException> { call, cause ->
|
||||||
|
call.respond(
|
||||||
|
cause.status,
|
||||||
|
apiErrorBody(cause.code, cause.message),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
routing {
|
||||||
|
apiRoutes(
|
||||||
|
users = seed.users,
|
||||||
|
library = seed.library,
|
||||||
|
coverArtService = seed.coverArt,
|
||||||
|
transcoder = FfmpegTranscoder("ffmpeg"),
|
||||||
|
radioService = RadioService(),
|
||||||
|
startScan = { false },
|
||||||
|
scanStatus = { ScanStatus(false, 0) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun HttpClient.token(user: String, password: String): String =
|
||||||
|
parse(login(user, password).bodyAsText()).string("token")
|
||||||
|
|
||||||
|
private suspend fun HttpClient.login(user: String, password: String) =
|
||||||
|
post("/api/v1/auth/login") {
|
||||||
|
contentType(ContentType.Application.Json)
|
||||||
|
setBody("""{"username":"$user","password":"$password","deviceName":"test","platform":"test"}""")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun io.ktor.client.request.HttpRequestBuilder.bearer(token: String) {
|
||||||
|
header(HttpHeaders.Authorization, "Bearer $token")
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun HttpClient.deleteMood(token: String, id: String) =
|
||||||
|
delete("/api/v1/moods/$id") {
|
||||||
|
bearer(token)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun seededContext(): Seed {
|
||||||
|
val musicA = Files.createDirectories(tempDir.resolve("music-a"))
|
||||||
|
val musicB = Files.createDirectories(tempDir.resolve("music-b"))
|
||||||
|
val longform = Files.createDirectories(tempDir.resolve("longform"))
|
||||||
|
|
||||||
|
val library = LibraryConfig(
|
||||||
|
listOf(
|
||||||
|
MusicFolder(1, "Alice Music", FolderType.MUSIC, musicA),
|
||||||
|
MusicFolder(2, "Bob Music", FolderType.MUSIC, musicB),
|
||||||
|
MusicFolder(10, "Long-form", FolderType.LONGFORM, longform),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
val users = UsersConfig(
|
||||||
|
listOf(
|
||||||
|
UserAccount("alice", "alice-pw", admin = true, folders = setOf(1)),
|
||||||
|
UserAccount("bob", "bob-pw", admin = false, folders = setOf(2)),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
val db = DatabaseFactory.connect(
|
||||||
|
AppConfig(
|
||||||
|
port = 8080,
|
||||||
|
dataDir = tempDir.resolve("data"),
|
||||||
|
libraryConfigPath = tempDir.resolve("library.yaml"),
|
||||||
|
usersFile = tempDir.resolve("users.yaml"),
|
||||||
|
ffmpegPath = "ffmpeg",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
ConfigRepository.sync(library, users)
|
||||||
|
|
||||||
|
val aliceAmbient1 = seedSong(db, 1, "Alpha", "Focus One", "Deep Work", "Alpha/Focus One/01.mp3", "Ambient", musicA)
|
||||||
|
val aliceAmbient2 = seedSong(db, 1, "Beta", "Focus Two", "Soft Light", "Beta/Focus Two/01.mp3", "Ambient", musicA)
|
||||||
|
val aliceRock = seedSong(db, 1, "Gamma", "Loud", "Noise", "Gamma/Loud/01.mp3", "Rock", musicA)
|
||||||
|
val bobSong = seedSong(db, 2, "Bob Artist", "Bob Album", "Bob Song", "Bob Artist/Bob Album/01.mp3", "Ambient", musicB)
|
||||||
|
val longformSong = seedSong(
|
||||||
|
db, 10, "Long Narrator", "Long Book", "Chapter One",
|
||||||
|
"Long Narrator/Long Book/01.mp3", "Ambient", longform,
|
||||||
|
)
|
||||||
|
|
||||||
|
return Seed(
|
||||||
|
db = db,
|
||||||
|
library = library,
|
||||||
|
users = users,
|
||||||
|
coverArt = CoverArtService(tempDir.resolve("data")),
|
||||||
|
aliceAmbient1 = aliceAmbient1,
|
||||||
|
aliceAmbient2 = aliceAmbient2,
|
||||||
|
aliceRock = aliceRock,
|
||||||
|
bobSong = bobSong,
|
||||||
|
longformSong = longformSong,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun seedSong(
|
||||||
|
db: DatabaseHandle,
|
||||||
|
folderId: Int,
|
||||||
|
artistName: String,
|
||||||
|
albumName: String,
|
||||||
|
title: String,
|
||||||
|
relativePath: String,
|
||||||
|
genre: String,
|
||||||
|
root: Path,
|
||||||
|
): String {
|
||||||
|
val file = root.resolve(relativePath)
|
||||||
|
Files.createDirectories(file.parent)
|
||||||
|
Files.write(file, "ID3-fake-audio".toByteArray())
|
||||||
|
|
||||||
|
val artistId = IdGenerator.artistId(artistName)
|
||||||
|
val albumId = IdGenerator.albumId(artistName, albumName)
|
||||||
|
val songId = IdGenerator.songId(folderId, relativePath)
|
||||||
|
val now = Instant.now().toString()
|
||||||
|
|
||||||
|
transaction(db.database) {
|
||||||
|
ArtistsTable.insertIgnore {
|
||||||
|
it[id] = artistId
|
||||||
|
it[name] = artistName
|
||||||
|
it[sortName] = artistName
|
||||||
|
it[searchText] = IdGenerator.normalize(artistName)
|
||||||
|
}
|
||||||
|
AlbumsTable.insertIgnore {
|
||||||
|
it[id] = albumId
|
||||||
|
it[name] = albumName
|
||||||
|
it[year] = 2026
|
||||||
|
it[createdAt] = now
|
||||||
|
it[searchText] = IdGenerator.normalize("$albumName $artistName")
|
||||||
|
}
|
||||||
|
AlbumArtistsTable.insertIgnore {
|
||||||
|
it[this.albumId] = albumId
|
||||||
|
it[this.artistId] = artistId
|
||||||
|
it[position] = 0
|
||||||
|
}
|
||||||
|
SongsTable.insert {
|
||||||
|
it[id] = songId
|
||||||
|
it[this.albumId] = albumId
|
||||||
|
it[this.folderId] = folderId
|
||||||
|
it[this.title] = title
|
||||||
|
it[displayArtist] = artistName
|
||||||
|
it[this.albumName] = albumName
|
||||||
|
it[trackNumber] = 1
|
||||||
|
it[discNumber] = 1
|
||||||
|
it[year] = 2026
|
||||||
|
it[duration] = 120
|
||||||
|
it[bitRate] = 128
|
||||||
|
it[size] = Files.size(file)
|
||||||
|
it[suffix] = "mp3"
|
||||||
|
it[contentType] = "audio/mpeg"
|
||||||
|
it[this.relativePath] = relativePath
|
||||||
|
it[fileMtime] = 0
|
||||||
|
it[createdAt] = now
|
||||||
|
it[updatedAt] = now
|
||||||
|
it[searchText] = IdGenerator.normalize("$title $artistName $albumName $artistName")
|
||||||
|
}
|
||||||
|
SongArtistsTable.insert {
|
||||||
|
it[this.songId] = songId
|
||||||
|
it[this.artistId] = artistId
|
||||||
|
it[position] = 0
|
||||||
|
}
|
||||||
|
SongGenresTable.insert {
|
||||||
|
it[this.songId] = songId
|
||||||
|
it[this.genre] = genre
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return songId
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseBody(body: String): JsonObject =
|
||||||
|
Json.parseToJsonElement(body).jsonObject
|
||||||
|
|
||||||
|
private fun parse(body: String): JsonObject =
|
||||||
|
Json.parseToJsonElement(body).jsonObject
|
||||||
|
|
||||||
|
private fun JsonObject.string(name: String): String = this[name]!!.jsonPrimitive.content
|
||||||
|
|
||||||
|
private fun JsonObject.int(name: String): Int = this[name]!!.jsonPrimitive.int
|
||||||
|
|
||||||
|
private data class Seed(
|
||||||
|
val db: DatabaseHandle,
|
||||||
|
val library: LibraryConfig,
|
||||||
|
val users: UsersConfig,
|
||||||
|
val coverArt: CoverArtService,
|
||||||
|
val aliceAmbient1: String,
|
||||||
|
val aliceAmbient2: String,
|
||||||
|
val aliceRock: String,
|
||||||
|
val bobSong: String,
|
||||||
|
val longformSong: String,
|
||||||
|
) : AutoCloseable {
|
||||||
|
override fun close() = db.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,649 +0,0 @@
|
|||||||
package win.taptap.musicmanager.subsonic
|
|
||||||
|
|
||||||
import io.ktor.client.request.get
|
|
||||||
import io.ktor.client.request.header
|
|
||||||
import io.ktor.client.request.post
|
|
||||||
import io.ktor.client.request.setBody
|
|
||||||
import io.ktor.client.statement.bodyAsBytes
|
|
||||||
import io.ktor.client.statement.bodyAsText
|
|
||||||
import io.ktor.http.ContentType
|
|
||||||
import io.ktor.http.HttpHeaders
|
|
||||||
import io.ktor.http.HttpStatusCode
|
|
||||||
import io.ktor.http.contentType
|
|
||||||
import io.ktor.serialization.kotlinx.json.json
|
|
||||||
import io.ktor.server.application.install
|
|
||||||
import io.ktor.server.plugins.contentnegotiation.ContentNegotiation
|
|
||||||
import io.ktor.server.plugins.partialcontent.PartialContent
|
|
||||||
import io.ktor.server.routing.routing
|
|
||||||
import io.ktor.server.testing.ApplicationTestBuilder
|
|
||||||
import io.ktor.server.testing.testApplication
|
|
||||||
import java.nio.file.Files
|
|
||||||
import java.nio.file.Path
|
|
||||||
import java.time.Instant
|
|
||||||
import kotlinx.coroutines.CoroutineScope
|
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
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.assertTrue
|
|
||||||
import org.jetbrains.exposed.sql.insert
|
|
||||||
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.AlbumArtistsTable
|
|
||||||
import win.taptap.musicmanager.db.AlbumGenresTable
|
|
||||||
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.SongArtistsTable
|
|
||||||
import win.taptap.musicmanager.db.SongGenresTable
|
|
||||||
import win.taptap.musicmanager.db.SongsTable
|
|
||||||
import win.taptap.musicmanager.mood.MoodService
|
|
||||||
import win.taptap.musicmanager.scanner.CoverArtService
|
|
||||||
import win.taptap.musicmanager.scanner.ScanStatus
|
|
||||||
import win.taptap.musicmanager.subsonic.routes.subsonicRoutes
|
|
||||||
import win.taptap.musicmanager.transcoding.FfmpegTranscoder
|
|
||||||
import win.taptap.musicmanager.util.IdGenerator
|
|
||||||
|
|
||||||
class BrowsingRoutesTest {
|
|
||||||
|
|
||||||
@TempDir
|
|
||||||
lateinit var tempDir: Path
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `music folders are scoped to the user and long-form is shared`() {
|
|
||||||
seededContext().use { seed ->
|
|
||||||
testApplication {
|
|
||||||
setupApp(seed)
|
|
||||||
|
|
||||||
val alice = parseBody(client.get("/rest/getMusicFolders?${credentials("alice", "alice-pw")}").bodyAsText())
|
|
||||||
val aliceIds = folderIds(alice)
|
|
||||||
assertEquals(listOf(1, 10), aliceIds)
|
|
||||||
|
|
||||||
val bob = parseBody(client.get("/rest/getMusicFolders?${credentials("bob", "bob-pw")}").bodyAsText())
|
|
||||||
assertEquals(listOf(2, 10), folderIds(bob))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `artist and album browsing only exposes visible music`() {
|
|
||||||
seededContext().use { seed ->
|
|
||||||
testApplication {
|
|
||||||
setupApp(seed)
|
|
||||||
|
|
||||||
val artists = parseBody(client.get("/rest/getArtists?${credentials("alice", "alice-pw")}").bodyAsText())
|
|
||||||
val index = artists["artists"]!!.jsonObject["index"]!!.jsonArray
|
|
||||||
val names = index.flatMap { it.jsonObject["artist"]!!.jsonArray }
|
|
||||||
.map { it.jsonObject["name"]!!.jsonPrimitive.content }
|
|
||||||
assertEquals(listOf("Alice Artist"), names)
|
|
||||||
|
|
||||||
val artist = parseBody(
|
|
||||||
client.get("/rest/getArtist?${credentials("alice", "alice-pw")}&id=${seed.aliceArtistId}").bodyAsText(),
|
|
||||||
)
|
|
||||||
val albums = artist["artist"]!!.jsonObject["album"]!!.jsonArray
|
|
||||||
assertEquals(1, albums.size)
|
|
||||||
assertEquals(seed.aliceAlbumId, albums[0].jsonObject["id"]!!.jsonPrimitive.content)
|
|
||||||
|
|
||||||
val album = parseBody(
|
|
||||||
client.get("/rest/getAlbum?${credentials("alice", "alice-pw")}&id=${seed.aliceAlbumId}").bodyAsText(),
|
|
||||||
)
|
|
||||||
val songs = album["album"]!!.jsonObject["song"]!!.jsonArray
|
|
||||||
assertEquals(1, songs.size)
|
|
||||||
assertEquals(seed.aliceSongId, songs[0].jsonObject["id"]!!.jsonPrimitive.content)
|
|
||||||
assertEquals("mp3", songs[0].jsonObject["suffix"]!!.jsonPrimitive.content)
|
|
||||||
assertEquals("audio/mpeg", songs[0].jsonObject["contentType"]!!.jsonPrimitive.content)
|
|
||||||
|
|
||||||
val hidden = parseBody(
|
|
||||||
client.get("/rest/getSong?${credentials("alice", "alice-pw")}&id=${seed.bobSongId}").bodyAsText(),
|
|
||||||
)
|
|
||||||
assertEquals("failed", hidden["status"]!!.jsonPrimitive.content)
|
|
||||||
assertEquals(70, hidden["error"]!!.jsonObject["code"]!!.jsonPrimitive.int)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `search3 filters by query and supports empty and wildcard queries`() {
|
|
||||||
seededContext().use { seed ->
|
|
||||||
testApplication {
|
|
||||||
setupApp(seed)
|
|
||||||
|
|
||||||
val alice = parseSearch(
|
|
||||||
client.get("/rest/search3?${credentials("alice", "alice-pw")}&query=alice").bodyAsText(),
|
|
||||||
)
|
|
||||||
assertEquals(1, alice["artist"]!!.jsonArray.size)
|
|
||||||
assertEquals(1, alice["album"]!!.jsonArray.size)
|
|
||||||
assertEquals(1, alice["song"]!!.jsonArray.size)
|
|
||||||
|
|
||||||
val none = parseSearch(
|
|
||||||
client.get("/rest/search3?${credentials("alice", "alice-pw")}&query=nothing-matches").bodyAsText(),
|
|
||||||
)
|
|
||||||
assertEquals(0, none["artist"]!!.jsonArray.size)
|
|
||||||
assertEquals(0, none["album"]!!.jsonArray.size)
|
|
||||||
assertEquals(0, none["song"]!!.jsonArray.size)
|
|
||||||
|
|
||||||
val all = parseSearch(
|
|
||||||
client.get("/rest/search3?${credentials("bob", "bob-pw")}&query=*").bodyAsText(),
|
|
||||||
)
|
|
||||||
assertEquals(1, all["song"]!!.jsonArray.size)
|
|
||||||
assertEquals(seed.bobSongId, all["song"]!!.jsonArray[0].jsonObject["id"]!!.jsonPrimitive.content)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `streams and downloads the original file and serves covers`() {
|
|
||||||
seededContext().use { seed ->
|
|
||||||
testApplication {
|
|
||||||
setupApp(seed)
|
|
||||||
|
|
||||||
val stream = client.get("/rest/stream?${credentials("alice", "alice-pw")}&id=${seed.aliceSongId}")
|
|
||||||
assertEquals(HttpStatusCode.OK, stream.status)
|
|
||||||
assertEquals(seed.aliceAudioBytes.toList(), stream.bodyAsBytes().toList())
|
|
||||||
|
|
||||||
val ranged = client.get("/rest/stream?${credentials("alice", "alice-pw")}&id=${seed.aliceSongId}") {
|
|
||||||
header(HttpHeaders.Range, "bytes=0-3")
|
|
||||||
}
|
|
||||||
assertEquals(HttpStatusCode.PartialContent, ranged.status)
|
|
||||||
assertEquals(seed.aliceAudioBytes.take(4), ranged.bodyAsBytes().toList())
|
|
||||||
|
|
||||||
val download = client.get("/rest/download?${credentials("alice", "alice-pw")}&id=${seed.aliceSongId}")
|
|
||||||
assertEquals(HttpStatusCode.OK, download.status)
|
|
||||||
assertTrue(
|
|
||||||
download.headers["Content-Disposition"]!!
|
|
||||||
.contains("filename*=UTF-8''song.mp3"),
|
|
||||||
)
|
|
||||||
|
|
||||||
val cover = client.get(
|
|
||||||
"/rest/getCoverArt?${credentials("alice", "alice-pw")}&id=${seed.aliceAlbumId}&size=16",
|
|
||||||
)
|
|
||||||
assertEquals(HttpStatusCode.OK, cover.status)
|
|
||||||
assertTrue(cover.bodyAsBytes().isNotEmpty())
|
|
||||||
|
|
||||||
val otherUsersCover = client.get(
|
|
||||||
"/rest/getCoverArt?${credentials("bob", "bob-pw")}&id=${seed.aliceAlbumId}",
|
|
||||||
)
|
|
||||||
assertEquals(HttpStatusCode.NotFound, otherUsersCover.status)
|
|
||||||
|
|
||||||
val otherUsersSong = parseBody(
|
|
||||||
client.get("/rest/stream?${credentials("bob", "bob-pw")}&id=${seed.aliceSongId}").bodyAsText(),
|
|
||||||
)
|
|
||||||
assertEquals(70, otherUsersSong["error"]!!.jsonObject["code"]!!.jsonPrimitive.int)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `getSong returns the expected offline metadata`() {
|
|
||||||
seededContext().use { seed ->
|
|
||||||
testApplication {
|
|
||||||
setupApp(seed)
|
|
||||||
|
|
||||||
val song = parseBody(
|
|
||||||
client.get("/rest/getSong?${credentials("alice", "alice-pw")}&id=${seed.aliceSongId}").bodyAsText(),
|
|
||||||
)["song"]!!.jsonObject
|
|
||||||
|
|
||||||
assertEquals(seed.aliceSongId, song["id"]!!.jsonPrimitive.content)
|
|
||||||
assertEquals(seed.aliceAlbumId, song["albumId"]!!.jsonPrimitive.content)
|
|
||||||
assertEquals(seed.aliceArtistId, song["artistId"]!!.jsonPrimitive.content)
|
|
||||||
assertEquals(seed.aliceFileSize.toString(), song["size"]!!.jsonPrimitive.content)
|
|
||||||
assertEquals("Rock", song["genre"]!!.jsonPrimitive.content)
|
|
||||||
assertEquals(128, song["bitRate"]!!.jsonPrimitive.int)
|
|
||||||
assertEquals("music", song["type"]!!.jsonPrimitive.content)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `album feeds genres and random songs are visibility scoped`() {
|
|
||||||
seededContext().use { seed ->
|
|
||||||
testApplication {
|
|
||||||
setupApp(seed)
|
|
||||||
val auth = credentials("alice", "alice-pw")
|
|
||||||
|
|
||||||
val albums = parseBody(
|
|
||||||
client.get("/rest/getAlbumList2?$auth&type=alphabeticalByName&size=10").bodyAsText(),
|
|
||||||
)["albumList2"]!!.jsonObject["album"]!!.jsonArray
|
|
||||||
assertEquals(1, albums.size)
|
|
||||||
assertEquals(seed.aliceAlbumId, albums[0].jsonObject["id"]!!.jsonPrimitive.content)
|
|
||||||
|
|
||||||
val recent = parseBody(
|
|
||||||
client.get("/rest/getAlbumList2?$auth&type=recent&size=10").bodyAsText(),
|
|
||||||
)["albumList2"]!!.jsonObject["album"]!!.jsonArray
|
|
||||||
assertEquals(1, recent.size)
|
|
||||||
|
|
||||||
// Feishin sends an inverted range for descending by-year queries.
|
|
||||||
val byYear = parseBody(
|
|
||||||
client.get("/rest/getAlbumList2?$auth&type=byYear&fromYear=2026&toYear=0").bodyAsText(),
|
|
||||||
)["albumList2"]!!.jsonObject["album"]!!.jsonArray
|
|
||||||
assertEquals(1, byYear.size)
|
|
||||||
|
|
||||||
val genres = parseBody(client.get("/rest/getGenres?$auth").bodyAsText())["genres"]!!
|
|
||||||
.jsonObject["genre"]!!.jsonArray
|
|
||||||
assertEquals(listOf("Rock"), genres.map { it.jsonObject["value"]!!.jsonPrimitive.content })
|
|
||||||
|
|
||||||
val byGenre = parseBody(
|
|
||||||
client.get("/rest/getSongsByGenre?$auth&genre=Rock&count=10").bodyAsText(),
|
|
||||||
)["songsByGenre"]!!.jsonObject["song"]!!.jsonArray
|
|
||||||
assertEquals(seed.aliceSongId, byGenre.single().jsonObject["id"]!!.jsonPrimitive.content)
|
|
||||||
|
|
||||||
val random = parseBody(
|
|
||||||
client.get("/rest/getRandomSongs?$auth&size=10").bodyAsText(),
|
|
||||||
)["randomSongs"]!!.jsonObject["song"]!!.jsonArray
|
|
||||||
assertEquals(seed.aliceSongId, random.single().jsonObject["id"]!!.jsonPrimitive.content)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `scrobbling stars ratings and bookmarks are per user`() {
|
|
||||||
seededContext().use { seed ->
|
|
||||||
testApplication {
|
|
||||||
setupApp(seed)
|
|
||||||
val alice = credentials("alice", "alice-pw")
|
|
||||||
val bob = credentials("bob", "bob-pw")
|
|
||||||
|
|
||||||
client.get("/rest/scrobble?$alice&id=${seed.aliceSongId}")
|
|
||||||
val played = parseBody(
|
|
||||||
client.get("/rest/getSong?$alice&id=${seed.aliceSongId}").bodyAsText(),
|
|
||||||
)["song"]!!.jsonObject
|
|
||||||
assertEquals(1, played["playCount"]!!.jsonPrimitive.int)
|
|
||||||
|
|
||||||
client.get("/rest/star?$alice&id=${seed.aliceSongId}&albumId=${seed.aliceAlbumId}")
|
|
||||||
val starred = parseBody(client.get("/rest/getStarred2?$alice").bodyAsText())["starred2"]!!
|
|
||||||
.jsonObject
|
|
||||||
assertEquals(1, starred["song"]!!.jsonArray.size)
|
|
||||||
assertEquals(1, starred["album"]!!.jsonArray.size)
|
|
||||||
|
|
||||||
val bobStarred = parseBody(client.get("/rest/getStarred2?$bob").bodyAsText())["starred2"]!!
|
|
||||||
.jsonObject
|
|
||||||
assertEquals(0, bobStarred["song"]!!.jsonArray.size)
|
|
||||||
|
|
||||||
client.get("/rest/setRating?$alice&id=${seed.aliceSongId}&rating=4")
|
|
||||||
client.get("/rest/setRating?$alice&id=${seed.aliceAlbumId}&rating=5")
|
|
||||||
|
|
||||||
val ratedSong = parseBody(
|
|
||||||
client.get("/rest/getSong?$alice&id=${seed.aliceSongId}").bodyAsText(),
|
|
||||||
)["song"]!!.jsonObject
|
|
||||||
assertEquals(4, ratedSong["userRating"]!!.jsonPrimitive.int)
|
|
||||||
|
|
||||||
val ratedAlbum = parseBody(
|
|
||||||
client.get("/rest/getAlbum?$alice&id=${seed.aliceAlbumId}").bodyAsText(),
|
|
||||||
)["album"]!!.jsonObject
|
|
||||||
assertEquals(5, ratedAlbum["userRating"]!!.jsonPrimitive.int)
|
|
||||||
|
|
||||||
client.get("/rest/createBookmark?$alice&id=${seed.aliceSongId}&position=5000")
|
|
||||||
val bookmarks = parseBody(client.get("/rest/getBookmarks?$alice").bodyAsText())["bookmarks"]!!
|
|
||||||
.jsonObject["bookmark"]!!.jsonArray
|
|
||||||
assertEquals(1, bookmarks.size)
|
|
||||||
assertEquals(5000, bookmarks[0].jsonObject["position"]!!.jsonPrimitive.int)
|
|
||||||
assertEquals(
|
|
||||||
seed.aliceSongId,
|
|
||||||
bookmarks[0].jsonObject["entry"]!!.jsonObject["id"]!!.jsonPrimitive.content,
|
|
||||||
)
|
|
||||||
|
|
||||||
client.get("/rest/deleteBookmark?$alice&id=${seed.aliceSongId}")
|
|
||||||
val empty = parseBody(client.get("/rest/getBookmarks?$alice").bodyAsText())["bookmarks"]!!
|
|
||||||
.jsonObject["bookmark"]!!.jsonArray
|
|
||||||
assertEquals(0, empty.size)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `playlists enforce ownership and filter entries by visibility`() {
|
|
||||||
seededContext().use { seed ->
|
|
||||||
testApplication {
|
|
||||||
setupApp(seed)
|
|
||||||
val alice = credentials("alice", "alice-pw")
|
|
||||||
val bob = credentials("bob", "bob-pw")
|
|
||||||
|
|
||||||
val created = parseBody(
|
|
||||||
client.get("/rest/createPlaylist?$alice&name=Alice List&songId=${seed.aliceSongId}").bodyAsText(),
|
|
||||||
)["playlist"]!!.jsonObject
|
|
||||||
val playlistId = created["id"]!!.jsonPrimitive.content
|
|
||||||
assertEquals("Alice List", created["name"]!!.jsonPrimitive.content)
|
|
||||||
assertEquals(1, created["songCount"]!!.jsonPrimitive.int)
|
|
||||||
|
|
||||||
val aliceList = parseBody(client.get("/rest/getPlaylists?$alice").bodyAsText())["playlists"]!!
|
|
||||||
.jsonObject["playlist"]!!.jsonArray
|
|
||||||
assertEquals(1, aliceList.size)
|
|
||||||
|
|
||||||
val bobDetail = parseBody(
|
|
||||||
client.get("/rest/getPlaylist?$bob&id=$playlistId").bodyAsText(),
|
|
||||||
)["playlist"]!!.jsonObject
|
|
||||||
assertEquals(1, bobDetail["songCount"]!!.jsonPrimitive.int)
|
|
||||||
assertEquals(0, bobDetail["entry"]!!.jsonArray.size)
|
|
||||||
|
|
||||||
val forbidden = parseBody(
|
|
||||||
client.get("/rest/deletePlaylist?$bob&id=$playlistId").bodyAsText(),
|
|
||||||
)
|
|
||||||
assertEquals(50, forbidden["error"]!!.jsonObject["code"]!!.jsonPrimitive.int)
|
|
||||||
|
|
||||||
client.get("/rest/updatePlaylist?$alice&playlistId=$playlistId&songIndexToRemove=0")
|
|
||||||
val emptied = parseBody(
|
|
||||||
client.get("/rest/getPlaylist?$alice&id=$playlistId").bodyAsText(),
|
|
||||||
)["playlist"]!!.jsonObject
|
|
||||||
assertEquals(0, emptied["entry"]!!.jsonArray.size)
|
|
||||||
|
|
||||||
val deleted = parseBody(
|
|
||||||
client.get("/rest/deletePlaylist?$alice&id=$playlistId").bodyAsText(),
|
|
||||||
)
|
|
||||||
assertEquals("ok", deleted["status"]!!.jsonPrimitive.content)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `form posts are accepted for client compatibility`() {
|
|
||||||
seededContext().use { seed ->
|
|
||||||
testApplication {
|
|
||||||
setupApp(seed)
|
|
||||||
|
|
||||||
val response = client.post("/rest/getAlbumList2.view") {
|
|
||||||
contentType(ContentType.Application.FormUrlEncoded)
|
|
||||||
setBody("${credentials("alice", "alice-pw")}&type=alphabeticalByName&size=10")
|
|
||||||
}
|
|
||||||
|
|
||||||
assertEquals(HttpStatusCode.OK, response.status)
|
|
||||||
val albums = parseBody(response.bodyAsText())["albumList2"]!!
|
|
||||||
.jsonObject["album"]!!.jsonArray
|
|
||||||
assertEquals(seed.aliceAlbumId, albums[0].jsonObject["id"]!!.jsonPrimitive.content)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `music directory and play queue expose folders albums and songs`() {
|
|
||||||
seededContext().use { seed ->
|
|
||||||
testApplication {
|
|
||||||
setupApp(seed)
|
|
||||||
val auth = credentials("alice", "alice-pw")
|
|
||||||
|
|
||||||
val folder = parseBody(
|
|
||||||
client.get("/rest/getMusicDirectory?$auth&id=1").bodyAsText(),
|
|
||||||
)["directory"]!!.jsonObject
|
|
||||||
val folderChildren = folder["child"]!!.jsonArray
|
|
||||||
assertEquals(1, folderChildren.size)
|
|
||||||
assertEquals(seed.aliceAlbumId, folderChildren[0].jsonObject["id"]!!.jsonPrimitive.content)
|
|
||||||
assertEquals("true", folderChildren[0].jsonObject["isDir"]!!.jsonPrimitive.content)
|
|
||||||
|
|
||||||
val album = parseBody(
|
|
||||||
client.get("/rest/getMusicDirectory?$auth&id=${seed.aliceAlbumId}").bodyAsText(),
|
|
||||||
)["directory"]!!.jsonObject
|
|
||||||
assertEquals(seed.aliceSongId, album["child"]!!.jsonArray[0].jsonObject["id"]!!.jsonPrimitive.content)
|
|
||||||
|
|
||||||
client.get("/rest/savePlayQueue?$auth&id=${seed.aliceSongId}&position=1000")
|
|
||||||
val queue = parseBody(client.get("/rest/getPlayQueue?$auth").bodyAsText())["playQueue"]!!
|
|
||||||
.jsonObject
|
|
||||||
assertEquals(seed.aliceSongId, queue["entry"]!!.jsonArray[0].jsonObject["id"]!!.jsonPrimitive.content)
|
|
||||||
assertEquals(1000, queue["position"]!!.jsonPrimitive.int)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `music directory exposes artist albums for folder browsing`() {
|
|
||||||
seededContext().use { seed ->
|
|
||||||
testApplication {
|
|
||||||
setupApp(seed)
|
|
||||||
val auth = credentials("alice", "alice-pw")
|
|
||||||
|
|
||||||
val artist = parseBody(
|
|
||||||
client.get("/rest/getMusicDirectory?$auth&id=${seed.aliceArtistId}").bodyAsText(),
|
|
||||||
)["directory"]!!.jsonObject
|
|
||||||
assertEquals(seed.aliceArtistId, artist["id"]!!.jsonPrimitive.content)
|
|
||||||
|
|
||||||
val albums = artist["child"]!!.jsonArray
|
|
||||||
assertEquals(1, albums.size)
|
|
||||||
assertEquals(seed.aliceAlbumId, albums[0].jsonObject["id"]!!.jsonPrimitive.content)
|
|
||||||
assertEquals(seed.aliceArtistId, albums[0].jsonObject["parent"]!!.jsonPrimitive.content)
|
|
||||||
assertEquals("true", albums[0].jsonObject["isDir"]!!.jsonPrimitive.content)
|
|
||||||
|
|
||||||
val album = parseBody(
|
|
||||||
client.get("/rest/getMusicDirectory?$auth&id=${seed.aliceAlbumId}").bodyAsText(),
|
|
||||||
)["directory"]!!.jsonObject
|
|
||||||
assertEquals(seed.aliceSongId, album["child"]!!.jsonArray[0].jsonObject["id"]!!.jsonPrimitive.content)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `lyrics endpoint returns an empty structure when the song has no lyrics`() {
|
|
||||||
seededContext().use { seed ->
|
|
||||||
testApplication {
|
|
||||||
setupApp(seed)
|
|
||||||
val auth = credentials("alice", "alice-pw")
|
|
||||||
|
|
||||||
val body = parseBody(
|
|
||||||
client.get("/rest/getLyricsBySongId?$auth&id=${seed.aliceSongId}").bodyAsText(),
|
|
||||||
)
|
|
||||||
val lyricsList = body["lyricsList"]!!.jsonObject
|
|
||||||
assertEquals(0, lyricsList["structuredLyrics"]?.jsonArray?.size ?: 0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun ApplicationTestBuilder.setupApp(seed: Seed) {
|
|
||||||
application {
|
|
||||||
install(ContentNegotiation) {
|
|
||||||
json(Json { ignoreUnknownKeys = true; encodeDefaults = true })
|
|
||||||
}
|
|
||||||
install(PartialContent)
|
|
||||||
routing {
|
|
||||||
subsonicRoutes(
|
|
||||||
users = seed.users,
|
|
||||||
library = seed.library,
|
|
||||||
coverArtService = seed.coverArt,
|
|
||||||
transcoder = FfmpegTranscoder("ffmpeg"),
|
|
||||||
moodService = MoodService(CoroutineScope(Dispatchers.Unconfined)),
|
|
||||||
startScan = { false },
|
|
||||||
scanStatus = { ScanStatus(false, 0) },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun seededContext(): Seed {
|
|
||||||
val musicA = Files.createDirectories(tempDir.resolve("music-a"))
|
|
||||||
val musicB = Files.createDirectories(tempDir.resolve("music-b"))
|
|
||||||
val longform = Files.createDirectories(tempDir.resolve("longform"))
|
|
||||||
|
|
||||||
val library = LibraryConfig(
|
|
||||||
listOf(
|
|
||||||
MusicFolder(1, "Alice Music", FolderType.MUSIC, musicA),
|
|
||||||
MusicFolder(2, "Bob Music", FolderType.MUSIC, musicB),
|
|
||||||
MusicFolder(10, "Long-form", FolderType.LONGFORM, longform),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
val users = UsersConfig(
|
|
||||||
listOf(
|
|
||||||
UserAccount("alice", "alice-pw", admin = true, folders = setOf(1)),
|
|
||||||
UserAccount("bob", "bob-pw", admin = false, folders = setOf(2)),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
val db = DatabaseFactory.connect(
|
|
||||||
AppConfig(
|
|
||||||
port = 8080,
|
|
||||||
dataDir = tempDir.resolve("data"),
|
|
||||||
libraryConfigPath = tempDir.resolve("library.yaml"),
|
|
||||||
usersFile = tempDir.resolve("users.yaml"),
|
|
||||||
ffmpegPath = "ffmpeg",
|
|
||||||
),
|
|
||||||
)
|
|
||||||
ConfigRepository.sync(library, users)
|
|
||||||
|
|
||||||
val aliceAudio = musicA.resolve("Alice Artist/Alice Album/song.mp3")
|
|
||||||
Files.createDirectories(aliceAudio.parent)
|
|
||||||
val audioBytes = "ID3-fake-audio-payload".toByteArray()
|
|
||||||
Files.write(aliceAudio, audioBytes)
|
|
||||||
|
|
||||||
val bobAudio = musicB.resolve("Bob Artist/Bob Album/song.mp3")
|
|
||||||
Files.createDirectories(bobAudio.parent)
|
|
||||||
Files.write(bobAudio, "ID3-bob".toByteArray())
|
|
||||||
|
|
||||||
val alice = seedSong(
|
|
||||||
db = db,
|
|
||||||
folderId = 1,
|
|
||||||
artistName = "Alice Artist",
|
|
||||||
albumName = "Alice Album",
|
|
||||||
title = "Alice Song",
|
|
||||||
relativePath = "Alice Artist/Alice Album/song.mp3",
|
|
||||||
genre = "Rock",
|
|
||||||
fileSize = Files.size(aliceAudio),
|
|
||||||
)
|
|
||||||
val bob = seedSong(
|
|
||||||
db = db,
|
|
||||||
folderId = 2,
|
|
||||||
artistName = "Bob Artist",
|
|
||||||
albumName = "Bob Album",
|
|
||||||
title = "Bob Song",
|
|
||||||
relativePath = "Bob Artist/Bob Album/song.mp3",
|
|
||||||
genre = "Jazz",
|
|
||||||
fileSize = Files.size(bobAudio),
|
|
||||||
)
|
|
||||||
|
|
||||||
val coverArt = CoverArtService(tempDir.resolve("data"))
|
|
||||||
val coverPng = tempDir.resolve("cover.png")
|
|
||||||
TestAudio.writePng(coverPng, 64, 64)
|
|
||||||
coverArt.saveCover(alice.albumId, Files.readAllBytes(coverPng))
|
|
||||||
MediaRepository.setAlbumCover(alice.albumId)
|
|
||||||
|
|
||||||
return Seed(
|
|
||||||
db = db,
|
|
||||||
library = library,
|
|
||||||
users = users,
|
|
||||||
coverArt = coverArt,
|
|
||||||
aliceArtistId = alice.artistId,
|
|
||||||
aliceAlbumId = alice.albumId,
|
|
||||||
aliceSongId = alice.songId,
|
|
||||||
bobArtistId = bob.artistId,
|
|
||||||
bobAlbumId = bob.albumId,
|
|
||||||
bobSongId = bob.songId,
|
|
||||||
aliceAudioBytes = audioBytes,
|
|
||||||
aliceFileSize = Files.size(aliceAudio),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun seedSong(
|
|
||||||
db: DatabaseHandle,
|
|
||||||
folderId: Int,
|
|
||||||
artistName: String,
|
|
||||||
albumName: String,
|
|
||||||
title: String,
|
|
||||||
relativePath: String,
|
|
||||||
genre: String,
|
|
||||||
fileSize: Long,
|
|
||||||
): SeededSong {
|
|
||||||
val artistId = IdGenerator.artistId(artistName)
|
|
||||||
val albumId = IdGenerator.albumId(artistName, albumName)
|
|
||||||
val songId = IdGenerator.songId(folderId, relativePath)
|
|
||||||
val now = Instant.now().toString()
|
|
||||||
|
|
||||||
transaction(db.database) {
|
|
||||||
ArtistsTable.insert {
|
|
||||||
it[id] = artistId
|
|
||||||
it[name] = artistName
|
|
||||||
it[sortName] = artistName
|
|
||||||
it[searchText] = IdGenerator.normalize(artistName)
|
|
||||||
}
|
|
||||||
AlbumsTable.insert {
|
|
||||||
it[id] = albumId
|
|
||||||
it[name] = albumName
|
|
||||||
it[year] = 2026
|
|
||||||
it[createdAt] = now
|
|
||||||
it[searchText] = IdGenerator.normalize("$albumName $artistName")
|
|
||||||
}
|
|
||||||
AlbumArtistsTable.insert {
|
|
||||||
it[this.albumId] = albumId
|
|
||||||
it[this.artistId] = artistId
|
|
||||||
it[position] = 0
|
|
||||||
}
|
|
||||||
SongsTable.insert {
|
|
||||||
it[id] = songId
|
|
||||||
it[this.albumId] = albumId
|
|
||||||
it[this.folderId] = folderId
|
|
||||||
it[this.title] = title
|
|
||||||
it[displayArtist] = artistName
|
|
||||||
it[this.albumName] = albumName
|
|
||||||
it[trackNumber] = 1
|
|
||||||
it[discNumber] = 1
|
|
||||||
it[year] = 2026
|
|
||||||
it[duration] = 120
|
|
||||||
it[bitRate] = 128
|
|
||||||
it[size] = fileSize
|
|
||||||
it[suffix] = "mp3"
|
|
||||||
it[contentType] = "audio/mpeg"
|
|
||||||
it[this.relativePath] = relativePath
|
|
||||||
it[fileMtime] = 0
|
|
||||||
it[createdAt] = now
|
|
||||||
it[searchText] = IdGenerator.normalize("$title $artistName $albumName $artistName")
|
|
||||||
}
|
|
||||||
SongArtistsTable.insert {
|
|
||||||
it[this.songId] = songId
|
|
||||||
it[this.artistId] = artistId
|
|
||||||
it[position] = 0
|
|
||||||
}
|
|
||||||
SongGenresTable.insert {
|
|
||||||
it[this.songId] = songId
|
|
||||||
it[this.genre] = genre
|
|
||||||
}
|
|
||||||
AlbumGenresTable.insert {
|
|
||||||
it[this.albumId] = albumId
|
|
||||||
it[this.genre] = genre
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return SeededSong(artistId, albumId, songId)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun credentials(user: String, password: String): String {
|
|
||||||
val salt = "test-salt"
|
|
||||||
return "u=$user&t=${SubsonicAuthenticator.md5Hex(password + salt)}&s=$salt"
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun parseBody(body: String): JsonObject =
|
|
||||||
Json.parseToJsonElement(body).jsonObject["subsonic-response"]!!.jsonObject
|
|
||||||
|
|
||||||
private fun parseSearch(body: String): JsonObject =
|
|
||||||
parseBody(body)["searchResult3"]!!.jsonObject
|
|
||||||
|
|
||||||
private fun folderIds(body: JsonObject): List<Int> =
|
|
||||||
body["musicFolders"]!!.jsonObject["musicFolder"]!!.jsonArray
|
|
||||||
.map { it.jsonObject["id"]!!.jsonPrimitive.int }
|
|
||||||
|
|
||||||
private data class SeededSong(val artistId: String, val albumId: String, val songId: String)
|
|
||||||
|
|
||||||
private data class Seed(
|
|
||||||
val db: DatabaseHandle,
|
|
||||||
val library: LibraryConfig,
|
|
||||||
val users: UsersConfig,
|
|
||||||
val coverArt: CoverArtService,
|
|
||||||
val aliceArtistId: String,
|
|
||||||
val aliceAlbumId: String,
|
|
||||||
val aliceSongId: String,
|
|
||||||
val bobArtistId: String,
|
|
||||||
val bobAlbumId: String,
|
|
||||||
val bobSongId: String,
|
|
||||||
val aliceAudioBytes: ByteArray,
|
|
||||||
val aliceFileSize: Long,
|
|
||||||
) : AutoCloseable {
|
|
||||||
override fun close() = db.close()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,410 +0,0 @@
|
|||||||
package win.taptap.musicmanager.subsonic
|
|
||||||
|
|
||||||
import io.ktor.client.HttpClient
|
|
||||||
import io.ktor.client.request.get
|
|
||||||
import io.ktor.client.statement.bodyAsText
|
|
||||||
import io.ktor.serialization.kotlinx.json.json
|
|
||||||
import io.ktor.server.application.install
|
|
||||||
import io.ktor.server.plugins.contentnegotiation.ContentNegotiation
|
|
||||||
import io.ktor.server.plugins.partialcontent.PartialContent
|
|
||||||
import io.ktor.server.routing.routing
|
|
||||||
import io.ktor.server.testing.ApplicationTestBuilder
|
|
||||||
import io.ktor.server.testing.testApplication
|
|
||||||
import java.nio.file.Files
|
|
||||||
import java.nio.file.Path
|
|
||||||
import java.time.Instant
|
|
||||||
import kotlinx.coroutines.CoroutineScope
|
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
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 org.jetbrains.exposed.sql.insert
|
|
||||||
import org.jetbrains.exposed.sql.insertIgnore
|
|
||||||
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
|
|
||||||
import win.taptap.musicmanager.db.AlbumArtistsTable
|
|
||||||
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.SongArtistsTable
|
|
||||||
import win.taptap.musicmanager.db.SongGenresTable
|
|
||||||
import win.taptap.musicmanager.db.SongsTable
|
|
||||||
import win.taptap.musicmanager.mood.MoodService
|
|
||||||
import win.taptap.musicmanager.mood.MoodSessionTracker
|
|
||||||
import win.taptap.musicmanager.scanner.CoverArtService
|
|
||||||
import win.taptap.musicmanager.scanner.ScanStatus
|
|
||||||
import win.taptap.musicmanager.subsonic.routes.subsonicRoutes
|
|
||||||
import win.taptap.musicmanager.transcoding.FfmpegTranscoder
|
|
||||||
import win.taptap.musicmanager.util.IdGenerator
|
|
||||||
|
|
||||||
class MoodRoutesTest {
|
|
||||||
|
|
||||||
@TempDir
|
|
||||||
lateinit var tempDir: Path
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `creating a mood generates a private music-only playlist`() {
|
|
||||||
clearSessions()
|
|
||||||
seededContext().use { seed ->
|
|
||||||
testApplication {
|
|
||||||
setupApp(seed)
|
|
||||||
val auth = credentials("alice", "alice-pw")
|
|
||||||
|
|
||||||
val mood = client.createMood(auth, "Focus", listOf(seed.aliceAmbient1), target = 10)
|
|
||||||
val id = mood.string("id")
|
|
||||||
assertEquals(1, mood.int("seedCount"))
|
|
||||||
assertTrue(mood.string("generatedAt").isNotBlank())
|
|
||||||
|
|
||||||
val entries = mood.ids("entry")
|
|
||||||
assertTrue(seed.aliceAmbient1 in entries)
|
|
||||||
assertTrue(seed.aliceAmbient2 in entries)
|
|
||||||
assertFalse(seed.bobSong in entries)
|
|
||||||
assertFalse(seed.longformSong in entries)
|
|
||||||
|
|
||||||
// A long-form song is not a valid mood seed and must not enter the mix.
|
|
||||||
val bookish = client.createMood(auth, "Bookish", listOf(seed.longformSong), target = 5)
|
|
||||||
assertEquals(0, bookish.int("seedCount"))
|
|
||||||
assertEquals(0, bookish.ids("entry").size)
|
|
||||||
|
|
||||||
val playlist = parseBody(
|
|
||||||
client.get("/rest/getPlaylist?$auth&id=$id").bodyAsText(),
|
|
||||||
)["playlist"]!!.jsonObject
|
|
||||||
assertEquals("Focus", playlist.string("name"))
|
|
||||||
assertEquals(entries.size, playlist["entry"]!!.jsonArray.size)
|
|
||||||
|
|
||||||
val bobAuth = credentials("bob", "bob-pw")
|
|
||||||
val bobMoods = parseBody(client.get("/rest/getMoods?$bobAuth").bodyAsText())["moods"]!!.jsonObject
|
|
||||||
assertEquals(0, bobMoods["mood"]?.jsonArray?.size ?: 0)
|
|
||||||
|
|
||||||
val denied = parseBody(client.get("/rest/getPlaylist?$bobAuth&id=$id").bodyAsText())
|
|
||||||
assertEquals(70, denied["error"]!!.jsonObject["code"]!!.jsonPrimitive.int)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `promoting a playlist keeps its id and rejects song edits`() {
|
|
||||||
clearSessions()
|
|
||||||
seededContext().use { seed ->
|
|
||||||
testApplication {
|
|
||||||
setupApp(seed)
|
|
||||||
val auth = credentials("alice", "alice-pw")
|
|
||||||
|
|
||||||
val playlist = parseBody(
|
|
||||||
client.get(
|
|
||||||
"/rest/createPlaylist?$auth&name=Road&songId=${seed.aliceAmbient1}&songId=${seed.aliceAmbient2}",
|
|
||||||
).bodyAsText(),
|
|
||||||
)["playlist"]!!.jsonObject
|
|
||||||
val id = playlist.string("id")
|
|
||||||
|
|
||||||
val promoted = parseBody(
|
|
||||||
client.get("/rest/promotePlaylistToMood?$auth&playlistId=$id&targetSize=10").bodyAsText(),
|
|
||||||
)["mood"]!!.jsonObject
|
|
||||||
assertEquals(id, promoted.string("id"))
|
|
||||||
assertEquals(2, promoted.int("seedCount"))
|
|
||||||
assertEquals(2, promoted.ids("seed").size)
|
|
||||||
assertTrue(seed.aliceAmbient1 in promoted.ids("entry"))
|
|
||||||
|
|
||||||
val edit = parseBody(
|
|
||||||
client.get(
|
|
||||||
"/rest/updatePlaylist?$auth&playlistId=$id&songIdToAdd=${seed.aliceRock}",
|
|
||||||
).bodyAsText(),
|
|
||||||
)
|
|
||||||
assertEquals(50, edit["error"]!!.jsonObject["code"]!!.jsonPrimitive.int)
|
|
||||||
|
|
||||||
val bobAuth = credentials("bob", "bob-pw")
|
|
||||||
val denied = parseBody(client.get("/rest/getPlaylist?$bobAuth&id=$id").bodyAsText())
|
|
||||||
assertEquals(70, denied["error"]!!.jsonObject["code"]!!.jsonPrimitive.int)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `star pins to the active mood and unstar removes only star seeds`() {
|
|
||||||
clearSessions()
|
|
||||||
seededContext().use { seed ->
|
|
||||||
testApplication {
|
|
||||||
setupApp(seed)
|
|
||||||
val auth = credentials("alice", "alice-pw")
|
|
||||||
|
|
||||||
val mood = client.createMood(
|
|
||||||
auth,
|
|
||||||
"Pinned",
|
|
||||||
listOf(seed.aliceAmbient1),
|
|
||||||
target = 10,
|
|
||||||
expandRelated = false,
|
|
||||||
)
|
|
||||||
val id = mood.string("id")
|
|
||||||
|
|
||||||
// Opening the mood makes it active.
|
|
||||||
client.get("/rest/getPlaylist?$auth&id=$id").bodyAsText()
|
|
||||||
|
|
||||||
val star = parseBody(client.get("/rest/star?$auth&id=${seed.aliceAmbient2}").bodyAsText())
|
|
||||||
assertEquals("ok", star.string("status"))
|
|
||||||
|
|
||||||
val afterStar = parseBody(client.get("/rest/getMood?$auth&id=$id").bodyAsText())["mood"]!!.jsonObject
|
|
||||||
assertEquals(2, afterStar.int("seedCount"))
|
|
||||||
assertTrue(seed.aliceAmbient2 in afterStar.ids("seed"))
|
|
||||||
assertTrue(seed.aliceAmbient1 in afterStar.ids("seed"))
|
|
||||||
|
|
||||||
val refreshed = parseBody(client.get("/rest/refreshMood?$auth&id=$id").bodyAsText())["mood"]!!.jsonObject
|
|
||||||
assertTrue(seed.aliceAmbient2 in refreshed.ids("entry"))
|
|
||||||
|
|
||||||
parseBody(client.get("/rest/unstar?$auth&id=${seed.aliceAmbient2}").bodyAsText())
|
|
||||||
val afterUnstar = parseBody(client.get("/rest/getMood?$auth&id=$id").bodyAsText())["mood"]!!.jsonObject
|
|
||||||
assertEquals(1, afterUnstar.int("seedCount"))
|
|
||||||
assertTrue(seed.aliceAmbient1 in afterUnstar.ids("seed"))
|
|
||||||
assertFalse(seed.aliceAmbient2 in afterUnstar.ids("seed"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `star without a session pins moods that already contain the song`() {
|
|
||||||
clearSessions()
|
|
||||||
seededContext().use { seed ->
|
|
||||||
testApplication {
|
|
||||||
setupApp(seed)
|
|
||||||
val auth = credentials("alice", "alice-pw")
|
|
||||||
|
|
||||||
val mood = client.createMood(auth, "Related", listOf(seed.aliceAmbient1), target = 10)
|
|
||||||
val id = mood.string("id")
|
|
||||||
assertTrue(seed.aliceAmbient2 in mood.ids("entry"))
|
|
||||||
|
|
||||||
// No getPlaylist call: there is no active mood session.
|
|
||||||
parseBody(client.get("/rest/star?$auth&id=${seed.aliceAmbient2}").bodyAsText())
|
|
||||||
|
|
||||||
val afterStar = parseBody(client.get("/rest/getMood?$auth&id=$id").bodyAsText())["mood"]!!.jsonObject
|
|
||||||
assertEquals(2, afterStar.int("seedCount"))
|
|
||||||
assertTrue(seed.aliceAmbient2 in afterStar.ids("seed"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun ApplicationTestBuilder.setupApp(seed: Seed) {
|
|
||||||
application {
|
|
||||||
install(ContentNegotiation) {
|
|
||||||
json(Json { ignoreUnknownKeys = true; encodeDefaults = true })
|
|
||||||
}
|
|
||||||
install(PartialContent)
|
|
||||||
routing {
|
|
||||||
subsonicRoutes(
|
|
||||||
users = seed.users,
|
|
||||||
library = seed.library,
|
|
||||||
coverArtService = seed.coverArt,
|
|
||||||
transcoder = FfmpegTranscoder("ffmpeg"),
|
|
||||||
moodService = MoodService(CoroutineScope(Dispatchers.Unconfined)),
|
|
||||||
startScan = { false },
|
|
||||||
scanStatus = { ScanStatus(false, 0) },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun seededContext(): Seed {
|
|
||||||
val musicA = Files.createDirectories(tempDir.resolve("music-a"))
|
|
||||||
val musicB = Files.createDirectories(tempDir.resolve("music-b"))
|
|
||||||
val longform = Files.createDirectories(tempDir.resolve("longform"))
|
|
||||||
|
|
||||||
val library = LibraryConfig(
|
|
||||||
listOf(
|
|
||||||
MusicFolder(1, "Alice Music", FolderType.MUSIC, musicA),
|
|
||||||
MusicFolder(2, "Bob Music", FolderType.MUSIC, musicB),
|
|
||||||
MusicFolder(10, "Long-form", FolderType.LONGFORM, longform),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
val users = UsersConfig(
|
|
||||||
listOf(
|
|
||||||
UserAccount("alice", "alice-pw", admin = true, folders = setOf(1)),
|
|
||||||
UserAccount("bob", "bob-pw", admin = false, folders = setOf(2)),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
val db = DatabaseFactory.connect(
|
|
||||||
AppConfig(
|
|
||||||
port = 8080,
|
|
||||||
dataDir = tempDir.resolve("data"),
|
|
||||||
libraryConfigPath = tempDir.resolve("library.yaml"),
|
|
||||||
usersFile = tempDir.resolve("users.yaml"),
|
|
||||||
ffmpegPath = "ffmpeg",
|
|
||||||
),
|
|
||||||
)
|
|
||||||
ConfigRepository.sync(library, users)
|
|
||||||
|
|
||||||
val aliceAmbient1 = seedSong(
|
|
||||||
db, 1, "Alpha", "Focus One", "Deep Work",
|
|
||||||
"Alpha/Focus One/01.mp3", "Ambient", musicA,
|
|
||||||
)
|
|
||||||
val aliceAmbient2 = seedSong(
|
|
||||||
db, 1, "Beta", "Focus Two", "Soft Light",
|
|
||||||
"Beta/Focus Two/01.mp3", "Ambient", musicA,
|
|
||||||
)
|
|
||||||
val aliceRock = seedSong(
|
|
||||||
db, 1, "Gamma", "Loud", "Noise",
|
|
||||||
"Gamma/Loud/01.mp3", "Rock", musicA,
|
|
||||||
)
|
|
||||||
val aliceAmbient3 = seedSong(
|
|
||||||
db, 1, "Alpha", "Focus One", "Second Wind",
|
|
||||||
"Alpha/Focus One/02.mp3", "Ambient", musicA,
|
|
||||||
)
|
|
||||||
val bobSong = seedSong(
|
|
||||||
db, 2, "Bob Artist", "Bob Album", "Bob Song",
|
|
||||||
"Bob Artist/Bob Album/01.mp3", "Ambient", musicB,
|
|
||||||
)
|
|
||||||
val longformSong = seedSong(
|
|
||||||
db, 10, "Long Narrator", "Long Book", "Chapter One",
|
|
||||||
"Long Narrator/Long Book/01.mp3", "Ambient", longform,
|
|
||||||
)
|
|
||||||
|
|
||||||
return Seed(
|
|
||||||
db = db,
|
|
||||||
library = library,
|
|
||||||
users = users,
|
|
||||||
coverArt = CoverArtService(tempDir.resolve("data")),
|
|
||||||
aliceAmbient1 = aliceAmbient1,
|
|
||||||
aliceAmbient2 = aliceAmbient2,
|
|
||||||
aliceRock = aliceRock,
|
|
||||||
aliceAmbient3 = aliceAmbient3,
|
|
||||||
bobSong = bobSong,
|
|
||||||
longformSong = longformSong,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun seedSong(
|
|
||||||
db: DatabaseHandle,
|
|
||||||
folderId: Int,
|
|
||||||
artistName: String,
|
|
||||||
albumName: String,
|
|
||||||
title: String,
|
|
||||||
relativePath: String,
|
|
||||||
genre: String,
|
|
||||||
root: Path,
|
|
||||||
): String {
|
|
||||||
val file = root.resolve(relativePath)
|
|
||||||
Files.createDirectories(file.parent)
|
|
||||||
Files.write(file, "ID3-fake-audio".toByteArray())
|
|
||||||
|
|
||||||
val artistId = IdGenerator.artistId(artistName)
|
|
||||||
val albumId = IdGenerator.albumId(artistName, albumName)
|
|
||||||
val songId = IdGenerator.songId(folderId, relativePath)
|
|
||||||
val now = Instant.now().toString()
|
|
||||||
|
|
||||||
transaction(db.database) {
|
|
||||||
ArtistsTable.insertIgnore {
|
|
||||||
it[id] = artistId
|
|
||||||
it[name] = artistName
|
|
||||||
it[sortName] = artistName
|
|
||||||
it[searchText] = IdGenerator.normalize(artistName)
|
|
||||||
}
|
|
||||||
AlbumsTable.insertIgnore {
|
|
||||||
it[id] = albumId
|
|
||||||
it[name] = albumName
|
|
||||||
it[year] = 2026
|
|
||||||
it[createdAt] = now
|
|
||||||
it[searchText] = IdGenerator.normalize("$albumName $artistName")
|
|
||||||
}
|
|
||||||
AlbumArtistsTable.insertIgnore {
|
|
||||||
it[this.albumId] = albumId
|
|
||||||
it[this.artistId] = artistId
|
|
||||||
it[position] = 0
|
|
||||||
}
|
|
||||||
SongsTable.insert {
|
|
||||||
it[id] = songId
|
|
||||||
it[this.albumId] = albumId
|
|
||||||
it[this.folderId] = folderId
|
|
||||||
it[this.title] = title
|
|
||||||
it[displayArtist] = artistName
|
|
||||||
it[this.albumName] = albumName
|
|
||||||
it[trackNumber] = 1
|
|
||||||
it[discNumber] = 1
|
|
||||||
it[year] = 2026
|
|
||||||
it[duration] = 120
|
|
||||||
it[bitRate] = 128
|
|
||||||
it[size] = Files.size(file)
|
|
||||||
it[suffix] = "mp3"
|
|
||||||
it[contentType] = "audio/mpeg"
|
|
||||||
it[this.relativePath] = relativePath
|
|
||||||
it[fileMtime] = 0
|
|
||||||
it[createdAt] = now
|
|
||||||
it[searchText] = IdGenerator.normalize("$title $artistName $albumName $artistName")
|
|
||||||
}
|
|
||||||
SongArtistsTable.insert {
|
|
||||||
it[this.songId] = songId
|
|
||||||
it[this.artistId] = artistId
|
|
||||||
it[position] = 0
|
|
||||||
}
|
|
||||||
SongGenresTable.insert {
|
|
||||||
it[this.songId] = songId
|
|
||||||
it[this.genre] = genre
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return songId
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun HttpClient.createMood(
|
|
||||||
auth: String,
|
|
||||||
name: String,
|
|
||||||
seeds: List<String>,
|
|
||||||
target: Int,
|
|
||||||
expandRelated: Boolean = true,
|
|
||||||
): JsonObject {
|
|
||||||
val seedParams = seeds.joinToString("") { "&songId=$it" }
|
|
||||||
val body = get(
|
|
||||||
"/rest/createMood?$auth&name=$name$seedParams&targetSize=$target&expandRelated=$expandRelated",
|
|
||||||
).bodyAsText()
|
|
||||||
return parseBody(body)["mood"]!!.jsonObject
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun clearSessions() {
|
|
||||||
MoodSessionTracker.clear("alice")
|
|
||||||
MoodSessionTracker.clear("bob")
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun credentials(user: String, password: String): String {
|
|
||||||
val salt = "test-salt"
|
|
||||||
return "u=$user&t=${SubsonicAuthenticator.md5Hex(password + salt)}&s=$salt"
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun parseBody(body: String): JsonObject =
|
|
||||||
Json.parseToJsonElement(body).jsonObject["subsonic-response"]!!.jsonObject
|
|
||||||
|
|
||||||
private fun JsonObject.string(name: String): String =
|
|
||||||
this[name]!!.jsonPrimitive.content
|
|
||||||
|
|
||||||
private fun JsonObject.int(name: String): Int =
|
|
||||||
this[name]!!.jsonPrimitive.int
|
|
||||||
|
|
||||||
private fun JsonObject.ids(name: String): List<String> =
|
|
||||||
this[name]!!.jsonArray.map { it.jsonObject["id"]!!.jsonPrimitive.content }
|
|
||||||
|
|
||||||
private data class Seed(
|
|
||||||
val db: DatabaseHandle,
|
|
||||||
val library: LibraryConfig,
|
|
||||||
val users: UsersConfig,
|
|
||||||
val coverArt: CoverArtService,
|
|
||||||
val aliceAmbient1: String,
|
|
||||||
val aliceAmbient2: String,
|
|
||||||
val aliceRock: String,
|
|
||||||
val aliceAmbient3: String,
|
|
||||||
val bobSong: String,
|
|
||||||
val longformSong: String,
|
|
||||||
) : AutoCloseable {
|
|
||||||
override fun close() = db.close()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,68 +0,0 @@
|
|||||||
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<String, String>): Parameters = Parameters.build {
|
|
||||||
pairs.forEach { (key, value) -> append(key, value) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,212 +0,0 @@
|
|||||||
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.coroutines.CoroutineScope
|
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
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 org.junit.jupiter.api.io.TempDir
|
|
||||||
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.mood.MoodService
|
|
||||||
import win.taptap.musicmanager.scanner.CoverArtService
|
|
||||||
import win.taptap.musicmanager.scanner.ScanStatus
|
|
||||||
import win.taptap.musicmanager.subsonic.routes.subsonicRoutes
|
|
||||||
import win.taptap.musicmanager.transcoding.FfmpegTranscoder
|
|
||||||
|
|
||||||
class SystemRoutesTest {
|
|
||||||
|
|
||||||
@TempDir
|
|
||||||
lateinit var tempDir: java.nio.file.Path
|
|
||||||
|
|
||||||
@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)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `getUser returns roles and folder ids with admin restrictions`() = testApplication {
|
|
||||||
setupApp()
|
|
||||||
|
|
||||||
val own = parse(client.get("/rest/getUser?${credentials()}&username=alice").bodyAsText())
|
|
||||||
val alice = own["user"]!!.jsonObject
|
|
||||||
assertEquals("alice", alice.string("username"))
|
|
||||||
assertEquals("true", alice["adminRole"]!!.jsonPrimitive.content)
|
|
||||||
assertEquals("true", alice["downloadRole"]!!.jsonPrimitive.content)
|
|
||||||
assertEquals(listOf(1), alice["folder"]!!.jsonArray.map { it.jsonPrimitive.int })
|
|
||||||
|
|
||||||
val other = parse(client.get("/rest/getUser?${credentials()}&username=bob").bodyAsText())
|
|
||||||
assertEquals("bob", other["user"]!!.jsonObject.string("username"))
|
|
||||||
|
|
||||||
val forbidden = parse(client.get("/rest/getUser?${credentials(user = "bob")}&username=alice").bodyAsText())
|
|
||||||
assertEquals("failed", forbidden.string("status"))
|
|
||||||
assertEquals(50, forbidden["error"]!!.jsonObject["code"]!!.jsonPrimitive.int)
|
|
||||||
|
|
||||||
val missing = parse(client.get("/rest/getUser?${credentials()}").bodyAsText())
|
|
||||||
assertEquals(10, missing["error"]!!.jsonObject["code"]!!.jsonPrimitive.int)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `jukebox and internet radio endpoints return valid empty responses`() = testApplication {
|
|
||||||
setupApp()
|
|
||||||
|
|
||||||
val jukebox = parse(client.get("/rest/jukeboxControl?${credentials()}&action=status").bodyAsText())
|
|
||||||
assertEquals("false", jukebox["jukeboxStatus"]!!.jsonObject["playing"]!!.jsonPrimitive.content)
|
|
||||||
|
|
||||||
val radio = parse(client.get("/rest/getInternetRadioStations?${credentials()}").bodyAsText())
|
|
||||||
assertEquals(
|
|
||||||
0,
|
|
||||||
radio["internetRadioStations"]!!.jsonObject["internetRadioStation"]!!.jsonArray.size,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `getUsers is admin only`() = testApplication {
|
|
||||||
setupApp()
|
|
||||||
|
|
||||||
val admin = parse(client.get("/rest/getUsers?${credentials()}").bodyAsText())
|
|
||||||
val names = admin["users"]!!.jsonObject["user"]!!.jsonArray
|
|
||||||
.map { it.jsonObject.string("username") }
|
|
||||||
assertEquals(setOf("alice", "bob"), names.toSet())
|
|
||||||
|
|
||||||
val regular = parse(client.get("/rest/getUsers?${credentials(user = "bob")}").bodyAsText())
|
|
||||||
assertEquals(50, regular["error"]!!.jsonObject["code"]!!.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,
|
|
||||||
library = LibraryConfig(
|
|
||||||
listOf(MusicFolder(1, "Music", FolderType.MUSIC, tempDir)),
|
|
||||||
),
|
|
||||||
coverArtService = CoverArtService(tempDir.resolve("data")),
|
|
||||||
transcoder = FfmpegTranscoder("ffmpeg"),
|
|
||||||
moodService = MoodService(CoroutineScope(Dispatchers.Unconfined)),
|
|
||||||
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)),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Reference in new issue
Block a user