@doitian/dsh-music 0.1.5 → 0.1.7

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,
@@ -389,6 +417,14 @@ export class MusicRouter {
389
417
  }
390
418
 
391
419
  this.store.setTaste(id, level);
420
+ // A disliked track leaves the queue wherever it sits — the playing one
421
+ // too, which moves playback on to the next. Every dislike comes through
422
+ // here, so the transport's ✕, the legacy feedback route and a row removal
423
+ // all agree, and the page no longer presses next on top of it.
424
+ if (level === 'disliked') {
425
+ const at = this.player.queue.findIndex((track) => track.id === id);
426
+ if (at >= 0) this.player.remove(at);
427
+ }
392
428
  return { ok: true, id, level };
393
429
  }
394
430
 
@@ -485,7 +521,6 @@ export class MusicRouter {
485
521
  return sendJson(res, 400, { error: 'tracks must be a non-empty array' });
486
522
  }
487
523
  this.player.setQueue(tracks, { startIndex, source: 'user' });
488
- this.store.recordPlay(this.player.current() ?? tracks[0]);
489
524
  return sendJson(res, 200, await this.snapshot());
490
525
  }
491
526
  if (route === '/queue' && method === 'POST') {
@@ -554,6 +589,18 @@ export class MusicRouter {
554
589
  * so a click cannot be turned into the wrong direction by a stale poll, and
555
590
  * disliking a liked track is one request rather than two racing ones.
556
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
+
557
604
  if (route === '/taste' && method === 'POST') {
558
605
  const { trackId, level } = await readJson(req);
559
606
  const applied = await this.applyTaste(trackId, level);
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,9 +82,23 @@ 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
 
94
+ /**
95
+ * Whether a play is evidence of taste: neither skipped, nor a DJ pick still
96
+ * waiting to be heard through. Plays recorded before either flag existed count.
97
+ */
98
+ export function isHeard(entry) {
99
+ return !entry.skipped && !entry.tentative;
100
+ }
101
+
77
102
  /**
78
103
  * JSON-document store for the plugin's data directory.
79
104
  *
@@ -177,38 +202,60 @@ export class SessionStore {
177
202
  // --------------------------------------------------------------- history
178
203
 
179
204
  /**
180
- * Record a play and return the durable taste picture the DJ reasons over.
205
+ * Record a play.
206
+ *
207
+ * A `tentative` play is one the DJ chose. It counts as heard — and so as
208
+ * taste — only once {@link confirmPlay} says the listener got past the skip
209
+ * window. Otherwise every track the DJ queued would read as approval of
210
+ * itself, and a few batches of charts would teach the DJ the charts are
211
+ * what the listener likes. It still counts as played for avoiding repeats.
212
+ *
181
213
  * @param {{id: number, name: string, artists: string[]}} track
214
+ * @param {{tentative?: boolean}} [options]
182
215
  */
183
- recordPlay(track) {
216
+ recordPlay(track, { tentative = false } = {}) {
184
217
  this.state.history.unshift({
185
218
  id: track.id,
186
219
  name: track.name,
187
220
  artists: track.artists ?? [],
188
221
  at: Date.now(),
222
+ ...(tentative ? { tentative: true } : {}),
189
223
  });
190
224
  if (this.state.history.length > MAX_HISTORY) this.state.history.length = MAX_HISTORY;
191
225
  this.touch();
192
226
  }
193
227
 
228
+ /** The listener heard a tentative play through: it now counts as taste. */
229
+ confirmPlay(trackId) {
230
+ const play = this.state.history.find((entry) => entry.id === Number(trackId));
231
+ if (!play?.tentative) return;
232
+ delete play.tentative;
233
+ this.touch();
234
+ }
235
+
194
236
  /** Recent track ids, newest first — used to avoid repeats. */
195
237
  recentIds(limit = 50) {
196
238
  return this.state.history.slice(0, limit).map((entry) => entry.id);
197
239
  }
198
240
 
199
- /** Most-played artists, most frequent first. A skipped play is not a play. */
241
+ /** Most-played artists, most frequent first. Only plays heard through count. */
200
242
  topArtists(limit = 8) {
201
- const counts = new Map();
202
- for (const entry of this.state.history.slice(0, 150)) {
203
- if (entry.skipped) continue;
204
- for (const artist of entry.artists) counts.set(artist, (counts.get(artist) ?? 0) + 1);
205
- }
206
- return [...counts.entries()]
243
+ return [...this.heardArtists().entries()]
207
244
  .sort((a, b) => b[1] - a[1])
208
245
  .slice(0, limit)
209
246
  .map(([artist]) => artist);
210
247
  }
211
248
 
249
+ /** Artist → plays heard through, among the recent history. */
250
+ heardArtists(window = 150) {
251
+ const counts = new Map();
252
+ for (const entry of this.state.history.slice(0, window)) {
253
+ if (!isHeard(entry)) continue;
254
+ for (const artist of entry.artists ?? []) counts.set(artist, (counts.get(artist) ?? 0) + 1);
255
+ }
256
+ return counts;
257
+ }
258
+
212
259
  /**
213
260
  * One track's taste level: `liked`, `disliked`, or `none` (never rated).
214
261
  * @param {number|string} trackId
@@ -305,6 +352,46 @@ export class SessionStore {
305
352
  return this.state.feedback;
306
353
  }
307
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
+
308
395
  /**
309
396
  * A compact digest for the DJ prompt: what has been played, what is liked,
310
397
  * what is disliked — never the raw cookie or account details.
package/lib/state.js CHANGED
@@ -33,6 +33,14 @@ const SEEK_EPSILON_MS = 1_000;
33
33
  const SKIP_WINDOW_MS = 30_000;
34
34
  const SKIP_WINDOW_FRACTION = 0.25;
35
35
 
36
+ /**
37
+ * Mark who queued a track. A track the DJ chose has to be heard through
38
+ * before it counts as taste; one the listener chose counts at once.
39
+ */
40
+ function tag(track, queuedBy) {
41
+ return queuedBy && track?.id ? { ...track, queuedBy } : track;
42
+ }
43
+
36
44
  export class Player {
37
45
  /**
38
46
  * @param {object} [options]
@@ -82,6 +90,14 @@ export class Player {
82
90
  * @type {((track: object) => void) | undefined}
83
91
  */
84
92
  this.onSkip = undefined;
93
+ /**
94
+ * Called once with the current track when the listener has heard it
95
+ * through: past the skip window, or to its end.
96
+ * @type {((track: object) => void) | undefined}
97
+ */
98
+ this.onHeard = undefined;
99
+ /** The track `onHeard` was last called for, so it fires once per play. */
100
+ this.heardId = null;
85
101
  }
86
102
 
87
103
  /** Subscribe to state changes. @returns {() => void} unsubscribe */
@@ -117,8 +133,12 @@ export class Player {
117
133
  }
118
134
 
119
135
  /** Replace the whole queue. `startIndex` selects what plays first. */
120
- setQueue(tracks, { startIndex = 0, play = true, source } = {}) {
121
- const normalized = tracks.map((track) => normalizeTrack(track) ?? track).filter((track) => track?.id);
136
+ setQueue(tracks, { startIndex = 0, play = true, source, queuedBy } = {}) {
137
+ const normalized = tracks
138
+ .map((track) => normalizeTrack(track) ?? track)
139
+ .filter((track) => track?.id)
140
+ .map((track) => tag(track, queuedBy));
141
+ this.heardId = null;
122
142
  this.queue = normalized;
123
143
  this.index = normalized.length === 0 ? -1 : Math.min(Math.max(startIndex, 0), normalized.length - 1);
124
144
  this.pendingSeek = null;
@@ -130,11 +150,11 @@ export class Player {
130
150
  }
131
151
 
132
152
  /** Append tracks, de-duplicating against the queue tail. */
133
- append(tracks, { source, play = true } = {}) {
153
+ append(tracks, { source, play = true, queuedBy } = {}) {
134
154
  const existing = new Set(this.queue.map((track) => track.id));
135
155
  const added = [];
136
156
  for (const raw of tracks) {
137
- const track = normalizeTrack(raw) ?? raw;
157
+ const track = tag(normalizeTrack(raw) ?? raw, queuedBy);
138
158
  if (!track?.id || existing.has(track.id)) continue;
139
159
  existing.add(track.id);
140
160
  added.push(track);
@@ -149,11 +169,11 @@ export class Player {
149
169
  }
150
170
 
151
171
  /** Insert tracks directly after the cursor. */
152
- insertNext(tracks, { source } = {}) {
172
+ insertNext(tracks, { source, queuedBy } = {}) {
153
173
  const existing = new Set(this.queue.map((track) => track.id));
154
174
  const added = [];
155
175
  for (const raw of tracks) {
156
- const track = normalizeTrack(raw) ?? raw;
176
+ const track = tag(normalizeTrack(raw) ?? raw, queuedBy);
157
177
  if (!track?.id || existing.has(track.id)) continue;
158
178
  existing.add(track.id);
159
179
  added.push(track);
@@ -183,14 +203,17 @@ export class Player {
183
203
  /** Remove one queue position. */
184
204
  remove(index) {
185
205
  if (index < 0 || index >= this.queue.length) return this.snapshot();
206
+ const wasCurrent = index === this.index;
186
207
  this.queue.splice(index, 1);
187
208
  if (this.queue.length === 0) {
188
209
  this.index = -1;
189
210
  this.playing = false;
190
211
  } else if (index < this.index) {
191
212
  this.index -= 1;
192
- } else if (index === this.index) {
193
- this.index = Math.min(this.index, this.queue.length - 1);
213
+ } else if (wasCurrent) {
214
+ // The next track takes the removed one's place. Past the end, the queue
215
+ // wraps to its start, as `next` does, rather than going back a track.
216
+ if (this.index >= this.queue.length) this.index = 0;
194
217
  this.pendingSeek = 0;
195
218
  }
196
219
  this.bump({ transport: true });
@@ -236,6 +259,7 @@ export class Player {
236
259
  const left = this.current();
237
260
  const skipped = !auto && step > 0 && this.#heardBriefly();
238
261
  this.index = this.#nextIndex(step);
262
+ if (this.current() !== left) this.heardId = null;
239
263
  this.pendingSeek = 0;
240
264
  this.playing = true;
241
265
  this.reported = { ...this.reported, position: 0, duration: 0, error: null, at: Date.now() };
@@ -257,8 +281,31 @@ export class Player {
257
281
  if (!current || this.reported.trackId !== current.id) return false;
258
282
  const position = Number(this.reported.position) || 0;
259
283
  if (position <= 0) return false;
260
- const duration = Number(this.reported.duration) || Number(current.duration) || 0;
261
- return position < Math.max(SKIP_WINDOW_MS, duration * SKIP_WINDOW_FRACTION);
284
+ return position < this.#skipWindow(current);
285
+ }
286
+
287
+ /** How much of `track` must play before moving on is no longer a skip. */
288
+ #skipWindow(track) {
289
+ const duration = Number(this.reported.duration) || Number(track.duration) || 0;
290
+ return Math.max(SKIP_WINDOW_MS, duration * SKIP_WINDOW_FRACTION);
291
+ }
292
+
293
+ /**
294
+ * Tell the taste record, once per play, that the current track was heard
295
+ * through — past the skip window, or to its end. The two windows are one:
296
+ * a track is either skipped or heard, never both and never neither once it
297
+ * has played that far.
298
+ */
299
+ #noteHeard({ ended = false } = {}) {
300
+ const current = this.current();
301
+ if (!current || this.heardId === current.id || this.reported.trackId !== current.id) return;
302
+ if (!ended && (Number(this.reported.position) || 0) < this.#skipWindow(current)) return;
303
+ this.heardId = current.id;
304
+ try {
305
+ this.onHeard?.(current);
306
+ } catch (error) {
307
+ this.logger?.warn?.(`[music] heard listener failed: ${error.message}`);
308
+ }
262
309
  }
263
310
 
264
311
  #notifySkip(track) {
@@ -272,6 +319,7 @@ export class Player {
272
319
  /** Jump to an explicit queue position. */
273
320
  jump(index) {
274
321
  if (index < 0 || index >= this.queue.length) return this.snapshot();
322
+ if (index !== this.index) this.heardId = null;
275
323
  this.index = index;
276
324
  this.pendingSeek = 0;
277
325
  this.playing = true;
@@ -355,6 +403,8 @@ export class Player {
355
403
  this.lastError = this.reported.error;
356
404
  }
357
405
 
406
+ this.#noteHeard({ ended: Boolean(ended) });
407
+
358
408
  let advanced = false;
359
409
  if (ended || error) {
360
410
  this.logger?.info?.(`[music] track ${ended ? 'ended' : 'failed'}, advancing`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@doitian/dsh-music",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
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",