@doitian/dsh-music 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +28 -0
- package/README.md +482 -2
- package/cordis.patch.yml +22 -0
- package/icon.svg +8 -0
- package/lib/client.js +466 -0
- package/lib/dj.js +543 -0
- package/lib/index.js +618 -0
- package/lib/netease.js +609 -0
- package/lib/panel.html +1105 -0
- package/lib/router.js +569 -0
- package/lib/session.js +346 -0
- package/lib/state.js +389 -0
- package/lib/vendor/qrcode.js +2297 -0
- package/package.json +67 -4
package/lib/router.js
ADDED
|
@@ -0,0 +1,569 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP surface for the music plugin.
|
|
3
|
+
*
|
|
4
|
+
* Everything the panel needs is served from one prefix (default `/music`):
|
|
5
|
+
*
|
|
6
|
+
* GET /music/panel the player page
|
|
7
|
+
* GET /music/vendor/qrcode.js vendored QR encoder (MIT)
|
|
8
|
+
* GET /music/stream/<id> audio bytes, Range-aware
|
|
9
|
+
* * /music/api/* JSON API
|
|
10
|
+
*
|
|
11
|
+
* The audio route is a proxy rather than a redirect. Two reasons: the CDN URL
|
|
12
|
+
* only lives 20 minutes and needs the session cookie at *resolution* time, and
|
|
13
|
+
* proxying keeps playback same-origin so the page never mixes http and https.
|
|
14
|
+
*
|
|
15
|
+
* @module dsh-music/router
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { Readable } from 'node:stream';
|
|
19
|
+
|
|
20
|
+
import { DEFAULT_LEVEL, LEVELS, isLevel } from './netease.js';
|
|
21
|
+
|
|
22
|
+
/** Resolved CDN URLs are reused for this long (they live 20 minutes). */
|
|
23
|
+
const URL_CACHE_MS = 15 * 60 * 1000;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Version of the page/engine boundary, advertised on `/health`.
|
|
27
|
+
*
|
|
28
|
+
* Contract 2 moved playback out of the player page and into the client
|
|
29
|
+
* plugin's always-mounted engine. A client bundle that does not see this value
|
|
30
|
+
* stays out of the way, because a host predating it still serves a page that
|
|
31
|
+
* owns its own `<audio>` — starting both would play every track twice.
|
|
32
|
+
*/
|
|
33
|
+
const PANEL_CONTRACT = 2;
|
|
34
|
+
|
|
35
|
+
/** Response headers copied from the CDN, mapped to their canonical spelling. */
|
|
36
|
+
const FORWARDED_HEADERS = {
|
|
37
|
+
'content-type': 'Content-Type',
|
|
38
|
+
'content-length': 'Content-Length',
|
|
39
|
+
'content-range': 'Content-Range',
|
|
40
|
+
'cache-control': 'Cache-Control',
|
|
41
|
+
'etag': 'ETag',
|
|
42
|
+
'last-modified': 'Last-Modified',
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/** A small JSON/HTTP helper set. */
|
|
46
|
+
function sendJson(res, status, value) {
|
|
47
|
+
const body = Buffer.from(JSON.stringify(value ?? null), 'utf8');
|
|
48
|
+
res.writeHead(status, {
|
|
49
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
50
|
+
'Content-Length': body.length,
|
|
51
|
+
'Cache-Control': 'no-store',
|
|
52
|
+
});
|
|
53
|
+
res.end(body);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function sendText(res, status, text, type = 'text/plain; charset=utf-8') {
|
|
57
|
+
const body = Buffer.from(text, 'utf8');
|
|
58
|
+
res.writeHead(status, { 'Content-Type': type, 'Content-Length': body.length });
|
|
59
|
+
res.end(body);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Read and parse a JSON request body, bounded. */
|
|
63
|
+
async function readJson(req, limit = 256 * 1024) {
|
|
64
|
+
const chunks = [];
|
|
65
|
+
let size = 0;
|
|
66
|
+
for await (const chunk of req) {
|
|
67
|
+
size += chunk.length;
|
|
68
|
+
if (size > limit) throw new Error('request body too large');
|
|
69
|
+
chunks.push(chunk);
|
|
70
|
+
}
|
|
71
|
+
if (size === 0) return {};
|
|
72
|
+
try {
|
|
73
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
74
|
+
} catch {
|
|
75
|
+
throw new Error('invalid JSON body');
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export class MusicRouter {
|
|
80
|
+
/**
|
|
81
|
+
* @param {object} options
|
|
82
|
+
* @param {string} options.base route prefix, e.g. `/music`.
|
|
83
|
+
* @param {import('./netease.js').Netease} options.api
|
|
84
|
+
* @param {import('./state.js').Player} options.player
|
|
85
|
+
* @param {import('./session.js').SessionStore} options.store
|
|
86
|
+
* @param {import('./session.js').QrLogin} options.qr
|
|
87
|
+
* @param {import('./dj.js').AiDj} options.dj
|
|
88
|
+
* @param {string} options.panelHtml
|
|
89
|
+
* @param {string} options.qrcodeJs
|
|
90
|
+
* @param {object} [options.config]
|
|
91
|
+
* @param {() => Promise<object>} [options.listRoutes] curator routes for the picker.
|
|
92
|
+
* @param {() => object} [options.diagnostics] extra facts for `/health`.
|
|
93
|
+
* @param {{warn: Function, info: Function, debug: Function}} [options.logger]
|
|
94
|
+
*/
|
|
95
|
+
constructor({ base, api, player, store, qr, dj, panelHtml, qrcodeJs, config = {}, listRoutes, diagnostics, logger }) {
|
|
96
|
+
this.base = base.replace(/\/+$/, '');
|
|
97
|
+
this.api = api;
|
|
98
|
+
this.player = player;
|
|
99
|
+
this.store = store;
|
|
100
|
+
this.qr = qr;
|
|
101
|
+
this.dj = dj;
|
|
102
|
+
this.panelHtml = panelHtml;
|
|
103
|
+
this.qrcodeJs = qrcodeJs;
|
|
104
|
+
this.config = config;
|
|
105
|
+
this.listRoutes = listRoutes;
|
|
106
|
+
this.diagnostics = diagnostics;
|
|
107
|
+
this.logger = logger;
|
|
108
|
+
/** @type {Map<string, {url: string, payload: object, expiresAt: number}>} */
|
|
109
|
+
this.urlCache = new Map();
|
|
110
|
+
/** In-flight audio resolutions, so parallel Range requests share one call. */
|
|
111
|
+
this.pendingUrls = new Map();
|
|
112
|
+
/** What the last stream request actually resolved, for the UI and health. */
|
|
113
|
+
this.lastAudio = null;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The level to stream at.
|
|
118
|
+
*
|
|
119
|
+
* The player's saved choice wins over the profile patch, matching how the
|
|
120
|
+
* curator route resolves — a GUI choice should not be silently overridden.
|
|
121
|
+
* An unknown value falls back rather than failing a request.
|
|
122
|
+
*/
|
|
123
|
+
preferredLevel() {
|
|
124
|
+
const asked = this.store.settings.level || this.config.audioLevel || DEFAULT_LEVEL;
|
|
125
|
+
return isLevel(asked) ? asked : DEFAULT_LEVEL;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** The levels the player may choose, with labels. */
|
|
129
|
+
levelChoices() {
|
|
130
|
+
return { levels: LEVELS, preferred: this.preferredLevel() };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// ------------------------------------------------------------------ audio
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Resolve (and cache) the signed CDN URL for one track at one level.
|
|
137
|
+
*
|
|
138
|
+
* Keyed by level as well as id: the same track at two qualities is two
|
|
139
|
+
* different files, and serving one while the browser expects the other would
|
|
140
|
+
* corrupt the byte stream it is range-requesting.
|
|
141
|
+
*/
|
|
142
|
+
async resolveAudio(id, level = this.preferredLevel()) {
|
|
143
|
+
const key = `${id}:${level}`;
|
|
144
|
+
const cached = this.urlCache.get(key);
|
|
145
|
+
// The cache holds a record; callers get the resolution payload itself.
|
|
146
|
+
if (cached && cached.expiresAt > Date.now()) return cached.payload;
|
|
147
|
+
if (this.pendingUrls.has(key)) return this.pendingUrls.get(key);
|
|
148
|
+
const pending = this.api
|
|
149
|
+
.songUrl(id, { level })
|
|
150
|
+
.then((resolved) => {
|
|
151
|
+
if (resolved.ok) {
|
|
152
|
+
this.urlCache.set(key, {
|
|
153
|
+
url: resolved.url,
|
|
154
|
+
payload: resolved,
|
|
155
|
+
expiresAt: Date.now() + Math.min(resolved.expiresInMs, URL_CACHE_MS),
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
return resolved;
|
|
159
|
+
})
|
|
160
|
+
.finally(() => this.pendingUrls.delete(key));
|
|
161
|
+
this.pendingUrls.set(key, pending);
|
|
162
|
+
return pending;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Stream one track's bytes, forwarding the browser's Range header upstream so
|
|
167
|
+
* seeking works and the browser can buffer progressively.
|
|
168
|
+
*
|
|
169
|
+
* `?level=` names the quality. It is part of the URL rather than implicit
|
|
170
|
+
* state so that changing the preference yields a different resource: the
|
|
171
|
+
* browser then loads a fresh file instead of range-requesting offsets of one
|
|
172
|
+
* encoding against another.
|
|
173
|
+
*/
|
|
174
|
+
async handleStream(req, res, id, level) {
|
|
175
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
176
|
+
sendJson(res, 405, { error: 'method not allowed' });
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
const trackId = Number(id);
|
|
180
|
+
if (!Number.isFinite(trackId)) {
|
|
181
|
+
sendJson(res, 400, { error: 'invalid track id' });
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
const requestedLevel = isLevel(level) ? level : this.preferredLevel();
|
|
185
|
+
|
|
186
|
+
let resolved;
|
|
187
|
+
try {
|
|
188
|
+
resolved = await this.resolveAudio(trackId, requestedLevel);
|
|
189
|
+
} catch (error) {
|
|
190
|
+
this.logger?.warn?.(`[music] could not resolve audio for ${trackId}: ${error.message}`);
|
|
191
|
+
sendJson(res, 502, { error: `could not resolve audio: ${error.message}` });
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
if (!resolved.ok) {
|
|
195
|
+
// 403 tells the panel this is an entitlement problem, not a transient one.
|
|
196
|
+
this.lastAudio = {
|
|
197
|
+
trackId,
|
|
198
|
+
requested: requestedLevel,
|
|
199
|
+
served: null,
|
|
200
|
+
downgraded: false,
|
|
201
|
+
error: resolved.reason,
|
|
202
|
+
at: Date.now(),
|
|
203
|
+
};
|
|
204
|
+
sendJson(res, 403, { error: `track ${trackId} is ${resolved.reason}`, code: resolved.code });
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// Recorded here rather than at resolution time, so a cache hit still
|
|
209
|
+
// reports what is actually being served — otherwise switching back to a
|
|
210
|
+
// cached level would leave the UI describing the previous one.
|
|
211
|
+
this.lastAudio = {
|
|
212
|
+
trackId,
|
|
213
|
+
requested: requestedLevel,
|
|
214
|
+
served: resolved.level,
|
|
215
|
+
downgraded: resolved.downgraded,
|
|
216
|
+
br: resolved.br,
|
|
217
|
+
type: resolved.type,
|
|
218
|
+
size: resolved.size,
|
|
219
|
+
at: Date.now(),
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
let upstream;
|
|
223
|
+
try {
|
|
224
|
+
upstream = await this.api.fetchAudio(resolved.url, {
|
|
225
|
+
range: req.headers.range,
|
|
226
|
+
method: req.method === 'HEAD' ? 'HEAD' : 'GET',
|
|
227
|
+
});
|
|
228
|
+
} catch (error) {
|
|
229
|
+
this.urlCache.delete(`${trackId}:${requestedLevel}`);
|
|
230
|
+
sendJson(res, 502, { error: `CDN request failed: ${error.message}` });
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// A CDN miss expiry can still answer 403/404; drop the cache so the next
|
|
235
|
+
// attempt re-resolves instead of serving a dead URL.
|
|
236
|
+
if (upstream.status === 403 || upstream.status === 404) {
|
|
237
|
+
this.urlCache.delete(`${trackId}:${requestedLevel}`);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const headers = { 'Accept-Ranges': 'bytes' };
|
|
241
|
+
for (const [lower, canonical] of Object.entries(FORWARDED_HEADERS)) {
|
|
242
|
+
const value = upstream.headers.get(lower);
|
|
243
|
+
if (value) headers[canonical] = value;
|
|
244
|
+
}
|
|
245
|
+
if (!headers['Content-Type']) headers['Content-Type'] = 'audio/mpeg';
|
|
246
|
+
|
|
247
|
+
res.writeHead(upstream.status, headers);
|
|
248
|
+
if (req.method === 'HEAD' || !upstream.body) {
|
|
249
|
+
res.end();
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
try {
|
|
253
|
+
await new Promise((resolve, reject) => {
|
|
254
|
+
const source = Readable.fromWeb(upstream.body);
|
|
255
|
+
source.on('error', reject);
|
|
256
|
+
res.on('error', reject);
|
|
257
|
+
res.on('close', () => source.destroy());
|
|
258
|
+
source.pipe(res);
|
|
259
|
+
res.on('finish', resolve);
|
|
260
|
+
});
|
|
261
|
+
} catch (error) {
|
|
262
|
+
this.logger?.debug?.(`[music] stream ended early for ${trackId}: ${error.message}`);
|
|
263
|
+
res.destroy();
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// -------------------------------------------------------------------- API
|
|
268
|
+
|
|
269
|
+
/** The panel's poll target: full player snapshot including account and DJ. */
|
|
270
|
+
snapshot(extra = {}) {
|
|
271
|
+
return {
|
|
272
|
+
...this.player.snapshot(),
|
|
273
|
+
account: this.api.account,
|
|
274
|
+
authenticated: this.api.authenticated,
|
|
275
|
+
settings: this.store.settings,
|
|
276
|
+
modelSource: this.modelSource(),
|
|
277
|
+
/** Preferred quality, plus what the last stream request actually served. */
|
|
278
|
+
audio: { preferred: this.preferredLevel(), last: this.lastAudio },
|
|
279
|
+
...extra,
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** Where the live curator route came from. */
|
|
284
|
+
modelSource() {
|
|
285
|
+
const settings = this.store.settings;
|
|
286
|
+
if (settings.djProvider || settings.djModel) return 'panel';
|
|
287
|
+
if (this.config?.dj?.provider || this.config?.dj?.model) return 'config';
|
|
288
|
+
return 'discovered';
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Route one `/music/api/*` request. */
|
|
292
|
+
async handleApi(req, res, pathname) {
|
|
293
|
+
const route = pathname.slice(`${this.base}/api`.length).replace(/\/+$/, '') || '/';
|
|
294
|
+
const method = req.method ?? 'GET';
|
|
295
|
+
const query = new URL(req.url ?? '/', 'http://localhost').searchParams;
|
|
296
|
+
|
|
297
|
+
// ---- player state -----------------------------------------------------
|
|
298
|
+
if (route === '/state' && method === 'GET') {
|
|
299
|
+
return sendJson(res, 200, this.snapshot());
|
|
300
|
+
}
|
|
301
|
+
if (route === '/report' && method === 'POST') {
|
|
302
|
+
const body = await readJson(req);
|
|
303
|
+
this.player.report(body);
|
|
304
|
+
return sendJson(res, 200, this.snapshot());
|
|
305
|
+
}
|
|
306
|
+
if (route === '/seek-consumed' && method === 'POST') {
|
|
307
|
+
this.player.takeSeek();
|
|
308
|
+
return sendJson(res, 200, this.snapshot());
|
|
309
|
+
}
|
|
310
|
+
if (route === '/control' && method === 'POST') {
|
|
311
|
+
const { action, value } = await readJson(req);
|
|
312
|
+
switch (action) {
|
|
313
|
+
case 'play': this.player.setPlaying(true); break;
|
|
314
|
+
case 'pause': this.player.setPlaying(false); break;
|
|
315
|
+
case 'toggle': this.player.toggle(); break;
|
|
316
|
+
case 'next': this.player.move(1); break;
|
|
317
|
+
case 'previous': this.player.move(-1); break;
|
|
318
|
+
case 'seek': this.player.seek(value); break;
|
|
319
|
+
case 'volume': this.player.setVolume(value); break;
|
|
320
|
+
case 'mute': this.player.setMuted(value); break;
|
|
321
|
+
case 'mode': this.player.setMode(value); break;
|
|
322
|
+
default: return sendJson(res, 400, { error: `unknown action "${action}"` });
|
|
323
|
+
}
|
|
324
|
+
return sendJson(res, 200, this.snapshot());
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// ---- queue ------------------------------------------------------------
|
|
328
|
+
if (route === '/play' && method === 'POST') {
|
|
329
|
+
const { tracks, startIndex } = await readJson(req);
|
|
330
|
+
if (!Array.isArray(tracks) || tracks.length === 0) {
|
|
331
|
+
return sendJson(res, 400, { error: 'tracks must be a non-empty array' });
|
|
332
|
+
}
|
|
333
|
+
this.player.setQueue(tracks, { startIndex, source: 'user' });
|
|
334
|
+
this.store.recordPlay(this.player.current() ?? tracks[0]);
|
|
335
|
+
return sendJson(res, 200, this.snapshot());
|
|
336
|
+
}
|
|
337
|
+
if (route === '/queue' && method === 'POST') {
|
|
338
|
+
const { action, tracks, index } = await readJson(req);
|
|
339
|
+
if (action === 'replace' && Array.isArray(tracks)) this.player.setQueue(tracks, { source: 'user' });
|
|
340
|
+
else if (action === 'append' && Array.isArray(tracks)) this.player.append(tracks, { source: 'user' });
|
|
341
|
+
else if (action === 'insert' && Array.isArray(tracks)) this.player.insertNext(tracks, { source: 'user' });
|
|
342
|
+
else if (action === 'remove') this.player.remove(Number(index));
|
|
343
|
+
else if (action === 'jump') this.player.jump(Number(index));
|
|
344
|
+
else if (action === 'clear') this.player.clear();
|
|
345
|
+
else return sendJson(res, 400, { error: `unknown queue action "${action}"` });
|
|
346
|
+
return sendJson(res, 200, this.snapshot());
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// ---- catalogue --------------------------------------------------------
|
|
350
|
+
if (route === '/search' && method === 'GET') {
|
|
351
|
+
const keyword = (query.get('q') ?? '').trim();
|
|
352
|
+
if (!keyword) return sendJson(res, 400, { error: 'missing q' });
|
|
353
|
+
const limit = Math.min(Math.max(Number(query.get('limit')) || 30, 1), 100);
|
|
354
|
+
const result = await this.api.searchSongs(keyword, { limit });
|
|
355
|
+
result.tracks = await this.api.withCovers(result.tracks);
|
|
356
|
+
return sendJson(res, 200, result);
|
|
357
|
+
}
|
|
358
|
+
if (route.startsWith('/track/') && method === 'GET') {
|
|
359
|
+
const id = Number(route.slice('/track/'.length));
|
|
360
|
+
const [track] = await this.api.songDetail([id]);
|
|
361
|
+
if (!track) return sendJson(res, 404, { error: `track ${id} not found` });
|
|
362
|
+
return sendJson(res, 200, { track });
|
|
363
|
+
}
|
|
364
|
+
if (route.startsWith('/lyric/') && method === 'GET') {
|
|
365
|
+
const id = Number(route.slice('/lyric/'.length));
|
|
366
|
+
return sendJson(res, 200, await this.api.lyric(id));
|
|
367
|
+
}
|
|
368
|
+
if (route === '/charts' && method === 'GET') {
|
|
369
|
+
return sendJson(res, 200, await this.api.toplists());
|
|
370
|
+
}
|
|
371
|
+
if (route === '/playlists' && method === 'GET') {
|
|
372
|
+
return sendJson(res, 200, await this.api.personalizedPlaylists(12));
|
|
373
|
+
}
|
|
374
|
+
if (route === '/new' && method === 'GET') {
|
|
375
|
+
const tracks = await this.api.personalizedNewsongs(20);
|
|
376
|
+
return sendJson(res, 200, await this.api.withCovers(tracks));
|
|
377
|
+
}
|
|
378
|
+
if (route.startsWith('/playlist/') && method === 'GET') {
|
|
379
|
+
const id = Number(route.slice('/playlist/'.length));
|
|
380
|
+
const playlist = await this.api.playlistDetail(id);
|
|
381
|
+
return sendJson(res, 200, {
|
|
382
|
+
id: playlist.id,
|
|
383
|
+
name: playlist.name,
|
|
384
|
+
cover: playlist.cover,
|
|
385
|
+
tracks: await this.api.withCovers(playlist.tracks),
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
// ---- feedback ---------------------------------------------------------
|
|
390
|
+
if (route === '/feedback' && method === 'POST') {
|
|
391
|
+
const { kind, trackId } = await readJson(req);
|
|
392
|
+
if (!['likes', 'dislikes', 'skips'].includes(kind)) {
|
|
393
|
+
return sendJson(res, 400, { error: `unknown feedback kind "${kind}"` });
|
|
394
|
+
}
|
|
395
|
+
this.store.recordFeedback(kind, trackId);
|
|
396
|
+
return sendJson(res, 200, { feedback: this.store.feedback });
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
// ---- streaming quality ------------------------------------------------
|
|
400
|
+
if (route === '/quality' && method === 'GET') {
|
|
401
|
+
return sendJson(res, 200, { ...this.levelChoices(), last: this.lastAudio });
|
|
402
|
+
}
|
|
403
|
+
if (route === '/quality' && method === 'POST') {
|
|
404
|
+
const { level } = await readJson(req);
|
|
405
|
+
if (!isLevel(level)) {
|
|
406
|
+
return sendJson(res, 400, {
|
|
407
|
+
error: `unknown level "${level}"`,
|
|
408
|
+
levels: LEVELS.map((entry) => entry.id),
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
this.store.updateSettings({ level });
|
|
412
|
+
this.logger?.info?.(`[music] streaming quality set to ${level} from the player`);
|
|
413
|
+
// The running stream keeps its bytes; the next load or seek uses this.
|
|
414
|
+
return sendJson(res, 200, this.snapshot());
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// ---- AI DJ ------------------------------------------------------------
|
|
418
|
+
if (route === '/dj/models' && method === 'GET') {
|
|
419
|
+
const listed = this.listRoutes ? await this.listRoutes() : { routes: [], error: 'no model service is mounted' };
|
|
420
|
+
return sendJson(res, 200, {
|
|
421
|
+
...listed,
|
|
422
|
+
selected: { provider: this.dj.model.provider ?? null, model: this.dj.model.model ?? null },
|
|
423
|
+
source: this.modelSource(),
|
|
424
|
+
/** The patch's pin, so the picker can offer "revert". */
|
|
425
|
+
configured: {
|
|
426
|
+
provider: this.config?.dj?.provider ?? null,
|
|
427
|
+
model: this.config?.dj?.model ?? null,
|
|
428
|
+
},
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
if (route === '/dj/test' && method === 'POST') {
|
|
432
|
+
// One throwaway plan: the candidate pool is real, but nothing is queued,
|
|
433
|
+
// so the picker can answer "does this route actually work?" safely.
|
|
434
|
+
const plan = await this.dj.plan({ prompt: this.store.settings.djPrompt ?? '', count: 1 });
|
|
435
|
+
return sendJson(res, 200, {
|
|
436
|
+
source: plan.source,
|
|
437
|
+
route: plan.route ?? null,
|
|
438
|
+
modelError: this.dj.modelError,
|
|
439
|
+
note: plan.note ?? null,
|
|
440
|
+
vibe: plan.vibe ?? null,
|
|
441
|
+
picked: plan.tracks.map((track) => `${track.name} — ${(track.artists ?? []).join('/')}`),
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
if (route === '/dj' && method === 'POST') {
|
|
445
|
+
const { enabled, prompt, replan, provider, model } = await readJson(req);
|
|
446
|
+
|
|
447
|
+
if (provider !== undefined || model !== undefined) {
|
|
448
|
+
const nextProvider = provider === undefined ? this.store.settings.djProvider : String(provider ?? '');
|
|
449
|
+
const nextModel = model === undefined ? this.store.settings.djModel : String(model ?? '');
|
|
450
|
+
this.store.updateSettings({ djProvider: nextProvider, djModel: nextModel });
|
|
451
|
+
// Empty means "no choice made here", which reverts to the patch pin.
|
|
452
|
+
const configured = this.config?.dj ?? {};
|
|
453
|
+
this.dj.setModel({
|
|
454
|
+
provider: nextProvider || configured.provider || null,
|
|
455
|
+
model: nextModel || configured.model || null,
|
|
456
|
+
});
|
|
457
|
+
this.logger?.info?.(
|
|
458
|
+
`[music] curator route set to ${this.dj.model.provider ?? '(none)'}/${this.dj.model.model ?? '(none)'} from the player`,
|
|
459
|
+
);
|
|
460
|
+
}
|
|
461
|
+
if (prompt !== undefined) this.store.updateSettings({ djPrompt: String(prompt) });
|
|
462
|
+
if (enabled !== undefined) this.dj.setEnabled(enabled);
|
|
463
|
+
if (replan || (enabled && this.player.queue.length === 0)) {
|
|
464
|
+
// Planning is slow; answer immediately and let the panel poll the result.
|
|
465
|
+
void this.dj.topUp({ force: true });
|
|
466
|
+
} else if (prompt !== undefined && this.player.dj.enabled) {
|
|
467
|
+
void this.dj.topUp({ force: true });
|
|
468
|
+
}
|
|
469
|
+
return sendJson(res, 200, this.snapshot());
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
// ---- login ------------------------------------------------------------
|
|
473
|
+
if (route === '/login/qr' && method === 'POST') {
|
|
474
|
+
const attempt = await this.qr.start();
|
|
475
|
+
return sendJson(res, 200, { ...attempt, loggedIn: this.api.authenticated });
|
|
476
|
+
}
|
|
477
|
+
if (route === '/login/poll' && method === 'POST') {
|
|
478
|
+
const result = await this.qr.poll();
|
|
479
|
+
return sendJson(res, 200, { ...result, loggedIn: this.api.authenticated, account: this.api.account });
|
|
480
|
+
}
|
|
481
|
+
if (route === '/login/cookie' && method === 'POST') {
|
|
482
|
+
const { cookie } = await readJson(req);
|
|
483
|
+
if (!cookie || typeof cookie !== 'string') return sendJson(res, 400, { error: 'missing cookie' });
|
|
484
|
+
this.api.setCookie(cookie.trim());
|
|
485
|
+
const account = await this.api.fetchAccount().catch(() => null);
|
|
486
|
+
if (!account) {
|
|
487
|
+
return sendJson(res, 400, { error: 'the cookie did not yield an account (expired or malformed?)' });
|
|
488
|
+
}
|
|
489
|
+
this.store.setSession(this.api.jar.header(), account);
|
|
490
|
+
return sendJson(res, 200, { account, loggedIn: true });
|
|
491
|
+
}
|
|
492
|
+
if (route === '/login/logout' && method === 'POST') {
|
|
493
|
+
this.api.clearCookie();
|
|
494
|
+
this.store.clearSession();
|
|
495
|
+
this.qr.reset();
|
|
496
|
+
return sendJson(res, 200, { loggedIn: false });
|
|
497
|
+
}
|
|
498
|
+
if (route === '/login/status' && method === 'GET') {
|
|
499
|
+
const account = this.api.authenticated ? await this.api.fetchAccount().catch(() => null) : null;
|
|
500
|
+
return sendJson(res, 200, { loggedIn: Boolean(account), account, qr: this.qr.snapshot() });
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
return sendJson(res, 404, { error: `unknown endpoint ${route}` });
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/**
|
|
507
|
+
* Top-level dispatcher for every request under the configured prefix.
|
|
508
|
+
* @returns {Promise<boolean>} whether the request was handled.
|
|
509
|
+
*/
|
|
510
|
+
async handle(req, res) {
|
|
511
|
+
const parsed = new URL(req.url ?? '/', 'http://localhost');
|
|
512
|
+
const pathname = parsed.pathname;
|
|
513
|
+
const query = parsed.searchParams;
|
|
514
|
+
if (pathname !== this.base && !pathname.startsWith(`${this.base}/`)) return false;
|
|
515
|
+
|
|
516
|
+
try {
|
|
517
|
+
const rest = pathname.slice(this.base.length);
|
|
518
|
+
|
|
519
|
+
if (rest === '' || rest === '/' || rest === '/panel' || rest === '/panel/') {
|
|
520
|
+
const html = this.panelHtml.replaceAll('__BASE__', this.base);
|
|
521
|
+
res.writeHead(200, {
|
|
522
|
+
'Content-Type': 'text/html; charset=utf-8',
|
|
523
|
+
'Cache-Control': 'no-store',
|
|
524
|
+
});
|
|
525
|
+
res.end(html);
|
|
526
|
+
return true;
|
|
527
|
+
}
|
|
528
|
+
if (rest === '/vendor/qrcode.js') {
|
|
529
|
+
res.writeHead(200, {
|
|
530
|
+
'Content-Type': 'text/javascript; charset=utf-8',
|
|
531
|
+
'Cache-Control': 'public, max-age=86400',
|
|
532
|
+
});
|
|
533
|
+
res.end(this.qrcodeJs);
|
|
534
|
+
return true;
|
|
535
|
+
}
|
|
536
|
+
if (rest === '/health') {
|
|
537
|
+
sendJson(res, 200, {
|
|
538
|
+
ok: true,
|
|
539
|
+
prefix: this.base,
|
|
540
|
+
panelContract: PANEL_CONTRACT,
|
|
541
|
+
audio: { preferred: this.preferredLevel(), last: this.lastAudio },
|
|
542
|
+
authenticated: this.api.authenticated,
|
|
543
|
+
account: this.api.account,
|
|
544
|
+
playing: this.player.playing,
|
|
545
|
+
queued: this.player.queue.length,
|
|
546
|
+
...(this.diagnostics ? this.diagnostics() : {}),
|
|
547
|
+
});
|
|
548
|
+
return true;
|
|
549
|
+
}
|
|
550
|
+
if (rest.startsWith('/stream/')) {
|
|
551
|
+
await this.handleStream(req, res, rest.slice('/stream/'.length), query.get('level'));
|
|
552
|
+
return true;
|
|
553
|
+
}
|
|
554
|
+
if (rest.startsWith('/api/')) {
|
|
555
|
+
await this.handleApi(req, res, pathname);
|
|
556
|
+
return true;
|
|
557
|
+
}
|
|
558
|
+
sendJson(res, 404, { error: `not found: ${pathname}` });
|
|
559
|
+
return true;
|
|
560
|
+
} catch (error) {
|
|
561
|
+
this.logger?.warn?.(`[music] request ${pathname} failed: ${error.stack ?? error.message}`);
|
|
562
|
+
if (!res.headersSent) sendJson(res, 500, { error: error.message });
|
|
563
|
+
else res.destroy();
|
|
564
|
+
return true;
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
export { sendJson, sendText, readJson, PANEL_CONTRACT };
|