@doitian/dsh-music 0.1.7 → 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/README.md CHANGED
@@ -24,6 +24,8 @@ Optional. Signed out, search, charts, playlists, lyrics and non-VIP playback all
24
24
 
25
25
  Click **登录 Sign in** in the player and scan the QR code with the NetEase Cloud Music app, or ask the agent to use `music_login`. The cookie is stored in `$DSH_HOME/music/session.json`.
26
26
 
27
+ **Listening history.** Signed in, songs you play here show up in your NetEase history — 最近播放 and 听歌排行 — on every device, as plays from the web. A song counts once you've listened past the skip window (30 seconds, or a quarter of a long song); one you skip sooner isn't recorded. To keep your plays local, set `scrobble: false` (see [Configuration](#configuration)).
28
+
27
29
  ## Agent tools
28
30
 
29
31
  | Tool | Purpose |
@@ -95,6 +97,7 @@ All fields are optional, under the plugin entry's `config` in your profile's `co
95
97
  | `audioLevel` | `exhigh` | Starting quality, until you pick one in the player |
96
98
  | `dataDir` | `$DSH_HOME/music` | Where `session.json` lives |
97
99
  | `requestTimeoutMs` | `15000` | NetEase request deadline |
100
+ | `scrobble` | `true` | Report your plays to your NetEase listening history |
98
101
  | `dj.provider` / `dj.model` | session model | The DJ's model, as above |
99
102
 
100
103
  Batch size (`djBatchSize`, 5) and refill threshold (`djAutoExtendBelow`, 3) have no control in the player. Edit them in `session.json` while the harness is stopped.
@@ -116,6 +119,6 @@ Batch size (`djBatchSize`, 5) and refill threshold (`djAutoExtendBelow`, 3) have
116
119
  ## Known limitations
117
120
 
118
121
  - VIP tracks don't play while signed out, and some tracks are sold per album, so they don't play even with VIP (for example 晴天, `id 186016`).
119
- - Without NetEase's encrypted API there is no scrobbling, no playlist editing and no heartbeat mode (心动模式), and a dislike stays local.
122
+ - There is no playlist editing and no heartbeat mode (心动模式), and a dislike stays local: NetEase has no plain endpoint for any of them.
120
123
  - The DJ's model mode hasn't yet been tested end to end with a real model. If it misbehaves, `dj.modelError` says why, and the DJ keeps working without it.
121
124
  - Only your newest 500 likes are offered back as candidates.
package/lib/index.js CHANGED
@@ -24,6 +24,7 @@ import { Player } from './state.js';
24
24
  import { AiDj } from './dj.js';
25
25
  import { LikeState } from './likes.js';
26
26
  import { MusicRouter } from './router.js';
27
+ import { Scrobbler } from './scrobble.js';
27
28
 
28
29
  export const name = 'music';
29
30
 
@@ -237,6 +238,12 @@ export function apply(ctx, config = {}) {
237
238
  });
238
239
  player.onHeard = (track) => store.confirmPlay(track.id);
239
240
 
241
+ // Plays reach the account's listening history the way the web player's do.
242
+ // On by default; `config.scrobble: false` keeps them local.
243
+ const scrobbler = new Scrobbler({ api, enabled: config.scrobble !== false, logger });
244
+ player.onStart = (track) => scrobbler.start(track);
245
+ player.onFinish = (track, play) => void scrobbler.finish(track, play);
246
+
240
247
  // A periodic sweep catches the cases the track-end hook misses: a paused
241
248
  // panel, a failed track, or a DJ that was switched on with a short queue.
242
249
  const sweep = setInterval(() => {
@@ -286,6 +293,8 @@ export function apply(ctx, config = {}) {
286
293
  },
287
294
  /** How much of the account's like state is cached, and why it is not. */
288
295
  likes: likes.status(),
296
+ /** Whether plays are reported to the listening history, and how the last went. */
297
+ scrobble: scrobbler.status(),
289
298
  dataDir,
290
299
  session: { authenticated: api.authenticated, nickname: api.account?.nickname ?? null, vip: Boolean(api.account?.vip) },
291
300
  uptimeMs: Math.round(process.uptime() * 1000),
package/lib/netease.js CHANGED
@@ -2,8 +2,10 @@
2
2
  * Minimal, dependency-free client for the NetEase Cloud Music (music.163.com)
3
3
  * web API.
4
4
  *
5
- * Only the plain (non-`weapi`/`eapi`) endpoints are used: they need no request
6
- * encryption and work with a normal browser session cookie. Authentication
5
+ * The plain (non-`weapi`/`eapi`) endpoints are used wherever they work: they
6
+ * need no request encryption and work with a normal browser session cookie.
7
+ * The one exception is scrobbling ({@link Netease#weblog}), which only counts
8
+ * when sent the way the web player sends it. Authentication
7
9
  * upgrades the client from anonymous browsing to personal recommendations and
8
10
  * VIP song URLs; everything else works without it.
9
11
  *
@@ -17,13 +19,31 @@
17
19
  * - `api/song/like` POST: like / un-like, needs a session
18
20
  * - `api/song/like/check` which of these ids the account liked
19
21
  * - `api/login/qrcode/*` QR login handshake
22
+ * - `weapi/feedback/weblog` on clientlogusf.music.163.com: play logs,
23
+ * which is what the listening history is built from
20
24
  *
21
25
  * @module dsh-music/netease
22
26
  */
23
27
 
28
+ import { weapiEncrypt } from './weapi.js';
29
+
24
30
  /** Hosts used by the public web client. */
25
31
  const API_ORIGIN = 'https://music.163.com';
26
32
 
33
+ /**
34
+ * Where the web player sends its play logs. The same path on music.163.com
35
+ * answers `success` and records nothing, which is why plays from this plugin
36
+ * never reached the listening history until this host was found.
37
+ */
38
+ const LOG_ORIGIN = 'https://clientlogusf.music.163.com';
39
+
40
+ /**
41
+ * The cookies that mark a request as the desktop client. A play log carrying
42
+ * them is dropped, so the log request sends the session without them — as the
43
+ * web player, which it is.
44
+ */
45
+ const CLIENT_COOKIES = /^(os|appver|channel)=/;
46
+
27
47
  /** A desktop-browser UA; NetEase serves different shapes to unknown agents. */
28
48
  const UA =
29
49
  'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36';
@@ -579,6 +599,40 @@ export class Netease {
579
599
  return normalizeTracks(data?.data);
580
600
  }
581
601
 
602
+ // --------------------------------------------------------------- play logs
603
+
604
+ /**
605
+ * Send play logs the way the web player does: weapi-encrypted, to the log
606
+ * host, with the session but not the desktop-client cookies. Verified live —
607
+ * a `startplay` then a `play` of 阴天 reached 最近播放 within 20 seconds,
608
+ * while the same logs with `os=pc` set, or sent to music.163.com, were
609
+ * accepted and never recorded.
610
+ *
611
+ * @param {object[]} logs `{action, json}` entries, as the web player builds them.
612
+ * @throws {NeteaseError} when NetEase refuses the logs.
613
+ */
614
+ async weblog(logs) {
615
+ const csrf = this.jar.get('__csrf') ?? '';
616
+ const cookie = this.jar
617
+ .header()
618
+ .split(/;\s*/)
619
+ .filter((pair) => pair && !CLIENT_COOKIES.test(pair))
620
+ .join('; ');
621
+ const data = await this.call(`${LOG_ORIGIN}/weapi/feedback/weblog`, {
622
+ method: 'POST',
623
+ query: { csrf_token: csrf },
624
+ body: weapiEncrypt({ logs: JSON.stringify(logs), csrf_token: csrf }),
625
+ headers: { Cookie: cookie },
626
+ });
627
+ if (String(data?.code) !== '200') {
628
+ throw new NeteaseError(data?.message || `weblog refused (code ${data?.code})`, {
629
+ code: data?.code,
630
+ endpoint: 'feedback/weblog',
631
+ });
632
+ }
633
+ return data;
634
+ }
635
+
582
636
  // ------------------------------------------------------------------ likes
583
637
 
584
638
  /**
@@ -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/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);
@@ -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.7",
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"