@audiofool/moondog 0.4.0-beta.2 → 0.4.0-beta.4

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.
Files changed (96) hide show
  1. package/README.md +19 -8
  2. package/package.json +1 -1
  3. package/scripts/moondog.mjs +130 -106
  4. package/src/core/apple-library-source-status.mjs +64 -18
  5. package/src/core/apple-projection-domain-services.mjs +67 -52
  6. package/src/core/capability-catalog.mjs +18 -2
  7. package/src/core/import-source-history.mjs +28 -0
  8. package/src/core/library-draft.mjs +16 -0
  9. package/src/core/library-names.mjs +12 -0
  10. package/src/core/library-store.mjs +361 -23
  11. package/src/core/listener-avoids.mjs +31 -0
  12. package/src/core/listening-action.mjs +41 -0
  13. package/src/core/listening-moment.mjs +67 -0
  14. package/src/core/listening-now.mjs +69 -28
  15. package/src/core/listening-profile-domain-services.mjs +32 -18
  16. package/src/core/listening-scope.mjs +119 -0
  17. package/src/core/moondog-application.mjs +1045 -270
  18. package/src/core/play-follower.mjs +104 -0
  19. package/src/core/portable-playlist.mjs +125 -0
  20. package/src/core/profile-discovery-draft.mjs +35 -0
  21. package/src/core/track-title.mjs +70 -4
  22. package/src/i18n/import-history.mjs +647 -0
  23. package/src/i18n/messages/de.mjs +3 -3
  24. package/src/i18n/messages/en.mjs +3 -3
  25. package/src/i18n/messages/es.mjs +3 -3
  26. package/src/i18n/messages/fr.mjs +3 -3
  27. package/src/i18n/messages/it.mjs +3 -3
  28. package/src/i18n/messages/ja.mjs +3 -3
  29. package/src/i18n/messages/ko.mjs +3 -3
  30. package/src/i18n/messages/pt.mjs +3 -3
  31. package/src/i18n/messages/zh-Hant.mjs +3 -3
  32. package/src/i18n/messages/zh.mjs +3 -3
  33. package/src/i18n/screen/es.mjs +90 -26
  34. package/src/i18n/screen/ja.mjs +89 -25
  35. package/src/i18n/screen/pt.mjs +90 -26
  36. package/src/i18n/screen/zh.mjs +89 -25
  37. package/src/importers/apple-music-library/import-batch.mjs +64 -32
  38. package/src/importers/apple-music-library/normalize.mjs +36 -6
  39. package/src/importers/apple-music-library/save-time.mjs +17 -0
  40. package/src/importers/zip-reader.mjs +24 -2
  41. package/src/integrations/apple-music/catalog-playlist-reader.mjs +111 -0
  42. package/src/integrations/apple-music/catalog.mjs +84 -25
  43. package/src/integrations/apple-music/music-app-listening.mjs +107 -0
  44. package/src/integrations/apple-music/music-app.mjs +6 -2
  45. package/src/integrations/apple-music/song-id.mjs +13 -0
  46. package/src/integrations/apple-music/terminal-preview-player.mjs +154 -44
  47. package/src/integrations/listenbrainz/history-file.mjs +63 -35
  48. package/src/integrations/netease/ncm-cli-player.mjs +355 -68
  49. package/src/integrations/netease/queue-occurrence.mjs +138 -0
  50. package/src/integrations/playlist-links.mjs +93 -30
  51. package/src/integrations/public-playlists.mjs +21 -15
  52. package/src/integrations/spotify/account-data-history.mjs +9 -10
  53. package/src/integrations/spotify/account-data-profile.mjs +1 -0
  54. package/src/integrations/spotify/extended-streaming-history.mjs +57 -52
  55. package/src/integrations/spotify/history-archive.mjs +8 -18
  56. package/src/integrations/spotify/library-snapshot.mjs +2 -1
  57. package/src/integrations/spotify/service.mjs +29 -11
  58. package/src/integrations/spotify/web-api-client.mjs +2 -2
  59. package/src/integrations/stable-audio/local-generator.mjs +13 -5
  60. package/src/integrations/youtube-music/takeout.mjs +12 -8
  61. package/src/memory/local-memory-store.mjs +479 -27
  62. package/src/memory/reflection-worker.mjs +19 -0
  63. package/src/profile/apple-library-import.mjs +56 -2
  64. package/src/profile/history-import.mjs +58 -27
  65. package/src/profile/listener-corrections.mjs +2 -4
  66. package/src/profile/listener-profile-build.mjs +133 -46
  67. package/src/profile/listener-profile-store.mjs +57 -4
  68. package/src/profile/listener-profile-verification.mjs +11 -5
  69. package/src/profile/listener-profile-worker.mjs +36 -10
  70. package/src/profile/listening-history-store.mjs +975 -354
  71. package/src/profile/listening-profile-projection.mjs +130 -160
  72. package/src/profile/local-file-import.mjs +172 -0
  73. package/src/profile/moondog-suggestions.mjs +40 -11
  74. package/src/profile/profile-exploration.mjs +36 -6
  75. package/src/profile/recorded-measures.mjs +5 -0
  76. package/src/profile/spotify-archive-taste.mjs +41 -65
  77. package/src/runtime/pi/agent-runtime.mjs +368 -221
  78. package/src/runtime/pi/custom-endpoints.mjs +30 -8
  79. package/src/runtime/pi/memory-agent-runtime.mjs +45 -3
  80. package/src/runtime/pi/moondog-model.mjs +6 -0
  81. package/src/runtime/pi/playback-rules.mjs +100 -0
  82. package/src/runtime/pi/profile-build-runtime.mjs +85 -24
  83. package/src/surfaces/cli/brand-components.mjs +9 -6
  84. package/src/surfaces/cli/command-completions.mjs +8 -1
  85. package/src/surfaces/cli/format-output.mjs +207 -34
  86. package/src/surfaces/cli/history-import-view.mjs +130 -21
  87. package/src/surfaces/cli/listenbrainz-command.mjs +7 -2
  88. package/src/surfaces/cli/listener-profile-command.mjs +67 -8
  89. package/src/surfaces/cli/listening-menu.mjs +3 -0
  90. package/src/surfaces/cli/profile-command.mjs +1 -0
  91. package/src/surfaces/cli/spotify-command.mjs +17 -25
  92. package/src/surfaces/cli/taste-period.mjs +22 -0
  93. package/src/surfaces/cli/taste-profile-model.mjs +52 -32
  94. package/src/surfaces/cli/tui.mjs +557 -170
  95. package/src/surfaces/html/tasteprint.mjs +181 -93
  96. package/src/surfaces/import-source-history.mjs +80 -0
