import Imap, { ImapMessageAttributes, MailBoxes } from "imap"; import { getMailbox, updateMailbox } from "../../db/imap/imap"; import { Attrs, AttrsWithEnvelope } from "../../interfaces/mail/attrs.interface"; import logger from "../../system/Logger"; import RegisterMessageInApp from "../saveMessage"; import { saveMessage } from "../storeMessage"; export default class Box { imap: Imap; boxName: string; id: number; box: MailBoxes; constructor(_imap, _boxId, _boxName) { this.imap = _imap; this.boxName = _boxName; this.id = _boxId; this.box; this.init(); } async init() { this.box = (await getMailbox(this.id))[0]; const readOnly = true; this.imap.openBox(this.boxName, readOnly, (err, box) => { if (err) logger.err(err); this.sync(this.box.uidnext, box.uidnext); }); } sync(savedUid, currentUid) { const promises: Promise[] = []; const mails: Attrs[] = []; logger.log(`Syncing from ${savedUid} to ${currentUid} uid`); const f = this.imap.seq.fetch(`${savedUid}:${currentUid}`, { // const f = this.imap.seq.fetch(`${savedUid}:${currentUid}`, { size: true, envelope: true, }); f.on("message", (msg, seqno) => { msg.once("attributes", (attrs: AttrsWithEnvelope) => { console.log(attrs.envelope) mails.push(attrs); promises.push(saveMessage(attrs, this.id, this.imap)); }); }); f.once("error", (err) => { logger.err("Fetch error: " + err); }); f.once("end", async () => { let step = 20; logger.log(promises.length) for (let i = 0; i < promises.length; i += step) { for (let j = i; j < (i + step && promises.length); j++) { await new Promise((resolve, reject) => { promises[j] .then(async (res: number) => { const register = new RegisterMessageInApp(res, mails[j], this.id); await register.save(); resolve(""); }) .catch((err) => { reject(err); }); }); } logger.log(`Saved messages ${i + step > promises.length ? promises.length : i + step}/${mails.length}`); updateMailbox(this.id, mails[i].uid); } updateMailbox(this.id, currentUid); }); } }