forked from raawaa/jav-scrapy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jav.js
executable file
·490 lines (454 loc) · 18.4 KB
/
jav.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
#!/usr/bin/env node
'use strict';
var cheerio = require('cheerio');
var request = require('request');
var async = require('async');
require('colors');
var program = require('commander');
var userHome = require('user-home');
var path = require('path');
var fs = require('fs');
var mkdirp = require('mkdirp');
const _ = require('lodash');
// global var
const VERSION = require('./package.json').version;
const baseUrl = 'https://www.busjav.fun/'; // 另有备用地址: https://www.busfan.fun/, https://www.seedmm.fun/
const searchUrl = '/search';
var pageIndex = 1;
var currentPageHtml = null;
program
.version(VERSION)
.usage('[options]')
.option('-p, --parallel <num>', '设置抓取并发连接数,默认值:2', 2)
.option('-t, --timeout <num>', '自定义连接超时时间(毫秒)。默认值:30000毫秒')
.option('-l, --limit <num>', '设置抓取影片的数量上限,0为抓取全部影片。默认值:0', 0)
.option('-o, --output <file_path>', '设置磁链和封面抓取结果的保存位置,默认为当前用户的主目录下的 magnets 文件夹', path.join(userHome, 'magnets'))
.option('-s, --search <string>', '搜索关键词,可只抓取搜索结果的磁链或封面')
.option('-b, --base <url>', '自定义抓取的起始页')
.option('-x, --proxy <url>', '使用代理服务器, 例:-x http://127.0.0.1:8087')
.option('-n, --nomag', '是否抓取尚无磁链的影片')
.option('-a, --allmag', '是否抓取影片的所有磁链(默认只抓取文件体积最大的磁链)')
.option('-N, --nopic', '不抓取图片')
.parse(process.argv);
var parallel = parseInt(program.parallel);
var timeout = parseInt(program.timeout) || 30000;
var proxy = process.env.http_proxy || program.proxy;
// console.log('proxy: ', proxy);
request = request.defaults({
timeout: timeout,
headers: {
'Referer': 'http://www.javbus2.pw'
}
});
if (proxy) {
request = request.defaults({
'proxy': proxy
});
}
var count = parseInt(program.limit);
var hasLimit = (count !== 0),
targetFound = false;
var output = program.output.replace(/['"]/g, '');
console.log('========== 获取资源站点:%s =========='.green.bold, baseUrl);
console.log('并行连接数:'.green, parallel.toString().green.bold, ' ',
'连接超时设置:'.green, (timeout / 1000.0).toString().green.bold, '秒'.green);
console.log('磁链保存位置: '.green, output.green.bold);
console.log('代理服务器: '.green, (proxy ? proxy : '无').green.bold);
/****************************
*****************************
**** MAIN LOOP START ! ******
****************************
****************************/
mkdirp.sync(output);
async.during(
pageExist,
// when page exist
function (callback) {
async.waterfall(
[parseLinks, getItems],
function (err) {
pageIndex++;
if (err) return callback(err);
return callback(null);
});
},
// page not exits or finished parsing
function (err) {
if (err) {
console.log('抓取过程终止:%s', err.message);
return process.exit(1);
}
if (hasLimit && (count < 1)) {
console.log('已尝试抓取%s部影片,本次抓取完毕'.green.bold, program.limit);
} else {
console.log('抓取完毕'.green.bold);
}
return process.exit(0); // 不等待未完成的异步请求,直接结束进程
}
);
/****************************
*****************************
**** MAIN LOOP END ! ******
****************************
****************************/
function parseLinks(next) {
let $ = cheerio.load(currentPageHtml);
let links = [],
fanhao = [];
let totalCountCurPage = $('a.movie-box').length;
if (hasLimit) {
if (count > totalCountCurPage) {
$('a.movie-box').each(link_fanhao_handler);
} else {
$('a.movie-box').slice(0, count).each(link_fanhao_handler);
}
} else {
$('a.movie-box').each(link_fanhao_handler);
}
if (program.search && links.length == 1) {
targetFound = true;
}
function link_fanhao_handler() {
let link = $(this).attr('href');
links.push(link);
fanhao.push(link.split('/').pop());
}
console.log('正处理以下番号影片...\n'.green + fanhao.toString().yellow);
next(null, links);
}
function getItems(links, next) {
async.forEachOfLimit(
links,
parallel,
getItemPage,
function (err) {
if (err) {
if (err.message === 'limit') {
return next();
}
throw err;
}
console.log('===== 第%d页处理完毕 ====='.green, pageIndex);
console.log();
return next();
});
}
function pageExist(callback) {
if (hasLimit && (count < 1) || targetFound) {
return callback();
}
var url = baseUrl + (pageIndex === 1 ? '' : ('/page/' + pageIndex));
if (program.search) {
url = baseUrl + searchUrl + '/' + encodeURI(program.search) + (pageIndex === 1 ? '' : ('/' + pageIndex));
} else if (program.base) {
url = program.base + (pageIndex === 1 ? '' : ('/' + pageIndex));
} else {
// 只在没有指定搜索条件时显示
console.log('获取第%d页中的影片链接 ( %s )...'.green, pageIndex, url);
}
let retryCount = 1;
async.retry(3,
function (callback) {
let options = program.nomag ? { url: url, headers: { 'Cookie': 'existmag=all' } } : { url: url };
request
.get(options, function (err, res, body) {
if (err) {
if (err.status === 404) {
console.error('已抓取完所有页面, StatusCode:', err.status);
} else {
retryCount++;
console.error('第%d页页面获取失败:%s'.red, pageIndex, err.message);
console.error('...进行第%d次尝试...'.red, retryCount);
}
return callback(err);
}
currentPageHtml = body;
return callback(null, res);
});
},
function (err, res) {
if (err) {
if (err.status === 404) {
return callback(null, false);
}
return callback(err);
}
return callback(null, res.statusCode == 200);
});
}
function parse(script) {
let gid_r = /gid\s+=\s+(\d+)/g.exec(script);
let gid = gid_r[1];
let uc_r = /uc\s+=\s(\d+)/g.exec(script);
let uc = uc_r[1];
let img = '';
if(/img\s+=\s+'http/i.test(script)){ //如果是完整外站url地址
img = /img\s+=\s+'([^']+)'/g.exec(script)[1];
}else{ // 如果是本站相对地址
img = new URL(/img\s+=\s+'([^']+)'/g.exec(script)[1], baseUrl).toString();
}
return {
gid: gid,
img: img,
uc: uc,
lang: 'zh'
};
}
function getItemPage(link, index, callback) {
let fanhao = link.split('/').pop();
let coverFilePath = path.join(output, fanhao + '.jpg');
let magnetFilePath = path.join(output, fanhao + '.txt');
if (hasLimit) {
count--;
}
try {
fs.accessSync(coverFilePath, fs.F_OK);
fs.accessSync(magnetFilePath, fs.F_OK);
console.log(('[' + fanhao + ']').yellow.bold.inverse + ' ' + 'Alreday fetched, SKIP!'.yellow);
return callback();
} catch (e) {
request
.get(link, function (err, res, body) {
if (err) {
console.error(('[' + fanhao + ']').red.bold.inverse + ' ' + err.message.red);
return callback(null);
}
let $ = cheerio.load(body);
let script = $('script', 'body').eq(2).html();
let meta = parse(script);
meta.category = [];
$('div.col-md-3 > p').each(function (i, e) {
let text = $(e).text();
if (text.includes('發行日期:')) {
meta.date = text.replace('發行日期: ', '');
} else if (text.includes('系列:')) {
meta.series = text.replace('系列:', '');
} else if (text.includes('類別:')) {
$('div.col-md-3 > p > span.genre').each(function (idx, span) {
let $span = $(span);
if (!$span.attr('onmouseover')) {
meta.category.push($span.text());
}
});
}
});
// 提取演员
meta.actress = [];
$('span.genre').each(function (i, e) {
let $e = $(e);
if ($e.attr('onmouseover')) {
meta.actress.push($e.find('a').text());
}
});
// 提取片名
meta.title = $('h3').text();
getItemMagnet(link, meta, callback);
if (!program.nopic) {
// 所有截图link
var snapshots = [];
$('a.sample-box').each(function (i, e) {
let $e = $(e);
snapshots.push($e.attr('href'));
});
getSnapshots(link, snapshots);
}
});
}
}
function getSnapshots(link, snapshots) {
// https://pics.dmm.co.jp/digital/video/118abp00454/118abp00454jp-1.jpg
for (var i = 0; i < snapshots.length; i++) {
if(/^https?:\/\//i.test(snapshots[i])){
getSnapshot(link, snapshots[i]);
}else{
getSnapshot(link, new URL(snapshots[i], baseUrl).toString());
}
}
// console.log('截图下载完毕:' + link);
}
function getSnapshot(link, snahpshotLink) {
let fanhao = link.split('/').pop();
let itemOutput = output + '/' + fanhao;
mkdirp.sync(itemOutput);
let snapshotName = snahpshotLink.split('/').pop();
let fileFullPath = path.join(itemOutput, snapshotName);
fs.access(fileFullPath, fs.F_OK, function (err) {
if (err) {
var snapshotFileStream = fs.createWriteStream(fileFullPath + '.part');
var finished = false;
request.get(snahpshotLink)
.on('end', function () {
if (!finished) {
fs.renameSync(fileFullPath + '.part', fileFullPath);
finished = true;
console.log(('[' + fanhao + ']').green.bold.inverse + '[截图]'.yellow.inverse, fileFullPath);
}
})
.on('error', function (err) {
if (!finished) {
finished = true;
console.error(('[' + fanhao + ']').red.bold.inverse + '[截图]'.yellow.inverse, err.message.red);
}
})
.pipe(snapshotFileStream);
} else {
console.log(('[' + fanhao + ']').green.bold.inverse + '[截图]'.yellow.inverse, 'file already exists, skip!'.yellow);
}
});
}
function getItemMagnet(link, meta, done) {
function text2size(text) {
let re = /([0-9.]+)([GMTK]B)/i;
let found = _.trim(text).match(re);
if (found) {
let num = found[1];
let unit;
switch (found[2]) {
case 'GB':
unit = 1000;
break;
case 'MB':
unit = 1;
break;
default:
unit = 0;
break;
}
return num * unit;
} else {
return 0;
}
}
let fanhao = link.split('/').pop();
let itemOutput = output + '/' + fanhao;
mkdirp.sync(itemOutput);
let magnetFilePath = path.join(itemOutput, fanhao + '.json');
let jsonInfo = {
title: meta.title,
data: meta.date,
series: meta.series,
category: meta.category,
actress: meta.actress
};
fs.access(magnetFilePath, fs.F_OK, function (err) {
if (err) {
request
.get(baseUrl + '/ajax/uncledatoolsbyajax.php?gid=' + meta.gid + '&lang=' + meta.lang + '&img=' + meta.img + '&uc=' + meta.uc + '&floor=' + Math.floor(Math.random() * 1e3 + 1),
function (err, res, body) {
if (err) {
console.error(('[' + fanhao + ']').red.bold.inverse + ' ' + err.message.red);
return done(null); // one magnet fetch fail, do not crash the whole task.
}
const $ = cheerio.load(body);
if ($('tr').eq(-1).children('td').eq(1).children('a').text()) {
let mag_sizes = $('tr').map(function readMagnetAndSize(i, e) {
let anchorInSecondTableCell = $(e).children('td').eq(1).children('a');
return {
magnet: anchorInSecondTableCell.attr('href'),
size: text2size(anchorInSecondTableCell.text()),
sizeText: _.trim(anchorInSecondTableCell.text())
};
}).get();
mag_sizes = _.orderBy(mag_sizes, 'size', 'desc');
const magOrdered = _.map(mag_sizes, x => x.magnet);
jsonInfo.magnets = program.allmag ? magOrdered : _.slice(magOrdered, 0, 1);
fs.writeFile(path.join(itemOutput, fanhao + '-magnet.txt'), jsonInfo.magnets.toString().replace(',', '\n'), function (err) {
if (err) {
throw err;
}
console.log(('[' + fanhao + ']').green.bold.inverse + '[磁链]'.yellow.inverse);
console.log(jsonInfo.magnets);
});
}
fs.writeFile(magnetFilePath, JSON.stringify(jsonInfo, '', 4),
function (err) {
if (err) {
throw err;
}
console.log(('[' + fanhao + ']').green.bold.inverse + '[信息]'.yellow.inverse + '影片信息已抓取');
if (!program.nopic) {
getItemCover(link, meta, done);
} else { return done(); }
});
});
} else {
console.log(('[' + fanhao + ']').green.bold.inverse + '[信息]'.yellow.inverse, 'file already exists, skip!'.yellow);
if (!program.nopic) getItemCover(link, meta, done);
else return done();
}
});
}
function getItemCover(link, meta, done) {
var fanhao = link.split('/').pop();
var filename = fanhao + 'l.jpg';
let itemOutput = output + '/' + fanhao;
mkdirp.sync(itemOutput);
var fileFullPath = path.join(itemOutput, filename);
fs.access(fileFullPath, fs.F_OK, function (err) {
if (err) {
var coverFileStream = fs.createWriteStream(fileFullPath + '.part');
var finished = false;
request.get(meta.img)
.on('end', function () {
if (!finished) {
fs.renameSync(fileFullPath + '.part', fileFullPath);
finished = true;
console.error(('[' + fanhao + ']').green.bold.inverse + '[封面]'.yellow.inverse, fileFullPath);
// getItemSmallCover(link, meta, done);
return done();
}
})
.on('error', function (err) {
if (!finished) {
finished = true;
console.error(('[' + fanhao + ']').red.bold.inverse + '[封面]'.yellow.inverse, err.message.red);
// getItemSmallCover(link, meta, done);
return done();
}
})
.pipe(coverFileStream);
} else {
console.log(('[' + fanhao + ']').green.bold.inverse + '[封面]'.yellow.inverse, 'file already exists, skip!'.yellow);
// getItemSmallCover(link, meta, done);
return done();
}
});
}
// 获取封面小图
function getItemSmallCover(link, meta, done) {
// 大图地址:
// https://pics.javbus.info/cover/5cfb_b.jpg
// 小图地址:
// https://pics.javbus.info/thumb/5cfb.jpg
var fanhao = link.split('/').pop();
var filename = fanhao + 's.jpg';
let itemOutput = output + '/' + fanhao;
mkdirp.sync(itemOutput);
var fileFullPath = path.join(itemOutput, filename);
fs.access(fileFullPath, fs.F_OK, function (err) {
if (err) {
var coverFileStream = fs.createWriteStream(fileFullPath + '.part');
var finished = false;
request.get(meta.img.replace('cover', 'thumb').replace('_b', ''))
.on('end', function () {
if (!finished) {
fs.renameSync(fileFullPath + '.part', fileFullPath);
finished = true;
console.error(('[' + fanhao + ']').green.bold.inverse + '[小封面]'.yellow.inverse, fileFullPath);
return done();
}
})
.on('error', function (err) {
if (!finished) {
finished = true;
console.error(('[' + fanhao + ']').red.bold.inverse + '[小封面]'.yellow.inverse, err.message.red);
return done();
}
})
.pipe(coverFileStream);
} else {
console.log(('[' + fanhao + ']').green.bold.inverse + '[小封面]'.yellow.inverse, 'file already exists, skip!'.yellow);
return done();
}
});
}