Use Experiments API to setup unread listener

This commit is contained in:
Ximi1970
2020-05-09 17:10:54 +02:00
parent de2a4b6897
commit 21ca49d37f
8 changed files with 193 additions and 306 deletions

View File

@@ -9,8 +9,6 @@
<h3>Background</h3>
<p>Background HTML</p>
<div id="filters" data-filters="undefined"></div>
<script src="js/defaults.js"></script>
<div id="icon" data-icon-mime="" data-icon=""></div>

View File

@@ -1,11 +1,6 @@
var SysTrayX = {
startupState: undefined,
pollTiming: {
pollStartupDelay: "60",
pollInterval: "60",
},
platformInfo: undefined,
browserInfo: undefined,
@@ -15,11 +10,11 @@ var SysTrayX = {
SysTrayX.Messaging = {
accounts: [],
countType: 0,
filtersExt: undefined,
filters: undefined,
init: function () {
// Get the filters from the storage
SysTrayX.Messaging.getFilters();
// Lookout for storage changes
browser.storage.onChanged.addListener(SysTrayX.Messaging.storageChanged);
@@ -38,6 +33,7 @@ SysTrayX.Messaging = {
// Send preferences to app
SysTrayX.Messaging.sendPreferences();
/*
// New mail listener (TB76+)
if (SysTrayX.browserInfo.majorVersion > 75) {
//
@@ -47,17 +43,25 @@ SysTrayX.Messaging = {
SysTrayX.Messaging.newMail
);
}
*/
// Start polling the accounts
window.setTimeout(
SysTrayX.Messaging.pollAccounts,
SysTrayX.pollTiming.pollStartupDelay * 1000
);
// Set the count type in the folderChange listener
browser.folderChange.setCountType(Number(SysTrayX.Messaging.countType));
// Set the filters in the folderChange listener
browser.folderChange.setFilters(SysTrayX.Messaging.filtersExt);
browser.folderChange.onUnreadMailChange.addListener(function (unread) {
console.debug("folderChangeListener: " + unread);
SysTrayX.Messaging.unreadCb(unread)
});
// Try to catch the window state
browser.windows.onFocusChanged.addListener(SysTrayX.Window.focusChanged);
},
/*
newMail: async function (folder, messages) {
console.debug(
"New mail: " + folder.accountId + ", " + messages.messages.length
@@ -71,26 +75,28 @@ SysTrayX.Messaging = {
}
console.debug("Unread: " + unread);
},
*/
//
// Handle a storage change
//
storageChanged: function (changes, area) {
// Get the new preferences
SysTrayX.Messaging.getFilters();
if ("pollStartupDelay" in changes && changes["pollStartupDelay"].newValue) {
SysTrayX.pollTiming = {
...SysTrayX.pollTiming,
pollStartupDelay: changes["pollStartupDelay"].newValue,
};
if ("filtersExt" in changes && changes["filtersExt"].newValue) {
SysTrayX.Messaging.filtersExt = changes["filtersExt"].newValue;
browser.folderChange.setFilters(SysTrayX.Messaging.filtersExt);
}
if ("pollInterval" in changes && changes["pollInterval"].newValue) {
SysTrayX.pollTiming = {
...SysTrayX.pollTiming,
pollInterval: changes["pollInterval"].newValue,
};
if ("filters" in changes && changes["filters"].newValue) {
SysTrayX.Messaging.filters = changes["filters"].newValue;
}
if ("countType" in changes && changes["countType"].newValue) {
SysTrayX.Messaging.countType = changes["countType"].newValue;
browser.folderChange.setCountType(Number(SysTrayX.Messaging.countType));
}
if ("addonprefchanged" in changes && changes["addonprefchanged"].newValue) {
@@ -106,86 +112,6 @@ SysTrayX.Messaging = {
}
},
//
// Poll the accounts
//
pollAccounts: function () {
//
// Get the unread nessages of the selected accounts
//
const filtersDiv = document.getElementById("filters");
const filtersAttr = filtersDiv.getAttribute("data-filters");
if (filtersAttr !== "undefined") {
const filters = JSON.parse(filtersAttr);
if (filters.length > 0) {
SysTrayX.Messaging.unReadMessages(filters).then(
SysTrayX.Messaging.unreadCb
);
} else {
SysTrayX.Link.postSysTrayXMessage({ unreadMail: 0 });
}
} else {
// Never saved anything, construct temporary filters
if (SysTrayX.Messaging.accounts.length > 0) {
// Construct inbox filters for all accounts
let filters = [];
SysTrayX.Messaging.accounts.forEach((account) => {
const inbox = account.folders.filter(
(folder) => folder.type == "inbox"
);
if (inbox.length > 0) {
filters.push({
unread: true,
folder: inbox[0],
});
}
});
// Store them in the background HTML
const filtersDiv = document.getElementById("filters");
filtersDiv.setAttribute("data-filters", JSON.stringify(filters));
SysTrayX.Messaging.unReadMessages(filters).then(
SysTrayX.Messaging.unreadCb
);
} else {
// No accounts, no mail
SysTrayX.Link.postSysTrayXMessage({ unreadMail: 0 });
}
}
// Next round...
window.setTimeout(
SysTrayX.Messaging.pollAccounts,
SysTrayX.pollTiming.pollInterval * 1000
);
},
//
// Use the messages API to get the unread messages (Promise)
// Be aware that the data is only avaiable inside the callback
//
unReadMessages: async function (filters) {
let unreadMessages = 0;
for (let i = 0; i < filters.length; ++i) {
let page = await browser.messages.query(filters[i]);
let unread = page.messages.length;
while (page.id) {
page = await browser.messages.continueList(page.id);
unread = unread + page.messages.length;
}
unreadMessages = unreadMessages + unread;
}
return unreadMessages;
},
//
// Callback for unReadMessages
//
@@ -215,8 +141,6 @@ SysTrayX.Messaging = {
sendPreferences: function () {
const getter = browser.storage.sync.get([
"debug",
"pollStartupDelay",
"pollInterval",
"minimizeType",
"startMinimized",
"iconType",
@@ -224,14 +148,13 @@ SysTrayX.Messaging = {
"icon",
"showNumber",
"numberColor",
"countType",
]);
getter.then(this.sendPreferencesStorage, this.onSendPreferecesStorageError);
},
sendPreferencesStorage: function (result) {
const debug = result.debug || "false";
const pollStartupDelay = result.pollStartupDelay || "60";
const pollInterval = result.pollInterval || "60";
const minimizeType = result.minimizeType || "1";
const startMinimized = result.startMinimized || "false";
const iconType = result.iconType || "0";
@@ -239,13 +162,12 @@ SysTrayX.Messaging = {
const icon = result.icon || [];
const showNumber = result.showNumber || "true";
const numberColor = result.numberColor || "#000000";
const countType = result.countType || "0";
// Send it to the app
SysTrayX.Link.postSysTrayXMessage({
preferences: {
debug: debug,
pollStartupDelay: pollStartupDelay,
pollInterval: pollInterval,
minimizeType: minimizeType,
startMinimized: startMinimized,
iconType: iconType,
@@ -253,6 +175,7 @@ SysTrayX.Messaging = {
icon: icon,
showNumber: showNumber,
numberColor: numberColor,
countType: countType,
},
});
@@ -269,26 +192,6 @@ SysTrayX.Messaging = {
console.log(`GetIcon Error: ${error}`);
},
//
// Get the filters from the storage
//
getFilters: function () {
const getter = browser.storage.sync.get("filters");
getter.then(this.getFiltersStorage, this.onGetFiltersStorageError);
},
//
// Get the filters from the storage and
// make them available in the background HTML
//
getFiltersStorage: function (result) {
const filters = result.filters || undefined;
// Store them in the background HTML
const filtersDiv = document.getElementById("filters");
filtersDiv.setAttribute("data-filters", JSON.stringify(filters));
},
onGetAccountsStorageError: function (error) {
console.log(`GetAccounts Error: ${error}`);
},
@@ -372,6 +275,13 @@ SysTrayX.Link = {
});
}
const countType = response["preferences"].countType;
if (countType) {
browser.storage.sync.set({
countType: countType,
});
}
const minimizeType = response["preferences"].minimizeType;
if (minimizeType) {
browser.storage.sync.set({
@@ -386,20 +296,6 @@ SysTrayX.Link = {
});
}
const pollStartupDelay = response["preferences"].pollStartupDelay;
if (pollStartupDelay) {
browser.storage.sync.set({
pollStartupDelay: pollStartupDelay,
});
}
const pollInterval = response["preferences"].pollInterval;
if (pollInterval) {
browser.storage.sync.set({
pollInterval: pollInterval,
});
}
const debug = response["preferences"].debug;
if (debug) {
browser.storage.sync.set({
@@ -432,9 +328,6 @@ async function start() {
SysTrayX.startupState = state;
// Get the poll timing
SysTrayX.pollTiming = await getPollTiming();
// Set platform
SysTrayX.platformInfo = await browser.runtime
.getPlatformInfo()
@@ -482,6 +375,15 @@ async function start() {
// Get all accounts
SysTrayX.Messaging.accounts = await browser.accounts.list();
// Get the extended filters
SysTrayX.Messaging.filtersExt = await getFiltersExt();
// Get the filters
SysTrayX.Messaging.filters = await getFilters();
// Get the count type
SysTrayX.Messaging.countType = await getCountType();
// Setup the link first
SysTrayX.Link.init();

View File

@@ -15,11 +15,11 @@ async function getDefaultIcon() {
const iconStored = await getIcon.then(getStoredIcon, onStoredIconError);
if (!iconStored) {
const toDataURL = url =>
const toDataURL = (url) =>
fetch(url)
.then(response => response.blob())
.then((response) => response.blob())
.then(
blob =>
(blob) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
@@ -30,11 +30,8 @@ async function getDefaultIcon() {
// Convert image to storage param
let { iconMime, iconBase64 } = await toDataURL("icons/blank-icon.png").then(
dataUrl => {
const data = dataUrl
.split(":")
.pop()
.split(",");
(dataUrl) => {
const data = dataUrl.split(":").pop().split(",");
return { iconMime: data[0].split(";")[0], iconBase64: data[1] };
}
);
@@ -42,7 +39,7 @@ async function getDefaultIcon() {
// Store default icon (base64)
browser.storage.sync.set({
iconMime: iconMime,
icon: iconBase64
icon: iconBase64,
});
// Store in HTML
@@ -69,19 +66,49 @@ async function getStartupState() {
}
//
// Get poll timing
// Get filters
//
async function getPollTiming() {
function getDelayAndInterval(result) {
return { pollStartupDelay: result.pollStartupDelay || "60", pollInterval: result.pollInterval || "60" };
async function getFilters() {
function getFiltersCb(result) {
return result.filters || undefined;
}
function onDelayAndIntervalError() {
return { pollStartupDelay: "60", pollInterval: "60" };
function onFiltersError() {
return undefined;
}
const getTiming = browser.storage.sync.get([
"pollStartupDelay",
"pollInterval"]);
return await getTiming.then(getDelayAndInterval, onDelayAndIntervalError);
const getFilters = browser.storage.sync.get("filters");
return await getFilters.then(getFiltersCb, onFiltersError);
}
//
// Get extended filters
//
async function getFiltersExt() {
function getFiltersExtCb(result) {
return result.filtersExt || undefined;
}
function onFiltersExtError() {
return undefined;
}
const getFiltersExt = browser.storage.sync.get("filtersExt");
return await getFiltersExt.then(getFiltersExtCb, onFiltersExtError);
}
//
// Get count type
//
async function getCountType() {
function getCountTypeCb(result) {
return result.countType || "0";
}
function onCountTypeError() {
return undefined;
}
const getCountType = browser.storage.sync.get("countType");
return await getCountType.then(getCountTypeCb, onCountTypeError);
}

View File

@@ -19,7 +19,7 @@ SysTrayX.Accounts = {
* Callback for getAccounts
*/
getAccountsCb: function (mailAccount) {
function createFolderTree(folders) {
function createFolderTree(accountName, folders) {
let result = [];
let level = { result };
@@ -31,8 +31,9 @@ SysTrayX.Accounts = {
if (!r[name]) {
r[name] = { result: [] };
r.result.push({
name: folder.name,
accountName: accountName,
accountId: folder.accountId,
name: folder.name,
path: folder.path,
children: r[name].result,
});
@@ -113,7 +114,10 @@ SysTrayX.Accounts = {
typeLi.appendChild(typeText);
// Create a usable folder tree
const folders = createFolderTree(accounts[prop][i].folders);
const folders = createFolderTree(
accounts[prop][i].name,
accounts[prop][i].folders
);
// Recursive list creator
function createListLevel(level) {
@@ -136,8 +140,10 @@ SysTrayX.Accounts = {
typeEleInput.setAttribute(
"value",
JSON.stringify({
accountName: element.accountName,
accountId: element.accountId,
path: element.path,
name: element.name,
})
);
if (element.children.length > 0) {

View File

@@ -1,15 +0,0 @@
function pollStartupDelay(e) {
// console.debug("Startup: " + e.target.value);
}
function pollInterval(e) {
// console.debug("Interval: " + e.target.value);
}
document
.getElementById("pollStartupDelay")
.addEventListener("change", pollStartupDelay);
document
.getElementById("pollInterval")
.addEventListener("change", pollInterval);

View File

@@ -35,5 +35,22 @@
"options_ui": {
"page": "options.html",
"open_in_tab": true
},
"experiment_apis": {
"folderChange": {
"schema": "schema_folderchange.json",
"parent": {
"scopes": [
"addon_parent"
],
"paths": [
[
"folderChange"
]
],
"script": "js/folderChange.js"
}
}
}
}

View File

@@ -125,6 +125,16 @@
</td>
</tr>
</table>
<table id="countprops" style="display:none">
<tr>
<td>
<label for="countType">Message count type: </label>
<input type="radio" name="countType" value="0" /> Unread
<input type="radio" name="countType" value="1" /> New
</td>
</tr>
</table>
</form>
<div id="icon" data-icon-mime="" data-icon=""></div>
@@ -139,42 +149,6 @@
<ul id="accountsTree"></ul>
<br />
<table id="pollselect">
<tr>
<td>
<label for="pollStartupDelay" }>Poll startup delay</label>
</td>
<td>
<input
type="number"
id="pollStartupDelay"
name="pollStartupDelay"
step="1"
min="1"
max="999"
value="60"
style="width: 4em;"
/>
</td>
</tr>
<tr>
<td>
<label for="pollInterval" }>Poll interval</label>
</td>
<td>
<input
type="number"
id="pollInterval"
name="pollInterval"
step="1"
min="1"
max="999"
value="60"
style="width: 4em;"
/>
</td>
</tr>
</table>
</form>
<div id="filters" data-filters="undefined"></div>

View File

@@ -31,12 +31,21 @@ SysTrayX.SaveOptions = {
});
let filters = [];
let filtersExt = [];
checkedFolders.forEach((folder) => {
const mailFolder = JSON.parse(folder.value);
const mailFolderExt = JSON.parse(folder.value);
filtersExt.push({
unread: true,
folder: mailFolderExt,
});
filters.push({
unread: true,
folder: mailFolder,
folder: {
accountId: mailFolderExt.accountId,
path: mailFolderExt.path,
},
});
});
@@ -44,34 +53,20 @@ SysTrayX.SaveOptions = {
const filtersDiv = document.getElementById("filters");
filtersDiv.setAttribute("data-filters", JSON.stringify(filters));
// Store extended query filters
browser.storage.sync.set({
filtersExt: filtersExt,
});
// Store query filters
browser.storage.sync.set({
filters: filters,
});
//
// Save poll startup delay state
//
const pollStartupDelay = document.querySelector(
'input[name="pollStartupDelay"]'
).value;
browser.storage.sync.set({
pollStartupDelay: pollStartupDelay,
});
//
// Save poll interval state
//
const pollInterval = document.querySelector('input[name="pollInterval"]')
.value;
browser.storage.sync.set({
pollInterval: pollInterval,
});
//
// Save debug state
//
let debug = document.querySelector('input[name="debug"]').checked;
const debug = document.querySelector('input[name="debug"]').checked;
browser.storage.sync.set({
debug: `${debug}`,
});
@@ -91,7 +86,7 @@ SysTrayX.SaveOptions = {
//
// Save start minimized state
//
let startMinimized = document.querySelector('input[name="startMinimized"]')
const startMinimized = document.querySelector('input[name="startMinimized"]')
.checked;
browser.storage.sync.set({
startMinimized: `${startMinimized}`,
@@ -108,9 +103,9 @@ SysTrayX.SaveOptions = {
iconType: iconType,
});
let iconDiv = document.getElementById("icon");
let iconBase64 = iconDiv.getAttribute("data-icon");
let iconMime = iconDiv.getAttribute("data-icon-mime");
const iconDiv = document.getElementById("icon");
const iconBase64 = iconDiv.getAttribute("data-icon");
const iconMime = iconDiv.getAttribute("data-icon-mime");
// Store icon (base64)
browser.storage.sync.set({
@@ -126,7 +121,7 @@ SysTrayX.SaveOptions = {
//
// Save enable number state
//
let showNumber = document.querySelector('input[name="showNumber"]').checked;
const showNumber = document.querySelector('input[name="showNumber"]').checked;
browser.storage.sync.set({
showNumber: `${showNumber}`,
});
@@ -134,10 +129,19 @@ SysTrayX.SaveOptions = {
//
// Save number color
//
let numberColor = document.querySelector('input[name="numberColor"]').value;
const numberColor = document.querySelector('input[name="numberColor"]').value;
browser.storage.sync.set({
numberColor: `${numberColor}`,
});
//
// Save count type preferences
//
const countType = document.querySelector('input[name="countType"]:checked')
.value;
browser.storage.sync.set({
countType: countType,
});
},
};
@@ -200,24 +204,6 @@ SysTrayX.RestoreOptions = {
SysTrayX.RestoreOptions.onFiltersError
);
//
// Restore poll startup delay state
//
const getPollStartupDelay = browser.storage.sync.get("pollStartupDelay");
getPollStartupDelay.then(
SysTrayX.RestoreOptions.setPollStartupDelay,
SysTrayX.RestoreOptions.onPollStartupDelayError
);
//
// Restore poll interval state
//
const getPollInterval = browser.storage.sync.get("pollInterval");
getPollInterval.then(
SysTrayX.RestoreOptions.setPollInterval,
SysTrayX.RestoreOptions.onPollIntervalError
);
//
// Restore enable number state
//
@@ -235,6 +221,15 @@ SysTrayX.RestoreOptions = {
SysTrayX.RestoreOptions.setNumberColor,
SysTrayX.RestoreOptions.onNumberColorError
);
//
// Restore count type
//
const getCountType = browser.storage.sync.get("countType");
getCountType.then(
SysTrayX.RestoreOptions.setCountType,
SysTrayX.RestoreOptions.onCountTypeError
);
},
//
@@ -387,6 +382,22 @@ SysTrayX.RestoreOptions = {
console.log(`numberColor Error: ${error}`);
},
//
// Restore count type
//
setCountType: function (result) {
const countType = result.countType || "0";
const radioButton = document.querySelector(
`input[name="countType"][value="${countType}"]`
);
radioButton.checked = true;
},
onCountTypeError: function (error) {
console.log(`countType Error: ${error}`);
},
//
// Restore filters callbacks
//
@@ -459,34 +470,6 @@ SysTrayX.RestoreOptions = {
onFiltersError: function (error) {
console.log(`Filters Error: ${error}`);
},
//
// Restore poll startup delay state callbacks
//
setPollStartupDelay: function (result) {
const pollStartupDelay = result.pollStartupDelay || 60;
const input = document.querySelector(`input[name="pollStartupDelay"]`);
input.value = pollStartupDelay;
},
onPollStartupDelayError: function (error) {
console.log(`Poll startup delay Error: ${error}`);
},
//
// Restore poll interval state callbacks
//
setPollInterval: function (result) {
const pollInterval = result.pollInterval || 60;
const input = document.querySelector(`input[name="pollInterval"]`);
input.value = pollInterval;
},
onPollPollInterval: function (error) {
console.log(`Poll interval Error: ${error}`);
},
};
SysTrayX.StorageChanged = {
@@ -522,6 +505,11 @@ SysTrayX.StorageChanged = {
numberColor: changes[item].newValue,
});
}
if (item === "countType") {
SysTrayX.RestoreOptions.setCountType({
countType: changes[item].newValue,
});
}
if (item === "minimizeType") {
SysTrayX.RestoreOptions.setMinimizeType({
minimizeType: changes[item].newValue,
@@ -532,16 +520,6 @@ SysTrayX.StorageChanged = {
startMinimized: changes[item].newValue,
});
}
if (item === "pollStartupDelay") {
SysTrayX.RestoreOptions.setPollStartupDelay({
pollStartupDelay: changes[item].newValue,
});
}
if (item === "pollInterval") {
SysTrayX.RestoreOptions.setPollInterval({
pollInterval: changes[item].newValue,
});
}
if (item === "debug") {
SysTrayX.RestoreOptions.setDebug({
debug: changes[item].newValue,