started to convert to typescript
This commit is contained in:
76
back/mails/imap/Box.ts
Normal file
76
back/mails/imap/Box.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import { ImapMessageAttributes } from "imap";
|
||||
import { getMailbox, updateMailbox } from "../../db/imap/imap";
|
||||
import logger from "../../system/Logger";
|
||||
import RegisterMessageInApp from "../saveMessage";
|
||||
import { saveMessage } from "../storeMessage";
|
||||
|
||||
export default class Box {
|
||||
imap: Imap;
|
||||
boxName: string;
|
||||
id: number;
|
||||
box: Object;
|
||||
|
||||
constructor(_imap, _boxId, _boxName) {
|
||||
this.imap = _imap;
|
||||
this.boxName = _boxName;
|
||||
this.id = _boxId;
|
||||
this.box;
|
||||
this.init();
|
||||
}
|
||||
|
||||
async init() {
|
||||
this.box = (await getMailbox(this.id))[0];
|
||||
|
||||
const readOnly = true;
|
||||
this.imap.openBox(this.boxName, readOnly, (err, box) => {
|
||||
if (err) logger.error(err);
|
||||
this.sync(this.box.uidnext, box.uidnext);
|
||||
});
|
||||
}
|
||||
|
||||
sync(savedUid, currentUid) {
|
||||
const promises: Promise<unknown>[] = [];
|
||||
const mails: ImapMessageAttributes[] = [];
|
||||
logger.log(`Syncing from ${savedUid} to ${currentUid} uid`);
|
||||
const f = this.imap.seq.fetch(`${savedUid}:${currentUid}`, {
|
||||
// const f = this.imap.seq.fetch(`${savedUid}:${currentUid}`, {
|
||||
size: true,
|
||||
envelope: true,
|
||||
});
|
||||
|
||||
f.on("message", (msg, seqno) => {
|
||||
msg.once("attributes", (attrs: Attrs) => {
|
||||
console.log(attrs.envelope)
|
||||
mails.push(attrs);
|
||||
promises.push(saveMessage(attrs, this.id, this.imap));
|
||||
});
|
||||
});
|
||||
|
||||
f.once("error", (err) => {
|
||||
logger.error("Fetch error: " + err);
|
||||
});
|
||||
|
||||
f.once("end", async () => {
|
||||
let step = 20;
|
||||
logger.log(promises.length)
|
||||
for (let i = 0; i < promises.length; i += step) {
|
||||
for (let j = i; j < (i + step && promises.length); j++) {
|
||||
await new Promise((resolve, reject) => {
|
||||
promises[j]
|
||||
.then(async (res) => {
|
||||
const register = new RegisterMessageInApp(res, mails[j], this.id);
|
||||
await register.save();
|
||||
resolve("");
|
||||
})
|
||||
.catch((err) => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
}
|
||||
logger.log(`Saved messages ${i + step > promises.length ? promises.length : i + step}/${mails.length}`);
|
||||
updateMailbox(this.id, mails[i].uid);
|
||||
}
|
||||
updateMailbox(this.id, currentUid);
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user