77 lines
2.4 KiB
TypeScript
77 lines
2.4 KiB
TypeScript
import { Account } from "./ImapSync";
|
|
|
|
import Imap from "imap";
|
|
import { getAllMailboxes, registerMailbox } from "../../db/imap/imap";
|
|
import logger from "../../system/Logger";
|
|
import Box from "./Box";
|
|
|
|
export class ImapInstance {
|
|
imap: Imap;
|
|
account: Account;
|
|
boxes: Box[];
|
|
|
|
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.error("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 Box(this.imap, mailboxes[0].mailbox_id, mailboxes[0].mailbox_name));
|
|
} else {
|
|
this.imap.getBoxes("", (err, boxes) => {
|
|
if (err) logger.error(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;
|
|
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;
|
|
}
|
|
} |