@doitian/dsh-music 0.1.6 → 0.1.8

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
@@ -22,7 +22,7 @@
22
22
  import { Readable } from 'node:stream';
23
23
 
24
24
  import { DEFAULT_LEVEL, LEVELS, isLevel } from './netease.js';
25
- import { TASTE_LEVELS } from './session.js';
25
+ import { BOOST_DIRECTIONS, TASTE_LEVELS } from './session.js';
26
26
 
27
27
  /** Resolved CDN URLs are reused for this long (they live 20 minutes). */
28
28
  const URL_CACHE_MS = 15 * 60 * 1000;
@@ -309,9 +309,35 @@ export class MusicRouter {
309
309
  ...track,
310
310
  liked: this.likes.isLiked(track.id),
311
311
  disliked: this.store.taste(track.id) === 'disliked',
312
+ /** A temporary "more/less like this", or null. */
313
+ boost: this.store.boostOf(track.id),
312
314
  };
313
315
  }
314
316
 
317
+ /**
318
+ * Boost a track for a while, or clear its boost, and let the DJ act on it now.
319
+ *
320
+ * The track is looked up in the queue first, so the boost can name it without
321
+ * a request; one that is not queued is resolved through NetEase.
322
+ *
323
+ * @returns {Promise<{ok: boolean, status?: number, reason?: string, boost?: object|null, effect?: object}>}
324
+ */
325
+ async applyBoost(trackId, direction, minutes) {
326
+ const id = Number(trackId);
327
+ if (!Number.isFinite(id)) return { ok: false, status: 400, reason: `invalid track id "${trackId}"` };
328
+ if (direction !== 'none' && !BOOST_DIRECTIONS.includes(direction)) {
329
+ return { ok: false, status: 400, reason: `unknown boost "${direction}" (expected more, less or none)` };
330
+ }
331
+ const track =
332
+ this.player.queue.find((entry) => entry.id === id) ??
333
+ (await this.api.songDetail([id]).then((found) => found[0]).catch(() => null));
334
+ if (!track) return { ok: false, status: 404, reason: `track ${id} not found` };
335
+ const boost = this.store.setBoost(track, direction, minutes);
336
+ const effect = await this.dj.applyBoost(track, direction).catch(() => ({ queued: 0, removed: 0 }));
337
+ this.player.bump();
338
+ return { ok: true, boost, effect };
339
+ }
340
+
315
341
  /**
316
342
  * The panel's poll target: full player snapshot including account and DJ.
317
343
  *
@@ -326,6 +352,8 @@ export class MusicRouter {
326
352
  ...base,
327
353
  queue: base.queue.map((track) => this.tasteView(track)),
328
354
  current: this.tasteView(base.current),
355
+ /** Boosts still in force, newest first, with when each ends. */
356
+ boosts: this.store.activeBoosts(),
329
357
  account: this.api.account,
330
358
  authenticated: this.api.authenticated,
331
359
  settings: this.store.settings,
