started to convert to typescript
This commit is contained in:
77
back/mails/imap/ImapInstance.ts
Normal file
77
back/mails/imap/ImapInstance.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user