@doitian/dsh-music 0.1.7 → 0.1.9

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, turn off the **Listening history** switch at the top of the player (it's there while you're signed in), or set `scrobble: false` in the config; the switch wins over the config.
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, until you use the player's switch |
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,16 @@ 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; the player's switch, then `config.scrobble: false`, keep them local.
243
+ const scrobbler = new Scrobbler({
244
+ api,
245
+ enabled: typeof store.settings.scrobble === 'boolean' ? store.settings.scrobble : config.scrobble !== false,
246
+ logger,
247
+ });
248
+ player.onStart = (track) => scrobbler.start(track);
249
+ player.onFinish = (track, play) => void scrobbler.finish(track, play);
250
+
240
251
  // A periodic sweep catches the cases the track-end hook misses: a paused
241
252
  // panel, a failed track, or a DJ that was switched on with a short queue.
242
253
  const sweep = setInterval(() => {
@@ -255,6 +266,7 @@ export function apply(ctx, config = {}) {
255
266
  qr,
256
267
  dj,
257
268
  likes,
269
+ scrobbler,
258
270
  panelHtml: PANEL_HTML,
259
271
  qrcodeJs: QRCODE_JS,
260
272
  config,
@@ -286,6 +298,8 @@ export function apply(ctx, config = {}) {
286
298
  },
287
299
  /** How much of the account's like state is cached, and why it is not. */
288
300
  likes: likes.status(),
301
+ /** Whether plays are reported to the listening history, and how the last went. */
302
+ scrobble: scrobbler.status(),
289
303
  dataDir,
290
304
  session: { authenticated: api.authenticated, nickname: api.account?.nickname ?? null, vip: Boolean(api.account?.vip) },
291
305
  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
  /**
package/lib/panel.html CHANGED
@@ -48,7 +48,11 @@
48
48
  background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 6px 10px;
49
49
  }
50
50
  input:focus, select:focus, button:focus-visible { outline: 2px solid color-mix(in srgb, var(--accent) 45%, transparent); outline-offset: 1px; }
51
- svg { display: block; width: 18px; height: 18px; fill: currentColor; }
51
+ /* One icon set, one stroke: every icon on the page is drawn the same way,
52
+ and a state fills the outline rather than swapping in another glyph. */
53
+ svg.i { display: block; width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; flex: none; }
54
+ svg.i.filled { fill: currentColor; }
55
+ svg.i.small { width: 14px; height: 14px; }
52
56
 
53
57
  /* ------------------------------------------------------------ layout
54
58
  Wide: the stage (what is playing) on the left, what comes next — the
@@ -104,7 +108,8 @@
104
108
  display: grid; place-items: center; color: var(--faint); font-size: 40px;
105
109
  box-shadow: 0 6px 24px color-mix(in srgb, #000 14%, transparent);
106
110
  }
107
- .cover::before { content: "♪"; }
111
+ #cover-icon { display: grid; place-items: center; width: 38%; height: 38%; }
112
+ #cover-icon svg.i { width: 100%; height: 100%; stroke-width: 1.5; }
108
113
  #cover { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
109
114
  .np-text { min-width: 0; flex: 1; display: flex; flex-direction: column; gap: 2px; }
110
115
  .now-title { font-size: 22px; font-weight: 700; line-height: 1.25; overflow-wrap: anywhere; }
@@ -116,7 +121,7 @@
116
121
  .taste { display: flex; gap: 6px; margin-top: 10px; flex-wrap: wrap; }
117
122
  .taste button {
118
123
  width: 34px; height: 34px; padding: 0; border-radius: 50%; display: grid; place-items: center;
119
- background: none; font-size: 15px; line-height: 1; color: var(--muted);
124
+ background: none; color: var(--muted);
120
125
  }
121
126
  .taste button:hover:not(:disabled) { color: var(--fg); background: var(--hover); }
122
127
  .taste button.on { color: var(--accent); background: var(--accent-soft); border-color: transparent; }
@@ -132,7 +137,8 @@
132
137
  .transport button:hover:not(:disabled) { background: var(--hover); }
133
138
  .transport #play { width: 52px; height: 52px; background: var(--accent); color: #fff; box-shadow: 0 4px 14px color-mix(in srgb, var(--accent) 35%, transparent); }
134
139
  .transport #play:hover:not(:disabled) { background: color-mix(in srgb, var(--accent) 88%, #000); }
135
- .transport #play svg { width: 22px; height: 22px; }
140
+ .transport svg.i { width: 20px; height: 20px; }
141
+ .transport #play svg.i { width: 22px; height: 22px; }
136
142
 
137
143
  .secondary { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; font-size: 12px; }
138
144
  .secondary select, .secondary > button { padding: 4px 8px; font-size: 12px; }
@@ -165,18 +171,21 @@
165
171
  .dj-card .card-head .title { color: var(--fg); font-size: 13px; font-weight: 650; text-transform: none; letter-spacing: 0; }
166
172
  .dj-body { display: flex; flex-direction: column; gap: 8px; padding: 0 12px; font-size: 12px; }
167
173
  #dj-prompt { width: 100%; }
168
- /* The DJ switch: a toggle that reads on or off at a glance. */
169
- #dj-toggle {
174
+ /* A switch reads on or off at a glance: the DJ, the listening history. */
175
+ .switch {
170
176
  position: relative; width: 38px; height: 22px; padding: 0; border-radius: 11px;
171
177
  background: color-mix(in srgb, var(--fg) 20%, transparent); border: 0; color: transparent; overflow: hidden;
172
178
  }
173
- #dj-toggle::after {
179
+ .switch::after {
174
180
  content: ""; position: absolute; top: 3px; left: 3px; width: 16px; height: 16px; border-radius: 50%;
175
181
  background: #fff; transition: transform 0.15s; box-shadow: 0 1px 3px color-mix(in srgb, #000 30%, transparent);
176
182
  }
177
- #dj-toggle.on { background: var(--accent); }
178
- #dj-toggle.on::after { transform: translateX(16px); }
179
- #dj-toggle:hover:not(:disabled) { filter: brightness(0.96); }
183
+ .switch.on { background: var(--accent); }
184
+ .switch.on::after { transform: translateX(16px); }
185
+ .switch:hover:not(:disabled) { filter: brightness(0.96); }
186
+ /* The listening-history switch only means something signed in. */
187
+ .history { display: flex; align-items: center; gap: 7px; color: var(--muted); font-size: 12px; }
188
+ .history[hidden] { display: none; }
180
189
  .plan b { color: var(--accent); }
181
190
  .plan .muted, .muted { color: var(--muted); }
182
191
  .plan > div + div { margin-top: 2px; }
@@ -187,7 +196,7 @@
187
196
  display: inline-flex; gap: 2px; align-items: center; color: var(--fg);
188
197
  background: var(--accent-soft); border-radius: 999px; padding: 1px 2px 1px 9px;
189
198
  }
190
- #boosts .boost button { border: 0; background: none; padding: 0 6px; color: var(--muted); }
199
+ #boosts .boost button { border: 0; background: none; padding: 2px 5px; color: var(--muted); }
191
200
  #boosts .boost button:hover:not(:disabled) { color: var(--fg); }
192
201
 
193
202
  /* The DJ model picker is a set-once setting, so it keeps only its header
@@ -214,7 +223,7 @@
214
223
  .row.playing { background: var(--accent-soft); }
215
224
  .row.playing .name { color: var(--accent); font-weight: 600; }
216
225
  .row .idx { width: 20px; text-align: right; color: var(--faint); font-variant-numeric: tabular-nums; flex: none; font-size: 12px; }
217
- .row.playing .idx { color: var(--accent); }
226
+ .row.playing .idx { color: var(--accent); display: grid; justify-items: end; }
218
227
  .row img { width: 36px; height: 36px; border-radius: 6px; object-fit: cover; flex: none; background: var(--panel); }
219
228
  .row .meta { min-width: 0; flex: 1; }
220
229
  .row .name { display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
@@ -222,14 +231,15 @@
222
231
  .row .tag { font-size: 10px; border: 1px solid var(--line); border-radius: 4px; padding: 0 4px; color: var(--muted); flex: none; }
223
232
  .row .dur { color: var(--muted); font-variant-numeric: tabular-nums; flex: none; font-size: 12px; min-width: 32px; text-align: right; }
224
233
  .row .acts { display: none; gap: 4px; flex: none; }
225
- .row .acts button { padding: 1px 6px; font-size: 11px; background: none; color: var(--muted); }
234
+ .row .acts button { padding: 3px 5px; background: none; color: var(--muted); }
235
+ .row .acts button:hover:not(:disabled) { color: var(--fg); }
226
236
  .row:hover .acts { display: flex; }
227
237
  /* The list's own like control. A liked track keeps its filled heart
228
238
  visible; the hollow one only appears on hover, so an unrated list is
229
239
  not a wall of outlines. */
230
240
  .row .heart {
231
- background: none; border: 0; padding: 0; width: 16px; flex: none;
232
- font-size: 14px; line-height: 1; color: var(--muted); opacity: 0; transition: opacity 0.12s;
241
+ background: none; border: 0; padding: 0; flex: none;
242
+ color: var(--muted); opacity: 0; transition: opacity 0.12s;
233
243
  }
234
244
  .row:hover .heart { opacity: 1; }
235
245
  .row .heart.on { opacity: 1; color: var(--accent); }
@@ -257,6 +267,10 @@
257
267
  <header>
258
268
  <div class="brand"><span data-i18n="brand">Music</span><small>music.163.com</small></div>
259
269
  <div class="spacer"></div>
270
+ <div class="history" id="history" hidden>
271
+ <span id="history-label" data-i18n="scrobbleLabel">Listening history</span>
272
+ <button id="scrobble-toggle" class="switch" role="switch" aria-labelledby="history-label"></button>
273
+ </div>
260
274
  <div id="account"></div>
261
275
  </header>
262
276
 
@@ -264,7 +278,7 @@
264
278
  <section class="stage">
265
279
  <div id="notices"></div>
266
280
  <div class="np">
267
- <div class="cover"><img id="cover" alt="" /></div>
281
+ <div class="cover"><span id="cover-icon"></span><img id="cover" alt="" /></div>
268
282
  <div class="np-text">
269
283
  <div class="now-title" id="np-title" data-i18n="nothingPlaying">Nothing playing</div>
270
284
  <div class="now-artists" id="np-artists"></div>
@@ -272,10 +286,10 @@
272
286
  <!-- Labels are state-dependent (a filled heart un-likes), so the
273
287
  script owns text and title rather than data-i18n. -->
274
288
  <div class="taste">
275
- <button id="like" title="Like">♡</button>
276
- <button id="dislike" title="Dislike">✕</button>
277
- <button id="boost-more" title="More like this for an hour">▲</button>
278
- <button id="boost-less" title="Fewer like this for an hour">▼</button>
289
+ <button id="like" title="Like"></button>
290
+ <button id="dislike" title="Dislike"></button>
291
+ <button id="boost-more" title="More like this for an hour"></button>
292
+ <button id="boost-less" title="Fewer like this for an hour"></button>
279
293
  </div>
280
294
  </div>
281
295
  </div>
@@ -286,9 +300,9 @@
286
300
  <span id="t-dur">0:00</span>
287
301
  </div>
288
302
  <div class="transport">
289
- <button id="prev" data-i18n-title="prev" title="Previous"><svg viewBox="0 0 24 24"><path d="M6 5h2v14H6zM20 5v14L9.5 12z"/></svg></button>
290
- <button id="play" data-i18n-title="playPause" title="Play/pause"><svg viewBox="0 0 24 24"><path d="M8 5v14l11-7z"/></svg></button>
291
- <button id="next" data-i18n-title="next" title="Next"><svg viewBox="0 0 24 24"><path d="M16 5h2v14h-2zM4 5v14l10.5-7z"/></svg></button>
303
+ <button id="prev" data-i18n-title="prev" title="Previous"></button>
304
+ <button id="play" data-i18n-title="playPause" title="Play/pause"></button>
305
+ <button id="next" data-i18n-title="next" title="Next"></button>
292
306
  </div>
293
307
  <div class="secondary">
294
308
  <button id="mode" data-i18n-title="modeTitle" data-i18n="modeList" title="Playback mode">List</button>
@@ -316,7 +330,7 @@
316
330
  <div class="card-head">
317
331
  <span class="title">AI DJ</span>
318
332
  <span class="grow"></span>
319
- <button id="dj-toggle" role="switch" data-i18n-title="djToggleTitle" title="Continuous AI DJ: keep the queue stocked">AI DJ</button>
333
+ <button id="dj-toggle" class="switch" role="switch" data-i18n-title="djToggleTitle" title="Continuous AI DJ: keep the queue stocked">AI DJ</button>
320
334
  </div>
321
335
  <div class="dj-body">
322
336
  <input id="dj-prompt" data-i18n-ph="djPromptPh" placeholder="AI DJ mood, e.g. rainy afternoon jazz" />
@@ -473,6 +487,11 @@
473
487
  boostCleared: '已取消临时偏好',
474
488
  boostsTitle: '临时偏好',
475
489
  boostMinutes: '{n} 分钟',
490
+ scrobbleLabel: '听歌记录',
491
+ scrobbleOnTitle: '播放计入网易云听歌记录(最近播放、听歌排行)——点击停止',
492
+ scrobbleOffTitle: '播放只留在本地——点击计入网易云听歌记录',
493
+ scrobbleOn: '播放将计入网易云听歌记录',
494
+ scrobbleOff: '播放不再计入听歌记录',
476
495
  djOn: 'AI DJ 已开启',
477
496
  djOff: 'AI DJ 已关闭',
478
497
  connectFailed: '连接失败:',
@@ -570,6 +589,11 @@
570
589
  boostCleared: 'Boost cleared',
571
590
  boostsTitle: 'Boosts',
572
591
  boostMinutes: '{n} min',
592
+ scrobbleLabel: 'Listening history',
593
+ scrobbleOnTitle: 'Plays are added to your NetEase listening history (最近播放, 听歌排行) — click to stop',
594
+ scrobbleOffTitle: 'Plays stay local — click to add them to your NetEase listening history',
595
+ scrobbleOn: 'Plays will be added to your NetEase listening history',
596
+ scrobbleOff: 'Plays will stay local',
573
597
  djOn: 'AI DJ on',
574
598
  djOff: 'AI DJ off',
575
599
  connectFailed: 'Cannot reach the host: ',
@@ -597,19 +621,62 @@
597
621
  }
598
622
 
599
623
  /** Translate a key, interpolating `{name}` placeholders from `vars`. */
600
- /** Monochrome icons for controls whose glyph changes with state. */
624
+ /**
625
+ * The page's one icon set: Lucide (https://lucide.dev, ISC licence), drawn
626
+ * as 24px outlines. DSH shares no icon set with plugins — the shell's
627
+ * module table holds React, Cordis and its UI primitives, none an icon
628
+ * library — and this page is its own document, so it carries its own.
629
+ * A state fills an outline (a liked heart) rather than swapping glyphs.
630
+ */
601
631
  const ICONS = {
602
- play: '<path d="M8 5v14l11-7z"/>',
603
- pause: '<path d="M7 5h4v14H7zM13 5h4v14h-4z"/>',
604
- volume: '<path d="M4 9v6h4l5 4V5L8 9zM16 8.5a4.5 4.5 0 0 1 0 7l-1-1.3a2.9 2.9 0 0 0 0-4.4zM17.8 5.6a8 8 0 0 1 0 12.8l-1-1.3a6.4 6.4 0 0 0 0-10.2z"/>',
605
- muted: '<path d="M4 9v6h4l5 4V5L8 9zM16.3 9.4l1.1-1.1 2.1 2.1 2.1-2.1 1.1 1.1-2.1 2.1 2.1 2.1-1.1 1.1-2.1-2.1-2.1 2.1-1.1-1.1 2.1-2.1z"/>',
632
+ play: '<polygon points="6 3 20 12 6 21 6 3"/>',
633
+ pause: '<rect x="14" y="4" width="4" height="16" rx="1"/><rect x="6" y="4" width="4" height="16" rx="1"/>',
634
+ skipBack: '<polygon points="19 20 9 12 19 4 19 20"/><line x1="5" x2="5" y1="19" y2="5"/>',
635
+ skipForward: '<polygon points="5 4 15 12 5 20 5 4"/><line x1="19" x2="19" y1="5" y2="19"/>',
636
+ volume: '<polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14"/>',
637
+ muted: '<polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><line x1="22" x2="16" y1="9" y2="15"/><line x1="16" x2="22" y1="9" y2="15"/>',
638
+ heart: '<path d="M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z"/>',
639
+ x: '<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',
640
+ more: '<path d="m17 11-5-5-5 5"/><path d="m17 18-5-5-5 5"/>',
641
+ less: '<path d="m7 6 5 5 5-5"/><path d="m7 13 5 5 5-5"/>',
642
+ music: '<path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/>',
606
643
  };
607
644
 
608
- /** Paint `name` into `el`, touching the DOM only when it changes. */
609
- function setIcon(el, name) {
610
- if (!el || el.dataset.icon === name) return;
611
- el.dataset.icon = name;
612
- el.innerHTML = `<svg viewBox="0 0 24 24" aria-hidden="true">${ICONS[name]}</svg>`;
645
+ function paintStaticIcons() {
646
+ setIcon($('prev'), 'skipBack');
647
+ setIcon($('next'), 'skipForward');
648
+ setIcon($('dislike'), 'x');
649
+ setIcon($('boost-more'), 'more');
650
+ setIcon($('boost-less'), 'less');
651
+ setIcon($('cover-icon'), 'music');
652
+ }
653
+
654
+ /**
655
+ * The listening-history switch: shown only signed in — there is no history
656
+ * to write to otherwise — and on when plays are being reported.
657
+ */
658
+ function paintHistory() {
659
+ const scrobble = state?.scrobble;
660
+ const signedIn = Boolean(state?.authenticated);
661
+ $('history').hidden = !signedIn || !scrobble;
662
+ const on = Boolean(scrobble?.enabled);
663
+ $('scrobble-toggle').classList.toggle('on', on);
664
+ $('scrobble-toggle').setAttribute?.('aria-checked', String(on));
665
+ $('scrobble-toggle').title = t(on ? 'scrobbleOnTitle' : 'scrobbleOffTitle');
666
+ }
667
+
668
+ /** One icon as markup; `filled` fills the outline, `small` is the compact size. */
669
+ function icon(name, { filled = false, small = false } = {}) {
670
+ const classes = ['i', filled ? 'filled' : '', small ? 'small' : ''].filter(Boolean).join(' ');
671
+ return `<svg class="${classes}" viewBox="0 0 24 24" aria-hidden="true">${ICONS[name]}</svg>`;
672
+ }
673
+
674
+ /** Paint an icon into `el`, touching the DOM only when it changes. */
675
+ function setIcon(el, name, options = {}) {
676
+ const key = `${name}${options.filled ? ':filled' : ''}`;
677
+ if (!el || el.dataset.icon === key) return;
678
+ el.dataset.icon = key;
679
+ el.innerHTML = icon(name, options);
613
680
  }
614
681
 
615
682
  function t(key, vars) {
@@ -999,10 +1066,11 @@
999
1066
  $('lyrics').innerHTML = '<p class="hint">—</p>';
1000
1067
  }
1001
1068
  }
1002
- setIcon($('play'), state.playing ? 'pause' : 'play');
1069
+ setIcon($('play'), state.playing ? 'pause' : 'play', { filled: true });
1003
1070
  $('mode').textContent = { list: t('modeList'), single: t('modeSingle'), shuffle: t('modeShuffle') }[state.mode] || t('modeList');
1004
1071
  $('counts').textContent = state.counts ? `(${state.counts.queued})` : '';
1005
1072
  $('dj-toggle').classList.toggle('on', Boolean(state.dj?.enabled));
1073
+ paintHistory();
1006
1074
  // The mood brief is persisted player setting, not part of the DJ status
1007
1075
  // block, so it comes from `settings`.
1008
1076
  if (document.activeElement !== $('dj-prompt')) $('dj-prompt').value = state.settings?.djPrompt ?? '';
@@ -1090,13 +1158,13 @@
1090
1158
  const index = start + offset;
1091
1159
  const playing = index === state.index;
1092
1160
  return `<div class="row ${playing ? 'playing' : ''}" data-jump="${index}">
1093
- <span class="idx">${playing ? '▶' : index + 1}</span>
1161
+ <span class="idx">${playing ? icon('play', { filled: true, small: true }) : index + 1}</span>
1094
1162
  <img src="${esc(track.picUrl || '')}" alt="" loading="lazy">
1095
1163
  <span class="meta"><span class="name">${esc(track.name)}</span><span class="sub">${esc((track.artists || []).join(' / '))}</span></span>
1096
1164
  ${track.vip ? '<span class="tag">VIP</span>' : ''}
1097
- <button class="heart ${track.liked ? 'on' : ''}" data-like="${index}" title="${esc(t(track.liked ? 'unlike' : 'like'))}">${track.liked ? '♥' : '♡'}</button>
1165
+ <button class="heart ${track.liked ? 'on' : ''}" data-like="${index}" title="${esc(t(track.liked ? 'unlike' : 'like'))}">${icon('heart', { filled: track.liked, small: true })}</button>
1098
1166
  <span class="dur">${fmt(track.duration)}</span>
1099
- <span class="acts"><button data-remove="${index}" title="${esc(t('remove'))}">✕</button></span>
1167
+ <span class="acts"><button data-remove="${index}" title="${esc(t('remove'))}">${icon('x', { small: true })}</button></span>
1100
1168
  </div>`;
1101
1169
  })
