-
Notifications
You must be signed in to change notification settings - Fork 5
/
background.js
501 lines (449 loc) · 19 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
// Set fluidDBHost to 'localhost:9000' if testing against a local FluidDB.
var fluidDBHost = 'fluiddb.fluidinfo.com';
var twitterUserURLRegex = new RegExp('^https?://twitter.com/#!/(\\w+)$');
var linkRegex = /^\w+:\/\//;
var currentSelection = null;
var tabThatCreatedCurrentSelection = null;
var maxSelectionLengthToLookup = 200;
// Tabs that were created as a part of the OAuth login process and which
// are candidates for auto-deletion (when OAuth authorization is granted).
var oauthAutoCloseTabs = {};
// Things we consider as possibly being an about value that corresponds to
// something that's being followed, e.g., '@username' or 'wordnik.com'.
var followeeRegex = /^@?([\w\.]+)$/;
// ----------------- Settings -----------------
var settings = new Store('settings', {
notificationTimeout: 30,
sidebarSide: 'right',
sidebarWidth: 300
});
var anonFluidinfoAPI = fluidinfo({instance: 'http://' + fluidDBHost + '/'});
var absoluteHref = function(linkURL, docURL){
/*
* Turn a possibly relative linkURL (the href="" part of an <a> tag)
* into something absolute. If linkURL does not specify a host, use
* the one in the document's URL (given in docURL).
*/
var url;
if (linkRegex.test(linkURL)){
// The link looks absolute (i.e., http:// or https:// or ftp://).
url = linkURL;
}
else if (linkURL.slice(0, 7).toLowerCase() === 'mailto:'){
url = linkURL.split(':')[1].toLowerCase();
}
else {
// A relative link. Prepend the current document protocol & host+port.
var parts = docURL.split('/');
if (linkURL.charAt(0) === '/'){
url = parts[0] + '//' + parts[2] + linkURL;
}
else {
url = parts[0] + '//' + parts[2] + '/' + linkURL;
}
}
return url;
};
var createSelectionNotification = function(about){
displayNotification({
about: about,
tabId: 'selection'
});
};
var removeSelectionNotification = function(){
deleteNotificationForTab('selection');
var port = chrome.tabs.connect(tabThatCreatedCurrentSelection, {name: 'sidebar'});
port.postMessage({
action: 'hide sidebar'
});
tabThatCreatedCurrentSelection = null;
};
// Listen for incoming messages from the tab content script or the sidebar
// iframe script with events (link mouseover, link mouseout, selection
// set/cleared, etc).
chrome.extension.onConnect.addListener(function(port){
if (port.name === 'content-script'){
port.onMessage.addListener(function(msg){
if (typeof msg.selection !== 'undefined'){
if (currentSelection === null || msg.selection !== currentSelection){
chrome.tabs.getSelected(null, function(tab){
tabThatCreatedCurrentSelection = tab.id;
currentSelection = msg.selection;
removeContextMenuItemsByContext('selection');
addContextMenuItem(currentSelection, 'selection');
if (currentSelection.length < maxSelectionLengthToLookup){
createSelectionNotification(currentSelection);
}
});
}
}
else if (msg.selectionCleared){
if (currentSelection !== null){
currentSelection = null;
removeContextMenuItemsByContext('selection');
removeSelectionNotification();
}
}
else if (msg.mouseout){
// The mouse moved off a link so clear all link-related context
// menu items.
removeContextMenuItemsByContext('link');
}
else if (msg.mouseover){
// The mouse moved over a new link. Remove existing link-related
// context menu items.
removeContextMenuItemsByContext('link');
var url;
// There are <a> tags with no href in them.
if (msg.linkURL){
url = absoluteHref(msg.linkURL, msg.docURL);
addContextMenuItem(url, 'link');
}
// And there are <a> tags with no text in them.
if (msg.text){
if (msg.linkURL){
url = absoluteHref(msg.linkURL, msg.docURL);
var match = twitterUserURLRegex.exec(url);
if (match !== null){
// We can test against match[1] as the regexp captures the username,
// so if it matched, match[1] will always be defined.
var name = match[1];
var lower = name.toLowerCase();
if (lower !== 'following' && lower !== 'followers'){
// Update with @name
addContextMenuItem('@' + name, 'link');
// Look for "fullname @username" text.
var spaceAt = msg.text.indexOf(' @');
if (spaceAt !== -1){
// Note that Twitter now put U-200F (RIGHT-TO-LEFT MARK) after
// people's names, and we need to zap it. You'll know if this
// creeps back in, as clicking on the link in the context menu
// will take you to something ending in %E2%80%8F (the UTF-8
// for that codepoint).
var fullname = msg.text.slice(0, spaceAt).replace(/^\s+|[\s\u200F]+$/g, '');
addContextMenuItem(fullname, 'link');
}
}
return;
}
}
addContextMenuItem(msg.text, 'link');
}
}
else if (msg.injectSidebarJS){
chrome.tabs.getSelected(null, function(tab){
chrome.tabs.executeScript(tab.id, {
allFrames: true,
file: 'iframe.js'
});
});
}
else {
console.log('Unrecognized message sent by content script:');
console.log(msg);
}
});
}
else if (port.name === 'sidebar-iframe'){
// Process messages coming from the sidebar iframe.
port.onMessage.addListener(function(msg){
chrome.tabs.getSelected(null, function(tab){
var sidebarPort = chrome.tabs.connect(tab.id, {name: 'sidebar'});
if (msg.action === 'hide sidebar'){
sidebarPort.postMessage({
action: 'hide sidebar'
});
}
else if (msg.action === 'oauth login'){
chrome.tabs.create({
index: tab.index + 1,
openerTabId: tab.id,
url: 'http://' + lovemedoHost + '/login/fluidinfo/'
}, function(createdTab){
// Mark the tab as something we want to close automatically.
oauthAutoCloseTabs[createdTab.id] = port;
});
}
else if (msg.action === 'open'){
chrome.tabs.update(tab.id, {
url: absoluteHref(msg.linkURL, msg.docURL)
});
}
else {
console.log('Unrecognized message sent by sidebar iframe:');
console.log(msg);
}
});
});
}
else {
console.log('Got connection on port with unknown name.');
console.log(port);
}
});
// ------------------- Listen for requests.
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse){
if (request.action === 'get-settings'){
sendResponse(settings.toObject());
}
else if (request.action === 'update-current-tab-url'){
chrome.tabs.update(sender.tab.id, {
url: request.url
});
}
else {
console.log('Unknown request received by background page:');
console.log(request);
}
}
);
// -------------------- Tag values for current tab's URL --------------------
// valuesCache is keyed by tab id, values are objects with a tagValueHandler
// (as returned by makeTagValueHandler) and a JS object holding the tag paths
// on the object.
var valuesCache = {};
var deleteValuesCacheForTab = function(tabId){
if (valuesCache[tabId] !== undefined){
valuesCache[tabId].tagValueHandler.ignoreFutureResults();
delete valuesCache[tabId];
}
};
var notifications = {};
var timeouts = {};
var createNotification = function(tabId){
if (window.webkitNotifications){
if (! notifications[tabId]){
var notification = window.webkitNotifications.createHTMLNotification('notification.html');
notification.show();
notifications[tabId] = notification;
notification.onclose = function(){
deleteNotificationForTab(tabId);
};
}
}
else {
console.log("Notifications are not supported for this browser/OS version yet.");
}
};
var deleteNotificationForTab = function(tabId){
if (notifications[tabId] !== undefined){
if (timeouts[tabId] !== undefined){
clearTimeout(timeouts[tabId]);
delete timeouts[tabId];
}
notifications[tabId].cancel();
delete notifications[tabId];
}
};
var displayNotification = function(options){
var tabId = options.tabId;
var about = options.about;
deleteValuesCacheForTab(tabId);
deleteNotificationForTab(tabId);
valuesCache[tabId] = {
tagPaths: {}, // Will be filled in in onSuccess, below.
tagValueHandler: makeTagValueHandler({
about: about,
session: anonFluidinfoAPI
})
};
var onError = function(result){
// Ignore 404 errors, which just indicate there are no tags for the object.
if (result.status != 404){
console.log('Got error from Fluidinfo fetching tags for about ' + about);
console.log(result);
}
};
var showFolloweeTags = function(result){
var onError = function(result){
console.log('Got error from Fluidinfo fetching anon/follows tag.');
console.log(result);
};
var onSuccess = function(following){
var followees = {};
var i;
// Get the name part of all about values that look like "@name"
// or a domain, as these can be considered a user that this user
// is following.
var userIsFollowingSomething = false;
var data = following.data;
for (i = 0; i < data.length; i++){
var match = followeeRegex.exec(data[i]['fluiddb/about']);
if (match !== null){
var what = match[1].toLowerCase();
if (what !== 'anon'){
followees[what] = true;
userIsFollowingSomething = true;
}
}
}
if (!userIsFollowingSomething){
return;
}
// Look at the tags on the object and get the ones that have
// namespaces that correspond to things the user is following
// and that we know how to display in a custom way.
var tagPaths = result.data.tagPaths;
var neededTags = [];
var knownPrefixes = [];
var seenPrefixes = {};
for (i = 0; i < tagPaths.length; i++){
var tagPath = tagPaths[i];
var namespace = tagPath.slice(0, tagPath.indexOf('/'));
var namespaceWithSlash = namespace + '/';
if (followees.hasOwnProperty(namespace) &&
customDisplayPrefixes.hasOwnProperty(namespaceWithSlash)){
// This is one of the anon user's followees tags, and we have a custom
// display function for it.
neededTags.push(tagPath);
if (!seenPrefixes.hasOwnProperty(namespaceWithSlash)){
knownPrefixes.push(namespaceWithSlash);
seenPrefixes[namespaceWithSlash] = true;
}
}
}
if (knownPrefixes.length > 0 && neededTags.length > 0){
valuesCache[tabId].tagValueHandler.get({
onError: function(response){
console.log('Fluidinfo API call failed:');
console.log(response);
},
onSuccess: function(){
createNotification(tabId, 'followees');
var timeout = settings.get('notificationTimeout');
if (timeout){
var hide = function(){
deleteNotificationForTab(tabId, 'followees');
};
if (! timeouts.hasOwnProperty(tabId)){
timeouts[tabId] = {};
}
timeouts[tabId] = setTimeout(hide, timeout * 1000);
}
var populate = function(){
var found = false;
var info = tabId + '_followees';
chrome.extension.getViews({type: 'notification'}).forEach(function(win){
// Populate any new notification window (win._lovemedo_info undefined)
// or re-populate if win._lovemedo_info is the current tabId (in which
// case we are processing a reload).
if (!found &&
(win._lovemedo_info === undefined || win._lovemedo_info === info)){
if (win.populate){
win._lovemedo_info = info;
win.populate({
about: about,
knownPrefixes: knownPrefixes,
tabId: (tabId === 'selection' ? tabThatCreatedCurrentSelection : tabId),
tagValueHandler: valuesCache[tabId].tagValueHandler
});
found = true;
}
}
});
if (!found){
setTimeout(populate, 50);
}
};
setTimeout(populate, 50);
},
tags: neededTags
});
}
};
// Get the about values from the objects the anon user follows.
anonFluidinfoAPI.query({
select: ['fluiddb/about'],
where: ['has anon/follows'],
onError: onError,
onSuccess: onSuccess
});
};
var onSuccess = function(result){
showFolloweeTags(result);
};
// Pull back tag paths on the object for the current about value. Do
// this as the anonymous user to make sure we don't send identifying
// info with lookups. Only publicly readable tags will be returned as
// a result.
anonFluidinfoAPI.api.get({
path: ['about', valueUtils.lowercaseAboutValue(about)],
onError: onError,
onSuccess: onSuccess
});
};
chrome.tabs.onRemoved.addListener(function(tabId, changeInfo, tab){
deleteValuesCacheForTab(tabId);
deleteNotificationForTab(tabId);
if (tabId === tabThatCreatedCurrentSelection){
removeSelectionNotification();
}
});
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
if (changeInfo.status === 'loading'){
if (oauthAutoCloseTabs.hasOwnProperty(tabId)){
// This tab is a candidate for automatic closing after successful
// OAuth login.
var dashboardURLPrefix = 'http://' + lovemedoHost;
if (tab.url.slice(0, 39) === 'https://api.twitter.com/oauth/authorize'){
// We're in the intermediate state, the fate of the OAuth login
// attempt is still unknown. Do nothing.
}
else if (tab.url.slice(0, dashboardURLPrefix.length) === dashboardURLPrefix){
// We're loading a valid loveme.do URL, so the OAuth
// approval was granted. Remove the OAuth tab. Tell the tab
// that made it to reload its sidebar now that login has
// succeeded, and make it the active tab so the user is
// returned to what they were originally looking at.
var port = oauthAutoCloseTabs[tabId];
port.postMessage({action: 'reload'});
chrome.tabs.remove(tabId);
chrome.tabs.update(tab.openerTabId, {active: true});
delete oauthAutoCloseTabs[tabId];
}
else {
// The tab has gone on to do something else (i.e., it is no
// longer doing oauth stuff). Unmark it as a candidate for
// automatic deletion.
delete oauthAutoCloseTabs[tabId];
}
}
else {
displayNotification({
about: tab.url,
tabId: tabId
});
}
}
});
chrome.tabs.onRemoved.addListener(function(tabId, removeInfo){
// An OAuth login tab that's being closed should no longer be marked
// for auto deletion.
if (oauthAutoCloseTabs.hasOwnProperty(tabId)){
delete oauthAutoCloseTabs[tabId];
}
});
// Inject our content scripts into existing tabs, skipping chrome's own
// tabs (trying to inject into them gives a console error message).
chrome.tabs.query({}, function(tabs){
var files = ['shortcut.js', 'sidebar.js', 'content.js'];
for (var i = 0; i < tabs.length; i++){
var tab = tabs[i];
if (! valueUtils.isChromeURL(tab.url)){
for (var j = 0; j < files.length; j++){
chrome.tabs.executeScript(tab.id, {
file: files[j]
});
}
}
}
});
// Set up the click listener on the extension icon.
chrome.browserAction.onClicked.addListener(function(tab){
var port = chrome.tabs.connect(tab.id, {name: 'sidebar'});
port.postMessage({
about: (currentSelection === null) ? tab.url : currentSelection,
action: 'toggle sidebar'
});
});