68 lines
1.8 KiB
C#
68 lines
1.8 KiB
C#
using System.IO;
|
|
using System.Linq;
|
|
using System.Threading;
|
|
using xAiApi.Interfaces;
|
|
using xCommons.Extensions;
|
|
using xExceptions.Constants;
|
|
using System.Threading.Tasks;
|
|
using System.Collections.Generic;
|
|
|
|
namespace xAiApi.Providers
|
|
{
|
|
/// <summary>
|
|
/// Composite extractor that delegates to appropriate extractor
|
|
/// based on MIME type ...
|
|
/// </summary>
|
|
public class XCompositeFileContentExtractor : IXFileContentExtractor
|
|
{
|
|
//
|
|
private readonly IEnumerable<IXFileContentExtractor> extractors;
|
|
|
|
public XCompositeFileContentExtractor(
|
|
IEnumerable<IXFileContentExtractor> extractors
|
|
)
|
|
{
|
|
this.extractors = extractors;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Check if this extractor supports the specified MIME type ...
|
|
/// </summary>
|
|
public bool CanExtract(string mimeType)
|
|
{
|
|
return extractors.Any(e => e.CanExtract(mimeType));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Extract text content from file stream ...
|
|
/// </summary>
|
|
public async Task<string> ExtractAsync(
|
|
Stream fileStream,
|
|
string mimeType,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
var extractor = 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;
|
|
}
|
|
}
|
|
} |