@audiofool/moondog 0.4.0-beta.3 → 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.
- package/README.md +19 -8
- package/package.json +1 -1
- package/scripts/moondog.mjs +95 -103
- package/src/core/apple-library-source-status.mjs +64 -18
- package/src/core/apple-projection-domain-services.mjs +63 -52
- package/src/core/capability-catalog.mjs +18 -2
- package/src/core/import-source-history.mjs +28 -0
- package/src/core/library-draft.mjs +16 -0
- package/src/core/library-names.mjs +12 -0
- package/src/core/library-store.mjs +361 -23
- package/src/core/listener-avoids.mjs +31 -0
- package/src/core/listening-action.mjs +41 -0
- package/src/core/listening-moment.mjs +67 -0
- package/src/core/listening-now.mjs +69 -28
- package/src/core/listening-profile-domain-services.mjs +28 -18
- package/src/core/listening-scope.mjs +119 -0
- package/src/core/moondog-application.mjs +1003 -267
- package/src/core/play-follower.mjs +73 -37
- package/src/core/portable-playlist.mjs +125 -0
- package/src/core/profile-discovery-draft.mjs +35 -0
- package/src/core/track-title.mjs +70 -4
- package/src/i18n/import-history.mjs +647 -0
- package/src/i18n/messages/de.mjs +3 -3
- package/src/i18n/messages/en.mjs +3 -3
- package/src/i18n/messages/es.mjs +3 -3
- package/src/i18n/messages/fr.mjs +3 -3
- package/src/i18n/messages/it.mjs +3 -3
- package/src/i18n/messages/ja.mjs +3 -3
- package/src/i18n/messages/ko.mjs +3 -3
- package/src/i18n/messages/pt.mjs +3 -3
- package/src/i18n/messages/zh-Hant.mjs +3 -3
- package/src/i18n/messages/zh.mjs +3 -3
- package/src/i18n/screen/es.mjs +89 -26
- package/src/i18n/screen/ja.mjs +88 -25
- package/src/i18n/screen/pt.mjs +89 -26
- package/src/i18n/screen/zh.mjs +88 -25
- package/src/importers/apple-music-library/import-batch.mjs +64 -32
- package/src/importers/apple-music-library/normalize.mjs +36 -6
- package/src/importers/apple-music-library/save-time.mjs +17 -0
- package/src/importers/zip-reader.mjs +24 -2
- package/src/integrations/apple-music/catalog-playlist-reader.mjs +111 -0
- package/src/integrations/apple-music/catalog.mjs +84 -25
- package/src/integrations/apple-music/song-id.mjs +13 -0
- package/src/integrations/apple-music/terminal-preview-player.mjs +154 -44
- package/src/integrations/listenbrainz/history-file.mjs +63 -35
- package/src/integrations/netease/ncm-cli-player.mjs +355 -68
- package/src/integrations/netease/queue-occurrence.mjs +138 -0
- package/src/integrations/playlist-links.mjs +93 -30
- package/src/integrations/public-playlists.mjs +21 -15
- package/src/integrations/spotify/account-data-history.mjs +9 -10
- package/src/integrations/spotify/account-data-profile.mjs +1 -0
- package/src/integrations/spotify/extended-streaming-history.mjs +57 -52
- package/src/integrations/spotify/history-archive.mjs +8 -18
- package/src/integrations/spotify/library-snapshot.mjs +2 -1
- package/src/integrations/spotify/service.mjs +29 -11
- package/src/integrations/spotify/web-api-client.mjs +2 -2
- package/src/integrations/stable-audio/local-generator.mjs +13 -5
- package/src/integrations/youtube-music/takeout.mjs +12 -8
- package/src/memory/local-memory-store.mjs +479 -27
- package/src/memory/reflection-worker.mjs +1 -0
- package/src/profile/apple-library-import.mjs +56 -2
- package/src/profile/history-import.mjs +58 -27
- package/src/profile/listener-corrections.mjs +2 -4
- package/src/profile/listener-profile-build.mjs +128 -45
- package/src/profile/listener-profile-store.mjs +25 -4
- package/src/profile/listener-profile-verification.mjs +11 -5
- package/src/profile/listener-profile-worker.mjs +24 -8
- package/src/profile/listening-history-store.mjs +944 -367
- package/src/profile/listening-profile-projection.mjs +123 -156
- package/src/profile/local-file-import.mjs +172 -0
- package/src/profile/moondog-suggestions.mjs +40 -11
- package/src/profile/profile-exploration.mjs +36 -6
- package/src/profile/recorded-measures.mjs +5 -0
- package/src/profile/spotify-archive-taste.mjs +41 -65
- package/src/runtime/pi/agent-runtime.mjs +360 -215
- package/src/runtime/pi/custom-endpoints.mjs +30 -8
- package/src/runtime/pi/memory-agent-runtime.mjs +43 -3
- package/src/runtime/pi/playback-rules.mjs +100 -0
- package/src/runtime/pi/profile-build-runtime.mjs +81 -24
- package/src/surfaces/cli/brand-components.mjs +9 -6
- package/src/surfaces/cli/command-completions.mjs +8 -1
- package/src/surfaces/cli/format-output.mjs +207 -34
- package/src/surfaces/cli/history-import-view.mjs +130 -21
- package/src/surfaces/cli/listenbrainz-command.mjs +7 -2
- package/src/surfaces/cli/listener-profile-command.mjs +67 -10
- package/src/surfaces/cli/listening-menu.mjs +3 -0
- package/src/surfaces/cli/profile-command.mjs +1 -0
- package/src/surfaces/cli/spotify-command.mjs +17 -25
- package/src/surfaces/cli/taste-period.mjs +22 -0
- package/src/surfaces/cli/taste-profile-model.mjs +52 -32
- package/src/surfaces/cli/tui.mjs +557 -170
- package/src/surfaces/html/tasteprint.mjs +181 -93
- package/src/surfaces/import-source-history.mjs +80 -0
|
@@ -11,19 +11,51 @@ import { createPlayerNow } from "../../core/listening-now.mjs";
|
|
|
11
11
|
|
|
12
12
|
// Players that play one file without a window and exit at its end, in order of preference.
|
|
13
13
|
// None of them may read or write the terminal: the listening room owns it.
|
|
14
|
-
const
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
],
|
|
20
|
-
};
|
|
14
|
+
const playersWithProgress = [
|
|
15
|
+
{ command: "ffplay", args: ["-nodisp", "-autoexit", "-loglevel", "quiet"] },
|
|
16
|
+
{ command: "mpv", args: ["--no-video", "--no-terminal"] },
|
|
17
|
+
];
|
|
18
|
+
const systemPlayers = { darwin: [{ command: "afplay", args: [] }], linux: playersWithProgress };
|
|
21
19
|
const longestQueue = 30;
|
|
22
20
|
// A library playlist plays as many entries as the application sends it, as the window does.
|
|
23
21
|
const longestPlaylist = 50;
|
|
24
22
|
const largestPreview = 10 * 1024 * 1024;
|
|
25
23
|
// Some routes to Apple's audio host take over 20 seconds for one preview.
|
|
26
24
|
const downloadTimeoutMs = 60_000;
|
|
25
|
+
const stoppedError = () => Object.assign(new Error("Apple Music playback was stopped."), { name: "AbortError", code: "apple_music_playback_stopped" });
|
|
26
|
+
|
|
27
|
+
// Only this request's rows belong on its receipt, even if another request appends to the queue.
|
|
28
|
+
function firstStartReceipt(sources, timeoutMs) {
|
|
29
|
+
const { promise, resolve, reject } = Promise.withResolvers();
|
|
30
|
+
const failed = [], completed = [];
|
|
31
|
+
let index = 0;
|
|
32
|
+
let settled = false;
|
|
33
|
+
const finish = (started = null, pending = null) => {
|
|
34
|
+
if (settled) return;
|
|
35
|
+
settled = true;
|
|
36
|
+
clearTimeout(timer);
|
|
37
|
+
resolve({ started, queued: started || pending ? sources.slice(index + 1) : [], failed: [...failed],
|
|
38
|
+
...(pending ? { pending } : {}), ...(completed.length ? { completed: [...completed] } : {}) });
|
|
39
|
+
};
|
|
40
|
+
const timer = setTimeout(() => finish(null, sources[index]), timeoutMs);
|
|
41
|
+
return {
|
|
42
|
+
promise,
|
|
43
|
+
waiting: () => !settled,
|
|
44
|
+
playing() { finish(sources[index]); },
|
|
45
|
+
advance(how) {
|
|
46
|
+
if (settled) return;
|
|
47
|
+
if (how === "failed") failed.push(sources[index]);
|
|
48
|
+
if (how === "ended") completed.push(sources[index]);
|
|
49
|
+
if (++index === sources.length) finish();
|
|
50
|
+
},
|
|
51
|
+
cancel() {
|
|
52
|
+
if (settled) return;
|
|
53
|
+
settled = true;
|
|
54
|
+
clearTimeout(timer);
|
|
55
|
+
reject(stoppedError());
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
}
|
|
27
59
|
|
|
28
60
|
// The same addresses the website's player accepts.
|
|
29
61
|
const https = (value, allowed) => {
|
|
@@ -38,9 +70,10 @@ const previewHost = (host) => host === "audio-ssl.itunes.apple.com";
|
|
|
38
70
|
const linkHost = (host) => host === "music.apple.com";
|
|
39
71
|
|
|
40
72
|
/** The first system player on PATH that can play a preview, or null. */
|
|
41
|
-
export async function findSystemPlayer({ platform = process.platform, environment = process.env } = {}) {
|
|
73
|
+
export async function findSystemPlayer({ platform = process.platform, environment = process.env, confirmStart = false } = {}) {
|
|
42
74
|
const folders = String(environment.PATH ?? "").split(path.delimiter).filter((folder) => path.isAbsolute(folder));
|
|
43
|
-
|
|
75
|
+
const candidates = confirmStart && platform === "darwin" ? [...playersWithProgress, ...systemPlayers.darwin] : systemPlayers[platform] ?? [];
|
|
76
|
+
for (const { command, args } of candidates) {
|
|
44
77
|
for (const folder of folders) {
|
|
45
78
|
const file = path.join(folder, command);
|
|
46
79
|
try {
|
|
@@ -64,9 +97,13 @@ export async function createTerminalPreviewPlayer({
|
|
|
64
97
|
environment,
|
|
65
98
|
fetchImpl = globalThis.fetch,
|
|
66
99
|
temporaryRoot = tmpdir(),
|
|
100
|
+
startConfirmationMs = 1500,
|
|
67
101
|
} = {}) {
|
|
68
102
|
const player = await findSystemPlayer({ platform, environment });
|
|
69
103
|
if (!player) return null;
|
|
104
|
+
// Prefer audio-clock evidence when the Mac already has FFplay or mpv. Ordinary play still uses afplay.
|
|
105
|
+
const confirmingPlayer = (platform ?? process.platform) === "darwin"
|
|
106
|
+
? await findSystemPlayer({ platform, environment, confirmStart: true }) ?? player : player;
|
|
70
107
|
const listeners = new Set();
|
|
71
108
|
let folder = null;
|
|
72
109
|
let files = 0;
|
|
@@ -82,6 +119,12 @@ export async function createTerminalPreviewPlayer({
|
|
|
82
119
|
try { listener(event); } catch {}
|
|
83
120
|
}
|
|
84
121
|
};
|
|
122
|
+
const previewTrack = (track) => {
|
|
123
|
+
const title = String(track?.title ?? "").trim();
|
|
124
|
+
const catalog_url = https(track?.catalog_url, linkHost);
|
|
125
|
+
const preview = https(track?.preview_url, previewHost);
|
|
126
|
+
return title && catalog_url && preview ? { title, artist_credit: String(track.artist_credit ?? "").trim(), catalog_url, preview } : null;
|
|
127
|
+
};
|
|
85
128
|
const removeFolder = () => {
|
|
86
129
|
if (folder) rmSync(folder, { recursive: true, force: true });
|
|
87
130
|
folder = null;
|
|
@@ -112,23 +155,65 @@ export async function createTerminalPreviewPlayer({
|
|
|
112
155
|
|
|
113
156
|
// Resolves "ended" when the song played to its end, "stopped" when /skip or /stop ended it, and
|
|
114
157
|
// "failed" when the player could not play it (no audio device, an unreadable file).
|
|
115
|
-
const playFile = (file) => new Promise((resolve) => {
|
|
116
|
-
const
|
|
158
|
+
const playFile = (file, onStart, confirmStart) => new Promise((resolve) => {
|
|
159
|
+
const chosen = confirmStart ? confirmingPlayer : player;
|
|
160
|
+
const backend = path.basename(chosen.command);
|
|
161
|
+
const ffplay = confirmStart && backend === "ffplay";
|
|
162
|
+
const mpv = confirmStart && backend === "mpv";
|
|
163
|
+
const args = ffplay ? ["-nodisp", "-autoexit", "-hide_banner", "-loglevel", "level+info", "-stats"]
|
|
164
|
+
: mpv ? ["--no-video", "--no-input-terminal", "--terminal=yes", "--term-playing-msg=MOONDOG_AUDIO_STARTED", "--term-status-msg="] : chosen.args;
|
|
165
|
+
const playing = spawn(chosen.command, [...args, file], { stdio: ["ignore", mpv ? "pipe" : "ignore", ffplay ? "pipe" : "ignore"] });
|
|
117
166
|
child = playing;
|
|
167
|
+
let started = false, audioStream = false, decoderError = false;
|
|
168
|
+
const start = () => {
|
|
169
|
+
if (!started && child === playing && !playing.killed) { started = true; onStart(); }
|
|
170
|
+
};
|
|
171
|
+
// FFplay reports its audio clock and mpv the playback start. afplay reports neither, so
|
|
172
|
+
// it starts once it runs 300 ms; a bad file or no audio device ends it sooner.
|
|
173
|
+
const progress = ffplay ? playing.stderr : mpv ? playing.stdout : null;
|
|
174
|
+
let survived = null;
|
|
175
|
+
if (progress) {
|
|
176
|
+
let tail = "", lastClock = null;
|
|
177
|
+
progress.setEncoding("utf8").on("data", chunk => {
|
|
178
|
+
const lines = (tail + chunk).split(/[\r\n]/u);
|
|
179
|
+
tail = lines.pop().slice(-512);
|
|
180
|
+
for (const line of lines) {
|
|
181
|
+
if (mpv && line.trim() === "MOONDOG_AUDIO_STARTED") { start(); return; }
|
|
182
|
+
if (!ffplay) continue;
|
|
183
|
+
if (/\[(?:error|fatal|panic)\]/u.test(line)) decoderError = true;
|
|
184
|
+
if (/^\[info\]\s*Stream #\d+:\d+[^:]*: Audio:/u.test(line)) audioStream = true;
|
|
185
|
+
const clock = !started && /^\[info\]\s*(-?\d+(?:\.\d+)?)\s+M-A:\s*[-\d.]+\s+fd=\s*\d+\s+aq=/u.exec(line);
|
|
186
|
+
if (!clock) continue;
|
|
187
|
+
const position = Number(clock[1]);
|
|
188
|
+
if (position > 0 && lastClock !== null && position > lastClock) { start(); return; }
|
|
189
|
+
lastClock = position;
|
|
190
|
+
}
|
|
191
|
+
});
|
|
192
|
+
}
|
|
118
193
|
const finish = (how) => {
|
|
194
|
+
clearTimeout(survived);
|
|
119
195
|
if (child === playing) child = null;
|
|
120
196
|
resolve(how);
|
|
121
197
|
};
|
|
198
|
+
if (!confirmStart) playing.once("spawn", start);
|
|
199
|
+
else if (!progress) playing.once("spawn", () => { survived = setTimeout(start, 300); });
|
|
122
200
|
playing.once("error", () => finish("failed"));
|
|
123
|
-
|
|
201
|
+
// FFplay also exits zero on corrupt input. A short, valid file can reach EOF between two clock samples.
|
|
202
|
+
playing.once("close", code => finish(playing.killed ? "stopped"
|
|
203
|
+
: code === 0 && (!ffplay || started || (audioStream && !decoderError)) ? "ended" : "failed"));
|
|
124
204
|
});
|
|
125
205
|
|
|
126
|
-
const start = (tracks) => {
|
|
206
|
+
const start = (tracks, { sources, confirmStart, signal } = {}) => {
|
|
127
207
|
const controller = new AbortController();
|
|
128
208
|
const downloads = new Map();
|
|
209
|
+
const receipt = confirmStart ? firstStartReceipt(sources, startConfirmationMs) : null;
|
|
129
210
|
// skip() ends the song playing, or the download of the song about to play.
|
|
130
|
-
const current = { controller, skipDownload: null, tracks };
|
|
211
|
+
const current = { controller, receipt, skipDownload: null, tracks, accepting: true };
|
|
131
212
|
queue = current;
|
|
213
|
+
const abort = () => { if (queue === current && receipt?.waiting()) stop(); };
|
|
214
|
+
if (receipt) signal?.addEventListener("abort", abort, { once: true });
|
|
215
|
+
const confirmation = receipt?.promise.finally(() => signal?.removeEventListener("abort", abort));
|
|
216
|
+
if (receipt && signal?.aborted) { abort(); return confirmation; }
|
|
132
217
|
const fetchFile = (index) => {
|
|
133
218
|
if (!downloads.has(index)) {
|
|
134
219
|
const own = new AbortController();
|
|
@@ -149,7 +234,9 @@ export async function createTerminalPreviewPlayer({
|
|
|
149
234
|
const pending = tracks[index].file
|
|
150
235
|
? { ready: true, file: Promise.resolve(tracks[index].file), abort: () => {}, skipped: () => false }
|
|
151
236
|
: fetchFile(index);
|
|
152
|
-
|
|
237
|
+
// Even a prefetched or local file waits for its player process to start.
|
|
238
|
+
if (!confirmStart && pending.ready && !generated) now.observe({ type: "loading", position: index + 1 });
|
|
239
|
+
else emit({ type: "loading", ...song });
|
|
153
240
|
current.skipDownload = pending.abort;
|
|
154
241
|
const file = await pending.file;
|
|
155
242
|
current.skipDownload = null;
|
|
@@ -158,20 +245,23 @@ export async function createTerminalPreviewPlayer({
|
|
|
158
245
|
if (index + 1 < tracks.length && !tracks[index + 1].file) void fetchFile(index + 1);
|
|
159
246
|
if (!file) {
|
|
160
247
|
// An error, a timeout, or an oversized file; a listener's /skip is not a failure.
|
|
161
|
-
if (!pending.skipped()) emit({ type: "failed", ...song });
|
|
248
|
+
if (!pending.skipped()) emit({ type: "failed", reason: "download", ...song });
|
|
249
|
+
receipt?.advance(pending.skipped() ? "stopped" : "failed");
|
|
162
250
|
continue;
|
|
163
251
|
}
|
|
164
|
-
emit({ type: "playing", ...song });
|
|
165
|
-
// A listener may stop the queue as the song starts, as Moondog's stream does past its time limit.
|
|
166
|
-
if (controller.signal.aborted) break;
|
|
167
|
-
const how = await playFile(file);
|
|
252
|
+
const how = await playFile(file, () => { receipt?.playing(); emit({ type: "playing", ...song }); }, confirmStart);
|
|
168
253
|
// A made track that played to its end, that /skip ended, or that could not play, as the loop
|
|
169
254
|
// back from listening and Moondog's stream count it; /stop aborts the queue first.
|
|
170
|
-
if (
|
|
255
|
+
if (!controller.signal.aborted) {
|
|
256
|
+
if (how === "failed") emit({ type: "failed", reason: "decoder", ...song });
|
|
257
|
+
else if (generated) emit({ type: how === "ended" ? "finished" : "skipped", ...song });
|
|
258
|
+
receipt?.advance(how);
|
|
259
|
+
}
|
|
171
260
|
if (!tracks[index].file) await rm(file, { force: true });
|
|
172
261
|
if (controller.signal.aborted) break;
|
|
173
262
|
}
|
|
174
263
|
} finally {
|
|
264
|
+
current.accepting = false;
|
|
175
265
|
await Promise.all([...downloads.values()].map(async (pending) => {
|
|
176
266
|
const file = await pending.file;
|
|
177
267
|
if (file) await rm(file, { force: true });
|
|
@@ -182,10 +272,12 @@ export async function createTerminalPreviewPlayer({
|
|
|
182
272
|
}
|
|
183
273
|
}
|
|
184
274
|
})();
|
|
275
|
+
return confirmation;
|
|
185
276
|
};
|
|
186
277
|
|
|
187
278
|
const stop = () => {
|
|
188
279
|
if (!queue) return false;
|
|
280
|
+
queue.receipt?.cancel();
|
|
189
281
|
queue.controller.abort();
|
|
190
282
|
queue = null;
|
|
191
283
|
child?.kill();
|
|
@@ -196,40 +288,58 @@ export async function createTerminalPreviewPlayer({
|
|
|
196
288
|
|
|
197
289
|
return {
|
|
198
290
|
// A new set of previews replaces the queue and starts from its first song.
|
|
199
|
-
play(tracks, { album } = {}) {
|
|
200
|
-
if (
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
})).filter((track) => track.title && track.catalog_url && track.preview).slice(0, longestQueue);
|
|
207
|
-
if (!accepted.length) return;
|
|
291
|
+
play(tracks, { album, confirmStart = false, signal } = {}) {
|
|
292
|
+
if (confirmStart) signal?.throwIfAborted();
|
|
293
|
+
if (closed) return confirmStart ? { started: null, queued: [], failed: [] } : [];
|
|
294
|
+
const accepted = (Array.isArray(tracks) ? tracks : []).map(source => ({ source, song: previewTrack(source) }))
|
|
295
|
+
.filter(item => item.song).slice(0, longestQueue);
|
|
296
|
+
if (!accepted.length) return confirmStart ? { started: null, queued: [], failed: [] } : [];
|
|
297
|
+
const previews = accepted.map(item => item.song);
|
|
208
298
|
stop();
|
|
209
299
|
emit({
|
|
210
300
|
type: "queue",
|
|
211
|
-
tracks:
|
|
301
|
+
tracks: previews.map(({ title, artist_credit, catalog_url }) => ({ title, artist_credit, catalog_url })),
|
|
212
302
|
album: album?.title
|
|
213
303
|
? { title: String(album.title), artist_credit: String(album.artist_credit ?? ""), catalog_url: https(album.catalog_url, linkHost) }
|
|
214
304
|
: null,
|
|
215
305
|
});
|
|
216
|
-
|
|
306
|
+
const sources = accepted.map(item => item.source);
|
|
307
|
+
return start(previews, { sources, confirmStart, signal }) ?? sources;
|
|
308
|
+
},
|
|
309
|
+
// The player loop reads this same array when the current song ends.
|
|
310
|
+
enqueuePreviews(tracks) {
|
|
311
|
+
if (closed || !queue?.accepting) return null;
|
|
312
|
+
const firstPosition = queue.tracks.length + 1;
|
|
313
|
+
const accepted = tracks.filter((track) => {
|
|
314
|
+
const song = previewTrack(track);
|
|
315
|
+
if (!song) return false;
|
|
316
|
+
queue.tracks.push(song);
|
|
317
|
+
now.appended(song);
|
|
318
|
+
return true;
|
|
319
|
+
});
|
|
320
|
+
if (accepted.length) emit({ type: "append", firstPosition,
|
|
321
|
+
tracks: queue.tracks.slice(firstPosition - 1).map(({ title, artist_credit, catalog_url }) => ({ title, artist_credit, catalog_url })) });
|
|
322
|
+
return accepted;
|
|
217
323
|
},
|
|
218
324
|
// A playlist from the listener's library: Apple Music previews and tracks Moondog made, in one queue.
|
|
219
325
|
// A song is { title, artist_credit, catalog_url, preview_url }; a made track { generated: true, id, title, file }.
|
|
220
|
-
playList(tracks) {
|
|
221
|
-
if (
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
326
|
+
playList(tracks, { confirmStart = false, signal } = {}) {
|
|
327
|
+
if (confirmStart) signal?.throwIfAborted();
|
|
328
|
+
if (closed) return confirmStart ? { started: null, queued: [], failed: [] } : [];
|
|
329
|
+
const accepted = (Array.isArray(tracks) ? tracks : []).map(source => {
|
|
330
|
+
const song = source?.generated === true
|
|
331
|
+
? { title: String(source.title ?? "").trim(), artist_credit: "", generated: true, id: String(source.id ?? ""),
|
|
332
|
+
file: typeof source.file === "string" && path.isAbsolute(source.file) ? source.file : null }
|
|
333
|
+
: previewTrack(source);
|
|
334
|
+
return { source, song };
|
|
335
|
+
}).filter(({ song }) => song?.title && (!song.generated || song.file)).slice(0, longestPlaylist);
|
|
336
|
+
if (!accepted.length) return confirmStart ? { started: null, queued: [], failed: [] } : [];
|
|
337
|
+
const songs = accepted.map(item => item.song);
|
|
229
338
|
stop();
|
|
230
|
-
emit({ type: "queue", tracks:
|
|
339
|
+
emit({ type: "queue", tracks: songs.map(({ title, artist_credit, catalog_url, generated, id }) => (generated
|
|
231
340
|
? { title, artist_credit: "", generated: true, id } : { title, artist_credit, catalog_url })), album: null });
|
|
232
|
-
|
|
341
|
+
const sources = accepted.map(item => item.source);
|
|
342
|
+
return start(songs, { sources, confirmStart, signal }) ?? sources;
|
|
233
343
|
},
|
|
234
344
|
// A track Moondog made on this Mac: { id, title, file }, played whole and kept after it ends.
|
|
235
345
|
playGenerated({ id, title, file } = {}) {
|
|
@@ -244,7 +354,7 @@ export async function createTerminalPreviewPlayer({
|
|
|
244
354
|
enqueueGenerated({ id, title, file } = {}) {
|
|
245
355
|
const name = String(title ?? "").trim();
|
|
246
356
|
if (closed || !name || typeof file !== "string" || !path.isAbsolute(file)) return;
|
|
247
|
-
if (!queue
|
|
357
|
+
if (!queue?.accepting) return this.playGenerated({ id, title, file });
|
|
248
358
|
queue.tracks.push({ title: name, artist_credit: "", generated: true, id: String(id ?? ""), file });
|
|
249
359
|
now.appended({ title: name, generated: true, id: String(id ?? "") });
|
|
250
360
|
},
|
|
@@ -278,14 +278,16 @@ function normalizedRows(records, capturedAt, { allowServerMappings }) {
|
|
|
278
278
|
normalizedIdentityText(title),
|
|
279
279
|
normalizedIdentityText(release ?? ""),
|
|
280
280
|
);
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
281
|
+
// The server may resolve this same MSID to a MusicBrainz recording on
|
|
282
|
+
// its next export. That enriches the recording, not the listening event.
|
|
283
|
+
const listenRecordingKey = recordingMsid
|
|
284
|
+
? `listenbrainz-msid:${recordingMsid}`
|
|
285
|
+
: recordingMbid
|
|
286
|
+
? `musicbrainz:${recordingMbid}`
|
|
285
287
|
: `label:${labelFingerprint}`;
|
|
286
288
|
const tuple = [
|
|
287
289
|
occurredAt,
|
|
288
|
-
|
|
290
|
+
listenRecordingKey,
|
|
289
291
|
durations.playedMs === undefined ? "unknown" : durations.playedMs,
|
|
290
292
|
].join("\0");
|
|
291
293
|
return {
|
|
@@ -296,12 +298,26 @@ function normalizedRows(records, capturedAt, { allowServerMappings }) {
|
|
|
296
298
|
recordingMsid,
|
|
297
299
|
recordingMbid,
|
|
298
300
|
labelFingerprint,
|
|
299
|
-
identityKey,
|
|
300
301
|
tuple,
|
|
301
302
|
...durations,
|
|
302
303
|
};
|
|
303
304
|
});
|
|
304
|
-
|
|
305
|
+
// 0.4.0-beta.3 and earlier keyed a mapped listen on its MusicBrainz
|
|
306
|
+
// recording and numbered equal keys in file order. Mapped listens keep that
|
|
307
|
+
// event ID, so either version recognizes a listen the other saved.
|
|
308
|
+
const legacyOrdinals = new Map();
|
|
309
|
+
for (const row of rows) {
|
|
310
|
+
if (!row.recordingMbid) continue;
|
|
311
|
+
row.legacyTuple = [row.occurredAt, `musicbrainz:${row.recordingMbid}`, row.playedMs === undefined ? "unknown" : row.playedMs].join("\0");
|
|
312
|
+
row.legacyOrdinal = (legacyOrdinals.get(row.legacyTuple) ?? 0) + 1;
|
|
313
|
+
legacyOrdinals.set(row.legacyTuple, row.legacyOrdinal);
|
|
314
|
+
}
|
|
315
|
+
return rows.sort((left, right) => lexicalCompare(left.tuple, right.tuple) ||
|
|
316
|
+
lexicalCompare(right.recordingMbid ?? "", left.recordingMbid ?? ""));
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
export function listenBrainzMsidTrackRefId(msid) {
|
|
320
|
+
return uuidV5(msid, LISTENBRAINZ_MSID_TRACK_NAMESPACE);
|
|
305
321
|
}
|
|
306
322
|
|
|
307
323
|
function trackIdentity(row) {
|
|
@@ -332,10 +348,7 @@ function trackIdentity(row) {
|
|
|
332
348
|
}
|
|
333
349
|
if (row.recordingMsid) {
|
|
334
350
|
return {
|
|
335
|
-
trackRefId:
|
|
336
|
-
row.recordingMsid,
|
|
337
|
-
LISTENBRAINZ_MSID_TRACK_NAMESPACE,
|
|
338
|
-
),
|
|
351
|
+
trackRefId: listenBrainzMsidTrackRefId(row.recordingMsid),
|
|
339
352
|
identityStatus: "provisional",
|
|
340
353
|
externalRefs: [
|
|
341
354
|
{
|
|
@@ -441,12 +454,18 @@ export function projectListenBrainzHistory({
|
|
|
441
454
|
row.tuple,
|
|
442
455
|
duplicateOrdinal,
|
|
443
456
|
);
|
|
457
|
+
// The deduplication key follows the listen's MSID, which stays the same
|
|
458
|
+
// when the server maps or remaps its recording. The two unique columns
|
|
459
|
+
// let either one recognize a listen saved before.
|
|
460
|
+
const eventId = uuidV5(
|
|
461
|
+
row.recordingMbid
|
|
462
|
+
? hashParts("listenbrainz-listen-v1", normalizedSubjectId, row.legacyTuple, row.legacyOrdinal)
|
|
463
|
+
: eventFingerprint,
|
|
464
|
+
LISTENBRAINZ_EVENT_NAMESPACE,
|
|
465
|
+
);
|
|
444
466
|
listeningEvents.push({
|
|
445
467
|
schema_version: 1,
|
|
446
|
-
listening_event_id:
|
|
447
|
-
eventFingerprint,
|
|
448
|
-
LISTENBRAINZ_EVENT_NAMESPACE,
|
|
449
|
-
),
|
|
468
|
+
listening_event_id: eventId,
|
|
450
469
|
subject_id: normalizedSubjectId,
|
|
451
470
|
track_ref_id: identity.trackRefId,
|
|
452
471
|
track_ref_revision: 1,
|
|
@@ -455,6 +474,9 @@ export function projectListenBrainzHistory({
|
|
|
455
474
|
ingested_at: normalizedCapturedAt,
|
|
456
475
|
interaction_mode: "unknown",
|
|
457
476
|
...(row.playedMs !== undefined ? { played_ms: row.playedMs } : {}),
|
|
477
|
+
// A shared MusicBrainz recording can have several source MSIDs. Keep the
|
|
478
|
+
// one this listen actually supplied, including an explicitly absent ID.
|
|
479
|
+
...(row.recordingMbid ? { extensions: { "listenbrainz.recording_msid": row.recordingMsid } } : {}),
|
|
458
480
|
context: { context_type: "unknown" },
|
|
459
481
|
provenance: {
|
|
460
482
|
source_kind: "import",
|
|
@@ -495,24 +517,21 @@ export function projectListenBrainzHistory({
|
|
|
495
517
|
};
|
|
496
518
|
}
|
|
497
519
|
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
subjectId,
|
|
501
|
-
capturedAt = new Date().toISOString(),
|
|
502
|
-
} = {}) {
|
|
520
|
+
/** Use one file snapshot for format detection, validation and the saved digest. */
|
|
521
|
+
export async function readHistoryJsonSource(filePath) {
|
|
503
522
|
if (typeof filePath !== "string" || !filePath.trim()) {
|
|
504
|
-
fail("A
|
|
523
|
+
fail("A history JSON path is required.");
|
|
505
524
|
}
|
|
506
525
|
const resolvedPath = path.resolve(filePath);
|
|
507
526
|
if (path.extname(resolvedPath).toLowerCase() !== ".json") {
|
|
508
|
-
fail("
|
|
527
|
+
fail("Listening history must be supplied as a JSON file.");
|
|
509
528
|
}
|
|
510
529
|
let handle;
|
|
511
530
|
try {
|
|
512
531
|
handle = await open(resolvedPath, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
513
532
|
} catch {
|
|
514
533
|
fail(
|
|
515
|
-
"The
|
|
534
|
+
"The history JSON could not be opened safely.",
|
|
516
535
|
"listenbrainz_history_unreadable",
|
|
517
536
|
);
|
|
518
537
|
}
|
|
@@ -524,28 +543,37 @@ export async function readListenBrainzHistoryFile({
|
|
|
524
543
|
file.size < 1 ||
|
|
525
544
|
file.size > LISTENBRAINZ_HISTORY_LIMITS.maximumFileBytes
|
|
526
545
|
) {
|
|
527
|
-
fail("
|
|
546
|
+
fail("Choose a regular history JSON file no larger than 256 MB.");
|
|
528
547
|
}
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
548
|
+
const buffer = Buffer.alloc(file.size + 1);
|
|
549
|
+
let size = 0;
|
|
550
|
+
while (size < buffer.length) {
|
|
551
|
+
const { bytesRead } = await handle.read(buffer, size, buffer.length - size, null);
|
|
552
|
+
if (!bytesRead) break;
|
|
553
|
+
size += bytesRead;
|
|
535
554
|
}
|
|
555
|
+
if (size !== file.size) fail("The history JSON changed while it was being read. Finish the download and try again.");
|
|
556
|
+
bytes = buffer.subarray(0, size);
|
|
536
557
|
} finally {
|
|
537
558
|
await handle.close();
|
|
538
559
|
}
|
|
539
560
|
|
|
540
|
-
let jsonText;
|
|
541
561
|
try {
|
|
542
|
-
|
|
562
|
+
return { bytes, text: utf8Decoder.decode(bytes).replace(/^\uFEFF/u, "") };
|
|
543
563
|
} catch {
|
|
544
|
-
fail("The
|
|
564
|
+
fail("The history file is not valid UTF-8 JSON.");
|
|
545
565
|
}
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
export async function readListenBrainzHistoryFile({
|
|
569
|
+
filePath,
|
|
570
|
+
subjectId,
|
|
571
|
+
capturedAt = new Date().toISOString(),
|
|
572
|
+
} = {}, source) {
|
|
573
|
+
const { bytes, text } = source ?? await readHistoryJsonSource(filePath);
|
|
546
574
|
let document;
|
|
547
575
|
try {
|
|
548
|
-
document = JSON.parse(
|
|
576
|
+
document = JSON.parse(text);
|
|
549
577
|
} catch {
|
|
550
578
|
fail("The ListenBrainz history file is invalid JSON.");
|
|
551
579
|
}
|
|
@@ -554,7 +582,7 @@ export async function readListenBrainzHistoryFile({
|
|
|
554
582
|
document,
|
|
555
583
|
fileSha256: createHash("sha256").update(bytes).digest("hex"),
|
|
556
584
|
fileSizeBytes: bytes.length,
|
|
557
|
-
memberName: path.basename(
|
|
585
|
+
memberName: path.basename(filePath),
|
|
558
586
|
capturedAt,
|
|
559
587
|
});
|
|
560
588
|
}
|