forked from XxHuberrr/Mineradio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
4407 lines (4220 loc) · 171 KB
/
Copy pathserver.js
File metadata and controls
4407 lines (4220 loc) · 171 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
// ====================================================================
// 粒子音乐可视化播放器 — Server v2
// - 网易云搜索 / 歌曲URL / 封面/音频代理
// - 扫码登录 (login_qr_*) + cookie 持久化 (./.cookie)
// - 试听检测 (freeTrialInfo) + 全 quality 探测
// - 所有受保护 API 都会带上已登录用户的 cookie
// ====================================================================
const {
search,
cloudsearch,
song_detail,
song_url,
song_url_v1,
login_qr_key,
login_qr_create,
login_qr_check,
login_status,
logout,
user_account,
user_playlist,
comment_music,
artist_detail,
artist_top_song,
artist_songs,
like: like_song,
likelist,
song_like_check,
playlist_tracks,
playlist_track_add,
playlist_create,
playlist_detail,
playlist_track_all,
personalized,
recommend_resource,
recommend_songs,
dj_detail,
dj_program,
dj_hot,
dj_sublist,
user_audio,
dj_paygift,
record_recent_voice,
sati_resource_sub_list,
lyric,
lyric_new,
} = require('NeteaseCloudMusicApi');
const http = require('http');
const https = require('https');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const tls = require('tls');
const { once } = require('events');
const { fileURLToPath } = require('url');
const { analyzePodcastDjStream, analyzePodcastDjIntro } = require('./dj-analyzer');
const {
LxSourceManager,
resolveWithLx,
searchKuwo,
} = require('./lib/lx-source');
const PORT = process.env.PORT || 3000;
const HOST = process.env.HOST || '0.0.0.0';
const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36';
const COOKIE_FILE = process.env.COOKIE_FILE || path.join(__dirname, '.cookie');
const QQ_COOKIE_FILE = process.env.QQ_COOKIE_FILE || path.join(__dirname, '.qq-cookie');
const LX_SOURCE_FILE = process.env.MINERADIO_LX_SOURCE_FILE || path.join(__dirname, '.lx-source.js');
const UPDATE_WORK_DIR = process.env.MINERADIO_UPDATE_DIR || path.join(__dirname, 'updates');
const UPDATE_DOWNLOAD_DIR = process.env.MINERADIO_UPDATE_DOWNLOAD_DIR || path.join(UPDATE_WORK_DIR, 'downloads');
const UPDATE_PATCH_BACKUP_DIR = process.env.MINERADIO_PATCH_BACKUP_DIR || path.join(UPDATE_WORK_DIR, 'backups', 'patches');
const BEATMAP_CACHE_DIR = process.env.MINERADIO_BEAT_CACHE_DIR || 'D:\\MineradioCache\\beatmaps';
const APP_PACKAGE = readPackageInfo();
const APP_VERSION = process.env.MINERADIO_VERSION || APP_PACKAGE.version || '0.9.11';
const UPDATE_CONFIG = readUpdateConfig(APP_PACKAGE);
const PATCH_MAX_BYTES = 12 * 1024 * 1024;
const PATCH_ALLOWED_ROOTS = new Set(['public', 'desktop', 'build']);
const PATCH_ALLOWED_FILES = new Set(['server.js', 'dj-analyzer.js', 'package.json', 'package-lock.json']);
const UPDATE_FALLBACK_NOTES = [
'电影镜头节奏更松',
'音源失败自动换源',
'右上角更新提示',
];
const OPEN_METEO_FORECAST_URL = 'https://api.open-meteo.com/v1/forecast';
const OPEN_METEO_GEOCODE_URL = 'https://geocoding-api.open-meteo.com/v1/search';
const WEATHER_IP_LOCATION_URL = 'http://ip-api.com/json/';
const WEATHER_DEFAULT_LOCATION = {
name: '上海',
country: 'China',
latitude: 31.2304,
longitude: 121.4737,
timezone: 'Asia/Shanghai',
};
const updateDownloadJobs = new Map();
const lxSourceManager = new LxSourceManager(LX_SOURCE_FILE);
process.on('uncaughtException', (err) => {
console.error('[UncaughtException]', err && err.stack || err);
});
process.on('unhandledRejection', (err) => {
console.error('[UnhandledRejection]', err && err.stack || err);
});
async function fetchLxSourceScriptFromUrl(sourceUrl) {
const raw = String(sourceUrl || '').trim();
if (!/^https?:\/\//i.test(raw)) throw new Error('LX_SOURCE_URL_INVALID');
const resp = await fetchWithTimeout(raw, {
headers: {
'User-Agent': `Mineradio/${APP_VERSION}`,
Accept: 'application/javascript,text/javascript,text/plain,*/*',
},
}, 15000);
if (!resp.ok) throw new Error('LX_SOURCE_URL_HTTP_' + resp.status);
const text = await resp.text();
if (!text.trim()) throw new Error('LX_SOURCE_EMPTY');
if (Buffer.byteLength(text, 'utf8') > 2 * 1024 * 1024) throw new Error('LX_SOURCE_TOO_LARGE');
return text;
}
function applySystemCertificateAuthorities() {
try {
if (typeof tls.getCACertificates !== 'function' || typeof tls.setDefaultCACertificates !== 'function') return;
const bundled = tls.getCACertificates('default') || [];
const system = tls.getCACertificates('system') || [];
if (!system.length) return;
const seen = new Set();
const merged = [];
bundled.concat(system).forEach(cert => {
if (!cert || seen.has(cert)) return;
seen.add(cert);
merged.push(cert);
});
if (merged.length > bundled.length) tls.setDefaultCACertificates(merged);
} catch (e) {
console.warn('[TLS] system CA merge skipped:', e.message);
}
}
applySystemCertificateAuthorities();
const MIME = {
'.html': 'text/html; charset=utf-8',
'.js': 'application/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.ico': 'image/x-icon',
'.svg': 'image/svg+xml',
};
// ---------- Cookie 持久化 ----------
const COOKIE_ATTRIBUTE_NAMES = new Set(['path', 'domain', 'expires', 'max-age', 'samesite', 'secure', 'httponly']);
function collectCookiePair(picked, key, value) {
key = String(key || '').trim();
if (!key || COOKIE_ATTRIBUTE_NAMES.has(key.toLowerCase())) return;
if (value === null || value === undefined) return;
picked.set(key, String(value).trim());
}
function collectCookieInput(input, picked) {
if (input === null || input === undefined) return;
if (Array.isArray(input)) {
input.forEach(item => collectCookieInput(item, picked));
return;
}
if (typeof input === 'object') {
if (input.name && Object.prototype.hasOwnProperty.call(input, 'value')) {
collectCookiePair(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')) {
collectCookiePair(picked, key, value.value);
} else if (typeof value !== 'object') {
collectCookiePair(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;
collectCookiePair(picked, raw.slice(0, idx), raw.slice(idx + 1));
});
});
}
function normalizeCookieHeader(input) {
const picked = new Map();
collectCookieInput(input, picked);
return Array.from(picked.entries())
.filter(([key, value]) => key && value != null && String(value) !== '')
.map(([key, value]) => `${key}=${value}`)
.join('; ');
}
function rawCookieFallback(input) {
if (typeof input === 'string') return input.trim();
if (Array.isArray(input) && input.every(item => typeof item === 'string')) return input.join('; ').trim();
return '';
}
let userCookie = '';
try { if (fs.existsSync(COOKIE_FILE)) userCookie = fs.readFileSync(COOKIE_FILE, 'utf8').trim(); }
catch (e) { userCookie = ''; }
function saveCookie(c) {
userCookie = normalizeCookieHeader(c) || rawCookieFallback(c);
try { fs.writeFileSync(COOKIE_FILE, userCookie); } catch (e) {}
}
let qqCookie = '';
try { if (fs.existsSync(QQ_COOKIE_FILE)) qqCookie = fs.readFileSync(QQ_COOKIE_FILE, 'utf8').trim(); }
catch (e) { qqCookie = ''; }
function saveQQCookie(c) {
qqCookie = normalizeCookieHeader(c) || rawCookieFallback(c);
try { fs.writeFileSync(QQ_COOKIE_FILE, qqCookie); } catch (e) {}
}
// ---------- 工具 ----------
function serveStatic(res, filePath) {
const ext = path.extname(filePath);
fs.readFile(filePath, (err, data) => {
if (err) { res.writeHead(404); res.end('Not Found'); return; }
res.writeHead(200, { 'Content-Type': MIME[ext] || 'text/plain' });
res.end(data);
});
}
function sendJSON(res, data, status) {
res.writeHead(status || 200, {
'Content-Type': 'application/json; charset=utf-8',
'Access-Control-Allow-Origin': '*',
'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate',
'Pragma': 'no-cache',
'Expires': '0',
});
res.end(JSON.stringify(data));
}
function readPackageInfo() {
try {
const raw = fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8');
return JSON.parse(raw);
} catch (e) {
return {};
}
}
function parseGitHubRepository(input) {
const raw = String(input || '').trim();
if (!raw) return null;
const direct = raw.match(/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/);
if (direct) return { owner: direct[1], repo: direct[2].replace(/\.git$/i, '') };
const github = raw.match(/github\.com[:/]([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?(?:[#/?].*)?$/i);
if (github) return { owner: github[1], repo: github[2].replace(/\.git$/i, '') };
return null;
}
function readUpdateConfig(pkg) {
const local = (pkg && pkg.mineradio && pkg.mineradio.update) || {};
const repoHint = process.env.MINERADIO_UPDATE_REPOSITORY
|| process.env.GITHUB_REPOSITORY
|| local.repository
|| local.github
|| (pkg && pkg.repository && (pkg.repository.url || pkg.repository))
|| '';
const parsed = parseGitHubRepository(repoHint) || {};
const owner = process.env.MINERADIO_UPDATE_OWNER || local.owner || parsed.owner || '';
const repo = process.env.MINERADIO_UPDATE_REPO || local.repo || parsed.repo || '';
return {
provider: local.provider || 'github',
owner,
repo,
configured: !!(owner && repo),
preview: local.preview !== false,
preferMirrors: local.preferMirrors !== false,
mirrors: readUpdateMirrors(local),
manifest: process.env.MINERADIO_UPDATE_MANIFEST
|| process.env.MINERADIO_UPDATE_MANIFEST_URL
|| process.env.MINERADIO_UPDATE_MANIFEST_FILE
|| '',
};
}
function parseUpdateMirrorList(value) {
if (Array.isArray(value)) return value;
return String(value || '').split(/[\n,;]/);
}
function readUpdateMirrors(local) {
const envMirrors = process.env.MINERADIO_UPDATE_MIRRORS || process.env.MINERADIO_UPDATE_MIRROR || '';
const raw = envMirrors
? parseUpdateMirrorList(envMirrors)
: parseUpdateMirrorList(local.mirrors || local.downloadMirrors || []);
const seen = new Set();
const mirrors = [];
raw.forEach(item => {
const url = String(item || '').trim();
if (!/^https?:\/\//i.test(url)) return;
const key = url.replace(/\/+$/, '').toLowerCase();
if (seen.has(key)) return;
seen.add(key);
mirrors.push(url);
});
return mirrors.slice(0, 6);
}
function normalizeDigest(value, algorithm) {
const raw = String(value || '').trim();
if (!raw) return '';
const prefix = new RegExp('^' + algorithm + ':', 'i');
return raw.replace(prefix, '').trim().replace(/^['"]|['"]$/g, '');
}
function assetDigestInfo(asset) {
const digest = String(asset && asset.digest || '').trim();
return {
sha256: normalizeDigest((asset && asset.sha256) || (/^sha256:/i.test(digest) ? digest : ''), 'sha256').toLowerCase(),
sha512: normalizeDigest((asset && asset.sha512) || (/^sha512:/i.test(digest) ? digest : ''), 'sha512'),
};
}
function buildMirrorUrl(originalUrl, mirror) {
const source = String(originalUrl || '').trim();
const base = String(mirror || '').trim();
if (!/^https?:\/\//i.test(source) || !/^https?:\/\//i.test(base)) return '';
if (base.includes('{encodedUrl}')) return base.replace(/\{encodedUrl\}/g, encodeURIComponent(source));
if (base.includes('{url}')) return base.replace(/\{url\}/g, source);
return base.replace(/\/+$/, '/') + source;
}
function uniqueDownloadCandidates(urls, opts) {
opts = opts || {};
const directUrls = (Array.isArray(urls) ? urls : [urls])
.map(url => String(url || '').trim())
.filter(url => /^https?:\/\//i.test(url));
const directSet = new Set(directUrls.map(url => url.toLowerCase()));
const mirrors = opts.useMirrors === false ? [] : (UPDATE_CONFIG.mirrors || []);
const mirrored = [];
directUrls.forEach(source => {
mirrors.forEach((mirror, index) => {
const url = buildMirrorUrl(source, mirror);
if (url) mirrored.push({
url,
label: '国内加速线路 ' + (index + 1),
mirrored: true,
});
});
});
const direct = directUrls.map(url => ({
url,
label: directSet.has(url.toLowerCase()) ? 'GitHub 直连' : '下载线路',
mirrored: false,
}));
const ordered = UPDATE_CONFIG.preferMirrors === false ? direct.concat(mirrored) : mirrored.concat(direct);
const seen = new Set();
return ordered.filter(item => {
const key = item.url.toLowerCase();
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
function publicDownloadUrls(candidates) {
return (Array.isArray(candidates) ? candidates : [])
.map(item => item && item.url)
.filter(Boolean);
}
function normalizeVersion(value) {
return String(value || '').trim().replace(/^v/i, '').replace(/[+].*$/, '').replace(/-.+$/, '');
}
function compareVersions(a, b) {
const aa = normalizeVersion(a).split('.').map(n => parseInt(n, 10) || 0);
const bb = normalizeVersion(b).split('.').map(n => parseInt(n, 10) || 0);
const len = Math.max(aa.length, bb.length, 3);
for (let i = 0; i < len; i++) {
const left = aa[i] || 0;
const right = bb[i] || 0;
if (left > right) return 1;
if (left < right) return -1;
}
return 0;
}
function cleanReleaseLine(line) {
return String(line || '')
.replace(/^\s*#{1,6}\s*/, '')
.replace(/^\s*[-*]\s+/, '')
.replace(/^\s*\d+[.)]\s+/, '')
.replace(/\*\*/g, '')
.replace(/`/g, '')
.trim();
}
function extractReleaseNotes(body) {
const notes = [];
String(body || '').split(/\r?\n/).forEach(line => {
const text = cleanReleaseLine(line);
if (!text) return;
if (/^(what'?s changed|changes|changelog|full changelog|更新日志)$/i.test(text)) return;
if (/^https?:\/\//i.test(text)) return;
if (text.length > 72) return;
notes.push(text);
});
return notes.slice(0, 4);
}
function pickReleaseAsset(assets) {
const list = Array.isArray(assets) ? assets : [];
const preferred = list.find(a => /\.(exe|msi)$/i.test(a && a.name || ''))
|| list.find(a => /\.(zip|7z)$/i.test(a && a.name || ''))
|| list[0];
if (!preferred) return null;
const digest = assetDigestInfo(preferred);
const candidates = uniqueDownloadCandidates(preferred.browser_download_url || '');
return {
name: preferred.name || '',
size: preferred.size || 0,
contentType: preferred.content_type || '',
downloadUrl: preferred.browser_download_url || '',
downloadUrls: publicDownloadUrls(candidates),
sha256: digest.sha256 || '',
sha512: digest.sha512 || '',
};
}
function patchAssetVersions(name) {
const matches = String(name || '').match(/\d+(?:[._-]\d+){1,3}/g) || [];
return matches.map(item => normalizeVersion(item.replace(/[._-]/g, '.'))).filter(Boolean);
}
function pickPatchAsset(assets, currentVersion, latestVersion) {
const list = Array.isArray(assets) ? assets : [];
const current = normalizeVersion(currentVersion || APP_VERSION);
const latest = normalizeVersion(latestVersion || '');
const preferred = list.find(a => {
const name = String(a && a.name || '');
if (!/\.(patch\.json|patch|json)$/i.test(name)) return false;
const versions = patchAssetVersions(name);
if (latest) return versions[0] === current && versions[versions.length - 1] === latest;
return versions[0] === current && name.toLowerCase().includes('patch');
}) || list.find(a => {
const name = String(a && a.name || '');
if (!/\.(patch\.json|patch|json)$/i.test(name)) return false;
const versions = patchAssetVersions(name);
return versions[0] === current && name.toLowerCase().includes('patch');
}) || list.find(a => /\.(patch\.json|patch)$/i.test(a && a.name || ''));
if (!preferred) return null;
const digest = assetDigestInfo(preferred);
const candidates = uniqueDownloadCandidates(preferred.browser_download_url || '');
return {
name: preferred.name || '',
size: preferred.size || 0,
contentType: preferred.content_type || '',
downloadUrl: preferred.browser_download_url || '',
downloadUrls: publicDownloadUrls(candidates),
sha256: digest.sha256 || '',
sha512: digest.sha512 || '',
};
}
function updateAssetNameFromUrl(value) {
try {
const u = new URL(String(value || ''));
const base = path.basename(decodeURIComponent(u.pathname || ''));
if (base) return base;
} catch (_) {}
return path.basename(String(value || '').split('?')[0]) || '';
}
function normalizeManifestUpdateInfo(data) {
data = data || {};
const release = data.release || {};
const asset = release.asset || data.asset || {};
const latestVersion = normalizeVersion(
data.latestVersion
|| data.version
|| release.version
|| release.tagName
|| release.tag_name
|| release.name
|| APP_VERSION
) || APP_VERSION;
const downloadUrl = release.downloadUrl || data.downloadUrl || asset.downloadUrl || asset.browser_download_url || '';
const patch = release.patch || data.patch || null;
const assetUrls = [downloadUrl].concat(Array.isArray(asset.downloadUrls) ? asset.downloadUrls : []);
const patchUrls = patch ? [patch.downloadUrl].concat(Array.isArray(patch.downloadUrls) ? patch.downloadUrls : []) : [];
const patchInfo = patch && patch.downloadUrl ? {
name: patch.name || updateAssetNameFromUrl(patch.downloadUrl) || `Mineradio-${APP_VERSION}→${latestVersion}.patch.json`,
size: Number(patch.size || 0) || 0,
contentType: patch.contentType || patch.content_type || 'application/json',
downloadUrl: patch.downloadUrl,
downloadUrls: publicDownloadUrls(uniqueDownloadCandidates(patchUrls)),
from: normalizeVersion(patch.from || APP_VERSION),
to: normalizeVersion(patch.to || latestVersion),
sha256: normalizeDigest(patch.sha256 || '', 'sha256').toLowerCase(),
sha512: normalizeDigest(patch.sha512 || '', 'sha512'),
} : null;
const notes = Array.isArray(release.notes) && release.notes.length
? release.notes.slice(0, 4).map(cleanReleaseLine).filter(Boolean)
: (extractReleaseNotes(release.body || data.body).length ? extractReleaseNotes(release.body || data.body) : UPDATE_FALLBACK_NOTES);
const assetInfo = downloadUrl ? {
name: asset.name || updateAssetNameFromUrl(downloadUrl) || `Mineradio-${latestVersion}-Setup.exe`,
size: Number(asset.size || 0) || 0,
contentType: asset.contentType || asset.content_type || '',
downloadUrl,
downloadUrls: publicDownloadUrls(uniqueDownloadCandidates(assetUrls)),
sha256: normalizeDigest(asset.sha256 || '', 'sha256').toLowerCase(),
sha512: normalizeDigest(asset.sha512 || release.sha512 || data.sha512 || '', 'sha512'),
} : null;
return {
configured: true,
preview: false,
updateAvailable: data.updateAvailable != null ? !!data.updateAvailable : compareVersions(latestVersion, APP_VERSION) > 0,
currentVersion: APP_VERSION,
latestVersion,
release: {
tagName: release.tagName || release.tag_name || data.tagName || ('v' + latestVersion),
name: release.name || data.name || ('Mineradio v' + latestVersion),
version: latestVersion,
publishedAt: release.publishedAt || release.published_at || data.publishedAt || '',
htmlUrl: release.htmlUrl || release.html_url || data.htmlUrl || '',
downloadUrl,
asset: assetInfo,
patch: patchInfo,
patchAvailable: !!(patchInfo && patchInfo.downloadUrl && compareVersions(latestVersion, APP_VERSION) > 0),
summary: release.summary || data.summary || notes[0] || '发现新版本,建议更新。',
notes,
},
source: 'manifest',
};
}
async function readUpdateManifest(ref) {
const value = String(ref || '').trim();
if (!value) throw new Error('UPDATE_MANIFEST_MISSING');
if (/^https?:\/\//i.test(value)) {
const resp = await fetch(value, {
headers: { 'User-Agent': `Mineradio/${APP_VERSION}` },
});
if (!resp.ok) throw new Error('Update manifest ' + resp.status);
return resp.json();
}
const file = /^file:/i.test(value) ? fileURLToPath(value) : path.resolve(value);
return JSON.parse(fs.readFileSync(file, 'utf8'));
}
async function fetchManifestUpdateInfo(ref) {
try {
const data = await readUpdateManifest(ref);
return normalizeManifestUpdateInfo(data);
} catch (err) {
return localUpdateFallback(err.message || 'Update manifest failed', { configured: true });
}
}
function beatCacheRootInfo() {
const dir = path.resolve(BEATMAP_CACHE_DIR);
const root = path.parse(dir).root;
const drive = root ? root.replace(/[\\\/]+$/, '').toUpperCase() : '';
const allowed = !!root && !/^C:$/i.test(drive);
const available = allowed && fs.existsSync(root);
return { dir, root, drive, allowed, available };
}
function ensureBeatMapCacheDir() {
const info = beatCacheRootInfo();
if (!info.allowed) {
const err = new Error('BEAT_CACHE_ON_C_DRIVE_DISABLED');
err.code = 'BEAT_CACHE_ON_C_DRIVE_DISABLED';
err.info = info;
throw err;
}
if (!info.available) {
const err = new Error('BEAT_CACHE_DRIVE_UNAVAILABLE');
err.code = 'BEAT_CACHE_DRIVE_UNAVAILABLE';
err.info = info;
throw err;
}
fs.mkdirSync(info.dir, { recursive: true });
return info.dir;
}
function safeBeatMapCacheFile(key) {
const raw = String(key || '').trim();
if (!raw || raw.length > 240) return null;
const hash = crypto.createHash('sha1').update(raw).digest('hex');
const label = raw.replace(/[^a-z0-9_.-]+/gi, '_').replace(/^_+|_+$/g, '').slice(0, 48) || 'beatmap';
return path.join(ensureBeatMapCacheDir(), `${label}-${hash}.json`);
}
function compactBeatMapCachePayload(body) {
const key = String(body && body.key || '').trim();
const map = body && body.map;
if (!key || !map || typeof map !== 'object') return null;
return {
v: 1,
key,
savedAt: Date.now(),
meta: {
provider: String(body.provider || '').slice(0, 32),
title: String(body.title || '').slice(0, 160),
artist: String(body.artist || '').slice(0, 160),
mode: String(body.mode || 'mr').slice(0, 32),
},
map,
};
}
function readBeatMapCache(key) {
const file = safeBeatMapCacheFile(key);
if (!file || !fs.existsSync(file)) return null;
const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
return raw && raw.map ? raw : null;
}
function writeBeatMapCache(body) {
const payload = compactBeatMapCachePayload(body);
if (!payload) return { ok: false, error: 'INVALID_BEATMAP_CACHE_PAYLOAD' };
const file = safeBeatMapCacheFile(payload.key);
if (!file) return { ok: false, error: 'INVALID_BEATMAP_CACHE_KEY' };
const tmp = file + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(payload));
fs.renameSync(tmp, file);
return { ok: true, key: payload.key, savedAt: payload.savedAt, dir: path.dirname(file) };
}
function localUpdateFallback(reason, opts) {
opts = opts || {};
const configured = !!(opts.configured != null ? opts.configured : false);
return {
configured,
preview: UPDATE_CONFIG.preview,
updateAvailable: false,
currentVersion: APP_VERSION,
latestVersion: APP_VERSION,
release: {
tagName: 'v' + APP_VERSION,
name: 'Mineradio v' + APP_VERSION,
version: APP_VERSION,
htmlUrl: '',
downloadUrl: '',
summary: '当前版本,更新检测已就绪。',
notes: UPDATE_FALLBACK_NOTES,
},
reason: reason || '',
};
}
function updateError(code, message, cause) {
const err = new Error(message || code);
err.code = code;
if (cause) err.cause = cause;
return err;
}
function classifyUpdateError(err) {
const code = String(err && err.code || '').trim();
const message = String(err && err.message || err || '').trim();
const detail = message || code || '未知错误';
if (/HASH|DIGEST|CHECKSUM/i.test(code + ' ' + message)) {
return { code: code || 'UPDATE_HASH_MISMATCH', reason: '文件校验失败,可能是线路缓存异常,已拦截该安装包。', detail };
}
if (/SIZE_MISMATCH|content length/i.test(code + ' ' + message)) {
return { code: code || 'UPDATE_SIZE_MISMATCH', reason: '下载文件大小不一致,可能是网络中断或线路缓存不完整。', detail };
}
if (/AbortError|TIMEOUT|ETIMEDOUT|timeout/i.test(code + ' ' + message)) {
return { code: code || 'UPDATE_TIMEOUT', reason: '连接超时,当前网络到更新线路不稳定。', detail };
}
if (/ENOTFOUND|EAI_AGAIN|DNS|fetch failed|getaddrinfo/i.test(code + ' ' + message)) {
return { code: code || 'UPDATE_DNS_FAILED', reason: '域名解析失败,可能是当前网络无法连接该更新线路。', detail };
}
if (/ECONNRESET|ECONNREFUSED|socket|network/i.test(code + ' ' + message)) {
return { code: code || 'UPDATE_NETWORK_FAILED', reason: '网络连接被中断,已尝试切换更新线路。', detail };
}
const http = message.match(/\bHTTP[_\s-]?(\d{3})\b/i) || message.match(/\b(\d{3})\b/);
if (http) {
const status = Number(http[1]);
if (status === 403) return { code: code || 'UPDATE_HTTP_403', reason: '更新线路返回 403,可能被限流或拦截。', detail };
if (status === 404) return { code: code || 'UPDATE_HTTP_404', reason: '更新文件不存在,可能 release 资源还没有同步完成。', detail };
if (status >= 500) return { code: code || 'UPDATE_HTTP_5XX', reason: '更新线路服务器异常,请稍后重试。', detail };
return { code: code || ('UPDATE_HTTP_' + status), reason: '更新线路返回 HTTP ' + status + '。', detail };
}
return { code: code || 'UPDATE_FAILED', reason: '更新失败:' + detail, detail };
}
async function fetchWithTimeout(url, opts, timeoutMs) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs || 12000);
try {
return await fetch(url, Object.assign({}, opts || {}, { signal: controller.signal }));
} finally {
clearTimeout(timer);
}
}
async function fetchTextFromCandidates(candidates, timeoutMs) {
const list = Array.isArray(candidates) && candidates.length ? candidates : [];
const failures = [];
for (let i = 0; i < list.length; i++) {
const candidate = list[i];
try {
const resp = await fetchWithTimeout(candidate.url, {
headers: { 'User-Agent': `Mineradio/${APP_VERSION}` },
}, timeoutMs || 6500);
if (!resp.ok) throw updateError('HTTP_' + resp.status, 'HTTP ' + resp.status);
return { text: await resp.text(), candidate };
} catch (err) {
const info = classifyUpdateError(err);
failures.push(candidate.label + ': ' + info.reason);
}
}
throw updateError('UPDATE_ALL_LINES_FAILED', failures.join(';') || 'All update lines failed');
}
function yamlScalar(text, key) {
const pattern = new RegExp('^\\s*' + key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\s*:\\s*(.+?)\\s*$', 'm');
const match = String(text || '').match(pattern);
if (!match) return '';
return match[1].trim().replace(/^['"]|['"]$/g, '');
}
function githubReleaseDownloadUrl(version, fileName) {
const tag = 'v' + normalizeVersion(version);
const encodedOwner = encodeURIComponent(UPDATE_CONFIG.owner);
const encodedRepo = encodeURIComponent(UPDATE_CONFIG.repo);
const encodedName = String(fileName || '').split('/').map(part => encodeURIComponent(part)).join('/');
return `https://github.com/${encodedOwner}/${encodedRepo}/releases/download/${tag}/${encodedName}`;
}
function parseLatestYmlUpdateInfo(text, reason) {
const latestVersion = normalizeVersion(yamlScalar(text, 'version') || APP_VERSION) || APP_VERSION;
const assetPath = yamlScalar(text, 'path') || yamlScalar(text, 'url') || `Mineradio-${latestVersion}-Setup.exe`;
const sha512 = normalizeDigest(yamlScalar(text, 'sha512'), 'sha512');
const size = Number(yamlScalar(text, 'size') || 0) || 0;
const releaseDate = yamlScalar(text, 'releaseDate');
const downloadUrl = githubReleaseDownloadUrl(latestVersion, assetPath);
const candidates = uniqueDownloadCandidates(downloadUrl);
const asset = {
name: updateAssetNameFromUrl(downloadUrl) || assetPath,
size,
contentType: 'application/octet-stream',
downloadUrl,
downloadUrls: publicDownloadUrls(candidates),
sha256: '',
sha512,
};
return {
configured: true,
preview: false,
updateAvailable: compareVersions(latestVersion, APP_VERSION) > 0,
currentVersion: APP_VERSION,
latestVersion,
release: {
tagName: 'v' + latestVersion,
name: 'Mineradio v' + latestVersion,
version: latestVersion,
publishedAt: releaseDate,
htmlUrl: `https://github.com/${UPDATE_CONFIG.owner}/${UPDATE_CONFIG.repo}/releases/tag/v${latestVersion}`,
downloadUrl,
asset,
patch: null,
patchAvailable: false,
summary: '发现新版本,已启用备用更新线路。',
notes: ['更新检测已切换到备用线路', '下载时会自动选择国内加速线路', '下载失败会显示具体原因和当前速度'],
},
source: 'latest-yml',
reason: reason || '',
};
}
async function fetchLatestYmlUpdateInfo(reason) {
if (!UPDATE_CONFIG.configured || UPDATE_CONFIG.provider !== 'github') throw updateError('UPDATE_REPOSITORY_NOT_CONFIGURED');
const latestYmlUrl = `https://github.com/${encodeURIComponent(UPDATE_CONFIG.owner)}/${encodeURIComponent(UPDATE_CONFIG.repo)}/releases/latest/download/latest.yml`;
const candidates = uniqueDownloadCandidates(latestYmlUrl);
const result = await fetchTextFromCandidates(candidates, 6500);
return parseLatestYmlUpdateInfo(result.text, reason);
}
async function fetchLatestUpdateInfo() {
if (UPDATE_CONFIG.manifest) return fetchManifestUpdateInfo(UPDATE_CONFIG.manifest);
if (!UPDATE_CONFIG.configured || UPDATE_CONFIG.provider !== 'github') return localUpdateFallback();
const apiUrl = `https://api.github.com/repos/${encodeURIComponent(UPDATE_CONFIG.owner)}/${encodeURIComponent(UPDATE_CONFIG.repo)}/releases/latest`;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 8500);
try {
const resp = await fetch(apiUrl, {
signal: controller.signal,
headers: {
'User-Agent': `Mineradio/${APP_VERSION}`,
'Accept': 'application/vnd.github+json',
},
});
if (!resp.ok) {
try { return await fetchLatestYmlUpdateInfo('GitHub Releases ' + resp.status); }
catch (_) { return localUpdateFallback('GitHub Releases ' + resp.status, { configured: true }); }
}
const data = await resp.json();
const latestVersion = normalizeVersion(data.tag_name || data.name || APP_VERSION) || APP_VERSION;
const asset = pickReleaseAsset(data.assets);
const patch = pickPatchAsset(data.assets, APP_VERSION, latestVersion);
const notes = extractReleaseNotes(data.body).length ? extractReleaseNotes(data.body) : UPDATE_FALLBACK_NOTES;
return {
configured: true,
preview: false,
updateAvailable: compareVersions(latestVersion, APP_VERSION) > 0,
currentVersion: APP_VERSION,
latestVersion,
release: {
tagName: data.tag_name || ('v' + latestVersion),
name: data.name || ('Mineradio v' + latestVersion),
version: latestVersion,
publishedAt: data.published_at || '',
htmlUrl: data.html_url || '',
downloadUrl: asset ? asset.downloadUrl : '',
asset,
patch,
patchAvailable: !!(patch && patch.downloadUrl && compareVersions(latestVersion, APP_VERSION) > 0),
summary: notes[0] || '发现新版本,建议更新。',
notes,
},
};
} catch (err) {
const reason = err && err.message || 'Update check failed';
try { return await fetchLatestYmlUpdateInfo(reason); }
catch (fallbackErr) { return localUpdateFallback((fallbackErr && fallbackErr.message) || reason, { configured: true }); }
} finally {
clearTimeout(timer);
}
}
function safeUpdateFileName(name, version) {
const raw = String(name || '').trim() || `Mineradio-${version || APP_VERSION}.exe`;
const cleaned = raw
.replace(/[<>:"/\\|?*\x00-\x1F]/g, '-')
.replace(/\s+/g, ' ')
.trim()
.slice(0, 160);
return cleaned || `Mineradio-${version || APP_VERSION}.exe`;
}
function publicUpdateJob(job) {
if (!job) return { ok: false, error: 'UPDATE_JOB_NOT_FOUND' };
return {
ok: job.status !== 'error',
id: job.id,
status: job.status,
progress: job.progress || 0,
received: job.received || 0,
total: job.total || 0,
speedBps: job.speedBps || 0,
etaSeconds: job.etaSeconds || 0,
sourceLabel: job.sourceLabel || '',
attempt: job.attempt || 0,
attempts: job.attempts || 0,
mode: job.mode || 'installer',
message: job.message || '',
restartRequired: !!job.restartRequired,
cached: !!job.cached,
fileName: job.fileName || '',
filePath: job.status === 'ready' ? job.filePath : '',
version: job.version || '',
releaseUrl: job.releaseUrl || '',
error: job.error || '',
errorReason: job.errorReason || '',
errorDetail: job.errorDetail || '',
failedAttempts: Array.isArray(job.failedAttempts) ? job.failedAttempts.slice(0, 6) : [],
createdAt: job.createdAt,
updatedAt: job.updatedAt,
};
}
function activeUpdateJobFor(version) {
const jobs = Array.from(updateDownloadJobs.values()).sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0));
return jobs.find(job => job.version === version && (job.status === 'queued' || job.status === 'downloading' || job.status === 'ready'));
}
function trimUpdateJobs() {
const jobs = Array.from(updateDownloadJobs.values()).sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0));
jobs.slice(8).forEach(job => updateDownloadJobs.delete(job.id));
}
async function downloadUpdateAsset(job) {
const tmpPath = job.filePath + '.download';
try {
fs.mkdirSync(UPDATE_DOWNLOAD_DIR, { recursive: true });
job.status = 'downloading';
job.updatedAt = Date.now();
const resp = await fetch(job.downloadUrl, {
headers: {
'User-Agent': `Mineradio/${APP_VERSION}`,
},
});
if (!resp.ok) throw new Error('Download failed ' + resp.status);
const totalHeader = parseInt(resp.headers.get('content-length') || '0', 10) || 0;
job.total = totalHeader || job.total || 0;
job.received = 0;
job.progress = 0;
job.speedBps = 0;
job.etaSeconds = 0;
job.message = job.total ? '正在下载完整安装包' : '正在下载完整安装包,等待服务器返回大小';
job.updatedAt = Date.now();
let speedWindowAt = Date.now();
let speedWindowBytes = 0;
const writer = fs.createWriteStream(tmpPath);
const reader = resp.body.getReader();
try {
while (true) {
const chunk = await reader.read();
if (chunk.done) break;
const buf = Buffer.from(chunk.value);
job.received += buf.length;
speedWindowBytes += buf.length;
const now = Date.now();
if (now - speedWindowAt >= 900) {
job.speedBps = Math.round(speedWindowBytes / Math.max(0.001, (now - speedWindowAt) / 1000));
speedWindowAt = now;
speedWindowBytes = 0;
}
if (job.total > 0) {
job.progress = Math.max(1, Math.min(99, Math.round((job.received / job.total) * 100)));
job.etaSeconds = job.speedBps > 0 ? Math.max(0, Math.round((job.total - job.received) / job.speedBps)) : 0;
} else {
const kb = Math.max(1, job.received / 1024);
job.progress = Math.max(1, Math.min(88, Math.round(Math.log10(kb + 1) * 24)));
}
job.message = job.total > 0 ? '正在下载完整安装包' : '正在下载完整安装包,服务器未提供总大小';
job.updatedAt = Date.now();
if (!writer.write(buf)) await once(writer, 'drain');
}
} finally {
writer.end();
await once(writer, 'finish').catch(() => {});
}
if (fs.existsSync(job.filePath)) fs.unlinkSync(job.filePath);
fs.renameSync(tmpPath, job.filePath);
job.status = 'ready';
job.progress = 100;
job.message = '安装包已下载';
job.updatedAt = Date.now();
} catch (e) {
try { if (fs.existsSync(tmpPath)) fs.unlinkSync(tmpPath); } catch (_) {}
job.status = 'error';
job.error = e.message || 'UPDATE_DOWNLOAD_FAILED';
job.updatedAt = Date.now();
}
}
function sha512Base64(buffer) {
return crypto.createHash('sha512').update(buffer).digest('base64');
}
function sha512Hex(buffer) {
return crypto.createHash('sha512').update(buffer).digest('hex');
}
function verifyUpdateBuffer(buffer, job) {
const expectedSize = Number(job.expectedSize || job.total || 0) || 0;
if (expectedSize > 0 && buffer.length !== expectedSize) {
throw updateError('UPDATE_SIZE_MISMATCH', `Expected ${expectedSize} bytes, got ${buffer.length}`);
}
const expectedSha256 = normalizeDigest(job.sha256 || '', 'sha256').toLowerCase();
if (expectedSha256 && sha256Hex(buffer) !== expectedSha256) {
throw updateError('UPDATE_SHA256_MISMATCH', 'Downloaded sha256 mismatch');
}
const expectedSha512 = normalizeDigest(job.sha512 || '', 'sha512');
if (expectedSha512) {
const actualBase64 = sha512Base64(buffer);
const actualHex = sha512Hex(buffer).toLowerCase();
if (actualBase64 !== expectedSha512 && actualHex !== expectedSha512.toLowerCase()) {
throw updateError('UPDATE_SHA512_MISMATCH', 'Downloaded sha512 mismatch');
}
}
}
function verifyUpdateFile(filePath, job) {
verifyUpdateBuffer(fs.readFileSync(filePath), job);
}
function moveInvalidUpdateFile(filePath, reason) {
try {
if (!filePath || !fs.existsSync(filePath)) return;
const dir = path.dirname(filePath);
const ext = path.extname(filePath);
const base = path.basename(filePath, ext);
const invalidPath = path.join(dir, `${base}.invalid-${Date.now()}${ext || '.bin'}`);
fs.renameSync(filePath, invalidPath);
console.warn('[UpdateDownload] cached installer moved aside:', reason || 'invalid', invalidPath);
} catch (e) {
console.warn('[UpdateDownload] failed to move invalid cached installer:', e.message);
}
}
function reuseVerifiedInstallerJob(opts) {
if (!opts || !opts.filePath || !fs.existsSync(opts.filePath)) return null;
if (!opts.expectedSize && !opts.sha256 && !opts.sha512) return null;
const now = Date.now();
const stat = fs.statSync(opts.filePath);
const job = {
id: 'cached-' + now.toString(36) + '-' + Math.random().toString(36).slice(2, 8),
status: 'ready',
progress: 100,
received: stat.size || 0,
total: opts.expectedSize || stat.size || 0,
speedBps: 0,
etaSeconds: 0,
sourceLabel: '本地缓存',
attempt: 0,
attempts: opts.attempts || 0,
mode: 'installer',
message: '安装包已下载,可直接打开安装',
fileName: opts.fileName || path.basename(opts.filePath),
filePath: opts.filePath,
version: opts.version || '',
downloadUrl: opts.downloadUrl || '',
downloadCandidates: opts.downloadCandidates || [],
expectedSize: opts.expectedSize || 0,
sha256: opts.sha256 || '',
sha512: opts.sha512 || '',
releaseUrl: opts.releaseUrl || '',
failedAttempts: [],
cached: true,
createdAt: now,
updatedAt: now,
error: '',
};
try {
verifyUpdateFile(opts.filePath, job);
updateDownloadJobs.set(job.id, job);
trimUpdateJobs();
return job;
} catch (err) {
moveInvalidUpdateFile(opts.filePath, (err && err.message) || 'cache verification failed');
return null;
}
}
function setUpdateJobError(job, err, fallbackMessage) {
const info = classifyUpdateError(err);
job.status = 'error';
job.error = info.code;
job.errorReason = info.reason;
job.errorDetail = info.detail;