1102
1170
  .join('');
@@ -1114,7 +1182,7 @@
1114
1182
  const track = state?.current;
1115
1183
  const liked = Boolean(track?.liked);
1116
1184
  const disliked = Boolean(track?.disliked);
1117
- $('like').textContent = liked ? '♥' : '♡';
1185
+ setIcon($('like'), 'heart', { filled: liked });
1118
1186
  $('like').classList.toggle('on', liked);
1119
1187
  $('like').title = t(liked ? 'unlike' : 'like');
1120
1188
  $('dislike').classList.toggle('on', disliked);
@@ -1140,7 +1208,7 @@
1140
1208
  boosts
1141
1209
  .map((boost) => {
1142
1210
  const minutes = Math.max(Math.round((boost.until - now) / 60_000), 1);
1143
- return `<span class="boost">${boost.direction === 'more' ? '▲' : '▼'} ${esc(boost.name)} · ${esc(t('boostMinutes', { n: minutes }))}<button data-unboost="${boost.id}" title="${esc(t('boostClear'))}">✕</button></span>`;
1211
+ return `<span class="boost">${icon(boost.direction === 'more' ? 'more' : 'less', { small: true })} ${esc(boost.name)} · ${esc(t('boostMinutes', { n: minutes }))}<button data-unboost="${boost.id}" title="${esc(t('boostClear'))}">${icon('x', { small: true })}</button></span>`;
1144
1212
  })
