using DocumentOperator.Application.CheckPdfAttachments.Queries; using DocumentOperator.Application.Common.DTOs; using DocumentOperator.Application.ExtractPdfAttachments; using DocumentOperator.Domain.Common.Exceptions; using MediatR; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace DocumentOperator.API.Controllers; /// /// Controller for PDF attachment operations (detection, extraction, embedding) /// [ApiController] [Route("api/pdf/attachments")] [Produces("application/json")] public class PdfAttachmentController(IMediator mediator) : ControllerBase { /// /// Checks if a PDF contains embedded files (attachments) and returns their metadata. /// Supports multipart/form-data file upload. /// /// The PDF file to check for attachments /// Cancellation token /// Attachment check result with metadata for all found attachments /// PDF successfully checked - returns attachment details /// Invalid input (file missing, not a PDF, or corrupted) /// Internal server error during PDF processing [HttpPost("check")] [Consumes("multipart/form-data")] [ProducesResponseType(typeof(AttachmentCheckResult), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] public async Task CheckAttachmentsFromFile( IFormFile file, CancellationToken cancellationToken) { // Use IFormFile stream directly (no intermediate byte[] conversion) using var pdfStream = file.OpenReadStream(); // Send query to MediatR (ValidationBehavior runs automatically) var query = new CheckPdfAttachmentsQuery { PdfStream = pdfStream }; var result = await mediator.Send(query, cancellationToken); return Ok(result); } /// /// Checks if a PDF contains embedded files (attachments) and returns their metadata. /// Supports Base64-encoded PDF via JSON payload. /// /// Request containing Base64-encoded PDF /// Cancellation token /// Attachment check result with metadata for all found attachments /// PDF successfully checked - returns attachment details /// Invalid input (Base64 format error, not a PDF, or corrupted) /// Internal server error during PDF processing [HttpPost("check")] [Consumes("application/json")] [ProducesResponseType(typeof(AttachmentCheckResult), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] public async Task CheckAttachmentsFromBase64( [FromBody] CheckPdfAttachmentsRequest request, CancellationToken cancellationToken) { // Convert Base64 to stream (wrap in try-catch to throw BadRequestException) byte[] pdfBytes; try { pdfBytes = Convert.FromBase64String(request.Base64Pdf); } catch (FormatException ex) { throw new BadRequestException("Invalid Base64 format: " + ex.Message); } using var pdfStream = new MemoryStream(pdfBytes); // Send query to MediatR (ValidationBehavior runs automatically) var query = new CheckPdfAttachmentsQuery { PdfStream = pdfStream }; var result = await mediator.Send(query, cancellationToken); return Ok(result); } /// /// Extracts all embedded files from a PDF and returns them as a ZIP archive. /// Supports multipart/form-data file upload. /// /// The PDF file to extract attachments from /// Cancellation token /// ZIP archive containing all extracted attachments /// Attachments extracted successfully - returns ZIP file /// Invalid input (file missing, not a PDF, or corrupted) /// PDF contains no attachments /// Internal server error during PDF processing [HttpPost("extract")] [Consumes("multipart/form-data")] [ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] public async Task ExtractAttachmentsFromFile( IFormFile file, CancellationToken cancellationToken) { // Use IFormFile stream directly (no intermediate byte[] conversion) using var pdfStream = file.OpenReadStream(); // Send command to MediatR var command = new ExtractPdfAttachmentsCommand { PdfStream = pdfStream }; byte[] zipBytes = await mediator.Send(command, cancellationToken); // Return ZIP file return File(zipBytes, "application/zip", "attachments.zip"); } /// /// Extracts all embedded files from a PDF and returns them as a ZIP archive. /// Supports Base64-encoded PDF via JSON payload. /// /// Request containing Base64-encoded PDF /// Cancellation token /// ZIP archive containing all extracted attachments /// Attachments extracted successfully - returns ZIP file /// Invalid input (Base64 format error, not a PDF, or corrupted) /// PDF contains no attachments /// Internal server error during PDF processing [HttpPost("extract")] [Consumes("application/json")] [ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] public async Task ExtractAttachmentsFromBase64( [FromBody] ExtractPdfAttachmentsRequest request, CancellationToken cancellationToken) { // Convert Base64 to stream (wrap in try-catch to throw BadRequestException) byte[] pdfBytes; try { pdfBytes = Convert.FromBase64String(request.Base64Pdf); } catch (FormatException ex) { throw new BadRequestException("Invalid Base64 format: " + ex.Message); } using var pdfStream = new MemoryStream(pdfBytes); // Send command to MediatR var command = new ExtractPdfAttachmentsCommand { PdfStream = pdfStream }; byte[] zipBytes = await mediator.Send(command, cancellationToken); // Return ZIP file return File(zipBytes, "application/zip", "attachments.zip"); } } /// /// Request DTO for Base64-encoded PDF attachment check /// public record CheckPdfAttachmentsRequest { /// /// PDF document encoded as Base64 string /// /// JVBERi0xLjQKJeLjz9MKMSAwIG9iago8PC9UeXBlL0NhdGFsb2c... public string Base64Pdf { get; init; } = string.Empty; } /// /// Request DTO for Base64-encoded PDF attachment extraction /// public record ExtractPdfAttachmentsRequest { /// /// PDF document encoded as Base64 string /// /// JVBERi0xLjQKJeLjz9MKMSAwIG9iago8PC9UeXBlL0NhdGFsb2c... public required string Base64Pdf { get; init; } }