const { getMailbox, updateMailbox } = require("../../db/imap/imap"); const { logger } = require("../../system/Logger"); const { registerMessageInApp } = require("../saveMessage"); const { saveMessage } = require("../storeMessage"); class Box { 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.error(err); this.sync(this.box.uidnext, box.uidnext); }); } sync(savedUid, currentUid) { const promises = []; const mails = []; logger.log(`Syncing from ${savedUid} to ${currentUid} uid`); const f = this.imap.seq.fetch(`${savedUid}:${currentUid}`, { size: true, envelope: true, }); f.on("message", (msg, seqno) => { msg.once("attributes", (attrs) => { mails.push(attrs); promises.push(saveMessage(attrs, this.id, this.imap)); }); }); f.once("error", (err) => { logger.error("Fetch error: " + err); }); f.once("end", async () => { let step = 20; for (let i = 0; i < promises.length; i += step) { for (let j = i; j < (i + step && promises.length); j++) { console.log(j, promises.length, promises[j]) await new Promise((resolve, reject) => { promises[j] .then(async (res) => { await registerMessageInApp(res, mails[j], this.id); 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); } // await Promise.all(promises).then(async (res) => { // for (let i = 0; i < mails.length; i++) { // logger.log(`Saved message ${i}/${mails.length}`); // } // }); updateMailbox(this.id, currentUid); }); } } module.exports = { Box, };