import Workflow, { UniqueActivity } from "@entity-access/entity-access/dist/workflows/Workflow.js"; import Inject from "@entity-access/entity-access/dist/di/di.js"; import SocialMailContext from "../../model/SocialMailContext.js"; // import BroadcastEmailToMX from "./BroadcastEmailToMX.js"; import DateTime from "@entity-access/entity-access/dist/types/DateTime.js"; import sleep from "../../../common/sleep.js"; import { randomUUID } from "crypto"; import DispatchEmailToMX from "../smtp/DispatchEmailToMX.js"; import EmailAddressService from "../../services/EmailAddressService.js"; import TimeSpan from "@entity-access/entity-access/dist/types/TimeSpan.js"; import Sql from "@entity-access/entity-access/dist/sql/Sql.js"; import { AppWorkflowContext } from "../AppWorkflowContext.js"; /** * Broadcasting Email is done in following manner. * * 1. Status of Incoming Email is set to `published`. This workflow will not set it, it must be set via backend. * 2. Same email is forwarded to all the subscribers. * 3. Original Email Headers are stripped, from email address is removed. * 4. In Future - Any email address in the html and text body is also removed. * 5. Forwarding same email makes it easier to keep unique message id, and it will help in * creating the threads. */ export interface IBroadcastEmail { emailID: number; mailboxID: number; senderID: number; sendToModeratorsOnly?: boolean; } export default class BroadcastEmail extends Workflow { static taskGroup = "batch"; public static async broadcast(context: AppWorkflowContext, be: IBroadcastEmail) { const { mailboxID , emailID } = be; return context.queue(BroadcastEmail, be, { id: `broadcast-${mailboxID}-${emailID}-${Date.now()}`, throttle: { group: `broadcast-${emailID}`, maxPerSecond: 1 } }); } private from: string; private threadID: number; async run() { this.preserveTime = TimeSpan.fromDays(1); this.failedPreserveTime = TimeSpan.fromHours(1); if (!this.input.sendToModeratorsOnly) { const { from, threadID } = await this.publish(); this.from = from; this.threadID = threadID; } for (let i = 0; i < 10000; i++) { let all = Number(await this.getCount(i)); if (!all) { break; } all = await this.insert(i); await sleep(1000); } } @UniqueActivity async publish( @Inject db?: SocialMailContext, @Inject eas?: EmailAddressService ) { // we need to send one copy to self in case this is a public channel // to display it in blog db.verifyFilters = false; const { mailboxID, emailID } = this.input; const datePublished = DateTime.now; const dateUpdated = datePublished; // mark it as published... const [email] = await db.emails.where(this.input, (x, p) => x.emailID === p.emailID) .updateSelect((x) => ({ status: "published"})); // find first attachment const types = ["video/%", "image/%"]; const firstAttachment = await db.appFiles.where({ types, emailID }, (x, p) => x.emailID === p.emailID && Sql.text.likeAny(x.contentType, p.types)) .orderByDescending((x) => Sql.text.like(x.contentType, "video/%")) .first(); const previewFileID = firstAttachment?.appFileID; await db.mailboxes.statements.update({ datePublished }, { mailboxID }); const mailbox = await eas.getMailboxFromId(mailboxID); const domain = await eas.getDomainByID(mailbox.domainID); const watermark = mailbox.channelVideoWatermark || domain.name; if (watermark) { await db.appFiles.where({ emailID }, (x, p) => x.emailID === p.emailID) .update({ watermark}, (_x, p) => ({ watermark: p.watermark})) } // gmail sends in-reply-to for forwarded messages. // ideally in-reply-to must not be set if the message was forwarded let isThread = email.parentID === null; if (isThread) { await db.channelEmails.statements.upsert({ previewFileID, isThread: true, datePublished, dateUpdated,mailboxID, emailID }, (x) => x, { mailboxID, emailID }); } else { await db.channelEmails.statements.upsert({ previewFileID, datePublished, dateUpdated, mailboxID, emailID }, (x) => x, { mailboxID, emailID }); } if(email.parentID) { const { parentID } = email; isThread = !(await db.channelEmails.where({ mailboxID , parentID}, (x, p) => x.emailID === p.parentID && x.mailboxID === p.mailboxID) .some()); } // load email.. const from = (await eas.getEmailAddress(this.input.mailboxID)).emailAddress; return { from, threadID: email.threadID }; } @UniqueActivity async getCount( _: any, @Inject db?: SocialMailContext ) { return this.getPending(db).count(); } @UniqueActivity async insert( _: number, @Inject db?: SocialMailContext, @Inject eas?: EmailAddressService ) { let last = 0; const { emailID, mailboxID: senderID } = this.input; const { from } = this; const dateCreated = DateTime.now; const { channelVideoWatermark } = await eas.getHostedMailboxByID(senderID); let all = 0; for (let index = 0; index < 100; index++) { const subscribers = await this.getPending(db) .limit(100) .toArray(); last = subscribers.length; if (!last) { break; } all += last; let eta = dateCreated; for (const { emailAddressID, mailboxID, emailAddress: { emailAddress: to} } of subscribers) { const accessCode = randomUUID().replaceAll("-", ""); await using tx = await db.connection.createTransaction(); const activity = await db.subscriberActivities.statements.insert({ activity: "scheduled", emailID, emailAddressID, mailboxID, accessCode, dateCreated }); const host = to.split("@").pop(); const { activityID } = activity; await this.context.queue(DispatchEmailToMX, { recipientAddressID: emailAddressID, recipientAddress: to, emailID, senderID, external: false, doNotSendDR: true, saveHeadersOnly: true, activityID, accessCode, broadcast: true, from, /** In broadcast, we will send attachments as links only */ sendAttachmentsAsLinks: true, channelVideoWatermark, modifyTo: true, listID: senderID, host, }, { id: `bulk-dispatch-to-mx-${activityID}`, eta, taskGroup: BroadcastEmail.taskGroup }); await tx.commit(); eta = eta.addSeconds(1); } } return all; } private getPending(db: SocialMailContext) { if (this.input.sendToModeratorsOnly) { // we only send to mods return db.mailboxContacts.where(this.input, (x, p) => x.mailboxID === p.mailboxID && x.emailAddressID !== p.mailboxID && (x.isOwner === true || x.isModerator === true) && !x.emailAddress.subscriberActivities.some((sa) => sa.emailID === p.emailID)).include((x) => x.emailAddress); } const input = { ... this.input, threadID: this.threadID ?? this.input.emailID }; return db.mailboxContacts.where(input, (x, p) => x.mailboxID === p.mailboxID && x.emailAddressID !== p.mailboxID && x.emailAddressID !== p.senderID && !x.emailAddress.subscriberActivities.some((sa) => sa.emailID === p.emailID) && x.status === "active" && (x.subscriptionType === null || x.subscriptionType === "all" || x.mailbox.emails.some((ce) => ce.emailID === p.threadID && ce.email.threadParticipants.some((tp) => tp.emailAddressID === x.emailAddressID)) ) ) .include((x) => x.emailAddress); } }