using System.Buffers.Binary; using System.IO.Compression; using Helpdesk.Application.Common; using Helpdesk.Application.Issues; using Microsoft.Extensions.Logging; namespace Helpdesk.Infrastructure.Files; internal sealed class FileAttachmentStore(ILogger logger) : IAttachmentStore { internal static readonly string UploadDirectory = Path.Combine(AppContext.BaseDirectory, "uploads"); public async Task SaveAsync(AttachmentUpload upload, CancellationToken ct) { if (upload.SizeBytes is <= 0 or > AttachmentLimits.MaxFileBytes) throw new FieldValidationException("files", "Příloha musí mít velikost od 1 B do 10 MB."); var name = Path.GetFileName(upload.FileName.Replace('\\', '/')).Trim(); if (name.Length is 0 or > 255 || name.Any(char.IsControl)) throw new FieldValidationException("files", "Neplatný název přílohy."); var extension = Path.GetExtension(name).ToLowerInvariant(); var contentType = extension switch { ".jpg" or ".jpeg" => "image/jpeg", ".png" => "image/png", ".heic" => "image/heic", ".pdf" => "application/pdf", ".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document", _ => throw new FieldValidationException("files", "Tento typ přílohy není povolen."), }; Directory.CreateDirectory(UploadDirectory); var key = Guid.NewGuid().ToString("D"); var path = FilePath(key); var created = false; try { await using var input = upload.OpenRead(); await using var output = new FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, bufferSize: 64 * 1024, useAsync: true); created = true; var buffer = new byte[64 * 1024]; long written = 0; int read; while ((read = await input.ReadAsync(buffer, ct)) > 0) { written += read; if (written > upload.SizeBytes) throw new FieldValidationException("files", "Velikost přílohy neodpovídá požadavku."); await output.WriteAsync(buffer.AsMemory(0, read), ct); } if (written != upload.SizeBytes) throw new FieldValidationException("files", "Velikost přílohy neodpovídá požadavku."); output.Position = 0; if (!await HasExpectedFormatAsync(output, extension, ct)) throw new FieldValidationException("files", "Obsah přílohy neodpovídá její příponě."); return new StoredAttachment(name, key, contentType, written); } catch { if (created) Delete(key); throw; } } public Stream OpenRead(string storedFileName) { try { return new FileStream(FilePath(storedFileName), FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 64 * 1024, useAsync: true); } catch (IOException exception) when (exception is FileNotFoundException or DirectoryNotFoundException) { logger.LogError(exception, "Soubor přílohy {AttachmentKey} v úložišti chybí.", storedFileName); throw new NotFoundException("Soubor přílohy není dostupný."); } } public void Delete(string storedFileName) { try { File.Delete(FilePath(storedFileName)); } catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) { logger.LogError(exception, "Soubor přílohy {AttachmentKey} se nepodařilo uklidit.", storedFileName); } } private string FilePath(string key) => Guid.TryParseExact(key, "D", out _) ? Path.Combine(UploadDirectory, key) : throw new InvalidOperationException("Neplatný klíč souboru přílohy."); private static async Task HasExpectedFormatAsync(Stream stream, string extension, CancellationToken ct) { var header = new byte[(int)Math.Min(stream.Length, 512)]; await stream.ReadExactlyAsync(header, ct); return extension switch { ".jpg" or ".jpeg" => header.AsSpan().StartsWith(new byte[] { 0xff, 0xd8, 0xff }), ".png" => header.AsSpan().StartsWith(new byte[] { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a }), ".pdf" => header.AsSpan().StartsWith("%PDF-"u8), ".heic" => IsHeic(header, stream.Length), ".docx" => IsDocx(stream, header), _ => false, }; } private static bool IsHeic(ReadOnlySpan header, long length) { if (header.Length < 16 || !header.Slice(4, 4).SequenceEqual("ftyp"u8)) return false; var boxLength = BinaryPrimitives.ReadUInt32BigEndian(header); if (boxLength < 16 || boxLength > length) return false; for (var offset = 8; offset + 4 <= Math.Min(boxLength, header.Length); offset += 4) { if (offset == 12) continue; // minor_version var brand = header.Slice(offset, 4); if (brand.SequenceEqual("heic"u8) || brand.SequenceEqual("heix"u8) || brand.SequenceEqual("hevc"u8) || brand.SequenceEqual("hevx"u8)) return true; } return false; } private static bool IsDocx(Stream stream, ReadOnlySpan header) { if (!header.StartsWith(new byte[] { 0x50, 0x4b, 0x03, 0x04 })) return false; stream.Position = 0; try { using var zip = new ZipArchive(stream, ZipArchiveMode.Read, leaveOpen: true); return zip.GetEntry("[Content_Types].xml") is not null && zip.GetEntry("word/document.xml") is not null; } catch (InvalidDataException) { return false; } } }