forked from matchu/Strict-Workflow
-
Notifications
You must be signed in to change notification settings - Fork 5
/
background.js
501 lines (431 loc) · 13.2 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
/*
Constants
*/
var PREFS = loadPrefs(),
BADGE_BACKGROUND_COLORS = {
work: [192, 0, 0, 255],
break: [0, 192, 0, 255]
}, RING = new Audio("ring.ogg"),
ringLoaded = false;
loadRingIfNecessary();
function defaultPrefs() {
return {
siteList: [
'facebook.com',
'youtube.com',
'twitter.com',
'tumblr.com',
'pinterest.com',
'myspace.com',
'livejournal.com',
'digg.com',
'stumbleupon.com',
'reddit.com',
'kongregate.com',
'newgrounds.com',
'addictinggames.com',
'hulu.com'
],
durations: { // in seconds
work: 25 * 60,
break: 5 * 60
},
shouldRing: true,
clickRestarts: false,
whitelist: false,
userName: '',
authToken: '',
goal: ''
}
}
function loadPrefs() {
if(typeof localStorage['prefs'] !== 'undefined') {
return updatePrefsFormat(JSON.parse(localStorage['prefs']));
} else {
return savePrefs(defaultPrefs());
}
}
function updatePrefsFormat(prefs) {
// Sometimes we need to change the format of the PREFS module. When just,
// say, adding boolean flags with false as the default, there's no
// compatibility issue. However, in more complicated situations, we need
// to modify an old PREFS module's structure for compatibility.
if(prefs.hasOwnProperty('domainBlacklist')) {
// Upon adding the whitelist feature, the domainBlacklist property was
// renamed to siteList for clarity.
prefs.siteList = prefs.domainBlacklist;
delete prefs.domainBlacklist;
savePrefs(prefs);
console.log("Renamed PREFS.domainBlacklist to PREFS.siteList");
}
if(!prefs.hasOwnProperty('showNotifications')) {
// Upon adding the option to disable notifications, added the
// showNotifications property, which defaults to true.
prefs.showNotifications = true;
savePrefs(prefs);
console.log("Added PREFS.showNotifications");
}
return prefs;
}
function savePrefs(prefs) {
localStorage['prefs'] = JSON.stringify(prefs);
return prefs;
}
function setPrefs(prefs) {
PREFS = savePrefs(prefs);
loadRingIfNecessary();
return prefs;
}
function loadRingIfNecessary() {
console.log('is ring necessary?');
if(PREFS.shouldRing && !ringLoaded) {
console.log('ring is necessary');
RING.onload = function () {
console.log('ring loaded');
ringLoaded = true;
}
RING.load();
}
}
var ICONS = {
ACTION: {
CURRENT: {},
PENDING: {}
},
FULL: {},
}, iconTypeS = ['default', 'work', 'break'],
iconType;
for(var i in iconTypeS) {
iconType = iconTypeS[i];
ICONS.ACTION.CURRENT[iconType] = "icons/" + iconType + ".png";
ICONS.ACTION.PENDING[iconType] = "icons/" + iconType + "_pending.png";
ICONS.FULL[iconType] = "icons/" + iconType + "_full.png";
}
/*
Models
*/
function Pomodoro(options) {
this.mostRecentMode = 'break';
this.nextMode = 'work';
this.running = false;
this.comment = '';
this.splitComment = '';
this.goal = PREFS.goal;
this.onTimerEnd = function (timer) {
this.running = false;
if (this.mostRecentMode == 'work') {
var url = 'https://www.beeminder.com/api/v1/users/' + PREFS.userName
+ '/goals/' + this.goal + '/datapoints.json';
console.log(url);
jQuery.ajax({
type: "POST",
url: url,
data: {"auth_token": PREFS.authToken,"value": 1,"comment":this.splitComment},
tryCount: 0,
retryLimit: 5,
success: function(data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
$.ajax(this);
return;
}
var info = "An error occurred.\n" + "textStatus: " + textStatus
+ "\nerrorThrown: " + errorThrown;
var advice = "\nEdit the options page with your beeminder "
+ "username, goalname, and auth token if you haven't already."
alert(info + advice);
}
});
}
}
this.start = function () {
var mostRecentMode = this.mostRecentMode, timerOptions = {};
this.mostRecentMode = this.nextMode;
this.nextMode = mostRecentMode;
for(var key in options.timer) {
timerOptions[key] = options.timer[key];
}
timerOptions.type = this.mostRecentMode;
timerOptions.duration = options.getDurations()[this.mostRecentMode];
this.running = true;
this.currentTimer = new Pomodoro.Timer(this, timerOptions);
this.currentTimer.start();
}
this.restart = function () {
if(this.currentTimer) {
this.currentTimer.restart();
}
}
}
Pomodoro.Timer = function Timer(pomodoro, options) {
var tickInterval, timer = this;
this.pomodoro = pomodoro;
this.timeRemaining = options.duration;
this.type = options.type;
this.start = function () {
tickInterval = setInterval(tick, 1000);
options.onStart(timer);
options.onTick(timer);
}
this.restart = function() {
this.timeRemaining = options.duration;
options.onTick(timer);
}
this.timeRemainingString = function () {
if(this.timeRemaining >= 60) {
return Math.round(this.timeRemaining / 60) + "m";
} else {
return (this.timeRemaining % 60) + "s";
}
}
function tick() {
timer.timeRemaining--;
options.onTick(timer);
if(timer.timeRemaining <= 0) {
clearInterval(tickInterval);
pomodoro.onTimerEnd(timer);
options.onEnd(timer);
}
}
}
/*
Views
*/
// The code gets really cluttered down here. Refactor would be in order,
// but I'm busier with other projects >_<
function locationsMatch(location, listedPattern) {
return domainsMatch(location.domain, listedPattern.domain) &&
pathsMatch(location.path, listedPattern.path);
}
function parseLocation(location) {
var components = location.split('/');
return {domain: components.shift(), path: components.join('/')};
}
function pathsMatch(test, against) {
/*
index.php ~> [null]: pass
index.php ~> index: pass
index.php ~> index.php: pass
index.php ~> index.phpa: fail
/path/to/location ~> /path/to: pass
/path/to ~> /path/to: pass
/path/to/ ~> /path/to/location: fail
*/
return !against || test.substr(0, against.length) == against;
}
function domainsMatch(test, against) {
/*
google.com ~> google.com: case 1, pass
www.google.com ~> google.com: case 3, pass
google.com ~> www.google.com: case 2, fail
google.com ~> yahoo.com: case 3, fail
yahoo.com ~> google.com: case 2, fail
bit.ly ~> goo.gl: case 2, fail
mail.com ~> gmail.com: case 2, fail
gmail.com ~> mail.com: case 3, fail
*/
// Case 1: if the two strings match, pass
if(test === against) {
return true;
} else {
var testFrom = test.length - against.length - 1;
// Case 2: if the second string is longer than first, or they are the same
// length and do not match (as indicated by case 1 failing), fail
if(testFrom < 0) {
return false;
} else {
// Case 3: if and only if the first string is longer than the second and
// the first string ends with a period followed by the second string,
// pass
return test.substr(testFrom) === '.' + against;
}
}
}
function isLocationBlocked(location) {
for(var k in PREFS.siteList) {
listedPattern = parseLocation(PREFS.siteList[k]);
if(locationsMatch(location, listedPattern)) {
// If we're in a whitelist, a matched location is not blocked => false
// If we're in a blacklist, a matched location is blocked => true
return !PREFS.whitelist;
}
}
// If we're in a whitelist, an unmatched location is blocked => true
// If we're in a blacklist, an unmatched location is not blocked => false
return PREFS.whitelist;
}
function executeInTabIfBlocked(action, tab) {
var file = "content_scripts/" + action + ".js", location;
location = tab.url.split('://');
location = parseLocation(location[1]);
if(isLocationBlocked(location)) {
chrome.tabs.executeScript(tab.id, {file: file});
}
}
function executeInAllBlockedTabs(action) {
var windows = chrome.windows.getAll({populate: true}, function (windows) {
var tabs, tab, domain, listedDomain;
for(var i in windows) {
tabs = windows[i].tabs;
for(var j in tabs) {
executeInTabIfBlocked(action, tabs[j]);
}
}
});
}
function logComment (comment) {
console.log(comment);
}
var notification, mainPomodoro = new Pomodoro({
getDurations: function () { return PREFS.durations },
timer: {
onEnd: function (timer) {
chrome.browserAction.setIcon({
path: ICONS.ACTION.PENDING[timer.pomodoro.nextMode]
});
chrome.browserAction.setBadgeText({text: ''});
if(PREFS.showNotifications) {
var nextModeName = chrome.i18n.getMessage(timer.pomodoro.nextMode);
chrome.notifications.create("", {
type: "basic",
title: chrome.i18n.getMessage("timer_end_notification_header"),
message: chrome.i18n.getMessage("timer_end_notification_body",
nextModeName),
iconUrl: ICONS.FULL[timer.type]
}, function() {});
}
if(PREFS.shouldRing) {
console.log("playing ring", RING);
RING.play();
}
},
onStart: function (timer) {
chrome.browserAction.setIcon({
path: ICONS.ACTION.CURRENT[timer.type]
});
chrome.browserAction.setBadgeBackgroundColor({
color: BADGE_BACKGROUND_COLORS[timer.type]
});
if(timer.type == 'work') {
executeInAllBlockedTabs('block');
} else {
executeInAllBlockedTabs('unblock');
}
if(notification) notification.cancel();
var tabViews = chrome.extension.getViews({type: 'tab'}), tab;
for(var i in tabViews) {
tab = tabViews[i];
if(typeof tab.startCallbacks !== 'undefined') {
tab.startCallbacks[timer.type]();
}
}
},
onTick: function (timer) {
chrome.browserAction.setBadgeText({text: timer.timeRemainingString()});
}
}
});
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
if(message.popupOpen) {
chrome.runtime.sendMessage({displayComment: mainPomodoro.comment});
// Get the number of pomodoros done today
var userUrl = 'https://www.beeminder.com/api/v1/users/' + PREFS.userName + '.json';
// Generate dateString to only count pomodoros from today
var todayDate = new Date();
var yyyy = todayDate.getFullYear();
var mm = todayDate.getMonth() + 1;
var dd = todayDate.getDate();
if (dd<10) {
dd='0'+dd;
}
else
dd=dd.toString();
if (mm<10) {
mm = '0'+mm;
}
else
mm=mm.toString();
var dateString = yyyy+mm+dd;
var todayTime = Math.round(todayDate.getTime()/1000 - 86400);// check up to 24 hrs before current time
// Query user and add up all pomodoros since todayTime that match the dateString
jQuery.ajax({
type: "GET",
url: userUrl,
data: {"auth_token": PREFS.authToken,"diff_since": todayTime},
tryCount: 0,
retryLimit: 5,
success: function(data) {
console.log(data);
var value = 0;
for (goal in data.goals) {
var goalObj = data.goals[goal];
if (goalObj.slug == mainPomodoro.goal) {
for (datapoint in goalObj.datapoints){
if (dateString == goalObj.datapoints[datapoint].daystamp){
value += goalObj.datapoints[datapoint].value;
}
}
console.log(value);
chrome.runtime.sendMessage({value: value});
}
}
},
error: function(jqXHR, textStatus, errorThrown) {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
$.ajax(this);
return;
}
var info = "An error occurred.\n" + "textStatus: " + textStatus
+ "\nerrorThrown: " + errorThrown;
var advice = "\nEdit the options page with your beeminder "
+ "username, goalname, and auth token if you haven't already."
alert(info + advice);
}
});
if(mainPomodoro.running) {
if(PREFS.clickRestarts) {
mainPomodoro.restart();
}
} else {
mainPomodoro.start();
}
}
else if (message.comment){
mainPomodoro.comment = message.comment;
var patt = new RegExp(/\S*\s*#(\w+)/);
var res = patt.exec(mainPomodoro.comment);
if (res) {
mainPomodoro.goal = res[1];
}
else {
mainPomodoro.goal = PREFS.goal;
}
var splits = mainPomodoro.comment.split(/\s*#/);
mainPomodoro.splitComment = splits[0];
}
});
chrome.browserAction.onClicked.addListener(function (tab) {
if(mainPomodoro.running) {
if(PREFS.clickRestarts) {
mainPomodoro.restart();
}
} else {
mainPomodoro.start();
}
});
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if(mainPomodoro.mostRecentMode == 'work') {
executeInTabIfBlocked('block', tab);
}
});
chrome.notifications.onClicked.addListener(function (id) {
// Clicking the notification brings you back to Chrome, in whatever window
// you were last using.
chrome.windows.getLastFocused(function (window) {
chrome.windows.update(window.id, {focused: true});
});
});