Skip to content

Commit

Permalink
Tickets papnkukn#32 and papnkukn#33
Browse files Browse the repository at this point in the history
  • Loading branch information
joaoaugustogrobe committed Apr 5, 2023
1 parent 5f4abb6 commit 4ec7d67
Showing 1 changed file with 42 additions and 3 deletions.
45 changes: 42 additions & 3 deletions lib/eml-format.js
Original file line number Diff line number Diff line change
Expand Up @@ -173,9 +173,7 @@ var emlformat = {
//Convert =0D to '\r', =20 to ' ', etc.
if (!charset || charset == "utf8" || charset == "utf-8") {
return s
.replace(/=([\w\d]{2})=([\w\d]{2})=([\w\d]{2})/gi, function(matcher, p1, p2, p3, offset, string) { return Buffer.from([ parseInt(p1, 16), parseInt(p2, 16), parseInt(p3, 16) ]).toString("utf8"); })
.replace(/=([\w\d]{2})=([\w\d]{2})/gi, function(matcher, p1, p2, offset, string) { return Buffer.from([ parseInt(p1, 16), parseInt(p2, 16) ]).toString("utf8"); })
.replace(/=([\w\d]{2})/gi, function(matcher, p1, offset, string) { return String.fromCharCode(parseInt(p1, 16)); })
.replace(/((=\w{2}((=)?\r?\n)?){1,})+/g, (matcher) => this.decodeUtf8String(matcher))
.replace(/=\r?\n/gi, ""); //Join line
}
else {
Expand All @@ -184,6 +182,47 @@ var emlformat = {
.replace(/=([\w\d]{2})/gi, function(matcher, p1, offset, string) { return iconv.decode(Buffer.from([ parseInt(p1, 16) ]), charset); })
.replace(/=\r?\n/gi, ""); //Join line
}
},

decodeUtf8String: function(inputStr) {
function decodeSequence(match) {
let bytes = match.match(/(?<=\=)[0-9A-Fa-f]{2}/g)
if (!bytes) return match;
bytes = bytes.map(b => parseInt(b, 16));
return recursiveDecodeSequence(bytes)
}

function recursiveDecodeSequence(bytes) {
let byte1 = bytes[0];
if (!byte1) return ""; // exit of recursion

if (byte1 <= 0x7F) {
return String.fromCharCode(byte1) + recursiveDecodeSequence(bytes.slice(1));
}
if (byte1 >= 0xC0 && byte1 <= 0xDF) {
let byte2 = bytes[1];
let codePoint = ((byte1 & 0x1F) << 6) | (byte2 & 0x3F);
return String.fromCharCode(codePoint) + recursiveDecodeSequence(bytes.slice(2));
}
if (byte1 >= 0xE0 && byte1 <= 0xEF) {
let byte2 = bytes[1];
let byte3 = bytes[2];
let codePoint = ((byte1 & 0x0F) << 12) | ((byte2 & 0x3F) << 6) | (byte3 & 0x3F);
return String.fromCharCode(codePoint) + recursiveDecodeSequence(bytes.slice(3));
}
if (byte1 >= 0xF0 && byte1 <= 0xF7) {
let byte2 = bytes[1];
let byte3 = bytes[2];
let byte4 = bytes[3];
let codePoint = ((byte1 & 0x07) << 18) | ((byte2 & 0x3F) << 12) | ((byte3 & 0x3F) << 6) | (byte4 & 0x3F);
return String.fromCodePoint(codePoint) + recursiveDecodeSequence(bytes.slice(4));
}

return "�";
}
return inputStr
.replace(/((=)?\r?\n)?/g, "") // handle line break
.replace(/(?:(?:=\w{2}){1,}\r?\n?)+/g, decodeSequence);
}
};

Expand Down

0 comments on commit 4ec7d67

Please sign in to comment.