/* eslint-disable no-console */ import Inject, { RegisterScoped } from "@entity-access/entity-access/dist/di/di.js"; import HtmlTransform, { TransformContext } from "./HtmlTransform.js"; import { RegExpExtra } from "../../../protocols/core/RegExpExtra.js"; import SocialMailContext from "../../model/SocialMailContext.js"; import AppFile from "../../model/entities/AppFile.js"; import EncryptionService from "../encryption/EncryptionService.js"; import ChannelUrlService from "../channels/ChannelUrlService.js"; import XNode from "@entity-access/server-pages/dist/html/XNode.js"; import { Base36 } from "../../../common/Base36.js"; import EmailCommands from "../../../protocols/core/EmailCommands.js"; const maxAttachmentSize = 25*1024*1024; @RegisterScoped export default class BlogContentTransformer { @Inject db: SocialMailContext; @Inject ec: EncryptionService; @Inject urlService: ChannelUrlService; cache = {} as Record; /** * This method replaces, * 1. Images/Videos with absolute urls with CDN. * 2. Hash Tags with anchor tag with additional attributes. * 3. Time with time tag with additional attributes. * 4. `cid` urls with absolute file url to avoid round trip by client. * @param param0 */ async sanitizeExternalResources({ emailID, kEmailID36 = Base36.encode(emailID), html, prefix, blog = void 0, senderDomain = void 0, senderEmail = void 0, messageID, listID = void 0, unsubscribeLink = void 0, trackerUrl = void 0 }) { const t = new HtmlTransform(html); const eDomain = senderDomain ? this.ec.general.encrypt(senderDomain) : void 0; const postID = this.ec.general.encrypt(emailID); const { urlService } = this; for(const c of t.all()) { const { node, element } = c; if (c.isTextNode) { const parent = node.parentElement; if (!/^(STYLE|SCRIPT|A)$/.test(parent.tagName)) { const v = RegExpExtra.replaceLinks(node.nodeValue, listID ? blog : void 0); // content has been replaced... if (v !== node.nodeValue) { c.replaceNodeWithHtml(v); } } continue; } if (!c.isElement) { continue; } if (prefix) { c.replaceSrc(prefix); c.replaceSrc(prefix, "srcset"); c.replaceBackground(prefix); } if (element.getAttribute("data-stream-enabled")) { await this.updateStream(c, { emailID, eDomain, postID }); continue; } const hashTag = element.getAttribute("hash-tag"); if (hashTag) { if(element.tagName === "A") { element.setAttribute("href", `/${blog}/tag/${hashTag.replace(/^#+/, "")}`); } } const contentID = element.getAttribute("data-content-id"); if (contentID) { const file = await this.getAttachment(emailID, contentID); if (file) { if (/video/i.test(file.contentType)) { // add poster url... element.setAttribute("poster", urlService.toImageUrl({ eDomain, postID, file, publicRead: true })); element.setAttribute("src", urlService.toWebMUrl({ eDomain, postID, file, publicRead: true })); } else { element.setAttribute("src", urlService.toImageUrl({ eDomain, postID, file, size: 0, publicRead: true })); } } continue; } // check for cid: for (const a of c.iterateAttributes(["src", "href"])) { if (!a.value?.startsWith("cid:")) { continue; } const file = await this.getAttachment(emailID, a.value); if (!file) { continue; } element.setAttribute("data-original-src", a.value); element.setAttribute("data-content-id", file.contentID); if (/video/i.test(file.contentType)) { if (a.name === "href") { element.setAttribute(a.name, urlService.toWebMLinkUrl({ eDomain, postID, file })); } else { // add poster url... element.setAttribute("poster", urlService.toImageUrl({ eDomain, postID, file, publicRead: true })); element.setAttribute(a.name, urlService.toWebMUrl({ eDomain, postID, file, publicRead: true })); } } else { element.setAttribute(a.name, urlService.toImageUrl({ eDomain, postID, file, size: 0 })); } } } await t.commit(); if (trackerUrl) { const clean = t.root; let trackerImg = clean.querySelector(`*[data-social-mail-tracker]`) as HTMLImageElement; if (!trackerImg) { trackerImg = t.root.ownerDocument.createElement("img"); clean.appendChild(trackerImg); } trackerImg.setAttribute("data-social-mail-tracker","tracker"); trackerImg.src = trackerUrl; trackerImg.style.width = "1px"; trackerImg.style.height = "1px"; trackerImg.style.margin = "0"; trackerImg.style.opacity = "0"; } const { root } = t; if (listID) { try { let emojiBar = root.querySelector(`:not(blockquote,details) [data-social-mail-commands="emoji-bar"]`); if (!emojiBar) { emojiBar = root.ownerDocument.createElement("footer"); emojiBar.setAttribute("data-social-mail-commands", "emoji-bar"); root.ownerDocument.body.appendChild(emojiBar); } emojiBar.setAttribute("style", "border: solid 1px lightgray;border-radius: 9999px;padding: 2px;padding-left: 5px;" + "padding-right: 5px;display: table;margin-top: 20px;width: 100%;box-sizing: border-box;"); const emojiButton = (emoji, { label = "", title=label, body = emoji, mail = emoji, style="", href = `mailto:${senderEmail}?subject=${EmailCommands.encode({ emoji, kEmailID36, messageID })}&body=${body}&in-reply-to=${messageID}` } = {}) => (({emoji}{label} ) as XNode).render(); emojiBar.innerHTML = ` ${ emojiButton("👍", { title: "Great" })} ${ emojiButton("❤️", { title: "Love it" })} ${ emojiButton("🙂", { title: "Good" })} ${ emojiButton("🙏", { title: "Thank you" })} ${emojiButton("💬", { label: "Reply", body: "" })} ${ emojiButton("❌", { label: "Unsubscribe", href: unsubscribeLink, style: "display:table-cell; text-align: right;"})} `; } catch (error) { console.error(error); } } return t.html; } async getAttachment(emailID, cid) { cid = cid.split(":").pop(); const cidTagged = `<${cid}>`; return this.cache[cid] ??= await this.db.appFiles.where({ emailID, cid, cidTagged}, (x, p) => x.emailID === p.emailID && (x.contentID === p.cid || x.contentID === p.cidTagged)) .first(); } async updateStream(c: TransformContext, { emailID, eDomain, postID }) { const e = c.element; if(e.hasAttribute("data-stream-enabled")) { const contentID = e.getAttribute("data-content-id"); if (contentID) { const file = await this.getAttachment(emailID, contentID); if (file) { const { urlService } = this; switch(e.tagName) { case "A": e.setAttribute("href", urlService.toWebMLinkUrl({ eDomain, file, postID })); break; case "VIDEO": if (file.fileSize > maxAttachmentSize) { e.setAttribute("src", urlService.toWebMUrl({ eDomain, file, postID, publicRead: true })); } else { e.setAttribute("src", `cid:${contentID}`); } e.setAttribute("poster", urlService.toImageUrl({ eDomain, file, postID, publicRead: true })); break; // case "IMG": // e.setAttribute("src", imgUrl); // break; } } } } } }