1145
1213
  .join('')
1146
1214
  : '';
@@ -1741,6 +1809,21 @@
1741
1809
  if (target) return sendBoost(Number(target.dataset.unboost), 'none', target);
1742
1810
  };
1743
1811
 
1812
+ $('scrobble-toggle').onclick = async (event) => {
1813
+ const next = !state?.scrobble?.enabled;
1814
+ const button = event?.currentTarget;
1815
+ if (button) button.disabled = true;
1816
+ try {
1817
+ state = await api('/scrobble', { method: 'POST', body: { enabled: next } });
1818
+ render();
1819
+ toast(t(next ? 'scrobbleOn' : 'scrobbleOff'));
1820
+ } catch (error) {
1821
+ toast(failureText(error));
1822
+ } finally {
1823
+ if (button) button.disabled = false;
1824
+ }
1825
+ };
1826
+
1744
1827
  $('dj-toggle').onclick = async () => {
1745
1828
  try {
1746
1829
  const data = await api('/dj', { method: 'POST', body: { enabled: !state?.dj?.enabled, prompt: $('dj-prompt').value } });
@@ -1787,6 +1870,7 @@
1787
1870
  }
1788
1871
  }
1789
1872
 
1873
+ paintStaticIcons();
1790
1874
  applyLocale();
