@audiofool/moondog 0.3.0-beta.15 → 0.3.0-beta.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +6 -3
  2. package/package.json +3 -2
  3. package/scripts/moondog.mjs +4 -5
  4. package/src/core/capability-catalog.mjs +24 -14
  5. package/src/core/host.mjs +30 -0
  6. package/src/core/library-store.mjs +33 -1
  7. package/src/core/listening-now.mjs +7 -2
  8. package/src/core/moondog-application.mjs +219 -143
  9. package/src/i18n/messages/de.mjs +4 -3
  10. package/src/i18n/messages/en.mjs +4 -3
  11. package/src/i18n/messages/es.mjs +4 -3
  12. package/src/i18n/messages/fr.mjs +4 -3
  13. package/src/i18n/messages/it.mjs +4 -3
  14. package/src/i18n/messages/ja.mjs +4 -3
  15. package/src/i18n/messages/ko.mjs +4 -3
  16. package/src/i18n/messages/pt.mjs +4 -3
  17. package/src/i18n/messages/zh-Hant.mjs +4 -3
  18. package/src/i18n/messages/zh.mjs +4 -3
  19. package/src/i18n/screen/es.mjs +16 -3
  20. package/src/i18n/screen/ja.mjs +16 -3
  21. package/src/i18n/screen/pt.mjs +16 -3
  22. package/src/i18n/screen/zh.mjs +16 -3
  23. package/src/importers/zip-reader.mjs +61 -0
  24. package/src/integrations/apple-music/music-app.mjs +3 -2
  25. package/src/integrations/lastfm/history.mjs +2 -1
  26. package/src/integrations/lyrics/lrclib.mjs +1 -1
  27. package/src/integrations/netease/ncm-cli-player.mjs +62 -20
  28. package/src/integrations/open-music-similarity/artist-radio.mjs +3 -3
  29. package/src/integrations/spotify/account-data-history.mjs +63 -57
  30. package/src/integrations/spotify/authentication.mjs +2 -22
  31. package/src/integrations/spotify/extended-streaming-history.mjs +48 -40
  32. package/src/integrations/spotify/history-archive.mjs +2 -13
  33. package/src/integrations/spotify/service.mjs +62 -57
  34. package/src/integrations/spotify/web-api-client.mjs +4 -2
  35. package/src/integrations/user-agent.mjs +6 -0
  36. package/src/integrations/web/codex-web.mjs +3 -1
  37. package/src/integrations/youtube-music/takeout.mjs +11 -16
  38. package/src/profile/history-import.mjs +3 -1
  39. package/src/runtime/pi/agent-runtime.mjs +138 -136
  40. package/src/runtime/pi/next-songs.mjs +71 -0
  41. package/src/runtime/pi/persistent-credential-store.mjs +2 -0
  42. package/src/surfaces/cli/command-completions.mjs +1 -0
  43. package/src/surfaces/cli/format-output.mjs +19 -7
  44. package/src/surfaces/cli/tui.mjs +24 -1
@@ -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",
@@ -1442,68 +1447,68 @@ export function createSpotifyService(options = {}) {
1442
1447
  return actionReceipt("playback.queue.add");
1443
1448
  },
1444
1449
 
1445
- async createPlaylistWithTracks(value, { signal } = {}) {
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 } = {}) {
1446
1455
  signal?.throwIfAborted();
1447
1456
  const input = inputObject(value);
1448
- const name = cleanPlaylistText(
1449
- input.name,
1450
- SPOTIFY_SERVICE_LIMITS.playlistNameLengthMax,
1451
- "invalid_playlist_name",
1452
- "name",
1453
- );
1454
- const description =
1455
- input.description === undefined
1456
- ? undefined
1457
- : cleanPlaylistText(
1458
- input.description,
1459
- SPOTIFY_SERVICE_LIMITS.playlistDescriptionLengthMax,
1460
- "invalid_playlist_description",
1461
- "description",
1462
- );
1463
- const uris = requiredTrackUris(
1464
- input.uris,
1465
- "invalid_playlist_tracks",
1466
- SPOTIFY_SERVICE_LIMITS.playlistTracksMax,
1467
- );
1468
- const playlist = await client.createPlaylist({
1469
- name,
1470
- ...(description ? { description } : {}),
1471
- }, { signal });
1472
- if (!playlist?.id) {
1473
- fail(
1474
- "playlist_creation_failed",
1475
- "Spotify did not return the created playlist.",
1476
- { outcomeUnknown: true },
1477
- );
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
+ }
1478
1484
  }
