forked from proginosko/LeechBlockNG
-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
990 lines (824 loc) · 25.4 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
/* 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
var gGotOptions = false;
var gOptions = {};
var gTabs = [];
var gSetCounted = [];
var gFocusWindowId = 0;
function log(message) { console.log("[LBNG] " + message); }
function warn(message) { console.warn("[LBNG] " + message); }
// Refresh menus
//
function refreshMenus() {
if (!browser.menus) {
return; // no support for menus!
}
browser.menus.removeAll();
let context = gOptions["contextMenu"] ? "all" : "browser_action";
// Options
browser.menus.create({
id: "options",
title: "Options",
contexts: [context, "tools_menu"]
});
// Lockdown
browser.menus.create({
id: "lockdown",
title: "Lockdown",
contexts: [context, "tools_menu"]
});
browser.menus.create({
type: "separator",
contexts: [context]
});
// Add Site
browser.menus.create({
id: "addSite",
title: "Add Site",
contexts: [context]
});
// 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: [context, "tools_menu"]
});
}
}
// Retrieve options from local storage
//
function retrieveOptions() {
//log("retrieveOptions");
browser.storage.local.get().then(onGot, onError);
function onGot(options) {
gGotOptions = true;
gOptions = Object.assign({}, options); // clone
cleanOptions(gOptions);
cleanTimeData(gOptions);
gSetCounted = Array(NUM_SETS).fill(false);
refreshMenus();
loadSiteLists();
}
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);
// Update options
gOptions[`sites${set}`] = sites;
gOptions[`blockRE${set}`] = regexps.block;
gOptions[`allowRE${set}`] = regexps.allow;
gOptions[`keywordRE${set}`] = regexps.keyword;
// 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;
browser.storage.local.set(options).catch(
function (error) { warn("Cannot set options: " + error); }
);
}
}
}
// Save time data to local storage
//
function saveTimeData() {
//log("saveTimeData");
if (!gGotOptions) {
return;
}
let options = {};
for (let set = 1; set <= NUM_SETS; set++) {
options[`timedata${set}`] = gOptions[`timedata${set}`];
}
browser.storage.local.set(options).catch(
function (error) { warn("Cannot set options: " + error); }
);
}
// Update ID of focused window
//
function updateFocusedWindowId() {
if (!browser.windows) {
return; // no support for windows!
}
browser.windows.getLastFocused().then(
function (win) { gFocusWindowId = win.id; },
function (error) { warn("Cannot get focused window: " + error); }
);
}
// Process tabs: update time spent and check for blocks
//
function processTabs() {
//log("processTabs");
gSetCounted.fill(false);
browser.tabs.query({}).then(onGot, onError);
function onGot(tabs) {
// Process all 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);
}
}
// Save time data to local storage
saveTimeData();
}
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);
// 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 = (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 URL without hash part (unless it's a hash-bang part)
let pageURL = parsedURL.page;
if (parsedURL.hash != null && /^!/.test(parsedURL.hash)) {
pageURL += "#" + parsedURL.hash;
}
// Get current time/date
let timedate = new Date();
// Get current time in seconds
let now = Math.floor(Date.now() / 1000);
gTabs[id].secsLeft = Infinity;
for (let set = 1; set <= NUM_SETS; set++) {
// Get regular expressions for matching sites to block/allow
let blockRE = gOptions[`blockRE${set}`];
if (blockRE == "") continue; // no block for this set
let allowRE = gOptions[`allowRE${set}`];
let keywordRE = gOptions[`keywordRE${set}`];
// 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 periodStart = getTimePeriodStart(now, limitPeriod);
let conjMode = gOptions[`conjMode${set}`];
let days = gOptions[`days${set}`];
let blockURL = gOptions[`blockURL${set}`];
let activeBlock = gOptions[`activeBlock${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);
// 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 (doBlock && (!isRepeat || activeBlock)) {
// Get final URL for block page
blockURL = blockURL.replace(/\$S/g, set).replace(/\$U/g, pageURL);
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 (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 warnSecs = gOptions["warnSecs"];
if (warnSecs) {
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 set = gTabs[id].secsLeftSet;
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 = gOptions[`blockRE${set}`];
if (blockRE == "") continue; // no block for this set
let allowRE = gOptions[`allowRE${set}`];
// 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 periodStart = getTimePeriodStart(now, limitPeriod);
let conjMode = gOptions[`conjMode${set}`];
let days = gOptions[`days${set}`];
// Avoid overcounting time for non-focused tabs
if (!countFocus && gSetCounted[set - 1]) {
continue;
} else {
gSetCounted[set - 1] = 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) {});
}
// Create info for blocking/delaying page
//
function createBlockInfo(url) {
// 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 {};
}
// 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}`];
return {
blockedSet: blockedSet,
blockedSetName: blockedSetName,
blockedURL: blockedURL,
unblockTime: unblockTime,
delaySecs: delaySecs
};
}
// 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 periodStart = getTimePeriodStart(now, limitPeriod);
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);
let timedata = gOptions[`timedata${set}`];
// Apply lockdown only if it doesn't reduce any current lockdown
if (endTime > timedata[4]) {
timedata[4] = endTime;
}
gOptions[`timedata${set}`] = timedata;
}
// Cancel lockdown for specified set
//
function cancelLockdown(set) {
//log("cancelLockdown: " + set);
gOptions[`timedata${set}`][4] = 0;
}
// Open extension page (either create new tab or activate existing tab)
//
function openExtensionPage(url) {
let fullURL = browser.extension.getURL(url);
browser.tabs.query({ url: fullURL }).then(onGot, onError);
function onGot(tabs) {
if (tabs.length > 0) {
browser.tabs.update(tabs[0].id, { active: true });
} else {
browser.tabs.create({ url: fullURL });
}
}
function onError(error) {
browser.tabs.create({ url: fullURL });
}
}
// Open page blocked by delaying page
//
function openDelayedPage(id, url, set) {
//log("openDelayedPage: " + id + " " + url);
// Get parsed URL for this page
let parsedURL = getParsedURL(url);
// Set parameters for allowing host
gTabs[id].allowedHost = parsedURL.host;
if (!gOptions[`delayFirst${set}`]) {
gTabs[id].allowedPath = parsedURL.path;
}
// Redirect page
browser.tabs.update(id, { url: url });
}
// Add site to block set
//
function addSiteToSet(url, set) {
//log("addSiteToSet: " + url + " " + set);
if (!/^http/i.test(url) || set < 1 || set > NUM_SETS) {
return;
}
if (!gGotOptions) {
return;
}
// Get parsed URL for this page
let parsedURL = getParsedURL(url);
// Get sites for this set
let sites = gOptions[`sites${set}`];
// Add site if not already included
let site = parsedURL.host.replace(/^www\./, "");
let patterns = sites.split(/\s+/);
if (patterns.indexOf(site) < 0) {
// Get sorted list of sites including new one
patterns.push(site);
sites = patterns.sort().join(" ").replace(/(^ +)|( +$)/g, "");
// Get regular expressions to match sites
let regexps = getRegExpSites(sites);
// Update options
gOptions[`sites${set}`] = sites;
gOptions[`blockRE${set}`] = regexps.block;
gOptions[`allowRE${set}`] = regexps.allow;
gOptions[`keywordRE${set}`] = regexps.keyword;
// 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;
browser.storage.local.set(options).catch(
function (error) { warn("Cannot set options: " + error); }
);
}
}
/*** EVENT HANDLERS BEGIN HERE ***/
function handleMenuClick(info, tab) {
let id = info.menuItemId;
if (id == "options") {
browser.runtime.openOptionsPage();
} else if (id == "lockdown") {
openExtensionPage("lockdown.html");
} else if (id.startsWith("addSite-")) {
addSiteToSet(info.pageUrl, id.substr(8));
}
}
function handleMessage(message, sender, sendResponse) {
if (!sender) {
warn("No sender!");
return;
}
//log("handleMessage: " + sender.tab.id + " " + message.type);
if (message.type == "close") {
// Close tab requested
browser.tabs.remove(sender.tab.id);
} else if (message.type == "options") {
// Options updated
retrieveOptions();
} else if (message.type == "lockdown") {
if (!message.endTime) {
// Lockdown canceled
cancelLockdown(message.set);
} else {
// Lockdown requested
applyLockdown(message.set, message.endTime);
}
} else if (message.type == "blocked") {
// Block info requested by blocking/delaying page
let info = createBlockInfo(sender.url);
sendResponse(info);
} else if (message.type == "delayed") {
// Redirect requested by delaying page
openDelayedPage(sender.tab.id, message.blockedURL, message.blockedSet);
}
}
function handleTabCreated(tab) {
//log("handleTabCreated: " + tab.id);
}
function handleTabUpdated(tabId, changeInfo, tab) {
//log("handleTabUpdated: " + tabId);
let focus = tab.active && (!gFocusWindowId || tab.windowId == gFocusWindowId);
if (changeInfo.status && changeInfo.status == "complete") {
clockPageTime(tab.id, true, focus);
let blocked = checkTab(tab.id, tab.url, false);
if (!blocked) {
updateTimer(tab.id);
}
}
}
function handleTabActivated(activeInfo) {
//log("handleTabActivated: " + activeInfo.tabId);
let focus = (!gFocusWindowId || activeInfo.windowId == gFocusWindowId);
clockPageTime(activeInfo.tabId, true, focus);
updateTimer(activeInfo.tabId);
}
function handleTabRemoved(tabId, removeInfo) {
//log("handleTabRemoved: " + tabId);
clockPageTime(tabId, false, false);
}
function handleBeforeNavigate(navDetails) {
//log("handleBeforeNavigate: " + navDetails.tabId);
clockPageTime(navDetails.tabId, false, false);
if (navDetails.frameId == 0) {
checkTab(navDetails.tabId, navDetails.url, false);
}
}
function handleWinFocused(winId) {
//log("handleWinFocused: " + winId);
gFocusWindowId = winId;
}
function onInterval() {
//log("onInterval");
if (!gGotOptions) {
retrieveOptions();
} else {
processTabs();
}
}
/*** STARTUP CODE BEGINS HERE ***/
if (browser.menus) {
browser.menus.onClicked.addListener(handleMenuClick);
}
browser.runtime.onMessage.addListener(handleMessage);
//browser.tabs.onCreated.addListener(handleTabCreated);
browser.tabs.onUpdated.addListener(handleTabUpdated);
browser.tabs.onActivated.addListener(handleTabActivated);
browser.tabs.onRemoved.addListener(handleTabRemoved);
browser.webNavigation.onBeforeNavigate.addListener(handleBeforeNavigate);
if (browser.windows) {
browser.windows.onFocusChanged.addListener(handleWinFocused);
}
window.setInterval(onInterval, TICK_TIME);