-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPage.js
135 lines (115 loc) · 2.64 KB
/
Page.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
const url = require('url');
const chalk = require('chalk');
const request = require('request');
const { JSDOM } = require('jsdom');
class Page {
/**
* @param {Url} urlInfo
* @param {IncomingMessage} response
*/
constructor(urlInfo, response) {
this.urlInfo = urlInfo;
this.response = response;
this.outgoingPages = [];
this.incomingPages = [];
}
/**
* @return {Url[]}
*/
getOutgoingLinks() {
if (!this.isHTML()) {
return [];
}
const dom = this.getDOM();
const anchors = dom.window.document.querySelectorAll('a[href]');
const links = [];
for (const anchor of anchors) {
const next = url.parse(url.resolve(this.urlInfo.href, anchor.href));
// Not an HTTP resource?
if (next.protocol === null || !next.protocol.match(/^https?:$/)) continue;
links.push(next);
}
return links;
}
/**
* @param {Page} page
*/
addIncomingPage(page) {
this.incomingPages.push(page);
}
/**
* @param {Page} page
*/
addOutgoingPage(page) {
this.outgoingPages.push(page);
}
/**
* @return {JSDOM}
*/
getDOM() {
if (!this.dom) this.dom = new JSDOM(this.response.body);
return this.dom;
}
/**
* @return {string}
*/
getUrl() {
return url.format(Object.assign({}, this.urlInfo, { hash: null }));
}
/**
* @return {number}
*/
getStatusCode() {
return this.response.statusCode;
}
/**
* @param {string} name
* @return {undefined|string}
*/
getHeader(name) {
return this.response.headers[name];
}
isHTML() {
const contentType = this.response.headers['content-type'] || 'text/html';
return contentType.match(/^text\/html/);
}
/**
* @return {boolean}
*/
isSuccess() {
return this.response.statusCode >= 100 && this.response.statusCode < 300;
}
/**
* @return {boolean}
*/
isRedirect() {
return this.response.statusCode >= 300 && this.response.statusCode < 400;
}
/**
* @return {boolean}
*/
isClientError() {
return this.response.statusCode >= 400 && this.response.statusCode < 500;
}
/**
* @return {boolean}
*/
isServerError() {
return this.response.statusCode >= 500 && this.response.statusCode < 600;
}
log() {
let str;
if (this.isRedirect()) {
str = chalk.bgYellow.black(this.getStatusCode());
} else if (this.isClientError()) {
str = chalk.bgRed.white(this.getStatusCode());
} else if (this.isServerError()) {
str = chalk.bgBlack.red(this.getStatusCode());
} else {
str = chalk.bgGreen.black(this.getStatusCode());
}
str += ` ${this.getUrl()}`;
return str;
}
}
exports.Page = Page;