mail/back/mails/imap/Box.js

59 lines
1.6 KiB
JavaScript

const { getMailbox, updateMailbox } = require("../../db/imap/imap");
const { DEBUG } = require("../../utils/debug");
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) DEBUG.log(err);
this.sync(this.box.uidnext, box.uidnext);
});
}
sync(savedUid, currentUid) {
const promises = [];
const mails = [];
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) => {
DEBUG.log("Fetch error: " + err);
});
f.once("end", async () => {
await Promise.all(promises).then(async (res) => {
for (let i = 0; i < mails.length; i++) {
console.log(i, mails[i].uid)
await registerMessageInApp(res[i], mails[i]);
}
});
updateMailbox(this.id, currentUid);
});
}
}
module.exports = {
Box,
};