This repository has been archived by the owner on Jan 9, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
batcher.js
89 lines (73 loc) · 2.78 KB
/
batcher.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
const DEBUG = false;
const DRY_RUN = false;
const resolutions = [360, 480, 720, 1080];
// Uses XHR because for some reason it doesn't send an Origin header
// while fetch() sends 'Origin: null', which triggers CSRF protection
function post(path, params, callback) {
let xhr = new XMLHttpRequest();
xhr.open("POST", path, true);
xhr.onreadystatechange = function () {
if (callback && xhr.readyState == 4)
callback(xhr);
};
let formData = new FormData();
for (let key in params) {
formData.append(key, params[key]);
}
xhr.send(formData);
}
async function getSettings() {
let defaultsURL = browser.runtime.getURL("options/defaults.json");
let response = await fetch(defaultsURL, { mode: "no-cors" });
let defaults = await response.json();
return browser.storage.sync.get(defaults);
}
async function downloadVisibleLinks(res) {
let magnets = {};
magnets[res] = document.querySelectorAll("div[class$='" + res + "p'] a[title='Magnet Link']");
if (!DRY_RUN) {
let settings = await getSettings();
let torrentAddPath = "api/v2/torrents/add";
if (settings.apiVersion == 1) {
torrentAddPath = "command/download";
}
let downloadEndpoint = `http://${settings.host}:${settings.port}/${torrentAddPath}`;
let magnetURLs = Array.from(magnets[res], a => a.href).reverse().join("\n");
let callback = null;
if (DEBUG) {
callback = function (xhr) {
console.log(
`Response from '${xhr.responseURL}':\n` +
`Status: ${xhr.status}\n` +
`Response: '${xhr.responseText}'`
);
}
}
post(downloadEndpoint, { urls: magnetURLs }, callback);
} else {
console.log("Magnets found for " + res + "p: " + magnets[res].length);
}
}
function injectElements() {
let parent = document.querySelector(".episode-container");
let div = document.createElement("div");
div.setAttribute("class", "hs-batcher");
div.style.paddingTop = "5px";
parent.insertBefore(div, parent.childNodes[4].nextSibling);
let wrapper = document.createElement("div");
wrapper.style.textAlign = "center";
div.append(wrapper);
let select = document.createElement("select");
for (let i = 0; i < resolutions.length; i++) {
let option = document.createElement("option");
option.value = resolutions[i];
option.text = resolutions[i] + "p";
select.append(option);
}
wrapper.append(select);
let button = document.createElement("button");
button.innerHTML = "Download";
button.onclick = () => downloadVisibleLinks(select.options[select.selectedIndex].value);
wrapper.append(button);
}
injectElements();