1485
+ signal?.throwIfAborted();
1486
+ const updated = Boolean(copy);
1487
+ let written = 0;
1479
1488
  try {
1480
- signal?.throwIfAborted();
1481
- await client.addPlaylistTracks({ playlistId: playlist.id, uris }, { signal });
1482
- } catch (error) {
1483
- const rejected = error?.outcomeUnknown === false ||
1484
- (Number.isInteger(error?.status) && error.status >= 400 && error.status < 500) ||
1485
- (error?.name === "AbortError" && signal?.aborted);
1486
- if (error?.outcomeUnknown === true || !rejected) {
1487
- fail(
1488
- "playlist_created_tracks_unknown",
1489
- "Spotify created the private playlist, but did not confirm whether its tracks were added. Check the playlist before trying again.",
1490
- { outcomeUnknown: true },
1491
- );
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 });
1492
1496
  }
1493
- fail(
1494
- "playlist_created_without_tracks",
1495
- "Spotify created the private playlist but did not accept its tracks. Check the empty playlist before trying again.",
1496
- );
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;
1497
1505
  }
1498
1506
  return {
1499
- ...actionReceipt("playlist.write"),
1500
- playlist: {
1501
- name: playlist.name ?? name,
1502
- track_count: uris.length,
1503
- is_public: false,
1504
- },
1505
- ...(playlist.uri ? { playlist_uri: playlist.uri } : {}),
1506
- ...(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),
1507
1512
  };
1508
1513
  },
1509
1514
 
