-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
350 lines (322 loc) · 8.72 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
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
const requestHeaders = {};
const videoFragments = {};
const startTime = Date.now();
findTab();
chrome.runtime.onConnect.addListener((port) => {
if (port.name === "keepAlive") {
setTimeout(() => port.disconnect(), 250e3);
port.onDisconnect.addListener(() => findTab());
}
});
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.to === "background") {
if (message.subject === "download_file") {
downloadFile(message.data);
} else if (message.subject === "get_arrays") {
getArrays(message.data);
}
}
});
chrome.webNavigation.onBeforeNavigate.addListener((data) => {
console.log(`[${elapsedTime()}s] [T${data.tabId}] ${data.url}`);
});
chrome.webNavigation.onCommitted.addListener((data) => {
if (["reload", "typed", "generated"].includes(data.transitionType)) {
chrome.storage.local.remove(data.tabId.toString());
}
});
chrome.webRequest.onSendHeaders.addListener(
(data) => {
if (data.tabId !== -1) {
requestHeaders[data.requestId] = data.requestHeaders;
}
},
{
urls: ["<all_urls>"],
},
["requestHeaders", "extraHeaders"]
);
chrome.webRequest.onHeadersReceived.addListener(
(data) => {
if (data.tabId !== -1) {
chrome.tabs.get(data.tabId, (tab) => {
if (!tab) {
return;
}
data.tabURL = tab.url;
const header = getHeader(data.responseHeaders, "content-type");
data.mimeType = header && header.value.split(";", 1)[0];
if (matchURL(data)) {
updateWebRequests(data);
}
});
}
},
{
urls: ["<all_urls>"],
},
["responseHeaders", "extraHeaders"]
);
async function findTab(tabs) {
if (chrome.runtime.lastError) {
}
for (const { id: tabId } of tabs ||
(await chrome.tabs.query({ url: "*://*/*" }))) {
try {
await chrome.scripting.executeScript({
target: { tabId },
func: connect,
});
chrome.tabs.onUpdated.removeListener(onUpdate);
return;
} catch (e) {}
}
chrome.tabs.onUpdated.addListener(onUpdate);
}
function connect() {
chrome.runtime
.connect({ name: "keepAlive" })
.onDisconnect.addListener(connect);
}
function onUpdate(tabId, info, tab) {
/^https?:/.test(info.url) && findTab([tab]);
}
function elapsedTime() {
return ((Date.now() - startTime) / 1000).toFixed(2);
}
async function downloadFile(data) {
const downloadId = await chrome.downloads.download({
url: sanitizeURL(data.url),
});
if (downloadId) {
console.log(
`[${elapsedTime()}s] [R${data.requestId}] [D${downloadId}] ${data.url}`
);
} else {
console.log(
`[${elapsedTime()}s] [R${data.requestId}] Error: Failed to download ${
data.url
}`
);
}
}
function filterArray(array) {
return array instanceof Array && array.length;
}
async function getArrays(data) {
try {
let urls = videoFragments[data.requestId];
if (!urls || !urls.length) {
urls = await getPlaylistURL(data);
if (!urls.length) {
throw `Error: Cannot download ${data.url}`;
}
videoFragments[data.requestId] = urls;
}
let promises = [];
for (const [i, url] of urls.entries()) {
async function promise() {
updateDownloadStatus(data, {
msg: `[${i + 1}/${urls.length}] ${url}`,
perc: ((i + 1) * 100) / urls.length,
});
const array = await getArrayFromURL(
url,
data,
`${i + 1}/${urls.length}`
);
if (!filterArray(array)) {
throw `[${i + 1}/${urls.length}] Error: Cannot download ${data.url}`;
}
chrome.tabs.sendMessage(
data.tabId,
{
from: "background",
to: "content_script",
subject: "arrays_to_blob",
data: {
requestId: data.requestId,
array: array,
idx: i,
length: urls.length,
},
},
() => chrome.runtime.lastError
);
}
promises.push(promise());
if (promises.length === 10) {
await Promise.all(promises);
promises = [];
}
}
if (promises.length) {
await Promise.all(promises);
promises = [];
}
chrome.tabs.sendMessage(
data.tabId,
{
from: "background",
to: "content_script",
subject: "blob_to_url",
data: { requestId: data.requestId },
},
() => chrome.runtime.lastError
);
} catch (err) {
err = `[R${data.requestId}] ${err}`;
chrome.tabs.sendMessage(
data.tabId,
{
from: "background",
to: "content_script",
subject: "alert",
data: err,
},
() => chrome.runtime.lastError
);
console.log(`[${elapsedTime()}s] ${err}`);
}
updateDownloadStatus(data);
}
async function getPlaylistURL(data) {
let res = await fetch(data.url);
let text = (await res.text()) + "\n";
let urls = Array.from(text.matchAll(/,\n(.*)\n/g), (match) =>
sanitizeURL(new URL(match[1], data.url).href)
);
if (urls.length !== 0) {
return urls;
}
urls = {};
const heights = Array.from(
text.matchAll(/RESOLUTION=.*x(.*)\n(.*)\n/g),
(match) => {
let height = match[1];
const idx = height.indexOf(",");
if (idx !== -1) {
height = height.substring(0, idx);
}
urls[height] = sanitizeURL(new URL(match[2], data.url).href);
return parseInt(height);
}
);
if (heights.length) {
const maxHeight = Math.max(...heights).toString();
res = await fetch(urls[maxHeight]);
text = (await res.text()) + "\n";
urls = Array.from(text.matchAll(/,\n(.*)\n/g), (match) =>
sanitizeURL(new URL(match[1], urls[maxHeight]).href)
);
return urls;
}
return [];
}
async function getArrayFromURL(url, data, perc) {
console.log(`[${elapsedTime()}s] [R${data.requestId}] [${perc}] ${url}`);
try {
const res = await fetch(url);
const arrayBuffer = await res.arrayBuffer();
return Array.from(new Uint32Array(arrayBuffer));
} catch (err) {
err = `[R${data.requestId}] [${perc}] ${err}`;
chrome.tabs.sendMessage(
data.tabId,
{
from: "background",
to: "content_script",
subject: "alert",
data: err,
},
() => chrome.runtime.lastError
);
console.log(`[${elapsedTime()}s] ${err}`);
return null;
}
}
async function updateDownloadStatus(data, downloadStatus = null) {
if (downloadStatus) {
data.downloadStatus = downloadStatus;
} else {
delete data.downloadStatus;
}
chrome.runtime.sendMessage(
{
from: "background",
to: "popup",
subject: "update_status",
data: data,
},
() => chrome.runtime.lastError
);
let storage = await chrome.storage.local.get(data.tabId.toString());
const object = storage[data.tabId.toString()];
if (object instanceof Array && object.length) {
object[data.idx] = data;
storage = {};
storage[data.tabId.toString()] = object;
chrome.storage.local.set(storage);
}
}
function updateWebRequests(data) {
chrome.storage.local.get(data.tabId.toString(), (storage) => {
let object = storage[data.tabId.toString()];
if (!object) {
object = [];
}
data.idx = object.length;
if (requestHeaders[data.requestId]) {
data.requestHeaders = requestHeaders[data.requestId];
}
if (matchPlaylistURL(data)) {
data.isPlaylist = true;
}
object.push(data);
storage = {};
storage[data.tabId.toString()] = object;
chrome.storage.local.set(storage);
});
}
function getHeader(headers, headerName) {
for (let i = 0; i < headers.length; i++) {
if (headers[i].name.toLowerCase() === headerName) {
return headers[i];
}
}
}
function sanitizeURL(url) {
// Define your custom rules here
if (url.match(/googleusercontent\.com\/.*&url=.*/g)) {
return Array.from(
url.matchAll(/googleusercontent\.com\/.*&url=(.*)/g)
)[0][1];
}
return url;
}
function matchURL(data) {
// Define your custom rules here
if (data.tabURL.match(/https?:\/\/www\.youtube\.com/g)) {
return false;
}
return (
(data.mimeType &&
(data.mimeType === "application/vnd.apple.mpegurl" ||
data.mimeType.match(/^(video|audio)/g))) ||
data.url.match(/^(?!.*\bthumbnails\.vtt\b).*\.(m3u8|aaa|ts|vtt|srt)\b/g) ||
data.url.match(/\/br\/H[1-4]/g) ||
data.url.match(/\bmaster\.txt\b/g) ||
data.url.match(/\/subtitles?\//g) ||
data.url.includes("/m3/") ||
data.url.includes("googleusercontent.com/download/storage/")
);
}
function matchPlaylistURL(data) {
// Define your custom rules here
return (
data.mimeType === "application/vnd.apple.mpegurl" ||
data.url.includes("master.txt") ||
data.url.includes(".m3u8") ||
data.url.includes("/m3/")
);
}