forked from matchu/Strict-Workflow
-
Notifications
You must be signed in to change notification settings - Fork 1
/
background.js
374 lines (322 loc) · 9.68 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
/*
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,
autostartWork: false,
autostartBreak: true,
whitelist: false
}
}
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.onTimerEnd = function (timer) {
this.running = false;
}
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]);
}
}
});
}
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: ''});
var nextModeName = chrome.i18n.getMessage(timer.pomodoro.nextMode);
if(PREFS.showNotifications) {
notification = webkitNotifications.createNotification(
ICONS.FULL[timer.type],
chrome.i18n.getMessage("timer_end_notification_header"),
chrome.i18n.getMessage("timer_end_notification_body", nextModeName)
);
notification.onclick = function () {
console.log("Will get last focused");
chrome.windows.getLastFocused(function (window) {
chrome.windows.update(window.id, {focused: true});
});
this.cancel();
};
notification.show();
}
if(PREFS.shouldRing) {
console.log("playing ring", RING);
RING.play();
}
if(nextModeName == 'break' && PREFS.autostartBreak) {
mainPomodoro.start();
}
if(nextModeName == 'work' && PREFS.autostartWork) {
mainPomodoro.start();
}
},
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) setTimeout(function(){notification.cancel();}, '10000');
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.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);
}
});