@@ -561,6 +589,18 @@ export class MusicRouter {
561
589
  * so a click cannot be turned into the wrong direction by a stale poll, and
562
590
  * disliking a liked track is one request rather than two racing ones.
563
591
  */
592
+ /**
593
+ * A temporary push on the DJ: `direction` is `more` or `less` for an hour
594
+ * (or `minutes`), and `none` clears it. Unlike a taste level it expires on
595
+ * its own.
596
+ */
597
+ if (route === '/boost' && method === 'POST') {
598
+ const { trackId, direction, minutes } = await readJson(req);
599
+ const applied = await this.applyBoost(trackId, direction, minutes);
600
+ if (!applied.ok) return sendJson(res, applied.status ?? 502, { error: applied.reason });
601
+ return sendJson(res, 200, await this.snapshot({ boostEffect: applied.effect }));
602
+ }
603
+
564
604
  if (route === '/taste' && method === 'POST') {
565
605
  const { trackId, level } = await readJson(req);
566
606
  const applied = await this.applyTaste(trackId, level);
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Reports plays to NetEase, so they appear in the account's listening history
3
+ * (最近播放, 听歌排行) like plays in the official clients.
4
+ *
5
+ * It sends what the web player sends: `startplay` when a track starts, and
6
+ * `play` when that play ends, with the seconds heard and how it ended (`ui`
7
+ * when it played out, `interrupt` when the listener moved on). A play left
8
+ * inside the skip window is not reported at all — a track skipped after ten
9
+ * seconds was not listened to, and the history should not say it was.
10
+ *
11
+ * Reporting is best-effort: a failure is logged and recorded for
12
+ * `/music/health`, and never reaches playback.
13
+ *
14
+ * @module dsh-music/scrobble
15
+ */
16
+
17
+ export class Scrobbler {
18
+ /**
19
+ * @param {object} options
20
+ * @param {import('./netease.js').Netease} options.api
21
+ * @param {boolean} [options.enabled] `config.scrobble`; on unless set to false.
22
+ * @param {{warn: Function, info: Function, debug: Function}} [options.logger]
23
+ */
24
+ constructor({ api, enabled = true, logger } = {}) {
25
+ this.api = api;
26
+ this.enabled = enabled;
27
+ this.logger = logger;
28
+ /** The last `play` report: which track, when, and whether NetEase took it. */
29
+ this.last = null;
30
+ }
31
+
32
+ /** A track started playing. */
33
+ start(track) {
34
+ if (!this.#active() || !track?.id) return;
35
+ void this.#send([
36
+ { action: 'startplay', json: { id: track.id, type: 'song', content: `id=${track.id}`, mainsite: '1', mainsiteWeb: '1' } },
37
+ ]).catch(() => {});
38
+ }
39
+
40
+ /**
41
+ * A play ended. Only a play heard past the skip window is reported.
42
+ * @param {{id: number, name?: string}} track
43
+ * @param {{seconds: number, ended: boolean, heard: boolean}} play
44
+ * @returns {Promise<void>}
45
+ */
46
+ async finish(track, { seconds, ended, heard }) {
47
+ if (!this.#active() || !track?.id || !heard) return;
48
+ const time = Math.max(Math.round(seconds), 1);
49
+ try {
50
+ await this.#send([
51
+ {
52
+ action: 'play',
53
+ json: {
54
+ type: 'song',
55
+ wifi: 0,
56
+ download: 0,
57
+ id: track.id,
58
+ time,
59
+ end: ended ? 'ui' : 'interrupt',
60
+ mainsite: '1',
61
+ mainsiteWeb: '1',
62
+ content: `id=${track.id}`,
63
+ },
64
+ },
65
+ ]);
66
+ this.last = { id: track.id, name: track.name ?? '', seconds: time, ended, at: Date.now(), error: null };
67
+ } catch (error) {
68
+ this.last = { id: track.id, name: track.name ?? '', seconds: time, ended, at: Date.now(), error: error.message };
69
+ this.logger?.warn?.(`[music] could not report the play of ${track.id}: ${error.message}`);
70
+ }
71
+ }
72
+
73
+ /** What `/music/health` shows. */
74
+ status() {
75
+ return { enabled: this.enabled, active: this.#active(), last: this.last };
76
+ }
77
+
78
+ #active() {
79
+ return this.enabled && Boolean(this.api?.authenticated);
80
+ }
81
+
82
+ #send(logs) {
83
+ return this.api.weblog(logs);
84
+ }
85
+ }
package/lib/session.js CHANGED
@@ -29,6 +29,17 @@ const MAX_FEEDBACK = 500;
29
29
  */
30
30
  export const TASTE_LEVELS = ['liked', 'none', 'disliked'];
31
31
 
32
+ /** The directions a temporary boost can push the DJ in. */
33
+ export const BOOST_DIRECTIONS = ['more', 'less'];
34
+
35
+ /** How long a boost lasts unless asked otherwise, and the bounds on asking. */
36
+ export const BOOST_DEFAULT_MINUTES = 60;
37
+ const BOOST_MIN_MINUTES = 5;
38
+ const BOOST_MAX_MINUTES = 12 * 60;
39
+
40
+ /** Boosts held at once; the oldest goes first. */
41
+ const MAX_BOOSTS = 10;
42
+
32
43
  /** QR codes are refreshed before the API reports them expired. */
33
44
  const QR_TTL_MS = 110_000;
34
45
 
@@ -71,6 +82,12 @@ function emptyState() {
71
82
  },
72
83
  history: [],
73
84
  feedback: { likes: [], dislikes: [], skips: [] },
