-
Notifications
You must be signed in to change notification settings - Fork 57
/
background.js
244 lines (203 loc) · 5.84 KB
/
background.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
"use strict";
const MAX_ITEMS = 10;
const downloads = new Map();
const currentRequests = new Map();
const defaultOptions = {
doubleQuotes: false,
excludeHeaders: "Accept-Encoding Connection",
command: "curl",
curlOptions: "",
wgetOptions: "",
aria2Options: "",
};
function getOptions() {
return new Promise((resolve) => {
browser.storage.local.get().then((res) => {
res = Object.assign({}, defaultOptions, res);
resolve(res);
});
});
}
function setOptions(values) {
new Promise((resolve) => {
browser.storage.local.set(values).then(() =>
getOptions().then((c) => {
resolve(c);
})
);
});
}
function resetOptions() {
new Promise((resolve) => {
browser.storage.local.clear().then(() =>
getOptions().then((c) => {
resolve(c);
})
);
});
}
function clear() {
downloads.clear();
}
function getDownloadList() {
const list = [];
for (let [reqId, req] of downloads)
list.push({
id: reqId,
url: req.url,
filename: req.filename,
size: req.size,
});
return list;
}
function generateCommand(reqId, options) {
const request = downloads.get(reqId);
if (!request) throw new Error("Request not found");
let excludeHeaders = options.excludeHeaders
.split(" ")
.map((h) => h.toLowerCase());
let headers = request.headers.filter(
(h) => excludeHeaders.indexOf(h.name.toLowerCase()) === -1
);
const cmd = window[options.command](
request.url,
request.method,
headers,
request.payload,
request.filename,
options
);
return cmd;
}
function handleMessage(msg) {
const name = msg[0];
const args = msg.slice(1);
if (name === "getOptions") return getOptions();
else if (name === "setOptions") return setOptions(...args);
else if (name === "resetOptions") return resetOptions();
else if (name === "getDownloadList")
return new Promise((resolve) => resolve(getDownloadList()));
else if (name === "clear") return clear(...args);
else if (name === "generateCommand")
return new Promise((resolve) => {
try {
resolve(generateCommand(...args));
} catch (err) {
resolve(err.message);
}
});
}
browser.runtime.onMessage.addListener(handleMessage);
function onBeforeRequest(details) {
if (
(details.type === "main_frame" || details.type === "sub_frame") &&
details.tabId >= 0
) {
const now = Date.now();
// Just in case of a leak
currentRequests.forEach((req, reqId) => {
if (req.timestamp + 10000 < now) currentRequests.delete(reqId);
});
const req = {
id: details.requestId,
method: details.method,
url: details.url,
timestamp: now,
payload: details.requestBody,
};
currentRequests.set(details.requestId, req);
}
}
function onSendHeaders(details) {
const req = currentRequests.get(details.requestId);
if (req) {
req.headers = details.requestHeaders;
} else if (
(details.type === "main_frame" || details.type === "sub_frame") &&
details.tabId >= 0 &&
details.method === "GET"
) {
// Firefox 52 (ESR) doesn't call "onBeforeRequest" because requestBody
// property isn't supported
const now = Date.now();
// Just in case of a leak
currentRequests.forEach((r, reqId) => {
if (r.timestamp + 10000 < now) currentRequests.delete(reqId);
});
currentRequests.set(details.requestId, {
id: details.requestId,
method: details.method,
url: details.url,
timestamp: now,
headers: details.requestHeaders,
});
}
}
function onResponseStarted(details) {
const request = currentRequests.get(details.requestId);
if (!request) return;
currentRequests.delete(details.requestId);
if (details.statusCode !== 200 || details.fromCache) return;
let contentType, contentDisposition;
for (let header of details.responseHeaders) {
let headerName = header.name.toLowerCase();
if (headerName === "content-type") {
contentType = header.value.toLowerCase();
} else if (headerName === "content-disposition") {
contentDisposition = header.value.toLowerCase();
request.filename = window.getFilenameFromContentDisposition(header.value);
} else if (headerName === "content-length") {
request.size = +header.value;
}
}
if (!contentDisposition || !contentDisposition.startsWith("attachment"))
if (
contentType.startsWith("text/html") ||
contentType.startsWith("text/plain") ||
contentType.startsWith("image/") ||
contentType.startsWith("application/xhtml") ||
contentType.startsWith("application/xml")
)
return;
if (!request.filename)
request.filename = window.getFilenameFromUrl(request.url);
downloads.set(details.requestId, request);
browser.browserAction.getBadgeText({}).then((txt) => {
browser.browserAction.setBadgeText({ text: `${+txt + 1}` });
});
if (downloads.size > MAX_ITEMS) {
let keys = Array.from(downloads.keys());
keys.slice(0, keys.length - MAX_ITEMS).forEach((k) => downloads.delete(k));
}
}
function onBeforeRedirect() {
// Need to listen to this event otherwise the new request will include
// the old URL. This is possibly a bug.
}
function onErrorOccurred(details) {
currentRequests.delete(details.requestId);
}
browser.webRequest.onBeforeRedirect.addListener(onBeforeRedirect, {
urls: ["<all_urls>"],
});
browser.webRequest.onErrorOccurred.addListener(onErrorOccurred, {
urls: ["<all_urls>"],
});
browser.webRequest.onBeforeRequest.addListener(
onBeforeRequest,
{ urls: ["<all_urls>"] },
["requestBody"]
);
browser.webRequest.onSendHeaders.addListener(
onSendHeaders,
{ urls: ["<all_urls>"] },
["requestHeaders"]
);
browser.webRequest.onResponseStarted.addListener(
onResponseStarted,
{
urls: ["<all_urls>"],
},
["responseHeaders"]
);
browser.browserAction.setBadgeBackgroundColor({ color: "#4a90d9" });