179 lines
5.7 KiB
TypeScript
179 lines
5.7 KiB
TypeScript
import { useState, useEffect, useCallback, useRef } from 'react';
|
|
import { useToast } from './use-toast';
|
|
import { EmailMessage, EmailContent } from '@/types/email';
|
|
import { processContentWithDirection } from '@/lib/utils/text-direction';
|
|
|
|
interface EmailFetchState {
|
|
email: EmailMessage | null;
|
|
loading: boolean;
|
|
error: string | null;
|
|
}
|
|
|
|
interface UseEmailFetchProps {
|
|
onEmailLoaded?: (email: EmailMessage) => void;
|
|
onError?: (error: string) => void;
|
|
}
|
|
|
|
export function useEmailFetch({ onEmailLoaded, onError }: UseEmailFetchProps = {}) {
|
|
const [state, setState] = useState<EmailFetchState>({
|
|
email: null,
|
|
loading: false,
|
|
error: null
|
|
});
|
|
|
|
const abortControllerRef = useRef<AbortController | null>(null);
|
|
const { toast } = useToast();
|
|
|
|
// Validate email fetch parameters
|
|
const validateFetchParams = (emailId: string, accountId: string, folder: string) => {
|
|
if (!emailId || typeof emailId !== 'string') {
|
|
throw new Error('Invalid email ID');
|
|
}
|
|
|
|
if (!accountId || typeof accountId !== 'string') {
|
|
throw new Error('Invalid account ID');
|
|
}
|
|
|
|
if (!folder || typeof folder !== 'string') {
|
|
throw new Error('Invalid folder');
|
|
}
|
|
|
|
// Validate UID format
|
|
if (!/^\d+$/.test(emailId)) {
|
|
throw new Error('Email ID must be a numeric UID');
|
|
}
|
|
};
|
|
|
|
// Fetch email with proper error handling and cancellation
|
|
const fetchEmail = useCallback(async (emailId: string, accountId: string, folder: string) => {
|
|
if (!emailId || !accountId || !folder) {
|
|
console.error('Missing required parameters for fetchEmail');
|
|
return;
|
|
}
|
|
|
|
// Abort any previous request
|
|
if (abortControllerRef.current) {
|
|
abortControllerRef.current.abort();
|
|
}
|
|
|
|
abortControllerRef.current = new AbortController();
|
|
setState(prev => ({ ...prev, loading: true, error: null }));
|
|
|
|
try {
|
|
const response = await fetch(
|
|
`/api/courrier/${emailId}?accountId=${encodeURIComponent(accountId)}&folder=${encodeURIComponent(folder)}`,
|
|
{
|
|
signal: abortControllerRef.current?.signal
|
|
}
|
|
);
|
|
|
|
if (!response.ok) {
|
|
throw new Error(`Failed to fetch email: ${response.statusText}`);
|
|
}
|
|
|
|
const data = await response.json();
|
|
|
|
// Create a valid email message object with required fields
|
|
const processContent = (data: any): EmailContent => {
|
|
// Extract initial content from all possible sources
|
|
let initialContent: any = {};
|
|
|
|
if (typeof data.content === 'object' && data.content) {
|
|
// Use content object directly if available
|
|
initialContent = data.content;
|
|
} else {
|
|
// Build content object from separate properties
|
|
if (typeof data.content === 'string') {
|
|
// Check if content appears to be HTML
|
|
if (data.content.includes('<') &&
|
|
(data.content.includes('<html') ||
|
|
data.content.includes('<body') ||
|
|
data.content.includes('<div'))) {
|
|
initialContent.html = data.content;
|
|
} else {
|
|
initialContent.text = data.content;
|
|
}
|
|
} else {
|
|
// Check for separate html and text properties
|
|
if (data.html) initialContent.html = data.html;
|
|
if (data.text) initialContent.text = data.text;
|
|
else if (data.plainText) initialContent.text = data.plainText;
|
|
}
|
|
}
|
|
|
|
// Use the centralized content processing function
|
|
const processedContent = processContentWithDirection(initialContent);
|
|
|
|
return {
|
|
text: processedContent.text,
|
|
html: processedContent.html,
|
|
isHtml: !!processedContent.html,
|
|
direction: processedContent.direction
|
|
};
|
|
};
|
|
|
|
const transformedEmail: EmailMessage = {
|
|
id: data.id || emailId,
|
|
subject: data.subject || '',
|
|
from: data.from || '',
|
|
to: data.to || '',
|
|
cc: data.cc,
|
|
bcc: data.bcc,
|
|
date: data.date || new Date().toISOString(),
|
|
flags: Array.isArray(data.flags) ? data.flags : [],
|
|
content: processContent(data),
|
|
attachments: data.attachments
|
|
};
|
|
|
|
console.log('Email processed:', transformedEmail.id,
|
|
'HTML:', !!transformedEmail.content.html,
|
|
'Text length:', transformedEmail.content.text.length);
|
|
|
|
setState({ email: transformedEmail, loading: false, error: null });
|
|
onEmailLoaded?.(transformedEmail);
|
|
|
|
// Mark as read if not already
|
|
if (!transformedEmail.flags?.includes('seen')) {
|
|
try {
|
|
await fetch(`/api/courrier/${emailId}/mark-read`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ action: 'mark-read' })
|
|
});
|
|
} catch (err: any) {
|
|
console.error('Error marking email as read:', err);
|
|
}
|
|
}
|
|
} catch (err: any) {
|
|
// Don't set error if request was aborted
|
|
if (err.name === 'AbortError') {
|
|
return;
|
|
}
|
|
|
|
console.error('Error fetching email:', err);
|
|
const errorMessage = err instanceof Error ? err.message : 'Failed to load email';
|
|
setState(prev => ({ ...prev, loading: false, error: errorMessage }));
|
|
onError?.(errorMessage);
|
|
|
|
toast({
|
|
title: 'Error',
|
|
description: errorMessage,
|
|
variant: 'destructive'
|
|
});
|
|
}
|
|
}, [onEmailLoaded, onError, toast]);
|
|
|
|
// Cleanup on unmount
|
|
useEffect(() => {
|
|
return () => {
|
|
if (abortControllerRef.current) {
|
|
abortControllerRef.current.abort();
|
|
}
|
|
};
|
|
}, []);
|
|
|
|
return {
|
|
...state,
|
|
fetchEmail
|
|
};
|
|
}
|