85
+ /**
86
+ * Temporary pushes on the DJ: "more like this" or "less like this" for one
87
+ * track, until `until`. Unlike a taste level they expire on their own, so a
88
+ * passing mood does not become a standing preference.
89
+ */
90
+ boosts: [],
74
91
  };
75
92
  }
76
93
 
@@ -335,6 +352,46 @@ export class SessionStore {
335
352
  return this.state.feedback;
336
353
  }
337
354
 
355
+ // ---------------------------------------------------------------- boosts
356
+
357
+ /**
358
+ * Boost one track for a while, replacing any boost it already has, or clear
359
+ * it with direction `none`.
360
+ *
361
+ * @param {{id: number, name?: string, artists?: string[]}} track
362
+ * @param {'more'|'less'|'none'} direction
363
+ * @param {number} [minutes] how long it lasts; clamped to 5 minutes – 12 hours.
364
+ * @returns {object|null} the boost now held, or null when it was cleared.
365
+ */
366
+ setBoost(track, direction, minutes = BOOST_DEFAULT_MINUTES) {
367
+ const id = Number(track?.id);
368
+ if (!Number.isFinite(id)) return null;
369
+ const now = Date.now();
370
+ this.state.boosts = (this.state.boosts ?? []).filter((boost) => boost.id !== id && boost.until > now);
371
+ if (!BOOST_DIRECTIONS.includes(direction)) {
372
+ this.save();
373
+ return null;
374
+ }
375
+ const span = Math.min(Math.max(Number(minutes) || BOOST_DEFAULT_MINUTES, BOOST_MIN_MINUTES), BOOST_MAX_MINUTES);
376
+ const boost = { id, name: track.name ?? '', artists: track.artists ?? [], direction, until: now + span * 60_000 };
377
+ this.state.boosts.unshift(boost);
378
+ if (this.state.boosts.length > MAX_BOOSTS) this.state.boosts.length = MAX_BOOSTS;
379
+ // Written through: a boost is a deliberate act, and it is short-lived
380
+ // enough that losing it to a crash would be most of its life.
381
+ this.save();
382
+ return boost;
383
+ }
384
+
385
+ /** The boosts still in force, newest first. Expired ones are simply not returned. */
386
+ activeBoosts(now = Date.now()) {
387
+ return (this.state.boosts ?? []).filter((boost) => boost.until > now);
388
+ }
389
+
390
+ /** One track's boost direction, or null. */
391
+ boostOf(trackId, now = Date.now()) {
392
+ return this.activeBoosts(now).find((boost) => boost.id === Number(trackId))?.direction ?? null;
393
+ }
394
+
338
395
  /**
339
396
  * A compact digest for the DJ prompt: what has been played, what is liked,
340
397
  * what is disliked — never the raw cookie or account details.
package/lib/state.js CHANGED
@@ -98,6 +98,20 @@ export class Player {
98
98
  this.onHeard = undefined;
99
99
  /** The track `onHeard` was last called for, so it fires once per play. */
100
100
  this.heardId = null;
101
+ /**
102
+ * Called once when a track starts playing — its first reported position —
103
+ * and once when that play ends, however it ends: the track finishing or
104
+ * failing, a skip, a jump, the queue replaced or cleared. `seconds` is how
105
+ * much was heard, `ended` whether it played to its end, and `heard`
106
+ * whether it got past the skip window. The listening history is built
107
+ * from these.
108
+ * @type {((track: object) => void) | undefined}
109
+ */
110
+ this.onStart = undefined;
111
+ /** @type {((track: object, play: {seconds: number, ended: boolean, heard: boolean}) => void) | undefined} */
112
+ this.onFinish = undefined;
113
+ /** The track whose play `onStart` opened and `onFinish` has not closed yet. */
114
+ this.startedId = null;
101
115
  }
102
116
 
103
117
  /** Subscribe to state changes. @returns {() => void} unsubscribe */
