/* eslint-disable no-console */ import { NamedObjectPool } from "@entity-access/entity-access/dist/common/ObjectPool.js"; import Inject from "@entity-access/entity-access/dist/di/di.js"; import DateTime from "@entity-access/entity-access/dist/types/DateTime.js"; import TimeSpan from "@entity-access/entity-access/dist/types/TimeSpan.js"; import Workflow, { UniqueActivity } from "@entity-access/entity-access/dist/workflows/Workflow.js"; import SocialMailContext from "../../model/SocialMailContext.js"; import SMTPClient, { ISmtpResponse } from "../../smtp/client/SMTPClient.js"; import { SmtpStatusCodes } from "../../smtp/client/SmtpStatusCodes.js"; import MailDispatcherService from "./MailDispatcherService.js"; import EmailLogService from "../../services/email-logs/EmailLogService.js"; import EmailAddressService from "../../services/EmailAddressService.js"; // import PostReceiveWorkflow from "../post-receive/PostReceiveWorkflow.js"; import ESmtpClient from "../../../protocols/smtp/ESmtpClient.js"; import EncryptionService from "../../services/encryption/EncryptionService.js"; import { IMessageEnvelope } from "./IMessageEnvelope.js"; import EmailSerializerService from "../../smtp/services/EmailSerializerService.js"; import ServerLogger from "@entity-access/server-pages/dist/core/ServerLogger.js"; import PendingReferencesWorkflow from "../pending/PendingReferencesWorkflow.js"; import { globalEnv } from "../../../common/globalEnv.js"; import FetchBuilder from "@web-atoms/fetch-builder"; import Sql from "@entity-access/entity-access/dist/sql/Sql.js"; import { NODATA, NOTFOUND } from "node:dns"; import DeliveryStatusService from "../../smtp/delivery/DeliveryStatusService.js"; export const smtpPool = new NamedObjectPool((host) => ({ asyncFactory: () => new SMTPClient({ host, helo: globalEnv.host }).connect(), destroy: (item) => item.dispose(), subscribeForRemoval: (po, clear) => { po.onEnd(() => { console.log(`Socket closed ...`); clear(); }); }, })); export default class DispatchEmailToMX extends Workflow { static taskGroup = "send"; static taskGroups = ["priority-send"]; private response: ISmtpResponse; private signedFileLogID: number; async run() { let ts = TimeSpan.fromSeconds(60); this.signedFileLogID = await this.signEmail(); const { external } = this.input; for (let index = 0; index < 5; index++) { const pauseSendingTill = await this.getPauseSendingTill(index); if(pauseSendingTill) { await this.delay(TimeSpan.fromSeconds(pauseSendingTill)); } const status = this.response = await (external ? this.sendExternalMail(index) : this.sendMail(index)); switch(status.statusCode) { case SmtpStatusCodes.Ok: await this.saveStatus(); return null; case SmtpStatusCodes.ExceededStorageAllocation: case SmtpStatusCodes.MailboxBusy: case SmtpStatusCodes.TransactionFailed: case SmtpStatusCodes.ServiceNotAvailable: break; default: await this.saveStatus(); return status.status; } await this.delay(ts); ts = ts.add(ts); } if (!this.response) { this.response = { logs: "Timeout", status: "0", statusCode: 0 as any }; } await this.saveStatus(); return "Failed after multiple attempts"; } @UniqueActivity async getPauseSendingTill(i, @Inject db?: SocialMailContext ) { const pause = await db.domains .where(this.input, (x, p) => x.name === p.host && x.pauseSendingTill !== null) .first(); if (!pause?.pauseSendingTill) { return 0; } const ts = DateTime.from(pause.pauseSendingTill).diff(DateTime.now); if(ts.totalSeconds > 0) { return ts.totalSeconds; } return 0; } @UniqueActivity async signEmail( @Inject mds?: MailDispatcherService ) { return await mds.encodeForBulk(this.input); } @UniqueActivity async sendExternalMail( attempt: number, @Inject els?: EmailLogService, @Inject db?: SocialMailContext, @Inject es?: EncryptionService ) { let st = await db.mailboxSyncTargets .where(this.input, (x, p) => x.mailboxID === p.senderID && (x.direction === "out" || x.protocol === "smtp") && x.active === true) .first(); if (!st) { // recreate smtp from imap const it = await db.mailboxSyncTargets.where(this.input, (x, p) => x.mailboxID === p.senderID && x.active === true && (x.direction === "in" || x.protocol === "imap") ).first(); if (it?.host?.startsWith("imap.")) { st = { ... it, syncTargetID: void 0, protocol: "smtp", direction: "out", host: it.host.replace("imap.", "smtp."), port: it.port === 993 ? 465 : 25 }; await db.mailboxSyncTargets.statements.insert(st); } else { throw new Error(`No Smtp Settings Available to send an email.`); } } const { host, username, password: passwordEncrypted } = st; const password = es.secure.decrypt(passwordEncrypted); await using client = await ESmtpClient.connect({ host, startTLS: true, auth: { login: { username, password } } }); const file = await els.load({ logID: this.signedFileLogID }); const { from , recipientAddress } = this.input; // since remote file might be compressed const status = await client.sendRequest(from, [recipientAddress], file); if (Number(status.statusCode) >= 400) { if(/deferred|throttle/i.test(status.logs)) { await db.domains.withKeys({ name: host }) .update({ pauseSendingTill: DateTime.now.addMinutes(1) }); } ServerLogger.reportError({ error: status.logs, host, route: recipientAddress, }); } return status; } @UniqueActivity async sendMail( attempt: number, @Inject els?: EmailLogService, @Inject eas?: EmailAddressService, @Inject ess?: EmailSerializerService, @Inject db?: SocialMailContext ) { // if it is local... // save signedFileLogID to MailboxContactEmail const { recipientAddressID, external } = this.input; const { signedFileLogID } = this; const mailbox = await eas.getMailboxFromId(recipientAddressID); if (mailbox && !external && !mailbox.isExternal) { const localFile = await els.load({ logID: signedFileLogID }); // attachments are missing.... await ess.save(localFile, { mailboxes: [mailbox], isDraft: false, received: true, sender: this.input.from }); await PendingReferencesWorkflow.queue(this.context); return { statusCode: SmtpStatusCodes.Ok, status: "Ok", logs: "Delivered Locally." }; } const { host, recipientAddress } = this.input; // check if we smtp is not available const smtpNotAvailableTill = await db.domains.where(this.input, (x, p) => x.name === p.host && x.smtpNotAvailableTill !== null && x.smtpNotAvailableTill > Sql.date.now()).first(); if (smtpNotAvailableTill) { return { smtpNotAvailableTill: smtpNotAvailableTill.smtpNotAvailableReason, statusCode: SmtpStatusCodes.TransactionFailed, status: "Failed", logs: `Smtp blocked for ${host}` }; } try { await using client = await smtpPool.acquire(host); const file = await els.load({ logID: this.signedFileLogID }); // since remote file might be compressed const status = await client.send({ ... this.input, to: [recipientAddress] }, file); if (Number(status.statusCode) >= 400) { if(/deferred|throttle/i.test(status.logs)) { await db.domains.withKeys({ name: host }) .update({ pauseSendingTill: DateTime.now.addMinutes(1) }); } ServerLogger.reportError({ error: status.logs, route: recipientAddress, host, }); } return status; } catch (error) { if(error.code === "ECONNREFUSED" || error.code === NODATA || error.code === NOTFOUND ) { try { const reason = error.code ? `${host} ${error.code}` : `${host} ${error.stack ?? error}`; await db.domains.where(this.input,(x, p) => x.name === p.host) .update({ reason }, (x, p) => ({ smtpNotAvailableTill: Sql.date.addDays(Sql.date.now(), 1), smtpNotAvailableReason: p.reason })); } catch (e1) { ServerLogger.error(e1); } } return { statusCode: SmtpStatusCodes.TransactionFailed, status: "Failed", logs: error.cause ? (error.cause.stack + "\n" + (error.stack ?? error)) : (error.stack ?? error) }; } } @UniqueActivity async saveStatus( @Inject db?: SocialMailContext, @Inject els?: EmailLogService, @Inject eas?: EmailAddressService, @Inject dss?: DeliveryStatusService ) { const { emailID, recipientAddressID: emailAddressID, activityID, senderID } = this.input; db.verifyFilters = false; if (this.signedFileLogID && this.input.saveHeadersOnly) { // delete the log file... await els.delete(this.signedFileLogID); } const { logID } = await els.saveText(emailID, this.input.recipientAddress, this.response.logs); const now = DateTime.now; const success = this.response?.statusCode === SmtpStatusCodes.Ok; const activity = success ? "sent" : ((this.response?.statusCode as number) >= 500 ? "rejected" : "delivery-failed"); await dss.report({ emailAddressID, emailID, mailboxID: senderID, logID, activity, dateCreated: now, }); if (success) { if (activityID) { await db.subscriberActivities.statements.update({ activity: "sent" }, { activityID}); } else { const { recipientAddress } = this.input; console.log(JSON.stringify({ emailID, sent: true, recipient: recipientAddress })); await db.emailRecipients.withKeys({ emailID, emailAddressID }) .update({ logID, status: "sent", dateSent: now }); } return; } if (activityID) { await db.subscriberActivities.statements.update({ activity: "sent-failed" }, { activityID}); } else { await db.emailRecipients.withKeys({ emailID, emailAddressID }) .update({ status: "sent-failed", logID, dateSent: now }); } db.raiseEvents = true; let unsubscribePost; let unsubscribe; let returnPath; const email = await db.emails.withKeys({ emailID }).select(); if(email.headers) { try { const headers = JSON.parse(email.headers); if (/yes|true/i.test(headers["Auto-Unsubscribe-On-Fail"])) { unsubscribePost = headers["List-Unsubscribe-Post"]; unsubscribe = headers["List-Unsubscribe"]; } returnPath = headers["Return-Path"]; } catch { // do nothing... } } if (unsubscribe) { if(unsubscribePost) { const urlParam = new URLSearchParams(unsubscribePost.trim()); let fb = FetchBuilder.post(unsubscribe); for(const m of urlParam.keys()) { const v = urlParam.get(m); fb = fb.form(m, v); } fb.asTextResponse().catch(console.error); } FetchBuilder.get(unsubscribe).jsonBody({}).asTextResponse().catch(console.error); } if (!this.input.doNotSendDR) { // check if there is a return path... const e = await db.emailRecipients .where(this.input, (x, p) => x.emailID === p.emailID && x.emailAddressID === p.recipientAddressID) .include((x) => [x.emailAddress]) .first(); const recipients = [db.emailRecipients.add({ emailAddressID: email.senderID, type: "to", name: e.name })]; if (returnPath) { try { const rpID = await eas.getId(returnPath); recipients.push(db.emailRecipients.add({ emailAddressID: rpID, type: "to", name: e.name })); } catch { // ignore error... } } e.status = "sent-failed"; e.error = this.response.status; // send mailer daemon... db.emails.add({ senderName: e.name ?? "Mailer Daemon", senderID: this.input.recipientAddressID, parentID: e.emailID, subject: `Mailer Daemon Delivery Failed`, textBody: `Mail delivery to ${e.emailAddress.emailAddress} failed with following error\r\nError Code: ${this.response.statusCode}\r\n${this.response.status}`, htmlBody: `

Mail delivery to ${e.emailAddress.emailAddress} failed with following error

Error Code: ${this.response.statusCode}

${this.response.status.split("\n").join("\n
")}

`, status: "received", received: true, dateCreated: now, dateSent: now, dateReceived: now, recipients }); await db.saveChanges(); } } }