import Inject, { ServiceProvider } from "@entity-access/entity-access/dist/di/di.js"; import SocialMailContext from "../../model/SocialMailContext.js"; import TimeSpan from "@entity-access/entity-access/dist/types/TimeSpan.js"; import DateTime from "@entity-access/entity-access/dist/types/DateTime.js"; import MailboxSyncTarget from "../../model/entities/MailboxSyncTarget.js"; import ImapClient, { IImapFolder } from "../../../protocols/imap/client/ImapClient.js"; import EmailSerializerService from "../../smtp/services/EmailSerializerService.js"; import Workflow, { UniqueActivity } from "@entity-access/entity-access/dist/workflows/Workflow.js"; import AVService from "../../storage/volume/av/AVService.js"; import UpdateTagsWorkflow from "../email/UpdateTagsWorkflow.js"; import ScopeVars from "../../../common/ScopeVars.js"; import EncryptionService from "../../services/encryption/EncryptionService.js"; import { AppWorkflowContext } from "../AppWorkflowContext.js"; interface ISyncState { log: string[], total: string, progress: string, mailboxes: { [key: string]: { lastUID: string; lastIndex:string; uidValidity: string; } } } export default class SyncMailboxWorkflow extends Workflow { static taskGroup = "sync"; public static startSyncing(context: AppWorkflowContext, id: number) { return context.queue(SyncMailboxWorkflow, id, { id: `sync-mailbox-id-${id}` }); } public static async stopSyncing(context: AppWorkflowContext, id: number) { const wid = `sync-mailbox-id-${id}`; await context.get(this, wid); } private db?: SocialMailContext; private serializer?: EmailSerializerService; private started: DateTime; private syncState: ISyncState; private target: MailboxSyncTarget; // private progress: bigint = 0n; // private total: bigint = 0n; async run() { this.preserveTime = TimeSpan.fromMinutes(1); this.failedPreserveTime = TimeSpan.fromMinutes(15); await this.sync(0); } @UniqueActivity async sync( i: number, @Inject db?: SocialMailContext, @Inject serializer?: EmailSerializerService ) { this.db = db; this.serializer = serializer; db.raiseEvents = false; db.verifyFilters = false; const { target, syncState } = await this.loadSyncTarget(); this.syncState = syncState; this.target = target; syncState.log = []; this.started = DateTime.now; // eslint-disable-next-line no-console console.log(`${this.started.toJSON()} Sync Start: ${target.username} with host ${target.host}`); const sv = ScopeVars.fromScope(this); sv.taskGroup = "sync-queue"; try { // verify if AV is loaded await AVService.scanner(); await this.syncImap(target, syncState); target.lastSync = DateTime.now; target.lastSyncStatus = "success"; syncState.log = []; } catch (error) { // eslint-disable-next-line no-console console.error(JSON.stringify({ error: error.cause?.stack ?? error.cause ?? error.stack ?? error, log: syncState.log })) target.lastSync = DateTime.now; target.lastSyncStatus = "failed"; target.lastSyncError = `${error.stack ?? error}`; syncState.log.push(target.lastSyncError); } target.syncState = JSON.stringify(syncState); await db.saveChanges(); } async syncImap(target: MailboxSyncTarget, syncState: ISyncState) { const { host , port, username , password, isSecure: ssl, allFolderName } = target; // decrypt password const es = ServiceProvider.resolve(this, EncryptionService); using client = await ImapClient.connect({ host, port, username, password: es.secure.decrypt(password), ssl, startSSL: true, logger(item, ... others) { // console.log(item, ... others); syncState.log.push(item.stack ? item.stack : item.toString()); } }); let folders = await client.list(); let allFolder = folders.find((x) => x.specialUse?.all); if (!allFolder) { if (allFolderName) { allFolder = folders.find((x) => x.name === allFolderName); } } if (allFolder) { folders = [allFolder]; } syncState.total = "0"; if(!syncState.progress) { syncState.progress = "0"; } for (const folder of folders) { await this.syncImapFolder(target, client, syncState, folder); } } async syncImapFolder( target: MailboxSyncTarget, client: ImapClient, syncState: ISyncState, folder: IImapFolder) { const examine = await client.examine(folder.name); const { mailboxID } = target; const state = (syncState.mailboxes[folder.name] ??= { lastUID: "0", uidValidity: "0", lastIndex: "0" }); const lastUID = BigInt(state.lastUID || 0); const uidValidity = BigInt(examine.uidValidity); const uidNext = BigInt(examine.uidNext); const step = 128n; syncState.total = BigInt(examine.exists).toString(); // we will move to 1 if uidValidity changes... let start = BigInt(state.uidValidity || "0") !== uidValidity ? 1n: lastUID + 1n; if (syncState.total === "0") { // console.log(`No more messages in folder ${folder.name}`); return; } state.uidValidity = uidValidity.toString(); const { serializer } = this; const { first, last } = await client.uidGetAvailableRange(); if(start < first) { start = first; } if (start > last) { // console.log(`${start} is more than ${last} in ${folder.name}`); return; } // console.log(`${start} < ${last}, reading ${folder.name}`); // we should not run for more than 5 minutes while( DateTime.now.diff(this.started).totalMinutes < 14) { if (start >= uidNext) { break; } if (start > last) { break; } // run with only 10 messages per iteration... // console.log(`Begin sync ${start}`); const end = start + step; // console.log(`Begin sync ${start} - ${end}`); const range = await client.uidFetchRange({ start, end}); // const q = new AsyncQueue(); // const tasks = [] as { emailID: string, labels: string[], fetchPromise: Promise}[]; const begin = start; let i = 0; let pi = 0; let currentLastUID = start; // const tm = new AsyncTaskManager(4); for (const iterator of range) { await client.noop(); i++; const { emailID, uid, labels, messageId, from } = iterator; const cUID = BigInt(uid); state.lastIndex = iterator.index.toString(); const existingEmail = await this.getExistingEmail(emailID, mailboxID, from, messageId); if(existingEmail) { if (existingEmail.status !== "draft") { // we might need to update status... // tags... if (labels?.length) { const tags = labels.join(","); await this.db.emails.where(existingEmail, (x, p) => x.emailID === p.emailID) .update({ tags }, (x, p) => ({ tags: p.tags})); } await this.context.queue(UpdateTagsWorkflow, existingEmail.emailID, { id: `update-tags-email-id-${existingEmail.emailID}`}); // we will send noop to // prevent disconnection syncState.progress = (BigInt(syncState.progress) + 1n).toString(); if (cUID > currentLastUID && cUID < end) { currentLastUID = cUID; } continue; } } // Sync isn't duplicate email // console.log(`New email ${messageId} from ${from}`); const isDraft = labels?.some((r) => /^\\Draft$/i.test(r)); const result = await client.uidFetchRFC822(uid); syncState.progress = (BigInt(syncState.progress) + 1n).toString(); // console.log(`Saving ${uid}`); await serializer.saveRFC822(result.rfc822, { externalEmailID: emailID, localEmailID: existingEmail?.emailID, messageId, labels, mailbox: target.mailbox, receivedViaSMTP: false, isDraft, silent: true }); if (cUID > currentLastUID && cUID < end) { currentLastUID = cUID; } // console.log(`Saved ${uid}`); } // await q.wait(); state.lastUID = currentLastUID.toString(); start += step; await this.saveState(); // eslint-disable-next-line no-console console.log(`${target.username}: Since UID: ${begin}, Saved ${pi++}/${i}, Progress ${state.lastIndex}/${syncState.total}`); } console.log(`${target.username}: Sync done for ${folder.name}`); } protected toDebugString() { let log = this.syncState?.log; if(!log) { return ""; } if(log.length > 20) { log = log.slice(log.length - 20); } return log as any; } private async getExistingEmail(emailID: string, mailboxID: number, from: string, messageId: string) { // this will never match probably messageId ||= " "; if (from) { from = from.toLowerCase(); } if (emailID) { const e = await this.db.emails.where({ emailID, mailboxID, messageId }, (x, p) => x.externalEmailID === p.emailID && x.syncedMailboxID === p.mailboxID ) .first(); if (e) { return e; } } return await this.db.emails.where({ mailboxID, messageId, from }, (x, p) => x.sentMessageID === p.messageId && x.senderID === p.mailboxID ) .first(); } private async saveState() { const { syncState } = this; if(syncState.log.length > 200) { syncState.log = syncState.log.slice(syncState.log.length - 200); } this.target.syncState = JSON.stringify(this.syncState); await this.db.mailboxSyncTargets.statements.update(this.target); } private async loadSyncTarget() { const id = this.input; const target = await this.db.mailboxSyncTargets .where({ id }, (x, p) => x.syncTargetID === p.id && x.active === true) .include((x) => [x.mailbox.emailAddress]) .first(); if (target === null) { throw new Error(`No active sync found for ${id}`); } let syncState: ISyncState = { log: [], progress: "0", total: "0", mailboxes: { } }; if (target.syncState) { try { const ss = JSON.parse(target.syncState); if(ss?.mailboxes) { syncState = ss; } } catch { // do nothing } } return { target, syncState }; } }