-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathindex.js
More file actions
1733 lines (1565 loc) · 69.8 KB
/
index.js
File metadata and controls
1733 lines (1565 loc) · 69.8 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
// ==Headers==
// @Name: 软件更新管理器
// @Name-en: softwareUpdateManager
// @Description: 下载并安装可更新的软件
// @Description-en: download and install softwares when updates available
// @Version: 1.2.0
// @Author: dodying
// @Created: 2021-02-15 09:58:50
// @Modified: 2021/2/15 17:59:50
// @Namespace: https://github.com/dodying/Nodejs
// @SupportURL: https://github.com/dodying/Nodejs/issues
// @Require: cheerio,commander,deepmerge,fs-extra,html-to-text,iconv-lite,node-notifier,readline-sync,request,request-promise,socks5-http-client,socks5-https-client
// ==/Headers==
/* eslint-disable no-control-regex */
// 设置
let _ = require('./config');
// 导入原生模块
const path = require('path');
const cp = require('child_process');
const readline = require('readline');
const util = require('util');
// 导入第三方模块
const commander = require('commander');
const program = new commander.Command();
const fse = require('fs-extra');
const cheerio = require('cheerio');
const readlineSync = require('readline-sync');
const request = require('request');
// const requestPromise = require('request-promise')
// const Agent = require('socks5-http-client/lib/Agent')
// const Agent2 = require('socks5-https-client/lib/Agent')
const notifier = require('node-notifier');
const merge = require('deepmerge');
// const iconv = require('iconv-lite')
const html2Text = require('html-to-text');
const walk = require('./js/walk');
const replace = require('./js/replaceWithDict');
const req = require('./js/req');
req.config.set('_', _);
const reqRaw = req.raw;
const reqHEAD = req.head;
// Console
const color = {
Reset: '\x1b[0m',
Bright: '\x1b[1m',
Dim: '\x1b[2m',
Underscore: '\x1b[4m',
Blink: '\x1b[5m',
Reverse: '\x1b[7m',
Hidden: '\x1b[8m',
FgBlack: '\x1b[30m',
FgRed: '\x1b[31m',
FgGreen: '\x1b[32m',
FgYellow: '\x1b[33m',
FgBlue: '\x1b[34m',
FgMagenta: '\x1b[35m',
FgCyan: '\x1b[36m',
FgWhite: '\x1b[37m',
BgBlack: '\x1b[40m',
BgRed: '\x1b[41m',
BgGreen: '\x1b[42m',
BgYellow: '\x1b[43m',
BgBlue: '\x1b[44m',
BgMagenta: '\x1b[45m',
BgCyan: '\x1b[46m',
BgWhite: '\x1b[47m'
};
const _color = {
log: color.FgGreen,
warn: color.FgYellow,
error: color.BgRed,
debug: color.FgBlue
};
var consoleRaw = {};
function logModify (colorMsg, msg) {
let lastKey;
return typeof msg === 'string' ? msg.split('\n').map(j => {
if (j.match(/^(.*):\t(.*)$/) || lastKey) {
let result = j.match(/^(.*):\t(.*)$/);
if (result) {
lastKey = result[1];
} else {
result = [null, lastKey, j];
}
lastKey = result[1];
let space = 16 - result[1].length - 1;
if (result[2].match(/^"/)) space = space - 1;
return `${color.FgCyan}${result[1]}${color.Reset}:${' '.repeat(space)}${colorMsg}${result[2]}${color.Reset}`;
} else {
return `${colorMsg}${j}${color.Reset}`;
}
}).join('\n') : msg;
}
for (const i of ['log', 'warn', 'error', 'debug']) {
consoleRaw[i] = console[i];
const logFile = path.resolve(__dirname, 'index.log');
const colorRe = new RegExp('\x1b\\[\\d+m', 'gi');
console[i] = (...args) => {
for (let msg of args) {
let msgString;
if (msg instanceof Error) msg = `Error:\t${util.format(msg).trim()}`;
if (typeof msg === 'string') {
msg = logModify(_color[i], msg);
if (_.debug) msgString = msg.replace(colorRe, '');
} else {
if (_.debug) msgString = util.formatWithOptions(_.formatOptions, msg);
}
if (_.debug) fse.appendFileSync(logFile, msgString + '\n');
if (i !== 'debug' || (_.debug && typeof msg === 'string')) consoleRaw[i](msg);
}
};
}
for (const i in readlineSync) {
if (!i.match(/^(question|keyIn|prompt)/)) continue;
const raw = readlineSync[i];
if (i.match(/^(keyIn|question)./)) {
readlineSync[i] = (text, ...args) => {
const msg = logModify(_color.warn, text);
if (msg && _.debug) {
let msgString = msg;
if (msg instanceof Array) msgString = msgString.join('\n');
const logFile = path.resolve(__dirname, 'index.log');
const colorRe = new RegExp('\x1b\\[\\d+m', 'gi');
fse.appendFileSync(logFile, msgString.replace(colorRe, '') + '\n');
}
const title = process.title;
process.title = `[Wait] ${title}`;
const result = raw(msg, ...args);
process.title = title;
return result;
};
}
}
for (const i in _.defaultOptions) util.inspect.defaultOptions[i] = _.defaultOptions[i];
_.archivePath = path.resolve(__dirname, _.archivePath);
_.download.urlWithoutHeader = [].concat(_.download.urlWithoutHeader, 'sourceforge.net', 'osdn.net', 'mediafire.com');
const exts = ['.zip', '.7z', '.exe', '.msi', '.rar', '.jar', '.tar', '.gz', '.bz2', '.xz', '.nupkg', '.dll', '.appx', '.appxbundle', '.msix', '.msixbundle', '.iso'];
const exts2 = ['.gz', '.bz2', '.xz'];
const releasePage = 'https://github.com/dodying/softwareUpdateManager/releases/tag/plugins';
const software = {};
const fns = { cheerio, getNow, spawnSync, req, reqRaw, reqHEAD, getHash, dirname: __dirname };
walk('js', { nodir: true, matchFile: /\.js$/ }).map(i => i.split(/[\\/]/).splice(1).join('/').replace(/\.js$/, '')).forEach(i => {
const arr = i.split(/[/_]/);
let obj = fns;
for (let j = 0; j < arr.length - 1; j++) {
if (!(arr[j] in obj)) obj[arr[j]] = {};
obj = obj[arr[j]];
}
obj[arr[arr.length - 1]] = require(`./js/${i}.js`);
});
let databaseFile = `${__dirname}/database.json`;
let database = fse.existsSync(databaseFile) ? JSON.parse(fse.readFileSync(databaseFile, 'utf-8')) : {};
let mode;
// Function
function getNow () { return new Date().toLocaleString(_.locale, { hour12: false }); }
function spawnSync (...argsForSpwan) {
return new Promise(resolve => {
const child = cp.spawn(...argsForSpwan);
child.stdout.pipe(process.stdout);
child.stderr.pipe(process.stderr);
child.on('exit', function (code) {
let end;
if (code.toString() !== '0') {
end = 'error';
console.error(`Command:\t${argsForSpwan[0]}`);
console.error(`Command-Args:${argsForSpwan[1].map(i => `{${i}}`).join(', ')}\n`);
console.error(`Exit-Code:\t${code.toString()}`);
} else {
end = true;
}
resolve(end);
});
});
}
function getHash (file, algorithm) {
// Hash algorithms: MD2 MD4 MD5 SHA1 SHA256 SHA384 SHA512
return cp.spawnSync(path.resolve(process.env.SystemRoot, 'System32', 'certutil.exe'), ['-hashfile', file, algorithm]).output[1].toString().split(/[\r\n]+/)[1];
}
function ExtendSoftware (data) {
const valid = any => typeof any === 'string' || any instanceof Array || any instanceof Function;
if (data.version && valid(data.version)) {
if (typeof data.version === 'string') {
data.version = { selector: data.version };
} else if (data.version instanceof Function) {
data.version = { func: data.version };
} else if (data.version instanceof Array) {
data.version = {
selector: data.version[0],
attr: data.version[1],
match: data.version[2],
replace: data.version[3]
};
}
}
if (data.changelog && valid(data.changelog)) {
data.changelog = [].concat(data.changelog);
if (typeof data.changelog[0] === 'string') {
if (!data.changelog[0].match(/^https?:/i)) data.changelog.unshift(null);
data.changelog = {
url: data.changelog[0],
selector: data.changelog[1],
attr: data.changelog[2],
match: data.changelog[3],
split: data.changelog[4]
};
} else if (typeof data.changelog[0] === 'function') {
data.changelog = {
func: data.changelog[0]
};
}
}
if (data.download && valid(data.download)) {
data.download = [].concat(data.download);
if (typeof data.download[0] === 'string') {
if (data.download[0].match(/^https?:/i)) {
data.download = {
plain: data.download[0],
output: data.download[1]
};
} else {
data.download = {
selector: data.download[0],
attr: data.download[1],
match: data.download[2],
output: data.download[3]
};
}
} else if (typeof data.download[0] === 'function') {
data.download = {
func: data.download[0],
output: data.download[1]
};
}
}
if (data.install && (typeof data.install === 'string' || data.install instanceof Array)) {
data.install = [].concat(data.install);
if (require(`./js/${data.install[0]}`)) {
const func = require(`./js/${data.install[0]}`);
const args = data.install.slice(1);
data.install = info => func(info, ...args);
} else {
delete data.install;
}
}
return data;
}
function getPath (cmd) {
return cp.spawnSync(process.env.comspec, ['/c', `echo "${cmd}"`], {
env: Object.assign({}, process.env, {
'ProgramFiles(x86)': process.env['ProgramFiles(x86)'] || process.env.ProgramFiles
})
}).output[1].toString().trim().match(/^\\"(.*)\\"$/)[1];
}
// Main-version
async function getLatestVersion (i) {
const iEscaped = i.replace(/[:*?"<>|]/g, '-');
const reqOption = { uri: software[i].url };
if (software[i].url.match(/:\/\/api.github.com\//) && _.request.github) {
if (!reqOption.headers) reqOption.headers = {};
reqOption.headers.Authorization = `token ${_.request.github}`;
reqOption.headers['User-Agent'] = _.request.userAgent;
}
const res = await req(reqOption, { useProxy: software[i].useProxy });
let returnValue;
if (res && (res.statusMessage === 'OK' || (res.statusCode >= 200 && res.statusCode < 300))) {
returnValue = await (async function () {
const $ = cheerio.load(res.body);
if (_.debug) {
const parentPath = path.dirname(`debug/${iEscaped}.html`);
if (!fse.existsSync(parentPath)) fse.mkdirsSync(parentPath);
fse.writeFileSync(`debug/${iEscaped}.html`, res.body);
fse.writeJsonSync(`debug/${iEscaped}.json`, res, {
spaces: 2,
replacer: (key, value) => key === 'body' ? undefined : value
});
}
// if ($('title').text().trim()) console.debug(`Title:\t${$('title').text().trim()}`);
let version;
if ('selector' in software[i].version) {
try {
version = $(software[i].version.selector);
} catch (error) {
console.error(`Error:\tSelector "${software[i].version.selector}" Invalid when "version"`);
return false;
}
if (version.length === 0) {
console.error(`Error:\tSelector "${software[i].version.selector}" Nothing when "version"`);
return null;
}
version = version.eq(0);
version = (software[i].version.attr === 'text' || !software[i].version.attr) ? version.text() : software[i].version.attr === 'html' ? $.html(version) : version.attr(software[i].version.attr);
version = version.trim();
if (version === '') {
console.error(`Error:\tAttribute "${software[i].version.attr}" Empty when "version"`);
return null;
}
// console.debug({ version });
const regexp = software[i].version.match || /(\d+[\d.]+\d+)/;
const matched = version.match(regexp);
if (!matched) {
console.error(`Error:\tRegExp "${regexp}" Dont Match Text "${version}" when "version"`);
return null;
}
if (software[i].version.replace) {
version = matched[0].replace(regexp, software[i].version.replace);
} else {
version = matched.length > 1 ? matched[1] : matched[0];
}
} else if ('func' in software[i].version) {
try {
version = await software[i].version.func(res, $, fns, software[i].versionChoice);
if (!version) {
console.error('Error:\t"func" return nothing when "version"');
return null;
}
if (version instanceof Array) version = version.length ? version[1] : version[0];
} catch (error) {
console.error(`Error:\t${util.format(error)}`);
return null;
}
} else {
console.error('Error:\tNo "selector"/"func" in "version"');
return null;
}
if (!version) {
console.error('Error:\tGet nullish value in "version"');
return null;
}
if (typeof version !== 'string') version = String(version);
// if (version.match(/^(\d+[\d.]+\d+)( |-)Build( |-)(\d+)$/i)) console.debug(`Version-Raw:\t${version}`);
version = version.replace(/^(\d+[\d.]+\d+)( |-)Build( |-)(\d+)$/i, '$1.$4').replace(/[\\/:*?"<>|]/g, '-').trim();
return { version, res, $ };
})();
} else {
if (res) {
console.error(`Error:\t${res.statusCode} ${res.statusMessage}`);
} else {
console.error('Error:\tRequest return nothing');
}
}
return returnValue;
}
async function getVersion (filepath) {
if (fse.existsSync(filepath)) {
let info;
try {
info = await new Promise(resolve => {
cp.exec(`wmic DATAFILE where name="${filepath.replace(/[/\\]/g, '\\\\')}" get version`, (err, stdout, stderr) => {
if (err) {
resolve('0');
} else {
resolve(stdout);
}
});
});
if (info.match(/Version\s+([\d.]+)/)) return info.match(/Version\s+([\d.]+)/)[1];
} catch (error) {
}
}
return '0';
}
function versionMax (v1, v2) {
const arr1 = v1.split(/[.\-_]+/);
const arr2 = v2.split(/[.\-_]+/);
const length = Math.min(arr1.length, arr2.length);
for (let i = 0; i < length; i++) {
const str1 = arr1[i];
const str2 = arr2[i];
const float1 = parseFloat(str1);
const float2 = parseFloat(str2);
if (isNaN(float1) || isNaN(float2)) {
if (str1 > str2) {
return true;
} else if (str1 < str2) {
return false;
}
} else {
if (float1 > float2) {
return true;
} else if (float1 < float2) {
return false;
}
}
}
return arr1.length > arr2.length;
}
// Main-changelog
async function getLatestVersionChangelog (i, versionLatest, res, $) {
if (software[i].changelog.url) {
let url;
if (!software[i].changelog.url.match(/^https?:/i)) {
url = $(software[i].changelog.url).eq(0).attr('href');
if (!url) return;
} else {
url = software[i].changelog.url;
}
url = replace(url);
res = await req(url, { useProxy: software[i].useProxy });
if (res && (res.statusMessage === 'OK' || (res.statusCode >= 200 && res.statusCode < 300))) {
$ = cheerio.load(res.body);
// if ($('title').text().trim()) console.debug(`Title:\t${$('title').text().trim()}`);
} else {
if (res) {
console.error(`Error:\t${res.statusCode} ${res.statusMessage}`);
} else {
console.error('Error:\tRequest return nothing');
}
return;
}
}
const html2TextConfig = {
tables: true,
wordwrap: false,
// linkHrefBaseUrl: res.request.uri.href,
ignoreImage: true,
// preserveNewlines: true,
uppercaseHeadings: false,
format: {
heading: function (elem, fn, options) {
var h = fn(elem.children, options);
return `\n\n${color.Bright + color.Reverse}${h}${color.Reset}\n`;
},
horizontalLine: () => '\n' + '-'.repeat(80) + '\n\n'
},
unorderedListItemPrefix: '├─ ' // https://en.wikipedia.org/wiki/Box-drawing_character
};
if (software[i].changelog.split) html2TextConfig.format = null;
let changelog;
if ('func' in software[i].changelog) {
try {
let convert;
changelog = await software[i].changelog.func(res, $, fns);
changelog = [].concat(changelog)
;[changelog, convert] = changelog;
if (convert) changelog = html2Text.fromString(changelog, html2TextConfig);
return changelog;
} catch (error) {
console.error(`Error:\t${util.format(error)}`);
return null;
}
} else {
if (software[i].changelog.split) {
software[i].changelog.selector = software[i].changelog.selector || 'body';
software[i].changelog.attr = software[i].changelog.attr || 'html';
software[i].changelog.match = software[i].changelog.match || /^\s*[\d.]+/;
}
if (res.headers['content-type'].match(/^(text\/plain|text\/markdown|application\/octet-stream)/) && software[i].changelog.selector === 'body' && software[i].changelog.attr === 'html') {
changelog = res.body;
} else {
if (software[i].changelog.selector === 'body' && software[i].changelog.attr === 'html') console.debug(res.headers['content-type']);
try {
changelog = $(software[i].changelog.selector);
} catch (error) {
console.debug(`Error:\tSelector "${software[i].changelog.selector}" Invalid when "changelog"`);
return false;
}
if (changelog.length === 0) {
console.debug(`Error:\tSelector "${software[i].changelog.selector}" Nothing when "changelog"`);
return null;
}
changelog = changelog.eq(0);
changelog = (software[i].changelog.attr === 'text' || !software[i].changelog.attr) ? html2Text.fromString($.html(changelog), html2TextConfig) : software[i].changelog.attr === 'html' ? $.html(changelog) : changelog.attr(software[i].changelog.attr);
if (!changelog || changelog.trim() === '') {
console.debug(`Error:\tAttribute "${software[i].changelog.attr}" Empty when "changelog"`);
return null;
}
changelog = changelog.replace(new RegExp(`\n${html2TextConfig.unorderedListItemPrefix}\n`, 'g'), '\n');
}
if (software[i].changelog.split) {
const lineArr = changelog.replace(/[\u0000\r]/g, '').trim().split(/\n/);
const split = lineArr.filter(line => line.match(software[i].changelog.match));
// console.debug({ lineArr, split });
const start = lineArr.indexOf(split[0]);
if (start === -1) return null;
let end = lineArr.indexOf(split[1]);
end = end === -1 ? lineArr.length : end;
changelog = lineArr.slice(start, end).join('\n');
} else {
if (software[i].changelog.match) changelog = changelog.match(software[i].download.match)[1];
}
}
// if (changelog) fse.moveSync(`software/${i}.js`, `software-ok/${i}.js`)
return changelog;
}
// Main-download
/**
* @param {number} value
* @param {array} formats
* @param {(array | number)} steps
* @param {string} output
* @example valueHumanReadable(322350904, ['bytes', 'KB', 'MB', 'GB'], 1024, '{-1}{-1f}') => 307MB
* @example valueHumanReadable(135400, ['s', 'min', 'h', 'day'], [60, 60, 24], '{2}:{1}:{0}') => 13:36:40
*/
function valueHumanReadable (value, formats, steps, output) {
let outputRaw = value;
if (typeof steps === 'number') steps = new Array(formats.length).join(',').split(',').map(i => steps);
let index = 0;
const arr = [];
const obj = {};
while (outputRaw >= steps[index] && index + 1 < formats.length) {
arr.push(parseInt(outputRaw) % steps[index]);
outputRaw = outputRaw / steps[index];
obj[(index + 1).toString() + '.2'] = (outputRaw).toFixed(2) * 1;
index = index + 1;
}
arr.push(steps[index] ? parseInt(outputRaw) % steps[index] : parseInt(outputRaw));
for (let i = 0; i < formats.length; i++) {
obj[i] = arr[i] || 0;
obj[i.toString() + 'f'] = formats[i];
if (i < arr.length) {
obj[i - arr.length] = arr[i] || 0;
obj[(i - arr.length).toString() + '.2'] = obj[i.toString() + '.2'];
obj[(i - arr.length).toString() + 'f'] = formats[i];
}
}
return replace(output, obj);
}
async function downloadFile (uri, i, target) {
fse.mkdirsSync(path.dirname(target));
software[i].retry = software[i].retry + 1;
const requestProxy = _.request.proxy;
_.request.proxy = _.download.proxy;
const option = {
uri: uri
};
if (_.download.timeout) option.timeout = _.download.timeout * 1000;
const _withoutHeader = _.download.urlWithoutHeader.some(urlfilter => uri.match(urlfilter) || software[i].url.match(urlfilter)) || software[i].withoutHeader;
if (_withoutHeader) {
option.jar = request.jar();
option.headers = {};
}
const isContinue = _.download.continue && fse.existsSync(target) && fse.existsSync(target + '.json');
if (isContinue) {
option.headers = Object.assign(option.headers, {
Range: 'bytes=' + fse.statSync(target).size + '-'
});
}
if (option.headers) {
if (_.download.userAgent) {
option.headers['User-Agent'] = _.download.userAgent;
} else {
delete option.headers['User-Agent'];
}
}
let headers = isContinue ? fse.readJSONSync(target + '.json') : null;
const checkFile = () => {
if (!fse.existsSync(target)) return false;
const md5 = headers.etag;
if (md5) {
const arr = headers.etag.split(/[^0-9a-f]/i).filter(i => i);
if (arr[0].length === 32 && arr[0].toLowerCase() === getHash(target, 'md5')) {
if (arr[0].toLowerCase() !== getHash(target, 'md5')) return false;
}
}
const size = headers['content-length'];
if (size) {
if (+size !== fse.statSync(target).size) return false;
} else {
return false;
}
return true;
};
const result = await new Promise((resolve, reject) => {
const req = reqRaw(option, { useProxy: software[i].useProxy });
let intervalId, printProgress;
const interval = 0.8; // 单位:s
const errorHandle = async error => {
if (fse.existsSync(target)) fse.unlinkSync(target);
// if (fse.existsSync(target + '.json')) fse.unlinkSync(target + '.json')
if (printProgress instanceof Function) printProgress();
req.abort();
clearInterval(intervalId);
_.request.proxy = requestProxy;
console.error(`Try-${software[i].retry}:\t${error.message}`);
if (_.download.retry > software[i].retry) {
await new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, _.download.retryDelay * 1000);
});
software[i].useProxy = !software[i].useProxy;
return downloadFile(uri, i, target);
} else {
return resolve('error');
}
};
const successHanle = (res) => {
if (printProgress instanceof Function) printProgress();
req.abort();
clearInterval(intervalId);
_.request.proxy = requestProxy;
if (res.headers['last-modified']) {
let lastModified = res.headers['last-modified'];
lastModified = new Date(lastModified);
fse.utimesSync(target, lastModified, lastModified);
if (!_.download.continue) {
fse.unlinkSync(target + '.json');
} else {
fse.utimesSync(target + '.json', lastModified, lastModified);
}
}
resolve(true);
};
req.on('response', async res => {
if (!isContinue) {
headers = res.headers;
fse.writeJSONSync(target + '.json', res.headers, { spaces: 2 });
}
if (fse.existsSync(target) && (res.headers['content-length'] === '0' || (headers['content-length'] && +headers['content-length'] === fse.statSync(target).size))) {
if (checkFile()) {
successHanle(res);
} else {
await errorHandle(new Error('File no Match'));
}
return;
}
if (fse.existsSync(target) && !res.headers['content-range'] && res.headers['content-length'] !== '0') fse.unlinkSync(target);
let dl = fse.existsSync(target) ? fse.statSync(target).size : 0;
const len = parseInt(res.headers['content-length'], 10) + dl;
let dlLast = dl;
let time = new Date().getTime() / 1000;
let timeLast = time;
const filename = path.basename(target);
const sizeFormats = ['bytes', 'KB', 'MB', 'GB'];
console.log(`[${valueHumanReadable(len, sizeFormats, 1024, '{-1.2} {-1f}')}] ${res.request.uri.href} ==> ${filename}`);
printProgress = () => {
if (_.download.quiet) return;
const speed = (dl - dlLast) / (time - timeLast || interval);
const remain = valueHumanReadable((len - dl) / speed, ['s', 'min', 'h', 'd'], [60, 60, 24], '{3}{3f} {2}{2f} {1}{1f} {0}{0f}');
const speedRead = valueHumanReadable(speed, sizeFormats, 1024, '{-1.2} {-1f}/s');
const percent = (100.0 * dl / len).toFixed(0) * 1;
const dRead = valueHumanReadable(dl, sizeFormats, 1024, '{-1.2} {-1f}');
readline.clearLine(process.stdout, 0);
readline.cursorTo(process.stdout, 0);
process.stdout.write(`${percent}% [${'='.repeat(percent)}${percent <= 99 ? '>' : ''}${' '.repeat(100 - percent)}] ${dRead} ${speedRead} ${remain}\r`);
};
intervalId = setInterval(printProgress, interval * 1000);
res.pipe(fse.createWriteStream(target, { flags: 'a' })).on('finish', async () => {
if (!headers['content-length'] || checkFile()) {
successHanle(res);
} else {
await errorHandle(new Error('File no Match'));
}
}).on('error', async error => {
await errorHandle(error);
});
res.on('data', chunk => {
timeLast = time;
time = new Date().getTime() / 1000;
dlLast = dl;
dl += chunk.length;
});
}).on('error', async error => {
await errorHandle(error);
});
});
return result;
}
function getExt (uri) {
const uri1 = uri.replace('/download', '');
const matched = path.extname(uri1).toLocaleLowerCase();
if (exts.includes(matched)) {
return exts2.includes(matched) ? path.extname(path.parse(uri1).name) + matched : matched;
}
}
async function downloadLatestVersion (i, versionLatest, res, $) {
const iEscaped = i.replace(/[:*?"<>|]/g, '-');
let download, ext, matched;
if ('plain' in software[i].download) { // download url is regular
download = replace(software[i].download.plain);
} else if ('selector' in software[i].download) { // can get download from html
try {
download = $(software[i].download.selector);
} catch (error) {
console.error(`Error:\tSelector "${software[i].download.selector}" Invalid when "download"`);
return false;
}
if (download.length === 0) {
console.error(`Error:\tSelector "${software[i].download.selector}" Nothing when "download"`);
return null;
}
download = download.eq(0);
download = software[i].download.attr === 'text' ? download.text() : software[i].download.attr === 'html' ? $.html(download) : download.attr(software[i].download.attr || 'href');
if (!download || download.trim() === '') {
console.error(`Error:\tAttribute "${software[i].download.attr}" Empty when "download"`);
return null;
}
download = software[i].download.match && download.match(software[i].download.match) ? download.match(software[i].download.match)[1] : download;
} else if ('func' in software[i].download) {
try {
download = await software[i].download.func(res, $, fns, software[i].downloadChoice);
download = [].concat(download)
;[download, ext] = download;
if (!download) {
console.error('Error:\t"func" return nothing when "download"');
return null;
}
} catch (error) {
console.error(`Error:\t${util.format(error)}`);
return null;
}
} else {
console.error('Error:\tNo "plain"/"selector"/"func" in "download"');
return null;
}
download = new URL(download, res.request.uri.href).href;
if (ext) {
} else if (software[i].download.output) {
ext = software[i].download.output;
} else if ((matched = getExt(download))) {
ext = matched;
} else {
software[i].retry = 0;
const res1 = await reqHEAD(download, { useProxy: software[i].useProxy, withoutHeader: software[i].withoutHeader });
if (!res1) {
console.error(`Error:\tCan't Access "${download}"`);
console.error('Error:\tCan\'t get Extension name, please set "output" in "download"');
return null;
} else if ((matched = getExt(res1.request.uri.pathname))) {
ext = matched;
} else if (res1.headers['content-disposition'] && (matched = res1.headers['content-disposition'].match(/filename="?(.*?)"?(;|$)/)) && matched[1] && (matched = getExt(matched[1]))) {
ext = matched;
} else {
console.error('Error:\tCan\'t get Extension name, please set "output" in "download"');
return null;
}
}
if (!ext) return null;
let output = iEscaped + '-' + versionLatest + ext.toLowerCase();
output = path.resolve(_.archivePath, output);
if (JSON.parse(JSON.stringify(req.config.get('cookies')))._jar.cookies.length) {
fse.writeFileSync('cookies.txt', JSON.parse(JSON.stringify(req.config.get('cookies')))._jar.cookies.map(i => [`.${i.domain}`, i.hostOnly ? 'TRUE' : 'FALSE', i.path, i.secure ? 'TRUE' : 'FALSE', i.expires ? Math.round(new Date(i.expires).getTime() / 1000) : '0', i.key, i.value].join('\t')).join('\r\n'));
}
const args = [];
let end;
const _withoutHeader = _.download.urlWithoutHeader.some(urlfilter => download.match(urlfilter) || software[i].url.match(urlfilter)) || software[i].withoutHeader;
const _prxoy = _.download.proxy;
const _withProxyRule = _.urlWithProxy.some(urlfilter => download.match(urlfilter) || software[i].url.match(urlfilter));
const _withProxyMode = _.useProxy === 2 || (_.useProxy === 1 && software[i].useProxy);
const _withProxyAuto = req.config.get('proxyList')[new URL(download).hostname] || req.config.get('proxyList')[new URL(software[i].url).hostname];
const _withProxy = _withProxyRule || _withProxyMode || _withProxyAuto;
const _withoutProxy = _.urlWithoutProxy.some(urlfilter => download.match(urlfilter));
const _withProxyForce = _.urlWithProxyForce.some(urlfilter => download.match(urlfilter) || software[i].url.match(urlfilter));
const _withoutProxyForce = _.urlWithoutProxyForce.some(urlfilter => download.match(urlfilter) || software[i].url.match(urlfilter));
const _useProxy = _prxoy && (_withProxyForce || (_withProxy && !_withoutProxy)) && !_withoutProxyForce;
if (['test'].includes(mode)) {
const res = await reqHEAD(download, { useProxy: _useProxy, withoutHeader: _withoutHeader });
if (res && (res.statusMessage === 'OK' || (res.statusCode >= 200 && res.statusCode < 300))) {
if (res.headers['content-length']) {
const len = parseInt(res.headers['content-length'], 10);
const sizeFormats = ['bytes', 'KB', 'MB', 'GB'];
console.log(`File Size:\t${valueHumanReadable(len, sizeFormats, 1024, '{-1.2} {-1f}')}`);
} else {
console.log('File Size:\tUnknown');
}
// TODO SOFTWARE TEST
// software[i]._test_ok = true;
// TODO SOFTWARE TEST
} else if (res) {
console.error(`Error:\t${res.statusCode} ${res.statusMessage}`);
}
// TODO SOFTWARE TEST
// const name = i.split(':')[0];
// const similarSoftwares = Object.entries(software).filter(arr => arr[0].split(':')[0] === name);
// if (fse.existsSync(`software/${name}.js`) && similarSoftwares.indexOf(similarSoftwares.find(arr => arr[0] === i)) + 1 === similarSoftwares.length && similarSoftwares.every(arr => arr[1]._test_ok)) {
// const pathnew = `software-${similarSoftwares.every(arr => arr[1]._test_ok) ? 'ok' : 'test'}/${name}.js`;
// if (!fse.existsSync(path.dirname(pathnew))) fse.mkdirsSync(path.dirname(pathnew));
// fse.renameSync(`software/${name}.js`, pathnew);
// }
// TODO SOFTWARE TEST
return null;
}
console.log(`Download${_useProxy ? '+proxy' : ''}:\t${download}`);
console.log(`Output:\t${output}`);
console.log();
if (_.download.method === 'request') {
software[i].retry = 0;
end = await downloadFile(download, i, output);
} else if (_.download.method === 'aria2c') {
if (_.download.continue && fse.existsSync(output)) args.push('--continue');
if (_.download.quiet) args.push('--quiet');
if (_.download.retry) args.push('--max-tries=' + _.download.retry, '--retry-wait=' + _.download.retryDelay);
if (_.download.timeout) args.push('--timeout=' + _.download.timeout);
if (!_withoutHeader) {
if (fse.existsSync('cookies.txt')) args.push('--load-cookies=cookies.txt'); // Load Cookies from FILE
if (_.download.userAgent) args.push(`--user-agent="${_.download.userAgent}"`);
args.push(`--referer="${software[i].url}"`);
}
if (_useProxy) {
args.push(`--all-proxy=${_.download.proxy}`);
}
args.push('--check-certificate=false'); // Verify the peer using certificates
args.push('--remote-time'); // Retrieve timestamp of the remote file from the remote HTTP/FTP server and if it is available, apply it to the local file.
args.push('--auto-file-renaming=false'); // Rename file name if the same file already exists.
args.push('--allow-overwrite=true'); // Restart download from scratch if the corresponding control file doesn’t exist.
args.push('--file-allocation=none'); // Specify file allocation method.
args.push('--min-split-size=1M'); // aria2 does not split less than 2*SIZE byte range.
args.push('--max-connection-per-server=64'); // The maximum number of connections to one server for each download.
args.push('--split=64'); // Download a file using N connections.
args.push('--console-log-level=error'); // Set log level to output to console.
if (_.debug) args.push(`--log=debug\\${iEscaped}-aria2c.log`); // The file name of the log file.
args.push(`--out=${path.relative('', output)}`, download);
end = await spawnSync('plugins\\aria2c.exe', args);
} else if (_.download.method === 'wget') {
if (_.download.continue && fse.existsSync(output)) args.push('--continue');
if (_.download.quiet) args.push('--quiet');
if (_.download.retry) args.push('--tries=' + _.download.retry, '--waitretry=' + _.download.retryDelay);
if (_.download.timeout) args.push('--timeout=' + _.download.timeout);
if (!_withoutHeader) {
if (fse.existsSync('cookies.txt')) args.push('--load-cookies=cookies.txt'); // load cookies from FILE before session
if (_.download.userAgent) args.push(`--user-agent="${_.download.userAgent}"`);
args.push(`--referer="${software[i].url}"`);
}
if (_useProxy) {
args.push('-e', 'use_proxy=yes');
args.push('-e', `http_proxy=${_.download.proxy}`);
args.push('-e', `https_proxy=${_.download.proxy}`);
args.push('--no-check-certificate'); // don't validate the server's certificate
}
args.push('--no-verbose'); // turn off verboseness, without being quiet
args.push('--show-progress'); // display the progress bar in any verbosity mode
if (_.debug) args.push('--debug', `--append-output=debug\\${iEscaped}-wget.log`); // append messages to FILE
args.push(`--output-document=${output}`, download);
end = await spawnSync('plugins\\wget.exe', args);
} else if (_.download.method === 'curl') {
if (_.download.continue && fse.existsSync(output)) args.push('--continue-at', '-');
if (_.download.quiet) args.push('--silent');
if (_.download.retry) args.push('--retry', _.download.retry, '--retry-delay', _.download.retryDelay);
if (_.download.timeout) args.push('--max-time', _.download.timeout);
if (!_withoutHeader) {
if (fse.existsSync('cookies.txt')) args.push('--cookie', 'cookies.txt'); // Send cookies from string/file
if (_.download.userAgent) args.push('--user-agent', _.download.userAgent);
args.push('--referer', software[i].url);
}
if (_useProxy) {
args.push('--proxy', _.download.proxy);
args.push('--insecure'); // Allow insecure server connections when using SSL
}
args.push('--remote-time'); // Set the remote file's time on the local output
args.push('--location'); // Follow redirects
if (_.debug) args.push('--verbose'); // append messages to FILE
args.push('--output', output, download);
end = await spawnSync('plugins\\curl.exe', args);
}
console.log();
if (end === 'error') {
console.error('Error:\tDownload new version Error');
if (['test-download', 'test-install'].includes(mode)) {
// go-on
} else if (readlineSync.keyInYNStrict(`Open:\t${download}`)) cp.execSync(`start "" "${download}"`);
return null;
} else if (['backup'].includes(mode)) {
return null;
} else {
return { output };
}
}
// Main-virus
async function virusCheckFile (file) {
const sha256 = getHash(file, 'sha256');
let res = await req({
uri: 'https://www.virustotal.com/vtapi/v2/file/report',
method: 'POST',
form: {
apikey: _.virus.apiKey,
resource: sha256
}
});
if (!res.statusCode || !res.body) return virusCheckFile(file);
if (res.json.response_code === -2) return 'Scaning';
if (res.json.response_code === 0 && _.virus.upload) {
console.log('Notice:\tYour file is uploading to scan');
res = await req({
uri: 'https://www.virustotal.com/vtapi/v2/file/scan',
method: 'POST',
formData: {
apikey: _.virus.apiKey,
file: {
value: fse.createReadStream(file),
options: {
filename: path.basename(file),
contentType: 'application/octet-stream'
}
}
}
});
return virusCheckFile(file);
}
if (res.json.response_code === 0 && !_.virus.upload) return 'No Data';
let result = Object.keys(res.json.scans).map(i => {
return Object.assign({ name: i }, res.json.scans[i]);
});
console.warn(result.filter(i => i.detected).map(i => `Warn:\t${i.name}: ${i.result}`).join('\n'));
result = result.filter(i => {
const ignoreSoftware = _.virus.ignoreSoftware.some(keyword => {
if (typeof keyword === 'string') {
return i.name === keyword;
} else if (keyword instanceof RegExp) {
return i.name.match(keyword);
}
});
const ignoreResult = _.virus.ignoreSoftware.some(keyword => {
if (typeof keyword === 'string') {
return i.result === keyword;
} else if (keyword instanceof RegExp) {
return i.result.match(keyword);
}