Neah/lib/utils/email-utils.ts
2025-05-01 10:31:52 +02:00

443 lines
13 KiB
TypeScript

/**
* Unified Email Utilities
*
* This file contains all email-related utility functions:
* - Content normalization
* - Email formatting (replies, forwards)
* - Text direction detection
*/
// Import from centralized DOMPurify configuration instead of configuring directly
import { sanitizeHtml, getDOMPurify } from './dom-purify-config';
import {
EmailMessage,
EmailContent,
EmailAddress,
LegacyEmailMessage
} from '@/types/email';
import { adaptLegacyEmail } from '@/lib/utils/email-adapters';
import { decodeInfomaniakEmail, adaptMimeEmail, isMimeFormat } from './email-mime-decoder';
import { detectTextDirection, applyTextDirection } from '@/lib/utils/text-direction';
// Export the sanitizeHtml function from the centralized config
export { sanitizeHtml };
/**
* Standard interface for formatted email responses
*/
export interface FormattedEmail {
to: string;
cc?: string;
subject: string;
content: EmailContent;
}
/**
* Utility type that combines EmailMessage and LegacyEmailMessage
* to allow access to properties that might exist in either type
*/
type AnyEmailMessage = {
id: string;
subject: string | undefined;
from: any;
to: any;
cc?: any;
date: any;
content?: any;
html?: string;
text?: string;
attachments?: any[];
flags?: any;
[key: string]: any;
};
/**
* Format email addresses for display
* Can handle both array of EmailAddress objects or a string
*/
export function formatEmailAddresses(addresses: EmailAddress[] | string | undefined): string {
if (!addresses) return '';
// If already a string, return as is
if (typeof addresses === 'string') {
return addresses;
}
// If array, format each address
if (Array.isArray(addresses) && addresses.length > 0) {
return addresses.map(addr =>
addr.name && addr.name !== addr.address
? `${addr.name} <${addr.address}>`
: addr.address
).join(', ');
}
return '';
}
/**
* Format date for display
*/
export function formatEmailDate(date: Date | string | undefined): string {
if (!date) return '';
try {
const dateObj = typeof date === 'string' ? new Date(date) : date;
return dateObj.toLocaleString('en-US', {
weekday: 'short',
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
} catch (e) {
return typeof date === 'string' ? date : date.toString();
}
}
/**
* Format plain text for HTML display with proper line breaks
*/
export function formatPlainTextToHtml(text: string | null | undefined): string {
if (!text) return '';
// Escape HTML characters to prevent XSS
const escapedText = text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;');
// Format plain text with proper line breaks and paragraphs
return escapedText
.replace(/\r\n|\r|\n/g, '<br>') // Convert all newlines to <br>
.replace(/((?:<br>){2,})/g, '</p><p>') // Convert multiple newlines to paragraphs
.replace(/<br><\/p>/g, '</p>') // Fix any <br></p> combinations
.replace(/<p><br>/g, '<p>'); // Fix any <p><br> combinations
}
/**
* Normalize email content to our standard format regardless of input format
*/
export function normalizeEmailContent(email: any): EmailMessage {
if (!email) {
throw new Error('Cannot normalize null or undefined email');
}
// First check if this is a MIME format email that needs decoding
if (email.content && isMimeFormat(email.content)) {
try {
console.log('Detected MIME format email, decoding...');
return adaptMimeEmail(email);
} catch (error) {
console.error('Error decoding MIME email:', error);
// Continue with regular normalization if MIME decoding fails
}
}
// Check if it's already in the standardized format
if (email.content && typeof email.content === 'object' &&
(email.content.html !== undefined || email.content.text !== undefined)) {
// Already in the correct format
return email as EmailMessage;
}
// Otherwise, adapt from legacy format and cast to EmailMessage
return adaptLegacyEmail(email as LegacyEmailMessage) as unknown as EmailMessage;
}
/**
* Render normalized email content into HTML for display
*/
export function renderEmailContent(content: EmailContent | null): string {
if (!content) {
return '<div class="email-content-empty">No content available</div>';
}
const safeContent = {
text: content.text || '',
html: content.html || '',
isHtml: !!content.isHtml,
direction: content.direction || 'ltr'
};
// If we have HTML content and isHtml flag is true, use it
if (safeContent.isHtml && safeContent.html) {
return sanitizeHtml(safeContent.html);
}
// Otherwise, convert text to HTML with proper line breaks
if (safeContent.text) {
return `<div dir="${safeContent.direction}">${formatPlainTextToHtml(safeContent.text)}</div>`;
}
return '<div class="email-content-empty">No content available</div>';
}
/**
* Format email for reply
*/
export function formatReplyEmail(originalEmail: EmailMessage | LegacyEmailMessage | null, type: 'reply' | 'reply-all' = 'reply'): FormattedEmail {
if (!originalEmail) {
return {
to: '',
cc: '',
subject: '',
content: {
text: '',
html: '',
isHtml: false,
direction: 'ltr' as const
}
};
}
// Cast to AnyEmailMessage for property access
const email = originalEmail as AnyEmailMessage;
// Format the recipients
const to = Array.isArray(email.from)
? email.from.map((addr: any) => {
if (typeof addr === 'string') return addr;
return addr.address ? addr.address : '';
}).filter(Boolean).join(', ')
: typeof email.from === 'string'
? email.from
: '';
// For reply-all, include other recipients in CC
let cc = '';
if (type === 'reply-all') {
const toRecipients = Array.isArray(email.to)
? email.to.map((addr: any) => {
if (typeof addr === 'string') return addr;
return addr.address ? addr.address : '';
}).filter(Boolean)
: typeof email.to === 'string'
? [email.to]
: [];
const ccRecipients = Array.isArray(email.cc)
? email.cc.map((addr: any) => {
if (typeof addr === 'string') return addr;
return addr.address ? addr.address : '';
}).filter(Boolean)
: typeof email.cc === 'string'
? [email.cc]
: [];
cc = [...toRecipients, ...ccRecipients].join(', ');
}
// Format the subject
const subject = email.subject && !email.subject.startsWith('Re:')
? `Re: ${email.subject}`
: email.subject || '';
// Format the content
const originalDate = email.date ? new Date(email.date) : new Date();
const dateStr = originalDate.toLocaleString();
const fromStr = Array.isArray(email.from)
? email.from.map((addr: any) => {
if (typeof addr === 'string') return addr;
return addr.name ? `${addr.name} <${addr.address}>` : addr.address;
}).join(', ')
: typeof email.from === 'string'
? email.from
: 'Unknown Sender';
const toStr = Array.isArray(email.to)
? email.to.map((addr: any) => {
if (typeof addr === 'string') return addr;
return addr.name ? `${addr.name} <${addr.address}>` : addr.address;
}).join(', ')
: typeof email.to === 'string'
? email.to
: '';
// Extract original content
const originalTextContent =
typeof email.content === 'object' && email.content?.text ? email.content.text :
typeof email.content === 'string' ? email.content :
email.text || '';
const originalHtmlContent =
typeof email.content === 'object' && email.content?.html ? email.content.html :
email.html ||
(typeof email.content === 'string' && email.content.includes('<')
? email.content
: '');
// Get the direction from the original email
const originalDirection =
typeof email.content === 'object' && email.content?.direction ? email.content.direction :
detectTextDirection(originalTextContent);
// Create content with appropriate quote formatting
const replyBody = `
<br/>
<br/>
<blockquote style="border-left: 2px solid #ddd; padding-left: 10px; margin: 10px 0; color: #505050;">
<p>On ${dateStr}, ${fromStr} wrote:</p>
${originalHtmlContent || originalTextContent.replace(/\n/g, '<br>')}
</blockquote>
`;
// Apply consistent text direction
const htmlContent = applyTextDirection(replyBody);
// Create plain text content
const textContent = `
On ${dateStr}, ${fromStr} wrote:
> ${originalTextContent.split('\n').join('\n> ')}
`;
return {
to,
cc,
subject,
content: {
text: textContent,
html: htmlContent,
isHtml: true,
direction: 'ltr' as const // Reply is LTR, but original content keeps its direction in the blockquote
}
};
}
/**
* Format email for forwarding
*/
export function formatForwardedEmail(originalEmail: EmailMessage | LegacyEmailMessage | null): FormattedEmail {
if (!originalEmail) {
return {
to: '',
subject: '',
content: {
text: '',
html: '',
isHtml: false,
direction: 'ltr' as const
}
};
}
// Cast to AnyEmailMessage for property access
const email = originalEmail as AnyEmailMessage;
// Format the subject
const subject = email.subject && !email.subject.startsWith('Fwd:')
? `Fwd: ${email.subject}`
: email.subject || '';
// Format from, to, cc for the header
const fromStr = Array.isArray(email.from)
? email.from.map((addr: any) => {
if (typeof addr === 'string') return addr;
return addr.name ? `${addr.name} <${addr.address}>` : addr.address;
}).join(', ')
: typeof email.from === 'string'
? email.from
: 'Unknown Sender';
const toStr = Array.isArray(email.to)
? email.to.map((addr: any) => {
if (typeof addr === 'string') return addr;
return addr.name ? `${addr.name} <${addr.address}>` : addr.address;
}).join(', ')
: typeof email.to === 'string'
? email.to
: '';
const ccStr = Array.isArray(email.cc)
? email.cc.map((addr: any) => {
if (typeof addr === 'string') return addr;
return addr.name ? `${addr.name} <${addr.address}>` : addr.address;
}).join(', ')
: typeof email.cc === 'string'
? email.cc
: '';
const dateStr = email.date ? new Date(email.date).toLocaleString() : 'Unknown Date';
// Extract original content
const originalTextContent =
typeof email.content === 'object' && email.content?.text ? email.content.text :
typeof email.content === 'string' ? email.content :
email.text || '';
const originalHtmlContent =
typeof email.content === 'object' && email.content?.html ? email.content.html :
email.html ||
(typeof email.content === 'string' && email.content.includes('<')
? email.content
: '');
// Get the direction from the original email
const originalDirection =
typeof email.content === 'object' && email.content?.direction ? email.content.direction :
detectTextDirection(originalTextContent);
// Create forwarded content with header information
const forwardBody = `
<br/>
<br/>
<div class="email-forwarded-content">
<p>---------- Forwarded message ---------</p>
<p><strong>From:</strong> ${fromStr}</p>
<p><strong>Date:</strong> ${dateStr}</p>
<p><strong>Subject:</strong> ${email.subject || ''}</p>
<p><strong>To:</strong> ${toStr}</p>
${ccStr ? `<p><strong>Cc:</strong> ${ccStr}</p>` : ''}
<div style="margin-top: 15px; border-top: 1px solid #eee; padding-top: 15px;">
${originalHtmlContent || originalTextContent.replace(/\n/g, '<br>')}
</div>
</div>
`;
// Apply consistent text direction
const htmlContent = applyTextDirection(forwardBody);
// Create plain text content
const textContent = `
---------- Forwarded message ---------
From: ${fromStr}
Date: ${dateStr}
Subject: ${email.subject || ''}
To: ${toStr}
${ccStr ? `Cc: ${ccStr}\n` : ''}
${originalTextContent}
`;
return {
to: '',
subject,
content: {
text: textContent,
html: htmlContent,
isHtml: true,
direction: 'ltr' as const // Forward is LTR, but original content keeps its direction
}
};
}
/**
* Format an email for reply or reply-all - canonical implementation
*/
export function formatEmailForReplyOrForward(
email: EmailMessage | LegacyEmailMessage | null,
type: 'reply' | 'reply-all' | 'forward'
): FormattedEmail {
// Use our dedicated formatters
if (type === 'forward') {
return formatForwardedEmail(email);
} else {
return formatReplyEmail(email, type as 'reply' | 'reply-all');
}
}