Skip to content

A fully open source & end-to-end encrypted note taking alternative to Evernote.

feat: use regex to parse attachments

thecodrrf4ee495d6bac
diff --git a/packages/core/__tests__/utils/index.js b/packages/core/__tests__/utils/index.js
index 72b3c999f..3407cba97 100644
--- a/packages/core/__tests__/utils/index.js
+++ b/packages/core/__tests__/utils/index.js
@@ -34,7 +34,7 @@ var TEST_NOTE = {
},
};
-const IMG_CONTENT = `"<p>This is a note for me.j</p>\n<p><img src=\"data:image/png;base64,iVBORw0K\" class=\"attachment\" alt=\"Screenshot_20210915_102333.png\" data-mime=\"image/png\" data-hash=\"d3eab72e94e3cd35\" data-filename=\"Screenshot_20210915_102333.png\" data-size=\"68609\" style=\"float: left;\" /> &nbsp;</p>\n<p>&nbsp;</p>"`;
+const IMG_CONTENT = `<p>This is a note for me.j</p>\n<p><img src="data:image/png;base64,iVBORw0K" class="attachment" alt="Screenshot_20210915_102333.png" data-mime="image/png" data-hash="d3eab72e94e3cd35" data-filename="Screenshot_20210915_102333.png" data-size="68609" style="float: left;" /> &nbsp;</p>\n<p>&nbsp;</p>`;
const LONG_TEXT =
"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
diff --git a/packages/core/collections/content.js b/packages/core/collections/content.js
index 4fc893ad7..b8b887902 100644
--- a/packages/core/collections/content.js
+++ b/packages/core/collections/content.js
@@ -103,9 +103,7 @@ export default class Content extends Collection {
const allAttachments = this._db.attachments.all;
const content = getContentFromData(contentItem.type, contentItem.data);
- const { data, attachments } = await content.extractAttachments(
- (data, type) => this._db.attachments.save(data, type)
- );
+ const { data, attachments } = content.extractAttachments();
const noteAttachments = allAttachments.filter((attachment) =>
hasItem(attachment.noteIds, contentItem.noteId)
@@ -127,6 +125,18 @@ export default class Content extends Collection {
}
for (let attachment of toAdd) {
+ if (attachment.data && attachment.type) {
+ const { key, metadata } = await this._db.attachments.save(
+ attachment.data,
+ attachment.type
+ );
+ attachment = {
+ type: attachment.type,
+ filename: metadata.hash,
+ ...metadata,
+ key,
+ };
+ }
await this._db.attachments.add(attachment, contentItem.noteId);
}
diff --git a/packages/core/content-types/__tests__/tiny.test.js b/packages/core/content-types/__tests__/tiny.test.js
index 81f4948df..34653ed5f 100644
--- a/packages/core/content-types/__tests__/tiny.test.js
+++ b/packages/core/content-types/__tests__/tiny.test.js
@@ -3,9 +3,7 @@ import Tiny from "../tiny";
test("img src is empty after extract attachments", async () => {
const tiny = new Tiny(IMG_CONTENT);
- const result = await tiny.extractAttachments(async () => {
- return { key: "hello", metadata: {} };
- });
+ const result = tiny.extractAttachments();
expect(result.attachments.length).toBe(1);
expect(result.data).not.toContain(`src="data:image/png;`);
expect(result.data).not.toContain(`src=`);
diff --git a/packages/core/content-types/tiny.js b/packages/core/content-types/tiny.js
index caccbfe5f..256f88eb8 100644
--- a/packages/core/content-types/tiny.js
+++ b/packages/core/content-types/tiny.js
@@ -4,7 +4,13 @@ import dataurl from "../utils/dataurl";
var converter = new showdown.Converter();
converter.setFlavor("original");
+const HASH_REGEX = /data-hash="(\S+)"/g;
+const SRC_HASH_REGEX =
+ /src="data:(image\/.+);base64,(\S+)"|data-hash="(\S+)"/gm;
+const TAG_REGEX = /<(span|img)[^>]+/gm;
+
const splitter = /\W+/gm;
+
class Tiny {
constructor(data) {
this.data = data;
@@ -55,91 +61,88 @@ class Tiny {
}
async insertMedia(getData) {
- if (!("HTMLParser" in global)) return;
-
- let doc = HTMLParser.createElement("div");
- doc.innerHTML = this.data;
- const attachmentElements = doc.querySelectorAll("img");
-
- for (var i = 0; i < attachmentElements.length; ++i) {
- const attachment = attachmentElements[i];
- switch (attachment.tagName) {
- case "IMG": {
- const hash = getDatasetAttribute(attachment, "hash");
- if (!hash) continue;
-
- const src = await getData(hash, {
- total: attachmentElements.length,
- current: i,
- });
- if (!src) continue;
- attachment.setAttribute("src", src);
- break;
- }
+ let document = this.data;
+
+ const matches = Array.from(this.data.matchAll(TAG_REGEX));
+ for (let i = 0; i < matches.length; ++i) {
+ const match = matches[i];
+ const nodeName = match[1];
+
+ if (nodeName === "img") {
+ const node = match[0];
+
+ const hashMatch = node.match(HASH_REGEX);
+ if (!hashMatch) continue;
+
+ const [attribute, hash] = hashMatch;
+
+ const src = await getData(hash, {
+ total: matches.length,
+ current: i,
+ });
+ if (!src) continue;
+
+ const srcAttribute = createAttribute("src", src);
+ const replacedNode = replaceAt(
+ node,
+ hashMatch.index,
+ attribute,
+ srcAttribute
+ );
+ document = replaceAt(this.data, match.index, node, replacedNode);
}
}
- return doc.innerHTML;
+ return document;
}
- async extractAttachments(store) {
- if (!("HTMLParser" in global)) return;
-
- let doc = HTMLParser.createElement("div");
- doc.innerHTML = this.data;
- const attachmentElements = doc.querySelectorAll("img,.attachment");
-
+ extractAttachments() {
const attachments = [];
- for (var i = 0; i < attachmentElements.length; ++i) {
- const attachment = attachmentElements[i];
- switch (attachment.tagName) {
- case "IMG": {
- if (!getDatasetAttribute(attachment, "hash")) {
- const src = attachment.getAttribute("src");
- if (!src) continue;
-
- const { data, mime } = dataurl.toObject(src);
- if (!data) continue;
-
- const type =
- getDatasetAttribute(attachment, "mime") || mime || "image/jpeg";
- const { key, metadata } = await store(data, "base64");
- setDatasetAttribute(attachment, "hash", metadata.hash);
-
- attachments.push({
- type,
- filename:
- getDatasetAttribute(attachment, "filename") || metadata.hash,
- ...metadata,
- key,
- });
- } else {
- attachments.push({
- hash: getDatasetAttribute(attachment, "hash"),
- });
- }
- attachment.removeAttribute("src");
+ let document = this.data;
+
+ for (let match of this.data.matchAll(TAG_REGEX)) {
+ const nodeName = match[1];
+ const node = match[0];
+ const attachment = { hash: undefined, data: undefined, type: undefined };
+
+ switch (nodeName) {
+ case "img": {
+ const replacedNode = node.replace(
+ SRC_HASH_REGEX,
+ (match, mime, data, hash) => {
+ if (mime) attachment.type = mime;
+ if (data) attachment.data = data;
+ if (hash) attachment.hash = hash;
+ return match.startsWith("src") ? "" : match;
+ }
+ );
+ document = replaceAt(this.data, match.index, node, replacedNode);
break;
}
- default: {
- if (!getDatasetAttribute(attachment, "hash")) continue;
- attachments.push({
- hash: getDatasetAttribute(attachment, "hash"),
- });
+ case "span": {
+ const matches = node.match(HASH_REGEX);
+ if (!matches) continue;
+ const [_match, hash] = matches;
+ attachments.push({ hash });
break;
}
}
+ if (attachment.hash || attachment.data) attachments.push(attachment);
}
- return { data: doc.innerHTML, attachments };
+
+ return { data: document, attachments };
}
}
export default Tiny;
-function getDatasetAttribute(element, attribute) {
- return element.getAttribute(`data-${attribute}`);
+function replaceAt(str, index, match, replacement) {
+ let start = str.slice(0, index);
+ start += replacement;
+ start += str.slice(index + match.length);
+ return start;
}
-function setDatasetAttribute(element, attribute, value) {
- return element.setAttribute(`data-${attribute}`, value);
+function createAttribute(key, value) {
+ return `${key}="${value}"`;
}
function getHeadlineFromText(text) {