@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/netease.js ADDED
@@ -0,0 +1,609 @@
1
+ /**
2
+ * Minimal, dependency-free client for the NetEase Cloud Music (music.163.com)
3
+ * web API.
4
+ *
5
+ * Only the plain (non-`weapi`/`eapi`) endpoints are used: they need no request
6
+ * encryption and work with a normal browser session cookie. Authentication
7
+ * upgrades the client from anonymous browsing to personal recommendations and
8
+ * VIP song URLs; everything else works without it.
9
+ *
10
+ * Verified against the live API:
11
+ * - `api/search/get/web` anonymous OK
12
+ * - `api/song/enhance/player/url` anonymous OK for fee=8, `url: null` for fee=1 (VIP)
13
+ * - `api/v6/playlist/detail` anonymous OK
14
+ * - `api/toplist` anonymous OK
15
+ * - `api/discovery/simiSong` anonymous OK
16
+ * - `api/personalized/newsong` anonymous OK
17
+ * - `api/login/qrcode/*` QR login handshake
18
+ *
19
+ * @module dsh-music/netease
20
+ */
21
+
22
+ /** Hosts used by the public web client. */
23
+ const API_ORIGIN = 'https://music.163.com';
24
+
25
+ /** A desktop-browser UA; NetEase serves different shapes to unknown agents. */
26
+ const UA =
27
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36';
28
+
29
+ /**
30
+ * NetEase `fee` codes seen in track payloads.
31
+ * 0 = free, 1 = VIP only, 4 = paid album, 8 = free but high-quality needs VIP.
32
+ * Anonymous callers still receive a stream for most `fee=8` tracks.
33
+ */
34
+ const FEE = { FREE: 0, VIP: 1, ALBUM: 4, LIMITED: 8 };
35
+
36
+ /**
37
+ * Requestable audio levels, richest first.
38
+ *
39
+ * Order matters: it is the downgrade ladder. NetEase refuses a level per track
40
+ * (`code -110` for the object-audio tiers, `url: null` when a track has no
41
+ * lossless master), and several of the richer ids resolve to the same Hi-Res
42
+ * stream, so a refusal walks down this list until something plays.
43
+ *
44
+ * Measured on a VIP account: `hires` served FLAC at ~1677–1785 kbps,
45
+ * `lossless` ~908–1016 kbps, and the rest 320/192/128 kbps MP3.
46
+ */
47
+ export const LEVELS = [
48
+ { id: 'jymaster', label: '超清母带 / Master', kind: 'flac' },
49
+ { id: 'dolby', label: '杜比全景声 / Dolby Atmos', kind: 'flac' },
50
+ { id: 'sky', label: '沉浸环绕声 / Immersive', kind: 'flac' },
51
+ { id: 'jyeffect', label: '沉浸声 / Spatial', kind: 'flac' },
52
+ { id: 'hires', label: 'Hi-Res 无损 / Hi-Res lossless', kind: 'flac' },
53
+ { id: 'lossless', label: '无损 / Lossless', kind: 'flac' },
54
+ { id: 'exhigh', label: '极高 / 320 kbps', kind: 'mp3' },
55
+ { id: 'higher', label: '较高 / 192 kbps', kind: 'mp3' },
56
+ { id: 'standard', label: '标准 / 128 kbps', kind: 'mp3' },
57
+ ];
58
+
59
+ /** The default level, matching NetEase's own web player. */
60
+ export const DEFAULT_LEVEL = 'exhigh';
61
+
62
+ /** Whether a string names a level this client knows. */
63
+ export function isLevel(value) {
64
+ return LEVELS.some((entry) => entry.id === value);
65
+ }
66
+
67
+ /** Raised for a request the API answered with a non-success business code. */
68
+ export class NeteaseError extends Error {
69
+ constructor(message, { code, endpoint, payload } = {}) {
70
+ super(message);
71
+ this.name = 'NeteaseError';
72
+ this.code = code;
73
+ this.endpoint = endpoint;
74
+ this.payload = payload;
75
+ }
76
+ }
77
+
78
+ /**
79
+ * A small cookie store good enough for one NetEase web session.
80
+ *
81
+ * NetEase sets `MUSIC_U` on the QR-login success response; that cookie alone
82
+ * carries the account, so persistence is just serialising this map.
83
+ */
84
+ export class CookieJar {
85
+ /** @type {Map<string, string>} */
86
+ #map = new Map();
87
+
88
+ constructor(initial) {
89
+ if (initial) this.load(initial);
90
+ }
91
+
92
+ /** Merge a `Cookie:` header string. Existing names are overwritten. */
93
+ load(header) {
94
+ for (const part of String(header ?? '').split(';')) {
95
+ const match = /^\s*([^=;]+)=([^;]*)\s*$/.exec(part);
96
+ if (match) this.#map.set(match[1], match[2]);
97
+ }
98
+ return this;
99
+ }
100
+
101
+ /** Merge every `Set-Cookie` header a response carried. */
102
+ absorb(response) {
103
+ const list =
104
+ typeof response.headers.getSetCookie === 'function'
105
+ ? response.headers.getSetCookie()
106
+ : [response.headers.get('set-cookie')].filter(Boolean);
107
+ for (const cookie of list) {
108
+ // A single header may pack several cookies, each starting `name=`.
109
+ for (const part of String(cookie).split(/,(?=[^;=]+=[^;]*)/)) {
110
+ const match = /^\s*([^=;]+)=([^;]*)/.exec(part);
111
+ if (match) this.#map.set(match[1].trim(), match[2]);
112
+ }
113
+ }
114
+ return this;
115
+ }
116
+
117
+ has(name) {
118
+ return this.#map.has(name);
119
+ }
120
+
121
+ get(name) {
122
+ return this.#map.get(name);
123
+ }
124
+
125
+ set(name, value) {
126
+ this.#map.set(name, value);
127
+ return this;
128
+ }
129
+
130
+ delete(name) {
131
+ return this.#map.delete(name);
132
+ }
133
+
134
+ /** The `Cookie:` header value. */
135
+ header() {
136
+ return [...this.#map.entries()].map(([k, v]) => `${k}=${v}`).join('; ');
137
+ }
138
+
139
+ /** Plain object, for persistence. */
140
+ toJSON() {
141
+ return Object.fromEntries(this.#map);
142
+ }
143
+
144
+ clear() {
145
+ this.#map.clear();
146
+ return this;
147
+ }
148
+ }
149
+
150
+ /** `?param=` sizing suffix for a NetEase image URL. */
151
+ export function resizeImage(url, size = 224) {
152
+ if (!url) return null;
153
+ if (!/music\.126\.net/.test(url)) return url;
154
+ // Idempotent: a URL that already carries `?param=` is re-sized, not doubled.
155
+ const base = String(url).split('?')[0];
156
+ return `${base}?param=${size}y${size}`;
157
+ }
158
+
159
+ /**
160
+ * Normalise the several track shapes NetEase returns into one.
161
+ *
162
+ * Search results use `artists`/`album`/`duration`; playlist and detail payloads
163
+ * use `ar`/`al`/`dt`; `personalized/newsong` nests the track under `song`.
164
+ *
165
+ * This is **idempotent**: tracks flow through several layers (the API client,
166
+ * the agent tools, the DJ, the panel's `/play` round-trip), so an
167
+ * already-normalised track — where `artists` holds plain strings and `album` is
168
+ * a string — must survive a second pass unchanged. Reading `artist.name` there
169
+ * would silently drop every artist.
170
+ */
171
+ export function normalizeTrack(raw) {
172
+ const track = raw?.song && raw.song.id ? raw.song : raw;
173
+ if (!track?.id) return null;
174
+ const artists = (track.ar ?? track.artists ?? [])
175
+ .map((artist) => (typeof artist === 'string' ? artist : artist?.name))
176
+ .filter(Boolean);
177
+ const albumRaw = track.al ?? track.album ?? {};
178
+ const album = typeof albumRaw === 'string' ? albumRaw : (albumRaw?.name ?? '');
179
+ const duration = track.dt ?? track.duration ?? 0;
180
+ const fee = track.fee ?? 0;
181
+ return {
182
+ id: track.id,
183
+ name: track.name ?? '',
184
+ artists,
185
+ album,
186
+ picUrl: resizeImage(track.picUrl ?? albumRaw?.picUrl ?? null),
187
+ duration,
188
+ fee,
189
+ /** VIP-gated tracks still play when the session is entitled. */
190
+ vip: fee === FEE.VIP || fee === FEE.ALBUM,
191
+ mvid: track.mvid ?? track.mv ?? 0,
192
+ };
193
+ }
194
+
195
+ /** Normalise a list, dropping entries the API returned without an id. */
196
+ function normalizeTracks(list) {
197
+ return (list ?? []).map(normalizeTrack).filter(Boolean);
198
+ }
199
+
200
+ /** `[1,2]` — NetEase wants bracketed ids in query strings. */
201
+ function idList(ids) {
202
+ return encodeURIComponent(JSON.stringify([...ids].map(Number)));
203
+ }
204
+
205
+ /**
206
+ * Anonymous-or-authenticated NetEase web API client.
207
+ */
208
+ export class Netease {
209
+ /**
210
+ * @param {object} [options]
211
+ * @param {string} [options.cookie] initial `Cookie:` header value.
212
+ * @param {number} [options.timeoutMs] per-request deadline.
213
+ * @param {{warn: Function, info: Function, debug: Function}} [options.logger]
214
+ */
215
+ constructor({ cookie, timeoutMs = 15_000, logger } = {}) {
216
+ this.jar = new CookieJar(cookie);
217
+ this.timeoutMs = timeoutMs;
218
+ this.logger = logger;
219
+ /** Logged-in account summary, refreshed on demand. */
220
+ this.account = null;
221
+ }
222
+
223
+ /** Whether a `MUSIC_U` session cookie is held. */
224
+ get authenticated() {
225
+ return this.jar.has('MUSIC_U');
226
+ }
227
+
228
+ /** Replace the session cookie wholesale (manual paste or QR success). */
229
+ setCookie(header) {
230
+ this.jar.clear().load('os=pc; appver=2.10.6; channel=netease').load(header);
231
+ this.account = null;
232
+ return this;
233
+ }
234
+
235
+ clearCookie() {
236
+ this.jar.clear().load('os=pc; appver=2.10.6; channel=netease');
237
+ this.account = null;
238
+ return this;
239
+ }
240
+
241
+ /**
242
+ * One API call. Absorbs cookies, parses JSON, and never throws for a
243
+ * business-level failure code — callers inspect `code`.
244
+ */
245
+ async call(pathname, { method = 'GET', query, body, headers = {} } = {}) {
246
+ const url = new URL(pathname, API_ORIGIN);
247
+ if (query) {
248
+ for (const [key, value] of Object.entries(query)) {
249
+ if (value !== undefined && value !== null) url.searchParams.set(key, String(value));
250
+ }
251
+ }
252
+ const init = {
253
+ method,
254
+ redirect: 'manual',
255
+ signal: AbortSignal.timeout(this.timeoutMs),
256
+ headers: {
257
+ Referer: `${API_ORIGIN}/`,
258
+ Origin: API_ORIGIN,
259
+ 'User-Agent': UA,
260
+ Cookie: this.jar.header(),
261
+ ...(body ? { 'Content-Type': 'application/x-www-form-urlencoded' } : {}),
262
+ ...headers,
263
+ },
264
+ ...(body ? { body: typeof body === 'string' ? body : new URLSearchParams(body).toString() } : {}),
265
+ };
266
+
267
+ let response;
268
+ try {
269
+ response = await fetch(url, init);
270
+ } catch (cause) {
271
+ throw new NeteaseError(`NetEase request failed: ${pathname}`, {
272
+ code: 'NETWORK',
273
+ endpoint: pathname,
274
+ payload: cause,
275
+ });
276
+ }
277
+ this.jar.absorb(response);
278
+
279
+ const text = await response.text();
280
+ let data;
281
+ try {
282
+ data = JSON.parse(text);
283
+ } catch {
284
+ // NetEase answers HTML for a few error pages; surface a short excerpt.
285
+ throw new NeteaseError(`NetEase returned non-JSON for ${pathname} (HTTP ${response.status})`, {
286
+ code: 'BAD_PAYLOAD',
287
+ endpoint: pathname,
288
+ payload: text.slice(0, 200),
289
+ });
290
+ }
291
+ this.logger?.debug?.(`[music] ${pathname} -> code=${data?.code} http=${response.status}`);
292
+ return data;
293
+ }
294
+
295
+ /**
296
+ * Raw streaming fetch, used by the audio proxy. The caller owns the body.
297
+ * @returns {Promise<Response>}
298
+ */
299
+ async fetchAudio(url, { range, method = 'GET' } = {}) {
300
+ const headers = {
301
+ Referer: `${API_ORIGIN}/`,
302
+ 'User-Agent': UA,
303
+ Cookie: this.jar.header(),
304
+ };
305
+ if (range) headers.Range = range;
306
+ const response = await fetch(url, {
307
+ method,
308
+ headers,
309
+ redirect: 'follow',
310
+ signal: AbortSignal.timeout(30_000),
311
+ });
312
+ this.jar.absorb(response);
313
+ return response;
314
+ }
315
+
316
+ // ---------------------------------------------------------------- browsing
317
+
318
+ /** Full-text song search. `songCount` reports the total match count. */
319
+ async searchSongs(keyword, { limit = 20, offset = 0 } = {}) {
320
+ const data = await this.call('/api/search/get/web', {
321
+ query: { csrf_token: '', s: keyword, type: 1, offset, limit },
322
+ });
323
+ const result = data?.result ?? {};
324
+ return {
325
+ total: result.songCount ?? 0,
326
+ tracks: normalizeTracks(result.songs),
327
+ };
328
+ }
329
+
330
+ /**
331
+ * Fill in cover art for tracks that arrived without any.
332
+ *
333
+ * The search endpoint omits `album.picUrl` entirely, so a search result list
334
+ * renders without artwork unless the detail endpoint is consulted.
335
+ */
336
+ async withCovers(tracks) {
337
+ const missing = tracks.filter((track) => !track.picUrl).map((track) => track.id);
338
+ if (missing.length === 0) return tracks;
339
+ // The detail endpoint accepts a bracketed id list; batch it so a 200-track
340
+ // playlist does not ride on one oversized request.
341
+ const covers = new Map();
342
+ for (let offset = 0; offset < missing.length; offset += 50) {
343
+ const details = await this.songDetail(missing.slice(offset, offset + 50)).catch(() => []);
344
+ for (const track of details) covers.set(track.id, track.picUrl);
345
+ }
346
+ return tracks.map((track) => ({ ...track, picUrl: track.picUrl ?? covers.get(track.id) ?? null }));
347
+ }
348
+
349
+ /** Search across all entity types; used to resolve a playlist/artist query. */
350
+ async search(keyword, { type = 1, limit = 20, offset = 0 } = {}) {
351
+ const data = await this.call('/api/search/get/web', {
352
+ query: { csrf_token: '', s: keyword, type, offset, limit },
353
+ });
354
+ return data?.result ?? {};
355
+ }
356
+
357
+ /** Track metadata, including cover art and the VIP fee code. */
358
+ async songDetail(ids) {
359
+ const list = [...ids].map(Number).filter(Number.isFinite);
360
+ if (list.length === 0) return [];
361
+ const data = await this.call('/api/song/detail', { query: { ids: JSON.stringify(list) } });
362
+ return normalizeTracks(data?.songs);
363
+ }
364
+
365
+ /**
366
+ * Resolve a playable audio URL for one track at the requested level.
367
+ *
368
+ * Walks down {@link LEVELS} from the requested level until the API serves
369
+ * something, because entitlement and availability are per track: a track with
370
+ * no lossless master, or a level the region does not carry, is refused while
371
+ * the same track streams fine one tier lower. `downgraded` reports when that
372
+ * happened so a caller can say so rather than pretending.
373
+ *
374
+ * `ok: false` with `code: 404` means nothing was available at any level
375
+ * (unavailable to this session, or gated behind a purchase).
376
+ *
377
+ * @param {number|string} id track id.
378
+ * @param {{level?: string}} [options] `level` is one of {@link LEVELS}.
379
+ */
380
+ async songUrl(id, { level = DEFAULT_LEVEL } = {}) {
381
+ const requestedLevel = isLevel(level) ? level : DEFAULT_LEVEL;
382
+ const ladder = LEVELS.slice(LEVELS.findIndex((entry) => entry.id === requestedLevel));
383
+
384
+ let lastCode;
385
+ for (const candidate of ladder) {
386
+ const entry = await this.#songUrlAt(id, candidate);
387
+ if (entry?.url) {
388
+ const served = entry.level ?? candidate.id;
389
+ return {
390
+ ok: true,
391
+ id: Number(id),
392
+ url: entry.url,
393
+ br: entry.br ?? 0,
394
+ size: entry.size ?? 0,
395
+ type: entry.type ?? candidate.kind,
396
+ level: served,
397
+ requestedLevel,
398
+ downgraded: served !== requestedLevel,
399
+ gain: entry.gain ?? 0,
400
+ peak: entry.peak ?? 0,
401
+ expiresInMs: (entry.expi ?? 1200) * 1000,
402
+ };
403
+ }
404
+ lastCode = entry?.code ?? lastCode;
405
+ }
406
+
407
+ return {
408
+ ok: false,
409
+ id: Number(id),
410
+ code: lastCode,
411
+ requestedLevel,
412
+ reason: this.authenticated
413
+ ? 'unavailable to this account at any quality (needs a purchase such as a digital album, or is region-locked or removed)'
414
+ : 'unavailable without a signed-in session (VIP-only or region-locked)',
415
+ };
416
+ }
417
+
418
+ /** One level attempt against the v1 player-url endpoint. */
419
+ async #songUrlAt(id, candidate) {
420
+ const data = await this.call('/api/song/enhance/player/url/v1', {
421
+ query: {
422
+ ids: JSON.stringify([Number(id)]),
423
+ level: candidate.id,
424
+ encodeType: candidate.kind,
425
+ },
426
+ });
427
+ return data?.data?.[0];
428
+ }
429
+
430
+ /** Synced lyric text. `noLyric: true` marks an instrumental. */
431
+ async lyric(id) {
432
+ const data = await this.call('/api/song/lyric', {
433
+ query: { id: Number(id), lv: 1, kv: 1, tv: -1 },
434
+ });
435
+ return {
436
+ lrc: data?.lrc?.lyric ?? '',
437
+ translated: data?.tlyric?.lyric ?? '',
438
+ romaji: data?.romalrc?.lyric ?? '',
439
+ noLyric: Boolean(data?.nolyric),
440
+ };
441
+ }
442
+
443
+ /** Playlist header plus its first `limit` tracks. */
444
+ async playlistDetail(id, { limit = 500 } = {}) {
445
+ const data = await this.call('/api/v6/playlist/detail', {
446
+ query: { id: Number(id), n: limit },
447
+ });
448
+ const playlist = data?.playlist;
449
+ if (!playlist) {
450
+ throw new NeteaseError(`playlist ${id} not found`, { code: data?.code, endpoint: 'playlist/detail' });
451
+ }
452
+ return {
453
+ id: playlist.id,
454
+ name: playlist.name,
455
+ description: playlist.description ?? '',
456
+ cover: resizeImage(playlist.coverImgUrl, 500),
457
+ trackCount: playlist.trackCount ?? 0,
458
+ playCount: playlist.playCount ?? 0,
459
+ creator: playlist.creator?.nickname ?? '',
460
+ tracks: normalizeTracks(playlist.tracks),
461
+ };
462
+ }
463
+
464
+ /** The public charts (飙升榜/新歌榜/热歌榜/...). */
465
+ async toplists() {
466
+ const data = await this.call('/api/toplist');
467
+ return (data?.list ?? []).map((item) => ({
468
+ id: item.id,
469
+ name: item.name,
470
+ cover: resizeImage(item.coverImgUrl, 300),
471
+ updateFrequency: item.updateFrequency ?? '',
472
+ trackCount: item.trackCount ?? 0,
473
+ }));
474
+ }
475
+
476
+ /** Similar tracks — the main "more like this" signal for the DJ. */
477
+ async simiSongs(id, { limit = 20 } = {}) {
478
+ const data = await this.call('/api/discovery/simiSong', {
479
+ query: { songid: Number(id), limit },
480
+ });
481
+ return normalizeTracks(data?.songs);
482
+ }
483
+
484
+ /** Anonymous "new songs picked for you" feed. */
485
+ async personalizedNewsongs(limit = 10) {
486
+ const data = await this.call('/api/personalized/newsong', { query: { limit } });
487
+ return normalizeTracks(data?.result);
488
+ }
489
+
490
+ /** Anonymous recommended playlists. */
491
+ async personalizedPlaylists(limit = 10) {
492
+ const data = await this.call('/api/personalized/playlist', { query: { limit } });
493
+ return (data?.result ?? []).map((item) => ({
494
+ id: item.id,
495
+ name: item.name,
496
+ cover: resizeImage(item.picUrl, 300),
497
+ playCount: item.playCount ?? 0,
498
+ trackCount: item.trackCount ?? 0,
499
+ }));
500
+ }
501
+
502
+ /** Daily recommendations. Requires a session; empty list when anonymous. */
503
+ async recommendSongs(limit = 20) {
504
+ const data = await this.call('/api/v1/discovery/recommend/songs', { query: { limit } });
505
+ const result = data?.data;
506
+ return normalizeTracks(result?.dailySongs ?? result?.recommend);
507
+ }
508
+
509
+ /**
510
+ * 心动模式 (heartbeat mode): a personalised continuation of a seed track
511
+ * inside a playlist context. Requires a session.
512
+ */
513
+ async intelligenceList(songId, playlistId, { limit = 20 } = {}) {
514
+ const data = await this.call('/api/playmode/intelligence/list', {
515
+ query: {
516
+ id: Number(songId),
517
+ pid: Number(playlistId),
518
+ sid: Number(songId),
519
+ count: limit,
520
+ },
521
+ });
522
+ if (String(data?.code) !== '200') {
523
+ throw new NeteaseError('intelligence list unavailable', {
524
+ code: data?.code,
525
+ endpoint: 'playmode/intelligence/list',
526
+ });
527
+ }
528
+ return normalizeTracks(data?.data);
529
+ }
530
+
531
+ // -------------------------------------------------------------- account
532
+
533
+ /** Account summary; `null` when the session is anonymous or expired. */
534
+ async fetchAccount() {
535
+ if (!this.authenticated) {
536
+ this.account = null;
537
+ return null;
538
+ }
539
+ const data = await this.call('/api/nuser/account/get');
540
+ const profile = data?.profile;
541
+ this.account = profile
542
+ ? {
543
+ uid: profile.userId,
544
+ nickname: profile.nickname,
545
+ avatar: resizeImage(profile.avatarUrl, 120),
546
+ vip: Boolean(profile.vipType && profile.vipType > 0),
547
+ vipType: profile.vipType ?? 0,
548
+ }
549
+ : null;
550
+ return this.account;
551
+ }
552
+
553
+ /** The user's own playlists (created + collected). */
554
+ async userPlaylists(uid, { limit = 100 } = {}) {
555
+ const data = await this.call('/api/user/playlist', {
556
+ query: { uid: Number(uid), offset: 0, limit },
557
+ });
558
+ return (data?.playlist ?? []).map((item) => ({
559
+ id: item.id,
560
+ name: item.name,
561
+ cover: resizeImage(item.coverImgUrl, 300),
562
+ trackCount: item.trackCount ?? 0,
563
+ subscribed: Boolean(item.subscribed),
564
+ }));
565
+ }
566
+
567
+ // ------------------------------------------------------------ QR login
568
+
569
+ /**
570
+ * Start a QR login: the returned `loginUrl` is what the QR image encodes and
571
+ * the mobile app scans. Poll with {@link qrPoll}.
572
+ */
573
+ async qrStart() {
574
+ const data = await this.call('/api/login/qrcode/unikey', { query: { type: 1 } });
575
+ if (data?.code !== 200 || !data?.unikey) {
576
+ throw new NeteaseError('could not start QR login', {
577
+ code: data?.code,
578
+ endpoint: 'login/qrcode/unikey',
579
+ payload: data,
580
+ });
581
+ }
582
+ return { unikey: data.unikey, loginUrl: `${API_ORIGIN}/login?codekey=${data.unikey}` };
583
+ }
584
+
585
+ /**
586
+ * Poll one QR login attempt.
587
+ *
588
+ * Codes: `800` expired, `801` waiting for scan, `802` scanned awaiting
589
+ * confirmation, `803` success — on which the session cookie is set.
590
+ * @returns {Promise<{code: number, message: string, done: boolean}>}
591
+ */
592
+ async qrPoll(unikey) {
593
+ const data = await this.call('/api/login/qrcode/client/login', {
594
+ query: { key: unikey, type: 1 },
595
+ });
596
+ const code = Number(data?.code);
597
+ if (code === 803) {
598
+ // Some responses carry the cookie in the body as well as in Set-Cookie.
599
+ if (typeof data?.cookie === 'string' && data.cookie) this.jar.load(data.cookie);
600
+ if (!this.authenticated) {
601
+ return { code, message: data?.message ?? '登录成功但未收到会话 cookie', done: false };
602
+ }
603
+ await this.fetchAccount().catch(() => null);
604
+ }
605
+ return { code, message: data?.message ?? '', done: code === 803 && this.authenticated };
606
+ }
607
+ }
608
+
609
+ export { API_ORIGIN, FEE, UA };