-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
391 lines (337 loc) · 11.7 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
var pollIntervalMin = 1; // 1 minute
var pollIntervalMax = 60; // 1 hour
var requestTimeout = 1000 * 2; // 2 seconds
function onMatched(hostName, tabId, sendResponse) {
var pageTypeId = getPageTypeByHostName(hostName);
var selectedPageType = types[pageTypeId];
switch (selectedPageType.type) {
case 'site':
// If site type was matching
var site = getSite(selectedPageType.hostname);
if (!site) {
chrome.pageAction.hide(tabId);
} else {
tabs[tabId] = site.hostname;
sites[site.hostname] = site;
chrome.pageAction.show(tabId);
var test = progress[site.hostname];
sendResponse({ 'profile': site, 'progress': test, 'tabId': tabId });
}
break;
case 'source':
var source = availableSources[selectedPageType.hostname];
if (source) {
source.init(tabId);
}
break;
default:
break;
}
}
function onSourceRefresh(hostName, tabId, sendResponse) {
if (selectedSource) {
selectedSource.refresh();
}
}
function onUpdateStatus(tabId, status, sendResponse) {
// Content script should only be able to update their own status
var hostname = tabs[tabId];
progress[hostname]['status'] = status;
if (sendResponse && typeof (sendResponse) === 'function') {
sendResponse();
}
}
function onUpdateData(tabId, data, sendResponse) {
// Content script should only be able to update their own data
var hostname = tabs[tabId];
progress[hostname]['data'] = data;
if (sendResponse && typeof (sendResponse) === 'function') {
sendResponse();
}
}
function onLogin(tabId) {
var hostname = tabs[tabId];
var site = getSite(hostname);
if (site && site.hostname) {
var options = {
'url': false,
'active': false
};
progress[site.hostname] = { 'status': 'remindPass', 'sourceTabId': tabId };
var profileType = false;
for (var profileTypeName in availableSites) {
var tmpProfileType = availableSites[profileTypeName];
if (tmpProfileType.hostname == site.hostname) {
options.url = tmpProfileType.remindUrl;
profileType = tmpProfileType;
}
}
// Update pageAction icon
updateStepAndStatus(progress[site.hostname], 1, 1);
// https://developer.chrome.com/extensions/tabs#method-create
chrome.tabs.create(options, function (tab) {
tabs[tab.id] = profileType.hostname;
progress[site.hostname]['currentTab'] = tab.id;
// initiate a refresh interval
if (selectedSource) {
selectedSource.refresh();
}
});
}
}
// update site profile and stores it
function onUpdateProfile(tabId, userId) {
var hostname = tabs[tabId];
var site = getSite(hostname);
if (site && site.hostname) {
site.userId = userId;
saveProfile(site);
}
}
function onOpenTab(tabId, url, sendResponse) {
var options = {
'url': url,
'active': false
};
// https://developer.chrome.com/extensions/tabs#method-create
chrome.tabs.create(options, function (tab) {
sendResponse(tab);
});
}
function onCloseTab(tabId, sendResponse) {
delete tabs[tabId];
chrome.tabs.remove(tabId);
if (sendResponse && typeof (sendResponse) === 'function') {
sendResponse();
}
}
function onGeneratePassword(tabId, length, useLowercase, useUppercase, useNumbers, useSymbols, sendResponse) {
var pass = genPass(length, useLowercase, useUppercase, useNumbers, useSymbols);
sendResponse(pass);
}
function onLoginDone(tabId, sendResponse) {
var hostname = tabs[tabId];
var sourceTabId = progress[hostname]['sourceTabId'];
var currentTabId = progress[hostname]['currentTab'];
onCloseTab(currentTabId);
chrome.tabs.sendMessage(sourceTabId, { 'action': 'loginDone' });
chrome.runtime.sendMessage({
'action': 'iconUpdate',
'step': 4,
'status': 2
});
if (sendResponse && typeof (sendResponse) === 'function') {
sendResponse();
}
}
function onIconUpdate(tabId, step, status, sendResponse) {
var hostname = tabs[tabId];
var p = progress[hostname];
updateStepAndStatus(p, step, status);
sendResponse();
}
// listening on actions from popup and contentscripts
chrome.runtime.onMessage.addListener(function (options, sender, sendResponse) {
var tabId = false;
if (sender.tab) {
// Calls from tabs
tabId = sender.tab.id;
} else {
// Calls from popup
tabId = options.tabId;
}
switch (options.action) {
case 'sourceRefresh':
onSourceRefresh(options.hostname, tabId, sendResponse);
break;
case 'matched':
onMatched(options.hostname, tabId, sendResponse);
return true;
//break;
case 'openTab':
onOpenTab(tabId, options.url, sendResponse);
break;
case 'closeTab':
onCloseTab(options.tabId, sendResponse);
break;
case 'updateProfile':
onUpdateProfile(tabId, options.userId, sendResponse);
break;
case 'updateStatus':
onUpdateStatus(tabId, options.status, sendResponse);
break;
case 'updateData':
onUpdateData(tabId, options.data, sendResponse);
break;
case 'login':
// 1. open remindPass url
// 2. change status
onLogin(tabId, sendResponse);
break;
case 'genPass':
var length = options.length || 60; // Use 60 as default length.
var useLowercase = options.useLowercase || true;
var useUppercase = options.useUppercase || true;
var useNumbers = options.useNumbers || true;
var useSymbols = options.useSymbols || true;
onGeneratePassword(tabId, length, useLowercase, useUppercase, useNumbers, useSymbols, sendResponse);
break;
case 'updateProfile':
onUpdateProfile(tabId, options.userId, sendResponse);
return true;
//break;
case 'loginDone':
onLoginDone(tabId, sendResponse);
break;
case 'iconUpdate':
onIconUpdate(tabId, options.step, options.status, sendResponse);
break;
}
});
function saveProfile(profile) {
if (profile && profile.hostname) {
profile.stored = true;
localStorage.setItem(profile.hostname, JSON.stringify(profile));
sites[profile.hostname] = profile;
// Yes... this is stupid...
}
}
function getSite(id) {
var site = false;
var tmp = localStorage.getItem(id);
if (tmp) {
site = JSON.parse(tmp);
}
if (!site) {
site = {
'hostname': id,
'name': id,
'stored': false,
'setup': false,
'userId': false
};
}
for (var siteId in availableSites) {
var availableSite = availableSites[siteId];
if (availableSite.hostname == id) {
for (var propName in availableSite) {
site[propName] = availableSite[propName]
}
}
}
return site;
}
chrome.tabs.onSelectionChanged.addListener(function (tabId, info) {
selectedId = tabId;
});
chrome.tabs.onRemoved.addListener(function (tabId, removeInfo) {
delete tabs[tabId];
});
function 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);
// Use a repeating alarm so that it fires again if there was a problem
// setting the next alarm.
chrome.alarms.create('refresh', { periodInMinutes: delay });
}
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();
if (selectedSource) {
selectedSource.refresh();
}
}
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 });
}
});
}
function onInit() {
init();
localStorage.requestFailureCount = 0; // used for exponential backoff
startRequest({ scheduleRequest: true, showLoadingAnimation: true });
chrome.alarms.create('watchdog', { periodInMinutes: 5 });
}
function onAlarm(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 setSelectedSource(selectedSourceName) {
selectedSource = availableSources[selectedSourceName];
}
function setSelectedSourceName(sourceName) {
selectedSourceName = sourceName;
localStorage.setItem("selectedSource", sourceName);
setSelectedSource(sourceName);
}
function initConfig() {
var path = chrome.extension.getURL("config.json");
getFileContent(path, function (data) {
config = JSON.parse(data);
// load available sites
for (var siteIndex in config.sites) {
var siteId = config.sites[siteIndex];
var sitePath = chrome.extension.getURL("sites/" + siteId + "-config.json");
getFileContent(sitePath, function (siteData) {
var site = JSON.parse(siteData);
availableSites[site.hostname] = site;
types[site.hostname] = { 'hostname': site.hostname, 'type': 'site' };
}, function () { });
}
// load sources
for (var sourceIndex in config.sources) {
var sourceId = config.sources[sourceIndex];
var sourcesPath = chrome.extension.getURL("sources/" + sourceId + "-config.json");
getFileContent(sourcesPath, function (sourceData) {
var source = JSON.parse(sourceData);
var tmp = availableSources[source.hostname];
source.refresh = tmp.refresh;
source.init = tmp.init;
availableSources[source.hostname] = source;
types[source.hostname] = { 'hostname': source.hostname, 'type': 'source' };
}, function () { });
}
}, function () { });
}
function checkForSource() {
if (selectedSourceName in availableSources) {
setSelectedSource(selectedSourceName);
} else {
setTimeout(checkForSource, 100);
}
}
function init() {
selectedSourceName = localStorage.getItem("selectedSource");
if (!selectedSourceName) {
// https://developer.chrome.com/extensions/tabs#method-create
var options = { 'url': chrome.runtime.getURL('setup.html') };
chrome.tabs.create(options, function (tab) { });
} else {
checkForSource();
}
initConfig();
}
chrome.runtime.onInstalled.addListener(onInit);
chrome.alarms.onAlarm.addListener(onAlarm);
if (chrome.runtime && chrome.runtime.onStartup) {
chrome.runtime.onStartup.addListener(function () {
init();
startRequest({ scheduleRequest: false, showLoadingAnimation: false });
});
}