-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
322 lines (259 loc) · 10.9 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
var iterationsSinceLastSave = 0;
var sitesToAdd = new Array();
var userIsActive = false;
var TIME_LIMITED_SITES_SNOOZE_DURATION = 600000;
setInterval(checkActiveTab, 1000); //1 second
setInterval(checkLateTime, 840000); //14 minutes
setInterval(checkLastGoalView, 1800000); //30 minutes
setInterval(checkTimeLimitedSites, 540000); //9 minutes
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.messageType && msg.messageType == "createNewTab" && msg.url)
chrome.tabs.create({ 'url': msg.url });
else if (msg.messageType && msg.messageType == "pageLoaded")
checkTimeLimitedSites();
});
chrome.runtime.onInstalled.addListener(function (details) {
if (details.reason == "install") {
chrome.runtime.openOptionsPage();
if (chrome.runtime.id == "gpbdmbcehgeedlilhdeolifmboafbcjb") {
$.ajax({
url: 'http://tollski.com/pct_manager/index.php',
type: 'post',
data: {
type: "install"
},
headers: {
}
},
function() {});
}
var whitelistArray = ["nofap.com"];
chrome.storage.local.set({
siteWhitelist: whitelistArray
}, function() {});
}
});
/*
*/
//checkActiveTab: Tracks time spent on websites.
function checkActiveTab() {
//Get the active browser tab. It must be completely loaded.
chrome.tabs.query({active: true, currentWindow: true, status: "complete"}, function(tabArray) {
// since only one tab should be active and in the current window at once
// the return variable should only have one entry
var activeTab = tabArray[0];
if (activeTab) { //If we got a tab that is active in the current window and completely loaded: ...
chrome.tabs.sendMessage(activeTab.id, { requestType: "getLastActiveTime" }, function(response) { //Send a message to the tab requesting its last active time.
if (chrome.runtime.lastError)
console.log("Error: " + chrome.runtime.lastError.message)
else if (response.lastActiveTime) {
if (response.lastActiveTime <= 30) {
userIsActive= true;
var siteHost = getSiteHost(activeTab);
console.log(siteHost + ": " + response.lastActiveTime + "s");
var hostFound = false;
for (i = 0; i < sitesToAdd.length; i++) {
if (sitesToAdd[i].host === siteHost) {
sitesToAdd[i].time++;
hostFound = true;
break;
}
}
if (!hostFound) {
var newSite = {
host: siteHost,
time: 1
};
sitesToAdd.push(newSite);
}
}
else
userIsActive = false;
}
});
}
});
//Save the data every 10 seconds.
iterationsSinceLastSave++;
if (iterationsSinceLastSave >= 10) {
//Copy the new information and erase the original array.
var tempSitesToAdd = new Array();
tempSitesToAdd.push.apply(tempSitesToAdd, sitesToAdd);
sitesToAdd = new Array();
iterationsSinceLastSave = 0;
chrome.storage.local.get({
visitedSitesDictionary: {}
}, function (items) {
var updatedSitesDictionary = items.visitedSitesDictionary;
var todayDate = getTodayDateFormatted();
if (!updatedSitesDictionary[todayDate])
updatedSitesDictionary[todayDate] = new Array();
//console.log(updatedSitesDictionary[todayDate]);
var updatedSites = updatedSitesDictionary[todayDate];
for (i = 0; i < tempSitesToAdd.length; i++) {
console.log(tempSitesToAdd[i].host + ": " + tempSitesToAdd[i].time);
index = binarySearchSites(tempSitesToAdd[i].host, updatedSites, 0, updatedSites.length - 1);
console.log(index);
if (index > -1)
updatedSites[index].time += tempSitesToAdd[i].time;
else {
updatedSites.push(tempSitesToAdd[i]);
updatedSites.sort(compareByHostAscending);
}
}
updatedSitesDictionary[todayDate] = updatedSites;
chrome.storage.local.set({
visitedSitesDictionary: updatedSitesDictionary
}, function() {});
});
}
}
//checkLateTime: Checks if the current time is set as a "late time" by the user. Notifies the user if it is.
function checkLateTime() {
if (!userIsActive)
return;
chrome.storage.sync.get({
enableLateAlert: false,
lateAlertStartTime: "0000",
lateAlertEndTime: "0100"
}, function(items) {
if (!items.enableLateAlert)
return;
var startTimeString = items.lateAlertStartTime;
var endTimeString = items.lateAlertEndTime;
var startTime = parseInt(startTimeString.substr(0,2)) + (parseInt(startTimeString.substr(2,2)) / 60);
var endTime = parseInt(endTimeString.substr(0,2)) + (parseInt(endTimeString.substr(2,2)) / 60);
var now = new Date();
var currTime = now.getHours() + (now.getMinutes() / 60);
if ((startTime < endTime && (startTime <= currTime && currTime < endTime)) || (startTime > endTime && (startTime < currTime || currTime < endTime))) {
var currTimeString = "";
if (now.getHours() === 0)
currTimeString += "12";
else
currTimeString += now.getHours();
if (now.getMinutes() < 10)
currTimeString += ":0" + now.getMinutes();
else
currTimeString += ":" + now.getMinutes();
if (now.getHours() < 12)
currTimeString += "AM";
else
currTimeString += "PM";
chrome.tabs.query({active: true, currentWindow: true}, function(tabArray) {
var activeTab = tabArray[0];
chrome.tabs.sendMessage(activeTab.id, { requestType: "addNotification", notificationReason: "Late Alert", notificationDescription: "It is " + currTimeString + "." });
});
}
});
}
//checkTimeLimitedSites: Checks if the active page is a time-limited website. If it is and the user has surpassed his time limit it notifies the user.
function checkTimeLimitedSites() {
console.log("Checking time limited sites.");
if (!userIsActive)
return;
var snooze = false;
chrome.storage.local.get({
siteTimeLimitedSnoozeEnd: 0
}, function (items) {
var now = new Date();
console.log("now.getTime()-items.siteTimeLimitedSnoozeEnd: " + (now.getTime() - items.siteTimeLimitedSnoozeEnd));
if (now.getTime() < items.siteTimeLimitedSnoozeEnd) {
console.log("Time-Limited Alerts On Snooze");
return;
}
//Get the active browser tab. It must be completely loaded.
chrome.tabs.query({active: true, currentWindow: true, status: "complete"}, function(tabArray) {
// since only one tab should be active and in the current window at once
// the return variable should only have one entry
var activeTab = tabArray[0];
if (activeTab) { //If we got a tab that is active in the current window and completely loaded: ...
chrome.tabs.sendMessage(activeTab.id, { requestType: "getLastActiveTime" }, function(response) { //Send a message to the tab requesting its last active time.
if (chrome.runtime.lastError)
console.log("Error: " + chrome.runtime.lastError.message)
else if (response.lastActiveTime && response.lastActiveTime <= 30) {
var siteHost = getSiteHost(activeTab);
chrome.storage.local.get({
siteTimeLimitedList: new Array(),
siteTimeLimitedTime1: 0,
siteTimeLimitedTime2: 0,
visitedSitesDictionary: {}
}, function (items) {
var limitedSites = items.siteTimeLimitedList;
var limitTime1 = items.siteTimeLimitedTime1 * 60;
var limitTime2 = items.siteTimeLimitedTime2 * 60;
var sitesDictionary = items.visitedSitesDictionary;
console.log("limited sites: " + limitedSites);
var index = binarySearch(siteHost, limitedSites, 0, limitedSites.length - 1);
if (index === -1) //If current site isn't a time-limited site: return.
return;
console.log(siteHost + " is a time-limited site. index=" + index);
var todayDate = getTodayDateFormatted();
if (!sitesDictionary[todayDate]) //If the array of sites we have visited today is empty: return.
return;
console.log("site dictionary for today is not empty");
var sitesToday = sitesDictionary[todayDate];
index = binarySearchSites(siteHost, sitesToday, 0, sitesToday.length - 1);
if (index === -1) //If current site isn't in the list of sites visited today: return.
return;
console.log(siteHost + " has been visited today.");
//Calculate time spent on time-limited sites today.
var timeSpentOnLimitedSitesToday = 0;
for (i = 0; i < limitedSites.length; i++) {
index = binarySearchSites(limitedSites[i], sitesToday, 0, sitesToday.length - 1);
if (index > -1) {
timeSpentOnLimitedSitesToday += sitesToday[index].time;
console.log("time spend on " + limitedSites[i] + "(" + sitesToday[index].host + "): " + sitesToday[index].time);
}
}
console.log("timeSpentOnLimitedSitesToday: " + timeSpentOnLimitedSitesToday);
if (timeSpentOnLimitedSitesToday >= limitTime1) //If the user hasn reached his time limit: ...
chrome.tabs.sendMessage(activeTab.id, { requestType: "timeLimitedAlert", limitNumber: 1, timeSpent: Math.floor(timeSpentOnLimitedSitesToday / 60) });
if (timeSpentOnLimitedSitesToday >= limitTime2) //If the user hasn reached his time limit: ...
chrome.tabs.sendMessage(activeTab.id, { requestType: "timeLimitedAlert", limitNumber: 2, timeSpent: Math.floor(timeSpentOnLimitedSitesToday / 60) });
});
}
});
}
});
});
}
//checkLastGoalView: Notifies the user if he has not visited his goals page in 7 or more days.
function checkLastGoalView() {
if (!userIsActive)
return;
chrome.storage.sync.get({
goalReviewNotificationEnabled: true,
lastGoalPageViewTime: 0
}, function(items) {
if (!items.goalReviewNotificationEnabled)
return;
if (items.lastGoalPageViewTime === 0) {
//alert("You have never viewed your goals page.");
chrome.tabs.query({active: true, currentWindow: true}, function(tabArray) {
var activeTab = tabArray[0];
chrome.tabs.sendMessage(activeTab.id, { requestType: "addNotification", notificationReason: "Goal Reminder:", notificationDescription: "You have not yet viewed your goals page." });
});
return;
}
var today = new Date();
var timeSinceLastGoalView = today.getTime() - items.lastGoalPageViewTime;
if (timeSinceLastGoalView > 86400000 * 7) {
//alert("You haven't reviewed your goals for " + Math.floor(timeSinceLastGoalView / 86400000) + " days. (You can disable these notifications on the options page.)");
chrome.tabs.query({active: true, currentWindow: true}, function(tabArray) {
var activeTab = tabArray[0];
chrome.tabs.sendMessage(activeTab.id, { requestType: "addNotification", notificationReason: "Goal Reminder:", notificationDescription: "You have not yet reviewed your goals for " + Math.floor(timeSinceLastGoalView / 86400000) + " days." });
});
}
});
}
//getSiteHost: Returns the hostname of the website that the given tab is on.
function getSiteHost(activeTab) {
var loc = document.createElement("a");
loc.href = activeTab.url;
var siteHost = loc.hostname;
if (siteHost.toLowerCase().indexOf("www.") === 0)
siteHost = siteHost.substring(4, siteHost.length);
return siteHost;
}
/*
*/