-
-
Notifications
You must be signed in to change notification settings - Fork 67
/
background.js
1067 lines (989 loc) · 39.8 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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Utils from "./js/utils.js";
import Configs from "./js/config.js";
import Aria2 from "./js/aria2.js";
import Aria2Options from "./js/aria2Options.js";
const NID_DEFAULT = "NID_DEFAULT";
const NID_TASK_NEW = "NID_TASK_NEW";
const NID_TASK_STOPPED = "NID_TASK_STOPPED";
const NID_CAPTURED_OTHERS = "NID_CAPTURED_OTHERS";
var CurrentTabUrl = "about:blank";
var MonitorId = -1;
var MonitorInterval = 3000; // Aria2 monitor interval 3000ms
var RemoteAria2List = [];
const isDownloadListened = () => chrome.downloads.onDeterminingFilename.hasListener(captureDownload);
/**
* @typedef RpcItem
* @type {Object}
* @property {string} name - The name of the Aria2 RPC Server.
* @property {string} url - The RPC URL with the secret key.
* @property {string} location - The path to save download file.
* @property {string} pattern - The URL pattern for auto-matching.
*/
/**
* @typedef DownloadItem
* @type {Object}
* @property {string} url - Single url or multiple urls which are conjunct with '\n'.
* @property {string} filename
* @property {string} dir - Download directory
* @property {string} referrer
* @property {Object} options - Aria2 RPC options
* @property {boolean} multiTask - Indicate whether includes multiple urls.
* @property {string} type - "DOWNLOAD_VIA_BROWSER" will invoke a chrome download.
*/
(function main() {
init();
registerAllListeners();
})()
/**
* Invoke a download task
*
* @param {DownloadItem} downloadItem
* @param {RpcItem} rpcItem
* @returns {boolean} the result of creating download task
*/
async function download(downloadItem, rpcItem) {
if (!downloadItem || !downloadItem.url) {
console.warn("Download: Invalid download item, download request is dismissed!");
return false;
}
let result = true;
if (!("multiTask" in downloadItem)) {
downloadItem.multiTask = downloadItem.url.includes('\n');
}
if (downloadItem.type == "DOWNLOAD_VIA_BROWSER") {
try {
if (downloadItem.multiTask) {
let urls = downloadItem.url.split('\n');
for (const url of urls) {
await chrome.downloads.download({ url });
}
} else {
await chrome.downloads.download({ url: downloadItem.url, filename: downloadItem.filename });
}
} catch {
result = false;
}
} else {
if (!rpcItem || !rpcItem.url) {
rpcItem = getRpcServer(downloadItem.url + downloadItem.filename);
}
downloadItem.dir = rpcItem.location;
if (!downloadItem.filename) downloadItem.filename = '';
if (Configs.askBeforeDownload || downloadItem.multiTask) {
try {
await launchUI(downloadItem);
} catch (error) {
result = false;
console.warn("Download: Launch UI failed.");
}
} else {
result = await send2Aria(downloadItem, rpcItem);
}
}
return result;
}
async function getCookies(downloadItem) {
let storeId = downloadItem.incognito == true ? "1" : "0";
let url = downloadItem.multiTask ? downloadItem.referrer : downloadItem.url;
let cookies = await chrome.cookies.getAll({ url, storeId });
let cookieItems = [];
for (const cookie of cookies) {
cookieItems.push(cookie.name + "=" + cookie.value);
}
return cookieItems;
}
async function send2Aria(downloadItem, rpcItem) {
let cookieItems = [];
try {
if (rpcItem.ignoreInsecure || Utils.isLocalhost(rpcItem.url) || /^(https|wss)/i.test(rpcItem.url)) {
cookieItems = await getCookies(downloadItem);
}
} catch (error) {
console.warn(error.message);
}
let headers = [];
if (cookieItems.length > 0) {
headers.push("Cookie: " + cookieItems.join("; "));
}
headers.push("User-Agent: " + navigator.userAgent);
let options = await Aria2Options.getUriTaskOptions(rpcItem.url);
if (!!options.header) {
options.header = options.header.split('\n').filter(item => !/^(cookie|user-agent|connection)/i.test(item));
headers = headers.concat(options.header);
}
options.header = headers;
if (downloadItem.referrer) options.referer = downloadItem.referrer;
if (downloadItem.filename) options.out = downloadItem.filename;
if (downloadItem.dir) options.dir = downloadItem.dir;
if (downloadItem.hasOwnProperty('options')) {
options = Object.assign(options, downloadItem.options);
}
let remote = Utils.parseUrl(rpcItem.url);
remote.name = rpcItem.name;
let aria2 = new Aria2(remote);
let silent = Configs.keepSilent;
return aria2.addUri(downloadItem.url, options).then(function (response) {
if (response && response.error) {
return Promise.reject(response.error);
}
Aria2Options.getGlobalOptions(rpcItem.url).then(function (globalOptions) {
if (Object.keys(globalOptions).length > 0)
aria2.setGlobalOptions(globalOptions);
});
if (Configs.allowNotification) {
const data = { method: "aria2.onExportSuccess", source: aria2, gid: response.result };
if (!downloadItem.filename)
downloadItem.filename = Utils.getFileNameFromUrl(downloadItem.url);
data.contextMessage = Utils.formatFilepath(options.dir) + downloadItem.filename;
notifyTaskStatus(data);
}
return Promise.resolve(true);
}).catch(function (error) {
if (Configs.allowNotification) {
let contextMessage = '';
if (error && error.message) {
if (error.message.toLowerCase().includes('unauthorized'))
contextMessage = "Secret key is incorrect."
else if (error.message.toLowerCase().includes("failed to fetch"))
contextMessage = "Aria2 server is unreachable.";
else
contextMessage = "Error:" + error.message;
}
const data = { method: "aria2.onExportError", source: aria2, contextMessage };
notifyTaskStatus(data);
}
return Promise.resolve(false);
});
}
/**
* Get a rpc item whose pattern(s) matches the giving resource url
*
* @param {string} url - The resource url to be downloaded
* @return {RpcItem} a RpcItem which refers to an Aria2 RPC server
*/
function getRpcServer(url) {
let defaultIndex = 0;
for (let i = 1; i < Configs.rpcList.length; i++) {
const patternStr = Configs.rpcList[i]['pattern'];
if (patternStr == '*') {
defaultIndex = i;
continue;
}
for (let pattern of patternStr.split(',')) {
pattern = pattern.trim();
if (matchRule(url, pattern)) {
return Configs.rpcList[i];
}
}
}
return Configs.rpcList[defaultIndex];
}
function matchRule(str, rule) {
return new RegExp("^" + rule.replaceAll('*', '.*') + "$").test(str);
}
function shouldCapture(downloadItem) {
var currentTabUrl = new URL(CurrentTabUrl);
var url = new URL(downloadItem.referrer || downloadItem.url);
if (downloadItem.byExtensionId == chrome.runtime.id) {
return false;
}
if (downloadItem.error || downloadItem.state != "in_progress" || !/^(https?|s?ftp):/i.test(downloadItem.url)) {
return false;
}
for (var i in Configs.allowedSites) {
if (matchRule(currentTabUrl.hostname, Configs.allowedSites[i]) || matchRule(url.hostname, Configs.allowedSites[i])) {
return true;
}
}
for (var i in Configs.blockedSites) {
if (matchRule(currentTabUrl.hostname, Configs.blockedSites[i]) || matchRule(url.hostname, Configs.blockedSites[i])) {
return false;
}
}
for (var i in Configs.allowedExts) {
if (downloadItem.filename.endsWith(Configs.allowedExts[i]) || Configs.allowedExts[i] == "*") {
return true;
}
}
for (var i in Configs.blockedExts) {
if (downloadItem.filename.endsWith(Configs.blockedExts[i]) || Configs.blockedExts[i] == "*") {
return false;
}
}
return downloadItem.fileSize >= Configs.fileSize * 1024 * 1024
}
function enableCapture() {
if (!isDownloadListened()) {
chrome.downloads.onDeterminingFilename.addListener(captureDownload);
}
chrome.action.setIcon({
path: {
'32': "images/logo32.png",
'64': "images/logo64.png",
'128': "images/logo128.png",
'256': "images/logo256.png"
}
});
Configs.integration = true;
chrome.contextMenus.update("MENU_CAPTURE_DOWNLOAD", { checked: true });
}
function disableCapture() {
if (isDownloadListened()) {
chrome.downloads.onDeterminingFilename.removeListener(captureDownload);
}
chrome.action.setIcon({
path: {
'32': "images/logo32-dark.png",
'64': "images/logo64-dark.png",
'128': "images/logo128-dark.png",
'256': "images/logo256-dark.png"
}
});
Configs.integration = false;
chrome.contextMenus.update("MENU_CAPTURE_DOWNLOAD", { checked: false });
}
async function captureDownload(downloadItem, suggest) {
if (downloadItem.byExtensionId) {
// TODO: Filename assigned by chrome.downloads.download() was not passed in
// and will be discarded by Chrome. No solution or workaround right now. The
// only way is disabling capture before other extensions call chrome.downloads.download().
suggest();
const title = chrome.i18n.getMessage("RemindCaptureTip");
const message = chrome.i18n.getMessage("RemindCaptureTipDes");
const requireInteraction = true;
const btnTitle1 = chrome.i18n.getMessage("Dismiss");
const btnTitle2 = chrome.i18n.getMessage("NeverRemind");
const buttons = [{ title: btnTitle1 }, { title: btnTitle2 }];
if (Configs.remindCaptureTip && downloadItem.byExtensionId != chrome.runtime.id) {
Utils.showNotification({ title, message, buttons, requireInteraction }, NID_CAPTURED_OTHERS);
}
}
//always use finalurl when it is available
if (downloadItem.finalUrl && downloadItem.finalUrl != "about:blank") {
downloadItem.url = downloadItem.finalUrl;
}
if (Configs.integration && shouldCapture(downloadItem)) {
chrome.downloads.cancel(downloadItem.id).then(() => {
if (chrome.runtime.lastError)
chrome.runtime.lastError = null;
});
if (downloadItem.referrer == "about:blank") {
downloadItem.referrer = "";
}
let rpcItem = getRpcServer(downloadItem.url + downloadItem.filename);
let successful = await download(downloadItem, rpcItem);
if (!successful && Utils.isLocalhost(rpcItem.url)) {
disableCapture();
chrome.downloads.download({ url: downloadItem.url }).then(enableCapture);
}
}
}
async function launchUI(info) {
const index = chrome.runtime.getURL('ui/ariang/index.html');
let webUiUrl = index + '#!'; // launched from notification, option menu or browser toolbar icon
/* assemble the final web ui url */
if (info?.hasOwnProperty("filename") && info.url) { // launched for new task
const downloadItem = info;
webUiUrl = webUiUrl + "/new?url=" + encodeURIComponent(btoa(encodeURI(downloadItem.url)));
if (downloadItem.referrer && downloadItem.referrer != "" && downloadItem.referrer != "about:blank") {
webUiUrl = webUiUrl + "&referer=" + encodeURIComponent(downloadItem.referrer);
}
let header = "User-Agent: " + navigator.userAgent;
let cookies = await getCookies(downloadItem);
if (cookies.length > 0) {
header += "\nCookie: " + cookies.join(";");
}
webUiUrl = webUiUrl + "&header=" + encodeURIComponent(header);
if (downloadItem.filename) {
webUiUrl = webUiUrl + "&filename=" + encodeURIComponent(downloadItem.filename);
}
if (downloadItem.dir) {
webUiUrl = webUiUrl + "&dir=" + encodeURIComponent(downloadItem.dir);
}
} else if (typeof info === "string" && info.startsWith(NID_TASK_STOPPED)) { // launched from task done notification click
const gid = info.slice(NID_TASK_STOPPED.length) || '';
webUiUrl += gid ? "/task/detail/" + gid : "/stopped";
} else {
webUiUrl = index;
}
chrome.tabs.query({ "url": index }).then(function (tabs) {
if (tabs?.length > 0) {
chrome.windows.update(tabs[0].windowId, {
focused: true
});
let prop = { active: true };
if (webUiUrl != index) prop.url = webUiUrl;
chrome.tabs.update(tabs[0].id, prop);
return;
}
if (Configs.webUIOpenStyle == "window") {
openInWindow(webUiUrl);
} else {
chrome.tabs.create({
url: webUiUrl
});
}
});
}
async function openInWindow(url) {
let screen = await chrome.system.display.getInfo()
const w = Math.floor(screen[0].workArea.width * 0.75);
const h = Math.floor(screen[0].workArea.height * 0.75)
const l = Math.floor(screen[0].workArea.width * 0.12);
const t = Math.floor(screen[0].workArea.height * 0.12);
chrome.windows.create({
url: url,
width: w,
height: h,
left: l,
top: t,
type: 'popup',
focused: false
}).then(function (window) {
chrome.windows.update(window.id, {
focused: true
});
});
}
function createRpcOptionsMenu() {
let rpcOptionsList = [];
for (const i in Configs.rpcList) {
if (!Configs.rpcList[i].pattern || Configs.rpcList[i].pattern == '*') {
rpcOptionsList.push({ id: i, name: Configs.rpcList[i].name })
}
}
if (rpcOptionsList.length < 1) return;
let needParentMenu = true;
for (const menuItem of rpcOptionsList) {
if (needParentMenu) {
let title = '🔘 ' + chrome.i18n.getMessage("selectDefaultRpcStr");
chrome.contextMenus.create({
"type": "normal",
"id": "MENU_RPC_LIST",
"title": title,
"contexts": ["action"]
});
needParentMenu = false;
}
let checked = Configs.rpcList[menuItem.id].pattern == '*'
chrome.contextMenus.create({
"type": "radio",
"checked": checked,
"id": "MENU_RPC_LIST-" + menuItem.id,
"parentId": "MENU_RPC_LIST",
"title": menuItem.name,
"contexts": ["action"]
});
}
}
function createOptionMenu() {
let title = chrome.i18n.getMessage("downloadCaptureStr");
chrome.contextMenus.create({
"type": "checkbox",
"checked": Configs.integration,
"id": "MENU_CAPTURE_DOWNLOAD",
"title": '📥 ' + title,
"contexts": ["action"]
});
title = chrome.i18n.getMessage("monitorAria2Str");
chrome.contextMenus.create({
"type": "checkbox",
"checked": Configs.monitorAria2,
"id": "MENU_MONITOR_ARIA2",
"title": '🩺 ' + title,
"contexts": ["action"]
});
chrome.contextMenus.create({
"type": "separator",
"id": "separator",
"contexts": ["action"]
});
if (Utils.getPlatform() == `Windows` && RemoteAria2List[0]?.isLocalhost) {
title = chrome.i18n.getMessage("startAria2Str");
chrome.contextMenus.create({
"type": "normal",
"id": "MENU_START_ARIA2",
"title": '⚡️ ' + title,
"contexts": ["action"]
});
} else {
title = chrome.i18n.getMessage("openWebUIStr");
chrome.contextMenus.create({
"type": "normal",
"id": "MENU_OPEN_WEB_UI",
"title": '🪟 ' + title,
"contexts": ["action"]
});
}
title = chrome.i18n.getMessage("websiteFilterStr");
chrome.contextMenus.create({
"type": "normal",
"id": "MENU_WEBSITE_FILTER",
"title": '🔛 ' + title,
"contexts": ["action"]
});
title = chrome.i18n.getMessage("addToWhiteListStr");
chrome.contextMenus.create({
"type": "normal",
"id": "MENU_UPDATE_ALLOW_SITE",
"parentId": "MENU_WEBSITE_FILTER",
"title": '✅ ' + title,
"contexts": ["action"]
});
title = chrome.i18n.getMessage("addToBlackListStr");
chrome.contextMenus.create({
"type": "normal",
"id": "MENU_UPDATE_BLOCK_SITE",
"parentId": "MENU_WEBSITE_FILTER",
"title": '🚫 ' + title,
"contexts": ["action"]
});
createRpcOptionsMenu();
}
function createContextMenu() {
var strExport = chrome.i18n.getMessage("contextmenuTitle");
let strExportAllDes = chrome.i18n.getMessage("exportAllDes");
if (Configs.exportAll) {
chrome.contextMenus.create({
id: "MENU_EXPORT_ALL",
title: strExportAllDes,
contexts: ['page']
});
}
if (Configs.contextMenus) {
if (Configs.askBeforeExport) {
chrome.contextMenus.create({
id: "MENU_EXPORT_TO",
title: strExport + "AriaNG",
contexts: ['link', 'selection']
});
} else {
let title = '';
for (const i in Configs.rpcList) {
if (Configs.rpcList.length == 1) {
title = strExport + Configs.rpcList[i]['name'] + ' 📥';
} else if (Configs.rpcList.length > 1) {
title = '📥 ' + strExport + Configs.rpcList[i]['name'];
}
chrome.contextMenus.create({
id: "MENU_EXPORT_TO-" + i,
title: title,
contexts: ['link', 'selection']
});
}
}
}
}
function onMenuClick(info, tab) {
const url = decodeURI(info.linkUrl || info.selectionText);
const referrer = info.frameUrl || info.pageUrl;
const filename = '';
// mock a DownloadItem
let downloadItem = { url, referrer, filename };
if (info.menuItemId == "MENU_OPEN_WEB_UI") {
launchUI();
} else if (info.menuItemId == "MENU_START_ARIA2") {
const url = chrome.runtime.getURL('aria2.html');
chrome.tabs.create({ url });
} else if (info.menuItemId == "MENU_CAPTURE_DOWNLOAD") {
chrome.storage.local.set({ integration: info.checked });
} else if (info.menuItemId == "MENU_MONITOR_ARIA2") {
chrome.storage.local.set({ monitorAria2: info.checked });
} else if (info.menuItemId == "MENU_UPDATE_BLOCK_SITE") {
updateBlockedSites(tab);
updateOptionMenu(tab);
} else if (info.menuItemId == "MENU_UPDATE_ALLOW_SITE") {
updateAllowedSites(tab);
updateOptionMenu(tab);
} else if (info.menuItemId.startsWith("MENU_RPC_LIST")) {
let id = info.menuItemId.split('-')[1];
getRpcServer('*').pattern = '';
Configs.rpcList[id].pattern = '*';
chrome.storage.local.set(Configs);
} else if (info.menuItemId.startsWith("MENU_EXPORT_TO")) {
if (Configs.askBeforeExport) {
const rpcItem = getRpcServer(downloadItem.url);
downloadItem.dir = rpcItem.location;
launchUI(downloadItem);
} else {
let id = info.menuItemId.split('-')[1];
const rpcItem = Configs.rpcList[id];
downloadItem.dir = rpcItem.location;
send2Aria(downloadItem, rpcItem);
}
} else if (info.menuItemId == "MENU_EXPORT_ALL" && !tab.url.startsWith("chrome")) {
chrome.scripting.executeScript({
target: { tabId: tab.id, allFrames: !info.frameId, frameIds: info.frameId ? [info.frameId] : undefined },
func: exportAllLinks,
args: [Configs.allowedExts, Configs.blockedExts]
});
}
}
function updateOptionMenu(tab) {
let blockedSitesSet = new Set(Configs.blockedSites);
let allowedSitesSet = new Set(Configs.allowedSites);
if (tab == null || !tab.active) {
if (!tab) {
console.warn("Could not get active tab, update option menu failed.")
};
return;
}
let url = new URL(tab.url || "about:blank");
let title = '✅ ';
if (allowedSitesSet.has(url.hostname)) {
title += chrome.i18n.getMessage("removeFromWhiteListStr");
} else {
title += chrome.i18n.getMessage("addToWhiteListStr");
}
chrome.contextMenus.update("MENU_UPDATE_ALLOW_SITE", { title });
title = '🚫 '
if (blockedSitesSet.has(url.hostname)) {
title += chrome.i18n.getMessage("removeFromBlackListStr");
} else {
title += chrome.i18n.getMessage("addToBlackListStr");
}
chrome.contextMenus.update("MENU_UPDATE_BLOCK_SITE", { title });
}
function updateAllowedSites(tab) {
if (tab == null || tab.url == null) {
console.warn("Could not get active tab url, update option menu failed.");
}
if (!tab.active || tab.url.startsWith("chrome"))
return;
var allowedSitesSet = new Set(Configs.allowedSites);
var url = new URL(tab.url);
if (allowedSitesSet.has(url.hostname)) {
allowedSitesSet.delete(url.hostname);
} else {
allowedSitesSet.add(url.hostname);
}
Configs.allowedSites = Array.from(allowedSitesSet);
chrome.storage.local.set({ allowedSites: Configs.allowedSites });
}
function updateBlockedSites(tab) {
if (tab == null || tab.url == null) {
console.warn("Could not get active tab url, update option menu failed.");
}
if (!tab.active || tab.url.startsWith("chrome"))
return;
var blockedSitesSet = new Set(Configs.blockedSites);
var url = new URL(tab.url);
if (blockedSitesSet.has(url.hostname)) {
blockedSitesSet.delete(url.hostname);
} else {
blockedSitesSet.add(url.hostname);
}
Configs.blockedSites = Array.from(blockedSitesSet);
chrome.storage.local.set({ blockedSites: Configs.blockedSites });
}
function enableMonitor() {
if (MonitorId !== -1) {
console.warn("Warn: Monitor has already started.");
return;
}
monitorAria2();
MonitorId = setInterval(monitorAria2, MonitorInterval);
Configs.monitorAria2 = true;
chrome.contextMenus.update("MENU_MONITOR_ARIA2", { checked: true });
}
function disableMonitor() {
clearInterval(MonitorId);
MonitorId = -1;
chrome.action.setBadgeText({ text: "" });
chrome.action.setTitle({ title: "" });
Configs.monitorAria2 = false;
chrome.contextMenus.update("MENU_MONITOR_ARIA2", { checked: false });
if (Configs.integration && !isDownloadListened()) {
chrome.downloads.onDeterminingFilename.addListener(captureDownload);
}
chrome.power.releaseKeepAwake();
}
async function monitorAria2() {
let connected = 0, disconnected = 0, localConnected = 0, errorMessage = '';
let active = 0, stopped = 0, waiting = 0, uploadSpeed = 0, downloadSpeed = 0;
for (const i in RemoteAria2List) {
const remoteAria2 = RemoteAria2List[i];
try {
let response = await remoteAria2.getGlobalStat();
if (response && response.error) {
throw response.error;
}
connected++;
remoteAria2.isLocalhost && localConnected++;
active += Number(response.result.numActive);
stopped += Number(response.result.numStopped);
waiting += Number(response.result.numWaiting);
uploadSpeed += Number(response.result.uploadSpeed);
downloadSpeed += Number(response.result.downloadSpeed);
if (Configs.integration && i == 0 && !isDownloadListened()) {
chrome.downloads.onDeterminingFilename.addListener(captureDownload);
}
if (Configs.allowNotification) remoteAria2.openSocket();
} catch (error) {
disconnected++;
if (i == 0) {
if (error.message?.toLowerCase().includes('unauthorized'))
errorMessage = "Secret key is incorrect"
else
errorMessage = "Aria2 server is unreachable";
if (Configs.monitorAria2 && Configs.integration && isDownloadListened()) {
chrome.downloads.onDeterminingFilename.removeListener(captureDownload);
}
}
} finally {
if (!Configs.allowNotification) remoteAria2.closeSocket();
if (!Configs.monitorAll) break;
}
}
if (active > 0) {
if (MonitorInterval == 3000) {
MonitorInterval = 1000;
disableMonitor();
enableMonitor();
}
if (Configs.keepAwake && localConnected > 0)
chrome.power.requestKeepAwake("system");
else
chrome.power.releaseKeepAwake();
} else if (active == 0) {
if (MonitorInterval == 1000) {
MonitorInterval = 3000;
disableMonitor();
enableMonitor();
}
chrome.power.releaseKeepAwake();
}
let color = 'green', text = '', title = '';
let connectedStr = chrome.i18n.getMessage("connected");
let disconnectedStr = chrome.i18n.getMessage("disconnected");
if (Configs.monitorAll) title = `${connectedStr}: ${connected} ${disconnectedStr}: ${disconnected}\n`
if (connected > 0) {
if (active > 0) {
color = (Configs.monitorAll && connected < RemoteAria2List.length) ? '#0077cc' : 'green';
text = active.toString();
} else if (waiting > 0) {
color = '#DDD';
text = waiting.toString();
}
uploadSpeed = Utils.getReadableSpeed(uploadSpeed);
downloadSpeed = Utils.getReadableSpeed(downloadSpeed);
let uploadStr = chrome.i18n.getMessage("upload");
let downloadStr = chrome.i18n.getMessage("download");
let waitStr = chrome.i18n.getMessage("wait");
let finishStr = chrome.i18n.getMessage("finish");
title += `${downloadStr}: ${active} ${waitStr}: ${waiting} ${finishStr}: ${stopped}\n${uploadStr}: ${uploadSpeed} ${downloadStr}: ${downloadSpeed}`;
} else {
if (localConnected == 0) chrome.power.releaseKeepAwake();
color = "#A83030" // red;
text = 'E';
if (Configs.monitorAll)
title += 'No Aria2 server is reachable.';
else
title += `Failed to connect with ${RemoteAria2List[0].name}. ${errorMessage}.`;
}
if (Configs.monitorAria2) {
chrome.action.setBadgeBackgroundColor({ color });
chrome.action.setBadgeText({ text });
chrome.action.setTitle({ title });
}
}
function registerAllListeners() {
chrome.action.onClicked.addListener(launchUI);
chrome.contextMenus.onClicked.addListener(onMenuClick);
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (changeInfo.status == "loading" && tab?.active) {
CurrentTabUrl = tab?.url || "about:blank";
updateOptionMenu(tab);
}
});
chrome.tabs.onActivated.addListener(function (activeInfo) {
chrome.tabs.get(activeInfo.tabId).then(function (tab) {
CurrentTabUrl = tab?.url || "about:blank";
updateOptionMenu(tab);
});
});
chrome.windows.onFocusChanged.addListener(function (windowId) {
chrome.tabs.query({ windowId: windowId, active: true }).then(function (tabs) {
if (tabs?.length > 0) {
CurrentTabUrl = tabs[0].url || "about:blank";
updateOptionMenu(tabs[0]);
}
});
});
chrome.notifications.onClicked.addListener(function (id) {
if (id.startsWith(NID_TASK_NEW) || id.startsWith(NID_TASK_STOPPED))
launchUI(id);
chrome.notifications.clear(id);
});
chrome.notifications.onButtonClicked.addListener(function (nid, buttonIndex) {
if (nid == NID_CAPTURED_OTHERS) {
switch (buttonIndex) {
case 0:
break;
case 1:
chrome.storage.local.set({ remindCaptureTip: false });
break;
}
}
chrome.notifications.clear(nid);
});
chrome.commands.onCommand.addListener(function (command) {
if (command === "toggle-capture") {
Configs.integration = !Configs.integration;
chrome.storage.local.set({ integration: Configs.integration });
} else if (command === "launch-aria2") {
const url = chrome.runtime.getURL('aria2.html');
chrome.tabs.create({ url });
}
});
chrome.runtime.onInstalled.addListener(function (details) {
if (details.reason == "install") {
const url = chrome.runtime.getURL("options.html");
chrome.storage.local.set(Configs).then(() => chrome.tabs.create({ url }));
} else if (details.reason == "update") {
const manifest = chrome.runtime.getManifest();
/* new version update notification */
let title = `Version ${manifest.version} 🚀`;
let message = `${manifest.name} has been updated.`;
let contextMessage = `Welcome more advices and supports. 🎉`;
let requireInteraction = true;
let silent = true; // Configs.keepSilent;
false && Utils.showNotification({ title, message, contextMessage, silent, requireInteraction });
}
});
/* receive request from other extensions */
chrome.runtime.onMessageExternal.addListener(
function (downloadItem) {
if (Configs.allowExternalRequest) {
download(downloadItem);
}
}
);
/* receive download request from magnet page, export all, ariaNG */
chrome.runtime.onMessage.addListener(
function (message, sender, sendResponse) {
switch (message.type) {
case "DOWNLOAD":
case "EXPORT_ALL":
download(message.data);
break;
case "DOWNLOAD_VIA_BROWSER":
let downloadItem = message.data || {};
downloadItem.type = "DOWNLOAD_VIA_BROWSER";
download(downloadItem);
break;
case "QUERY_WINDOW_STATE":
chrome.windows.get(message.data).then(
(window) => { sendResponse({ data: window }) }
);
return true;
}
}
);
/* Listen to the setting changes from options menu and page to control the extension behaviors */
chrome.storage.onChanged.addListener(function (changes, area) {
if (area !== "local") return;
let needReInit = changes.rpcList || changes.contextMenus || changes.askBeforeExport || changes.exportAll || changes.allowNotification
|| changes.integration || changes.monitorAria2 || changes.monitorAll || changes.captureMagnet || changes.webUIOpenStyle;
if (needReInit) {
init();
} else {
for (const [key, { oldValue, newValue }] of Object.entries(changes)) {
Configs[key] = newValue;
}
}
});
}
/* init popup url, context menu, download capture and aria2 monitor */
function init() {
chrome.storage.local.get().then((configs) => {
Object.assign(Configs, configs);
let url = Configs.webUIOpenStyle == "popup" ? chrome.runtime.getURL('ui/ariang/popup.html') : '';
chrome.action.setPopup({
popup: url
});
initRemoteAria2();
chrome.contextMenus.removeAll();
createOptionMenu();
createContextMenu();
updateOptionMenu({ url: CurrentTabUrl, active: true });
Configs.integration ? enableCapture() : disableCapture();
Configs.monitorAria2 ? enableMonitor() : disableMonitor();
url = Configs.captureMagnet ? "https://github.com/alexhua/Aria2-Explore/issues/98" : '';
chrome.runtime.setUninstallURL(url);
});
}
function initRemoteAria2() {
let uniqueRpcList = Utils.compactRpcList(Configs.rpcList);
for (const i in uniqueRpcList) {
RemoteAria2List = RemoteAria2List.slice(0, uniqueRpcList.length);
let rpcItem = uniqueRpcList[i];
let remote = Utils.parseUrl(rpcItem.url);
remote.name = rpcItem.name;
if (RemoteAria2List[i]) {
RemoteAria2List[i].setRemote(remote.name, remote.rpcUrl, remote.secretKey);
} else {
RemoteAria2List[i] = new Aria2(remote);
}
if (Configs.monitorAria2 && Configs.allowNotification && (i == 0 || Configs.monitorAll)) {
RemoteAria2List[i].regMessageHandler(notifyTaskStatus);
} else {
RemoteAria2List[i].unRegMessageHandler(notifyTaskStatus);
}
}
}
/**
* @param {object} data received event
* @param {string} data.method event name (required)
* @param {string} data.contextMessage context message to notify
* @param {string} data.gid corresponding task gid
* @param {Aria2} data.source the event source
*/
async function notifyTaskStatus(data) {
const events = ["aria2.onDownloadComplete", "aria2.onBtDownloadComplete",
"aria2.onDownloadError", "aria2.onExportSuccess", "aria2.onExportError"];
if (!data || !events.includes(data.method)) return;
const aria2 = data.source;
const gid = data.params?.length ? data.params[0]["gid"] : data.gid ?? '';
let message = data.method;
let contextMessage = data.contextMessage ?? '';
if (!contextMessage && gid) {
try {
const response = await aria2.tellStatus(gid, ["dir", "files", "bittorrent"]);
if (response?.result) {
const dir = Utils.formatFilepath(response.result.dir);
const bittorrent = response.result.bittorrent;
const files = response.result.files ?? [];
if (bittorrent?.info?.name) {
contextMessage = dir + bittorrent.info.name;
} else if (files.length && files[0].path) {
contextMessage = Utils.formatFilepath(files[0].path, false);
} else {
contextMessage = dir + Utils.getFileNameFromUrl(files[0].uris[0].uri);
}
if (message == 'aria2.onDownloadComplete' && bittorrent && !(contextMessage.startsWith("[METADATA]") || contextMessage.endsWith(".torrent"))) {
message = 'aria2.onSeedingComplete';
}
}
} catch {
console.warn("NotifyStatus: Can not get context message");
}
}
let title = "taskNotification", sign = '', nid = '';
switch (message) {
case "aria2.onDownloadStart":
message = "DownloadStart";
sign = ' ⬇️';
nid = NID_DEFAULT + gid;
break;
case "aria2.onDownloadComplete":
message = "DownloadComplete";
sign = ' ✅';
nid = NID_TASK_STOPPED + gid;
break;
case "aria2.onSeedingComplete":
message = "SeedingOver";
sign = ' ⬆️ ✅';
nid = NID_DEFAULT + gid;
break;
case "aria2.onBtDownloadComplete":
message = "DownloadComplete";
sign = ' ✅';
nid = NID_TASK_STOPPED + gid;
break;
case "aria2.onDownloadError":
message = "DownloadError";
sign = ' ❌';
nid = NID_TASK_STOPPED + gid;
break;
case "aria2.onExportSuccess":
title = "ExportSucceedStr"
message = "ExportSucceedDes";
sign = ' ⬇️';
nid = NID_DEFAULT + gid;
break;
case "aria2.onExportError":
title = "ExportFailedStr";
message = "ExportFailedDes";
sign = ' ❌';
nid = NID_DEFAULT + Aria2.RequestId;
break;
}
if (message) {
title = chrome.i18n.getMessage(title);
message = chrome.i18n.getMessage(message, aria2 ? aria2.name : "Aria2") + sign;
let silent = Configs.keepSilent;
Utils.showNotification({ title, message, contextMessage, silent }, nid);
}
}
/**
* Web page injector which will send all valid urls to background js
*
* @param {Array} allowedExts - The file extension list which will export
* @param {Array} blockedExts - The blocked file extension list which will not export
*/
function exportAllLinks(allowedExts, blockedExts) {
if (!Array.isArray(allowedExts)) allowedExts = [];
if (!Array.isArray(blockedExts)) blockedExts = [];