Commit 2a0c660c by Edgar HIPP

Update algorithm

parent b868beeb
"use strict";
const _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
// public method for encoding
module.exports.encode = function (input) {
let output = "";
let chr1, chr2, chr3, enc1, enc2, enc3, enc4;
let i = 0;
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
}
else if (isNaN(chr3)) {
enc4 = 64;
}
output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
}
return output;
};
"use strict";
const DOMParser = require("xmldom").DOMParser;
const XMLSerializer = require("xmldom").XMLSerializer;
const DocUtils = {};
DocUtils.xml2Str = function (xmlNode) {
const a = new XMLSerializer();
return a.serializeToString(xmlNode);
};
DocUtils.str2xml = function (str, errorHandler) {
const parser = new DOMParser({errorHandler});
return parser.parseFromString(str, "text/xml");
};
DocUtils.maxArray = function (a) { return Math.max.apply(null, a); };
DocUtils.decodeUtf8 = function (s) {
try {
if (s === undefined) { return undefined; }
// replace Ascii 160 space by the normal space, Ascii 32
return decodeURIComponent(escape(DocUtils.convertSpaces(s)));
}
catch (e) {
const err = new Error("End");
err.properties.data = s;
err.properties.explanation = "Could not decode string to UFT8";
throw err;
}
};
DocUtils.encodeUtf8 = function (s) {
return unescape(encodeURIComponent(s));
};
DocUtils.convertSpaces = function (s) {
return s.replace(new RegExp(String.fromCharCode(160), "g"), " ");
};
DocUtils.pregMatchAll = function (regex, content) {
/* regex is a string, content is the content. It returns an array of all matches with their offset, for example:
regex=la
content=lolalolilala
returns: [{0: 'la',offset: 2},{0: 'la',offset: 8},{0: 'la',offset: 10}]
*/
if (typeof regex !== "object") {
regex = (new RegExp(regex, "g"));
}
const matchArray = [];
const replacer = function () {
const pn = Array.prototype.slice.call(arguments);
pn.pop();
const offset = pn.pop();
// add match so that pn[0] = whole match, pn[1]= first parenthesis,...
pn.offset = offset;
return matchArray.push(pn);
};
content.replace(regex, replacer);
return matchArray;
};
const DocUtils = require("docxtemplater").DocUtils;
module.exports = DocUtils;
"use strict";
const XmlTemplater = require("docxtemplater").XmlTemplater;
const QrCode = require("qrcode-reader");
module.exports = class DocxQrCode {
constructor(imageData, xmlTemplater, imgName, num, getDataFromString) {
this.xmlTemplater = xmlTemplater;
this.imgName = imgName || "";
this.num = num;
this.getDataFromString = getDataFromString;
this.callbacked = false;
this.data = imageData;
if (this.data === undefined) { throw new Error("data of qrcode can't be undefined"); }
this.ready = false;
this.result = null;
}
decode(callback) {
this.callback = callback;
const self = this;
this.qr = new QrCode();
this.qr.callback = function () {
self.ready = true;
self.result = this.result;
const testdoc = new XmlTemplater(this.result,
{fileTypeConfig: self.xmlTemplater.fileTypeConfig,
tags: self.xmlTemplater.tags,
Tags: self.xmlTemplater.Tags,
parser: self.xmlTemplater.parser,
});
testdoc.render();
self.result = testdoc.content;
return self.searchImage();
};
return this.qr.decode({width: this.data.width, height: this.data.height}, this.data.decoded);
}
searchImage() {
const cb = (_err, data) => {
this.data = data || this.data.data;
return this.callback(this, this.imgName, this.num);
};
if (!(this.result != null)) { return cb(); }
return this.getDataFromString(this.result, cb);
}
};
"use strict";
const DocUtils = require("./docUtils");
const imageExtensions = ["gif", "jpeg", "jpg", "emf", "png"];
const imageListRegex = /[^.]+\.([^.]+)/;
const extensionRegex = /[^.]+\.([^.]+)/;
module.exports = class ImgManager {
constructor(zip, fileName) {
constructor(zip, fileName, xmlDocuments) {
this.zip = zip;
this.fileName = fileName;
this.endFileName = this.fileName.replace(/^.*?([a-z0-9]+)\.xml$/, "$1");
}
getImageList() {
const imageList = [];
Object.keys(this.zip.files).forEach(function (path) {
const extension = path.replace(imageListRegex, "$1");
if (imageExtensions.indexOf(extension) >= 0) {
imageList.push({path: path, files: this.zip.files[path]});
}
});
return imageList;
this.xmlDocuments = xmlDocuments;
const relsFileName = this.getRelsFile(fileName);
this.relsDoc = xmlDocuments[relsFileName] || this.createEmptyRelsDoc(xmlDocuments, relsFileName);
}
setImage(fileName, data, options) {
options = options || {};
this.zip.remove(fileName);
return this.zip.file(fileName, data, options);
getRelsFile(fileName) {
let fileParts = fileName.split("/");
fileParts[fileParts.length - 1] = fileParts[fileParts.length - 1] + ".rels";
fileParts = [fileParts[0], "_rels"].concat(fileParts.slice(1));
return fileParts.join("/");
}
hasImage(fileName) {
return this.zip.files[fileName] != null;
createEmptyRelsDoc(xmlDocuments, relsFileName) {
const file = this.zip.files["word/_rels/document.xml.rels"];
const content = DocUtils.decodeUtf8(file.asText());
const relsDoc = DocUtils.str2xml(content);
const relationships = relsDoc.getElementsByTagName("Relationships")[0];
const relationshipChilds = relationships.getElementsByTagName("Relationship");
for (let i = 0, l = relationshipChilds.length; i < l; i++) {
relationships.removeChild(relationshipChilds[i]);
}
xmlDocuments[relsFileName] = relsDoc;
return relsDoc;
}
loadImageRels() {
const file = this.zip.files[`word/_rels/${this.endFileName}.xml.rels`] || this.zip.files["word/_rels/document.xml.rels"];
if (file == null) { return; }
const content = DocUtils.decodeUtf8(file.asText());
this.xmlDoc = DocUtils.str2xml(content);
// Get all Rids
const RidArray = [0];
const iterable = this.xmlDoc.getElementsByTagName("Relationship");
for (let i = 0, tag; i < iterable.length; i++) {
tag = iterable[i];
const id = tag.getAttribute("Id");
const iterable = this.relsDoc.getElementsByTagName("Relationship");
return Array.prototype.reduce.call(iterable, function (max, relationship) {
const id = relationship.getAttribute("Id");
if (/^rId[0-9]+$/.test(id)) {
RidArray.push(parseInt(id.substr(3), 10));
return Math.max(max, parseInt(id.substr(3), 10));
}
}
this.maxRid = DocUtils.maxArray(RidArray);
this.imageRels = [];
return this;
return max;
}, 0);
}
// Add an extension type in the [Content_Types.xml], is used if for example you want word to be able to read png files (for every extension you add you need a contentType)
addExtensionRels(contentType, extension) {
const content = this.zip.files["[Content_Types].xml"].asText();
const xmlDoc = DocUtils.str2xml(content);
let addTag = true;
const defaultTags = xmlDoc.getElementsByTagName("Default");
for (let i = 0, tag; i < defaultTags.length; i++) {
tag = defaultTags[i];
if (tag.getAttribute("Extension") === extension) { addTag = false; }
}
if (addTag) {
const types = xmlDoc.getElementsByTagName("Types")[0];
const newTag = xmlDoc.createElement("Default");
newTag.namespaceURI = null;
newTag.setAttribute("ContentType", contentType);
newTag.setAttribute("Extension", extension);
types.appendChild(newTag);
return this.setImage("[Content_Types].xml", DocUtils.encodeUtf8(DocUtils.xml2Str(xmlDoc)));
const contentTypeDoc = this.xmlDocuments["[Content_Types].xml"];
const defaultTags = contentTypeDoc.getElementsByTagName("Default");
const extensionRegistered = Array.prototype.some.call(defaultTags, function (tag) {
return tag.getAttribute("Extension") === extension;
});
if (extensionRegistered) {
return;
}
const types = contentTypeDoc.getElementsByTagName("Types")[0];
const newTag = contentTypeDoc.createElement("Default");
newTag.namespaceURI = null;
newTag.setAttribute("ContentType", contentType);
newTag.setAttribute("Extension", extension);
types.appendChild(newTag);
}
// Adding an image and returns it's Rid
// Add an image and returns it's Rid
addImageRels(imageName, imageData, i) {
if (i == null) {
i = 0;
}
const realImageName = i === 0 ? imageName : imageName + `(${i})`;
if ((this.zip.files[`word/media/${realImageName}`] != null)) {
if (this.zip.files[`word/media/${realImageName}`] != null) {
return this.addImageRels(imageName, imageData, i + 1);
}
this.maxRid++;
const file = {
const image = {
name: `word/media/${realImageName}`,
data: imageData,
options: {
base64: false,
binary: true,
compression: null,
date: new Date(),
dir: false,
},
};
this.zip.file(file.name, file.data, file.options);
const extension = realImageName.replace(/[^.]+\.([^.]+)/, "$1");
this.zip.file(image.name, image.data, image.options);
const extension = realImageName.replace(extensionRegex, "$1");
this.addExtensionRels(`image/${extension}`, extension);
const relationships = this.xmlDoc.getElementsByTagName("Relationships")[0];
const newTag = this.xmlDoc.createElement("Relationship");
const relationships = this.relsDoc.getElementsByTagName("Relationships")[0];
const newTag = this.relsDoc.createElement("Relationship");
newTag.namespaceURI = null;
newTag.setAttribute("Id", `rId${this.maxRid}`);
const maxRid = this.loadImageRels() + 1;
newTag.setAttribute("Id", `rId${maxRid}`);
newTag.setAttribute("Type", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image");
newTag.setAttribute("Target", `media/${realImageName}`);
relationships.appendChild(newTag);
this.setImage(`word/_rels/${this.endFileName}.xml.rels`, DocUtils.encodeUtf8(DocUtils.xml2Str(this.xmlDoc)));
return this.maxRid;
}
getImageName(id) {
id = id || 0;
const nameCandidate = "Copie_" + id + ".png";
const fullPath = this.getFullPath(nameCandidate);
if (this.hasImage(fullPath)) {
return this.getImageName(id + 1);
}
return nameCandidate;
}
getFullPath(imgName) { return `word/media/${imgName}`; }
// This is to get an image by it's rId (returns null if no img was found)
getImageByRid(rId) {
const relationships = this.xmlDoc.getElementsByTagName("Relationship");
for (let i = 0, relationship; i < relationships.length; i++) {
relationship = relationships[i];
const cRId = relationship.getAttribute("Id");
if (rId === cRId) {
const path = relationship.getAttribute("Target");
if (path.substr(0, 6) === "media/") {
return this.zip.files[`word/${path}`];
}
throw new Error("Rid is not an image");
}
}
throw new Error("No Media with this Rid found");
return maxRid;
}
};
"use strict";
const DocUtils = require("./docUtils");
const DocxQrCode = require("./docxQrCode");
const PNG = require("png-js");
const base64encode = require("./base64").encode;
module.exports = class ImgReplacer {
constructor(xmlTemplater, imgManager) {
this.xmlTemplater = xmlTemplater;
this.imgManager = imgManager;
this.imageSetter = this.imageSetter.bind(this);
this.imgMatches = [];
this.xmlTemplater.numQrCode = 0;
}
findImages() {
this.imgMatches = DocUtils.pregMatchAll(/<w:drawing[^>]*>.*?<a:blip.r:embed.*?<\/w:drawing>/g, this.xmlTemplater.content);
return this;
}
replaceImages() {
this.qr = [];
this.xmlTemplater.numQrCode += this.imgMatches.length;
const iterable = this.imgMatches;
for (let imgNum = 0, match; imgNum < iterable.length; imgNum++) {
match = iterable[imgNum];
this.replaceImage(match, imgNum);
}
return this;
}
imageSetter(docxqrCode) {
if (docxqrCode.callbacked === true) { return; }
docxqrCode.callbacked = true;
docxqrCode.xmlTemplater.numQrCode--;
this.imgManager.setImage(`word/media/${docxqrCode.imgName}`, docxqrCode.data, {binary: true});
return this.popQrQueue(this.imgManager.fileName + "-" + docxqrCode.num, false);
}
getXmlImg(match) {
const baseDocument = `<?xml version="1.0" ?>
<w:document
mc:Ignorable="w14 wp14"
xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"
xmlns:v="urn:schemas-microsoft-com:vml"
xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"
xmlns:w10="urn:schemas-microsoft-com:office:word"
xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml"
xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml"
xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"
xmlns:wp14="http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing"
xmlns:wpc="http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas"
xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup"
xmlns:wpi="http://schemas.microsoft.com/office/word/2010/wordprocessingInk"
xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">${match[0]}</w:document>
`;
const f = function (e) {
if (e === "fatalError") {
throw new Error("fatalError");
}
};
return DocUtils.str2xml(baseDocument, f);
}
replaceImage(match, imgNum) {
const num = parseInt(Math.random() * 10000, 10);
let xmlImg;
try {
xmlImg = this.getXmlImg(match);
}
catch (e) {
return;
}
const tagrId = xmlImg.getElementsByTagName("a:blip")[0];
if (tagrId == null) { throw new Error("tagRiD undefined !"); }
const rId = tagrId.getAttribute("r:embed");
const tag = xmlImg.getElementsByTagName("wp:docPr")[0];
if (tag == null) { throw new Error("tag undefined"); }
// if image is already a replacement then do nothing
if (tag.getAttribute("name").substr(0, 6) === "Copie_") { return; }
const imgName = this.imgManager.getImageName();
this.pushQrQueue(this.imgManager.fileName + "-" + num, true);
const newId = this.imgManager.addImageRels(imgName, "");
this.xmlTemplater.imageId++;
const oldFile = this.imgManager.getImageByRid(rId);
this.imgManager.setImage(this.imgManager.getFullPath(imgName), oldFile.data, {binary: true});
tag.setAttribute("name", `${imgName}`);
tagrId.setAttribute("r:embed", `rId${newId}`);
const imageTag = xmlImg.getElementsByTagName("w:drawing")[0];
if (imageTag == null) { throw new Error("imageTag undefined"); }
const replacement = DocUtils.xml2Str(imageTag);
this.xmlTemplater.content = this.xmlTemplater.content.replace(match[0], replacement);
return this.decodeImage(oldFile, imgName, num, imgNum);
}
decodeImage(oldFile, imgName, num, imgNum) {
const mockedQrCode = {xmlTemplater: this.xmlTemplater, imgName: imgName, data: oldFile.asBinary(), num: num};
if (!/\.png$/.test(oldFile.name)) {
return this.imageSetter(mockedQrCode);
}
return ((imgName) => {
const base64 = base64encode(oldFile.asBinary());
const binaryData = new Buffer(base64, "base64");
const png = new PNG(binaryData);
const finished = (a) => {
png.decoded = a;
try {
this.qr[imgNum] = new DocxQrCode(png, this.xmlTemplater, imgName, num, this.getDataFromString);
return this.qr[imgNum].decode(this.imageSetter);
}
catch (e) {
return this.imageSetter(mockedQrCode);
}
};
return png.decode(finished);
})(imgName);
}
};
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment