using System.IO;
using System.Linq;
using System.Threading;
using xAiModels.Models;
using xCommons.Extensions;
using xExceptions.Constants;
using System.Threading.Tasks;
using System.Collections.Generic;
using xAiApi.Interfaces.Extractors;
namespace xAiApi.Providers.Extractors
{
///
/// Composite extractor that delegates to appropriate extractor
/// based on MIME type ...
///
public class XFileContentExtractor : IXFileContentExtractor
{
//
private readonly IList _extractors = [];
public XFileContentExtractor(
IEnumerable availableExtractors
)
{
//
_extractors = [.. availableExtractors
.Where(e => e.GetType() != typeof(XFileContentExtractor))];
}
///
/// Check if this extractor supports the specified MIME type ...
///
///
///
///
public bool CanExtract(
string mimeType,
string[] extractors = null
)
{
//
return GetExtractors(extractors)
.Any(e => e.CanExtract(mimeType));
}
///
/// Extract text content from file stream ...
///
///
///
///
///
///
public async Task ExtractAsync(
Stream fileStream,
string mimeType,
string[] extractors = null,
CancellationToken cancellationToken = default
)
{
//
var extractor = GetExtractors(extractors)
.FirstOrDefault(e => e.CanExtract(mimeType));
if (extractor.IsNull())
{
//
XException.NotAllowed.Throw(
$"Unsupported file type: {mimeType}"
);
}
//
var result = await extractor
.ExtractAsync(
mimeType: mimeType,
fileStream: fileStream,
cancellationToken: cancellationToken
);
//
return result;
}
///
/// Extract content from stream as Rich Result ...
///
///
///
///
///
///
///
public async Task ExtractRichAsync(
Stream fileStream,
string fileName,
string mimeType,
string[] extractors = null,
CancellationToken cancellationToken = default
)
{
//
var extractor = GetExtractors(extractors)
.FirstOrDefault(e => e.CanExtract(mimeType));
if (extractor.IsNull())
{
//
XException.NotAllowed.Throw(
$"Unsupported file type: {mimeType}"
);
}
//
var result = await extractor
.ExtractRichAsync(
mimeType: mimeType,
fileName: fileName,
fileStream: fileStream,
cancellationToken: cancellationToken
);
//
return result;
}
///
/// Extract Provided Extractors ...
///
///
///
private IList GetExtractors(string[] extractors = null)
{
//
var result = new List();
//
if (extractors.IsNull() || !extractors.HasChild())
{
//
result = [.. _extractors];
}
else
{
//
result = [.. _extractors
.Where(e => extractors
.Any(ex => e.GetType().FullName.Contains(ex)))];
}
//
return result;
}
}
}