@@ -8,6 +8,9 @@ import { access, constants, readFile, stat } from "node:fs/promises";
8
8
  import path from "node:path";
9
9
 
10
10
  import { environmentPathKey } from "../../core/host.mjs";
11
+ import { ARTIST_CREDIT_SEPARATORS } from "../../core/listener-avoids.mjs";
12
+ import { catalogNameKey as catalogKey, matchesLibrarySong, normalizedTrackTitle } from "../../core/track-title.mjs";
13
+ import { NeteaseQueueOccurrence } from "./queue-occurrence.mjs";
11
14
 
12
15
  const COMMAND_TIMEOUT_MS = 20_000;
13
16
  // Where Homebrew and npm put ncm-cli, the node it runs on, and mpv, for a PATH that lacks them.
@@ -103,11 +106,19 @@ function cliRunner({ environment }) {
103
106
  };
104
107
  }
105
108
 
106
- function checked(result, what) {
109
+ // These replies explicitly reject a recording. A network error or a silent daemon cannot establish that.
110
+ const recordingRefusal = /^(?:暂无版权|没有版权|无版权)[。!!]?$/u;
111
+ const namedRecordingRefusal = /(?:歌曲|单曲|曲目)(?:暂无版权|没有版权|无版权|已下架)|\b(?:this|the) (?:song|track|recording) is (?:unavailable|not (?:available|playable))\b/iu;
112
+
113
+ function checked(result, what, { playingSong = false } = {}) {
107
114
  const message = String(result?.message ?? "").trim();
108
115
  if (result?.success === false || (result?.code !== undefined && result.code !== 200)) {
109
116
  if (/请求总量超限/u.test(message)) throw failure("netease_rate_limited", "NetEase says today's request limit is used up (请求总量超限). Stop and tell the listener.");
110
- if (/登录|login|token|授权/iu.test(message)) throw failure("netease_signed_out", `NetEase is not signed in (${message}). The listener can run: ncm-cli login`);
117
+ if (result?.code === 429) throw failure("netease_rate_limited", "NetEase is limiting requests. Try again later.");
118
+ if (result?.code === 401 || /登录|login|token|授权/iu.test(message)) throw failure("netease_signed_out", `NetEase is not signed in (${message}). The listener can run: ncm-cli login`);
119
+ if (playingSong && !(result?.code >= 500) && (recordingRefusal.test(message) || namedRecordingRefusal.test(message))) {
120
+ throw failure("netease_song_unavailable", `NetEase could not ${what}: ${message}`);
121
+ }
111
122
  throw failure("netease_failed", `NetEase could not ${what}${message ? `: ${message}` : "."}`);
112
123
  }
113
124
  return result;
@@ -131,14 +142,46 @@ function songOf(record) {
131
142
 
132
143
  const fold = (value) => String(value ?? "").normalize("NFKC").toLocaleLowerCase("en-US").replace(/[\s\p{P}\p{S}]+/gu, "");
133
144
 
145
+ function matchesSavedRecording(song, item) {
146
+ return (item.recordingId == null || [song.id, song.original_id].includes(String(item.recordingId))) &&
147
+ matchesLibrarySong({ title: item.title, artist_credit: item.artist }, song.title, song.artists);
148
+ }
149
+
150
+ // A title such as "Pine Mountain" is a different song. Only a labeled recording can extend
151
+ // the requested title, including NetEase's covers, remixes and Chinese versions such as (治愈版).
152
+ const lastLabel = /(?:\([^()]+\)|\[[^\]]+\]|\s+[-\u2013\u2014]\s+[^-\u2013\u2014]+)$/u;
153
+ const neteaseEdition = /(?:\b(?:cover|remix|mix|instrumental|karaoke|ver\.?)|版(?:本)?|翻唱|伴奏|[现現][场場]|混音)\s*[)\]]?$|\b(?:cover|remix) by\s/iu;
154
+
155
+ function isRecordingVersion(title, wanted) {
156
+ let name = title.normalize("NFKC").replaceAll("【", "[").replaceAll("】", "]").trim();
157
+ let suffix;
158
+ while ((suffix = name.match(lastLabel))) {
159
+ if (catalogKey(normalizedTrackTitle(name)) === catalogKey(name) && !neteaseEdition.test(suffix[0])) break;
160
+ name = name.slice(0, suffix.index).trimEnd();
161
+ if (catalogKey(name) === wanted) return true;
162
+ }
163
+ return false;
164
+ }
165
+
134
166
  // The best playable recording of a named song: by the named artist before another artist's, and
