forked from proginosko/LeechBlockNG
-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
1256 lines (1046 loc) · 31.6 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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const TICK_TIME = 1000; // update every second
function log(message) { console.log("[LBNG] " + message); }
function warn(message) { console.warn("[LBNG] " + message); }
var gStorage = browser.storage.local;
var gIsAndroid = false;
var gGotOptions = false;
var gOptions = {};
var gTabs = [];
var gSetCounted = [];
var gSavedTimeData = [];
var gRegExps = [];
var gFocusWindowId = 0;
var gOverrideIcon = false;
var gSaveSecsCount = 0;
// Create (precompile) regular expressions
//
function createRegExps() {
// Create new RegExp objects
for (let set = 1; set <= NUM_SETS; set++) {
gRegExps[set] = {};
let blockRE = gOptions[`regexpBlock${set}`] || gOptions[`blockRE${set}`];
gRegExps[set].block = blockRE ? new RegExp(blockRE, "i") : null;
let allowRE = gOptions[`regexpAllow${set}`] || gOptions[`allowRE${set}`];
gRegExps[set].allow = allowRE ? new RegExp(allowRE, "i") : null;
let keywordRE = gOptions[`keywordRE${set}`];
gRegExps[set].keyword = keywordRE ? new RegExp(keywordRE, "i") : null;
}
}
// Test URL against block/allow regular expressions
//
function testURL(pageURL, blockRE, allowRE) {
return (blockRE && blockRE.test(pageURL)
&& !(allowRE && allowRE.test(pageURL)));
}
// Refresh menus
//
function refreshMenus() {
if (!browser.menus) {
return; // no support for menus!
}
browser.menus.removeAll();
let context = gOptions["contextMenu"] ? "all" : "browser_action";
let contexts = gOptions["toolsMenu"] ? [context, "tools_menu"] : [context];
// Options
browser.menus.create({
id: "options",
title: "Options",
contexts: contexts
});
// Lockdown
browser.menus.create({
id: "lockdown",
title: "Lockdown",
contexts: contexts
});
// Override
browser.menus.create({
id: "override",
title: "Override",
contexts: contexts
});
// Statistics
browser.menus.create({
id: "stats",
title: "Statistics",
contexts: contexts
});
browser.menus.create({
type: "separator",
contexts: [context] // never in tools menu
});
// Add Site
browser.menus.create({
id: "addSite",
title: "Add Site",
contexts: [context] // never in tools menu
});
// Add Site submenu
for (let set = 1; set <= NUM_SETS; set++) {
let title = `Add Site to Block Set ${set}`;
let setName = gOptions[`setName${set}`];
if (setName) {
title += ` (${setName})`;
}
browser.menus.create({
id: `addSite-${set}`,
parentId: "addSite",
title: title,
contexts: contexts
});
}
}
// Retrieve options from storage
//
function retrieveOptions(update) {
//log("retrieveOptions: " + update);
browser.storage.local.get("sync").then(onGotSync, onError);
function onGotSync(options) {
gStorage = options["sync"]
? browser.storage.sync
: browser.storage.local;
gStorage.get().then(onGot, onError);
}
function onGot(options) {
// Copy retrieved options (exclude timedata if update)
for (let option in options) {
if (!update || !/^timedata/.test(option)) {
gOptions[option] = options[option];
}
}
gGotOptions = true;
cleanOptions(gOptions);
cleanTimeData(gOptions);
createRegExps();
refreshMenus();
loadSiteLists();
updateIcon();
// Keep track of saved time data to avoid unnecessary writes
for (let set = 1; set <= NUM_SETS; set++) {
gSavedTimeData[set] = gOptions[`timedata${set}`].toString();
}
}
function onError(error) {
gGotOptions = false;
warn("Cannot get options: " + error);
}
}
// Load lists of sites if URLs specified
//
function loadSiteLists() {
//log("loadSiteLists");
let time = Date.now();
for (let set = 1; set <= NUM_SETS; set++) {
// Get sites for block set from HTTP source (if specified)
let sitesURL = gOptions[`sitesURL${set}`];
if (sitesURL) {
sitesURL = sitesURL.replace(/\$S/, set).replace(/\$T/, time);
try {
let req = new XMLHttpRequest();
req.set = set;
req.open("GET", sitesURL, true);
req.overrideMimeType("text/plain");
req.onload = onLoad;
req.send();
} catch (error) {
warn("Cannot load sites from URL: " + sitesURL);
}
}
}
function onLoad(event) {
let req = event.target;
if (req.readyState == XMLHttpRequest.DONE && req.status == 200) {
let set = req.set;
let sites = req.responseText;
sites = sites.replace(/\s+/g, " ").replace(/(^ +)|( +$)|(\w+:\/+)/g, "");
sites = sites.split(" ").sort().join(" "); // sort alphabetically
// Get regular expressions to match sites
let regexps = getRegExpSites(sites, gOptions["matchSubdomains"]);
// Update options
gOptions[`sites${set}`] = sites;
gOptions[`blockRE${set}`] = regexps.block;
gOptions[`allowRE${set}`] = regexps.allow;
gOptions[`keywordRE${set}`] = regexps.keyword;
createRegExps();
// Save updated options to local storage
let options = {};
options[`sites${set}`] = sites;
options[`blockRE${set}`] = regexps.block;
options[`allowRE${set}`] = regexps.allow;
options[`keywordRE${set}`] = regexps.keyword;
gStorage.set(options).catch(
function (error) { warn("Cannot set options: " + error); }
);
}
}
}
// Save time data to storage
//
function saveTimeData() {
//log("saveTimeData");
if (!gGotOptions) {
return;
}
let options = {};
let touched = false;
for (let set = 1; set <= NUM_SETS; set++) {
let timedata = gOptions[`timedata${set}`];
if (gSavedTimeData[set] != timedata.toString()) {
options[`timedata${set}`] = timedata;
gSavedTimeData[set] = timedata.toString();
touched = true;
}
}
if (touched) {
gStorage.set(options).catch(
function (error) { warn("Cannot save time data: " + error); }
);
}
}
// Restart time data
//
function restartTimeData(set) {
//log("restartTimeData: " + set);
if (!gGotOptions) {
return;
}
// Get current time in seconds
let now = Math.floor(Date.now() / 1000);
if (!set) {
for (set = 1; set <= NUM_SETS; set++) {
gOptions[`timedata${set}`][0] = now;
gOptions[`timedata${set}`][1] = 0;
}
} else {
gOptions[`timedata${set}`][0] = now;
gOptions[`timedata${set}`][1] = 0;
}
saveTimeData();
}
// Update ID of focused window
//
function updateFocusedWindowId() {
if (!browser.windows) {
return; // no support for windows!
}
browser.windows.getCurrent().then(
function (win) {
gFocusWindowId = win.focused ? win.id : browser.windows.WINDOW_ID_NONE;
},
function (error) {
warn("Cannot get current window: " + error);
}
);
}
// Process tabs: update time spent and check for blocks
//
function processTabs(active) {
//log("processTabs: " + active);
gSetCounted = []; // reset
if (active) {
// Process only active tabs
browser.tabs.query({ active: true }).then(onGot, onError);
} else {
// Process all tabs
browser.tabs.query({}).then(onGot, onError);
}
function onGot(tabs) {
for (let tab of tabs) {
let focus = tab.active && (!gFocusWindowId || tab.windowId == gFocusWindowId);
// Force update of time spent on this page
clockPageTime(tab.id, false, false);
clockPageTime(tab.id, true, focus);
let blocked = checkTab(tab.id, tab.url, true);
if (!blocked) {
updateTimer(tab.id);
}
}
}
function onError(error) {
warn("Cannot get tabs: " + error);
}
}
// Check the URL of a tab and applies block if necessary (returns true if blocked)
//
function checkTab(id, url, isRepeat) {
//log("checkTab: " + id + " " + url + " " + isRepeat);
function isSameHost(host1, host2) {
return (host1 == host2)
|| (host1 == "www." + host2)
|| (host2 == "www." + host1);
}
// Quick exit for about:blank
if (url == "about:blank") {
return false; // not blocked
}
if (!gTabs[id]) {
// Create object to track this tab
gTabs[id] = { allowedHost: null, allowedPath: null };
}
// Quick exit for non-blockable URLs
if (!/^(http|file|about)/i.test(url)) {
gTabs[id].blockable = false;
return false; // not blocked
}
gTabs[id].blockable = true;
gTabs[id].url = url;
// Get parsed URL for this page
let parsedURL = getParsedURL(url);
// Check for allowed host/path
let ah = isSameHost(gTabs[id].allowedHost, parsedURL.host);
let ap = !gTabs[id].allowedPath || (gTabs[id].allowedPath == parsedURL.path);
if (ah && ap) {
return false; // not blocked
} else {
gTabs[id].allowedHost = null;
gTabs[id].allowedPath = null;
}
// Get current time/date
let timedate = new Date();
// Get current time in seconds
let now = Math.floor(Date.now() / 1000);
// Get override end time
let overrideEndTime = gOptions["oret"];
gTabs[id].secsLeft = Infinity;
for (let set = 1; set <= NUM_SETS; set++) {
// Get URL of page (possibly with hash part)
let pageURL = parsedURL.page;
let pageURLWithHash = parsedURL.page;
if (parsedURL.hash != null) {
pageURLWithHash += "#" + parsedURL.hash;
if (/^!/.test(parsedURL.hash) || !gOptions[`ignoreHash${set}`]) {
pageURL = pageURLWithHash;
}
}
// Get regular expressions for matching sites to block/allow
let blockRE = gRegExps[set].block;
if (!blockRE) continue; // no block for this set
let allowRE = gRegExps[set].allow;
let keywordRE = gRegExps[set].keyword;
// Get options for preventing access to about:addons and about:support
let prevAddons = gOptions[`prevAddons${set}`];
let prevSupport = gOptions[`prevSupport${set}`];
// Test URL against block/allow regular expressions
if (testURL(pageURL, blockRE, allowRE)
|| (prevAddons && /^about:addons/i.test(pageURL))
|| (prevSupport && /^about:support/i.test(pageURL))) {
// Get options for this set
let timedata = gOptions[`timedata${set}`];
let times = gOptions[`times${set}`];
let minPeriods = getMinPeriods(times);
let limitMins = gOptions[`limitMins${set}`];
let limitPeriod = gOptions[`limitPeriod${set}`];
let limitOffset = gOptions[`limitOffset${set}`];
let periodStart = getTimePeriodStart(now, limitPeriod, limitOffset);
let conjMode = gOptions[`conjMode${set}`];
let days = gOptions[`days${set}`];
let blockURL = gOptions[`blockURL${set}`];
let activeBlock = gOptions[`activeBlock${set}`];
let allowOverride = gOptions[`allowOverride${set}`];
let showTimer = gOptions[`showTimer${set}`];
// Check day
let onSelectedDay = days[timedate.getDay()];
// Check time periods
let secsLeftBeforePeriod = Infinity;
if (onSelectedDay && times) {
// Get number of minutes elapsed since midnight
let mins = timedate.getHours() * 60 + timedate.getMinutes();
// Check each time period in turn
for (let mp of minPeriods) {
if (mins >= mp.start && mins < mp.end) {
secsLeftBeforePeriod = 0;
} else if (mins < mp.start) {
// Compute exact seconds before this time period starts
let secs = (mp.start - mins) * 60 - timedate.getSeconds();
if (secs < secsLeftBeforePeriod) {
secsLeftBeforePeriod = secs;
}
}
}
}
// Check time limit
let secsLeftBeforeLimit = Infinity;
if (onSelectedDay && limitMins && limitPeriod) {
// Compute exact seconds before this time limit expires
secsLeftBeforeLimit = limitMins * 60;
if (timedata[2] == periodStart) {
let secs = secsLeftBeforeLimit - timedata[3];
secsLeftBeforeLimit = Math.max(0, secs);
}
}
let withinTimePeriods = (secsLeftBeforePeriod == 0);
let afterTimeLimit = (secsLeftBeforeLimit == 0);
// Check lockdown condition
let lockdown = (timedata[4] > now);
// Check override condition
let override = (overrideEndTime > now) && allowOverride;
// Determine whether this page should now be blocked
let doBlock = lockdown
|| (!conjMode && (withinTimePeriods || afterTimeLimit))
|| (conjMode && (withinTimePeriods && afterTimeLimit));
// Redirect page if all relevant block conditions are fulfilled
if (!override && doBlock && (!isRepeat || activeBlock)) {
// Get final URL for block page
blockURL = blockURL.replace(/\$S/g, set).replace(/\$U/g, pageURLWithHash);
if (keywordRE) {
// Check for keyword(s) before blocking
let message = {
type: "keyword",
keywordRE: keywordRE
};
browser.tabs.sendMessage(id, message).then(
function (keyword) {
if (keyword) {
// Redirect page
browser.tabs.update(id, { url: blockURL });
}
},
function (error) {}
);
} else {
// Redirect page
browser.tabs.update(id, { url: blockURL });
return true; // blocked
}
}
// Update seconds left before block
let secsLeft = conjMode
? (secsLeftBeforePeriod + secsLeftBeforeLimit)
: Math.min(secsLeftBeforePeriod, secsLeftBeforeLimit);
if (override) {
secsLeft = Math.max(secsLeft, overrideEndTime - now);
}
if (showTimer && secsLeft < gTabs[id].secsLeft) {
gTabs[id].secsLeft = secsLeft;
gTabs[id].secsLeftSet = set;
}
}
}
checkWarning(id);
return false; // not blocked
}
// Check for warning message (and display message if needed)
//
function checkWarning(id) {
let set = gTabs[id].secsLeftSet;
let warnSecs = gOptions["warnSecs"];
let canWarn = !gOptions["warnImmediate"] || gOptions[`activeBlock${set}`]
if (warnSecs && canWarn) {
let secsLeft = Math.round(gTabs[id].secsLeft);
if (secsLeft > warnSecs) {
gTabs[id].warned = false;
} else if (secsLeft > 0 && !gTabs[id].warned) {
gTabs[id].warned = true;
// Send message to tab
let text = `Sites in Block Set ${set}`;
let setName = gOptions[`setName${set}`];
if (setName) {
text += ` (${setName})`;
}
text += ` will be blocked in ${secsLeft} seconds.`;
let message = {
type: "alert",
text: text
};
browser.tabs.sendMessage(id, message).catch(
function (error) { gTabs[id].warned = false; }
);
}
}
}
// Clock time spent on page
//
function clockPageTime(id, open, focus) {
if (!gTabs[id] || !gTabs[id].blockable) {
return;
}
// Get current time in milliseconds
let time = Date.now();
// Clock time during which page has been open
let secsOpen = 0;
if (open) {
if (gTabs[id].openTime == undefined) {
// Set open time for this page
gTabs[id].openTime = time;
}
} else {
if (gTabs[id].openTime != undefined) {
if (/^(http|file)/i.test(gTabs[id].url)) {
// Calculate seconds spent on this page (while open)
secsOpen = ((time - gTabs[id].openTime) / 1000);
}
gTabs[id].openTime = undefined;
}
}
// Clock time during which page has been focused
let secsFocus = 0;
if (focus) {
if (gTabs[id].focusTime == undefined) {
// Set focus time for this page
gTabs[id].focusTime = time;
}
} else {
if (gTabs[id].focusTime != undefined) {
if (/^(http|file)/i.test(gTabs[id].url)) {
// Calculate seconds spent on this page (while focused)
secsFocus = ((time - gTabs[id].focusTime) / 1000);
}
gTabs[id].focusTime = undefined;
}
}
// Update time data if necessary
if (secsOpen > 0 || secsFocus > 0) {
updateTimeData(gTabs[id].url, secsOpen, secsFocus);
}
}
// Update time data for specified page
//
function updateTimeData(url, secsOpen, secsFocus) {
//log("updateTimeData: " + url + " " + secsOpen + " " + secsFocus);
// Get parsed URL for this page
let parsedURL = getParsedURL(url);
let pageURL = parsedURL.page;
// Get current time/date
let timedate = new Date();
// Get current time in seconds
let now = Math.floor(Date.now() / 1000);
for (let set = 1; set <= NUM_SETS; set++) {
// Get regular expressions for matching sites to block/allow
let blockRE = gRegExps[set].block;
if (!blockRE) continue; // no block for this set
let allowRE = gRegExps[set].allow;
// Test URL against block/allow regular expressions
if (testURL(pageURL, blockRE, allowRE)) {
// Get options for this set
let timedata = gOptions[`timedata${set}`];
let countFocus = gOptions[`countFocus${set}`];
let times = gOptions[`times${set}`];
let minPeriods = getMinPeriods(times);
let limitPeriod = gOptions[`limitPeriod${set}`];
let limitOffset = gOptions[`limitOffset${set}`];
let periodStart = getTimePeriodStart(now, limitPeriod, limitOffset);
let conjMode = gOptions[`conjMode${set}`];
let days = gOptions[`days${set}`];
// Avoid overcounting time for non-focused tabs
if (!countFocus && gSetCounted[set]) {
continue;
} else {
gSetCounted[set] = true;
}
// Reset time data if currently invalid
if (!Array.isArray(timedata) || timedata.length != 5) {
timedata = [now, 0, 0, 0, 0];
}
// Get number of seconds spent on page (focused or open)
let secsSpent = countFocus ? secsFocus : secsOpen;
// Update data for total time spent
timedata[1] = +timedata[1] + secsSpent;
// Determine whether we should count time spent on page in
// specified time period (we should only count time on selected
// days -- and in conjunction mode, only within time periods)
let countTimeSpentInPeriod = days[timedate.getDay()];
if (countTimeSpentInPeriod && conjMode) {
countTimeSpentInPeriod = false;
// Get number of minutes elapsed since midnight
let mins = timedate.getHours() * 60 + timedate.getMinutes();
// Check each time period in turn
for (let mp of minPeriods) {
if (mins >= mp.start && mins < mp.end) {
countTimeSpentInPeriod = true;
}
}
}
// Update data for time spent in specified time period
if (countTimeSpentInPeriod && periodStart > 0 && timedata[2] >= 0) {
if (timedata[2] != periodStart) {
// We've entered a new time period, so start new count
timedata[2] = periodStart;
timedata[3] = secsSpent;
} else {
// We haven't entered a new time period, so keep counting
timedata[3] = +timedata[3] + secsSpent;
}
}
// Update time data for this set
gOptions[`timedata${set}`] = timedata;
}
}
}
// Update timer
//
function updateTimer(id) {
if (!gTabs[id] || !gTabs[id].blockable || /^about/i.test(gTabs[id].url)) {
return;
}
// Send message to tab
let secsLeft = gTabs[id].secsLeft;
let message = {
type: "timer",
size: gOptions["timerSize"],
location: gOptions["timerLocation"]
};
if (!gOptions["timerVisible"] || secsLeft == undefined || secsLeft == Infinity) {
message.text = null; // hide timer
} else {
message.text = formatTime(secsLeft); // show timer with time left
}
browser.tabs.sendMessage(id, message).catch(function (error) {});
// Set tooltip
if (!gIsAndroid) {
if (secsLeft == undefined || secsLeft == Infinity) {
browser.browserAction.setTitle({ title: null, tabId: id });
} else {
let title = "LeechBlock [" + formatTime(secsLeft) + "]"
browser.browserAction.setTitle({ title: title, tabId: id });
}
}
// Set badge timer (if option selected)
if (!gIsAndroid && gOptions["timerBadge"] && secsLeft < 600) {
let m = Math.floor(secsLeft / 60);
let s = Math.floor(secsLeft) % 60;
let text = m + ":" + ((s < 10) ? "0" + s : s);
browser.browserAction.setBadgeBackgroundColor({ color: "#666" });
browser.browserAction.setBadgeText({ text: text, tabId: id });
} else {
browser.browserAction.setBadgeText({ text: "", tabId: id });
}
}
// Update button icon
//
function updateIcon() {
if (gIsAndroid) {
return; // icon not supported yet
}
// Get current time in seconds
let now = Math.floor(Date.now() / 1000);
// Get override end time
let overrideEndTime = gOptions["oret"];
// Change icon only if override status has changed
if (!gOverrideIcon && overrideEndTime > now) {
browser.browserAction.setIcon({ path: OVERRIDE_ICON });
gOverrideIcon = true;
} else if (gOverrideIcon && overrideEndTime <= now) {
browser.browserAction.setIcon({ path: DEFAULT_ICON });
gOverrideIcon = false;
}
}
// Create info for blocking/delaying page
//
function createBlockInfo(url) {
// Get theme
let theme = gOptions["theme"];
// Get parsed URL
let parsedURL = getParsedURL(url);
let pageURL = parsedURL.page;
if (parsedURL.args == null || parsedURL.args.length < 2) {
warn("Cannot create block info: not enough arguments in URL.");
return { theme: theme };
}
// Get block set and URL (including hash part) of blocked page
let blockedSet = parsedURL.args.shift();
let blockedSetName = gOptions[`setName${blockedSet}`];
let blockedURL = parsedURL.query.substring(3); // retains original separators (& or ;)
if (parsedURL.hash != null) {
blockedURL += "#" + parsedURL.hash;
}
// Get unblock time for block set
let unblockTime = getUnblockTime(blockedSet);
if (unblockTime != null) {
// Convert to string
if (unblockTime.getDate() == new Date().getDate()) {
// Same day: show time only
unblockTime = unblockTime.toLocaleTimeString();
} else {
// Different day: show date and time
unblockTime = unblockTime.toLocaleString();
}
}
// Get delaying time for block set
let delaySecs = gOptions[`delaySecs${blockedSet}`];
// Get reloading time (if specified)
let reloadSecs = gOptions[`reloadSecs${blockedSet}`];
return {
theme: theme,
blockedSet: blockedSet,
blockedSetName: blockedSetName,
blockedURL: blockedURL,
unblockTime: unblockTime,
delaySecs: delaySecs,
reloadSecs: reloadSecs
};
}
// Return time when blocked sites will be unblocked (as Date object)
//
function getUnblockTime(set) {
// Check for invalid set number
if (set < 1 || set > NUM_SETS) {
return null;
}
// Get current time/date
let timedate = new Date();
// Get current time in seconds
let now = Math.floor(Date.now() / 1000);
// Get options for this set
let timedata = gOptions[`timedata${set}`];
let times = gOptions[`times${set}`];
let minPeriods = getMinPeriods(times);
let limitMins = gOptions[`limitMins${set}`];
let limitPeriod = gOptions[`limitPeriod${set}`];
let limitOffset = gOptions[`limitOffset${set}`];
let periodStart = getTimePeriodStart(now, limitPeriod, limitOffset);
let conjMode = gOptions[`conjMode${set}`];
let days = gOptions[`days${set}`];
// Check for valid time data
if (!Array.isArray(timedata) || timedata.length != 5) {
return null;
}
// Check for 24/7 block
if (times == ALL_DAY_TIMES && allTrue(days) && !conjMode) {
return null;
}
// Check for lockdown
if (now < timedata[4]) {
// Return end time for lockdown
return new Date(timedata[4] * 1000);
}
// Get number of minutes elapsed since midnight
let mins = timedate.getHours() * 60 + timedate.getMinutes();
// Create list of time periods for today and following seven days
let day = timedate.getDay();
let allMinPeriods = [];
for (let i = 0; i <= 7; i++) {
if (days[(day + i) % 7]) {
let offset = (i * 1440);
for (let mp of minPeriods) {
// Create new time period with offset
let mp1 = {
start: (mp.start + offset),
end: (mp.end + offset)
};
if (allMinPeriods.length == 0) {
// Add new time period
allMinPeriods.push(mp1);
} else {
let mp0 = allMinPeriods[allMinPeriods.length - 1];
if (mp1.start <= mp0.end) {
// Merge time period into previous one
mp0.end = mp1.end;
} else {
// Add new time period
allMinPeriods.push(mp1);
}
}
}
}
}
let timePeriods = (times != "");
let timeLimit = (limitMins && limitPeriod);
if (timePeriods && !timeLimit) {
// Case 1: within time periods (no time limit)
// Find relevant time period
for (let mp of allMinPeriods) {
if (mins >= mp.start && mins < mp.end) {
// Return end time for time period
return new Date(
timedate.getFullYear(),
timedate.getMonth(),
timedate.getDate(),
0, mp.end);
}
}
} else if (!timePeriods && timeLimit) {
// Case 2: after time limit (no time periods)
// Return end time for current time limit period
return new Date(timedata[2] * 1000 + limitPeriod * 1000);
} else if (timePeriods && timeLimit) {
if (conjMode) {
// Case 3: within time periods AND after time limit
// Find relevant time period
for (let mp of allMinPeriods) {
if (mins >= mp.start && mins < mp.end) {
// Return the earlier of the two end times
let td1 = new Date(
timedate.getFullYear(),
timedate.getMonth(),
timedate.getDate(),
0, mp.end);
let td2 = new Date(timedata[2] * 1000 + limitPeriod * 1000);
return (td1 < td2) ? td1 : td2;
}
}
} else {
// Case 4: within time periods OR after time limit
// Determine whether time limit was exceeded
let afterTimeLimit = (timedata[2] == periodStart)
&& (timedata[3] >= (limitMins * 60));
if (afterTimeLimit) {
// Check against end time for current time limit period instead
let td = new Date(timedata[2] * 1000 + limitPeriod * 1000);
mins = td.getHours() * 60 + td.getMinutes();
}
// Find relevant time period
for (let mp of allMinPeriods) {
if (mins >= mp.start && mins < mp.end) {
// Return end time for time period
return new Date(
timedate.getFullYear(),
timedate.getMonth(),
timedate.getDate(),
0, mp.end);
}
}
}
}
return null;
}
// Apply lockdown for specified set
//
function applyLockdown(set, endTime) {
//log("applyLockdown: " + set + " " + endTime);
if (!gGotOptions) {
return;
}
// Apply lockdown only if it doesn't reduce any current lockdown
if (endTime > gOptions[`timedata${set}`][4]) {
gOptions[`timedata${set}`][4] = endTime;
}
saveTimeData();
}
// Cancel lockdown for specified set
//
function cancelLockdown(set) {
//log("cancelLockdown: " + set);
if (!gGotOptions) {
return;
}
gOptions[`timedata${set}`][4] = 0;
saveTimeData();
}
// Apply override
//
function applyOverride() {
//log("applyOverride");
if (!gGotOptions) {
return;
}
let overrideMins = gOptions["orm"];
if (overrideMins) {
// Calculate end time
let overrideEndTime = Math.floor(Date.now() / 1000) + (overrideMins * 60);
// Update option
gOptions["oret"] = overrideEndTime;
// Save updated option to local storage
let options = {};
options["oret"] = overrideEndTime;
gStorage.set(options).catch(
function (error) { warn("Cannot set options: " + error); }
);
updateIcon();
}
}
// Open extension page (either create new tab or activate existing tab)