@doitian/dsh-music 1.0.0 → 1.2.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.
@@ -0,0 +1,343 @@
1
+ /**
2
+ * Audio playback, shared by both owners of the `<audio>` element.
3
+ *
4
+ * Normally that is the client plugin's engine in the shell document
5
+ * (lib/client.js); when the engine is inert, it is the player page's fallback
6
+ * transport (lib/panel.html). Both run this one file, so the fades, the seek
7
+ * hold, the autoplay retry and the resource identity cannot drift apart.
8
+ *
9
+ * The host serves it at `/music/playback.js`, read in the same module
10
+ * generation as the page, and the page loads it with a `<script>` of its own:
11
+ * the page never runs code from the bundle. The engine loads the same URL only
12
+ * after the panel-contract handshake, which makes what `createPlayback` takes
13
+ * and returns part of that contract — changing either needs a new
14
+ * `PANEL_CONTRACT`.
15
+ *
16
+ * A classic script rather than a module, since no bundler stands in front of
17
+ * either document. Everything but `window.__dshMusicPlayback` stays in its own
18
+ * scope, so nothing here can collide with the page's top-level names.
19
+ *
20
+ * @module dsh-music/playback
21
+ */
22
+
23
+ (function () {
24
+ /**
25
+ * Volume fades: play and pause ease over `FADE_MS`. A seek fades to silence
26
+ * over `SEEK_FADE_MS` and holds there until no other seek has arrived for
27
+ * `SEEK_SETTLE_MS`; only then does it jump and fade back in, so a burst of
28
+ * seeks plays nothing in between and jumps once.
29
+ */
30
+ const FADE_MS = 300;
31
+ const SEEK_FADE_MS = 120;
32
+ const SEEK_SETTLE_MS = 400;
33
+ const FADE_STEP_MS = 16;
34
+
35
+ /**
36
+ * Create a hidden `<audio>` element in this document and keep it in line
37
+ * with the host's desired state.
38
+ *
39
+ * The owner keeps everything about where that state comes from: it hands
40
+ * each snapshot over, and `report` posts to `/report` with the track it
41
+ * believes is current, {@link progress}, and `extra`.
42
+ *
43
+ * @param {object} options
44
+ * @param {string} options.base route prefix, e.g. `/music`.
45
+ * @param {() => string} options.streamOrigin origin that serves audio bytes; `''` keeps the document's.
46
+ * @param {(path: string, init?: object) => Promise<object>} options.call one JSON round-trip under `${base}/api`.
47
+ * @param {(extra: object) => unknown} options.report tell the host where playback actually is.
48
+ */
49
+ function createPlayback({ base, streamOrigin, call, report }) {
50
+ const audio = document.createElement('audio');
51
+ audio.preload = 'auto';
52
+ audio.setAttribute('aria-hidden', 'true');
53
+ audio.style.display = 'none';
54
+ (document.body ?? document.documentElement).appendChild(audio);
55
+
56
+ let appliedTransport = -1;
57
+ let disposed = false;
58
+ /** Guards against stacking overlapping `play()` attempts. */
59
+ let playing = false;
60
+ /** The host's volume; the element plays at `level * gain`. */
61
+ let level = 1;
62
+ /** Fade multiplier, eased by {@link fadeTo}. */
63
+ let gain = 1;
64
+ /** The running fade, if any: its timer and the gain it heads for. */
65
+ let fade = null;
66
+ /** Fading out towards a pause that has not happened yet. */
67
+ let pausing = false;
68
+ /** Seek target in seconds, held until the seeks settle (or a pause lands). */
69
+ let seekTarget = null;
70
+ /** The silent wait after a seek; any fade, or another seek, cancels it. */
71
+ let hold = null;
72
+
73
+ function applyVolume() {
74
+ audio.volume = Math.min(Math.max(level * gain, 0), 1);
75
+ }
76
+
77
+ /**
78
+ * Ease `gain` to `to`, then call `done`.
79
+ *
80
+ * Paced by the clock rather than by counting steps, so a throttled timer
81
+ * in a hidden window makes the ramp coarser but not longer. The duration
82
+ * scales with the distance left, so reversing halfway keeps the rate. A
83
+ * new fade replaces the running one, `done` included.
84
+ */
85
+ function fadeTo(to, ms, done) {
86
+ clearInterval(fade?.timer);
87
+ clearTimeout(hold);
88
+ hold = null;
89
+ const from = gain;
90
+ const start = Date.now();
91
+ const span = Math.abs(to - from) * ms;
92
+ const current = { to, timer: 0 };
93
+ const step = () => {
94
+ const progress = span > 0 ? Math.min((Date.now() - start) / span, 1) : 1;
95
+ gain = from + (to - from) * progress;
96
+ applyVolume();
97
+ if (progress < 1) return;
98
+ clearInterval(current.timer);
99
+ if (fade === current) fade = null;
100
+ done?.();
101
+ };
102
+ current.timer = setInterval(step, FADE_STEP_MS);
103
+ fade = current;
104
+ step();
105
+ }
106
+
107
+ function land() {
108
+ if (seekTarget === null) return;
109
+ try {
110
+ audio.currentTime = seekTarget;
111
+ } catch { /* not seekable until metadata arrives */ }
112
+ seekTarget = null;
113
+ }
114
+
115
+ /**
116
+ * Fade to silence and wait there for the seeks to settle, then jump and
117
+ * fade back in. Called again while silent, it restarts the wait at once,
118
+ * which is what cancels the playback queued for the previous target.
119
+ */
120
+ function holdForSeek() {
121
+ fadeTo(0, SEEK_FADE_MS, () => {
122
+ hold = setTimeout(() => {
123
+ land();
124
+ fadeTo(1, SEEK_FADE_MS);
125
+ }, SEEK_SETTLE_MS);
126
+ });
127
+ }
128
+
129
+ /**
130
+ * Seek, debounced while audible. A seek during the fade-out only moves
131
+ * the target; the pause that may be fading out lands it instead.
132
+ */
133
+ function seek(seconds) {
134
+ seekTarget = seconds;
135
+ if (audio.paused) land();
136
+ else if (fade?.to !== 0) holdForSeek();
137
+ }
138
+
139
+ function fadeOutAndPause() {
140
+ if (pausing) return;
141
+ pausing = true;
142
+ fadeTo(0, FADE_MS, () => {
143
+ pausing = false;
144
+ land();
145
+ audio.pause();
146
+ void report({});
147
+ });
148
+ }
149
+
150
+ /** Play was asked for again before the fade-out reached the pause. */
151
+ function cancelPause() {
152
+ pausing = false;
153
+ if (seekTarget !== null) holdForSeek();
154
+ else fadeTo(1, FADE_MS);
155
+ }
156
+
157
+ /**
158
+ * Start playback, tolerating a refusal.
159
+ *
160
+ * Chromium blocks audio until the page has been activated by a gesture,
161
+ * so an attempt can legitimately fail and has to be repeatable. Both
162
+ * outcomes are reported at once, so the host — and the panel's hint —
163
+ * learns the real state instead of waiting for the next scheduled report.
164
+ * `blocked` says which: only the autoplay policy's `NotAllowedError` is a
165
+ * reason to ask for a click, not an attempt still under way or one
166
+ * interrupted by a new source.
167
+ */
168
+ function attemptPlay() {
169
+ if (playing || disposed) return;
170
+ // Already playing (a repeated `playNow()`): restarting the fade would
171
+ // drop the audio out, so only call off a pause that is fading out.
172
+ if (!audio.paused) {
173
+ if (pausing) cancelPause();
174
+ return;
175
+ }
176
+ playing = true;
177
+ // Start silent and fade in once the browser has agreed to play.
178
+ pausing = false;
179
+ fadeTo(0, 0);
180
+ land();
181
+ audio.play().then(
182
+ () => {
183
+ playing = false;
184
+ // A seek that arrived while play() was pending owns the fade-in.
185
+ if (seekTarget === null) fadeTo(1, FADE_MS);
186
+ void report({ blocked: false });
187
+ },
188
+ (error) => {
189
+ playing = false;
190
+ void report(error?.name === 'NotAllowedError' ? { blocked: true } : {});
191
+ },
192
+ );
193
+ }
194
+
195
+ /** Apply what a transport revision carries: the one-shot seek, once. */
196
+ function reconcile(next) {
197
+ if (next.transportRev === appliedTransport) return;
198
+ appliedTransport = next.transportRev;
199
+
200
+ if (next.pendingSeek !== null && next.pendingSeek !== undefined) {
201
+ seek(next.pendingSeek / 1000);
202
+ // One-shot: drop it so the next read cannot re-apply the seek.
203
+ void call('/seek-consumed', { method: 'POST', body: {} }).catch(() => {});
204
+ }
205
+ }
206
+
207
+ /**
208
+ * Decide which resource the element should be playing.
209
+ *
210
+ * Runs on every update rather than behind the `transportRev` gate,
211
+ * because the resource identity includes the streaming quality: quality
212
+ * is not a one-shot transport change, and gating it meant a switch did
213
+ * nothing until something else moved the revision.
214
+ *
215
+ * The level is part of the URL, not implicit host state: the same track at
216
+ * two levels is two different files, so a change must load a new one
217
+ * instead of range-requesting offsets into the other encoding. The track
218
+ * id stays in the key so a switch resumes in place.
219
+ */
220
+ function applySource(next) {
221
+ const track = next.current;
222
+ if (!track) {
223
+ if (audio.dataset.trackKey !== undefined) {
224
+ delete audio.dataset.trackKey;
225
+ delete audio.dataset.trackId;
226
+ audio.pause();
227
+ audio.removeAttribute('src');
228
+ audio.load();
229
+ }
230
+ return;
231
+ }
232
+
233
+ const quality = next.audio?.preferred ?? 'exhigh';
234
+ const origin = streamOrigin();
235
+ // The origin is part of the identity, so a stream base published after
236
+ // boot still moves the element off the unseekable scheme.
237
+ const key = `${track.id}:${quality}:${origin}`;
238
+ if (audio.dataset.trackKey === key) return;
239
+
240
+ const sameTrack = audio.dataset.trackId === String(track.id);
241
+ // A held seek belongs to the track it was aimed at: a reload of the
242
+ // same track resumes there, another track drops it.
243
+ const resumeAt = sameTrack ? (seekTarget ?? audio.currentTime) : 0;
244
+ seekTarget = null;
245
+ audio.dataset.trackKey = key;
246
+ audio.dataset.trackId = String(track.id);
247
+ if (resumeAt > 0.5) {
248
+ audio.addEventListener(
249
+ 'loadedmetadata',
250
+ () => {
251
+ try {
252
+ audio.currentTime = resumeAt;
253
+ } catch { /* not seekable */ }
254
+ },
255
+ { once: true },
256
+ );
257
+ }
258
+ audio.src = `${origin}${base}/stream/${track.id}?level=${encodeURIComponent(quality)}`;
259
+ audio.load();
260
+ }
261
+
262
+ /**
263
+ * Keep the element in line with the desired transport, on every update.
264
+ *
265
+ * Deliberately outside the `transportRev` gate: a refused `play()` does
266
+ * not change the revision, so gating this would leave the music stopped
267
+ * for good after the first refusal — the panel would show the autoplay
268
+ * hint and pressing it would fix nothing.
269
+ */
270
+ function enforce(next) {
271
+ level = next.muted ? 0 : next.volume;
272
+ applyVolume();
273
+ if (!next.current) return;
274
+ if (next.playing && audio.paused) attemptPlay();
275
+ else if (next.playing && pausing) cancelPause();
276
+ else if (!next.playing && !audio.paused) fadeOutAndPause();
277
+ }
278
+
279
+ /** Milliseconds into the track. A held seek counts as already there. */
280
+ function position() {
281
+ return ((seekTarget ?? audio.currentTime) || 0) * 1000;
282
+ }
283
+
284
+ /**
285
+ * The fields of a `/report`, apart from the track. A held seek is where
286
+ * playback is about to be; reporting the old position would pull the
287
+ * panel's bar back while it waits.
288
+ */
289
+ function progress() {
290
+ return {
291
+ position: Math.round(position()),
292
+ duration: Number.isFinite(audio.duration) ? Math.round(audio.duration * 1000) : undefined,
293
+ playing: !audio.paused,
294
+ };
295
+ }
296
+
297
+ audio.addEventListener('ended', () => {
298
+ // The old position plays on silently while a seek is held; reaching its
299
+ // end is not the track finishing, so land the seek instead of advancing.
300
+ if (seekTarget !== null) {
301
+ land();
302
+ if (audio.paused) attemptPlay();
303
+ return;
304
+ }
305
+ void report({ ended: true });
306
+ });
307
+ audio.addEventListener('error', () => {
308
+ // Fires for an unavailable track and for a dropped connection alike;
309
+ // the host skips to the next track on either.
310
+ if (audio.dataset.trackId) void report({ error: 'audio element error (track unavailable or network)' });
311
+ });
312
+
313
+ return {
314
+ audio,
315
+ /** Bring the element in line with one host state. */
316
+ apply(next) {
317
+ if (disposed || !next) return;
318
+ reconcile(next);
319
+ applySource(next);
320
+ enforce(next);
321
+ },
322
+ reconcile,
323
+ applySource,
324
+ enforce,
325
+ /** Retry playback synchronously, from inside a click. */
326
+ playNow: attemptPlay,
327
+ position,
328
+ progress,
329
+ dispose() {
330
+ disposed = true;
331
+ clearInterval(fade?.timer);
332
+ clearTimeout(hold);
333
+ try {
334
+ audio.pause();
335
+ audio.removeAttribute('src');
336
+ audio.remove();
337
+ } catch { /* the document may already be gone */ }
338
+ },
339
+ };
340
+ }
341
+
342
+ window.__dshMusicPlayback = { createPlayback };
343
+ })();
package/lib/router.js CHANGED
@@ -4,8 +4,10 @@
4
4
  * Everything the panel needs is served from one prefix (default `/music`):
