mail/back/mails/imap/ImapInstance.ts
2023-04-09 23:46:33 +02:00

77 lines
2.4 KiB
TypeScript

import { Account } from "../EmailManager";
import Imap from "imap";
import { getAllMailboxes, registerMailbox } from "../../db/imap/imap-db";
import logger from "../../system/Logger";
import Mailbox from "./Mailbox";
export class ImapInstance {
imap: Imap;
account: Account;
boxes: Mailbox[];
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", () => {
logger.log("Imap connected for " + this.account.user);
this.imapReady();
});
this.imap.once("error", (err) => {
logger.err("Imap error for " + this.account.user + ": " + err);
});
this.imap.once("end", () => {
logger.log("Connection ended for " + this.account.user);
});
this.imap.connect();
}
imapReady() {
getAllMailboxes(this.account.id).then((mailboxes) => {
if (mailboxes.length > 0) {
this.boxes.push(new Mailbox(this.imap, mailboxes[0].mailbox_id, mailboxes[0].mailbox_name));
} else {
this.imap.getBoxes("", (err, boxes) => {
if (err) logger.err(err);
const allBoxName = this.getAllBox(boxes);
registerMailbox(this.account.id, allBoxName).then((mailboxId) => {
this.boxes.push(new Mailbox(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;
if (allBox.includes("/")) return; // already found
if (!boxes[key].children) return; // no children
allBox = key;
Object.keys(boxes[key].children).forEach((childBoxes) => {
if (boxes[key].children[childBoxes].attribs.includes("\\All")) {
allBox += "/" + childBoxes;
}
});
});
if (!allBox.includes("/")) logger.warn("Did not find 'All' mailbox");
return allBox;
}
}