@doitian/dsh-music 0.1.10 → 1.1.0
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/lib/client.js +177 -152
- package/lib/feed.js +191 -0
- package/lib/index.js +7 -2
- package/lib/panel.html +356 -175
- package/lib/playback.js +343 -0
- package/lib/router.js +48 -6
- package/lib/state.js +9 -3
- package/package.json +6 -17
package/lib/client.js
CHANGED
|
@@ -23,7 +23,16 @@
|
|
|
23
23
|
* on the plugin's own lifetime in the shell document, which keeps running no
|
|
24
24
|
* matter which panel is on screen. The page becomes a remote control over the
|
|
25
25
|
* host's shared state, and `window.__dshMusicEngine.sync()` lets it apply a
|
|
26
|
-
* command
|
|
26
|
+
* command at once.
|
|
27
|
+
*
|
|
28
|
+
* ## How the engine hears about changes
|
|
29
|
+
*
|
|
30
|
+
* The host pushes its state over `/music/api/events` (an event stream; see
|
|
31
|
+
* lib/feed.js) whenever something the engine acts on changes. The engine
|
|
32
|
+
* re-reads `/state` itself only while that stream is down. A short local clock
|
|
33
|
+
* still runs regardless, because two things never reach the host as a change:
|
|
34
|
+
* a play the browser refused, which must be retried until it is allowed, and
|
|
35
|
+
* the position reports the engine owes the host.
|
|
27
36
|
*
|
|
28
37
|
* @module @doitian/dsh-music/client
|
|
29
38
|
*/
|
|
@@ -72,8 +81,13 @@ window.__ModuleLoader__.load({
|
|
|
72
81
|
/** Bound in apply() once the dictionary is registered; English until then. */
|
|
73
82
|
let t = (key) => DICTIONARY.en[key] ?? key;
|
|
74
83
|
|
|
75
|
-
/**
|
|
76
|
-
|
|
84
|
+
/**
|
|
85
|
+
* The engine's own clock: it retries a refused play, sends a report when one
|
|
86
|
+
* is due, and re-reads the host while the event stream is down.
|
|
87
|
+
*/
|
|
88
|
+
const TICK_MS = 500;
|
|
89
|
+
/** A stream the browser gave up on (an error answer) is opened again after this. */
|
|
90
|
+
const RELISTEN_MS = 10_000;
|
|
77
91
|
/** Position report cadence while playing, and while idle. */
|
|
78
92
|
const REPORT_MS = 1000;
|
|
79
93
|
const IDLE_REPORT_MS = 5000;
|
|
@@ -88,6 +102,23 @@ window.__ModuleLoader__.load({
|
|
|
88
102
|
: '';
|
|
89
103
|
}
|
|
90
104
|
|
|
105
|
+
/**
|
|
106
|
+
* Origin that serves audio bytes.
|
|
107
|
+
*
|
|
108
|
+
* The desktop shell runs on the `dsh-app://` custom scheme, whose responses
|
|
109
|
+
* Chromium cannot byte-range (electron/electron#38749): audio plays, but a
|
|
110
|
+
* seek collapses to zero and restarts the track. The shell publishes its
|
|
111
|
+
* real HTTP origin as `__DSH_TRANSPORT__.streamBaseUrl` for exactly this;
|
|
112
|
+
* in a browser it is absent and the document origin serves.
|
|
113
|
+
*/
|
|
114
|
+
function streamOrigin() {
|
|
115
|
+
try {
|
|
116
|
+
const base = window.__DSH_TRANSPORT__?.streamBaseUrl;
|
|
117
|
+
if (typeof base === 'string' && base) return new URL(base).origin;
|
|
118
|
+
} catch { /* a malformed base falls back to the document origin */ }
|
|
119
|
+
return origin();
|
|
120
|
+
}
|
|
121
|
+
|
|
91
122
|
/** Player page URL, shown in errors and used as the iframe source. */
|
|
92
123
|
function panelUrl() {
|
|
93
124
|
return `${origin()}${BASE}/panel`;
|
|
@@ -97,14 +128,15 @@ window.__ModuleLoader__.load({
|
|
|
97
128
|
|
|
98
129
|
/**
|
|
99
130
|
* The page/engine boundary this bundle expects, mirrored from the host's
|
|
100
|
-
* `/health`.
|
|
131
|
+
* `/health`. It covers the host's playback core too: see
|
|
132
|
+
* {@link loadPlayback}, and {@link createEngine} for why it is checked at all.
|
|
101
133
|
*/
|
|
102
134
|
const PANEL_CONTRACT = 2;
|
|
103
135
|
|
|
104
136
|
/** An engine that does nothing, for a host that predates the contract. */
|
|
105
137
|
function inertEngine() {
|
|
106
138
|
// `playback: false` is the page's cue to own the audio element itself.
|
|
107
|
-
return { playback: false, inert: true, sync() {}, playNow() {}, state: () => null, dispose() {} };
|
|
139
|
+
return { playback: false, inert: true, sync() {}, playNow() {}, state: () => null, position: () => 0, dispose() {} };
|
|
108
140
|
}
|
|
109
141
|
|
|
110
142
|
/**
|
|
@@ -135,6 +167,33 @@ window.__ModuleLoader__.load({
|
|
|
135
167
|
}
|
|
136
168
|
}
|
|
137
169
|
|
|
170
|
+
/**
|
|
171
|
+
* Load the playback core the host serves beside the page.
|
|
172
|
+
*
|
|
173
|
+
* The page's fallback transport runs the same file, which is the point:
|
|
174
|
+
* the fades, the seek hold and the autoplay retry exist once. It comes
|
|
175
|
+
* from the host rather than this bundle because the host and the page are
|
|
176
|
+
* one generation and this bundle may be another; the handshake has already
|
|
177
|
+
* established that the host's generation is the one this engine expects.
|
|
178
|
+
* A host from before the core was split out does not serve it, and that
|
|
179
|
+
* leaves the engine inert like any other mismatch.
|
|
180
|
+
*
|
|
181
|
+
* @returns {Promise<{createPlayback: Function} | null>}
|
|
182
|
+
*/
|
|
183
|
+
function loadPlayback() {
|
|
184
|
+
return new Promise((resolve) => {
|
|
185
|
+
const script = document.createElement('script');
|
|
186
|
+
const settle = (core) => {
|
|
187
|
+
script.remove();
|
|
188
|
+
resolve(typeof core?.createPlayback === 'function' ? core : null);
|
|
189
|
+
};
|
|
190
|
+
script.addEventListener('load', () => settle(window.__dshMusicPlayback));
|
|
191
|
+
script.addEventListener('error', () => settle(null));
|
|
192
|
+
script.src = `${BASE}/playback.js`;
|
|
193
|
+
(document.head ?? document.documentElement).appendChild(script);
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
|
|
138
197
|
/**
|
|
139
198
|
* Start the persistent audio engine, after a contract handshake.
|
|
140
199
|
*
|
|
@@ -143,7 +202,7 @@ window.__ModuleLoader__.load({
|
|
|
143
202
|
* this engine as well would play every track twice — so the engine stays
|
|
144
203
|
* inert and the old behaviour applies until the two are refreshed together.
|
|
145
204
|
*
|
|
146
|
-
* @returns {Promise<{sync: () => void, state: () => object | null, dispose: () => void}>}
|
|
205
|
+
* @returns {Promise<{sync: () => void, state: () => object | null, position: () => number, dispose: () => void}>}
|
|
147
206
|
*/
|
|
148
207
|
async function createEngine() {
|
|
149
208
|
if (!(await pageAcceptsEngine())) {
|
|
@@ -153,27 +212,32 @@ window.__ModuleLoader__.load({
|
|
|
153
212
|
);
|
|
154
213
|
return inertEngine();
|
|
155
214
|
}
|
|
215
|
+
const core = await loadPlayback();
|
|
216
|
+
if (!core) {
|
|
217
|
+
console.warn('[music] the host serves no playback core; leaving playback to the page until the harness restarts.');
|
|
218
|
+
return inertEngine();
|
|
219
|
+
}
|
|
156
220
|
|
|
157
221
|
// A hot re-materialization must not leave a second element playing.
|
|
158
222
|
try {
|
|
159
223
|
window.__dshMusicEngine?.dispose?.();
|
|
160
224
|
} catch { /* ignore a stale engine */ }
|
|
161
225
|
|
|
162
|
-
const audio = document.createElement('audio');
|
|
163
|
-
audio.preload = 'auto';
|
|
164
|
-
audio.setAttribute('aria-hidden', 'true');
|
|
165
|
-
audio.style.display = 'none';
|
|
166
|
-
(document.body ?? document.documentElement).appendChild(audio);
|
|
167
|
-
|
|
168
226
|
let state = null;
|
|
169
|
-
let appliedTransport = -1;
|
|
170
227
|
// Start the clock now so the first tick reconciles without also posting a
|
|
171
228
|
// redundant position report.
|
|
172
229
|
let lastReportAt = Date.now();
|
|
173
230
|
let disposed = false;
|
|
174
231
|
let inflight = false;
|
|
175
|
-
/**
|
|
176
|
-
let
|
|
232
|
+
/** The host's event stream, and whether it is open. */
|
|
233
|
+
let events = null;
|
|
234
|
+
let streaming = false;
|
|
235
|
+
let relisten = null;
|
|
236
|
+
/** The newest snapshot version adopted; see {@link take}. */
|
|
237
|
+
let versionFloor = 0;
|
|
238
|
+
|
|
239
|
+
const playback = core.createPlayback({ base: BASE, streamOrigin, call, report });
|
|
240
|
+
const { audio, reconcile, applySource, enforce } = playback;
|
|
177
241
|
|
|
178
242
|
/** One JSON round-trip to the host. */
|
|
179
243
|
async function call(path, init) {
|
|
@@ -186,154 +250,107 @@ window.__ModuleLoader__.load({
|
|
|
186
250
|
return text ? JSON.parse(text) : {};
|
|
187
251
|
}
|
|
188
252
|
|
|
189
|
-
/**
|
|
190
|
-
function
|
|
191
|
-
if (
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
}
|
|
198
|
-
//
|
|
199
|
-
|
|
200
|
-
|
|
253
|
+
/** Tell the host where playback actually is. */
|
|
254
|
+
async function report(extra) {
|
|
255
|
+
if (!state?.current) return;
|
|
256
|
+
lastReportAt = Date.now();
|
|
257
|
+
try {
|
|
258
|
+
const next = await call('/report', {
|
|
259
|
+
method: 'POST',
|
|
260
|
+
body: { trackId: state.current.id, ...playback.progress(), ...extra },
|
|
261
|
+
});
|
|
262
|
+
// Taken, not acted on: acting here would retry a refused play from
|
|
263
|
+
// the answer to its own refusal, as fast as the host can reply.
|
|
264
|
+
if (next?.rev !== undefined) take(next);
|
|
265
|
+
} catch { /* the next update carries the host's view */ }
|
|
201
266
|
}
|
|
202
267
|
|
|
203
268
|
/**
|
|
204
|
-
*
|
|
269
|
+
* Adopt one host state, unless it is older than the one held.
|
|
205
270
|
*
|
|
206
|
-
*
|
|
207
|
-
*
|
|
208
|
-
* one
|
|
209
|
-
*
|
|
271
|
+
* A report's answer and a pushed frame travel on different connections,
|
|
272
|
+
* so one read earlier can land later; adopting it would undo the newer
|
|
273
|
+
* one — resume a pause, or load the quality just left — with no frame
|
|
274
|
+
* coming to repair it. While the stream is open, a state whose `version`
|
|
275
|
+
* is older than the newest one adopted is dropped. A reconnect drops the
|
|
276
|
+
* floor, since a restarted host counts its versions from zero again.
|
|
277
|
+
* A host without versions is taken as it comes.
|
|
210
278
|
*
|
|
211
|
-
*
|
|
212
|
-
* two levels is two different files, so a change must load a new one
|
|
213
|
-
* instead of range-requesting offsets into the other encoding. The track
|
|
214
|
-
* id stays in the key so a switch resumes in place.
|
|
279
|
+
* @returns {boolean} whether it was adopted.
|
|
215
280
|
*/
|
|
216
|
-
function
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
audio.pause();
|
|
223
|
-
audio.removeAttribute('src');
|
|
224
|
-
audio.load();
|
|
225
|
-
}
|
|
226
|
-
return;
|
|
281
|
+
function take(next) {
|
|
282
|
+
if (disposed || !next) return false;
|
|
283
|
+
const version = Number(next.version);
|
|
284
|
+
if (Number.isFinite(version)) {
|
|
285
|
+
if (streaming && version < versionFloor) return false;
|
|
286
|
+
versionFloor = version;
|
|
227
287
|
}
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
if (audio.dataset.trackKey === key) return;
|
|
232
|
-
|
|
233
|
-
const sameTrack = audio.dataset.trackId === String(track.id);
|
|
234
|
-
const resumeAt = sameTrack ? audio.currentTime : 0;
|
|
235
|
-
audio.dataset.trackKey = key;
|
|
236
|
-
audio.dataset.trackId = String(track.id);
|
|
237
|
-
if (resumeAt > 0.5) {
|
|
238
|
-
audio.addEventListener(
|
|
239
|
-
'loadedmetadata',
|
|
240
|
-
() => {
|
|
241
|
-
try {
|
|
242
|
-
audio.currentTime = resumeAt;
|
|
243
|
-
} catch { /* not seekable */ }
|
|
244
|
-
},
|
|
245
|
-
{ once: true },
|
|
246
|
-
);
|
|
247
|
-
}
|
|
248
|
-
audio.src = `${origin()}${BASE}/stream/${track.id}?level=${encodeURIComponent(level)}`;
|
|
249
|
-
audio.load();
|
|
288
|
+
state = next;
|
|
289
|
+
reconcile(next);
|
|
290
|
+
return true;
|
|
250
291
|
}
|
|
251
292
|
|
|
252
|
-
/**
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
* outcomes are reported at once, so the host — and the panel's hint —
|
|
258
|
-
* learns the real state instead of waiting for the next scheduled report.
|
|
259
|
-
*/
|
|
260
|
-
function attemptPlay() {
|
|
261
|
-
if (playing || disposed) return;
|
|
262
|
-
playing = true;
|
|
263
|
-
const done = () => {
|
|
264
|
-
playing = false;
|
|
265
|
-
void report({});
|
|
266
|
-
};
|
|
267
|
-
audio.play().then(done, done);
|
|
293
|
+
/** Adopt one host state and bring the element in line with it. */
|
|
294
|
+
function receive(next) {
|
|
295
|
+
if (!take(next)) return;
|
|
296
|
+
applySource(next);
|
|
297
|
+
enforce(next);
|
|
268
298
|
}
|
|
269
299
|
|
|
270
|
-
/**
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
function enforce(next) {
|
|
279
|
-
audio.volume = next.muted ? 0 : next.volume;
|
|
280
|
-
if (!next.current) return;
|
|
281
|
-
if (next.playing && audio.paused) {
|
|
282
|
-
attemptPlay();
|
|
283
|
-
} else if (!next.playing && !audio.paused) {
|
|
284
|
-
audio.pause();
|
|
285
|
-
void report({});
|
|
300
|
+
/** Read the host's state over a plain request. */
|
|
301
|
+
async function poll() {
|
|
302
|
+
if (disposed || inflight) return;
|
|
303
|
+
inflight = true;
|
|
304
|
+
try {
|
|
305
|
+
receive(await call('/state'));
|
|
306
|
+
} catch { /* host not reachable yet; the next tick tries again */ } finally {
|
|
307
|
+
inflight = false;
|
|
286
308
|
}
|
|
287
309
|
}
|
|
288
310
|
|
|
289
|
-
/**
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
reconcile(next);
|
|
311
|
+
/** Subscribe to the host's pushed state, where the browser can. */
|
|
312
|
+
function listen() {
|
|
313
|
+
relisten = null;
|
|
314
|
+
const Source = window.EventSource;
|
|
315
|
+
if (disposed || typeof Source !== 'function') return;
|
|
316
|
+
events = new Source(`${API}/events`);
|
|
317
|
+
events.onopen = () => {
|
|
318
|
+
streaming = true;
|
|
319
|
+
versionFloor = 0;
|
|
320
|
+
};
|
|
321
|
+
events.onerror = () => {
|
|
322
|
+
streaming = false;
|
|
323
|
+
// A dropped connection is retried by the browser; an error status
|
|
324
|
+
// (a host that predates the route) closes the stream for good.
|
|
325
|
+
if (events?.readyState === Source.CLOSED) {
|
|
326
|
+
events = null;
|
|
327
|
+
if (!disposed) relisten = setTimeout(listen, RELISTEN_MS);
|
|
307
328
|
}
|
|
308
|
-
}
|
|
329
|
+
};
|
|
330
|
+
events.addEventListener('state', (event) => {
|
|
331
|
+
try {
|
|
332
|
+
receive(JSON.parse(event.data));
|
|
333
|
+
} catch { /* a garbled frame; the next one carries the whole state */ }
|
|
334
|
+
});
|
|
309
335
|
}
|
|
310
336
|
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
if (disposed || inflight) return;
|
|
321
|
-
inflight = true;
|
|
322
|
-
try {
|
|
323
|
-
const next = await call('/state');
|
|
324
|
-
state = next;
|
|
325
|
-
reconcile(next);
|
|
326
|
-
applySource(next);
|
|
327
|
-
enforce(next);
|
|
328
|
-
const due = next.playing && !audio.paused ? REPORT_MS : IDLE_REPORT_MS;
|
|
329
|
-
if (audio.dataset.trackId && Date.now() - lastReportAt >= due) void report({});
|
|
330
|
-
} catch { /* host not reachable yet; keep polling */ } finally {
|
|
331
|
-
inflight = false;
|
|
337
|
+
function tick() {
|
|
338
|
+
if (disposed) return;
|
|
339
|
+
if (!streaming) void poll();
|
|
340
|
+
else if (state) {
|
|
341
|
+
// The host has nothing new to say about a refused play, so it is
|
|
342
|
+
// retried here, against the state already held — which a report's
|
|
343
|
+
// answer may have moved to the next track without loading it.
|
|
344
|
+
applySource(state);
|
|
345
|
+
enforce(state);
|
|
332
346
|
}
|
|
347
|
+
const due = state?.playing && !audio.paused ? REPORT_MS : IDLE_REPORT_MS;
|
|
348
|
+
if (audio.dataset.trackId && Date.now() - lastReportAt >= due) void report({});
|
|
333
349
|
}
|
|
334
350
|
|
|
335
|
-
const timer = setInterval(
|
|
336
|
-
void
|
|
351
|
+
const timer = setInterval(tick, TICK_MS);
|
|
352
|
+
void poll();
|
|
353
|
+
listen();
|
|
337
354
|
|
|
338
355
|
return {
|
|
339
356
|
/**
|
|
@@ -342,30 +359,38 @@ window.__ModuleLoader__.load({
|
|
|
342
359
|
* engine never leaves playback unowned.
|
|
343
360
|
*/
|
|
344
361
|
playback: true,
|
|
345
|
-
/**
|
|
362
|
+
/** Re-read the host now: the page just sent a command and wants it applied. */
|
|
346
363
|
sync() {
|
|
347
|
-
|
|
364
|
+
void poll();
|
|
348
365
|
},
|
|
349
366
|
/**
|
|
350
367
|
* Retry playback synchronously, for a click on the autoplay hint.
|
|
351
368
|
*
|
|
352
369
|
* Called from inside the gesture so the attempt lands while the page is
|
|
353
|
-
* being activated, rather than on the next
|
|
370
|
+
* being activated, rather than on the next tick.
|
|
354
371
|
*/
|
|
355
372
|
playNow() {
|
|
356
|
-
|
|
373
|
+
playback.playNow();
|
|
357
374
|
},
|
|
358
375
|
state() {
|
|
359
376
|
return state;
|
|
360
377
|
},
|
|
378
|
+
/**
|
|
379
|
+
* Where playback is, in milliseconds, read off the element itself, so
|
|
380
|
+
* the page's bar moves smoothly without a report per frame. A held seek
|
|
381
|
+
* counts as already there.
|
|
382
|
+
*/
|
|
383
|
+
position() {
|
|
384
|
+
return playback.position();
|
|
385
|
+
},
|
|
361
386
|
dispose() {
|
|
362
387
|
disposed = true;
|
|
363
388
|
clearInterval(timer);
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
389
|
+
clearTimeout(relisten);
|
|
390
|
+
events?.close();
|
|
391
|
+
events = null;
|
|
392
|
+
streaming = false;
|
|
393
|
+
playback.dispose();
|
|
369
394
|
},
|
|
370
395
|
};
|
|
371
396
|
}
|
package/lib/feed.js
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server-sent player state, for the player page and the audio engine.
|
|
3
|
+
*
|
|
4
|
+
* `GET /music/api/events` holds the response open as an event stream and
|
|
5
|
+
* writes the full snapshot whenever something either of them would show or
|
|
6
|
+
* act on changes. Both used to re-read `/state` on a timer — the page every
|
|
7
|
+
* 1.5 s, the engine every 500 ms — and the page rebuilt its lists on every
|
|
8
|
+
* read whether or not anything had moved.
|
|
9
|
+
*
|
|
10
|
+
* A change is found by comparing snapshots rather than by trusting every
|
|
11
|
+
* mutation to announce itself: the snapshot draws on the player, the session
|
|
12
|
+
* store, the like cache, the scrobbler and the stream resolver, and several of
|
|
13
|
+
* those change without passing through the player. Announcements only decide
|
|
14
|
+
* *when* to compare: on a player bump, after any API write, and on a slow
|
|
15
|
+
* sweep that catches what announces nothing (a boost running out, a like
|
|
16
|
+
* resolved in the background, a sign-in from an agent tool). The position
|
|
17
|
+
* report the engine posts every second bumps the player, but moves nothing
|
|
18
|
+
* the comparison sees, so a playing track sends no frames.
|
|
19
|
+
*
|
|
20
|
+
* @module dsh-music/feed
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/** Keeps idle connections, and the desktop shell's forwarding fetch, alive. */
|
|
24
|
+
const HEARTBEAT_MS = 25_000;
|
|
25
|
+
|
|
26
|
+
/** How soon a dropped browser connection reconnects. */
|
|
27
|
+
const RETRY_MS = 2_000;
|
|
28
|
+
|
|
29
|
+
/** Compare this often even when nothing announced a change. */
|
|
30
|
+
const SWEEP_MS = 5_000;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The snapshot as the page and engine see it, minus what moves while a track
|
|
34
|
+
* plays: the position, its timestamp, and the revision a position report bumps.
|
|
35
|
+
* The last stream request's time goes too: every seek is a new range request,
|
|
36
|
+
* and the time is all that changes about it.
|
|
37
|
+
*/
|
|
38
|
+
export function visibleKey(snapshot) {
|
|
39
|
+
const { rev, version, reported, audio, ...rest } = snapshot ?? {};
|
|
40
|
+
const { position, at, ...steady } = reported ?? {};
|
|
41
|
+
const { at: requestedAt, ...last } = audio?.last ?? {};
|
|
42
|
+
return JSON.stringify({ ...rest, reported: steady, audio: { ...audio, last } });
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Numbers snapshots by what they show, for the clients' ordering guard.
|
|
47
|
+
*
|
|
48
|
+
* The player's `rev` cannot order them: a streaming quality, a setting or a
|
|
49
|
+
* resolved like changes the snapshot without bumping it, so a report's late
|
|
50
|
+
* answer and a newer pushed frame could share a `rev` and the stale one win.
|
|
51
|
+
* `version` moves whenever {@link visibleKey} does, whatever moved it, and
|
|
52
|
+
* never for a position report.
|
|
53
|
+
*/
|
|
54
|
+
export class SnapshotVersions {
|
|
55
|
+
constructor() {
|
|
56
|
+
this.key = undefined;
|
|
57
|
+
this.version = 0;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** `snapshot` with its `version`. */
|
|
61
|
+
stamp(snapshot) {
|
|
62
|
+
const key = visibleKey(snapshot);
|
|
63
|
+
if (key !== this.key) {
|
|
64
|
+
this.key = key;
|
|
65
|
+
this.version += 1;
|
|
66
|
+
}
|
|
67
|
+
return { ...snapshot, version: this.version };
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function frame(snapshot) {
|
|
72
|
+
return `event: state\ndata: ${JSON.stringify(snapshot)}\n\n`;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export class StateFeed {
|
|
76
|
+
/**
|
|
77
|
+
* @param {object} options
|
|
78
|
+
* @param {() => Promise<object>} options.snapshot the state document to send.
|
|
79
|
+
* @param {{warn: Function}} [options.logger]
|
|
80
|
+
* @param {number} [options.sweepMs]
|
|
81
|
+
* @param {number} [options.heartbeatMs]
|
|
82
|
+
*/
|
|
83
|
+
constructor({ snapshot, logger, sweepMs = SWEEP_MS, heartbeatMs = HEARTBEAT_MS }) {
|
|
84
|
+
this.snapshot = snapshot;
|
|
85
|
+
this.logger = logger;
|
|
86
|
+
this.sweepMs = sweepMs;
|
|
87
|
+
this.heartbeatMs = heartbeatMs;
|
|
88
|
+
/** @type {Set<import('node:http').ServerResponse>} */
|
|
89
|
+
this.clients = new Set();
|
|
90
|
+
/** Clients that have not been sent a state yet. */
|
|
91
|
+
this.newcomers = new Set();
|
|
92
|
+
/** What the clients were last sent, as {@link visibleKey}. */
|
|
93
|
+
this.lastKey = undefined;
|
|
94
|
+
/** The comparison under way, and whether another was asked for meanwhile. */
|
|
95
|
+
this.pending = null;
|
|
96
|
+
this.dirty = false;
|
|
97
|
+
this.sweep = undefined;
|
|
98
|
+
this.heartbeat = undefined;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Take over one `GET /events` response for as long as the client stays. */
|
|
102
|
+
attach(req, res) {
|
|
103
|
+
res.writeHead(200, {
|
|
104
|
+
'Content-Type': 'text/event-stream; charset=utf-8',
|
|
105
|
+
'Cache-Control': 'no-store',
|
|
106
|
+
'X-Accel-Buffering': 'no',
|
|
107
|
+
});
|
|
108
|
+
res.write(`retry: ${RETRY_MS}\n\n`);
|
|
109
|
+
this.clients.add(res);
|
|
110
|
+
this.newcomers.add(res);
|
|
111
|
+
this.#start();
|
|
112
|
+
const leave = () => {
|
|
113
|
+
this.newcomers.delete(res);
|
|
114
|
+
if (!this.clients.delete(res)) return;
|
|
115
|
+
if (this.clients.size === 0) this.#stop();
|
|
116
|
+
};
|
|
117
|
+
req.on('close', leave);
|
|
118
|
+
res.on('close', leave);
|
|
119
|
+
res.on('error', leave);
|
|
120
|
+
// Through the same queue as every other frame, so a newcomer's first state
|
|
121
|
+
// can never land after a newer one.
|
|
122
|
+
this.changed();
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Something may have changed; compare once the current burst has settled. */
|
|
126
|
+
changed() {
|
|
127
|
+
if (this.clients.size === 0) return;
|
|
128
|
+
if (this.pending) {
|
|
129
|
+
this.dirty = true;
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
this.pending = this.#flush().finally(() => {
|
|
133
|
+
this.pending = null;
|
|
134
|
+
if (this.dirty) {
|
|
135
|
+
this.dirty = false;
|
|
136
|
+
this.changed();
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** End every stream and stop the timers; the route is going away. */
|
|
142
|
+
close() {
|
|
143
|
+
for (const res of this.clients) {
|
|
144
|
+
try {
|
|
145
|
+
res.end();
|
|
146
|
+
} catch { /* the socket is already gone */ }
|
|
147
|
+
}
|
|
148
|
+
this.clients.clear();
|
|
149
|
+
this.newcomers.clear();
|
|
150
|
+
this.#stop();
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async #flush() {
|
|
154
|
+
// One comparison for a burst of synchronous mutations, not one each.
|
|
155
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
156
|
+
let snapshot;
|
|
157
|
+
try {
|
|
158
|
+
snapshot = await this.snapshot();
|
|
159
|
+
} catch (error) {
|
|
160
|
+
this.logger?.warn?.(`[music] event stream could not read the state: ${error.message}`);
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
const key = visibleKey(snapshot);
|
|
164
|
+
// Everyone when it moved; otherwise only those who have nothing yet.
|
|
165
|
+
const targets = key === this.lastKey ? [...this.newcomers] : [...this.clients];
|
|
166
|
+
this.lastKey = key;
|
|
167
|
+
this.newcomers.clear();
|
|
168
|
+
if (targets.length === 0) return;
|
|
169
|
+
const text = frame(snapshot);
|
|
170
|
+
for (const res of targets) res.write(text);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
#start() {
|
|
174
|
+
if (this.sweep !== undefined) return;
|
|
175
|
+
this.sweep = setInterval(() => this.changed(), this.sweepMs);
|
|
176
|
+
this.sweep.unref?.();
|
|
177
|
+
this.heartbeat = setInterval(() => {
|
|
178
|
+
for (const res of this.clients) res.write(': ping\n\n');
|
|
179
|
+
}, this.heartbeatMs);
|
|
180
|
+
this.heartbeat.unref?.();
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
#stop() {
|
|
184
|
+
clearInterval(this.sweep);
|
|
185
|
+
clearInterval(this.heartbeat);
|
|
186
|
+
this.sweep = undefined;
|
|
187
|
+
this.heartbeat = undefined;
|
|
188
|
+
// Nobody holds the last frame any more; the next client starts afresh.
|
|
189
|
+
this.lastKey = undefined;
|
|
190
|
+
}
|
|
191
|
+
}
|
package/lib/index.js
CHANGED
|
@@ -33,7 +33,7 @@ export const inject = ['tools', 'webServer'];
|
|
|
33
33
|
|
|
34
34
|
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
|
35
35
|
|
|
36
|
-
/** Read a shipped asset once at module load;
|
|
36
|
+
/** Read a shipped asset once at module load; they are small. */
|
|
37
37
|
function readAsset(...segments) {
|
|
38
38
|
return fs.readFileSync(path.join(HERE, ...segments), 'utf8');
|
|
39
39
|
}
|
|
@@ -44,9 +44,12 @@ function readAsset(...segments) {
|
|
|
44
44
|
* Deliberately module-scoped rather than read inside {@link apply}: a plugin
|
|
45
45
|
* remount re-runs `apply`, and reading here instead would let a remounted
|
|
46
46
|
* plugin serve a page from a *newer* working tree than the code it is running
|
|
47
|
-
* beside. The page and the module must describe the same contract
|
|
47
|
+
* beside. The page and the module must describe the same contract, and so must
|
|
48
|
+
* the playback core: the page runs it, and the engine trusts it on the strength
|
|
49
|
+
* of that contract.
|
|
48
50
|
*/
|
|
49
51
|
const PANEL_HTML = readAsset('panel.html');
|
|
52
|
+
const PLAYBACK_JS = readAsset('playback.js');
|
|
50
53
|
const QRCODE_JS = readAsset('vendor', 'qrcode.js');
|
|
51
54
|
|
|
52
55
|
/**
|
|
@@ -279,6 +282,7 @@ export function apply(ctx, config = {}) {
|
|
|
279
282
|
likes,
|
|
280
283
|
scrobbler,
|
|
281
284
|
panelHtml: PANEL_HTML,
|
|
285
|
+
playbackJs: PLAYBACK_JS,
|
|
282
286
|
qrcodeJs: QRCODE_JS,
|
|
283
287
|
config,
|
|
284
288
|
listRoutes: () => dj.listRoutes(),
|
|
@@ -752,6 +756,7 @@ export function apply(ctx, config = {}) {
|
|
|
752
756
|
} catch {
|
|
753
757
|
// The route table is already gone when the webserver unloads first.
|
|
754
758
|
}
|
|
759
|
+
router.dispose();
|
|
755
760
|
store.close();
|
|
756
761
|
logger.debug('[music] unloaded');
|
|
757
762
|
});
|