-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
1478 lines (1403 loc) · 60.1 KB
/
index.js
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
/* eslint-disable no-shadow */
// ==Headers==
// @Name: webVideo
// @Description: 根据list.txt下载网页视频(主要是NSFW)
// @Version: 1.1.898
// @Author: dodying
// @Created: 2020-10-27 15:58:28
// @Modified: 2022-09-11 11:17:06
// @Namespace: https://github.com/dodying/Nodejs
// @SupportURL: https://github.com/dodying/Nodejs/issues
// @Require: cheerio,m3u8-parser,puppeteer,crypto-js,commander,dotenv
// ==/Headers==
// 设置
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
const config = {
workDir: 'E:\\Downloads\\Torrents\\###1\\###m3u8',
format: ['.mp4', '.avi', '.ts', '.mkv', '.wmv'].concat(['.asf', '.asx', '.bik', '.divx', '.flv', '.ifo', '.mov', '.mpe', '.mpeg', '.mpg', '.mpg4', '.ogm', '.qt', '.rm', '.rmv', '.rmvb', '.smk', '.vob', '.wm', '.xvid']),
executable: {
'N_m3u8DL-CLI': 'm3u8.exe', // https://github.com/nilaoda/N_m3u8DL-CLI
aria2c: 'aria2c.exe', // 支持更多选项
IDMan: 'D:\\GreenSoftware\\_Basis\\Internet Download Manager\\Bin\\IDMan.exe', // 可视化
ffmpeg: 'ffmpeg',
},
downloadMode: 'auto', // one of ['auto', 'hls', 'direct']
directDownloadMode: 'aria2c', // one of ['aria2c', 'IDMan']
proxyHTTP: 'http://127.0.0.1:8118', // aria2c 代理
reqConfig: {
proxy: 'http://127.0.0.1:8118',
request: {
timeout: 60 * 1000,
followAllRedirects: false,
strictSSL: false,
},
autoProxy: true,
withProxy: [
'91porn.com',
// 'papapa.info',
'3atv.cc',
'zmxx22.com',
'avtb01.com',
'4hu.tv',
'8x8x.com',
'xvideos.com',
'pornhub.com',
'tokyomotion.net', 'osakamotion.net',
'daftsex.com', 'daxab.com',
'xhamster.com',
'spankbang.com',
'tnaflix.com',
'netflav.com', 'avple.video', 'fvs.io', /ff-\d{2}.com/,
],
withoutProxy: ['ph666.me'],
logLevel: ['debug', 'warn', 'error'],
setCookie: [],
},
checkDurationFailed: 'skip', // one of ['retry', 'skip'] // 下载完成后,如果长度不匹配,则重试或跳过
listFiles: {
list: './list.txt',
exceedLimit: './list-exceedLimit.txt',
failed: './list-failed.txt',
succeed: './list-succeed.txt',
cookies: './cookies.txt',
checkFailed: './list-checkFailed.txt',
},
};
// 全局变量
let list = [];
const succeedList = [];
let workingHostname;
let exiting = false;
let browser;
// 导入原生模块
const fs = require('fs');
const path = require('path');
const cp = require('child_process');
// 导入第三方模块
const cheerio = require('cheerio');
const m3u8Parser = require('m3u8-parser');
const puppeteer = require('puppeteer');
const CryptoJS = require('crypto-js');
const { program } = require('commander');
require('dotenv').config();
require('../_lib/log').hack();
const wait = require('../_lib/wait');
const req = require('../_lib/req');
const walkEverything = require('../_lib/walkEverything');
// Function
const getVideoInfo = async (file, timeout = 10 * 1000) => {
// ffprobe -of json -show_streams -show_format "G:\H\###unwatched\032511_057.mp4"
const result = cp.spawnSync('ffprobe', ['-of', 'json', '-show_streams', '-show_format', file], { timeout, windowsHide: true });
try {
if (result.stdout && result.stdout.toString()) {
let metadata = result.stdout.toString();
metadata = JSON.parse(metadata);
if (!metadata.format) return [new Error()];
for (const i of ['duration', 'size']) {
metadata.format[i] = parseFloat(metadata.format[i]);
}
return [null, metadata];
}
if (result.stderr) console.log(result.stderr.toString());
return [result.stderr ? result.stderr.toString() : new Error()];
} catch (error) {
if (error.message === 'Unexpected end of JSON input') {
return getVideoInfo(file, timeout);
}
console.log(error);
return [error];
}
// return new Promise((resolve, reject) => {
// ffmpeg.ffprobe(file, function (err, metadata) {
// if (err) console.error({ err });
// resolve([err, metadata]);
// });
// // setTimeout(() => {
// // }, timeout);
// });
};
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', (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);
});
});
}
const doExit = () => {
exiting = true;
// fs.appendFileSync(config.listFiles.succeed, `${succeedList.join('\n')}\n`);
if (list) fs.writeFileSync(config.listFiles.list, list.filter((i) => !succeedList.includes(i)).join('\n'));
if (workingHostname) cp.spawnSync('wmic', ['process', 'where', `name='${path.basename(config.executable['N_m3u8DL-CLI'])}' and commandline like '%${workingHostname}%'`, 'Call', 'Terminate']);
if (browser) browser.close();
process.exit();
};
const checkDurationHLS = async (remote, local) => { // 错误返回undefined,否则为长度是否正确
const [err, localInfo] = await getVideoInfo(local);
if (err) return;
const localDuration = localInfo.format.duration;
let videoRes = await req(remote);
if (!videoRes || videoRes.statusCode !== 200) return;
let parser = new m3u8Parser.Parser();
parser.push(videoRes.body);
parser.end();
// fs.writeFileSync('./1.json', JSON.stringify(parser.manifest, null, 2));
let remoteDuration = parser.manifest.totalDuration || parser.manifest.segments.map((i) => i.duration).filter((i) => i).reduce((pre, cur) => pre + cur, 0);
if (remoteDuration === 0 && parser.manifest.playlists && parser.manifest.playlists.find((i) => i.uri).uri) {
videoRes = await req(parser.manifest.playlists.find((i) => i.uri).uri);
if (!videoRes || videoRes.statusCode !== 200) return;
parser = new m3u8Parser.Parser();
parser.push(videoRes.body);
parser.end();
// fs.writeFileSync('./2.json', JSON.stringify(parser.manifest, null, 2));
remoteDuration = parser.manifest.totalDuration || parser.manifest.segments.map((i) => i.duration).filter((i) => i).reduce((pre, cur) => pre + cur, 0);
}
const delta = remoteDuration - localDuration;
// console.log({ localDuration, remoteDuration, delta: delta, percent: Math.abs(delta) / remoteDuration }); process.exit();
return Math.abs(delta) / remoteDuration < (delta > 0 ? 0.1 : 1);
};
const checkDurationVideo = async (duration, file) => {
const [err, localInfo] = await getVideoInfo(file);
if (err) return;
const localDuration = localInfo.format.duration;
const remoteDuration = duration * 1;
const delta = remoteDuration - localDuration;
return Math.abs(delta) / remoteDuration < (delta > 0 ? 0.1 : 1);
};
const getRemoteInfo = async (url, lib) => {
if (lib.urlModify && typeof lib.urlModify === 'function') url = lib.urlModify(url);
console.log(`${lib.puppeteer ? 'Puppeteer' : 'Request'}:\t${lib.name} ${url}`);
let info = {};
if (lib.puppeteer) {
if (!browser) {
try {
browser = await puppeteer.launch({
// executablePath: `${__dirname}/chrome-win`,
args: [`--proxy-server=${config.reqConfig.proxy}`],
// devtools: true,
}); // https://github.com/puppeteer/puppeteer/blob/main/examples/proxy.js
} catch (error) {
console.log(error);
process.exit();
}
}
const page = await browser.newPage();
page.setDefaultNavigationTimeout(60 * 1000);
page.waitForNavigation({ waitUntil: 'networkidle2' });
await page.evaluateOnNewDocument(() => { // https://blog.51cto.com/xuedingmaojun/3079389
/* eslint-disable no-undef */
/* eslint-disable no-proto */
Object.defineProperty(navigator, 'webdriver', {
get: () => undefined,
});
const newProto = navigator.__proto__;
delete newProto.webdriver; // 删除navigator.webdriver字段
navigator.__proto__ = newProto;
window.chrome = {}; // 添加window.chrome字段,为增加真实性还需向内部填充一些值
window.chrome.app = {
InstallState: 'hehe', RunningState: 'haha', getDetails: 'xixi', getIsInstalled: 'ohno',
};
window.chrome.csi = function () {};
window.chrome.loadTimes = function () {};
window.chrome.runtime = function () {};
Object.defineProperty(navigator, 'userAgent', { // userAgent在无头模式下有headless字样,所以需覆写
get: () => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.113 Safari/537.36',
});
Object.defineProperty(navigator, 'plugins', { // 伪装真实的插件信息
get: () => [{
description: 'Portable Document Format',
filename: 'internal-pdf-viewer',
length: 1,
name: 'Chrome PDF Plugin',
}],
});
Object.defineProperty(navigator, 'languages', { // 添加语言
get: () => ['zh-CN', 'zh', 'en'],
});
const originalQuery = window.navigator.permissions.query; // notification伪装
window.navigator.permissions.query = (parameters) => (
parameters.name === 'notifications'
? Promise.resolve({ state: Notification.permission })
: originalQuery(parameters)
);
/* eslint-enable no-undef */
/* eslint-enable no-proto */
});
const requests = [];
page.on('requestfinished', async (req) => {
const res = req.response();
let body;
try {
body = ['image', 'media', 'font'].includes(req.resourceType()) ? await res.buffer() : await res.text();
} catch (error) {
body = null;
}
requests.push({
method: req.method(),
url: req.url(),
headers: req.headers(),
postData: req.postData(),
redirectChain: req.redirectChain().map((i) => i.url()),
resourceType: req.resourceType(),
response: {
headers: res.headers(),
ok: res.ok(),
status: res.status(),
statusText: res.statusText(),
url: res.url(),
body,
},
});
});
if (lib.beforeLoad && typeof lib.beforeLoad === 'function') await lib.beforeLoad(page, url, requests);
let res;
try {
res = await page.goto(url, { waitUntil: 'networkidle2', timeout: 60 * 1000 });
} catch (error) {
console.error(error);
}
if (res && res.ok()) {
try {
info = await lib.getInfo(page, url, requests);
} catch (error) {
info = {};
console.error('an expection on page.evaluate ', error);
}
}
fs.writeFileSync(config.listFiles.cookies, (await page.cookies('streamtape.com')).map((i) => [
i.domain,
'TRUE',
i.path,
i.secure ? 'TRUE' : 'FALSE',
i.expires ? Math.round(new Date(i.expires).getTime() / 1000) : '0',
i.name,
i.value,
].join('\t')).join('\r\n'));
await page.close();
} else {
const res = await req({ uri: url, ...lib.request || {} }, lib.requestUser || {});
if (!res || res.statusCode !== 200) {
if (res) {
succeedList.push(url);
fs.appendFileSync(config.listFiles.failed, `${url}\n`);
console.error(`Error:\t${res.statusCode}`);
}
info.failed = true;
return info;
}
let valueToGetInfo;
try {
valueToGetInfo = typeof lib.beforeGetInfo === 'function' ? await lib.beforeGetInfo(res) : null;
} catch (error) {
console.log(error);
console.error(`Error:\tbeforeGetInfo Failed when "${url}"`);
return info;
}
if (typeof lib.getInfo === 'function') {
try {
info = await lib.getInfo(res, valueToGetInfo);
} catch (error) {
console.log(error);
console.error(`Error:\tgetInfo Failed when "${url}"`);
}
} else {
for (const key in lib.getInfo) {
if (typeof lib.getInfo[key] === 'function') {
try {
info[key] = await lib.getInfo[key](res, valueToGetInfo);
} catch (error) {
console.log(error);
console.error(`Error:\tgetInfo "${key}" Failed when "${url}"`);
}
} else if (typeof lib.getInfo[key] === 'string' || lib.getInfo[key] instanceof Array) {
let [selector, attribute, match, replace] = [].concat(lib.getInfo[key]);
if (!attribute) attribute = 'text';
const element = res.$(selector);
if (element.length === 0) {
if (['id', 'title', 'duration', 'videoHLS', 'videoDirect'].includes(key)) fs.writeFileSync(`./${url.replace(/[\\/:*?"<>|]/g, '-')}.html`, res.body);
console.error(`Error:\tSelector "${selector}" Nothing when "${url}"`);
continue;
}
let value = attribute === 'text' ? element.eq(0).text() : (attribute === 'html' ? element.eq(0).html() : element.eq(0).attr(attribute));
if (value) value = value.trim();
if (!value) {
console.error(`Error:\tAttribute "${attribute}" Empty when "${url}"`);
continue;
}
if (match && replace) {
value = value.replace(match, replace);
} else if (match) {
const temp = value.match(match);
if (!temp) {
console.error(`Error:\tRegExp "${match}" Dont Match Text "${value}" when "url"`);
continue;
}
value = temp[1];
}
info[key] = value;
}
}
}
fs.writeFileSync(config.listFiles.cookies, (JSON.parse(JSON.stringify(req.config.get('request').jar))._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'));
}
return info;
};
const getSimilarFile = (info, exts = config.format) => fs.readdirSync(config.workDir)
.filter((i) => i.startsWith(`[${info.name}][${info.id}]`) && exts.includes(path.extname(i)))
.map((i) => path.join(config.workDir, i))
.filter((i) => fs.statSync(i).isFile())[0];
const downloadWith = { // 仅当错误时返回错误
HLS: async (info, filename, url) => {
workingHostname = new URL(info.videoHLS).hostname;
await spawnSync('start', ['', '/wait', config.executable['N_m3u8DL-CLI'], `"${info.videoHLS}"`, '--workDir', `"${config.workDir}"`, '--retryCount', '10', '--timeOut', '10', '--enableDelAfterDone', '--saveName', `"${filename}"`], { timeout: 5 * 60 * 1000, shell: true, windowsHide: false });
while (true) {
await wait(10000);
let running = cp.spawnSync('wmic', ['process', 'where', `name='${path.basename(config.executable['N_m3u8DL-CLI'])}' and commandline like '%${new URL(info.videoHLS).hostname}%'`, 'get', 'ExecutablePath,', 'Caption']).output[1].toString();
running = !running.match(/^\s*$/);
if (!exiting && !running) break;
}
workingHostname = null;
},
Direct: async (info, filename, url) => {
if (config.directDownloadMode === 'aria2c') {
const end = await spawnSync(config.executable.aria2c, [
'--async-dns=false',
'--continue',
'--max-tries=10', '--retry-wait=30', '--timeout=30',
`--load-cookies=${config.listFiles.cookies}`,
`--referer=${url}`, '--user-agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Safari/537.36 Edg/87.0.664.55"',
'--check-certificate=false', (config.reqConfig.withProxy.some((i) => url.match(i) || info.videoDirect.match(i)) && !config.reqConfig.withoutProxy.some((i) => url.match(i) || info.videoDirect.match(i)) ? `--all-proxy=${config.proxyHTTP}` : ''),
'--auto-file-renaming=false', '--allow-overwrite=true',
'--file-allocation=none',
// '--min-split-size=1M', '--max-connection-per-server=64', '--split=64',
'--console-log-level=error',
`--dir="${config.workDir}"`, `--out="${filename}.mp4.!downloading"`,
`"${info.videoDirect}"`,
]);
// fs.unlinkSync(config.listFiles.cookies);
if (end === 'error') {
return new Error('Error:\tDownload Interrupt');
} if (end === true) {
const similarFile = getSimilarFile(info, ['.!downloading']);
fs.renameSync(similarFile, similarFile.replace(/\.!downloading$/, ''));
}
} else if (config.directDownloadMode === 'IDMan') {
// https://www.internetdownloadmanager.com/support/command_line.html
await spawnSync(config.executable.IDMan, [
'/d', info.videoDirect,
'/p', config.workDir,
'/f', `${filename}.mp4`,
'/n', '/h', '/q',
]);
} else {
return new Error('Error:\t请指定下载方式');
}
},
};
// Main
let libs = [
/*
interface Lib {
name: string; // 唯一标识
tryOtherLib // 如果失败/超过限制,当tryOtherLib为true时,尝试其他规则,否则跳过该视频
filter: string | RegExp; // 链接匹配时使用当前规则
urlModify: function(url) => urlNew; // 匹配规则后,修改链接
puppeteer: boolean; // 是否使用无头浏览器 // https://zhaoqize.github.io/puppeteer-api-zh_CN/#/
beforeLoad: async function(page, url, requests); // 当使用无头浏览器时,载入页面前运行
getInfo: async function(page, url, requests) => Info;
request: object; // 请求时的其他选项(详见https://github.com/request/request/#requestoptions-callback)
requestUser: object; // 请求时的其他选项(用户)(详见_lib/req optionUser)
beforeGetInfo: async function(res); // 在getInfo之前进行,返回任意数
getInfo: async function | Info;
// 其他功能
link: function(id) => url;
test: object;
}
interface Info {
name
id: string | Array | async function(res, value);
// 当string/array时,[selector, ?attribute = 'text', ?match, ?replace]
// 当function时,参数中的value为beforeGetInfo返回值
title // 标题
uploader // 演员或上传者
duration // 视频时长(单位秒)
videoHLS // m3u8下载(推荐),下载器支持多线程下载
videoDirect // 直接下载,多线程下载需网站支持
chapters // 章节 JSON eg: [{ "title": "第一章", "start": time_in_ms }]
// 特殊的
failed // 失败,如视频被删等情况
exceedLimit // 超过限制,下次运行时再次尝试
tryOtherLib // 如果失败/超过限制,当tryOtherLib为true时,尝试其他规则,否则跳过该视频
}
// 文件一般命名为 [name][id][uploader]title
*/
// 国内
{ // 91porn-heiporn
name: '91porn-heiporn',
filter: /91porn.com\/view_video.php\?viewkey=([a-z0-9]+)|heiporn.com\/player-index-([a-z0-9]+).html/,
urlModify: (url) => {
if (url.match(/91porn.com\/view_video.php\?viewkey=([a-z0-9]+)/)) {
const id = url.match(/91porn.com\/view_video.php\?viewkey=([a-z0-9]+)/)[1];
return `https://www.heiporn.com/player-index-${id}.html`;
}
return url;
},
puppeteer: true,
getInfo: async (page, url) => page.evaluate(() => {
let duration = document.querySelector('.am-table>tbody>tr:nth-child(1)>td:nth-child(2)').textContent;
if (!duration.match(/((\d+):)?(\d+):(\d+)/)) return { failed: true };
const [, , hours, minutes, seconds] = duration.match(/((\d+):)?(\d+):(\d+)/);
duration = (hours ? hours * 60 * 60 : 0) + minutes * 60 + seconds * 1;
return {
name: '91porn',
id: window.location.href.match(/heiporn.com\/player-index-([a-z0-9]+).html/)[1],
title: document.querySelector('.am-panel-title').textContent.replace(/^片名:/, ''),
uploader: document.querySelector('.am-table>tbody>tr:nth-child(4)>td:nth-child(2)').textContent.trim(),
duration,
videoDirect: window.play,
};
}),
link: (id) => `https://www.heiporn.com/player-index-${id}.html`,
test: {
url: 'https://www.heiporn.com/player-index-7e42283b4f5ab36da134.html',
name: '91porn',
id: '7e42283b4f5ab36da134',
title: '18岁大一漂亮学妹,水嫩性感,再爽一次!',
uploader: '千岁九王爷',
duration: 431,
videoDirect: /91p\d+.com\/\/mp43\/\d+.mp4/,
},
},
{ // 91porn
name: '91porn',
filter: /91porn.com\/view_video.php\?viewkey=([a-z0-9]+)/,
request: {
headers: {
Cookie: 'language=cn_CN',
},
},
getInfo: {
id: (res) => res.request.uri.href.match(/(91porn.com)\/view_video.php\?viewkey=([a-z0-9]+)/)[2],
exceedLimit: (res) => !res.$('#player_one>script').length,
title: '#videodetails:nth-child(1)>h4:nth-child(1)',
uploader: '.title-yakov>a[href*="uprofile.php"]>span',
duration: (res) => {
const duration = res.$('.info:contains("时长")>.video-info-span').text();
const [, , hours, minutes, seconds] = duration.match(/((\d+):)?(\d+):(\d+)/);
return (hours ? hours * 60 * 60 : 0) + minutes * 60 + seconds * 1;
},
videoDirect: async (res) => {
try {
const script = res.$('#player_one>script').html().match(/strencode(\d?)\(.*?\)/);
const html = decodeURIComponent(script[0]);
return html.match(/src='(.*?)'/)[1];
// const res1 = await req({ uri: `https://91porn.com/js/m${script[1]}.js`, cache: true });
// const html = eval(`(function (){atob = (str) => CryptoJS.enc.Base64.parse(str).toString(CryptoJS.enc.Utf8);const window = { atob };${res1.body};return ${script[0].replace(/%/g, '%25')}})();`); // eslint-disable-line no-eval
// return html.match(/src='(.*?)'/)[1];
} catch (error) {
console.log(error);
return null;
}
},
},
link: (id) => `http://91porn.com/view_video.php?viewkey=${id}`,
test: {
url: 'http://91porn.com/view_video.php?viewkey=7e42283b4f5ab36da134',
name: '91porn',
id: '7e42283b4f5ab36da134',
title: '18岁大一漂亮学妹,水嫩性感,再爽一次!',
uploader: '千岁九王爷',
duration: 431,
videoDirect: /91p\d+.com\/\/mp43\/\d+.mp4/,
exceedLimit: false,
},
},
// 国内-第三方
{ // papapa.info
name: 'papapa.info',
filter: /(papapa.info|yase\d+.xyz)\/vod\/play\/id\/(\d+)/,
request: {
headers: {
Cookie: process.env.Cookie_For_Papapa,
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
},
},
beforeGetInfo: (res) => res.request.uri.href.match(/(papapa.info|yase1.xyz)\/vod\/play\/id\/(\d+)/)[2],
getInfo: {
id: (res, id) => id,
title: '.video-title>h1',
uploader: '.hr-director+a[href*="/director/"]',
videoHLS: async (res, id) => {
const res1 = await req({
uri: `https://papapa.info/vod/getPlayUrl?id=${id}&is_win=true`,
headers: {
Cookie: process.env.Cookie_For_Papapa,
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
},
}, {
check: (res) => {
try {
const json = JSON.parse(res.body);
return json.data;
} catch (error) {}
},
});
let url = res1.json.data.url.replace(/-/g, '/').replace(/_/g, '+');
url = CryptoJS.enc.Base64.parse(url).toString(CryptoJS.enc.Utf8);
let key = res.$('#play-ads').html();
let url1 = '';
for (let i = 0; i < url.length; i++) {
url1 = url1 + String.fromCharCode(url.charCodeAt(i) ^ key.charCodeAt(i % key.length));
}
if (!url1.startsWith('aHR0cHM6')) {
key = `${id}content`;
url1 = '';
for (let i = 0; i < url.length; i++) {
url1 = url1 + String.fromCharCode(url.charCodeAt(i) ^ key.charCodeAt(i % key.length));
}
}
url1 = CryptoJS.enc.Base64.parse(url1).toString(CryptoJS.enc.Utf8);
return url1;
},
},
link: (id) => `https://papapa.info/vod/play/id/${id}/sid/1/nid/1.html`,
test: {
url: 'https://papapa.info/vod/play/id/100/sid/1/nid/1.html',
name: 'papapa.info',
id: '100',
title: '带验证,匆匆忙忙拍的,下次改进吧',
uploader: 'Lareine',
videoHLS: /(papapa.info|yase\d+.xyz)\/video\/complete\/.*?\/index.m3u8/,
},
},
{ // 3atv.cc
name: '3atv.cc',
filter: /(3atv.cc|3a\d+.com|app\d+.com)\/play\/([\d-]+).html/,
getInfo: {
id: (res) => res.request.uri.href.match(/(3atv.cc|3a\d+.com|app\d+.com)\/play\/([\d-]+).html/)[2],
title: '.bread>a:last-child',
videoHLS: async (res) => {
try {
const script = res.$('script[src^="/upload/playdata/"]').attr('src');
const res1 = await req(new URL(script, res.request.uri.href).href);
const url = eval(`(function (){${res1.body};return mac_url;})();`); // eslint-disable-line no-eval
return url;
} catch (error) {
return null;
}
},
},
link: (id) => `http://3atv.cc/play/${id}.html`,
test: {
url: 'http://3atv.cc/play/9921-1-1.html',
name: '3atv.cc',
id: '9921-1-1',
title: 'c2020121_6',
videoHLS: /play\d+.com\/.*?\/index.m3u8/,
},
},
{ // zmxx22
name: 'zmxx22',
filter: /(zm[a-z]{2}\d{2}.com)\/video\/show\/id\/(\d+)/,
getInfo: {
id: (res) => res.request.uri.href.match(/(zm[a-z]{2}\d{2}.com)\/video\/show\/id\/(\d+)/)[2],
title: '.watch>.title:nth-child(1)',
videoHLS: async (res) => res.body.match(/url = '(.*?)'/)[1],
},
link: (id) => `https://www.zmxx22.com/video/show/id/${id}`,
test: {
url: 'https://www.zmxx22.com/video/show/id/40754',
name: 'zmxx22',
id: '40754',
title: 'BBAN-242 色情的身体邀请性感模特',
videoHLS: /videozm.whqhyg.com:8091\/.*?\/index\.m3u8/,
},
},
{ // avtb01
name: 'avtb01',
filter: /(avtb\d+.com)\/(\d+)\//,
getInfo: {
id: (res) => res.request.uri.href.match(/(avtb\d+.com)\/(\d+)\//)[2],
title: '#video>h1',
uploader: '.content-container>div>div>a[href^="/users/"]',
duration: ['[property="og:video:duration"]', 'content'],
videoDirect: async (res) => {
const sources = res.$('#player>source').toArray().map((i) => ({
src: res.$(i).attr('src'),
label: res.$(i).attr('label'),
})).sort((a, b) => -Math.sign(a.label.match(/^(\d+)/)[1] - b.label.match(/^(\d+)/)[1]));
return sources[0].src;
},
},
link: (id) => `https://www.avtb01.com/${id}/`,
test: {
url: 'https://www.avtb2047.com/231472/',
name: 'avtb01',
id: '231472',
title: '我要给老公戴绿帽!快操我 淫水喷不停 !有露脸',
uploader: 'A淘小管家',
duration: '249',
videoDirect: /rachno2.rubinclass.com\/media\/videos\/(mobile|mp4)\/\d+.mp4\?st=.*/,
},
},
{ // 4hu.tv
name: '4hu.tv',
filter: /(4hu.tv|4hu[a-z]\d{2}.com)\/vod\/html(.*?)\.html/,
getInfo: {
id: (res) => res.request.uri.href.match(/(4hu.tv|4hu[a-z]\d{2}.com)\/vod\/html(.*?)\.html/)[2].replace(/\//g, '-'),
title: '.detail-title>h2',
videoHLS: async (res) => {
for (const url of res.$('.playlist>ul>li>a[href*="_play_"]').toArray().map((i) => res.$(i).attr('href'))) {
const res1 = await req(url);
const [, serverNumber, pathname] = res1.body.match(/new Clappr\.Player\(\{source: "https:\/\/"\+(CN\d+)\+"(.*?\.m3u8)"/);
const script = await req({ uri: '/html5/html5.min.hls.js', cache: true });
const server = eval(`(function (){${script.body}; return ${serverNumber};})()`); // eslint-disable-line no-eval
// const res2 = await req.head(`https://${server}${pathname}`);
// if (res2 && res.statusCode === 200)
return `https://${server}${pathname}`;
}
},
videoDirect: async (res) => {
for (const url of res.$('.playlist>ul>li>a[href*="_down_"]').toArray().map((i) => res.$(i).attr('href'))) {
const res1 = await req(url);
if (res1.body.match(/httpurl = "(.*?\.mp4)"/)) return res1.body.match(/httpurl = "(.*?\.mp4)"/)[1];
}
},
},
link: (id) => `https://4hu.tv/vod/html${id.replace(/-/g, '/')}.html`,
test: {
url: 'https://4hu.tv/vod/html9/html22/40863.html',
name: '4hu.tv',
id: '9-html22-40863',
title: '110219_199 已婚妇女的淫秽比赛 つるのゆう,菊池くみこ',
videoHLS: /m3u8.\d+cdn.com\/videos\/.*?\/hls\/.*?.m3u8/,
videoDirect: /d1.xia12345.com\/dl2\/videos\/.*?\/downloads\/.*?.mp4/,
},
},
{ // 8x8x
name: '8x8x',
filter: /(8x8x.com|8x\w{4}.com)\/html\/(\d+)\//,
getInfo: {
id: (res) => res.request.uri.href.match(/(8x8x.com|8x\w{4}.com)\/html\/(\d+)\//)[2],
title: '.w_z>h3',
videoHLS: async (res) => {
const res1 = await req({ uri: '/static/main/main.js', cache: true });
const servers = res1.body.match(/window.globalConfig = \{\r\n\s*item\s*:\s*'\[(.*?)\]'/)[1].split(',').map((i) => i.match(/^"(.*)"$/)[1]);
const server = servers[Math.floor(Math.random() * servers.length)]; // 随机挑选
return server + res.$('#vpath').text();
},
videoDirect: ['#downallurl', 'href'],
},
link: (id) => `https://8x8x.com/html/${id}/`,
test: {
url: 'https://8x7n9m.com/html/35995/',
name: '8x8x',
id: '35995',
title: '无码:年轻貌美的女孩为了钱,任人玩弄玉体',
videoHLS: /\/v\/.*?\/index.m3u8/,
videoDirect: /ppp.downloadxx.com\/assets\/.*?.mp4/,
},
},
{ // avgle // TODO
name: 'avgle',
filter: /(avgle.com)\/video\/([^/]+)\//,
puppeteer: true,
// async beforeLoad(page, url, requests) {
// await page.setRequestInterception(true);
// page.on('request', (interceptedRequest) => {
// if (interceptedRequest.url() === 'https://avgle.com/templates/frontend/videojs-contrib-hls.js') {
// interceptedRequest.respond({
// body: fs.readFileSync(`${__dirname}/src/videojs-contrib-hls.js`, 'utf-8'),
// });
// } else {
// interceptedRequest.continue();
// }
// });
// page.on('console', (msg) => {
// for (let i = 0; i < msg.args().length; ++i) { console.log(`${i}: ${msg.args()[i]}`); }
// });
// },
getInfo: async (page, url, requests) => {
const info = await page.evaluate(() => ({
/* eslint-disable no-undef */
name: 'avgle',
id: window.location.href.match(/(avgle.com)\/video\/([^/]+)\//)[2],
title: document.querySelector('[property="og:title"]').getAttribute('content'),
duration: document.querySelector('[property="video:duration"]').getAttribute('content') * 1,
test: window.test,
/* eslint-enable no-undef */
}));
console.log(info);
// info.videoHLS = JSON.parse(requests.find((i) => i.resourceType === 'xhr' && i.url.includes('video-url.php')).response.body).url;
// TODO
// to debugger videoJs.xhr)(options, function(error, response) {
return info;
},
link: (id) => `https://avgle.com/video/${id}/`,
test: {
url: 'https://avgle.com/video/NxDTUTg51Tl/',
name: 'avgle',
id: 'NxDTUTg51Tl',
title: '[FC2 PPV 1789879] [COSPACO] [UNCENSORED] 美脚さんでキョウカちゃんPart3♪へんたいふしんしゃさんにえちえちな女の子にさせられちゃいました【個人撮影】 - 1',
duration: 2058,
videoHLS: /qooqlevideo.com/,
},
},
{ // kisscos
name: 'kisscos',
filter: /kisscos.net\/([^/]+)\//,
puppeteer: true,
getInfo: async (page, url, requests) => {
/* eslint-disable no-undef */
// if (await page.evaluate(() => document.querySelector('.post-tape a.current').parentElement.nextElementSibling)) {
// const url = await page.evaluate(() => document.querySelector('.post-tape a.current').parentElement.nextElementSibling.querySelector('a').href);
// list.push(url);
// }
/* eslint-enable no-undef */
const value = await page.evaluate(async () => {
/* eslint-disable no-undef */
const url = [...document.querySelector('#serverSelect').options].find((i) => i.value.includes('stream')).value;
return url;
/* eslint-enable no-undef */
});
await page.select('select#serverSelect', value);
await wait.for(() => requests.find((i) => i.resourceType === 'media' && i.url.match(/tapecontent.net/)), 30 * 1000);
const info = await page.evaluate(() => ({
/* eslint-disable no-undef */
name: 'kisscos',
id: window.location.href.match(/kisscos.net\/([^/]+)\//)[1],
title: document.querySelector('.single-title').textContent + (document.querySelector('.post-tape a.current') ? (`[${document.querySelector('.post-tape a.current').textContent}]`) : ''),
/* eslint-enable no-undef */
}));
info.videoDirect = requests.find((i) => i.resourceType === 'media' && i.url.match(/tapecontent.net/)).url;
return info;
},
link: (id) => `https://kisscos.net/${id}/`,
test: {
url: 'https://kisscos.net/fc2-ppv-1789879/',
name: 'kisscos',
id: 'fc2-ppv-1789879',
title: 'FC2-PPV-1789879 美脚さんでキョウカちゃんPart3♪へんたいふしんしゃさんにえちえちな女の子にさせられちゃいました【個人撮影】[1]',
videoDirect: /tapecontent.net\/.*.mp4/,
},
},
// 国外-第一方
{ // xvideos
name: 'xvideos',
filter: /\.xvideos.com\/video(\d+)|xvideos.com\/prof-video-click\/upload/,
request: {
headers: {
'Accept-Language': 'zh-CN',
},
},
getInfo: {
id: (res) => res.request.uri.href.match(/\/video(\d+)\//)[1],
title: ['[property="og:title"]', 'content'],
uploader: '.video-metadata .uploader-tag>.name',
duration: ['[property="og:duration"]', 'content'],
videoHLS: (res) => res.body.match(/html5player.setVideoHLS\('(.*?)'\);/)[1],
videoDirect: (res) => res.body.match(/html5player.setVideoUrlHigh\('(.*?)'\);/)[1],
},
link: (id) => `https://www.xvideos.com/video${id}/`,
test: {
url: 'https://www.xvideos.com/video59537313/_-_',
name: 'xvideos',
id: '59537313',
title: '撕裂连裤袜和体内射精 - 欺骗妻子得到硬的丈夫从邻居回来后性交',
uploader: 'Perfecthelen',
duration: '418',
videoHLS: /xvideos-cdn.com\/.*?\/videos\/hls\/.*?\/hls.m3u8/,
videoDirect: /xvideos-cdn.com\/.*?\/.*?.mp4/,
},
},
{ // pornhub
name: 'pornhub',
filter: /pornhub.com\/view_video.php\?viewkey=([a-z0-9]+)/,
getInfo: async (res) => {
if (res.request.uri.href.match(/modelhub.com\/video/)) { // TODO modelhub
return { failed: true };
}
const $ = cheerio.load(res.body);
const script = $('script').toArray().map((i) => $(i).html()).find((i) => i.match(/var\s+(flashvars_\d+)\s+=\s+/));
let flashvars;
try {
const name = script.match(/var\s+(flashvars_\d+)\s+=\s+/)[1];
flashvars = eval(`(function (){var playerObjList = {}; ${script}; return ${name};})()`); // eslint-disable-line no-eval
} catch (error) {
console.log(error);
// return {};
}
if (!flashvars || !flashvars.mediaDefinitions) {
if (!res.request.uri.href.match(/[a-z]+\.pornhub\.com/)) return {};
const lib = libs.find((i) => i.name === 'pornhub-ph666');
const url = res.request.uri.href.replace(/[a-z]+\.pornhub\.com/, 'ph666.me');
console.log(`Try ph666.me:\t${url}`);
const res1 = await req({ uri: url, ...lib.request || {} });
return lib.getInfo(res1);
}
return {
id: res.request._rp_options.uri.match(/(pornhub.com|pornhubpremium.com|ph666.me)\/view_video.php\?viewkey=([a-z0-9]+)/)[2],
name: 'pornhub',
title: flashvars.video_title,
uploader: $('.video-detailed-info>.userRow>.userInfo>.usernameWrap a').text(),
duration: flashvars.video_duration,
videoHLS: flashvars.mediaDefinitions.sort((a, b) => -Math.sign(a.quality - b.quality)).find((i) => i.format === 'hls').videoUrl,
// videoDirect: flashvars.mediaDefinitions.sort((a, b) => -Math.sign(a.quality - b.quality)).find(i => i.format === 'mp4').videoUrl,
chapters: flashvars.actionTags ? JSON.stringify(flashvars.actionTags.split(',').map((i) => {
const chapter = i.match(/^(?<title>.*?):(?<start>\d+)$/).groups;
chapter.start = chapter.start * 1000;
return chapter;
})) : '',
};
},
link: (id) => `https://cn.pornhub.com/view_video.php?viewkey=${id}`,
test: {
url: 'https://cn.pornhub.com/view_video.php?viewkey=ph5e6f7c6e43ed1',
name: 'pornhub',
id: 'ph5e6f7c6e43ed1',
title: '最新汤不热阿黑颜COS女神『Maste』大尺度私拍流出 口爆女神 灵舌搅动给你舔到爆 高清私拍60P 高清720P版',
uploader: 'z5805246',
duration: '1100',
videoHLS: /(phncdn.com|phprcdn.com)\/hls\/videos\/.*?\/master.m3u8/,
// videoDirect: /phncdn.com\/videos\/.*?.mp4/,
chapters: '[{"title":"Blowjob","start":48000},{"title":"Facial","start":839000}]',
},
},
{ // pornhub-ph666
name: 'pornhub-ph666',
filter: /ph666.me\/view_video.php\?viewkey=([a-z0-9]+)/,
request: {
headers: {
Cookie: 'fanClubInfoPop=1; authToken=2bd7671dcc71be9d; __cfduid=d3f9a622ca3dbf5daf8dc927a4866465e1603711336',
},
},
getInfo: async (res) => {
const $ = cheerio.load(res.body);
if (!$('.video-wrapper>#player').length || $('.video-wrapper>#player>.lockedFanclub').length) {
return { failed: true };
}
return libs.find((i) => i.name === 'pornhub' && i.filter.source.startsWith('pornhub.com')).getInfo(res);
},
link: (id) => `https://ph666.me/view_video.php?viewkey=${id}`,
test: {
url: 'https://ph666.me/view_video.php?viewkey=ph5fd25f4b8d256',
name: 'pornhub',
id: 'ph5fd25f4b8d256',
title: 'CUTIE CREAM TEEN LIZ JORDAN FIRST TIME THREESOME CREAMPIE + CUM MOUTH',
uploader: 'Spank Monster',
duration: '2693',
videoHLS: /(phncdn.com|phprcdn.com)\/hls\/videos\/.*?\/master.m3u8/,
// videoDirect: /(phncdn.com|phprcdn.com)\/videos\/.*?.mp4/,
chapters: '[{"title":"Blowjob","start":290000},{"title":"Handjob","start":326000},{"title":"Doggystyle","start":896000},{"title":"Blowjob","start":1932000}]',
},
},
// 国外-第三方
{ // tokyomotion osakamotion
name: 'tokyomotion',
filter: /(tokyo|osaka)motion.net\/video\/\d+/,
request: {
gzip: false,
},
getInfo: {
name: (res) => res.request.uri.host.match(/^(www.)?(?<site>(tokyo|osaka)motion).net$/).groups.site,
id: (res) => res.request.uri.href.match(/\/video\/(\d+)\//)[1],
title: ['[property="og:title"]', 'content'],
uploader: '.user-container>a>span',
duration: ['[property="video:duration"]', 'content'],
videoDirect: ['#vjsplayer>source:nth-child(1)', 'src'],
},
link: (id) => `https://www.tokyomotion.net/video/${id}/`,
test: {
url: 'https://www.tokyomotion.net/video/1563523/ncy-021',
name: 'tokyomotion',
id: '1563523',
title: 'NCY-021',
uploader: 'zhaoji987',
duration: '2311.04',
videoDirect: /tokyomotion.net\/vsrc\/hd\//,
},
},
{ // osakamotion
name: 'osakamotion',
link: (id) => `https://www.osakamotion.net/video/${id}/`,
},
{ // DaftSex
name: 'DaftSex',
filter: /(daftsex.com)\/watch\/(-?\d+_\d+)/,
getInfo: {
id: (res) => res.request.uri.href.match(/(daftsex.com)\/watch\/(-?\d+_\d+)/)[2],
title: ['[property="og:title"]', 'content'],
uploader: '.playlists>.video-item:nth-child(1)>a>.video-title',