1791
1875
  watchShellLocale();
1792
1876
  refresh();
package/lib/router.js CHANGED
@@ -108,13 +108,14 @@ export class MusicRouter {
108
108
  * @param {() => object} [options.diagnostics] extra facts for `/health`.
109
109
  * @param {{warn: Function, info: Function, debug: Function}} [options.logger]
110
110
  */
111
- constructor({ base, api, player, store, qr, dj, likes, panelHtml, qrcodeJs, config = {}, listRoutes, diagnostics, logger }) {
111
+ constructor({ base, api, player, store, qr, dj, likes, scrobbler, panelHtml, qrcodeJs, config = {}, listRoutes, diagnostics, logger }) {
112
112
  this.base = base.replace(/\/+$/, '');
113
113
  this.api = api;
114
114
  this.player = player;
115
115
  this.store = store;
116
116
  this.qr = qr;
117
117
  this.dj = dj;
118
+ this.scrobbler = scrobbler;
118
119
  this.likes = likes;
119
120
  this.panelHtml = panelHtml;
120
121
  this.qrcodeJs = qrcodeJs;
@@ -358,6 +359,8 @@ export class MusicRouter {
358
359
  authenticated: this.api.authenticated,
359
360
  settings: this.store.settings,
360
361
  modelSource: this.modelSource(),
362
+ /** Whether plays reach the NetEase listening history, for the player's switch. */
363
+ scrobble: this.scrobbler?.status() ?? null,
361
364
  /** Preferred quality, plus what the last stream request actually served. */
362
365
  audio: { preferred: this.preferredLevel(), last: this.lastAudio },
363
366
  ...extra,
@@ -594,6 +597,19 @@ export class MusicRouter {
594
597
  * (or `minutes`), and `none` clears it. Unlike a taste level it expires on
595
598
  * its own.
596
599
  */
600
+ /**
601
+ * The player's listening-history switch. The choice is saved and beats
602
+ * `config.scrobble`, so a stale profile setting cannot override it.
603
+ */
604
+ if (route === '/scrobble' && method === 'POST') {
605
+ const { enabled } = await readJson(req);
606
+ if (typeof enabled !== 'boolean') return sendJson(res, 400, { error: 'enabled must be true or false' });
607
+ this.store.updateSettings({ scrobble: enabled });
608
+ if (this.scrobbler) this.scrobbler.enabled = enabled;
609
+ this.logger?.info?.(`[music] listening history ${enabled ? 'on' : 'off'} from the player`);
610
+ return sendJson(res, 200, await this.snapshot());
611
+ }
612
+
597
613
  if (route === '/boost' && method === 'POST') {
598
614
  const { trackId, direction, minutes } = await readJson(req);
599
615
  const applied = await this.applyBoost(trackId, direction, minutes);
@@ -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
@@ -79,6 +79,12 @@ function emptyState() {
79
79
  * and every restart inside one conversation.
80
80
  */
81
81
  djSessionId: '',
82
+ /**
83
+ * Whether plays are reported to the NetEase listening history, as chosen
84
+ * in the player. `null` means no choice made here, so `config.scrobble`
85
+ * applies; a choice beats it, as the quality and DJ model choices do.
86
+ */
87
+ scrobble: null,
82
88
  },
83
89
  history: [],
84
90
  feedback: { likes: [], dislikes: [], skips: [] },
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.9",
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"