-
Notifications
You must be signed in to change notification settings - Fork 878
/
crawler.ts
341 lines (312 loc) · 12.1 KB
/
crawler.ts
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
import { EventEmitter } from "events";
import { Cluster } from "./rateLimiter/index.js";
import { isBoolean, isFunction, setDefaults, flattenDeep, lowerObjectKeys, isNumber } from "./lib/utils.js";
import { getValidOptions, alignOptions, getCharset } from "./options.js";
import { getLogger } from "./logger.js";
import type { CrawlerOptions, RequestOptions, RequestConfig, CrawlerResponse } from "./types/crawler.js";
import { load } from "cheerio";
import got from "got";
import seenreq from "seenreq";
import iconv from "iconv-lite";
// @todo: remove seenreq dependency
const log = getLogger();
class Crawler extends EventEmitter {
private _limiters: Cluster;
private _UAIndex = 0;
private _proxyIndex = 0;
public options: CrawlerOptions;
public seen: any;
constructor(options?: CrawlerOptions) {
super();
const defaultOptions: CrawlerOptions = {
maxConnections: 10,
rateLimit: 0,
priorityLevels: 10,
skipDuplicates: false,
homogeneous: false,
method: "GET",
forceUTF8: false,
jQuery: true,
priority: 5,
retries: 2,
retryInterval: 3000,
timeout: 20000,
isJson: false,
silence: false,
};
this.options = { ...defaultOptions, ...options };
if (this.options.rateLimit! > 0) {
this.options.maxConnections = 1;
}
if (this.options.silence) {
log.settings.minLevel = 7;
}
this._limiters = new Cluster({
maxConnections: this.options.maxConnections!,
rateLimit: this.options.rateLimit!,
priorityLevels: this.options.priorityLevels!,
defaultPriority: this.options.priority!,
homogeneous: this.options.homogeneous,
});
this.seen = new seenreq(this.options.seenreq);
this.seen
.initialize()
.then(() => {
log.debug("seenreq initialized");
})
.catch((error: unknown) => {
log.error(error);
});
this.on("_release", () => {
log.debug(`Queue size: ${this.queueSize}`);
if (this._limiters.empty) this.emit("drain");
});
}
private _detectHtmlOnHeaders = (headers: Record<string, unknown>): boolean => {
const contentType = headers["content-type"] as string;
if (/xml|html/i.test(contentType)) return true;
return false;
};
private _schedule = (options: CrawlerOptions): void => {
this.emit("schedule", options);
this._limiters
.getRateLimiter(options.rateLimiterId)
.submit(options.priority as number, (done, rateLimiterId) => {
options.release = () => {
done();
this.emit("_release");
};
options.callback = options.callback || options.release;
if (rateLimiterId) {
this.emit("limiterChange", options, rateLimiterId);
}
if (options.html) {
options.url = options.url ?? "";
this._handler(null, options, { body: options.html, headers: { "content-type": "text/html" } });
} else {
options.url = options.url ?? options.uri;
if (typeof options.url === "function") {
options.url((url: string) => {
options.url = url;
this._execute(options);
});
} else {
delete options.uri;
this._execute(options);
}
}
});
};
private _execute = async (options: CrawlerOptions): Promise<CrawlerResponse> => {
if (options.proxy) log.debug(`Using proxy: ${options.proxy}`);
else if (options.proxies) log.debug(`Using proxies: ${options.proxies}`);
options.headers = options.headers ?? {};
options.headers = lowerObjectKeys(options.headers);
if (options.forceUTF8 || options.isJson) options.encoding = "utf8";
if (Array.isArray(options.userAgents)) {
this._UAIndex = this._UAIndex % options.userAgents.length;
options.headers["user-agent"] = options.userAgents[this._UAIndex];
this._UAIndex++;
} else {
options.headers["user-agent"] = options.headers["user-agent"] ?? options.userAgents;
}
if (!options.proxy && Array.isArray(options.proxies)) {
this._proxyIndex = this._proxyIndex % options.proxies.length;
options.proxy = options.proxies[this._proxyIndex];
this._proxyIndex++;
}
const request = async () => {
if (options.skipEventRequest !== true) {
this.emit("request", options);
}
let response: CrawlerResponse;
try {
response = await got(alignOptions(options));
} catch (error) {
log.debug(error);
return this._handler(error, options);
}
return this._handler(null, options, response);
};
if (isFunction(options.preRequest)) {
try {
options.preRequest!(options, async (err?: Error | null) => {
if (err) {
log.debug(err);
return this._handler(err, options);
}
return await request();
});
} catch (err) {
log.error(err);
throw err;
}
} else {
return await request();
}
};
private _handler = (error: unknown, options: RequestOptions, response?: CrawlerResponse): CrawlerResponse => {
if (error) {
if (options.retries && options.retries > 0) {
log.warn(`${error} occurred on ${options.url}. ${options.retries ? `(${options.retries} retries left)` : ""}`);
setTimeout(() => {
options.retries!--;
this._execute(options as CrawlerOptions);
}, options.retryInterval);
return;
} else {
log.error(`${error} occurred on ${options.url}. Request failed.`);
if (options.callback && typeof options.callback === "function") {
return options.callback(error, { options }, options.release);
} else {
throw error;
}
}
}
if (!response.body) response.body = "";
log.debug("Got " + (options.url || "html") + " (" + response.body.length + " bytes)...");
response.options = options;
response.charset = getCharset(response.headers);
if (!response.charset) {
const match = response.body.toString().match(/charset=['"]?([\w.-]+)/i);
response.charset = match ? match[1].trim().toLowerCase() : null;
}
log.debug("Charset: " + response.charset);
if (options.encoding !== null) {
options.encoding = options.encoding ?? response.charset ?? "utf8";
try {
if (!Buffer.isBuffer(response.body)) response.body = Buffer.from(response.body);
response.body = iconv.decode(response.body, options.encoding as string);
response.body = response.body.toString();
} catch (err) {
log.error(err);
}
}
if (options.isJson) {
try {
response.body = JSON.parse(response.body);
} catch (_err) {
log.warn("JSON parsing failed, body is not JSON. Set isJson to false to mute this warning.");
}
}
if (options.jQuery === true && !options.isJson) {
if (response.body === "" || !this._detectHtmlOnHeaders(response.headers)) {
log.warn("response body is not HTML, skip injecting. Set jQuery to false to mute this warning.");
} else {
try {
response.$ = load(response.body);
} catch (_err) {
log.warn("HTML detected failed. Set jQuery to false to mute this warning.");
}
}
}
if (options.callback && typeof options.callback === "function") {
return options.callback(null, response, options.release);
}
return response;
};
public get queueSize(): number {
return 0;
}
/**
* @param rateLimiterId
* @param property
* @param value
* @description Set the rate limiter property.
* @version 2.0.0 Only support `rateLimit` change.
* @example
* ```js
* const crawler = new Crawler();
* crawler.setLimiter(0, "rateLimit", 1000);
* ```
*/
public setLimiter(rateLimiterId: number, property: string, value: unknown): void {
if (!isNumber(rateLimiterId)) {
log.error("rateLimiterId must be a number");
return;
}
if (property === "rateLimit") {
this._limiters.getRateLimiter(rateLimiterId).setRateLimit(value as number);
}
// @todo other properties
}
/**
* @param options
* @returns if there is a "callback" function in the options, return the result of the callback function. \
* Otherwise, return a promise, which resolves when the request is successful and rejects when the request fails.
* In the case of the promise, the resolved value will be the response object.
* @description Send a request directly.
* @example
* ```js
* const crawler = new Crawler();
* crawler.send({
* url: "https://example.com",
* callback: (error, response, done) => { done(); }
* });
* await crawler.send("https://example.com");
* ```
*/
public send = async (options: RequestConfig): Promise<CrawlerResponse> => {
options = getValidOptions(options);
options.retries = options.retries ?? 0;
setDefaults(options, this.options);
options.skipEventRequest = isBoolean(options.skipEventRequest) ? options.skipEventRequest : true;
delete options.preRequest;
return await this._execute(options);
};
/**
* @deprecated
* @description Old interface version. It is recommended to use `Crawler.send()` instead.
* @see Crawler.send
*/
public direct = async (options: RequestConfig): Promise<CrawlerResponse> => {
return await this.send(options);
};
/**
* @param options
* @description Add a request to the queue.
* @example
* ```js
* const crawler = new Crawler();
* crawler.add({
* url: "https://example.com",
* callback: (error, response, done) => { done(); }
* });
* ```
*/
public add = (options: RequestConfig): void => {
let optionsArray = Array.isArray(options) ? options : [options];
optionsArray = flattenDeep(optionsArray);
optionsArray.forEach(options => {
try {
options = getValidOptions(options) as RequestOptions;
} catch (err) {
log.warn(err);
return;
}
setDefaults(options, this.options);
options.headers = { ...this.options.headers, ...options.headers };
if (!this.options.skipDuplicates) {
this._schedule(options as CrawlerOptions);
return;
}
this.seen
.exists(options, options.seenreq)
.then((rst: any) => {
if (!rst) {
this._schedule(options as CrawlerOptions);
}
})
.catch((error: unknown) => log.error(error));
});
};
/**
* @deprecated
* @description Old interface version. It is recommended to use `Crawler.add()` instead.
* @see Crawler.add
*/
public queue = (options: RequestConfig): void => {
return this.add(options);
};
}
export default Crawler;