@doitian/dsh-music 0.0.0-stage → 0.1.1

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/lib/session.js ADDED
@@ -0,0 +1,346 @@
1
+ /**
2
+ * Session persistence and the QR-login state machine.
3
+ *
4
+ * The NetEase session is a single `MUSIC_U` cookie, so persistence is a small
5
+ * JSON document under the plugin's data directory. It also carries the local
6
+ * taste signals the AI DJ reads: play history plus like/dislike/skip feedback.
7
+ *
8
+ * @module dsh-music/session
9
+ */
10
+
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+
14
+ /** Cookie sent for anonymous browsing; `os=pc` selects the desktop payloads. */
15
+ export const ANONYMOUS_COOKIE = 'os=pc; appver=2.10.6; channel=netease';
16
+
17
+ /** Play-history entries retained for DJ context. */
18
+ const MAX_HISTORY = 300;
19
+
20
+ /** Feedback lists are bounded so the file cannot grow without limit. */
21
+ const MAX_FEEDBACK = 500;
22
+
23
+ /** QR codes are refreshed before the API reports them expired. */
24
+ const QR_TTL_MS = 110_000;
25
+
26
+ /** Empty persisted document. */
27
+ function emptyState() {
28
+ return {
29
+ version: 1,
30
+ cookie: '',
31
+ account: null,
32
+ savedAt: null,
33
+ settings: {
34
+ /**
35
+ * Streaming quality chosen in the player. Empty means "no choice made
36
+ * here", so the profile patch's `audioLevel` supplies the initial value;
37
+ * a persisted `'exhigh'` would silently mask it.
38
+ */
39
+ level: '',
40
+ /** Whether the continuous DJ keeps the queue topped up. */
41
+ djEnabled: false,
42
+ /** Free-text taste/mood brief the DJ includes in its prompt. */
43
+ djPrompt: '',
44
+ /**
45
+ * Curator route chosen from the player. Empty means "use the profile
46
+ * patch's `config.dj`", so clearing the picker reverts to it.
47
+ */
48
+ djProvider: '',
49
+ djModel: '',
50
+ djAutoExtendBelow: 3,
51
+ djBatchSize: 5,
52
+ },
53
+ history: [],
54
+ feedback: { likes: [], dislikes: [], skips: [] },
55
+ };
56
+ }
57
+
58
+ /**
59
+ * JSON-document store for the plugin's data directory.
60
+ *
61
+ * Writes are atomic (temp file + rename) so a crash mid-write cannot leave a
62
+ * truncated session behind, and every mutation schedules a debounced save so
63
+ * high-frequency updates such as playback position do not thrash the disk.
64
+ */
65
+ export class SessionStore {
66
+ /**
67
+ * @param {object} options
68
+ * @param {string} options.file absolute path to the JSON document.
69
+ * @param {{warn: Function, info: Function, debug: Function}} [options.logger]
70
+ * @param {number} [options.saveDelayMs] debounce window for `touch()`.
71
+ */
72
+ constructor({ file, logger, saveDelayMs = 1_500 }) {
73
+ this.file = file;
74
+ this.logger = logger;
75
+ this.saveDelayMs = saveDelayMs;
76
+ this.state = emptyState();
77
+ this.timer = undefined;
78
+ this.closed = false;
79
+ }
80
+
81
+ /** Read the document, tolerating absence and corruption. */
82
+ load() {
83
+ try {
84
+ const text = fs.readFileSync(this.file, 'utf8');
85
+ const parsed = JSON.parse(text);
86
+ this.state = { ...emptyState(), ...parsed, settings: { ...emptyState().settings, ...parsed.settings } };
87
+ this.logger?.debug?.(`[music] session loaded (${this.state.cookie ? 'authenticated' : 'anonymous'})`);
88
+ } catch (error) {
89
+ if (error.code !== 'ENOENT') {
90
+ this.logger?.warn?.(`[music] could not read session file, starting fresh: ${error.message}`);
91
+ }
92
+ }
93
+ return this.state;
94
+ }
95
+
96
+ /** Write immediately. */
97
+ save() {
98
+ if (this.timer !== undefined) {
99
+ clearTimeout(this.timer);
100
+ this.timer = undefined;
101
+ }
102
+ this.state.savedAt = new Date().toISOString();
103
+ try {
104
+ fs.mkdirSync(path.dirname(this.file), { recursive: true });
105
+ const temp = `${this.file}.tmp`;
106
+ fs.writeFileSync(temp, `${JSON.stringify(this.state, null, 2)}\n`, 'utf8');
107
+ fs.renameSync(temp, this.file);
108
+ } catch (error) {
109
+ this.logger?.warn?.(`[music] could not save session: ${error.message}`);
110
+ }
111
+ }
112
+
113
+ /** Persist after a quiet period; used by frequently changing fields. */
114
+ touch() {
115
+ if (this.closed) return;
116
+ if (this.timer !== undefined) return;
117
+ this.timer = setTimeout(() => {
118
+ this.timer = undefined;
119
+ this.save();
120
+ }, this.saveDelayMs);
121
+ this.timer.unref?.();
122
+ }
123
+
124
+ /** Stop the debounce timer, flushing pending work. */
125
+ close() {
126
+ this.closed = true;
127
+ this.save();
128
+ }
129
+
130
+ // ---------------------------------------------------------------- session
131
+
132
+ get cookie() {
133
+ return this.state.cookie || '';
134
+ }
135
+
136
+ setSession(cookie, account) {
137
+ this.state.cookie = cookie || '';
138
+ this.state.account = account ?? null;
139
+ this.save();
140
+ }
141
+
142
+ clearSession() {
143
+ this.state.cookie = '';
144
+ this.state.account = null;
145
+ this.save();
146
+ }
147
+
148
+ get settings() {
149
+ return this.state.settings;
150
+ }
151
+
152
+ updateSettings(patch) {
153
+ Object.assign(this.state.settings, patch);
154
+ this.save();
155
+ return this.state.settings;
156
+ }
157
+
158
+ // --------------------------------------------------------------- history
159
+
160
+ /**
161
+ * Record a play and return the durable taste picture the DJ reasons over.
162
+ * @param {{id: number, name: string, artists: string[]}} track
163
+ */
164
+ recordPlay(track) {
165
+ this.state.history.unshift({
166
+ id: track.id,
167
+ name: track.name,
168
+ artists: track.artists ?? [],
169
+ at: Date.now(),
170
+ });
171
+ if (this.state.history.length > MAX_HISTORY) this.state.history.length = MAX_HISTORY;
172
+ this.touch();
173
+ }
174
+
175
+ /** Recent track ids, newest first — used to avoid repeats. */
176
+ recentIds(limit = 50) {
177
+ return this.state.history.slice(0, limit).map((entry) => entry.id);
178
+ }
179
+
180
+ /** Most-played artists, most frequent first. */
181
+ topArtists(limit = 8) {
182
+ const counts = new Map();
183
+ for (const entry of this.state.history.slice(0, 150)) {
184
+ for (const artist of entry.artists) counts.set(artist, (counts.get(artist) ?? 0) + 1);
185
+ }
186
+ return [...counts.entries()]
187
+ .sort((a, b) => b[1] - a[1])
188
+ .slice(0, limit)
189
+ .map(([artist]) => artist);
190
+ }
191
+
192
+ /** Record like/dislike/skip feedback for one track. */
193
+ recordFeedback(kind, trackId) {
194
+ const list = this.state.feedback[kind];
195
+ if (!list || !Number.isFinite(Number(trackId))) return this.state.feedback;
196
+ const id = Number(trackId);
197
+ const index = list.indexOf(id);
198
+ if (kind === 'skips') {
199
+ // Skips are counters, not membership: keep the newest occurrence.
200
+ list.unshift(id);
201
+ if (list.length > MAX_FEEDBACK) list.length = MAX_FEEDBACK;
202
+ } else if (index >= 0) {
203
+ list.splice(index, 1);
204
+ } else {
205
+ list.unshift(id);
206
+ if (list.length > MAX_FEEDBACK) list.length = MAX_FEEDBACK;
207
+ // Liking and disliking a track are mutually exclusive.
208
+ const opposite = kind === 'likes' ? this.state.feedback.dislikes : this.state.feedback.likes;
209
+ const oppositeIndex = opposite.indexOf(id);
210
+ if (oppositeIndex >= 0) opposite.splice(oppositeIndex, 1);
211
+ }
212
+ this.touch();
213
+ return this.state.feedback;
214
+ }
215
+
216
+ get feedback() {
217
+ return this.state.feedback;
218
+ }
219
+
220
+ /**
221
+ * A compact digest for the DJ prompt: what has been played, what is liked,
222
+ * what is disliked — never the raw cookie or account details.
223
+ */
224
+ tasteDigest({ history = 15 } = {}) {
225
+ const name = (entry) =>
226
+ typeof entry === 'object' ? `${entry.name} — ${(entry.artists ?? []).join('/')}` : `#${entry}`;
227
+ const byId = new Map(this.state.history.map((entry) => [entry.id, entry]));
228
+ return {
229
+ recentlyPlayed: this.state.history.slice(0, history).map(name),
230
+ topArtists: this.topArtists(8),
231
+ liked: this.state.feedback.likes.slice(0, 15).map((id) => byId.get(id)).filter(Boolean).map(name),
232
+ disliked: this.state.feedback.dislikes.slice(0, 15).map((id) => byId.get(id)).filter(Boolean).map(name),
233
+ dislikedIds: this.state.feedback.dislikes.slice(0, 80),
234
+ recentIds: this.recentIds(60),
235
+ };
236
+ }
237
+ }
238
+
239
+ /**
240
+ * One QR-login attempt at a time, refreshed automatically as codes expire.
241
+ *
242
+ * The panel shows `loginUrl` as a QR image; the mobile app scans it and the
243
+ * poll below turns `803` into the session cookie on the caller's client.
244
+ */
245
+ export class QrLogin {
246
+ /**
247
+ * @param {object} options
248
+ * @param {import('./netease.js').Netease} options.api
249
+ * @param {SessionStore} options.store
250
+ * @param {{warn: Function, info: Function, debug: Function}} [options.logger]
251
+ */
252
+ constructor({ api, store, logger }) {
253
+ this.api = api;
254
+ this.store = store;
255
+ this.logger = logger;
256
+ this.current = null;
257
+ this.lastError = null;
258
+ }
259
+
260
+ /** Start a fresh QR code, replacing any previous one. */
261
+ async start() {
262
+ const { unikey, loginUrl } = await this.api.qrStart();
263
+ this.current = {
264
+ unikey,
265
+ loginUrl,
266
+ state: 'waiting',
267
+ message: '等待扫码 (waiting for scan)',
268
+ startedAt: Date.now(),
269
+ expiresAt: Date.now() + QR_TTL_MS,
270
+ };
271
+ this.lastError = null;
272
+ this.logger?.debug?.(`[music] QR login started ${unikey}`);
273
+ return this.current;
274
+ }
275
+
276
+ /** Existing QR code, or a new one when none is live. */
277
+ async ensure() {
278
+ if (!this.current) return this.start();
279
+ if (Date.now() >= this.current.expiresAt && this.current.state !== 'scanned') {
280
+ return this.start();
281
+ }
282
+ return this.current;
283
+ }
284
+
285
+ /** Forget the current attempt (used on logout). */
286
+ reset() {
287
+ this.current = null;
288
+ }
289
+
290
+ /**
291
+ * Advance the attempt by one poll. On success the cookie is written to the
292
+ * session store so it survives a restart.
293
+ * @returns {Promise<{state: string, message: string, account?: object|null, loginUrl?: string}>}
294
+ */
295
+ async poll() {
296
+ if (!this.current) await this.start();
297
+ const attempt = this.current;
298
+ if (attempt.state === 'success') {
299
+ return { state: 'success', message: '已登录 (signed in)', account: this.api.account };
300
+ }
301
+ if (Date.now() >= attempt.expiresAt) {
302
+ await this.start();
303
+ return { state: 'expired', message: '二维码已刷新 (QR refreshed)', loginUrl: this.current.loginUrl };
304
+ }
305
+
306
+ let result;
307
+ try {
308
+ result = await this.api.qrPoll(attempt.unikey);
309
+ } catch (error) {
310
+ this.lastError = error.message;
311
+ this.logger?.warn?.(`[music] QR poll failed: ${error.message}`);
312
+ return { state: attempt.state, message: `轮询失败 (poll failed): ${error.message}`, loginUrl: attempt.loginUrl };
313
+ }
314
+
315
+ if (result.code === 800) {
316
+ await this.start();
317
+ return { state: 'expired', message: '二维码已过期,已刷新 (expired, refreshed)', loginUrl: this.current.loginUrl };
318
+ }
319
+ if (result.code === 802) {
320
+ attempt.state = 'scanned';
321
+ attempt.message = '已扫码,请在手机上确认 (scanned, confirm on phone)';
322
+ } else if (result.done) {
323
+ attempt.state = 'success';
324
+ attempt.message = '登录成功 (signed in)';
325
+ const account = this.api.account ?? (await this.api.fetchAccount().catch(() => null));
326
+ this.store.setSession(this.api.jar.header(), account);
327
+ this.logger?.info?.(`[music] QR login succeeded${account ? ` as ${account.nickname}` : ''}`);
328
+ return { state: 'success', message: attempt.message, account };
329
+ }
330
+
331
+ return { state: attempt.state, message: attempt.message, loginUrl: attempt.loginUrl };
332
+ }
333
+
334
+ /** Serializable view for the panel and the agent-facing login tool. */
335
+ snapshot() {
336
+ if (!this.current) return { state: 'idle', message: '未开始 (not started)' };
337
+ return {
338
+ state: this.current.state,
339
+ message: this.current.message,
340
+ loginUrl: this.current.loginUrl,
341
+ unikey: this.current.unikey,
342
+ expiresAt: this.current.expiresAt,
343
+ error: this.lastError,
344
+ };
345
+ }
346
+ }