refactor: remove the server-rendered web UI
All browsing and mood management now live in the native client. Drop the embedded HTML page, the WEB_UI setting, the /ui route and the chart env entry; the server only exposes /api/v1, /health and a small root banner.
This commit is contained in:
1 parent
54cf807a9b
commit
bf6c9e7394
6 files changed
+7
-646
No files matched your search
@@ -16,7 +16,6 @@ import io.ktor.server.plugins.partialcontent.PartialContent
|
||||
import io.ktor.server.plugins.statuspages.StatusPages
|
||||
import io.ktor.server.request.path
|
||||
import io.ktor.server.response.respond
|
||||
import io.ktor.server.response.respondRedirect
|
||||
import io.ktor.server.response.respondText
|
||||
import io.ktor.server.routing.get
|
||||
import io.ktor.server.routing.routing
|
||||
@@ -68,12 +67,6 @@ fun main() {
|
||||
scanner.start(applicationScope)
|
||||
}
|
||||
|
||||
val webUiHtml = if (config.webUiEnabled) {
|
||||
AppConfig::class.java.getResource("/web/index.html")?.readText()
|
||||
} else {
|
||||
null
|
||||
}
|
||||
|
||||
val server = embeddedServer(Netty, port = config.port, host = "0.0.0.0") {
|
||||
install(ContentNegotiation) {
|
||||
json(
|
||||
@@ -131,9 +124,11 @@ fun main() {
|
||||
|
||||
routing {
|
||||
get("/health") { call.respondText("ok") }
|
||||
if (webUiHtml != null) {
|
||||
get("/") { call.respondRedirect("/ui") }
|
||||
get("/ui") { call.respondText(webUiHtml, ContentType.Text.Html) }
|
||||
get("/") {
|
||||
call.respondText(
|
||||
"AudioManager\nAPI: /api/v1\nHealth: /health\n",
|
||||
ContentType.Text.Plain,
|
||||
)
|
||||
}
|
||||
apiRoutes(
|
||||
users = users,
|
||||
|
||||
@@ -14,7 +14,6 @@ data class AppConfig(
|
||||
val libraryConfigPath: Path,
|
||||
val usersFile: Path,
|
||||
val ffmpegPath: String,
|
||||
val webUiEnabled: Boolean = true,
|
||||
) {
|
||||
val databasePath: Path get() = dataDir.resolve("musicmanager.db")
|
||||
|
||||
@@ -28,20 +27,12 @@ data class AppConfig(
|
||||
?: throw IllegalArgumentException("PORT must be an integer, got: $rawPort")
|
||||
require(port in 1..65535) { "PORT must be between 1 and 65535, got: $port" }
|
||||
|
||||
val webUi = value("WEB_UI", "true").lowercase()
|
||||
val webUiEnabled = when (webUi) {
|
||||
"true", "1", "yes", "on" -> true
|
||||
"false", "0", "no", "off" -> false
|
||||
else -> throw IllegalArgumentException("WEB_UI must be true or false, got: $webUi")
|
||||
}
|
||||
|
||||
return AppConfig(
|
||||
port = port,
|
||||
dataDir = Path.of(value("DATA_DIR", "./data")),
|
||||
libraryConfigPath = Path.of(value("LIBRARY_CONFIG", "./config/library.yaml")),
|
||||
usersFile = Path.of(value("USERS_FILE", "./config/users.yaml")),
|
||||
ffmpegPath = value("FFMPEG_PATH", "ffmpeg"),
|
||||
webUiEnabled = webUiEnabled,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,614 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>AudioManager</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg:#0d1117; --panel:#161b22; --panel-2:#1c2330; --border:#2b3441;
|
||||
--text:#e6edf3; --muted:#8b98a9; --accent:#7c9cff; --accent-2:#59d3a5;
|
||||
--danger:#ff7b72; --radius:14px;
|
||||
}
|
||||
* { box-sizing:border-box; }
|
||||
body { margin:0; font:15px/1.5 system-ui,-apple-system,Segoe UI,sans-serif; background:var(--bg); color:var(--text); }
|
||||
button, input, select, textarea { font:inherit; }
|
||||
button {
|
||||
background:var(--panel-2); color:var(--text); border:1px solid var(--border);
|
||||
border-radius:10px; padding:8px 14px; cursor:pointer;
|
||||
}
|
||||
button:hover { border-color:#3d4a5c; }
|
||||
button.primary { background:linear-gradient(135deg,#6d8cff,#8f6dff); border:none; color:white; font-weight:600; }
|
||||
button.ghost { background:transparent; }
|
||||
button.danger { color:var(--danger); }
|
||||
input, select, textarea {
|
||||
background:#0f151d; color:var(--text); border:1px solid var(--border);
|
||||
border-radius:10px; padding:9px 12px; width:100%;
|
||||
}
|
||||
a { color:var(--accent); }
|
||||
header {
|
||||
display:flex; align-items:center; gap:12px; padding:14px 22px;
|
||||
border-bottom:1px solid var(--border); position:sticky; top:0; background:rgba(13,17,23,.92);
|
||||
backdrop-filter:blur(10px); z-index:5;
|
||||
}
|
||||
.logo { font-weight:750; letter-spacing:.3px; font-size:17px; }
|
||||
.logo span { color:var(--accent); }
|
||||
.spacer { flex:1; }
|
||||
main { max-width:1080px; margin:0 auto; padding:22px; padding-bottom:130px; }
|
||||
.muted { color:var(--muted); }
|
||||
.row { display:flex; align-items:center; gap:10px; flex-wrap:wrap; }
|
||||
.hidden { display:none !important; }
|
||||
.grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(240px,1fr)); gap:14px; margin-top:18px; }
|
||||
.card {
|
||||
background:linear-gradient(160deg,var(--panel),#131923); border:1px solid var(--border);
|
||||
border-radius:var(--radius); padding:18px; display:flex; flex-direction:column; gap:10px;
|
||||
}
|
||||
.card h3 { margin:0; font-size:18px; }
|
||||
.card .counts { color:var(--muted); font-size:13px; }
|
||||
.card .actions { display:flex; gap:8px; margin-top:auto; }
|
||||
table { width:100%; border-collapse:collapse; margin-top:10px; }
|
||||
th, td { text-align:left; padding:9px 8px; border-bottom:1px solid var(--border); font-size:14px; }
|
||||
th { color:var(--muted); font-weight:600; font-size:12px; text-transform:uppercase; letter-spacing:.6px; }
|
||||
.pill { display:inline-block; padding:2px 9px; border-radius:20px; background:#233047; color:#b9c8e6; font-size:12px; }
|
||||
.error { color:var(--danger); }
|
||||
.ok { color:var(--accent-2); }
|
||||
#login { max-width:380px; margin:12vh auto; padding:26px; background:var(--panel); border:1px solid var(--border); border-radius:18px; }
|
||||
#login h1 { margin:0 0 4px; font-size:24px; }
|
||||
#login .field { margin-top:14px; }
|
||||
form.stack { display:grid; gap:12px; max-width:600px; }
|
||||
label { display:grid; gap:6px; font-size:13px; color:var(--muted); }
|
||||
label.check { display:flex; align-items:center; gap:9px; color:var(--text); }
|
||||
label.check input { width:auto; }
|
||||
#status { position:fixed; bottom:86px; left:50%; transform:translateX(-50%); background:#202a3a; border:1px solid var(--border); border-radius:20px; padding:5px 14px; font-size:12px; color:var(--muted); opacity:0; transition:opacity .2s; pointer-events:none; }
|
||||
#status.show { opacity:1; }
|
||||
#player {
|
||||
position:fixed; left:0; right:0; bottom:0; background:rgba(17,23,32,.97); border-top:1px solid var(--border);
|
||||
padding:12px 22px; display:flex; align-items:center; gap:14px; backdrop-filter:blur(12px);
|
||||
}
|
||||
#player .art { width:52px; height:52px; border-radius:10px; background:#243043; flex:none; overflow:hidden; }
|
||||
#player .art img { width:100%; height:100%; object-fit:cover; }
|
||||
#player .meta { min-width:0; flex:1; }
|
||||
#player .title { font-weight:650; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
||||
#player .sub { color:var(--muted); font-size:13px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
||||
#player .buttons { display:flex; gap:8px; }
|
||||
.modal {
|
||||
position:fixed; inset:0; background:rgba(0,0,0,.6); display:flex; align-items:center;
|
||||
justify-content:center; z-index:20; padding:20px;
|
||||
}
|
||||
.modal .sheet { background:var(--panel); border:1px solid var(--border); border-radius:18px; padding:22px; width:min(460px,100%); max-height:80vh; overflow:auto; }
|
||||
.modal h3 { margin-top:0; }
|
||||
.choice { display:block; width:100%; text-align:left; margin-top:8px; }
|
||||
.empty { padding:40px; text-align:center; color:var(--muted); border:1px dashed var(--border); border-radius:var(--radius); }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<section id="login">
|
||||
<h1>Audio<span style="color:var(--accent)">Manager</span></h1>
|
||||
<p class="muted">Mood-based streaming. Sign in to continue.</p>
|
||||
<form id="loginForm" class="stack">
|
||||
<div class="field"><label>Username<input id="username" autocomplete="username" required></label></div>
|
||||
<div class="field"><label>Password<input id="password" type="password" autocomplete="current-password" required></label></div>
|
||||
<div id="loginStatus" class="error" style="min-height:20px"></div>
|
||||
<button class="primary" type="submit">Sign in</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<div id="app" class="hidden">
|
||||
<header>
|
||||
<div class="logo">Audio<span>Manager</span></div>
|
||||
<button class="ghost" id="moodsBtn">Moods</button>
|
||||
<button class="ghost" id="libraryBtn">Library</button>
|
||||
<span class="spacer"></span>
|
||||
<button class="ghost hidden" id="scanBtn">Scan library</button>
|
||||
<span class="muted" id="whoami"></span>
|
||||
<button class="ghost" id="logoutBtn">Sign out</button>
|
||||
</header>
|
||||
|
||||
<main id="content"></main>
|
||||
|
||||
<div id="status"></div>
|
||||
|
||||
<div id="player" class="hidden">
|
||||
<div class="art"><img id="playerArt" alt=""></div>
|
||||
<div class="meta">
|
||||
<div class="title" id="playerTitle">Nothing playing</div>
|
||||
<div class="sub" id="playerSub"></div>
|
||||
<div class="sub" id="playerMood"></div>
|
||||
</div>
|
||||
<div class="buttons">
|
||||
<button id="addCurrentBtn">Add to mood</button>
|
||||
<button id="chooseMoodBtn">Choose mood</button>
|
||||
<button class="danger" id="skipBtn">Skip</button>
|
||||
</div>
|
||||
<audio id="audio" preload="none"></audio>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const state = {
|
||||
token: localStorage.getItem('am.token') || '',
|
||||
user: null,
|
||||
moods: [],
|
||||
session: null,
|
||||
queue: [],
|
||||
current: null,
|
||||
mode: null,
|
||||
moodId: null,
|
||||
};
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
function esc(value) {
|
||||
return String(value ?? '').replace(/[&<>"']/g, (ch) => ({
|
||||
'&': '&', '<': '<', '>': '>', '"': '"', "'": ''',
|
||||
}[ch]));
|
||||
}
|
||||
|
||||
function toast(message, isError) {
|
||||
const node = $('status');
|
||||
node.textContent = message || '';
|
||||
node.classList.toggle('show', !!message);
|
||||
node.classList.toggle('error', !!isError);
|
||||
clearTimeout(toast.timer);
|
||||
toast.timer = setTimeout(() => node.classList.remove('show'), 3500);
|
||||
}
|
||||
|
||||
async function api(path, options = {}) {
|
||||
const headers = { 'Accept': 'application/json' };
|
||||
if (state.token) headers['Authorization'] = `Bearer ${state.token}`;
|
||||
if (options.body !== undefined) headers['Content-Type'] = 'application/json';
|
||||
|
||||
const response = await fetch(`/api/v1${path}`, {
|
||||
method: options.method || (options.body !== undefined ? 'POST' : 'GET'),
|
||||
headers,
|
||||
body: options.body !== undefined ? JSON.stringify(options.body) : undefined,
|
||||
});
|
||||
|
||||
if (response.status === 401 && state.token) {
|
||||
logout();
|
||||
throw new Error('Session expired, sign in again');
|
||||
}
|
||||
if (response.status === 204) return null;
|
||||
const body = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
throw new Error(body?.error?.message || `Request failed (${response.status})`);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
function mediaUrl(path) {
|
||||
return `/api/v1${path}${path.includes('?') ? '&' : '?'}token=${encodeURIComponent(state.token)}`;
|
||||
}
|
||||
|
||||
async function login(event) {
|
||||
event.preventDefault();
|
||||
const username = $('username').value.trim();
|
||||
const password = $('password').value;
|
||||
if (!username || !password) return;
|
||||
|
||||
$('loginStatus').textContent = 'Signing in...';
|
||||
try {
|
||||
const response = await fetch('/api/v1/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password, deviceName: 'Web', platform: 'web' }),
|
||||
});
|
||||
const body = await response.json().catch(() => ({}));
|
||||
if (!response.ok) throw new Error(body?.error?.message || 'Sign in failed');
|
||||
state.token = body.token;
|
||||
state.user = body.user;
|
||||
localStorage.setItem('am.token', body.token);
|
||||
await start();
|
||||
} catch (error) {
|
||||
$('loginStatus').textContent = error.message;
|
||||
}
|
||||
}
|
||||
|
||||
function logout() {
|
||||
state.token = '';
|
||||
state.user = null;
|
||||
state.session = null;
|
||||
state.queue = [];
|
||||
localStorage.removeItem('am.token');
|
||||
$('audio').pause();
|
||||
$('player').classList.add('hidden');
|
||||
$('app').classList.add('hidden');
|
||||
$('login').classList.remove('hidden');
|
||||
$('username').value = '';
|
||||
$('password').value = '';
|
||||
}
|
||||
|
||||
async function start() {
|
||||
if (!state.user) state.user = await api('/me');
|
||||
$('login').classList.add('hidden');
|
||||
$('app').classList.remove('hidden');
|
||||
$('whoami').textContent = state.user.name;
|
||||
$('scanBtn').classList.toggle('hidden', !state.user.admin);
|
||||
await showMoods();
|
||||
}
|
||||
|
||||
async function showMoods() {
|
||||
state.mode = 'moods';
|
||||
state.moodId = null;
|
||||
$('content').innerHTML = '<p class="muted">Loading moods...</p>';
|
||||
try {
|
||||
state.moods = (await api('/moods')).moods;
|
||||
const cards = state.moods.map((mood) => `
|
||||
<article class="card">
|
||||
<h3>${esc(mood.name)}</h3>
|
||||
<div class="counts">${mood.seedCount} seeds${mood.newRecommendations ? ` · ${mood.newRecommendations} new picks` : ''}</div>
|
||||
${mood.lastError ? `<div class="error" style="font-size:12px">${esc(mood.lastError)}</div>` : ''}
|
||||
<div class="actions">
|
||||
<button class="primary" data-play="${esc(mood.id)}">Play</button>
|
||||
<button data-open="${esc(mood.id)}">Edit</button>
|
||||
</div>
|
||||
</article>`).join('');
|
||||
|
||||
$('content').innerHTML = `
|
||||
<div class="row">
|
||||
<h2 style="margin:0">Moods</h2>
|
||||
<span class="spacer"></span>
|
||||
<button class="primary" id="newMood">New mood</button>
|
||||
</div>
|
||||
<p class="muted">Radio is generated live: each batch mixes seeds, genres and what you finish or skip.</p>
|
||||
${cards ? `<div class="grid">${cards}</div>` : '<div class="empty">No moods yet. Create your first one.</div>'}`;
|
||||
|
||||
$('newMood').onclick = showCreateMood;
|
||||
} catch (error) {
|
||||
$('content').innerHTML = `<p class="error">${esc(error.message)}</p>`;
|
||||
}
|
||||
}
|
||||
|
||||
function showCreateMood() {
|
||||
state.mode = 'create';
|
||||
$('content').innerHTML = `
|
||||
<div class="row"><button class="ghost" id="back">← Moods</button></div>
|
||||
<h2>New mood</h2>
|
||||
<form id="moodForm" class="stack">
|
||||
<label>Name<input name="name" required placeholder="Focus"></label>
|
||||
<label>Description<input name="description" placeholder="Deep work without lyrics"></label>
|
||||
<label>Genres<input name="genres" placeholder="Ambient, Electronic"></label>
|
||||
<label>Free-text hint<input name="query" placeholder="ambient focus"></label>
|
||||
<div class="row">
|
||||
<label style="flex:1">Batch target<input name="targetSize" type="number" min="5" max="500" value="30"></label>
|
||||
<label style="flex:1">Refresh hours<input name="refreshHours" type="number" min="1" max="720" value="24"></label>
|
||||
</div>
|
||||
<label class="check"><input name="ytEnabled" type="checkbox" checked> Enable YT Music discovery</label>
|
||||
<div class="row"><button class="primary" type="submit">Create mood</button></div>
|
||||
</form>`;
|
||||
$('back').onclick = showMoods;
|
||||
$('moodForm').onsubmit = async (event) => {
|
||||
event.preventDefault();
|
||||
const form = new FormData(event.target);
|
||||
try {
|
||||
const created = await api('/moods', {
|
||||
body: {
|
||||
name: form.get('name'),
|
||||
description: form.get('description') || null,
|
||||
query: form.get('query') || null,
|
||||
genres: String(form.get('genres') || '').split(',').map((s) => s.trim()).filter(Boolean),
|
||||
targetSize: Number(form.get('targetSize')),
|
||||
refreshHours: Number(form.get('refreshHours')),
|
||||
ytEnabled: form.get('ytEnabled') === 'on',
|
||||
},
|
||||
});
|
||||
await showMood(created.mood.id);
|
||||
} catch (error) { toast(error.message, true); }
|
||||
};
|
||||
}
|
||||
|
||||
async function showMood(id) {
|
||||
state.mode = 'mood';
|
||||
state.moodId = id;
|
||||
$('content').innerHTML = '<p class="muted">Loading mood...</p>';
|
||||
try {
|
||||
const [detail, preview] = await Promise.all([
|
||||
api(`/moods/${id}`),
|
||||
api(`/moods/${id}/preview?limit=20`),
|
||||
]);
|
||||
const mood = detail.mood;
|
||||
const seeds = detail.seeds;
|
||||
const recommendations = detail.recommendations;
|
||||
|
||||
$('content').innerHTML = `
|
||||
<div class="row"><button class="ghost" id="back">← Moods</button><span class="spacer"></span>
|
||||
<button class="primary" id="play">Play radio</button>
|
||||
<button class="danger" id="delete">Delete</button>
|
||||
</div>
|
||||
<h2 style="margin-bottom:4px">${esc(mood.name)}</h2>
|
||||
<p class="muted">${esc(mood.description || 'No description')} · ${mood.seedCount} seeds · updated ${esc(new Date(mood.changedAt).toLocaleString())}</p>
|
||||
${mood.lastError ? `<p class="error">${esc(mood.lastError)}</p>` : ''}
|
||||
|
||||
<h3>Seeds</h3>
|
||||
${seeds.length ? `<table><tbody>${seeds.map((seed) => `
|
||||
<tr>
|
||||
<td><strong>${esc(seed.song.title)}</strong></td>
|
||||
<td class="muted">${esc(seed.song.artist)}</td>
|
||||
<td><span class="pill">${esc(seed.origin)}</span></td>
|
||||
<td style="text-align:right"><button data-unseed="${esc(seed.song.id)}">Remove</button></td>
|
||||
</tr>`).join('')}</tbody></table>` : '<p class="muted">No seeds. Add a few songs to anchor the mood.</p>'}
|
||||
|
||||
<h3 style="margin-top:28px">Add seeds</h3>
|
||||
<div class="row">
|
||||
<input id="seedQuery" placeholder="Search your music" style="max-width:360px">
|
||||
<button id="seedSearch">Search</button>
|
||||
</div>
|
||||
<div id="seedResults"></div>
|
||||
|
||||
<h3 style="margin-top:28px">Next batch preview</h3>
|
||||
${preview.songs.length ? `<table><tbody>${preview.songs.map(songRow).join('')}</tbody></table>` : '<p class="muted">The mood has no playable music yet.</p>'}
|
||||
|
||||
<h3 style="margin-top:28px">Recommendations</h3>
|
||||
${recommendations.length ? `<table><tbody>${recommendations.map((rec) => `
|
||||
<tr><td><strong>${esc(rec.title)}</strong></td><td class="muted">${esc(rec.artist)}</td>
|
||||
<td><span class="pill">${esc(rec.state)}</span></td></tr>`).join('')}</tbody></table>`
|
||||
: '<p class="muted">No recommendations yet. YT discovery can fill this list once configured.</p>'}
|
||||
|
||||
<h3 style="margin-top:28px">Settings</h3>
|
||||
<form id="settings" class="stack">
|
||||
<label>Name<input name="name" value="${esc(mood.name)}" required></label>
|
||||
<label>Description<input name="description" value="${esc(mood.description || '')}"></label>
|
||||
<label>Genres<input name="genres" value="${esc((mood.genres || []).join(', '))}"></label>
|
||||
<label>Free-text hint<input name="query" value="${esc(mood.query || '')}"></label>
|
||||
<div class="row">
|
||||
<label style="flex:1">Batch target<input name="targetSize" type="number" min="5" max="500" value="${mood.targetSize}"></label>
|
||||
<label style="flex:1">Refresh hours<input name="refreshHours" type="number" min="1" max="720" value="${mood.refreshHours}"></label>
|
||||
</div>
|
||||
<label class="check"><input name="ytEnabled" type="checkbox" ${mood.ytEnabled ? 'checked' : ''}> Enable YT Music discovery</label>
|
||||
<div class="row"><button class="primary" type="submit">Save settings</button></div>
|
||||
</form>`;
|
||||
|
||||
$('back').onclick = showMoods;
|
||||
$('play').onclick = () => playMood(id, mood.name);
|
||||
$('delete').onclick = async () => {
|
||||
if (!confirm(`Delete mood "${mood.name}"?`)) return;
|
||||
try { await api(`/moods/${id}`, { method: 'DELETE' }); await showMoods(); }
|
||||
catch (error) { toast(error.message, true); }
|
||||
};
|
||||
$('seedSearch').onclick = () => searchSeeds(id, seeds);
|
||||
$('seedQuery').addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Enter') { event.preventDefault(); searchSeeds(id, seeds); }
|
||||
});
|
||||
$('settings').onsubmit = async (event) => {
|
||||
event.preventDefault();
|
||||
const form = new FormData(event.target);
|
||||
try {
|
||||
await api(`/moods/${id}`, {
|
||||
method: 'PATCH',
|
||||
body: {
|
||||
name: form.get('name'),
|
||||
description: form.get('description') || '',
|
||||
query: form.get('query') || '',
|
||||
genres: String(form.get('genres') || '').split(',').map((s) => s.trim()).filter(Boolean),
|
||||
targetSize: Number(form.get('targetSize')),
|
||||
refreshHours: Number(form.get('refreshHours')),
|
||||
ytEnabled: form.get('ytEnabled') === 'on',
|
||||
},
|
||||
});
|
||||
toast('Saved');
|
||||
await showMood(id);
|
||||
} catch (error) { toast(error.message, true); }
|
||||
};
|
||||
} catch (error) {
|
||||
$('content').innerHTML = `<p class="error">${esc(error.message)}</p>`;
|
||||
}
|
||||
}
|
||||
|
||||
function songRow(song) {
|
||||
return `<tr>
|
||||
<td><strong>${esc(song.title)}</strong></td>
|
||||
<td class="muted">${esc(song.artist)}</td>
|
||||
<td class="muted">${esc(song.album)}</td>
|
||||
<td style="text-align:right"><button data-addseed="${esc(song.id)}">Add</button></td>
|
||||
</tr>`;
|
||||
}
|
||||
|
||||
async function searchSeeds(moodId, seeds) {
|
||||
const query = $('seedQuery').value.trim();
|
||||
if (!query) return;
|
||||
try {
|
||||
const result = await api(`/library/search?q=${encodeURIComponent(query)}&scope=music&limit=30`);
|
||||
const existing = new Set(seeds.map((seed) => seed.song.id));
|
||||
const songs = result.songs.filter((song) => !existing.has(song.id));
|
||||
$('seedResults').innerHTML = songs.length
|
||||
? `<table><tbody>${songs.map(songRow).join('')}</tbody></table>`
|
||||
: '<p class="muted">No new matches.</p>';
|
||||
$('seedResults').querySelectorAll('[data-addseed]').forEach((button) => {
|
||||
button.onclick = async () => {
|
||||
try {
|
||||
await api(`/moods/${moodId}/seeds`, { body: { songId: button.dataset.addseed } });
|
||||
await showMood(moodId);
|
||||
} catch (error) { toast(error.message, true); }
|
||||
};
|
||||
});
|
||||
} catch (error) { toast(error.message, true); }
|
||||
}
|
||||
|
||||
document.addEventListener('click', async (event) => {
|
||||
const unseed = event.target.closest('[data-unseed]');
|
||||
if (unseed && state.moodId) {
|
||||
try {
|
||||
await api(`/moods/${state.moodId}/seeds/${unseed.dataset.unseed}`, { method: 'DELETE' });
|
||||
await showMood(state.moodId);
|
||||
} catch (error) { toast(error.message, true); }
|
||||
return;
|
||||
}
|
||||
const play = event.target.closest('[data-play]');
|
||||
if (play) { playMood(play.dataset.play); return; }
|
||||
const open = event.target.closest('[data-open]');
|
||||
if (open) { showMood(open.dataset.open); return; }
|
||||
});
|
||||
|
||||
/* ---- radio player ---- */
|
||||
|
||||
async function playMood(moodId, name) {
|
||||
try {
|
||||
if (state.session) {
|
||||
await api(`/sessions/${state.session.id}`, { method: 'DELETE' }).catch(() => {});
|
||||
}
|
||||
const session = await api(`/moods/${moodId}/sessions`, { body: { limit: 12 } });
|
||||
state.session = session;
|
||||
state.queue = [...session.queue];
|
||||
state.current = null;
|
||||
$('player').classList.remove('hidden');
|
||||
$('playerMood').textContent = `Mood · ${name || session.moodName}`;
|
||||
toast(`${state.queue.length} tracks queued`);
|
||||
playNext();
|
||||
} catch (error) { toast(error.message, true); }
|
||||
}
|
||||
|
||||
async function playNext() {
|
||||
if (!state.session) return;
|
||||
if (!state.queue.length) {
|
||||
try {
|
||||
const more = await api(`/sessions/${state.session.id}/next`, {
|
||||
body: { limit: 12, excludeSongIds: [] },
|
||||
});
|
||||
state.queue.push(...more.songs);
|
||||
} catch (error) { toast(error.message, true); }
|
||||
}
|
||||
const song = state.queue.shift();
|
||||
if (!song) { toast('No playable tracks left in this mood'); return; }
|
||||
|
||||
state.current = song;
|
||||
$('playerTitle').textContent = song.title;
|
||||
$('playerSub').textContent = `${song.artist} · ${song.album}`;
|
||||
$('playerArt').src = mediaUrl(`/covers/${song.albumId}?size=160`);
|
||||
const audio = $('audio');
|
||||
audio.src = mediaUrl(`/songs/${song.id}/stream`);
|
||||
try { await audio.play(); } catch (_) { /* browser autoplay policy */ }
|
||||
reportEvent(song.id, 'started');
|
||||
}
|
||||
|
||||
function reportEvent(songId, type) {
|
||||
if (!state.session || !songId) return;
|
||||
const position = Math.round($('audio').currentTime || 0);
|
||||
api(`/sessions/${state.session.id}/events`, {
|
||||
body: { events: [{ songId, type, positionSeconds: position }] },
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
function skip() {
|
||||
if (state.current) reportEvent(state.current.id, 'skipped');
|
||||
playNext();
|
||||
}
|
||||
|
||||
$('audio').addEventListener('ended', () => {
|
||||
if (state.current) reportEvent(state.current.id, 'completed');
|
||||
playNext();
|
||||
});
|
||||
|
||||
async function addCurrent(targetMoodId) {
|
||||
if (!state.session || !state.current) { toast('Nothing is playing', true); return; }
|
||||
try {
|
||||
const result = await api(`/sessions/${state.session.id}/add-to-mood`, {
|
||||
body: { songId: state.current.id, moodId: targetMoodId || null },
|
||||
});
|
||||
toast(result.added ? `Added to ${result.mood.name}` : `Already in ${result.mood.name}`);
|
||||
closeModal();
|
||||
if (state.mode === 'mood') await showMood(state.moodId);
|
||||
} catch (error) { toast(error.message, true); }
|
||||
}
|
||||
|
||||
function chooseMood() {
|
||||
if (!state.session) { toast('Start a mood first', true); return; }
|
||||
const moods = state.moods.length ? state.moods : [];
|
||||
openModal(`
|
||||
<h3>Add “${esc(state.current?.title || 'track')}” to</h3>
|
||||
<button class="choice primary" id="currentMoodChoice">Current mood (${esc(state.session.moodName)})</button>
|
||||
${moods.filter((mood) => mood.id !== state.session.moodId).map((mood) =>
|
||||
`<button class="choice" data-choice="${esc(mood.id)}">${esc(mood.name)}</button>`).join('')}
|
||||
`);
|
||||
$('currentMoodChoice').onclick = () => addCurrent(null);
|
||||
document.querySelectorAll('[data-choice]').forEach((button) => {
|
||||
button.onclick = () => addCurrent(button.dataset.choice);
|
||||
});
|
||||
}
|
||||
|
||||
async function showLibrary() {
|
||||
state.mode = 'library';
|
||||
state.moodId = null;
|
||||
$('content').innerHTML = `
|
||||
<h2>Library</h2>
|
||||
<div class="row"><input id="libQuery" placeholder="Search songs" style="max-width:420px"><button id="libSearch">Search</button></div>
|
||||
<div id="libResults"></div>`;
|
||||
const run = async () => {
|
||||
const query = $('libQuery').value.trim();
|
||||
if (!query) return;
|
||||
try {
|
||||
const result = await api(`/library/search?q=${encodeURIComponent(query)}&limit=50`);
|
||||
$('libResults').innerHTML = result.songs.length
|
||||
? `<table><tbody>${result.songs.map((song) => `
|
||||
<tr><td><strong>${esc(song.title)}</strong></td><td class="muted">${esc(song.artist)}</td>
|
||||
<td class="muted">${esc(song.album)}</td>
|
||||
<td style="text-align:right"><button data-libplay="${esc(song.id)}">Play</button></td></tr>`).join('')}</tbody></table>`
|
||||
: '<p class="muted">No matches.</p>';
|
||||
$('libResults').querySelectorAll('[data-libplay]').forEach((button) => {
|
||||
button.onclick = () => {
|
||||
const song = result.songs.find((item) => item.id === button.dataset.libplay);
|
||||
playDirect(song);
|
||||
};
|
||||
});
|
||||
} catch (error) { toast(error.message, true); }
|
||||
};
|
||||
$('libSearch').onclick = run;
|
||||
$('libQuery').addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Enter') { event.preventDefault(); run(); }
|
||||
});
|
||||
}
|
||||
|
||||
function playDirect(song) {
|
||||
if (!song) return;
|
||||
state.current = song;
|
||||
state.session = null;
|
||||
state.queue = [];
|
||||
$('player').classList.remove('hidden');
|
||||
$('playerTitle').textContent = song.title;
|
||||
$('playerSub').textContent = `${song.artist} · ${song.album}`;
|
||||
$('playerMood').textContent = '';
|
||||
$('playerArt').src = mediaUrl(`/covers/${song.albumId}?size=160`);
|
||||
const audio = $('audio');
|
||||
audio.src = mediaUrl(`/songs/${song.id}/stream`);
|
||||
audio.play().catch(() => {});
|
||||
}
|
||||
|
||||
function openModal(html) {
|
||||
closeModal();
|
||||
const modal = document.createElement('div');
|
||||
modal.className = 'modal';
|
||||
modal.id = 'modal';
|
||||
modal.innerHTML = `<div class="sheet">${html}<div style="margin-top:16px;text-align:right"><button id="closeModal">Cancel</button></div></div>`;
|
||||
modal.addEventListener('click', (event) => { if (event.target === modal) closeModal(); });
|
||||
document.body.appendChild(modal);
|
||||
$('closeModal').onclick = closeModal;
|
||||
}
|
||||
|
||||
function closeModal() {
|
||||
const modal = $('modal');
|
||||
if (modal) modal.remove();
|
||||
}
|
||||
|
||||
$('loginForm').addEventListener('submit', login);
|
||||
$('logoutBtn').onclick = logout;
|
||||
$('moodsBtn').onclick = showMoods;
|
||||
$('libraryBtn').onclick = showLibrary;
|
||||
$('skipBtn').onclick = skip;
|
||||
$('addCurrentBtn').onclick = () => addCurrent(null);
|
||||
$('chooseMoodBtn').onclick = chooseMood;
|
||||
$('scanBtn').onclick = async () => {
|
||||
try {
|
||||
await api('/scan', { method: 'POST' });
|
||||
toast('Scan started');
|
||||
} catch (error) { toast(error.message, true); }
|
||||
};
|
||||
|
||||
if (state.token) {
|
||||
api('/me').then(async (user) => {
|
||||
state.user = user;
|
||||
await start();
|
||||
}).catch(() => logout());
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in new issue
Block a user