@@ -138,6 +152,7 @@ export class Player {
138
152
  .map((track) => normalizeTrack(track) ?? track)
139
153
  .filter((track) => track?.id)
140
154
  .map((track) => tag(track, queuedBy));
155
+ this.#finish();
141
156
  this.heardId = null;
142
157
  this.queue = normalized;
143
158
  this.index = normalized.length === 0 ? -1 : Math.min(Math.max(startIndex, 0), normalized.length - 1);
@@ -169,11 +184,11 @@ export class Player {
169
184
  }
170
185
 
171
186
  /** Insert tracks directly after the cursor. */
172
- insertNext(tracks, { source } = {}) {
187
+ insertNext(tracks, { source, queuedBy } = {}) {
173
188
  const existing = new Set(this.queue.map((track) => track.id));
174
189
  const added = [];
175
190
  for (const raw of tracks) {
176
- const track = normalizeTrack(raw) ?? raw;
191
+ const track = tag(normalizeTrack(raw) ?? raw, queuedBy);
177
192
  if (!track?.id || existing.has(track.id)) continue;
178
193
  existing.add(track.id);
179
194
  added.push(track);
@@ -204,6 +219,7 @@ export class Player {
204
219
  remove(index) {
205
220
  if (index < 0 || index >= this.queue.length) return this.snapshot();
206
221
  const wasCurrent = index === this.index;
222
+ if (wasCurrent) this.#finish();
207
223
  this.queue.splice(index, 1);
208
224
  if (this.queue.length === 0) {
209
225
  this.index = -1;
@@ -222,6 +238,7 @@ export class Player {
222
238
 
223
239
  /** Empty the queue and stop. */
224
240
  clear() {
241
+ this.#finish();
225
242
  this.queue = [];
226
243
  this.index = -1;
227
244
  this.playing = false;
@@ -258,6 +275,7 @@ export class Player {
258
275
  if (this.queue.length === 0) return this.snapshot();
259
276
  const left = this.current();
260
277
  const skipped = !auto && step > 0 && this.#heardBriefly();
278
+ this.#finish();
261
279
  this.index = this.#nextIndex(step);
262
280
  if (this.current() !== left) this.heardId = null;
263
281
  this.pendingSeek = 0;
@@ -308,6 +326,40 @@ export class Player {
308
326
  }
309
327
  }
310
328
 
329
+ /** Open the play of the current track once it is really playing. */
330
+ #noteStart({ ended = false } = {}) {
331
+ const current = this.current();
332
+ if (!current || this.startedId === current.id || this.reported.trackId !== current.id) return;
333
+ if (!ended && !((Number(this.reported.position) || 0) > 0)) return;
334
+ this.startedId = current.id;
335
+ try {
336
+ this.onStart?.(current);
337
+ } catch (error) {
338
+ this.logger?.warn?.(`[music] start listener failed: ${error.message}`);
339
+ }
340
+ }
341
+
342
+ /**
343
+ * Close the current play, if one is open. Called before anything moves the
344
+ * cursor or restarts the track, while the report still describes the play
345
+ * that is ending. A replay of the same track — single repeat, a jump to
346
+ * itself — then opens a play of its own, and has to be heard again.
347
+ */
348
+ #finish({ ended = false } = {}) {
349
+ const track = this.current();
350
+ if (!track || this.startedId !== track.id) return;
351
+ const heard = this.heardId === track.id;
352
+ const durationMs = Number(this.reported.duration) || Number(track.duration) || 0;
353
+ const seconds = (ended ? durationMs : Number(this.reported.position) || 0) / 1000;
354
+ this.startedId = null;
355
+ this.heardId = null;
356
+ try {
357
+ this.onFinish?.(track, { seconds, ended, heard });
358
+ } catch (error) {
359
+ this.logger?.warn?.(`[music] finish listener failed: ${error.message}`);
360
+ }
361
+ }
362
+
311
363
  #notifySkip(track) {
312
364
  try {
313
365
  this.onSkip?.(track);
@@ -319,6 +371,7 @@ export class Player {
319
371
  /** Jump to an explicit queue position. */
320
372
  jump(index) {
321
373
  if (index < 0 || index >= this.queue.length) return this.snapshot();
374
+ this.#finish();
322
375
  if (index !== this.index) this.heardId = null;
323
376
  this.index = index;
324
377
  this.pendingSeek = 0;
@@ -403,7 +456,9 @@ export class Player {
403
456
  this.lastError = this.reported.error;
404
457
  }
405
458
 
459
+ this.#noteStart({ ended: Boolean(ended) });
406
460
  this.#noteHeard({ ended: Boolean(ended) });
461
+ if (ended) this.#finish({ ended: true });
407
462
 
408
463
  let advanced = false;
409
464
  if (ended || error) {
package/lib/weapi.js ADDED
@@ -0,0 +1,58 @@
1
+ /**
2
+ * NetEase's `weapi` request encryption, for the few endpoints the plain web
3
+ * API accepts but ignores.
4
+ *
5
+ * The plugin talks to the plain (`/api/…`) endpoints wherever they work,
6
+ * because they need no client secrets. Scrobbling is the exception that
7
+ * forced this module: a play reaches the listening history only when it is
8
+ * sent the way the web player sends it — encrypted, to the log host, without
9
+ * the desktop-client cookies — and the plain endpoint answers `success` to
10
+ * anything, even an empty request, while recording nothing. See
11
+ * `Netease#weblog`.
12
+ *
13
+ * The scheme is the web player's own: the JSON body is AES-128-CBC encrypted
14
+ * with a fixed key, then again with a random 16-character key, and that key —
15
+ * reversed — is RSA-encrypted without padding under NetEase's published
16
+ * public key. The constants are the web player's, as documented by the
17
+ * MIT-licensed NeteaseCloudMusicApi project.
18
+ *
19
+ * @module dsh-music/weapi
20
+ */
21
+
22
+ import crypto from 'node:crypto';
23
+
24
+ const PRESET_KEY = '0CoJUm6Qyw8W8jud';
25
+ const IV = '0102030405060708';
26
+ const BASE62 = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
27
+ const PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
28
+ MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDgtQn2JZ34ZC28NWYpAUd98iZ37BUrX/aKzmFbt7clFSs6sXqHauqKWqdtLkF2KexO40H1YTX8z2lSgBBOAxLsvaklV8k4cBFK9snQXE9/DDaFt6Rr7iVZMldczhC0JNgTz+SHXT6CBHuX3e9SdB1Ua44oncaTWz7OBGLbCiK45wIDAQAB
29
+ -----END PUBLIC KEY-----`;
30
+
31
+ function aes(text, key) {
32
+ const cipher = crypto.createCipheriv('aes-128-cbc', Buffer.from(key), Buffer.from(IV));
33
+ return Buffer.concat([cipher.update(text, 'utf8'), cipher.final()]).toString('base64');
34
+ }
35
+
36
+ function rsa(text) {
37
+ const message = Buffer.from(text);
38
+ const padded = Buffer.concat([Buffer.alloc(128 - message.length), message]);
39
+ return crypto.publicEncrypt({ key: PUBLIC_KEY, padding: crypto.constants.RSA_NO_PADDING }, padded).toString('hex');
40
+ }
41
+
42
+ /**
43
+ * Encrypt one request body the way the web player does.
44
+ *
45
+ * @param {object} data the body, `csrf_token` included.
46
+ * @param {string} [secretKey] the per-request key; random unless a test pins it.
47
+ * @returns {{params: string, encSecKey: string}} the form fields to POST.
48
+ */
49
+ export function weapiEncrypt(data, secretKey = randomKey()) {
50
+ return {
51
+ params: aes(aes(JSON.stringify(data), PRESET_KEY), secretKey),
52
+ encSecKey: rsa([...secretKey].reverse().join('')),
53
+ };
54
+ }
55
+
56
+ function randomKey() {
57
+ return Array.from(crypto.randomBytes(16), (byte) => BASE62[byte % BASE62.length]).join('');
58
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@doitian/dsh-music",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
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",
@@ -40,6 +40,8 @@
40
40
  "lib/state.js",
41
41
  "lib/dj.js",
42
42
  "lib/cache.js",
43
+ "lib/weapi.js",
44
+ "lib/scrobble.js",
43
45
  "lib/likes.js",
44
46
  "lib/router.js",
45
47
  "lib/panel.html",
@@ -55,8 +57,8 @@
55
57
  "access": "public"
56
58
  },
57
59
  "scripts": {
58
- "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/likes.js && node --check lib/router.js",
59
- "test": "node test/netease.test.mjs && node test/cache.test.mjs && node test/likes.test.mjs && node test/dj.test.mjs && node test/client.test.mjs",
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",
60
62
  "probe:headers": "node scripts/probe-headers.mjs",
61
63
  "test:live": "node test/host.test.mjs",
62
64
  "test:all": "npm test && npm run test:live"