@doitian/dsh-music 0.1.8 → 0.1.10

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/router.js CHANGED
@@ -21,12 +21,19 @@
21
21
 
22
22
  import { Readable } from 'node:stream';
23
23
 
24
+ import { TtlCache } from './cache.js';
24
25
  import { DEFAULT_LEVEL, LEVELS, isLevel } from './netease.js';
25
26
  import { BOOST_DIRECTIONS, TASTE_LEVELS } from './session.js';
26
27
 
27
28
  /** Resolved CDN URLs are reused for this long (they live 20 minutes). */
28
29
  const URL_CACHE_MS = 15 * 60 * 1000;
29
30
 
31
+ /** Song details are kept this long: a wiki or an introduction is edited rarely. */
32
+ const INFO_TTL_MS = 6 * 60 * 60 * 1000;
33
+
34
+ /** A written introduction is kept longer: each one costs a model call. */
35
+ const INTRO_TTL_MS = 7 * 24 * 60 * 60 * 1000;
36
+
30
37
  /**
31
38
  * Version of the page/engine boundary, advertised on `/health`.
32
39
  *
@@ -108,13 +115,14 @@ export class MusicRouter {
108
115
  * @param {() => object} [options.diagnostics] extra facts for `/health`.
109
116
  * @param {{warn: Function, info: Function, debug: Function}} [options.logger]
110
117
  */
