forked from GoogleChrome/chrome-extensions-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
351 lines (306 loc) · 10.3 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
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var animationFrames = 36;
var animationSpeed = 10; // ms
var canvas = document.getElementById('canvas');
var loggedInImage = document.getElementById('logged_in');
var canvasContext = canvas.getContext('2d');
var pollIntervalMin = 1; // 1 minute
var pollIntervalMax = 60; // 1 hour
var requestTimeout = 1000 * 2; // 2 seconds
var rotation = 0;
var loadingAnimation = new LoadingAnimation();
// Legacy support for pre-event-pages.
var oldChromeVersion = !chrome.runtime;
var requestTimerId;
function getGmailUrl() {
return "https://mail.google.com/mail/";
}
// Identifier used to debug the possibility of multiple instances of the
// extension making requests on behalf of a single user.
function getInstanceId() {
if (!localStorage.hasOwnProperty("instanceId"))
localStorage.instanceId = 'gmc' + parseInt(Date.now() * Math.random(), 10);
return localStorage.instanceId;
}
function getFeedUrl() {
// "zx" is a Gmail query parameter that is expected to contain a random
// string and may be ignored/stripped.
return getGmailUrl() + "feed/atom?zx=" + encodeURIComponent(getInstanceId());
}
function isGmailUrl(url) {
// Return whether the URL starts with the Gmail prefix.
return url.startsWith(getGmailUrl());
}
// A "loading" animation displayed while we wait for the first response from
// Gmail. This animates the badge text with a dot that cycles from left to
// right.
function LoadingAnimation() {
this.timerId_ = 0;
this.maxCount_ = 8; // Total number of states in animation
this.current_ = 0; // Current state
this.maxDot_ = 4; // Max number of dots in animation
}
LoadingAnimation.prototype.paintFrame = function() {
var text = "";
for (var i = 0; i < this.maxDot_; i++) {
text += (i == this.current_) ? "." : " ";
}
if (this.current_ >= this.maxDot_)
text += "";
chrome.browserAction.setBadgeText({text:text});
this.current_++;
if (this.current_ == this.maxCount_)
this.current_ = 0;
}
LoadingAnimation.prototype.start = function() {
if (this.timerId_)
return;
var self = this;
this.timerId_ = window.setInterval(function() {
self.paintFrame();
}, 100);
}
LoadingAnimation.prototype.stop = function() {
if (!this.timerId_)
return;
window.clearInterval(this.timerId_);
this.timerId_ = 0;
}
function updateIcon() {
if (!localStorage.hasOwnProperty('unreadCount')) {
chrome.browserAction.setIcon({path:"gmail_not_logged_in.png"});
chrome.browserAction.setBadgeBackgroundColor({color:[190, 190, 190, 230]});
chrome.browserAction.setBadgeText({text:"?"});
} else {
chrome.browserAction.setIcon({path: "gmail_logged_in.png"});
chrome.browserAction.setBadgeBackgroundColor({color:[208, 0, 24, 255]});
chrome.browserAction.setBadgeText({
text: localStorage.unreadCount != "0" ? localStorage.unreadCount : ""
});
}
}
function scheduleRequest() {
console.log('scheduleRequest');
var randomness = Math.random() * 2;
var exponent = Math.pow(2, localStorage.requestFailureCount || 0);
var multiplier = Math.max(randomness * exponent, 1);
var delay = Math.min(multiplier * pollIntervalMin, pollIntervalMax);
delay = Math.round(delay);
console.log('Scheduling for: ' + delay);
if (oldChromeVersion) {
if (requestTimerId) {
window.clearTimeout(requestTimerId);
}
requestTimerId = window.setTimeout(onAlarm, delay*60*1000);
} else {
console.log('Creating alarm');
// Use a repeating alarm so that it fires again if there was a problem
// setting the next alarm.
chrome.alarms.create('refresh', {periodInMinutes: delay});
}
}
// ajax stuff
function startRequest(params) {
// Schedule request immediately. We want to be sure to reschedule, even in the
// case where the extension process shuts down while this request is
// outstanding.
if (params && params.scheduleRequest) scheduleRequest();
function stopLoadingAnimation() {
if (params && params.showLoadingAnimation) loadingAnimation.stop();
}
if (params && params.showLoadingAnimation)
loadingAnimation.start();
getInboxCount(
function(count) {
stopLoadingAnimation();
updateUnreadCount(count);
},
function() {
stopLoadingAnimation();
delete localStorage.unreadCount;
updateIcon();
}
);
}
function getInboxCount(onSuccess, onError) {
var xhr = new XMLHttpRequest();
var abortTimerId = window.setTimeout(function() {
xhr.abort(); // synchronously calls onreadystatechange
}, requestTimeout);
function handleSuccess(count) {
localStorage.requestFailureCount = 0;
window.clearTimeout(abortTimerId);
if (onSuccess)
onSuccess(count);
}
var invokedErrorCallback = false;
function handleError() {
++localStorage.requestFailureCount;
window.clearTimeout(abortTimerId);
if (onError && !invokedErrorCallback)
onError();
invokedErrorCallback = true;
}
try {
xhr.onreadystatechange = function() {
if (xhr.readyState != 4)
return;
if (xhr.responseXML) {
var xmlDoc = xhr.responseXML;
var fullCountSet = xmlDoc.evaluate("/gmail:feed/gmail:fullcount",
xmlDoc, gmailNSResolver, XPathResult.ANY_TYPE, null);
var fullCountNode = fullCountSet.iterateNext();
if (fullCountNode) {
handleSuccess(fullCountNode.textContent);
return;
} else {
console.error(chrome.i18n.getMessage("gmailcheck_node_error"));
}
}
handleError();
};
xhr.onerror = function(error) {
handleError();
};
xhr.open("GET", getFeedUrl(), true);
xhr.send(null);
} catch(e) {
console.error(chrome.i18n.getMessage("gmailcheck_exception", e));
handleError();
}
}
function gmailNSResolver(prefix) {
if(prefix == 'gmail') {
return 'http://purl.org/atom/ns#';
}
}
function updateUnreadCount(count) {
var changed = localStorage.unreadCount != count;
localStorage.unreadCount = count;
updateIcon();
if (changed)
animateFlip();
}
function ease(x) {
return (1-Math.sin(Math.PI/2+x*Math.PI))/2;
}
function animateFlip() {
rotation += 1/animationFrames;
drawIconAtRotation();
if (rotation <= 1) {
setTimeout(animateFlip, animationSpeed);
} else {
rotation = 0;
updateIcon();
}
}
function drawIconAtRotation() {
canvasContext.save();
canvasContext.clearRect(0, 0, canvas.width, canvas.height);
canvasContext.translate(
Math.ceil(canvas.width/2),
Math.ceil(canvas.height/2));
canvasContext.rotate(2*Math.PI*ease(rotation));
canvasContext.drawImage(loggedInImage,
-Math.ceil(canvas.width/2),
-Math.ceil(canvas.height/2));
canvasContext.restore();
chrome.browserAction.setIcon({imageData:canvasContext.getImageData(0, 0,
canvas.width,canvas.height)});
}
function goToInbox() {
console.log('Going to inbox...');
chrome.tabs.getAllInWindow(undefined, function(tabs) {
for (var i = 0, tab; tab = tabs[i]; i++) {
if (tab.url && isGmailUrl(tab.url)) {
console.log('Found Gmail tab: ' + tab.url + '. ' +
'Focusing and refreshing count...');
chrome.tabs.update(tab.id, {selected: true});
startRequest({scheduleRequest:false, showLoadingAnimation:false});
return;
}
}
console.log('Could not find Gmail tab. Creating one...');
chrome.tabs.create({url: getGmailUrl()});
});
}
function onInit() {
console.log('onInit');
localStorage.requestFailureCount = 0; // used for exponential backoff
startRequest({scheduleRequest:true, showLoadingAnimation:true});
if (!oldChromeVersion) {
// TODO(mpcomplete): We should be able to remove this now, but leaving it
// for a little while just to be sure the refresh alarm is working nicely.
chrome.alarms.create('watchdog', {periodInMinutes:5});
}
}
function onAlarm(alarm) {
console.log('Got alarm', alarm);
// |alarm| can be undefined because onAlarm also gets called from
// window.setTimeout on old chrome versions.
if (alarm && alarm.name == 'watchdog') {
onWatchdog();
} else {
startRequest({scheduleRequest:true, showLoadingAnimation:false});
}
}
function onWatchdog() {
chrome.alarms.get('refresh', function(alarm) {
if (alarm) {
console.log('Refresh alarm exists. Yay.');
} else {
console.log('Refresh alarm doesn\'t exist!? ' +
'Refreshing now and rescheduling.');
startRequest({scheduleRequest:true, showLoadingAnimation:false});
}
});
}
if (oldChromeVersion) {
updateIcon();
onInit();
} else {
chrome.runtime.onInstalled.addListener(onInit);
chrome.alarms.onAlarm.addListener(onAlarm);
}
var filters = {
// TODO(aa): Cannot use urlPrefix because all the url fields lack the protocol
// part. See crbug.com/140238.
url: [{urlContains: getGmailUrl().replace(/^https?\:\/\//, '')}]
};
function onNavigate(details) {
if (details.url && isGmailUrl(details.url)) {
console.log('Recognized Gmail navigation to: ' + details.url + '.' +
'Refreshing count...');
startRequest({scheduleRequest:false, showLoadingAnimation:false});
}
}
if (chrome.webNavigation && chrome.webNavigation.onDOMContentLoaded &&
chrome.webNavigation.onReferenceFragmentUpdated) {
chrome.webNavigation.onDOMContentLoaded.addListener(onNavigate, filters);
chrome.webNavigation.onReferenceFragmentUpdated.addListener(
onNavigate, filters);
} else {
chrome.tabs.onUpdated.addListener(function(_, details) {
onNavigate(details);
});
}
chrome.browserAction.onClicked.addListener(goToInbox);
if (chrome.runtime && chrome.runtime.onStartup) {
chrome.runtime.onStartup.addListener(function() {
console.log('Starting browser... updating icon.');
startRequest({scheduleRequest:false, showLoadingAnimation:false});
updateIcon();
});
} else {
// This hack is needed because Chrome 22 does not persist browserAction icon
// state, and also doesn't expose onStartup. So the icon always starts out in
// wrong state. We don't actually use onStartup except as a clue that we're
// in a version of Chrome that has this problem.
chrome.windows.onCreated.addListener(function() {
console.log('Window created... updating icon.');
startRequest({scheduleRequest:false, showLoadingAnimation:false});
updateIcon();
});
}