-
Notifications
You must be signed in to change notification settings - Fork 801
Expand file tree
/
Copy pathqishui-api.js
More file actions
3497 lines (3328 loc) · 129 KB
/
Copy pathqishui-api.js
File metadata and controls
3497 lines (3328 loc) · 129 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const fs = require('fs');
const crypto = require('crypto');
const http = require('http');
const https = require('https');
const path = require('path');
const QISHUI_API_BASE = (process.env.QISHUI_API_BASE || 'https://open.douyin.com').replace(/\/+$/, '');
const QISHUI_RELATED_MEDIA_PATH = '/api/luna/v1/platform/feed/related-media/';
const QISHUI_FEED_SONG_TAB_PATH = '/api/luna/v1/platform/feed/song-tab/';
const QISHUI_SCOPE = 'luna.openapi.platform.play_core';
const DEFAULT_QISHUI_TOKEN_FILE = path.join(__dirname, '.qishui-token');
const QISHUI_UA = 'Mineradio/2.1.0 (Qishui official OpenAPI bridge)';
const QISHUI_OAUTH_AUTH_URL = (process.env.QISHUI_OAUTH_AUTH_URL || 'https://open.douyin.com/platform/oauth/connect').replace(/\/+$/, '');
const QISHUI_OAUTH_TOKEN_URL = process.env.QISHUI_OAUTH_TOKEN_URL || 'https://open.douyin.com/oauth/access_token/';
const QISHUI_PUBLIC_ENABLED = process.env.QISHUI_PUBLIC_ENABLED !== '0';
const QISHUI_PUBLIC_SEARCH_URL = process.env.QISHUI_PUBLIC_SEARCH_URL || 'https://api-vehicle.volcengine.com/v2/search/type';
const QISHUI_PUBLIC_CONTENTS_URL = process.env.QISHUI_PUBLIC_CONTENTS_URL || 'https://api-vehicle.volcengine.com/v2/custom/contents';
const QISHUI_VIRTUAL_FEED_PLAYLIST_ID = 'qishui-feed';
const QISHUI_WEB_LIKED_PLAYLIST_ID = 'qishui-liked';
const QISHUI_WEB_RECENT_PLAYLIST_ID = 'qishui-recent';
const QISHUI_WEB_API_BASES = (process.env.QISHUI_WEB_API_BASES || 'https://api5-lq.qishui.com,https://api.qishui.com')
.split(',')
.map(item => item.trim().replace(/\/+$/, ''))
.filter(Boolean);
const QISHUI_WEB_PC_API_BASE = (process.env.QISHUI_WEB_PC_API_BASE || 'https://api.qishui.com').replace(/\/+$/, '');
const QISHUI_PUBLIC_HEADERS = {
'Accept': 'application/json,text/plain,*/*',
'User-Agent': 'Mineradio/2.1.0 (Qishui public catalog bridge)',
};
const QISHUI_WEB_UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) SodaMusic/3.1.0 Chrome/136.0.7103.59 Electron/36.4.0-rs.22.release.main.1 TTElectron/36.4.0-rs.22.release.main.1 Safari/537.36';
const QISHUI_PC_APP_UA = 'LunaPC/3.3.0(359450208)';
const QISHUI_WEB_DEFAULT_PARAMS = {
aid: '386088',
app_name: 'luna_pc',
device_platform: 'web',
channel: 'pc_web',
};
function firstEnv(keys) {
for (const key of keys) {
const value = String(process.env[key] || '').trim();
if (value) return value;
}
return '';
}
function normalizeQishuiOAuthFileConfig(raw, file) {
raw = raw && typeof raw === 'object' ? raw : {};
const oauth = raw.oauth && typeof raw.oauth === 'object' ? raw.oauth : raw;
return {
clientKey: String(oauth.clientKey || oauth.client_key || oauth.clientId || oauth.client_id || oauth.key || '').trim(),
clientSecret: String(oauth.clientSecret || oauth.client_secret || oauth.secret || '').trim(),
redirectUri: String(oauth.redirectUri || oauth.redirect_uri || oauth.redirectURL || oauth.redirect_url || '').trim(),
scope: String(oauth.scope || oauth.scopes || '').trim(),
file,
source: file ? 'file' : '',
};
}
function qishuiOAuthConfigFileCandidates() {
const candidates = [];
const add = (value) => {
value = String(value || '').trim();
if (!value) return;
const resolved = path.resolve(value);
if (!candidates.includes(resolved)) candidates.push(resolved);
};
add(firstEnv(['QISHUI_OAUTH_CONFIG_FILE', 'DOUYIN_OAUTH_CONFIG_FILE']));
try { add(path.join(path.dirname(qishuiTokenFile()), '.qishui-oauth.json')); } catch (_) {}
add(path.join(__dirname, '.qishui-oauth.json'));
add(path.join(__dirname, 'qishui-oauth.json'));
return candidates;
}
function readQishuiOAuthFileConfig() {
const candidates = qishuiOAuthConfigFileCandidates();
for (const file of candidates) {
try {
if (!fs.existsSync(file)) continue;
const parsed = JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''));
const config = normalizeQishuiOAuthFileConfig(parsed, file);
if (config.clientKey || config.clientSecret || config.redirectUri || config.scope) return config;
} catch (e) {
console.warn('[QishuiOAuthConfig] ignored invalid config file:', file, e.message);
}
}
return normalizeQishuiOAuthFileConfig(null, candidates[0] || '');
}
function getQishuiOAuthConfig() {
const fileConfig = readQishuiOAuthFileConfig();
const clientKey = firstEnv(['QISHUI_OAUTH_CLIENT_KEY', 'QISHUI_CLIENT_KEY', 'DOUYIN_CLIENT_KEY']) || fileConfig.clientKey;
const clientSecret = firstEnv(['QISHUI_OAUTH_CLIENT_SECRET', 'QISHUI_CLIENT_SECRET', 'DOUYIN_CLIENT_SECRET']) || fileConfig.clientSecret;
const redirectUri = firstEnv(['QISHUI_OAUTH_REDIRECT_URI', 'QISHUI_REDIRECT_URI', 'DOUYIN_REDIRECT_URI']) || fileConfig.redirectUri;
const scope = firstEnv(['QISHUI_OAUTH_SCOPE', 'DOUYIN_OAUTH_SCOPE']) || fileConfig.scope || QISHUI_SCOPE;
const missing = [];
if (!clientKey) missing.push('QISHUI_OAUTH_CLIENT_KEY');
if (!clientSecret) missing.push('QISHUI_OAUTH_CLIENT_SECRET');
if (!redirectUri) missing.push('QISHUI_OAUTH_REDIRECT_URI');
else if (!/^https:\/\//i.test(redirectUri)) missing.push('QISHUI_OAUTH_REDIRECT_URI(https)');
return {
configured: missing.length === 0,
clientKey,
clientSecret,
redirectUri,
scope,
authUrl: QISHUI_OAUTH_AUTH_URL,
tokenUrl: QISHUI_OAUTH_TOKEN_URL,
missing,
configFile: fileConfig.file || '',
configSource: fileConfig.source || (clientKey || clientSecret || redirectUri ? 'env' : ''),
};
}
function qishuiOAuthConfigError(config) {
const err = new Error('QISHUI_OAUTH_NOT_CONFIGURED');
err.code = 'QISHUI_OAUTH_NOT_CONFIGURED';
err.missing = (config && config.missing) || [];
err.message = 'QISHUI_OAUTH_NOT_CONFIGURED: ' + err.missing.join(', ');
return err;
}
function buildQishuiOAuthAuthorizeUrl(state) {
const config = getQishuiOAuthConfig();
if (!config.configured) throw qishuiOAuthConfigError(config);
const url = new URL(config.authUrl);
url.searchParams.set('client_key', config.clientKey);
url.searchParams.set('response_type', 'code');
url.searchParams.set('scope', config.scope);
url.searchParams.set('redirect_uri', config.redirectUri);
if (state) url.searchParams.set('state', state);
return url.toString();
}
function createTtlCache(maxEntries, defaultTtlMs) {
const store = new Map();
const inflight = new Map();
return {
get(key) {
const hit = store.get(key);
if (!hit || Date.now() - hit.at > hit.ttl) return null;
return hit.value;
},
set(key, value, ttlMs) {
store.set(key, { at: Date.now(), ttl: ttlMs || defaultTtlMs, value });
if (store.size > maxEntries) {
const oldest = [...store.entries()].sort((a, b) => a[1].at - b[1].at)[0];
if (oldest) store.delete(oldest[0]);
}
},
clear() {
store.clear();
inflight.clear();
},
async wrap(key, ttlMs, fn) {
const cached = this.get(key);
if (cached !== null) return cached;
if (inflight.has(key)) return inflight.get(key);
const promise = Promise.resolve().then(fn).then((value) => {
const resolvedTtlMs = typeof ttlMs === 'function' ? ttlMs(value) : ttlMs;
this.set(key, value, resolvedTtlMs);
return value;
}).finally(() => inflight.delete(key));
inflight.set(key, promise);
return promise;
},
};
}
const qishuiSearchCache = createTtlCache(80, 2 * 60 * 1000);
const qishuiLyricCache = createTtlCache(240, 30 * 60 * 1000);
const qishuiPublicDetailCache = createTtlCache(240, 30 * 60 * 1000);
const qishuiFeedCache = createTtlCache(16, 90 * 1000);
const qishuiWebLibraryCache = createTtlCache(24, 90 * 1000);
const qishuiWebPlaylistCache = createTtlCache(48, 90 * 1000);
const qishuiWebPlaylistCursorCache = new Map();
const qishuiMembershipCache = createTtlCache(24, 60 * 1000);
const qishuiMembershipPositiveHistory = new Map();
const QISHUI_MEMBERSHIP_POSITIVE_CACHE_MS = 10 * 1000;
const QISHUI_MEMBERSHIP_POSITIVE_GRACE_MS = 20 * 1000;
const qishuiTrackMetadataCache = createTtlCache(120, 20 * 1000);
const qishuiPlaybackCache = createTtlCache(120, 4 * 60 * 1000);
function requestText(targetUrl, opts, body) {
opts = opts || {};
return new Promise((resolve, reject) => {
const u = new URL(targetUrl);
const lib = u.protocol === 'https:' ? https : http;
const req = lib.request(u, {
method: opts.method || 'GET',
headers: opts.headers || {},
}, response => {
const chunks = [];
response.on('data', chunk => chunks.push(chunk));
response.on('end', () => {
const text = Buffer.concat(chunks).toString('utf8');
if (response.statusCode >= 400) {
const err = new Error('HTTP ' + response.statusCode);
err.statusCode = response.statusCode;
err.body = text;
reject(err);
return;
}
resolve(text);
});
});
req.setTimeout(Number(opts.timeoutMs) || 7000, () => req.destroy(new Error('Request timeout')));
req.on('error', reject);
if (body) req.write(body);
req.end();
});
}
async function requestJson(targetUrl, opts, body) {
const text = await requestText(targetUrl, opts, body);
try {
return JSON.parse(text);
} catch (e) {
const err = new Error('Invalid JSON from Qishui OpenAPI');
err.cause = e;
err.body = text;
throw err;
}
}
function requestJsonWithMeta(targetUrl, opts, body) {
opts = opts || {};
return requestTextWithMeta(targetUrl, opts, body).then(meta => {
try {
return { json: JSON.parse(meta.text), headers: meta.headers || {}, statusCode: meta.statusCode };
} catch (e) {
const err = new Error('Invalid JSON from Qishui API');
err.cause = e;
err.body = meta.text;
err.headers = meta.headers || {};
throw err;
}
});
}
function requestTextWithMeta(targetUrl, opts, body) {
opts = opts || {};
return new Promise((resolve, reject) => {
const u = new URL(targetUrl);
const lib = u.protocol === 'https:' ? https : http;
const req = lib.request(u, {
method: opts.method || 'GET',
headers: opts.headers || {},
}, response => {
const chunks = [];
response.on('data', chunk => chunks.push(chunk));
response.on('end', () => {
const text = Buffer.concat(chunks).toString('utf8');
if (response.statusCode >= 400) {
const err = new Error('HTTP ' + response.statusCode);
err.statusCode = response.statusCode;
err.body = text;
err.headers = response.headers || {};
reject(err);
return;
}
resolve({ text, headers: response.headers || {}, statusCode: response.statusCode });
});
});
req.setTimeout(Number(opts.timeoutMs) || 7000, () => req.destroy(new Error('Request timeout')));
req.on('error', reject);
if (body) req.write(body);
req.end();
});
}
function urlWithParams(baseUrl, params) {
const u = new URL(baseUrl);
Object.keys(params || {}).forEach(key => {
const value = params[key];
if (value == null || value === '') return;
u.searchParams.set(key, String(value));
});
return u.toString();
}
function qishuiPcUrl(apiPath, params) {
const target = /^https?:\/\//i.test(apiPath)
? apiPath
: (QISHUI_WEB_PC_API_BASE + apiPath);
return urlWithParams(target, params || {});
}
function qishuiSessionCookieHeader(cookieText) {
const normalized = normalizeQishuiCookieInput(cookieText);
const obj = qishuiCookieObject(normalized);
if (qishuiCookieHasLogin(normalized)) return normalized;
const sessionid = normalizeText(obj.sessionid || obj.sessionid_ss || '');
return sessionid ? ('sessionid=' + sessionid + ';') : normalized;
}
function qishuiHeadersWithCookie(headers, cookieText) {
const out = Object.assign({}, headers || {});
const cookie = normalizeQishuiCookieInput(cookieText);
if (cookie) out.Cookie = cookie;
return out;
}
function qishuiPcStatusError(payload, fallback) {
if (!payload || typeof payload !== 'object') return null;
const code = Number(payload.status_code == null ? payload.error_code : payload.status_code);
if (!isFinite(code) || code === 0) return null;
const info = payload.status_info || {};
const message = normalizeText(info.status_msg || payload.message || payload.status_msg || fallback || 'QISHUI_PC_API_ERROR');
const err = new Error(message || 'QISHUI_PC_API_ERROR');
err.code = 'QISHUI_PC_API_' + code;
err.statusCode = code;
err.body = payload;
return err;
}
function qishuiTokenFile() {
return process.env.QISHUI_TOKEN_FILE || DEFAULT_QISHUI_TOKEN_FILE;
}
function normalizeQishuiToken(value) {
let token = String(value || '').trim();
token = token.replace(/^bearer\s+/i, '').trim();
const headerMatch = token.match(/(?:access-token|access_token)\s*[:=]\s*([^;\s]+)/i);
if (headerMatch) token = headerMatch[1].trim();
return token;
}
const QISHUI_COOKIE_ATTRIBUTE_NAMES = new Set(['path', 'domain', 'expires', 'max-age', 'samesite', 'secure', 'httponly']);
function collectQishuiCookiePair(picked, key, value) {
key = String(key || '').trim();
if (!key || QISHUI_COOKIE_ATTRIBUTE_NAMES.has(key.toLowerCase())) return;
if (value === null || value === undefined) return;
picked.set(key, String(value).trim());
}
function collectQishuiCookieInput(input, picked) {
if (input === null || input === undefined) return;
if (Array.isArray(input)) {
input.forEach(item => collectQishuiCookieInput(item, picked));
return;
}
if (typeof input === 'object') {
if (input.name && Object.prototype.hasOwnProperty.call(input, 'value')) {
collectQishuiCookiePair(picked, input.name, input.value);
return;
}
Object.keys(input).forEach(key => {
const value = input[key];
if (value && typeof value === 'object' && Object.prototype.hasOwnProperty.call(value, 'value')) {
collectQishuiCookiePair(picked, key, value.value);
} else if (typeof value !== 'object') {
collectQishuiCookiePair(picked, key, value);
}
});
return;
}
String(input).split(/\r?\n/).forEach(line => {
line.split(';').forEach(part => {
const raw = String(part || '').trim();
const idx = raw.indexOf('=');
if (idx <= 0) return;
collectQishuiCookiePair(picked, raw.slice(0, idx), raw.slice(idx + 1));
});
});
}
function normalizeQishuiCookieInput(input) {
const picked = new Map();
collectQishuiCookieInput(input, picked);
return Array.from(picked.entries())
.filter(([key, value]) => key && value != null && String(value) !== '')
.map(([key, value]) => `${key}=${value}`)
.join('; ');
}
function qishuiCookieObject(cookieText) {
const out = {};
String(cookieText || '').split(';').forEach(part => {
const idx = part.indexOf('=');
if (idx <= 0) return;
const key = part.slice(0, idx).trim();
const value = part.slice(idx + 1).trim();
if (key) out[key] = value;
});
return out;
}
function qishuiCookieHasLogin(cookieText) {
return /(?:^|;\s*)(sessionid|sessionid_ss|sid_guard|sid_tt|uid_tt|uid_tt_ss)=/i.test(String(cookieText || ''));
}
function qishuiCookieFingerprint(cookieText) {
const normalized = normalizeQishuiCookieInput(cookieText);
return crypto.createHash('sha1').update(normalized).digest('hex').slice(0, 16);
}
function qishuiCookieUserId(cookieText) {
const obj = qishuiCookieObject(cookieText);
const raw = String(obj.uid_tt || obj.uid_tt_ss || obj.sessionid || obj.sessionid_ss || obj.sid_guard || '').trim();
if (!raw) return '';
return 'web:' + crypto.createHash('sha1').update(raw).digest('hex').slice(0, 12);
}
function clearQishuiRuntimeCaches() {
qishuiSearchCache.clear && qishuiSearchCache.clear();
qishuiFeedCache.clear && qishuiFeedCache.clear();
qishuiWebLibraryCache.clear && qishuiWebLibraryCache.clear();
qishuiWebPlaylistCache.clear && qishuiWebPlaylistCache.clear();
qishuiWebPlaylistCursorCache.clear();
qishuiMembershipCache.clear && qishuiMembershipCache.clear();
qishuiMembershipPositiveHistory.clear();
qishuiTrackMetadataCache.clear && qishuiTrackMetadataCache.clear();
qishuiPlaybackCache.clear && qishuiPlaybackCache.clear();
}
function qishuiAccessTokenInfo() {
const envKeys = ['QISHUI_ACCESS_TOKEN', 'DOUYIN_ACCESS_TOKEN', 'DOUYIN_OPEN_ACCESS_TOKEN'];
for (const key of envKeys) {
const token = normalizeQishuiToken(process.env[key] || '');
if (token) return { token, source: 'env:' + key, file: qishuiTokenFile() };
}
const file = qishuiTokenFile();
try {
if (fs.existsSync(file)) {
const token = normalizeQishuiToken(fs.readFileSync(file, 'utf8'));
if (token) return { token, source: 'file', file };
}
} catch (_) {}
return { token: '', source: '', file };
}
function qishuiAccessToken() {
return qishuiAccessTokenInfo().token;
}
function saveQishuiAccessToken(value) {
const token = normalizeQishuiToken(value);
if (!token || token.length < 10) {
const err = new Error('INVALID_QISHUI_TOKEN');
err.code = 'INVALID_QISHUI_TOKEN';
throw err;
}
const file = qishuiTokenFile();
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, token, 'utf8');
clearQishuiRuntimeCaches();
return { ...getQishuiStatus(), saved: true };
}
function clearQishuiAccessToken() {
const file = qishuiTokenFile();
try { if (fs.existsSync(file)) fs.unlinkSync(file); } catch (_) {}
clearQishuiRuntimeCaches();
return { ...getQishuiStatus(), ok: true };
}
async function exchangeQishuiOAuthCode(code) {
code = normalizeText(code);
if (!code) {
const err = new Error('QISHUI_OAUTH_CODE_REQUIRED');
err.code = 'QISHUI_OAUTH_CODE_REQUIRED';
throw err;
}
const config = getQishuiOAuthConfig();
if (!config.configured) throw qishuiOAuthConfigError(config);
const body = new URLSearchParams();
body.set('client_key', config.clientKey);
body.set('client_secret', config.clientSecret);
body.set('code', code);
body.set('grant_type', 'authorization_code');
const bodyText = body.toString();
const json = await requestJson(config.tokenUrl, {
method: 'POST',
timeoutMs: 10000,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(bodyText),
'User-Agent': QISHUI_UA,
},
}, bodyText);
const data = (json && json.data) || json || {};
const errCode = Number(data.error_code || data.err_code || json.error_code || json.err_code || 0);
if (errCode) {
const err = new Error(String(data.description || data.message || json.description || json.message || 'QISHUI_OAUTH_TOKEN_ERROR'));
err.code = errCode;
err.body = json;
throw err;
}
const token = normalizeQishuiToken(data.access_token || json.access_token || '');
if (!token) {
const err = new Error('QISHUI_OAUTH_TOKEN_MISSING');
err.code = 'QISHUI_OAUTH_TOKEN_MISSING';
err.body = json;
throw err;
}
const status = saveQishuiAccessToken(token);
return {
...status,
oauth: true,
openId: data.open_id || data.openid || '',
scope: data.scope || status.scope,
expiresIn: data.expires_in || 0,
refreshExpiresIn: data.refresh_expires_in || 0,
};
}
function qishuiRestriction(category, message, action, extra) {
return {
provider: 'qishui',
category,
action: action || '',
message,
...(extra || {}),
};
}
function qishuiUnavailable(message, category, extra) {
const restriction = qishuiRestriction(
category || 'provider_limited',
message || '汽水音乐开放平台当前没有公开可交给播放器直连的音频 URL,已按匹配源处理。',
'switch_source',
{ playbackMode: 'recommend-match', scope: QISHUI_SCOPE }
);
return Object.assign({
provider: 'qishui',
playbackMode: 'recommend-match',
url: '',
playable: false,
trial: false,
loggedIn: !!qishuiAccessToken(),
playbackKeyReady: false,
restriction,
reason: restriction.category,
message: restriction.message,
}, extra || {});
}
function getQishuiStatus(cookieText) {
const tokenInfo = qishuiAccessTokenInfo();
const tokenConfigured = !!tokenInfo.token;
const cookie = normalizeQishuiCookieInput(cookieText);
const webSession = qishuiCookieHasLogin(cookie);
const configured = tokenConfigured || webSession;
const oauthConfig = getQishuiOAuthConfig();
return {
provider: 'qishui',
label: '汽水音乐',
short: 'QS',
configured,
tokenConfigured,
webSession,
cookieReady: webSession,
// Only an authenticated Passport Web session is an account login.
// A legacy OpenAPI token may still power catalogue/recommendation calls,
// but must never bypass the official QR login or impersonate a user.
loggedIn: webSession,
playbackMode: webSession ? 'direct-url' : 'recommend-match',
scope: QISHUI_SCOPE,
userId: webSession ? qishuiCookieUserId(cookie) : '',
nickname: webSession ? '汽水音乐账号' : '',
vipType: 0,
vipLevel: 'none',
isVip: false,
isSvip: false,
vipLabel: '无VIP',
membershipKnown: false,
tokenFile: tokenInfo.file,
tokenSource: tokenInfo.source,
oauthConfigured: oauthConfig.configured,
oauthMissing: oauthConfig.missing,
oauthScope: oauthConfig.scope,
oauthConfigSource: oauthConfig.configSource,
// Legacy quick-check guard: search: configured || QISHUI_PUBLIC_ENABLED.
capabilities: {
search: tokenConfigured || webSession || QISHUI_PUBLIC_ENABLED,
relatedMedia: tokenConfigured,
feedSongTab: tokenConfigured || webSession,
lyric: true,
playableUrl: webSession,
login: true,
webOAuth: oauthConfig.configured,
userPlaylists: configured,
playlistTracks: configured,
webSession,
},
message: webSession
? '汽水音乐官方扫码登录已连接,可同步歌单与我的喜欢,并按账号权益播放。'
: tokenConfigured
? '已有旧版开放平台目录授权;账号功能仍需完成官方扫码登录。'
: (QISHUI_PUBLIC_ENABLED
? '请使用抖音 App 扫描 Mineradio 中的汽水官方二维码;未登录时仅保留公开搜索匹配。'
: '请使用抖音 App 扫描 Mineradio 中的汽水官方二维码完成登录。'),
};
}
function qishuiUrl(apiPath) {
return QISHUI_API_BASE + apiPath;
}
async function qishuiPost(apiPath, payload) {
const token = qishuiAccessToken();
if (!token) {
const err = new Error('QISHUI_TOKEN_REQUIRED');
err.code = 'QISHUI_TOKEN_REQUIRED';
throw err;
}
const body = JSON.stringify(payload || {});
const json = await requestJson(qishuiUrl(apiPath), {
method: 'POST',
timeoutMs: 7000,
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(body),
'User-Agent': QISHUI_UA,
'access-token': token,
},
}, body);
const errCode = Number(json && json.data && (json.data.error_code || json.data.err_code || json.data.code) || json && (json.error_code || json.err_code || json.code) || 0);
if (errCode) {
const err = new Error(String((json && json.data && (json.data.description || json.data.message)) || json.description || json.message || 'QISHUI_API_ERROR'));
err.code = errCode;
err.body = json;
throw err;
}
return json;
}
function normalizeText(value) {
return String(value == null ? '' : value).replace(/\s+/g, ' ').trim();
}
function normalizeLyricBody(value) {
return String(value == null ? '' : value).replace(/\r\n/g, '\n').replace(/\r/g, '\n').trim();
}
function qishuiLyricTimestamp(ms) {
ms = Math.max(0, Number(ms) || 0);
const minutes = Math.floor(ms / 60000);
const seconds = Math.floor((ms % 60000) / 1000);
const centiseconds = Math.floor((ms % 1000) / 10);
return '[' +
String(minutes).padStart(2, '0') + ':' +
String(seconds).padStart(2, '0') + '.' +
String(centiseconds).padStart(2, '0') +
']';
}
function qishuiConvertLyric(value) {
const input = normalizeLyricBody(value);
if (!input) return { lyric: '', yrc: '' };
const lrcLines = [];
const yrcLines = [];
let converted = false;
input.split('\n').forEach(rawLine => {
const line = String(rawLine || '').trim();
const timed = line.match(/^\[(\d+),(\d+)\](.*)$/);
if (!timed) return;
const lineStart = Math.max(0, Number(timed[1]) || 0);
const lineDuration = Math.max(0, Number(timed[2]) || 0);
const body = timed[3] || '';
const wordPattern = /([<(])(\d+),(\d+),(\d+)[>)]([^<(]*)/g;
let wordMatch;
let text = '';
let yrcBody = '';
while ((wordMatch = wordPattern.exec(body))) {
const rawStart = Math.max(0, Number(wordMatch[2]) || 0);
const wordDuration = Math.max(0, Number(wordMatch[3]) || 0);
const wordText = String(wordMatch[5] || '');
if (!wordText) continue;
const absoluteStart = wordMatch[1] === '<'
? lineStart + rawStart
: (rawStart >= Math.max(0, lineStart - 500) ? rawStart : lineStart + rawStart);
text += wordText;
yrcBody += '(' + absoluteStart + ',' + wordDuration + ',' + (Number(wordMatch[4]) || 0) + ')' + wordText;
}
if (!text) text = body.replace(/[<(]\d+,\d+,\d+[>)]/g, '');
text = text.replace(/\s+/g, ' ').trim();
if (!text) return;
converted = true;
lrcLines.push(qishuiLyricTimestamp(lineStart) + text);
yrcLines.push('[' + lineStart + ',' + lineDuration + ']' + (yrcBody || text));
});
if (!converted) return { lyric: input, yrc: '' };
return {
lyric: lrcLines.join('\n'),
yrc: yrcLines.join('\n'),
};
}
function firstUrl(value) {
if (!value) return '';
if (typeof value === 'string') return value;
if (Array.isArray(value)) return value.map(firstUrl).find(Boolean) || '';
if (typeof value === 'object') {
return firstUrl(value.url_list || value.urls || value.url || value.uri || value.main_url || value.cover_url || value.download_url);
}
return '';
}
function qishuiImageUrl(value, suffix) {
if (!value) return '';
if (typeof value === 'string') {
const text = normalizeText(value);
if (!/^https?:\/\//i.test(text)) return '';
return suffix && !text.includes('~') ? text + suffix : text;
}
if (Array.isArray(value)) return value.map(item => qishuiImageUrl(item, suffix)).find(Boolean) || '';
if (typeof value !== 'object') return '';
const cover = normalizeText(firstUrl(value.urls || value.url_list || value.urlList || value.url || value.main_url || value.cover_url || value.image_url || ''));
const uri = normalizeText(value.uri || value.url_key || value.image_uri || value.cover_uri || '');
let out = cover;
if (out && uri && !out.includes(uri)) out += uri;
if (!out && /^https?:\/\//i.test(uri)) out = uri;
if (!/^https?:\/\//i.test(out)) return '';
return suffix && !out.includes('~') ? out + suffix : out;
}
function qishuiFirstImageUrl(suffix) {
for (let i = 1; i < arguments.length; i++) {
const url = qishuiImageUrl(arguments[i], suffix);
if (url) return url;
}
return '';
}
function pickObject() {
for (let i = 0; i < arguments.length; i++) {
const value = arguments[i];
if (value && typeof value === 'object' && !Array.isArray(value)) return value;
}
return {};
}
function qishuiProfileFromUser(user) {
user = user && typeof user === 'object' ? user : {};
const nickname = normalizeText(
user.nickname ||
user.nick_name ||
user.nickName ||
user.display_name ||
user.displayName ||
user.name ||
user.public_name ||
user.publicName ||
user.douyin_id ||
''
);
const userId = normalizeText(
user.id ||
user.user_id ||
user.userId ||
user.uid ||
user.sec_uid ||
user.secUid ||
user.open_id ||
''
);
const avatar = qishuiFirstImageUrl('~c5_300x300.jpg',
user.larger_avatar_url,
user.medium_avatar_url,
user.avatar_url,
user.avatarUrl,
user.avatar,
user.user_avatar,
user.pic,
user.icon
);
return {
userId,
nickname,
avatar,
douyinId: normalizeText(user.douyin_id || user.unique_id || user.short_id || ''),
profileReady: !!(userId || nickname || avatar),
};
}
const QISHUI_VIP_NUMBER_KEYS = new Set([
'viptype', 'viplevel', 'membertype', 'memberlevel', 'musicviptype', 'musicviplevel',
]);
const QISHUI_SVIP_NUMBER_KEYS = new Set([
'sviptype', 'sviplevel', 'superviptype', 'superviplevel',
]);
const QISHUI_VIP_FLAG_KEYS = new Set([
'isvip', 'ismember', 'hasvip', 'hasmembership', 'vipactive', 'vipenabled',
]);
const QISHUI_SVIP_FLAG_KEYS = new Set([
'issvip', 'issupervip', 'hassvip', 'hassupervip', 'svipactive', 'svipenabled',
]);
const QISHUI_MEMBERSHIP_LABEL_KEYS = new Set([
'viplevelname', 'vipname', 'memberlevelname', 'membername', 'membershiplevel', 'membershiptype',
]);
const QISHUI_VIP_CONTAINER_KEYS = new Set([
'vipinfo', 'vipdetail', 'vipbenefit', 'vippackage', 'memberinfo', 'memberdetail',
'memberbenefit', 'memberpackage', 'membershipinfo', 'membershipdetail',
]);
const QISHUI_SVIP_CONTAINER_KEYS = new Set([
'svipinfo', 'svipdetail', 'svipbenefit', 'svippackage', 'supervipinfo',
'supervipdetail', 'supervipbenefit', 'supervippackage',
]);
const QISHUI_MEMBERSHIP_STATUS_KEYS = new Set([
'status', 'state', 'active', 'valid', 'enabled', 'isactive', 'isvalid', 'isenabled',
]);
const QISHUI_MEMBERSHIP_GENERIC_EXPIRY_KEYS = new Set([
'expiretime', 'expiresat', 'expirationtime', 'expiredat', 'endtime', 'validuntil',
]);
const QISHUI_VIP_EXPIRY_KEYS = new Set([
'vipexpiretime', 'vipexpiresat', 'vipexpiredat', 'vipendtime',
'memberexpiretime', 'memberexpiresat', 'memberexpiredat', 'memberendtime',
]);
const QISHUI_SVIP_EXPIRY_KEYS = new Set([
'svipexpiretime', 'svipexpiresat', 'svipexpiredat', 'svipendtime',
]);
function qishuiNormalizedFieldKey(value) {
return String(value || '').toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g, '');
}
function qishuiExplicitPositive(value) {
if (value === true) return true;
if (typeof value === 'number') return Number.isFinite(value) && value > 0;
const text = normalizeText(value).toLowerCase();
if (!text) return false;
if (/^\d+(?:\.\d+)?$/.test(text)) return Number(text) > 0;
return /^(true|yes|active|valid|enabled|opened|vip|svip|premium|member|会员|已开通|有效)$/.test(text);
}
function qishuiExplicitNegative(value) {
if (value === false || value === null) return true;
if (typeof value === 'number') return Number.isFinite(value) && value <= 0;
const text = normalizeText(value).toLowerCase();
if (!text) return false;
if (/^\d+(?:\.\d+)?$/.test(text)) return Number(text) <= 0;
return /^(false|no|inactive|invalid|disabled|closed|expired|none|free|normal|ordinary|非会员|普通用户|未开通|无vip|已过期|过期)$/.test(text);
}
function qishuiMembershipLevelValue(value) {
const text = normalizeText(value).toLowerCase().replace(/[\s_-]+/g, '');
if (/^(svip|supervip|超级会员|超级vip|豪华会员)$/.test(text)) return 'svip';
if (/^(vip|premium|member|会员|普通会员)$/.test(text)) return 'vip';
if (/^(none|free|normal|ordinary|novip|非会员|普通用户|未开通|无vip|已过期|过期)$/.test(text)) return 'none';
return '';
}
function qishuiMembershipExpiryMillis(value) {
if (value === null || value === undefined || value === '') return 0;
const number = Number(value);
if (Number.isFinite(number) && number > 0) {
return number < 100000000000 ? number * 1000 : number;
}
const parsed = Date.parse(String(value));
return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
}
function qishuiMembershipObjectState(value, level) {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return { known: false, active: null, expiresAt: 0 };
}
let known = false;
let statusPositive = false;
let statusNegative = false;
let genericExpiryKnown = false;
let genericExpiryExpired = false;
let genericFutureExpiry = 0;
let levelExpiryKnown = false;
let levelExpiryExpired = false;
let levelFutureExpiry = 0;
const levelExpiryKeys = level === 'svip'
? QISHUI_SVIP_EXPIRY_KEYS
: (level === 'vip' ? QISHUI_VIP_EXPIRY_KEYS : null);
for (const [key, item] of Object.entries(value)) {
const normalizedKey = qishuiNormalizedFieldKey(key);
const isGenericExpiry = QISHUI_MEMBERSHIP_GENERIC_EXPIRY_KEYS.has(normalizedKey);
const isLevelExpiry = levelExpiryKeys
? levelExpiryKeys.has(normalizedKey)
: (QISHUI_VIP_EXPIRY_KEYS.has(normalizedKey) || QISHUI_SVIP_EXPIRY_KEYS.has(normalizedKey));
if (isGenericExpiry || isLevelExpiry) {
const expiresAt = qishuiMembershipExpiryMillis(item);
const isKnownExpiry = expiresAt > 0 || (
item !== '' &&
item !== null &&
item !== undefined &&
Number.isFinite(Number(item)) &&
Number(item) <= 0
);
if (!isKnownExpiry) continue;
known = true;
if (isLevelExpiry) {
levelExpiryKnown = true;
if (expiresAt > Date.now()) {
levelFutureExpiry = Math.max(levelFutureExpiry, expiresAt);
} else {
levelExpiryExpired = true;
}
} else {
genericExpiryKnown = true;
if (expiresAt > Date.now()) {
genericFutureExpiry = Math.max(genericFutureExpiry, expiresAt);
} else {
genericExpiryExpired = true;
}
}
continue;
}
if (!QISHUI_MEMBERSHIP_STATUS_KEYS.has(normalizedKey)) continue;
if (qishuiExplicitNegative(item)) {
known = true;
statusNegative = true;
} else if (qishuiExplicitPositive(item)) {
known = true;
statusPositive = true;
}
}
// Tier-specific expiry is authoritative for that tier. Generic expiry is a
// fallback only when the object has no expiry for the requested tier. This
// keeps an expired/zero SVIP field from cancelling a valid VIP, and vice
// versa, when both tiers are returned in the same official response object.
const expiryKnown = levelExpiryKnown || genericExpiryKnown;
const expiryExpired = levelExpiryKnown ? levelExpiryExpired : genericExpiryExpired;
const futureExpiry = levelExpiryKnown ? levelFutureExpiry : genericFutureExpiry;
const active = statusNegative || expiryExpired
? false
: (futureExpiry > 0 || (!expiryKnown && statusPositive) ? true : (expiryKnown ? false : null));
return {
known,
active,
expiresAt: active === true ? futureExpiry : 0,
};
}
function qishuiMembershipFromData(value) {
value = value && typeof value === 'object' ? value : {};
let membershipKnown = false;
let isVip = false;
let isSvip = false;
let vipType = 0;
let svipType = 0;
let vipExpiresAt = 0;
let svipExpiresAt = 0;
let visited = 0;
const rememberExpiry = (level, expiresAt) => {
expiresAt = Number(expiresAt) || 0;
if (expiresAt <= Date.now()) return;
if (level === 'svip') {
if (!svipExpiresAt || expiresAt < svipExpiresAt) svipExpiresAt = expiresAt;
return;
}
if (level === 'vip' && (!vipExpiresAt || expiresAt < vipExpiresAt)) vipExpiresAt = expiresAt;
};
const applyLevel = (level, numericValue, active, expiresAt) => {
if (active === false || !level) return;
if (level === 'svip') {
isSvip = true;
isVip = true;
svipType = Math.max(svipType, Number(numericValue) || 1);
rememberExpiry('svip', expiresAt);
return;
}
if (level === 'vip') {
isVip = true;
vipType = Math.max(vipType, Number(numericValue) || 1);
rememberExpiry('vip', expiresAt);
}
};
const visit = (node, depth) => {
if (!node || typeof node !== 'object' || depth > 6 || visited > 600) return;
visited += 1;
if (Array.isArray(node)) {
node.slice(0, 120).forEach(item => visit(item, depth + 1));
return;
}
const vipObjectState = qishuiMembershipObjectState(node, 'vip');
const svipObjectState = qishuiMembershipObjectState(node, 'svip');
for (const [key, item] of Object.entries(node).slice(0, 160)) {
const normalizedKey = qishuiNormalizedFieldKey(key);
if (QISHUI_SVIP_NUMBER_KEYS.has(normalizedKey)) {
membershipKnown = true;
const number = Number(item);
if (Number.isFinite(number) && number > 0) applyLevel('svip', number, svipObjectState.active, svipObjectState.expiresAt);
} else if (QISHUI_VIP_NUMBER_KEYS.has(normalizedKey)) {
membershipKnown = true;
const number = Number(item);
if (Number.isFinite(number) && number > 0) applyLevel('vip', number, vipObjectState.active, vipObjectState.expiresAt);
} else if (QISHUI_SVIP_FLAG_KEYS.has(normalizedKey)) {
membershipKnown = true;
if (qishuiExplicitPositive(item)) applyLevel('svip', 1, svipObjectState.active, svipObjectState.expiresAt);
} else if (QISHUI_VIP_FLAG_KEYS.has(normalizedKey)) {
membershipKnown = true;
if (qishuiExplicitPositive(item)) applyLevel('vip', 1, vipObjectState.active, vipObjectState.expiresAt);
} else if (QISHUI_MEMBERSHIP_LABEL_KEYS.has(normalizedKey)) {
membershipKnown = true;
const level = qishuiMembershipLevelValue(item);
const state = level === 'svip' ? svipObjectState : vipObjectState;
applyLevel(level, 1, state.active, state.expiresAt);
} else if (QISHUI_SVIP_CONTAINER_KEYS.has(normalizedKey) || QISHUI_VIP_CONTAINER_KEYS.has(normalizedKey)) {