73 lines
2.1 KiB
JavaScript
73 lines
2.1 KiB
JavaScript
const Imap = require("imap");
|
|
const { getAllMailboxes, registerMailbox } = require("../../db/imap/imap");
|
|
const { DEBUG } = require("../../utils/debug");
|
|
const { Box } = require("./Box");
|
|
|
|
class ImapInstance {
|
|
constructor(account) {
|
|
this.imap = new Imap({
|
|
user: account.user,
|
|
password: account.password,
|
|
tlsOptions: { servername: account.host },
|
|
host: account.host,
|
|
port: account.port,
|
|
tls: account.tls,
|
|
});
|
|
|
|
this.account = account;
|
|
this.boxes = [];
|
|
|
|
/**
|
|
* IMAP
|
|
*/
|
|
this.imap.once("ready", () => {
|
|
DEBUG.log("imap connected")
|
|
this.imapReady();
|
|
});
|
|
|
|
this.imap.once("error", function (err) {
|
|
DEBUG.log(err);
|
|
});
|
|
|
|
this.imap.once("end", function () {
|
|
DEBUG.log("Connection ended");
|
|
});
|
|
|
|
this.imap.connect();
|
|
}
|
|
|
|
imapReady() {
|
|
getAllMailboxes(this.account.id).then((mailboxes) => {
|
|
if (mailboxes.length > 0) {
|
|
this.boxes.push(new Box(this.imap, mailboxes[0].mailbox_id, mailboxes[0].mailbox_name));
|
|
} else {
|
|
this.imap.getBoxes('', (err, boxes) => {
|
|
if (err) DEBUG.log(err);
|
|
const allBoxName = this.getAllBox(boxes);
|
|
registerMailbox(this.account.id, allBoxName).then((mailboxId) => {
|
|
this.boxes.push(new Box(this.imap, mailboxId, allBoxName));
|
|
});
|
|
});
|
|
}
|
|
});
|
|
}
|
|
|
|
getAllBox(boxes) {
|
|
// ideally we should get the all box to get all messages
|
|
let allBox;
|
|
Object.keys(boxes).forEach(key => {
|
|
if (key === 'INBOX') return;
|
|
allBox = key;
|
|
Object.keys(boxes[key].children).forEach((childBoxes) => {
|
|
if (boxes[key].children[childBoxes].attribs.includes('\\All')) {
|
|
allBox += '/' + childBoxes;
|
|
}
|
|
});
|
|
});
|
|
return allBox;
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
ImapInstance
|
|
} |