Remove duplicated code

1.1.101
Chris Fuertes 4 years ago
parent 34f65578f3
commit 8548d92c07

@ -443,9 +443,7 @@ let pEpHdrView = {
return message;
}
function updateSubjectFromMessage(message) {
}
function extractInnerBodyWithOriginalMessage(originalMessage) {
return async function extractInnerBody(message) {
@ -539,549 +537,7 @@ let pEpHdrView = {
});
}).catch(err => {
let pEpController = ChromeUtils.import("chrome://p4t/content/p4tb.js").pEpController;
const RATING_COLOR_NO_COLOR = "no-color";
const PGP_MESSAGE_HEADER = "-----BEGIN PGP MESSAGE-----";
const PGP_MESSAGE_FOOTER = "-----END PGP MESSAGE-----";
const OUTER_TAG = "pEp-Wrapped-Message-Info: OUTER";
const TAG_PRIVACY_NODE_ID = "pEp-msghdr-privacy-label";
function updatePrivacy(privacyStatus, msgHdr) {
let privacyTextClass = pEpController.privacyStatusToTextClass(privacyStatus);
let oldNode = document.getElementById(TAG_PRIVACY_NODE_ID);
if (oldNode) {
oldNode.parentNode.removeChild(oldNode);
}
// Add privacy bar to message
let newNode = document.createXULElement("hbox");
newNode.classList.add("header-privacy-bar");
newNode.classList.add(privacyTextClass.class);
newNode.id = TAG_PRIVACY_NODE_ID;
let privacyLabel = document.createTextNode(privacyTextClass.text);
newNode.appendChild(privacyLabel);
let mainHeaderAreaNode = document.getElementById("msgHeaderView");
mainHeaderAreaNode.parentNode.appendChild(newNode);
// Set property for message list
msgHdr.setStringProperty("pEpPrivacy", privacyStatus)
}
function reloadPrivacy(msgHdr) {
let privacyStatus = msgHdr.getStringProperty("pEpPrivacy");
if (!privacyStatus) {
// Remove privacy bar if there's no status to show
let oldNode = document.getElementById(TAG_PRIVACY_NODE_ID);
if (oldNode) {
oldNode.parentNode.removeChild(oldNode);
}
return;
}
updatePrivacy(privacyStatus, msgHdr);
}
function getINNERBody(body) {
let INNER_TAG = "pEp-Wrapped-Message-Info: INNER\r\n";
if (body.indexOf(INNER_TAG) < 0) return body;
return body.slice(body.indexOf(INNER_TAG) + INNER_TAG.length);
}
function reformatBody(body) {
let gTxtConverter = Cc["@mozilla.org/txttohtmlconv;1"].createInstance(Ci.mozITXTToHTMLConv);
let convFlags = Ci.mozITXTToHTMLConv.kURLs;
// start processing the message
body = body.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
const lines = body.split(/\n/);
let oldCiteLevel = 0;
let citeLevel = 0;
let preface = "";
const logLineStart = {
value: 0
};
let isSignature = false;
for (let i = 0; i < lines.length; i++) {
preface = "";
oldCiteLevel = citeLevel;
if (lines[i].search(/^[> \t]*>$/) === 0)
lines[i] += " ";
citeLevel = gTxtConverter.citeLevelTXT(lines[i], logLineStart);
if (citeLevel > oldCiteLevel) {
preface = '</pre>';
for (let j = 0; j < citeLevel - oldCiteLevel; j++) {
preface += '<blockquote type="cite">';
}
preface += '<pre wrap="">\n';
} else if (citeLevel < oldCiteLevel) {
preface = '</pre>';
for (let j = 0; j < oldCiteLevel - citeLevel; j++)
preface += "</blockquote>";
preface += '<pre wrap="">\n';
}
if (logLineStart.value > 0) {
preface += '<span class="moz-txt-citetags">' +
gTxtConverter.scanTXT(lines[i].substr(0, logLineStart.value), convFlags) +
'</span>';
} else if (lines[i] == "-- ") {
preface += '<div class="moz-txt-sig">';
isSignature = true;
}
lines[i] = preface + gTxtConverter.scanTXT(lines[i].substr(logLineStart.value), convFlags);
}
const r = '<pre wrap="">' + lines.join("\n") + (isSignature ? '</div>' : '') + '</pre>';
return r;
}
function updateBody(newBody) {
console.log("updateBody: ", newBody);
let panel = getMessagePane();
let bodyElement = panel.document.getElementsByTagName("body")[0];
let node = bodyElement.firstChild;
while (node) {
if (node.nodeName === "DIV" || node.nodeName === "PRE") {
if (node.textContent.indexOf(PGP_MESSAGE_HEADER)) {
node.innerHTML = newBody;
return;
}
}
node = node.nextSibling;
}
}
/* global currentHeaderData: false, gViewAllHeaders: false, gExpandedHeaderList: false, goDoCommand: false, HandleSelectedAttachments: false */
function updateSubject(newSubject) {
console.log("updateSubject:", newSubject);
//FIXME VALIDATE THAT THE MESSAGE STILL THE SAME AND NOT REPLACE IT WITH A PREVIOUS MESSAGE SUBJECT
let subjectBox = document.getElementById("expandedsubjectBox");
subjectBox.headerValue = newSubject;
gFolderDisplay.selectedMessage.subject = newSubject;
}
function addAttachment(attachment) {
let attachmentString = "";
attachmentString += `Content-type: ${attachment.mime_type};\n`;
if (attachment.filename) {
attachmentString += `Content-Disposition: inline; filename="${attachment.filename}"\n\n`;
} else {
attachmentString += `Content-Disposition: inline;\n\n`;
}
attachmentString += `${atob(attachment.value)}\n`;
return attachmentString;
}
let _parseAddress = (address) => {
let hdr = Cc["@mozilla.org/messenger/headerparser;1"].createInstance(Ci.nsIMsgHeaderParser);
let mails = hdr.parseEncodedHeader(address, "utf-8");
return mails.map((mail) => {
return {
address: mail.email,
username: mail.name
};
})
};
let copyMessageToFolder = (msgHdr, content) => {
if (!pEpController.isTrustedServer(msgHdr.folder.URI)) return;
let msgFolder = msgHdr.folder;
let isDraftOrTemplate = false;
let msgFlags = 0;
let msgKeywords = "";
let msgWindow = null;
let msgArray = Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray);
msgArray.appendElement(msgHdr, false);
// Create temp file to upload to smpt server
let tempFile = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties).get("TmpD", Ci.nsIFile);
tempFile.append("pEpMsg.eml");
tempFile.createUnique(0, 0o600);
// ensure that file gets deleted on exit, if something goes wrong ...
let extAppLauncher = Cc["@mozilla.org/mime;1"].getService(Ci.nsPIExternalAppLauncher);
extAppLauncher.deleteTemporaryFileOnExit(tempFile);
let outputStream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);
outputStream.init(tempFile, 2, 0x200, false); // open as "write only"
outputStream.write(content, content.length);
outputStream.close();
let file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
file.initWithPath(tempFile.path);
let msgCopyService = Cc["@mozilla.org/messenger/messagecopyservice;1"].getService(Ci.nsIMsgCopyService);
let copyListener = {
QueryInterface: function (iid) {
if (iid.equals(Ci.nsIMsgCopyServiceListener) || iid.equals(Ci.nsISupports)) {
return this;
}
throw Components.results.NS_NOINTERFACE;
},
GetMessageId: function (messageId) {
},
SetMessageKey: function (key) {
},
OnStopCopy: function (statusCode) {
console.log("(6)");
console.debug("pepmsghdrview.js: copyListener: OnStopCopy()\n");
if (statusCode !== 0) {
console.log("(7) ERROR");
console.error("pepmsghdrview.js: Error copying message: " + statusCode + "\n");
}
console.debug("pepmsghdrview.js: Copy complete\n");
try {
let urlListener = null;
msgFolder.getNewMessages(msgWindow, urlListener);
let deleteStorage = false;
let isMove = false;
let listener = null;
let allowUndo = false;
msgFolder.deleteMessages(msgArray, msgWindow, deleteStorage, isMove, listener, allowUndo);
tempFile.remove(false);
} catch (ex) {
try {
file.remove(false);
} catch (ex) {
console.debug("pepmsghdrview.js: Could not delete temp file\n");
}
}
}
};
msgCopyService.CopyFileMessage(file, msgFolder, msgHdr, isDraftOrTemplate, msgFlags, msgKeywords, copyListener, msgWindow);
};
let readMailFromUri = (msgUri) => {
let msgWindow = Cc["@mozilla.org/messenger/msgwindow;1"].createInstance();
//msgWindow = msgWindow.QueryInterface(Ci.nsIMsgWindow);
let msgStream = Cc["@mozilla.org/network/sync-stream-listener;1"].createInstance();
msgStream = msgStream.QueryInterface(Ci.nsIInputStream);
let messenger = Cc["@mozilla.org/messenger;1"].getService(Ci.nsIMessenger);
let msgService = messenger.messageServiceFromURI(msgUri);
let scriptInputStream = Cc["@mozilla.org/scriptableinputstream;1"].createInstance();
scriptInputStream = scriptInputStream.QueryInterface(Ci.nsIScriptableInputStream);
scriptInputStream.init(msgStream);
try {
msgService.streamMessage(msgUri, // uri of message to stream
msgStream, // a stream listener listening to the message
msgWindow, // a nsIMsgWindow for progress and status feedback
null, // a nsIUrlListener that is notified when url starts and stops
false, // it will create a stream converter from message rfc2822 to
null // Header added to the URI. e.g., header=filter
);
} catch (ex) {
console.debug("Error while reading mail from server", ex);
}
// Get only the PGP message
let keyFound = false;
let content = "";
let str = "";
const INPUTSTREAM_READING_SIZE = 512;
while (scriptInputStream.available()) {
str = scriptInputStream.read(INPUTSTREAM_READING_SIZE);
content += str;
}
return content;
};
let getCurrentMessageURI = () => {
if (gFolderDisplay.selectedMessages.length === 1) {
return gFolderDisplay.selectedMessageUris[0];
}
return null;
};
let pEpHdrView = {
init: function () {
console.log("pEpHdrView: init()", this);
window.addEventListener("load", this.onLoadListener.bind(this), false);
},
destroy: function () {
console.log("pEpHdrView: destroy()");
},
onLoadListener: function (event) {
console.log("pepmsghdrview.js: onLoadListener()", this);
let onStartHeadersMessageListener = () => {
let messagePanelFrame = getMessagePane();
console.log("pepmsghdrview.js: onLoadMsgPanelFrameListener(), frame: ", messagePanelFrame);
if (messagePanelFrame != null) {
console.log("pepmsghdrview.js: onLoadListener() added listener");
messagePanelFrame.addEventListener("load", this.onLoadMsgPanelFrameListener.bind(this), false);
}
};
let onEndHeadersMessageListener = () => {
};
gMessageListeners.push({
onStartHeaders: onStartHeadersMessageListener,
onEndHeaders: onEndHeadersMessageListener
});
onStartHeadersMessageListener();
onEndHeadersMessageListener();
},
onLoadMsgPanelFrameListener: function (event) {
console.log("pepmsghdrview.js: onLoadMsgPanelFrameListener() CurrentHeaderData", currentHeaderData);
console.log("pepmsghdrview.js: onLoadMsgPanelFrameListener() FolderDisplay:", gFolderDisplay);
let selectedMessage = gFolderDisplay.selectedMessage;
let msgHdr = selectedMessage.folder.GetMessageHeader(selectedMessage.messageKey);
// Load stored privacy label
reloadPrivacy(msgHdr);
// Load stored decrypted message
let decryptedMessageStored = msgHdr.getStringProperty("pEpDecryptedMessage");
if (decryptedMessageStored) {
updateBody(decryptedMessageStored);
return;
}
// read email from tb
let currentUri = getCurrentMessageURI();
if (currentUri === null) {
return;
}
let mimeMessage;
try {
mimeMessage = readMailFromUri(currentUri);
} catch (e) {
console.debug("Errors while reading message from uri", e);
}
// Process mail
this.processMail(mimeMessage, msgHdr);
},
processMail: function (mimeMessage, msgHdr) {
function updateStuff(body, subject, headers, mime) {
//let {body, subject, headers, mime} = msg;
updateBody(body);
updateSubject(subject);
if (headers) {
headers.setStringProperty("pEpDecryptedMessage", body);
copyMessageToFolder(headers, mime);
}
}
function checkAndReplaceLongMsg(message) {
if (message.longmsg === "") {
for (let attachment of message.attachments) {
if (attachment.mime_type === "application/octet-stream") {
message.longmsg = atob(attachment.value);
break;
}
}
}
return message;
}
function setPrivacyStatusFromHeader(message) {
if (message.opt_fields && message.opt_fields.includes("X-EncStatus")) {
let color;
switch (message.opt_fields["X-EncStatus"]) {
case "have_no_key":
case "unreliable":
case "unencrypted":
color = "no-color";
break;
case "reliable":
color = "yellow";
break;
case "trusted":
case "trusted_and_anonymized":
case "fully_anonymous":
color = "green";
break;
case "mistrust":
case "b0rken":
case "under_attack":
color = "red";
break;
default:
color = "no-color";
}
updatePrivacy(color, msgHdr);
}
return message;
}
function validateDecryptOutput(message) {
if (message === null) {
throw new Error("decryptMailWithMessage(): Empty response");
}
return message;
}
function updatePrivacyFromMessage(message) {
pEpController.getPrivacyColorFromRating(message.rating).then(colorRating => {
updatePrivacy(colorRating, msgHdr);
}
);
return message;
}
function updateSubjectFromMessage(message) {
}
function extractInnerBodyWithOriginalMessage(originalMessage) {
return async function extractInnerBody(message) {
if (message.longmsg.indexOf(OUTER_TAG) < 0) {
return {
body: reformatBody(getINNERBody(message.longmsg) + "\r\n\r\n"),
subject: message.shortmsg,
headers: msgHdr,
mime: originalMessage.longmsg
};
}
if (!(message.attachments && message.attachments.length > 0)) {
throw new Error("decryptMailWithMessage(): Inner body found without attachments");
}
for (let attachment of message.attachments) {
if (attachment.mime_type !== "text/rfc822") continue;
return await pEpController.messageFromMIME(atob(attachment.value)).then((decoded_message) => {
if (typeof decoded_message.opt_fields === "undefined") {
decoded_message.opt_fields.push(originalMessage.opt_fields);
} else {
decoded_message.opt_fields = originalMessage.opt_fields;
}
let newBody;
if (decoded_message.longmsg_formatted) {
newBody = decoded_message.longmsg_formatted;
} else {
newBody = reformatBody(getINNERBody(decoded_message.longmsg) + "\r\n\r\n");
}
let mimeBody = originalMessage.longmsg.substr(originalMessage.longmsg.indexOf("Content-Type: message/rfc822\r\n\r\n") + "Content-Type: message/rfc822\r\n\r\n".length).replace("Content-Disposition: inline; filename=\"msg.txt\"\r\n", "");
return {
body: newBody,
subject: decoded_message.shortmsg || originalMessage.shortmsg,
headers: msgHdr,
mime: mimeBody
};
});
}
}
}
async function updateBodyFromMessage(message) {
if (message.longmsg_formatted) {
return {
body: message.longmsg_formatted,
subject: message.shortmsg,
headers: msgHdr,
mime: message.longmsg
};
}
return await pEpController.messageFromMIME(message.longmsg).then(extractInnerBodyWithOriginalMessage(message));
}
// controller
// .messageFromMIME(mimeMessage)
// .then(checkAndReplaceLongMsg)
// .then(setPrivacyStatusFromHeader)
// .then(controller.decryptMailWithMessage)
// .then(validateDecryptOutput)
// .then(updatePrivacyFromMessage)
// .then(updateBodyFromMessage)
// .then(updateStuff)
//
// .catch( err => {
// console.log("pepmsghdrview.js: onLoadMsgPanelFrameListener(): decryptMailWithMessage", err)
// });
pEpController.messageFromMIME(mimeMessage).then(message => {
message = checkAndReplaceLongMsg(message);
setPrivacyStatusFromHeader(message);
pEpController.decryptMailWithMessage(message).then(decryptedmessage => {
validateDecryptOutput(decryptedmessage);
updatePrivacyFromMessage(decryptedmessage);
updateBodyFromMessage(decryptedmessage).then((msg) => {
updateStuff(msg.body, msg.subject, msg.headers, msg.mime);
});
}).catch(err => {
console.log("pepmsghdrview.js: onLoadMsgPanelFrameListener(): decryptMailWithMessage", err)
});
}).catch(err => {
console.log("pepmsghdrview.js: onLoadMsgPanelFrameListener(): getMimeDecodedMessage", err)
});
}
};
window.addEventListener('load', pEpHdrView.init.bind(pEpHdrView), false); console.log("pepmsghdrview.js: onLoadMsgPanelFrameListener(): decryptMailWithMessage", err)
console.log("pepmsghdrview.js: processMail(): messageFromMIME()", err);
});
}).catch(err => {
console.log("pepmsghdrview.js: onLoadMsgPanelFrameListener(): getMimeDecodedMessage", err)

Loading…
Cancel
Save