@@ -9,7 +9,6 @@ export const SPOTIFY_WEB_API_LIMITS = Object.freeze({
9
9
  queueItemsMax: 50,
10
10
  artistsPerItemMax: 5,
11
11
  searchResultsMax: 10,
12
- playlistTracksMax: 20,
13
12
  playlistsPageMax: 50,
14
13
  playlistItemsPageMax: 50,
15
14
  playlistEditTracksMax: 100,
@@ -905,9 +904,12 @@ export function createSpotifyWebApiClient({
905
904
  await request("/me/playlists", {
906
905
  method: "POST",
907
906
  signal,
907
+ // Spotify writes the word "null" as the description when none is sent, so an empty one always goes.
908
+ // public: false asks to keep the playlist off the listener's profile. Spotify's own apps can still show it
909
+ // as a public playlist, and the Web API has no way to make one private, so no receipt calls it private.
908
910
  body: {
909
911
  name,
910
- ...(description ? { description } : {}),
912
+ description: description || "",
911
913
  public: false,
912
914
  },
913
915
  }),
@@ -0,0 +1,6 @@
1
+ import { readFileSync } from "node:fs";
2
+
3
+ // The identity Moondog gives public music-data services: its name, version and project page.
4
+ const { version } = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
5
+
6
+ export const MOONDOG_USER_AGENT = `Moondog/${version} (https://github.com/Audiofool934/moondog)`;
@@ -6,6 +6,7 @@ import path from "node:path";
6
6
 
7
7
  import Ajv from "ajv";
8
8
 
9
+ import { environmentPathKey } from "../../core/host.mjs";
9
10
  import { createWebOperations, failure, webResult } from "./web-result.mjs";
10
11
 
11
12
  export { projectWebResearchResult, publicWebUrl } from "./web-result.mjs";
@@ -101,7 +102,8 @@ export async function runCodexProcess(binary, args, { environment, cwd, input =
101
102
  async function findCodex(environment) {
102
103
  const candidates = environment.MOONDOG_CODEX_BIN
103
104
  ? [environment.MOONDOG_CODEX_BIN]
104
- : (environment.PATH ?? "").split(path.delimiter).filter(Boolean).map((entry) => path.resolve(entry, "codex"));
105
+ : (environment[environmentPathKey(environment)] ?? "").split(path.delimiter).filter(Boolean)
106
+ .map((entry) => path.resolve(entry, process.platform === "win32" ? "codex.exe" : "codex"));
105
107
  for (const candidate of candidates) {
106
108
  if (!path.isAbsolute(candidate)) continue;
107
109
  try { await access(candidate, constants.X_OK); return candidate; } catch {}
@@ -1,12 +1,9 @@
1
- import { execFile } from "node:child_process";
2
1
  import { constants } from "node:fs";
3
- import { open, mkdtemp, writeFile, rm } from "node:fs/promises";
4
- import { tmpdir } from "node:os";
2
+ import { open } from "node:fs/promises";
5
3
  import path from "node:path";
6
- import { promisify } from "node:util";
4
+ import { openZipArchive } from "../../importers/zip-reader.mjs";
7
5
  import { musicHash, prepareMusicBundle } from "../../profile/music-import-bundle.mjs";
8
6
 
9
- const exec = promisify(execFile);
10
7
  const maximumBytes = 256 * 1024 * 1024;
11
8
  const memberBytes = 64 * 1024 * 1024;
12
9
  const maximumRecords = 100_000;
@@ -103,27 +100,25 @@ export async function readYouTubeMusicTakeout({ filePath, subjectId, capturedAt
103
100
  const sources = [];
104
101
  if (/\.zip$/iu.test(filePath)) {
105
102
  // Read from one private snapshot: manifest digest and preview describe exactly the same bytes.
106
- const root = await mkdtemp(path.join(tmpdir(), "moondog-takeout-"));
103
+ let zip;
107
104
  try {
108
- const zip = path.join(root, "takeout.zip");
109
- await writeFile(zip, bytes, { mode: 0o600 });
110
- const { stdout } = await exec("unzip", ["-Z1", zip], { maxBuffer: 1024 * 1024, timeout: 15_000 });
111
- const names = stdout.trimEnd().split("\n");
112
- const selected = names.filter((name) => /(?:^|\/)(?:watch-history\.json|music[- ]library[- ]songs\.csv|library[- ]songs\.csv)$/iu.test(name));
105
+ zip = await openZipArchive(bytes);
106
+ } catch {
107
+ throw new Error("Could not read this Takeout ZIP. Finish the download and use an unencrypted ZIP, or extract music-library-songs.csv and watch-history.json and import each file.");
108
+ }
109
+ try {
110
+ const selected = zip.names.filter((name) => /(?:^|\/)(?:watch-history\.json|music[- ]library[- ]songs\.csv|library[- ]songs\.csv)$/iu.test(name));
113
111
  if (!selected.length) throw new Error("No supported YouTube Music files in this ZIP. Include music library songs and history in Google Takeout; set history format to JSON, not HTML.");
114
112
  if (selected.length > 100 || new Set(selected).size !== selected.length) throw new Error("Takeout contains too many or duplicate music files.");
115
113
  let total = 0;
116
114
  for (const name of selected) {
117
115
  if (name.startsWith("/") || name.split("/").includes("..") || /[\\*?\[\]\u0000-\u001f\u007f]/u.test(name)) throw new Error("Unsupported archive member path.");
118
- const { stdout: content } = await exec("unzip", ["-p", zip, name], { encoding: "buffer", maxBuffer: memberBytes, timeout: 15_000 });
116
+ const content = await zip.read(name, memberBytes);
119
117
  total += content.length;
120
118
  if (total > maximumBytes) throw new Error("Unpacked music data exceeds 256 MB. Import the extracted files separately.");
121
119
  sources.push({ name: `${musicHash(name).slice(0, 12)}-${path.basename(name)}`, content });
122
120
  }
123
- } catch (error) {
124
- if (error.cmd || error.code === "ENOENT") throw new Error("Could not read this Takeout ZIP. Finish the download and use an unencrypted ZIP, or extract music-library-songs.csv and watch-history.json and import each file. ZIP reading requires unzip on this computer.");
125
- throw error;
126
- } finally { await rm(root, { recursive: true, force: true }); }
121
+ } finally { zip.close(); }
127
122
  } else {
128
123
  if (bytes.length > memberBytes) throw new Error("Choose a music CSV or history JSON smaller than 64 MB.");
129
124
  sources.push({ name: path.basename(filePath), content: bytes });
@@ -85,7 +85,9 @@ function literalPath(input) {
85
85
  if (quote && character === quote) {
86
86
  fail("history_import_path_invalid", "Paste one complete file path, not several quoted arguments.");
87
87
  }
88
- if (character === "\\" && quote !== "'") {
88
+ // Windows paths use backslashes as separators, including paths from the desktop file picker.
89
+ // Only POSIX input uses backslashes to escape spaces or shell punctuation.
90
+ if (character === "\\" && quote !== "'" && process.platform !== "win32") {
89
91
  const next = value[index + 1];
90
92
  const allowed = quote === '"' ? /["\\$`]/u : /[ \t()\[\]{}!&;'"\\#$~`]/u;
91
93
  if (!next || !allowed.test(next)) {