import Inject, { RegisterScoped, ServiceProvider } from "@entity-access/entity-access/dist/di/di.js"; import SocialMailContext from "../../model/SocialMailContext.js"; import DKIM from "nodemailer/lib/dkim/index.js"; import MailComposer from "nodemailer/lib/mail-composer/index.js"; import AppFile from "../../model/entities/AppFile.js"; import TempFileService from "../../storage/TempFileService.js"; import BaseStorage from "../../storage/BaseStorage.js"; import HtmlSanitizer from "../../services/dom/HtmlSanitizer.js"; import { Base36 } from "../../../common/Base36.js"; import { globalEnv } from "../../../common/globalEnv.js"; import EmailLogService from "../../services/email-logs/EmailLogService.js"; import { LocalFile } from "@entity-access/server-pages/dist/core/LocalFile.js"; import CachedEmailService from "../../smtp/services/CachedEmailService.js"; import DateTime from "@entity-access/entity-access/dist/types/DateTime.js"; import { randomUUID } from "node:crypto"; import DomainKeyService from "../../services/domain-keys/DomainKeyService.js"; import EncryptionService from "../../services/encryption/EncryptionService.js"; import { IMessageEnvelope } from "./IMessageEnvelope.js"; import BlogContentTransformer from "../../services/dom/BlogContentTransformer.js"; import EmailParserService from "../../smtp/services/EmailParserService.js"; import encodeAttachments from "./encodeAttachments.js"; import XNode from "@entity-access/server-pages/dist/html/XNode.js"; import ChannelUrlService from "../../services/channels/ChannelUrlService.js"; import mime from "mime-types"; import { parse } from "node:path"; import type { Attachment } from "nodemailer"; @RegisterScoped export default class MailDispatcherService { @Inject db: SocialMailContext; @Inject tfs: TempFileService; @Inject storage: BaseStorage; @Inject emailLogService: EmailLogService; @Inject htmlSanitizer: HtmlSanitizer; @Inject cachedEmailService: CachedEmailService; @Inject encryptionService: EncryptionService; @Inject blogContentTransformer: BlogContentTransformer; @Inject eps: EmailParserService; @Inject channelUrlService: ChannelUrlService; async encodeForBulk({ senderID, emailID, recipientAddressID, recipientAddress, activityID, accessCode, external, listID, broadcast, from, saveHeadersOnly, channelVideoWatermark, sendAttachmentsAsLinks }: IMessageEnvelope) { const { db, tfs } = this; db.verifyFilters = false; db.raiseEvents = false; const dateCreated = DateTime.now; if (!activityID) { accessCode = randomUUID().replaceAll("-", ""); // lets create one... const a = await db.subscriberActivities.statements.insert({ emailID, mailboxID: senderID, emailAddressID: recipientAddressID, dateCreated, accessCode, activity: "scheduled" }); activityID = a.activityID; } const q = db.emails.where({ emailID} , (x, p) => x.emailID === p.emailID); const email = await q .include((x) => [ x.mimeFile, x.senderEmail.mailbox.emailAddress, x.recipients.forEach((r) => r.emailAddress), x.attachments.forEach((a) => a.fileContent) ]) .first(); const mb = await db.mailboxes .where({ senderID}, (x, p) => x.mailboxID === p.senderID) .include((x) => x.emailAddress) .first(); const to = email.recipients.filter((r) => r.type === "to") .map((r) => r.replyTo ?? r.emailAddress.emailAddress) ?? []; const cc = email.recipients.filter((r) => r.type === "cc") .map((r) => r.emailAddress.emailAddress); if (!email.senderName) { email.senderName = email.senderEmail.mailbox.emailAddress.name; } const senderEmail = from ?? mb.emailAddress.emailAddress; const domainName = channelVideoWatermark || senderEmail.split("@").pop(); const eDomain = this.encryptionService.general.encrypt(domainName); let html: string = email.htmlBody ?? await this.cachedEmailService.getHtmlText(email); const toAttachment = async (ea: AppFile): Promise => { if (sendAttachmentsAsLinks || ea.fileSize > 25*1024*1024 ) { // create a hyper link... const downloadLink = /^video\//i.test(ea.contentType) && listID && domainName ? this.channelUrlService.toWebMUrl({ eDomain, file: ea, publicRead: true }) : this.channelUrlService.toFileUrl({ file: ea, publicRead: true}); const url = new URL(downloadLink); const { base } = parse(url.pathname); const contentType = mime.lookup(base) || "application/octet-stream"; return { content: downloadLink, filename: base, contentType: "message/external-body", contentDisposition: ea.contentDisposition as any, cid: ea.contentID ?? ea.appFileID.toString(), headers: { "access-type": "URL", "URL": downloadLink.trim(), "host": globalEnv.host, "expect-content-type": contentType, "expiration": DateTime.now.addDays(30).asJSDate.toJSON(), "size": ea.fileSize.toString(), } }; } const tf = await tfs.downloadAppFile(ea); return { content: tf.openReadStream(), filename: ea.name, contentType: ea.contentType, contentDisposition: (ea.contentDisposition as any) || "attachment", cid: ea.contentID ?? ea.appFileID.toString() }; }; const attachments = await Promise.all((email.attachments ?? []) .map(toAttachment)); if(sendAttachmentsAsLinks && email.attachments?.length) { for(const a of attachments) { if(a.cid) { const cid = a.cid.replace(/\<|\>/ig, ""); html = html.replaceAll("cid:" + cid, a.content as string) } } html += (encodeAttachments(attachments) as XNode).render(); // enclose it in a single div html = `
${html}
`; } const headers = JSON.parse(email.headers ?? "{}"); let { inReplyTo } = headers; if (email.parentID) { await db.changeSet.getEntry(email).loadNavigationAsync((x) => x.parent); if (email.parent) { inReplyTo = `<${email.parent.headerMessageID}>`; } } if (inReplyTo) { if (!inReplyTo.startsWith("<")) { inReplyTo = `<${inReplyTo}>`; } } const messageID = email.headerMessageID; let unsubscribeLink = listID ? `https://${globalEnv.host}/social-mail/c/u/${Base36.encode(activityID)}/${accessCode}` : void 0; if (html) { const kEmailID36 = Base36.encode(emailID); const trackerUrl = email.doNotTrack ? void 0 : `https://${globalEnv.host}/social-mail/social/t/${kEmailID36}/${Base36.encode(activityID)}/`; html = await this.blogContentTransformer.sanitizeExternalResources({ senderDomain: listID ? domainName : void 0, emailID, kEmailID36, html, senderEmail, messageID, unsubscribeLink, prefix: void 0, listID, trackerUrl, blog: senderEmail }); // } else { // const postID = this.encryptionService.general.encrypt(emailID.toString()); // const s = htmlSanitizer.sanitize(html, email.textBody, { // senderEmail, // emailID: Base36.encode(emailID), // messageID: email.headerMessageID, // uid: Base36.encode(activityID), // accessCode, // postID, // attachments: email.attachments ?? [], // listID, // trackerUrl: `https://${globalEnv.host}/social-mail/social/t/${Base36.encode(emailID)}/${Base36.encode(activityID)}/` // }); // html = s.html; // } } const fromAddress = from ?? mb.emailAddress.emailAddress; if (listID) { headers["List-Id"] = `<${fromAddress}>`; headers["List-Unsubscribe"] = `<${unsubscribeLink}>`; headers["List-Unsubscribe-Post"] = `List-Unsubscribe=One-Click`; // change recipient address to single one... if(broadcast) { to.length = 0; to[0] = recipientAddress; } } let replyTo; const keys = Object.keys(headers).map((x) => [x,x.toLowerCase()]); const keySet = new Set(); for(const [h,lh] of keys) { keySet.add(h); keySet.add(lh); switch(lh) { case "message-id": case "messageid": delete headers[h]; continue; case "reply-to": case "replyto": replyTo = headers[h]; delete headers[h]; continue; case "in-reply-to": if (!inReplyTo) { inReplyTo = headers[h]; } delete headers[h]; continue; } } if (email.mimeFile && email.doNotTrack) { const ef = await this.emailLogService.load(email.mimeFile); const parsed = await this.eps.parse(ef); for(const h of parsed.headers) { if(keySet.has(h.keyLowerCase)) { continue; } switch(h.keyLowerCase) { case "reply-to": case "content-type": continue; case "in-reply-to": if (inReplyTo) { continue; } break; } headers[h.key] = h.value; } // we need to copy attachments... } // prepare transport... const mail = new MailComposer({ from: { name: email.senderName, address: fromAddress }, to, cc, html, text: email.textBody, subject: email.subject, messageId: email.headerMessageID, date: new Date(), headers, replyTo, inReplyTo, attachments, attachDataUrls: true }); const mimeMessage = mail.compile(); const mailFile = await tfs.createFrom(`${email.emailID}.eml`, mimeMessage.createReadStream(), "message/rfc822"); if (external) { const log = await this.emailLogService.save(emailID, mailFile); return log.logID; } const signed = await this.signFile({ emailID, senderID, file: mailFile, saveHeadersOnly, recipientID: to[0]}); return signed; } async signFile({ emailID, senderID, file, recipientID, saveHeadersOnly }: { emailID: number, recipientID, senderID, file: LocalFile, saveHeadersOnly?: boolean } ) { const { tfs } = this; const dks = ServiceProvider.resolve(this, DomainKeyService); const dk = await dks.getDomainKey(senderID); const signer = new DKIM({ domainName: dk.hostedDomain.domain.name, keySelector: dk.name, privateKey: dk.privateKey }); const mailFile = await tfs.createFrom(`${emailID}-${recipientID}.eml`, signer.sign( file.openReadStream()), "message/rfc822"); const log = await this.emailLogService.save(emailID, mailFile); if (saveHeadersOnly) { // save a copy... const headers = await tfs.createTempFile(".log", `${emailID}-${recipientID}.headers.log`, "message/rfc822"); for await(const line of mailFile.lines()) { if (!line) { break; } await headers.appendLine(line); await this.emailLogService.save(emailID, headers); } } return log.logID; } async encode({ senderID, senderName, senderEmail, subject, html, text, to, messageId = void 0 }) { const { tfs } = this; messageId ??= `${randomUUID()}@${globalEnv.host}`; const mail = new MailComposer({ from: { name: senderName, address: senderEmail }, to, html, text, subject, messageId, }); const mime = mail.compile(); const dks = ServiceProvider.resolve(this, DomainKeyService); const dk = await dks.getDomainKey(senderID); if (!dk) { return await tfs.createFrom(`email-notification.eml`, mime.createReadStream(), "message/rfc822"); } const signer = new DKIM({ domainName: dk.hostedDomain.domain.name, keySelector: dk.name, privateKey: dk.privateKey }); return await tfs.createFrom(`email-notification.eml`, signer.sign( mime.createReadStream()), "message/rfc822"); } }