/* eslint-disable no-console */ import Inject, { RegisterScoped, ServiceProvider } from "@entity-access/entity-access/dist/di/di.js"; import SocialMailContext from "../../model/SocialMailContext.js"; import MailboxContact from "../../model/entities/MailboxContact.js"; import DateTime from "@entity-access/entity-access/dist/types/DateTime.js"; import SocketService from "../../services/socket/AppSocketService.js"; import EmailAddressService from "../../services/EmailAddressService.js"; import ChannelService from "./ChannelService.js"; import { Email } from "../../model/entities/Email.js"; import Sql from "@entity-access/entity-access/dist/sql/Sql.js"; import EngagementService from "./EngagementService.js"; // import PostReceiveWorkflow from "../../workflows/post-receive/PostReceiveWorkflow.js"; import Hashtags from "../../../common/Hashtags.js"; import TagService from "../../services/tags/TagService.js"; import ChangeEntry from "@entity-access/entity-access/dist/model/changes/ChangeEntry.js"; export type IMailboxThreadInfo = Partial & { sent?: boolean, silent?: boolean, timeRead?: DateTime, engagement?: string; tagIDs?: number[]; email: Email; newOpenThread: number; newThread: number; }; export interface IUpdateReferenceParameters { emailID, silent?: boolean, timeRead?: DateTime, dateUpdated?: DateTime }; @RegisterScoped export default class EmailReferenceService { public enableTriggers = true; @Inject private db: SocialMailContext; @Inject private socketService: SocketService; @Inject private emailAddressService: EmailAddressService; @Inject private engagementService: EngagementService; @Inject private tagService: TagService; public async updateReferences(options: IUpdateReferenceParameters) { const email = await this.updateEmailReferences(options); if (email.engagement) { await this.db.mailboxContactEmails .where(options, (x, p) => x.emailID === p.emailID) .update(email, (x, p) => ({ engagement: p.engagement})); } await this.db.emails.where(options, (x, p) => x.emailID === p.emailID) .update((x) => ({ dateUpdated: Sql.date.now()})); } async updateThread( mt: IMailboxThreadInfo) { const { mailbox, mailboxID, emailAddressID, lastEmailID: emailID, // sent, silent, dateUpdated = DateTime.now, engagement, tagIDs, email, } = mt; let { newOpenThread, newThread, } = mt; let { timeRead } = mt; const { db, socketService, emailAddressService } = this; // await eternity.queue(UpdateMailboxStorage, mailboxID, { id: `update-mailbox-storage-${mailboxID}`}); db.raiseEvents = false; db.verifyFilters = false; if (mailboxID === email.senderID) { timeRead = null; } // we will first insert it in the mailbox thread email. await db.mailboxContactEmails.statements.selectOrInsert({ mailboxID, emailAddressID, timeRead, emailID, dateReceived: dateUpdated, engagement }); if (mailbox) { if (mailbox.parentID) { // run action... const emailAddress = await emailAddressService.getEmailAddress(mailboxID); const cs = ServiceProvider.resolve(this, ChannelService); if (/subscribe\-/i.test(emailAddress.emailAddress)) { await cs.subscribe(mailbox.parentID, emailAddressID); } if (/unsubscribe\-/i.test(emailAddress.emailAddress)) { await cs.unsubscribe(mailbox.parentID, emailAddressID); } } } const unread = silent ? 0 : (email.received ? 1 : 0); const total = 1; let newRequest = email.received && email.senderID !== mailboxID; let blocked = false; let spam = false; let addFolder = true; const name = spam ? "Spam" : blocked ? "Blocked" : newRequest ? "New" : "Contacts"; let folderTagID = await this.tagService.getSystemTagID(name); let unarchive = !newThread; let archived = false; await db.mailboxContacts.statements.upsert({ emailAddressID, mailboxID, folderTagID, openThreads: newOpenThread === 1 ? 1 : 0, totalThreads: newThread === 1 ? 1 : 0, lastEmailID: emailID, newRequest, dateUpdated, blocked, archived: false, alwaysArchived: false, spam, unread, total }, (item) => { addFolder = false; item.unread = item.unread ? item.unread + ( unread ? 1 : 0 ) : 0; item.total = item.total ? item.total + 1 : 1; item.dateUpdated = dateUpdated; newRequest = item.newRequest; blocked = item.blocked; spam = item.spam; if(!item.folderTagID) { item.folderTagID = folderTagID; } else { folderTagID = item.folderTagID; } if (item.autoClose || item.blocked) { newOpenThread = 0; newThread = 0; } if (item.alwaysArchived) { unarchive = false; } else { if (item.archived) { archived = true; if (unarchive) { item.archived = false; } } } item.openThreads = Math.max(0, item.openThreads + newOpenThread); item.totalThreads = Math.max(0, item.totalThreads + newThread); if(item.lastEmailID < emailID) { item.lastEmailID = emailID; } return item; } ); // reschedule the trigger // if (this.enableTriggers && !/draft|pending/i.test(email.status)) { // await PostReceiveWorkflow.queue(eternity, // { senderID, recipientID, emailID, sent }, // DateTime.from(email.dateSent)); // } /** * This should go to everyone as client may need to refresh the UI, however silent will indicate * whether to show any notification or not. * * This has to be setup here as PostReceive workflow will not be executed for sent items. * */ socketService.mailboxRoom.newMail(mailboxID, emailAddressID, emailID, silent); if (addFolder) { await db.mailboxFolders.statements.upsert({ mailboxID, tagID: folderTagID, count: 1 }, (x) => { if (archived) { if(!unarchive) { return x; } x.count++; x.archivedCount = Math.max(0, x.archivedCount--); return x; } x.count++; return x; }, { mailboxID, tagID: folderTagID }); } await db.mailboxes.where({ mailboxID }, (x, p) => x.mailboxID === p.mailboxID) .update({ newThread, newOpenThread, unread: unread ? 1 : 0 }, (x, p) => ({ openThreads: Sql.math.max(0, x.openThreads + Sql.cast.asInteger(p.newOpenThread)), totalThreads: Sql.math.max(0, x.totalThreads + Sql.cast.asInteger(p.newThread)), dateUpdated: Sql.date.now(), unread: Sql.math.max(0, x.unread + Sql.cast.asInteger(p.unread)) })); if (tagIDs) { for (const tagID of tagIDs) { await db.mailboxTags.statements.upsert({ mailboxID, tagID, count: 1 }, (item) => { item.count++; item.dateUpdated = dateUpdated; return item; }, { mailboxID, tagID } ); await db.mailboxContactTags.statements.upsert({ mailboxID, emailAddressID, tagID, count: 1 }, (item) => { item.count++; item.dateUpdated = dateUpdated; return item; }, { mailboxID, emailAddressID, tagID, } ); } } } async updateSentReferences(entity: Email, entry: ChangeEntry) { if (entity.status !== "scheduled") { return; } if (entity.stateReferencesUpdated) { return; } const mailboxID = entity.senderID; const hosted = await this.emailAddressService.getHostedMailboxByID(mailboxID); if (!hosted) { return; } const { emailID } = entity; await this.db.emailAddresses.where(entity, (x, p) => x.emailAddressID === p.senderID || x.recipients.some((r) => r.emailID === p.emailID) ).include((x) => x.mailbox).toArray(); const contacts = await this.tagService.getSystemTagID("Contacts"); const now = DateTime.now; for (const { emailAddressID } of entity.recipients) { // we should save this only if sender is hosted on our system... await this.db.mailboxContacts.statements.upsert({ mailboxID, emailAddressID, folderTagID: contacts, dateCreated: now, dateUpdated: now, lastEmailID: emailID }, void 0, { mailboxID, emailAddressID }); await this.db.mailboxContactEmails.statements.selectOrInsert({ mailboxID, emailAddressID, emailID, dateReceived: now }, { emailID, mailboxID, emailAddressID }); } } private async updateHashtags(email: Email) { if (!email.textBody) { return; } const { db } = this; const tags = [] as number[]; for (const tag of Hashtags.extract(`${email.tags || ""};\n${email.textBody}`)) { const tagIDs = await this.tagService.getTagIDs(tag); tags.push(... tagIDs); for (const tagID of tagIDs) { await db.emailTags.statements.selectOrInsert({ emailID: email.emailID, tagID }); } } return tags; } private async updateEmailReferences({ emailID, silent, timeRead, dateUpdated }: IUpdateReferenceParameters) { const { db } = this; const email = await db.emails .where({ emailID }, (x, p) => x.emailID === p.emailID) .include((x) => [ x.recipients.forEach((r) => r.emailAddress.mailbox), x.senderEmail.mailbox, x.thread.lastReply ]) .first(); const { thread, headers } = email; // add reply to in set of emailRecipients if (headers) { const json = JSON.parse(headers); // replyTo should only be saved for // received emails if (json.replyTo && email.received) { email.recipients ??= []; const replyTos = !Array.isArray(json.replyTo) ? [json.replyTo] : json.replyTo; let changed = false; for(const replyTo of replyTos) { const rt = (replyTo as string).toLowerCase().trim(); const rtID = await this.emailAddressService.getId(rt); if (email.recipients.some((r) => r.emailAddressID === rtID)) { continue; } await db.emailRecipients.statements.selectOrInsert({ emailID, emailAddressID: rtID, type: "replyTo" }, { emailID, emailAddressID: rtID, type: "replyTo" }); changed = true; } if (changed) { return await this.updateEmailReferences({ emailID, silent, timeRead, dateUpdated }); } } } // fix lastReply of thread... if (thread && email.status !== "draft") { const { lastReply } = thread; if (!lastReply || (lastReply.dateCreated < email.dateCreated && lastReply.emailID !== email.emailID)) { if (thread.senderID === email.senderID) { thread.lastReplyID = null; thread.lastReply = null; } else { thread.lastReply = email; thread.lastReplyID = email.emailID; } await db.emails.statements.update({ lastReplyID: thread.lastReplyID }, { emailID: thread.emailID }); } } let newThread = 0; let newOpenThread = 0; if (thread && !email.hasUnsubscribe) { // yes thread exists... // and was already open const closeThread = email.senderID !== thread.senderID; const previousReply = await db.emails.where(email, (x, p) => x.threadID === p.threadID && x.emailID !== p.emailID) .orderByDescending((x) => x.emailID) .first(); // thread was open if previous reply was sent by the thread's sender const wasThreadOpen = !previousReply || previousReply.senderID === thread.senderID; if (wasThreadOpen) { // thread was already open... if (closeThread) { newOpenThread--; } } else { // thread was already closed if (!closeThread) { newOpenThread++; } } } else if (!email.hasUnsubscribe){ newThread = 1; newOpenThread = 1; } // update tags.. const tagIDs = await this.updateHashtags(email); const engagement = await this.engagementService.trackEngagement(email); if (email.forwardedID) { const count = await db.emails .where(email, (x, p) => x.emailID === p.forwardedID) .count(); await db.emails .where(email, (x, p) => x.emailID === p.forwardedID) .update({ count }, (x, p) => ({ forwardCount: Sql.cast.asInteger(p.count) })); } db.verifyFilters = false; db.raiseEvents = true; email.recipients ??= []; const { senderID } = email; const senderMailbox = email.senderEmail?.mailbox; const { syncedMailboxID} = email; const sent = (!email.received && email.status !== "received") || (syncedMailboxID && syncedMailboxID === email.senderID); // received must be stored based on sender's mailboxes... // Email was sent from senderMailbox if (sent) { silent = true; timeRead = dateUpdated; for (const { emailAddressID, emailAddress } of email.recipients) { if (!emailAddress) { console.warn(`EmailAddressID ${emailAddressID} in Recipient of EmailID ${emailID} not registered`); continue; } if (senderMailbox) { // Sender's Thread - Outbox // we might have self cc // so we will allow self storage await this.updateThread({ engagement, mailboxID: senderID, emailAddressID, lastEmailID: emailID, sent: true, silent, timeRead, dateUpdated, tagIDs, email, newOpenThread, newThread, }); } else { // this should never be the case... } // event sent emails are part of mailbox // await db.mailboxEmails.statements.selectOrInsert({ // mailboxID: senderID, // emailID // }); // if (mailbox) { // // this is the case when email was sent from the system // // we will insert in respective mailboxes here... // // await db.mailboxEmails.statements.selectOrInsert({ // // mailboxID: emailAddressID, // // emailID // // }); // saved.add(emailAddressID); // // Recipient's thread - Inbox // await this.updateThread({ // engagement, // mailbox, // mailboxID: emailAddressID, // emailAddressID: senderID, // lastEmailID: emailID, // silent, // timeRead, // dateUpdated, // tagIDs, // email, // newOpenThread, // newThread, // }); // } } } else { if (!senderID) { return email; } for (const { emailAddressID, emailAddress: { mailbox } } of email.recipients) { // this is the case when email is received from outside // we will only store in mailboxes that exist on the system if (mailbox) { if (syncedMailboxID) { // we will only store // if recipientID matches.. if (syncedMailboxID !== emailAddressID) { continue; } } // await db.mailboxEmails.statements.selectOrInsert({ // mailboxID: emailAddressID, // emailID // }); const mailboxID = emailAddressID; await this.updateThread({ engagement, mailbox, mailboxID, emailAddressID: senderID, lastEmailID: emailID, silent, timeRead, dateUpdated, tagIDs, email, newOpenThread, newThread, }); continue; } } } // this is the case when mail is either forwarded // or sent as bcc to hosted mailbox // in that case we will put mail in sender's folder // if (email.mailboxes) { // for (const { mailbox } of email.mailboxes) { // const mailboxID = mailbox.mailboxID; // if (saved.has(mailboxID)) { // continue; // } // await this.updateThread({ // engagement, // mailbox, // mailboxID, // emailAddressID: senderID, // lastEmailID: emailID, // silent, // timeRead, // dateUpdated, // tagIDs, // email, // newOpenThread, // newThread, // }); // } // } return email; } }