/* eslint-disable no-console */ import { RegisterSingleton, ServiceProvider } from "@entity-access/entity-access/dist/di/di.js"; import SocialMailContext from "../model/SocialMailContext.js"; import { globalServices } from "../../globalServices.js"; import EntityAccessError from "@entity-access/entity-access/dist/common/EntityAccessError.js"; import Domain from "../model/entities/Domain.js"; import { AppWorkflowContext } from "../workflows/AppWorkflowContext.js"; import IndexEmailAddressWorkflow from "../workflows/email/index/IndexEmailAddressWorkflow.js"; import { hash } from "node:crypto"; import type EmailAddress from "../model/entities/EmailAddress.js"; import { ICacheContainer, ObjectCache, cacheFor } from "../../common/cacheFor.js"; @RegisterSingleton export default class EmailAddressService implements ICacheContainer { cache: ObjectCache; @cacheFor() public async getHostedDomain(name: string) { name = name.toLowerCase().trim(); using scope = globalServices.createScope(); const db = scope.resolve(SocialMailContext); return await db.hostedDomains.where({ name }, (x, p) => x.domain.name === p.name) .include((x) => x.domain) .first(); } @cacheFor() public async getHostedDomainByID(id: number) { using scope = globalServices.createScope(); const db = scope.resolve(SocialMailContext); return await db.hostedDomains.where({ id }, (x, p) => x.domainID === p.id) .include((x) => x.domain) .first(); } @cacheFor() public async getOrCreateDomain(name: string) { name = name.toLocaleLowerCase().trim(); using scope = globalServices.createScope(); const db = scope.resolve(SocialMailContext); db.raiseEvents = false; db.verifyFilters = false; let d = { name, domainID: void 0 } as Partial; let lastError; for (let index = 0; index < 3; index++) { try { // d = await db.domains.saveDirect({ // mode: "selectOrInsert", // changes: d, // keys: d // }); d = await db.domains.statements.selectOrInsert(d, { name }); return d.domainID; } catch (error){ lastError = error; } } throw lastError; } @cacheFor() public async lookupDomainID(emailAddressID: number) { using scope = globalServices.createScope(); const db = scope.resolve(SocialMailContext); db.raiseEvents = false; db.verifyFilters = false; const d = await db.emailAddresses .where({ emailAddressID }, (x, p) => x.emailAddressID === p.emailAddressID) .first(); if (d) { return d.domainID; } throw new EntityAccessError(`No domainID registered for email address id ${emailAddressID}`); } @cacheFor() public async getMailboxFromId(id) { using scope = globalServices.createScope(); const db = scope.resolve(SocialMailContext); const mb = await db.mailboxes.where({ id }, (x, p) => x.mailboxID === p.id) .include((x) => x.emailAddress) .first(); return mb; } @cacheFor() public async getDomainByID(id) { using scope = globalServices.createScope(); const db = scope.resolve(SocialMailContext); const mb = await db.domains.where({ id }, (x, p) => x.domainID === p.id) .first(); return mb; } @cacheFor() public async getMailboxId(emailAddress: string) { emailAddress = emailAddress.trim().toLocaleLowerCase(); using scope = globalServices.createScope(); const db = scope.resolve(SocialMailContext); const mb = await db.mailboxes.where({ emailAddress}, (x, p) => x.emailAddress.emailAddress === p.emailAddress) .first(); return mb?.mailboxID; } @cacheFor() public async getMailbox(emailAddress: string) { emailAddress = emailAddress.trim().toLocaleLowerCase(); using scope = globalServices.createScope(); const db = scope.resolve(SocialMailContext); const mb = await db.mailboxes.where({ emailAddress}, (x, p) => x.emailAddress.emailAddress === p.emailAddress) .first(); return mb; } @cacheFor() public async getEmailAddressFrom(emailAddress: string) { const id = await this.getId(emailAddress); using scope = globalServices.createScope(); const db = scope.resolve(SocialMailContext); const mb = await db.emailAddresses.where({ id}, (x, p) => x.emailAddressID === p.id) .include((x) => x.mailbox.domain) .first(); return mb; } @cacheFor() public async getHostedMailboxByAddress(emailAddress: string) { emailAddress = emailAddress.trim().toLocaleLowerCase(); using scope = globalServices.createScope(); const db = scope.resolve(SocialMailContext); const mb = await db.mailboxes.where({ emailAddress }, (x, p) => x.emailAddress.emailAddress === p.emailAddress && x.isExternal === false) .first(); return mb?.mailboxID > 0 ? mb.mailboxID : void 0; } @cacheFor() public async getHostedMailboxByID(mailboxID: number) { using scope = globalServices.createScope(); const db = scope.resolve(SocialMailContext); return await db.mailboxes.where({ mailboxID }, (x, p) => x.mailboxID === p.mailboxID) .include((x) => x.emailAddress) .first(); } @cacheFor() public async getMailboxByAddress(address: string) { address = address.trim().toLowerCase(); using scope = globalServices.createScope(); const db = scope.resolve(SocialMailContext); return await db.mailboxes.where({ address }, (x, p) => x.emailAddress.emailAddress === p.address) .include((x) => x.emailAddress) .first(); } @cacheFor() public async isHostedChannelID(emailAddressID) { using scope = globalServices.createScope(); const db = scope.resolve(SocialMailContext); const mb = await db.mailboxes.where({ emailAddressID}, (x, p) => x.mailboxID === p.emailAddressID && x.isChannel === true) .first(); return mb?.mailboxID > 0; } @cacheFor() public async getEmailAddress(id: number) { using scope = globalServices.createScope(); const db = scope.resolve(SocialMailContext); const emailAddress = await db.emailAddresses .where({ id }, (x, p) => x.emailAddressID === p.id) .first(); return emailAddress; } public async getOrCreateChildMailbox(parentID: number, prefix: string) { using scope = globalServices.createScope(); const db = scope.resolve(SocialMailContext); db.raiseEvents = false; db.verifyFilters = false; const emailAddress = await this.getEmailAddress(parentID); const child = `${prefix}${emailAddress.emailAddress}`; const mailbox = await db.mailboxes .where({ parentID, child }, (x, p) => x.emailAddress.emailAddress === p.child && x.parentID === p.parentID ) .first(); if (mailbox) { return mailbox; } const mailboxID = await this.getId(`${prefix}${emailAddress.emailAddress}`); const { domainID } = emailAddress; const mb = db.mailboxes.add({ mailboxID, parentID, domainID, maxStorage: Number.MAX_SAFE_INTEGER }); await db.saveChanges(); return mb; } @cacheFor() public async getIdIfExists(emailAddress: string) { emailAddress = emailAddress.trim().toLocaleLowerCase(); using scope = globalServices.createScope(); const db = scope.resolve(SocialMailContext); const e = await db.emailAddresses.withKeys({ emailAddress }).select(); return e?.emailAddressID; } @cacheFor() public async getId(emailAddress: string, name: string = emailAddress, validate = true) { emailAddress = emailAddress.trim().toLocaleLowerCase(); name = name?.trim(); const tokens = emailAddress.split("@"); if (tokens.length !== 2) { if (validate) { throw new EntityAccessError(`Invalid email address ${emailAddress}`); } return await this.getId(emailAddress + "@empty", name); } const [ username, domainName ] = tokens; using scope = globalServices.createScope(); const db = scope.resolve(SocialMailContext); db.raiseEvents = false; db.verifyFilters = false; const domainID = await this.getOrCreateDomain(domainName); name ||= username; if (name.length > 399) { name = name.substring(0, 399); } let largeEmailAddress; let largeEmailHash; const originalEmail = emailAddress; for (let index = 0; index < 3; index++) { try { if (originalEmail.length > 399) { const h = await this.generateHashedEmail(db, originalEmail, domainName); largeEmailAddress = originalEmail; largeEmailHash = h.largeEmailHash; emailAddress = h.emailAddress; } const changes = { emailAddress, name, domainID, } as Partial; if (largeEmailAddress) { changes.largeEmailAddress = largeEmailAddress; changes.largeEmailHash = largeEmailHash; } // const keys = { // emailAddress // }; // const ea = await db.emailAddresses.saveDirect({ // mode: "selectOrInsert", // changes, // keys // }); const ea = await db.emailAddresses.statements.selectOrInsert(changes, { emailAddress }); const hasMailbox = await db.mailboxes.where(ea, (x, p) => x.mailboxID === p.emailAddressID).some(); if (name && ea.name !== name) { // schedule for names tag const wc = ServiceProvider.resolve(this, AppWorkflowContext); await IndexEmailAddressWorkflow.queue(wc); } if(!hasMailbox && ((name && ea.name !== name) || ea.domainID !== domainID)) { ea.name = name; ea.domainID = domainID; // schedule tag updates... await db.emailAddresses.statements.update(ea); // await db.emailAddresses.saveDirect({ // mode: "update", // changes: { // name, // domainID // }, // keys: { // emailAddressID: ea.emailAddressID // } // }); } return ea.emailAddressID; } catch (error) { console.error(error); } } } async generateHashedEmail(db: SocialMailContext, emailAddress, domainName) { const largeEmailHash = hash("sha256", emailAddress, "hex"); let e = await db.emailAddresses.statements.select({}, { largeEmailHash }); if (e) { e = await db.emailAddresses.where({ largeEmailHash}, (x, p) => x.largeEmailHash === p.largeEmailHash) .orderByDescending((x) => x.emailAddressID) .first(); if (e.largeEmailAddress !== emailAddress) { return { largeEmailHash, emailAddress: `${BigInt(e.emailAddressID).toString(36)}-${largeEmailHash}@${domainName}`}; } } return { largeEmailHash, emailAddress: `${largeEmailHash}@${domainName}` }; } }