/* eslint-disable no-console */ import { tokenize } from "../../core/tokenizer.js"; import SocketClient from "../../socket/client/SocketClient.js"; import { ImapParser } from "../parser/imapParser.js"; export interface IImapResponse { data: string[]; end: string; } export interface IImapFolder { name: string; separator: string, specialUse: { all?: boolean, archive?: boolean, drafts?: boolean, flagged?: boolean, junk?: boolean, sent?: boolean, important?: boolean, trash?: boolean }, options: { hasNoChildren?, noSelect?, hasChildren?, } } /** * ImapClient vs other Imap Libraries. * 1. This one has generators allowing less memory and more CPU usage. * 2. RegEx based forward only parser */ export default class ImapClient { public static async connect({ host, username, password, startSSL = true, ssl = false, port = ssl ? 993 : 143, logger = console.log }) { const socket = await SocketClient.connect({ port, host, ssl, logger}); const greeting = await socket.readLine(); if (!greeting || !greeting.startsWith("* OK")) { socket.destroy(); throw new Error("Invalid IMAP Greeting"); } socket.timeout = 1 * 60 * 1000; const imapClient = new ImapClient(socket, logger); try { await imapClient.getCapabilities(); logger?.(`LOGIN "${username}" "********"`); await imapClient.sendCommand(`LOGIN "${username}" "${password}"`, void 0, false); return imapClient; } catch (error) { imapClient.socket.destroy(); throw error; } } public readonly capabilities = new Map(); public get timeout() { return this.socket.timeout; } public set timeout(v) { this.socket.timeout = v; } private id: number = 1; private pending: Map void, reject: (error) => void}> = new Map(); private constructor(private socket: SocketClient, private logger: (item) => void) { socket.onTimeout((error)=> { for(const p of this.pending.values()) { p.reject(error); } logger?.(error); // this.pending.clear(); }); this.start().catch((error) => { // we need to stop all pending... for(const p of this.pending.values()) { p.reject(error); } logger?.(error); // this.pending.clear(); }); } /** * Retrieve list of all folders... */ async list() { let specialUse = ""; if (this.capabilities.has("SPECIAL-USE")) { specialUse = " RETURN (SPECIAL-USE)"; } const list = await this.sendCommand(`LIST "" "*"${specialUse}`); const folders = [] as IImapFolder[]; for (const iterator of list.data) { folders.push(ImapParser.list(iterator)); } return folders; } async examine(folder) { const r = await this.sendCommand(`EXAMINE "${ImapParser.encodeUtf7(folder)}"`); return ImapParser.examine(r.data); } noop() { return this.sendCommand("NOOP"); } async uidGetAvailableRange() { const fetchFirst = await this.sendCommand(`FETCH 1 UID`); const fetchLast = await this.sendCommand(`UID FETCH * (UID)`); const { value: firstR } = ImapParser.fetch(fetchFirst.data).next(); const { value: lastR } = ImapParser.fetch(fetchLast.data).next(); const first = firstR?.uid; const last = lastR?.uid; return { first: first ? BigInt(first) : BigInt(0), last: last ? BigInt(last) : BigInt(0) }; } async uidFetchRange({ start = 1 as number | bigint, end = 10 as number | bigint, internalDate = true, from = true, flags = true, messageID = true} = {}) { const options = []; if (flags) { options.push("FLAGS"); } const fields = []; if (messageID) { fields.push("Message-ID"); } if (from) { fields.push("From"); } if (fields.length) { options.push(`BODY[HEADER.FIELDS (${fields.join(" ")})]`); } if(internalDate) { options.push("INTERNALDATE"); } if (this.capabilities.has("X-GM-EXT-1")) { options.push("X-GM-MSGID"); options.push("X-GM-LABELS"); } if (this.capabilities.has("OBJECTID")) { options.push("EMAILID"); } const r = await this.sendCommand(`UID FETCH ${start}:${end} (${options.join(" ")})`); return ImapParser.fetch(r.data); } async uidFetchRFC822(id) { const r = await this.sendCommand(`UID FETCH ${id} (BODY.PEEK[])`); const { value, done } = ImapParser.fetch(r.data).next(); if (done) { throw new Error("Parser error"); } return value; } async sendCommand( line: string, transformer?: (tx: IImapResponse) => T, log = true): Promise { const id = `X${(this.id++).toString(16)}`; await this.socket.writeLine(`${id} ${line}`, { log }); const r = await new Promise((resolve, reject) => { this.pending.set(id, { resolve, reject }); }); if (transformer) { return transformer(r as any); } return r as any; } [Symbol.dispose]() { this.socket.destroy(); } private async getCapabilities() { const capabilities = await this.sendCommand("CAPABILITY"); for (const iterator of tokenize(capabilities.data[0], " ")) { const tokens = iterator.split("="); const [key] = tokens; const value = tokens[1] ?? key; this.capabilities.set(key, value); } this.logger?.(capabilities); } private async start() { let data = []; let firstToken: string; while(true) { let line = await this.socket.readLine(); if (line.startsWith("*")) { // we will have to read buffer of exactly defined characters... // if the line ends with {(\d+)} const lastLine = line.substring(1).trimStart(); if (lastLine.endsWith("}")) { const index = lastLine.lastIndexOf("{"); if (index !== -1) { const length = parseInt(lastLine.substring(index + 1, lastLine.length - 1), 10); // read these many bytes... // lastLine = lastLine.substring(0, index); const literal = (await this.socket.readChars(length)).toString("ascii"); // parser will take care of literal // data.push(`${lastLine}\r\n${current}`); // we will inject literal as an object with toString so // analyzer can skip it if it needs to data.push( lastLine, { literal, toString() { return this.literal; } } ); continue; } } data.push(lastLine); continue; } const originalLine = line; const firstTokenIndex = line.indexOf(' '); if (firstTokenIndex === -1) { data.push(line); continue; } firstToken = line.substring(0, firstTokenIndex).trim(); const pending = this.pending.get(firstToken); if (!pending) { // now such command found... // console.error(`Unknown response`); data.push(line); continue; } line = line.substring(firstTokenIndex).trimStart(); if (line.startsWith("NO")) { if(this.pending.delete(firstToken)) { try { pending.reject(new Error(originalLine)); } catch {} // end of command ... } data = []; } if (line.startsWith("BAD")) { if(this.pending.delete(firstToken)) { try { pending.reject(new Error(line)); } catch {} // end of command ... } data = []; } if (line.startsWith("OK")) { // end of command ... if(this.pending.delete(firstToken)) { try { pending.resolve({ data, end: line }); } catch {} } data = []; } } } }