@doitian/dsh-music 0.1.4 → 0.1.6
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 +56 -602
- package/cordis.patch.yml +12 -8
- package/lib/cache.js +156 -0
- package/lib/dj.js +509 -76
- package/lib/index.js +25 -8
- package/lib/netease.js +33 -0
- package/lib/panel.html +3 -4
- package/lib/router.js +8 -1
- package/lib/session.js +75 -16
- package/lib/state.js +96 -6
- package/package.json +4 -3
package/lib/index.js
CHANGED
|
@@ -149,8 +149,9 @@ export function apply(ctx, config = {}) {
|
|
|
149
149
|
* The deployment's default model selection: the route a freshly created agent
|
|
150
150
|
* starts on, and the same choice the composer/command model picker writes.
|
|
151
151
|
*
|
|
152
|
-
* This is the seam that makes the
|
|
153
|
-
* separate decisions
|
|
152
|
+
* This is the seam that makes the session's model and the DJ's model two
|
|
153
|
+
* separate decisions; only the choice is shared, since the DJ calls its model
|
|
154
|
+
* directly rather than through an agent. `agent-default-model` owns the first; `dj.provider` /
|
|
154
155
|
* `dj.model` owns the second; and the DJ follows the session model when the
|
|
155
156
|
* plugin pins nothing, instead of picking an arbitrary first route.
|
|
156
157
|
*/
|
|
@@ -187,6 +188,14 @@ export function apply(ctx, config = {}) {
|
|
|
187
188
|
},
|
|
188
189
|
});
|
|
189
190
|
player.onLowQueue = () => dj.topUp();
|
|
191
|
+
player.onSkip = (track) => {
|
|
192
|
+
// The panel's ✕ records the dislike and then presses next, so an early
|
|
193
|
+
// dislike would also count as a skip — but only inside the skip window,
|
|
194
|
+
// which would make the same judgement weigh differently by when it came.
|
|
195
|
+
if (store.taste(track.id) === 'disliked') return;
|
|
196
|
+
store.recordSkip(track.id);
|
|
197
|
+
logger.debug(`[music] skip recorded for ${track.id}`);
|
|
198
|
+
};
|
|
190
199
|
|
|
191
200
|
/** Tool names that registered successfully; surfaced by `/music/health`. */
|
|
192
201
|
const registeredTools = [];
|
|
@@ -216,13 +225,17 @@ export function apply(ctx, config = {}) {
|
|
|
216
225
|
.catch((error) => logger.warn(`[music] account check failed: ${error.message}`));
|
|
217
226
|
|
|
218
227
|
// ---------------------------------------------------------- history + DJ
|
|
228
|
+
// The one place a play is recorded: whenever the current track changes, by
|
|
229
|
+
// whatever path. Recording it again where the queue is set counted every
|
|
230
|
+
// played track twice, and an appended one as a play of the current track.
|
|
219
231
|
let lastRecorded = null;
|
|
220
232
|
player.subscribe(() => {
|
|
221
233
|
const current = player.current();
|
|
222
234
|
if (!current || current.id === lastRecorded) return;
|
|
223
235
|
lastRecorded = current.id;
|
|
224
|
-
store.recordPlay(current);
|
|
236
|
+
store.recordPlay(current, { tentative: current.queuedBy === 'dj' });
|
|
225
237
|
});
|
|
238
|
+
player.onHeard = (track) => store.confirmPlay(track.id);
|
|
226
239
|
|
|
227
240
|
// A periodic sweep catches the cases the track-end hook misses: a paused
|
|
228
241
|
// panel, a failed track, or a DJ that was switched on with a short queue.
|
|
@@ -383,7 +396,6 @@ export function apply(ctx, config = {}) {
|
|
|
383
396
|
if (mode === 'append') player.append(tracks, { source: 'agent' });
|
|
384
397
|
else if (mode === 'next') player.insertNext(tracks, { source: 'agent' });
|
|
385
398
|
else player.setQueue(tracks, { startIndex: 0, play: true, source: 'agent' });
|
|
386
|
-
store.recordPlay(player.current() ?? tracks[0]);
|
|
387
399
|
|
|
388
400
|
const summary = player.summary();
|
|
389
401
|
return {
|
|
@@ -503,8 +515,8 @@ export function apply(ctx, config = {}) {
|
|
|
503
515
|
title: 'AI DJ (NetEase Cloud Music)',
|
|
504
516
|
description:
|
|
505
517
|
'Run or configure the continuous AI DJ for the user\'s NetEase Cloud Music panel. ' +
|
|
506
|
-
'With `enabled: true` the DJ keeps the queue stocked: it gathers candidates from similar songs,
|
|
507
|
-
'recommendations, the charts and any mood brief, then either asks the model to choose or scores them by the ' +
|
|
518
|
+
'With `enabled: true` the DJ keeps the queue stocked: it gathers candidates from similar songs, personal FM, ' +
|
|
519
|
+
'liked songs not heard lately, the daily recommendations, the charts and any mood brief, then either asks the model to choose or scores them by the ' +
|
|
508
520
|
'listener\'s liked artists, novelty and feedback. Pass `prompt` for a mood or vibe, and `replan` to refill now.',
|
|
509
521
|
parameters: {
|
|
510
522
|
type: 'object',
|
|
@@ -513,7 +525,10 @@ export function apply(ctx, config = {}) {
|
|
|
513
525
|
enabled: { type: 'boolean', description: 'Turn continuous queue topping-up on or off.' },
|
|
514
526
|
prompt: { type: 'string', description: 'Mood or request, e.g. "rainy afternoon jazz", "90s cantopop".' },
|
|
515
527
|
replan: { type: 'boolean', description: 'Plan and queue a fresh batch immediately.' },
|
|
516
|
-
count: {
|
|
528
|
+
count: {
|
|
529
|
+
type: 'integer',
|
|
530
|
+
description: 'How many tracks to plan (1-25; default 8 for `start`, the player\'s batch size for `replan`).',
|
|
531
|
+
},
|
|
517
532
|
start: { type: 'boolean', description: 'Replace the queue with a freshly planned batch (a full DJ session).' },
|
|
518
533
|
},
|
|
519
534
|
},
|
|
@@ -524,6 +539,7 @@ export function apply(ctx, config = {}) {
|
|
|
524
539
|
`AI DJ is ${value.enabled ? 'on' : 'off'} (${value.source}${value.route ? ` via ${value.route}` : ''}). ` +
|
|
525
540
|
(value.modelError ? `Model tier unavailable: ${value.modelError}. ` : '') +
|
|
526
541
|
(value.vibe ? `Vibe: ${value.vibe}. ` : '') +
|
|
542
|
+
(value.searchedAs.length ? `Brief searched as: ${value.searchedAs.join('; ')}. ` : '') +
|
|
527
543
|
(value.names.length
|
|
528
544
|
? `Queued ${value.added} track(s):\n${value.names.map((entry, index) => `${index + 1}. ${entry}`).join('\n')}`
|
|
529
545
|
: value.note || 'No new tracks were queued.') +
|
|
@@ -540,7 +556,7 @@ export function apply(ctx, config = {}) {
|
|
|
540
556
|
if (args.start) {
|
|
541
557
|
plan = await dj.start({ prompt, count });
|
|
542
558
|
} else if (args.replan || (enabled === true && player.queue.length === 0)) {
|
|
543
|
-
plan = await dj.topUp({ force: true });
|
|
559
|
+
plan = await dj.topUp({ force: true, count: args.count === undefined ? undefined : count });
|
|
544
560
|
}
|
|
545
561
|
|
|
546
562
|
const summary = player.summary();
|
|
@@ -550,6 +566,7 @@ export function apply(ctx, config = {}) {
|
|
|
550
566
|
route: plan?.route ?? summary.dj.lastPlan?.route ?? null,
|
|
551
567
|
modelError: player.dj.modelError ?? null,
|
|
552
568
|
vibe: plan?.vibe ?? summary.dj.lastPlan?.vibe ?? '',
|
|
569
|
+
searchedAs: plan?.searchedAs ?? summary.dj.lastPlan?.searchedAs ?? [],
|
|
553
570
|
note: plan?.note ?? (plan && plan.tracks.length === 0 ? 'no candidates were available' : ''),
|
|
554
571
|
added: plan?.tracks.length ?? 0,
|
|
555
572
|
names: (plan?.tracks ?? []).map((track) => `${track.name} — ${(track.artists ?? []).join('/')}`),
|
package/lib/netease.js
CHANGED
|
@@ -372,6 +372,21 @@ export class Netease {
|
|
|
372
372
|
return data?.result ?? {};
|
|
373
373
|
}
|
|
374
374
|
|
|
375
|
+
/**
|
|
376
|
+
* Playlists matching a keyword. Listeners name and tag playlists by mood
|
|
377
|
+
* (雨天, 爵士, 深夜…), so this is how a mood finds music, where a song search
|
|
378
|
+
* only matches titles and lyrics.
|
|
379
|
+
*/
|
|
380
|
+
async searchPlaylists(keyword, { limit = 10 } = {}) {
|
|
381
|
+
const result = await this.search(keyword, { type: 1000, limit });
|
|
382
|
+
return (result.playlists ?? []).map((item) => ({
|
|
383
|
+
id: item.id,
|
|
384
|
+
name: item.name,
|
|
385
|
+
trackCount: item.trackCount ?? 0,
|
|
386
|
+
playCount: item.playCount ?? 0,
|
|
387
|
+
}));
|
|
388
|
+
}
|
|
389
|
+
|
|
375
390
|
/** Track metadata, including cover art and the VIP fee code. */
|
|
376
391
|
async songDetail(ids) {
|
|
377
392
|
const list = [...ids].map(Number).filter(Number.isFinite);
|
|
@@ -476,6 +491,12 @@ export class Netease {
|
|
|
476
491
|
playCount: playlist.playCount ?? 0,
|
|
477
492
|
creator: playlist.creator?.nickname ?? '',
|
|
478
493
|
tracks: normalizeTracks(playlist.tracks),
|
|
494
|
+
/**
|
|
495
|
+
* Every track id, in order. For a playlist the account does not own,
|
|
496
|
+
* `tracks` stops at the first 20 while this list is complete, so it is
|
|
497
|
+
* the only way to reach the rest.
|
|
498
|
+
*/
|
|
499
|
+
trackIds: (playlist.trackIds ?? []).map((entry) => entry.id).filter(Number.isFinite),
|
|
479
500
|
};
|
|
480
501
|
}
|
|
481
502
|
|
|
@@ -524,6 +545,18 @@ export class Netease {
|
|
|
524
545
|
return normalizeTracks(result?.dailySongs ?? result?.recommend);
|
|
525
546
|
}
|
|
526
547
|
|
|
548
|
+
/**
|
|
549
|
+
* 私人FM (personal FM): a few tracks NetEase picks for this account, a
|
|
550
|
+
* different few on every call. Requires a session.
|
|
551
|
+
*
|
|
552
|
+
* This is the personalised feed the plain API still serves; heartbeat mode
|
|
553
|
+
* ({@link intelligenceList}) answers `code 500` there for every seed.
|
|
554
|
+
*/
|
|
555
|
+
async personalFm() {
|
|
556
|
+
const data = await this.call('/api/v1/radio/get');
|
|
557
|
+
return normalizeTracks(data?.data);
|
|
558
|
+
}
|
|
559
|
+
|
|
527
560
|
/**
|
|
528
561
|
* 心动模式 (heartbeat mode): a personalised continuation of a seed track
|
|
529
562
|
* inside a playlist context. Requires a session.
|
package/lib/panel.html
CHANGED
|
@@ -1551,10 +1551,9 @@
|
|
|
1551
1551
|
await sendTaste(track, 'none', event?.currentTarget);
|
|
1552
1552
|
return;
|
|
1553
1553
|
}
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
}
|
|
1554
|
+
// The host takes a disliked track out of the queue, and moves on when it
|
|
1555
|
+
// was playing; pressing next here as well would skip a second track.
|
|
1556
|
+
if (await sendTaste(track, 'disliked', event?.currentTarget)) toast(t('disliked'));
|
|
1558
1557
|
};
|
|
1559
1558
|
|
|
1560
1559
|
$('dj-toggle').onclick = async () => {
|
package/lib/router.js
CHANGED
|
@@ -389,6 +389,14 @@ export class MusicRouter {
|
|
|
389
389
|
}
|
|
390
390
|
|
|
391
391
|
this.store.setTaste(id, level);
|
|
392
|
+
// A disliked track leaves the queue wherever it sits — the playing one
|
|
393
|
+
// too, which moves playback on to the next. Every dislike comes through
|
|
394
|
+
// here, so the transport's ✕, the legacy feedback route and a row removal
|
|
395
|
+
// all agree, and the page no longer presses next on top of it.
|
|
396
|
+
if (level === 'disliked') {
|
|
397
|
+
const at = this.player.queue.findIndex((track) => track.id === id);
|
|
398
|
+
if (at >= 0) this.player.remove(at);
|
|
399
|
+
}
|
|
392
400
|
return { ok: true, id, level };
|
|
393
401
|
}
|
|
394
402
|
|
|
@@ -485,7 +493,6 @@ export class MusicRouter {
|
|
|
485
493
|
return sendJson(res, 400, { error: 'tracks must be a non-empty array' });
|
|
486
494
|
}
|
|
487
495
|
this.player.setQueue(tracks, { startIndex, source: 'user' });
|
|
488
|
-
this.store.recordPlay(this.player.current() ?? tracks[0]);
|
|
489
496
|
return sendJson(res, 200, await this.snapshot());
|
|
490
497
|
}
|
|
491
498
|
if (route === '/queue' && method === 'POST') {
|
package/lib/session.js
CHANGED
|
@@ -74,6 +74,14 @@ function emptyState() {
|
|
|
74
74
|
};
|
|
75
75
|
}
|
|
76
76
|
|
|
77
|
+
/**
|
|
78
|
+
* Whether a play is evidence of taste: neither skipped, nor a DJ pick still
|
|
79
|
+
* waiting to be heard through. Plays recorded before either flag existed count.
|
|
80
|
+
*/
|
|
81
|
+
export function isHeard(entry) {
|
|
82
|
+
return !entry.skipped && !entry.tentative;
|
|
83
|
+
}
|
|
84
|
+
|
|
77
85
|
/**
|
|
78
86
|
* JSON-document store for the plugin's data directory.
|
|
79
87
|
*
|
|
@@ -177,37 +185,60 @@ export class SessionStore {
|
|
|
177
185
|
// --------------------------------------------------------------- history
|
|
178
186
|
|
|
179
187
|
/**
|
|
180
|
-
* Record a play
|
|
188
|
+
* Record a play.
|
|
189
|
+
*
|
|
190
|
+
* A `tentative` play is one the DJ chose. It counts as heard — and so as
|
|
191
|
+
* taste — only once {@link confirmPlay} says the listener got past the skip
|
|
192
|
+
* window. Otherwise every track the DJ queued would read as approval of
|
|
193
|
+
* itself, and a few batches of charts would teach the DJ the charts are
|
|
194
|
+
* what the listener likes. It still counts as played for avoiding repeats.
|
|
195
|
+
*
|
|
181
196
|
* @param {{id: number, name: string, artists: string[]}} track
|
|
197
|
+
* @param {{tentative?: boolean}} [options]
|
|
182
198
|
*/
|
|
183
|
-
recordPlay(track) {
|
|
199
|
+
recordPlay(track, { tentative = false } = {}) {
|
|
184
200
|
this.state.history.unshift({
|
|
185
201
|
id: track.id,
|
|
186
202
|
name: track.name,
|
|
187
203
|
artists: track.artists ?? [],
|
|
188
204
|
at: Date.now(),
|
|
205
|
+
...(tentative ? { tentative: true } : {}),
|
|
189
206
|
});
|
|
190
207
|
if (this.state.history.length > MAX_HISTORY) this.state.history.length = MAX_HISTORY;
|
|
191
208
|
this.touch();
|
|
192
209
|
}
|
|
193
210
|
|
|
211
|
+
/** The listener heard a tentative play through: it now counts as taste. */
|
|
212
|
+
confirmPlay(trackId) {
|
|
213
|
+
const play = this.state.history.find((entry) => entry.id === Number(trackId));
|
|
214
|
+
if (!play?.tentative) return;
|
|
215
|
+
delete play.tentative;
|
|
216
|
+
this.touch();
|
|
217
|
+
}
|
|
218
|
+
|
|
194
219
|
/** Recent track ids, newest first — used to avoid repeats. */
|
|
195
220
|
recentIds(limit = 50) {
|
|
196
221
|
return this.state.history.slice(0, limit).map((entry) => entry.id);
|
|
197
222
|
}
|
|
198
223
|
|
|
199
|
-
/** Most-played artists, most frequent first. */
|
|
224
|
+
/** Most-played artists, most frequent first. Only plays heard through count. */
|
|
200
225
|
topArtists(limit = 8) {
|
|
201
|
-
|
|
202
|
-
for (const entry of this.state.history.slice(0, 150)) {
|
|
203
|
-
for (const artist of entry.artists) counts.set(artist, (counts.get(artist) ?? 0) + 1);
|
|
204
|
-
}
|
|
205
|
-
return [...counts.entries()]
|
|
226
|
+
return [...this.heardArtists().entries()]
|
|
206
227
|
.sort((a, b) => b[1] - a[1])
|
|
207
228
|
.slice(0, limit)
|
|
208
229
|
.map(([artist]) => artist);
|
|
209
230
|
}
|
|
210
231
|
|
|
232
|
+
/** Artist → plays heard through, among the recent history. */
|
|
233
|
+
heardArtists(window = 150) {
|
|
234
|
+
const counts = new Map();
|
|
235
|
+
for (const entry of this.state.history.slice(0, window)) {
|
|
236
|
+
if (!isHeard(entry)) continue;
|
|
237
|
+
for (const artist of entry.artists ?? []) counts.set(artist, (counts.get(artist) ?? 0) + 1);
|
|
238
|
+
}
|
|
239
|
+
return counts;
|
|
240
|
+
}
|
|
241
|
+
|
|
211
242
|
/**
|
|
212
243
|
* One track's taste level: `liked`, `disliked`, or `none` (never rated).
|
|
213
244
|
* @param {number|string} trackId
|
|
@@ -272,19 +303,34 @@ export class SessionStore {
|
|
|
272
303
|
recordFeedback(kind, trackId) {
|
|
273
304
|
const id = Number(trackId);
|
|
274
305
|
if (!Number.isFinite(id)) return this.state.feedback;
|
|
275
|
-
if (kind === 'skips')
|
|
276
|
-
// Skips are counters, not membership: keep the newest occurrence.
|
|
277
|
-
const skips = this.state.feedback.skips;
|
|
278
|
-
skips.unshift(id);
|
|
279
|
-
if (skips.length > MAX_FEEDBACK) skips.length = MAX_FEEDBACK;
|
|
280
|
-
this.touch();
|
|
281
|
-
return this.state.feedback;
|
|
282
|
-
}
|
|
306
|
+
if (kind === 'skips') return this.recordSkip(id);
|
|
283
307
|
const level = kind === 'likes' ? 'liked' : kind === 'dislikes' ? 'disliked' : null;
|
|
284
308
|
if (!level) return this.state.feedback;
|
|
285
309
|
return this.setTaste(id, this.taste(id) === level ? 'none' : level);
|
|
286
310
|
}
|
|
287
311
|
|
|
312
|
+
/**
|
|
313
|
+
* Count a skip: the listener moved past the track early.
|
|
314
|
+
*
|
|
315
|
+
* Skips are counters, not membership, so each one is kept as an occurrence.
|
|
316
|
+
* The play it cut short is marked as well, because the history is what the
|
|
317
|
+
* DJ reads artist affinity from, and a track abandoned after ten seconds
|
|
318
|
+
* would otherwise count as one more play of that artist.
|
|
319
|
+
*
|
|
320
|
+
* @param {number|string} trackId
|
|
321
|
+
*/
|
|
322
|
+
recordSkip(trackId) {
|
|
323
|
+
const id = Number(trackId);
|
|
324
|
+
if (!Number.isFinite(id)) return this.state.feedback;
|
|
325
|
+
const skips = this.state.feedback.skips;
|
|
326
|
+
skips.unshift(id);
|
|
327
|
+
if (skips.length > MAX_FEEDBACK) skips.length = MAX_FEEDBACK;
|
|
328
|
+
const play = this.state.history.find((entry) => entry.id === id);
|
|
329
|
+
if (play) play.skipped = true;
|
|
330
|
+
this.touch();
|
|
331
|
+
return this.state.feedback;
|
|
332
|
+
}
|
|
333
|
+
|
|
288
334
|
get feedback() {
|
|
289
335
|
return this.state.feedback;
|
|
290
336
|
}
|
|
@@ -297,13 +343,26 @@ export class SessionStore {
|
|
|
297
343
|
const name = (entry) =>
|
|
298
344
|
typeof entry === 'object' ? `${entry.name} — ${(entry.artists ?? []).join('/')}` : `#${entry}`;
|
|
299
345
|
const byId = new Map(this.state.history.map((entry) => [entry.id, entry]));
|
|
346
|
+
const skipCounts = new Map();
|
|
347
|
+
for (const id of this.state.feedback.skips) skipCounts.set(id, (skipCounts.get(id) ?? 0) + 1);
|
|
348
|
+
const skippedArtists = new Map();
|
|
349
|
+
for (const entry of this.state.history.slice(0, 150)) {
|
|
350
|
+
if (!entry.skipped) continue;
|
|
351
|
+
for (const artist of entry.artists ?? []) skippedArtists.set(artist, (skippedArtists.get(artist) ?? 0) + 1);
|
|
352
|
+
}
|
|
300
353
|
return {
|
|
301
354
|
recentlyPlayed: this.state.history.slice(0, history).map(name),
|
|
302
355
|
topArtists: this.topArtists(8),
|
|
303
356
|
liked: this.state.feedback.likes.slice(0, 15).map((id) => byId.get(id)).filter(Boolean).map(name),
|
|
304
357
|
disliked: this.state.feedback.dislikes.slice(0, 15).map((id) => byId.get(id)).filter(Boolean).map(name),
|
|
358
|
+
// Newest first, one line per track however often it was skipped.
|
|
359
|
+
skipped: [...skipCounts.keys()].slice(0, 15).map((id) => byId.get(id)).filter(Boolean).map(name),
|
|
305
360
|
dislikedIds: this.state.feedback.dislikes.slice(0, 80),
|
|
306
361
|
recentIds: this.recentIds(60),
|
|
362
|
+
/** Track id → how many times it was skipped. */
|
|
363
|
+
skipCounts,
|
|
364
|
+
/** Artist → skipped plays among the recent history. */
|
|
365
|
+
skippedArtists,
|
|
307
366
|
};
|
|
308
367
|
}
|
|
309
368
|
}
|
package/lib/state.js
CHANGED
|
@@ -25,6 +25,22 @@ export const MODES = ['list', 'single', 'shuffle'];
|
|
|
25
25
|
/** A pending seek is delivered once and then cleared. */
|
|
26
26
|
const SEEK_EPSILON_MS = 1_000;
|
|
27
27
|
|
|
28
|
+
/**
|
|
29
|
+
* A manual "next" before this much of a track has played is a skip: the
|
|
30
|
+
* listener rejected the track rather than finished with it. The window is 30 s,
|
|
31
|
+
* or a quarter of the track when that is longer.
|
|
32
|
+
*/
|
|
33
|
+
const SKIP_WINDOW_MS = 30_000;
|
|
34
|
+
const SKIP_WINDOW_FRACTION = 0.25;
|
|
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
|
+
|
|
28
44
|
export class Player {
|
|
29
45
|
/**
|
|
30
46
|
* @param {object} [options]
|
|
@@ -69,6 +85,19 @@ export class Player {
|
|
|
69
85
|
* @type {(() => Promise<void>) | undefined}
|
|
70
86
|
*/
|
|
71
87
|
this.onLowQueue = undefined;
|
|
88
|
+
/**
|
|
89
|
+
* Called with a track the listener moved past early, for the taste record.
|
|
90
|
+
* @type {((track: object) => void) | undefined}
|
|
91
|
+
*/
|
|
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;
|
|
72
101
|
}
|
|
73
102
|
|
|
74
103
|
/** Subscribe to state changes. @returns {() => void} unsubscribe */
|
|
@@ -104,8 +133,12 @@ export class Player {
|
|
|
104
133
|
}
|
|
105
134
|
|
|
106
135
|
/** Replace the whole queue. `startIndex` selects what plays first. */
|
|
107
|
-
setQueue(tracks, { startIndex = 0, play = true, source } = {}) {
|
|
108
|
-
const normalized = tracks
|
|
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;
|
|
109
142
|
this.queue = normalized;
|
|
110
143
|
this.index = normalized.length === 0 ? -1 : Math.min(Math.max(startIndex, 0), normalized.length - 1);
|
|
111
144
|
this.pendingSeek = null;
|
|
@@ -117,11 +150,11 @@ export class Player {
|
|
|
117
150
|
}
|
|
118
151
|
|
|
119
152
|
/** Append tracks, de-duplicating against the queue tail. */
|
|
120
|
-
append(tracks, { source, play = true } = {}) {
|
|
153
|
+
append(tracks, { source, play = true, queuedBy } = {}) {
|
|
121
154
|
const existing = new Set(this.queue.map((track) => track.id));
|
|
122
155
|
const added = [];
|
|
123
156
|
for (const raw of tracks) {
|
|
124
|
-
const track = normalizeTrack(raw) ?? raw;
|
|
157
|
+
const track = tag(normalizeTrack(raw) ?? raw, queuedBy);
|
|
125
158
|
if (!track?.id || existing.has(track.id)) continue;
|
|
126
159
|
existing.add(track.id);
|
|
127
160
|
added.push(track);
|
|
@@ -170,14 +203,17 @@ export class Player {
|
|
|
170
203
|
/** Remove one queue position. */
|
|
171
204
|
remove(index) {
|
|
172
205
|
if (index < 0 || index >= this.queue.length) return this.snapshot();
|
|
206
|
+
const wasCurrent = index === this.index;
|
|
173
207
|
this.queue.splice(index, 1);
|
|
174
208
|
if (this.queue.length === 0) {
|
|
175
209
|
this.index = -1;
|
|
176
210
|
this.playing = false;
|
|
177
211
|
} else if (index < this.index) {
|
|
178
212
|
this.index -= 1;
|
|
179
|
-
} else if (
|
|
180
|
-
|
|
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;
|
|
181
217
|
this.pendingSeek = 0;
|
|
182
218
|
}
|
|
183
219
|
this.bump({ transport: true });
|
|
@@ -220,18 +256,70 @@ export class Player {
|
|
|
220
256
|
*/
|
|
221
257
|
move(step, { auto = false } = {}) {
|
|
222
258
|
if (this.queue.length === 0) return this.snapshot();
|
|
259
|
+
const left = this.current();
|
|
260
|
+
const skipped = !auto && step > 0 && this.#heardBriefly();
|
|
223
261
|
this.index = this.#nextIndex(step);
|
|
262
|
+
if (this.current() !== left) this.heardId = null;
|
|
224
263
|
this.pendingSeek = 0;
|
|
225
264
|
this.playing = true;
|
|
226
265
|
this.reported = { ...this.reported, position: 0, duration: 0, error: null, at: Date.now() };
|
|
227
266
|
this.bump({ transport: true });
|
|
267
|
+
if (skipped && this.current() !== left) this.#notifySkip(left);
|
|
228
268
|
if (auto) this.#maybeExtend();
|
|
229
269
|
return this.snapshot();
|
|
230
270
|
}
|
|
231
271
|
|
|
272
|
+
/**
|
|
273
|
+
* Whether the current track was heard, but only briefly.
|
|
274
|
+
*
|
|
275
|
+
* Only a reported position counts: a track the panel never started (paused,
|
|
276
|
+
* blocked by autoplay, still loading) was not listened to, so moving past it
|
|
277
|
+
* says nothing about it.
|
|
278
|
+
*/
|
|
279
|
+
#heardBriefly() {
|
|
280
|
+
const current = this.current();
|
|
281
|
+
if (!current || this.reported.trackId !== current.id) return false;
|
|
282
|
+
const position = Number(this.reported.position) || 0;
|
|
283
|
+
if (position <= 0) return false;
|
|
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
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
#notifySkip(track) {
|
|
312
|
+
try {
|
|
313
|
+
this.onSkip?.(track);
|
|
314
|
+
} catch (error) {
|
|
315
|
+
this.logger?.warn?.(`[music] skip listener failed: ${error.message}`);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
232
319
|
/** Jump to an explicit queue position. */
|
|
233
320
|
jump(index) {
|
|
234
321
|
if (index < 0 || index >= this.queue.length) return this.snapshot();
|
|
322
|
+
if (index !== this.index) this.heardId = null;
|
|
235
323
|
this.index = index;
|
|
236
324
|
this.pendingSeek = 0;
|
|
237
325
|
this.playing = true;
|
|
@@ -315,6 +403,8 @@ export class Player {
|
|
|
315
403
|
this.lastError = this.reported.error;
|
|
316
404
|
}
|
|
317
405
|
|
|
406
|
+
this.#noteHeard({ ended: Boolean(ended) });
|
|
407
|
+
|
|
318
408
|
let advanced = false;
|
|
319
409
|
if (ended || error) {
|
|
320
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.
|
|
3
|
+
"version": "0.1.6",
|
|
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",
|
|
@@ -39,6 +39,7 @@
|
|
|
39
39
|
"lib/session.js",
|
|
40
40
|
"lib/state.js",
|
|
41
41
|
"lib/dj.js",
|
|
42
|
+
"lib/cache.js",
|
|
42
43
|
"lib/likes.js",
|
|
43
44
|
"lib/router.js",
|
|
44
45
|
"lib/panel.html",
|
|
@@ -54,8 +55,8 @@
|
|
|
54
55
|
"access": "public"
|
|
55
56
|
},
|
|
56
57
|
"scripts": {
|
|
57
|
-
"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/likes.js && node --check lib/router.js",
|
|
58
|
-
"test": "node test/netease.test.mjs && node test/likes.test.mjs && node test/dj.test.mjs && node test/client.test.mjs",
|
|
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",
|
|
59
60
|
"probe:headers": "node scripts/probe-headers.mjs",
|
|
60
61
|
"test:live": "node test/host.test.mjs",
|
|
61
62
|
"test:all": "npm test && npm run test:live"
|