5
5
  *
6
6
  * GET /music/panel the player page
7
+ * GET /music/playback.js audio playback core, for the page and the engine
7
8
  * GET /music/vendor/qrcode.js vendored QR encoder (MIT)
8
9
  * GET /music/stream/<id> audio bytes, Range-aware
10
+ * GET /music/api/events the state as an event stream (see feed.js)
9
11
  * * /music/api/* JSON API
10
12
  *
11
13
  * The audio route is a proxy rather than a redirect. Two reasons: the CDN URL
@@ -22,6 +24,7 @@
22
24
  import { Readable } from 'node:stream';
23
25
 
24
26
  import { TtlCache } from './cache.js';
27
+ import { SnapshotVersions, StateFeed } from './feed.js';
25
28
  import { DEFAULT_LEVEL, LEVELS, isLevel } from './netease.js';
26
29
  import { BOOST_DIRECTIONS, TASTE_LEVELS } from './session.js';
27
30
 
@@ -31,6 +34,9 @@ const URL_CACHE_MS = 15 * 60 * 1000;
31
34
  /** Song details are kept this long: a wiki or an introduction is edited rarely. */
32
35
  const INFO_TTL_MS = 6 * 60 * 60 * 1000;
33
36
 
37
+ /** Lyrics are kept a day: they are rarely corrected, and "instrumental" is an answer too. */
38
+ const LYRIC_TTL_MS = 24 * 60 * 60 * 1000;
39
+
34
40
  /** A written introduction is kept longer: each one costs a model call. */
