-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathserver.js
More file actions
1328 lines (1270 loc) · 56.7 KB
/
Copy pathserver.js
File metadata and controls
1328 lines (1270 loc) · 56.7 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';
/*
WallHub server.js v4.1
─────────────────────────────────────────────────────────────────
两步策略:
1. 抓 workshop/browse HTML → 提取 FileID 列表 (带详细调试)
2. POST GetPublishedFileDetails (无需key) → 批量拿真实数据
调试接口: GET /api/debug → 查看原始HTML结构
*/
const http = require('http');
const https = require('https');
const tls = require('tls');
const fs = require('fs');
const path = require('path');
const os = require('os');
const { spawn, execFileSync } = require('child_process');
const { URL } = require('url');
const PORT = process.env.PORT ? parseInt(process.env.PORT) : 3090;
const PUBLIC = path.join(__dirname, 'public');
const DOWNLOAD_DIR = path.join(__dirname, 'downloads');
const PERSONA_CACHE = new Map();
const STEAM_PREF_COOKIE = [
'birthtime=946684801',
'lastagecheckage=1-January-2000',
'mature_content=1',
'wants_mature_content=1',
'wants_mature_content_violence=1',
'wants_mature_content_sex=1',
'wants_adult_content=1',
'wants_adult_content_violence=1',
'wants_adult_content_sex=1',
'wants_community_generated_adult_content=1',
process.env.STEAM_COUNTRY ? `steamCountry=${process.env.STEAM_COUNTRY}` : '',
`Steam_Language=${process.env.STEAM_LANG || 'schinese'}`,
'timezoneOffset=28800,0',
].filter(Boolean).join('; ');
// ─── CORS + helpers ────────────────────────────────────────────────
function cors(res) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
}
function send(res, code, body, ct) {
cors(res);
res.writeHead(code, { 'Content-Type': ct || 'text/plain; charset=utf-8' });
res.end(body);
}
function jsonRes(res, code, obj) {
send(res, code, JSON.stringify(obj), 'application/json; charset=utf-8');
}
function readBody(req) {
return new Promise((res, rej) => {
let s = '';
req.on('data', c => s += c);
req.on('end', () => res(s));
req.on('error', rej);
});
}
function mimeType(p) {
return ({'.html':'text/html; charset=utf-8','.js':'application/javascript; charset=utf-8',
'.css':'text/css; charset=utf-8','.json':'application/json; charset=utf-8',
'.svg':'image/svg+xml','.png':'image/png','.jpg':'image/jpeg','.ico':'image/x-icon'}
[path.extname(p).toLowerCase()]) || 'application/octet-stream';
}
// ─── HTTP ──────────────────────────────────────────────────────────
const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36';
function parseProxyUrl(raw) {
if (!raw) return null;
let v = String(raw).trim();
if (!v) return null;
if (!/^[a-z]+:\/\//i.test(v)) v = `http://${v}`;
try {
const u = new URL(v);
if (!u.hostname) return null;
return {
protocol: (u.protocol || 'http:').toLowerCase(),
hostname: u.hostname,
port: u.port ? parseInt(u.port) : ((u.protocol || '').toLowerCase() === 'https:' ? 443 : 80),
username: decodeURIComponent(u.username || ''),
password: decodeURIComponent(u.password || ''),
};
} catch {
return null;
}
}
function parseWinProxyServer(raw, protocol) {
const v = String(raw || '').trim();
if (!v) return null;
const map = {};
for (const seg of v.split(';').map(s => s.trim()).filter(Boolean)) {
const m = seg.match(/^([^=]+)=(.+)$/);
if (m) map[m[1].toLowerCase()] = m[2].trim();
}
const key = protocol === 'https:' ? 'https' : 'http';
const pick = map[key] || map.http || map.https || (Object.keys(map).length ? '' : v);
return parseProxyUrl(pick);
}
function readWindowsSystemProxy(protocol) {
if (process.platform !== 'win32') return null;
try {
const enable = execFileSync(
'reg.exe',
['query', 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings', '/v', 'ProxyEnable'],
{ encoding: 'utf8' }
);
if (!/\b0x1\b/i.test(enable)) return null;
const server = execFileSync(
'reg.exe',
['query', 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings', '/v', 'ProxyServer'],
{ encoding: 'utf8' }
);
const m = server.match(/ProxyServer\s+REG_\w+\s+([^\r\n]+)/i);
return m ? parseWinProxyServer(m[1], protocol) : null;
} catch {
return null;
}
}
function resolveProxyForProtocol(protocol) {
const isHttps = protocol === 'https:';
const envRaw = isHttps
? (process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy || process.env.ALL_PROXY || process.env.all_proxy || '')
: (process.env.HTTP_PROXY || process.env.http_proxy || process.env.ALL_PROXY || process.env.all_proxy || '');
return parseProxyUrl(envRaw) || readWindowsSystemProxy(protocol);
}
function proxyAuth(proxy) {
if (!proxy || !proxy.username) return '';
const token = Buffer.from(`${proxy.username}:${proxy.password || ''}`, 'utf8').toString('base64');
return `Basic ${token}`;
}
function formatProxyUrl(proxy) {
if (!proxy || !proxy.hostname) return '';
const auth = proxy.username
? `${encodeURIComponent(proxy.username)}:${encodeURIComponent(proxy.password || '')}@`
: '';
return `http://${auth}${proxy.hostname}:${proxy.port || 80}`;
}
function proxyKey(proxy) {
if (!proxy) return 'direct';
return `${proxy.protocol || 'http:'}|${proxy.hostname}|${proxy.port || 80}|${proxy.username || ''}|${proxy.password || ''}`;
}
function getProxyCandidates(protocol, hostname) {
const list = [];
const add = (p) => { if (p && p.hostname) list.push(p); };
const customProxyHost = String(process.env.WALLHUB_PROXY_HOST || '').trim();
add(parseProxyUrl(process.env.WALLHUB_PROXY || process.env.wallhub_proxy || ''));
const resolved = resolveProxyForProtocol(protocol);
add(resolved);
if (customProxyHost && resolved && /^(127\.0\.0\.1|localhost)$/i.test(resolved.hostname)) {
add(parseProxyUrl(`http://${customProxyHost}:${resolved.port || 80}`));
}
const extraPortsRaw = String(process.env.WALLHUB_PROXY_PORTS || '').trim();
if (extraPortsRaw && process.platform === 'win32') {
const ports = extraPortsRaw
.split(',')
.map(s => parseInt(String(s).trim()))
.filter(n => n > 0 && n < 65536);
const hosts = customProxyHost ? ['127.0.0.1', 'localhost', customProxyHost] : ['127.0.0.1', 'localhost'];
for (const p of ports) {
for (const h of hosts) add(parseProxyUrl(`http://${h}:${p}`));
}
}
const seen = new Set();
const uniq = [];
for (const p of list) {
const k = proxyKey(p);
if (seen.has(k)) continue;
seen.add(k);
uniq.push(p);
}
if (!(isSteamHost(hostname) && uniq.length > 0)) uniq.push(null);
return uniq;
}
function shouldRetryWithNextProxy(err) {
if (!err) return false;
if (err.code && ['ECONNREFUSED', 'ETIMEDOUT', 'ECONNRESET', 'EHOSTUNREACH', 'ENETUNREACH', 'EPIPE', 'EPROTO'].includes(err.code)) return true;
const m = String(err.message || '');
return /Proxy CONNECT|ECONNREFUSED|ETIMEDOUT|socket hang up/i.test(m);
}
function isSteamHost(hostname) {
const h = String(hostname || '').toLowerCase();
return h.includes('steamcommunity.com') || h.includes('steampowered.com') || h.includes('steamusercontent.com');
}
function buildUrlFromOpts(opts) {
const protocol = opts.protocol || 'https:';
const port = opts.port ? `:${opts.port}` : '';
return `${protocol}//${opts.hostname}${port}${opts.path || '/'}`;
}
function doRequestByCurl(opts, body, timeout, proxy) {
return new Promise((resolve, reject) => {
const url = buildUrlFromOpts(opts);
const args = [
'--silent',
'--show-error',
'--location',
'--max-time', String(Math.max(8, Math.ceil((timeout || 22000) / 1000))),
'--request', opts.method || 'GET',
'--url', url,
'--output', '-',
'--write-out', '\n__WALLHUB_HTTP_CODE__:%{http_code}',
];
if (proxy && proxy.hostname) args.push('--proxy', formatProxyUrl(proxy));
const headers = opts.headers || {};
for (const [k, v] of Object.entries(headers)) {
if (v === undefined || v === null || v === '') continue;
args.push('-H', `${k}: ${String(v)}`);
}
if (body && String(opts.method || 'GET').toUpperCase() !== 'GET') {
const payload = Buffer.isBuffer(body) ? body.toString('utf8') : String(body);
args.push('--data-binary', payload);
}
const cp = spawn('curl.exe', args, { windowsHide: true, env: Object.assign({}, process.env) });
const chunks = [];
let err = '';
cp.stdout.on('data', d => chunks.push(Buffer.from(d)));
cp.stderr.on('data', d => err += d.toString());
cp.on('error', e => reject(e));
cp.on('close', code => {
const raw = Buffer.concat(chunks).toString('utf8');
const marker = '\n__WALLHUB_HTTP_CODE__:';
const idx = raw.lastIndexOf(marker);
const httpCode = idx >= 0 ? parseInt(raw.slice(idx + marker.length).trim()) : 0;
const bodyText = idx >= 0 ? raw.slice(0, idx) : raw;
if (code !== 0) return reject(new Error((err || `curl exit ${code}`).trim().slice(-1200)));
if (httpCode < 200 || httpCode >= 300) return reject(new Error(`HTTP ${httpCode || 502}`));
resolve(Buffer.from(bodyText, 'utf8'));
});
});
}
function doRequestByCurlCascade(opts, body, timeout, proxies, idx) {
const i = idx || 0;
const proxy = proxies[Math.min(i, proxies.length - 1)];
return doRequestByCurl(opts, body, timeout, proxy).catch((e) => {
if (shouldRetryWithNextProxy(e) && i + 1 < proxies.length) {
return doRequestByCurlCascade(opts, body, timeout, proxies, i + 1);
}
throw e;
});
}
const AUTO_PROXY = resolveProxyForProtocol('https:') || resolveProxyForProtocol('http:');
if (AUTO_PROXY) {
const auto = formatProxyUrl(AUTO_PROXY);
if (auto) {
if (!process.env.HTTP_PROXY && !process.env.http_proxy) {
process.env.HTTP_PROXY = auto;
process.env.http_proxy = auto;
}
if (!process.env.HTTPS_PROXY && !process.env.https_proxy) {
process.env.HTTPS_PROXY = auto;
process.env.https_proxy = auto;
}
if (!process.env.ALL_PROXY && !process.env.all_proxy) {
process.env.ALL_PROXY = auto;
process.env.all_proxy = auto;
}
}
}
function doRequest(opts, body, redirects, proxyIndex) {
const redirectCount = redirects || 0;
const currentProxyIndex = proxyIndex || 0;
const protocol = opts.protocol || 'https:';
const timeout = opts.timeout || 22000;
const proxies = getProxyCandidates(protocol, opts.hostname);
const proxy = proxies[Math.min(currentProxyIndex, proxies.length - 1)];
const attemptTimeout = proxy ? Math.min(timeout, 12000) : timeout;
if (process.platform === 'win32' && process.env.WALLHUB_DISABLE_CURL_PROXY !== '1') {
return doRequestByCurlCascade(opts, body, attemptTimeout, proxies, currentProxyIndex);
}
return new Promise((resolve, reject) => {
const retryNext = (err) => {
if (shouldRetryWithNextProxy(err) && currentProxyIndex + 1 < proxies.length) {
return doRequest(opts, body, redirectCount, currentProxyIndex + 1).then(resolve).catch(reject);
}
reject(err);
};
const onResponse = (rs) => {
if (rs.statusCode >= 300 && rs.statusCode < 400 && rs.headers.location) {
rs.resume();
if (redirectCount >= 3) return reject(new Error('Too many redirects'));
let loc = rs.headers.location;
if (!/^https?:\/\//i.test(loc)) loc = `${protocol}//${opts.hostname}${loc}`;
try {
const u = new URL(loc);
return doRequest({
protocol: u.protocol,
hostname: u.hostname,
port: u.port ? parseInt(u.port) : undefined,
path: u.pathname + u.search,
method: 'GET',
headers: opts.headers,
timeout,
}, null, redirectCount + 1, 0)
.then(resolve).catch(reject);
} catch(e) { return reject(e); }
}
if (rs.statusCode < 200 || rs.statusCode >= 300) { rs.resume(); return reject(new Error(`HTTP ${rs.statusCode}`)); }
const bufs = [];
rs.on('data', d => bufs.push(d));
rs.on('end', () => resolve(Buffer.concat(bufs)));
rs.on('error', retryNext);
};
const onError = (e) => retryNext(e);
const writeEnd = (req) => {
req.on('error', onError);
req.on('timeout', () => req.destroy(new Error('Timeout')));
if (body) req.write(body);
req.end();
};
if (!proxy) {
const mod = protocol === 'http:' ? http : https;
const req = mod.request({
protocol,
hostname: opts.hostname,
port: opts.port || (protocol === 'http:' ? 80 : 443),
path: opts.path,
method: opts.method || 'GET',
headers: opts.headers || {},
timeout: attemptTimeout,
}, onResponse);
writeEnd(req);
return;
}
const auth = proxyAuth(proxy);
if (protocol === 'http:') {
const headers = Object.assign({}, opts.headers || {});
if (auth) headers['Proxy-Authorization'] = auth;
const fullPath = `${protocol}//${opts.hostname}${opts.port ? `:${opts.port}` : ''}${opts.path || '/'}`;
const req = http.request({
hostname: proxy.hostname,
port: proxy.port || 80,
method: opts.method || 'GET',
path: fullPath,
headers,
timeout: attemptTimeout,
}, onResponse);
writeEnd(req);
return;
}
const connectHeaders = {};
if (auth) connectHeaders['Proxy-Authorization'] = auth;
const connectReq = http.request({
hostname: proxy.hostname,
port: proxy.port || 80,
method: 'CONNECT',
path: `${opts.hostname}:${opts.port || 443}`,
headers: connectHeaders,
timeout: attemptTimeout,
});
connectReq.on('connect', (res, socket) => {
if (res.statusCode !== 200) {
socket.destroy();
return reject(new Error(`Proxy CONNECT ${res.statusCode}`));
}
const secureSocket = tls.connect({
socket,
servername: opts.hostname,
});
secureSocket.on('error', onError);
const req = https.request({
hostname: opts.hostname,
port: opts.port || 443,
path: opts.path,
method: opts.method || 'GET',
headers: opts.headers || {},
createConnection: () => secureSocket,
agent: false,
timeout: attemptTimeout,
}, onResponse);
writeEnd(req);
});
connectReq.on('error', onError);
connectReq.on('timeout', () => connectReq.destroy(new Error('Timeout')));
connectReq.end();
});
}
function GET(url, extra, timeout) {
const u = new URL(url);
return doRequest({
protocol: u.protocol,
hostname: u.hostname,
port: u.port ? parseInt(u.port) : undefined,
path: u.pathname + u.search,
method: 'GET',
headers: Object.assign({
'User-Agent': UA, 'Accept-Language': 'zh-CN,zh;q=0.9', 'Accept-Encoding': 'identity',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Cookie': STEAM_PREF_COOKIE,
}, extra || {}),
timeout: timeout || 22000,
});
}
function POST(url, body, timeout) {
const u = new URL(url);
const buf = Buffer.from(body, 'utf8');
return doRequest({
protocol: u.protocol,
hostname: u.hostname,
port: u.port ? parseInt(u.port) : undefined,
path: u.pathname + u.search,
method: 'POST',
headers: {
'User-Agent': UA, 'Accept-Encoding': 'identity', 'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': buf.length,
},
timeout: timeout || 22000,
}, buf);
}
// ─────────────────────────────────────────────────────────────────
// GetPublishedFileDetails (POST, no API key required!)
// Returns: preview_url, title, subscriptions, views, favorited, file_size, tags, etc.
// ─────────────────────────────────────────────────────────────────
async function getFileDetails(ids, timeoutMs) {
if (!ids.length) return [];
const parts = [`itemcount=${ids.length}`];
ids.forEach((id, i) => parts.push(`publishedfileids%5B${i}%5D=${id}`));
console.log(`[FileDetails] POST for ${ids.length} ids: ${ids.slice(0,3).join(',')}...`);
const buf = await POST(
'https://api.steampowered.com/ISteamRemoteStorage/GetPublishedFileDetails/v1/',
parts.join('&'), timeoutMs || 25000
);
const data = JSON.parse(buf.toString('utf8'));
const list = (data.response && data.response.publishedfiledetails) || [];
const withThumb = list.filter(d => d.preview_url).length;
console.log(`[FileDetails] Got ${list.length} records, ${withThumb} with preview_url`);
if (list[0]) {
console.log(`[FileDetails] Sample[0]: title="${list[0].title}", preview="${list[0].preview_url ? list[0].preview_url.substring(0,60)+'...' : 'NONE'}"`);
}
return list;
}
async function getFileDetailsSafe(ids) {
const uniqIds = Array.from(new Set((ids || []).map(v => String(v).trim()).filter(Boolean)));
if (!uniqIds.length) return [];
let list = [];
try {
list = await getFileDetails(uniqIds, 9000);
} catch (e) {
console.warn('[FileDetails] Batch failed:', e.message);
}
const okCount = list.filter(d => d && d.result === 1).length;
if (okCount > 0 || uniqIds.length <= 3) return list;
const merged = {};
const chunkSize = 8;
const chunks = [];
for (let i = 0; i < uniqIds.length; i += chunkSize) chunks.push(uniqIds.slice(i, i + chunkSize));
const parts = await Promise.all(chunks.map((chunk, idx) =>
getFileDetails(chunk, 7000).catch((e) => {
console.warn(`[FileDetails] Chunk ${idx + 1} failed:`, e.message);
return [];
})
));
parts.forEach(part => part.forEach(d => { if (d && d.publishedfileid) merged[String(d.publishedfileid)] = d; }));
const fallbackList = uniqIds.map(id => merged[id]).filter(Boolean);
console.log(`[FileDetails] Safe fallback merged ${fallbackList.length}/${uniqIds.length}`);
return fallbackList;
}
// ─────────────────────────────────────────────────────────────────
// Scrape workshop/browse → extract FileIDs + real total count
// ─────────────────────────────────────────────────────────────────
async function scrapeIds(params) {
const sortMap = { 1:'trend', 2:'mostrecent', 21:'lastupdated', 16:'totaluniquesubscribers' };
const sort = sortMap[parseInt(params.query_type)] || 'trend';
const page = parseInt(params.page) || 1;
const appId = params.appid || 431960;
const qs = [
`appid=${appId}`,
`browsesort=${sort}`,
`section=readytouseitems`,
`actualsort=${sort}`,
`p=${page}`,
`numperpage=${params.numperpage || 30}`,
];
if (params.search_text) qs.push(`searchtext=${encodeURIComponent(params.search_text)}`);
if (params.days && sort === 'trend' && String(params.days) !== '0') qs.push(`days=${params.days}`);
// Required tags logic:
// If user selects too many tags (e.g. "Select All"), Steam often returns 0 results.
// We'll clear the tags if count > 8, assuming the user wants to see everything.
const tags = [];
for (const [k, v] of Object.entries(params)) {
if (/^requiredtags/.test(k) && v) tags.push(String(v));
}
if (tags.length > 8) {
console.log(`[Scrape] Too many tags (${tags.length}), clearing filter to show all.`);
// Don't add to qs
} else {
tags.forEach(t => qs.push(`requiredtags[]=${encodeURIComponent(t)}`));
}
const url = `https://steamcommunity.com/workshop/browse/?${qs.join('&')}`;
console.log(`[Scrape] ${url}`);
const html = (await GET(url)).toString('utf8');
// ── Extract real total_count from Steam HTML ──
// Steam renders something like: "Showing 1-30 of 45,678 entries"
// or: <div class="workshopBrowsePagingInfo">Showing 1-30 of 45,678 entries</div>
// Also: data in the paging summary text
let totalCount = 0;
// Pattern 1: English "Showing X-Y of Z entries"
const showingM = html.match(/[Ss]howing\s+[\d,]+-[\d,]+\s+of\s+([\d,]+)/);
if (showingM) totalCount = parseInt(showingM[1].replace(/,/g,''));
// Pattern 1b: Chinese "显示第 1-30 项,共 1,234 项" or similar
if (!totalCount) {
const cnM = html.match(/共\s*([\d,]+)\s*(?:项|条|个)/);
if (cnM) totalCount = parseInt(cnM[1].replace(/,/g,''));
}
// Pattern 2: workshopBrowsePagingInfo div
if (!totalCount) {
const pagingM = html.match(/workshopBrowsePagingInfo[^>]*>([\s\S]*?)<\/div>/);
if (pagingM) {
const numM = pagingM[1].match(/([\d,]+)\s*(?:entries|条|项)/i);
if (numM) totalCount = parseInt(numM[1].replace(/,/g,''));
}
}
// Pattern 3: paging_controls total
if (!totalCount) {
const pageCtrl = html.match(/paging_controls[\s\S]{0,500}?([\d,]+)\s*(?:results|entries|items)/i);
if (pageCtrl) totalCount = parseInt(pageCtrl[1].replace(/,/g,''));
}
// Pattern 4: any standalone large number in paging section
if (!totalCount) {
const pageSec = html.match(/workshop(?:BrowsePaging|Paging)[^]*?(\d[\d,]{3,})/);
if (pageSec) totalCount = parseInt(pageSec[1].replace(/,/g,''));
}
// Extract all publishedfileids
const seen = new Set();
const ids = [];
const hints = {};
for (const m of html.matchAll(/data-publishedfileid="(\d+)"/g)) {
const id = m[1];
if (seen.has(id)) continue;
seen.add(id);
ids.push(id);
const idx = typeof m.index === 'number' ? m.index : -1;
if (idx >= 0) {
const block = html.substring(Math.max(0, idx - 280), idx + 3400);
const titleM = block.match(/class="workshopItemTitle[^"]*"[^>]*>([\s\S]*?)<\/div>/i);
const imgM = block.match(/class="workshopItemPreviewImage[^"]*"[^>]+src="([^"]+)"/i) ||
block.match(/<img[^>]+src="([^"]+)"[^>]*>/i);
const authorM = block.match(/class="workshopItemAuthorName[^"]*"[\s\S]{0,1200}?<a[^>]*>([\s\S]*?)<\/a>/i);
const creatorM = block.match(/workshop_author_link[^"]*"[^>]+href="[^"]*\/profiles\/(\d{17})\/?/i);
hints[id] = {
title: cleanText(titleM ? titleM[1] : ''),
preview_url: imgM ? cleanText(imgM[1]) : '',
author: cleanText(authorM ? authorM[1] : ''),
creator: creatorM ? creatorM[1] : '',
};
}
}
console.log(`[Scrape] Found ${ids.length} IDs, totalCount from HTML: ${totalCount}`);
// Debug img tags
const firstIdx = html.indexOf('data-publishedfileid');
if (firstIdx !== -1) {
const block = html.substring(Math.max(0, firstIdx - 300), firstIdx + 2500);
const imgTags = block.match(/<img[^>]+>/g) || [];
console.log(`[Scrape] img tags near first item: ${imgTags.length}`);
imgTags.slice(0, 3).forEach((t, i) => console.log(` img[${i}]: ${t.substring(0, 150)}`));
} else {
console.log('[Scrape] ⚠️ No publishedfileid found! HTML length:', html.length);
}
return { ids, totalCount, hints };
}
// ─────────────────────────────────────────────────────────────────
// Main Query: Scrape IDs → GetPublishedFileDetails → respond
// ─────────────────────────────────────────────────────────────────
async function handleQuery(req, res) {
let payload;
try { payload = JSON.parse(await readBody(req)); }
catch { return jsonRes(res, 400, { error: 'Bad JSON' }); }
const params = payload.params || {};
const page = parseInt(params.page) || 1;
const numperpage = parseInt(params.numperpage) || 30;
const genreOr = [];
if (Array.isArray(params.genre_or)) params.genre_or.forEach(g => g && genreOr.push(String(g).toLowerCase()));
for (const [k, v] of Object.entries(params)) {
if (/^genre_or\[\d+\]$/.test(k) && v) genreOr.push(String(v).toLowerCase());
}
try {
const mapItem = (id, d, hint = {}) => {
const hintAuthor = cleanText(hint && hint.author);
const hintCreator = cleanText(hint && hint.creator);
const hintTitle = cleanText(hint && hint.title);
const hintPreview = cleanText(hint && hint.preview_url);
if (d && d.result === 1) {
return {
publishedfileid: id,
title: d.title || id,
preview_url: d.preview_url || '',
subscriptions: d.subscriptions || 0,
lifetime_subscriptions: d.lifetime_subscriptions || d.subscriptions || 0,
views: d.views || 0,
favorited: d.favorited || 0,
lifetime_favorited: d.lifetime_favorited || d.favorited || 0,
file_size: d.file_size || 0,
time_updated: d.time_updated || 0,
time_created: d.time_created || 0,
short_description: d.short_description || '',
tags: d.tags || [],
author: hintAuthor || '',
creator: d.creator || hintCreator || '',
};
}
return {
publishedfileid: id, title: hintTitle || `壁纸 ${id}`, preview_url: hintPreview || '',
subscriptions: 0, lifetime_subscriptions: 0, views: 0,
favorited: 0, lifetime_favorited: 0, file_size: 0,
time_updated: 0, time_created: 0, short_description: '', tags: [], author: hintAuthor || '', creator: hintCreator || '',
};
};
const hasGenreOr = genreOr.length > 1;
if (!hasGenreOr) {
const { ids, totalCount, hints } = await scrapeIds(params);
if (!ids.length) {
return jsonRes(res, 200, { response: { publishedfiledetails: [], total: 0 } });
}
let details = [];
try { details = await getFileDetailsSafe(ids); }
catch (err) { console.warn('[FileDetails Error]', err.message); }
const detailMap = {};
details.forEach(d => { if (d && d.publishedfileid) detailMap[d.publishedfileid] = d; });
const items = ids.map(id => mapItem(id, detailMap[id], (hints && hints[id]) || {}));
const total = totalCount > 0 ? totalCount : (ids.length >= numperpage ? 50000 : ids.length);
console.log(`[Query] Returning ${items.length} items, total=${total}`);
return jsonRes(res, 200, { response: { publishedfiledetails: items, total, total_count: items.length } });
}
const matched = [];
const seen = new Set();
let totalCount = 0;
let cursorPage = page;
let scanned = 0;
while (matched.length < numperpage && scanned < 6 && cursorPage <= 999) {
const pageParams = Object.assign({}, params, { page: cursorPage });
const pageData = await scrapeIds(pageParams);
if (!totalCount && pageData.totalCount) totalCount = pageData.totalCount;
if (!pageData.ids.length) break;
let details = [];
try { details = await getFileDetailsSafe(pageData.ids); }
catch (err) { console.warn('[FileDetails Error]', err.message); }
const detailMap = {};
details.forEach(d => { if (d && d.publishedfileid) detailMap[d.publishedfileid] = d; });
for (const id of pageData.ids) {
if (seen.has(id)) continue;
seen.add(id);
const d = detailMap[id];
if (!(d && d.result === 1)) continue;
const tagSet = new Set((d.tags || []).map(t => String(t.tag || t).toLowerCase()));
if (!genreOr.some(g => tagSet.has(g))) continue;
matched.push(mapItem(id, d, (pageData.hints && pageData.hints[id]) || {}));
if (matched.length >= numperpage) break;
}
cursorPage += 1;
scanned += 1;
}
const total = totalCount > 0 ? totalCount : 50000;
console.log(`[Query] Genre OR(${genreOr.length}) returning ${matched.length} items, total=${total}, scanned=${scanned}`);
jsonRes(res, 200, { response: { publishedfiledetails: matched, total, total_count: matched.length } });
} catch (err) {
console.error('[Query Error]', err.message);
jsonRes(res, 502, { error: err.message });
}
}
// ─────────────────────────────────────────────────────────────────
// Detail page: API + HTML scrape + comments
// ─────────────────────────────────────────────────────────────────
async function handleDetails(res, id) {
console.log(`[Detail] id=${id}`);
// A: GetPublishedFileDetails for single item
let A = null;
try {
const list = await getFileDetails([id]);
A = list[0] && list[0].result === 1 ? list[0] : null;
} catch (e) { console.warn('[Detail API]', e.message); }
const withDeadline = (promise, ms, fallback) => new Promise(resolve => {
let settled = false;
const timer = setTimeout(() => {
if (settled) return;
settled = true;
resolve(fallback);
}, ms);
Promise.resolve(promise)
.then(v => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(v);
})
.catch(() => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(fallback);
});
});
const detailTask = (async () => {
try {
const detailHtml = (await GET(
`https://steamcommunity.com/sharedfiles/filedetails/?id=${id}`,
{ 'Accept-Language': 'zh-CN,zh;q=0.9' }, 9000
)).toString('utf8');
return { detailHtml, H: parseDetailHtml(detailHtml) };
} catch (e) {
console.warn('[Detail HTML]', e.message);
return { detailHtml: '', H: null };
}
})();
const commentsTask = (async () => {
try {
const cUrl = `https://steamcommunity.com/comment/PublishedFile_Public/render/${id}/-1/`;
const cBody = 'start=0&count=50&feature2=-1&l=schinese&userreview_offset=-1';
const u = new URL(cUrl);
const buf = await doRequest({
protocol: u.protocol,
hostname: u.hostname,
port: u.port ? parseInt(u.port) : undefined,
path: u.pathname + u.search,
method: 'POST',
headers: {
'User-Agent': UA,
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Content-Length': Buffer.byteLength(cBody),
'Accept': '*/*',
'X-Requested-With': 'XMLHttpRequest',
'Origin': 'https://steamcommunity.com',
'Referer': `https://steamcommunity.com/sharedfiles/filedetails/?id=${id}`,
'Cookie': STEAM_PREF_COOKIE,
},
timeout: 9000
}, cBody);
const cData = JSON.parse(buf.toString('utf8'));
if (cData.success) return parseComments(cData.comments_html || '');
console.warn(`[Comments] Steam returned success=false, id=${id}`);
return [];
} catch (e) {
console.warn('[Comments]', e.message);
return [];
}
})();
const detailResult = await withDeadline(detailTask, 9500, { detailHtml: '', H: null });
let H = detailResult.H;
let detailHtml = detailResult.detailHtml;
let comments = await withDeadline(commentsTask, 9500, []);
if (!comments.length && detailHtml) comments = parseComments(detailHtml);
const creatorId = (A && A.creator) ? String(A.creator) : ((H && H.creator_id) ? String(H.creator_id) : '');
const resolvedPersona = await resolvePersonaName(creatorId);
const htmlAuthor = cleanText(H && H.author);
const finalAuthor = (htmlAuthor && !looksLikeSteamId(htmlAuthor))
? htmlAuthor
: (resolvedPersona || htmlAuthor || creatorId || '');
const out = {
publishedfileid: id,
title: (A&&A.title) || (H&&H.title) || '',
preview_url: (A&&A.preview_url) || (H&&H.preview_url) || '',
description: (H&&H.description) || (A&&A.short_description) || '',
author: finalAuthor,
subscriptions: fmtStat((A&&(A.lifetime_subscriptions||A.subscriptions)), H&&H.subscriptions),
favorited: fmtStat((A&&(A.lifetime_favorited||A.favorited)), H&&H.favorited),
views: fmtStat((A&&A.views), H&&H.views),
file_size: fmtBytes(A&&A.file_size) || (H&&H.file_size) || '未知',
time_updated: fmtTime(A&&A.time_updated) || (H&&H.time_updated) || '未知',
time_created: fmtTime(A&&A.time_created) || (H&&H.time_created) || '未知',
tags: (A&&A.tags&&A.tags.map(t=>t.tag||t)) || (H&&H.tags) || [],
comments,
};
console.log(`[Detail] Result: preview=${out.preview_url?'YES':'NO'}, subs=${out.subscriptions}, cmts=${comments.length}`);
jsonRes(res, 200, out);
}
function fmtStat(n, fallback) {
n = parseInt(n) || 0;
if (n > 0) {
if (n>=1e6) return (n/1e6).toFixed(1)+'M';
if (n>=1e3) return (n/1e3).toFixed(1)+'K';
return n.toLocaleString();
}
return fallback || '0';
}
function fmtBytes(b) {
b = parseInt(b); if (!b||b<=0) return null;
if (b>=1073741824) return (b/1073741824).toFixed(1)+' GB';
if (b>=1048576) return (b/1048576).toFixed(1)+' MB';
if (b>=1024) return (b/1024).toFixed(1)+' KB';
return b+' B';
}
function fmtTime(ts) {
ts = parseInt(ts); if (!ts) return null;
return new Date(ts*1000).toLocaleDateString('zh-CN',{year:'numeric',month:'2-digit',day:'2-digit'});
}
function looksLikeSteamId(v) {
return /^\d{17}$/.test(String(v || '').trim());
}
function cleanText(v) {
return String(v || '').replace(/<[^>]+>/g,'').replace(/\s+/g,' ').trim();
}
async function resolvePersonaName(steamId) {
const sid = String(steamId || '').trim();
if (!looksLikeSteamId(sid)) return '';
if (PERSONA_CACHE.has(sid)) return PERSONA_CACHE.get(sid);
try {
const html = (await GET(`https://steamcommunity.com/profiles/${sid}/?xml=1`, { 'Accept': 'application/xml,text/xml,*/*;q=0.8' }, 12000)).toString('utf8');
const m = html.match(/<steamID><!\[CDATA\[([\s\S]*?)\]\]><\/steamID>/i) || html.match(/<steamID>([\s\S]*?)<\/steamID>/i);
const name = cleanText(m ? m[1] : '');
PERSONA_CACHE.set(sid, name);
return name;
} catch {
PERSONA_CACHE.set(sid, '');
return '';
}
}
function parseDetailHtml(html) {
const titleM = html.match(/<div class="workshopItemTitle">([^<]+)<\/div>/);
const imgM = html.match(/id="previewImageMain"[^>]+src="([^"]+)"/) ||
html.match(/id="previewImage"[^>]+src="([^"]+)"/) ||
html.match(/class="workshopItemPreviewImageMain[^"]*"[^>]+src="([^"]+)"/);
const descM = html.match(/id="highlightContent"[^>]*>([\s\S]*?)<\/div>/) ||
html.match(/class="workshopItemDescription[^"]*"[^>]*>([\s\S]*?)<\/div>/);
const authBlkM = html.match(/class="workshopItemAuthorName[^"]*"[\s\S]{0,1200}?<\/a>/) ||
html.match(/class="friendBlock[^"]*"[\s\S]{0,2200}?<\/div>\s*<\/div>/);
const authM = authBlkM
? (authBlkM[0].match(/<a[^>]*>([^<]+)<\/a>/) || authBlkM[0].match(/class="friendBlockContent"[^>]*>\s*([\s\S]*?)<br/i))
: null;
const authHrefM = authBlkM
? (authBlkM[0].match(/href="[^"]*\/profiles\/(\d{17})\/?[^"]*"/i) || authBlkM[0].match(/friendBlockLinkOverlay"[^>]*href="[^"]*\/profiles\/(\d{17})\/?[^"]*"/i))
: null;
let subs='',favs='',views='',file_size='',time_updated='',time_created='';
for (const [,n,l] of html.matchAll(/<tr>\s*<td[^>]*>([^<]+)<\/td>\s*<td[^>]*>([^<]+)<\/td>\s*<\/tr>/g)) {
const lb = l.trim().toLowerCase();
if (lb.includes('visitor')||lb.includes('访问')) views = n.trim();
if (lb.includes('subscri')||lb.includes('订阅')) subs = n.trim();
if (lb.includes('favorit')||lb.includes('收藏')) favs = n.trim();
}
for (const [,l,v] of html.matchAll(/<div class="detailsStatLeft">([^<]+)<\/div>\s*<div class="detailsStatRight">([^<]+)<\/div>/g)) {
const lb = l.trim().toLowerCase(), vt = v.trim();
if (lb.includes('size')) file_size = vt;
if (lb.includes('updated')) time_updated = vt;
if (lb.includes('posted')) time_created = vt;
}
const tags = [];
for (const [,t] of html.matchAll(/<a[^>]+class="[^"]*workshopTagFilterItem[^"]*"[^>]*>\s*([^<]+)\s*<\/a>/g)) {
if (!tags.includes(t.trim())) tags.push(t.trim());
}
for (const [,t] of html.matchAll(/class="workshopTags"[^>]*>[\s\S]*?<a[^>]*>\s*([^<]+)\s*<\/a>/g)) {
const tag = t.trim();
if (tag && !tags.includes(tag)) tags.push(tag);
}
return {
title: titleM ? titleM[1].trim() : '',
preview_url: imgM ? imgM[1] : '',
description: descM ? descM[1].replace(/<br\s*\/?>/gi,'\n').replace(/<[^>]+>/g,'').replace(/&/g,'&').trim() : '',
author: authM ? authM[1].trim() : '',
creator_id: authHrefM ? authHrefM[1] : '',
subscriptions: subs, favorited: favs, views, file_size, time_updated, time_created, tags,
};
}
function parseComments(html) {
if (!html) return [];
const out = [];
const re = /<a[^>]*class="[^"]*commentthread_author_link[^"]*"[^>]*>([\s\S]*?)<\/a>[\s\S]{0,2400}?<span[^>]*class="[^"]*commentthread_comment_timestamp[^"]*"[^>]*>([\s\S]*?)<\/span>[\s\S]{0,4000}?<div[^>]*class="[^"]*commentthread_comment_text[^"]*"[^>]*>([\s\S]*?)<\/div>/g;
for (const m of html.matchAll(re)) {
const author = (m[1] || '').replace(/<[^>]+>/g,'').trim() || 'Steam User';
const date = (m[2] || '').replace(/<[^>]+>/g,'').trim();
const text = (m[3] || '').replace(/<br\s*\/?>/gi,'\n').replace(/<[^>]+>/g,'').trim();
if (!text) continue;
out.push({ author, date, text });
if (out.length >= 50) break;
}
return out;
}
// ─────────────────────────────────────────────────────────────────
// Handle Download Request (add to queue only)
// ─────────────────────────────────────────────────────────────────
function safeName(s) {
return String(s || '')
.replace(/[<>:"/\\|?*\x00-\x1F]/g, ' ')
.replace(/\s+/g, ' ')
.trim()
.slice(0, 120);
}
function extFromUrl(u, fallback) {
try {
const pathname = new URL(u).pathname || '';
const ext = path.extname(pathname).toLowerCase();
if (ext && ext.length <= 8) return ext;
} catch {}
return fallback || '.bin';
}
function extFromPath(p, fallback) {
const ext = path.extname(String(p || '')).toLowerCase();
return (ext && ext.length <= 8) ? ext : (fallback || '.bin');
}
function mimeFromExt(ext) {
const m = {
'.jpg':'image/jpeg','.jpeg':'image/jpeg','.png':'image/png','.webp':'image/webp','.gif':'image/gif',
'.mp4':'video/mp4','.webm':'video/webm','.wmv':'video/x-ms-wmv','.avi':'video/x-msvideo',
'.mkv':'video/x-matroska','.mov':'video/quicktime','.m4v':'video/x-m4v',
'.mp3':'audio/mpeg','.wav':'audio/wav',
'.zip':'application/zip','.rar':'application/vnd.rar','.7z':'application/x-7z-compressed',
};
return m[ext] || 'application/octet-stream';
}
function ensureDir(p) {
if (!fs.existsSync(p)) fs.mkdirSync(p, { recursive: true });
}
function runProcess(bin, args, timeoutMs) {
return new Promise((resolve, reject) => {
const cp = spawn(bin, args, { windowsHide: true, env: Object.assign({}, process.env) });
let out = '';
let err = '';
const timer = setTimeout(() => {
try { cp.kill(); } catch {}
reject(new Error('外部下载进程超时'));
}, timeoutMs || 240000);
cp.stdout.on('data', d => out += d.toString());
cp.stderr.on('data', d => err += d.toString());
cp.on('error', e => {
clearTimeout(timer);
reject(e);
});
cp.on('close', code => {
clearTimeout(timer);
if (code === 0) return resolve({ out, err });
reject(new Error((err || out || `exit ${code}`).trim().slice(-1200)));
});
});
}
async function resolveSteamCmdPath() {
const candidates = [
process.env.STEAMCMD_PATH || '',
path.join(__dirname, 'steamcmd', 'steamcmd.exe'),
'C:\\steamcmd\\steamcmd.exe',
'C:\\Program Files (x86)\\SteamCMD\\steamcmd.exe',
'C:\\Program Files\\SteamCMD\\steamcmd.exe',
].filter(Boolean);
for (const p of candidates) {
if (fs.existsSync(p)) return p;
}
try {
const out = await runProcess('where.exe', ['steamcmd']);
const first = String(out.out || '').split(/\r?\n/).map(s => s.trim()).find(Boolean);
if (first && fs.existsSync(first)) return first;
} catch {}
return null;
}
function psQuote(v) {
return String(v || '').replace(/'/g, "''");
}
function listFilesRecursive(root) {
const out = [];
const walk = (dir) => {
const ents = fs.readdirSync(dir, { withFileTypes: true });
for (const e of ents) {
const fp = path.join(dir, e.name);
if (e.isDirectory()) walk(fp);
else if (e.isFile()) out.push(fp);
}
};
walk(root);
return out;
}