111
- constructor({ base, api, player, store, qr, dj, likes, panelHtml, qrcodeJs, config = {}, listRoutes, diagnostics, logger }) {
118
+ constructor({ base, api, player, store, qr, dj, likes, scrobbler, panelHtml, qrcodeJs, config = {}, listRoutes, diagnostics, logger }) {
112
119
  this.base = base.replace(/\/+$/, '');
113
120
  this.api = api;
114
121
  this.player = player;
115
122
  this.store = store;
116
123
  this.qr = qr;
117
124
  this.dj = dj;
125
+ this.scrobbler = scrobbler;
118
126
  this.likes = likes;
119
127
  this.panelHtml = panelHtml;
120
128
  this.qrcodeJs = qrcodeJs;
@@ -128,6 +136,15 @@ export class MusicRouter {
128
136
  this.pendingUrls = new Map();
129
137
  /** What the last stream request actually resolved, for the UI and health. */
130
138
  this.lastAudio = null;
139
+ /** Song details for the panel, which barely change; each costs up to six requests. */
140
+ this.infoCache = new TtlCache({ maxEntries: 200 });
141
+ /** Model-written introductions, per track and language. */
142
+ this.introCache = new TtlCache({ maxEntries: 400 });
143
+ }
144
+
145
+ /** A song's details, shared by the details pane and the introduction written from them. */
146
+ songInfo(id) {
147
+ return this.infoCache.get(`info:${id}`, INFO_TTL_MS, () => this.api.songInfo(id));
131
148
  }
132
149
 
133
150
  /**
@@ -358,6 +375,8 @@ export class MusicRouter {
358
375
  authenticated: this.api.authenticated,
359
376
  settings: this.store.settings,
360
377
  modelSource: this.modelSource(),
378
+ /** Whether plays reach the NetEase listening history, for the player's switch. */
379
+ scrobble: this.scrobbler?.status() ?? null,
361
380
  /** Preferred quality, plus what the last stream request actually served. */
362
381
  audio: { preferred: this.preferredLevel(), last: this.lastAudio },
363
382
  ...extra,
@@ -524,14 +543,18 @@ export class MusicRouter {
524
543
  return sendJson(res, 200, await this.snapshot());
525
544
  }
526
545
  if (route === '/queue' && method === 'POST') {
527
- const { action, tracks, index } = await readJson(req);
546
+ const { action, tracks, index, keepCurrent } = await readJson(req);
528
547
  let removal = null;
529
548
  if (action === 'replace' && Array.isArray(tracks)) this.player.setQueue(tracks, { source: 'user' });
530
549
  else if (action === 'append' && Array.isArray(tracks)) this.player.append(tracks, { source: 'user' });
531
550
  else if (action === 'insert' && Array.isArray(tracks)) this.player.insertNext(tracks, { source: 'user' });
532
551
  else if (action === 'remove' || action === 'jump') removal = this.#queueAction(action, index);
533
- else if (action === 'clear') this.player.clear();
534
- else return sendJson(res, 400, { error: `unknown queue action "${action}"` });
552
+ else if (action === 'clear') {
553
+ // Unlike `remove`, clearing is housekeeping, not a judgement: nothing is rated.
554
+ if (keepCurrent) this.player.clearKeepingCurrent();
555
+ else this.player.clear();
556
+ this.player.requestExtension();
557
+ } else return sendJson(res, 400, { error: `unknown queue action "${action}"` });
535
558
  // Answer with the queue as it now stands, but record the judgement first:
536
559
  // the snapshot's hearts should already show it.
537
560
  if (removal?.dropped && removal.wasCurrent) await this.removeFromQueue(removal.track, true);
@@ -558,6 +581,32 @@ export class MusicRouter {
558
581
  const id = Number(route.slice('/lyric/'.length));
559
582
  return sendJson(res, 200, await this.api.lyric(id));
560
583
  }
584
+ if (route.startsWith('/info/') && method === 'GET') {
585
+ const id = Number(route.slice('/info/'.length));
586
+ if (!Number.isInteger(id) || id <= 0) return sendJson(res, 400, { error: 'invalid track id' });
587
+ return sendJson(res, 200, await this.songInfo(id));
588
+ }
589
+ /**
590
+ * A model-written introduction to the song. Always 200: with no model, or a
591
+ * failed one, `text` is empty and the panel shows NetEase's own prose. Only
592
+ * a written one is cached, so a model set up later is used at once.
593
+ */
594
+ if (route.startsWith('/intro/') && method === 'GET') {
595
+ const id = Number(route.slice('/intro/'.length));
596
+ if (!Number.isInteger(id) || id <= 0) return sendJson(res, 400, { error: 'invalid track id' });
597
+ const lang = query.get('lang') === 'zh' ? 'zh' : 'en';
598
+ try {
599
+ const intro = await this.introCache.get(`intro:${id}:${lang}`, INTRO_TTL_MS, async () => {
600
+ const written = await this.dj.introduce(await this.songInfo(id), { lang });
601
+ if (!written) throw new Error('no model route is available');
602
+ return written;
603
+ });
604
+ return sendJson(res, 200, intro);
605
+ } catch (error) {
606
+ this.logger?.debug?.(`[music] no introduction for ${id}: ${error.message}`);
607
+ return sendJson(res, 200, { text: '', reason: error.message });
608
+ }
609
+ }
561
610
  if (route === '/charts' && method === 'GET') {
562
611
  return sendJson(res, 200, await this.api.toplists());
563
612
  }
@@ -594,6 +643,19 @@ export class MusicRouter {
594
643
  * (or `minutes`), and `none` clears it. Unlike a taste level it expires on
595
644
  * its own.
596
645
  */
646
+ /**
647
+ * The player's listening-history switch. The choice is saved and beats
648
+ * `config.scrobble`, so a stale profile setting cannot override it.
649
+ */
650
+ if (route === '/scrobble' && method === 'POST') {
651
+ const { enabled } = await readJson(req);
652
+ if (typeof enabled !== 'boolean') return sendJson(res, 400, { error: 'enabled must be true or false' });
653
+ this.store.updateSettings({ scrobble: enabled });
654
+ if (this.scrobbler) this.scrobbler.enabled = enabled;
655
+ this.logger?.info?.(`[music] listening history ${enabled ? 'on' : 'off'} from the player`);
656
+ return sendJson(res, 200, await this.snapshot());
657
+ }
658
+
597
659
  if (route === '/boost' && method === 'POST') {
598
660
  const { trackId, direction, minutes } = await readJson(req);
599
661
  const applied = await this.applyBoost(trackId, direction, minutes);
@@ -691,7 +753,7 @@ export class MusicRouter {
691
753
  `[music] DJ model route set to ${this.dj.model.provider ?? '(none)'}/${this.dj.model.model ?? '(none)'} from the player`,
692
754
  );
693
755
  }
694
- if (prompt !== undefined) this.store.updateSettings({ djPrompt: String(prompt) });
756
+ if (prompt !== undefined) this.dj.setPrompt(prompt);
695
757
  if (enabled !== undefined) this.dj.setEnabled(enabled);
696
758
  if (replan || (enabled && this.player.queue.length === 0)) {
697
759
  // Planning is slow; answer immediately and let the panel poll the result.
package/lib/session.js CHANGED
@@ -40,6 +40,9 @@ const BOOST_MAX_MINUTES = 12 * 60;
40
40
  /** Boosts held at once; the oldest goes first. */
41
41
  const MAX_BOOSTS = 10;
42
42
 
43
+ /** Queue entries kept across a restart; the oldest played ones go first. */
44
+ const MAX_SAVED_QUEUE = 500;
45
+
43
46
  /** QR codes are refreshed before the API reports them expired. */
44
47
  const QR_TTL_MS = 110_000;
45
48
 
@@ -79,6 +82,12 @@ function emptyState() {
79
82
  * and every restart inside one conversation.
80
83
  */
81
84
  djSessionId: '',
85
+ /**
86
+ * Whether plays are reported to the NetEase listening history, as chosen
87
+ * in the player. `null` means no choice made here, so `config.scrobble`
88
+ * applies; a choice beats it, as the quality and DJ model choices do.
89
+ */
90
+ scrobble: null,
82
91
  },
83
92
  history: [],
84
93
  feedback: { likes: [], dislikes: [], skips: [] },
@@ -88,6 +97,11 @@ function emptyState() {
88
97
  * passing mood does not become a standing preference.
89
98
  */
90
99
  boosts: [],
100
+ /**
101
+ * The player's queue and cursor, so a restart picks up where it left off
102
+ * instead of waiting on the DJ's first plan.
103
+ */
104
+ queue: { tracks: [], index: -1 },
91
105
  };
92
106
  }
93
107
 
@@ -199,6 +213,19 @@ export class SessionStore {
199
213
  return this.state.settings;
200
214
  }
201
215
 
216
+ // ----------------------------------------------------------------- queue
217
+
218
+ get savedQueue() {
219
+ return this.state.queue ?? { tracks: [], index: -1 };
220
+ }
221
+
222
+ /** Keep the queue for the next run, dropping the oldest played tracks past the bound. */
223
+ saveQueue(tracks, index) {
224
+ const drop = Math.max(Math.min(tracks.length - MAX_SAVED_QUEUE, index), 0);
225
+ this.state.queue = { tracks: tracks.slice(drop, drop + MAX_SAVED_QUEUE), index: index - drop };
226
+ this.touch();
227
+ }
228
+
202
229
  // --------------------------------------------------------------- history
203
230
 
204
231
  /**
package/lib/state.js CHANGED
@@ -249,6 +249,31 @@ export class Player {
249
249
  return this.snapshot();
250
250
  }
251
251
 
252
+ /**
253
+ * Empty the queue but for the track at the cursor, which plays on
254
+ * undisturbed: its play stays open, so it is neither ended nor restarted.
255
+ */
256
+ clearKeepingCurrent() {
257
+ const current = this.current();
258
+ if (!current) return this.clear();
259
+ this.queue = [current];
260
+ this.index = 0;
261
+ this.bump({ transport: true });
262
+ return this.snapshot();
263
+ }
264
+
265
+ /**
266
+ * Put back a queue saved by an earlier run, paused at its cursor. Nothing is
267
+ * finished or bumped: no play was open, and nobody is subscribed yet.
268
+ */
269
+ restore({ tracks, index } = {}) {
270
+ const queue = Array.isArray(tracks) ? tracks.filter((track) => track?.id) : [];
271
+ if (queue.length === 0) return;
272
+ this.queue = queue;
273
+ this.index = Math.min(Math.max(Number(index) || 0, 0), queue.length - 1);
274
+ this.playing = false;
275
+ }
276
+
252
277
  // --------------------------------------------------------------- transport
253
278
 
254
279
  /** Index to advance to, honouring the repeat/shuffle mode. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@doitian/dsh-music",
3
- "version": "0.1.8",
3
+ "version": "0.1.10",
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",