forked from simplecrawler/simplecrawler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrawler.js
2007 lines (1712 loc) · 75.2 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
/**
* @file simplecrawler is a straightforward, event driven web crawler
* @author Christopher Giffard <[email protected]>
* @author Fredrik Ekelund <[email protected]>
*/
var FetchQueue = require("./queue.js"),
CookieJar = require("./cookies.js"),
packageJson = require("../package.json");
var http = require("http"),
https = require("https"),
EventEmitter = require("events").EventEmitter,
uri = require("urijs"),
async = require("async"),
zlib = require("zlib"),
util = require("util"),
iconv = require("iconv-lite"),
robotsTxtParser = require("robots-parser");
var QUEUE_ITEM_INITIAL_DEPTH = 1;
/**
* Creates a new crawler
* @class
* @param {String} initialURL The initial URL to fetch. The hostname that the crawler will confine requests to by default is inferred from this URL.
* @return {Crawler} Returns the crawler instance to enable chained API calls
*/
var Crawler = function(initialURL) {
// Allow the crawler to be initialized without the `new` operator. This is
// handy for chaining API calls
if (!(this instanceof Crawler)) {
return new Crawler(initialURL);
}
if (arguments.length > 1) {
throw new Error("Since 1.0.0, simplecrawler takes a single URL when initialized. Protocol, hostname, port and path are inferred from that argument.");
}
if (typeof initialURL !== "string") {
throw new Error("The crawler needs a URL string to know where to start crawling");
}
EventEmitter.call(this);
var crawler = this,
parsedURL = uri(initialURL).normalize();
/**
* Controls which URL to request first
* @type {String}
*/
this.initialURL = initialURL;
/**
* Determines what hostname the crawler should limit requests to (so long as
* {@link Crawler#filterByDomain} is true)
* @type {String}
*/
this.host = parsedURL.hostname();
/**
* Determines the interval at which new requests are spawned by the crawler,
* as long as the number of open requests is under the
* {@link Crawler#maxConcurrency} cap.
* @type {Number}
*/
this.interval = 250;
/**
* Maximum request concurrency. If necessary, simplecrawler will increase
* node's http agent maxSockets value to match this setting.
* @type {Number}
*/
this.maxConcurrency = 5;
/**
* Maximum time we'll wait for headers
* @type {Number}
*/
this.timeout = 300000; // 5 minutes
/**
* Maximum time we'll wait for async listeners
* @type {Number}
*/
this.listenerTTL = 10000; // 10 seconds
/**
* Crawler's user agent string
* @type {String}
* @default "Node/simplecrawler <version> (https://github.com/simplecrawler/simplecrawler)"
*/
this.userAgent =
"Node/" + packageJson.name + " " + packageJson.version +
" (" + packageJson.repository.url + ")";
/**
* Queue for requests. The crawler can use any implementation so long as it
* uses the same interface. The default queue is simply backed by an array.
* @type {FetchQueue}
*/
this.queue = new FetchQueue();
/**
* Controls whether the crawler respects the robots.txt rules of any domain.
* This is done both with regards to the robots.txt file, and `<meta>` tags
* that specify a `nofollow` value for robots. The latter only applies if
* the default {@link Crawler#discoverResources} method is used, though.
* @type {Boolean}
*/
this.respectRobotsTxt = true;
/**
* Controls whether the crawler is allowed to change the
* {@link Crawler#host} setting if the first response is a redirect to
* another domain.
* @type {Boolean}
*/
this.allowInitialDomainChange = false;
/**
* Controls whether HTTP responses are automatically decompressed based on
* their Content-Encoding header. If true, it will also assign the
* appropriate Accept-Encoding header to requests.
* @type {Boolean}
*/
this.decompressResponses = true;
/**
* Controls whether HTTP responses are automatically character converted to
* standard JavaScript strings using the {@link https://www.npmjs.com/package/iconv-lite|iconv-lite}
* module before emitted in the {@link Crawler#event:fetchcomplete} event.
* The character encoding is interpreted from the Content-Type header
* firstly, and secondly from any `<meta charset="xxx" />` tags.
* @type {Boolean}
*/
this.decodeResponses = false;
/**
* Controls whether the crawler fetches only URL's where the hostname
* matches {@link Crawler#host}. Unless you want to be crawling the entire
* internet, I would recommend leaving this on!
* @type {Boolean}
*/
this.filterByDomain = true;
/**
* Controls whether URL's that points to a subdomain of {@link Crawler#host}
* should also be fetched.
* @type {Boolean}
*/
this.scanSubdomains = false;
/**
* Controls whether to treat the www subdomain as the same domain as
* {@link Crawler#host}. So if {@link http://example.com/example} has
* already been fetched, {@link http://www.example.com/example} won't be
* fetched also.
* @type {Boolean}
*/
this.ignoreWWWDomain = true;
/**
* Controls whether to strip the www subdomain entirely from URL's at queue
* item construction time.
* @type {Boolean}
*/
this.stripWWWDomain = false;
/**
* Internal cache store. Must implement `SimpleCache` interface. You can
* save the site to disk using the built in file system cache like this:
*
* ```js
* crawler.cache = new Crawler.cache('pathToCacheDirectory');
* ```
* @type {SimpleCache}
*/
this.cache = null;
/**
* Controls whether an HTTP proxy should be used for requests
* @type {Boolean}
*/
this.useProxy = false;
/**
* If {@link Crawler#useProxy} is true, this setting controls what hostname
* to use for the proxy
* @type {String}
*/
this.proxyHostname = "127.0.0.1";
/**
* If {@link Crawler#useProxy} is true, this setting controls what port to
* use for the proxy
* @type {Number}
*/
this.proxyPort = 8123;
/**
* If {@link Crawler#useProxy} is true, this setting controls what username
* to use for the proxy
* @type {String}
*/
this.proxyUser = null;
/**
* If {@link Crawler#useProxy} is true, this setting controls what password
* to use for the proxy
* @type {String}
*/
this.proxyPass = null;
/**
* Controls whether to use HTTP Basic Auth
* @type {Boolean}
*/
this.needsAuth = false;
/**
* If {@link Crawler#needsAuth} is true, this setting controls what username
* to send with HTTP Basic Auth
* @type {String}
*/
this.authUser = null;
/**
* If {@link Crawler#needsAuth} is true, this setting controls what password
* to send with HTTP Basic Auth
* @type {String}
*/
this.authPass = null;
/**
* Controls whether to save and send cookies or not
* @type {Boolean}
*/
this.acceptCookies = true;
/**
* The module used to store cookies
* @type {CookieJar}
*/
this.cookies = new CookieJar();
/**
* Controls what headers (besides the default ones) to include with every
* request.
* @type {Object}
*/
this.customHeaders = {};
/**
* Controls what domains the crawler is allowed to fetch from, regardless of
* {@link Crawler#host} or {@link Crawler#filterByDomain} settings.
* @type {Array}
*/
this.domainWhitelist = [];
/**
* Controls what protocols the crawler is allowed to fetch from
* @type {RegExp[]}
*/
this.allowedProtocols = [
/^http(s)?$/i, // HTTP & HTTPS
/^(rss|atom|feed)(\+xml)?$/i // RSS / XML
];
/**
* Controls the maximum allowed size in bytes of resources to be fetched
* @default 16777216
* @type {Number}
*/
this.maxResourceSize = 1024 * 1024 * 16; // 16mb
/**
* Controls what mimetypes the crawler will scan for new resources. If
* {@link Crawler#downloadUnsupported} is false, this setting will also
* restrict what resources are downloaded.
* @type {Array.<RegExp|string>}
*/
this.supportedMimeTypes = [
/^text\//i,
/^application\/(rss|html|xhtml)?[+/-]?xml/i,
/^application\/javascript/i,
/^xml/i
];
/**
* Controls whether to download resources with unsupported mimetypes (as
* specified by {@link Crawler#supportedMimeTypes})
* @type {Boolean}
*/
this.downloadUnsupported = true;
/**
* Controls what URL encoding to use. Can be either "unicode" or "iso8859"
* @type {String}
*/
this.urlEncoding = "unicode";
/**
* Controls whether to strip query string parameters from URL's at queue
* item construction time.
* @type {Boolean}
*/
this.stripQuerystring = false;
/**
* Controls whether to sort query string parameters from URL's at queue
* item construction time.
* @type {Boolean}
*/
this.sortQueryParameters = false;
/**
* Collection of regular expressions and functions that are applied in the
* default {@link Crawler#discoverResources} method.
* @type {Array.<RegExp|Function>}
*/
this.discoverRegex = [
/\s(?:href|src)\s*=\s*("|').*?\1/ig,
/\s(?:href|src)\s*=\s*[^"'\s][^\s>]+/ig,
/\s?url\((["']).*?\1\)/ig,
/\s?url\([^"')]*?\)/ig,
// This could easily duplicate matches above, e.g. in the case of
// href="http://example.com"
/https?:\/\/[^?\s><'",]+/ig,
// This might be a bit of a gamble... but get hard-coded
// strings out of javacript: URLs. They're often popup-image
// or preview windows, which would otherwise be unavailable to us.
// Worst case scenario is we make some junky requests.
/^javascript:\s*[\w$.]+\(['"][^'"\s]+/ig,
// Find srcset links
function(string) {
var result = /\ssrcset\s*=\s*("|')(.*?)\1/.exec(string);
return Array.isArray(result) ? String(result[2]).split(",").map(function(string) {
return string.trim().split(/\s+/)[0];
}) : "";
},
// Find resources in <meta> redirects. We need to wrap these RegExp's in
// functions because we only want to return the first capture group, not
// the entire match. And we need two RegExp's because the necessary
// attributes on the <meta> tag can appear in any order
function(string) {
var match = string.match(/<meta[^>]*http-equiv\s*=\s*["']?refresh["']?[^>]*content\s*=\s*["'] ?[^"'>]*url=([^"'>]*)["']?[^>]*>/i);
return Array.isArray(match) ? [match[1]] : undefined;
},
function(string) {
var match = string.match(/<meta[^>]*content\s*=\s*["']?[^"'>]*url=([^"'>]*)["']?[^>]*http-equiv\s*=\s*["']?refresh["']?[^>]*>/i);
return Array.isArray(match) ? [match[1]] : undefined;
}
];
/**
* Controls whether the default {@link Crawler#discoverResources} should
* scan for new resources inside of HTML comments.
* @type {Boolean}
*/
this.parseHTMLComments = true;
/**
* Controls whether the default {@link Crawler#discoverResources} should
* scan for new resources inside of `<script>` tags.
* @type {Boolean}
*/
this.parseScriptTags = true;
/**
* Controls the max depth of resources that the crawler fetches. 0 means
* that the crawler won't restrict requests based on depth. The initial
* resource, as well as manually queued resources, are at depth 1. From
* there, every discovered resource adds 1 to its referrer's depth.
* @type {Number}
*/
this.maxDepth = 0;
/**
* Controls whether to proceed anyway when the crawler encounters an invalid
* SSL certificate.
* @type {Boolean}
*/
this.ignoreInvalidSSL = false;
/**
* Controls what HTTP agent to use. This is useful if you want to configure
* eg. a SOCKS client.
* @type {HTTPAgent}
*/
this.httpAgent = http.globalAgent;
/**
* Controls what HTTPS agent to use. This is useful if you want to configure
* eg. a SOCKS client.
* @type {HTTPAgent}
*/
this.httpsAgent = https.globalAgent;
// STATE (AND OTHER) VARIABLES NOT TO STUFF WITH
var hiddenProps = {
_downloadConditions: [],
_fetchConditions: [],
_isFirstRequest: true,
_openListeners: 0,
_openRequests: [],
_robotsTxts: [],
_touchedHosts: []
};
// Apply all the hidden props
Object.keys(hiddenProps).forEach(function(key) {
Object.defineProperty(crawler, key, {
writable: true,
enumerable: false,
value: hiddenProps[key]
});
});
};
util.inherits(Crawler, EventEmitter);
/**
* Starts or resumes the crawl. It adds a queue item constructed from
* {@link Crawler#initialURL} to the queue. The crawler waits for
* process.nextTick to begin, so handlers and other properties can be altered or
* addressed before the crawl commences.
* @return {Crawler} Returns the crawler instance to enable chained API calls
*/
Crawler.prototype.start = function() {
var crawler = this;
if (crawler.running) {
return crawler;
}
crawler.running = true;
var queueItem = crawler.processURL(crawler.initialURL);
queueItem.referrer = undefined;
queueItem.depth = QUEUE_ITEM_INITIAL_DEPTH;
crawler.queue.add(queueItem, false, function(error) {
if (error && error.code !== "DUPLICATE") {
throw error;
}
process.nextTick(function() {
crawler.crawlIntervalID = setInterval(crawler.crawl.bind(crawler),
crawler.interval);
crawler.crawl();
});
/**
* Fired when the crawl starts. This event gives you the opportunity to
* adjust the crawler's configuration, since the crawl won't actually start
* until the next processor tick.
* @event Crawler#crawlstart
*/
crawler.emit("crawlstart");
});
return crawler;
};
/**
* Determines whether robots.txt rules allows the fetching of a particular URL
* or not
* @param {String} url The full URL of the resource that is to be fetched (or not)
* @return {Boolean} Returns true if the URL is allowed to be fetched, otherwise false
*/
Crawler.prototype.urlIsAllowed = function(url) {
var crawler = this;
var formattedURL = uri(url).normalize().href(),
allowed = false;
// The punycode module sometimes chokes on really weird domain
// names. Catching those errors to prevent crawler from crashing
try {
allowed = crawler._robotsTxts.reduce(function(result, robots) {
var allowed = robots.isAllowed(formattedURL, crawler.userAgent);
return result !== undefined ? result : allowed;
}, undefined);
} catch (error) {
// URL will be avoided
}
return allowed === undefined ? true : allowed;
};
/**
* Generates a configuration object for http[s].request
* @param {QueueItem} queueItem The queue item for which a request option object should be generated
* @return {Object} Returns an object that can be passed directly to http[s].request
*/
Crawler.prototype.getRequestOptions = function(queueItem) {
var crawler = this;
var agent = queueItem.protocol === "https" ? crawler.httpsAgent : crawler.httpAgent;
// Extract request options from queue;
var requestHost = queueItem.host,
requestPort = queueItem.port,
requestPath = queueItem.path;
// Are we passing through an HTTP proxy?
if (crawler.useProxy) {
requestHost = crawler.proxyHostname;
requestPort = crawler.proxyPort;
requestPath = queueItem.url;
}
var isStandardHTTPPort = queueItem.protocol === "http" && queueItem.port !== 80,
isStandardHTTPSPort = queueItem.protocol === "https" && queueItem.port !== 443,
isStandardPort = isStandardHTTPPort || isStandardHTTPSPort;
// Load in request options
var requestOptions = {
method: "GET",
host: requestHost,
port: requestPort,
path: requestPath,
agent: agent,
headers: {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"User-Agent": crawler.userAgent,
"Host": queueItem.host + (queueItem.port && isStandardPort ? ":" + queueItem.port : "")
}
};
if (crawler.decompressResponses) {
requestOptions.headers["Accept-Encoding"] = "gzip, deflate";
}
if (queueItem.referrer) {
requestOptions.headers.Referer = queueItem.referrer;
}
// If port is one of the HTTP/HTTPS defaults, delete the option to avoid conflicts
if (requestPort === 80 || requestPort === 443 || !requestPort) {
delete requestOptions.port;
}
// Add cookie header from cookie jar if we're configured to
// send/accept cookies
if (crawler.acceptCookies && crawler.cookies.getAsHeader()) {
requestOptions.headers.cookie =
crawler.cookies.getAsHeader(queueItem.host, queueItem.path).join("; ");
}
// Add auth headers if we need them
if (crawler.needsAuth) {
var auth = crawler.authUser + ":" + crawler.authPass;
// Generate auth header
auth = "Basic " + Buffer.from(auth).toString("base64");
requestOptions.headers.Authorization = auth;
}
// Add proxy auth if we need it
if (crawler.proxyUser !== null && crawler.proxyPass !== null) {
var proxyAuth = crawler.proxyUser + ":" + crawler.proxyPass;
// Generate auth header
proxyAuth = "Basic " + Buffer.from(proxyAuth).toString("base64");
requestOptions.headers["Proxy-Authorization"] = proxyAuth;
}
if (crawler.cache !== null && crawler.cache.getCacheData) {
crawler.cache.getCacheData(queueItem, function(cacheObject) {
if (cacheObject) {
if (cacheObject.etag) {
requestOptions.headers["If-None-Match"] = cacheObject.etag;
}
if (cacheObject.lastModified) {
requestOptions.headers["If-Modified-Since"] = cacheObject.lastModified;
}
}
});
}
// And if we've got any custom headers available
if (crawler.customHeaders) {
for (var header in crawler.customHeaders) {
if (crawler.customHeaders.hasOwnProperty(header)) {
requestOptions.headers[header] = crawler.customHeaders[header];
}
}
}
return requestOptions;
};
/**
* Performs an HTTP request for the robots.txt resource on any domain
* @param {String} url The full URL to the robots.txt file, eg. "http://example.com/robots.txt"
* @param {Crawler~getRobotsTxtCallback} callback The callback called with the server's response, or an error
* @return {Crawler} Returns the crawler instance to enable chained API calls
*/
Crawler.prototype.getRobotsTxt = function(url, callback) {
var crawler = this,
errorMsg;
var robotsTxtUrl = uri(url);
var client = robotsTxtUrl.protocol() === "https" ? https : http;
// Apply the ignoreInvalidSSL setting to https connections
if (client === https && crawler.ignoreInvalidSSL) {
client.rejectUnauthorized = false;
client.strictSSL = false;
}
var requestOptions = crawler.getRequestOptions(crawler.processURL(robotsTxtUrl.href()));
// Get the resource!
var clientRequest = client.request(requestOptions, function(response) {
if (response.statusCode >= 200 && response.statusCode < 300) {
var responseLength =
parseInt(response.headers["content-length"], 10) ||
crawler.maxResourceSize,
responseBuffer = Buffer.alloc(responseLength),
responseLengthReceived = 0;
response.on("data", function(chunk) {
if (responseLengthReceived + chunk.length <= crawler.maxResourceSize) {
chunk.copy(responseBuffer, responseLengthReceived, 0, chunk.length);
responseLengthReceived += chunk.length;
} else {
response.destroy();
callback(new Error("robots.txt exceeded maxResourceSize"));
}
});
var decodeAndReturnResponse = function(error, responseBuffer) {
if (error) {
return callback(new Error("Couldn't unzip robots.txt response body"));
}
var contentType = response.headers["content-type"],
responseBody = crawler.decodeBuffer(responseBuffer, contentType);
callback(undefined, robotsTxtUrl.href(), responseBody);
};
response.on("end", function() {
var contentEncoding = response.headers["content-encoding"];
if (contentEncoding && /(gzip|deflate)/.test(contentEncoding)) {
zlib.unzip(responseBuffer, decodeAndReturnResponse);
} else {
decodeAndReturnResponse(undefined, responseBuffer);
}
});
} else if (response.statusCode >= 300 && response.statusCode < 400 &&
response.headers.location) {
response.destroy();
var redirectTarget;
try {
redirectTarget = uri(response.headers.location)
.absoluteTo(robotsTxtUrl)
.normalize();
} catch (error) {
var robotsTxtHost = uri(robotsTxtUrl).pathname("").href();
errorMsg = util.format("Faulty redirect URL when fetching robots.txt for %s", robotsTxtHost);
return callback(new Error(errorMsg));
}
if (crawler.domainValid(redirectTarget.hostname())) {
crawler.getRobotsTxt(redirectTarget.href(), callback);
} else {
errorMsg = util.format("%s redirected to a disallowed domain (%s)", robotsTxtUrl.href(), redirectTarget.hostname());
callback(new Error(errorMsg));
}
} else {
response.destroy();
errorMsg = util.format("Server responded with status %d when fetching robots.txt", response.statusCode);
callback(new Error(errorMsg));
}
});
clientRequest.end();
clientRequest.setTimeout(crawler.timeout, function() {
clientRequest.abort();
callback(new Error("robots.txt request timed out"));
});
clientRequest.on("error", function(errorData) {
if (!clientRequest.aborted) {
callback(errorData);
}
});
return crawler;
};
/**
* Determines whether the crawler supports a protocol
* @param {String} URL A full URL, eg. "http://example.com"
* @return {Boolean} Returns true if the protocol of the URL is supported, false if not
*/
Crawler.prototype.protocolSupported = function(URL) {
var protocol,
crawler = this;
try {
protocol = uri(URL).protocol();
// Unspecified protocol. Assume http
if (!protocol) {
protocol = "http";
}
} catch (e) {
// If URIjs died, we definitely /do not/ support the protocol.
return false;
}
return crawler.allowedProtocols.some(function(protocolCheck) {
return protocolCheck.test(protocol);
});
};
/**
* Determines whether the crawler supports a mimetype
* @param {String} mimetype Eg. "text/html" or "application/octet-stream"
* @return {Boolean} Returns true if the mimetype is supported, false if not
*/
Crawler.prototype.mimeTypeSupported = function(mimetype) {
var crawler = this;
return crawler.supportedMimeTypes.some(function(mimeCheck) {
if (typeof mimeCheck === "string") {
return mimeCheck === mimetype;
}
return mimeCheck.test(mimetype);
});
};
/**
* Constructs a queue item from a URL and a referrer queue item.
* @param {String} url An absolute or relative URL to construct a queue item from
* @param {QueueItem} [referrer] The queue item representing the resource where this URL was discovered
* @return {QueueItem} Returns a new queue item
*/
Crawler.prototype.processURL = function(url, referrer) {
var newUrl,
crawler = this;
if (typeof referrer !== "object") {
referrer = {
url: crawler.initialURL,
depth: QUEUE_ITEM_INITIAL_DEPTH - 1
};
}
// If the URL didn't contain anything, don't fetch it.
if (!(url && url.trim().length)) {
return false;
}
// Check if querystring should be ignored
if (crawler.stripQuerystring) {
url = uri(url).search("").href();
}
// Canonicalize the URL by sorting query parameters.
if (crawler.sortQueryParameters) {
url = uri(url).query(function(data) {
var _data = {};
Object.keys(data).sort().forEach(function(key) {
_data[key] = data[key];
});
return _data;
}).href();
}
if (crawler.stripWWWDomain && url.match(/https?:\/\/(www\.).*/i)) {
url = url.replace("www.", "");
}
try {
newUrl = uri(url).absoluteTo(referrer.url).normalize();
if (crawler.urlEncoding === "iso8859") {
newUrl = newUrl.iso8859();
}
} catch (e) {
// Couldn't process the URL, since URIjs choked on it.
return false;
}
// simplecrawler uses slightly different terminology to URIjs. Sorry!
return {
host: newUrl.hostname(),
path: newUrl.resource(),
port: newUrl.port(),
protocol: newUrl.protocol() || "http",
uriPath: newUrl.path(),
url: newUrl.href(),
depth: referrer.depth + 1,
referrer: referrer.url,
fetched: false,
status: "created",
stateData: {}
};
};
/**
* Performs string replace operations on a URL string. Eg. removes HTML
* attribute fluff around actual URL, replaces leading "//" with absolute
* protocol etc.
* @private
* @param {String} URL The URL to be cleaned
* @param {QueueItem} queueItem The queue item representing the resource where this URL was discovered
* @return {String} Returns the cleaned URL
*/
function cleanURL (URL, queueItem) {
return URL
.replace(/^(?:\s*href|\s*src)\s*=+\s*/i, "")
.replace(/^\s*/, "")
.replace(/^(['"])(.*)\1$/, "$2")
.replace(/^url\((.*)\)/i, "$1")
.replace(/^javascript:\s*(\w*\(['"](.*)['"]\))*.*/i, "$2")
.replace(/^(['"])(.*)\1$/, "$2")
.replace(/^\((.*)\)$/, "$1")
.replace(/^\/\//, queueItem.protocol + "://")
.replace(/&/gi, "&")
.replace(/&/gi, "&")
.replace(/&/gi, "&")
.replace(///gi, "/")
.split("#")
.shift()
.trim();
}
/**
* Cleans a list of resources, usually provided by
* {@link Crawler#discoverResources}. Also makes relative URL's absolute to the
* URL of the queueItem argument.
* @param {Array} urlMatch An array of URL's
* @param {QueueItem} queueItem The queue item representing the resource where the URL's were discovered
* @return {Array} Returns an array of unique and absolute URL's
*/
Crawler.prototype.cleanExpandResources = function (urlMatch, queueItem) {
"use strict";
var crawler = this;
if (!urlMatch) {
return [];
}
const URLs = new Set();
let URL;
for (let i = 0; i < urlMatch.length; i++) {
URL = urlMatch[i];
if (!URL) {
continue;
}
URL = cleanURL(URL, queueItem);
// Ensure URL is whole and complete
try {
URL = uri(URL)
.absoluteTo(queueItem.url || "")
.normalize()
.href();
} catch (e) {
// But if URI.js couldn't parse it - nobody can!
continue;
}
// If we hit an empty item, don't return it
if (!URL.length) {
continue;
}
// If we don't support the protocol in question
if (!crawler.protocolSupported(URL)) {
continue;
}
URLs.add(URL);
}
return Array.from(URLs);
};
/**
* Discovers linked resources in an HTML, XML or text document.
* @param {String} resourceText The body of the text document that is to be searched for resources
* @return {Array} Returns the array of discovered URL's. It is not the responsibility of this method to clean this array of duplicates etc. That's what {@link Crawler#cleanExpandResources} is for.
*/
Crawler.prototype.discoverResources = function(resourceText) {
var crawler = this;
if (!crawler.parseHTMLComments) {
resourceText = resourceText.replace(/<!--([\s\S]+?)-->/g, "");
}
if (!crawler.parseScriptTags) {
resourceText = resourceText.replace(/<script(.*?)>([\s\S]*?)<\/script>/gi, "");
}
if (crawler.respectRobotsTxt && /<meta(?:\s[^>]*)?\sname\s*=\s*["']?robots["']?[^>]*>/i.test(resourceText)) {
var robotsValue = /<meta(?:\s[^>]*)?\scontent\s*=\s*["']?([\w\s,]+)["']?[^>]*>/i.exec(resourceText.toLowerCase());
if (Array.isArray(robotsValue) && /nofollow/i.test(robotsValue[1])) {
return [];
}
}
// Rough scan for URLs
return crawler.discoverRegex.reduce(function(list, extracter) {
var resources;
if (extracter instanceof Function) {
resources = extracter(resourceText);
} else {
resources = resourceText.match(extracter);
}
return resources ? list.concat(resources) : list;
}, []);
};
/**
* Determines whether a domain is valid for crawling based on configurable
* rules.
* @param {String} host The domain name that's a candidate for fetching
* @return {Boolean} Returns true if the crawler if allowed to fetch resources from the domain, false if not.
*/
Crawler.prototype.domainValid = function(host) {
var crawler = this;
// If we're ignoring the WWW domain, remove the WWW for comparisons...
if (crawler.ignoreWWWDomain) {
host = host.replace(/^www\./i, "");
}
function domainInWhitelist(host) {
// If there's no whitelist, or the whitelist is of zero length,
// just return false.
if (!crawler.domainWhitelist || !crawler.domainWhitelist.length) {
return false;
}
// Otherwise, scan through it.
return crawler.domainWhitelist.some(function(entry) {
// If the domain is just equal, return true.
if (host === entry) {
return true;
}
// If we're ignoring WWW subdomains, and both domains,
// less www. are the same, return true.
if (crawler.ignoreWWWDomain && host === entry.replace(/^www\./i, "")) {
return true;
}
return false;
});
}
// Checks if the first domain is a subdomain of the second
function isSubdomainOf(subdomain, host) {
// Comparisons must be case-insensitive
subdomain = subdomain.toLowerCase();
host = host.toLowerCase();
// If we're ignoring www, remove it from both
// (if www is the first domain component...)
if (crawler.ignoreWWWDomain) {
subdomain = subdomain.replace(/^www./ig, "");
host = host.replace(/^www./ig, "");
}
// They should be the same flipped around!
return subdomain.split("").reverse().join("").substr(0, host.length) ===
host.split("").reverse().join("");
}
// If we're not filtering by domain, just return true.
return !crawler.filterByDomain ||
// Or if the domain is just the right one, return true.
host === crawler.host ||