forked from webrecorder/browsertrix-crawler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
crawler.js
1360 lines (1058 loc) · 38.9 KB
/
crawler.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
const child_process = require("child_process");
const path = require("path");
const fs = require("fs");
const os = require("os");
const fsp = require("fs/promises");
const http = require("http");
const url = require("url");
// to ignore HTTPS error for HEAD check
const HTTPS_AGENT = require("https").Agent({
rejectUnauthorized: false,
});
const HTTP_AGENT = require("http").Agent();
const fetch = require("node-fetch");
const puppeteer = require("puppeteer-core");
const { Cluster } = require("puppeteer-cluster");
const { Page } = require("puppeteer-core");
const { RedisCrawlState, MemoryCrawlState } = require("./util/state");
const AbortController = require("abort-controller");
const Sitemapper = require("sitemapper");
const { v4: uuidv4 } = require("uuid");
const yaml = require("js-yaml");
const warcio = require("warcio");
const behaviors = fs.readFileSync(path.join(__dirname, "behaviors.js"), {encoding: "utf8"});
const TextExtract = require("./util/textextract");
const { initStorage, getFileSize, getDirSize, interpolateFilename } = require("./util/storage");
const { ScreenCaster, WSTransport, RedisPubSubTransport } = require("./util/screencaster");
const { parseArgs } = require("./util/argParser");
const { initRedis } = require("./util/redis");
const { getBrowserExe, loadProfile, chromeArgs, getDefaultUA, evaluateWithCLI } = require("./util/browser");
const { BEHAVIOR_LOG_FUNC, HTML_TYPES, DEFAULT_SELECTORS } = require("./util/constants");
const { BlockRules } = require("./util/blockrules");
const crypto = require('crypto')
const shasum = crypto.createHash('sha1')
// ============================================================================
class Crawler {
constructor() {
this.headers = {};
this.crawlState = null;
this.emulateDevice = null;
// pages file
this.pagesFH = null;
this.crawlId = process.env.CRAWL_ID || os.hostname();
this.startTime = Date.now();
// was the limit hit?
this.limitHit = false;
this.userAgent = "";
const res = parseArgs();
this.params = res.parsed;
this.origConfig = res.origConfig;
this.saveStateFiles = [];
this.lastSaveTime = 0;
this.saveStateInterval = this.params.saveStateInterval * 1000;
this.debugLogging = this.params.logging.includes("debug");
if (this.params.profile) {
this.statusLog("With Browser Profile: " + this.params.profile);
}
this.emulateDevice = this.params.emulateDevice;
this.debugLog("Seeds", this.params.scopedSeeds);
this.captureBasePrefix = `http://${process.env.PROXY_HOST}:${process.env.PROXY_PORT}/${this.params.collection}/record`;
this.capturePrefix = this.captureBasePrefix + "/id_/";
this.gotoOpts = {
waitUntil: this.params.waitUntil,
timeout: this.params.timeout
};
// root collections dir
this.collDir = path.join(this.params.cwd, "collections", this.params.collection);
// pages directory
this.pagesDir = path.join(this.collDir, "pages");
// pages file
this.pagesFile = path.join(this.pagesDir, "pages.jsonl");
this.blockRules = null;
this.errorCount = 0;
this.exitCode = 0;
this.done = false;
this.sizeExceeded = false;
this.finalExit = false;
this.behaviorLastLine = null;
// The Redis URL for cross-crawl deduplication
this.redisDedup = null;
this.dedupRegexPatterns = new Array();
// The total count of skipped pages due to deduplication
this.totalSkipped = 0;
}
statusLog(...args) {
console.log(...args);
}
debugLog(...args) {
if (this.debugLogging) {
console.log(...args);
}
}
configureUA() {
// override userAgent
if (this.params.userAgent) {
if (this.emulateDevice) {
this.emulateDevice.userAgent = this.params.userAgent;
}
this.userAgent = this.params.userAgent;
return;
}
// if device set, it overrides the default Chrome UA
if (this.emulateDevice) {
this.userAgent = this.emulateDevice.userAgent;
} else {
this.userAgent = getDefaultUA();
}
// suffix to append to default userAgent
if (this.params.userAgentSuffix) {
this.userAgent += " " + this.params.userAgentSuffix;
if (this.emulateDevice) {
this.emulateDevice.userAgent += " " + this.params.userAgentSuffix;
}
}
}
async initCrawlState() {
const redisUrl = this.params.redisStoreUrl;
if (redisUrl) {
if (!redisUrl.startsWith("redis://")) {
throw new Error("stateStoreUrl must start with redis:// -- Only redis-based store currently supported");
}
let redis;
// Do not wait for Redis connection indefinitely.
let redisRetryCount = 0;
const maxRedisRetries = 10;
while (redisRetryCount < maxRedisRetries) {
try {
redis = await initRedis(redisUrl);
break;
} catch (e) {
//throw new Error("Unable to connect to state store Redis: " + redisUrl);
console.warn(`Waiting for redis at ${redisUrl}, ${redisRetryCount} out of ${maxRedisRetries} retries`);
await this.sleep(500);
}
}
// Check if Redis connection is OK
if (redisRetryCount < maxRedisRetries - 1) {
this.statusLog(`Storing state via Redis ${redisUrl} @ key prefix "${this.crawlId}"`);
this.crawlState = new RedisCrawlState(redis, this.params.crawlId, this.params.timeout * 2, os.hostname());
} else {
this.statusLog(`Redis connection has failed. State is: ${this.redis.state}. Storing state in memory instead.`);
this.crawlState = new MemoryCrawlState();
}
} else {
this.statusLog("Storing state in memory");
this.crawlState = new MemoryCrawlState();
}
// -----------------------------------------------------
// Check if we have activated cross-crawl deduplication.
// -----------------------------------------------------
if (this.params.crossCrawlDeduplicationPolicy === "curl" ||
this.params.crossCrawlDeduplicationPolicy === "crawl") {
const redisDedupUrl = this.params.crossCrawlDeduplicationRedisUrl;
// Set up Redis for deduplication
if (!redisDedupUrl) {
throw new Error("Cross-crawl deduplication policy selected but no redis URL specified");
}
this.redisDedup = await initRedis(redisDedupUrl);
console.log("Successfully set up Redis connection for cross-crawl deduplication");
// Set up the deduplication regex patterns
const dedupRegexPatternKeys = await this.redisDedup.keys("dedup-regex-pattern:*");
for (var i = 0; i < dedupRegexPatternKeys.length; i++) {
this.dedupRegexPatterns.push(await this.redisDedup.get(dedupRegexPatternKeys[i]));
console.log("Loaded regex: " + dedupRegexPatternKeys[i] + " - " + await this.redisDedup.get(dedupRegexPatternKeys[i]))
}
console.log("Successfully loaded " + dedupRegexPatternKeys.length + " deduplication regex patterns");
}
if (this.params.saveState === "always" && this.params.saveStateInterval) {
this.statusLog(`Saving crawl state every ${this.params.saveStateInterval} seconds, keeping last ${this.params.saveStateHistory} states`);
}
return this.crawlState;
}
initScreenCaster() {
let transport;
if (this.params.screencastPort) {
transport = new WSTransport(this.params.screencastPort);
this.debugLog(`Screencast server started on: ${this.params.screencastPort}`);
} else if (this.params.redisStoreUrl && this.params.screencastRedis) {
transport = new RedisPubSubTransport(this.params.redisStoreUrl, this.crawlId);
this.debugLog("Screencast enabled via redis pubsub");
}
if (!transport) {
return null;
}
return new ScreenCaster(transport, this.params.workers);
}
bootstrap() {
let opts = {};
if (this.params.logging.includes("pywb")) {
opts = {stdio: "inherit", cwd: this.params.cwd};
}
else{
opts = {stdio: "ignore", cwd: this.params.cwd};
}
this.browserExe = getBrowserExe();
this.configureUA();
this.headers = {"User-Agent": this.userAgent};
const subprocesses = [];
subprocesses.push(child_process.spawn("redis-server", {...opts, cwd: "/tmp/"}));
if (this.params.overwrite) {
console.log(`Clearing ${this.collDir} before starting`);
try {
fs.rmSync(this.collDir, { recursive: true, force: true });
} catch(e) {
console.warn(e);
}
}
child_process.spawnSync("wb-manager", ["init", this.params.collection], opts);
opts.env = {...process.env, COLL: this.params.collection, ROLLOVER_SIZE: this.params.rolloverSize};
subprocesses.push(child_process.spawn("uwsgi", [path.join(__dirname, "uwsgi.ini")], opts));
process.on("exit", () => {
for (const proc of subprocesses) {
proc.kill();
}
});
if (!this.params.headless && !process.env.NO_XVFB) {
child_process.spawn("Xvfb", [
process.env.DISPLAY,
"-listen",
"tcp",
"-screen",
"0",
process.env.GEOMETRY,
"-ac",
"+extension",
"RANDR"
]);
}
}
get puppeteerArgs() {
// Puppeter Options
return {
headless: this.params.headless,
executablePath: this.browserExe,
handleSIGINT: false,
handleSIGTERM: false,
handleSIGHUP: false,
ignoreHTTPSErrors: true,
args: chromeArgs(!process.env.NO_PROXY, this.userAgent),
userDataDir: this.profileDir,
defaultViewport: null,
};
}
async run() {
await fsp.mkdir(this.params.cwd, {recursive: true});
this.bootstrap();
let status;
try {
await this.crawl();
status = (this.exitCode === 0 ? "done" : "interrupted");
} catch(e) {
console.error("Crawl failed");
console.error(e);
this.exitCode = 9;
status = "failing";
if (await this.crawlState.incFailCount()) {
status = "failed";
}
// Write exception message to stats file
// ****************************
try {
await fsp.writeFile(this.params.statsFilename, JSON.stringify(e, Object.getOwnPropertyNames(e), 2), { flag: "a+" });
} catch (err) {
console.warn("Stats output failed", err);
}
// ****************************
} finally {
console.log(status);
if (this.crawlState) {
await this.crawlState.setStatus(status);
}
process.exit(this.exitCode);
}
}
_behaviorLog({data, type}) {
let behaviorLine;
console.log("Behavior log: " + data);
switch (type) {
case "info":
behaviorLine = JSON.stringify(data);
if (behaviorLine != this._behaviorLastLine) {
console.log(behaviorLine);
this._behaviorLastLine = behaviorLine;
}
break;
case "debug":
default:
if (this.params.behaviorsLogDebug) {
console.log("behavior debug: " + JSON.stringify(data));
}
}
}
async crawlPage({page, data}) {
try {
if (this.screencaster) {
await this.screencaster.screencastTarget(page.target(), data.url);
}
if (this.emulateDevice) {
await page.emulate(this.emulateDevice);
}
if (this.params.profile) {
await page._client.send("Network.setBypassServiceWorker", {bypass: true});
}
await page.evaluateOnNewDocument("Object.defineProperty(navigator, \"webdriver\", {value: false});");
if (this.params.behaviorOpts && !page.__bx_inited) {
await page.exposeFunction(BEHAVIOR_LOG_FUNC, (logdata) => this._behaviorLog(logdata));
await page.evaluateOnNewDocument(behaviors + `;\nself.__bx_behaviors.init(${this.params.behaviorOpts});`);
page.__bx_inited = true;
}
// run custom driver here
await this.driver({page, data, crawler: this});
const title = await page.title();
let text = "";
if (this.params.text && page.isHTMLPage) {
const client = await page.target().createCDPSession();
const result = await client.send("DOM.getDocument", {"depth": -1, "pierce": true});
text = await new TextExtract(result).parseTextFromDom();
}
await this.writePage(data, title, this.params.text ? text : null);
if (this.params.behaviorOpts) {
if (!page.isHTMLPage) {
console.log("Skipping behaviors for non-HTML page");
} else {
await Promise.allSettled(page.frames().map(frame => evaluateWithCLI(frame, "self.__bx_behaviors.run();")));
// also wait for general net idle
await this.netIdle(page);
}
}
await this.writeStats();
await this.checkLimits();
await this.serializeConfig();
} catch (e) {
console.warn(e);
}
}
async createWARCInfo(filename) {
const warcVersion = "WARC/1.0";
const type = "warcinfo";
const packageFileJSON = JSON.parse(await fsp.readFile("../app/package.json"));
const warcioPackageJSON = JSON.parse(await fsp.readFile("/app/node_modules/warcio/package.json"));
const pywbVersion = child_process.execSync("pywb -V", {encoding: "utf8"}).trim().split(" ")[1];
const info = {
"software": `Browsertrix-Crawler ${packageFileJSON.version} (with warcio.js ${warcioPackageJSON.version} pywb ${pywbVersion})`,
"format": "WARC File Format 1.0"
};
const warcInfo = {...info, ...this.params.warcInfo, };
const record = await warcio.WARCRecord.createWARCInfo({filename, type, warcVersion}, warcInfo);
const buffer = await warcio.WARCSerializer.serialize(record, {gzip: true});
return buffer;
}
async healthCheck(req, res) {
const threshold = this.params.workers * 2;
const pathname = url.parse(req.url).pathname;
switch (pathname) {
case "/healthz":
if (this.errorCount < threshold) {
console.log(`health check ok, num errors ${this.errorCount} < ${threshold}`);
res.writeHead(200);
res.end();
}
return;
}
console.log(`health check failed: ${this.errorCount} >= ${threshold}`);
res.writeHead(503);
res.end();
}
async checkLimits() {
let interrupt = false;
if (this.params.sizeLimit) {
const dir = path.join(this.collDir, "archive");
const size = await getDirSize(dir);
if (size >= this.params.sizeLimit) {
console.log(`Size threshold reached ${size} >= ${this.params.sizeLimit}, stopping`);
interrupt = true;
this.sizeExceeded = true;
}
}
if (this.params.timeLimit) {
const elapsed = (Date.now() - this.startTime) / 1000;
if (elapsed > this.params.timeLimit) {
console.log(`Time threshold reached ${elapsed} > ${this.params.timeLimit}, stopping`);
interrupt = true;
}
}
if (interrupt) {
this.crawlState.setDrain(true);
this.exitCode = 11;
}
}
async crawl() {
this.profileDir = await loadProfile(this.params.profile);
if (this.params.healthCheckPort) {
this.healthServer = http.createServer((...args) => this.healthCheck(...args));
this.statusLog(`Healthcheck server started on ${this.params.healthCheckPort}`);
this.healthServer.listen(this.params.healthCheckPort);
}
try {
this.driver = require(this.params.driver);
} catch(e) {
console.warn(e);
return;
}
await this.initCrawlState();
let initState = await this.crawlState.getStatus();
while (initState === "debug") {
console.log("Paused for debugging, will continue after manual resume");
await this.sleep(60);
initState = await this.crawlState.getStatus();
}
if (this.params.generateWACZ) {
this.storage = initStorage();
}
// Puppeteer Cluster init and options
this.cluster = await Cluster.launch({
concurrency: this.params.newContext,
maxConcurrency: this.params.workers,
skipDuplicateUrls: false,
timeout: this.params.timeout * 2,
puppeteerOptions: this.puppeteerArgs,
puppeteer,
monitor: this.params.logging.includes("stats")
});
this.cluster.jobQueue = this.crawlState;
await this.crawlState.setStatus("running");
if (this.params.state) {
await this.crawlState.load(this.params.state, this.params.scopedSeeds, true);
}
this.cluster.task((opts) => this.crawlPage(opts));
await this.initPages();
if (this.params.blockRules && this.params.blockRules.length) {
this.blockRules = new BlockRules(this.params.blockRules, this.captureBasePrefix, this.params.blockMessage, (text) => this.debugLog(text));
}
this.screencaster = this.initScreenCaster();
for (let i = 0; i < this.params.scopedSeeds.length; i++) {
const seed = this.params.scopedSeeds[i];
if (!await this.queueUrl(null, i, seed.url, 0, 0)) {
if (this.limitHit) {
break;
}
}
if (seed.sitemap) {
await this.parseSitemap(seed.sitemap, i);
}
}
await this.cluster.idle();
await this.cluster.close();
await this.serializeConfig(true);
this.writeStats();
if (this.pagesFH) {
await this.pagesFH.sync();
await this.pagesFH.close();
}
// extra wait for all resources to land into WARCs
await this.awaitPendingClear();
if (this.params.combineWARC) {
await this.combineWARC();
}
if (this.params.generateCDX) {
this.statusLog("Generating CDX");
await this.awaitProcess(child_process.spawn("wb-manager", ["reindex", this.params.collection], {stdio: "inherit", cwd: this.params.cwd}));
}
if (this.params.generateWACZ && (this.exitCode === 0 || this.finalExit || this.sizeExceeded)) {
await this.generateWACZ();
if (this.sizeExceeded) {
console.log(`Clearing ${this.collDir} before exit`);
try {
fs.rmSync(this.collDir, { recursive: true, force: true });
} catch(e) {
console.warn(e);
}
}
}
if (this.exitCode === 0 && this.params.waitOnDone && this.params.redisStoreUrl && !this.finalExit) {
this.done = true;
this.statusLog("All done, waiting for signal...");
await this.crawlState.setStatus("done");
// wait forever until signal
await new Promise(() => {});
}
}
async generateWACZ() {
this.statusLog("Generating WACZ");
const archiveDir = path.join(this.collDir, "archive");
// Get a list of the warcs inside
const warcFileList = await fsp.readdir(archiveDir);
// is finished (>0 pages and all pages written)
const isFinished = await this.crawlState.isFinished();
console.log(`Num WARC Files: ${warcFileList.length}`);
if (!warcFileList.length) {
// if finished, just return
if (isFinished) {
return;
}
throw new Error("No WARC Files, assuming crawl failed");
}
// Build the argument list to pass to the wacz create command
const waczFilename = this.params.collection.concat(".wacz");
const waczPath = path.join(this.collDir, waczFilename);
const createArgs = ["create", "--split-seeds", "-o", waczPath, "--pages", this.pagesFile];
if (process.env.WACZ_SIGN_URL) {
createArgs.push("--signing-url");
createArgs.push(process.env.WACZ_SIGN_URL);
if (process.env.WACZ_SIGN_TOKEN) {
createArgs.push("--signing-token");
createArgs.push(process.env.WACZ_SIGN_TOKEN);
}
}
createArgs.push("-f");
warcFileList.forEach((val, index) => createArgs.push(path.join(archiveDir, val))); // eslint-disable-line no-unused-vars
// create WACZ
const waczResult = await this.awaitProcess(child_process.spawn("wacz" , createArgs, {stdio: "inherit"}));
if (waczResult !== 0) {
console.log("create result", waczResult);
throw new Error("Unable to write WACZ successfully");
}
this.debugLog(`WACZ successfully generated and saved to: ${waczPath}`);
// Verify WACZ
/*
const validateArgs = ["validate"];
validateArgs.push("-f");
validateArgs.push(waczPath);
const waczVerifyResult = await this.awaitProcess(child_process.spawn("wacz", validateArgs, {stdio: "inherit"}));
if (waczVerifyResult !== 0) {
console.log("validate", waczVerifyResult);
throw new Error("Unable to verify WACZ created successfully");
}
*/
if (this.storage) {
const filename = process.env.STORE_FILENAME || "@[email protected]";
const targetFilename = interpolateFilename(filename, this.crawlId);
await this.storage.uploadCollWACZ(waczPath, targetFilename, isFinished);
}
}
awaitProcess(proc) {
return new Promise((resolve) => {
proc.on("close", (code) => resolve(code));
});
}
awaitProcessGetResultAsString(proc) {
var result = '';
return new Promise((resolve) => {
proc.stdout.on('data', function(data) {
result += data.toString();
});
proc.on('close', function(code) {
resolve(result);
});
});
}
async writeStats() {
if (this.params.statsFilename) {
const total = this.cluster.allTargetCount;
const workersRunning = this.cluster.workersBusy.length;
const numCrawled = total - (await this.cluster.jobQueue.size()) - workersRunning;
const limit = {max: this.params.limit || 0, hit: this.limitHit};
const dedupedPages = this.totalSkipped;
const stats = {numCrawled, workersRunning, total, limit, dedupedPages};
try {
await fsp.writeFile(this.params.statsFilename, JSON.stringify(stats, null, 2));
} catch (err) {
console.warn("Stats output failed", err);
}
}
}
async loadPage(page, urlData, selectorOptsList = DEFAULT_SELECTORS) {
const {url, seedId, depth, extraHops = 0} = urlData;
let isHTMLPage = true;
if (!await this.isHTML(url)) {
isHTMLPage = false;
try {
if (await this.directFetchCapture(url)) {
return;
}
} catch (e) {
// ignore failed direct fetch attempt, do browser-based capture
}
}
if (this.blockRules) {
await this.blockRules.initPage(page);
}
let ignoreAbort = false;
// Detect if ERR_ABORTED is actually caused by trying to load a non-page (eg. downloadable PDF),
// if so, don't report as an error
page.once("requestfailed", (req) => {
ignoreAbort = shouldIgnoreAbort(req);
});
const gotoOpts = isHTMLPage ? this.gotoOpts : "domcontentloaded";
try {
await page.goto(url, gotoOpts);
if (this.errorCount > 0) {
this.statusLog(`Page loaded, resetting error count ${this.errorCount} to 0`);
this.errorCount = 0;
}
} catch (e) {
let msg = e.message || "";
if (!msg.startsWith("net::ERR_ABORTED") || !ignoreAbort) {
this.statusLog(`ERROR: ${url}: ${msg}`);
this.errorCount++;
}
}
page.isHTMLPage = isHTMLPage;
if (!isHTMLPage) {
return;
}
const seed = this.params.scopedSeeds[seedId];
await this.checkCF(page);
await this.netIdle(page);
// skip extraction if at max depth
if (seed.isAtMaxDepth(depth) || !selectorOptsList) {
return;
}
for (const opts of selectorOptsList) {
const links = await this.extractLinks(page, opts);
await this.queueInScopeUrls(page, seedId, links, depth, extraHops);
}
const specialElems = await this.extractSpecialLinks(page);
await this.queueInScopeUrls(page, seedId, specialElems, depth, extraHops);
//console.log("Queued in special URLs: " + JSON.stringify(specialElems));
}
async netIdle(page) {
if (!this.params.netIdleWait) {
return;
}
// in case page starts loading via fetch/xhr immediately after page load,
// we want to ensure we don't exit too early
await this.sleep(0.5);
try {
await page.waitForNetworkIdle({timeout: this.params.netIdleWait * 1000});
} catch (e) {
console.log("note: waitForNetworkIdle timed out, ignoring");
// ignore, continue
}
}
async extractSpecialLinks(page) {
const results = [];
const selector= "iframe";
const extract = "src";
const loadFunc = (selector, extract) => {
return [...document.querySelectorAll(selector)].map(elem => elem.getAttribute(extract));
};
try {
const linkResults = await Promise.allSettled(page.frames().map(frame => frame.evaluate(loadFunc, selector, extract)));
if (linkResults) {
for (const linkResult of linkResults) {
if (!linkResult.value) continue;
for (const link of linkResult.value) {
if (!link) continue;
if (link.includes("https://reporter-podcast.podigee.io")) {
results.push(link);
}
}
}
}
} catch (e) {
console.warn("Link Extraction failed", e);
}
return results;
}
async extractLinks(page, {selector = "a[href]", extract = "href", isAttribute = false} = {}) {
const results = [];
const loadProp = (selector, extract) => {
return [...document.querySelectorAll(selector)].map(elem => elem[extract]);
};
const loadAttr = (selector, extract) => {
return [...document.querySelectorAll(selector)].map(elem => elem.getAttribute(extract));
};
const loadFunc = isAttribute ? loadAttr : loadProp;
try {
const linkResults = await Promise.allSettled(page.frames().map(frame => frame.evaluate(loadFunc, selector, extract)));
if (linkResults) {
for (const linkResult of linkResults) {
if (!linkResult.value) continue;
for (const link of linkResult.value) {
results.push(link);
}
}
}
} catch (e) {
console.warn("Link Extraction failed", e);
}
return results;
}
async queueInScopeUrls(page, seedId, urls, depth, extraHops = 0) {
try {
depth += 1;
const seed = this.params.scopedSeeds[seedId];
// new number of extra hops, set if this hop is out-of-scope (oos)
const newExtraHops = extraHops + 1;
for (const possibleUrl of urls) {
const res = seed.isIncluded(possibleUrl, depth, newExtraHops);
if (!res) {
continue;
}
const {url, isOOS} = res;
if (url) {
await this.queueUrl(page, seedId, url, depth, isOOS ? newExtraHops : extraHops);
}
}
} catch (e) {
console.error("Queuing Error: ", e);
}
}
async checkCF(page) {
try {
while (await page.$("div.cf-browser-verification.cf-im-under-attack")) {
this.statusLog("Cloudflare Check Detected, waiting for reload...");
await this.sleep(5.5);
}
} catch (e) {
//console.warn("Check CF failed, ignoring");
//console.warn(e);
}
}
async checkForCrossCrawlDeduplication(url, page) {
// First check if we have activated cross-crawl deduplication.
if (!this.params.crossCrawlDeduplicationPolicy ||
this.params.crossCrawlDeduplicationPolicy === "none") {
//this.statusLog("Not using cross-crawl deduplication policy.");
return true;
}
if (!page) {
return true;
}
if (!await this.isHTML(url)) {
return true;
}
// The connection to Redis, for cross-crawl deduplication hashes, has been already done
// during the crawl initialization phase.
// 0. Compute content hashsum,
// -- Sanitize the content string first
// 1. Compare with redis entry:
// -- if present, do not add to new list
// -- if not present, save (url, hash) in redis db, then add link to new list
// 2. Approve/reject url into/from frontier.
const startPage = new Date();
var text = "";
if (this.params.crossCrawlDeduplicationPolicy === "crawl") {
//this.statusLog("Using cross-crawl deduplication policy: crawl");
const pageToCheck = page;
const title = await page.title;
console.log("Dedup page title before=" + title);
await pageToCheck.goto(url, this.gotoOpts);
const title2 = await page.title;
console.log("Dedup page title after=" + title2);
const client = await pageToCheck.target().createCDPSession();
const result = await client.send("DOM.getDocument", {"depth": -1, "pierce": true});
text = await new TextExtract(result).parseTextFromDom();
}
else if (this.params.crossCrawlDeduplicationPolicy === "curl") {
let result = await this.awaitProcessGetResultAsString(child_process.spawn("curl", ['-sL' , url]));
text = await result.toString('UTF8');
}
else {
this.statusLog("Invalid cross-crawl deduplication policy: " + this.params.crossCrawlDeduplicationPolicy);
return true;
}
const stopPage = new Date();
const durationPage = (stopPage - startPage);
//console.log("Text before: " + text);
// Remove unnecessary elements from the page. Note that the "g" flag indicates "replace all", and
// the "s" flag takes newlines into account as well.
for (var i = 0; i < this.dedupRegexPatterns.length; i++) {
text = text.replace(new RegExp(this.dedupRegexPatterns[i], 'gs'),"");
}
//console.log("Text after: " + text);
// Hash the extracted text
const hash = crypto.createHash('sha1').update(text).digest('hex');
// The Redis key to check will be of the form: "dedupPolicy:url"
const key = this.params.crossCrawlDeduplicationPolicy + ":" + url;
const val = await this.redisDedup.get(key);
if (val) {
if ((val === hash)) {
// The hash is the same, we skip this url (don't queue it).
this.totalSkipped++;
//console.log("Skipping URL because it has the same hash as a previous crawl: " + url);
return false;
}
}
// Update the hash for this url
await this.redisDedup.set(key,hash);