-
Notifications
You must be signed in to change notification settings - Fork 16
/
conex-background.js
535 lines (449 loc) · 17.6 KB
/
conex-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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
const imageQuality = 8;
const defaultCookieStoreId = 'firefox-default';
const privateCookieStorePrefix = 'firefox-private';
const newTabs = new Set();
const newTabsUrls = new Map();
const newTabsTitles = new Map();
let lastCookieStoreId = defaultCookieStoreId;
//////////////////////////////////// exported functions (es6 import / export stuff is not supported in webextensions)
function interceptRequests() {
if(typeof browser.webRequest == 'object') {
console.info('set up request interceptor');
browser.webRequest.onBeforeRequest.addListener(
showContainerSelectionOnNewTabs,
{ urls: ["<all_urls>"], types: ["main_frame"] },
["blocking"]
);
}
}
function activateTab(tabId) {
browser.tabs.update(Number(tabId), {active: true}).then(tab => {
browser.windows.update(tab.windowId, {focused: true});
}, e => console.error(e));
}
function refreshSettings() {
readSettings = _refreshSettings();
}
function closeTab(tabId) {
browser.tabs.remove(Number(tabId));
}
function newTabInCurrentContainer(url) {
browser.tabs.query({active: true, windowId: browser.windows.WINDOW_ID_CURRENT}).then(tabs => {
cookieStoreId = tabs.length > 0 ? tabs[0].cookieStoreId : defaultCookieStoreId;
const createProperties = {
cookieStoreId: cookieStoreId
};
if(url) {
createProperties['url'] = url
}
browser.tabs.create(createProperties).catch(e => console.error(e));
}, e => console.error(e));
}
async function getTabsByContainer() {
await readSettings;
const containersTabsMap = {};
const tabs = browser.tabs.query({});
let bookmarkUrls = [];
if(settings['search-bookmarks']) {
const bookmarks = browser.bookmarks.search({});
try {
bookmarkUrls = (await bookmarks).filter(b => b.url != undefined).map(b => b.url.toLowerCase());
} catch (e) {
console.error('error querying bookmarks: ', e);
}
}
for(const tab of (await tabs).sort((a,b) => b.lastAccessed - a.lastAccessed)) {
const url = tab.url || "";
const thumbnailElement = createTabElement(tab, bookmarkUrls.indexOf(url.toLowerCase()) >= 0);
if (!containersTabsMap[tab.cookieStoreId]) {
containersTabsMap[tab.cookieStoreId] = [];
}
containersTabsMap[tab.cookieStoreId].push(thumbnailElement);
}
return containersTabsMap;
}
async function restoreTabContainersBackup(tabContainers, windows) {
const identities = createMissingTabContainers(tabContainers);
for (const tabs of windows) {
const w = browser.windows.create({});
for (const tab of tabs) {
if (!isBlessedUrl(tab.url)) {
continue;
}
let cookieStoreId = defaultCookieStoreId;
if (tab.container) {
cookieStoreId = (await identities).get(tab.container.toLowerCase());
}
const newTab = browser.tabs.create({ url: tab.url, cookieStoreId: cookieStoreId, windowId: (await w).id, active: false });
// we need to wait for the first onUpdated event before discarding, otherwise the tab is in limbo
const onUpdatedHandler = async function(tabId, changeInfo) {
if (tabId == (await newTab).id && changeInfo.status == "complete") {
browser.tabs.onCreated.removeListener(onUpdatedHandler);
browser.tabs.discard(tabId);
}
}
browser.tabs.onUpdated.addListener(onUpdatedHandler);
console.info(`creating tab ${tab.url} in container ${(await newTab).cookieStoreId} (cookieStoreId: ${cookieStoreId})`);
}
}
}
async function switchToContainer(cookieStoreId) {
const tabs = await browser.tabs.query({windowId: browser.windows.WINDOW_ID_CURRENT, cookieStoreId: cookieStoreId});
if (tabs.length == 0) {
const allTabs = await browser.tabs.query({windowId: browser.windows.WINDOW_ID_CURRENT});
if(allTabs.length > 0) {
browser.tabs.create({ openerTabId: allTabs[0].id, cookieStoreId: cookieStoreId, active: true });
} else {
console.error("did not find any active tab in window with id: ", browser.windows.WINDOW_ID_CURRENT);
}
} else {
const lastAccessedTabs = tabs.sort((a, b) => b.lastAccessed - a.lastAccessed);
// Try to switch to an unpinned tab, as switching a to pinned tab
// will not update the visible tabs
for (const tab of lastAccessedTabs) {
if (!tab.pinned) {
browser.tabs.update(tab.id, { active: true });
browser.windows.update(tab.windowId, { focused: true });
return;
}
}
// All tabs in this container are pinned. Just switch to first one
browser.tabs.update(lastAccessedTabs[0].id, { active: true });
browser.windows.update(lastAccessedTabs[0].windowId, { focused: true });
}
}
function openLinkInContainer(link, cookieStoreId) {
browser.tabs.create({url: link, cookieStoreId: cookieStoreId});
}
async function showCurrentContainerTabsOnly(activeTabId) {
await readSettings;
if(!settings["hide-tabs"] ) {
return;
}
const activeTab = await browser.tabs.get(activeTabId);
if(activeTab.pinned) {
return;
}
showContainerTabsOnly(activeTab.cookieStoreId);
}
async function showContainerTabsOnly(cookieStoreId) {
const allTabs = await browser.tabs.query({windowId: browser.windows.WINDOW_ID_CURRENT});
const visibleTabs = allTabs.filter(t => t.cookieStoreId == cookieStoreId).map(t => t.id);
const hiddenTabs = allTabs.filter(t => t.cookieStoreId != cookieStoreId).map(t => t.id);
// console.debug('visible tabs', visibleTabs, 'hidden tabs', hiddenTabs);
try {
showTabs(visibleTabs);
hideTabs(hiddenTabs);
} catch(e) {
console.error('error showing / hiding tabs', e);
}
}
async function openContainerSelector(url, title) {
const tab = await browser.tabs.create({
active: true,
cookieStoreId: defaultCookieStoreId,
url: url,
});
newTabsTitles.set(tab.id, title);
}
//////////////////////////////////// end of exported functions (again: es6 features not supported yet
const menuId = function(s) {
return `menu_id_for_${s}`;
}
const openInDifferentContainer = function(cookieStoreId, tab) {
const tabProperties = {
active: true,
cookieStoreId: cookieStoreId,
index: tab.index+1
};
if(tab.url != 'about:newtab' && tab.url != 'about:blank') {
tabProperties.url = tab.url;
}
browser.tabs.create(tabProperties);
browser.tabs.remove(tab.id);
}
const createMissingTabContainers = async function(tabContainers) {
const colors = ["blue", "turquoise", "green", "yellow", "orange", "red", "pink", "purple"];
const identities = await browser.contextualIdentities.query({});
const nameCookieStoreIdMap = new Map(identities.map(identity => [identity.name.toLowerCase(), identity.cookieStoreId]));
const promises = [];
for(const tabContainer of tabContainers) {
if(!nameCookieStoreIdMap.get(tabContainer.toLowerCase())) {
console.info(`creating tab container ${tabContainer}`);
const newIdentity = {name: tabContainer, icon: 'circle', color: colors[Math.floor(Math.random() * (8 - 0)) + 0]};
const identity = await browser.contextualIdentities.create(newIdentity);
nameCookieStoreIdMap.set(identity.name.toLowerCase(), identity.cookieStoreId);
}
}
return nameCookieStoreIdMap;
};
const isBlessedUrl = function(url) {
return url.startsWith('http') || url.startsWith('about:blank') || url.startsWith('about:newtab');
}
const showTabs = async function(tabIds) {
browser.tabs.show(tabIds);
}
const hideTabs = async function(tabIds) {
if(tabIds.length == 0) {
return;
}
browser.tabs.hide(tabIds);
}
const updateLastCookieStoreId = function(activeInfo) {
browser.tabs.get(activeInfo.tabId).then(tab => {
if((tab.url != 'about:blank' || (tab.url == 'about:blank' && tab.cookieStoreId != defaultCookieStoreId))
&& tab.cookieStoreId != lastCookieStoreId
&& !tab.cookieStoreId.startsWith(privateCookieStorePrefix)) {
console.debug(`cookieStoreId changed from ${lastCookieStoreId} -> ${tab.cookieStoreId}`);
lastCookieStoreId = tab.cookieStoreId;
}
}, e => console.error(`error setting cookieStoreId: ${e}`));
};
const storeScreenshot = async function(tabId, changeInfo, tab) {
if(changeInfo.status != "complete" || tab.url == 'about:blank' || tab.url == browser.extension.getURL('container-selector.html')) {
return;
}
readSettings;
const cleanedUrl = cleanUrl(tab.url);
try {
let imageData = null;
if(settings['create-thumbnail']) {
console.debug(`capturing tab for ${cleanedUrl}`);
imageData = await browser.tabs.captureTab(tab.id, { format: 'jpeg', quality: imageQuality });
console.debug(` capturing for ${cleanedUrl} finished`);
}
if(settings['show-favicons'] || settings['create-thumbnail']) {
console.debug(` storing captured image for tab for ${cleanedUrl}`);
// await browser.storage.local.set({ [cleanedUrl]: { thumbnail: imageData, favicon: tab.favIconUrl } });
console.debug(` succesfully created thumbnail for ${cleanedUrl}`);
}
// const favIconKey = `favicon:${cleanedUrl.split("/")[0]}`;
// browser.storage.local.set({ [favIconKey]: { favicon: tab.favIconUrl } });
} catch(e) {
console.error(`error creating tab screenshot: ${e}`);
}
};
const handleSettingsMigration = async function(details) {
await readSettings;
const currentVersion = 4;
if(settings['settings-version'] == currentVersion) {
return;
}
// old setting or first install: open the setting page
if (settings['settings-version'] == undefined) {
const settings = ['create-thumbnail', 'hide-tabs', 'search-bookmarks', 'search-history'];
for(let setting of settings) {
const settingId = 'conex/settings/' + setting;
console.debug(`setting ${settingId} to false`);
try {
browser.storage.local.set({ [settingId]: false });
} catch(e) {
console.error(`error persisting ${settingId}: ${e}`)
}
}
}
// setting version 1: tabHide was not optional
if(settings['settings-version'] == 1) {
try {
console.log("migrating settings from version 1")
const tabs = await browser.tabs.query({});
await browser.tabs.show(tabs.map(t => t.id));
await browser.storage.local.set({ 'conex/settings/hide-tabs': false });
await browser.permissions.remove({permissions: ['tabHide', 'notifications']});
await browser.storage.local.set({ 'conex/settings/settings-version': currentVersion });
} catch(e) {
console.error(`error persisting settings: ${e}`)
}
}
// setting version 2: no notifications necessary anymore
if(settings['settings-version'] == 2) {
try {
await browser.permissions.remove({permissions: ['notifications']});
await browser.storage.local.set({ 'conex/settings/settings-version': currentVersion });
} catch(e) {
console.error(`error persisting settings: ${e}`)
}
}
// setting version 3: no notifications necessary anymore
if(settings['settings-version'] == 3) {
try {
await browser.storage.local.set({ 'conex/settings/settings-version': currentVersion });
} catch(e) {
console.error(`error persisting settings: ${e}`)
}
}
try {
await browser.storage.local.set({ 'conex/settings/settings-version': currentVersion });
} catch (e) {
console.error(`error persisting ${settingId}: ${e}`)
}
refreshSettings();
await readSettings;
browser.runtime.openOptionsPage();
}
const showContainerSelectionOnNewTabs = async function(requestDetails) {
if(requestDetails.tabId < 0) {
return;
}
const tab = browser.tabs.get(requestDetails.tabId);
if ((!requestDetails.originUrl || requestDetails.originUrl == browser.extension.getURL("")) &&
newTabs.has(requestDetails.tabId) && requestDetails.url.startsWith('http')) {
if(settings['show-container-selector']) {
console.debug('is new tab', newTabs.has(requestDetails.tabId), requestDetails, (await tab));
newTabsUrls.set(requestDetails.tabId, requestDetails.url);
return { redirectUrl: browser.extension.getURL("container-selector.html") };
} else {
console.debug('re-opening tab in ', lastCookieStoreId, (await tab));
browser.tabs.create({
active: (await tab).active,
openerTabId: Number(requestDetails.tabId),
cookieStoreId: lastCookieStoreId,
url: requestDetails.url
});
browser.tabs.remove(Number(requestDetails.tabId));
return { cancel: true };
}
} else {
return { cancel: false };
}
};
const createContainerSelectorHTML = async function() {
const main = document.body.appendChild($e('div', {id: 'main'}, [
$e('h2', { id: 'title' }),
$e('span', {content: 'open in:'}),
$e('div', {id: 'tabcontainers'}),
$e('tt', { id: 'url' })
]));
document.body.appendChild(main);
const tabContainers = $1("#tabcontainers");
await renderTabContainers(tabContainers, lastCookieStoreId);
const src = $1('#main').innerHTML;
document.body.removeChild($1('#main'));
return src.replace(/(\r\n|\n|\r)/gm,"");
}
const fillContainerSelector = async function(details) {
if(details.url == browser.extension.getURL("container-selector.html")) {
const url = newTabsUrls.get(details.tabId).replace(/'/g, "\\\'");
newTabsUrls.delete(details.tabId);
const title = newTabsTitles.get(details.tabId) ? newTabsTitles.get(details.tabId) : '';
newTabsTitles.delete(details.tabId);
browser.tabs.executeScript(details.tabId, {code:
`const port = browser.runtime.connect(); \
document.querySelector('#main').innerHTML = '${await createContainerSelectorHTML()}'; \
document.querySelector('#title').innerHTML = '${title}'; \
document.querySelector('#url').innerHTML = '${url}'; \
document.title = '${url}'; \
for(const ul of document.querySelectorAll('#tabcontainers ul')) { \
const post = _ => port.postMessage({tabId: '${details.tabId}', url: '${url}', container: ul.id});
ul.addEventListener('click', post);
ul.addEventListener('keypress', e => {
if(e.key == 'Enter') { post(); }
});
}`});
browser.history.deleteUrl({url: browser.extension.getURL("container-selector.html")});
}
}
const closeIfReopened = async function(tab) {
if(!settings['close-reopened-tabs']) {
return;
}
const title = tab.title;
const index = tab.index;
const potentialOpenerIndex = index - 1;
if(potentialOpenerIndex < 0) {
return;
}
try {
const potentialOpeners = await browser.tabs.query({index: potentialOpenerIndex});
if(potentialOpeners.length > 0) {
if(potentialOpeners[0].url.includes(title)) {
console.info("detected re-opening of", potentialOpeners[0], " ... closing original tab");
await browser.tabs.remove(potentialOpeners[0].id);
showCurrentContainerTabsOnly(tab.id);
}
}
} catch(e) { console.debug(`error closing reopened tab with index: ${potentialOpenerIndex}, url: ${title}: ${e}`); }
}
const openIncognito = async function(url) {
const windows = await browser.windows.getAll();
for(const window of windows) {
if(window.incognito) {
await browser.windows.update(window.id, {focused: true});
try {
await browser.tabs.create({
active: true,
url: url,
windowId: window.id});
console.debug("incognito tab created");
} catch(e) { console.error("error creating new tab: ", e) };
return;
}
}
try {
browser.windows.create({
url: url,
incognito: true
})} catch(e) { console.error("error creating private window: ", e)};
}
browser.runtime.onConnect.addListener(function(p){
p.onMessage.addListener(function(msg) {
if(msg.container == "firefox-private") {
openIncognito(msg.url).then(browser.tabs.remove(Number(msg.tabId)));
} else {
browser.tabs.create({
active: true,
openerTabId: Number(msg.tabId),
cookieStoreId: msg.container,
url: msg.url
}).then(_ => browser.tabs.remove(Number(msg.tabId)),
e => console.error("error creating new tab: ", e));
}
});
});
/////////////////////////// setup listeners
browser.runtime.onInstalled.addListener(handleSettingsMigration);
browser.webNavigation.onCompleted.addListener(fillContainerSelector);
browser.tabs.onCreated.addListener(tab => {
if(tab.url == 'about:newtab' && tab.openerTabId == undefined && tab.cookieStoreId == defaultCookieStoreId && lastCookieStoreId != defaultCookieStoreId) {
openInDifferentContainer(lastCookieStoreId, tab);
}
});
browser.tabs.onCreated.addListener(tab => {
if(tab.url == 'about:blank') {
closeIfReopened(tab);
}
});
browser.tabs.onCreated.addListener(tab => {
if(tab.url == 'about:blank' && tab.openerTabId == undefined && tab.cookieStoreId == defaultCookieStoreId) {
newTabs.add(tab.id);
}
});
browser.windows.onFocusChanged.addListener(windowId => {
browser.tabs.query({active: true, windowId: windowId}).then(tabs => {
if(tabs.length > 0) {
lastCookieStoreId = tabs[0].cookieStoreId;
}
});
});
browser.tabs.onUpdated.addListener(tab => newTabs.delete(tab.id));
browser.tabs.onActivated.addListener(updateLastCookieStoreId);
browser.tabs.onActivated.addListener(function(activeInfo) {
showCurrentContainerTabsOnly(activeInfo.tabId);
});
browser.tabs.onUpdated.addListener(storeScreenshot);
interceptRequests();
browser.menus.create({ id: "settings", title: "Conex settings", onclick: function() {browser.runtime.openOptionsPage(); },
contexts: ["browser_action"]});
browser.tabs.query({active: true, windowId: browser.windows.WINDOW_ID_CURRENT}).then(tabs => {
if(tabs.length > 0) {
lastCookieStoreId = tabs[0].cookieStoreId;
}
});
browser.commands.onCommand.addListener(function(command) {
console.debug("command called", command);
if(command == "new-container") {
browser.browserAction.setBadgeText({text: "new"});
browser.browserAction.openPopup();
}
});
console.info('conex loaded');