@doitian/dsh-music 1.0.0 → 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.
@@ -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
 
@@ -41,6 +44,9 @@ const INTRO_TTL_MS = 7 * 24 * 60 * 60 * 1000;
41
44
  * plugin's always-mounted engine. A client bundle that does not see this value
42
45
  * stays out of the way, because a host predating it still serves a page that
43
46
  * owns its own `<audio>` — starting both would play every track twice.
47
+ *
48
+ * The engine also runs this host's `/music/playback.js`, so the contract
49
+ * covers that file's interface as well.
44
50
  */
45
51
  const PANEL_CONTRACT = 2;
46
52
 
@@ -109,13 +115,14 @@ export class MusicRouter {
109
115
  * @param {import('./dj.js').AiDj} options.dj
110
116
  * @param {import('./likes.js').LikeState} options.likes
111
117
  * @param {string} options.panelHtml
118
+ * @param {string} options.playbackJs
112
119
  * @param {string} options.qrcodeJs
113
120
  * @param {object} [options.config]
114
121
  * @param {() => Promise<object>} [options.listRoutes] model routes for the picker.
115
122
  * @param {() => object} [options.diagnostics] extra facts for `/health`.
116
123
  * @param {{warn: Function, info: Function, debug: Function}} [options.logger]
117
124
  */
118
- constructor({ base, api, player, store, qr, dj, likes, scrobbler, panelHtml, qrcodeJs, config = {}, listRoutes, diagnostics, logger }) {
125
+ constructor({ base, api, player, store, qr, dj, likes, scrobbler, panelHtml, playbackJs, qrcodeJs, config = {}, listRoutes, diagnostics, logger }) {
119
126
  this.base = base.replace(/\/+$/, '');
120
127
  this.api = api;
121
128
  this.player = player;
@@ -125,6 +132,7 @@ export class MusicRouter {
125
132
  this.scrobbler = scrobbler;
126
133
  this.likes = likes;
127
134
  this.panelHtml = panelHtml;
135
+ this.playbackJs = playbackJs;
128
136
  this.qrcodeJs = qrcodeJs;
129
137
  this.config = config;
130
138
  this.listRoutes = listRoutes;
@@ -140,6 +148,15 @@ export class MusicRouter {
140
148
  this.infoCache = new TtlCache({ maxEntries: 200 });
141
149
  /** Model-written introductions, per track and language. */
142
150
  this.introCache = new TtlCache({ maxEntries: 400 });
151
+ this.versions = new SnapshotVersions();
152
+ this.feed = new StateFeed({ snapshot: () => this.snapshot(), logger });
153
+ this.unsubscribe = player.subscribe(() => this.feed.changed());
154
+ }
155
+
156
+ /** Close the event streams; the route is being withdrawn. */
157
+ dispose() {
158
+ this.unsubscribe();
159
+ this.feed.close();
143
160
  }
144
161
 
145
162
  /** A song's details, shared by the details pane and the introduction written from them. */
@@ -235,6 +252,7 @@ export class MusicRouter {
235
252
  error: resolved.reason,
236
253
  at: Date.now(),
237
254
  };
255
+ this.feed.changed();
238
256
  sendJson(res, 403, { error: `track ${trackId} is ${resolved.reason}`, code: resolved.code });
239
257
  return;
240
258
  }
@@ -252,6 +270,7 @@ export class MusicRouter {
252
270
  size: resolved.size,
253
271
  at: Date.now(),
254
272
  };
273
+ this.feed.changed();
255
274
 
256
275
  let upstream;
257
276
  try {
@@ -356,16 +375,21 @@ export class MusicRouter {
356
375
  }
357
376
 
358
377
  /**
359
- * The panel's poll target: full player snapshot including account and DJ.
378
+ * What the panel and the engine read and are pushed: the full player
379
+ * snapshot, including account and DJ.
360
380
  *
361
381
  * Async because `liked` is NetEase's answer rather than the host's: the queued
362
382
  * tracks' like state is resolved (once, then cached) before the document is
363
383
  * written, so a heart never lags a poll behind the track it belongs to.
384
+ *
385
+ * Every answer carries a `version` (see {@link SnapshotVersions}), stamped
386
+ * once the snapshot is complete, so the clients can tell which of two
387
+ * answers is newer.
364
388
  */
365
389
  async snapshot(extra = {}) {
366
390
  await this.refreshLikes();
367
391
  const base = this.player.snapshot();
368
- return {
392
+ const snapshot = this.versions.stamp({
369
393
  ...base,
370
394
  queue: base.queue.map((track) => this.tasteView(track)),
371
395
  current: this.tasteView(base.current),
@@ -379,8 +403,8 @@ export class MusicRouter {
379
403
  scrobble: this.scrobbler?.status() ?? null,
380
404
  /** Preferred quality, plus what the last stream request actually served. */
381
405
  audio: { preferred: this.preferredLevel(), last: this.lastAudio },
382
- ...extra,
383
- };
406
+ });
407
+ return { ...snapshot, ...extra };
384
408
  }
385
409
 
386
410
  /** Where the DJ's model route comes from. */
@@ -507,6 +531,9 @@ export class MusicRouter {
507
531
  if (route === '/state' && method === 'GET') {
508
532
  return sendJson(res, 200, await this.snapshot());
509
533
  }
534
+ if (route === '/events' && method === 'GET') {
535
+ return this.feed.attach(req, res);
536
+ }
510
537
  if (route === '/report' && method === 'POST') {
511
538
  const body = await readJson(req);
512
539
  this.player.report(body);
@@ -756,7 +783,7 @@ export class MusicRouter {
756
783
  if (prompt !== undefined) this.dj.setPrompt(prompt);
757
784
  if (enabled !== undefined) this.dj.setEnabled(enabled);
758
785
  if (replan || (enabled && this.player.queue.length === 0)) {
759
- // Planning is slow; answer immediately and let the panel poll the result.
786
+ // Planning is slow; answer immediately, and the plan is pushed when it lands.
760
787
  void this.dj.topUp({ force: true });
761
788
  } else if (prompt !== undefined && this.player.dj.enabled) {
762
789
  void this.dj.topUp({ force: true });
@@ -822,6 +849,16 @@ export class MusicRouter {
822
849
  res.end(html);
823
850
  return true;
824
851
  }
852
+ if (rest === '/playback.js') {
853
+ // Never cached: the page and the engine must run the copy this host
854
+ // was read with, not one left over from an earlier generation.
855
+ res.writeHead(200, {
856
+ 'Content-Type': 'text/javascript; charset=utf-8',
857
+ 'Cache-Control': 'no-store',
858
+ });
859
+ res.end(this.playbackJs);
860
+ return true;
861
+ }
825
862
  if (rest === '/vendor/qrcode.js') {
826
863
  res.writeHead(200, {
827
864
  'Content-Type': 'text/javascript; charset=utf-8',
@@ -840,6 +877,8 @@ export class MusicRouter {
840
877
  account: this.api.account,
841
878
  playing: this.player.playing,
842
879
  queued: this.player.queue.length,
880
+ /** Open `/api/events` streams: the engine's, plus the page's while it is shown. */
881
+ eventStreams: this.feed.clients.size,
843
882
  ...(this.diagnostics ? this.diagnostics() : {}),
844
883
  });
845
884
  return true;
@@ -850,6 +889,9 @@ export class MusicRouter {
850
889
  }
851
890
  if (rest.startsWith('/api/')) {
852
891
  await this.handleApi(req, res, pathname);
892
+ // Not every write goes through the player: settings, the session and
893
+ // the like cache change behind it, so any write is worth a comparison.
894
+ if (req.method !== 'GET') this.feed.changed();
853
895
  return true;
854
896
  }
855
897
  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.1.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": {