@audiofool/moondog 0.3.0-beta.9 → 0.3.0
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 +40 -12
- package/package.json +5 -4
- package/scripts/moondog.mjs +47 -9
- package/src/core/apple-projection-domain-services.mjs +4 -0
- package/src/core/capability-catalog.mjs +46 -14
- package/src/core/host.mjs +30 -0
- package/src/core/library-store.mjs +82 -6
- package/src/core/listening-now.mjs +7 -2
- package/src/core/listening-profile-domain-services.mjs +4 -0
- package/src/core/moondog-application.mjs +412 -144
- package/src/i18n/messages/de.mjs +4 -3
- package/src/i18n/messages/en.mjs +4 -3
- package/src/i18n/messages/es.mjs +4 -3
- package/src/i18n/messages/fr.mjs +4 -3
- package/src/i18n/messages/it.mjs +4 -3
- package/src/i18n/messages/ja.mjs +4 -3
- package/src/i18n/messages/ko.mjs +4 -3
- package/src/i18n/messages/pt.mjs +4 -3
- package/src/i18n/messages/zh-Hant.mjs +4 -3
- package/src/i18n/messages/zh.mjs +4 -3
- package/src/i18n/screen/es.mjs +52 -6
- package/src/i18n/screen/ja.mjs +52 -6
- package/src/i18n/screen/pt.mjs +52 -6
- package/src/i18n/screen/zh.mjs +52 -6
- package/src/importers/zip-reader.mjs +61 -0
- package/src/integrations/apple-music/music-app.mjs +3 -2
- package/src/integrations/lastfm/history.mjs +2 -1
- package/src/integrations/lyrics/lrclib.mjs +1 -1
- package/src/integrations/netease/ncm-cli-player.mjs +62 -20
- package/src/integrations/open-music-similarity/artist-radio.mjs +3 -3
- package/src/integrations/playlist-links.mjs +114 -0
- package/src/integrations/public-playlists.mjs +41 -8
- package/src/integrations/spotify/account-data-history.mjs +63 -57
- package/src/integrations/spotify/authentication.mjs +2 -22
- package/src/integrations/spotify/extended-streaming-history.mjs +48 -40
- package/src/integrations/spotify/history-archive.mjs +2 -13
- package/src/integrations/spotify/service.mjs +88 -58
- package/src/integrations/spotify/web-api-client.mjs +12 -4
- package/src/integrations/user-agent.mjs +6 -0
- package/src/integrations/web/codex-web.mjs +3 -1
- package/src/integrations/web/deepseek-web.mjs +1 -1
- package/src/integrations/web/web-research.mjs +84 -17
- package/src/integrations/web/web-result.mjs +60 -12
- package/src/integrations/youtube-music/takeout.mjs +11 -16
- package/src/profile/history-import.mjs +3 -1
- package/src/profile/listening-history-store.mjs +55 -1
- package/src/profile/listening-profile-projection.mjs +1 -1
- package/src/profile/music-import-bundle.mjs +3 -1
- package/src/profile/music-providers.mjs +3 -0
- package/src/runtime/pi/agent-runtime.mjs +244 -146
- package/src/runtime/pi/configured-runtime.mjs +3 -0
- package/src/runtime/pi/image-input.mjs +148 -0
- package/src/runtime/pi/model-roles.mjs +121 -0
- package/src/runtime/pi/model-settings.mjs +112 -6
- package/src/runtime/pi/model-transport.mjs +9 -0
- package/src/runtime/pi/moondog-model.mjs +158 -0
- package/src/runtime/pi/next-songs.mjs +71 -0
- package/src/runtime/pi/persistent-credential-store.mjs +2 -0
- package/src/runtime/pi/public-model-catalog.mjs +10 -3
- package/src/runtime/pi/runtime-settings.mjs +7 -3
- package/src/surfaces/cli/brand-components.mjs +1 -1
- package/src/surfaces/cli/command-completions.mjs +43 -3
- package/src/surfaces/cli/format-output.mjs +19 -7
- package/src/surfaces/cli/invite-command.mjs +65 -0
- package/src/surfaces/cli/model-roles-command.mjs +60 -0
- package/src/surfaces/cli/tui.mjs +87 -5
|
@@ -54,7 +54,32 @@ async function boundedJson(response) {
|
|
|
54
54
|
catch { throw new Error("The service changed its playlist response or requires sign-in. No music was imported."); }
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
-
|
|
57
|
+
// A NetEase playlist, as { code, result: { id, name, privacy, trackCount, tracks } }. NetEase's web player reads
|
|
58
|
+
// playlists with v6, which answers every public one, a listener's Liked songs among them, with all its song ids but
|
|
59
|
+
// details for only the first few without a sign-in; the rest come from song/detail, 200 at a time, in the
|
|
60
|
+
// playlist's order. The older endpoint, which some playlists answer with code 20001, is the fallback.
|
|
61
|
+
const NETEASE_SONGS_MAX = 3000;
|
|
62
|
+
async function neteasePlaylist(id, fetchImpl) {
|
|
63
|
+
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);
|
|
65
|
+
const playlist = current?.code === 200 ? current.playlist : null;
|
|
66
|
+
if (!playlist || !Array.isArray(playlist.trackIds)) {
|
|
67
|
+
return boundedJson(await responseFor(`https://music.163.com/api/playlist/detail?id=${id}`, fetchImpl, referer));
|
|
68
|
+
}
|
|
69
|
+
const ids = playlist.trackIds.map((entry) => String(entry?.id ?? "")).filter((value) => numericId.test(value)).slice(0, NETEASE_SONGS_MAX);
|
|
70
|
+
const songs = new Map((Array.isArray(playlist.tracks) ? playlist.tracks : []).map((song) => [String(song?.id ?? ""), song]));
|
|
71
|
+
const missing = ids.filter((songId) => !songs.has(songId));
|
|
72
|
+
for (let start = 0; start < missing.length; start += 200) {
|
|
73
|
+
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));
|
|
75
|
+
for (const song of Array.isArray(detail?.songs) ? detail.songs : []) songs.set(String(song?.id ?? ""), song);
|
|
76
|
+
}
|
|
77
|
+
return { code: 200, result: { id: playlist.id, name: playlist.name, coverImgUrl: playlist.coverImgUrl, privacy: playlist.privacy, trackCount: playlist.trackCount ?? ids.length,
|
|
78
|
+
tracks: ids.map((songId) => songs.get(songId)).filter(Boolean) } };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** 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 }) {
|
|
58
83
|
let url = playlistLink(input);
|
|
59
84
|
let identity = playlistIdentity(url);
|
|
60
85
|
// Follow only official share redirects, never arbitrary network destinations or cookies.
|
|
@@ -69,10 +94,9 @@ export async function readPublicPlaylist({ input, subjectId, capturedAt, provide
|
|
|
69
94
|
if (!identity) throw new Error("Open this share link in your browser, then copy the full playlist page URL. Song, album and private playlist links are not supported.");
|
|
70
95
|
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.");
|
|
71
96
|
const qq = identity.provider === "qq_music";
|
|
72
|
-
const
|
|
73
|
-
? `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
|
|
74
|
-
:
|
|
75
|
-
const data = await boundedJson(await responseFor(endpoint, fetchImpl, qq ? "https://y.qq.com/" : "https://music.163.com/"));
|
|
97
|
+
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);
|
|
76
100
|
const playlist = qq ? data?.cdlist?.[0] : data?.result;
|
|
77
101
|
if ((qq ? data?.code !== 0 || data?.subcode !== 0 : data?.code !== 200) || !playlist
|
|
78
102
|
|| (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.");
|
|
@@ -90,12 +114,21 @@ export async function readPublicPlaylist({ input, subjectId, capturedAt, provide
|
|
|
90
114
|
title: musicText(qq ? song.songname : song.name),
|
|
91
115
|
artist: musicText(Array.isArray(artists) ? artists.map((artist) => musicText(artist?.name)).filter(Boolean).join(", ") : ""),
|
|
92
116
|
album: musicText(qq ? song.albumname : (song.album ?? song.al)?.name),
|
|
117
|
+
// NetEase names each album cover on its own image host; it is shown over https.
|
|
118
|
+
...(!qq && /^https?:\/\/p[0-9]+\.music\.126\.net\//u.test((song.album ?? song.al)?.picUrl ?? "") ? { artwork: (song.album ?? song.al).picUrl.replace(/^http:/u, "https:") } : {}),
|
|
93
119
|
playlistId: identity.id, playlistName: name, position: index + 1, member: "public-playlist.json",
|
|
94
120
|
};
|
|
95
121
|
}).filter((row) => row.id && row.title);
|
|
96
|
-
|
|
97
|
-
const
|
|
98
|
-
|
|
122
|
+
// NetEase's own image host, shown over https, as a song's cover is.
|
|
123
|
+
const cover = !qq && /^https?:\/\/p[0-9]+\.music\.126\.net\//u.test(playlist.coverImgUrl ?? "") ? playlist.coverImgUrl.replace(/^http:/u, "https:") : null;
|
|
124
|
+
return { provider: identity.provider, id: identity.id, url: url.href, name, total, rows, skipped: songs.length - rows.length, ...(cover ? { cover } : {}) };
|
|
125
|
+
}
|
|
126
|
+
|
|
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 });
|
|
129
|
+
const bytes = Buffer.from(JSON.stringify({ provider: source, id, name, rows }));
|
|
130
|
+
const prepared = prepareMusicBundle({ provider: source, subjectId, capturedAt, rows,
|
|
131
|
+
digest: musicHash(bytes), size: bytes.length, members: ["public-playlist.json"], fileName: name, skipped,
|
|
99
132
|
scopeNote: `${rows.length} of ${total ?? "an unknown number of"} songs could be read; the service hides some. Only this playlist is added. It shows what you keep, not what you played, and it may not be one you made.`,
|
|
100
133
|
});
|
|
101
134
|
prepared.preview.source = "public-playlist";
|
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
import { execFile } from "node:child_process";
|
|
2
1
|
import { createHash } from "node:crypto";
|
|
3
2
|
import { createReadStream } from "node:fs";
|
|
4
3
|
import { lstat } from "node:fs/promises";
|
|
5
4
|
import path from "node:path";
|
|
6
|
-
import {
|
|
5
|
+
import { openZipArchive } from "../../importers/zip-reader.mjs";
|
|
7
6
|
|
|
8
7
|
import { isUuid, uuidV5 } from "../../core/uuid-v5.mjs";
|
|
9
8
|
import {
|
|
@@ -32,7 +31,6 @@ export const SPOTIFY_ACCOUNT_DATA_HISTORY_LIMITS = Object.freeze({
|
|
|
32
31
|
maximumRecords: 500_000,
|
|
33
32
|
});
|
|
34
33
|
|
|
35
|
-
const execFileAsync = promisify(execFile);
|
|
36
34
|
const musicMemberPattern =
|
|
37
35
|
/^Spotify Account Data\/StreamingHistory_music_([0-9]+)\.json$/u;
|
|
38
36
|
const endTimePattern =
|
|
@@ -376,14 +374,20 @@ async function sha256File(filePath) {
|
|
|
376
374
|
return hash.digest("hex");
|
|
377
375
|
}
|
|
378
376
|
|
|
379
|
-
async function
|
|
377
|
+
async function openArchive(archivePath) {
|
|
380
378
|
try {
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
379
|
+
return await openZipArchive(archivePath);
|
|
380
|
+
} catch {
|
|
381
|
+
fail(
|
|
382
|
+
"The Spotify account-data ZIP could not be read safely.",
|
|
383
|
+
"spotify_account_data_archive_unreadable",
|
|
384
|
+
);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
async function zipText(archive, maximumBytes, member) {
|
|
389
|
+
try {
|
|
390
|
+
return (await archive.read(member, maximumBytes)).toString("utf8");
|
|
387
391
|
} catch {
|
|
388
392
|
fail(
|
|
389
393
|
"The Spotify account-data ZIP could not be read safely.",
|
|
@@ -468,58 +472,60 @@ export async function readSpotifyAccountDataHistoryArchive({
|
|
|
468
472
|
fail("The Spotify account-data ZIP is not a supported regular file.");
|
|
469
473
|
}
|
|
470
474
|
|
|
471
|
-
|
|
472
|
-
const
|
|
473
|
-
|
|
475
|
+
// One open archive serves the listing and every member, and is closed even when a check fails.
|
|
476
|
+
const archive = await openArchive(resolvedPath);
|
|
477
|
+
let members;
|
|
478
|
+
let profileMembers;
|
|
474
479
|
const records = [];
|
|
475
480
|
const documents = {};
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
)
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
481
|
+
try {
|
|
482
|
+
const listing = archive.names.join("\n");
|
|
483
|
+
members = selectedMusicMembers(listing);
|
|
484
|
+
profileMembers = selectedProfileMembers(listing);
|
|
485
|
+
let totalJsonBytes = 0;
|
|
486
|
+
for (const member of members) {
|
|
487
|
+
const jsonText = await zipText(archive, SPOTIFY_ACCOUNT_DATA_HISTORY_LIMITS.maximumMemberBytes, member.name);
|
|
488
|
+
totalJsonBytes += Buffer.byteLength(jsonText, "utf8");
|
|
489
|
+
if (
|
|
490
|
+
totalJsonBytes >
|
|
491
|
+
SPOTIFY_ACCOUNT_DATA_HISTORY_LIMITS.maximumTotalJsonBytes
|
|
492
|
+
) {
|
|
493
|
+
fail("Spotify music history JSON is too large to import safely.");
|
|
494
|
+
}
|
|
495
|
+
let parsed;
|
|
496
|
+
try {
|
|
497
|
+
parsed = JSON.parse(jsonText.replace(/^\uFEFF/u, ""));
|
|
498
|
+
} catch {
|
|
499
|
+
fail(`Spotify music history segment ${member.index} is invalid JSON.`);
|
|
500
|
+
}
|
|
501
|
+
if (!Array.isArray(parsed)) {
|
|
502
|
+
fail(`Spotify music history segment ${member.index} is not an array.`);
|
|
503
|
+
}
|
|
504
|
+
records.push(...parsed);
|
|
505
|
+
if (records.length > SPOTIFY_ACCOUNT_DATA_HISTORY_LIMITS.maximumRecords) {
|
|
506
|
+
fail("Spotify music history contains too many records.");
|
|
507
|
+
}
|
|
501
508
|
}
|
|
502
|
-
}
|
|
503
509
|
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
} catch {
|
|
521
|
-
fail(`Spotify account-profile file ${member.basename} is invalid JSON.`);
|
|
510
|
+
for (const member of profileMembers) {
|
|
511
|
+
const jsonText = await zipText(archive, SPOTIFY_ACCOUNT_DATA_HISTORY_LIMITS.maximumMemberBytes, member.name);
|
|
512
|
+
totalJsonBytes += Buffer.byteLength(jsonText, "utf8");
|
|
513
|
+
if (
|
|
514
|
+
totalJsonBytes >
|
|
515
|
+
SPOTIFY_ACCOUNT_DATA_HISTORY_LIMITS.maximumTotalJsonBytes
|
|
516
|
+
) {
|
|
517
|
+
fail("Spotify account-profile JSON is too large to import safely.");
|
|
518
|
+
}
|
|
519
|
+
try {
|
|
520
|
+
documents[member.basename] = JSON.parse(
|
|
521
|
+
jsonText.replace(/^\uFEFF/u, ""),
|
|
522
|
+
);
|
|
523
|
+
} catch {
|
|
524
|
+
fail(`Spotify account-profile file ${member.basename} is invalid JSON.`);
|
|
525
|
+
}
|
|
522
526
|
}
|
|
527
|
+
} finally {
|
|
528
|
+
archive.close();
|
|
523
529
|
}
|
|
524
530
|
|
|
525
531
|
const archiveSha256 = await sha256File(resolvedPath);
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { spawn } from "node:child_process";
|
|
2
1
|
import {
|
|
3
2
|
createHash,
|
|
4
3
|
randomBytes,
|
|
@@ -6,6 +5,8 @@ import {
|
|
|
6
5
|
} from "node:crypto";
|
|
7
6
|
import { createServer } from "node:http";
|
|
8
7
|
|
|
8
|
+
import { openInDefaultBrowser } from "../../core/host.mjs";
|
|
9
|
+
|
|
9
10
|
const SPOTIFY_AUTHORIZE_URL = "https://accounts.spotify.com/authorize";
|
|
10
11
|
const SPOTIFY_TOKEN_URL = "https://accounts.spotify.com/api/token";
|
|
11
12
|
const ACCESS_TOKEN_DEFAULT_LIFETIME_SECONDS = 60 * 60;
|
|
@@ -499,27 +500,6 @@ export async function refreshSpotifyAccessToken({
|
|
|
499
500
|
);
|
|
500
501
|
}
|
|
501
502
|
|
|
502
|
-
function openInDefaultBrowser(url) {
|
|
503
|
-
const [command, args] =
|
|
504
|
-
process.platform === "darwin"
|
|
505
|
-
? ["open", [url]]
|
|
506
|
-
: process.platform === "win32"
|
|
507
|
-
? ["rundll32", ["url.dll,FileProtocolHandler", url]]
|
|
508
|
-
: ["xdg-open", [url]];
|
|
509
|
-
return new Promise((resolve, reject) => {
|
|
510
|
-
const child = spawn(command, args, {
|
|
511
|
-
detached: true,
|
|
512
|
-
stdio: "ignore",
|
|
513
|
-
windowsHide: true,
|
|
514
|
-
});
|
|
515
|
-
child.once("error", reject);
|
|
516
|
-
child.once("spawn", () => {
|
|
517
|
-
child.unref();
|
|
518
|
-
resolve();
|
|
519
|
-
});
|
|
520
|
-
});
|
|
521
|
-
}
|
|
522
|
-
|
|
523
503
|
async function createCallbackListener({ redirectUri, expectedState, signal }) {
|
|
524
504
|
const redirect = normalizeRedirectUri(redirectUri);
|
|
525
505
|
let resolveCode;
|
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
import { execFile } from "node:child_process";
|
|
2
1
|
import { createHash } from "node:crypto";
|
|
3
2
|
import { createReadStream } from "node:fs";
|
|
4
3
|
import { lstat } from "node:fs/promises";
|
|
5
4
|
import path from "node:path";
|
|
6
|
-
import {
|
|
5
|
+
import { openZipArchive } from "../../importers/zip-reader.mjs";
|
|
7
6
|
|
|
8
7
|
import { isUuid, uuidV5 } from "../../core/uuid-v5.mjs";
|
|
9
8
|
import {
|
|
@@ -30,7 +29,6 @@ export const SPOTIFY_EXTENDED_HISTORY_LIMITS = Object.freeze({
|
|
|
30
29
|
maximumRecords: 500_000,
|
|
31
30
|
});
|
|
32
31
|
|
|
33
|
-
const execFileAsync = promisify(execFile);
|
|
34
32
|
const historyMemberPattern =
|
|
35
33
|
/^Spotify Extended Streaming History\/Streaming_History_(?:Audio|Video)_([0-9]{4})(?:_([0-9]+))?\.json$/u;
|
|
36
34
|
const trackUriPattern = /^spotify:track:([A-Za-z0-9]{22})$/u;
|
|
@@ -402,14 +400,20 @@ async function sha256File(filePath) {
|
|
|
402
400
|
return hash.digest("hex");
|
|
403
401
|
}
|
|
404
402
|
|
|
405
|
-
async function
|
|
403
|
+
async function openArchive(archivePath) {
|
|
406
404
|
try {
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
405
|
+
return await openZipArchive(archivePath);
|
|
406
|
+
} catch {
|
|
407
|
+
fail(
|
|
408
|
+
"The Spotify Extended History ZIP could not be read safely.",
|
|
409
|
+
"spotify_extended_history_archive_unreadable",
|
|
410
|
+
);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
async function zipText(archive, maximumBytes, member) {
|
|
415
|
+
try {
|
|
416
|
+
return (await archive.read(member, maximumBytes)).toString("utf8");
|
|
413
417
|
} catch {
|
|
414
418
|
fail(
|
|
415
419
|
"The Spotify Extended History ZIP could not be read safely.",
|
|
@@ -480,38 +484,42 @@ export async function readSpotifyExtendedStreamingHistoryArchive({
|
|
|
480
484
|
fail("The Spotify Extended History ZIP is not a supported regular file.");
|
|
481
485
|
}
|
|
482
486
|
|
|
483
|
-
|
|
484
|
-
const
|
|
487
|
+
// One open archive serves the listing and every member, and is closed even when a check fails.
|
|
488
|
+
const archive = await openArchive(resolvedPath);
|
|
489
|
+
let members;
|
|
485
490
|
const records = [];
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
491
|
+
try {
|
|
492
|
+
const listing = archive.names.join("\n");
|
|
493
|
+
members = selectedHistoryMembers(listing);
|
|
494
|
+
let totalJsonBytes = 0;
|
|
495
|
+
for (const member of members) {
|
|
496
|
+
const jsonText = await zipText(archive, SPOTIFY_EXTENDED_HISTORY_LIMITS.maximumMemberBytes, member.name);
|
|
497
|
+
totalJsonBytes += Buffer.byteLength(jsonText, "utf8");
|
|
498
|
+
if (
|
|
499
|
+
totalJsonBytes > SPOTIFY_EXTENDED_HISTORY_LIMITS.maximumTotalJsonBytes
|
|
500
|
+
) {
|
|
501
|
+
fail("Spotify Extended History JSON is too large to import safely.");
|
|
502
|
+
}
|
|
503
|
+
let parsed;
|
|
504
|
+
try {
|
|
505
|
+
parsed = JSON.parse(jsonText.replace(/^\uFEFF/u, ""));
|
|
506
|
+
} catch {
|
|
507
|
+
fail(
|
|
508
|
+
`Spotify Extended History audio/video file for ${member.year} is invalid JSON.`,
|
|
509
|
+
);
|
|
510
|
+
}
|
|
511
|
+
if (!Array.isArray(parsed)) {
|
|
512
|
+
fail(
|
|
513
|
+
`Spotify Extended History audio/video file for ${member.year} is not an array.`,
|
|
514
|
+
);
|
|
515
|
+
}
|
|
516
|
+
records.push(...parsed);
|
|
517
|
+
if (records.length > SPOTIFY_EXTENDED_HISTORY_LIMITS.maximumRecords) {
|
|
518
|
+
fail("Spotify Extended History contains too many records.");
|
|
519
|
+
}
|
|
514
520
|
}
|
|
521
|
+
} finally {
|
|
522
|
+
archive.close();
|
|
515
523
|
}
|
|
516
524
|
|
|
517
525
|
return projectSpotifyExtendedStreamingHistory({
|
|
@@ -1,12 +1,9 @@
|
|
|
1
|
-
import { execFile } from "node:child_process";
|
|
2
1
|
import path from "node:path";
|
|
3
|
-
import {
|
|
2
|
+
import { listZipMembers } from "../../importers/zip-reader.mjs";
|
|
4
3
|
|
|
5
4
|
import { readSpotifyAccountDataHistoryArchive } from "./account-data-history.mjs";
|
|
6
5
|
import { readSpotifyExtendedStreamingHistoryArchive } from "./extended-streaming-history.mjs";
|
|
7
6
|
|
|
8
|
-
const execFileAsync = promisify(execFile);
|
|
9
|
-
|
|
10
7
|
function fail(message, code = "spotify_history_archive_invalid") {
|
|
11
8
|
const error = new Error(message);
|
|
12
9
|
error.code = code;
|
|
@@ -20,15 +17,7 @@ export async function readSpotifyHistoryArchive(options = {}) {
|
|
|
20
17
|
const archivePath = path.resolve(options.archivePath);
|
|
21
18
|
let listing;
|
|
22
19
|
try {
|
|
23
|
-
|
|
24
|
-
"/usr/bin/unzip",
|
|
25
|
-
["-Z1", archivePath],
|
|
26
|
-
{
|
|
27
|
-
encoding: "utf8",
|
|
28
|
-
maxBuffer: 1024 * 1024,
|
|
29
|
-
windowsHide: true,
|
|
30
|
-
},
|
|
31
|
-
));
|
|
20
|
+
listing = (await listZipMembers(archivePath)).join("\n");
|
|
32
21
|
} catch {
|
|
33
22
|
fail(
|
|
34
23
|
"The Spotify history ZIP could not be read safely.",
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createSpotifyWebApiClient } from "./web-api-client.mjs";
|
|
2
2
|
import { readSpotifyLibrarySnapshot } from "./library-snapshot.mjs";
|
|
3
3
|
import { execFile } from "node:child_process";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
4
5
|
import { hostname } from "node:os";
|
|
5
6
|
import { setTimeout as delay } from "node:timers/promises";
|
|
6
7
|
|
|
@@ -9,10 +10,9 @@ export const SPOTIFY_SERVICE_LIMITS = Object.freeze({
|
|
|
9
10
|
playbackUrisMax: 100,
|
|
10
11
|
positionMsMax: 86_400_000,
|
|
11
12
|
playlistNameLengthMax: 100,
|
|
12
|
-
playlistDescriptionLengthMax: 200,
|
|
13
|
-
playlistTracksMax: 20,
|
|
14
13
|
editablePlaylistsPageMax: 50,
|
|
15
14
|
playlistEditTracksMax: 100,
|
|
15
|
+
playlistExportTracksMax: 2000,
|
|
16
16
|
playlistItemsPageMax: 50,
|
|
17
17
|
libraryTracksMax: 20,
|
|
18
18
|
recentlyPlayedDefault: 20,
|
|
@@ -353,6 +353,11 @@ function searchLimit(value) {
|
|
|
353
353
|
return value;
|
|
354
354
|
}
|
|
355
355
|
|
|
356
|
+
// What a playlist holds, in order, as one short value: two lists with the same signature hold the same songs.
|
|
357
|
+
function playlistSignature(uris) {
|
|
358
|
+
return createHash("sha256").update(uris.join("\n")).digest("hex");
|
|
359
|
+
}
|
|
360
|
+
|
|
356
361
|
function actionReceipt(action) {
|
|
357
362
|
return {
|
|
358
363
|
provider: "spotify",
|
|
@@ -905,10 +910,35 @@ export function createSpotifyService(options = {}) {
|
|
|
905
910
|
if (!playlist) fail("spotify_playlist_unavailable", "Spotify did not describe this playlist.");
|
|
906
911
|
const page = await client.getPlaylistItems({ playlistId, limit: SPOTIFY_SERVICE_LIMITS.playlistItemsPageMax, offset: 0 }, { signal })
|
|
907
912
|
.catch((error) => (signal?.aborted ? Promise.reject(error) : null));
|
|
908
|
-
return { name: playlist.name, uri: playlist.uri, tracks_total: playlist.tracks_total ?? null,
|
|
913
|
+
return { name: playlist.name, uri: playlist.uri, tracks_total: playlist.tracks_total ?? null, ...(playlist.image ? { image: playlist.image } : {}),
|
|
909
914
|
tracks: page ? page.items.map((entry) => entry.item).filter(Boolean) : null };
|
|
910
915
|
},
|
|
911
916
|
|
|
917
|
+
// Only a playlist's cover, for one imported before Moondog kept it.
|
|
918
|
+
async readPlaylistCover({ playlistId } = {}, { signal } = {}) {
|
|
919
|
+
return (await client.getPlaylist({ playlistId: requiredPlaylistId(String(playlistId ?? "")) }, { signal }))?.image ?? null;
|
|
920
|
+
},
|
|
921
|
+
|
|
922
|
+
// A whole playlist for the listener's library: its name, whether the signed-in listener owns it, and its
|
|
923
|
+
// songs page by page, up to 2,000. Spotify's own editorial playlists answer most apps with not found.
|
|
924
|
+
async readPlaylist({ playlistId } = {}, { signal } = {}) {
|
|
925
|
+
const id = requiredPlaylistId(String(playlistId ?? ""));
|
|
926
|
+
const playlist = await client.getPlaylist({ playlistId: id }, { signal });
|
|
927
|
+
if (!playlist) fail("spotify_playlist_unavailable", "Spotify did not describe this playlist.");
|
|
928
|
+
const tracks = [];
|
|
929
|
+
const pageSize = SPOTIFY_SERVICE_LIMITS.playlistItemsPageMax;
|
|
930
|
+
for (let offset = 0; offset < 2000; offset += pageSize) {
|
|
931
|
+
const page = await client.getPlaylistItems({ playlistId: id, limit: pageSize, offset }, { signal });
|
|
932
|
+
// A local file on the owner's computer has no catalog song to play or name; it stays out.
|
|
933
|
+
tracks.push(...page.items.filter((entry) => entry.is_local !== true).map((entry) => entry.item)
|
|
934
|
+
.filter((item) => item?.type === "track" && item.name && item.artists?.length && /^spotify:track:/u.test(item.uri ?? "")));
|
|
935
|
+
if (!page.has_more || !page.items.length) break;
|
|
936
|
+
}
|
|
937
|
+
const account = await client.getAccount({ signal }).catch((error) => (signal?.aborted ? Promise.reject(error) : null));
|
|
938
|
+
return { name: playlist.name, uri: playlist.uri, tracks_total: playlist.tracks_total ?? null,
|
|
939
|
+
owned: account?.account_id && playlist.owner_id ? account.account_id === playlist.owner_id : null, tracks };
|
|
940
|
+
},
|
|
941
|
+
|
|
912
942
|
// One device decision for a whole queue request. An idle device cannot take a
|
|
913
943
|
// queue entry, so the caller starts the first song there and queues the rest.
|
|
914
944
|
async queueTarget(value, { signal } = {}) {
|
|
@@ -1417,68 +1447,68 @@ export function createSpotifyService(options = {}) {
|
|
|
1417
1447
|
return actionReceipt("playback.queue.add");
|
|
1418
1448
|
},
|
|
1419
1449
|
|
|
1420
|
-
|
|
1450
|
+
// A library playlist's copy on Spotify: a new playlist, or the copy an earlier export made, set to
|
|
1451
|
+
// these songs in this order. previous names that copy and what the export left in it. A copy that holds
|
|
1452
|
+
// something else was changed on Spotify and is replaced only when the listener says so; a copy that is gone
|
|
1453
|
+
// from their Spotify library is made again.
|
|
1454
|
+
async exportPlaylist(value, { signal } = {}) {
|
|
1421
1455
|
signal?.throwIfAborted();
|
|
1422
1456
|
const input = inputObject(value);
|
|
1423
|
-
const
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
)
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
"Spotify did not return the created playlist.",
|
|
1451
|
-
{ outcomeUnknown: true },
|
|
1452
|
-
);
|
|
1457
|
+
const nameMax = SPOTIFY_SERVICE_LIMITS.playlistNameLengthMax;
|
|
1458
|
+
const name = cleanPlaylistText(Array.from(String(input.name ?? "")).slice(0, nameMax).join(""), nameMax, "invalid_playlist_name", "name");
|
|
1459
|
+
const uris = requiredTrackUris(input.uris, "invalid_playlist_tracks", SPOTIFY_SERVICE_LIMITS.playlistExportTracksMax);
|
|
1460
|
+
const batch = SPOTIFY_SERVICE_LIMITS.playlistEditTracksMax;
|
|
1461
|
+
let copy = null;
|
|
1462
|
+
if (isPlainObject(input.previous) && input.previous.playlistId) {
|
|
1463
|
+
const playlistId = requiredPlaylistId(input.previous.playlistId);
|
|
1464
|
+
const ownerId = accountId(await client.getAccount({ signal }));
|
|
1465
|
+
const found = await client.getPlaylist({ playlistId }, { signal }).catch((error) => (error?.status === 404 ? null : Promise.reject(error)));
|
|
1466
|
+
// Deleting a playlist on Spotify only takes it out of the listener's library; it still answers by its id.
|
|
1467
|
+
const kept = found?.id === playlistId && found.owner_id === ownerId && found.uri
|
|
1468
|
+
? await client.checkSavedTracks({ uris: [found.uri] }, { signal }).then((saved) => saved[0] !== false, (error) => (signal?.aborted ? Promise.reject(error) : true))
|
|
1469
|
+
: false;
|
|
1470
|
+
if (kept) {
|
|
1471
|
+
const there = [];
|
|
1472
|
+
const pageSize = SPOTIFY_SERVICE_LIMITS.playlistItemsPageMax;
|
|
1473
|
+
for (let offset = 0; offset < SPOTIFY_SERVICE_LIMITS.playlistExportTracksMax && found.tracks_total !== 0; offset += pageSize) {
|
|
1474
|
+
const page = await client.getPlaylistItems({ playlistId, limit: pageSize, offset }, { signal });
|
|
1475
|
+
there.push(...page.items.map((entry) => entry.item?.uri ?? ""));
|
|
1476
|
+
if (!page.has_more || !page.items.length) break;
|
|
1477
|
+
}
|
|
1478
|
+
if (input.replace !== true && playlistSignature(there) !== input.previous.signature) {
|
|
1479
|
+
return { provider: "spotify", ok: false, effect: "write_external", action: "playlist.export", state: "changed_on_spotify",
|
|
1480
|
+
playlist: { name: found.name, track_count: there.length, is_public: found.is_public === true } };
|
|
1481
|
+
}
|
|
1482
|
+
copy = found;
|
|
1483
|
+
}
|
|
1453
1484
|
}
|
|
1485
|
+
signal?.throwIfAborted();
|
|
1486
|
+
const updated = Boolean(copy);
|
|
1487
|
+
let written = 0;
|
|
1454
1488
|
try {
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
(
|
|
1461
|
-
|
|
1462
|
-
fail(
|
|
1463
|
-
"playlist_created_tracks_unknown",
|
|
1464
|
-
"Spotify created the private playlist, but did not confirm whether its tracks were added. Check the playlist before trying again.",
|
|
1465
|
-
{ outcomeUnknown: true },
|
|
1466
|
-
);
|
|
1489
|
+
if (copy) {
|
|
1490
|
+
if (copy.name !== name) await client.renamePlaylist({ playlistId: copy.id, name }, { signal });
|
|
1491
|
+
await client.replacePlaylistItems({ playlistId: copy.id, uris: uris.slice(0, batch) }, { signal });
|
|
1492
|
+
written = Math.min(batch, uris.length);
|
|
1493
|
+
} else {
|
|
1494
|
+
copy = await client.createPlaylist({ name }, { signal });
|
|
1495
|
+
if (!copy?.id) fail("playlist_creation_failed", "Spotify did not return the created playlist.", { outcomeUnknown: true });
|
|
1467
1496
|
}
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1497
|
+
for (; written < uris.length; written += batch) {
|
|
1498
|
+
signal?.throwIfAborted();
|
|
1499
|
+
await client.addPlaylistTracks({ playlistId: copy.id, uris: uris.slice(written, written + batch) }, { signal });
|
|
1500
|
+
}
|
|
1501
|
+
} catch (error) {
|
|
1502
|
+
// The copy exists with the songs sent so far. The caller keeps it, so the next export goes on with this copy.
|
|
1503
|
+
if (copy?.id && error && typeof error === "object") error.exportedCopy = { playlistId: copy.id, signature: playlistSignature(uris.slice(0, written)), track_count: written };
|
|
1504
|
+
throw error;
|
|
1472
1505
|
}
|
|
1473
1506
|
return {
|
|
1474
|
-
...actionReceipt("playlist.
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
},
|
|
1480
|
-
...(playlist.uri ? { playlist_uri: playlist.uri } : {}),
|
|
1481
|
-
...(playlist.id ? { playlist_id: playlist.id } : {}),
|
|
1507
|
+
...actionReceipt("playlist.export"),
|
|
1508
|
+
state: updated ? "updated" : "created",
|
|
1509
|
+
playlist: { name, track_count: uris.length },
|
|
1510
|
+
playlist_id: copy.id,
|
|
1511
|
+
signature: playlistSignature(uris),
|
|
1482
1512
|
};
|
|
1483
1513
|
},
|
|
1484
1514
|
|