-
Notifications
You must be signed in to change notification settings - Fork 1
/
background.js
105 lines (70 loc) · 2.64 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
function getUtorrentHost() {
return Shared.getSetting('protocol') + encodeURIComponent(Shared.getSetting('username')) + ":" + encodeURIComponent(Shared.getSetting('password')) + "@" + Shared.getSetting('host') + ":" + Shared.getSetting('port');
}
function getUtorrentToken() {
var xhr = new XMLHttpRequest();
xhr.open("GET", getUtorrentHost() + "/gui/token.html", false);
xhr.send(null);
if (xhr.readyState == 4 && xhr.status == 200) {
var parser = new DOMParser();
var token = parser.parseFromString(xhr.responseText, "text/html").getElementById("token").innerHTML;
return token;
} else {
Shared.notify('error', 'An error ocurred getting the auth token.');
}
return '';
}
function makeRequest(url) {
var resp = null;
var token = getUtorrentToken();
if (!token.length) {
return null;
}
var requestUrl = getUtorrentHost() + "/gui/?" + url + "&t=" + (new Date().getTime()) + "&token=" + token;
var xhr = new XMLHttpRequest();
xhr.open("GET", requestUrl, false);
xhr.send(null);
if (xhr.readyState == 4 && xhr.status == 200) {
resp = JSON.parse(xhr.responseText);
}
return resp;
}
function getTorrentHashFromUrl(url) {
return url.substring(url.indexOf('urn:btih:') + 9, url.indexOf('urn:btih:') + 49);
}
function getClickHandler() {
return function(info, tab) {
var response = makeRequest("action=add-url&s=" + encodeURIComponent(info.linkUrl));
if (typeof response == "object" && response.build > 0) {
Shared.notify('success');
if (Shared.getSetting('torrent-label') != "") {
var torrentHash = getTorrentHashFromUrl(info.linkUrl);
makeRequest("action=setprops&s=label&v=" + Shared.getSetting('torrent-label') + "&hash=" + torrentHash);
}
} else {
Shared.notify('error', 'An error ocurred sending link to uTorrent server.');
}
};
}
chrome.contextMenus.create({
"id": "utorrent-send-link",
"title": "Send to uTorrent",
"type": "normal",
"contexts": ["link"],
"targetUrlPatterns": ["magnet:*", "*://*/*.torrent"],
"onclick": getClickHandler()
});
if (Shared.getSetting('notifyme') != 'never') {
chrome.notifications.onClicked.addListener(function() {
chrome.tabs.create({
url: getUtorrentHost() + '/gui/'
});
});
}
// open the options page only the first time in order to configure
chrome.runtime.onInstalled.addListener(function() {
Shared.setSetting('protocol', 'http://');
chrome.tabs.create({
url: chrome.runtime.getURL('options.html')
});
});