/* 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 { INotificationEmail } from "./INotificationEmail.js"; import EncryptionService from "../../services/encryption/EncryptionService.js"; import ESmtpClient from "../../../protocols/smtp/ESmtpClient.js"; import ServerLogger from "@entity-access/server-pages/dist/core/ServerLogger.js"; import PendingReferencesWorkflow from "../pending/PendingReferencesWorkflow.js"; // import EmailReferenceService from "../../smtp/services/EmailReferenceService.js"; export const smtpPool = new NamedObjectPool((host) => ({ asyncFactory: () => new SMTPClient({ host }).connect(), destroy: (item) => item.dispose(), subscribeForRemoval: (po, clear) => { po.onEnd(() => { console.log(`Socket closed ...`); clear(); }); }, })); export default class DispatchNotificationToMX extends Workflow { private response: ISmtpResponse; async run() { let ts = TimeSpan.fromSeconds(60); for (let index = 0; index < 5; index++) { const status = this.response = this.input.external ? await this.sendExternalMail(index) : await this.sendMail(index); switch(status.statusCode) { case SmtpStatusCodes.Ok: return null; case SmtpStatusCodes.ExceededStorageAllocation: case SmtpStatusCodes.MailboxBusy: case SmtpStatusCodes.TransactionFailed: case SmtpStatusCodes.ServiceNotAvailable: break; default: throw new Error(status.status); } await this.delay(ts); ts = ts.add(ts); } const log = this.response?.status; if (log) { throw new Error(log); } return null; } @UniqueActivity async sendExternalMail(attempt: number, @Inject mds?: MailDispatcherService, @Inject eas?: EmailAddressService, @Inject db?: SocialMailContext, @Inject es?: EncryptionService ) { const senderMailbox = await eas.getMailbox(this.input.from); const senderID = senderMailbox.mailboxID; const signedFile = await mds.encode({ senderID, html: this.input.htmlBody, text: this.input.textBody, senderName: this.input.fromName, senderEmail: this.input.from, subject: this.input.subject, to: this.input.to }); const st = await db.mailboxSyncTargets .where(this.input, (x, p) => x.mailbox.emailAddress.emailAddress === p.from && (x.direction === "out" || x.protocol === "smtp") && x.active === true) .first(); 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 { from , to } = this.input; // since remote file might be compressed const status = await client.sendRequest(from, [to], signedFile); if (Number(status.statusCode) >= 400) { ServerLogger.reportError({ error: status.logs , info: { path: this.input.to, host }}); } return status; } @UniqueActivity async sendMail( attempt: number, @Inject els?: EmailLogService, @Inject eas?: EmailAddressService, @Inject db?: SocialMailContext, @Inject mds?: MailDispatcherService ) { const senderMailbox = await eas.getMailbox(this.input.from); const senderID = senderMailbox.mailboxID; // if it is local... // save signedFileLogID to MailboxContactEmail const mailboxID = await eas.getHostedMailboxByAddress(this.input.to); const signedFile = await mds.encode({ senderID, html: this.input.htmlBody, text: this.input.textBody, senderName: this.input.fromName, senderEmail: this.input.from, subject: this.input.subject, to: this.input.to }); const now = DateTime.now; if (mailboxID) { await using tx = await db.connection.createTransaction(); const { emailID } = await db.emails.statements.insert({ senderID, senderName: this.input.fromName, dateCreated: now, dateReceived: now, dateSent: now, received: true, subject: this.input.subject, status: "received" }); await db.emailRecipients.statements.insert({ emailID, emailAddressID: mailboxID, type: "to" }); await tx.commit(); const { logID: signedFileLogID } = await els.save(emailID, signedFile); await db.emails.statements.update({ mimeFileID: signedFileLogID }, { emailID }); await PendingReferencesWorkflow.queue(this.context); // await ers.updateReferences({ emailID, dateUpdated: DateTime.now, silent: false, timeRead: null }); // const dateReceived = DateTime.now; // await db.mailboxEmails.statements.selectOrInsert({ // mailboxID, // emailID // }); // await db.mailboxContacts.statements.upsert({ // mailboxID, // emailAddressID: senderID, // dateCreated: dateReceived, // dateUpdated: dateReceived, // lastEmailID: emailID // }); // await db.mailboxContactEmails.statements.upsert({ // mailboxID, // emailAddressID: senderID, // emailID, // signedFileLogID, // dateReceived // }); // await PostReceiveWorkflow.queue(this.context, { // senderID, // emailID, // recipientID: mailboxID, // sent: false // }); return { statusCode: SmtpStatusCodes.Ok, status: "Ok", logs: "Delivered Locally." }; } const host = this.input.to.split("@",2).pop().trim().toLocaleLowerCase(); await using client = await smtpPool.acquire(host); // since remote file might be compressed const status = await client.send({ from: this.input.from, host, to: [this.input.to] }, signedFile); if (Number(status.statusCode) >= 400) { ServerLogger.reportError({ error: status.logs, route: this.input.to, host, }); } return status; } }