Skip to content

Commit

Permalink
add rwh logger with level info #103
Browse files Browse the repository at this point in the history
  • Loading branch information
jeevatkm committed May 10, 2024
1 parent 4aad128 commit 902f0f1
Show file tree
Hide file tree
Showing 6 changed files with 89 additions and 33 deletions.
9 changes: 5 additions & 4 deletions background.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,26 @@
* /~https://github.com/jeevatkm/ReplyWithHeaderMozilla/blob/master/LICENSE
*/

import { rwhLogger } from './modules/logger.mjs';
import * as rwhMenus from './modules/menus.mjs';
import * as rwhCompose from './modules/compose.mjs';
import * as rwhTabs from './modules/tabs.mjs';
import * as rwhSettings from './modules/settings.mjs';

async function init() {
await rwhSettings.setDefaults();

rwhMenus.register();
await rwhMenus.register();

rwhTabs.register('messageCompose', async (tab) => {
await rwhCompose.process(tab);
});

rwhSettings.setDefaults();
}

try {
init();
console.info('Addon loaded successfully');
rwhLogger.info('Addon loaded successfully');
} catch(e) {
console.error(e);
rwhLogger.error(e);
}
37 changes: 19 additions & 18 deletions modules/compose.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

// RWH Compose Module

import { rwhLogger} from './logger.mjs';
import * as rwhSettings from './settings.mjs';
import * as rwhI18n from './headers-i18n.mjs';

Expand All @@ -18,17 +19,17 @@ const fwdHdrLookupString = '-------- ';
const plainTextFirstChars = '> ';

