-
Notifications
You must be signed in to change notification settings - Fork 9
/
qf-background.js
797 lines (673 loc) · 28.7 KB
/
qf-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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
import * as util from "./scripts/qf-util.mjs.js";
import {Licenser} from "./scripts/Licenser.mjs.js";
const QUICKFILTERS_APPNAME = "quickFilters@axelg.com";
const TOGGLEICON_ID = "toggleQuickFoldersIcon";
const REMOVEICON_ID = "removeQuickFoldersIcon";
var currentLicense;
var startupFinished = false;
var callbacks = [];
// [issue 371] Remove console error “receiving end does not exist”
function logReceptionError(x) {
if (x.message.includes("Receiving end does not exist.")) {
// no need to log - quickFilters is not installed or disabled.
} else {
console.log(x);
}
}
/* startupFinished: There is a general race condition between onInstall and our main() startup:
* - onInstall needs to be registered upfront (otherwise we might miss it)
* - but onInstall needs to wait with its execution until our main function has
* finished the init routine
* -> emit a custom event once we are done and let onInstall await that
*/
messenger.WindowListener.registerDefaultPrefs("chrome/content/scripts/quickfoldersDefaults.js");
messenger.runtime.onInstalled.addListener(async (data) => {
let { reason, temporary } = data,
isDebug = await messenger.LegacyPrefs.getPref("extensions.quickfolders.debug");
// Wait until the main startup routine has finished!
await new Promise((resolve) => {
if (startupFinished) {
if (isDebug) console.log("QuickFolders - startup code finished.");
// Looks like we missed the one send by main()
resolve();
}
callbacks.push(resolve);
});
if (isDebug) {
console.log("Startup has finished");
console.log("QuickFolders - currentLicense", currentLicense);
}
switch (reason) {
case "install":
{
let url = browser.runtime.getURL("popup/installed.html");
await browser.windows.create({ url, type: "popup", width: 910, height: 750, });
}
break;
// see below
case "update":
{
let currentLicenseInfo = currentLicense.info;
if (currentLicenseInfo.status == "Valid") {
// suppress update popup for users with licenses that have been recently renewed
let gpdays = currentLicenseInfo.licensedDaysLeft,
isLicensed = (currentLicenseInfo.status == "Valid");
if (isLicensed) {
if (isDebug) console.log("QuickFolders License - " + gpdays + " Days left.");
}
}
// set a flag which will be cleared by clicking the [QuickFolders] button once
setTimeout(
async function() {
let origVer = await messenger.LegacyPrefs.getPref("extensions.quickfolders.version","0");
const manifest = await messenger.runtime.getManifest();
// get pure version number / remove pre123 indicator
let installedVersion = manifest.version.replace(/pre.*/,"");
if (installedVersion > origVer) {
messenger.LegacyPrefs.setPref("extensions.quickfolders.hasNews", true);
}
messenger.NotifyTools.notifyExperiment({event: "updateQuickFoldersLabel"});
// replacement for showing history!!
// window.addEventListener("load",function(){ QuickFolders.Util.FirstRun.init(); },true);
messenger.NotifyTools.notifyExperiment({event: "firstRun"});
},
200
)
}
break;
// see below
}
if (isDebug) {
console.log ("QuickFolders: messenger.runtime.onInstalled finished!")
}
});
// display splash screen
function showSplash(msg="") {
// alternatively display this info in a tab with browser.tabs.create(...)
let url = browser.runtime.getURL("popup/update.html");
if (msg) url+= "?msg=" + encodeURI(msg);
let screenH = window.screen.height,
windowHeight = (screenH > 870) ? 870 : screenH;
browser.windows.create({ url, type: "popup", width: 1000, height: windowHeight, allowScriptsToClose: true,});
}
function showInstalled() {
let url = browser.runtime.getURL("popup/installed.html");
browser.windows.create({ url, type: "popup", width: 910, height: 800, allowScriptsToClose: true });
}
async function filterMailsRegex(searchOptions, tabId = null) {
const DEFAULT_BEHAVIOR = {
isSelectPrevious: await messenger.LegacyPrefs.getPref("extensions.quickfolders.findRelated.behavior.selectPrevious")
}
const group = searchOptions.group; // 0 for full match
const searchSelected = searchOptions.searchSelected;
const searchCriteria = searchOptions.searchCriteria; // if fields is null, do not change this!
let pattern = searchOptions.pattern; // allow overwriting in debugger for test!
const isEmpty = (!pattern); // non empty search string, reset!
const behavior = searchOptions.behavior || DEFAULT_BEHAVIOR;
const regex = new RegExp(pattern, "gm");
let results, searchVal = "";
if (isEmpty) {
// reset search!
}
// context.extension.tabManager.getWrapper(tabInfo).id
if (!tabId) {
const currentTab = await messenger.tabs.getCurrent();
if (!currentTab) return;
tabId = currentTab.id;
}
const selectedMessages = await messenger.mailTabs.getSelectedMessages(tabId);
if (selectedMessages.messages.length == 0) {
// do nothing?
// or reset search.
return;
}
// https://webextension-api.thunderbird.net/en/latest/mailTabs.html#mailtabs-quickfiltertextdetail
let searchTextProps = {}; // the text property is a QuickFilterTextDetail object!
let message = selectedMessages.messages[0];
const currentMessageHdrId = message.headerMessageId;
// retrieve a search text value from the selected message:
if (searchSelected.includes("subject")) {
results = regex.exec(message.subject);
if (results?.length > group) {
searchVal = results[group];
}
}
if (!searchVal && searchSelected.includes("recipients")) {
results = regex.exec(message.recipients.join(" "));
if (results?.length > group) {
searchVal = results[group];
}
}
if (!searchVal && searchSelected.includes("sender")) {
results = regex.exec(message.author);
if (results?.length > group) {
searchVal = results[group];
}
}
if (!searchVal && searchSelected.includes("body")) {
const fullMessage = await messenger.messages.getFull(message.messageId);
if (fullMessage) {
results = regex.exec(fullMessage.body);
if (results?.length > group) {
searchVal = results[group];
}
}
}
if (searchVal) {
// Remember last extracted search term, so we can use this for a search reset
// when user clicks "next unread message"
// we MUST reset this whenever use changes to a different folder!!!
// folder listener?
messenger.LegacyPrefs.setPref("extensions.quickfolders.findRelated.lastSearchVal", searchVal);
}
if (searchCriteria.includes("subject")) {
searchTextProps.subject = true;
}
if (searchCriteria.includes("recipients")) {
searchTextProps.recipients = true;
}
if (searchCriteria.includes("sender")) {
searchTextProps.author = true;
}
if (searchCriteria.includes("body")) {
searchTextProps.body = true;
}
searchTextProps.text = searchVal;
// we need to pass an object that contains obj.text=QuickFilterTextDetail !
if (tabId) {
await browser.mailTabs.setQuickFilter(tabId, {text: searchTextProps} );
} else {
await browser.mailTabs.setQuickFilter( {text: searchTextProps} );
}
if (behavior.isSelectPrevious) {
// select currentMessageId then go "up" to the previously received / sent mail
const options = {color:"white", background:"rgb(80,0,0)"};
const txt = "filterMailsRegex";
console.log(`QuickFolders %c${txt}`,
`color: ${options.color}; background: ${options.background}`,
`TO DO: select previous message from id: ${currentMessageHdrId}`);
}
}
// future function for icon support [issue 399]
async function addFolderPaneMenu() {
// replaces code from QuickFolders.Interface.folderPanePopup()
let isDebug = await messenger.LegacyPrefs.getPref("extensions.quickfolders.debug.tbmenus"),
txtAddIcon = messenger.i18n.getMessage("qf.foldercontextmenu.quickfolders.customizeIcon"),
txtRemoveIcon = messenger.i18n.getMessage("qf.foldercontextmenu.quickfolders.removeIcon");
if (isDebug) {
console.log("QuickFolders: addFolderPaneMenu()");
}
let menuProps = {
contexts: ["folder_pane"],
onclick: async (event) => {
if (isDebug) { console.log("QuickFolders folderpane context menu", event); }
const menuItem = { id: TOGGLEICON_ID }; // fake menu item to pass to doCommand
// determine folder of clicked tree item:
const selectedFolder = event?.selectedFolder || null;
// new multiple folders selection
const selectedFolders = event?.selectedFolders || null;
// multiple folders are selected, we cannot execute
if (selectedFolders && selectedFolders.length>1) {
console.log("QuickFolders: addFolderPaneMenu - cannot execute, multiple folders are selected!");
return;
}
const selectedAccount = event?.selectedAccount || null;
let URI = null;
if (selectedFolder) {
URI = await messenger.Utilities.getFolderUri(selectedFolder.accountId, selectedFolder.path);
} else if (selectedAccount) {
URI = await messenger.Utilities.getFolderUri(selectedAccount.id);
}
messenger.NotifyTools.notifyExperiment(
{
event: "toggleQuickFoldersIcon",
detail: {
commandItem: menuItem,
folderURI: URI,
selectedFolder: event.selectedFolder,
selectedAccount: event.selectedAccount
}
}
);
},
icons: {
"16": "chrome/content/skin/ico/image.svg"
} ,
enabled: true,
id: TOGGLEICON_ID,
title: txtAddIcon
}
let idToggle = await messenger.menus.create(menuProps); // id of menu item
let removeProps = {
contexts: ["folder_pane"],
onclick: async (event) => {
const menuItem = { id: REMOVEICON_ID }; // fake menu item to pass to doCommand
let currentTab = await messenger.mailTabs.getCurrent();
// determine folder of clicked tree item:
const selectedFolder = event?.selectedFolder || null;
const selectedAccount = event?.selectedAccount || null;
let URI = null;
if (selectedFolder) {
URI = await messenger.Utilities.getFolderUri(selectedFolder.accountId, selectedFolder.path);
} else if (selectedAccount) {
URI = await messenger.Utilities.getFolderUri(selectedAccount.id);
}
messenger.NotifyTools.notifyExperiment(
{ event: "removeQuickFoldersIcon",
detail: {
commandItem: menuItem,
folderURI: URI,
selectedFolder: event.selectedFolder,
selectedAccount: event.selectedAccount
} // , windowId: currentTab.windowId, tabId: currentTab.id
}
);
},
icons: {
"16": "chrome/content/skin/ico/picture-remove.svg"
} ,
enabled: true,
visible: false,
id: REMOVEICON_ID,
title: txtRemoveIcon
}
let idRemove = await messenger.menus.create(removeProps);
messenger.menus.onShown.addListener(async (info, tab) => {
const selectedFolder = info?.selectedFolder || null;
const selectedAccount = info?.selectedAccount || null;
const isServer = selectedAccount ? true : false;
let icon = null;
if (selectedFolder) {
icon = await messenger.Utilities.getFolderIcon(selectedFolder.accountId, selectedFolder.path);
} else if (selectedAccount) {
icon = await messenger.Utilities.getFolderIcon(selectedAccount.id);
}
if (isDebug) {
console.log("QuickFolders [debug.tbmenu]\n menus.onShown() - folderpane context menu:", selectedFolder, info, icon);
}
let hasIcon = (icon != null && icon.iconURL); // query the icon somehow.
if (hasIcon) {
await messenger.menus.update(idRemove, {visible: true});
} else {
await messenger.menus.update(idRemove, {visible: false});
}
if (!isServer && !selectedFolder) {
await messenger.menus.update(idToggle, {visible: false});
await messenger.menus.update(idRemove, {visible: false});
} else {
await messenger.menus.update(idToggle, {visible: true});
}
messenger.menus.refresh();
});
}
async function main() {
const legacy_root = "extensions.quickfolders.";
let key = await messenger.LegacyPrefs.getPref(legacy_root + "LicenseKey", ""),
forceSecondaryIdentity = await messenger.LegacyPrefs.getPref(legacy_root + "licenser.forceSecondaryIdentity") || false,
isDebug = await messenger.LegacyPrefs.getPref(legacy_root + "debug") || false,
isDebugLicenser = await messenger.LegacyPrefs.getPref(legacy_root + "debug.premium.licenser") || false;
currentLicense = new Licenser(key, { forceSecondaryIdentity, debug: isDebugLicenser });
await currentLicense.validate();
// All important stuff has been done.
// resolve all promises on the stack
if (isDebug) console.log("Finished setting up license startup code");
callbacks.forEach(callback => callback());
startupFinished = true;
let msg_commands = [
"currentDeckUpdate",
"getLicenseInfo",
"copyFolderEntries",
"pasteFolderEntries",
"legacyAdvancedSearch", // new global one!
"showAboutConfig", // new global one!
"showLicenseDialog", // new global one!
"slideAlert",
"updateCategoryBox",
"updateFoldersUI",
"updateLicense",
"updateMainWindow",
"updateNavigationBar",
"updateQuickFoldersLabel",
"updateUserStyles",
"readCategories",
"storeCategories",
"readToolbarStatus",
"storeToolbarStatus",
"toggleNavigationBars"
];
async function notificationHandler(data) {
let command = data.func || data.command;
switch (command) {
case "slideAlert":
util.slideAlert(...data.args);
break;
case "splashScreen":
let splashMessage = data.msg || "";
showSplash(splashMessage);
break;
case "splashInstalled":
showInstalled();
break;
case "getLicenseInfo":
return currentLicense.info;
case "getPlatformInfo":
return messenger.runtime.getPlatformInfo();
case "getBrowserInfo":
return messenger.runtime.getBrowserInfo();
case "getAddonInfo":
return messenger.management.getSelf();
case "updateQuickFoldersLabel":
// Broadcast main windows to run updateQuickFoldersLabel
messenger.NotifyTools.notifyExperiment({event: "updateQuickFoldersLabel"});
break;
case "updateUserStyles":
// Broadcast main windows to update their styles (and maybe single message windows???)
messenger.NotifyTools.notifyExperiment({event: "updateUserStyles"});
break;
case "updateFoldersUI": // replace observer
messenger.NotifyTools.notifyExperiment({event: "updateFoldersUI"});
break;
case "updateAllTabs":
// only update tabs, without styles - reads the tabs from the store to support:
// adding / renaming / deleting / re-categorizing / re-ordering
// across all Windows instances.
messenger.NotifyTools.notifyExperiment({event: "updateAllTabs"});
break;
case "updateNavigationBar":
await messenger.NotifyTools.notifyExperiment({event: "updateNavigationBar"});
break;
case "toggleNavigationBars": // toggles _all_ navigation bars (from options window)
messenger.NotifyTools.notifyExperiment({event: "toggleNavigationBars"});
break;
case "updateCategoryBox":
messenger.NotifyTools.notifyExperiment({event: "updateCategoryBox"});
break;
case "updateMainWindow": // we need to add one parameter (minimal) to pass through!
let isMinimal = (data.minimal) || false;
messenger.NotifyTools.notifyExperiment({event: "updateMainWindow", detail:{ minimal: isMinimal}});
break;
case "showAboutConfig":
// to do: create an API for this one
messenger.NotifyTools.notifyExperiment({
event: "showAboutConfig",
element: null,
filter: data.filter,
readOnly: data.readOnly,
updateUI: data.updateUI || false
});
break;
case "showLicenseDialog":
messenger.NotifyTools.notifyExperiment({
event: "showLicenseDialog",
referrer: data.referrer
});
break;
case "legacyAdvancedSearch":
messenger.NotifyTools.notifyExperiment({event: "legacyAdvancedSearch"});
break;
case "currentDeckUpdate":
messenger.NotifyTools.notifyExperiment({event: "currentDeckUpdate"});
break;
case "initKeyListeners":
messenger.NotifyTools.notifyExperiment({event: "initKeyListeners"});
break;
case "openPrefs":
let params = new URLSearchParams();
if (data.selectedTab || data.selectedTab==0) {
params.append("selectedTab", data.selectedTab);
}
if (data.mode) {
params.append("mode", data.mode);
}
let title = messenger.i18n.getMessage("qf.prefwindow.quickfolders.options");
// to get the tab - we need the activetab permission
// query for url
let url = browser.runtime.getURL("/html/options.html") + "*";
let oldTabs = await browser.tabs.query({url}); // destructure first
if (oldTabs.length) {
// get current windowId
let currentWin = await browser.windows.getCurrent();
let found = oldTabs.find( w => w.windowId == currentWin.id);
if (!found) {
[found] = oldTabs; // destructure first element
await browser.windows.update(found.windowId, {focused:true, drawAttention: true});
} else {
await browser.tabs.update(found.id, {active:true});
}
// activate the license tab!
if (data.mode) {
await browser.runtime.sendMessage({
activatePrefsPage: data.mode,
});
}
} else {
let optionsWin = await messenger.windows.create(
{ height: 720,
width: 840,
type: "panel",
url: `/html/options.html?${params.toString()}`,
allowScriptsToClose : true
}
);
}
// optionWin.sizeToContent()
break;
case "openAdvancedProps":
{
let params = new URLSearchParams();
const x = parseInt(data.x,10), y = parseInt(data.y,10);
params.append("folderURI", data.folderURI ); // to do: pass folder or url in event
params.append("x", x);
params.append("y", y);
let window = await messenger.windows.create({
left: x,
top: y,
type: "popup",
allowScriptsToClose: true,
url: `/html/quickfolders-tab-props.html?${params.toString()}`,
});
// focused: true,
}
break;
case "updateLicense":
let forceSecondaryIdentity = await messenger.LegacyPrefs.getPref(legacy_root + "licenser.forceSecondaryIdentity"),
isDebugLicenser = await messenger.LegacyPrefs.getPref(legacy_root + "debug.premium.licenser");
// we create a new Licenser object for overwriting, this will also ensure that key_type can be changed.
let newLicense = new Licenser(data.key, { forceSecondaryIdentity, debug: isDebugLicenser });
await newLicense.validate();
// Check new license and accept if ok.
// You may return values here, which will be send back to the caller.
// return false;
// Update background license.
await messenger.LegacyPrefs.setPref(legacy_root + "LicenseKey", newLicense.info.licenseKey);
currentLicense = newLicense;
// 1. Broadcast into Experiment
messenger.NotifyTools.notifyExperiment({licenseInfo: currentLicense.info});
// 2. notify options.html (new, using message API)
let message = {
msg: "updatedLicense",
licenseInfo: currentLicense.info
}
messenger.runtime.sendMessage(message);
messenger.NotifyTools.notifyExperiment({event: "updateAllTabs"});
// if ( (await messenger.management.getAll()).find(({ id }) => id === QUICKFILTERS_APPNAME) ) {
messenger.runtime.sendMessage(QUICKFILTERS_APPNAME,
{ command: "updateQuickFoldersLicense",
license: { status: currentLicense.info.status, keyType: currentLicense.info.keyType } }).catch(logReceptionError);
// }
return true;
case "updateLicenseTimer":
await currentLicense.updateLicenseDates();
messenger.NotifyTools.notifyExperiment({licenseInfo: currentLicense.info});
messenger.NotifyTools.notifyExperiment({event: "updateMainWindow", minimal: false});
break;
case "createSubfolder": // [issue 234]
// if folderName is not given - create a popup window
return browser.folders.create(data.parentPath, data.folderName || "test1"); // like await but returns
case "copyFolderEntries":
messenger.NotifyTools.notifyExperiment({event: "copyFolderEntriesToClipboard"});
break;
case "pasteFolderEntries":
messenger.NotifyTools.notifyExperiment({event: "pasteFolderEntriesFromClipboard"});
break;
case "updateQuickFilters":
{
let licenseStatus = currentLicense.info.status,
licenseType = currentLicense.info.keyType;
// require management permission to check if qF is installed
// if ( (await messenger.management.getAll()).find(({ id }) => id === QUICKFILTERS_APPNAME) ) {
messenger.runtime.sendMessage(QUICKFILTERS_APPNAME,
{ command: "injectButtonsQFNavigationBar",
license: { status: licenseStatus, keyType: licenseType } }).catch(logReceptionError);
// }
}
break;
case "searchMessages": // test
messenger.messages.list(data.folder);
break;
case "initActionButton": // initialize toggle toolbar button
messenger.Utilities.toggleToolbarAction(true); // patch action button (toolbar toggle)
break;
case "storeCategories": // store category in session
await messenger.sessions.setTabValue(data.tabId, "QuickFolders_Categories", data.categories);
break;
case "readCategories": // read category from tabsession
{
let cats = await messenger.sessions.getTabValue(data.tabId, "QuickFolders_Categories");
return cats;
}
case "storeToolbarStatus": // store toolbar visibilities in tabsession
await messenger.sessions.setTabValue(data.tabId, "QuickFolders_ToolbarStatus", data.status);
break;
case "filterMailsRegex": // filter based on current mail!
let regexOption = JSON.parse(data.searchOptions);
await filterMailsRegex(regexOption, data.tabId);
break;
case "readToolbarStatus": // store toolbar visibilities in tabsession
{
let status = await messenger.sessions.getTabValue(data.tabId, "QuickFolders_ToolbarStatus");
return status
}
case "addFolderPaneMenu":
addFolderPaneMenu();
break;
case "openLinkInTab":
// https://webextension-api.thunderbird.net/en/stable/tabs.html#query-queryinfo
{
let baseURI = data.baseURI || data.URL;
let found = await browser.tabs.query( { url:baseURI } );
if (found.length) {
let tab = found[0]; // first result
await browser.tabs.update(
tab.id,
{active:true, url: data.URL}
);
return;
}
browser.tabs.create(
{ active:true, url: data.URL }
);
}
break;
}
}
// background listener
messenger.NotifyTools.onNotifyBackground.addListener((data) => {
messenger.LegacyPrefs.getPref(legacy_root + "debug.notifications").then(
isLog => {
if (isLog && data.func) {
console.log ("=========================\n" +
"BACKGROUND LISTENER received: " + data.func + "\n" +
"=========================");
}
}
);
return notificationHandler(data); // returns the promise for notification Handler
});
// message listener - SELECTIVE!
// every message listener must have its unique set of messages (if it returns something)
messenger.runtime.onMessage.addListener((data, sender) => {
if (msg_commands.includes(data.command)) {
return notificationHandler(data, sender); // the result of this is a Promise
}
});
let browserInfo = await messenger.runtime.getBrowserInfo();
// Init WindowListener.
function getThunderbirdVersion() {
let parts = browserInfo.version.split(".");
return {
major: parseInt(parts[0]),
minor: parseInt(parts[1]),
revision: parts.length > 2 ? parseInt(parts[2]) : 0,
}
}
messenger.runtime.onMessageExternal.addListener( async (message, sender) =>
{
switch(message.command) {
case "queryQuickFoldersLicense":
return {
status: currentLicense.info.status,
keyType: currentLicense.info.keyType
}
break;
}
});
messenger.WindowListener.registerChromeUrl([
["content", "quickfolders", "chrome/content/"],
["content", "quickfolders-skins", "chrome/content/skin/tb91/"]
]);
messenger.WindowListener.registerWindow("chrome://messenger/content/messenger.xhtml", "chrome/content/scripts/qf-messenger.js");
// inject a separate script for current folder toolbar!
messenger.WindowListener.registerWindow("about:3pane", "chrome/content/scripts/qf-3pane.js");
messenger.WindowListener.registerWindow("about:message", "chrome/content/scripts/qf-3pane.js");
messenger.WindowListener.registerWindow("chrome://messenger/content/messengercompose/messengercompose.xhtml", "chrome/content/scripts/qf-composer.js");
messenger.WindowListener.registerWindow("chrome://messenger/content/SearchDialog.xhtml", "chrome/content/scripts/qf-searchDialog.js");
messenger.WindowListener.registerWindow("chrome://messenger/content/customizeToolbar.xhtml", "chrome/content/scripts/qf-customizetoolbar.js");
messenger.WindowListener.registerWindow("chrome://messenger/content/messageWindow.xhtml", "chrome/content/scripts/qf-messageWindow.js");
/*
* Start listening for opened windows. Whenever a window is opened, the registered
* JS file is loaded. To prevent namespace collisions, the files are loaded into
* an object inside the global window. The name of that object can be specified via
* the parameter of startListening(). This object also contains an extension member.
*/
// make sure session has loaded all tabs.
let [ mailTab ] = await browser.mailTabs.query({});
await browser.mailTabs.get(mailTab.id)
messenger.WindowListener.startListening();
// [issue 296] Exchange account validation (supported since TB98)
messenger.accounts.onCreated.addListener( async(id, account) => {
if (currentLicense.info.status == "MailNotConfigured") {
// redo license validation!
if (isDebugLicenser) console.log("Account added, redoing license validation", id, account); // test
currentLicense = new Licenser(key, { forceSecondaryIdentity, debug: isDebugLicenser });
await currentLicense.validate();
if(currentLicense.info.status != "MailNotConfigured") {
if (isDebugLicenser) console.log("notify experiment code of new license status: " + currentLicense.info.status);
messenger.NotifyTools.notifyExperiment({licenseInfo: currentLicense.info});
messenger.NotifyTools.notifyExperiment({event: "updateMainWindow", minimal: false});
}
if (isDebugLicenser) console.log("QF license info:", currentLicense.info); // test
}
else {
if (isDebugLicenser) console.log("QF license state after adding account:", currentLicense.info)
}
});
if (isDebug) {
console.log ("QuickFolders: add toggle-foldertree command... ")
}
let toggleFolderLabel = messenger.i18n.getMessage("commands.toggleFolderTree");
await messenger.commands.update({name:"toggle-foldertree", description: toggleFolderLabel });
messenger.commands.onCommand.addListener((command) => {
if (isDebug) { console.log("command listener received", command); }
switch (command) {
case "toggle-foldertree":
messenger.NotifyTools.notifyExperiment({event: "toggleFolderTree"});
break;
}
});
messenger.browserAction.onClicked.addListener((tab, info) => {
console.log("browserAction.click!");
messenger.Utilities.toggleToolbarAction(false);
});
} // main
main();