89 lines
2.9 KiB
TypeScript
89 lines
2.9 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.imap_host },
|
|
host: account.imap_host,
|
|
port: account.imap_port,
|
|
tls: account.tls,
|
|
});
|
|
this.account = account;
|
|
this.boxes = [];
|
|
|
|
/**
|
|
* IMAP init
|
|
*/
|
|
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(mailboxes[0].mailbox_id, mailboxes[0].mailbox_name, this));
|
|
} else {
|
|
this.getMailboxName("All").then((allBoxName) => {
|
|
registerMailbox(this.account.id, allBoxName).then((mailboxId) => {
|
|
this.boxes.push(new Mailbox(mailboxId, allBoxName, this));
|
|
});
|
|
});
|
|
}
|
|
});
|
|
};
|
|
|
|
getMailboxName(boxToFound: string): Promise<string> {
|
|
return new Promise((resolve, rejects) => {
|
|
let matchBox = "";
|
|
this.imap.getBoxes("", (err, boxes) => {
|
|
Object.keys(boxes).forEach((key) => {
|
|
if (matchBox.includes("/")) return; // already found
|
|
if (!boxes[key].children) return; // no children
|
|
matchBox = key;
|
|
Object.keys(boxes[key].children).forEach((childBox) => {
|
|
let attribs = boxes[key].children[childBox].attribs;
|
|
for (let i = 0; i < attribs.length; i++) {
|
|
if (attribs[i].includes(boxToFound)) {
|
|
matchBox += "/" + childBox;
|
|
}
|
|
}
|
|
});
|
|
});
|
|
if (!matchBox.includes("/")) {
|
|
logger.warn(`Did not find "${boxToFound}" mailbox`);
|
|
rejects();
|
|
} else {
|
|
resolve(matchBox);
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
getMailbox(mailboxId: number): Mailbox {
|
|
return this.boxes.find((box) => box.id === mailboxId);
|
|
}
|
|
}
|