135
167
  // the exact title before a longer one such as "稻香(治愈版)".
136
- function pick(songs, { title, artist }) {
137
- const wantTitle = fold(title);
138
- const wantArtist = fold(artist);
139
- const exactTitle = (song) => fold(song.title) === wantTitle;
140
- const titled = songs.filter((song) => exactTitle(song) || fold(song.title).startsWith(wantTitle));
141
- const byArtist = (song) => !wantArtist || song.artists.some((name) => fold(name) === wantArtist);
168
+ function pick(songs, { title, artist }, savedItem) {
169
+ if (savedItem) {
170
+ const matches = songs.filter(song => matchesSavedRecording(song, savedItem));
171
+ const song = matches.find(song => song.playable);
172
+ return song ? { song, other_artist: false } : { song: null, unplayable: matches.length > 0 };
173
+ }
174
+ const wantTitle = catalogKey(title);
175
+ if (!wantTitle) return { song: null, unplayable: false };
176
+ const exactTitle = song => catalogKey(song.title) === wantTitle;
177
+ const titled = songs.filter(song => exactTitle(song) || isRecordingVersion(song.title, wantTitle));
178
+ const wantArtist = catalogKey(artist);
179
+ const requestedArtists = artist.normalize("NFKC").split(ARTIST_CREDIT_SEPARATORS)
180
+ .flatMap(name => name.split(/\s+(?:and|x|×)\s+/iu)).map(catalogKey).filter(Boolean);
181
+ const byArtist = song => {
182
+ const credits = song.artists.map(catalogKey);
183
+ return !wantArtist || credits.includes(wantArtist) || (requestedArtists.length > 1 && requestedArtists.every(name => credits.includes(name)));
184
+ };
142
185
  const playable = titled.filter((song) => song.playable);
143
186
  const own = playable.filter(byArtist);
144
187
  const found = own.find(exactTitle) ?? own[0];
@@ -168,15 +211,23 @@ export function createNeteasePlayer({
168
211
  // so they run one at a time.
169
212
  let line = Promise.resolve();
170
213
  let running = 0;
171
- const run = (args) => {
214
+ const run = (args, beforeDispatch) => {
172
215
  running += 1;
173
- const result = line.then(() => runCli(args)).finally(() => { running -= 1; });
216
+ const result = line.then(() => { beforeDispatch?.(); return runCli(args); }).finally(() => { running -= 1; });
174
217
  line = result.catch(() => {});
175
218
  return result;
176
219
  };
177
220
  let status = { state: "unknown", message: null };
178
221
  let queue = [];
179
222
  let index = -1;
223
+ // Separate occurrences can use the same cached song. Only the original local receipt
224
+ // can bind its matching suggestion callbacks, including the nulls for listener choices.
225
+ const receiptEntries = new WeakMap();
226
+ let active = null;
227
+ let playAttempt = 0;
228
+ let untilStop = new AbortController();
229
+ let starting = false;
230
+ let readRevision = 0;
180
231
  // The last state read while a song played, to tell the end of a song from a pause.
181
232
  let last = null;
182
233
  const known = new Map();
@@ -188,61 +239,208 @@ export function createNeteasePlayer({
188
239
  while (known.size > KNOWN_SONGS) known.delete(known.keys().next().value);
189
240
  };
190
241
  const titleOf = (now) => (typeof now?.title === "string" && now.title.trim() ? now.title.trim() : null);
191
- const isSong = (now, song) => Boolean(song && titleOf(now)?.startsWith(song.title));
242
+ const isSong = (now, song) => {
243
+ const title = titleOf(now);
244
+ if (!title || !song) return false;
245
+ if (title === song.title) return true;
246
+ const prefix = `${song.title} - `;
247
+ if (!title.startsWith(prefix)) return false;
248
+ const credit = fold(title.slice(prefix.length));
249
+ return [song.artists.join(", "), ...song.artists].some((artist) => fold(artist) === credit);
250
+ };
192
251
 
193
- async function state() {
252
+ let keepAlive = null;
253
+ async function state(onCurrent) {
254
+ const readQueue = queue;
255
+ const readIndex = index;
256
+ const timer = keepAlive;
257
+ const revision = readRevision;
258
+ const loading = starting;
194
259
  const result = checked(await run(["state"]), "read what is playing");
195
- return result.state ?? {};
260
+ const now = result.state ?? {};
261
+ // Playback controls can replace the queue or stop this timer while the daemon answers.
262
+ if (loading || starting || revision !== readRevision || readQueue !== queue || readIndex !== index || timer !== keepAlive) return now;
263
+ const expected = queue[index];
264
+ // A different recording took the daemon away from this queue. A later play of our
265
+ // old song by the listener must not bring its former Up next back.
266
+ if (expected && titleOf(now) && !isSong(now, expected.song)) {
267
+ active?.discard();
268
+ active = null;
269
+ queue = [];
270
+ index = -1;
271
+ last = null;
272
+ letGo();
273
+ } else {
274
+ if (expected && active === expected) {
275
+ if (isSong(now, expected.song)) expected.observe(now);
276
+ else expected.discard(); // An empty daemon state also follows a stop or loss of the player.
277
+ }
278
+ if (onCurrent) await onCurrent(now);
279
+ }
280
+ return now;
196
281
  }
197
282
 
198
- let keepAlive = null;
199
283
  function stayConnected() {
200
284
  if (keepAlive) return;
201
285
  let idle = 0;
202
- keepAlive = setInterval(async () => {
203
- // A command already running keeps the daemon company.
204
- if (running) return;
205
- const now = await state().catch(() => null);
206
- if (!now) return;
207
- // The song that played to its end has stopped: the next queued one starts.
208
- const ended = last && now.status !== "playing" && Number.isFinite(last.duration) && last.position >= last.duration - keepAliveMs / 1000 - 1.5;
286
+ const follow = async (now) => {
287
+ // ncm-cli also calls a pause "stopped". A song parked partway through still
288
+ // owns its queue, even when it was paused just before the end.
289
+ const duration = last?.duration;
290
+ const parked = titleOf(now) && now.position > 0 && now.position < duration;
291
+ const ended = now.status !== "playing" && !parked && Number.isFinite(duration) && duration > 0 &&
292
+ last.position >= duration - keepAliveMs / 1000 - 1.5;
209
293
  if (ended && index + 1 < queue.length) {
210
- await playAt(index + 1).catch(() => {});
294
+ const owner = active;
295
+ try { await playForward(index + 1, false); }
296
+ catch { if (active === owner) last = null; } // A service error needs a new request, not a retry on every poll.
211
297
  return;
212
298
  }
213
- if (now.status === "playing") last = { position: Number(now.position) || 0, duration: Number(now.duration) };
299
+ if (now.status === "playing" && isSong(now, queue[index]?.song)) last = { position: Number(now.position) || 0, duration: Number(now.duration) };
214
300
  idle = now.status === "playing" || titleOf(now) ? 0 : idle + 1;
215
301
  if (idle >= 2) letGo();
302
+ };
303
+ const timer = setInterval(() => {
304
+ // A command already running keeps the daemon company.
305
+ if (!running && keepAlive === timer) return state(follow).catch(() => {});
216
306
  }, keepAliveMs);
217
- keepAlive.unref?.();
307
+ keepAlive = timer;
308
+ timer.unref?.();
218
309
  }
219
310
  function letGo() {
220
311
  clearInterval(keepAlive);
221
312
  keepAlive = null;
222
313
  }
314
+ function clearQueue() {
315
+ untilStop.abort();
316
+ untilStop = new AbortController();
317
+ ++playAttempt;
318
+ ++readRevision;
319
+ starting = false;
320
+ active?.discard();
321
+ active = null;
322
+ letGo();
323
+ queue = [];
324
+ index = -1;
325
+ last = null;
326
+ }
223
327
 
224
328
  // Plays one queued song and waits until the player reports it from its start, so a song of
225
329
  // the same title still finishing is not taken for it.
226
- async function playAt(position) {
227
- const song = queue[position];
228
- checked(await run(["play", "--song", "--encrypted-id", song.id, "--original-id", song.original_id]), `play ${song.title}`);
229
- index = position;
230
- last = null;
231
- for (let waited = 0; waited < START_WAIT_MS; waited += START_POLL_MS) {
232
- const now = await state();
233
- if (now.status === "playing" && isSong(now, song) && (Number(now.position) || 0) < 5) {
234
- stayConnected();
235
- return;
330
+ async function playAt(position, explicit = true, { currentState, beforeDispatch } = {}) {
331
+ const entry = queue[position], previous = active;
332
+ if (!entry) throw failure("netease_failed", "That song is no longer queued.");
333
+ const song = entry.song;
334
+ const attempt = ++playAttempt;
335
+ let awaitingStart = false;
336
+ ++readRevision;
337
+ starting = true;
338
+ const notStarted = () => failure("netease_not_started", `NetEase did not confirm that ${song.title} started.`);
339
+ const checkTarget = () => { if (attempt !== playAttempt || queue[position] !== entry) throw notStarted(); };
340
+ try {
341
+ let repeatPosition = null;
342
+ if (explicit && previous && (previous.tracking || previous.song.title === song.title)) {
343
+ // A different client may have taken the daemon. Only an owned final reading
344
+ // can attach a manual handoff to this occurrence.
345
+ let before = currentState;
346
+ if (!before) {
347
+ try { before = checked(await run(["state"]), "read what is playing").state; } catch { /* The new song can still play. */ }
348
+ checkTarget();
349
+ if (isSong(before, previous.song)) previous.observe(before);
350
+ else previous.discard();
351
+ }
352
+ if (isSong(before, song) && before.status === "playing" && Number.isFinite(before.position) && before.position < 5) {
353
+ repeatPosition = before.position;
354
+ }
355
+ }
356
+ const result = await run(["play", "--song", "--encrypted-id", song.id, "--original-id", song.original_id], () => {
357
+ checkTarget();
358
+ beforeDispatch?.(entry);
359
+ });
360
+ checkTarget();
361
+ checked(result, `play ${song.title}`, { playingSong: true });
362
+ awaitingStart = true;
363
+ index = -1;
364
+ last = null;
365
+ active = null;
366
+ for (let waited = 0; waited < START_WAIT_MS; waited += START_POLL_MS) {
367
+ const now = await state();
368
+ checkTarget();
369
+ const playingTarget = now.status === "playing" && isSong(now, song);
370
+ const startSeconds = Number(now.position) || 0;
371
+ const measured = Number.isFinite(now.position) && now.position >= 0;
372
+ if (!playingTarget) repeatPosition = null;
373
+ // mpv can still name the last copy. If it was already audible, its clock
374
+ // must reset before the same recording counts as a new queue occurrence.
375
+ const reset = repeatPosition === null || repeatPosition === 0 ||
376
+ (measured && startSeconds <= repeatPosition - Math.min(0.25, repeatPosition / 2));
377
+ if (playingTarget && startSeconds < 5 && reset) {
378
+ if (!measured || repeatPosition === 0) {
379
+ // A missing clock or two identical starts at zero cannot identify a new occurrence.
380
+ previous?.discard();
381
+ entry.discard();
382
+ } else if (explicit && previous !== entry) previous?.handoff();
383
+ else previous?.discard();
384
+ index = position;
385
+ active = entry;
386
+ entry.start(now);
387
+ stayConnected();
388
+ return;
389
+ }
390
+ await wait(START_POLL_MS);
391
+ }
392
+ throw notStarted();
393
+ } finally {
394
+ if (attempt === playAttempt) {
395
+ starting = false;
396
+ if (awaitingStart && !active && queue[position] === entry) {
397
+ previous?.discard();
398
+ queue = [];
399
+ letGo();
400
+ }
401
+ }
402
+ }
403
+ }
404
+
405
+ // A refused recording never started. Move past it only while this set still owns the next action.
406
+ async function playForward(position, explicit = true, { currentState, beforeDispatch, onUnavailable } = {}) {
407
+ const selected = queue, owner = active;
408
+ while (selected[position]) {
409
+ const entry = selected[position];
410
+ const start = playAt(position, explicit, { currentState, beforeDispatch });
411
+ const attempt = playAttempt;
412
+ try {
413
+ await start;
414
+ return true;
415
+ } catch (error) {
416
+ if (error.code !== "netease_song_unavailable" || attempt !== playAttempt || queue !== selected ||
417
+ selected[position] !== entry || active !== owner) throw error;
418
+ }
419
+ entry.discard();
420
+ selected.splice(position, 1);
421
+ ++readRevision;
422
+ onUnavailable?.(entry.song);
423
+ if (!selected[position]) return false;
424
+ currentState = checked(await run(["state"]), "read what is playing").state;
425
+ const idle = currentState?.status === "stopped" && !titleOf(currentState);
426
+ if (queue !== selected || attempt !== playAttempt || active !== owner || (!idle && !isSong(currentState, owner?.song))) {
427
+ throw failure("netease_transport_changed", "NetEase playback changed before the next song could start.");
236
428
  }
237
- await wait(START_POLL_MS);
238
429
  }
239
- throw failure("netease_not_started", `NetEase did not start ${song.title}. It may not be playable here, most often for copyright.`);
430
+ return false;
240
431
  }
241
432
 
242
433
  const player = {
243
434
  status: () => ({ ...status }),
244
435
  ready: () => status.state === "ready",
245
436
 
437
+ bindSuggestionOutcomes(receipt, bindings) {
438
+ const entries = receiptEntries.get(receipt);
439
+ if (!entries || !Array.isArray(bindings) || bindings.length !== entries.length) return;
440
+ receiptEntries.delete(receipt);
441
+ entries.forEach((entry, index) => entry.bind(bindings[index]));
442
+ },
443
+
246
444
  async check() {
247
445
  try {
248
446
  const result = await run(["login", "--check"]);
@@ -270,70 +468,154 @@ export function createNeteasePlayer({
270
468
  * playing. Songs NetEase marks as not playable are never sent to the player, nor songs
271
469
  * allow(song) refuses, such as the listener's Avoids; those are only counted. Before a lookup,
272
470
  * allow gets the title and artist asked for, as { title, artist_credit }. beforePlay runs just
273
- * before a song starts, which a queue with nothing loaded does too.
471
+ * before a song starts, which a queue with nothing loaded does too. A Library item must
472
+ * match the saved title, credit and any retained original or encrypted recordingId.
274
473
  */
275
- async play({ items = [], mode = "play", intent, allow = () => true, beforePlay } = {}) {
474
+ async play({ items = [], mode = "play", intent, allow = () => true, knownTrack, beforePlay, startIfIdle = true, library = false, signal: callerSignal } = {}) {
475
+ const signal = callerSignal ? AbortSignal.any([callerSignal, untilStop.signal]) : untilStop.signal;
476
+ signal.throwIfAborted();
276
477
  const found = [];
277
478
  const unplayable = [];
278
479
  const notFound = [];
279
480
  let avoided = 0;
481
+ let skippedKnown = 0;
482
+ const accept = (song) => {
483
+ if (!allow(song)) { avoided += 1; return false; }
484
+ if (knownTrack?.(song)) { skippedKnown += 1; return false; }
485
+ return true;
486
+ };
280
487
  for (const item of items.slice(0, 20)) {
488
+ signal.throwIfAborted();
281
489
  if (item?.id) {
282
490
  const song = known.get(String(item.id));
283
- if (!song) notFound.push({ id: String(item.id) });
491
+ if (!song || (library && !matchesSavedRecording(song, item))) notFound.push({ id: String(item.id) });
284
492
  else if (!song.playable) unplayable.push(song);
285
- else if (!allow(song)) avoided += 1;
286
- else found.push({ song, other_artist: false });
493
+ else if (accept(song)) found.push({ song, other_artist: false });
287
494
  continue;
288
495
  }
289
496
  const wanted = { title: String(item?.title ?? ""), artist: String(item?.artist ?? "") };
290
497
  if (!allow({ title: wanted.title, artist_credit: wanted.artist })) { avoided += 1; continue; }
291
- const result = pick(await player.search({ query: `${wanted.title} ${wanted.artist}`.trim(), limit: 10, intent }), wanted);
292
- if (result.song && !allow(result.song)) avoided += 1;
293
- else if (result.song) found.push(result);
498
+ const songs = await player.search({ query: `${wanted.title} ${wanted.artist}`.trim(), limit: 10, intent });
499
+ signal.throwIfAborted();
500
+ const result = pick(songs, wanted, library ? item : null);
501
+ if (result.song) {
502
+ if (accept(result.song)) found.push(result);
503
+ }
294
504
  else if (result.unplayable) unplayable.push({ title: wanted.title, artists: [wanted.artist].filter(Boolean) });
295
505
  else notFound.push(wanted);
296
506
  }
297
- const songs = found.map((entry) => entry.song);
298
507
  let outcome = "none";
299
- if (songs.length) {
300
- // A paused song still has its title; with nothing loaded, a queue request plays.
301
- const loaded = mode === "queue" && index >= 0 && titleOf(await state()) !== null;
302
- if (loaded) {
303
- queue = [...queue, ...songs];
304
- outcome = "queued";
508
+ let reason;
509
+ let accepted = [];
510
+ let entries = [];
511
+ if (found.length) {
512
+ // An owned, paused song keeps its queue. A song started elsewhere stays with its player.
513
+ const current = mode === "queue" ? await state() : null;
514
+ signal.throwIfAborted();
515
+ const loaded = isSong(current, queue[index]?.song);
516
+ const canStart = mode !== "queue" || (startIfIdle && current.status !== "playing" && !titleOf(current));
517
+ if (loaded || canStart) {
518
+ accepted = found.filter(({ song }) => accept(song));
519
+ if (!loaded && accepted.length && beforePlay) {
520
+ await beforePlay(signal);
521
+ signal.throwIfAborted();
522
+ accepted = accepted.filter(({ song }) => accept(song));
523
+ }
524
+ entries = accepted.map(({ song }) => new NeteaseQueueOccurrence(song, keepAliveMs));
525
+ if (entries.length) {
526
+ const oldQueue = queue, oldIndex = index;
527
+ const replacement = loaded ? [...queue, ...entries] : [...entries];
528
+ queue = replacement;
529
+ if (!loaded) {
530
+ let refused = 0;
531
+ try {
532
+ await playForward(0, true, { beforeDispatch: () => signal.throwIfAborted(),
533
+ onUnavailable: song => { refused++; unplayable.push({ title: song.title, artists: song.artists }); } });
534
+ entries = entries.slice(refused);
535
+ accepted = accepted.slice(refused);
536
+ } finally {
537
+ // A refusal left the old queue playing. An unconfirmed start has no owned next action.
538
+ if (queue === replacement && (!active || active === oldQueue[oldIndex])) {
539
+ queue = active ? oldQueue : [];
540
+ index = active ? oldIndex : -1;
541
+ }
542
+ }
543
+ }
544
+ if (entries.length) outcome = loaded ? "queued" : "playing";
545
+ }
305
546
  } else {
306
- await beforePlay?.();
307
- queue = songs;
308
- await playAt(0);
309
- outcome = "playing";
547
+ if (!startIfIdle) outcome = "not_playing";
548
+ if (titleOf(current)) reason = "external_playback";
310
549
  }
311
550
  }
312
- return {
551
+ const receipt = {
313
552
  mode: outcome,
314
- songs: found.map(({ song, other_artist: otherArtist }) => ({ ...song, other_artist: otherArtist })),
553
+ ...(reason ? { reason } : {}),
554
+ songs: accepted.map(({ song, other_artist: otherArtist }) => ({ ...song, other_artist: otherArtist })),
315
555
  unplayable,
316
556
  not_found: notFound,
317
557
  ...(avoided ? { skipped_avoided_count: avoided } : {}),
558
+ ...(skippedKnown ? { skipped_known_count: skippedKnown } : {}),
318
559
  };
560
+ if (entries.length) receiptEntries.set(receipt, entries);
561
+ return receipt;
319
562
  },
320
563
 
321
- async pause() { checked(await run(["pause"]), "pause"); },
564
+ async pause() {
565
+ const entry = active;
566
+ ++readRevision;
567
+ checked(await run(["pause"]), "pause");
568
+ if (entry === active) entry?.setPaused(true);
569
+ },
322
570
  async resume() {
571
+ const entry = active;
572
+ ++readRevision;
323
573
  checked(await run(["resume"]), "resume");
574
+ if (entry === active) entry?.setPaused(false);
324
575
  stayConnected();
325
576
  },
326
577
  // beforePlay runs just before a song starts, so the other players go quiet only for one.
327
578
  async next({ beforePlay } = {}) {
328
579
  if (index + 1 >= queue.length) throw failure("netease_failed", "Nothing is queued after this song.");
329
580
  await beforePlay?.();
330
- await playAt(index + 1);
581
+ if (!await playForward(index + 1)) throw failure("netease_song_unavailable", "No playable song remains in this queue.");
582
+ },
583
+ // The terminal controls only a song this adapter loaded. The state callback runs
584
+ // only while the same queue and position still own that read.
585
+ async controlOwnedPlayback(command, isSelected) {
586
+ const owner = active;
587
+ if (!owner || starting) return "idle";
588
+ let result;
589
+ let busy = false;
590
+ const act = async now => {
591
+ if (!isSelected() || active !== owner || !isSong(now, owner.song)) return;
592
+ // A queued CLI command can delay this write long enough for the daemon to change.
593
+ if (running) { busy = true; return; }
594
+ const next = queue[index + 1];
595
+ const verify = (target = next) => {
596
+ if (!isSelected() || active !== owner || queue[index] !== owner || (command === "skip" && queue[index + 1] !== target)) {
597
+ throw failure("netease_transport_changed", "The selected queue changed.");
598
+ }
599
+ };
600
+ if (command === "stop" && ["playing", "paused", "stopped"].includes(now.status)) {
601
+ checked(await run(["stop"], () => { verify(); clearQueue(); }), "stop");
602
+ result = "stopped";
603
+ } else if (command === "skip" && now.status === "playing") {
604
+ if (!next) { result = "no_next"; return; }
605
+ result = await playForward(index + 1, true, { currentState: now, beforeDispatch: verify }) ? "skipped" : "no_next";
606
+ }
607
+ };
608
+ await state(act);
609
+ if (busy && isSelected()) { busy = false; await state(act); }
610
+ return result ?? (isSelected() && !busy ? "idle" : "unavailable");
331
611
  },
332
612
  /** One playable song for a title and artist, matched as play() matches, or null. play() takes it back by id. */
333
- async find({ title, artist, intent } = {}) {
613
+ async find({ title, artist, intent, recordingId } = {}) {
334
614
  const wanted = { title: String(title ?? ""), artist: String(artist ?? "") };
335
615
  if (!wanted.title.trim()) return null;
336
- const result = pick(await player.search({ query: `${wanted.title} ${wanted.artist}`.trim(), limit: 10, intent }), wanted);
616
+ const songs = await player.search({ query: `${wanted.title} ${wanted.artist}`.trim(), limit: 10, intent });
617
+ if (recordingId) return songs.find((song) => song.playable && (song.original_id === recordingId || song.id === recordingId)) ?? null;
618
+ const result = pick(songs, wanted);
337
619
  return result.song && !result.other_artist ? result.song : null;
338
620
  },
339
621
  // A song in Up next, counted from the one after this (1 is the next): it plays now, past the ones before it.
@@ -353,17 +635,22 @@ export function createNeteasePlayer({
353
635
  if (index > 0 && (Number(now.position) || 0) <= 3) {
354
636
  await beforePlay?.();
355
637
  await playAt(index - 1);
356
- } else checked(await run(["seek", "0"]), "go back to the start");
638
+ } else {
639
+ const entry = active;
640
+ ++readRevision;
641
+ checked(await run(["seek", "0"]), "go back to the start");
642
+ if (entry === active) entry?.discard();
643
+ }
357
644
  },
358
645
  async seek({ positionMs = 0 } = {}) {
646
+ const entry = active;
647
+ ++readRevision;
359
648
  checked(await run(["seek", String(Math.max(0, Math.round(positionMs / 1000)))]), "move in the song");
649
+ if (entry === active) entry?.seek();
360
650
  last = null;
361
651
  },
362
652
  async stop() {
363
- letGo();
364
- queue = [];
365
- index = -1;
366
- last = null;
653
+ clearQueue();
367
654
  checked(await run(["stop"]), "stop");
368
655
  },
369
656
 
@@ -375,7 +662,7 @@ export function createNeteasePlayer({
375
662
  const now = await state();
376
663
  const title = titleOf(now);
377
664
  if (!title) return { state: "stopped", song: null, position_ms: 0, next: [] };
378
- const queued = queue[index];
665
+ const queued = queue[index]?.song;
379
666
  // ncm-cli names the song "title - artist"; a song played from elsewhere is shown by that name.
380
667
  const ours = isSong(now, queued);
381
668
  const song = ours ? queued : { id: null, original_id: null, title: title.replace(/\s+-\s+[^-]+$/u, ""),
@@ -384,7 +671,7 @@ export function createNeteasePlayer({
384
671
  state: now.status === "playing" ? "playing" : "paused",
385
672
  song: { ...song, duration_ms: Number.isFinite(now.duration) ? Math.round(now.duration * 1000) : song.duration_ms },
386
673
  position_ms: Number.isFinite(now.position) ? Math.round(now.position * 1000) : 0,
387
- next: ours ? queue.slice(index + 1) : [],
674
+ next: ours ? queue.slice(index + 1).map(entry => entry.song) : [],
388
675
  };
389
676
  },
390
677
  };