// parse name with utf7-imap import iconv from "iconv-lite"; import type { IImapFolder } from "../client/ImapClient.js"; import { stringParser } from "../../core/stringParser.js"; import DateTime from "@entity-access/entity-access/dist/types/DateTime.js"; import { tokenize } from "../../core/tokenizer.js"; import { stripBrackets } from "../../../common/stripBrackets.js"; export interface IGenericFetchResult { index?: number, uid: number; emailID?: string; labels?: string[], internalDate: DateTime; flags: Set; headers: { [key: string]: string}; rawData: string; rfc822: any; messageId: string; from?: string; response: { [key: string]: any}; }; const specialFolder = /^\\(all|archive|drafts|flagged|junk|sent|trash|important)$/i; const examineFlags = /^FLAGS\s+\(([^\)]+)\).*/i; const examineOkUIDValidityPair = /^OK\s+\[UIDVALIDITY\s+(\d+)\].*/gi; const examineOkUIDNext = /^OK\s+\[UIDNEXT\s+(\d+)\].*/gi; const examineOkHighestModSeq = /^OK\s+\[HIGHESTMODSEQ\s+(\d+)\].*/gi; const extractHeader = (headers: any, name) => { let v = headers[name]; if (v) { if (Array.isArray(v)) { v = v[0]; } v = stripBrackets(v); headers[name] = v; return v; } }; export class ImapParser { static encodeUtf7(folder: any) { return iconv.encode(folder, "utf7-imap"); } public static examine(lines: string[]) { const flags = []; let uidValidity = 0; let uidNext = 0; let exists = 0; let recent = 0; let highestModeSeq = void 0; for (const line of lines) { let groups = examineFlags.exec(line); if (groups?.length) { for (const iterator of groups[1].split(" ")) { flags.push(iterator); } continue; } groups = examineOkUIDValidityPair.exec(line); if (groups?.length) { uidValidity = parseInt(groups[1], 10); continue; } groups = examineOkUIDNext.exec(line); if (groups?.length) { uidNext = parseInt(groups[1], 10); continue; } groups = examineOkHighestModSeq.exec(line); if (groups?.length) { highestModeSeq = parseInt(groups[1], 10); continue; } groups = /(\d+)\s+EXISTS/i.exec(line); if (groups?.length) { exists = parseInt(groups[1], 10); continue; } groups = /(\d+)\s+RECENT/i.exec(line); if (groups?.length) { recent = parseInt(groups[1], 10); continue; } } return { flags, uidNext, uidValidity, highestModeSeq, exists, recent }; } public static list(text: string): IImapFolder { const r = /LIST\s+\(([^\)]*)\)\s+\"([^\"])\"\s+((\"([^\"]+)\")|(.+))/gi; const groups = r.exec(text); const [ _ , folderOptions, separator ] = groups; const folder = iconv.decode( Buffer.from( groups[5] ?? groups[3]), "utf7-imap"); const options = {}; const specialUse = {}; for (const iterator of folderOptions.split(" ")) { if (specialFolder.test(iterator)) { specialUse[iterator.substring(1).toLocaleLowerCase()] = true; continue; } const name = iterator.substring(1); options[name[0].toLocaleLowerCase() + name.substring(1)] = true; } return { specialUse, options, name: folder, separator }; } public static *fetch(text: any[]): Generator { if(!text?.length) { return; } const iterator = new ImapTokenStream(text); for(;;) { if(iterator.done) { return; } const r = {} as any; // sample // 9 FETCH (UID 10 FLAGS ($Junk \Seen) BODY[HEADER.FIELDS (Message-ID)] {55} // 9 FETCH (UID 10 INTERNALDATE "08-Dec-2004 05:36:05 +0000" FLAGS ($Junk \\Seen) BODY[HEADER.FIELDS (Message-ID)] {55} const body = {}; let bodyKey = ""; let rawData = ""; try { const index = iterator.readNumber(); if (iterator.consumeIf("EXISTS")) { continue; } if (iterator.consumeIf("EXPUNGE")) { continue; } iterator.expect("FETCH", "("); // read pairs... while(iterator.current !== ")") { // read... if(iterator.done) { return; } const { key, value } = iterator.readPair(); r[key] = value; if (key.startsWith("BODY")) { body[key] = value; body["rawData"] = value; rawData = value as any; bodyKey = key; } if (key.startsWith("BODY[]")) { body[key] = value; body["rawData"] = value; body["rfc822"] = value; rawData = value as any; bodyKey = key; } if (key === "RFC822") { rawData = value as any; body["rfc822"] = value; } } iterator.consume(); const date = r.INTERNALDATE; const headers = bodyKey.startsWith("BODY[HEADER") ? ImapParser.parseHeaders(rawData) : {}; const messageId = extractHeader(headers, "Message-ID"); const from = extractHeader(headers, "From"); // let messageId = headers["Message-ID"]; // if (messageId) { // if (Array.isArray(messageId)) { // messageId = messageId[0]; // } // if (messageId.startsWith("<") && messageId.endsWith(">")) { // headers["Message-ID"] = messageId = messageId.substring(1, messageId.length - 1); // } // } let emailID: string = r["EMAILID"] ?? r["X-GM-MSGID"]; if (emailID) { if (Array.isArray(emailID)) { emailID = emailID[0]; } if (emailID && /^\([^\)]+\)$/.test(emailID)) { emailID = emailID.substring(1, emailID.length - 1); } } let labels = r["X-GM-LABELS"]; if (Array.isArray(labels) && labels.length > 0) { const l = []; for (const it of labels) { let label = it as string; if(label.startsWith('"') && label.endsWith('"')) { label = label.substring(1, label.length-1); } if (label.startsWith("\\")) { label = label.substring(1); } l.push(label); } labels = l; } const fr = { index, uid: r.UID, emailID, labels, from, internalDate: date ? DateTime.parse(date.substring(0, date.length-2)) : void 0, flags: new Set(r.FLAGS ?? []), messageId, ... body, headers, response: r } as IGenericFetchResult; yield fr; } catch (error) { throw new Error(`Parsing failed for ${rawData}${text.join("\n")}\r\n${error}`); } } } static parseHeaders(text: string) { text = text.trimStart(); const headers = {}; let headerKey; let headerValue: string[]; for (const iterator of tokenize(text, "\r\n")) { if (!iterator) { if (headerKey) { headers[headerKey] = headerValue.length > 1 ? headerValue : headerValue[0]; } headerValue = []; headerKey = null; continue; } if (/^\s/.test(iterator)) { headerValue.push(iterator.trimStart()); continue; } if (headerKey) { headers[headerKey] = headerValue.length > 1 ? headerValue : headerValue[0]; } const [k, v] = iterator.split(":", 2); headerKey = k; headerValue = [v?.trimStart()]; } if (headerKey) { headers[headerKey] = headerValue.length > 1 ? headerValue : headerValue[0]; } return headers; } } class ImapTokenStream { private static *lineParser(lines: any[]) { for (const iterator of lines) { if (typeof iterator === "object") { yield iterator.literal; continue; } yield *stringParser(iterator); } } g: Generator; current: string; done: boolean; constructor(lines: any[]) { this.g = ImapTokenStream.lineParser(lines); this.consume(); } consumeIf(token) { const current = this.trimStart(); if (current === token) { this.consume(); return true; } return false; } readNumber() { const current = this.trimStart(); if (/[0-9]+/.test(current)) { this.consume(); return parseInt(current, 10); } throw new Error(`Expected number but found ${current}`); } /** * Reads the key in key value pair, key does contain square brackets * to represent an array of fields */ readKey() { // first read whatever we have unless we encounter `[` let key = this.trimStart(); this.consume(); if (this.current !== "[") { return key; } key += "["; for(;;) { const next = this.consume(); if (next === "]") { this.consume(); break; } key += next; } return key + "]"; } /** * This will read pair value.. */ readPair() { const key = this.readKey(); const start = this.trimStart(); if (start === "{") { this.consume(); this.consume(); this.expect("}"); const value = this.current; this.consume(); return { key, value }; } if (start === "\\") { const value = `\\${this.consume()}`; this.consume(); return { key, value }; } if (start === "(") { const value = []; for(;;) { const next = this.consume(); if (next === ")") { this.consume(); break; } if (/^\s$/.test(next)) { continue; } if (next === "\\") { value.push("\\" + this.consume()); continue; } value.push(next); } return { key, value }; } const r = { key , value: this.current }; this.consume(); return r; } expect(...tokens: string[]) { for (const token of tokens) { const current = this.trimStart(); if (token !== current) { throw new Error(`Expected ${token} and found ${current}`); } this.consume(); } } trimStart(throwIfEnded = true) { for(;;) { if (/^\s$/.test(this.current)) { this.consume(); continue; } if (this.done) { if (throwIfEnded) { throw new Error("Unexpected end of string"); } } return this.current; } } consume() { const { value, done } = this.g.next(); this.current = value; this.done = done; return value; } }