forked from stumbleupon/stumblebar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpage.js
469 lines (402 loc) · 12.5 KB
/
page.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
/**
* Handlers for page-related and tab-related functionality
*/
function Page() {
}
/**
* The current su toolbar state
*/
Page.state = {};
/**
* The current tab info
*/
Page.tab = {};
/**
* A cache of fetched SuUrls
*/
Page.urlCache = [];
Page.urlMap = {};
/**
* Get the last known state of the provided tab
*
* @param {Number} tabid Tab ID
* @return {Object} current state of tabid
*/
Page.lastState = function(tabid) {
return Page.state[tabid] || {};
}
/**
* Preload helper, takes an SU url object (usually the next stumble) and preloads that page
*
* @param {SuUrl} url SuUrl object to attempt to preload
*/
Page.preload = function(url) {
Page._prerender.href = url.url;
Page._prefetch.href = url.url;
Page._preload.href = url.url;
debug("Preload", url.url);
}
/**
* Browser icon click handler. Pings the current tab to see if it has rendered.
* If it has, it toggles hidden. If it hasn't, it attempts to stumble.
*
* @param {event} e window.event object
*/
Page.handleIconClick = function(e) {
Page.ping()
.then(function(res) {
return ToolbarEvent.handleRequest(
{
action: 'toggleHidden',
url: {},
data: {}
},
{ tab: res.tab },
function() {}
);
})
.catch(function(res) {
ToolbarEvent.stumble({}, res)
.catch(ToolbarEvent.loginPage);
});
}
/**
* Pings a tabid
*
* @param {Number} tabid Tab ID to ping
* @return {Promise}
*/
Page.ping = function(tabid) {
return new Promise(function(resolve, reject) {
browser.tabs.query({active: true, currentWindow: true}, function(tabs) {
if (!tabs[0])
return;
browser.tabs.sendMessage(tabid || tabs[0].id, {type: "ping", info: tabs[0]}, function(response) {
// Handle pages that we can't inject
if (!response || response.type != 'pong')
reject({tab: {id: tabid || tabs[0].id}, response});
else
resolve({tab: {id: tabid || tabs[0].id}, response});
});
});
});
}
/**
* Get the last url seen by the provided tab id
*
* @param {Number} tabid Tab ID
* @return {SuUrl}
*/
Page.lastUrl = function(tabid) {
return Page.tab[tabid] && Page.tab[tabid].url;
}
/**
* Get the last urlid seen by the provided tab id
*
* @param {Number} tabid Tab ID
* @return {SuUrl}
*/
Page.getUrlId = function(tabid) {
return Page.tab[tabid] && Page.tab[tabid].url && Page.tab[tabid].url.urlid;
}
/**
* Get the last urlid seen by the provided tab id
*
* @param {Number} tabid Tab ID
* @return {SuUrl}
*/
Page.getUrl = function(tabid) {
var url = Page.tab[tabid] && Page.tab[tabid].url && Page.tab[tabid].url.finalUrl // SuUrl
|| Page.tab[tabid] && Page.tab[tabid].info && Page.tab[tabid].info.url // Browser's tab
|| Page.tab[tabid] && Page.tab[tabid].status && Page.tab[tabid].status.url // What we noted
;
if (!url) {
return new Promise(function(resolve, reject) {
browser.tabs.get(tabid, function(tab) {
if (!tab || !tab.id || !tab.url)
return reject(new ToolbarError('Page', 'nourl', Page.tab[tabid]));
resolve(tab.url);
});
});
}
return Promise.resolve(url);
// browser.tabs.get(tabid, function(tab) {
// resolve(tab.url);
// });
}
/**
* Get a SuUrl from the urlCache
*
* @param {String} href The url to fetch from the cache
* @return {Object}
*/
Page.getUrlByHref = function(href) {
return Page.urlMap[href];
}
/**
* Get a SuUrl by urlid from the urlCache. Note that this may return an
* url that was generated in another mode and has that mode's metadata.
*
* @param {String} urlid The public url id
* @param {String} mode The mode
* @return {SuUrl}
*/
Page.getUrlByUrlid = function(urlid, mode) {
return Page.urlMap[mode + ':' + urlid] || Page.urlMap[urlid];
}
/**
* Cleans up url cache by trimming the cache down to 1000 urls
*/
Page.cleanupUrlCache = function() {
if (Page.urlCache.length >= 1e3) {
var errantUrl = Page.urlCache.splice(0, 1)[0];
Page.removeUrlFromUrlCache(errantUrl);
}
}
/**
* Removes a SuUrl from the url cache
*/
Page.removeUrlFromUrlCache = function(url) {
if (!url)
return;
if (url.urlid && url.mode)
delete Page.urlMap[url.urlid];
if (url.urlid)
delete Page.urlMap[url.mode + ':' + url.urlid];
if (url.url)
delete Page.urlMap[url.url];
if (url.finalUrl)
delete Page.urlMap[url.finalUrl];
}
/**
* Note the current SuUrl loaded by the current tabid. Adds url to the url cache, performs cleanup.
*
* @param {Number} tabid Tab ID
* @param {SuUrl} url An SuUrl object
* @return {SuUrl}
*/
Page.note = function(tabid, url, onlynote) {
if (!Page.tab[tabid])
Page.tab[tabid] = {};
if (url.urlid && url.mode)
Page.urlMap[url.mode + ':' + url.urlid] = url;
if (url.urlid)
Page.urlMap[url.urlid] = url;
if (url.url)
Page.urlMap[url.url] = url;
if (url.finalUrl)
Page.urlMap[url.finalUrl] = url;
if (Page.urlCache.indexOf(url) == -1)
Page.urlCache.push(url);
Page.cleanupUrlCache();
return onlynote ? url : Page.tab[tabid].url = url;
}
/**
* Handle URL changes triggered by tab or stumble events
*
* @param {String} href The new uri
* @param {Number} tabid Tab ID
* @return {Promise}
*/
Page.urlChange = function(href, tabid, incog, state) {
browser.tabs.getZoom(tabid, function(zoom) {
browser.tabs.sendMessage(tabid, { zoom: zoom });
});
// Handle http://su/su/{urlid} urls. Stop the request, redirect directly to page, return a promise
webtbPath = href.match(new RegExp("^https?://" + config.baseUrl + config.webtbPath));
if (webtbPath) {
ToolbarEvent._sanity();
var urlid = webtbPath[config.webtbPathNames.urlid];
if (urlid) {
debug('SUPATH MATCH ' + href);
// Stop current page from loading
//browser.tabs.executeScript(tabid, {
// code: "window.stop();",
//});
//browser.tabs.update(tabid, { url: 'about:blank' });
if (state != 'complete')
return;
// Override {urlid} if we have a returl (we're coming from a signup)
if (Page.state[tabid] && Page.state[tabid].returl) {
var url = Page.state[tabid].returl;
browser.tabs.update(tabid, { url: url });
ToolbarEvent.unhideToolbar();
return ToolbarEvent._buildResponse({ hidden: false });
}
return Promise.resolve(Page.getUrlByUrlid(urlid, config.mode) || ToolbarEvent.api.getUrlByUrlid(urlid))
.then(function(url) {
browser.tabs.update(tabid, { url: url.url });
ToolbarEvent.unhideToolbar();
return ToolbarEvent._buildResponse({ url: url, hidden: false })
})
.catch(ToolbarEvent.error);
;
}
}
suPath = href.match(new RegExp("^https?://" + config.baseUrl + '/logout'));
if (suPath) {
debug('LOGGING OUT');
return;
}
// If we're hitting http://su/..., revalidate our auth
suPath = href.match(new RegExp("^https?://" + config.baseUrl + '/(.*)'));
if (suPath && !config.authed) {
if (suPath)
ToolbarEvent._sanity();
debug('SUPATH SANITY CHECK ' + href);
}
// If we're hitting http://su/convo/..., set the conversation id on the page state
convoPath = href.match(new RegExp("^https?://" + config.baseUrl + config.convoPath));
if (convoPath) {
Page.state[tabid] = { convo: convoPath[config.convoPathNames.convoid] };
debug('CONVO ON ' + tabid);
}
// Attempted to pull the current url from the page cache or SU api. If we can,
// report it to the toolbar in the current tab
return Promise
.resolve(Page.getUrlByHref(href))
.then(function(url) {
return url && Page.getUrlByUrlid(url.urlid, config.mode);
})
.then(function(url) {
return url || (Page.tab[tabid].stumbling && Page.getUrlByUrlid(Page.tab[tabid].stumbling, config.mode));
})
.then(function(url) {
//return url || (!incog && ToolbarEvent.api.getUrlByHref(href)) || Promise.reject(new ToolbarError('Page', 'nourl-incog', Page.tab[tabid])); // No URL fetching in private mode
return url || Promise.reject(new ToolbarError('Page', 'nourl', Page.tab[tabid])); // No URL fetching in general
})
.then(function(url) {
if (!incog)
Page.note(tabid, url, Page.tab[tabid].status.url != href);
if (!(Page.tab[tabid] || {}).status || Page.tab[tabid].status.url == href)
browser.tabs.sendMessage(tabid, { url: url }, function() {});
})
.catch(function(error) {
Page.tab[tabid].url = {};
if (!(Page.tab[tabid] || {}).status || Page.tab[tabid].status.url == href)
browser.tabs.sendMessage(tabid, { url: { url: href } }, function() {});
});
;
}
/**
* Handle tab loading and complete messages
*
* @param {Number} tabid Tab ID
* @param {Object} info Tab info object
* @param {Object} tab The new state of the tab
*/
Page.handleTabUpdate = function(tabid, info, tab) {
var shouldLog = false;
shouldLog && debug('update', tabid, info, tab);
Page.ping().catch(function() {});
if (!Page.tab[tabid])
Page.tab[tabid] = {url: {}, status: {state: tab.incognito ? 'incog' : 'ready'}};
if (info.status == "loading") {
if (!tab.incognito) {
Page.tab[tabid].status = { state: info.status, url: tab.url };
}
// User is changing the URL
if (Page.tab[tabid].url && Page.tab[tabid].url.url != tab.url && !Page.tab[tabid].stumbling)
Page.tab[tabid].url = {}
Page.urlChange(info.url || tab.url, tabid, tab.incognito, info.status);
}
if (info.status == "complete") {
if (!tab.incognito) {
Page.tab[tabid].status = { state: info.status, url: tab.url };
Page.tab[tabid].info = tab;
if (Page.tab[tabid].url && (!Page.tab[tabid].stumbling || Page.tab[tabid].url.urlid == Page.tab[tabid].stumbling))
Page.tab[tabid].url.finalUrl = info.url || tab.url;
// Fudge stumbling timeout to handle meta refreshes and youtube
if (Page.stumblingTimeout)
window.clearTimeout(Page.stumblingTimeout);
Page.stumblingTimeout = window.setTimeout(function() {
if (Page.tab[tabid].stumbling && (!Page.tab[tabid].url.urlid || Page.tab[tabid].url.urlid == Page.tab[tabid].stumbling))
Page.tab[tabid].stumbling = false;
}, 1000);
}
Page.urlChange(info.url || tab.url, tabid, tab.incognito, info.status);
}
}
/**
* Does nothing, but in the future can be used to unload the stumblebar
* from contexts to save memory
*/
Page.handleTabSwitch = function(state) {
if (config.unloadNonVisibleBars) {
browser.tabs.query({}, function(tabs) {
tabs.forEach(function (tab) {
// We have to keep tabs persistent in incognito because we don't retain state for them
if (tab.incognito)
return;
if (state.tabId == tab.id)
browser.tabs.sendMessage(tab.id, {type: 'add'});
else
browser.tabs.sendMessage(tab.id, {type: 'remove'});
});
});
}
}
Page.handleWindowSwitch = function(state) {
browser.tabs.query({active: true, currentWindow: true}, function(tabs) {
if (tabs && tabs[0] && tabs[0].id)
Page.handleTabSwitch({tabId: tabs[0].id})
})
}
/**
* Clean up tab states and caches on tab close
*
* @param {Number} tabid Tab ID
*/
Page.handleTabClose = function(tabid) {
if (Page.state[tabid])
delete Page.state[tabid];
if (Page.tab[tabid]) {
Page.removeUrlFromUrlCache(Page.lastUrl(tabid));
delete Page.tab[tabid];
}
}
Page.handleZoom = function(zoom) {
browser.tabs.sendMessage(zoom.tabId, { zoom: zoom.newZoomFactor });
}
Page.handleFreshen = function() {
browser.tabs.query({}, function(tabs) {
tabs.forEach(function(tab) {
try {
browser.tabs.executeScript(tab.id, {
code: "" +
"if (document.getElementById('discoverbar')) {" +
" document.documentElement.removeChild(document.getElementById('discoverbar'), document.documentElement); " +
"}" +
"if (document.getElementById('__su__toolbar')) { " +
" document.body.removeChild(document.getElementById('__su__toolbar'), document.body); " +
" try { document.body.style.marginTop = 0; } catch (e) {}" +
"}"
});
} catch(e) {}
});
});
}
/**
* Initialize page handlers
*/
Page.init = function() {
// listen to tab URL changes
browser.tabs.onUpdated.addListener(Page.handleTabUpdate);
// listen to tab switching
browser.tabs.onActivated.addListener(Page.handleTabSwitch);
browser.windows.onFocusChanged.addListener(Page.handleWindowSwitch);
browser.tabs.onRemoved.addListener(Page.handleTabClose);
browser.tabs.onZoomChange.addListener(Page.handleZoom);
browser.browserAction.onClicked.addListener(Page.handleIconClick);
browser.runtime.onInstalled.addListener(Page.handleFreshen);
Page._prerender = document.createElement('link');
Page._prefetch = document.createElement('link');
Page._preload = document.createElement('link');
Page._prerender.rel = 'prerender';
Page._prefetch.rel = 'prefetch';
Page._preload.rel = 'preload';
document.body.appendChild(Page._prerender);
document.body.appendChild(Page._prefetch);
document.body.appendChild(Page._preload);
}
Page.init();