using System; using RtfPipe; using System.IO; using System.Linq; using System.Text; using System.Threading; using xAiModels.Models; using xCommons.Extensions; using System.Threading.Tasks; using xAiApi.Interfaces.Extractors; using System.Text.RegularExpressions; namespace xAiApi.Providers.Extractors { /// /// Extractor for Rich Text Format (RTF) documents /// (application/rtf, text/rtf) /// public class XRtfFileContentExtractor : IXRtfFileContentExtractor { /// /// Supported MIME Types ... /// private static readonly string[] SupportedMimeTypes = [ "text/rtf", "application/rtf", ]; /// /// Check if this extractor supports the specified MIME type ... /// /// /// public bool CanExtract(string mimeType) { // return SupportedMimeTypes.Contains( mimeType?.ToLowerInvariant() ?? string.Empty ); } /// /// Extract text content from file stream ... /// /// /// /// /// public async Task ExtractAsync( Stream fileStream, string mimeType, CancellationToken cancellationToken = default ) { // var result = await ExtractRichAsync( fileStream, "document.rtf", mimeType, cancellationToken ); // return result.Text; } /// /// Extract content from stream as Rich Result ... /// /// /// /// /// /// public async Task ExtractRichAsync( Stream fileStream, string fileName, string mimeType, CancellationToken cancellationToken = default ) { // var result = new XFileExtractionResult { FileName = fileName, MimeType = mimeType }; // try { // result.Text = await ExtractRtfAsync( fileStream, cancellationToken ); } catch (Exception ex) { // result.ErrorMessage = $"RTF extraction failed: {ex.Message}"; } // return result; } /// /// Extract RTF Content ... /// /// /// /// private async Task ExtractRtfAsync( Stream fileStream, CancellationToken cancellationToken ) { // var result = string.Empty; // // Read RTF content as string ... using var reader = new StreamReader( fileStream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, leaveOpen: true ); var rtfContent = await reader.ReadToEndAsync(); if (rtfContent.IsNullOrEmpty()) { result = string.Empty; } // // Convert RTF to HTML using RtfPipe ... var html = Rtf.ToHtml(rtfContent); // // Convert HTML to plain text ... result = HtmlToPlainText(html); // return result; } /// /// Converts Html to Text ... /// /// /// private string HtmlToPlainText(string html) { // var result = string.Empty; // if (html.IsNullOrEmpty()) { result = string.Empty; } // // Remove HTML tags ... result = Regex.Replace( html, "<.*?>", string.Empty, RegexOptions.Singleline ); // // Decode HTML entities ... result = System.Net.WebUtility.HtmlDecode(result); // // Normalize whitespace ... result = Regex.Replace(result, @"\s+", " ").Trim(); // return result; } } }