/
afanasevn
/
PdfEncoder
Обзор
Документация
Войти
/
afanasevn
/
PdfEncoder
Код
Запросы
0
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
src/PdfEncoder.Infrastructure/Pdf/PdfInputValidator.cs
92 строки
3 KB
IBS\NAfanasev
DocumentContext local functional
01 июл 2026, 15:30
01 июл 2026, 15:30
b4038c9
Код
Авторство
О чём код?
using Microsoft.Extensions.Options; using PdfEncoder.Application.Abstractions; using PdfEncoder.Application.Options; using PdfEncoder.Domain.Errors; using UglyToad.PdfPig; namespace PdfEncoder.Infrastructure.Pdf; /// <summary> /// Валидация входного PDF перед pipeline. /// </summary> public sealed class PdfInputValidator(IOptions<UploadOptions> uploadOptions) : IPdfInputValidator { private static ReadOnlySpan<byte> PdfMagic => "%PDF"u8; /// <inheritdoc /> public Task<int> ValidateAsync( ReadOnlyMemory<byte> content, string fileName, CancellationToken ct) { ct.ThrowIfCancellationRequested(); if (content.IsEmpty) { throw new PdfValidationException( "invalid-file", "File is empty.", statusCode: 400); } var span = content.Span; if (span.Length < PdfMagic.Length || !span[..PdfMagic.Length].SequenceEqual(PdfMagic)) { throw new PdfValidationException( "invalid-file", "File is not a valid PDF or is empty.", statusCode: 400); } var options = uploadOptions.Value; if (span.Length > options.MaxFileSizeBytes) { throw new PdfValidationException( "file-too-large", $"File exceeds maximum size of {options.MaxFileSizeBytes} bytes.", statusCode: 413); } try { using var document = PdfDocument.Open(content); if (document.IsEncrypted) { throw new PdfValidationException( "encrypted-pdf-not-supported", "Encrypted PDF is not supported.", statusCode: 400); } var pageCount = document.NumberOfPages; if (pageCount <= 0) { throw new PdfValidationException( "invalid-file", "PDF contains no pages.", statusCode: 400); } if (pageCount > options.MaxPages) { throw new PdfValidationException( "too-many-pages", $"PDF exceeds maximum page count of {options.MaxPages}.", statusCode: 400); } return Task.FromResult(pageCount); } catch (PdfValidationException) { throw; } catch (Exception ex) { throw new PdfValidationException( "invalid-file", $"Failed to read PDF '{fileName}': {ex.Message}", statusCode: 400); } } }