import { IEntityQuery } from "@entity-access/entity-access/dist/model/IFilterWithParameter.js"; import Mailbox from "../entities/Mailbox.js"; import AuthenticatedEvents from "./AuthenticatedEvents.js"; import ChangeEntry from "@entity-access/entity-access/dist/model/changes/ChangeEntry.js"; import Inject, { ServiceProvider } from "@entity-access/entity-access/dist/di/di.js"; import SocialMailContext from "../SocialMailContext.js"; import EmailAddressService from "../../services/EmailAddressService.js"; import { ForeignKeyFilter } from "@entity-access/entity-access/dist/model/events/EntityEvents.js"; import DateTime from "@entity-access/entity-access/dist/types/DateTime.js"; import ExternalQuery from "@entity-access/server-pages/dist/decorators/ExternalQuery.js"; import ExternalInvoke from "@entity-access/server-pages/dist/decorators/ExternalInvoke.js"; import Sql from "@entity-access/entity-access/dist/sql/Sql.js"; import Page from "@entity-access/server-pages/dist/Page.js"; import EntityAccessError from "@entity-access/entity-access/dist/common/EntityAccessError.js"; import SyncMailboxWorkflow from "../../workflows/sync/SyncMailboxWorkflow.js"; import WebSiteChannelService from "../../smtp/services/WebSiteChannelService.js"; import ChannelEmail from "../entities/ChannelEmail.js"; import MailboxTag from "../entities/MailboxTag.js"; import MailboxContactEvent from "../entities/MailboxContactEvent.js"; import ScopeVars from "../../../common/ScopeVars.js"; import MailboxFolderService from "../../services/mailboxes/MailboxFolderService.js"; import WelcomeMailService from "../../services/mailboxes/WelcomeMailService.js"; import CreateChannelWorkflow from "../../workflows/channel/creation/CreateChannelWorkflow.js"; import { AppWorkflowContext } from "../../workflows/AppWorkflowContext.js"; import UserLimitService from "../../services/user-limits/UserLimitService.js"; export default class MailboxEvents extends AuthenticatedEvents { @Inject db: SocialMailContext; @Inject emailAddressService: EmailAddressService; @Inject workflowContext: AppWorkflowContext; @Inject mailboxFolderService: MailboxFolderService; @Inject userLimitService: UserLimitService; channelAPI = false; @ExternalInvoke async updateFolders(mb: Mailbox) { await this.mailboxFolderService.updateFolders(mb); return {}; } @ExternalInvoke async fetch(mb: Mailbox) { const { mailboxID } = mb; const st = await this.db.mailboxSyncTargets.statements.select({}, { mailboxID, protocol: "imap" }); if (st) { await SyncMailboxWorkflow.startSyncing(this.workflowContext, st.syncTargetID); } } @ExternalQuery async channels(text: string, id, domainId) { this.channelAPI = true; ScopeVars.fromScope(this).fromWebSite = true; // get current host const page = ServiceProvider.resolve(this, Page as any) as Page; const host = page.request.host; const wcs = ServiceProvider.resolve(this, WebSiteChannelService); const { mailboxes, domains } = await wcs.getChannelAssociations(host); let q = mailboxes ? this.db.mailboxes.where({ mailboxes }, (x, p) => Sql.in(x.mailboxID, p.mailboxes)) : this.db.mailboxes.where({ domains }, (x, p) => Sql.in(x.domainID, p.domains)); if (text) { text = text.toLocaleLowerCase(); if (text.startsWith("@")) { text = text.substring(1); q = q.where({ text}, (x, p) => x.domain.name === p.text); } else if (text.endsWith("@")) { text = text.substring(0, text.length - 1) + "%"; q = q.where({ text }, (x, p) => Sql.text.like(x.emailAddress.emailAddress, p.text)); } else { q = q.where({ text }, (x, p) => x.emailAddress.emailAddress === p.text); } } if (id) { const ids = id.split(","); q = q.where({ ids }, (x, p) => x.mailboxID in p.ids); } if(domainId) { q = q.where({ domainId }, (x, p) => x.domainID === p.domainId); } return q.limit(10); } filter(query: IEntityQuery): IEntityQuery { if (this.verify) { this.sessionUser.ensureLoggedIn(); } if (this.sessionUser.isAdmin) { return query; } const { userID } = this.sessionUser; return query.where({ userID }, (x, p) => x.userMailboxes.some((um) => um.userID === p.userID) || x.domain.hostedDomain.domainUsers.some((d) => d.userID === p.userID)); } modify(query: IEntityQuery): IEntityQuery { if (this.verify) { this.sessionUser.ensureLoggedIn(); } if (this.sessionUser.isAdmin) { return query; } const { userID } = this.sessionUser; return query.where({ userID }, (x, p) => x.userMailboxes.some((um) => um.userID === p.userID) || x.domain.hostedDomain.domainUsers.some((d) => d.userID === p.userID && d.isAdmin === true)); } async beforeInsert(entity: Mailbox, entry: ChangeEntry) { if (this.verify) { this.sessionUser.ensureLoggedIn(); } if (entity.externalEmailAddress) { if(this.verify) { await this.userLimitService.assertCanCreateMailbox(); } await this.createExternalEmailAddress(entity, entry); return; } const { domainID, addSubscribers, authorName, authorEmail } = entity; if (addSubscribers || authorEmail) { if (!authorName) { throw new EntityAccessError(`Author Name and Email are mandatory to add subscribers`); } } let q = this.db.domains.where({ domainID }, (x, p) => x.domainID === p.domainID); // check if user has access to the domain... const { userID } = this.sessionUser; if (!this.sessionUser.isAdmin) { if (this.verify) { q = q.where({ userID }, (x, p) => x.hostedDomain.domainUsers.some((d) => d.userID === p.userID && d.isAdmin === true || d.allowCreateMailbox === true)); // get the prefix... const du = await this.db.hostedDomainUsers.where({ domainID, userID}, (x, p) => x.userID === p.userID && x.domainID === p.domainID).firstOrFail(); // if (du.allowCreateMailbox) { // addUser = true; // } if (du.prefix) { entity.username = du.prefix + entity.username; } await this.userLimitService.assertCanCreateMailbox(); } } if (!entity.mailboxID) { const domain = await q.firstOrFail(); const { name } = domain; const emailAddress = `${entity.username}@${name}`; entity.mailboxID = await this.emailAddressService.getId(emailAddress, entity.name || entity.username); } // if (userID && !this.sessionUser.isAdmin) { // // we need to add access to mailbox without security filter // const um = this.db.userMailboxes.add({ // userID // }); // // we will not check FK we it was inserted from this code // um[ignoreFK] = "mailbox"; // (entity.userMailboxes ??= []).push(um); // } entity.dateUpdated = DateTime.now; } async createExternalEmailAddress(entity: Mailbox, entry: ChangeEntry) { const { userID } = this.sessionUser; if (this.verify) { if (!this.sessionUser.isAdmin) { // check if user can create mailboxes.. const some = await this.db.users.where({ userID }, (x, p) => x.userID === p.userID && x.maxExternalInboxes > Sql.coll.sum(x.userMailboxes.map((u) => 1)) ) .some(); if (!some) { throw new EntityAccessError(`Max limit of mailboxes reached, Please upgrade your membership`); } } } const { emailAddressID: mailboxID, domainID } = await this.emailAddressService.getEmailAddressFrom(entity.externalEmailAddress); entity.mailboxID = mailboxID; entity.domainID = domainID; entity.isExternal = true; } beforeUpdate(entity: Mailbox, entry: ChangeEntry) { entity.dateUpdated = DateTime.now; } onForeignKeyFilter(filter: ForeignKeyFilter): IEntityQuery { if (filter.is((x) => x.emailAddress)) { return null; } if (filter.is((x) => x.domainID)) { return null; } } includeFilter(query: IEntityQuery, type?: any, key?: string) { if (type === ChannelEmail) { return query; } if (type === MailboxTag) { return query; } if (type === MailboxContactEvent) { return query; } return super.includeFilter(query, type, key); } async afterInsert(entity: Mailbox) { const ea = await this.emailAddressService.getEmailAddress(entity.mailboxID); this.emailAddressService.cache?.clear("getHostedMailboxByAddress"); this.emailAddressService.cache?.clear("getHostedMailboxByID"); this.emailAddressService.cache?.clear("getMailbox"); this.emailAddressService.cache?.clear("getMailboxByAddress"); this.emailAddressService.cache?.clear("getMailboxFromId"); this.emailAddressService.cache?.clear("getMailboxId"); const { userID } = this.sessionUser; if (!this.sessionUser.isAdmin && userID) { // lets add user if the user does not have access to domain const { domainID, mailboxID } = entity; const hasDomainAccess = await this.db.hostedDomainUsers.where({ userID, domainID}, (x, p) => x.domainID === p.domainID && x.userID === p.userID && x.isAdmin === true ).some(); if (!hasDomainAccess) { await this.db.userMailboxes.statements.selectOrInsert({ mailboxID, userID }, { mailboxID , userID }); } } await this.updateFolders(entity); if (!entity.isChannel) { const wms = ServiceProvider.resolve(this, WelcomeMailService); await wms.sendWelcomeMail(entity, ea); } else { // add default subscribers... if (entity.addSubscribers || entity.authorEmail) { const { mailboxID, domainID, addSubscribers, authorEmail, authorName } = entity; await this.workflowContext.queue(CreateChannelWorkflow, { mailboxID, domainID, addSubscribers, authorName, authorEmail }); } } // return this.updateIndex(entity); } // afterUpdate(entity: Mailbox, entry: ChangeEntry) { // return this.updateIndex(entity); // } // async updateIndex(entity: Mailbox) { // // if (entity.isChannel) { // // // make sure unsubscribe/subscribe exists... // // // await this.emailAddressService. // // // await this.emailAddressService.getOrCreateChildMailbox(entity.mailboxID, "subscribe-"); // // // await this.emailAddressService.getOrCreateChildMailbox(entity.mailboxID, "unsubscribe-"); // // } // } async beforeDelete(entity: Mailbox, entry: ChangeEntry) { this.sessionUser.ensureIsAdmin(); const{ db } = this; // if (!entity.deleteVerificationID) { // throw new EntityAccessError(`Delete operation not authorized`); // } // const [id, accessCode] = entity.deleteVerificationID.split(":") as any[]; // const v = await db.verificationTokens.statements.select({} , { verificationID: id, accessCode }); // if (!v) { // throw new EntityAccessError(`Delete operation not authorized`); // } await db.fileContents.asQuery() .where(entity, (x, p) => x.appFiles.some((a) => a.email.threadContacts.some((m) => m.mailboxID === p.mailboxID) || a.email.mailboxContactEvents.some((m) => m.mailboxID === p.mailboxID) )) .update((x) => ({ deleted: true })); await db.appFiles.asQuery() .delete(entity, (x, p) => x.email.threadContacts.some((m) => m.mailboxID === p.mailboxID) || x.email.mailboxContactEvents.some((m) => m.mailboxID === p.mailboxID)); await db.emails.asQuery() .delete(entity, (x, p) => x.threadContacts.some((m) => m.mailboxID === p.mailboxID) || x.mailboxContactEvents.some((m) => m.mailboxID === p.mailboxID) ); await db.mailboxContactEmails.asQuery() .delete(entity, (x, p) => x.mailboxID === p.mailboxID); await db.mailboxContactTags.asQuery() .delete(entity, (x, p) => x.mailboxID === p.mailboxID); await db.mailboxContacts.asQuery() .delete(entity, (x, p) => x.mailboxID === p.mailboxID); await db.channelEmails.asQuery() .delete(entity, (x, p) => x.mailboxID === p.mailboxID); } preJson(entity: Mailbox): Mailbox { if (ScopeVars.fromScope(this).fromWebSite || this.channelAPI) { entity.channelConfig = void 0; entity.contacts = void 0; entity.deleteVerificationID = void 0; entity.externalEmailAddress = void 0; entity.storage = void 0; entity.indexAttachments = void 0; entity.indexImageAttachments = void 0; entity.maxSendPerSecond = void 0; entity.nonMembersCanComment = void 0; entity.nonMembersCanPost = void 0; entity.nonMembersCanReact = void 0; entity.threadEmails = void 0; entity.totalThreads = void 0; entity.requiresCommentModeration = void 0; entity.requiresMembershipApproval = void 0; entity.requiresPostModeration = void 0; entity.maxStorage = void 0; entity.firstID = void 0; entity.isExternal = void 0; entity.isPrivateChannel = void 0; } entity.parentID = void 0; return entity; } }