35
41
  const INTRO_TTL_MS = 7 * 24 * 60 * 60 * 1000;
36
42
 
@@ -41,6 +47,9 @@ const INTRO_TTL_MS = 7 * 24 * 60 * 60 * 1000;
41
47
  * plugin's always-mounted engine. A client bundle that does not see this value
42
48
  * stays out of the way, because a host predating it still serves a page that
43
49
  * owns its own `<audio>` — starting both would play every track twice.
50
+ *
51
+ * The engine also runs this host's `/music/playback.js`, so the contract
52
+ * covers that file's interface as well.
44
53
  */
45
54
  const PANEL_CONTRACT = 2;
46
55
 
@@ -109,13 +118,14 @@ export class MusicRouter {
109
118
  * @param {import('./dj.js').AiDj} options.dj
110
119
  * @param {import('./likes.js').LikeState} options.likes
111
120
  * @param {string} options.panelHtml
121
+ * @param {string} options.playbackJs
112
122
  * @param {string} options.qrcodeJs
113
123
  * @param {object} [options.config]
114
124
  * @param {() => Promise<object>} [options.listRoutes] model routes for the picker.
115
125
  * @param {() => object} [options.diagnostics] extra facts for `/health`.
116
126
  * @param {{warn: Function, info: Function, debug: Function}} [options.logger]
117
127
  */
118
- constructor({ base, api, player, store, qr, dj, likes, scrobbler, panelHtml, qrcodeJs, config = {}, listRoutes, diagnostics, logger }) {
128
+ constructor({ base, api, player, store, qr, dj, likes, scrobbler, panelHtml, playbackJs, qrcodeJs, config = {}, listRoutes, diagnostics, logger }) {
119
129
  this.base = base.replace(/\/+$/, '');
120
130
  this.api = api;
121
131
  this.player = player;
@@ -125,6 +135,7 @@ export class MusicRouter {
125
135
  this.scrobbler = scrobbler;
126
136
  this.likes = likes;
127
137
  this.panelHtml = panelHtml;
138
+ this.playbackJs = playbackJs;
128
139
  this.qrcodeJs = qrcodeJs;
129
140
  this.config = config;
130
141
  this.listRoutes = listRoutes;
@@ -138,8 +149,25 @@ export class MusicRouter {
138
149
  this.lastAudio = null;
139
150
  /** Song details for the panel, which barely change; each costs up to six requests. */
140
151
  this.infoCache = new TtlCache({ maxEntries: 200 });
152
+ /** Lyrics, so the panel's prefetch of the next track's costs nothing when it plays. */
153
+ this.lyricCache = new TtlCache({ maxEntries: 200 });
141
154
  /** Model-written introductions, per track and language. */
142
155
  this.introCache = new TtlCache({ maxEntries: 400 });
156
+ this.versions = new SnapshotVersions();
157
+ this.feed = new StateFeed({ snapshot: () => this.snapshot(), logger });
158
+ /** The current track, next track and level last pre-resolved, so a position report does not repeat it. */
159
+ this.audioPrefetchKey = null;
160
+ this.unsubscribe = player.subscribe(() => {
161
+ this.feed.changed();
162
+ this.prefetchNextAudio();
163
+ });
164
+ this.prefetchNextAudio();
165
+ }
166
+
167
+ /** Close the event streams; the route is being withdrawn. */
168
+ dispose() {
169
+ this.unsubscribe();
170
+ this.feed.close();
143
171
  }
144
172
 
145
173
  /** A song's details, shared by the details pane and the introduction written from them. */
@@ -166,6 +194,28 @@ export class MusicRouter {
166
194
 
167
195
  // ------------------------------------------------------------------ audio
168
196
 
197
+ /**
198
+ * Resolve the next track's CDN URL while this one plays, so a track change
199
+ * skips that round trip. Only in list mode: shuffle has no known next track,
200
+ * and repeat-one's next is this one. Runs whether or not the panel is open.
201
+ */
202
+ prefetchNextAudio() {
203
+ const current = this.player.current();
204
+ const next = this.player.mode === 'list'
205
+ ? this.player.queue[(this.player.index + 1) % this.player.queue.length]
206
+ : null;
207
+ if (!this.player.playing || !current || !next || next.id === current.id) {
208
+ this.audioPrefetchKey = null;
209
+ return;
210
+ }
211
+ const level = this.preferredLevel();
212
+ const key = `${current.id}:${next.id}:${level}`;
213
+ if (this.audioPrefetchKey === key) return;
214
+ this.audioPrefetchKey = key;
215
+ // Keep speculative failures out of playback diagnostics and avoid retrying on every report.
216
+ void Promise.resolve().then(() => this.resolveAudio(next.id, level)).catch(() => {});
217
+ }
218
+
169
219
  /**
170
220
  * Resolve (and cache) the signed CDN URL for one track at one level.
171
221
  *
@@ -235,6 +285,7 @@ export class MusicRouter {
235
285
  error: resolved.reason,
236
286
  at: Date.now(),
237
287
  };
288
+ this.feed.changed();
238
289
  sendJson(res, 403, { error: `track ${trackId} is ${resolved.reason}`, code: resolved.code });
239
290
  return;
240
291
  }
@@ -252,6 +303,7 @@ export class MusicRouter {
252
303
  size: resolved.size,
253
304
  at: Date.now(),
254
305
  };
306
+ this.feed.changed();
255
307
 
256
308
  let upstream;
257
309
  try {
@@ -356,16 +408,21 @@ export class MusicRouter {
356
408
  }
357
409
 
358
410
  /**
359
- * The panel's poll target: full player snapshot including account and DJ.
411
+ * What the panel and the engine read and are pushed: the full player
412
+ * snapshot, including account and DJ.
360
413
  *
361
414
  * Async because `liked` is NetEase's answer rather than the host's: the queued
362
415
  * tracks' like state is resolved (once, then cached) before the document is
363
416
  * written, so a heart never lags a poll behind the track it belongs to.
417
+ *
418
+ * Every answer carries a `version` (see {@link SnapshotVersions}), stamped
419
+ * once the snapshot is complete, so the clients can tell which of two
420
+ * answers is newer.
364
421
  */
365
422
  async snapshot(extra = {}) {
366
423
  await this.refreshLikes();
367
424
  const base = this.player.snapshot();
368
- return {
425
+ const snapshot = this.versions.stamp({
369
426
  ...base,
370
427
  queue: base.queue.map((track) => this.tasteView(track)),
371
428
  current: this.tasteView(base.current),
@@ -379,8 +436,8 @@ export class MusicRouter {
379
436
  scrobble: this.scrobbler?.status() ?? null,
380
437
  /** Preferred quality, plus what the last stream request actually served. */
381
438
  audio: { preferred: this.preferredLevel(), last: this.lastAudio },
382
- ...extra,
383
- };
439
+ });
440
+ return { ...snapshot, ...extra };
384
441
  }
385
442
 
386
443
  /** Where the DJ's model route comes from. */
@@ -507,6 +564,9 @@ export class MusicRouter {
507
564
  if (route === '/state' && method === 'GET') {
508
565
  return sendJson(res, 200, await this.snapshot());
509
566
  }
567
+ if (route === '/events' && method === 'GET') {
568
+ return this.feed.attach(req, res);
569
+ }
510
570
  if (route === '/report' && method === 'POST') {
511
571
  const body = await readJson(req);
512
572
  this.player.report(body);
@@ -579,7 +639,9 @@ export class MusicRouter {
579
639
  }
580
640
  if (route.startsWith('/lyric/') && method === 'GET') {
581
641
  const id = Number(route.slice('/lyric/'.length));
582
- return sendJson(res, 200, await this.api.lyric(id));
642
+ if (!Number.isInteger(id) || id <= 0) return sendJson(res, 400, { error: 'invalid track id' });
643
+ const lyric = await this.lyricCache.get(`lyric:${id}`, LYRIC_TTL_MS, () => this.api.lyric(id));
644
+ return sendJson(res, 200, lyric);
583
645
  }
584
646
  if (route.startsWith('/info/') && method === 'GET') {
585
647
  const id = Number(route.slice('/info/'.length));
@@ -704,6 +766,7 @@ export class MusicRouter {
704
766
  });
705
767
  }
706
768
  this.store.updateSettings({ level });
769
+ this.prefetchNextAudio();
707
770
  this.logger?.info?.(`[music] streaming quality set to ${level} from the player`);
708
771
  // The running stream keeps its bytes; the next load or seek uses this.
709
772
  return sendJson(res, 200, await this.snapshot());
@@ -756,7 +819,7 @@ export class MusicRouter {
756
819
  if (prompt !== undefined) this.dj.setPrompt(prompt);
757
820
  if (enabled !== undefined) this.dj.setEnabled(enabled);
758
821
  if (replan || (enabled && this.player.queue.length === 0)) {
759
- // Planning is slow; answer immediately and let the panel poll the result.
822
+ // Planning is slow; answer immediately, and the plan is pushed when it lands.
760
823
  void this.dj.topUp({ force: true });
761
824
  } else if (prompt !== undefined && this.player.dj.enabled) {
762
825
  void this.dj.topUp({ force: true });
@@ -822,6 +885,16 @@ export class MusicRouter {
822
885
  res.end(html);
823
886
  return true;
824
887
  }
888
+ if (rest === '/playback.js') {
889
+ // Never cached: the page and the engine must run the copy this host
890
+ // was read with, not one left over from an earlier generation.
891
+ res.writeHead(200, {
892
+ 'Content-Type': 'text/javascript; charset=utf-8',
893
+ 'Cache-Control': 'no-store',
894
+ });
895
+ res.end(this.playbackJs);
896
+ return true;
897
+ }
825
898
  if (rest === '/vendor/qrcode.js') {
826
899
  res.writeHead(200, {
827
900
  'Content-Type': 'text/javascript; charset=utf-8',
@@ -840,6 +913,8 @@ export class MusicRouter {
840
913
  account: this.api.account,
841
914
  playing: this.player.playing,
842
915
  queued: this.player.queue.length,
916
+ /** Open `/api/events` streams: the engine's, plus the page's while it is shown. */
917
+ eventStreams: this.feed.clients.size,
843
918
  ...(this.diagnostics ? this.diagnostics() : {}),
844
919
  });
845
920
  return true;
@@ -850,6 +925,9 @@ export class MusicRouter {
850
925
  }
851
926
  if (rest.startsWith('/api/')) {
852
927
  await this.handleApi(req, res, pathname);
928
+ // Not every write goes through the player: settings, the session and
929
+ // the like cache change behind it, so any write is worth a comparison.
930
+ if (req.method !== 'GET') this.feed.changed();
853
931
  return true;
854
932
  }
855
933
  sendJson(res, 404, { error: `not found: ${pathname}` });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@doitian/dsh-music",
3
- "version": "1.0.0",
3
+ "version": "1.2.0",
4
4
  "description": "NetEase Cloud Music (music.163.com) player and AI DJ for DeepSeek Harness: a sidebar page with in-app playback, QR sign-in, and agent tools that curate the queue.",
5
5
  "keywords": [
6
6
  "dsh",
@@ -33,19 +33,7 @@
33
33
  "./package.json": "./package.json"
34
34
  },
35
35
  "files": [
36
- "lib/index.js",
37
- "lib/client.js",
38
- "lib/netease.js",
39
- "lib/session.js",
40
- "lib/state.js",
41
- "lib/dj.js",
42
- "lib/cache.js",
43
- "lib/weapi.js",
44
- "lib/scrobble.js",
45
- "lib/likes.js",
46
- "lib/router.js",
47
- "lib/panel.html",
48
- "lib/vendor/qrcode.js",
36
+ "lib/",
49
37
  "cordis.patch.yml",
50
38
  "icon.svg",
51
39
  "README.md"
@@ -57,10 +45,11 @@
57
45
  "access": "public"
58
46
  },
59
47
  "scripts": {
60
- "check": "node --check lib/index.js && node --check lib/client.js && node --check lib/netease.js && node --check lib/session.js && node --check lib/state.js && node --check lib/dj.js && node --check lib/cache.js && node --check lib/weapi.js && node --check lib/scrobble.js && node --check lib/likes.js && node --check lib/router.js",
61
- "test": "node test/netease.test.mjs && node test/cache.test.mjs && node test/scrobble.test.mjs && node test/likes.test.mjs && node test/dj.test.mjs && node test/client.test.mjs",
48
+ "check": "node scripts/check.mjs",
49
+ "changelog": "npx --yes git-cliff@2.14.2 --bump --output CHANGELOG.md",
50
+ "test": "node --test --test-isolation=none \"test/*.test.mjs\"",
62
51
  "probe:headers": "node scripts/probe-headers.mjs",
63
- "test:live": "node test/host.test.mjs",
52
+ "test:live": "node --test --test-isolation=none \"test/live/*.test.mjs\"",
64
53
  "test:all": "npm test && npm run test:live"
65
54
  },
66
55
  "dsh": {