forked from JimmyLaurent/cloudflare-scraper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
47 lines (41 loc) · 1.37 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
const request = require('request-promise-native');
const { isProtectedByStormwall, getStormwallCookie } = require('stormwall-bypass');
const { getUserAgent } = require('./src/utils');
const fillCookiesJar = require('./src/fillCookiesJar');
const { isCloudflareJSChallenge, isCloudflareCaptchaChallenge } = require('./src/utils');
function isCloudflareIUAMError(error) {
if (error.response) {
const { body } = error.response;
return isCloudflareJSChallenge(body) || isCloudflareCaptchaChallenge(body);
}
return false;
}
async function handleError(error) {
if (isCloudflareIUAMError(error)) {
const { options } = error;
await fillCookiesJar(request, options);
return request(options);
}
throw error;
}
function handleResponse(response, options) {
const { jar, url, uri } = options;
const targetUrl = uri || url;
const body = response.body || response;
if (isProtectedByStormwall(body)) {
const cookie = getStormwallCookie(body);
jar.setCookie(cookie, targetUrl);
return request(options);
}
return response;
}
async function cloudflareScraper(options) {
const response = await request({ ...options }).catch(handleError);
return handleResponse(response, options);
}
const defaultParams = {
jar: request.jar(),
headers: { 'User-Agent': getUserAgent() },
gzip: true
};
module.exports = request.defaults(defaultParams, cloudflareScraper);