-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbackground.js
80 lines (72 loc) · 2.26 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
browser.commands.onCommand.addListener(onCommand);
async function onCommand(command, tab) {
let folderIndex;
if (command.startsWith("move_mail"))
folderIndex = command.substring("move_mail_".length);
else if (command.startsWith("goto_"))
folderIndex = command.substring("goto_".length);
else {
console.log(`Received unknown command: ${command}`);
return;
}
console.log(`Received command ${command}.`);
const setting = await browser.storage.sync.get("folders").catch(console.error);
if (!setting || !setting.folders || !setting.folders[folderIndex] || !setting.folders[folderIndex].value) {
console.log("No folder setting found");
return;
}
const folderSetting = setting.folders[folderIndex].value;
console.log(`Got saved folder value: ${folderSetting}`);
const folder = await findFolder(folderSetting);
if (!folder) {
console.log(`Folder ${setting.folder} not found`);
return;
}
if (command.startsWith("move_mail"))
moveMail(tab.id, folder);
else if (command.startsWith("goto_"))
goto(tab.id, folder);
else
console.log("Unknown command:" + command);
}
async function moveMail(tabId, folder) {
const messages = await browser.messageDisplay.getDisplayedMessages(tabId);
if (!messages) {
console.log("No messages selected");
return;
}
const messageIds = messages.map(m => m.id);
console.log(`Message IDs: ${messageIds}`);
await browser.messages.move(messageIds, folder);
}
async function goto(tabId, folder) {
await browser.mailTabs.update(tabId, {
displayedFolder: folder
});
}
async function findFolder(folderSetting) {
try {
const setting = JSON.parse(folderSetting);
if (setting.accountId) {
const account = await browser.accounts.get(setting.accountId);
return findSubfolder(setting.folderPath, account.folders);
}
} catch (ex) {
// Saved with previous version which only contains the folder name
const accounts = await browser.accounts.list();
return findSubfolder(folderSetting, accounts.flatMap(account => account.folders));
}
}
function findSubfolder(path, list) {
if (!list)
return undefined;
let result = list.find(f => f.path === path);
if (result)
return result;
for (let i = 0; i < list.length; i++) {
result = findSubfolder(path, list[i].subFolders);
if (result)
return result;
}
return undefined;
}