@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
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { isMainThread, parentPort, Worker, workerData } from "node:worker_threads";
|
|
2
|
+
|
|
3
|
+
import { commitSpotifyQuickImport, isSharedPlaylistInput, prepareHistoryImport, prepareSpotifyQuickImport } from "./history-import.mjs";
|
|
4
|
+
|
|
5
|
+
async function savePreparedImport(prepared, { filePath, subjectId }) {
|
|
6
|
+
const { provider, bundle } = prepared;
|
|
7
|
+
if (provider === "apple-music-library" && !bundle.trackRefs.length && prepared.preview.excludedNonMusic) {
|
|
8
|
+
// The writer can only verify an old copy or decline this file. Neither needs a new listening subject.
|
|
9
|
+
const { persistAppleLibraryImport } = await import("./apple-library-import.mjs");
|
|
10
|
+
return persistAppleLibraryImport(bundle);
|
|
11
|
+
}
|
|
12
|
+
const { openListeningHistoryStore } = await import("./listening-history-store.mjs");
|
|
13
|
+
const environment = process.env;
|
|
14
|
+
const store = await openListeningHistoryStore({ environment });
|
|
15
|
+
try {
|
|
16
|
+
if (provider === "spotify-quick") return commitSpotifyQuickImport(store, prepared);
|
|
17
|
+
if (provider === "apple-music-library") {
|
|
18
|
+
const { persistAppleLibraryImport } = await import("./apple-library-import.mjs");
|
|
19
|
+
// A different client could have claimed the listening subject since the XML was inspected.
|
|
20
|
+
store.localSubjectId({ preferredSubjectId: subjectId });
|
|
21
|
+
return await persistAppleLibraryImport(bundle, { environment });
|
|
22
|
+
}
|
|
23
|
+
const command = { args: ["import-history", filePath], subjectId, stdout: { write() {} } };
|
|
24
|
+
if (provider === "listenbrainz") {
|
|
25
|
+
const { runListenBrainzCommand } = await import("../surfaces/cli/listenbrainz-command.mjs");
|
|
26
|
+
return await runListenBrainzCommand({ ...command, historyStore: store, historyFileImporter: () => bundle });
|
|
27
|
+
}
|
|
28
|
+
if (provider === "spotify") {
|
|
29
|
+
const { runSpotifyCommand } = await import("../surfaces/cli/spotify-command.mjs");
|
|
30
|
+
return await runSpotifyCommand({ ...command, recentActivityStore: store, historyArchiveImporter: () => bundle });
|
|
31
|
+
}
|
|
32
|
+
return { ...store.ingestImport(bundle), provider };
|
|
33
|
+
} finally {
|
|
34
|
+
store.close();
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function comparePreparedImport(prepared) {
|
|
39
|
+
if (prepared.provider === "apple-music-library") {
|
|
40
|
+
const { compareAppleLibraryImport } = await import("./apple-library-import.mjs");
|
|
41
|
+
return compareAppleLibraryImport(prepared.bundle);
|
|
42
|
+
}
|
|
43
|
+
const { compareListeningImport, compareSpotifyQuickImport } = await import("./listening-history-store.mjs");
|
|
44
|
+
return prepared.provider === "spotify-quick" ? compareSpotifyQuickImport(prepared) : compareListeningImport(prepared.bundle);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function runImportWorker(options) {
|
|
48
|
+
function report(type, error) {
|
|
49
|
+
parentPort.postMessage({ type, name: error.name, code: error.code, message: error.message });
|
|
50
|
+
}
|
|
51
|
+
try {
|
|
52
|
+
const onProgress = progress => parentPort.postMessage({ type: "progress", progress });
|
|
53
|
+
const prepared = options.recentPage
|
|
54
|
+
? prepareSpotifyQuickImport({ ...options, page: options.recentPage })
|
|
55
|
+
: await prepareHistoryImport({ ...options, onProgress });
|
|
56
|
+
onProgress({ stage: "comparing" });
|
|
57
|
+
const impact = await comparePreparedImport(prepared);
|
|
58
|
+
const nextCommand = () => new Promise(resolve => parentPort.once("message", resolve));
|
|
59
|
+
parentPort.postMessage({ type: "ready", provider: prepared.provider, preview: { ...prepared.preview, impact } });
|
|
60
|
+
while ((await nextCommand()) === "commit") {
|
|
61
|
+
let receipt;
|
|
62
|
+
try {
|
|
63
|
+
receipt = await savePreparedImport(prepared, options);
|
|
64
|
+
} catch (error) {
|
|
65
|
+
// The surface may offer Retry, using the same inspected file after storage becomes available.
|
|
66
|
+
report("save-error", error);
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
parentPort.postMessage({ type: "saved", receipt });
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
} catch (error) {
|
|
73
|
+
report("error", error);
|
|
74
|
+
} finally {
|
|
75
|
+
parentPort.close();
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (!isMainThread && workerData?.listeningImport && parentPort) {
|
|
80
|
+
await runImportWorker(workerData.listeningImport);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function previewGone() {
|
|
84
|
+
return Object.assign(new Error("That preview is gone. Open it again before importing."), { code: "history_import_preview_gone" });
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export async function prepareLocalFileImport(options = {}) {
|
|
88
|
+
options.signal?.throwIfAborted();
|
|
89
|
+
if (options.recentPage || options.provider === "lastfm" || isSharedPlaylistInput(options.filePath)) {
|
|
90
|
+
throw Object.assign(new Error("Choose a downloaded local file."), { code: "history_import_path_invalid" });
|
|
91
|
+
}
|
|
92
|
+
return prepareListeningImport(options);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Keep the inspected data off the client thread until the listener saves or closes the preview. */
|
|
96
|
+
export async function prepareListeningImport({ filePath, subjectId, provider, capturedAt, recentPage, librarySnapshot, libraryUnavailable, onProgress, signal, environment } = {}) {
|
|
97
|
+
signal?.throwIfAborted();
|
|
98
|
+
const worker = new Worker(new URL(import.meta.url), {
|
|
99
|
+
workerData: { listeningImport: { filePath, subjectId, provider, capturedAt, recentPage, librarySnapshot, libraryUnavailable } },
|
|
100
|
+
env: environment,
|
|
101
|
+
execArgv: [],
|
|
102
|
+
});
|
|
103
|
+
let phase = "reading";
|
|
104
|
+
let pending = Promise.withResolvers();
|
|
105
|
+
let failure;
|
|
106
|
+
let releaseAfterSave = false;
|
|
107
|
+
function finish() {
|
|
108
|
+
phase = "closed";
|
|
109
|
+
signal?.removeEventListener("abort", abort);
|
|
110
|
+
}
|
|
111
|
+
function fail(error) {
|
|
112
|
+
if (phase === "closed") return;
|
|
113
|
+
failure = error;
|
|
114
|
+
finish();
|
|
115
|
+
pending.reject(error);
|
|
116
|
+
}
|
|
117
|
+
function discard(reason) {
|
|
118
|
+
if (phase === "saving") { releaseAfterSave = true; return; }
|
|
119
|
+
if (phase === "closed") return;
|
|
120
|
+
fail(reason);
|
|
121
|
+
void worker.terminate();
|
|
122
|
+
}
|
|
123
|
+
const abort = () => discard(signal.reason);
|
|
124
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
125
|
+
const exited = new Promise(resolve => worker.once("exit", () => {
|
|
126
|
+
fail(previewGone());
|
|
127
|
+
resolve();
|
|
128
|
+
}));
|
|
129
|
+
worker.once("error", fail);
|
|
130
|
+
worker.on("message", (message) => {
|
|
131
|
+
if (phase === "closed") return;
|
|
132
|
+
if (message.type === "progress" && phase === "reading") {
|
|
133
|
+
try { onProgress?.(message.progress); }
|
|
134
|
+
catch (error) { discard(error); }
|
|
135
|
+
} else if (message.type === "ready" && phase === "reading") {
|
|
136
|
+
phase = "ready";
|
|
137
|
+
pending.resolve({ provider: message.provider, preview: message.preview });
|
|
138
|
+
} else if (message.type === "saved" && phase === "saving") {
|
|
139
|
+
finish();
|
|
140
|
+
pending.resolve(message.receipt);
|
|
141
|
+
} else if (message.type === "error" || message.type === "save-error") {
|
|
142
|
+
const error = Object.assign(new Error(message.message), { name: message.name });
|
|
143
|
+
if (message.code !== undefined) error.code = message.code;
|
|
144
|
+
if (message.type === "save-error") {
|
|
145
|
+
phase = "ready";
|
|
146
|
+
pending.reject(error);
|
|
147
|
+
if (releaseAfterSave) discard(previewGone());
|
|
148
|
+
} else {
|
|
149
|
+
fail(error);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
let inspected;
|
|
155
|
+
try { inspected = await pending.promise; }
|
|
156
|
+
catch (error) { await exited; throw error; }
|
|
157
|
+
return {
|
|
158
|
+
...inspected,
|
|
159
|
+
async commit() {
|
|
160
|
+
if (phase !== "ready") throw failure ?? previewGone();
|
|
161
|
+
phase = "saving";
|
|
162
|
+
pending = Promise.withResolvers();
|
|
163
|
+
worker.postMessage("commit");
|
|
164
|
+
try { return await pending.promise; }
|
|
165
|
+
finally { if (phase === "closed") await exited; }
|
|
166
|
+
},
|
|
167
|
+
close() {
|
|
168
|
+
discard(previewGone());
|
|
169
|
+
return exited;
|
|
170
|
+
},
|
|
171
|
+
};
|
|
172
|
+
}
|
|
@@ -9,9 +9,13 @@ const DAY_MS = 86_400_000;
|
|
|
9
9
|
// short enough that a later return is the listener's own. A play's time is when it ended, so one
|
|
10
10
|
// that ended before the request was the listener's; the 60 seconds only absorb clock skew. A
|
|
11
11
|
// matching play after the window is the listener's choice and marks the suggestion adopted. The
|
|
12
|
-
//
|
|
12
|
+
// Music.app watcher observes the listener's separate player, so its plays keep their own origin.
|
|
13
|
+
// The match runs whenever the profile is read, so a later history import is matched the same way.
|
|
13
14
|
export const SUGGESTION_WINDOW = Object.freeze({ beforeMs: 60_000, afterMs: 6 * HOUR_MS });
|
|
14
15
|
|
|
16
|
+
// Saving a curated playlist records a suggestion but starts no playback.
|
|
17
|
+
export const PLAYLIST_SAVE_ACTION = "playlist.write";
|
|
18
|
+
|
|
15
19
|
export const SUGGESTION_SERVICES = Object.freeze(["spotify", "netease", "apple_music"]);
|
|
16
20
|
|
|
17
21
|
// A track Moondog made on this Mac (src/integrations/stable-audio). It has no artist, so no song
|
|
@@ -71,6 +75,18 @@ export function suggestionIdentities(suggestion) {
|
|
|
71
75
|
].filter(Boolean))];
|
|
72
76
|
}
|
|
73
77
|
|
|
78
|
+
// Suggestion history can also match versions of the same song. A completed play is narrower:
|
|
79
|
+
// known recording IDs take priority, then the full title and primary artist when IDs cannot compare.
|
|
80
|
+
export function sameCompletedRecording(left, right) {
|
|
81
|
+
if (left.provider_track_id && left.provider_track_id === right.provider_track_id) return true;
|
|
82
|
+
if (left.isrc && right.isrc) return left.isrc === right.isrc;
|
|
83
|
+
if (left.provider_track_id && right.provider_track_id &&
|
|
84
|
+
left.provider_track_id.split(":", 1)[0] === right.provider_track_id.split(":", 1)[0]) return false;
|
|
85
|
+
if (normalizedArtistName(left.title) !== normalizedArtistName(right.title)) return false;
|
|
86
|
+
const names = primaryArtists(left).map(normalizedArtistName);
|
|
87
|
+
return primaryArtists(right).some(name => names.includes(normalizedArtistName(name)));
|
|
88
|
+
}
|
|
89
|
+
|
|
74
90
|
/**
|
|
75
91
|
* The ledger entry for one accepted host write, or null when it names no song. An album Moondog
|
|
76
92
|
* started names its release instead, so every song of it that plays matches.
|
|
@@ -133,10 +149,19 @@ export function markMoondogStartedPlays(eventRows, suggestions) {
|
|
|
133
149
|
if (!matches.length) return row;
|
|
134
150
|
const playedMs = Date.parse(row.event?.occurred_at);
|
|
135
151
|
if (!Number.isFinite(playedMs)) return row;
|
|
136
|
-
const
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
152
|
+
const provenance = row.event.provenance;
|
|
153
|
+
const source = provenance?.external_ref;
|
|
154
|
+
const musicApp = provenance?.source_kind === "tool" && source?.system === "apple_music" && source.entity_type === "apple_music.music_app_play";
|
|
155
|
+
// Moondog plays its own Apple Music queue through ApplicationMusicPlayer. The watcher reads Music.app.
|
|
156
|
+
if (!musicApp) {
|
|
157
|
+
const started = matches.find((entry) => entry.action !== PLAYLIST_SAVE_ACTION &&
|
|
158
|
+
playedMs >= entry.requestedMs - SUGGESTION_WINDOW.beforeMs && playedMs <= entry.requestedMs + SUGGESTION_WINDOW.afterMs);
|
|
159
|
+
if (started) return { ...row, moondog_suggestion_id: started.suggestion_id };
|
|
160
|
+
}
|
|
161
|
+
// A watched play that was already underway when Moondog made its suggestion cannot be a return to it.
|
|
162
|
+
const delay = musicApp && Number.isSafeInteger(row.event.played_ms) && row.event.played_ms >= 0
|
|
163
|
+
? row.event.played_ms : SUGGESTION_WINDOW.afterMs;
|
|
164
|
+
for (const entry of matches) if (playedMs > entry.requestedMs + delay) adopted.add(entry.suggestion_id);
|
|
140
165
|
return row;
|
|
141
166
|
});
|
|
142
167
|
return { rows, adopted };
|
|
@@ -152,9 +177,11 @@ export const MIX_SLOTS = Object.freeze(["familiar", "returning", "heard", "known
|
|
|
152
177
|
/** What the listener's own plays say about songs and artists, or null with no plays at all. */
|
|
153
178
|
export function listeningFamiliarity(catalog, referenceDate) {
|
|
154
179
|
const referenceMs = Date.parse(referenceDate ?? "");
|
|
155
|
-
|
|
180
|
+
const personal = Number.isFinite(referenceMs) ? catalog?.history_tracks ?? [] : [];
|
|
181
|
+
const moondogHeard = new Set((catalog?.moondog_suggestions ?? []).map(row => trackMatchKey(row.label, row.artist_credit)).filter(Boolean));
|
|
182
|
+
if (!personal.length && !moondogHeard.size) return null;
|
|
156
183
|
const tracks = new Map();
|
|
157
|
-
for (const row of
|
|
184
|
+
for (const row of personal) {
|
|
158
185
|
const key = trackMatchKey(row.label, row.artist_credit);
|
|
159
186
|
if (!key) continue;
|
|
160
187
|
const known = tracks.get(key) ?? { plays: 0, lastMs: 0 };
|
|
@@ -163,12 +190,13 @@ export function listeningFamiliarity(catalog, referenceDate) {
|
|
|
163
190
|
tracks.set(key, known);
|
|
164
191
|
}
|
|
165
192
|
const artists = new Set((catalog.history_artists ?? []).map((row) => normalizedArtistName(row.name)).filter(Boolean));
|
|
166
|
-
const moondogHeard = new Set((catalog.moondog_suggestions ?? []).map((row) => trackMatchKey(row.label, row.artist_credit)).filter(Boolean));
|
|
167
193
|
return { referenceMs, tracks, artists, moondogHeard };
|
|
168
194
|
}
|
|
169
195
|
|
|
170
|
-
export
|
|
171
|
-
|
|
196
|
+
export const isHeardMixSlot = (slot) => slot === "familiar" || slot === "returning" || slot === "heard";
|
|
197
|
+
|
|
198
|
+
export function mixSlot(track, familiarity, completed = false) {
|
|
199
|
+
if (!familiarity) return completed ? "heard" : "unknown";
|
|
172
200
|
const names = Array.isArray(track?.artists) && track.artists.length ? track.artists : creditNames(track?.artist_credit);
|
|
173
201
|
let plays = 0;
|
|
174
202
|
let lastMs = 0;
|
|
@@ -182,7 +210,8 @@ export function mixSlot(track, familiarity) {
|
|
|
182
210
|
lastMs = Math.max(lastMs, known.lastMs);
|
|
183
211
|
}
|
|
184
212
|
if (plays >= 3) return familiarity.referenceMs - lastMs <= 365 * DAY_MS ? "familiar" : "returning";
|
|
185
|
-
if (plays > 0 || moondogHeard) return "heard";
|
|
213
|
+
if (plays > 0 || moondogHeard || completed) return "heard";
|
|
214
|
+
if (!familiarity.tracks.size) return "unknown";
|
|
186
215
|
return names.some((name) => familiarity.artists.has(normalizedArtistName(name))) ? "known_artist" : "new";
|
|
187
216
|
}
|
|
188
217
|
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { avoidKey } from "../core/listener-avoids.mjs";
|
|
2
|
+
|
|
1
3
|
// The limits below apply to delivery, never to the corpus being analyzed.
|
|
2
4
|
export const PROFILE_SECTIONS = Object.freeze([
|
|
3
5
|
"overview", "history_artists", "history_tracks", "recent_artists", "recent_tracks",
|
|
@@ -9,6 +11,32 @@ export const PROFILE_SECTIONS = Object.freeze([
|
|
|
9
11
|
export const TRAJECTORIES = Object.freeze(["rising", "steady", "fading", "returning", "burst", "unknown"]);
|
|
10
12
|
|
|
11
13
|
const normalize = (value) => String(value ?? "").normalize("NFKC").toLocaleLowerCase("und");
|
|
14
|
+
// Recompose retained marks before substring search, so カ does not match ガ.
|
|
15
|
+
const choiceKey = (value) => avoidKey(value).normalize("NFC");
|
|
16
|
+
|
|
17
|
+
function matchesTrackCredit(row, needle, resolveChoice) {
|
|
18
|
+
if (row.entity_type !== "track" || !row.label || !row.artist_credit) return false;
|
|
19
|
+
const artist = choiceKey(row.artist_credit);
|
|
20
|
+
// A legacy Apple display label needs a catalog lookup only for a matching artist or a returned row.
|
|
21
|
+
for (const suffix of [` by ${artist}`, ` - ${artist}`]) {
|
|
22
|
+
if (needle.endsWith(suffix) && needle.slice(0, -suffix.length) === choiceKey(resolveChoice(row).label)) return true;
|
|
23
|
+
}
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function matchesField(row, needle, key) {
|
|
28
|
+
return [
|
|
29
|
+
row.name, row.label, row.artist_credit, row.release, row.genre, row.year, row.evidence_kind,
|
|
30
|
+
row.source_label, row.period, row.text, row.playlist_name, ...(row.playlist_names ?? []),
|
|
31
|
+
].some(text => key(text).includes(needle));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export const isListenerChoiceSection = section => section === "listener_preferences" || section === "listener_avoids";
|
|
35
|
+
|
|
36
|
+
export function listenerChoiceMatcher(query, resolveChoice = row => row) {
|
|
37
|
+
const needle = choiceKey(query) || normalize(query);
|
|
38
|
+
return row => Boolean(needle) && (matchesField(row, needle, choiceKey) || matchesTrackCredit(row, needle, resolveChoice));
|
|
39
|
+
}
|
|
12
40
|
|
|
13
41
|
export function profileExplorationInput(value = {}) {
|
|
14
42
|
if (!value || typeof value !== "object" || Array.isArray(value) ||
|
|
@@ -34,16 +62,17 @@ export function profileExplorationInput(value = {}) {
|
|
|
34
62
|
return { section, query: query.trim(), offset, limit, sort, ...(trajectory ? { trajectory } : {}) };
|
|
35
63
|
}
|
|
36
64
|
|
|
37
|
-
export function exploreProfileCatalog({ listening, apple, input }) {
|
|
65
|
+
export function exploreProfileCatalog({ listening, apple, input, resolveChoice = row => row }) {
|
|
38
66
|
const { section, query, offset, limit, sort, trajectory } = profileExplorationInput(input);
|
|
39
67
|
const catalog = { ...listening?.sections, ...apple?.sections };
|
|
40
68
|
const all = catalog[section] ?? [];
|
|
69
|
+
const choiceMatch = isListenerChoiceSection(section) ? listenerChoiceMatcher(query, resolveChoice) : null;
|
|
41
70
|
const needle = normalize(query);
|
|
42
|
-
let matches = all.filter((row) =>
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
71
|
+
let matches = all.filter((row) => {
|
|
72
|
+
if (trajectory && row.trajectory !== trajectory) return false;
|
|
73
|
+
if (!needle) return true;
|
|
74
|
+
return choiceMatch ? choiceMatch(row) : matchesField(row, needle, normalize);
|
|
75
|
+
});
|
|
47
76
|
if (sort !== "ranked") {
|
|
48
77
|
matches = matches.map((row, index) => ({ row, index })).sort((left, right) => {
|
|
49
78
|
const order = sort === "least_played"
|
|
@@ -53,6 +82,7 @@ export function exploreProfileCatalog({ listening, apple, input }) {
|
|
|
53
82
|
}).map(({ row }) => row);
|
|
54
83
|
}
|
|
55
84
|
const items = matches.slice(offset, offset + limit).map((row) => {
|
|
85
|
+
if (choiceMatch) return resolveChoice(row);
|
|
56
86
|
if (!needle || !row.playlist_names) return row;
|
|
57
87
|
// Search every membership, and keep matching names in the bounded display.
|
|
58
88
|
return { ...row, playlist_names: [...row.playlist_names].sort((left, right) =>
|
|
@@ -11,6 +11,11 @@ export function recordedShare(total, recorded, atLeast = 1) {
|
|
|
11
11
|
return recorded === 0 ? "none" : "some";
|
|
12
12
|
}
|
|
13
13
|
|
|
14
|
+
// Below 95% duration coverage, rank a listening period by plays.
|
|
15
|
+
export function rankingTimeCoverage(plays, timed) {
|
|
16
|
+
return recordedShare(plays, timed, 0.95);
|
|
17
|
+
}
|
|
18
|
+
|
|
14
19
|
/**
|
|
15
20
|
* What a set of plays recorded: its listening time and its skips, each "all",
|
|
16
21
|
* "some" or "none". `timedPlayCount` counts plays with a recorded length, and
|
|
@@ -1,18 +1,24 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import { collectionCoverage } from "./music-providers.mjs";
|
|
3
3
|
|
|
4
|
+
import { importHistoryStrings } from "../i18n/import-history.mjs";
|
|
5
|
+
import { SPOTIFY_EXTENDED_HISTORY_SCOPE } from "../integrations/spotify/extended-streaming-history.mjs";
|
|
4
6
|
import { readSpotifyHistoryArchive } from "../integrations/spotify/history-archive.mjs";
|
|
5
7
|
import { openEphemeralListeningHistoryStore } from "./listening-history-store.mjs";
|
|
6
8
|
|
|
7
9
|
export const SPOTIFY_ARCHIVE_SET_MAXIMUM = 2;
|
|
8
10
|
|
|
9
|
-
function
|
|
11
|
+
export function preferenceIdentity(item) {
|
|
12
|
+
return JSON.stringify([item.entity_type, normalizedLabel(item.label), normalizedLabel(item.artist_credit)]);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function uniquePreferences(items, maximum) {
|
|
10
16
|
const seen = new Set();
|
|
11
17
|
const values = [];
|
|
12
18
|
for (const item of items) {
|
|
13
|
-
|
|
14
|
-
const key =
|
|
15
|
-
if (
|
|
19
|
+
if (!normalizedLabel(item.label)) continue;
|
|
20
|
+
const key = preferenceIdentity(item);
|
|
21
|
+
if (seen.has(key)) continue;
|
|
16
22
|
seen.add(key);
|
|
17
23
|
values.push(item);
|
|
18
24
|
if (values.length === maximum) break;
|
|
@@ -68,68 +74,31 @@ function uniqueArtistFacets(listening, maximum) {
|
|
|
68
74
|
return values;
|
|
69
75
|
}
|
|
70
76
|
|
|
77
|
+
export function curatedPreferenceItems(listening, isAvoided = assertionAvoids) {
|
|
78
|
+
const curated = listening?.curated_preferences ?? {};
|
|
79
|
+
return [
|
|
80
|
+
...(curated.saved_tracks ?? []).map(item => ({
|
|
81
|
+
...item, entity_type: "track", signal: `Saved in ${item.source_label ?? "Spotify"} library`,
|
|
82
|
+
})),
|
|
83
|
+
...(curated.followed_artists ?? []).map(item => ({
|
|
84
|
+
...item, entity_type: "artist", label: item.name, signal: "Followed artist",
|
|
85
|
+
})),
|
|
86
|
+
...(curated.saved_albums ?? []).map(item => ({
|
|
87
|
+
...item, entity_type: "album", signal: "Saved album",
|
|
88
|
+
})),
|
|
89
|
+
...(curated.playlist_anchors ?? []).map(item => ({
|
|
90
|
+
...item, entity_type: "track", signal: `${item.source_label ?? "Spotify"} playlist anchor`,
|
|
91
|
+
})),
|
|
92
|
+
].filter(item => item.entity_type === "album"
|
|
93
|
+
? !isAvoided(listening, "artist", item.artist_credit)
|
|
94
|
+
: !isAvoided(listening, item.entity_type, item.label, item.artist_credit));
|
|
95
|
+
}
|
|
96
|
+
|
|
71
97
|
function strongPreferences(listening, maximum) {
|
|
72
|
-
const
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
...item,
|
|
77
|
-
signal: `You explicitly said you like this ${item.entity_type}`,
|
|
78
|
-
})),
|
|
79
|
-
...(curated.saved_tracks ?? [])
|
|
80
|
-
.filter(
|
|
81
|
-
(item) =>
|
|
82
|
-
!assertionAvoids(
|
|
83
|
-
listening,
|
|
84
|
-
"track",
|
|
85
|
-
item.label,
|
|
86
|
-
item.artist_credit,
|
|
87
|
-
),
|
|
88
|
-
)
|
|
89
|
-
.map((item) => ({
|
|
90
|
-
...item,
|
|
91
|
-
signal: `Saved in ${item.source_label ?? "Spotify"} library`,
|
|
92
|
-
})),
|
|
93
|
-
...(curated.followed_artists ?? [])
|
|
94
|
-
.filter(
|
|
95
|
-
(item) => !assertionAvoids(listening, "artist", item.name),
|
|
96
|
-
)
|
|
97
|
-
.map((item) => ({
|
|
98
|
-
...item,
|
|
99
|
-
label: item.name,
|
|
100
|
-
signal: "Followed artist",
|
|
101
|
-
})),
|
|
102
|
-
...(curated.saved_albums ?? [])
|
|
103
|
-
.filter(
|
|
104
|
-
(item) =>
|
|
105
|
-
!assertionAvoids(
|
|
106
|
-
listening,
|
|
107
|
-
"album",
|
|
108
|
-
item.label,
|
|
109
|
-
item.artist_credit,
|
|
110
|
-
),
|
|
111
|
-
)
|
|
112
|
-
.map((item) => ({
|
|
113
|
-
...item,
|
|
114
|
-
signal: "Saved album",
|
|
115
|
-
})),
|
|
116
|
-
...(curated.playlist_anchors ?? [])
|
|
117
|
-
.filter(
|
|
118
|
-
(item) =>
|
|
119
|
-
!assertionAvoids(
|
|
120
|
-
listening,
|
|
121
|
-
"track",
|
|
122
|
-
item.label,
|
|
123
|
-
item.artist_credit,
|
|
124
|
-
),
|
|
125
|
-
)
|
|
126
|
-
.map((item) => ({
|
|
127
|
-
...item,
|
|
128
|
-
signal: `${item.source_label ?? "Spotify"} playlist anchor`,
|
|
129
|
-
})),
|
|
130
|
-
],
|
|
131
|
-
maximum,
|
|
132
|
-
);
|
|
98
|
+
const stated = (listening.listener_assertions?.preferences ?? []).map(item => ({
|
|
99
|
+
...item, signal: `You explicitly said you like this ${item.entity_type}`,
|
|
100
|
+
}));
|
|
101
|
+
return uniquePreferences([...stated, ...curatedPreferenceItems(listening)], maximum);
|
|
133
102
|
}
|
|
134
103
|
|
|
135
104
|
function createListeningProfileProjection(
|
|
@@ -164,6 +133,8 @@ function createListeningProfileProjection(
|
|
|
164
133
|
.slice(0, maxItems)
|
|
165
134
|
.map((item) => ({
|
|
166
135
|
label: item.label,
|
|
136
|
+
entity_type: "track",
|
|
137
|
+
...(item.artist_credit ? { artist_credit: item.artist_credit } : {}),
|
|
167
138
|
level:
|
|
168
139
|
Number.isInteger(item.play_count) && item.play_count >= 20
|
|
169
140
|
? "high"
|
|
@@ -325,6 +296,7 @@ async function ingestSpotifyArchiveSet({
|
|
|
325
296
|
store,
|
|
326
297
|
capturedAt,
|
|
327
298
|
historyArchiveImporter,
|
|
299
|
+
persistent = false,
|
|
328
300
|
}) {
|
|
329
301
|
const archiveHashes = new Set();
|
|
330
302
|
const receipts = [];
|
|
@@ -334,6 +306,9 @@ async function ingestSpotifyArchiveSet({
|
|
|
334
306
|
subjectId,
|
|
335
307
|
capturedAt,
|
|
336
308
|
});
|
|
309
|
+
if (persistent && bundle.import_batch.data_scope === SPOTIFY_EXTENDED_HISTORY_SCOPE && !bundle.listening_events.length) {
|
|
310
|
+
throw new Error(importHistoryStrings("en").noExtendedMusic);
|
|
311
|
+
}
|
|
337
312
|
const archiveSha256 = bundle?.import_batch?.archive_sha256;
|
|
338
313
|
if (
|
|
339
314
|
typeof archiveSha256 === "string" &&
|
|
@@ -464,6 +439,7 @@ async function persistTasteFromSpotifyArchives({
|
|
|
464
439
|
store,
|
|
465
440
|
capturedAt: normalizedCapturedAt,
|
|
466
441
|
historyArchiveImporter,
|
|
442
|
+
persistent: true,
|
|
467
443
|
});
|
|
468
444
|
const listening = store.profileSummary({ subjectId, maxItems });
|
|
469
445
|
return {
|