@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
|
@@ -14,13 +14,16 @@ import { randomUUID } from "node:crypto";
|
|
|
14
14
|
import { chmod, mkdir } from "node:fs/promises";
|
|
15
15
|
import path from "node:path";
|
|
16
16
|
import { resolveMoondogStateDirectory } from "./state-directory.mjs";
|
|
17
|
+
import { namedLibraryRecording } from "./library-names.mjs";
|
|
18
|
+
import { parsePlaylistLink } from "../integrations/playlist-links.mjs";
|
|
17
19
|
|
|
18
20
|
export const LIBRARY_SCHEMA_VERSION = 1;
|
|
19
21
|
export const SAVED_PLAYLIST_ID = "saved";
|
|
20
22
|
export const MAX_DEPTH = 4;
|
|
21
23
|
export const MAX_ENTRIES = 2000;
|
|
22
24
|
const ORIGINS = new Set(["listener", "moondog", "spotify", "apple_music", "netease", "qq_music", "file"]);
|
|
23
|
-
|
|
25
|
+
// "source" marks the songs a playlist link brought in, at import or refresh; a later refresh may remove those only.
|
|
26
|
+
const ADDERS = new Set(["listener", "moondog", "source"]);
|
|
24
27
|
|
|
25
28
|
export const resolveLibraryPath = (environment = process.env) => path.join(resolveMoondogStateDirectory(environment), "library.sqlite");
|
|
26
29
|
|
|
@@ -72,6 +75,16 @@ const schema = `
|
|
|
72
75
|
|
|
73
76
|
const libraryError = (code, message) => Object.assign(new Error(message), { code });
|
|
74
77
|
|
|
78
|
+
// The collections the room's library face opens beside the playlists; none is stored, each is read from the entries.
|
|
79
|
+
export const MADE_COLLECTION_ID = "made";
|
|
80
|
+
const SEARCH_LIMIT = 200;
|
|
81
|
+
export const isCollectionId = (id) => {
|
|
82
|
+
const text = String(id ?? "");
|
|
83
|
+
return text === MADE_COLLECTION_ID || /^(album|artist|search):/u.test(text);
|
|
84
|
+
};
|
|
85
|
+
// An album and an artist go by the first name a song credits; a duet stays under its first singer.
|
|
86
|
+
const leadArtist = (credit) => String(credit ?? "").split(/\s*(?:,|;|、|\s+feat\.?\s+|\s+ft\.?\s+|\s+featuring\s+)\s*/iu)[0].trim();
|
|
87
|
+
|
|
75
88
|
function cleanText(value, maximum, label, { optional = false } = {}) {
|
|
76
89
|
if (optional && (value === undefined || value === null || (typeof value === "string" && !value.trim()))) return null;
|
|
77
90
|
if (typeof value !== "string") throw libraryError("library_invalid", `${label} must be text.`);
|
|
@@ -84,7 +97,10 @@ const madeIdPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[
|
|
|
84
97
|
|
|
85
98
|
// The ids a service gave a song, kept so the next play skips the search. Only short plain strings are kept.
|
|
86
99
|
// A cached Spotify recording keeps its own title and credit, so a later Avoid is checked against it.
|
|
87
|
-
const
|
|
100
|
+
const SOURCE_REF = { spotify: "spotify_uri", apple_music: "apple_music_id", netease: "netease_id", qq_music: "qq_music_id" };
|
|
101
|
+
// The Music app's persistent ID identifies a local track. It cannot resolve a public Apple Music song.
|
|
102
|
+
const providerRefs = [...Object.values(SOURCE_REF), "music_app_persistent_id"];
|
|
103
|
+
const REF_KEYS = [...providerRefs, "spotify_title", "spotify_credit"];
|
|
88
104
|
function cleanRefs(refs) {
|
|
89
105
|
const kept = {};
|
|
90
106
|
if (!refs || typeof refs !== "object") return kept;
|
|
@@ -121,9 +137,69 @@ export function normalizeLibraryEntry(entry) {
|
|
|
121
137
|
};
|
|
122
138
|
}
|
|
123
139
|
|
|
124
|
-
// The same song twice in Saved is one song; ISRC first, then title and artist without case or marks.
|
|
125
140
|
const fold = (value) => String(value ?? "").normalize("NFKD").replace(/\p{M}/gu, "").toLocaleLowerCase("en-US").replace(/[^\p{L}\p{N}]+/gu, " ").trim();
|
|
126
|
-
|
|
141
|
+
const nameKey = text => fold(text) || String(text ?? "").normalize("NFKC").trim();
|
|
142
|
+
const songNameKey = entry => JSON.stringify([nameKey(entry.title), nameKey(entry.artist_credit)]);
|
|
143
|
+
function recordingIds(entry) {
|
|
144
|
+
if (entry.kind === "made") return [`made:${entry.made_id}`];
|
|
145
|
+
const ids = entry.isrc ? [`isrc:${entry.isrc}`] : [];
|
|
146
|
+
for (const key of providerRefs) if (entry.refs?.[key]) ids.push(`${key}:${entry.refs[key]}`);
|
|
147
|
+
return ids;
|
|
148
|
+
}
|
|
149
|
+
export const entryIdentity = entry => recordingIds(entry)[0] ?? `song:${nameKey(entry.title)}|${nameKey(entry.artist_credit)}`;
|
|
150
|
+
function compatibleRecordings(a, b) {
|
|
151
|
+
if (a.isrc && b.isrc && a.isrc !== b.isrc) return false;
|
|
152
|
+
return providerRefs.every(key => !a.refs[key] || !b.refs[key] || a.refs[key] === b.refs[key]);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function matchUnidentifiedSong(entry, namesakes, hasId) {
|
|
156
|
+
const album = nameKey(entry.album);
|
|
157
|
+
const candidates = namesakes.filter(other => !album || !other.album || nameKey(other.album) === album);
|
|
158
|
+
const unidentified = candidates.filter(other => !recordingIds(other).length);
|
|
159
|
+
// Two identified songs join by a shared recording ID, or by title, artist and album when no ID of one kind
|
|
160
|
+
// (or ISRC) differs: the same song kept from two services. Two IDs of one kind are two recordings.
|
|
161
|
+
const identified = album ? candidates.filter(other => recordingIds(other).length && nameKey(other.album) === album &&
|
|
162
|
+
compatibleRecordings(entry, other)) : [];
|
|
163
|
+
const pool = hasId ? [...unidentified, ...identified] : unidentified.length ? unidentified : candidates;
|
|
164
|
+
const sameAlbum = pool.filter(other => nameKey(other.album) === album);
|
|
165
|
+
const matches = sameAlbum.length ? sameAlbum : pool;
|
|
166
|
+
return matches.length === 1 ? matches[0] : null;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// Saved and its derived collections use the same recording identity. Older rows can have
|
|
170
|
+
// only names. A later observation fills in their missing IDs without moving the row.
|
|
171
|
+
class LibraryRecordings {
|
|
172
|
+
byId = new Map();
|
|
173
|
+
byName = new Map();
|
|
174
|
+
|
|
175
|
+
register(entry) {
|
|
176
|
+
for (const id of recordingIds(entry)) this.byId.set(id, entry);
|
|
177
|
+
if (entry.kind === "song") {
|
|
178
|
+
const name = songNameKey(entry);
|
|
179
|
+
const namesakes = this.byName.get(name) ?? [];
|
|
180
|
+
namesakes.push(entry);
|
|
181
|
+
this.byName.set(name, namesakes);
|
|
182
|
+
}
|
|
183
|
+
return entry;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
keep(entry) {
|
|
187
|
+
const ids = recordingIds(entry);
|
|
188
|
+
const namesakes = this.byName.get(songNameKey(entry)) ?? [];
|
|
189
|
+
const exact = ids.map(id => this.byId.get(id)).find(Boolean);
|
|
190
|
+
const kept = exact ?? (entry.kind === "song" && namesakes.length
|
|
191
|
+
? matchUnidentifiedSong(entry, namesakes, ids.length > 0) : null);
|
|
192
|
+
if (!kept) return this.register(entry);
|
|
193
|
+
// Only add missing references. A second release with the same ISRC can have a different catalog ID.
|
|
194
|
+
if (entry.kind === "song") {
|
|
195
|
+
kept.refs = { ...entry.refs, ...kept.refs };
|
|
196
|
+
kept.isrc ??= entry.isrc;
|
|
197
|
+
kept.album ??= entry.album;
|
|
198
|
+
}
|
|
199
|
+
for (const id of ids) this.byId.set(id, kept);
|
|
200
|
+
return kept;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
127
203
|
|
|
128
204
|
const entryOf = (row) => ({
|
|
129
205
|
id: row.entry_id,
|
|
@@ -153,8 +229,18 @@ export function libraryMentions({ folders = [], playlists = [] } = {}, texts = [
|
|
|
153
229
|
...folders.map((folder) => ({ kind: "folder", id: folder.id, name: folder.name })),
|
|
154
230
|
].sort((a, b) => b.name.length - a.name.length);
|
|
155
231
|
const found = new Map();
|
|
156
|
-
for (const
|
|
157
|
-
let rest = String(text ?? "").toLowerCase();
|
|
232
|
+
for (const message of [...texts].reverse()) {
|
|
233
|
+
let rest = String(message?.text ?? message ?? "").toLowerCase();
|
|
234
|
+
// A message sent from the library has its displayed @name on the first line and the exact
|
|
235
|
+
// location beside it in the journal. Two playlists or albums can have the same name.
|
|
236
|
+
const ref = message?.libraryRef;
|
|
237
|
+
if (typeof ref === "string" && ref && rest.startsWith("@")) {
|
|
238
|
+
const kind = ref === "library" ? "library" : ref.startsWith("folder:") ? "folder" : "playlist";
|
|
239
|
+
const id = kind === "folder" ? ref.slice(7) : ref;
|
|
240
|
+
found.set(`${kind}:${id}`, { kind, id });
|
|
241
|
+
const newline = rest.indexOf("\n");
|
|
242
|
+
rest = newline < 0 ? "" : rest.slice(newline + 1);
|
|
243
|
+
}
|
|
158
244
|
if (!rest.includes("@")) continue;
|
|
159
245
|
for (const { kind, id, name } of names) {
|
|
160
246
|
const wanted = `@${name.toLowerCase()}`;
|
|
@@ -170,11 +256,79 @@ export function libraryMentions({ folders = [], playlists = [] } = {}, texts = [
|
|
|
170
256
|
return [...found.values()].slice(0, limit);
|
|
171
257
|
}
|
|
172
258
|
|
|
259
|
+
// Old imports may name a provider without retaining a usable link.
|
|
260
|
+
function linkedSource(origin, source) {
|
|
261
|
+
if (!Object.hasOwn(SOURCE_REF, origin) || source?.provider !== origin || !source.id || !source.url) return false;
|
|
262
|
+
try {
|
|
263
|
+
const link = parsePlaylistLink(source.url);
|
|
264
|
+
if (link.provider !== "public") return link.provider === origin && link.id === String(source.id);
|
|
265
|
+
const provider = new URL(link.url).hostname.endsWith(".qq.com") ? "qq_music" : "netease";
|
|
266
|
+
return provider === origin;
|
|
267
|
+
} catch { return false; }
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// Match occurrences, starting with recording IDs so a song known only by name cannot take a
|
|
271
|
+
// later occurrence's exact match. An ordinary playlist can keep the same recording several times.
|
|
272
|
+
function matchRefreshSongs(existing, incoming, provider) {
|
|
273
|
+
const available = new Set(existing);
|
|
274
|
+
const matched = Array(incoming.length).fill(null);
|
|
275
|
+
function match(keyOf, compatible = () => true) {
|
|
276
|
+
const byKey = new Map();
|
|
277
|
+
for (const song of available) {
|
|
278
|
+
const key = keyOf(song);
|
|
279
|
+
if (!key) continue;
|
|
280
|
+
if (!byKey.has(key)) byKey.set(key, []);
|
|
281
|
+
byKey.get(key).push(song);
|
|
282
|
+
}
|
|
283
|
+
incoming.forEach((song, index) => {
|
|
284
|
+
if (matched[index]) return;
|
|
285
|
+
const options = byKey.get(keyOf(song));
|
|
286
|
+
const found = options?.findIndex((other) => compatible(song, other)) ?? -1;
|
|
287
|
+
if (found < 0) return;
|
|
288
|
+
const [other] = options.splice(found, 1);
|
|
289
|
+
available.delete(other);
|
|
290
|
+
matched[index] = other;
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
const sourceRef = SOURCE_REF[provider];
|
|
294
|
+
match((song) => song.refs[sourceRef]);
|
|
295
|
+
match((song) => song.isrc);
|
|
296
|
+
const refs = Object.values(SOURCE_REF);
|
|
297
|
+
for (const key of refs) if (key !== sourceRef) match((song) => song.refs[key]);
|
|
298
|
+
match(songNameKey, compatibleRecordings);
|
|
299
|
+
return { matched, unmatched: available };
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function mergeRefreshSong(local, song) {
|
|
303
|
+
const refs = { ...local.refs };
|
|
304
|
+
if (song.refs.spotify_uri && refs.spotify_uri !== song.refs.spotify_uri) {
|
|
305
|
+
delete refs.spotify_title;
|
|
306
|
+
delete refs.spotify_credit;
|
|
307
|
+
}
|
|
308
|
+
Object.assign(refs, song.refs);
|
|
309
|
+
const album = song.album ?? local.album;
|
|
310
|
+
const isrc = song.isrc ?? local.isrc;
|
|
311
|
+
if (local.title === song.title && local.artist_credit === song.artist_credit && local.album === album && local.isrc === isrc &&
|
|
312
|
+
JSON.stringify(local.refs) === JSON.stringify(refs)) return local;
|
|
313
|
+
return { ...local, title: song.title, artist_credit: song.artist_credit, album, isrc, refs };
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
// Whether a playlist's link brought this song in. Imports before the "source" mark kept their songs as the
|
|
317
|
+
// listener's, added in the moment the playlist was made; a playlist with any marked song has the mark.
|
|
318
|
+
function fromLink(song, playlist, marked) {
|
|
319
|
+
if (song.added_by === "source") return true;
|
|
320
|
+
return !marked && song.added_by === "listener" && Date.parse(song.added_at) - Date.parse(playlist.createdAt) < 10_000;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// Snapshot only the rows a refresh can change. Renames, folder moves and exports survive a confirmation.
|
|
324
|
+
const refreshBasis = (playlist) => JSON.stringify([playlist.origin, playlist.source, playlist.entries]);
|
|
325
|
+
|
|
173
326
|
export class LibraryStore {
|
|
174
327
|
#database;
|
|
175
328
|
#clock;
|
|
176
329
|
#closed = false;
|
|
177
330
|
#listeners = new Set();
|
|
331
|
+
#refreshPlans = new WeakMap();
|
|
178
332
|
|
|
179
333
|
constructor(database, { clock = () => new Date() } = {}) {
|
|
180
334
|
this.#database = database;
|
|
@@ -184,14 +338,14 @@ export class LibraryStore {
|
|
|
184
338
|
|
|
185
339
|
#now() { return new Date(this.#clock()).toISOString(); }
|
|
186
340
|
#open() { if (this.#closed) throw libraryError("library_closed", "The library is closed."); }
|
|
187
|
-
#transaction(work) {
|
|
341
|
+
#transaction(work, notify = true) {
|
|
188
342
|
this.#open();
|
|
189
343
|
this.#database.exec("BEGIN IMMEDIATE");
|
|
190
344
|
try {
|
|
191
345
|
const result = work();
|
|
192
346
|
this.#database.exec("COMMIT");
|
|
193
347
|
// This connection's own writes leave its data version alone, so its surfaces hear of them here.
|
|
194
|
-
for (const listener of this.#listeners) { try { listener(); } catch { /* A surface's redraw can't undo the write. */ } }
|
|
348
|
+
if (notify) for (const listener of this.#listeners) { try { listener(); } catch { /* A surface's redraw can't undo the write. */ } }
|
|
195
349
|
return result;
|
|
196
350
|
} catch (error) {
|
|
197
351
|
this.#database.exec("ROLLBACK");
|
|
@@ -266,31 +420,121 @@ export class LibraryStore {
|
|
|
266
420
|
}
|
|
267
421
|
return null;
|
|
268
422
|
};
|
|
269
|
-
|
|
423
|
+
|
|
270
424
|
const playlists = this.#database.prepare(`SELECT p.playlist_id, p.folder_id, p.name, p.origin, p.source_json, p.position, p.updated_at,
|
|
271
425
|
(SELECT COUNT(*) FROM library_entries e WHERE e.playlist_id = p.playlist_id) AS count,
|
|
272
426
|
(SELECT COUNT(*) FROM library_entries e WHERE e.playlist_id = p.playlist_id AND e.kind = 'made') AS made
|
|
273
427
|
FROM library_playlists p`).all()
|
|
274
|
-
.map((row) =>
|
|
275
|
-
|
|
276
|
-
|
|
428
|
+
.map((row) => {
|
|
429
|
+
const source = row.source_json ? JSON.parse(row.source_json) : null;
|
|
430
|
+
return { id: row.playlist_id, folderId: row.folder_id ?? null, name: row.name, origin: row.origin, position: row.position,
|
|
431
|
+
updatedAt: row.updated_at, count: row.count, made: row.made, cover: source?.cover ? { artwork_url: source.cover } : coverOf(row.playlist_id),
|
|
432
|
+
linked: linkedSource(row.origin, source), ...(row.playlist_id === SAVED_PLAYLIST_ID ? { saved: true } : {}) };
|
|
433
|
+
});
|
|
277
434
|
return { folders, playlists };
|
|
278
435
|
}
|
|
279
436
|
|
|
280
|
-
/** One playlist with its entries in order, or null. */
|
|
437
|
+
/** One playlist with its entries in order, or null. An album, artist, made or search id reads a collection. */
|
|
281
438
|
playlist(id) {
|
|
282
439
|
this.#open();
|
|
283
|
-
|
|
440
|
+
if (isCollectionId(id)) return this.#gathered(String(id));
|
|
441
|
+
const row =this.#database.prepare("SELECT * FROM library_playlists WHERE playlist_id = ?").get(String(id ?? ""));
|
|
284
442
|
if (!row) return null;
|
|
285
443
|
const entries = this.#database.prepare("SELECT * FROM library_entries WHERE playlist_id = ? ORDER BY position, added_at").all(row.playlist_id).map(entryOf);
|
|
286
444
|
const exports = this.#database.prepare("SELECT provider, remote_id, url, count, signature, exported_at FROM library_exports WHERE playlist_id = ? ORDER BY provider")
|
|
287
445
|
.all(row.playlist_id).map((copy) => ({ provider: copy.provider, id: copy.remote_id, url: copy.url ?? null, count: copy.count,
|
|
288
446
|
signature: copy.signature ?? null, exportedAt: copy.exported_at }));
|
|
289
|
-
|
|
290
|
-
|
|
447
|
+
const source = row.source_json ? JSON.parse(row.source_json) : null;
|
|
448
|
+
return { id: row.playlist_id, folderId: row.folder_id ?? null, name: row.name, origin: row.origin, linked: linkedSource(row.origin, source),
|
|
449
|
+
...(source ? { source } : {}), createdAt: row.created_at, updatedAt: row.updated_at,
|
|
291
450
|
...(row.playlist_id === SAVED_PLAYLIST_ID ? { saved: true } : {}), ...(exports.length ? { exports } : {}), entries };
|
|
292
451
|
}
|
|
293
452
|
|
|
453
|
+
// Every song and made track in the library once, read across all its playlists: Saved first, then the playlists in
|
|
454
|
+
// their order, so a song kept in several places is the one Saved holds. Each entry keeps the playlist it came from.
|
|
455
|
+
#everything() {
|
|
456
|
+
this.#open();
|
|
457
|
+
const rows = this.#database.prepare(`SELECT e.*, p.position AS playlist_position FROM library_entries e
|
|
458
|
+
JOIN library_playlists p ON p.playlist_id = e.playlist_id ORDER BY p.position, p.playlist_id, e.position, e.added_at`).all();
|
|
459
|
+
const seen = new LibraryRecordings();
|
|
460
|
+
const entries = [];
|
|
461
|
+
for (const row of rows) {
|
|
462
|
+
const entry = { ...entryOf(row), playlist_id: row.playlist_id };
|
|
463
|
+
if (row.playlist_id === SAVED_PLAYLIST_ID) entries.push(seen.register(entry));
|
|
464
|
+
else if (seen.keep(entry) === entry) entries.push(entry);
|
|
465
|
+
}
|
|
466
|
+
return entries;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* The library by what it holds rather than how it is filed: the albums and artists its songs come from, and the
|
|
471
|
+
* tracks Moondog made, for the room's library face. Each opens as a playlist of its own (`playlist(id)`), read only.
|
|
472
|
+
*/
|
|
473
|
+
collection() {
|
|
474
|
+
const entries = this.#everything();
|
|
475
|
+
const albums = new Map();
|
|
476
|
+
const artists = new Map();
|
|
477
|
+
const made = entries.filter((entry) => entry.kind === "made");
|
|
478
|
+
const coverOf = (entry) => (entry.refs?.artwork_url ? { artwork_url: entry.refs.artwork_url } : null);
|
|
479
|
+
for (const entry of entries) {
|
|
480
|
+
if (entry.kind !== "song") continue;
|
|
481
|
+
const artist = leadArtist(entry.artist_credit);
|
|
482
|
+
if (artist) {
|
|
483
|
+
const key = `artist:${fold(artist)}`;
|
|
484
|
+
const known = artists.get(key) ?? { id: key, name: artist, count: 0, cover: null };
|
|
485
|
+
known.count += 1;
|
|
486
|
+
known.cover ??= coverOf(entry);
|
|
487
|
+
artists.set(key, known);
|
|
488
|
+
}
|
|
489
|
+
if (entry.album) {
|
|
490
|
+
const key = `album:${fold(entry.album)}|${fold(artist)}`;
|
|
491
|
+
const known = albums.get(key) ?? { id: key, name: entry.album, artist, count: 0, cover: null };
|
|
492
|
+
known.count += 1;
|
|
493
|
+
known.cover ??= coverOf(entry);
|
|
494
|
+
albums.set(key, known);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
const byName = (a, b) => a.name.localeCompare(b.name);
|
|
498
|
+
return {
|
|
499
|
+
songs: entries.length - made.length,
|
|
500
|
+
albums: [...albums.values()].sort(byName),
|
|
501
|
+
artists: [...artists.values()].sort(byName),
|
|
502
|
+
made: { id: MADE_COLLECTION_ID, count: made.length, cover: made.length ? { made_id: made.at(-1).made_id } : null },
|
|
503
|
+
};
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
// A collection the face opens: an album, an artist, the made tracks, or a search, shaped as a playlist without a
|
|
507
|
+
// place of its own. Its entries keep their real ids, so playing, keeping and copying them work as from a playlist.
|
|
508
|
+
#gathered(id) {
|
|
509
|
+
const entries = this.#everything();
|
|
510
|
+
const songs = (wanted) => entries.filter((entry) => entry.kind === "song" && wanted(entry));
|
|
511
|
+
if (id === MADE_COLLECTION_ID) {
|
|
512
|
+
return { id, name: "Made by Moondog", collection: "made", entries: entries.filter((entry) => entry.kind === "made").reverse() };
|
|
513
|
+
}
|
|
514
|
+
if (id.startsWith("album:")) {
|
|
515
|
+
const found = songs((entry) => entry.album && `album:${fold(entry.album)}|${fold(leadArtist(entry.artist_credit))}` === id);
|
|
516
|
+
if (!found.length) return null;
|
|
517
|
+
return { id, name: found[0].album, artist: leadArtist(found[0].artist_credit), collection: "album", entries: found };
|
|
518
|
+
}
|
|
519
|
+
if (id.startsWith("artist:")) {
|
|
520
|
+
const found = songs((entry) => `artist:${fold(leadArtist(entry.artist_credit))}` === id);
|
|
521
|
+
if (!found.length) return null;
|
|
522
|
+
// Album by album, then the loose songs, each in the order it was kept.
|
|
523
|
+
const ordered = [...found].sort((a, b) => (a.album ? 0 : 1) - (b.album ? 0 : 1) || String(a.album ?? "").localeCompare(String(b.album ?? "")));
|
|
524
|
+
return { id, name: leadArtist(found[0].artist_credit), collection: "artist", entries: ordered };
|
|
525
|
+
}
|
|
526
|
+
if (id.startsWith("search:")) {
|
|
527
|
+
const words = fold(id.slice(7)).split(" ").filter(Boolean);
|
|
528
|
+
if (!words.length) return null;
|
|
529
|
+
const found = entries.filter((entry) => {
|
|
530
|
+
const text = fold(`${entry.title} ${entry.artist_credit} ${entry.album ?? ""}`);
|
|
531
|
+
return words.every((word) => text.includes(word));
|
|
532
|
+
}).slice(0, SEARCH_LIMIT);
|
|
533
|
+
return { id, name: id.slice(7), collection: "search", entries: found };
|
|
534
|
+
}
|
|
535
|
+
return null;
|
|
536
|
+
}
|
|
537
|
+
|
|
294
538
|
/** Playlists whose names hold the words, best first, for the agent and the terminal. */
|
|
295
539
|
findPlaylists(query, { limit = 8 } = {}) {
|
|
296
540
|
const wanted = fold(query);
|
|
@@ -369,7 +613,8 @@ export class LibraryStore {
|
|
|
369
613
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(playlistId, folder ?? null, cleanText(name, 120, "Playlist name"), kept,
|
|
370
614
|
source && typeof source === "object" ? JSON.stringify(source).slice(0, 2000) : null, 1e9, at, at);
|
|
371
615
|
this.#place({ id: playlistId, kind: "playlist" }, folder ?? null, beforeId ?? null);
|
|
372
|
-
const
|
|
616
|
+
const by = linkedSource(kept, source) ? "source" : addedBy;
|
|
617
|
+
const added = entries?.length ? this.#add(playlistId, entries, { addedBy: by }) : { added: 0, already: 0 };
|
|
373
618
|
return { id: playlistId, ...added };
|
|
374
619
|
}
|
|
375
620
|
const playlistId = cleanId(id, "Playlist");
|
|
@@ -404,16 +649,21 @@ export class LibraryStore {
|
|
|
404
649
|
|
|
405
650
|
#add(playlistId, entries, { addedBy = "listener", beforeId = null } = {}) {
|
|
406
651
|
const list = (Array.isArray(entries) ? entries : [entries]).map(normalizeLibraryEntry);
|
|
407
|
-
const rows = this.#database.prepare("SELECT entry_id, kind, title, artist_credit, isrc, made_id FROM library_entries WHERE playlist_id = ? ORDER BY position").all(playlistId);
|
|
408
652
|
// Saved holds each song once; a playlist may hold one twice, as a set can.
|
|
409
653
|
const once = playlistId === SAVED_PLAYLIST_ID;
|
|
410
|
-
const
|
|
654
|
+
const rows = this.#database.prepare(`SELECT ${once ? "*" : "entry_id"} FROM library_entries WHERE playlist_id = ? ORDER BY position`).all(playlistId);
|
|
655
|
+
const known = new LibraryRecordings();
|
|
656
|
+
if (once) for (const row of rows) known.register(entryOf(row));
|
|
411
657
|
const fresh = [];
|
|
412
658
|
let already = 0;
|
|
413
659
|
for (const entry of list) {
|
|
414
|
-
const
|
|
415
|
-
if (
|
|
416
|
-
|
|
660
|
+
const kept = once ? known.keep(entry) : entry;
|
|
661
|
+
if (kept !== entry) {
|
|
662
|
+
already++;
|
|
663
|
+
if (kept.id && entry.kind === "song") this.#database.prepare("UPDATE library_entries SET refs_json = ?, album = ?, isrc = ? WHERE entry_id = ?")
|
|
664
|
+
.run(JSON.stringify(kept.refs), kept.album ?? null, kept.isrc ?? null, kept.id);
|
|
665
|
+
continue;
|
|
666
|
+
}
|
|
417
667
|
fresh.push(entry);
|
|
418
668
|
}
|
|
419
669
|
if (rows.length + fresh.length > MAX_ENTRIES) throw libraryError("library_full", `A playlist holds up to ${MAX_ENTRIES} entries.`);
|
|
@@ -461,6 +711,91 @@ export class LibraryStore {
|
|
|
461
711
|
});
|
|
462
712
|
}
|
|
463
713
|
|
|
714
|
+
/** Read-only. Keep the returned plan until the listener confirms its summary. */
|
|
715
|
+
previewPlaylistRefresh(playlistId, { entries, total, complete, source } = {}) {
|
|
716
|
+
const playlist = this.playlist(playlistId);
|
|
717
|
+
if (!playlist?.linked || source?.provider !== playlist.source.provider || String(source.id) !== String(playlist.source.id)) {
|
|
718
|
+
throw libraryError("playlist_not_linked", "This playlist has no matching source link.");
|
|
719
|
+
}
|
|
720
|
+
if (!Array.isArray(entries)) throw libraryError("library_invalid", "The source must supply a list of songs.");
|
|
721
|
+
const knownTotal = Number.isSafeInteger(total) && total >= 0;
|
|
722
|
+
let unreadable = knownTotal ? Math.max(0, total - entries.length) : 0;
|
|
723
|
+
const incoming = [];
|
|
724
|
+
for (const row of entries) {
|
|
725
|
+
try {
|
|
726
|
+
if (row?.kind && row.kind !== "song") { unreadable += 1; continue; }
|
|
727
|
+
incoming.push(normalizeLibraryEntry(row));
|
|
728
|
+
} catch (error) {
|
|
729
|
+
if (error.code !== "library_invalid") throw error;
|
|
730
|
+
unreadable += 1;
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
const partial = complete === false || !knownTotal || total !== entries.length || unreadable > 0;
|
|
734
|
+
if (incoming.length > MAX_ENTRIES) throw libraryError("library_full", `A playlist holds up to ${MAX_ENTRIES} entries.`);
|
|
735
|
+
const existing = playlist.entries.filter((song) => song.kind === "song");
|
|
736
|
+
const { matched, unmatched } = matchRefreshSongs(existing, incoming, source.provider);
|
|
737
|
+
// A song the listener (or Moondog) added here stays when the source lacks it, in its place like a made track.
|
|
738
|
+
const marked = playlist.entries.some((row) => row.added_by === "source");
|
|
739
|
+
const own = new Set([...unmatched].filter((song) => !fromLink(song, playlist, marked)));
|
|
740
|
+
const updates = [];
|
|
741
|
+
const songs = incoming.map((song, index) => {
|
|
742
|
+
const local = matched[index];
|
|
743
|
+
if (!local || partial) return local ?? song;
|
|
744
|
+
const merged = mergeRefreshSong(local, song);
|
|
745
|
+
if (merged !== local) updates.push(merged);
|
|
746
|
+
return merged;
|
|
747
|
+
});
|
|
748
|
+
const fresh = songs.filter((song) => !song.id);
|
|
749
|
+
const remove = partial ? [] : [...unmatched].filter((song) => !own.has(song)).map((song) => song.id);
|
|
750
|
+
const made = playlist.entries.length - existing.length;
|
|
751
|
+
// Made tracks retain their place among the catalog rows as far as the new source order allows.
|
|
752
|
+
const order = [];
|
|
753
|
+
if (partial) order.push(...playlist.entries, ...fresh);
|
|
754
|
+
else {
|
|
755
|
+
let index = 0;
|
|
756
|
+
for (const local of playlist.entries) {
|
|
757
|
+
if (local.kind === "made" || own.has(local)) order.push(local);
|
|
758
|
+
else if (index < songs.length) order.push(songs[index++]);
|
|
759
|
+
}
|
|
760
|
+
order.push(...songs.slice(index));
|
|
761
|
+
}
|
|
762
|
+
if (order.length > MAX_ENTRIES) throw libraryError("library_full", `A playlist holds up to ${MAX_ENTRIES} entries.`);
|
|
763
|
+
const removed = new Set(remove);
|
|
764
|
+
const survivors = playlist.entries.filter((row) => !removed.has(row.id)).map((row) => row.id);
|
|
765
|
+
const reordered = order.filter((row) => row.id).some((row, index) => row.id !== survivors[index]);
|
|
766
|
+
const cover = typeof source.cover === "string" && source.cover.length <= 2000 && source.cover.trim() && source.cover !== playlist.source.cover ? source.cover : null;
|
|
767
|
+
const changed = Boolean(fresh.length || remove.length || reordered || updates.length || cover);
|
|
768
|
+
const summary = Object.freeze({ added: fresh.length, removed: remove.length, kept: incoming.length - fresh.length, made, own: own.size, reordered, partial, unreadable, changed });
|
|
769
|
+
const plan = Object.freeze({ summary });
|
|
770
|
+
this.#refreshPlans.set(plan, { id: playlist.id, basis: refreshBasis(playlist), order, fresh, remove, updates, cover });
|
|
771
|
+
return plan;
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
/** Apply exactly the approved change while holding the SQLite write lock. */
|
|
775
|
+
applyPlaylistRefresh(plan) {
|
|
776
|
+
const edit = this.#refreshPlans.get(plan);
|
|
777
|
+
const stale = () => libraryError("playlist_refresh_stale", "The playlist changed. Preview its refresh again.");
|
|
778
|
+
if (!edit) throw stale();
|
|
779
|
+
const result = this.#transaction(() => {
|
|
780
|
+
const playlist = this.playlist(edit.id);
|
|
781
|
+
if (!playlist || refreshBasis(playlist) !== edit.basis) throw stale();
|
|
782
|
+
if (!plan.summary.changed) return plan.summary;
|
|
783
|
+
const remove = this.#database.prepare("DELETE FROM library_entries WHERE playlist_id = ? AND entry_id = ?");
|
|
784
|
+
for (const id of edit.remove) remove.run(edit.id, id);
|
|
785
|
+
const update = this.#database.prepare("UPDATE library_entries SET title = ?, artist_credit = ?, album = ?, isrc = ?, refs_json = ? WHERE entry_id = ?");
|
|
786
|
+
for (const row of edit.updates) update.run(row.title, row.artist_credit, row.album ?? null, row.isrc ?? null, JSON.stringify(row.refs), row.id);
|
|
787
|
+
const added = edit.fresh.length ? this.#add(edit.id, edit.fresh, { addedBy: "source" }).entry_ids : [];
|
|
788
|
+
let next = 0;
|
|
789
|
+
if (!plan.summary.partial) this.#renumberEntries(edit.order.map((row) => row.id ?? added[next++]));
|
|
790
|
+
if (edit.cover) this.#database.prepare("UPDATE library_playlists SET source_json = ? WHERE playlist_id = ?")
|
|
791
|
+
.run(JSON.stringify({ ...playlist.source, cover: edit.cover }), edit.id);
|
|
792
|
+
this.#touch(edit.id);
|
|
793
|
+
return plan.summary;
|
|
794
|
+
}, plan.summary.changed);
|
|
795
|
+
this.#refreshPlans.delete(plan);
|
|
796
|
+
return result;
|
|
797
|
+
}
|
|
798
|
+
|
|
464
799
|
/** An imported playlist's own cover, found after it came in. */
|
|
465
800
|
setPlaylistCover(playlistId, cover) {
|
|
466
801
|
return this.#transaction(() => {
|
|
@@ -526,7 +861,10 @@ export class LibraryStore {
|
|
|
526
861
|
/** Which of these entries Saved already holds, by identity, so a surface can show a filled mark. */
|
|
527
862
|
savedKeys() {
|
|
528
863
|
this.#open();
|
|
529
|
-
return new Set(this
|
|
864
|
+
return new Set(this.playlist(SAVED_PLAYLIST_ID).entries.flatMap(entry => {
|
|
865
|
+
const ids = recordingIds(entry);
|
|
866
|
+
return ids.length ? ids : [entryIdentity(entry), namedLibraryRecording(entry)];
|
|
867
|
+
}));
|
|
530
868
|
}
|
|
531
869
|
|
|
532
870
|
/** Calls listener after each write through this connection; returns the unsubscribe. */
|
|
@@ -51,6 +51,37 @@ function creditKeys(credit, artists = [], featured = []) {
|
|
|
51
51
|
return keys;
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
+
// These history formats supply one artist string, even though their stored track has an
|
|
55
|
+
// artist_credits array. A written feature identifies a guest; punctuation alone can be a band name.
|
|
56
|
+
const textHistoryCredits = new Set(["listenbrainz", "spotify-account-data", "spotify-extended-history", "lastfm", "youtube_music"]);
|
|
57
|
+
const writtenFeature = /(?:\s+[(\[(]?\s*|[(\[(]\s*)(?:featuring|feat\.?|ft\.?)\s+/iu;
|
|
58
|
+
|
|
59
|
+
export function historyAvoidArtists(track, source) {
|
|
60
|
+
const artists = (Array.isArray(track?.artist_credits) ? track.artist_credits : [])
|
|
61
|
+
.map(credit => typeof credit?.name === "string" ? credit.name.trim() : "").filter(Boolean);
|
|
62
|
+
if (artists.length !== 1 || !textHistoryCredits.has(source)) return artists;
|
|
63
|
+
const [credit] = artists;
|
|
64
|
+
const feature = writtenFeature.exec(credit);
|
|
65
|
+
if (!feature) return artists;
|
|
66
|
+
const lead = credit.slice(0, feature.index).trim();
|
|
67
|
+
const guests = credit.slice(feature.index + feature[0].length).replace(/[)\])]\s*$/u, "");
|
|
68
|
+
return [credit, lead, ...creditKeys(guests)].filter(Boolean);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// A retained history plan can name only the primary artist. Its own local track reference still
|
|
72
|
+
// identifies the source credits, including on plans made before a collaborator was avoided.
|
|
73
|
+
export function allowedDiscoveryTracks(gate, tracks, store, subjectId) {
|
|
74
|
+
if (!gate.size) return tracks.slice();
|
|
75
|
+
return tracks.filter(track => {
|
|
76
|
+
if (track.candidate_scope === "private_history") {
|
|
77
|
+
const stored = store?.historyTrackArtists?.({ subjectId, trackRefId: track.track_ref_id });
|
|
78
|
+
const artists = stored?.length ? stored : track.artists ?? [track.artist_credit];
|
|
79
|
+
return !gate.avoidsTrack({ ...track, artists });
|
|
80
|
+
}
|
|
81
|
+
return !gate.avoidsTrack(track);
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
54
85
|
const overlaps = (left, right) => [...left].some((key) => right.has(key));
|
|
55
86
|
|
|
56
87
|
/**
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// The count is the size of the accepted sequence. Starting a sequence starts its first song.
|
|
2
|
+
// These are past actions in one conversation; they do not describe the current service queue.
|
|
3
|
+
export function listeningAction(kind, receipt) {
|
|
4
|
+
if (!receipt) return null;
|
|
5
|
+
const sequence = (service, action, songs) => Array.isArray(songs) && songs.length
|
|
6
|
+
? { service, action, count: songs.length } : null;
|
|
7
|
+
|
|
8
|
+
if (kind === "music") {
|
|
9
|
+
if (receipt.provider === "netease") {
|
|
10
|
+
if (receipt.result === "queued") return sequence("netease", "queued", receipt.songs);
|
|
11
|
+
if (receipt.result === "playing") return sequence("netease", "started", receipt.songs);
|
|
12
|
+
return null;
|
|
13
|
+
}
|
|
14
|
+
if (receipt.state === "resolved" && (receipt.playing_in_order?.length || receipt.completed?.length)) {
|
|
15
|
+
return sequence("apple_music", "started", [...(receipt.completed ?? []), ...(receipt.playing_in_order ?? []), ...(receipt.queued_in_order ?? [])]);
|
|
16
|
+
}
|
|
17
|
+
return sequence("apple_music", "queued", receipt.queued_in_order);
|
|
18
|
+
}
|
|
19
|
+
if (kind === "generated" || kind === "replay") {
|
|
20
|
+
const started = receipt.state === "playing" || (kind === "generated" && receipt.state === "streaming");
|
|
21
|
+
return started && receipt.track ? { service: "moondog", action: "started", count: 1 } : null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// spotify_playback repeats a selection reference already covered by spotify_write.
|
|
25
|
+
if (receipt.provider !== "spotify" || receipt.effect !== "write_external" || receipt.ok !== true || receipt.already) return null;
|
|
26
|
+
if (kind === "spotify_plan" && ["accepted", "partial"].includes(receipt.state)) {
|
|
27
|
+
// A partial batch lists every accepted write in queued, including the first song if it started playback.
|
|
28
|
+
return sequence("spotify", receipt.started_playback ? "started" : "queued", receipt.queued);
|
|
29
|
+
}
|
|
30
|
+
if (kind === "spotify_write" && receipt.state === "accepted") {
|
|
31
|
+
if (receipt.action === "playback.queue.add") {
|
|
32
|
+
return { service: "spotify", action: receipt.started_playback ? "started" : "queued", count: 1 };
|
|
33
|
+
}
|
|
34
|
+
if (receipt.action === "playback.resume") {
|
|
35
|
+
// One named target can also be a whole album. A plain resume has no sequence length at all.
|
|
36
|
+
const count = receipt.track_count;
|
|
37
|
+
if (Number.isSafeInteger(count) && count > 0) return { service: "spotify", action: "started", count };
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// A listening direction belongs to this conversation. Only the listener can supply its words.
|
|
2
|
+
export function emptyListeningMoment() {
|
|
3
|
+
return { situation: null, likes: [], avoids: [], queue_action: null };
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
// Newest entry first. Only a completed turn commits directions; an earlier playback
|
|
7
|
+
// receipt remains true when the listener interrupts the words that followed it.
|
|
8
|
+
export function restoreListeningMoment(entries, readSnapshot) {
|
|
9
|
+
let action = null;
|
|
10
|
+
let directions = null;
|
|
11
|
+
for (const entry of entries) {
|
|
12
|
+
const snapshot = readSnapshot(entry);
|
|
13
|
+
action ??= snapshot?.queue_action;
|
|
14
|
+
if (entry.outcome === "completed") {
|
|
15
|
+
directions = snapshot;
|
|
16
|
+
break;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
return directions || action ? { ...(directions ?? emptyListeningMoment()), queue_action: action ?? null } : null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function momentQuotes(moment) {
|
|
23
|
+
return moment ? [moment.situation, ...moment.likes, ...moment.avoids].filter(Boolean) : [];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function invalidDirection(message) {
|
|
27
|
+
return Object.assign(new Error(message), { code: "listening_moment_invalid" });
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function updateListeningMoment(current, request, patch) {
|
|
31
|
+
const keys = ["situation", "likes", "avoids"];
|
|
32
|
+
if (!patch || Object.keys(patch).some(key => key !== "source_text" && !keys.includes(key)) ||
|
|
33
|
+
!keys.some(key => Object.hasOwn(patch, key))) throw invalidDirection("Choose a listening direction to update.");
|
|
34
|
+
const exactQuote = (value) => typeof value === "string" && value.trim().length > 0 &&
|
|
35
|
+
value.length <= 240 && request.includes(value);
|
|
36
|
+
if (!exactQuote(patch.source_text)) throw invalidDirection("Quote the listener's current message to change its listening direction.");
|
|
37
|
+
const next = structuredClone(current);
|
|
38
|
+
const marked = new Set();
|
|
39
|
+
for (const key of keys) {
|
|
40
|
+
if (!Object.hasOwn(patch, key)) continue;
|
|
41
|
+
const value = patch[key];
|
|
42
|
+
const previous = current[key];
|
|
43
|
+
if (key === "situation" && value === null) { next.situation = null; continue; }
|
|
44
|
+
const words = key === "situation" ? [value] : value;
|
|
45
|
+
if (!Array.isArray(words) || words.length > 5) throw invalidDirection("Use up to five listener quotes per list.");
|
|
46
|
+
for (const word of words) {
|
|
47
|
+
if (exactQuote(word)) marked.add(word);
|
|
48
|
+
else if (!(key === "situation" ? word === previous : previous.includes(word))) {
|
|
49
|
+
throw invalidDirection("Each new listening direction must quote the listener's current message exactly.");
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
next[key] = key === "situation" ? value : [...new Set(words)];
|
|
53
|
+
}
|
|
54
|
+
if (!marked.size) marked.add(patch.source_text);
|
|
55
|
+
return { next, marked: [...marked] };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// The shared local player keeps an event-driven selection. Sampling it makes no service requests.
|
|
59
|
+
export function localPlayerSelection(player) {
|
|
60
|
+
let now;
|
|
61
|
+
try { now = player?.nowPlaying?.(); }
|
|
62
|
+
catch { return null; }
|
|
63
|
+
if (typeof now?.song?.title !== "string" || !now.song.title) return null;
|
|
64
|
+
const song = (track) => ({ title: track.title.slice(0, 240),
|
|
65
|
+
...(typeof track.artist_credit === "string" && track.artist_credit ? { artist: track.artist_credit.slice(0, 240) } : {}) });
|
|
66
|
+
return { selected: song(now.song), next: (now.next ?? []).filter(track => typeof track?.title === "string").slice(0, 10).map(song) };
|
|
67
|
+
}
|