@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.
- package/README.md +19 -8
- package/package.json +1 -1
- package/scripts/moondog.mjs +130 -106
- package/src/core/apple-library-source-status.mjs +64 -18
- package/src/core/apple-projection-domain-services.mjs +67 -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 +32 -18
- package/src/core/listening-scope.mjs +119 -0
- package/src/core/moondog-application.mjs +1045 -270
- package/src/core/play-follower.mjs +104 -0
- 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 +90 -26
- package/src/i18n/screen/ja.mjs +89 -25
- package/src/i18n/screen/pt.mjs +90 -26
- package/src/i18n/screen/zh.mjs +89 -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/music-app-listening.mjs +107 -0
- package/src/integrations/apple-music/music-app.mjs +6 -2
- 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 +19 -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 +133 -46
- package/src/profile/listener-profile-store.mjs +57 -4
- package/src/profile/listener-profile-verification.mjs +11 -5
- package/src/profile/listener-profile-worker.mjs +36 -10
- package/src/profile/listening-history-store.mjs +975 -354
- package/src/profile/listening-profile-projection.mjs +130 -160
- 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 +368 -221
- package/src/runtime/pi/custom-endpoints.mjs +30 -8
- package/src/runtime/pi/memory-agent-runtime.mjs +45 -3
- package/src/runtime/pi/moondog-model.mjs +6 -0
- package/src/runtime/pi/playback-rules.mjs +100 -0
- package/src/runtime/pi/profile-build-runtime.mjs +85 -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 -8
- 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
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// Only the adapter holds this occurrence. Reading the public queue returns its song.
|
|
2
|
+
import { COUNTED_PLAY_MS } from "../../core/play-follower.mjs";
|
|
3
|
+
|
|
4
|
+
const MIN_HEARD_MS = 2_000;
|
|
5
|
+
// Some ncm-cli clocks report only whole seconds.
|
|
6
|
+
const POSITION_SLACK_MS = 1_000;
|
|
7
|
+
|
|
8
|
+
export class NeteaseQueueOccurrence {
|
|
9
|
+
#keepAliveMs;
|
|
10
|
+
#started = false;
|
|
11
|
+
#finished = false;
|
|
12
|
+
#continuous = true;
|
|
13
|
+
#heardBeforeSegment = 0;
|
|
14
|
+
#segmentMoved = 0;
|
|
15
|
+
#segmentElapsed = 0;
|
|
16
|
+
#playingSince = null;
|
|
17
|
+
#elapsedSinceRead = 0;
|
|
18
|
+
#sample = null;
|
|
19
|
+
#paused = false;
|
|
20
|
+
#record = null;
|
|
21
|
+
#outcome = null;
|
|
22
|
+
|
|
23
|
+
constructor(song, keepAliveMs) {
|
|
24
|
+
this.song = song;
|
|
25
|
+
this.#keepAliveMs = keepAliveMs;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
bind(record) {
|
|
29
|
+
if (this.#finished && !this.#outcome) return;
|
|
30
|
+
if (typeof record !== "function") { this.discard(); return; }
|
|
31
|
+
this.#record = record;
|
|
32
|
+
this.#deliver();
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
get tracking() { return !this.#finished && this.#record !== null; }
|
|
36
|
+
|
|
37
|
+
#deliver() {
|
|
38
|
+
if (!this.#record || !this.#outcome) return;
|
|
39
|
+
const record = this.#record, result = this.#outcome;
|
|
40
|
+
this.#record = null;
|
|
41
|
+
this.#outcome = null;
|
|
42
|
+
try { record(result)?.catch?.(() => {}); } catch { /* Playback continues if the ledger is unavailable. */ }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
get #heardMs() {
|
|
46
|
+
// A whole-second clock can move one second and then two between 1.5-second reads.
|
|
47
|
+
// Bound the accumulated distance by elapsed playing time across the segment.
|
|
48
|
+
return this.#heardBeforeSegment + Math.max(0, Math.min(this.#segmentMoved, this.#segmentElapsed));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
#finish(outcome, at, limit = Infinity) {
|
|
52
|
+
this.#finished = true;
|
|
53
|
+
this.#sample = null;
|
|
54
|
+
this.#outcome = { outcome, heardMs: Math.round(Math.min(this.#heardMs, limit)), at: new Date(at).toISOString() };
|
|
55
|
+
this.#deliver();
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
discard() {
|
|
59
|
+
if (this.#finished) return;
|
|
60
|
+
this.#finished = true;
|
|
61
|
+
this.#sample = null;
|
|
62
|
+
this.#record = null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
start(now) {
|
|
66
|
+
// Going Back to a previously visited slot is the listener's replay of that recording.
|
|
67
|
+
if (this.#started) { this.discard(); return; }
|
|
68
|
+
this.#started = true;
|
|
69
|
+
this.observe(now);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
seek() {
|
|
73
|
+
this.#heardBeforeSegment = this.#heardMs;
|
|
74
|
+
this.#segmentMoved = 0;
|
|
75
|
+
this.#segmentElapsed = 0;
|
|
76
|
+
this.#playingSince = null;
|
|
77
|
+
this.#elapsedSinceRead = 0;
|
|
78
|
+
this.#sample = null;
|
|
79
|
+
this.#continuous = false;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
#tick(playing, at) {
|
|
83
|
+
if (this.#playingSince !== null) this.#elapsedSinceRead += Math.max(0, at - this.#playingSince);
|
|
84
|
+
this.#playingSince = playing ? at : null;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
setPaused(paused) {
|
|
88
|
+
if (!this.#started || this.#finished) return;
|
|
89
|
+
this.#paused = paused;
|
|
90
|
+
// The next read supplies the parked position. Count the time between the last
|
|
91
|
+
// poll and the pause, including when the listener resumes before the next poll.
|
|
92
|
+
this.#tick(!paused, Date.now());
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
observe(now) {
|
|
96
|
+
if (!this.#started || this.#finished) return;
|
|
97
|
+
if (!["playing", "paused", "stopped"].includes(now?.status) || !Number.isFinite(now.position) || now.position < 0) {
|
|
98
|
+
this.seek();
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
const at = Date.now();
|
|
102
|
+
const position = Math.round(now.position * 1000);
|
|
103
|
+
const playing = now.status === "playing" && !this.#paused;
|
|
104
|
+
this.#tick(playing, at);
|
|
105
|
+
const elapsed = this.#elapsedSinceRead;
|
|
106
|
+
this.#elapsedSinceRead = 0;
|
|
107
|
+
const previous = this.#sample;
|
|
108
|
+
if (previous) {
|
|
109
|
+
const moved = position - previous.position;
|
|
110
|
+
// An unexpected restart may be a second player selecting the same recording.
|
|
111
|
+
if (moved < -1000 && position < 5000) { this.discard(); return; }
|
|
112
|
+
if (at < previous.at || elapsed > Math.max(5_000, 4 * this.#keepAliveMs) ||
|
|
113
|
+
moved < -POSITION_SLACK_MS || moved > elapsed + POSITION_SLACK_MS) {
|
|
114
|
+
this.seek();
|
|
115
|
+
this.#playingSince = playing ? at : null;
|
|
116
|
+
} else if (elapsed > 0) {
|
|
117
|
+
this.#segmentMoved += moved;
|
|
118
|
+
this.#segmentElapsed += elapsed;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
this.#sample = { at, position, playing };
|
|
122
|
+
// A pause is also called "stopped". A known recording parked at its measured duration
|
|
123
|
+
// is an end only if its positions slowly reached that duration while it was playing.
|
|
124
|
+
const duration = Number.isFinite(now.duration) ? Math.round(now.duration * 1000) : 0;
|
|
125
|
+
if (now.status === "stopped" && !this.#paused && duration > 0 && position >= duration) {
|
|
126
|
+
const tolerance = Math.min(2_000, duration * 0.1);
|
|
127
|
+
if ((elapsed > 0 || previous?.playing) && this.#continuous && this.#heardMs >= MIN_HEARD_MS && this.#heardMs >= duration - tolerance) {
|
|
128
|
+
this.#finish("completed", at, duration);
|
|
129
|
+
} else this.discard();
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
handoff() {
|
|
134
|
+
if (this.#finished) return;
|
|
135
|
+
if (!this.#sample || this.#heardMs < MIN_HEARD_MS) { this.discard(); return; }
|
|
136
|
+
this.#finish(this.#heardMs < COUNTED_PLAY_MS ? "skipped" : "partial", this.#sample.at);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
@@ -30,7 +30,7 @@ export function parsePlaylistLink(text) {
|
|
|
30
30
|
}
|
|
31
31
|
|
|
32
32
|
// The page's text, bounded, from Apple's own host only and never through a redirect elsewhere.
|
|
33
|
-
async function applePage(url, fetchImpl, signal) {
|
|
33
|
+
async function applePage(url, id, fetchImpl, signal) {
|
|
34
34
|
let response;
|
|
35
35
|
try {
|
|
36
36
|
response = await fetchImpl(url, { redirect: "follow", signal: AbortSignal.any([AbortSignal.timeout(20_000), ...(signal ? [signal] : [])]),
|
|
@@ -39,7 +39,14 @@ async function applePage(url, fetchImpl, signal) {
|
|
|
39
39
|
if (signal?.aborted) throw error;
|
|
40
40
|
fail("playlist_unreachable", "Couldn't reach Apple Music. Check your connection and try the link again.");
|
|
41
41
|
}
|
|
42
|
-
if (response.url
|
|
42
|
+
if (response.url) {
|
|
43
|
+
let target;
|
|
44
|
+
try { target = parsePlaylistLink(response.url); } catch { /* The service can redirect to a sign-in or error page. */ }
|
|
45
|
+
if (target?.provider !== "apple_music" || target.id !== id) {
|
|
46
|
+
await response.body?.cancel();
|
|
47
|
+
fail("playlist_unavailable", "Apple Music did not return the linked playlist.");
|
|
48
|
+
}
|
|
49
|
+
}
|
|
43
50
|
if (!response.ok) { await response.body?.cancel(); fail("playlist_unavailable", "Apple Music didn't show this playlist. Check that it opens in a browser without signing in."); }
|
|
44
51
|
const chunks = [];
|
|
45
52
|
let size = 0;
|
|
@@ -59,51 +66,107 @@ const text = (value, maximum = 200) => (typeof value === "string" ? Array.from(v
|
|
|
59
66
|
* wide share card). A long playlist's page may list only its first songs;
|
|
60
67
|
* read and total say how many.
|
|
61
68
|
*/
|
|
62
|
-
export async function readApplePlaylist({ id, url }, { fetchImpl = fetch, signal } = {}) {
|
|
63
|
-
const html = await applePage(url, fetchImpl, signal);
|
|
69
|
+
export async function readApplePlaylist({ id, url, storefront }, { fetchImpl = fetch, signal, readCatalog } = {}) {
|
|
70
|
+
const html = await applePage(url, id, fetchImpl, signal);
|
|
64
71
|
const block = (pattern) => { const match = pattern.exec(html); try { return match ? JSON.parse(match[1]) : null; } catch { return null; } };
|
|
65
|
-
const
|
|
72
|
+
const schemaBlock = block(/<script[^>]*id=["']?schema:music-playlist["']?[^>]*>([\s\S]*?)<\/script>/u) ?? block(/<script[^>]*application\/ld\+json[^>]*>([\s\S]*?)<\/script>/u);
|
|
73
|
+
const schema = schemaBlock?.["@type"] === "MusicPlaylist" ? schemaBlock : null;
|
|
74
|
+
let schemaForPlaylist = false;
|
|
75
|
+
if (typeof schema?.url === "string") {
|
|
76
|
+
try { schemaForPlaylist = parsePlaylistLink(schema.url).id === id; } catch { /* Older schemas have no usable playlist identity. */ }
|
|
77
|
+
}
|
|
66
78
|
const data = block(/<script[^>]*id="serialized-server-data"[^>]*>([\s\S]*?)<\/script>/u);
|
|
67
|
-
const
|
|
68
|
-
const
|
|
79
|
+
const belongs = (descriptor) => descriptor?.kind === "playlist" && descriptor.identifiers?.storeAdamID === id;
|
|
80
|
+
const pages = Array.isArray(data?.data) ? data.data.filter((page) => !page?.intent?.contentDescriptor || belongs(page.intent.contentDescriptor)) : null;
|
|
81
|
+
const sections = (pages ?? []).flatMap((page) => Array.isArray(page?.data?.sections) ? page.data.sections : []);
|
|
82
|
+
const listId = `track-list - ${id}`;
|
|
83
|
+
const isPlaylistTrackList = (section) => section?.id === listId && section.itemKind === "trackLockup" &&
|
|
84
|
+
belongs(section.containerContentDescriptor) && Array.isArray(section.items);
|
|
85
|
+
const lists = sections.filter(isPlaylistTrackList);
|
|
86
|
+
const hasMoreTracks = pages?.some((page) => {
|
|
87
|
+
const { nextIntent, sections } = page?.data ?? {};
|
|
88
|
+
return nextIntent?.$kind === "PlaylistPaginationIntent" && nextIntent.id === id &&
|
|
89
|
+
(belongs(page?.intent?.contentDescriptor) || (Array.isArray(sections) && sections.some(isPlaylistTrackList)));
|
|
90
|
+
});
|
|
69
91
|
const artworkAt = (node, size) => {
|
|
70
92
|
const url = node.artwork?.dictionary?.url;
|
|
71
93
|
return typeof url === "string" && url.startsWith("https://") ? url.replace("{w}x{h}", `${size}x${size}`).replace("{c}", "").replace("{f}", "jpg") : null;
|
|
72
94
|
};
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
95
|
+
const recordingId = (node) => node?.contentDescriptor?.kind === "song" ? String(node.contentDescriptor.identifiers?.storeAdamID ?? "") : "";
|
|
96
|
+
const trackOf = (node) => {
|
|
97
|
+
const catalog = recordingId(node);
|
|
98
|
+
const title = text(node?.title);
|
|
99
|
+
const artist = text(node?.artistName);
|
|
100
|
+
if (!/^\d{1,20}$/u.test(catalog) || !title || !artist) return null;
|
|
101
|
+
const artwork = artworkAt(node, 300);
|
|
102
|
+
return { id: catalog, title, artist, ...(artwork ? { artwork } : {}) };
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
// Older pages expose unnamed lockups in several rendering sections. Keep them readable for import.
|
|
106
|
+
// Only the requested playlist's own ordered list establishes membership, including repeated recordings.
|
|
107
|
+
const header = sections.find((section) => section?.id === `playlist-detail-header-section - ${id}` && section.itemKind === "containerDetailHeaderLockup");
|
|
108
|
+
let own = Array.isArray(header?.items) ? header.items.find((item) => belongs(item?.contentDescriptor) && typeof item.title === "string") : null;
|
|
109
|
+
const legacy = [];
|
|
110
|
+
const seen = new Set();
|
|
78
111
|
const walk = (node, depth) => {
|
|
79
|
-
if (!node || typeof node !== "object" || depth > 12 ||
|
|
112
|
+
if (!node || typeof node !== "object" || depth > 12 || (own && lists.length)) return;
|
|
80
113
|
if (Array.isArray(node)) { for (const each of node) walk(each, depth + 1); return; }
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
if (!own && node.contentDescriptor
|
|
84
|
-
if (
|
|
85
|
-
const
|
|
86
|
-
if (!seen.has(
|
|
87
|
-
seen.add(key);
|
|
88
|
-
const artwork = artworkAt(node, 300);
|
|
89
|
-
tracks.push({ id: key, title: text(node.title), artist: text(node.artistName), ...(artwork ? { artwork } : {}) });
|
|
90
|
-
}
|
|
114
|
+
if (node.containerContentDescriptor && !belongs(node.containerContentDescriptor)) return;
|
|
115
|
+
if (node.itemKind === "trackLockup" && node.id && node.id !== listId) return;
|
|
116
|
+
if (!own && belongs(node.contentDescriptor) && typeof node.title === "string") own = node;
|
|
117
|
+
if (!lists.length && legacy.length < 2000 && node.contentDescriptor?.kind === "song") {
|
|
118
|
+
const track = trackOf(node);
|
|
119
|
+
if (track && !seen.has(track.id)) { legacy.push(track); seen.add(track.id); }
|
|
91
120
|
return;
|
|
92
121
|
}
|
|
93
122
|
for (const value of Object.values(node)) walk(value, depth + 1);
|
|
94
123
|
};
|
|
95
|
-
walk(data, 0);
|
|
124
|
+
walk(pages ?? data, 0);
|
|
125
|
+
const first = lists[0]?.items;
|
|
126
|
+
const tracks = first ? first.slice(0, 2000).map(trackOf).filter(Boolean) : legacy;
|
|
96
127
|
const name = text(own?.title) || text(schema?.name) || text(/<meta property="og:title" content="([^"]+)"/u.exec(html)?.[1]) || "Apple Music playlist";
|
|
97
|
-
const
|
|
98
|
-
const
|
|
99
|
-
|
|
100
|
-
|
|
128
|
+
const countOf = (value) => /^\d+$/u.test(String(value)) && Number.isSafeInteger(Number(value)) ? Number(value) : null;
|
|
129
|
+
const schemaCount = schema?.url && !schemaForPlaylist ? null : schema?.numTracks;
|
|
130
|
+
const counts = [own?.trackCount, schemaCount].filter((value) => value != null).map(countOf);
|
|
131
|
+
// Apple can put the current page's row count in both fields even when another page follows.
|
|
132
|
+
const visibleRows = first?.length ?? tracks.length;
|
|
133
|
+
const total = counts.find((value) => value !== null && (!hasMoreTracks || value > visibleRows)) ?? null;
|
|
134
|
+
if (!tracks.length && !(total === 0 && (own || schema))) fail("playlist_unavailable", "Apple Music didn't list the songs of this playlist. Check that it is shared publicly.");
|
|
135
|
+
// A repeated rendering of this list is harmless only when it names the same occurrences in order.
|
|
136
|
+
const verifiedCount = countOf(own?.trackCount) ?? (schemaForPlaylist ? countOf(schemaCount) : null);
|
|
137
|
+
const complete = Boolean(!hasMoreTracks && first && first.length === tracks.length && verifiedCount === tracks.length && counts.every((count) => count === total) &&
|
|
138
|
+
lists.every(({ items }) => items.length === first.length && items.every((row, i) => recordingId(row) === tracks[i].id)));
|
|
139
|
+
const cover = own ? artworkAt(own, 600) : null;
|
|
140
|
+
const preview = { provider: "apple_music", id, url, name, ...(cover ? { cover } : {}), complete,
|
|
141
|
+
total: total !== null && total >= tracks.length ? total : null, tracks };
|
|
142
|
+
if (complete || !readCatalog || !storefront) return preview;
|
|
143
|
+
|
|
144
|
+
let catalog;
|
|
145
|
+
try { catalog = await readCatalog({ id, storefront }, { signal }); }
|
|
146
|
+
catch { signal?.throwIfAborted(); return preview; }
|
|
147
|
+
signal?.throwIfAborted();
|
|
148
|
+
if (catalog?.id !== id || catalog.storefront !== storefront || !Array.isArray(catalog.tracks)) return preview;
|
|
149
|
+
const count = Number.isSafeInteger(catalog.total) && catalog.total >= catalog.tracks.length ? catalog.total : null;
|
|
150
|
+
const catalogComplete = catalog.complete === true && count === catalog.tracks.length;
|
|
151
|
+
// If Apple has just edited a playlist, its page and its catalog can disagree on its size.
|
|
152
|
+
// A shorter response cannot authorize removing songs the same read still sees on the page.
|
|
153
|
+
if (catalog.tracks.length < tracks.length || (!catalogComplete && catalog.tracks.length === tracks.length)) {
|
|
154
|
+
return count !== null && count >= tracks.length && preview.total === null ? { ...preview, total: count } : preview;
|
|
155
|
+
}
|
|
156
|
+
// The catalog gives playlist order, including repeated songs. Keep covers from the public page by recording ID.
|
|
157
|
+
const artwork = new Map(tracks.filter(track => track.artwork).map(track => [track.id, track.artwork]));
|
|
158
|
+
const consistent = count === null || preview.total === null || count >= preview.total;
|
|
159
|
+
const knownTotal = count ?? preview.total;
|
|
160
|
+
return { ...preview, complete: catalogComplete && consistent,
|
|
161
|
+
total: consistent && knownTotal >= catalog.tracks.length ? knownTotal : null,
|
|
162
|
+
tracks: catalog.tracks.map(track => artwork.has(track.id) ? { ...track, artwork: artwork.get(track.id) } : track) };
|
|
101
163
|
}
|
|
102
164
|
|
|
103
165
|
/** A NetEase Music or QQ Music playlist through its public share link, as library songs. */
|
|
104
|
-
export async function readPublicPlaylistLink({ url }, { fetchImpl = fetch } = {}) {
|
|
166
|
+
export async function readPublicPlaylistLink({ url }, { fetchImpl = fetch, signal } = {}) {
|
|
105
167
|
// The public reader explains itself in words; the library's surfaces also need its kind, to say it in their language.
|
|
106
|
-
const playlist = await fetchPublicPlaylist({ input: url, fetchImpl }).catch((error) => {
|
|
168
|
+
const playlist = await fetchPublicPlaylist({ input: url, fetchImpl, signal }).catch((error) => {
|
|
169
|
+
signal?.throwIfAborted();
|
|
107
170
|
// Only the link checks' own refusals are about the link; any answer the service gave is about the playlist.
|
|
108
171
|
const aboutLink = /^(Paste a QQ Music|Use a playlist link|Open this share link|This link belongs to another service)/u;
|
|
109
172
|
if (!error.code) error.code = /^Could not reach/u.test(error.message) ? "playlist_unreachable" : aboutLink.test(error.message) ? "playlist_link_unsupported" : "playlist_unavailable";
|
|
@@ -34,11 +34,14 @@ function playlistIdentity(url) {
|
|
|
34
34
|
return null;
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
-
async function responseFor(url, fetchImpl, referer) {
|
|
37
|
+
async function responseFor(url, fetchImpl, referer, signal) {
|
|
38
38
|
try {
|
|
39
|
-
return await fetchImpl(url, { redirect: "manual", signal: AbortSignal.timeout(15_000),
|
|
39
|
+
return await fetchImpl(url, { redirect: "manual", signal: AbortSignal.any([AbortSignal.timeout(15_000), ...(signal ? [signal] : [])]),
|
|
40
40
|
headers: { "User-Agent": "Mozilla/5.0 (compatible; Moondog music metadata import)", ...(referer ? { Referer: referer } : {}) } });
|
|
41
|
-
} catch {
|
|
41
|
+
} catch {
|
|
42
|
+
signal?.throwIfAborted();
|
|
43
|
+
throw new Error("Could not reach the music service. Check your connection and try the same playlist link again.");
|
|
44
|
+
}
|
|
42
45
|
}
|
|
43
46
|
|
|
44
47
|
async function boundedJson(response) {
|
|
@@ -59,32 +62,34 @@ async function boundedJson(response) {
|
|
|
59
62
|
// details for only the first few without a sign-in; the rest come from song/detail, 200 at a time, in the
|
|
60
63
|
// playlist's order. The older endpoint, which some playlists answer with code 20001, is the fallback.
|
|
61
64
|
const NETEASE_SONGS_MAX = 3000;
|
|
62
|
-
async function neteasePlaylist(id, fetchImpl) {
|
|
65
|
+
async function neteasePlaylist(id, fetchImpl, signal) {
|
|
63
66
|
const referer = "https://music.163.com/";
|
|
64
|
-
const current = await boundedJson(await responseFor(`https://music.163.com/api/v6/playlist/detail?id=${id}&n=100000`, fetchImpl, referer)).catch(() => null);
|
|
67
|
+
const current = await boundedJson(await responseFor(`https://music.163.com/api/v6/playlist/detail?id=${id}&n=100000`, fetchImpl, referer, signal)).catch(() => { signal?.throwIfAborted(); return null; });
|
|
65
68
|
const playlist = current?.code === 200 ? current.playlist : null;
|
|
66
69
|
if (!playlist || !Array.isArray(playlist.trackIds)) {
|
|
67
|
-
return boundedJson(await responseFor(`https://music.163.com/api/playlist/detail?id=${id}`, fetchImpl, referer));
|
|
70
|
+
return boundedJson(await responseFor(`https://music.163.com/api/playlist/detail?id=${id}`, fetchImpl, referer, signal));
|
|
68
71
|
}
|
|
69
72
|
const ids = playlist.trackIds.map((entry) => String(entry?.id ?? "")).filter((value) => numericId.test(value)).slice(0, NETEASE_SONGS_MAX);
|
|
70
73
|
const songs = new Map((Array.isArray(playlist.tracks) ? playlist.tracks : []).map((song) => [String(song?.id ?? ""), song]));
|
|
71
74
|
const missing = ids.filter((songId) => !songs.has(songId));
|
|
72
75
|
for (let start = 0; start < missing.length; start += 200) {
|
|
73
76
|
const batch = missing.slice(start, start + 200);
|
|
74
|
-
const detail = await boundedJson(await responseFor(`https://music.163.com/api/song/detail/?ids=${encodeURIComponent(`[${batch.join(",")}]`)}`, fetchImpl, referer));
|
|
77
|
+
const detail = await boundedJson(await responseFor(`https://music.163.com/api/song/detail/?ids=${encodeURIComponent(`[${batch.join(",")}]`)}`, fetchImpl, referer, signal));
|
|
75
78
|
for (const song of Array.isArray(detail?.songs) ? detail.songs : []) songs.set(String(song?.id ?? ""), song);
|
|
76
79
|
}
|
|
77
|
-
|
|
80
|
+
// Some playlists expose only part of their ID list. An undercount cannot prove an empty source.
|
|
81
|
+
const total = Number(playlist.trackCount) < playlist.trackIds.length ? null : playlist.trackCount;
|
|
82
|
+
return { code: 200, result: { id: playlist.id, name: playlist.name, coverImgUrl: playlist.coverImgUrl, privacy: playlist.privacy, trackCount: total,
|
|
78
83
|
tracks: ids.map((songId) => songs.get(songId)).filter(Boolean) } };
|
|
79
84
|
}
|
|
80
85
|
|
|
81
86
|
/** A public QQ Music or NetEase playlist by its share link: { provider, id, url, name, total, rows, skipped }. */
|
|
82
|
-
export async function fetchPublicPlaylist({ input, provider, fetchImpl = fetch }) {
|
|
87
|
+
export async function fetchPublicPlaylist({ input, provider, fetchImpl = fetch, signal }) {
|
|
83
88
|
let url = playlistLink(input);
|
|
84
89
|
let identity = playlistIdentity(url);
|
|
85
90
|
// Follow only official share redirects, never arbitrary network destinations or cookies.
|
|
86
91
|
for (let index = 0; !identity && index < 4; index += 1) {
|
|
87
|
-
const response = await responseFor(url, fetchImpl);
|
|
92
|
+
const response = await responseFor(url, fetchImpl, undefined, signal);
|
|
88
93
|
const location = response.headers.get("location");
|
|
89
94
|
await response.body?.cancel();
|
|
90
95
|
if (response.status < 300 || response.status >= 400 || !location) break;
|
|
@@ -95,8 +100,8 @@ export async function fetchPublicPlaylist({ input, provider, fetchImpl = fetch }
|
|
|
95
100
|
if (provider && ["qq_music", "netease"].includes(provider) && provider !== identity.provider) throw new Error("This link belongs to another service. Go back and choose that service, or paste the matching playlist link.");
|
|
96
101
|
const qq = identity.provider === "qq_music";
|
|
97
102
|
const data = qq
|
|
98
|
-
? await boundedJson(await responseFor(`https://c.y.qq.com/qzone/fcg-bin/fcg_ucc_getcdinfo_byids_cp.fcg?type=1&json=1&utf8=1&onlysong=0&disstid=${identity.id}&format=json`, fetchImpl, "https://y.qq.com/"))
|
|
99
|
-
: await neteasePlaylist(identity.id, fetchImpl);
|
|
103
|
+
? await boundedJson(await responseFor(`https://c.y.qq.com/qzone/fcg-bin/fcg_ucc_getcdinfo_byids_cp.fcg?type=1&json=1&utf8=1&onlysong=0&disstid=${identity.id}&format=json`, fetchImpl, "https://y.qq.com/", signal))
|
|
104
|
+
: await neteasePlaylist(identity.id, fetchImpl, signal);
|
|
100
105
|
const playlist = qq ? data?.cdlist?.[0] : data?.result;
|
|
101
106
|
if ((qq ? data?.code !== 0 || data?.subcode !== 0 : data?.code !== 200) || !playlist
|
|
102
107
|
|| (qq ? Number(playlist.dir_show) === 0 : Number(playlist.privacy) === 10)) throw new Error("This playlist is unavailable publicly. Choose a playlist you can open without signing in; no account password or cookies are needed.");
|
|
@@ -104,7 +109,8 @@ export async function fetchPublicPlaylist({ input, provider, fetchImpl = fetch }
|
|
|
104
109
|
const songs = qq ? playlist.songlist : playlist.tracks;
|
|
105
110
|
if (!Array.isArray(songs) || songs.length > 10_000) throw new Error("The playlist format is unsupported or exceeds 10,000 songs.");
|
|
106
111
|
const name = musicText(qq ? playlist.dissname : playlist.name) || "Selected playlist";
|
|
107
|
-
const
|
|
112
|
+
const count = qq ? playlist.total_song_num ?? playlist.songnum : playlist.trackCount;
|
|
113
|
+
const totalValue = /^\d+$/u.test(String(count)) ? Number(count) : NaN;
|
|
108
114
|
const total = Number.isSafeInteger(totalValue) && totalValue >= songs.length ? totalValue : null;
|
|
109
115
|
const rows = songs.map((song, index) => {
|
|
110
116
|
if (!song || typeof song !== "object") return {};
|
|
@@ -124,8 +130,8 @@ export async function fetchPublicPlaylist({ input, provider, fetchImpl = fetch }
|
|
|
124
130
|
return { provider: identity.provider, id: identity.id, url: url.href, name, total, rows, skipped: songs.length - rows.length, ...(cover ? { cover } : {}) };
|
|
125
131
|
}
|
|
126
132
|
|
|
127
|
-
export async function readPublicPlaylist({ input, subjectId, capturedAt, provider, fetchImpl = fetch }) {
|
|
128
|
-
const { provider: source, id, name, total, rows, skipped } = await fetchPublicPlaylist({ input, provider, fetchImpl });
|
|
133
|
+
export async function readPublicPlaylist({ input, subjectId, capturedAt, provider, fetchImpl = fetch, signal }) {
|
|
134
|
+
const { provider: source, id, name, total, rows, skipped } = await fetchPublicPlaylist({ input, provider, fetchImpl, signal });
|
|
129
135
|
const bytes = Buffer.from(JSON.stringify({ provider: source, id, name, rows }));
|
|
130
136
|
const prepared = prepareMusicBundle({ provider: source, subjectId, capturedAt, rows,
|
|
131
137
|
digest: musicHash(bytes), size: bytes.length, members: ["public-playlist.json"], fileName: name, skipped,
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
|
-
import { createReadStream } from "node:fs";
|
|
3
2
|
import { lstat } from "node:fs/promises";
|
|
4
3
|
import path from "node:path";
|
|
5
4
|
import { openZipArchive } from "../../importers/zip-reader.mjs";
|
|
@@ -368,12 +367,6 @@ export function projectSpotifyAccountDataHistory({
|
|
|
368
367
|
};
|
|
369
368
|
}
|
|
370
369
|
|
|
371
|
-
async function sha256File(filePath) {
|
|
372
|
-
const hash = createHash("sha256");
|
|
373
|
-
for await (const chunk of createReadStream(filePath)) hash.update(chunk);
|
|
374
|
-
return hash.digest("hex");
|
|
375
|
-
}
|
|
376
|
-
|
|
377
370
|
async function openArchive(archivePath) {
|
|
378
371
|
try {
|
|
379
372
|
return await openZipArchive(archivePath);
|
|
@@ -446,6 +439,7 @@ export async function readSpotifyAccountDataHistoryArchive({
|
|
|
446
439
|
archivePath,
|
|
447
440
|
subjectId,
|
|
448
441
|
capturedAt = new Date().toISOString(),
|
|
442
|
+
onProgress,
|
|
449
443
|
} = {}) {
|
|
450
444
|
if (typeof archivePath !== "string" || !archivePath.trim()) {
|
|
451
445
|
fail("A Spotify account-data ZIP path is required.");
|
|
@@ -475,6 +469,7 @@ export async function readSpotifyAccountDataHistoryArchive({
|
|
|
475
469
|
// One open archive serves the listing and every member, and is closed even when a check fails.
|
|
476
470
|
const archive = await openArchive(resolvedPath);
|
|
477
471
|
let members;
|
|
472
|
+
let archiveSha256;
|
|
478
473
|
let profileMembers;
|
|
479
474
|
const records = [];
|
|
480
475
|
const documents = {};
|
|
@@ -482,6 +477,8 @@ export async function readSpotifyAccountDataHistoryArchive({
|
|
|
482
477
|
const listing = archive.names.join("\n");
|
|
483
478
|
members = selectedMusicMembers(listing);
|
|
484
479
|
profileMembers = selectedProfileMembers(listing);
|
|
480
|
+
const total = members.length + profileMembers.length;
|
|
481
|
+
let count = 0;
|
|
485
482
|
let totalJsonBytes = 0;
|
|
486
483
|
for (const member of members) {
|
|
487
484
|
const jsonText = await zipText(archive, SPOTIFY_ACCOUNT_DATA_HISTORY_LIMITS.maximumMemberBytes, member.name);
|
|
@@ -501,10 +498,11 @@ export async function readSpotifyAccountDataHistoryArchive({
|
|
|
501
498
|
if (!Array.isArray(parsed)) {
|
|
502
499
|
fail(`Spotify music history segment ${member.index} is not an array.`);
|
|
503
500
|
}
|
|
504
|
-
records.
|
|
505
|
-
if (records.length > SPOTIFY_ACCOUNT_DATA_HISTORY_LIMITS.maximumRecords) {
|
|
501
|
+
if (records.length + parsed.length > SPOTIFY_ACCOUNT_DATA_HISTORY_LIMITS.maximumRecords) {
|
|
506
502
|
fail("Spotify music history contains too many records.");
|
|
507
503
|
}
|
|
504
|
+
for (const record of parsed) records.push(record);
|
|
505
|
+
onProgress?.({ stage: "files", count: ++count, total });
|
|
508
506
|
}
|
|
509
507
|
|
|
510
508
|
for (const member of profileMembers) {
|
|
@@ -523,12 +521,13 @@ export async function readSpotifyAccountDataHistoryArchive({
|
|
|
523
521
|
} catch {
|
|
524
522
|
fail(`Spotify account-profile file ${member.basename} is invalid JSON.`);
|
|
525
523
|
}
|
|
524
|
+
onProgress?.({ stage: "files", count: ++count, total });
|
|
526
525
|
}
|
|
526
|
+
archiveSha256 = await archive.digest(file);
|
|
527
527
|
} finally {
|
|
528
528
|
archive.close();
|
|
529
529
|
}
|
|
530
530
|
|
|
531
|
-
const archiveSha256 = await sha256File(resolvedPath);
|
|
532
531
|
const historyBundle = projectSpotifyAccountDataHistory({
|
|
533
532
|
subjectId,
|
|
534
533
|
records,
|
|
@@ -440,6 +440,7 @@ function playlistEvidence(document, context) {
|
|
|
440
440
|
playlist_ref_id: playlistRef,
|
|
441
441
|
playlist_name: name,
|
|
442
442
|
playlist_position: itemIndex + 1,
|
|
443
|
+
...(addedAt ? { playlist_added_at: addedAt } : {}),
|
|
443
444
|
...(modifiedAt ? { playlist_modified_at: modifiedAt } : {}),
|
|
444
445
|
},
|
|
445
446
|
});
|