export async function process(tab) {
console.debug(`tab.id=${tab.id}, tab.type=${tab.type}, tab.mailTab=${tab.mailTab}`);
rwhLogger.debug(`tab.id=${tab.id}, tab.type=${tab.type}, tab.mailTab=${tab.mailTab}`);

let composeDetails = await messenger.compose.getComposeDetails(tab.id);
console.debug(composeDetails);
rwhLogger.debug(composeDetails);

let fullMsg = await messenger.messages.getFull(composeDetails.relatedMessageId);
console.debug(fullMsg);
rwhLogger.debug(fullMsg);

let rwh = new ReplyWithHeader(composeDetails, fullMsg).init();
if (!(rwh.isReply || rwh.isForward)) {
console.warn(`Unsupported compose type ${rwh.composeType}`);
rwhLogger.warn(`Unsupported compose type ${rwh.composeType}`);
return;
}

Expand Down Expand Up @@ -87,7 +88,7 @@ class ReplyWithHeader {
// Method

init() {
console.debug(`composeType=${this.composeType}, messageId=${this.#composeDetails.relatedMessageId}, isPlainText=${this.#composeDetails.isPlainText}`);
rwhLogger.debug(`composeType=${this.composeType}, messageId=${this.#composeDetails.relatedMessageId}, isPlainText=${this.#composeDetails.isPlainText}`);

return this;
}
Expand All @@ -106,17 +107,17 @@ class ReplyWithHeader {
}

if (this.isPlainText) {
console.debug('Plain Text', this.plainTextBody);
rwhLogger.debug('Plain Text', this.plainTextBody);
this.#text = this.plainTextBody;
result = Object.assign({}, result, await this._processPlainText());
} else {
console.debug('HTML Content', this.htmlBody);
rwhLogger.debug('HTML Content', this.htmlBody);
this.#document = this._createDocumentFromString(this.htmlBody);
result = Object.assign({}, result, await this._processHtml());
}

// Apply it to message compose window
console.debug(result);
rwhLogger.debug(result);
messenger.compose.setComposeDetails(tab.id, result);
}

Expand All @@ -126,8 +127,8 @@ class ReplyWithHeader {
let targetNodeClassName = this.targetNodeClassName;
let targetNode = this._getByClassName(targetNodeClassName);
if (!targetNode) {
console.error('Thunderbird email target node (moz-cite-prefix or moz-forward-container) is not found');
console.error('Due to internal changes in Thunderbird. RWH unable to process email headers, contact add-on author');
rwhLogger.error('Thunderbird email target node (moz-cite-prefix or moz-forward-container) is not found');
rwhLogger.error('Due to internal changes in Thunderbird. RWH unable to process email headers, contact add-on author');

// return original value as-is;
return {
Expand All @@ -146,10 +147,10 @@ class ReplyWithHeader {
'reply-to': await this._extractHeader('reply-to', true, true),
'subject': await this._extractHeader('subject', false, true),
}
console.debug(headers);
rwhLogger.debug(headers);

let rwhHeaderString = await this._createHtmlHeaders(headers);
console.debug(rwhHeaderString);
rwhLogger.debug(rwhHeaderString);

let rwhHeaderHtmlElement = this._createElementFromString(rwhHeaderString);
div.insertAdjacentElement(positionAfterBegin, rwhHeaderHtmlElement);
Expand Down Expand Up @@ -185,13 +186,13 @@ class ReplyWithHeader {
'reply-to': await this._extractHeader('reply-to', true, false),
'subject': await this._extractHeader('subject', false, false),
}
console.log(headers);
rwhLogger.debug(headers);

let rwhHeaders = await this._createPlainTextHeaders(headers);
console.log(rwhHeaders);
rwhLogger.debug(rwhHeaders);

let textLines = this.#text.split(/\r?\n/);
console.log(textLines);
rwhLogger.debug(textLines);

let locale = await rwhSettings.getHeaderLocale();
let startPos = 0;
Expand All @@ -215,7 +216,7 @@ class ReplyWithHeader {
}

if (startPos > 0) {
console.log('startPos', startPos, textLines[startPos]);
rwhLogger.debug('startPos', startPos, textLines[startPos]);
textLines.splice(startPos, linesToDelete, ...rwhHeaders);
}

Expand Down Expand Up @@ -311,15 +312,15 @@ class ReplyWithHeader {
let timeFormat = await rwhSettings.getHeaderTimeFormat();
let includeTimezone = await rwhSettings.isHeaderTimeZone();

console.debug('Date format: ' + (dateFormat == 1 ? 'UTC' : 'Locale (' + locale + ')')
rwhLogger.debug('Date format: ' + (dateFormat == 1 ? 'UTC' : 'Locale (' + locale + ')')
+ ', Time format: ' + (timeFormat == 1 ? '24-hour' : '12-hour')
+ (includeTimezone ? ', Include short timezone info' : ''))

let epoch = null;
try {
epoch = Date.parse(d);
} catch (e) {
console.error(error);
rwhLogger.error(error);
return fallback;
}

Expand Down
46 changes: 46 additions & 0 deletions modules/logger.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
* Copyright (c) Jeevanandam M. (jeeva@myjeeva.com)
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at
* /~https://github.com/jeevatkm/ReplyWithHeaderMozilla/blob/master/LICENSE
*/

// RWH Logger Module

const _no_op = function () { };

export var rwhLogger = {
LevelError: 1,
LevelWarn: 2,
LevelInfo: 3,
LevelDebug: 4,

get level() {
return this._level;
},

set level(level) {
this.error = (level >= this.LevelError)
? console.error.bind(window.console, 'RWH:ERROR::')
: _no_op;

this.warn = (level >= this.LevelWarn)
? console.warn.bind(window.console, 'RWH:WARN::')
: _no_op;

this.info = (level >= this.LevelInfo)
? console.info.bind(window.console, 'RWH:INFO::')
: _no_op;

this.debug = (level >= this.LevelDebug)
? console.debug.bind(window.console, 'RWH:DEBUG::')
: _no_op;

this._level = level;
}
};

// Log Level
rwhLogger.level = rwhLogger.LevelInfo;
9 changes: 7 additions & 2 deletions modules/settings.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

// RWH Settings Module

import { rwhLogger} from './logger.mjs';
import * as rwhUtils from './utils.mjs';

export const optionsPrefix = 'extensions.replywithheader.';
Expand Down Expand Up @@ -68,7 +69,7 @@ let rwhDefaultSettings = {
export async function get(key, fallback) {
let fullKey = optionsPrefix + key;
let obj = await messenger.storage.local.get(fullKey);
console.debug(obj);
rwhLogger.debug(obj);

if (rwhUtils.isObjectEmpty(obj)) {
return null;
Expand All @@ -80,10 +81,14 @@ export async function get(key, fallback) {

export async function set(key, value) {
let fullKey = optionsPrefix + key;
console.debug(fullKey, value);
rwhLogger.debug(fullKey, value);
messenger.storage.local.set({ [fullKey]: value });
}

export async function remove(key) {
await messenger.storage.local.remove(optionsPrefix + key);
}

export async function getInt(key) {
let v = await get(key, rwhDefaultSettings[key]);
return parseInt(v)
Expand Down
10 changes: 5 additions & 5 deletions modules/tabs.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@

// RWH Tabs Module

import { rwhLogger} from './logger.mjs';

const tabListeners = {};

messenger.tabs.onCreated.addListener(async (tab) => {
tabListeners[tab.type](tab);
});

async function findTab(messageId) {
export async function findTab(messageId) {
let tabs = await messenger.tabs.query();
for (let tab of tabs) {
let msg = await messenger.messageDisplay.getDisplayedMessage(tab.id);
Expand All @@ -26,12 +28,10 @@ async function findTab(messageId) {
return null;
}

async function register(tabType, listener) {
export async function register(tabType, listener) {
if (tabListeners[tabType]) {
console.warn(`Overwriting existing listener for ${tabType}`)
rwhLogger.warn(`Overwriting existing listener for ${tabType}`)
}

tabListeners[tabType] = listener;
}

export { register, findTab };
11 changes: 7 additions & 4 deletions options/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
* /~https://github.com/jeevatkm/ReplyWithHeaderMozilla/blob/master/LICENSE
*/

import { rwhLogger } from '../modules/logger.mjs';
import * as rwhNotifications from '../modules/notifications.mjs';
import * as rwhSettings from '../modules/settings.mjs';
import * as rwhI18n from '../modules/headers-i18n.mjs';
Expand All @@ -21,6 +22,8 @@ function tabListClickHandler(elem) {
}

function openRwhTab(target) {
rwhLogger.debug(target.id, 'aria-selected=', target.getAttribute('aria-selected'));

let selectedTab = document.querySelector('[aria-selected="true"]');
selectedTab.setAttribute('aria-selected', false);
target.setAttribute('aria-selected', true);
Expand Down Expand Up @@ -54,6 +57,7 @@ async function populateLocale(prefElement) {
));
}
}

async function loadPref(prefElement) {
let type = prefElement.dataset.type || prefElement.getAttribute("type") || prefElement.tagName;
let name = prefElement.dataset.preference;
Expand Down Expand Up @@ -116,7 +120,7 @@ async function savePref(prefElement) {

// function storageChanged(changes, area) {
// let changedItems = Object.keys(changes);
// console.info(changedItems);
// rwhLogger.info(changedItems);
// // for (let item of changedItems) {
// // if (area == userPrefStorageArea && item == "userPrefs") {
// // this._userPrefs = changes.userPrefs.newValue;
Expand Down Expand Up @@ -159,13 +163,12 @@ async function init() {
if (command) {
switch(command) {
case 'openHeadersTab':
// currently no action to perform
openRwhTab(document.getElementById('headersTab'));
case 'openAboutTab':
openRwhTab(document.getElementById('aboutTab'));
break;
}
// await rwhSettings.remove('options.ui.target.command');
await messenger.storage.local.remove(rwhSettings.optionsPrefix + 'options.ui.target.command');
await rwhSettings.remove('options.ui.target.command');
}

}
Expand Down

0 comments on commit 902f0f1

Please sign in to comment.