@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
|
@@ -226,7 +226,15 @@ function setIfDefined(target, key, value) {
|
|
|
226
226
|
if (value !== undefined) target[key] = value;
|
|
227
227
|
}
|
|
228
228
|
|
|
229
|
-
function
|
|
229
|
+
function explicitlyNonMusic(track) {
|
|
230
|
+
const mediaKind = typeof track["Media Kind"] === "string" ? track["Media Kind"].trim().toLowerCase() : "";
|
|
231
|
+
if (track["Music Video"] === true || mediaKind === "music video" || mediaKind === "song") return false;
|
|
232
|
+
return track.Podcast === true || track.Movie === true || track["TV Show"] === true ||
|
|
233
|
+
["podcast", "movie", "tv show", "audiobook"].includes(mediaKind) ||
|
|
234
|
+
(typeof track.Kind === "string" && /^(?:(?:purchased |protected )?AAC )?audiobook$/iu.test(track.Kind));
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function safeCoverage(parsed, filterMedia) {
|
|
230
238
|
const coverage = {
|
|
231
239
|
title: 0,
|
|
232
240
|
artist: 0,
|
|
@@ -243,7 +251,7 @@ function safeCoverage(parsed) {
|
|
|
243
251
|
};
|
|
244
252
|
|
|
245
253
|
for (const track of Object.values(parsed.root.Tracks)) {
|
|
246
|
-
if (!isPlainObject(track)) continue;
|
|
254
|
+
if (!isPlainObject(track) || (filterMedia && explicitlyNonMusic(track))) continue;
|
|
247
255
|
if (typeof track.Name === "string" && track.Name.trim()) coverage.title += 1;
|
|
248
256
|
if (typeof track.Artist === "string" && track.Artist.trim()) {
|
|
249
257
|
coverage.artist += 1;
|
|
@@ -277,6 +285,7 @@ function safeCoverage(parsed) {
|
|
|
277
285
|
}
|
|
278
286
|
|
|
279
287
|
export function summarizeAppleMusicLibrary(parsed) {
|
|
288
|
+
const excluded = Object.values(parsed.root.Tracks).filter(track => isPlainObject(track) && explicitlyNonMusic(track)).length;
|
|
280
289
|
return {
|
|
281
290
|
ok: true,
|
|
282
291
|
mode: "inspect",
|
|
@@ -288,12 +297,13 @@ export function summarizeAppleMusicLibrary(parsed) {
|
|
|
288
297
|
tracks: parsed.trackCount,
|
|
289
298
|
playlists: parsed.playlistCount,
|
|
290
299
|
playlist_item_references: parsed.playlistItemCount,
|
|
291
|
-
provisional_track_candidates: parsed.trackCount,
|
|
292
|
-
aggregate_track_snapshots: parsed.trackCount,
|
|
300
|
+
provisional_track_candidates: parsed.trackCount - excluded,
|
|
301
|
+
aggregate_track_snapshots: parsed.trackCount - excluded,
|
|
302
|
+
...(excluded ? { non_music_items_excluded: excluded } : {}),
|
|
293
303
|
core_listening_events: 0,
|
|
294
304
|
core_taste_events: 0,
|
|
295
305
|
},
|
|
296
|
-
coverage: safeCoverage(parsed),
|
|
306
|
+
coverage: safeCoverage(parsed, true),
|
|
297
307
|
semantics: {
|
|
298
308
|
source_is_library_snapshot: true,
|
|
299
309
|
source_is_complete_listening_history: false,
|
|
@@ -692,7 +702,23 @@ export async function validateAppleMusicImportRecords(records) {
|
|
|
692
702
|
}
|
|
693
703
|
}
|
|
694
704
|
|
|
705
|
+
// A previously saved copy has the same source digest and batch ID. Recreate its
|
|
706
|
+
// original bytes only if the writer needs to verify that immutable copy.
|
|
707
|
+
const previousNormalizations = new WeakMap();
|
|
708
|
+
|
|
709
|
+
export function previousAppleNormalization(records) {
|
|
710
|
+
return previousNormalizations.get(records)?.();
|
|
711
|
+
}
|
|
712
|
+
|
|
695
713
|
export async function normalizeAppleMusicLibrary(parsed, { subjectId }) {
|
|
714
|
+
const records = await normalizeTracks(parsed, subjectId, true);
|
|
715
|
+
if (records.manifest.warning_counts.non_music_media_excluded) {
|
|
716
|
+
previousNormalizations.set(records, () => normalizeTracks(parsed, subjectId, false));
|
|
717
|
+
}
|
|
718
|
+
return records;
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
async function normalizeTracks(parsed, subjectId, filterMedia) {
|
|
696
722
|
if (!isUuid(subjectId)) {
|
|
697
723
|
fail("subject_id_invalid", "Import requires a valid stable subject UUID");
|
|
698
724
|
}
|
|
@@ -736,6 +762,10 @@ export async function normalizeAppleMusicLibrary(parsed, { subjectId }) {
|
|
|
736
762
|
source_sha256: parsed.sourceSha256,
|
|
737
763
|
source_key: sourceKey,
|
|
738
764
|
});
|
|
765
|
+
if (filterMedia && explicitlyNonMusic(track)) {
|
|
766
|
+
warnings.push({ code: "non_music_media_excluded", scope: "track", source_record_key_sha256: sourceRecordKeySha256 });
|
|
767
|
+
continue;
|
|
768
|
+
}
|
|
739
769
|
const persistentId = cleanText(
|
|
740
770
|
track["Persistent ID"],
|
|
741
771
|
"persistent_id",
|
|
@@ -1101,7 +1131,7 @@ export async function normalizeAppleMusicLibrary(parsed, { subjectId }) {
|
|
|
1101
1131
|
core_taste_events: 0,
|
|
1102
1132
|
warnings: warnings.length,
|
|
1103
1133
|
},
|
|
1104
|
-
coverage: safeCoverage(parsed),
|
|
1134
|
+
coverage: safeCoverage(parsed, filterMedia),
|
|
1105
1135
|
warning_counts: warningCounts(warnings),
|
|
1106
1136
|
semantics: {
|
|
1107
1137
|
source_is_library_snapshot: true,
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { lstat, readFile } from "node:fs/promises";
|
|
2
|
+
|
|
3
|
+
// Keep the receipt beside the UUID directory so older Music importers see the same four files.
|
|
4
|
+
export const appleImportSaveTimePath = (batchDirectory) => `${batchDirectory}.saved-at`;
|
|
5
|
+
|
|
6
|
+
export async function readAppleImportSaveTime(batchDirectory) {
|
|
7
|
+
try {
|
|
8
|
+
const file = appleImportSaveTimePath(batchDirectory);
|
|
9
|
+
const metadata = await lstat(file);
|
|
10
|
+
if (!metadata.isFile() || metadata.size > 32 || (process.platform !== "win32" && (metadata.mode & 0o077) !== 0)) return null;
|
|
11
|
+
const time = (await readFile(file, "utf8")).trim();
|
|
12
|
+
return Number.isFinite(Date.parse(time)) && new Date(time).toISOString() === time ? time : null;
|
|
13
|
+
} catch {
|
|
14
|
+
// A canonical snapshot remains usable when its optional local save time is unavailable.
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
// Read ZIP members in process on every desktop platform. Nothing is extracted to disk.
|
|
2
2
|
import { crc32 } from "node:zlib";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { open, close, createReadStream, fstat } from "node:fs";
|
|
5
|
+
import { promisify } from "node:util";
|
|
3
6
|
import yauzl from "yauzl";
|
|
4
7
|
|
|
5
8
|
/**
|
|
@@ -9,7 +12,15 @@ import yauzl from "yauzl";
|
|
|
9
12
|
export async function openZipArchive(source, maximumNameBytes = 1024 * 1024) {
|
|
10
13
|
// The archive stays open after its entries are listed, so members can be read in any order.
|
|
11
14
|
const options = { strictFileNames: true, validateEntrySizes: true, autoClose: false };
|
|
12
|
-
|
|
15
|
+
// The file descriptor stays with the ZIP until close(), including while hashing the inspected bytes.
|
|
16
|
+
const fd = Buffer.isBuffer(source) ? null : await promisify(open)(source, "r");
|
|
17
|
+
let zip;
|
|
18
|
+
try {
|
|
19
|
+
zip = fd === null ? await yauzl.fromBufferPromise(source, options) : await yauzl.fromFdPromise(fd, options);
|
|
20
|
+
} catch (error) {
|
|
21
|
+
if (fd !== null) await promisify(close)(fd);
|
|
22
|
+
throw error;
|
|
23
|
+
}
|
|
13
24
|
const names = [];
|
|
14
25
|
const entries = new Map();
|
|
15
26
|
try {
|
|
@@ -46,7 +57,18 @@ export async function openZipArchive(source, maximumNameBytes = 1024 * 1024) {
|
|
|
46
57
|
return Buffer.concat(chunks, bytes);
|
|
47
58
|
}
|
|
48
59
|
|
|
49
|
-
|
|
60
|
+
async function digest(expectedFile) {
|
|
61
|
+
const hash = createHash("sha256");
|
|
62
|
+
if (fd === null) return hash.update(source).digest("hex");
|
|
63
|
+
for await (const chunk of createReadStream(null, { fd, start: 0, end: expectedFile.size - 1, autoClose: false })) hash.update(chunk);
|
|
64
|
+
const actual = await promisify(fstat)(fd);
|
|
65
|
+
if (["dev", "ino", "size", "mtimeMs", "ctimeMs"].some(key => actual[key] !== expectedFile[key])) {
|
|
66
|
+
throw Object.assign(new Error("The ZIP changed while it was being read. Open it again to preview it."), { code: "history_import_zip_changed" });
|
|
67
|
+
}
|
|
68
|
+
return hash.digest("hex");
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return { names, read, digest, close: () => zip.close() };
|
|
50
72
|
}
|
|
51
73
|
|
|
52
74
|
export async function listZipMembers(source, maximumBytes = 1024 * 1024) {
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// Reads public Apple Music playlist metadata through a marked, one-shot Mac helper.
|
|
2
|
+
import { execFile } from "node:child_process";
|
|
3
|
+
import { constants } from "node:fs";
|
|
4
|
+
import { access } from "node:fs/promises";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { promisify } from "node:util";
|
|
9
|
+
|
|
10
|
+
const execute = promisify(execFile);
|
|
11
|
+
const packageRoot = fileURLToPath(new URL("../../../", import.meta.url));
|
|
12
|
+
const maxOutput = 4 * 1024 * 1024;
|
|
13
|
+
// The standalone npm package ships without the desktop packaging and signing tools.
|
|
14
|
+
const releaseRequirement = [
|
|
15
|
+
'=anchor apple generic', 'identifier "ai.audiofool.moondog"',
|
|
16
|
+
"certificate 1[field.1.2.840.113635.100.6.2.6] exists",
|
|
17
|
+
"certificate leaf[field.1.2.840.113635.100.6.1.13] exists",
|
|
18
|
+
'certificate leaf[subject.OU] = "DAK5S3455A"',
|
|
19
|
+
].join(" and ");
|
|
20
|
+
|
|
21
|
+
async function runFile(file, args, { signal, ...options }) {
|
|
22
|
+
signal.throwIfAborted();
|
|
23
|
+
const running = execute(file, args, options);
|
|
24
|
+
const stop = () => running.child.kill("SIGKILL");
|
|
25
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
26
|
+
try {
|
|
27
|
+
return await running;
|
|
28
|
+
} finally {
|
|
29
|
+
signal.removeEventListener("abort", stop);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function bundles(root, applications) {
|
|
34
|
+
const parent = path.dirname(root);
|
|
35
|
+
if (path.basename(root) === "Resources" && path.basename(parent) === "Contents" &&
|
|
36
|
+
path.extname(path.dirname(parent)) === ".app") return [{ contents: parent, external: false }];
|
|
37
|
+
return [
|
|
38
|
+
{ contents: path.join(root, "app", "native", "build", "apps.noindex", "Moondog Music.app", "Contents"), external: false },
|
|
39
|
+
...applications.map(directory => ({ contents: path.join(directory, "Moondog.app", "Contents"), external: true })),
|
|
40
|
+
];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const label = (value) => typeof value === "string" && value.length <= 1024
|
|
44
|
+
? value.replace(/\s+/gu, " ").trim() : "";
|
|
45
|
+
|
|
46
|
+
function playlist(stdout, id, storefront) {
|
|
47
|
+
const data = JSON.parse(stdout);
|
|
48
|
+
if (data?.id !== id || data.storefront !== storefront || typeof data.complete !== "boolean" ||
|
|
49
|
+
!Array.isArray(data.tracks) || data.tracks.length > 2000) return null;
|
|
50
|
+
const { total, complete } = data;
|
|
51
|
+
if (total !== null && (!Number.isSafeInteger(total) || total < data.tracks.length)) return null;
|
|
52
|
+
if (complete && total !== data.tracks.length) return null;
|
|
53
|
+
const tracks = [];
|
|
54
|
+
for (const row of data.tracks) {
|
|
55
|
+
const title = label(row?.title), artist = label(row?.artist);
|
|
56
|
+
if (typeof row?.id !== "string" || !/^[1-9]\d{0,19}$/u.test(row.id) ||
|
|
57
|
+
!title || !artist || /[\u0000-\u001f\u007f-\u009f]/u.test(title + artist)) return null;
|
|
58
|
+
tracks.push({ id: row.id, title, artist });
|
|
59
|
+
}
|
|
60
|
+
return { id, storefront, tracks, complete, total };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function createCatalogPlaylistReader({
|
|
64
|
+
platform = process.platform, environment = process.env, root = packageRoot,
|
|
65
|
+
applications = [path.join(homedir(), "Applications"), "/Applications"], run = runFile, timeoutMs = 25_000,
|
|
66
|
+
} = {}) {
|
|
67
|
+
return async function readCatalogPlaylist(input, { signal } = {}) {
|
|
68
|
+
signal?.throwIfAborted();
|
|
69
|
+
const { id, storefront } = input ?? {};
|
|
70
|
+
if (platform !== "darwin" || environment.MOONDOG_SYSTEM_MUSIC === "off" ||
|
|
71
|
+
typeof id !== "string" || !/^pl\.[A-Za-z0-9.-]{6,80}$/u.test(id) ||
|
|
72
|
+
typeof storefront !== "string" || !/^[a-z]{2}$/u.test(storefront)) return null;
|
|
73
|
+
const deadline = AbortSignal.timeout(timeoutMs);
|
|
74
|
+
const bounded = signal ? AbortSignal.any([signal, deadline]) : deadline;
|
|
75
|
+
const options = { signal: bounded, encoding: "utf8", killSignal: "SIGKILL" };
|
|
76
|
+
for (const { contents, external } of bundles(root, applications)) {
|
|
77
|
+
signal?.throwIfAborted();
|
|
78
|
+
if (deadline.aborted) return null;
|
|
79
|
+
const file = path.join(contents, "MacOS", "moondog-music");
|
|
80
|
+
try {
|
|
81
|
+
await access(file, constants.X_OK);
|
|
82
|
+
// Check the actual plist type, including binary plists. Older helpers enter
|
|
83
|
+
// the interactive player even when given a command-line argument.
|
|
84
|
+
const { stdout } = await run("/usr/bin/plutil", ["-extract", "MoondogPublicPlaylistReader", "raw",
|
|
85
|
+
"-expect", "bool", "-o", "-", "--", path.join(contents, "Info.plist")], { ...options, maxBuffer: 1024, timeout: 2_000 });
|
|
86
|
+
if (stdout.trim() !== "true") continue;
|
|
87
|
+
if (external) {
|
|
88
|
+
// The bundle seals the capability marker. The executable must also match Moondog's release signature.
|
|
89
|
+
await run("/usr/bin/codesign", ["--verify", "--strict", "--test-requirement", releaseRequirement,
|
|
90
|
+
path.dirname(contents), file], { ...options, maxBuffer: 4096, timeout: 8_000 });
|
|
91
|
+
}
|
|
92
|
+
} catch {
|
|
93
|
+
signal?.throwIfAborted();
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
try {
|
|
97
|
+
const { stdout } = await run(file, ["--catalog-playlist", storefront, id], { ...options, maxBuffer: maxOutput });
|
|
98
|
+
signal?.throwIfAborted();
|
|
99
|
+
if (deadline.aborted) return null;
|
|
100
|
+
return playlist(stdout, id, storefront);
|
|
101
|
+
} catch {
|
|
102
|
+
signal?.throwIfAborted();
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
signal?.throwIfAborted();
|
|
107
|
+
return null;
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export const readCatalogPlaylist = createCatalogPlaylistReader();
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { uuidV5 } from "../../core/uuid-v5.mjs";
|
|
2
2
|
import { appleMusicStorefront } from "./storefront.mjs";
|
|
3
|
+
import { appleMusicSongId } from "./song-id.mjs";
|
|
4
|
+
import { catalogNameKey, exactLibrarySong, matchesLibrarySong, normalizedArtistName, normalizedTrackTitle, sameCreditedArtist, storedRecordingAgrees } from "../../core/track-title.mjs";
|
|
3
5
|
|
|
4
6
|
export const APPLE_MUSIC_CATALOG_TRACK_NAMESPACE =
|
|
5
7
|
"2837a09e-e5f0-5aa5-b271-bb99d8b0de20";
|
|
@@ -71,13 +73,33 @@ function safeText(value, maximum) {
|
|
|
71
73
|
}
|
|
72
74
|
|
|
73
75
|
function normalizeForMatch(value) {
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
.replace(releaseSuffixPattern, "")
|
|
76
|
+
const literal = String(value ?? "").normalize("NFKC").toLocaleLowerCase("und").trim();
|
|
77
|
+
const title = literal.replace(releaseSuffixPattern, "").trim() || literal;
|
|
78
|
+
return title
|
|
78
79
|
.replace(/["'‘’“”`]/gu, "")
|
|
79
80
|
.replace(/[^\p{L}\p{N}]+/gu, " ")
|
|
80
|
-
.trim();
|
|
81
|
+
.trim() || title;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const albumEdition = /\s*(?:[([]|\s+[-\u2013\u2014]\s+)(?:super deluxe|deluxe|expanded|special|collector['’]s|(?:\d+(?:st|nd|rd|th) )?anniversary) edition[)\]]?$/iu;
|
|
85
|
+
|
|
86
|
+
function preferNamedCredit(candidates, artist) {
|
|
87
|
+
const credit = item => item.artist_credit ?? item.artist_name;
|
|
88
|
+
const literal = normalizedArtistName(artist);
|
|
89
|
+
const wanted = catalogNameKey(artist);
|
|
90
|
+
return candidates.find(item => normalizedArtistName(credit(item)) === literal) ??
|
|
91
|
+
candidates.find(item => catalogNameKey(credit(item)) === wanted) ?? candidates[0];
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Prefer the exact title, then a labeled edition. Within each, prefer the exact credit.
|
|
95
|
+
function namedRecording(items, wantedTitle, artist, { album = false } = {}) {
|
|
96
|
+
const eligible = items.filter(item => sameCreditedArtist(artist, [item.artist_credit ?? item.artist_name]));
|
|
97
|
+
const exact = preferNamedCredit(eligible.filter(item => normalizeForMatch(item.title) === wantedTitle), artist);
|
|
98
|
+
if (exact) return exact;
|
|
99
|
+
return preferNamedCredit(eligible.filter(item => {
|
|
100
|
+
const title = album ? item.title.replace(albumEdition, "") : item.title;
|
|
101
|
+
return normalizeForMatch(normalizedTrackTitle(title)) === wantedTitle;
|
|
102
|
+
}), artist);
|
|
81
103
|
}
|
|
82
104
|
|
|
83
105
|
function safeCatalogId(value) {
|
|
@@ -258,6 +280,8 @@ function normalizeTrack(raw) {
|
|
|
258
280
|
const artworkUrl = safeArtworkUrl(raw.artworkUrl100);
|
|
259
281
|
if (previewUrl) track.preview_url = previewUrl;
|
|
260
282
|
if (artworkUrl) track.artwork_url = artworkUrl;
|
|
283
|
+
// Discovery copies public rows with opaque refs. Keep the recording ID for native playback lookup.
|
|
284
|
+
Object.defineProperty(track, "catalog_id", { value: catalogId });
|
|
261
285
|
return track;
|
|
262
286
|
}
|
|
263
287
|
|
|
@@ -483,6 +507,16 @@ export function createAppleMusicCatalogClient({
|
|
|
483
507
|
});
|
|
484
508
|
},
|
|
485
509
|
|
|
510
|
+
// A recording imported from an Apple Music playlist already has its catalog identity.
|
|
511
|
+
async trackById(catalogId) {
|
|
512
|
+
if (typeof catalogId !== "string" || !/^\d{1,20}$/u.test(catalogId)) return null;
|
|
513
|
+
const key = `track-id|${storefront()}|${catalogId}`;
|
|
514
|
+
return cachedRequest(cache, key, cacheTtlMs, now, async () => {
|
|
515
|
+
const results = await request("/lookup", { id: catalogId, country: storefront().toLowerCase(), entity: "song" });
|
|
516
|
+
return normalizeTrack(results.find((track) => safeCatalogId(track?.trackId) === catalogId));
|
|
517
|
+
});
|
|
518
|
+
},
|
|
519
|
+
|
|
486
520
|
async searchAlbums(query) {
|
|
487
521
|
const cleaned = cleanInputText(query, APPLE_MUSIC_CATALOG_LIMITS.discoveryQueryLengthMax, "apple_music_catalog_query_invalid", "album query");
|
|
488
522
|
const key = `albums|${storefront()}|${normalizeForMatch(cleaned)}`;
|
|
@@ -641,54 +675,79 @@ export function createAppleMusicCatalog({
|
|
|
641
675
|
};
|
|
642
676
|
},
|
|
643
677
|
|
|
644
|
-
//
|
|
645
|
-
async findPreview({ title, artist } = {}) {
|
|
678
|
+
// A preview, or an exact catalog recording for a player that can play whole songs.
|
|
679
|
+
async findPreview({ title, artist, catalogId, allowCatalogOnly = false, exactRecording = false } = {}, { signal } = {}) {
|
|
680
|
+
signal?.throwIfAborted();
|
|
681
|
+
const nativeId = track => allowCatalogOnly === true && appleMusicSongId(track);
|
|
682
|
+
const wanted = { title, artist_credit: artist };
|
|
683
|
+
const matches = track => matchesLibrarySong(wanted, track.title, [track.artist_credit]);
|
|
684
|
+
const result = track => {
|
|
685
|
+
const id = nativeId(track);
|
|
686
|
+
return { state: track ? "resolved" : "not_found", source: sourceMetadata(now, storefront),
|
|
687
|
+
...(track ? { track: id ? { ...track, catalog_id: id } : track } : {}) };
|
|
688
|
+
};
|
|
689
|
+
if (catalogId) {
|
|
690
|
+
const track = await client.trackById?.(catalogId);
|
|
691
|
+
signal?.throwIfAborted();
|
|
692
|
+
const playable = track?.preview_url || nativeId(track) === catalogId ? track : null;
|
|
693
|
+
if (!exactRecording) return result(playable);
|
|
694
|
+
// The stored ID names the recording, whatever title this storefront gives it. One this storefront lacks,
|
|
695
|
+
// or one that names another artist or another kind of recording, is looked for again by name.
|
|
696
|
+
if (playable && appleMusicSongId(track) === catalogId && storedRecordingAgrees(wanted, track.title, [track.artist_credit])) return result(track);
|
|
697
|
+
}
|
|
646
698
|
const cleanedTitle = cleanInputText(title, APPLE_MUSIC_CATALOG_LIMITS.discoveryQueryLengthMax, "apple_music_catalog_query_invalid", "track title");
|
|
647
699
|
const cleanedArtist = cleanInputText(artist, APPLE_MUSIC_CATALOG_LIMITS.discoveryQueryLengthMax, "apple_music_catalog_query_invalid", "artist");
|
|
648
700
|
const wantedTitle = normalizeForMatch(cleanedTitle);
|
|
649
|
-
const wantedArtist = normalizeForMatch(cleanedArtist);
|
|
650
701
|
const pick = (tracks) => {
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
702
|
+
if (exactRecording) {
|
|
703
|
+
const found = tracks.filter(track => (track.preview_url || nativeId(track)) && matches(track));
|
|
704
|
+
return preferNamedCredit(found.filter(track => exactLibrarySong(wanted, track.title, [track.artist_credit])), cleanedArtist) ??
|
|
705
|
+
preferNamedCredit(found, cleanedArtist);
|
|
706
|
+
}
|
|
707
|
+
const playable = tracks.filter(track => track.preview_url || (nativeId(track) && matches(track)));
|
|
708
|
+
return namedRecording(playable, wantedTitle, cleanedArtist);
|
|
654
709
|
};
|
|
655
710
|
let track = pick(await client.searchTracks(`${cleanedArtist} ${cleanedTitle}`));
|
|
711
|
+
signal?.throwIfAborted();
|
|
656
712
|
if (!track && typeof client.artistSongs === "function") {
|
|
657
713
|
for (const named of await namedArtists(cleanedArtist)) {
|
|
714
|
+
signal?.throwIfAborted();
|
|
658
715
|
track = pick(await client.artistSongs(named.catalog_id));
|
|
659
716
|
if (track) break;
|
|
660
717
|
}
|
|
661
718
|
}
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
source: sourceMetadata(now, storefront),
|
|
665
|
-
...(track ? { track } : {}),
|
|
666
|
-
};
|
|
719
|
+
signal?.throwIfAborted();
|
|
720
|
+
return result(track);
|
|
667
721
|
},
|
|
668
722
|
|
|
669
|
-
// One named album's
|
|
670
|
-
async findAlbumPreviews({ title, artist } = {}) {
|
|
723
|
+
// One named album's playable recordings, in track order.
|
|
724
|
+
async findAlbumPreviews({ title, artist, allowCatalogOnly = false } = {}, { signal } = {}) {
|
|
725
|
+
signal?.throwIfAborted();
|
|
671
726
|
if (typeof client.searchAlbums !== "function" || typeof client.albumTracks !== "function") {
|
|
672
727
|
fail("apple_music_catalog_unavailable", "Album previews are unavailable.");
|
|
673
728
|
}
|
|
674
729
|
const cleanedTitle = cleanInputText(title, APPLE_MUSIC_CATALOG_LIMITS.discoveryQueryLengthMax, "apple_music_catalog_query_invalid", "album title");
|
|
675
730
|
const cleanedArtist = cleanInputText(artist, APPLE_MUSIC_CATALOG_LIMITS.discoveryQueryLengthMax, "apple_music_catalog_query_invalid", "artist");
|
|
676
731
|
const wantedTitle = normalizeForMatch(cleanedTitle);
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
albums.find((candidate) => normalizeForMatch(candidate.title).startsWith(wantedTitle));
|
|
680
|
-
let album = pick((await client.searchAlbums(`${cleanedArtist} ${cleanedTitle}`))
|
|
681
|
-
.filter((candidate) => normalizeForMatch(candidate.artist_credit).includes(wantedArtist)));
|
|
732
|
+
let album = namedRecording(await client.searchAlbums(`${cleanedArtist} ${cleanedTitle}`), wantedTitle, cleanedArtist, { album: true });
|
|
733
|
+
signal?.throwIfAborted();
|
|
682
734
|
if (!album) {
|
|
683
735
|
for (const named of await namedArtists(cleanedArtist)) {
|
|
684
|
-
|
|
736
|
+
signal?.throwIfAborted();
|
|
737
|
+
const release = namedRecording(await client.artistReleases(named.catalog_id), wantedTitle, cleanedArtist, { album: true });
|
|
685
738
|
if (!release) continue;
|
|
686
739
|
album = { catalog_id: release.catalog_id, title: release.title, artist_credit: release.artist_name,
|
|
687
740
|
...(release.catalog_url ? { catalog_url: release.catalog_url } : {}) };
|
|
688
741
|
break;
|
|
689
742
|
}
|
|
690
743
|
}
|
|
691
|
-
|
|
744
|
+
signal?.throwIfAborted();
|
|
745
|
+
const tracks = album ? (await client.albumTracks(album.catalog_id)).flatMap(track => {
|
|
746
|
+
const id = allowCatalogOnly && appleMusicSongId(track);
|
|
747
|
+
if (id) return [{ ...track, catalog_id: id }];
|
|
748
|
+
return track.preview_url ? [track] : [];
|
|
749
|
+
}).slice(0, 30) : [];
|
|
750
|
+
signal?.throwIfAborted();
|
|
692
751
|
return {
|
|
693
752
|
state: tracks.length ? "resolved" : "not_found",
|
|
694
753
|
source: sourceMetadata(now, storefront),
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
const songId = /^[1-9]\d{0,19}$/u;
|
|
2
|
+
|
|
3
|
+
// An Apple song URL names its recording directly. An album URL names it in the i parameter.
|
|
4
|
+
export function appleMusicSongId(track) {
|
|
5
|
+
const url = URL.parse(track?.catalog_url);
|
|
6
|
+
let linked = null;
|
|
7
|
+
if (url?.protocol === "https:" && url.hostname === "music.apple.com") {
|
|
8
|
+
if (/^\/(?:[a-z]{2}\/)?album\//u.test(url.pathname)) linked = url.searchParams.get("i");
|
|
9
|
+
else linked = /^\/(?:[a-z]{2}\/)?song\/(?:[^/]+\/)?([1-9]\d{0,19})\/?$/u.exec(url.pathname)?.[1] ?? null;
|
|
10
|
+
}
|
|
11
|
+
const id = track?.catalog_id ?? linked;
|
|
12
|
+
return typeof id === "string" && songId.test(id) && (!linked || linked === id) ? id : null;
|
|
13
|
+
}
|