From 28a6478ea0ac0f9ce893cb503bcefead3685d119 Mon Sep 17 00:00:00 2001 From: alma Date: Fri, 25 Apr 2025 21:39:08 +0200 Subject: [PATCH] panel 2 courier api restore --- components/ComposeEmail.tsx | 231 ++++++++---------------------------- 1 file changed, 50 insertions(+), 181 deletions(-) diff --git a/components/ComposeEmail.tsx b/components/ComposeEmail.tsx index 18764a55..188b52d1 100644 --- a/components/ComposeEmail.tsx +++ b/components/ComposeEmail.tsx @@ -113,179 +113,20 @@ export default function ComposeEmail({ // Check if we have content if (!emailToProcess?.content) { console.error('[DEBUG] No email content found to process'); - - // Try to use body property if content is not available (for backward compatibility) - if (emailToProcess && 'body' in emailToProcess && emailToProcess.body) { - console.log('[DEBUG] Using body property as fallback for content'); - emailToProcess.content = emailToProcess.body; - } else if (emailToProcess) { - console.log('[DEBUG] Attempting to fetch email content directly'); - try { - // Fetch the email content if not available - const response = await fetch(`/api/courrier/${emailToProcess.id}?folder=${encodeURIComponent(emailToProcess.folder || 'INBOX')}&fetchFull=true`); - - if (!response.ok) { - throw new Error(`Failed to fetch email content: ${response.status}`); - } - - const fullContent = await response.json(); - console.log('[DEBUG] API response for full email content:', { - hasContent: !!fullContent?.content, - hasBody: !!fullContent?.body, - hasHtml: !!fullContent?.html, - hasText: !!fullContent?.text, - contentLength: fullContent?.content?.length || 0 - }); - - // Update the email content with the fetched full content - if (fullContent && fullContent.content) { - console.log('[DEBUG] Successfully fetched content for reply/forward'); - emailToProcess.content = fullContent.content; - } else if (fullContent && fullContent.body) { - console.log('[DEBUG] Successfully fetched body for reply/forward'); - emailToProcess.content = fullContent.body; - } else if (fullContent && fullContent.html) { - console.log('[DEBUG] Successfully fetched HTML for reply/forward'); - emailToProcess.content = fullContent.html; - } else if (fullContent && fullContent.text) { - console.log('[DEBUG] Successfully fetched TEXT for reply/forward'); - emailToProcess.content = fullContent.text; - } else { - console.error('[DEBUG] No usable content found in API response'); - - // Try using fullContent directly if it's a string - if (typeof fullContent === 'string' && fullContent.length > 0) { - console.log('[DEBUG] Using fullContent string directly'); - emailToProcess.content = fullContent; - } else { - throw new Error('No content in fetched email'); - } - } - - // Ensure we actually have content - if (!emailToProcess.content || emailToProcess.content.trim().length === 0) { - console.error('[DEBUG] Content still empty after fetch, using fallback'); - // Use any available preview or raw data - emailToProcess.content = emailToProcess.preview || - (fullContent.raw ? fullContent.raw : 'Email content unavailable'); - } - } catch (fetchError) { - console.error('[DEBUG] Error fetching email content:', fetchError); - composeBodyRef.current.innerHTML = ` -
-
-
Error: No original message content available.
-
- Please select the email again or try refreshing the page. -
-
- `; - setIsLoading(false); - return; - } - } else { - // No emailToProcess available - composeBodyRef.current.innerHTML = ` -
-
-
Error: No email selected for reply/forward.
-
- `; - setIsLoading(false); - return; - } + composeBodyRef.current.innerHTML = ` +
+
+
Unable to load original message content.
+
+ `; + setIsLoading(false); + return; } - // Add more debug logging to track content fetching - console.log('[DEBUG] Sending content to parse-email API, content type:', - typeof emailToProcess!.content, - 'length:', emailToProcess!.content.length, - 'starts with:', emailToProcess!.content.substring(0, 50) - ); - - let emailContent; - let parseSuccess = false; - - try { - // Parse the original email using the API - const response = await fetch('/api/parse-email', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ email: emailToProcess.content }), - }); - - console.log('[DEBUG] Parse-email API response status:', response.status); - - const data = await response.json(); - console.log('[DEBUG] Parse-email API response:', { - hasHtml: !!data.html, - hasText: !!data.text, - subject: data.subject, - error: data.error - }); - - if (!response.ok) { - throw new Error(data.error || 'Failed to parse email'); - } - - // Prioritize HTML content if available, fallback to text - emailContent = data.html || data.text || ''; - - // Add a fallback check if both HTML and text are empty - if (!emailContent.trim()) { - // Try to extract content from the raw source - console.log('[DEBUG] Empty content from parser, using raw content as fallback'); - emailContent = emailToProcess.content; - - // If content looks like HTML, use it directly, otherwise wrap in pre tags - if (!emailContent.startsWith('<') || !emailContent.endsWith('>')) { - emailContent = `
${emailContent}
`; - } - } - - parseSuccess = true; - } catch (error) { - console.error('[DEBUG] API parse error:', error); - // Try to use the content directly if API fails - emailContent = emailToProcess.content; - - // If content looks like HTML, use it directly, otherwise wrap in pre tags - if (!emailContent.startsWith('<') || !emailContent.endsWith('>')) { - emailContent = `
${emailContent}
`; - } - } - - if (!emailContent || !emailContent.trim()) { - console.warn('[DEBUG] No content available after parsing, trying direct content'); - // Final fallback: Try to use direct content or preview - emailContent = emailToProcess.content || emailToProcess.preview || - (emailToProcess.body ? - `
${emailToProcess.body}
` : - '
No content available in the original message
'); - } - // Format the reply/forward content - const formatQuotedContent = (content: string) => { - // First try to clean up any problematic formatting - let cleanedContent = content; - - // If content is very short or empty, add a clear message - if (!cleanedContent || cleanedContent.trim().length < 10) { - return `
Original message was empty or could not be loaded
`; - } - - // If we're working with plain text, make it readable - if (!cleanedContent.includes('<') || !cleanedContent.includes('>')) { - return `
${cleanedContent}
`; - } - - // For HTML content, ensure it's properly contained - return cleanedContent; - }; - - // Process email content + const type = replyTo ? 'reply' : 'forward'; + + // Use simple, reliable formatting for the quoted content const formatEmailAddresses = (addresses: any) => { if (!addresses) return 'Unknown'; if (typeof addresses === 'string') return addresses; @@ -294,25 +135,53 @@ export default function ComposeEmail({ } return String(addresses); }; - - const quotedContent = forwardFrom ? ` + + // Extract plain text content for reliable display + let emailContent = ''; + try { + // Parse the original email to get clean content + const response = await fetch('/api/parse-email', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ email: emailToProcess.content }), + }); + + if (response.ok) { + const data = await response.json(); + emailContent = data.text || ''; + // If no text content, try to extract from HTML + if (!emailContent && data.html) { + // Create a temporary div to extract text from HTML + const tempDiv = document.createElement('div'); + tempDiv.innerHTML = data.html; + emailContent = tempDiv.textContent || tempDiv.innerText || ''; + } + } + } catch (error) { + console.error('[DEBUG] Error parsing email:', error); + // Fallback to simple content extraction + emailContent = emailToProcess.content.replace(/<[^>]*>/g, ''); + } + + // Format the content based on reply type + const quotedContent = type === 'forward' ? `
---------- Forwarded message ---------
- From: ${formatEmailAddresses(emailToProcess?.from) || 'Unknown Sender'}
- Date: ${new Date(emailToProcess?.date || Date.now()).toLocaleString()}
- Subject: ${emailToProcess?.subject || 'No Subject'}
- To: ${formatEmailAddresses(emailToProcess?.to) || ''}
- ${emailToProcess?.cc ? `Cc: ${formatEmailAddresses(emailToProcess.cc)}
` : ''} + From: ${formatEmailAddresses(emailToProcess.from) || 'Unknown Sender'}
+ Date: ${new Date(emailToProcess.date || Date.now()).toLocaleString()}
+ Subject: ${emailToProcess.subject || 'No Subject'}
+ To: ${formatEmailAddresses(emailToProcess.to) || ''}
+ ${emailToProcess.cc ? `Cc: ${formatEmailAddresses(emailToProcess.cc)}
` : ''}
- ${formatQuotedContent(emailContent)} +
${emailContent}
` : `
- On ${new Date(emailToProcess?.date || Date.now()).toLocaleString()}, ${formatEmailAddresses(emailToProcess?.from) || 'Unknown Sender'} wrote: + On ${new Date(emailToProcess.date || Date.now()).toLocaleString()}, ${formatEmailAddresses(emailToProcess.from) || 'Unknown Sender'} wrote:
- ${formatQuotedContent(emailContent)} +
${emailContent}
`; @@ -364,7 +233,7 @@ export default function ComposeEmail({ e.stopPropagation(); e.preventDefault(); // Prevent the parent container from scrolling } - }, { passive: false }); + }, { passive: false }); // Important for preventDefault to work // Mark this element as having a scroll handler attached (container as HTMLElement).setAttribute('data-scroll-handler-attached', 'true');