import EmailCommands from "./EmailCommands.js"; const cmd = new RegExp("^(?\\p{Emoji}|" + EmailCommands.commands.join("|") + ")-k(?[^-]{1,50})-(?.+)", "u"); export const ReactionExtractor = { extract(email: { subject: string, textBody: string, headers: string | {[key: string]: any} }, attachmentsLoader: () => Promise, forceFullMatch = true) { return this.extractWithInReplyTo(email, attachmentsLoader, forceFullMatch).then(({ engagement } = { engagement: void 0 }) => engagement); }, async extractWithInReplyTo(email: { subject: string, textBody: string, firstHeader: (name) => string, }, attachmentsLoader: () => Promise, forceFullMatch = true) { try { let inReplyTo = null as string; let emailID = null as string; let engagement: string; const tokens = cmd.exec(email.subject); if (tokens?.length && tokens.groups) { const g = tokens.groups; engagement = g.engagement; emailID = g.emailID; inReplyTo = g.inReplyTo; return { engagement, inReplyTo, emailID }; } let index = email.subject?.indexOf(":"); if (index > 0 && index <= 50) { engagement = email.subject.substring(0, index); inReplyTo = email.subject.substring(index + 1); index = inReplyTo.indexOf(":"); if (index !== -1) { emailID = inReplyTo.substring(0, index); inReplyTo = inReplyTo.substring(index+1); } if (/^\p{Emoji}:/u.test(engagement)) { return { engagement, inReplyTo, emailID }; } } let { textBody } = email; textBody = textBody?.trim(); if (!textBody) { return {}; } const matches = /^\p{Emoji}:/u.exec(textBody); if(!matches) { return {}; } engagement = matches[0]; if (engagement === textBody) { return { engagement, inReplyTo, emailID }; } /** * If it starts with an emoji. There shouldn't be any other content except emoji for it * to be considered only as an emoji. * Any of following must be true. * * 1. It has a header x-engagement with the same emoji - This is social mail standard. * 2. It has a JSON attachment with emoji. (Google/Outlook). * 3. It has only Emoji txt. No reply body. */ // or else check reaction/json attachments sent from GMail // const jsonHeaders = typeof email.headers === "string" // ? JSON.parse(email.headers || "{}") // : typeof email.headers === "object" // ? email.headers // : {}; const jsonEngagement = email.firstHeader("x-engagement") ?? email.firstHeader("x-reaction"); if (jsonEngagement) { return { engagement: jsonEngagement }; } const attachments = await attachmentsLoader(); if (attachments) { for (const iterator of attachments) { if (/reaction/i.test(iterator.type) && /json/i.test(iterator.type)) { return { engagement }; } } } if (forceFullMatch) { return { engagement: null }; } return { engagement }; } catch (error) { // eslint-disable-next-line no-console console.error(error); } return {}; } };