-
Notifications
You must be signed in to change notification settings - Fork 151
/
Copy pathHttpClient.js
353 lines (309 loc) · 11.7 KB
/
HttpClient.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
/*
Makes HTML calls using Fetch API
*/
"use strict";
class FetchErrorHandler {
constructor() {
}
makeFailMessage(url, error) {
return chrome.i18n.getMessage("htmlFetchFailed", [url, error]);
}
makeFailCanRetryMessage(url, error) {
return this.makeFailMessage(url, error) + " " +
chrome.i18n.getMessage("httpFetchCanRetry");
}
getCancelButtonText() {
return chrome.i18n.getMessage("__MSG_button_error_Cancel__");
}
static cancelButtonText() {
return chrome.i18n.getMessage("__MSG_button_error_Cancel__");
}
onFetchError(url, error) {
return Promise.reject(new Error(this.makeFailMessage(url, error.message)));
}
onResponseError(url, wrapOptions, response) {
let failError = new Error(this.makeFailMessage(url, response.status));
let retry = FetchErrorHandler.getAutomaticRetryBehaviourForStatus(response);
if (retry.retryDelay.length === 0) {
return Promise.reject(failError);
}
if (wrapOptions.retry === undefined) {
wrapOptions.retry = retry;
return this.retryFetch(url, wrapOptions);
}
if (0 < wrapOptions.retry.retryDelay.length) {
return this.retryFetch(url, wrapOptions);
}
if (wrapOptions.retry.promptUser) {
return this.promptUserForRetry(url, wrapOptions, response, failError);
} else {
return Promise.reject(failError);
}
}
promptUserForRetry(url, wrapOptions, response, failError) {
let msg;
if (wrapOptions.retry.HTTP === 403) {
msg = new Error(chrome.i18n.getMessage("warning403ErrorResponse", new URL(response.url).hostname) + this.makeFailCanRetryMessage(url, response.status));
} else {
msg = new Error(new Error(this.makeFailCanRetryMessage(url, response.status)));
}
let cancelLabel = this.getCancelButtonText();
return new Promise(function(resolve, reject) {
if (wrapOptions.retry.HTTP === 403) {
msg.openurl = url;
msg.blockurl = url;
}
msg.retryAction = () => resolve(HttpClient.wrapFetchImpl(url, wrapOptions));
msg.cancelAction = () => reject(failError);
msg.cancelLabel = cancelLabel;
ErrorLog.showErrorMessage(msg);
});
}
async retryFetch(url, wrapOptions) {
let delayBeforeRetry = wrapOptions.retry.retryDelay.pop() * 1000;
await util.sleep(delayBeforeRetry);
return HttpClient.wrapFetchImpl(url, wrapOptions);
}
static getAutomaticRetryBehaviourForStatus(response) {
// seconds to wait before each retry (note: order is reversed)
let retryDelay = [120, 60, 30, 15];
switch(response.status) {
case 403:
/*
if (confirm(chrome.i18n.getMessage("warning403ErrorResponse", new URL(response.url).hostname))) {
// Open site
window.open(new URL(response.url), "_blank").focus();
alert(chrome.i18n.getMessage("wait403ErrorResponse", new URL(response.url).hostname));
} else {
// Do nothing!
}*/
return {retryDelay: [1], promptUser: true, HTTP: 403};
case 429:
FetchErrorHandler.show429Error(response);
return {retryDelay: retryDelay, promptUser: true};
case 445:
//Random Unique exception thrown on Webnovel/Qidian. Not part of w3 spec.
return {retryDelay: retryDelay, promptUser: false};
case 509:
// server asked for rate limiting
return {retryDelay: retryDelay, promptUser: true};
case 500:
// is fault at server, retry might clear
return {retryDelay: retryDelay, promptUser: false};
case 502:
case 503:
case 504:
case 520:
case 522:
// intermittant fault
return {retryDelay: retryDelay, promptUser: true};
default:
// it's dead Jim
return {retryDelay: [], promptUser: false};
}
}
static show429Error(response) {
let host = new URL(response.url).hostname;
if (!FetchErrorHandler.rateLimitedHosts.has(host)) {
FetchErrorHandler.rateLimitedHosts.add(host);
alert(chrome.i18n.getMessage("warning429ErrorResponse", host));
}
}
}
FetchErrorHandler.rateLimitedHosts = new Set();
class FetchImageErrorHandler extends FetchErrorHandler{
constructor(parentPageUrl) {
super();
this.parentPageUrl = parentPageUrl;
}
makeFailMessage(url, error) {
return chrome.i18n.getMessage("imageFetchFailed", [url, this.parentPageUrl, error]);
}
getCancelButtonText() {
return chrome.i18n.getMessage("__MSG_button_error_Skip__");
}
}
class HttpClient {
constructor() {
}
static makeOptions() {
return { credentials: "include" };
}
static wrapFetch(url, wrapOptions) {
if (wrapOptions == null) {
wrapOptions = {
errorHandler: new FetchErrorHandler()
}
}
if (wrapOptions.errorHandler == null) {
wrapOptions.errorHandler = new FetchErrorHandler();
}
wrapOptions.responseHandler = new FetchResponseHandler();
if (wrapOptions.makeTextDecoder != null) {
wrapOptions.responseHandler.makeTextDecoder = wrapOptions.makeTextDecoder;
}
return HttpClient.wrapFetchImpl(url, wrapOptions);
}
static fetchHtml(url) {
let wrapOptions = {
responseHandler: new FetchHtmlResponseHandler()
};
return HttpClient.wrapFetchImpl(url, wrapOptions);
}
static fetchJson(url, fetchOptions) {
let wrapOptions = {
responseHandler: new FetchJsonResponseHandler(),
fetchOptions: fetchOptions
};
return HttpClient.wrapFetchImpl(url, wrapOptions);
}
static fetchText(url) {
let wrapOptions = {
responseHandler: new FetchTextResponseHandler(),
};
return HttpClient.wrapFetchImpl(url, wrapOptions);
}
static async wrapFetchImpl(url, wrapOptions) {
if (BlockedHostNames.has(new URL(url).hostname)) {
let skipurlerror = new Error("!Blocked! URL skipped because the user blocked the site");
return wrapOptions.errorHandler.onFetchError(url, skipurlerror);
}
await HttpClient.setPartitionCookies(url);
if (wrapOptions.fetchOptions == null) {
wrapOptions.fetchOptions = HttpClient.makeOptions();
}
if (wrapOptions.errorHandler == null) {
wrapOptions.errorHandler = new FetchErrorHandler();
}
try
{
let response = await fetch(url, wrapOptions.fetchOptions);
return HttpClient.checkResponseAndGetData(url, wrapOptions, response)
}
catch (error)
{
return wrapOptions.errorHandler.onFetchError(url, error);
}
}
static checkResponseAndGetData(url, wrapOptions, response) {
if(!response.ok) {
return wrapOptions.errorHandler.onResponseError(url, wrapOptions, response);
} else {
let handler = wrapOptions.responseHandler;
handler.setResponse(response);
return handler.extractContentFromResponse(response);
}
}
static async setPartitionCookies(url) {
// get partitionKey in the form of https://<site name>.<tld>
let parsedUrl = new URL(url);
//keep old code for reference in case it changes again
//let topLevelSite = parsedUrl.protocol + "//" + parsedUrl.hostname;
try {
// get all cookie from the site which use the partitionKey (e.g. cloudflare)
//keep old code for reference in case it changes again
//let cookies = await chrome.cookies.getAll({partitionKey: {topLevelSite: topLevelSite}});
//set domain to the highest level from the website as all subdomains are included #1447 #1445
let urlparts = parsedUrl.hostname.split(".");
let cookies = "";
if (!util.isFirefox()) {
cookies = await chrome.cookies.getAll({domain: urlparts[urlparts.length-2]+"."+urlparts[urlparts.length-1],partitionKey: {}});
}else{
cookies = await browser.cookies.getAll({domain: urlparts[urlparts.length-2]+"."+urlparts[urlparts.length-1],partitionKey: {}});
}
cookies = cookies.filter(item => item.partitionKey != undefined);
//create new cookies for the site without the partitionKey
//cookies without the partitionKey get sent with fetch
cookies.forEach(element => chrome.cookies.set({
domain: element.domain,
url: "https://"+element.domain.substring(1),
name: element.name,
value: element.value
}));
} catch {
// Probably running browser that doesn't support partitionKey, e.g. Kiwi
}
}
}
let BlockedHostNames = new Set();
class FetchResponseHandler {
isHtml() {
return this.contentType.startsWith("text/html");
}
setResponse(response) {
this.response = response;
this.contentType = response.headers.get("content-type");
}
extractContentFromResponse(response) {
if (this.isHtml()) {
return this.responseToHtml(response);
} else {
return this.responseToBinary(response);
}
}
responseToHtml(response) {
return response.arrayBuffer().then(function(rawBytes) {
let data = this.makeTextDecoder(response).decode(rawBytes);
let html = new DOMParser().parseFromString(data, "text/html");
util.setBaseTag(this.response.url, html);
this.responseXML = html;
return this;
}.bind(this));
}
responseToBinary(response) {
return response.arrayBuffer().then(function(data) {
this.arrayBuffer = data;
return this;
}.bind(this));
}
responseToText(response) {
return response.arrayBuffer().then(function(rawBytes) {
return this.makeTextDecoder(response).decode(rawBytes);
}.bind(this));
}
responseToJson(response) {
return response.text().then(function(data) {
this.json = JSON.parse(data);
return this;
}.bind(this));
}
makeTextDecoder(response) {
let utflabel = this.charsetFromHeaders(response.headers);
return new TextDecoder(utflabel);
}
charsetFromHeaders(headers) {
let contentType = headers.get("Content-Type");
if (!util.isNullOrEmpty(contentType)) {
let pieces = contentType.toLowerCase().split("charset=");
if (2 <= pieces.length) {
return pieces[1].split(";")[0].replace(/"/g, "").trim();
}
}
return FetchResponseHandler.DEFAULT_CHARSET;
}
}
FetchResponseHandler.DEFAULT_CHARSET = "utf-8";
class FetchJsonResponseHandler extends FetchResponseHandler {
constructor() {
super();
}
extractContentFromResponse(response) {
return super.responseToJson(response);
}
}
class FetchTextResponseHandler extends FetchResponseHandler {
constructor() {
super();
}
extractContentFromResponse(response) {
return super.responseToText(response);
}
}
class FetchHtmlResponseHandler extends FetchResponseHandler {
constructor() {
super();
}
extractContentFromResponse(response) {
return super.responseToHtml(response);
}
}