-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbackground.js
103 lines (90 loc) · 3.04 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
let timeoutId = null;
chrome.tabs.onUpdated.addListener((tabId, info) => handleTab(tabId, info.url));
chrome.tabs.onActivated.addListener((info) => handleTab(info.tabId));
chrome.windows.onFocusChanged.addListener(() => handleTab());
async function handleTab(tabId, url) {
if (tabId === undefined || tabId === null) {
chrome.windows.getCurrent({}, (window) => {
if (window && window.id !== null && window.id !== undefined) {
chrome.tabs.query({active: true, windowId: window.id}, (tab) => {
if (tab.length !== 1) {
return;
}
tab = tab[0];
if (tab && tab.id !== null && tab.id !== undefined && tab.url) {
handleTab(tab.id, tab.url)
}
});
}
});
return;
}
if (!url) {
chrome.tabs.get(tabId, (tab) => {
if (tab && tab.url) {
handleTab(tabId, tab.url)
}
});
return;
}
let options = await getOptions();
if (!isDiscouraged(url, options.blacklist)) {
return;
}
if (options.schedule) {
let now = new Date();
let day = now.getDay();
if (day == 0) {
day += 7;
}
day--;
let schedule = options.schedule[day];
let timeOfDay = now.getHours() * 3600 * 1000;
timeOfDay += now.getMinutes() * 60 * 1000;
if (timeOfDay < schedule.from || timeOfDay >= schedule.to) {
return;
}
}
let unlockTime = options.lastUnlock;
let now = Date.now() / 1000;
if (unlockTime > now) {
chrome.storage.sync.set({'lastunlock': 0});
unlockTime = 0;
}
let unlocked = now - unlockTime <= options.siteTime;
if (unlocked) {
if (timeoutId !== null) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => handleTab(tabId), (options.siteTime - (now - unlockTime)) * 1000);
return;
}
lockTab(tabId, options.blacklist);
}
function lockTab(tabId, blacklist) {
chrome.storage.sync.set({'lastunlock': 0}, () => {
chrome.tabs.get(tabId, (tab) => {
if (tab.active && tab.url && isDiscouraged(tab.url, blacklist)) {
chrome.tabs.update(tabId, {url: chrome.runtime.getURL('unlock.html') + '?url=' + encodeURIComponent(tab.url)});
}
});
});
}
function isDiscouraged(url, blacklist) {
let a = document.createElement('a');
a.href = url;
let host = a.hostname.toLowerCase();
for (let i=0; i<blacklist.length; i++) {
let entry = blacklist[i].trim();
if (entry == "") {
continue;
}
if (entry.length <= host.length && host.indexOf(entry) === host.length - entry.length) {
let remaining = host.substring(0, host.length - entry.length);
if (remaining.length === 0 || remaining[remaining.length-1] === '.') {
return true;
}
}
}
return false;
}