-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbackground.js
300 lines (242 loc) · 8.86 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
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
// Use of this source code is governed by a license that can be
// found in the LICENSE file.
'use strict';
let tabHashmap = new Map();
// Chrome bullshit to keep the extension alive
const keepAlive = setInterval(chrome.runtime.getPlatformInfo, 25 * 1000);
/**
* Setup on extension init.
*/
chrome.runtime.onInstalled.addListener(function () {
chrome.runtime.openOptionsPage();
chrome.permissions.request({ origins: ["https://*/","http://*/"] });
});
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (changeInfo.url) {
tabHashmap.delete(tabId);
onNewUrl(tab);
} else if (changeInfo.status && tabHashmap.has(tabId)) {
// Per-tab badges go away when the tab is refreshed, so we put 'em back
updateBadge(tab, tabHashmap.get(tabId));
}
});
chrome.tabs.onActivated.addListener(function (activeInfo) {
chrome.tabs.get(activeInfo.tabId, function (tab) {
onNewUrl(tab);
});
});
chrome.runtime.onMessage.addListener(
function (request, sender, callback) {
// Multi-tab download req
if (request.type == "batchDownload") {
chrome.storage.sync.get(['server', 'api', 'categoryID'], function (result) {
request.tabs?.forEach(tab => {
sendDownloadRequest(tab, result.server, result.api, result.categoryID, true);
});
showNotification("Batch Download", `Queued ${request.tabs.length} URLs for download!`);
});
}
// Single tab download req
if (request.type == "downloadUrl") {
chrome.storage.sync.get(['server', 'api', 'categoryID'], function (result) {
sendDownloadRequest(request.tab, result.server, result.api, result.categoryID);
});
}
// Tab info req
if (request.type == "getTabInfo") {
callback(tabHashmap.get(request.tab.id));
}
// Reverify tab req
if (request.type == "recheckTab") {
tabHashmap.delete(request.tab.id);
onNewUrl(request.tab, true);
}
});
function onNewUrl(tab, bypassRegexes = false) {
// If the tab already has a browserAction, we do nothing
if (!tabHashmap.has(tab.id))
chrome.storage.sync.get(['server', 'api', 'supportedURLs'], function (result) {
if (typeof result.server !== 'undefined' && result.server.trim() !== "") // check for undefined
if (bypassRegexes || isUrlSupported(tab, result.supportedURLs))
checkUrl(result.server.trim(), result.api, tab);
else
updateTabInfo(tab, { status: "other", message: "This website is not supported for downloading.\nBut you can still try it!" });
else
updateTabInfo(tab, { status: "other", message: "Please setup your server settings." });
});
}
function isUrlSupported(tab, urlRegexes) {
if (typeof urlRegexes === 'undefined' || tab.url === undefined) return false;
urlRegexes = urlRegexes.map(s => new RegExp(s));
let checks = urlRegexes.map(regex => regex.test(tab.url));
return (checks.includes(true));
}
/**
* Send a call to the source finder to check if the given URL is already downloaded or not.
* Updates the badge with the results
* @param {*} serverUrl URL to LRR server
* @param {*} apiKey API Key for LRR server
* @param {*} url URL to check
*/
function checkUrl(serverUrl, apiKey, tab) {
updateTabInfo(tab, { status: "checking" });
if (tab.url === undefined) {
updateTabInfo(tab, { status: "other", message: "Not a downloadable URL. " });
return;
}
// The urlfinder plugin can handle the url as is.
console.log(`${serverUrl}/api/plugins/use?plugin=urlfinder&arg=${tab.url}`);
fetch(`${serverUrl}/api/plugins/use?plugin=urlfinder&arg=${tab.url}`,
{ method: "POST", headers: getAuthHeader(apiKey) })
.then(response => response.json())
.then((r) => {
if (r.success === 1) {
updateTabInfo(tab, { status: "downloaded", arcId: r.data.id });
} else {
updateTabInfo(tab, { status: "other", message: r.error });
}
})
.catch(error => {
updateTabInfo(tab, { status: "error", message: error.toString() });
// Turn this on for debug notifications
//showNotification("Error while checking URL :", error.toString());
});
}
/**
* Update the tab's browserAction, and update data in popup and hashmap.
* @param {*} tab Tab to update
* @param {*} infoObject Info object, should contain at least the "status" element.
*/
function updateTabInfo(tab, infoObject) {
chrome.tabs.get(tab.id, function () {
if (chrome.runtime.lastError) {
// Tab has likely been closed
console.log(chrome.runtime.lastError.message);
tabHashmap.delete(tab.id);
} else {
// Tab exists
updateBadge(tab, infoObject);
// Save info in hashmap, and send it to the popup if it's open
tabHashmap.set(tab.id, infoObject);
if (tab.active)
chrome.runtime.sendMessage({ type: "updateFromBackground", data: infoObject });
}
});
}
function updateBadge(tab, info) {
let color = "rgb(194, 25, 25)";
let text = "???";
try {
console.log(tab.id + " " + JSON.stringify(info));
switch (info.status) {
case "downloaded":
text = "✔";
color = "rgb(25, 194, 48)";
break;
case "downloading":
text = "#" + info.jobId;
color = "rgb(64, 124, 255)";
break;
case "checking":
text = "...";
color = "rgb(255, 174, 0)";
break;
case "error":
text = "ERR";
color = "rgb(194, 25, 25)";
break;
case "other":
text = "X";
color = "rgb(54, 57, 64)";
break;
}
} catch (e) { console.log(e); }
console.log(color + text);
chrome.action.setBadgeBackgroundColor({ color: color, tabId: tab.id });
chrome.action.setBadgeText({ text: text, tabId: tab.id });
}
// Send URLs to the Download API and add a checkJobStatus to track its progress.
function sendDownloadRequest(tab, serverUrl, apiKey, categoryID, isBatch = false) {
if (tab.url === undefined) {
updateTabInfo(tab, { status: "other", message: "Not a downloadable URL. " });
return;
}
let formData = new FormData();
formData.append('url', tab.url);
if (categoryID !== "") {
formData.append('catid', categoryID);
}
fetch(`${serverUrl}/api/download_url`, { method: "POST", body: formData, headers: getAuthHeader(apiKey) })
.then(response => response.json())
.then((data) => {
if (data.success) {
updateTabInfo(tab, { status: "downloading", jobId: data.job });
if (!isBatch)
showNotification(`Download for ${tab.url}`, `Queued as job #${data.job}!`);
// Check minion job state periodically to update the result
checkJobStatus(serverUrl, apiKey, data.job,
(d) => handleDownloadResult(tab, d.result),
(error) => console.log(error));
} else {
throw new Error(data.message);
}
})
.catch(error => showNotification(`Error while queuing ${tab.url}`, error.toString()));
}
function handleDownloadResult(tab, data) {
if (data.success === 1) {
updateTabInfo(tab, { status: "downloaded", arcId: data.id });
showNotification(`Download of ${tab.url} complete!`,
`File has been saved to your server and given the ID ${data.id}`);
chrome.storage.sync.get(['closeOnDL'], function (result) {
if (result.closeOnDL)
chrome.tabs.remove(tab.id);
});
} else {
updateTabInfo(tab, { status: "error", message: data.message });
showNotification(`Download for ${tab.url}`, `Failed: ${data.message}`);
}
}
function getAuthHeader(apiKey) {
return { Authorization: "Bearer " + btoa(apiKey) };
}
function showNotification(title, msg) {
var opt = {
type: "basic",
title: title,
message: (typeof msg === 'string' || msg instanceof String) ? msg : JSON.stringify(msg),
iconUrl: "images/get_started128.png"
}
console.log(title + " " + msg);
chrome.notifications?.create(null, opt, null);
}
/**
* Checks the status of a Download job until it's completed.
* Execute a callback on successful job completion.
* @param {*} serverUrl
* @param {*} apiKey
* @param {*} jobId
* @param {*} callback
* @param {*} failureCallback
*/
function checkJobStatus(serverUrl, apiKey, jobId, callback, failureCallback) {
fetch(`${serverUrl}/api/minion/${jobId}/detail`, { method: "GET", headers: getAuthHeader(apiKey) })
.then(response => response.ok ? response.json() : { success: 0, error: "Response was not OK" })
.then((data) => {
if (data.error)
throw new Error(data.error);
if (data.state === "failed") {
throw new Error(data.result);
}
if (data.state !== "finished") {
// Wait and retry, job isn't done yet
setTimeout(function () {
checkJobStatus(serverUrl, apiKey, jobId, callback, failureCallback);
}, 2000);
} else {
// Update UI with info
callback(data);
}
})
.catch(error => { showNotification("URL Download Failed", error.toString()); failureCallback(error) });
}