diff --git a/docs/DATA-MODEL.md b/docs/DATA-MODEL.md index c093b79..6c8f388 100644 --- a/docs/DATA-MODEL.md +++ b/docs/DATA-MODEL.md @@ -701,6 +701,36 @@ Migrazioni applicate in ordine: - `core` 20261111004 `create_audit_log` (M20261111_004_CreateAuditLog) - `core` 20261111005 `create_notifications` (M20261111_005_CreateNotifications) - `core` 20261111006 `create_user_settings` (M20261111_006_CreateUserSettings) +- `core` 20261111007 `create_attachments` (M20261111_007_CreateAttachments) + +#### `attachments` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `entity` | String(100) | no | | | +| `entity_id` | Int64 | no | | | +| `kind` | String(40) | no | | | +| `name` | String(255) | no | | | +| `mime` | String(150) | no | | | +| `size` | Int64 | no | | | +| `sha256` | String(64) | no | | | +| `version` | Int32 | no | | | +| `version_key` | String(300) | no | | | +| `generated_by` | String(100) | sì | | | +| `storage_key` | String(60) | no | | | +| `user_name` | String(100) | sì | | | +| `locked` | Bool | no | `false` | | +| `deleted_at` | DateTimeUtc | sì | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_attachments_deleted_at` su `deleted_at` +- indice `ix_attachments_entity_entity_id` su `entity`, `entity_id` +- indice unico `ux_attachments_entity_entity_id_version_key_version` su `entity`, `entity_id`, `version_key`, `version` #### `audit_log` diff --git a/docs/adr/0021-file-e-allegati.md b/docs/adr/0021-file-e-allegati.md new file mode 100644 index 0000000..b1a3f76 --- /dev/null +++ b/docs/adr/0021-file-e-allegati.md @@ -0,0 +1,73 @@ +# ADR 0021 - File e allegati: archivio su volume, versioni, cestino, scrittori in casa + +- **Stato:** accettata +- **Data:** 2026-11-11 +- **Modifica:** SPEC §2 (riga *PDF e file*), §9.4; milestone M3, issue #34 + +## Contesto + +La specifica chiede allegati per azienda con versioni, cestino di 30 giorni, archivio su volume con limite, quota e +aggancio per l'antivirus, e scrittori PDF, CSV, XLSX e ZIP scritti in casa (nessuna libreria esterna, ADR 0002). Lascia +aperti la regola di numerazione delle versioni, la forma dell'archivio, il perimetro della prima versione del PDF e le +impostazioni predefinite del CSV. Questo ADR fissa le scelte. + +## Decisione + +1. **Archivio.** `IFileStore` sta in `Khaemhat.Core.Files` (l'implementazione è in Infrastructure, che non vede + Application); `VolumeFileStore` scrive in `/files///`. Ogni file è scritto + prima come `.part` **nella stessa cartella**, contando i byte (limite) e calcolando lo SHA-256 durante la + copia; poi passa quota e scanner e viene rinominato. Mai file temporanei fuori dal volume dei dati. La chiave + salvata nel database è `aaaa/guid` (relativa alla cartella dell'azienda) e viene validata: non può uscire dalla + cartella. I `.part` rimasti da caricamenti interrotti si cancellano dopo un giorno. +2. **Limiti.** 25 MB per file e nessuna quota per impostazione predefinita; gli amministratori li cambiano con le + impostazioni di istanza `files.max-upload-mb` e `files.company-quota-mb`. Il limite di dimensione vale per i file + caricati; i file generati hanno solo la quota. La quota si calcola sommando i file della cartella dell'azienda. +3. **Antivirus.** `IFileScanner` riceve il file completo prima che diventi visibile; quello registrato + (`NoOpFileScanner`) accetta tutto. +4. **Versioni.** Ogni allegato ha una *serie* (`version_key`): per i file generati il codice del generatore + (`gen:`), per gli altri il nome in minuscolo (`name:`). La versione è il massimo della serie nel + record più uno, contando anche gli allegati nel cestino; un indice unico su record + serie + versione impedisce due + versioni uguali (in caso di conflitto si riprova). *Rigenera* è una nuova generazione: non sovrascrive mai. + Caricare un file con lo stesso nome ne crea la versione successiva e lascia consultabile la precedente. L'elenco + mostra di norma solo l'ultima versione di ogni serie; il nome di download porta il suffisso `_vN` dalla v2. +5. **Cestino.** Cancellare un allegato o il documento lo sposta nel cestino (`deleted_at`); il job di sistema + `system.attachments-trash` (ogni notte alle 3:45) elimina righe e file dopo 30 giorni. Un allegato **bloccato** + (`locked`, ad esempio l'XML inviato allo SDI) non si cancella, e un documento con allegati bloccati non può mandarli + nel cestino. Il blocco è definitivo. +6. **Permessi.** `attachments.read` per vedere e scaricare, `attachments.write` per caricare, generare e bloccare, + `attachments.delete` per cancellare e ripristinare. Il permesso sul documento lo verifica chi chiama, che lo + conosce. Ogni modifica scrive lo storico (`audit_log`); l'utente che ha caricato o generato il file è salvato anche + in `attachments.user_name`, perché le colonne di audit conoscono l'utente solo dentro una richiesta HTTP. +7. **Tipi di file.** Il tipo MIME si ricava dall'estensione quando è nota; quello dichiarato dal browser si usa solo + per estensioni sconosciute. I nomi file sono ripuliti (niente cartelle né caratteri vietati, massimo 255). +8. **CSV.** Predefiniti per Excel in italiano: separatore `;`, BOM UTF-8, virgola decimale, date `gg/mm/aaaa`, + righe CRLF, virgolette RFC 4180. Le celle di testo che iniziano con `=`, `+`, `-`, `@`, tabulazione o ritorno a capo + ricevono un apostrofo davanti (iniezione di formule); i numeri non vengono toccati. Disponibile anche il profilo + invariante (`,`, punto decimale, date ISO, senza BOM). +9. **Scrittura in streaming.** CSV, XLSX, ZIP e PDF scrivono sull'uscita solo con chiamate asincrone, quindi possono + scrivere direttamente nella risposta HTTP (dove le scritture sincrone sono vietate). `ZipArchive` scrive ancora in + modo sincrono le chiusure delle voci e la directory centrale: quei pochi byte passano da un piccolo buffer in + memoria (`AsyncOutputBuffer`) e vengono inviati con la chiamata asincrona successiva. +10. **PDF, prima versione.** PDF 1.7 con i 12 font Type1 standard latini (Symbol e ZapfDingbats esclusi) in + `WinAnsiEncoding` (lettere accentate, `€`, virgolette tipografiche), testo, linee, rettangoli, colori RGB, + immagini JPEG incorporate così come sono (`DCTDecode`), più pagine, dizionario *Info*, flussi compressi + `FlateDecode`, tabella xref. Coordinate in punti dall'angolo **in basso a sinistra**, testo posizionato sulla linea + di base. Le larghezze per misurare e andare a capo sono quelle AFM di Helvetica, Helvetica-Bold e Times-Roman; + corsivi e grassetti di Times usano quelle del tondo, Courier è a passo fisso. Una pagina viene scritta sull'uscita + quando inizia la successiva. **PDF/A-3** (font incorporati, XMP, output intent, allegati XML per la copia di + cortesia FatturaPA) è rimandato: annotato come TODO in `PdfWriter`. +11. **Generatori.** Un'uscita di *Genera file* è un `IFileGenerator` (codice, chiave del testo, tipo, estensione, + entità supportate, nome file, `GenerateAsync`); `FileGenerationService` scrive il risultato direttamente + nell'archivio e lo registra come allegato generato con la versione successiva, oppure lo scrive su un flusso senza + salvarlo (anteprima di stampa). Per il *documento di prova* dell'issue #34 ci sono tre generatori dell'entità + fittizia `demo.document`: PDF, CSV e XLSX con righe e importi inventati. + +## Conseguenze + +- Gli allegati nel cestino occupano spazio e quota per 30 giorni. +- Il calcolo della quota legge la cartella dell'azienda a ogni caricamento quando una quota è impostata: va bene per + le dimensioni attese; se diventasse lento si terrà un contatore. +- Un file rimasto senza riga (crash fra scrittura del file e inserimento) è solo spazio perso; il contrario non può + accadere, perché la riga si scrive dopo il file e il file si cancella se l'inserimento fallisce. +- I moduli che producono file (stampe, FatturaPA, report) registrano i loro `IFileGenerator`; quelli che ricevono + file dall'esterno (SDI, e-mail) usano `AttachmentService.AddAsync` con il tipo giusto e, se serve, `Locked`. diff --git a/src/Khaemhat.Application/Files/AttachmentService.cs b/src/Khaemhat.Application/Files/AttachmentService.cs new file mode 100644 index 0000000..6cc5fa4 --- /dev/null +++ b/src/Khaemhat.Application/Files/AttachmentService.cs @@ -0,0 +1,732 @@ +using System.Data.Common; +using System.Globalization; +using System.Text.RegularExpressions; +using Khaemhat.Application.Audit; +using Khaemhat.Application.Instance; +using Khaemhat.Application.Security; +using Khaemhat.Core.Files; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Infrastructure.Files; + +namespace Khaemhat.Application.Files; + +/// An attachment as the interface shows it. +/// The identifier. +/// The entity of the owning record. +/// The owning record. +/// Uploaded, generated, e-invoice or notification. +/// The name. +/// The download name, with the version suffix from v2 (fattura_v2.pdf). +/// The media type. +/// The size in bytes. +/// The SHA-256 of the content. +/// The version, from 1. +/// The generator code (generated files). +/// Whether it is locked (cannot be deleted). +/// Whether it is the latest version of its series. +/// When it was uploaded or generated (UTC). +/// Who uploaded or generated it. +/// When it was moved to the trash; if in use. +public sealed record AttachmentView( + long Id, string Entity, long EntityId, AttachmentKind Kind, string Name, string FileName, string Mime, long Size, string Sha256, + int Version, string? GeneratedBy, bool Locked, bool IsLatest, DateTime CreatedAt, string? CreatedBy, DateTime? DeletedAt) +{ + /// How the interface can preview the file. + public AttachmentPreview Preview => MediaTypes.PreviewOf(Mime); + + /// The version label, v1, v2... + public string VersionLabel => "v" + Version.ToString(CultureInfo.InvariantCulture); + + /// The view of a row. + /// The row. + /// Whether it is the latest of its series. + /// The view. + public static AttachmentView From(Attachment row, bool isLatest) + { + ArgumentNullException.ThrowIfNull(row); + return new AttachmentView( + row.Id, row.Entity, row.EntityId, row.Kind, row.Name, MediaTypes.VersionedFileName(row.Name, row.Version), row.Mime, row.Size, row.Sha256, + row.Version, row.GeneratedBy, row.Locked, isLatest, row.CreatedAt, row.UserName ?? row.CreatedBy, row.DeletedAt); + } +} + +/// An open attachment: its description and its content. Dispose it to close the file. +/// The attachment. +/// The content, a read-only seekable stream. +public sealed class AttachmentContent(AttachmentView attachment, Stream content) : IAsyncDisposable, IDisposable +{ + /// The attachment. + public AttachmentView Attachment { get; } = attachment; + + /// The content. + public Stream Content { get; } = content; + + /// + public ValueTask DisposeAsync() => Content.DisposeAsync(); + + /// + public void Dispose() => Content.Dispose(); +} + +/// A file to attach that is not uploaded by a user: an e-invoice, a notification, a file from a procedure. +/// The kind. +/// The file name. +/// The media type; from the extension when . +/// The procedure that produced it: the versions count per this code when set, per name otherwise. +/// Whether it is locked from the start (for example the XML sent to the SDI). +public sealed record AttachmentFile(AttachmentKind Kind, string FileName, string? Mime = null, string? GeneratedBy = null, bool Locked = false); + +/// +/// The attachments of the company records (SPEC §9.4; wiki Allegati e file): upload, generated files with +/// versions, list, download, ZIP of all, lock, trash and restore. An attachment belongs to exactly one record +/// (entity + entity_id); its bytes are in the , its row in attachments, +/// and every change writes the history (). +/// +/// +/// Permissions: reading needs attachments.read, uploading, generating and locking attachments.write, +/// deleting and restoring attachments.delete. The permission on the owning record is checked by the caller (the +/// document service or page), which knows it. A company user works only in its own company. Deleting moves to the +/// company trash; removes rows and files 30 days later. +/// +public sealed partial class AttachmentService +{ + /// Permission to see and download attachments. + public const string ReadPermission = "attachments.read"; + + /// Permission to upload and generate attachments. + public const string WritePermission = "attachments.write"; + + /// Permission to delete and restore attachments. + public const string DeletePermission = "attachments.delete"; + + /// The instance setting with the largest upload in MB (default 25). + public const string MaxUploadSetting = "files.max-upload-mb"; + + /// The instance setting with the space each company may use in MB (default: no quota). + public const string CompanyQuotaSetting = "files.company-quota-mb"; + + /// Error: no such attachment (or not in this company). + public const string NotFoundError = "attachments.not_found"; + + /// Error: the attachment is locked. + public const string LockedError = "attachments.locked"; + + /// Error: the file is larger than the limit. + public const string TooLargeError = "attachments.file_too_large"; + + /// Error: the company has no space left. + public const string QuotaError = "attachments.quota_exceeded"; + + /// Error: the scanner rejected the file. + public const string RejectedError = "attachments.file_rejected"; + + /// Error: the entity or record is not valid. + public const string InvalidOwnerError = "attachments.owner_invalid"; + + /// Error: the file is empty. + public const string EmptyError = "attachments.file_empty"; + + /// How long attachments stay in the trash. + public static readonly TimeSpan TrashRetention = TimeSpan.FromDays(30); + + private const int MaxVersionAttempts = 3; + private const long Megabyte = 1024 * 1024; + + private readonly IUnitOfWorkFactory _factory; + private readonly IFileStore _store; + private readonly PermissionService _permissions; + private readonly AuditTrail _audit; + private readonly SystemSettingsStore _settings; + private readonly FileStoreOptions _options; + private readonly TimeProvider _clock; + + /// Creates the service. + /// Opens the company databases. + /// The file store. + /// Checks permissions. + /// Writes the history. + /// Reads the limits set by the administrators. + /// The default limits. + /// The clock (trash dates). + public AttachmentService( + IUnitOfWorkFactory factory, IFileStore store, PermissionService permissions, AuditTrail audit, SystemSettingsStore settings, FileStoreOptions options, TimeProvider clock) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(store); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(audit); + ArgumentNullException.ThrowIfNull(settings); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(clock); + _factory = factory; + _store = store; + _permissions = permissions; + _audit = audit; + _settings = settings; + _options = options; + _clock = clock; + } + + /// The limits in force: the instance settings, else the store defaults (25 MB, no quota). + /// Cancellation. + /// The limits for uploads. + public async Task GetLimitsAsync(CancellationToken cancellationToken = default) + { + var max = await ReadMegabytesAsync(MaxUploadSetting, cancellationToken).ConfigureAwait(false) ?? _options.MaxFileBytes; + var quota = await ReadMegabytesAsync(CompanyQuotaSetting, cancellationToken).ConfigureAwait(false) ?? _options.CompanyQuotaBytes; + return new FileLimits(max, quota); + } + + /// Uploads a file to a record (streaming; the size limit and the quota apply). + /// Who uploads. + /// The company. + /// The entity of the record, for example sales.invoice. + /// The record. + /// The file name as received. + /// The type declared by the client (used only when the extension is unknown). + /// The content. + /// Cancellation. + /// The new attachment; a file with the same name as an existing one becomes its next version. + /// The actor may not upload. + /// The file is empty, too large, over quota or rejected. + public async Task UploadAsync( + Actor actor, string companyCode, string entity, long entityId, string fileName, string? declaredMime, Stream content, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(content); + var company = await DemandAsync(actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false); + CheckOwner(entity, entityId); + var limits = await GetLimitsAsync(cancellationToken).ConfigureAwait(false); + var stored = await StoreAsync(company, limits, (target, ct) => content.CopyToAsync(target, ct), cancellationToken).ConfigureAwait(false); + var name = MediaTypes.CleanFileName(fileName); + return await RecordAsync(actor, company, entity, entityId, new AttachmentFile(AttachmentKind.Uploaded, name, MediaTypes.Resolve(name, declaredMime)), stored, cancellationToken).ConfigureAwait(false); + } + + /// + /// Adds a file produced by Khaemhat, written by straight into the store. Each call adds + /// the next version of the series of (or of the name): this is "Rigenera". + /// + /// Who generates. + /// The company. + /// The entity of the record. + /// The record. + /// Kind, name, type, generator, lock. + /// Writes the content to the stream it receives (write-only, not seekable). + /// Cancellation. + /// The new attachment. + /// The actor may not add attachments. + /// The company has no space left, or the file is empty. + public async Task AddAsync( + Actor actor, string companyCode, string entity, long entityId, AttachmentFile file, Func write, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(file); + ArgumentNullException.ThrowIfNull(write); + var company = await DemandAsync(actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false); + CheckOwner(entity, entityId); + if (file.GeneratedBy is { } generator && (generator.Length is 0 or > 100)) + { + throw new ValidationFailedException([InvalidOwnerError]); + } + + // Files made by Khaemhat are bounded by their generator: only the quota applies. + var limits = await GetLimitsAsync(cancellationToken).ConfigureAwait(false); + var stored = await StoreAsync(company, new FileLimits(0, limits.QuotaBytes), write, cancellationToken).ConfigureAwait(false); + var name = MediaTypes.CleanFileName(file.FileName); + var normalized = file with { FileName = name, Mime = MediaTypes.Resolve(name, file.Mime) }; + return await RecordAsync(actor, company, entity, entityId, normalized, stored, cancellationToken).ConfigureAwait(false); + } + + /// The attachments of a record, newest first (trash excluded). + /// Who reads. + /// The company. + /// The entity. + /// The record. + /// Whether to list the earlier versions too (marked not ). + /// Cancellation. + /// The attachments. + public async Task> ListAsync( + Actor actor, string companyCode, string entity, long entityId, bool includeOlderVersions = false, CancellationToken cancellationToken = default) + { + var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + return Views(await ListRowsAsync(company, entity, entityId, cancellationToken).ConfigureAwait(false), includeOlderVersions); + } + + /// How many attachments a record has (latest versions only): the number on the toolbar icon. + /// Who reads. + /// The company. + /// The entity. + /// The record. + /// Cancellation. + /// The count. + public async Task CountAsync(Actor actor, string companyCode, string entity, long entityId, CancellationToken cancellationToken = default) => + (await ListAsync(actor, companyCode, entity, entityId, false, cancellationToken).ConfigureAwait(false)).Count; + + /// One attachment, in use or in the trash. + /// Who reads. + /// The company. + /// The attachment. + /// Cancellation. + /// The attachment, or . + public async Task GetAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default) + { + var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + return (await LoadAsync(company, attachmentId, cancellationToken).ConfigureAwait(false))?.View; + } + + /// Opens an attachment for download or preview. + /// Who reads. + /// The company. + /// The attachment. + /// Cancellation. + /// The attachment and its content; dispose it. + /// No such attachment in use, or its file is missing. + public async Task OpenAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default) + { + var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + var loaded = await LoadAsync(company, attachmentId, cancellationToken).ConfigureAwait(false); + if (loaded is not { } found || found.Row.DeletedAt is not null) + { + throw new KeyNotFoundException(NotFoundError); + } + + var (row, view) = found; + + try + { + return new AttachmentContent(view, _store.OpenRead(company, row.StorageKey)); + } + catch (FileStoreException ex) when (ex.Code == FileStoreException.NotFound) + { + throw new KeyNotFoundException(NotFoundError, ex); + } + } + + /// + /// Writes a ZIP with the latest version of every attachment of a record ("Scarica tutto"), streaming: the output + /// can be the HTTP response. + /// + /// Who downloads. + /// The company. + /// The entity. + /// The record. + /// The stream that receives the ZIP; it is left open. + /// Cancellation. + /// How many files were written. + public async Task WriteZipAsync(Actor actor, string companyCode, string entity, long entityId, Stream output, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(output); + var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + var rows = await ListRowsAsync(company, entity, entityId, cancellationToken).ConfigureAwait(false); + var keys = rows.ToDictionary(r => r.Id, r => r.StorageKey); + await using var zip = await ZipStreamWriter.CreateAsync(output, leaveOpen: true, cancellationToken).ConfigureAwait(false); + foreach (var attachment in Views(rows, includeOlderVersions: false)) + { + var key = keys[attachment.Id]; + if (!_store.Exists(company, key)) + { + continue; + } + + var content = _store.OpenRead(company, key); + await using (content.ConfigureAwait(false)) + { + var level = attachment.Mime is "image/jpeg" or "image/png" or MediaTypes.Zip or MediaTypes.Xlsx + ? System.IO.Compression.CompressionLevel.NoCompression + : System.IO.Compression.CompressionLevel.Optimal; + await zip.AddAsync(attachment.FileName, content, new DateTimeOffset(DateTime.SpecifyKind(attachment.CreatedAt, DateTimeKind.Utc)), level, cancellationToken).ConfigureAwait(false); + } + } + + return zip.Count; + } + + /// Locks an attachment: from now on it cannot be deleted (for example the XML sent to the SDI). Locks are permanent. + /// Who locks. + /// The company. + /// The attachment. + /// Cancellation. + /// A task. + public Task LockAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default) => + ChangeAsync( + actor, companyCode, attachmentId, WritePermission, + row => + { + if (row.Locked) + { + return false; + } + + row.Locked = true; + return true; + }, + cancellationToken); + + /// Moves one attachment to the company trash (restorable for 30 days). + /// Who deletes. + /// The company. + /// The attachment. + /// Cancellation. + /// A task. + /// The attachment is locked (). + public Task DeleteAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default) + { + var now = _clock.GetUtcNow().UtcDateTime; + return ChangeAsync( + actor, companyCode, attachmentId, DeletePermission, + row => + { + if (row.Locked) + { + throw new ValidationFailedException([LockedError]); + } + + if (row.DeletedAt is not null) + { + return false; + } + + row.DeletedAt = now; + return true; + }, + cancellationToken); + } + + /// Takes an attachment back from the trash. + /// Who restores. + /// The company. + /// The attachment. + /// Cancellation. + /// A task. + public Task RestoreAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default) => + ChangeAsync( + actor, companyCode, attachmentId, DeletePermission, + row => + { + if (row.DeletedAt is null) + { + return false; + } + + row.DeletedAt = null; + return true; + }, + cancellationToken); + + /// + /// Moves every attachment of a record to the trash: call it in the deletion of the record (the caller has checked + /// that the record may be deleted). Refused when an attachment is locked: a record with a sent e-invoice cannot go. + /// + /// Who deletes the record. + /// The company. + /// The entity. + /// The record. + /// Cancellation. + /// How many attachments were moved. + /// An attachment is locked (). + public Task TrashForEntityAsync(Actor actor, string companyCode, string entity, long entityId, CancellationToken cancellationToken = default) => + ChangeEntityAsync(actor, companyCode, entity, entityId, toTrash: true, cancellationToken); + + /// Takes back from the trash every attachment of a record (the record was restored). + /// Who restores. + /// The company. + /// The entity. + /// The record. + /// Cancellation. + /// How many attachments were restored. + public Task RestoreForEntityAsync(Actor actor, string companyCode, string entity, long entityId, CancellationToken cancellationToken = default) => + ChangeEntityAsync(actor, companyCode, entity, entityId, toTrash: false, cancellationToken); + + /// The company trash, most recently deleted first. + /// Who looks (needs attachments.delete). + /// The company. + /// Cancellation. + /// The attachments in the trash. + public async Task> ListTrashAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + var company = await DemandAsync(actor, companyCode, DeletePermission, cancellationToken).ConfigureAwait(false); + await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var rows = (await unitOfWork.Repository().ListAsync( + Query.For().Where(a => a.DeletedAt != null).OrderByDescending(a => a.DeletedAt).Take(1000), cancellationToken).ConfigureAwait(false)).Items; + return rows.Select(r => AttachmentView.From(r, isLatest: false)).ToList(); + } + + /// The space the company uses in the file store, with the quota in force. + /// Who looks. + /// The company. + /// Cancellation. + /// The usage. + public async Task GetUsageAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + var limits = await GetLimitsAsync(cancellationToken).ConfigureAwait(false); + return await _store.GetUsageAsync(company, limits.QuotaBytes, cancellationToken).ConfigureAwait(false); + } + + /// + /// Removes for good the attachments in the trash for more than 30 days, rows and files, and the partial files of + /// interrupted uploads. Run by the scheduled job . + /// + /// The company. + /// Cancellation. + /// How many attachments were removed. + public async Task PurgeTrashAsync(string companyCode, CancellationToken cancellationToken = default) + { + var company = CompanyCodes.Normalize(companyCode); + var limit = _clock.GetUtcNow().UtcDateTime - TrashRetention; + await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var repository = unitOfWork.Repository(); + var rows = (await repository.ListAsync(Query.For().Where(a => a.DeletedAt != null && a.DeletedAt < limit), cancellationToken).ConfigureAwait(false)).Items; + var removed = 0; + foreach (var row in rows) + { + await unitOfWork.InTransactionAsync( + async ct => + { + await repository.DeleteAsync(row.Id, ct).ConfigureAwait(false); + await _audit.RecordAsync(unitOfWork, AuditAction.Delete, row.Id, row, null, Actor.System.UserName, ct).ConfigureAwait(false); + }, + cancellationToken).ConfigureAwait(false); + + // The row is gone: the file follows (a file left behind by a crash here is only wasted space). + if (!await StorageKeyInUseAsync(repository, row.StorageKey, cancellationToken).ConfigureAwait(false)) + { + _store.Delete(company, row.StorageKey); + } + + removed++; + } + + _store.DeleteAbandonedParts(company, TimeSpan.FromDays(1)); + return removed; + } + + private static List Views(IReadOnlyList rows, bool includeOlderVersions) + { + var latest = rows.GroupBy(r => r.VersionKey, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.Max(r => r.Version), StringComparer.Ordinal); + return rows + .Select(r => AttachmentView.From(r, r.Version == latest[r.VersionKey])) + .Where(v => includeOlderVersions || v.IsLatest) + .ToList(); + } + + private static void CheckOwner(string entity, long entityId) + { + if (entity is null || entity.Length > 100 || !EntityPattern().IsMatch(entity) || entityId <= 0) + { + throw new ValidationFailedException([InvalidOwnerError]); + } + } + + private static string VersionKeyOf(AttachmentFile file) => + file.GeneratedBy is { } generator ? "gen:" + generator : "name:" + file.FileName.ToLowerInvariant(); + + private static async Task IsLatestAsync(IUnitOfWork unitOfWork, Attachment row, CancellationToken cancellationToken) + { + var (entity, id, key, version) = (row.Entity, row.EntityId, row.VersionKey, row.Version); + return await unitOfWork.Repository().CountAsync( + Query.For().Where(a => a.Entity == entity && a.EntityId == id && a.VersionKey == key && a.Version > version), + cancellationToken).ConfigureAwait(false) == 0; + } + + private static async Task StorageKeyInUseAsync(IRepository repository, string key, CancellationToken cancellationToken) => + await repository.CountAsync(Query.For().Where(a => a.StorageKey == key), cancellationToken).ConfigureAwait(false) > 0; + + [GeneratedRegex("^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_-]*)*$", RegexOptions.CultureInvariant)] + private static partial Regex EntityPattern(); + + private async Task DemandAsync(Actor actor, string companyCode, string permission, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(actor); + var company = CompanyCodes.Normalize(companyCode); + if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, company, StringComparison.Ordinal)) + { + throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A company user works only in its own company."); + } + + await _permissions.DemandAsync(actor, permission, cancellationToken).ConfigureAwait(false); + return company; + } + + private async Task ReadMegabytesAsync(string key, CancellationToken cancellationToken) + { + var value = await _settings.GetAsync(key, cancellationToken).ConfigureAwait(false); + return long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var megabytes) && megabytes >= 0 ? megabytes * Megabyte : null; + } + + private async Task StoreAsync(string company, FileLimits limits, Func write, CancellationToken cancellationToken) + { + try + { + await using var writer = await _store.CreateAsync(company, limits, cancellationToken).ConfigureAwait(false); + await write(writer.Content, cancellationToken).ConfigureAwait(false); + if (writer.Content.Length == 0) + { + throw new ValidationFailedException([EmptyError]); + } + + return await writer.CommitAsync(cancellationToken).ConfigureAwait(false); + } + catch (FileStoreException ex) + { + var code = ex.Code switch + { + FileStoreException.TooLarge => TooLargeError, + FileStoreException.QuotaExceeded => QuotaError, + _ => RejectedError, + }; + throw new ValidationFailedException(code, ex); + } + } + + private async Task RecordAsync( + Actor actor, string company, string entity, long entityId, AttachmentFile file, StoredFile stored, CancellationToken cancellationToken) + { + var key = VersionKeyOf(file); + try + { + for (var attempt = 1; ; attempt++) + { + try + { + return await InsertAsync(actor, company, entity, entityId, file, key, stored, cancellationToken).ConfigureAwait(false); + } + catch (DbException) when (attempt < MaxVersionAttempts) + { + // Two versions of the same series at once: the unique index refused one; take the next number. + } + } + } + catch + { + _store.Delete(company, stored.Key); + throw; + } + } + + private async Task InsertAsync( + Actor actor, string company, string entity, long entityId, AttachmentFile file, string key, StoredFile stored, CancellationToken cancellationToken) + { + await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var repository = unitOfWork.Repository(); + Attachment? row = null; + await unitOfWork.InTransactionAsync( + async ct => + { + var last = await repository.FindAsync( + Query.For().Where(a => a.Entity == entity && a.EntityId == entityId && a.VersionKey == key).OrderByDescending(a => a.Version).Take(1), + ct).ConfigureAwait(false); + row = new Attachment + { + Entity = entity, + EntityId = entityId, + Kind = file.Kind, + Name = file.FileName, + Mime = file.Mime ?? MediaTypes.OctetStream, + Size = stored.Size, + Sha256 = stored.Sha256, + Version = (last?.Version ?? 0) + 1, + VersionKey = key, + GeneratedBy = file.GeneratedBy, + StorageKey = stored.Key, + UserName = actor.UserName.Length > 100 ? actor.UserName[..100] : actor.UserName, + Locked = file.Locked, + }; + await repository.InsertAsync(row, ct).ConfigureAwait(false); + await _audit.RecordAsync(unitOfWork, AuditAction.Insert, row.Id, null, row, actor.UserName, ct).ConfigureAwait(false); + }, + cancellationToken).ConfigureAwait(false); + return AttachmentView.From(row!, isLatest: true); + } + + private async Task ChangeAsync(Actor actor, string companyCode, long attachmentId, string permission, Func change, CancellationToken cancellationToken) + { + var company = await DemandAsync(actor, companyCode, permission, cancellationToken).ConfigureAwait(false); + await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var repository = unitOfWork.Repository(); + await unitOfWork.InTransactionAsync( + async ct => + { + var row = await repository.GetAsync(attachmentId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFoundError); + var before = Copy(row); + if (change(row)) + { + await repository.UpdateAsync(row, ct).ConfigureAwait(false); + await _audit.RecordAsync(unitOfWork, AuditAction.Update, row.Id, before, row, actor.UserName, ct).ConfigureAwait(false); + } + }, + cancellationToken).ConfigureAwait(false); + } + + private async Task ChangeEntityAsync(Actor actor, string companyCode, string entity, long entityId, bool toTrash, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(actor); + var company = CompanyCodes.Normalize(companyCode); + if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, company, StringComparison.Ordinal)) + { + throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A company user works only in its own company."); + } + + CheckOwner(entity, entityId); + var now = _clock.GetUtcNow().UtcDateTime; + var changed = 0; + await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var repository = unitOfWork.Repository(); + await unitOfWork.InTransactionAsync( + async ct => + { + var query = toTrash + ? Query.For().Where(a => a.Entity == entity && a.EntityId == entityId && a.DeletedAt == null) + : Query.For().Where(a => a.Entity == entity && a.EntityId == entityId && a.DeletedAt != null); + var rows = (await repository.ListAsync(query, ct).ConfigureAwait(false)).Items; + if (toTrash && rows.Any(r => r.Locked)) + { + throw new ValidationFailedException([LockedError]); + } + + foreach (var row in rows) + { + var before = Copy(row); + row.DeletedAt = toTrash ? now : null; + await repository.UpdateAsync(row, ct).ConfigureAwait(false); + await _audit.RecordAsync(unitOfWork, AuditAction.Update, row.Id, before, row, actor.UserName, ct).ConfigureAwait(false); + changed++; + } + }, + cancellationToken).ConfigureAwait(false); + return changed; + } + + private async Task> ListRowsAsync(string company, string entity, long entityId, CancellationToken cancellationToken) + { + await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return (await unitOfWork.Repository().ListAsync( + Query.For().Where(a => a.Entity == entity && a.EntityId == entityId && a.DeletedAt == null).OrderByDescending(a => a.Id), + cancellationToken).ConfigureAwait(false)).Items; + } + + private async Task<(Attachment Row, AttachmentView View)?> LoadAsync(string company, long attachmentId, CancellationToken cancellationToken) + { + await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var row = await unitOfWork.Repository().GetAsync(attachmentId, cancellationToken).ConfigureAwait(false); + return row is null ? null : (row, AttachmentView.From(row, await IsLatestAsync(unitOfWork, row, cancellationToken).ConfigureAwait(false))); + } + + private static Attachment Copy(Attachment row) => new() + { + Id = row.Id, + Entity = row.Entity, + EntityId = row.EntityId, + Kind = row.Kind, + Name = row.Name, + Mime = row.Mime, + Size = row.Size, + Sha256 = row.Sha256, + Version = row.Version, + VersionKey = row.VersionKey, + GeneratedBy = row.GeneratedBy, + StorageKey = row.StorageKey, + UserName = row.UserName, + Locked = row.Locked, + DeletedAt = row.DeletedAt, + }; +} diff --git a/src/Khaemhat.Application/Files/AttachmentTrashPurgeJob.cs b/src/Khaemhat.Application/Files/AttachmentTrashPurgeJob.cs new file mode 100644 index 0000000..f98296d --- /dev/null +++ b/src/Khaemhat.Application/Files/AttachmentTrashPurgeJob.cs @@ -0,0 +1,36 @@ +using System.Globalization; +using Khaemhat.Application.Jobs; +using Khaemhat.Core.Instance; +using Khaemhat.Data.Companies; + +namespace Khaemhat.Application.Files; + +/// +/// Empties the company trash of attachments (SPEC §9.4): every night, in every company that is not disabled, removes +/// rows and files deleted more than 30 days ago and the partial files of interrupted uploads. +/// +/// The attachments. +/// The companies. +public sealed class AttachmentTrashPurgeJob(AttachmentService attachments, ICompanyRegistry companies) : IScheduledJob +{ + /// The job type. + public const string JobType = "system.attachments-trash"; + + /// + public string Type => JobType; + + /// + public async Task RunAsync(JobContext context, CancellationToken cancellationToken) + { + var removed = 0; + foreach (var company in await companies.ListAsync(cancellationToken).ConfigureAwait(false)) + { + if (company.Status is not CompanyStatus.Disabled) + { + removed += await attachments.PurgeTrashAsync(company.Code, cancellationToken).ConfigureAwait(false); + } + } + + return string.Create(CultureInfo.InvariantCulture, $"{removed} allegati eliminati dal cestino."); + } +} diff --git a/src/Khaemhat.Application/Files/DemoDocumentGenerators.cs b/src/Khaemhat.Application/Files/DemoDocumentGenerators.cs new file mode 100644 index 0000000..2162f1f --- /dev/null +++ b/src/Khaemhat.Application/Files/DemoDocumentGenerators.cs @@ -0,0 +1,238 @@ +using System.Globalization; +using Khaemhat.Infrastructure.Files; + +namespace Khaemhat.Application.Files; + +/// +/// The documento di prova of issue #34: a clearly fictitious document (entity ) used to try +/// attachments, generation, versions and print preview before the real documents exist (M5). Every value is invented. +/// +public static class DemoDocument +{ + /// The entity of the test document. + public const string Entity = "demo.document"; + + /// The title printed on the test document. + public const string Title = "Documento di prova"; + + /// The fictitious lines: code, description, quantity, unit price. + public static IReadOnlyList<(string Code, string Description, decimal Quantity, decimal UnitPrice)> Lines { get; } = + [ + ("PROVA-001", "Articolo di prova – vite inventata", 10m, 1.25m), + ("PROVA-002", "Servizio fittizio di consulenza (non reale)", 2m, 480m), + ("PROVA-003", "Materiale d'esempio: cavo €uro-test 3×1,5", 25.5m, 3.9m), + ("PROVA-004", "Riga con accenti: perché, città, più, così", 1m, 1234.56m), + ("PROVA-005", "Sconto finto", 1m, -50m), + ]; + + /// The headers of the line table. + public static IReadOnlyList Headers { get; } = ["Codice", "Descrizione", "Quantità", "Prezzo unitario", "Importo"]; + + /// The amount of a line. + /// The line. + /// Quantity times unit price, rounded to cents. + public static decimal Amount((string Code, string Description, decimal Quantity, decimal UnitPrice) line) => + Math.Round(line.Quantity * line.UnitPrice, 2, MidpointRounding.AwayFromZero); + + /// The total of the lines. + public static decimal Total => Lines.Sum(Amount); + + /// An amount in euro as Italians write it: € 1.234,56. + /// The amount. + /// The culture (it-IT). + /// The text. + public static string Euro(decimal value, CultureInfo culture) => + (value < 0 ? "-€ " : "€ ") + Math.Abs(value).ToString("N2", culture); + + /// The file name stem for a record. + /// The record. + /// For example documento-di-prova-7. + public static string Stem(FileGenerationContext context) + { + ArgumentNullException.ThrowIfNull(context); + return "documento-di-prova-" + context.EntityId.ToString(CultureInfo.InvariantCulture); + } +} + +/// The test PDF of the test document: title, a paragraph and the table of lines with amounts aligned right. +public sealed class DemoPdfGenerator : IFileGenerator +{ + /// The generator code. + public const string GeneratorCode = "demo.test-pdf"; + + /// + public string Code => GeneratorCode; + + /// + public string TitleKey => "files.generators.demo_pdf"; + + /// + public string MediaType => PdfWriter.MediaType; + + /// + public string Extension => ".pdf"; + + /// + public bool Supports(string entity) => entity == DemoDocument.Entity; + + /// + public string FileName(FileGenerationContext context) => DemoDocument.Stem(context) + Extension; + + /// + public async Task GenerateAsync(FileGenerationContext context, Stream output, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + var culture = context.Culture; + var accent = PdfColor.FromHex("#1F5F8B"); + var muted = PdfColor.Gray(110); + var info = new PdfDocumentInfo + { + Title = DemoDocument.Title + " n. " + context.EntityId.ToString(CultureInfo.InvariantCulture), + Author = context.CompanyCode, + Subject = "Documento fittizio per provare la generazione dei file", + CreationDate = new DateTimeOffset(DateTime.SpecifyKind(context.Now, DateTimeKind.Utc)), + }; + + await using var pdf = new PdfWriter(output, info, leaveOpen: true); + var page = await pdf.AddPageAsync(cancellationToken: cancellationToken).ConfigureAwait(false); + const double left = 50; + var right = page.Width - 50; + var y = page.Height - 70; + + page.DrawText(DemoDocument.Title, left, y, PdfFont.HelveticaBold, 20, accent); + page.DrawTextRight("n. " + context.EntityId.ToString(CultureInfo.InvariantCulture) + " del " + context.Now.ToString("d", culture), right, y, PdfFont.Helvetica, 10, muted); + y -= 12; + page.DrawLine(left, y, right, y, 1, accent); + y -= 22; + y = page.DrawParagraph( + "Questo è un documento di prova generato da Khaemhat: azienda " + context.CompanyCode + ", generato da " + context.Actor.UserName + + ". Righe, prezzi e importi sono inventati e servono solo a provare stampa, allegati e versioni (v1, v2…).", + left, y, right - left, PdfFont.Helvetica, 10, 13); + y -= 16; + + // Table: code, description, quantity, unit price, amount (the last three aligned right). + double[] edges = [left, left + 75, right - 205, right - 135, right - 65, right]; + page.DrawRectangle(left, y - 6, right - left, 18, fill: PdfColor.Gray(235)); + for (var i = 0; i < DemoDocument.Headers.Count; i++) + { + if (i < 2) + { + page.DrawText(DemoDocument.Headers[i], edges[i] + 4, y, PdfFont.HelveticaBold, 9); + } + else + { + page.DrawTextRight(DemoDocument.Headers[i], edges[i + 1] - 4, y, PdfFont.HelveticaBold, 9); + } + } + + y -= 20; + foreach (var line in DemoDocument.Lines) + { + page.DrawText(line.Code, edges[0] + 4, y, PdfFont.Courier, 9); + page.DrawText(PdfTextLayout.Fit(line.Description, PdfFont.Helvetica, 9, edges[2] - edges[1] - 8), edges[1] + 4, y, PdfFont.Helvetica, 9); + page.DrawTextRight(line.Quantity.ToString("#,##0.##", culture), edges[3] - 4, y, PdfFont.Helvetica, 9); + page.DrawTextRight(DemoDocument.Euro(line.UnitPrice, culture), edges[4] - 4, y, PdfFont.Helvetica, 9); + page.DrawTextRight(DemoDocument.Euro(DemoDocument.Amount(line), culture), edges[5] - 4, y, PdfFont.Helvetica, 9); + y -= 6; + page.DrawLine(left, y, right, y, 0.25, PdfColor.Gray(200)); + y -= 12; + } + + y -= 4; + page.DrawText("Totale", edges[3] + 4, y, PdfFont.HelveticaBold, 11); + page.DrawTextRight(DemoDocument.Euro(DemoDocument.Total, culture), right - 4, y, PdfFont.HelveticaBold, 11, accent); + + page.DrawText("Documento fittizio – nessun valore fiscale", left, 40, PdfFont.HelveticaOblique, 8, muted); + page.DrawTextRight("Pagina 1", right, 40, PdfFont.Helvetica, 8, muted); + await pdf.CloseAsync(cancellationToken).ConfigureAwait(false); + } +} + +/// The lines of the test document as CSV (Italian Excel: ;, decimal comma, BOM). +public sealed class DemoCsvGenerator : IFileGenerator +{ + /// The generator code. + public const string GeneratorCode = "demo.test-csv"; + + /// + public string Code => GeneratorCode; + + /// + public string TitleKey => "files.generators.demo_csv"; + + /// + public string MediaType => MediaTypes.Csv; + + /// + public string Extension => ".csv"; + + /// + public bool Supports(string entity) => entity == DemoDocument.Entity; + + /// + public string FileName(FileGenerationContext context) => DemoDocument.Stem(context) + "-righe" + Extension; + + /// + public async Task GenerateAsync(FileGenerationContext context, Stream output, CancellationToken cancellationToken) + { + await using var csv = new CsvWriter(output, CsvOptions.Italian, leaveOpen: true); + await csv.WriteRowAsync(DemoDocument.Headers, cancellationToken).ConfigureAwait(false); + foreach (var line in DemoDocument.Lines) + { + await csv.WriteRowAsync([line.Code, line.Description, line.Quantity, line.UnitPrice, DemoDocument.Amount(line)], cancellationToken).ConfigureAwait(false); + } + + await csv.FlushAsync(cancellationToken).ConfigureAwait(false); + } +} + +/// The lines of the test document as an XLSX sheet with bold header and euro amounts. +public sealed class DemoXlsxGenerator : IFileGenerator +{ + /// The generator code. + public const string GeneratorCode = "demo.test-xlsx"; + + /// + public string Code => GeneratorCode; + + /// + public string TitleKey => "files.generators.demo_xlsx"; + + /// + public string MediaType => XlsxWriter.MediaType; + + /// + public string Extension => ".xlsx"; + + /// + public bool Supports(string entity) => entity == DemoDocument.Entity; + + /// + public string FileName(FileGenerationContext context) => DemoDocument.Stem(context) + "-righe" + Extension; + + /// + public async Task GenerateAsync(FileGenerationContext context, Stream output, CancellationToken cancellationToken) + { + var xlsx = await XlsxWriter.CreateAsync(output, leaveOpen: true, cancellationToken: cancellationToken).ConfigureAwait(false); + await using (xlsx.ConfigureAwait(false)) + { + await xlsx.StartSheetAsync( + "Righe", + [ + new XlsxColumn(DemoDocument.Headers[0], 14), + new XlsxColumn(DemoDocument.Headers[1], 48), + new XlsxColumn(DemoDocument.Headers[2], 12, XlsxFormat.TwoDecimals), + new XlsxColumn(DemoDocument.Headers[3], 16, XlsxFormat.Euro), + new XlsxColumn(DemoDocument.Headers[4], 16, XlsxFormat.Euro), + ], + cancellationToken).ConfigureAwait(false); + foreach (var line in DemoDocument.Lines) + { + await xlsx.WriteRowAsync([line.Code, line.Description, line.Quantity, line.UnitPrice, DemoDocument.Amount(line)], cancellationToken).ConfigureAwait(false); + } + + await xlsx.WriteRowAsync([null, "Totale", null, null, DemoDocument.Total], cancellationToken).ConfigureAwait(false); + await xlsx.CompleteAsync(cancellationToken).ConfigureAwait(false); + } + } +} diff --git a/src/Khaemhat.Application/Files/FileGenerationService.cs b/src/Khaemhat.Application/Files/FileGenerationService.cs new file mode 100644 index 0000000..ad7b34a --- /dev/null +++ b/src/Khaemhat.Application/Files/FileGenerationService.cs @@ -0,0 +1,165 @@ +using System.Globalization; +using Khaemhat.Application.Security; +using Khaemhat.Core.Files; +using Khaemhat.Data; + +namespace Khaemhat.Application.Files; + +/// What a generator receives besides the output stream. +/// Who asked for the file (the generator reads data on its behalf). +/// The company. +/// The entity of the record, for example sales.invoice. +/// The record. +/// The culture of numbers, dates and texts (it-IT). +/// When the file is generated (UTC). +public sealed record FileGenerationContext(Actor Actor, string CompanyCode, string Entity, long EntityId, CultureInfo Culture, DateTime Now); + +/// +/// An output of the Genera file section (SPEC §9.4): print PDF, XML FatturaPA, rows in XLSX/CSV, courtesy ZIP... +/// Modules register theirs as singletons; runs them. +/// +public interface IFileGenerator +{ + /// The unique code, also written in attachments.generated_by (versions count per code), for example sales.invoice.pdf. + string Code { get; } + + /// The text key of the label shown in the interface (Italian text in the Web resources). + string TitleKey { get; } + + /// The media type of the output. + string MediaType { get; } + + /// The extension of the output, with the dot (.pdf). + string Extension { get; } + + /// Whether the generator applies to records of an entity. + /// The entity. + /// if it does. + bool Supports(string entity); + + /// The file name for a record, with extension (for example Fattura-2026-15.pdf). + /// The record. + /// The file name. + string FileName(FileGenerationContext context); + + /// Writes the file. The stream is write-only and not seekable; write with asynchronous calls. + /// The record. + /// The stream that receives the file; do not close it. + /// Cancellation. + /// A task. + Task GenerateAsync(FileGenerationContext context, Stream output, CancellationToken cancellationToken); +} + +/// The registered generators, by code. +public sealed class FileGeneratorRegistry +{ + private readonly Dictionary _byCode; + + /// Creates the registry. + /// The generators (codes must be unique). + public FileGeneratorRegistry(IEnumerable generators) + { + ArgumentNullException.ThrowIfNull(generators); + _byCode = new Dictionary(StringComparer.Ordinal); + foreach (var generator in generators) + { + if (!_byCode.TryAdd(generator.Code, generator)) + { + throw new InvalidOperationException($"Two file generators have code {generator.Code}."); + } + } + } + + /// Every generator, by code. + public IReadOnlyCollection All => _byCode.Values; + + /// The generator with a code. + /// The code. + /// The generator, or . + public IFileGenerator? Find(string code) => _byCode.GetValueOrDefault(code); + + /// The generators that apply to an entity, by code. + /// The entity. + /// The generators. + public IReadOnlyList For(string entity) => + _byCode.Values.Where(g => g.Supports(entity)).OrderBy(g => g.Code, StringComparer.Ordinal).ToList(); +} + +/// +/// Runs the generators (SPEC §9.4): writes the file straight into the file store and +/// records it as a generated attachment of the record, with the next version (v1, v2... "Rigenera"); +/// writes it to any stream without keeping it (print preview, direct download). +/// +/// The generators. +/// Records the generated files. +/// Checks permissions for . +/// The clock. +public sealed class FileGenerationService(FileGeneratorRegistry registry, AttachmentService attachments, PermissionService permissions, TimeProvider clock) +{ + /// Error: no generator with that code applies to the record. + public const string UnknownGeneratorError = "attachments.generator_unknown"; + + private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT"); + + /// The generators that apply to an entity (the Genera file list). + /// The entity. + /// The generators. + public IReadOnlyList AvailableFor(string entity) => registry.For(entity); + + /// Generates a file and attaches it to the record as the next version of the generator's series. + /// Who generates (needs attachments.write). + /// The company. + /// The entity. + /// The record. + /// The generator. + /// Cancellation. + /// The new attachment. + /// No such generator for the entity (). + public Task GenerateAsync( + Actor actor, string companyCode, string entity, long entityId, string generatorCode, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var generator = Resolve(entity, generatorCode); + var context = Context(actor, companyCode, entity, entityId); + var file = new AttachmentFile(AttachmentKind.Generated, generator.FileName(context), generator.MediaType, generator.Code); + return attachments.AddAsync(actor, companyCode, entity, entityId, file, (output, ct) => generator.GenerateAsync(context, output, ct), cancellationToken); + } + + /// Generates a file into a stream without attaching it (print preview, report download). + /// Who asks (needs attachments.read). + /// The company. + /// The entity. + /// The record. + /// The generator. + /// The stream; left open. + /// Cancellation. + /// The file name and media type of what was written. + public async Task<(string FileName, string MediaType)> WriteAsync( + Actor actor, string companyCode, string entity, long entityId, string generatorCode, Stream output, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(output); + var generator = Resolve(entity, generatorCode); + if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, CompanyCodes.Normalize(companyCode), StringComparison.Ordinal)) + { + throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A company user works only in its own company."); + } + + await permissions.DemandAsync(actor, AttachmentService.ReadPermission, cancellationToken).ConfigureAwait(false); + var context = Context(actor, companyCode, entity, entityId); + await generator.GenerateAsync(context, output, cancellationToken).ConfigureAwait(false); + return (MediaTypes.CleanFileName(generator.FileName(context)), generator.MediaType); + } + + private IFileGenerator Resolve(string entity, string generatorCode) + { + ArgumentNullException.ThrowIfNull(entity); + ArgumentNullException.ThrowIfNull(generatorCode); + return registry.Find(generatorCode) is { } generator && generator.Supports(entity) + ? generator + : throw new ValidationFailedException([UnknownGeneratorError]); + } + + private FileGenerationContext Context(Actor actor, string companyCode, string entity, long entityId) => + new(actor, CompanyCodes.Normalize(companyCode), entity, entityId, Italian, clock.GetUtcNow().UtcDateTime); +} diff --git a/src/Khaemhat.Application/Files/MediaTypes.cs b/src/Khaemhat.Application/Files/MediaTypes.cs new file mode 100644 index 0000000..60e1399 --- /dev/null +++ b/src/Khaemhat.Application/Files/MediaTypes.cs @@ -0,0 +1,157 @@ +using System.Text; + +namespace Khaemhat.Application.Files; + +/// How the interface can show a file in the preview (SPEC §9.4: PDF, images, XML, CSV/XLSX). +public enum AttachmentPreview +{ + /// No preview: the file can only be downloaded. + None = 0, + + /// The integrated PDF viewer. + Pdf = 1, + + /// An image, at full size with zoom. + Image = 2, + + /// XML, formatted and indented. + Xml = 3, + + /// CSV, as a grid. + Csv = 4, + + /// XLSX, as a grid. + Xlsx = 5, + + /// Plain text. + Text = 6, +} + +/// +/// Media types and file names of attachments. The media type is taken from the extension when it is known (the type +/// declared by a browser is not trusted), and file names are cleaned so they are safe on every file system and in a +/// ZIP. +/// +public static class MediaTypes +{ + /// The type of unknown content. + public const string OctetStream = "application/octet-stream"; + + /// PDF. + public const string Pdf = "application/pdf"; + + /// CSV. + public const string Csv = "text/csv"; + + /// XLSX. + public const string Xlsx = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; + + /// ZIP. + public const string Zip = "application/zip"; + + /// XML. + public const string Xml = "application/xml"; + + /// The longest file name kept. + public const int MaxFileNameLength = 255; + + private static readonly Dictionary ByExtension = new(StringComparer.OrdinalIgnoreCase) + { + [".pdf"] = Pdf, + [".xml"] = Xml, + [".p7m"] = "application/pkcs7-mime", + [".csv"] = Csv, + [".txt"] = "text/plain", + [".json"] = "application/json", + [".xlsx"] = Xlsx, + [".xls"] = "application/vnd.ms-excel", + [".ods"] = "application/vnd.oasis.opendocument.spreadsheet", + [".docx"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + [".doc"] = "application/msword", + [".odt"] = "application/vnd.oasis.opendocument.text", + [".zip"] = Zip, + [".jpg"] = "image/jpeg", + [".jpeg"] = "image/jpeg", + [".png"] = "image/png", + [".gif"] = "image/gif", + [".webp"] = "image/webp", + [".tif"] = "image/tiff", + [".tiff"] = "image/tiff", + [".eml"] = "message/rfc822", + }; + + /// The media type of a file: from its extension when known, else the declared type when well formed. + /// The file name. + /// The type declared by the client, if any. + /// The media type. + public static string Resolve(string fileName, string? declared = null) + { + if (ByExtension.TryGetValue(Path.GetExtension(fileName ?? string.Empty), out var known)) + { + return known; + } + + return IsWellFormed(declared) ? declared!.Trim().ToLowerInvariant() : OctetStream; + } + + /// How a file can be previewed. + /// The media type. + /// The preview. + public static AttachmentPreview PreviewOf(string? mime) => mime switch + { + Pdf => AttachmentPreview.Pdf, + "image/jpeg" or "image/png" or "image/gif" or "image/webp" => AttachmentPreview.Image, + Xml or "text/xml" => AttachmentPreview.Xml, + Csv => AttachmentPreview.Csv, + Xlsx => AttachmentPreview.Xlsx, + "text/plain" or "application/json" => AttachmentPreview.Text, + _ => AttachmentPreview.None, + }; + + /// + /// Cleans a file name: no folders, no control characters or characters Windows refuses, at most 255 characters + /// keeping the extension; file when nothing is left. + /// + /// The name as received. + /// The clean name. + public static string CleanFileName(string? fileName) + { + var name = (fileName ?? string.Empty).Replace('\\', '/'); + name = name[(name.LastIndexOf('/') + 1)..]; + var builder = new StringBuilder(name.Length); + foreach (var c in name) + { + builder.Append(char.IsControl(c) || c is ':' or '*' or '?' or '"' or '<' or '>' or '|' ? '_' : c); + } + + var clean = builder.ToString().Trim().TrimEnd('.').Trim(); + if (clean.Length > MaxFileNameLength) + { + var extension = Path.GetExtension(clean); + extension = extension.Length > 20 ? string.Empty : extension; + clean = clean[..(MaxFileNameLength - extension.Length)] + extension; + } + + return clean.Length == 0 || clean is "." or ".." ? "file" : clean; + } + + /// The download name of a version: name.pdf for v1, name_v2.pdf after. + /// The attachment name. + /// The version. + /// The file name. + public static string VersionedFileName(string name, int version) + { + ArgumentNullException.ThrowIfNull(name); + if (version <= 1) + { + return name; + } + + var extension = Path.GetExtension(name); + return name[..^extension.Length] + "_v" + version.ToString(System.Globalization.CultureInfo.InvariantCulture) + extension; + } + + private static bool IsWellFormed(string? mime) => + mime is { Length: > 2 and <= 150 } && mime.Count(c => c == '/') == 1 + && mime.Trim().All(c => char.IsAsciiLetterOrDigit(c) || c is '/' or '.' or '+' or '-'); +} diff --git a/src/Khaemhat.Application/Jobs/JobScheduler.cs b/src/Khaemhat.Application/Jobs/JobScheduler.cs index b57bad6..dd428a0 100644 --- a/src/Khaemhat.Application/Jobs/JobScheduler.cs +++ b/src/Khaemhat.Application/Jobs/JobScheduler.cs @@ -49,12 +49,13 @@ public sealed record SystemTaskDefinition(string Code, string Name, string JobTy /// public sealed class JobScheduler { - /// The system tasks of M2. + /// The system tasks (M2, attachments trash from M3). public static readonly IReadOnlyList SystemTasks = [ new("system.sessions-cleanup", "Pulizia sessioni scadute", SessionCleanupJob.JobType, "15 * * * *", 300), new("system.license-check", "Verifica licenza", LicenseCheckJob.JobType, "0 * * * *", 120), new("system.log-retention", "Conservazione del log", LogRetentionJob.JobType, "30 3 * * *", 1800), + new("system.attachments-trash", "Svuotamento cestino allegati", Files.AttachmentTrashPurgeJob.JobType, "45 3 * * *", 1800), ]; private readonly IUnitOfWorkFactory _factory; diff --git a/src/Khaemhat.Core/Files/Attachment.cs b/src/Khaemhat.Core/Files/Attachment.cs new file mode 100644 index 0000000..b9a366d --- /dev/null +++ b/src/Khaemhat.Core/Files/Attachment.cs @@ -0,0 +1,80 @@ +using Khaemhat.Core.Entities; + +namespace Khaemhat.Core.Files; + +/// Where an attachment comes from (SPEC §9.4). +public enum AttachmentKind +{ + /// A file uploaded by a user (the customer's order, a photo, a spreadsheet). + Uploaded = 0, + + /// A file produced by Khaemhat (print PDF, exported rows, courtesy ZIP). + Generated = 1, + + /// An electronic invoice (FatturaPA XML, P7M) issued or received. + EInvoice = 2, + + /// A notification of the exchange system (SDI receipts). + Notification = 3, +} + +/// +/// A file that belongs to exactly one record of the company (attachments, SPEC §9.4): a document, a party, an +/// item... There are no loose attachments. The bytes live in the company folder of the file store under +/// ; the row keeps name, type, size, SHA-256 and version. +/// +/// +/// Versions are numbered per inside the record: a generated file counts per generator code +/// (), so "Rigenera" adds v2, v3...; an uploaded file counts per file name, so +/// uploading a file with the same name again adds a version instead of replacing the previous one (ADR 0021). +/// +public sealed class Attachment : Entity +{ + /// The entity of the owning record, for example sales.invoice or parties.party. + public string Entity { get; set; } = string.Empty; + + /// The identifier of the owning record. + public long EntityId { get; set; } + + /// Where the file comes from. + public AttachmentKind Kind { get; set; } + + /// The file name shown and used for downloads (without the version suffix). + public string Name { get; set; } = string.Empty; + + /// The media type, for example application/pdf. + public string Mime { get; set; } = "application/octet-stream"; + + /// The size in bytes. + public long Size { get; set; } + + /// The SHA-256 of the content, 64 lowercase hexadecimal characters. + public string Sha256 { get; set; } = string.Empty; + + /// The version inside , from 1. + public int Version { get; set; } = 1; + + /// + /// The series the version counts in: gen:<generator code> for generated files, name:<lowercase + /// name> otherwise. Unique with the record and . + /// + public string VersionKey { get; set; } = string.Empty; + + /// The template or procedure that produced the file (generated files), for example demo.test-pdf. + public string? GeneratedBy { get; set; } + + /// Where the bytes are in the company folder of the file store (yyyy/guid). + public string StorageKey { get; set; } = string.Empty; + + /// + /// Who uploaded or generated the file (the actor of the service call). The audit column created_by knows + /// the user only inside an HTTP request; this one is always set. + /// + public string? UserName { get; set; } + + /// A locked file (for example the XML sent to the SDI) cannot be deleted or replaced. + public bool Locked { get; set; } + + /// When the attachment was moved to the company trash; while it is in use. + public DateTime? DeletedAt { get; set; } +} diff --git a/src/Khaemhat.Core/Files/IFileStore.cs b/src/Khaemhat.Core/Files/IFileStore.cs new file mode 100644 index 0000000..becbd0f --- /dev/null +++ b/src/Khaemhat.Core/Files/IFileStore.cs @@ -0,0 +1,172 @@ +namespace Khaemhat.Core.Files; + +/// A file saved in the store. +/// Where it is in the company folder (yyyy/guid); keep it to open or delete the file. +/// The size in bytes. +/// The SHA-256 of the content, lowercase hexadecimal. +public sealed record StoredFile(string Key, long Size, string Sha256); + +/// The space a company uses in the store. +/// How many files. +/// Their total size. +/// The quota of the company; 0 means no quota. +public sealed record FileUsage(long Files, long Bytes, long QuotaBytes) +{ + /// The bytes still available; without quota. + public long RemainingBytes => QuotaBytes <= 0 ? long.MaxValue : Math.Max(0, QuotaBytes - Bytes); + + /// Whether the company uses more than its quota. + public bool IsOverQuota => QuotaBytes > 0 && Bytes > QuotaBytes; +} + +/// The limits applied while a file is written. +/// The largest file accepted; 0 means no limit. +/// The space a company may use in all; 0 means no quota. +public sealed record FileLimits(long MaxBytes, long QuotaBytes) +{ + /// The default size limit of an uploaded file (SPEC §9.4): 25 MB. + public const long DefaultMaxBytes = 25L * 1024 * 1024; + + /// No limit at all (generated files are bounded by their generator). + public static FileLimits None { get; } = new(0, 0); +} + +/// Why the store refused a file. is one of the constants of this class. +public sealed class FileStoreException : Exception +{ + /// The file is larger than . + public const string TooLarge = "file_too_large"; + + /// The file would take the company over its quota. + public const string QuotaExceeded = "file_quota_exceeded"; + + /// The scanner () rejected the file. + public const string Rejected = "file_rejected"; + + /// The file does not exist in the store. + public const string NotFound = "file_not_found"; + + /// Creates the exception. + public FileStoreException() + : this(NotFound, "File store error.") + { + } + + /// Creates the exception. + /// The message. + public FileStoreException(string message) + : this(NotFound, message) + { + } + + /// Creates the exception. + /// The message. + /// The cause. + public FileStoreException(string message, Exception innerException) + : base(message, innerException) => Code = NotFound; + + /// Creates the exception. + /// The error code. + /// The message. + public FileStoreException(string code, string message) + : base(message) => Code = code; + + /// The error code. + public string Code { get; } +} + +/// +/// A file being written to the store: write the content to , then call +/// . Disposing without committing discards what was written. +/// +public interface IFileStoreWriter : IAsyncDisposable +{ + /// The write-only, non-seekable stream that receives the content (it counts bytes and computes SHA-256). + /// Writing goes past (code ). + Stream Content { get; } + + /// Completes the file: checks quota and scanner, then makes it visible under its key. + /// Cancellation. + /// The stored file. + /// The file is refused. + Task CommitAsync(CancellationToken cancellationToken = default); +} + +/// +/// Where attachment bytes live (SPEC §9.4): one folder per company, one subfolder per year. Writes are streamed and +/// atomic (a partial file is never visible under its key); every key belongs to one company and cannot reach outside +/// its folder. +/// +public interface IFileStore +{ + /// Saves a file read from a stream. + /// The company. + /// The content, read to the end. + /// The limits; for the store defaults. + /// Cancellation. + /// The stored file. + /// The file is refused (size, quota, scanner). + Task SaveAsync(string companyCode, Stream content, FileLimits? limits = null, CancellationToken cancellationToken = default); + + /// Starts a file that the caller writes (generators, ZIP packages). + /// The company. + /// The limits; for the store defaults. + /// Cancellation. + /// The writer; dispose it in every case. + Task CreateAsync(string companyCode, FileLimits? limits = null, CancellationToken cancellationToken = default); + + /// Opens a file for reading. + /// The company. + /// The key returned when the file was saved. + /// A read-only seekable stream; dispose it. + /// The file does not exist (code ). + Stream OpenRead(string companyCode, string key); + + /// Whether a file exists. + /// The company. + /// The key. + /// if it exists. + bool Exists(string companyCode, string key); + + /// Deletes a file; nothing happens when it does not exist. + /// The company. + /// The key. + /// if a file was deleted. + bool Delete(string companyCode, string key); + + /// The space the company uses, with its quota. + /// The company. + /// The quota to report; for the store default. + /// Cancellation. + /// The usage. + Task GetUsageAsync(string companyCode, long? quotaBytes = null, CancellationToken cancellationToken = default); + + /// Removes the partial files (.part) left by writes interrupted more than ago. + /// The company. + /// How old a partial file must be. + /// How many were removed. + int DeleteAbandonedParts(string companyCode, TimeSpan olderThan); +} + +/// The verdict of a scanner. +/// Whether the file may be stored. +/// Why it was refused (for example the name of the threat). +public sealed record FileScanResult(bool Clean, string? Reason = null) +{ + /// The file may be stored. + public static FileScanResult Ok { get; } = new(true); +} + +/// +/// The hook for an antivirus (SPEC §9.4): Khaemhat includes none, the default implementation accepts every file. It +/// runs on the complete file before it becomes visible. +/// +public interface IFileScanner +{ + /// Scans a file. + /// The company. + /// The content, readable from the start. + /// Cancellation. + /// The verdict. + ValueTask ScanAsync(string companyCode, Stream content, CancellationToken cancellationToken = default); +} diff --git a/src/Khaemhat.Data/CompanyDatabase/CompanyMaps.cs b/src/Khaemhat.Data/CompanyDatabase/CompanyMaps.cs index eedb93f..4d7af8a 100644 --- a/src/Khaemhat.Data/CompanyDatabase/CompanyMaps.cs +++ b/src/Khaemhat.Data/CompanyDatabase/CompanyMaps.cs @@ -1,3 +1,4 @@ +using Khaemhat.Core.Files; using Khaemhat.Core.Instance; using Khaemhat.Core.Security; using Khaemhat.Data.Mapping; @@ -106,3 +107,21 @@ public sealed class UserSettingMap : EntityMap Map(x => x.Key).MaxLength(200); } } + +/// Map of to attachments. +public sealed class AttachmentMap : EntityMap +{ + /// Creates the map. + public AttachmentMap() + { + ToTable("attachments"); + Map(x => x.Entity).MaxLength(100); + Map(x => x.Name).MaxLength(255); + Map(x => x.Mime).MaxLength(150); + Map(x => x.Sha256).MaxLength(64); + Map(x => x.VersionKey).MaxLength(300); + Map(x => x.GeneratedBy).MaxLength(100); + Map(x => x.StorageKey).MaxLength(60); + Map(x => x.UserName).MaxLength(100); + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_007_CreateAttachments.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_007_CreateAttachments.cs new file mode 100644 index 0000000..5082d00 --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_007_CreateAttachments.cs @@ -0,0 +1,37 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// The attachments of the company records, uploaded and generated (SPEC §9.4, ADR 0021). +[Migration(20261111_007, "create_attachments")] +public sealed class M20261111_007_CreateAttachments : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("attachments", t => + { + t.Id(); + t.String("entity", 100).NotNull(); + t.Int64("entity_id").NotNull(); + t.String("kind", 40).NotNull(); + t.String("name", 255).NotNull(); + t.String("mime", 150).NotNull(); + t.Int64("size").NotNull(); + t.String("sha256", 64).NotNull(); + t.Int32("version").NotNull(); + t.String("version_key", 300).NotNull(); + t.String("generated_by", 100); + t.String("storage_key", 60).NotNull(); + t.String("user_name", 100); + t.Bool("locked").NotNull().Default(false); + t.DateTimeUtc("deleted_at"); + t.AuditColumns(); + t.Index("ix_attachments_entity_entity_id", "entity", "entity_id"); + t.Unique("ux_attachments_entity_entity_id_version_key_version", "entity", "entity_id", "version_key", "version"); + t.Index("ix_attachments_deleted_at", "deleted_at"); + }); + } +} diff --git a/src/Khaemhat.Infrastructure/Files/AsyncOutputBuffer.cs b/src/Khaemhat.Infrastructure/Files/AsyncOutputBuffer.cs new file mode 100644 index 0000000..963a371 --- /dev/null +++ b/src/Khaemhat.Infrastructure/Files/AsyncOutputBuffer.cs @@ -0,0 +1,82 @@ +namespace Khaemhat.Infrastructure.Files; + +/// +/// Sits between and an output that refuses synchronous writes (an +/// ASP.NET Core response). The archive still writes some parts synchronously (entry trailers on dispose, the central +/// directory): those bytes are kept here and sent with the next asynchronous call or , while +/// the bulk of the data, written asynchronously, goes straight through. Memory stays bounded by the small synchronous +/// pieces, so archives are still streamed. +/// +/// The real output. +internal sealed class AsyncOutputBuffer(Stream output) : Stream +{ + private readonly MemoryStream _pending = new(); + + public override bool CanRead => false; + + public override bool CanSeek => false; + + public override bool CanWrite => true; + + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + /// Sends the bytes written synchronously to the output. + /// Cancellation. + /// A task. + public async Task DrainAsync(CancellationToken cancellationToken = default) + { + if (_pending.Length > 0) + { + await output.WriteAsync(_pending.GetBuffer().AsMemory(0, (int)_pending.Length), cancellationToken).ConfigureAwait(false); + _pending.SetLength(0); + } + } + + public override void Write(byte[] buffer, int offset, int count) => _pending.Write(buffer, offset, count); + + public override void Write(ReadOnlySpan buffer) => _pending.Write(buffer); + + public override void WriteByte(byte value) => _pending.WriteByte(value); + + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + await DrainAsync(cancellationToken).ConfigureAwait(false); + await output.WriteAsync(buffer, cancellationToken).ConfigureAwait(false); + } + + /// Does nothing: synchronous flushes would reach the output synchronously. + public override void Flush() + { + } + + public override async Task FlushAsync(CancellationToken cancellationToken) + { + await DrainAsync(cancellationToken).ConfigureAwait(false); + await output.FlushAsync(cancellationToken).ConfigureAwait(false); + } + + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _pending.Dispose(); + } + + base.Dispose(disposing); + } +} diff --git a/src/Khaemhat.Infrastructure/Files/CsvWriter.cs b/src/Khaemhat.Infrastructure/Files/CsvWriter.cs new file mode 100644 index 0000000..804e83f --- /dev/null +++ b/src/Khaemhat.Infrastructure/Files/CsvWriter.cs @@ -0,0 +1,310 @@ +using System.Globalization; +using System.Text; + +namespace Khaemhat.Infrastructure.Files; + +/// How numbers and dates are written in a CSV file. +public enum CsvNumberFormat +{ + /// Italian Excel: decimal comma (1234,5), dates dd/MM/yyyy, booleans VERO/FALSO. + Italian = 0, + + /// Machine readable: decimal point (1234.5), ISO 8601 dates, booleans true/false. + Invariant = 1, +} + +/// The options of a . The defaults suit Excel in Italian (ADR 0021). +public sealed record CsvOptions +{ + /// The field separator: ; by default, because Italian Excel uses the comma for decimals. + public char Separator { get; init; } = ';'; + + /// Whether the file starts with the UTF-8 byte order mark, which Excel needs to read accented letters. + public bool WriteByteOrderMark { get; init; } = true; + + /// How numbers, dates and booleans are formatted. + public CsvNumberFormat NumberFormat { get; init; } = CsvNumberFormat.Italian; + + /// + /// Whether text cells that a spreadsheet would read as a formula (starting with =, +, -, + /// @, tab or carriage return) get a leading apostrophe (CSV injection, OWASP). Numbers are never changed. + /// + public bool ProtectFormulas { get; init; } = true; + + /// The line terminator: CRLF as RFC 4180 says. + public string NewLine { get; init; } = "\r\n"; + + /// The Italian Excel defaults. + public static CsvOptions Italian { get; } = new(); + + /// Comma separator, invariant numbers, no byte order mark: for other programs. + public static CsvOptions Invariant { get; } = new() { Separator = ',', NumberFormat = CsvNumberFormat.Invariant, WriteByteOrderMark = false }; +} + +/// +/// Writes CSV files (RFC 4180) row by row (SPEC §2, §9.4). Fields with separator, quotes or line breaks are quoted and +/// quotes doubled. Rows are buffered in memory and written to the stream when the buffer grows past a few KB: use the +/// Async methods when the stream is an HTTP response, where synchronous writes are not allowed. +/// +/// +/// +/// await using var csv = new CsvWriter(response.Body); +/// await csv.WriteRowAsync(["Codice", "Descrizione", "Importo"]); +/// await csv.WriteRowAsync(["A1", "Vite M4", 12.5m]); +/// +/// +public sealed class CsvWriter : IDisposable, IAsyncDisposable +{ + private const int FlushThreshold = 16 * 1024; + private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT"); + private static readonly UTF8Encoding Utf8 = new(encoderShouldEmitUTF8Identifier: false); + + private readonly Stream _output; + private readonly bool _leaveOpen; + private readonly StringBuilder _buffer = new(); + private bool _rowHasFields; + private bool _preambleWritten; + private bool _disposed; + + /// Creates a writer. + /// The stream that receives the file. + /// The options; for . + /// Whether to leave open on dispose. + public CsvWriter(Stream output, CsvOptions? options = null, bool leaveOpen = false) + { + ArgumentNullException.ThrowIfNull(output); + _output = output; + _leaveOpen = leaveOpen; + Options = options ?? CsvOptions.Italian; + if (Options.Separator is '"' or '\r' or '\n') + { + throw new ArgumentException("The separator cannot be a quote or a line break.", nameof(options)); + } + } + + /// The options. + public CsvOptions Options { get; } + + /// The number of rows completed. + public long RowCount { get; private set; } + + /// Formats a text field: formula protection, then quoting when needed. + /// The text. + /// The options. + /// The field as written in the file. + public static string EscapeText(string? value, CsvOptions options) + { + ArgumentNullException.ThrowIfNull(options); + if (string.IsNullOrEmpty(value)) + { + return string.Empty; + } + + if (options.ProtectFormulas && value[0] is '=' or '+' or '-' or '@' or '\t' or '\r') + { + value = "'" + value; + } + + return Quote(value, options.Separator); + } + + /// Formats a value as it would be written (numbers and dates by ). + /// The value. + /// The options. + /// The field as written in the file. + public static string FormatValue(object? value, CsvOptions options) + { + ArgumentNullException.ThrowIfNull(options); + var culture = options.NumberFormat == CsvNumberFormat.Italian ? Italian : CultureInfo.InvariantCulture; + var italian = options.NumberFormat == CsvNumberFormat.Italian; + var text = value switch + { + null => null, + string s => s, + bool b => italian ? (b ? "VERO" : "FALSO") : (b ? "true" : "false"), + DateOnly d => d.ToString(italian ? "dd/MM/yyyy" : "yyyy-MM-dd", CultureInfo.InvariantCulture), + DateTime d when d.TimeOfDay == TimeSpan.Zero => d.ToString(italian ? "dd/MM/yyyy" : "yyyy-MM-dd", CultureInfo.InvariantCulture), + DateTime d => d.ToString(italian ? "dd/MM/yyyy HH:mm:ss" : "yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture), + DateTimeOffset d => d.ToString(italian ? "dd/MM/yyyy HH:mm:ss" : "yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture), + decimal m => m.ToString("0.############################", culture), + double x when double.IsFinite(x) => x.ToString("0.###############", culture), + float x when float.IsFinite(x) => x.ToString("0.#######", culture), + double or float => string.Empty, + IFormattable f => f.ToString(null, culture), + _ => value.ToString(), + }; + + // Only text can carry a formula: numbers, dates and booleans are written as they are. + return value is string or char or Enum || value is not IFormattable and not bool + ? EscapeText(text, options) + : Quote(text ?? string.Empty, options.Separator); + } + + /// Adds a field to the current row. + /// Text, number, date, boolean or (empty field). + /// This writer. + public CsvWriter WriteField(object? value) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (_rowHasFields) + { + _buffer.Append(Options.Separator); + } + + _buffer.Append(FormatValue(value, Options)); + _rowHasFields = true; + return this; + } + + /// Ends the current row; writes to the stream synchronously when the buffer is large. + public void EndRow() + { + CompleteRow(); + if (_buffer.Length >= FlushThreshold) + { + Flush(); + } + } + + /// Ends the current row; writes to the stream when the buffer is large. + /// Cancellation. + /// A task. + public async ValueTask EndRowAsync(CancellationToken cancellationToken = default) + { + CompleteRow(); + if (_buffer.Length >= FlushThreshold) + { + await FlushAsync(cancellationToken).ConfigureAwait(false); + } + } + + /// Writes a whole row (synchronous stream). + /// The fields. + public void WriteRow(params IEnumerable values) + { + ArgumentNullException.ThrowIfNull(values); + foreach (var value in values) + { + WriteField(value); + } + + EndRow(); + } + + /// Writes a whole row. + /// The fields. + /// Cancellation. + /// A task. + public ValueTask WriteRowAsync(IEnumerable values, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(values); + foreach (var value in values) + { + WriteField(value); + } + + return EndRowAsync(cancellationToken); + } + + /// Writes the buffered rows to the stream synchronously. + public void Flush() + { + var bytes = TakeBytes(); + if (bytes.Length > 0) + { + _output.Write(bytes); + } + + _output.Flush(); + } + + /// Writes the buffered rows to the stream. + /// Cancellation. + /// A task. + public async Task FlushAsync(CancellationToken cancellationToken = default) + { + var bytes = TakeBytes(); + if (bytes.Length > 0) + { + await _output.WriteAsync(bytes, cancellationToken).ConfigureAwait(false); + } + + await _output.FlushAsync(cancellationToken).ConfigureAwait(false); + } + + /// Ends a pending row, writes the buffer synchronously and closes the stream unless left open. + public void Dispose() + { + if (_disposed) + { + return; + } + + if (_rowHasFields) + { + CompleteRow(); + } + + Flush(); + _disposed = true; + if (!_leaveOpen) + { + _output.Dispose(); + } + } + + /// Ends a pending row, writes the buffer and closes the stream unless left open. + /// A task. + public async ValueTask DisposeAsync() + { + if (_disposed) + { + return; + } + + if (_rowHasFields) + { + CompleteRow(); + } + + await FlushAsync().ConfigureAwait(false); + _disposed = true; + if (!_leaveOpen) + { + await _output.DisposeAsync().ConfigureAwait(false); + } + } + + private static string Quote(string value, char separator) + { + var needsQuotes = value.Length > 0 + && (value.Contains(separator, StringComparison.Ordinal) || value.AsSpan().IndexOfAny("\"\r\n") >= 0 + || char.IsWhiteSpace(value[0]) || char.IsWhiteSpace(value[^1])); + return needsQuotes ? "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"" : value; + } + + private void CompleteRow() + { + ObjectDisposedException.ThrowIf(_disposed, this); + _buffer.Append(Options.NewLine); + _rowHasFields = false; + RowCount++; + } + + private byte[] TakeBytes() + { + var preamble = !_preambleWritten && Options.WriteByteOrderMark ? Encoding.UTF8.Preamble.ToArray() : []; + _preambleWritten = true; + if (_buffer.Length == 0 && preamble.Length == 0) + { + return []; + } + + var text = _buffer.ToString(); + _buffer.Clear(); + var bytes = new byte[preamble.Length + Utf8.GetByteCount(text)]; + preamble.CopyTo(bytes, 0); + Utf8.GetBytes(text, 0, text.Length, bytes, preamble.Length); + return bytes; + } +} diff --git a/src/Khaemhat.Infrastructure/Files/PdfFont.cs b/src/Khaemhat.Infrastructure/Files/PdfFont.cs new file mode 100644 index 0000000..29957d3 --- /dev/null +++ b/src/Khaemhat.Infrastructure/Files/PdfFont.cs @@ -0,0 +1,317 @@ +using System.Text; + +namespace Khaemhat.Infrastructure.Files; + +/// +/// The standard Type1 fonts every PDF reader has (PDF 1.7 §9.6.2.2), with WinAnsiEncoding so that Italian +/// letters and the euro sign print. Symbol and ZapfDingbats are not offered: they have no Latin encoding. +/// +public enum PdfFont +{ + /// Helvetica. + Helvetica = 0, + + /// Helvetica bold. + HelveticaBold = 1, + + /// Helvetica oblique. + HelveticaOblique = 2, + + /// Helvetica bold oblique. + HelveticaBoldOblique = 3, + + /// Times roman. + TimesRoman = 4, + + /// Times bold (measured with the Times roman widths). + TimesBold = 5, + + /// Times italic (measured with the Times roman widths). + TimesItalic = 6, + + /// Times bold italic (measured with the Times roman widths). + TimesBoldItalic = 7, + + /// Courier: every character is 600/1000 em wide. + Courier = 8, + + /// Courier bold. + CourierBold = 9, + + /// Courier oblique. + CourierOblique = 10, + + /// Courier bold oblique. + CourierBoldOblique = 11, +} + +/// +/// Text measuring and line breaking for the standard fonts, from the Adobe font metrics (AFM) widths in thousandths of +/// an em, and the WinAnsiEncoding (Windows-1252) used to write text. Helvetica, Helvetica bold and Times roman +/// widths are exact; the Times bold and italic faces reuse the roman widths (a close approximation); Courier is fixed +/// width. +/// +public static class PdfTextLayout +{ + // Widths for codes 32..126. + private static readonly int[] HelveticaAscii = + [ + 278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, + 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, + 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, + 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, + 333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, + 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584, + ]; + + private static readonly int[] HelveticaBoldAscii = + [ + 278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278, + 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611, + 975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778, + 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556, + 333, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611, + 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584, + ]; + + private static readonly int[] TimesAscii = + [ + 250, 333, 408, 500, 500, 833, 778, 180, 333, 333, 500, 564, 250, 333, 250, 278, + 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 278, 278, 564, 564, 564, 444, + 921, 722, 667, 667, 722, 611, 556, 722, 722, 333, 389, 722, 611, 889, 722, 722, + 556, 722, 667, 556, 611, 722, 722, 944, 722, 722, 611, 333, 278, 333, 469, 500, + 333, 444, 500, 444, 500, 444, 333, 500, 500, 278, 278, 500, 278, 778, 500, 500, + 500, 500, 333, 389, 278, 500, 500, 722, 500, 500, 444, 480, 200, 480, 541, + ]; + + // Widths for codes 128..159 (0 = not defined in WinAnsiEncoding). + private static readonly int[] HelveticaWin = + [ + 556, 0, 222, 556, 333, 1000, 556, 556, 333, 1000, 667, 333, 1000, 0, 611, 0, + 0, 222, 222, 333, 333, 350, 556, 1000, 333, 1000, 500, 333, 944, 0, 500, 667, + ]; + + private static readonly int[] HelveticaBoldWin = + [ + 556, 0, 278, 556, 500, 1000, 556, 556, 333, 1000, 667, 333, 1000, 0, 611, 0, + 0, 278, 278, 500, 500, 350, 556, 1000, 333, 1000, 556, 333, 944, 0, 500, 667, + ]; + + private static readonly int[] TimesWin = + [ + 500, 0, 333, 500, 444, 1000, 500, 500, 333, 1000, 556, 333, 889, 0, 611, 0, + 0, 333, 333, 444, 444, 350, 500, 1000, 333, 980, 389, 333, 722, 0, 444, 722, + ]; + + // Widths for codes 160..255. + private static readonly int[] HelveticaLatin = + [ + 278, 333, 556, 556, 556, 556, 260, 556, 333, 737, 370, 556, 584, 333, 737, 333, + 400, 584, 333, 333, 333, 556, 537, 278, 333, 333, 365, 556, 834, 834, 834, 611, + 667, 667, 667, 667, 667, 667, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278, + 722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611, + 556, 556, 556, 556, 556, 556, 889, 500, 556, 556, 556, 556, 278, 278, 278, 278, + 556, 556, 556, 556, 556, 556, 556, 584, 611, 556, 556, 556, 556, 500, 556, 500, + ]; + + private static readonly int[] HelveticaBoldLatin = + [ + 278, 333, 556, 556, 556, 556, 280, 556, 333, 737, 370, 556, 584, 333, 737, 333, + 400, 584, 333, 333, 333, 611, 556, 278, 333, 333, 365, 556, 834, 834, 834, 611, + 722, 722, 722, 722, 722, 722, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278, + 722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611, + 556, 556, 556, 556, 556, 556, 889, 556, 556, 556, 556, 556, 278, 278, 278, 278, + 611, 611, 611, 611, 611, 611, 611, 584, 611, 611, 611, 611, 611, 556, 611, 556, + ]; + + private static readonly int[] TimesLatin = + [ + 250, 333, 500, 500, 500, 500, 200, 500, 333, 760, 276, 500, 564, 333, 760, 333, + 400, 564, 300, 300, 333, 500, 453, 250, 333, 300, 310, 500, 750, 750, 750, 444, + 722, 722, 722, 722, 722, 722, 889, 667, 611, 611, 611, 611, 333, 333, 333, 333, + 722, 722, 722, 722, 722, 722, 722, 564, 722, 722, 722, 722, 722, 722, 556, 500, + 444, 444, 444, 444, 444, 444, 667, 444, 444, 444, 444, 444, 278, 278, 278, 278, + 500, 500, 500, 500, 500, 500, 500, 564, 500, 500, 500, 500, 500, 500, 500, 500, + ]; + + // Full tables for codes 0..255. + private static readonly int[] Helvetica = Table(HelveticaAscii, HelveticaWin, HelveticaLatin); + private static readonly int[] HelveticaBold = Table(HelveticaBoldAscii, HelveticaBoldWin, HelveticaBoldLatin); + private static readonly int[] Times = Table(TimesAscii, TimesWin, TimesLatin); + + // Unicode to WinAnsiEncoding for the codes 128..159 that differ from Latin-1. + private static readonly Dictionary WinAnsiSpecials = new() + { + ['€'] = 0x80, ['‚'] = 0x82, ['ƒ'] = 0x83, ['„'] = 0x84, ['…'] = 0x85, ['†'] = 0x86, ['‡'] = 0x87, ['ˆ'] = 0x88, + ['‰'] = 0x89, ['Š'] = 0x8A, ['‹'] = 0x8B, ['Œ'] = 0x8C, ['Ž'] = 0x8E, ['‘'] = 0x91, ['’'] = 0x92, ['“'] = 0x93, + ['”'] = 0x94, ['•'] = 0x95, ['–'] = 0x96, ['—'] = 0x97, ['˜'] = 0x98, ['™'] = 0x99, ['š'] = 0x9A, ['›'] = 0x9B, + ['œ'] = 0x9C, ['ž'] = 0x9E, ['Ÿ'] = 0x9F, + }; + + /// The PostScript name of a font, as written in /BaseFont. + /// The font. + /// The name, for example Helvetica-Bold. + public static string BaseFontName(PdfFont font) => font switch + { + PdfFont.Helvetica => "Helvetica", + PdfFont.HelveticaBold => "Helvetica-Bold", + PdfFont.HelveticaOblique => "Helvetica-Oblique", + PdfFont.HelveticaBoldOblique => "Helvetica-BoldOblique", + PdfFont.TimesRoman => "Times-Roman", + PdfFont.TimesBold => "Times-Bold", + PdfFont.TimesItalic => "Times-Italic", + PdfFont.TimesBoldItalic => "Times-BoldItalic", + PdfFont.Courier => "Courier", + PdfFont.CourierBold => "Courier-Bold", + PdfFont.CourierOblique => "Courier-Oblique", + PdfFont.CourierBoldOblique => "Courier-BoldOblique", + _ => throw new ArgumentOutOfRangeException(nameof(font), font, "Unknown font."), + }; + + /// + /// Encodes text in WinAnsiEncoding: ASCII, Latin-1 letters (àèéìòù...), the euro sign and the typographic + /// quotes and dashes. Line breaks and tabs become spaces; characters the encoding lacks become ?. + /// + /// The text. + /// One byte per character. + public static byte[] EncodeWinAnsi(string? text) + { + if (string.IsNullOrEmpty(text)) + { + return []; + } + + var bytes = new byte[text.Length]; + for (var i = 0; i < text.Length; i++) + { + bytes[i] = ToWinAnsi(text[i]); + } + + return bytes; + } + + /// The width of a character code in thousandths of an em. + /// The WinAnsiEncoding code. + /// The font. + /// The width. + public static int GlyphWidth(byte code, PdfFont font) => font switch + { + PdfFont.Helvetica or PdfFont.HelveticaOblique => Helvetica[code], + PdfFont.HelveticaBold or PdfFont.HelveticaBoldOblique => HelveticaBold[code], + PdfFont.TimesRoman or PdfFont.TimesBold or PdfFont.TimesItalic or PdfFont.TimesBoldItalic => Times[code], + _ => code >= 32 ? 600 : 0, + }; + + /// The width of a text in points. + /// The text. + /// The font. + /// The font size in points. + /// The width. + public static double Measure(string? text, PdfFont font, double size) + { + var total = 0; + foreach (var code in EncodeWinAnsi(text)) + { + total += GlyphWidth(code, font); + } + + return total * size / 1000.0; + } + + /// + /// Breaks a text into lines no wider than : at line breaks, then between words; a word + /// longer than a line is cut. + /// + /// The text. + /// The font. + /// The font size. + /// The line width in points. + /// The lines (one empty line for an empty text). + public static IReadOnlyList Wrap(string? text, PdfFont font, double size, double maxWidth) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxWidth); + var lines = new List(); + foreach (var paragraph in (text ?? string.Empty).Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n')) + { + var line = new StringBuilder(); + foreach (var word in paragraph.Split(' ', StringSplitOptions.RemoveEmptyEntries)) + { + var candidate = line.Length == 0 ? word : line + " " + word; + if (Measure(candidate, font, size) <= maxWidth) + { + line.Clear().Append(candidate); + continue; + } + + if (line.Length > 0) + { + lines.Add(line.ToString()); + line.Clear(); + } + + // A word wider than the line is cut where it no longer fits. + var rest = word; + while (Measure(rest, font, size) > maxWidth && rest.Length > 1) + { + var cut = rest.Length - 1; + while (cut > 1 && Measure(rest[..cut], font, size) > maxWidth) + { + cut--; + } + + lines.Add(rest[..cut]); + rest = rest[cut..]; + } + + line.Append(rest); + } + + lines.Add(line.ToString()); + } + + return lines; + } + + /// Shortens a text with an ellipsis so that it fits a width (table cells). + /// The text. + /// The font. + /// The font size. + /// The width in points. + /// The text, shortened if needed. + public static string Fit(string? text, PdfFont font, double size, double maxWidth) + { + text ??= string.Empty; + if (Measure(text, font, size) <= maxWidth) + { + return text; + } + + for (var length = text.Length - 1; length > 0; length--) + { + var candidate = text[..length].TrimEnd() + "…"; + if (Measure(candidate, font, size) <= maxWidth) + { + return candidate; + } + } + + return string.Empty; + } + + private static byte ToWinAnsi(char c) => c switch + { + '\t' or '\r' or '\n' => (byte)' ', + >= ' ' and <= '~' => (byte)c, + >= ' ' and <= 'ÿ' => (byte)c, + _ => WinAnsiSpecials.TryGetValue(c, out var code) ? code : (byte)'?', + }; + + private static int[] Table(int[] ascii, int[] win, int[] latin) + { + var table = new int[256]; + ascii.CopyTo(table, 32); + win.CopyTo(table, 128); + latin.CopyTo(table, 160); + return table; + } +} diff --git a/src/Khaemhat.Infrastructure/Files/PdfWriter.cs b/src/Khaemhat.Infrastructure/Files/PdfWriter.cs new file mode 100644 index 0000000..f310170 --- /dev/null +++ b/src/Khaemhat.Infrastructure/Files/PdfWriter.cs @@ -0,0 +1,679 @@ +using System.Globalization; +using System.IO.Compression; +using System.Text; + +namespace Khaemhat.Infrastructure.Files; + +/// An RGB colour. +/// Red, 0-255. +/// Green, 0-255. +/// Blue, 0-255. +public readonly record struct PdfColor(byte R, byte G, byte B) +{ + /// Black. + public static PdfColor Black { get; } = new(0, 0, 0); + + /// White. + public static PdfColor White { get; } = new(255, 255, 255); + + /// A grey. + /// 0 (black) to 255 (white). + /// The colour. + public static PdfColor Gray(byte level) => new(level, level, level); + + /// A colour from #RRGGBB. + /// The colour, with or without #. + /// The colour. + public static PdfColor FromHex(string hex) + { + ArgumentNullException.ThrowIfNull(hex); + var value = hex.TrimStart('#'); + if (value.Length != 6 || !int.TryParse(value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var rgb)) + { + throw new FormatException("A colour is written #RRGGBB."); + } + + return new PdfColor((byte)(rgb >> 16), (byte)(rgb >> 8), (byte)rgb); + } +} + +/// The document information dictionary. +public sealed record PdfDocumentInfo +{ + /// The title. + public string? Title { get; init; } + + /// The author (the company or the user). + public string? Author { get; init; } + + /// The subject. + public string? Subject { get; init; } + + /// Keywords. + public string? Keywords { get; init; } + + /// The program that created the content. + public string Creator { get; init; } = "Khaemhat"; + + /// When the document was created; now when omitted. + public DateTimeOffset? CreationDate { get; init; } +} + +/// What the header of a JPEG file says. +/// Width in pixels. +/// Height in pixels. +/// 1 (grey), 3 (RGB/YCbCr) or 4 (CMYK). +/// Bits per component, normally 8. +/// An Adobe CMYK JPEG, whose components are stored inverted. +public sealed record JpegInfo(int Width, int Height, int Components, int BitsPerComponent, bool AdobeInverted) +{ + /// + /// Reads the size and components from the start-of-frame marker of a JPEG file, walking the marker segments from + /// the start-of-image marker. + /// + /// The file. + /// The header. + /// The data is not a JPEG file the PDF can embed. + public static JpegInfo Read(ReadOnlySpan jpeg) + { + if (jpeg.Length < 4 || jpeg[0] != 0xFF || jpeg[1] != 0xD8) + { + throw new InvalidDataException("Not a JPEG file (no SOI marker)."); + } + + var adobe = false; + var i = 2; + while (i < jpeg.Length) + { + if (jpeg[i] != 0xFF) + { + throw new InvalidDataException("Corrupt JPEG file (marker expected)."); + } + + while (i < jpeg.Length && jpeg[i] == 0xFF) + { + i++; + } + + if (i >= jpeg.Length) + { + break; + } + + var marker = jpeg[i++]; + if (marker is 0x01 or 0xD8 or (>= 0xD0 and <= 0xD7)) + { + continue; + } + + if (marker is 0xD9 or 0xDA) + { + break; + } + + if (i + 2 > jpeg.Length) + { + break; + } + + var length = (jpeg[i] << 8) | jpeg[i + 1]; + if (length < 2 || i + length > jpeg.Length) + { + throw new InvalidDataException("Corrupt JPEG file (segment length)."); + } + + if (marker is >= 0xC0 and <= 0xCF and not 0xC4 and not 0xC8 and not 0xCC) + { + if (length < 8) + { + throw new InvalidDataException("Corrupt JPEG file (frame header)."); + } + + var bits = jpeg[i + 2]; + var height = (jpeg[i + 3] << 8) | jpeg[i + 4]; + var width = (jpeg[i + 5] << 8) | jpeg[i + 6]; + var components = jpeg[i + 7]; + if (width == 0 || height == 0 || components is not (1 or 3 or 4)) + { + throw new InvalidDataException("Unsupported JPEG file (size or components)."); + } + + return new JpegInfo(width, height, components, bits, adobe && components == 4); + } + + if (marker == 0xEE && length >= 7 && jpeg.Slice(i + 2, 5).SequenceEqual("Adobe"u8)) + { + adobe = true; + } + + i += length; + } + + throw new InvalidDataException("Not a JPEG file the PDF can embed (no frame header)."); + } +} + +/// An image added to a document; draw it on any page with . +public sealed class PdfImage +{ + internal PdfImage(int objectNumber, string name, JpegInfo info) + { + ObjectNumber = objectNumber; + Name = name; + Info = info; + } + + /// Width in pixels. + public int Width => Info.Width; + + /// Height in pixels. + public int Height => Info.Height; + + /// The JPEG header. + public JpegInfo Info { get; } + + internal int ObjectNumber { get; } + + internal string Name { get; } +} + +/// +/// A page being drawn. Coordinates are PDF points (1/72 inch) from the bottom-left corner; text is placed by +/// its baseline. Use to measure and wrap text. +/// +public sealed class PdfPage +{ + private readonly StringBuilder _content = new(); + + internal PdfPage(int number, double width, double height) + { + Number = number; + Width = width; + Height = height; + } + + /// The page number, from 1. + public int Number { get; } + + /// The width in points. + public double Width { get; } + + /// The height in points. + public double Height { get; } + + internal SortedSet Fonts { get; } = []; + + internal SortedDictionary Images { get; } = new(StringComparer.Ordinal); + + internal bool IsClosed { get; set; } + + /// Writes a line of text. + /// The text (one line; see ). + /// The left edge. + /// The baseline. + /// The font. + /// The size in points. + /// The colour; black when omitted. + public void DrawText(string? text, double x, double y, PdfFont font, double size, PdfColor? color = null) + { + Check(); + var bytes = PdfTextLayout.EncodeWinAnsi(text); + if (bytes.Length == 0) + { + return; + } + + Fonts.Add(font); + var c = color ?? PdfColor.Black; + _content.Append("q ").Append(Color(c)).Append(" rg BT /").Append(PdfWriter.FontResource(font)).Append(' ').Append(Num(size)) + .Append(" Tf 1 0 0 1 ").Append(Num(x)).Append(' ').Append(Num(y)).Append(" Tm ("); + foreach (var b in bytes) + { + switch (b) + { + case (byte)'(' or (byte)')' or (byte)'\\': + _content.Append('\\').Append((char)b); + break; + case < 0x20 or >= 0x7F: + _content.Append('\\').Append(Convert.ToString(b, 8).PadLeft(3, '0')); + break; + default: + _content.Append((char)b); + break; + } + } + + _content.Append(") Tj ET Q\n"); + } + + /// Writes a line of text ending at (amounts in a column). + /// The text. + /// The right edge. + /// The baseline. + /// The font. + /// The size. + /// The colour. + public void DrawTextRight(string? text, double right, double y, PdfFont font, double size, PdfColor? color = null) => + DrawText(text, right - PdfTextLayout.Measure(text, font, size), y, font, size, color); + + /// Writes a line of text centred on . + /// The text. + /// The centre. + /// The baseline. + /// The font. + /// The size. + /// The colour. + public void DrawTextCentered(string? text, double center, double y, PdfFont font, double size, PdfColor? color = null) => + DrawText(text, center - (PdfTextLayout.Measure(text, font, size) / 2), y, font, size, color); + + /// Writes a paragraph wrapped to a width, from a first baseline downwards. + /// The text. + /// The left edge. + /// The first baseline. + /// The width. + /// The font. + /// The size. + /// The distance between baselines; 1.2 times the size when omitted. + /// The colour. + /// The baseline after the last line. + public double DrawParagraph(string? text, double x, double y, double width, PdfFont font, double size, double? lineHeight = null, PdfColor? color = null) + { + var step = lineHeight ?? size * 1.2; + foreach (var line in PdfTextLayout.Wrap(text, font, size, width)) + { + DrawText(line, x, y, font, size, color); + y -= step; + } + + return y; + } + + /// Draws a line. + /// Start x. + /// Start y. + /// End x. + /// End y. + /// The width in points. + /// The colour; black when omitted. + public void DrawLine(double x1, double y1, double x2, double y2, double lineWidth = 0.5, PdfColor? color = null) + { + Check(); + _content.Append("q ").Append(Num(lineWidth)).Append(" w ").Append(Color(color ?? PdfColor.Black)).Append(" RG ") + .Append(Num(x1)).Append(' ').Append(Num(y1)).Append(" m ").Append(Num(x2)).Append(' ').Append(Num(y2)).Append(" l S Q\n"); + } + + /// Draws a rectangle, filled and/or outlined. + /// The left edge. + /// The bottom edge. + /// The width. + /// The height. + /// The outline colour, or for none. + /// The fill colour, or for none. + /// The outline width. + public void DrawRectangle(double x, double y, double width, double height, PdfColor? stroke = null, PdfColor? fill = null, double lineWidth = 0.5) + { + Check(); + if (stroke is null && fill is null) + { + return; + } + + _content.Append("q "); + if (stroke is { } s) + { + _content.Append(Num(lineWidth)).Append(" w ").Append(Color(s)).Append(" RG "); + } + + if (fill is { } f) + { + _content.Append(Color(f)).Append(" rg "); + } + + var paint = (stroke, fill) switch + { + (not null, not null) => "B", + (not null, null) => "S", + _ => "f", + }; + _content.Append(Num(x)).Append(' ').Append(Num(y)).Append(' ').Append(Num(width)).Append(' ').Append(Num(height)).Append(" re ").Append(paint).Append(" Q\n"); + } + + /// Draws an image scaled to a box. + /// The image, from . + /// The left edge. + /// The bottom edge. + /// The width. + /// The height. + public void DrawImage(PdfImage image, double x, double y, double width, double height) + { + ArgumentNullException.ThrowIfNull(image); + Check(); + Images[image.Name] = image.ObjectNumber; + _content.Append("q ").Append(Num(width)).Append(" 0 0 ").Append(Num(height)).Append(' ').Append(Num(x)).Append(' ').Append(Num(y)) + .Append(" cm /").Append(image.Name).Append(" Do Q\n"); + } + + internal byte[] ContentBytes() => Encoding.ASCII.GetBytes(_content.ToString()); + + internal static string Num(double value) + { + if (!double.IsFinite(value)) + { + throw new ArgumentOutOfRangeException(nameof(value), value, "Coordinates must be finite numbers."); + } + + var text = Math.Round(value, 3).ToString("0.###", CultureInfo.InvariantCulture); + return text == "-0" ? "0" : text; + } + + private static string Color(PdfColor c) => Num(c.R / 255.0) + " " + Num(c.G / 255.0) + " " + Num(c.B / 255.0); + + private void Check() + { + if (IsClosed) + { + throw new InvalidOperationException($"Page {Number} is finished: draw on the current page."); + } + } +} + +/// +/// Writes PDF 1.7 documents (SPEC §2 "PDF e file"), written in house: the 12 standard Latin Type1 fonts with +/// WinAnsiEncoding, text, lines, rectangles, RGB colours, JPEG images, several pages, the information +/// dictionary, Flate-compressed content streams and a correct cross-reference table. Pages are written to the +/// output as soon as the next page starts, so long documents do not stay in memory; only asynchronous writes reach +/// the output, which can therefore be an HTTP response. +/// +/// +/// TODO (FatturaPA courtesy copies, SPEC §2): PDF/A-3 with embedded XML attachments (PdfA3Embedder) needs +/// embedded fonts, an XMP metadata stream and an output intent; this first version does not produce PDF/A. +/// +/// +/// +/// await using var pdf = new PdfWriter(stream, new PdfDocumentInfo { Title = "Prova" }); +/// var page = await pdf.AddPageAsync(); +/// page.DrawText("Totale € 1.234,50", 40, page.Height - 60, PdfFont.HelveticaBold, 14); +/// await pdf.CloseAsync(); +/// +/// +public sealed class PdfWriter : IAsyncDisposable +{ + /// The media type of a PDF file. + public const string MediaType = "application/pdf"; + + /// The width of an A4 page in points. + public const double A4Width = 595.28; + + /// The height of an A4 page in points. + public const double A4Height = 841.89; + + private const int CatalogObject = 1; + private const int PagesObject = 2; + private const int InfoObject = 3; + + private readonly Stream _output; + private readonly bool _leaveOpen; + private readonly PdfDocumentInfo _info; + private readonly MemoryStream _buffer = new(); + private readonly List _offsets = [0, -1, -1, -1]; + private readonly List _pageObjects = []; + private readonly Dictionary _fontObjects = []; + private long _flushed; + private int _images; + private PdfPage? _page; + private bool _closed; + + /// Starts a document. + /// The stream that receives the file; it need not be seekable. + /// The document information; for none but the creator. + /// Whether to leave open on dispose. + public PdfWriter(Stream output, PdfDocumentInfo? info = null, bool leaveOpen = false) + { + ArgumentNullException.ThrowIfNull(output); + _output = output; + _leaveOpen = leaveOpen; + _info = info ?? new PdfDocumentInfo(); + Ascii("%PDF-1.7\n%"); + _buffer.Write([0xE2, 0xE3, 0xCF, 0xD3, (byte)'\n']); + } + + /// Whether content streams are Flate-compressed (turn it off only to inspect the output). + public bool CompressContent { get; init; } = true; + + /// The number of pages started. + public int PageCount => _pageObjects.Count + (_page is null ? 0 : 1); + + /// The current page, or before the first. + public PdfPage? CurrentPage => _page; + + /// Finishes the current page (writing it to the output) and starts a new one. + /// The width in points; A4 when omitted. + /// The height in points; A4 when omitted. + /// Cancellation. + /// The new page. + public async Task AddPageAsync(double width = A4Width, double height = A4Height, CancellationToken cancellationToken = default) + { + ObjectDisposedException.ThrowIf(_closed, this); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + FinishPage(); + await FlushAsync(cancellationToken).ConfigureAwait(false); + _page = new PdfPage(_pageObjects.Count + 1, width, height); + return _page; + } + + /// Adds a JPEG image to the document (embedded as is, DCTDecode). + /// The JPEG file. + /// The image, to draw on any page. + /// The data is not a JPEG file the PDF can embed. + public PdfImage AddJpeg(ReadOnlySpan jpeg) + { + ObjectDisposedException.ThrowIf(_closed, this); + var info = JpegInfo.Read(jpeg); + var number = Allocate(); + var colorSpace = info.Components switch { 1 => "/DeviceGray", 4 => "/DeviceCMYK", _ => "/DeviceRGB" }; + var decode = info.AdobeInverted ? " /Decode [1 0 1 0 1 0 1 0]" : string.Empty; + BeginObject(number); + Ascii(string.Create( + CultureInfo.InvariantCulture, + $"<< /Type /XObject /Subtype /Image /Width {info.Width} /Height {info.Height} /ColorSpace {colorSpace} /BitsPerComponent {info.BitsPerComponent}{decode} /Filter /DCTDecode /Length {jpeg.Length} >>\nstream\n")); + _buffer.Write(jpeg); + Ascii("\nendstream\nendobj\n"); + _images++; + return new PdfImage(number, "Im" + _images.ToString(CultureInfo.InvariantCulture), info); + } + + /// Writes what is buffered to the output. + /// Cancellation. + /// A task. + public async Task FlushAsync(CancellationToken cancellationToken = default) + { + if (_buffer.Length == 0) + { + return; + } + + await _output.WriteAsync(_buffer.GetBuffer().AsMemory(0, (int)_buffer.Length), cancellationToken).ConfigureAwait(false); + _flushed += _buffer.Length; + _buffer.SetLength(0); + } + + /// + /// Finishes the document: the last page, fonts, page tree, catalogue, information, cross-reference table and + /// trailer. A document without pages gets one blank page. + /// + /// Cancellation. + /// A task. + public async Task CloseAsync(CancellationToken cancellationToken = default) + { + if (_closed) + { + return; + } + + if (_page is null && _pageObjects.Count == 0) + { + _page = new PdfPage(1, A4Width, A4Height); + } + + FinishPage(); + foreach (var (font, number) in _fontObjects.OrderBy(f => f.Value)) + { + BeginObject(number); + Ascii($"<< /Type /Font /Subtype /Type1 /BaseFont /{PdfTextLayout.BaseFontName(font)} /Encoding /WinAnsiEncoding >>\nendobj\n"); + } + + BeginObject(PagesObject); + Ascii("<< /Type /Pages /Kids [" + string.Join(' ', _pageObjects.Select(p => Ref(p))) + "] /Count " + + _pageObjects.Count.ToString(CultureInfo.InvariantCulture) + " >>\nendobj\n"); + BeginObject(CatalogObject); + Ascii("<< /Type /Catalog /Pages " + Ref(PagesObject) + " >>\nendobj\n"); + BeginObject(InfoObject); + Ascii("<< " + InfoEntries() + ">>\nendobj\n"); + + var xref = Position; + var size = _offsets.Count.ToString(CultureInfo.InvariantCulture); + var table = new StringBuilder(); + table.Append("xref\n0 ").Append(size).Append('\n').Append("0000000000 65535 f\r\n"); + for (var i = 1; i < _offsets.Count; i++) + { + if (_offsets[i] < 0) + { + throw new InvalidOperationException($"Object {i} was allocated but never written."); + } + + table.Append(_offsets[i].ToString("D10", CultureInfo.InvariantCulture)).Append(" 00000 n\r\n"); + } + + var id = Convert.ToHexString(Guid.NewGuid().ToByteArray()); + table.Append("trailer\n<< /Size ").Append(size).Append(" /Root ").Append(Ref(CatalogObject)).Append(" /Info ").Append(Ref(InfoObject)) + .Append(" /ID [<").Append(id).Append("> <").Append(id).Append(">] >>\nstartxref\n") + .Append(xref.ToString(CultureInfo.InvariantCulture)).Append("\n%%EOF\n"); + Ascii(table.ToString()); + _closed = true; + await FlushAsync(cancellationToken).ConfigureAwait(false); + await _output.FlushAsync(cancellationToken).ConfigureAwait(false); + if (!_leaveOpen) + { + await _output.DisposeAsync().ConfigureAwait(false); + } + } + + /// Closes the document if it is still open. + /// A task. + public async ValueTask DisposeAsync() + { + await CloseAsync().ConfigureAwait(false); + await _buffer.DisposeAsync().ConfigureAwait(false); + } + + internal static string FontResource(PdfFont font) => "F" + ((int)font + 1).ToString(CultureInfo.InvariantCulture); + + private long Position => _flushed + _buffer.Length; + + private static string Ref(int number) => number.ToString(CultureInfo.InvariantCulture) + " 0 R"; + + private static string PdfDate(DateTimeOffset value) => + "D:" + value.UtcDateTime.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture) + "Z"; + + /// A text string: ASCII as a literal, anything else as UTF-16BE with byte order mark. + private static string TextString(string value) + { + if (value.All(c => c is >= ' ' and <= '~')) + { + return "(" + value.Replace("\\", "\\\\", StringComparison.Ordinal).Replace("(", "\\(", StringComparison.Ordinal).Replace(")", "\\)", StringComparison.Ordinal) + ")"; + } + + return ""; + } + + private string InfoEntries() + { + var entries = new StringBuilder(); + void Add(string key, string? value) + { + if (!string.IsNullOrEmpty(value)) + { + entries.Append('/').Append(key).Append(' ').Append(TextString(value)).Append(' '); + } + } + + Add("Title", _info.Title); + Add("Author", _info.Author); + Add("Subject", _info.Subject); + Add("Keywords", _info.Keywords); + Add("Creator", _info.Creator); + Add("Producer", "Khaemhat PdfWriter"); + var created = PdfDate(_info.CreationDate ?? DateTimeOffset.UtcNow); + entries.Append("/CreationDate (").Append(created).Append(") /ModDate (").Append(created).Append(") "); + return entries.ToString(); + } + + private int Allocate() + { + _offsets.Add(-1); + return _offsets.Count - 1; + } + + private void BeginObject(int number) + { + _offsets[number] = Position; + Ascii(number.ToString(CultureInfo.InvariantCulture) + " 0 obj\n"); + } + + private void Ascii(string text) => _buffer.Write(Encoding.ASCII.GetBytes(text)); + + private void FinishPage() + { + if (_page is not { } page) + { + return; + } + + page.IsClosed = true; + _page = null; + + var content = page.ContentBytes(); + var filter = string.Empty; + if (CompressContent) + { + using var compressed = new MemoryStream(); + using (var zlib = new ZLibStream(compressed, CompressionLevel.Optimal, leaveOpen: true)) + { + zlib.Write(content); + } + + content = compressed.ToArray(); + filter = " /Filter /FlateDecode"; + } + + var contentObject = Allocate(); + BeginObject(contentObject); + Ascii("<< /Length " + content.Length.ToString(CultureInfo.InvariantCulture) + filter + " >>\nstream\n"); + _buffer.Write(content); + Ascii("\nendstream\nendobj\n"); + + var fonts = new StringBuilder(); + foreach (var font in page.Fonts) + { + if (!_fontObjects.TryGetValue(font, out var number)) + { + number = Allocate(); + _fontObjects[font] = number; + } + + fonts.Append('/').Append(FontResource(font)).Append(' ').Append(Ref(number)).Append(' '); + } + + var images = string.Concat(page.Images.Select(i => "/" + i.Key + " " + Ref(i.Value) + " ")); + var resources = "/ProcSet [/PDF /Text /ImageB /ImageC]" + + (fonts.Length > 0 ? " /Font << " + fonts + ">>" : string.Empty) + + (images.Length > 0 ? " /XObject << " + images + ">>" : string.Empty); + + var pageObject = Allocate(); + BeginObject(pageObject); + Ascii("<< /Type /Page /Parent " + Ref(PagesObject) + " /MediaBox [0 0 " + PdfPage.Num(page.Width) + " " + PdfPage.Num(page.Height) + + "] /Resources << " + resources + " >> /Contents " + Ref(contentObject) + " >>\nendobj\n"); + _pageObjects.Add(pageObject); + } +} diff --git a/src/Khaemhat.Infrastructure/Files/VolumeFileStore.cs b/src/Khaemhat.Infrastructure/Files/VolumeFileStore.cs new file mode 100644 index 0000000..406e942 --- /dev/null +++ b/src/Khaemhat.Infrastructure/Files/VolumeFileStore.cs @@ -0,0 +1,348 @@ +using System.Globalization; +using System.Security.Cryptography; +using System.Text.RegularExpressions; +using Khaemhat.Core.Files; +using Khaemhat.Data; + +namespace Khaemhat.Infrastructure.Files; + +/// Where the store keeps files and the default limits. +/// The root folder, <KHAEMHAT_DATA_DIR>/files. +public sealed record FileStoreOptions(string RootDirectory) +{ + /// The largest file accepted when the caller gives no limit (25 MB). + public long MaxFileBytes { get; init; } = FileLimits.DefaultMaxBytes; + + /// The space each company may use when the caller gives no quota; 0 means no quota. + public long CompanyQuotaBytes { get; init; } + + /// The options for a data folder: files in <dataDir>/files. + /// The value of KHAEMHAT_DATA_DIR. + /// The options. + public static FileStoreOptions ForDataDirectory(string dataDirectory) + { + ArgumentException.ThrowIfNullOrWhiteSpace(dataDirectory); + return new FileStoreOptions(Path.Combine(dataDirectory, "files")); + } + + /// The limits used when the caller gives none. + public FileLimits DefaultLimits => new(MaxFileBytes, CompanyQuotaBytes); +} + +/// The scanner used when no antivirus is plugged in: every file is accepted. +public sealed class NoOpFileScanner : IFileScanner +{ + /// + public ValueTask ScanAsync(string companyCode, Stream content, CancellationToken cancellationToken = default) => + ValueTask.FromResult(FileScanResult.Ok); +} + +/// +/// The file store on the data volume (SPEC §9.4): <root>/<COMPANY>/<yyyy>/<guid>. A file is +/// written to <guid>.part in the same folder while its size is checked and its SHA-256 computed, then +/// renamed: nothing is ever written outside the data folder and a partial file never appears under a key. +/// +public sealed partial class VolumeFileStore : IFileStore +{ + private const string PartExtension = ".part"; + private const int BufferSize = 81920; + + private readonly FileStoreOptions _options; + private readonly IFileScanner _scanner; + private readonly TimeProvider _clock; + + /// Creates the store. + /// The root folder and the default limits. + /// The antivirus hook. + /// The clock (the year folder). + public VolumeFileStore(FileStoreOptions options, IFileScanner scanner, TimeProvider clock) + { + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(scanner); + ArgumentNullException.ThrowIfNull(clock); + if (!Path.IsPathFullyQualified(options.RootDirectory)) + { + throw new ArgumentException("The root of the file store must be an absolute path.", nameof(options)); + } + + _options = options; + _scanner = scanner; + _clock = clock; + } + + /// The root folder. + public string RootDirectory => _options.RootDirectory; + + /// Whether a key has the form the store produces (yyyy/guid). + /// The key. + /// if valid. + public static bool IsValidKey(string? key) => key is not null && KeyPattern().IsMatch(key); + + /// + public async Task SaveAsync(string companyCode, Stream content, FileLimits? limits = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(content); + await using var writer = await CreateAsync(companyCode, limits, cancellationToken).ConfigureAwait(false); + await content.CopyToAsync(writer.Content, BufferSize, cancellationToken).ConfigureAwait(false); + return await writer.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + /// + public Task CreateAsync(string companyCode, FileLimits? limits = null, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + var company = CompanyFolder(companyCode); + var year = _clock.GetUtcNow().Year.ToString("D4", CultureInfo.InvariantCulture); + var folder = Path.Combine(company, year); + Directory.CreateDirectory(folder); + var name = Guid.NewGuid().ToString("N"); + var writer = new Writer(this, CompanyCodes.Normalize(companyCode), year + "/" + name, Path.Combine(folder, name), limits ?? _options.DefaultLimits); + return Task.FromResult(writer); + } + + /// + public Stream OpenRead(string companyCode, string key) + { + var path = PathOf(companyCode, key); + try + { + return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, BufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan); + } + catch (Exception ex) when (ex is FileNotFoundException or DirectoryNotFoundException) + { + throw new FileStoreException(FileStoreException.NotFound, $"The file {key} does not exist in the store of {companyCode}."); + } + } + + /// + public bool Exists(string companyCode, string key) => File.Exists(PathOf(companyCode, key)); + + /// + public bool Delete(string companyCode, string key) + { + var path = PathOf(companyCode, key); + if (!File.Exists(path)) + { + return false; + } + + File.Delete(path); + return true; + } + + /// + public Task GetUsageAsync(string companyCode, long? quotaBytes = null, CancellationToken cancellationToken = default) + { + var quota = quotaBytes ?? _options.CompanyQuotaBytes; + var folder = CompanyFolder(companyCode); + long files = 0, bytes = 0; + if (Directory.Exists(folder)) + { + foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", SearchOption.AllDirectories)) + { + cancellationToken.ThrowIfCancellationRequested(); + if (!file.Name.EndsWith(PartExtension, StringComparison.Ordinal)) + { + files++; + bytes += file.Length; + } + } + } + + return Task.FromResult(new FileUsage(files, bytes, quota)); + } + + /// + public int DeleteAbandonedParts(string companyCode, TimeSpan olderThan) + { + var folder = CompanyFolder(companyCode); + if (!Directory.Exists(folder)) + { + return 0; + } + + var limit = _clock.GetUtcNow().UtcDateTime - olderThan; + var deleted = 0; + foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*" + PartExtension, SearchOption.AllDirectories)) + { + if (file.LastWriteTimeUtc < limit) + { + try + { + file.Delete(); + deleted++; + } + catch (IOException) + { + // Still being written by another process: it will be removed next time. + } + } + } + + return deleted; + } + + private string CompanyFolder(string companyCode) => Path.Combine(_options.RootDirectory, CompanyCodes.Normalize(companyCode)); + + private string PathOf(string companyCode, string key) + { + if (!IsValidKey(key)) + { + throw new ArgumentException("Not a key of the file store.", nameof(key)); + } + + return Path.Combine(CompanyFolder(companyCode), key.Replace('/', Path.DirectorySeparatorChar)); + } + + [GeneratedRegex("^[0-9]{4}/[0-9a-f]{32}$", RegexOptions.CultureInvariant)] + private static partial Regex KeyPattern(); + + /// A file being written: the .part file and the counting stream over it. + private sealed class Writer : IFileStoreWriter + { + private readonly VolumeFileStore _store; + private readonly string _company; + private readonly string _key; + private readonly string _finalPath; + private readonly string _partPath; + private readonly FileLimits _limits; + private readonly FileStream _file; + private readonly HashingStream _content; + private bool _committed; + private bool _disposed; + + public Writer(VolumeFileStore store, string company, string key, string finalPath, FileLimits limits) + { + _store = store; + _company = company; + _key = key; + _finalPath = finalPath; + _partPath = finalPath + PartExtension; + _limits = limits; + _file = new FileStream(_partPath, FileMode.CreateNew, FileAccess.Write, FileShare.Read, BufferSize, FileOptions.Asynchronous); + _content = new HashingStream(_file, limits.MaxBytes); + } + + public Stream Content => _content; + + public async Task CommitAsync(CancellationToken cancellationToken = default) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (_committed) + { + throw new InvalidOperationException("The file is already committed."); + } + + await _file.FlushAsync(cancellationToken).ConfigureAwait(false); + var size = _content.Length; + if (_limits.QuotaBytes > 0) + { + var usage = await _store.GetUsageAsync(_company, _limits.QuotaBytes, cancellationToken).ConfigureAwait(false); + if (usage.Bytes + size > _limits.QuotaBytes) + { + throw new FileStoreException(FileStoreException.QuotaExceeded, $"The company {_company} has no space left for {size} bytes."); + } + } + + await using (var scan = new FileStream(_partPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, BufferSize, FileOptions.Asynchronous)) + { + var verdict = await _store._scanner.ScanAsync(_company, scan, cancellationToken).ConfigureAwait(false); + if (!verdict.Clean) + { + throw new FileStoreException(FileStoreException.Rejected, "The file was rejected by the scanner: " + (verdict.Reason ?? "no reason given") + "."); + } + } + + var hash = _content.HashHex(); + await _file.DisposeAsync().ConfigureAwait(false); + File.Move(_partPath, _finalPath); + _committed = true; + return new StoredFile(_key, size, hash); + } + + public async ValueTask DisposeAsync() + { + if (_disposed) + { + return; + } + + _disposed = true; + _content.ReleaseHash(); + await _file.DisposeAsync().ConfigureAwait(false); + if (!_committed && File.Exists(_partPath)) + { + File.Delete(_partPath); + } + } + } + + /// A write-only stream that enforces the size limit and computes SHA-256 on the way. + private sealed class HashingStream(Stream inner, long maxBytes) : Stream + { + private readonly IncrementalHash _hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + private long _length; + + public override bool CanRead => false; + + public override bool CanSeek => false; + + public override bool CanWrite => true; + + public override long Length => _length; + + public override long Position + { + get => _length; + set => throw new NotSupportedException(); + } + + public string HashHex() => Convert.ToHexStringLower(_hash.GetCurrentHash()); + + public void ReleaseHash() => _hash.Dispose(); + + public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count)); + + public override void Write(ReadOnlySpan buffer) + { + Account(buffer); + inner.Write(buffer); + } + + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + Account(buffer.Span); + return inner.WriteAsync(buffer, cancellationToken); + } + + public override void Flush() => inner.Flush(); + + public override Task FlushAsync(CancellationToken cancellationToken) => inner.FlushAsync(cancellationToken); + + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + // The writer owns the file stream and the hash. + base.Dispose(disposing); + } + + private void Account(ReadOnlySpan buffer) + { + if (maxBytes > 0 && _length + buffer.Length > maxBytes) + { + throw new FileStoreException(FileStoreException.TooLarge, $"The file is larger than {maxBytes} bytes."); + } + + _length += buffer.Length; + _hash.AppendData(buffer); + } + } +} diff --git a/src/Khaemhat.Infrastructure/Files/XlsxWriter.cs b/src/Khaemhat.Infrastructure/Files/XlsxWriter.cs new file mode 100644 index 0000000..0b18475 --- /dev/null +++ b/src/Khaemhat.Infrastructure/Files/XlsxWriter.cs @@ -0,0 +1,753 @@ +using System.Globalization; +using System.IO.Compression; +using System.Text; +using System.Xml; + +namespace Khaemhat.Infrastructure.Files; + +/// The number format of a spreadsheet column. +public enum XlsxFormat +{ + /// By value: dates get a date format, everything else the general one. + General = 0, + + /// Whole numbers with thousands separator (#,##0). + WholeNumber = 1, + + /// Two decimals with thousands separator (#,##0.00). + TwoDecimals = 2, + + /// Euro amounts (#,##0.00 €). + Euro = 3, + + /// Percentages with two decimals; the value 0.22 shows as 22,00%. + Percent = 4, + + /// Dates. + Date = 5, + + /// Dates with time. + DateTime = 6, + + /// Text: numbers typed later in the cell stay text. + Text = 7, +} + +/// A column of a sheet. +/// The header, written in bold in the first row; for no header. +/// The width in characters; for the spreadsheet default. +/// The number format of the cells. +public sealed record XlsxColumn(string? Header, double? Width = null, XlsxFormat Format = XlsxFormat.General); + +/// The options of an . +public sealed record XlsxOptions +{ + /// + /// Whether text goes to the shared strings table (smaller files with repeated text, but every distinct string is + /// kept in memory until the end) instead of inline in each cell (the default, fully streaming). + /// + public bool UseSharedStrings { get; init; } + + /// Whether the header row stays visible while scrolling. + public bool FreezeHeaderRow { get; init; } = true; +} + +/// +/// Writes Office Open XML spreadsheets (.xlsx, SPEC §2, §9.4) with and +/// , row by row, without holding the sheet in memory: text (inline or shared strings), numbers, +/// dates as serial numbers with a date format, booleans, a bold header row, column widths and a frozen header. +/// Only asynchronous writes reach the output, so it can be an HTTP response. +/// +/// +/// +/// await using var xlsx = await XlsxWriter.CreateAsync(stream); +/// await xlsx.StartSheetAsync("Righe", [new("Codice", 12), new("Importo", 14, XlsxFormat.Euro)]); +/// await xlsx.WriteRowAsync(["A1", 12.5m]); +/// await xlsx.CompleteAsync(); +/// +/// +public sealed class XlsxWriter : IAsyncDisposable +{ + /// The media type of an .xlsx file. + public const string MediaType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; + + /// The longest sheet name Excel accepts. + public const int MaxSheetNameLength = 31; + + /// The longest text a cell holds. + public const int MaxCellTextLength = 32767; + + private const string MainNs = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"; + private const string RelNs = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; + private const string PackageRelNs = "http://schemas.openxmlformats.org/package/2006/relationships"; + private const string ContentTypesNs = "http://schemas.openxmlformats.org/package/2006/content-types"; + private const string WorksheetType = "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"; + + // Indexes in cellXfs of styles.xml. + private const int StyleGeneral = 0; + private const int StyleHeader = 1; + private const int StyleDate = 2; + private const int StyleDateTime = 3; + private const int StyleInteger = 4; + private const int StyleDecimal = 5; + private const int StyleEuro = 6; + private const int StylePercent = 7; + private const int StyleText = 8; + + private static readonly DateTime Epoch = new(1899, 12, 30, 0, 0, 0, DateTimeKind.Unspecified); + + private readonly ZipArchive _archive; + private readonly AsyncOutputBuffer _buffer; + private readonly Stream _output; + private readonly bool _leaveOpen; + private readonly XlsxOptions _options; + private readonly List _sheetNames = []; + private readonly Dictionary _sharedIndex = new(StringComparer.Ordinal); + private readonly List _shared = []; + private Stream? _sheetStream; + private XmlWriter? _sheet; + private IReadOnlyList _columns = []; + private int _row; + private bool _completed; + + private XlsxWriter(ZipArchive archive, AsyncOutputBuffer buffer, Stream output, bool leaveOpen, XlsxOptions options) + { + _archive = archive; + _buffer = buffer; + _output = output; + _leaveOpen = leaveOpen; + _options = options; + } + + /// The names of the sheets started so far (after cleaning). + public IReadOnlyList SheetNames => _sheetNames; + + /// Starts a workbook. + /// The stream that receives the file; it need not be seekable. + /// The options. + /// Whether to leave open on dispose. + /// Cancellation. + /// The writer; complete or dispose it. + public static async Task CreateAsync(Stream output, XlsxOptions? options = null, bool leaveOpen = false, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(output); + var buffer = new AsyncOutputBuffer(output); + var archive = await ZipArchive.CreateAsync(buffer, ZipArchiveMode.Create, leaveOpen: true, Encoding.UTF8, cancellationToken).ConfigureAwait(false); + return new XlsxWriter(archive, buffer, output, leaveOpen, options ?? new XlsxOptions()); + } + + /// + /// Makes a valid sheet name: without [ ] : * ? / \, without apostrophes at the ends, at most 31 characters, + /// different (ignoring case) from the names already used. + /// + /// The wanted name. + /// The names already in the workbook. + /// The name. + public static string CleanSheetName(string? name, IReadOnlyCollection used) + { + ArgumentNullException.ThrowIfNull(used); + var builder = new StringBuilder(); + foreach (var c in name ?? string.Empty) + { + if (c is not ('[' or ']' or ':' or '*' or '?' or '/' or '\\') && !char.IsControl(c)) + { + builder.Append(c); + } + } + + var clean = builder.ToString().Trim().Trim('\'').Trim(); + if (clean.Length == 0) + { + clean = "Foglio" + (used.Count + 1).ToString(CultureInfo.InvariantCulture); + } + + clean = clean.Length > MaxSheetNameLength ? clean[..MaxSheetNameLength] : clean; + var candidate = clean; + for (var i = 2; used.Contains(candidate, StringComparer.OrdinalIgnoreCase); i++) + { + var suffix = " (" + i.ToString(CultureInfo.InvariantCulture) + ")"; + candidate = clean[..Math.Min(clean.Length, MaxSheetNameLength - suffix.Length)] + suffix; + } + + return candidate; + } + + /// The spreadsheet serial number of a date (days since 1899-12-30, time as fraction). + /// The date. + /// The serial number. + public static double ToSerialDate(DateTime value) => (value - Epoch).TotalDays; + + /// The letters of a column: 0 is A, 26 is AA. + /// The zero-based column. + /// The letters. + public static string ColumnName(int index) + { + ArgumentOutOfRangeException.ThrowIfNegative(index); + var name = string.Empty; + for (var n = index + 1; n > 0; n = (n - 1) / 26) + { + name = (char)('A' + ((n - 1) % 26)) + name; + } + + return name; + } + + /// Starts a sheet (ending the previous one); with column headers the first row is the bold header. + /// The sheet name, cleaned by . + /// The columns, or . + /// Cancellation. + /// A task. + public async Task StartSheetAsync(string name, IReadOnlyList? columns = null, CancellationToken cancellationToken = default) + { + ObjectDisposedException.ThrowIf(_completed, this); + await EndSheetAsync(cancellationToken).ConfigureAwait(false); + var clean = CleanSheetName(name, _sheetNames); + _sheetNames.Add(clean); + _columns = columns ?? []; + _row = 0; + + var entry = _archive.CreateEntry($"xl/worksheets/sheet{_sheetNames.Count.ToString(CultureInfo.InvariantCulture)}.xml", CompressionLevel.Optimal); + _sheetStream = await entry.OpenAsync(cancellationToken).ConfigureAwait(false); + _sheet = XmlWriter.Create(_sheetStream, XmlSettings()); + var w = _sheet; + await w.WriteStartDocumentAsync(true).ConfigureAwait(false); + await w.WriteStartElementAsync(null, "worksheet", MainNs).ConfigureAwait(false); + await w.WriteAttributeStringAsync("xmlns", "r", null, RelNs).ConfigureAwait(false); + + var hasHeader = _columns.Any(c => c.Header is not null); + await w.WriteStartElementAsync(null, "sheetViews", MainNs).ConfigureAwait(false); + await w.WriteStartElementAsync(null, "sheetView", MainNs).ConfigureAwait(false); + if (_sheetNames.Count == 1) + { + await w.WriteAttributeStringAsync(null, "tabSelected", null, "1").ConfigureAwait(false); + } + + await w.WriteAttributeStringAsync(null, "workbookViewId", null, "0").ConfigureAwait(false); + if (hasHeader && _options.FreezeHeaderRow) + { + await w.WriteStartElementAsync(null, "pane", MainNs).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "ySplit", null, "1").ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "topLeftCell", null, "A2").ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "activePane", null, "bottomLeft").ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "state", null, "frozen").ConfigureAwait(false); + await w.WriteEndElementAsync().ConfigureAwait(false); + await w.WriteStartElementAsync(null, "selection", MainNs).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "pane", null, "bottomLeft").ConfigureAwait(false); + await w.WriteEndElementAsync().ConfigureAwait(false); + } + + await w.WriteEndElementAsync().ConfigureAwait(false); + await w.WriteEndElementAsync().ConfigureAwait(false); + + await w.WriteStartElementAsync(null, "sheetFormatPr", MainNs).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "defaultRowHeight", null, "15").ConfigureAwait(false); + await w.WriteEndElementAsync().ConfigureAwait(false); + + if (_columns.Any(c => c.Width is not null)) + { + await w.WriteStartElementAsync(null, "cols", MainNs).ConfigureAwait(false); + for (var i = 0; i < _columns.Count; i++) + { + if (_columns[i].Width is { } width) + { + var index = (i + 1).ToString(CultureInfo.InvariantCulture); + await w.WriteStartElementAsync(null, "col", MainNs).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "min", null, index).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "max", null, index).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "width", null, Math.Clamp(width, 1, 255).ToString("0.##", CultureInfo.InvariantCulture)).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "customWidth", null, "1").ConfigureAwait(false); + await w.WriteEndElementAsync().ConfigureAwait(false); + } + } + + await w.WriteEndElementAsync().ConfigureAwait(false); + } + + await w.WriteStartElementAsync(null, "sheetData", MainNs).ConfigureAwait(false); + if (hasHeader) + { + await WriteRowCoreAsync(_columns.Select(c => (object?)c.Header), header: true).ConfigureAwait(false); + } + } + + /// Writes a row in the current sheet (a sheet Foglio1 is started if none is). + /// + /// The cells: , numbers, , , ; + /// leaves the cell empty; anything else is written as text. + /// + /// Cancellation. + /// A task. + public async Task WriteRowAsync(IEnumerable values, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(values); + ObjectDisposedException.ThrowIf(_completed, this); + if (_sheet is null) + { + await StartSheetAsync("Foglio1", null, cancellationToken).ConfigureAwait(false); + } + + await WriteRowCoreAsync(values, header: false).ConfigureAwait(false); + } + + /// Ends the last sheet and writes workbook, styles, shared strings, relationships and content types. + /// Cancellation. + /// A task. + public async Task CompleteAsync(CancellationToken cancellationToken = default) + { + if (_completed) + { + return; + } + + if (_sheetNames.Count == 0) + { + await StartSheetAsync("Foglio1", null, cancellationToken).ConfigureAwait(false); + } + + await EndSheetAsync(cancellationToken).ConfigureAwait(false); + await WritePartAsync("xl/workbook.xml", WriteWorkbookAsync, cancellationToken).ConfigureAwait(false); + await WritePartAsync("xl/styles.xml", WriteStylesAsync, cancellationToken).ConfigureAwait(false); + if (_options.UseSharedStrings) + { + await WritePartAsync("xl/sharedStrings.xml", WriteSharedStringsAsync, cancellationToken).ConfigureAwait(false); + } + + await WritePartAsync("xl/_rels/workbook.xml.rels", WriteWorkbookRelationshipsAsync, cancellationToken).ConfigureAwait(false); + await WritePartAsync("_rels/.rels", WritePackageRelationshipsAsync, cancellationToken).ConfigureAwait(false); + await WritePartAsync("[Content_Types].xml", WriteContentTypesAsync, cancellationToken).ConfigureAwait(false); + _completed = true; + await _archive.DisposeAsync().ConfigureAwait(false); + await _buffer.FlushAsync(cancellationToken).ConfigureAwait(false); + await _buffer.DisposeAsync().ConfigureAwait(false); + if (!_leaveOpen) + { + await _output.DisposeAsync().ConfigureAwait(false); + } + } + + /// Completes the workbook if needed and closes the stream unless left open. + /// A task. + public async ValueTask DisposeAsync() + { + if (!_completed) + { + await CompleteAsync().ConfigureAwait(false); + } + } + + private static XmlWriterSettings XmlSettings() => new() + { + Async = true, + Encoding = new UTF8Encoding(false), + Indent = false, + CloseOutput = false, + }; + + private static string CleanText(string value) + { + var builder = new StringBuilder(Math.Min(value.Length, MaxCellTextLength)); + for (var i = 0; i < value.Length && builder.Length < MaxCellTextLength; i++) + { + var c = value[i]; + if (char.IsHighSurrogate(c) && i + 1 < value.Length && char.IsLowSurrogate(value[i + 1])) + { + if (builder.Length + 2 > MaxCellTextLength) + { + break; + } + + builder.Append(c).Append(value[i + 1]); + i++; + } + else if (XmlConvert.IsXmlChar(c)) + { + builder.Append(c); + } + } + + return builder.ToString(); + } + + private static int StyleOf(XlsxFormat format) => format switch + { + XlsxFormat.WholeNumber => StyleInteger, + XlsxFormat.TwoDecimals => StyleDecimal, + XlsxFormat.Euro => StyleEuro, + XlsxFormat.Percent => StylePercent, + XlsxFormat.Date => StyleDate, + XlsxFormat.DateTime => StyleDateTime, + XlsxFormat.Text => StyleText, + _ => StyleGeneral, + }; + + private static string? NumberText(object value) => value switch + { + byte or sbyte or short or ushort or int or uint or long or ulong => Convert.ToString(value, CultureInfo.InvariantCulture), + decimal m => m.ToString(CultureInfo.InvariantCulture), + double d when double.IsFinite(d) => d.ToString("R", CultureInfo.InvariantCulture), + float f when float.IsFinite(f) => ((double)f).ToString("R", CultureInfo.InvariantCulture), + _ => null, + }; + + private async Task WriteRowCoreAsync(IEnumerable values, bool header) + { + var w = _sheet!; + _row++; + var rowNumber = _row.ToString(CultureInfo.InvariantCulture); + await w.WriteStartElementAsync(null, "row", MainNs).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "r", null, rowNumber).ConfigureAwait(false); + var column = 0; + foreach (var value in values) + { + if (value is not null) + { + var format = !header && column < _columns.Count ? _columns[column].Format : XlsxFormat.General; + await WriteCellAsync(w, ColumnName(column) + rowNumber, value, header ? StyleHeader : StyleOf(format), format).ConfigureAwait(false); + } + + column++; + } + + await w.WriteEndElementAsync().ConfigureAwait(false); + } + + private async Task WriteCellAsync(XmlWriter w, string reference, object value, int style, XlsxFormat format) + { + switch (value) + { + case bool b: + await StartCellAsync(w, reference, style, "b").ConfigureAwait(false); + await w.WriteElementStringAsync(null, "v", MainNs, b ? "1" : "0").ConfigureAwait(false); + break; + case DateTime date: + var dateStyle = style == StyleGeneral ? (date.TimeOfDay == TimeSpan.Zero ? StyleDate : StyleDateTime) : style; + await StartCellAsync(w, reference, dateStyle, null).ConfigureAwait(false); + await w.WriteElementStringAsync(null, "v", MainNs, ToSerialDate(date).ToString("R", CultureInfo.InvariantCulture)).ConfigureAwait(false); + break; + case DateOnly day: + await StartCellAsync(w, reference, style == StyleGeneral ? StyleDate : style, null).ConfigureAwait(false); + await w.WriteElementStringAsync(null, "v", MainNs, ToSerialDate(day.ToDateTime(TimeOnly.MinValue)).ToString("R", CultureInfo.InvariantCulture)).ConfigureAwait(false); + break; + default: + if (format != XlsxFormat.Text && NumberText(value) is { } number) + { + await StartCellAsync(w, reference, style, null).ConfigureAwait(false); + await w.WriteElementStringAsync(null, "v", MainNs, number).ConfigureAwait(false); + break; + } + + if (value is double or float) + { + // NaN and infinity have no spreadsheet value: the cell stays empty. + return; + } + + var text = CleanText(Convert.ToString(value, CultureInfo.InvariantCulture) ?? string.Empty); + if (_options.UseSharedStrings) + { + if (!_sharedIndex.TryGetValue(text, out var index)) + { + index = _shared.Count; + _shared.Add(text); + _sharedIndex[text] = index; + } + + await StartCellAsync(w, reference, style, "s").ConfigureAwait(false); + await w.WriteElementStringAsync(null, "v", MainNs, index.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false); + } + else + { + await StartCellAsync(w, reference, style, "inlineStr").ConfigureAwait(false); + await w.WriteStartElementAsync(null, "is", MainNs).ConfigureAwait(false); + await WriteTextElementAsync(w, text).ConfigureAwait(false); + await w.WriteEndElementAsync().ConfigureAwait(false); + } + + break; + } + + await w.WriteEndElementAsync().ConfigureAwait(false); + } + + private static async Task StartCellAsync(XmlWriter w, string reference, int style, string? type) + { + await w.WriteStartElementAsync(null, "c", MainNs).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "r", null, reference).ConfigureAwait(false); + if (style != StyleGeneral) + { + await w.WriteAttributeStringAsync(null, "s", null, style.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false); + } + + if (type is not null) + { + await w.WriteAttributeStringAsync(null, "t", null, type).ConfigureAwait(false); + } + } + + private static async Task WriteTextElementAsync(XmlWriter w, string text) + { + await w.WriteStartElementAsync(null, "t", MainNs).ConfigureAwait(false); + if (text.Length > 0 && (char.IsWhiteSpace(text[0]) || char.IsWhiteSpace(text[^1]))) + { + await w.WriteAttributeStringAsync("xml", "space", null, "preserve").ConfigureAwait(false); + } + + await w.WriteStringAsync(text).ConfigureAwait(false); + await w.WriteEndElementAsync().ConfigureAwait(false); + } + + private async Task EndSheetAsync(CancellationToken cancellationToken) + { + if (_sheet is null) + { + return; + } + + await _sheet.WriteEndElementAsync().ConfigureAwait(false); + await _sheet.WriteEndElementAsync().ConfigureAwait(false); + await _sheet.WriteEndDocumentAsync().ConfigureAwait(false); + await _sheet.FlushAsync().ConfigureAwait(false); + await _sheet.DisposeAsync().ConfigureAwait(false); + _sheet = null; + cancellationToken.ThrowIfCancellationRequested(); + await _sheetStream!.DisposeAsync().ConfigureAwait(false); + _sheetStream = null; + await _buffer.DrainAsync(cancellationToken).ConfigureAwait(false); + } + + private async Task WritePartAsync(string name, Func write, CancellationToken cancellationToken) + { + var entry = _archive.CreateEntry(name, CompressionLevel.Optimal); + var stream = await entry.OpenAsync(cancellationToken).ConfigureAwait(false); + await using (stream.ConfigureAwait(false)) + { + var w = XmlWriter.Create(stream, XmlSettings()); + await using var writerScope = w.ConfigureAwait(false); + await w.WriteStartDocumentAsync(true).ConfigureAwait(false); + await write(w).ConfigureAwait(false); + await w.WriteEndDocumentAsync().ConfigureAwait(false); + await w.FlushAsync().ConfigureAwait(false); + } + + await _buffer.DrainAsync(cancellationToken).ConfigureAwait(false); + } + + private async Task WriteWorkbookAsync(XmlWriter w) + { + await w.WriteStartElementAsync(null, "workbook", MainNs).ConfigureAwait(false); + await w.WriteAttributeStringAsync("xmlns", "r", null, RelNs).ConfigureAwait(false); + await w.WriteStartElementAsync(null, "sheets", MainNs).ConfigureAwait(false); + for (var i = 0; i < _sheetNames.Count; i++) + { + var id = (i + 1).ToString(CultureInfo.InvariantCulture); + await w.WriteStartElementAsync(null, "sheet", MainNs).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "name", null, _sheetNames[i]).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "sheetId", null, id).ConfigureAwait(false); + await w.WriteAttributeStringAsync("r", "id", RelNs, "rId" + id).ConfigureAwait(false); + await w.WriteEndElementAsync().ConfigureAwait(false); + } + + await w.WriteEndElementAsync().ConfigureAwait(false); + await w.WriteEndElementAsync().ConfigureAwait(false); + } + + private async Task WriteSharedStringsAsync(XmlWriter w) + { + var count = _shared.Count.ToString(CultureInfo.InvariantCulture); + await w.WriteStartElementAsync(null, "sst", MainNs).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "count", null, count).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "uniqueCount", null, count).ConfigureAwait(false); + foreach (var text in _shared) + { + await w.WriteStartElementAsync(null, "si", MainNs).ConfigureAwait(false); + await WriteTextElementAsync(w, text).ConfigureAwait(false); + await w.WriteEndElementAsync().ConfigureAwait(false); + } + + await w.WriteEndElementAsync().ConfigureAwait(false); + } + + private static async Task WriteStylesAsync(XmlWriter w) + { + await w.WriteStartElementAsync(null, "styleSheet", MainNs).ConfigureAwait(false); + + await w.WriteStartElementAsync(null, "numFmts", MainNs).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "count", null, "1").ConfigureAwait(false); + await w.WriteStartElementAsync(null, "numFmt", MainNs).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "numFmtId", null, "164").ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "formatCode", null, "#,##0.00\\ \"€\"").ConfigureAwait(false); + await w.WriteEndElementAsync().ConfigureAwait(false); + await w.WriteEndElementAsync().ConfigureAwait(false); + + await w.WriteStartElementAsync(null, "fonts", MainNs).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "count", null, "2").ConfigureAwait(false); + foreach (var bold in new[] { false, true }) + { + await w.WriteStartElementAsync(null, "font", MainNs).ConfigureAwait(false); + if (bold) + { + await w.WriteElementStringAsync(null, "b", MainNs, string.Empty).ConfigureAwait(false); + } + + await WriteValElementAsync(w, "sz", "11").ConfigureAwait(false); + await WriteValElementAsync(w, "name", "Calibri").ConfigureAwait(false); + await WriteValElementAsync(w, "family", "2").ConfigureAwait(false); + await w.WriteEndElementAsync().ConfigureAwait(false); + } + + await w.WriteEndElementAsync().ConfigureAwait(false); + + await w.WriteStartElementAsync(null, "fills", MainNs).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "count", null, "2").ConfigureAwait(false); + foreach (var pattern in new[] { "none", "gray125" }) + { + await w.WriteStartElementAsync(null, "fill", MainNs).ConfigureAwait(false); + await w.WriteStartElementAsync(null, "patternFill", MainNs).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "patternType", null, pattern).ConfigureAwait(false); + await w.WriteEndElementAsync().ConfigureAwait(false); + await w.WriteEndElementAsync().ConfigureAwait(false); + } + + await w.WriteEndElementAsync().ConfigureAwait(false); + + await w.WriteStartElementAsync(null, "borders", MainNs).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "count", null, "1").ConfigureAwait(false); + await w.WriteStartElementAsync(null, "border", MainNs).ConfigureAwait(false); + foreach (var side in new[] { "left", "right", "top", "bottom", "diagonal" }) + { + await w.WriteElementStringAsync(null, side, MainNs, string.Empty).ConfigureAwait(false); + } + + await w.WriteEndElementAsync().ConfigureAwait(false); + await w.WriteEndElementAsync().ConfigureAwait(false); + + await w.WriteStartElementAsync(null, "cellStyleXfs", MainNs).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "count", null, "1").ConfigureAwait(false); + await WriteXfAsync(w, numberFormat: 0, font: 0, cellXf: false).ConfigureAwait(false); + await w.WriteEndElementAsync().ConfigureAwait(false); + + // The order matches the Style* constants. + (int NumberFormat, int Font)[] cellXfs = [(0, 0), (0, 1), (14, 0), (22, 0), (3, 0), (4, 0), (164, 0), (10, 0), (49, 0)]; + await w.WriteStartElementAsync(null, "cellXfs", MainNs).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "count", null, cellXfs.Length.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false); + foreach (var (numberFormat, font) in cellXfs) + { + await WriteXfAsync(w, numberFormat, font, cellXf: true).ConfigureAwait(false); + } + + await w.WriteEndElementAsync().ConfigureAwait(false); + + await w.WriteStartElementAsync(null, "cellStyles", MainNs).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "count", null, "1").ConfigureAwait(false); + await w.WriteStartElementAsync(null, "cellStyle", MainNs).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "name", null, "Normal").ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "xfId", null, "0").ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "builtinId", null, "0").ConfigureAwait(false); + await w.WriteEndElementAsync().ConfigureAwait(false); + await w.WriteEndElementAsync().ConfigureAwait(false); + + await w.WriteEndElementAsync().ConfigureAwait(false); + } + + private static async Task WriteValElementAsync(XmlWriter w, string name, string value) + { + await w.WriteStartElementAsync(null, name, MainNs).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "val", null, value).ConfigureAwait(false); + await w.WriteEndElementAsync().ConfigureAwait(false); + } + + private static async Task WriteXfAsync(XmlWriter w, int numberFormat, int font, bool cellXf) + { + await w.WriteStartElementAsync(null, "xf", MainNs).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "numFmtId", null, numberFormat.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "fontId", null, font.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "fillId", null, "0").ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "borderId", null, "0").ConfigureAwait(false); + if (cellXf) + { + await w.WriteAttributeStringAsync(null, "xfId", null, "0").ConfigureAwait(false); + if (numberFormat != 0) + { + await w.WriteAttributeStringAsync(null, "applyNumberFormat", null, "1").ConfigureAwait(false); + } + + if (font != 0) + { + await w.WriteAttributeStringAsync(null, "applyFont", null, "1").ConfigureAwait(false); + } + } + + await w.WriteEndElementAsync().ConfigureAwait(false); + } + + private async Task WriteWorkbookRelationshipsAsync(XmlWriter w) + { + await w.WriteStartElementAsync(null, "Relationships", PackageRelNs).ConfigureAwait(false); + for (var i = 1; i <= _sheetNames.Count; i++) + { + var id = i.ToString(CultureInfo.InvariantCulture); + await WriteRelationshipAsync(w, "rId" + id, RelNs + "/worksheet", "worksheets/sheet" + id + ".xml").ConfigureAwait(false); + } + + var next = _sheetNames.Count + 1; + await WriteRelationshipAsync(w, "rId" + next.ToString(CultureInfo.InvariantCulture), RelNs + "/styles", "styles.xml").ConfigureAwait(false); + if (_options.UseSharedStrings) + { + await WriteRelationshipAsync(w, "rId" + (next + 1).ToString(CultureInfo.InvariantCulture), RelNs + "/sharedStrings", "sharedStrings.xml").ConfigureAwait(false); + } + + await w.WriteEndElementAsync().ConfigureAwait(false); + } + + private static async Task WritePackageRelationshipsAsync(XmlWriter w) + { + await w.WriteStartElementAsync(null, "Relationships", PackageRelNs).ConfigureAwait(false); + await WriteRelationshipAsync(w, "rId1", RelNs + "/officeDocument", "xl/workbook.xml").ConfigureAwait(false); + await w.WriteEndElementAsync().ConfigureAwait(false); + } + + private static async Task WriteRelationshipAsync(XmlWriter w, string id, string type, string target) + { + await w.WriteStartElementAsync(null, "Relationship", PackageRelNs).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "Id", null, id).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "Type", null, type).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "Target", null, target).ConfigureAwait(false); + await w.WriteEndElementAsync().ConfigureAwait(false); + } + + private async Task WriteContentTypesAsync(XmlWriter w) + { + await w.WriteStartElementAsync(null, "Types", ContentTypesNs).ConfigureAwait(false); + await WriteDefaultTypeAsync(w, "rels", "application/vnd.openxmlformats-package.relationships+xml").ConfigureAwait(false); + await WriteDefaultTypeAsync(w, "xml", "application/xml").ConfigureAwait(false); + await WriteOverrideAsync(w, "/xl/workbook.xml", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml").ConfigureAwait(false); + for (var i = 1; i <= _sheetNames.Count; i++) + { + await WriteOverrideAsync(w, "/xl/worksheets/sheet" + i.ToString(CultureInfo.InvariantCulture) + ".xml", WorksheetType).ConfigureAwait(false); + } + + await WriteOverrideAsync(w, "/xl/styles.xml", "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml").ConfigureAwait(false); + if (_options.UseSharedStrings) + { + await WriteOverrideAsync(w, "/xl/sharedStrings.xml", "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml").ConfigureAwait(false); + } + + await w.WriteEndElementAsync().ConfigureAwait(false); + } + + private static async Task WriteDefaultTypeAsync(XmlWriter w, string extension, string contentType) + { + await w.WriteStartElementAsync(null, "Default", ContentTypesNs).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "Extension", null, extension).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "ContentType", null, contentType).ConfigureAwait(false); + await w.WriteEndElementAsync().ConfigureAwait(false); + } + + private static async Task WriteOverrideAsync(XmlWriter w, string part, string contentType) + { + await w.WriteStartElementAsync(null, "Override", ContentTypesNs).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "PartName", null, part).ConfigureAwait(false); + await w.WriteAttributeStringAsync(null, "ContentType", null, contentType).ConfigureAwait(false); + await w.WriteEndElementAsync().ConfigureAwait(false); + } +} diff --git a/src/Khaemhat.Infrastructure/Files/ZipStreamWriter.cs b/src/Khaemhat.Infrastructure/Files/ZipStreamWriter.cs new file mode 100644 index 0000000..e65f95d --- /dev/null +++ b/src/Khaemhat.Infrastructure/Files/ZipStreamWriter.cs @@ -0,0 +1,188 @@ +using System.Globalization; +using System.IO.Compression; +using System.Text; + +namespace Khaemhat.Infrastructure.Files; + +/// +/// Writes a ZIP archive straight to a stream that need not be seekable, such as an HTTP response (SPEC §9.4: mass +/// prints and "Scarica tutto" are streamed, never staged in temporary files). A thin wrapper over +/// in mode that only uses its asynchronous API, cleans +/// entry names and makes duplicates unique (fattura.pdf, fattura (2).pdf). +/// +/// +/// +/// await using var zip = await ZipStreamWriter.CreateAsync(response.Body, leaveOpen: true, cancellationToken); +/// await zip.AddAsync("fattura.pdf", pdfStream, cancellationToken: cancellationToken); +/// await zip.AddAsync("fattura.xml", xmlBytes, cancellationToken: cancellationToken); +/// +/// +public sealed class ZipStreamWriter : IAsyncDisposable +{ + private const int MaxNameLength = 200; + private readonly ZipArchive _archive; + private readonly AsyncOutputBuffer _buffer; + private readonly Stream _output; + private readonly bool _leaveOpen; + private readonly HashSet _names = new(StringComparer.OrdinalIgnoreCase); + private bool _disposed; + + private ZipStreamWriter(ZipArchive archive, AsyncOutputBuffer buffer, Stream output, bool leaveOpen) + { + _archive = archive; + _buffer = buffer; + _output = output; + _leaveOpen = leaveOpen; + } + + /// The number of entries written. + public int Count => _names.Count; + + /// Starts an archive. + /// The stream that receives the archive. + /// Whether to leave open on dispose. + /// Cancellation. + /// The writer; dispose it to write the central directory. + public static async Task CreateAsync(Stream output, bool leaveOpen = false, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(output); + var buffer = new AsyncOutputBuffer(output); + var archive = await ZipArchive.CreateAsync(buffer, ZipArchiveMode.Create, leaveOpen: true, Encoding.UTF8, cancellationToken).ConfigureAwait(false); + return new ZipStreamWriter(archive, buffer, output, leaveOpen); + } + + /// + /// Cleans an entry name: forward slashes for folders, no drive, no .., no leading slash, no characters that + /// Windows refuses, at most 200 characters. + /// + /// The name. + /// The clean name (file when nothing is left). + public static string CleanEntryName(string name) + { + ArgumentNullException.ThrowIfNull(name); + var parts = name.Replace('\\', '/').Split('/', StringSplitOptions.RemoveEmptyEntries) + .Select(CleanSegment) + .Where(p => p.Length > 0 && p != "." && p != "..") + .ToArray(); + var clean = string.Join('/', parts); + if (clean.Length > MaxNameLength) + { + var extension = Path.GetExtension(clean); + clean = clean[..(MaxNameLength - extension.Length)] + extension; + } + + return clean.Length == 0 ? "file" : clean; + } + + /// Adds an entry with the content of a stream, read to the end. + /// The entry name. + /// The content. + /// The date shown for the entry; now when omitted. + /// The compression: suits files already compressed (JPEG, ZIP, P7M). + /// Cancellation. + /// The name actually used (made unique). + public async Task AddAsync( + string entryName, Stream content, DateTimeOffset? lastWrite = null, CompressionLevel level = CompressionLevel.Optimal, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(content); + var (name, target) = await OpenEntryAsync(entryName, lastWrite, level, cancellationToken).ConfigureAwait(false); + await using (target.ConfigureAwait(false)) + { + await content.CopyToAsync(target, cancellationToken).ConfigureAwait(false); + } + + await _buffer.DrainAsync(cancellationToken).ConfigureAwait(false); + return name; + } + + /// Adds an entry with the given bytes. + /// The entry name. + /// The content. + /// The date shown for the entry; now when omitted. + /// The compression. + /// Cancellation. + /// The name actually used (made unique). + public async Task AddAsync( + string entryName, ReadOnlyMemory content, DateTimeOffset? lastWrite = null, CompressionLevel level = CompressionLevel.Optimal, CancellationToken cancellationToken = default) + { + var (name, target) = await OpenEntryAsync(entryName, lastWrite, level, cancellationToken).ConfigureAwait(false); + await using (target.ConfigureAwait(false)) + { + await target.WriteAsync(content, cancellationToken).ConfigureAwait(false); + } + + await _buffer.DrainAsync(cancellationToken).ConfigureAwait(false); + return name; + } + + /// + /// Opens an entry for the caller to write (for example a generator writing a PDF directly into the archive). Write + /// to the stream with asynchronous calls and dispose it before adding the next entry (the few bytes written when it + /// is disposed are sent with the next call). + /// + /// The entry name. + /// The date shown for the entry; now when omitted. + /// The compression. + /// Cancellation. + /// The name actually used and the entry stream. + public async Task<(string Name, Stream Content)> OpenEntryAsync( + string entryName, DateTimeOffset? lastWrite = null, CompressionLevel level = CompressionLevel.Optimal, CancellationToken cancellationToken = default) + { + ObjectDisposedException.ThrowIf(_disposed, this); + await _buffer.DrainAsync(cancellationToken).ConfigureAwait(false); + var name = Unique(CleanEntryName(entryName)); + var entry = _archive.CreateEntry(name, level); + entry.LastWriteTime = lastWrite ?? DateTimeOffset.Now; + var stream = await entry.OpenAsync(cancellationToken).ConfigureAwait(false); + return (name, stream); + } + + /// Writes the central directory and closes the stream unless left open. + /// A task. + public async ValueTask DisposeAsync() + { + if (_disposed) + { + return; + } + + _disposed = true; + await _archive.DisposeAsync().ConfigureAwait(false); + await _buffer.FlushAsync().ConfigureAwait(false); + await _buffer.DisposeAsync().ConfigureAwait(false); + if (!_leaveOpen) + { + await _output.DisposeAsync().ConfigureAwait(false); + } + } + + private static string CleanSegment(string segment) + { + var builder = new StringBuilder(segment.Length); + foreach (var c in segment) + { + builder.Append(char.IsControl(c) || c is ':' or '*' or '?' or '"' or '<' or '>' or '|' ? '_' : c); + } + + return builder.ToString().Trim().TrimEnd('.'); + } + + private string Unique(string name) + { + if (_names.Add(name)) + { + return name; + } + + var extension = Path.GetExtension(name); + var stem = name[..^extension.Length]; + for (var i = 2; ; i++) + { + var candidate = string.Create(CultureInfo.InvariantCulture, $"{stem} ({i}){extension}"); + if (_names.Add(candidate)) + { + return candidate; + } + } + } +} diff --git a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs index 98e017a..bbb4827 100644 --- a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs +++ b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs @@ -1,6 +1,7 @@ using System.Globalization; using Khaemhat.Application.Audit; using Khaemhat.Application.Configuration; +using Khaemhat.Application.Files; using Khaemhat.Application.Instance; using Khaemhat.Application.Jobs; using Khaemhat.Application.Licensing; @@ -10,6 +11,7 @@ using Khaemhat.Application.Notifications; using Khaemhat.Application.Preferences; using Khaemhat.Application.Security; using Khaemhat.Core.Caching; +using Khaemhat.Core.Files; using Khaemhat.Core.Logging; using Khaemhat.Core.Security; using Khaemhat.Data; @@ -20,6 +22,7 @@ using Khaemhat.Data.Migrations; using Khaemhat.Data.PostgreSql; using Khaemhat.Data.Sqlite; using Khaemhat.Infrastructure.Caching; +using Khaemhat.Infrastructure.Files; using Khaemhat.Infrastructure.Licensing; using Khaemhat.Infrastructure.Logging; using Khaemhat.Infrastructure.Security; @@ -144,6 +147,18 @@ internal static class KhaemhatServices services.AddScoped(); services.AddScoped(); services.AddScoped(); + + // Files and attachments (#34): store on the data volume, antivirus hook, attachments, generators, trash job. + services.AddSingleton(FileStoreOptions.ForDataDirectory(options.DataDir)); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); return services; } } diff --git a/tests/Khaemhat.Data.Tests/MappingTests.cs b/tests/Khaemhat.Data.Tests/MappingTests.cs index b12988c..29ab7d2 100644 --- a/tests/Khaemhat.Data.Tests/MappingTests.cs +++ b/tests/Khaemhat.Data.Tests/MappingTests.cs @@ -71,7 +71,7 @@ public sealed class MappingTests [ "sys_companies", "sys_data_protection_keys", "sys_job_locks", "sys_job_runs", "sys_license_activations", "sys_licenses", "sys_log", "sys_notifications", "sys_roles_templates", "sys_scheduled_tasks", "sys_security_audit", "sys_sessions", "sys_settings", "sys_user_settings", "sys_users", - "audit_log", "notifications", "role_permissions", "roles", "user_permission_overrides", "user_roles", "user_sessions", "user_settings", "users", + "attachments", "audit_log", "notifications", "role_permissions", "roles", "user_permission_overrides", "user_roles", "user_sessions", "user_settings", "users", ]; CollectionAssert.AreEquivalent(expected, registry.Maps.Select(m => m.Table).ToArray()); } diff --git a/tests/Khaemhat.Infrastructure.Tests/Files/AsyncOnlyStream.cs b/tests/Khaemhat.Infrastructure.Tests/Files/AsyncOnlyStream.cs new file mode 100644 index 0000000..a825cb2 --- /dev/null +++ b/tests/Khaemhat.Infrastructure.Tests/Files/AsyncOnlyStream.cs @@ -0,0 +1,62 @@ +namespace Khaemhat.Infrastructure.Tests.Files; + +/// +/// A write-only, non-seekable stream that refuses synchronous writes, like an ASP.NET Core response body: the writers +/// must stream to it with asynchronous calls only. +/// +internal sealed class AsyncOnlyStream : Stream +{ + private readonly MemoryStream _inner = new(); + + public override bool CanRead => false; + + public override bool CanSeek => false; + + public override bool CanWrite => true; + + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public bool WasDisposed { get; private set; } + + public byte[] ToArray() => _inner.ToArray(); + + public override void Flush() => throw new InvalidOperationException("Synchronous flush."); + + public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask; + + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new InvalidOperationException("Synchronous write."); + + public override void Write(ReadOnlySpan buffer) => throw new InvalidOperationException("Synchronous write."); + + public override void WriteByte(byte value) => throw new InvalidOperationException("Synchronous write."); + + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + _inner.WriteAsync(buffer, offset, count, cancellationToken); + + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) => + _inner.WriteAsync(buffer, cancellationToken); + + protected override void Dispose(bool disposing) + { + WasDisposed = true; + base.Dispose(disposing); + } + + public override async ValueTask DisposeAsync() + { + WasDisposed = true; + await base.DisposeAsync(); + } +} diff --git a/tests/Khaemhat.Infrastructure.Tests/Files/PdfWriterTests.cs b/tests/Khaemhat.Infrastructure.Tests/Files/PdfWriterTests.cs new file mode 100644 index 0000000..389ba2b --- /dev/null +++ b/tests/Khaemhat.Infrastructure.Tests/Files/PdfWriterTests.cs @@ -0,0 +1,211 @@ +using System.Globalization; +using System.IO.Compression; +using System.Text; +using System.Text.RegularExpressions; +using Khaemhat.Infrastructure.Files; + +namespace Khaemhat.Infrastructure.Tests.Files; + +/// The in-house PDF writer, first version (SPEC §2 "PDF e file", issue #34). +[TestClass] +public sealed partial class PdfWriterTests +{ + private static readonly Encoding Latin1 = Encoding.Latin1; + + [TestMethod] + public async Task Document_HasHeaderTrailerAndXrefOffsetsThatPointAtTheObjects() + { + var bytes = await WriteAsync(async pdf => + { + var first = await pdf.AddPageAsync(); + first.DrawText("Prima pagina", 50, 780, PdfFont.HelveticaBold, 16); + first.DrawLine(50, 770, 545, 770, 1, PdfColor.FromHex("#1F5F8B")); + first.DrawRectangle(50, 700, 200, 40, PdfColor.Black, PdfColor.Gray(230)); + var second = await pdf.AddPageAsync(PdfWriter.A4Height, PdfWriter.A4Width); + second.DrawTextRight("€ 1.234,56", 800, 500, PdfFont.TimesRoman, 10); + await pdf.AddPageAsync(); + Assert.AreEqual(3, pdf.PageCount); + }); + var text = Latin1.GetString(bytes); + + StringAssert.StartsWith(text, "%PDF-1.7\n"); + StringAssert.EndsWith(text, "%%EOF\n"); + StringAssert.Contains(text, "/Type /Pages /Kids ["); + StringAssert.Contains(text, "/Count 3"); + Assert.AreEqual(3, PageObject().Count(text)); + StringAssert.Contains(text, "/MediaBox [0 0 841.89 595.28]"); + + var startxref = long.Parse(StartXref().Match(text).Groups[1].Value, CultureInfo.InvariantCulture); + Assert.AreEqual("xref", text.Substring((int)startxref, 4)); + var header = XrefHeader().Match(text, (int)startxref); + var size = int.Parse(header.Groups[1].Value, CultureInfo.InvariantCulture); + var entries = XrefEntry().Matches(text, header.Index + header.Length).Take(size).ToList(); + Assert.HasCount(size, entries); + Assert.AreEqual("f", entries[0].Groups[3].Value); + for (var i = 1; i < size; i++) + { + var offset = int.Parse(entries[i].Groups[1].Value, CultureInfo.InvariantCulture); + StringAssert.StartsWith(text[offset..], $"{i} 0 obj\n", $"xref entry {i}"); + } + + StringAssert.Contains(text, $"/Size {size} /Root 1 0 R /Info 3 0 R"); + } + + [TestMethod] + public async Task Text_IsWinAnsiEncoded_EuroAndAccentsIncluded() + { + var bytes = await WriteAsync( + async pdf => + { + var page = await pdf.AddPageAsync(); + page.DrawText("Totale € città (prova) \\ fine", 50, 700, PdfFont.Helvetica, 12, PdfColor.FromHex("#FF0000")); + }, + compress: false); + var text = Latin1.GetString(bytes); + + // € is 0x80 (octal 200), à is 0xE0 (octal 340); parentheses and backslash are escaped. + StringAssert.Contains(text, "(Totale \\200 citt\\340 \\(prova\\) \\\\ fine) Tj"); + StringAssert.Contains(text, "1 0 0 rg BT /F1 12 Tf 1 0 0 1 50 700 Tm"); + StringAssert.Contains(text, "/BaseFont /Helvetica /Encoding /WinAnsiEncoding"); + CollectionAssert.AreEqual(new byte[] { 0x80, 0xE0, 0xE8, 0xE9, 0xEC, 0xF2, 0xF9, (byte)'?' }, PdfTextLayout.EncodeWinAnsi("€àèéìòù漢")); + } + + [TestMethod] + public async Task ContentStreams_AreFlateCompressed() + { + var bytes = await WriteAsync(async pdf => (await pdf.AddPageAsync()).DrawText("Compresso è meglio", 50, 700, PdfFont.Courier, 10)); + var text = Latin1.GetString(bytes); + var match = FlateStream().Match(text); + Assert.IsTrue(match.Success); + + var length = int.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture); + var start = match.Index + match.Length; + using var zlib = new ZLibStream(new MemoryStream(bytes, start, length), CompressionMode.Decompress); + using var reader = new StreamReader(zlib, Latin1); + StringAssert.Contains(reader.ReadToEnd(), "(Compresso \\350 meglio) Tj"); + } + + [TestMethod] + public async Task DocumentInfo_IsWritten_WithUnicodeAsUtf16() + { + var info = new PdfDocumentInfo { Title = "Fattura n. 7", Author = "Società Prova", CreationDate = new DateTimeOffset(2026, 11, 11, 10, 30, 0, TimeSpan.Zero) }; + var output = new AsyncOnlyStream(); + await using (var pdf = new PdfWriter(output, info, leaveOpen: true)) + { + await pdf.AddPageAsync(); + } + + var text = Latin1.GetString(output.ToArray()); + StringAssert.Contains(text, "/Title (Fattura n. 7)"); + StringAssert.Contains(text, "/Author Task.CompletedTask)); + + StringAssert.Contains(text, "/Count 1"); + } + + [TestMethod] + public void Jpeg_SizeAndComponents_AreReadFromTheFrameHeader() + { + var info = JpegInfo.Read(TinyJpeg(width: 64, height: 32, components: 3)); + + Assert.AreEqual(new JpegInfo(64, 32, 3, 8, false), info); + Assert.AreEqual(1, JpegInfo.Read(TinyJpeg(10, 10, 1)).Components); + Assert.IsTrue(JpegInfo.Read(TinyJpeg(10, 10, 4, adobe: true)).AdobeInverted); + Assert.ThrowsExactly(() => JpegInfo.Read("not a jpeg"u8)); + Assert.ThrowsExactly(() => JpegInfo.Read(new byte[] { 0xFF, 0xD8, 0xFF, 0xD9 })); + } + + [TestMethod] + public async Task Jpeg_IsEmbeddedAsIs_WithDctDecode() + { + var jpeg = TinyJpeg(64, 32, 3); + var bytes = await WriteAsync(async pdf => + { + var image = pdf.AddJpeg(jpeg); + var page = await pdf.AddPageAsync(); + page.DrawImage(image, 50, 600, 128, 64); + Assert.AreEqual(64, image.Width); + }); + var text = Latin1.GetString(bytes); + + StringAssert.Contains(text, $"/Subtype /Image /Width 64 /Height 32 /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length {jpeg.Length} >>"); + StringAssert.Contains(text, "/XObject << /Im1 "); + Assert.IsGreaterThanOrEqualTo(0, text.IndexOf(Latin1.GetString(jpeg), StringComparison.Ordinal)); + } + + [TestMethod] + public void Measure_UsesTheAfmWidths_AndWrapKeepsLinesInsideTheWidth() + { + // Helvetica: "A" = 667, "i" = 222; Helvetica-Bold: "A" = 722; Courier: 600 for every character. + Assert.AreEqual(6.67, PdfTextLayout.Measure("A", PdfFont.Helvetica, 10), 1e-9); + Assert.AreEqual(8.89, PdfTextLayout.Measure("Ai", PdfFont.Helvetica, 10), 1e-9); + Assert.AreEqual(7.22, PdfTextLayout.Measure("A", PdfFont.HelveticaBold, 10), 1e-9); + Assert.AreEqual(5.56, PdfTextLayout.Measure("€", PdfFont.Helvetica, 10), 1e-9); + Assert.AreEqual(18, PdfTextLayout.Measure("abc", PdfFont.Courier, 10), 1e-9); + Assert.AreEqual(PdfTextLayout.Measure("e", PdfFont.Helvetica, 10), PdfTextLayout.Measure("è", PdfFont.Helvetica, 10)); + + var text = "Questo è un paragrafo abbastanza lungo da andare a capo più volte, con una parolaincredibilmentelunghissimachenonstainriga."; + var lines = PdfTextLayout.Wrap(text, PdfFont.Helvetica, 10, 120); + Assert.IsGreaterThan(2, lines.Count); + Assert.IsTrue(lines.All(l => PdfTextLayout.Measure(l, PdfFont.Helvetica, 10) <= 120)); + Assert.AreEqual(text.Replace(" ", string.Empty, StringComparison.Ordinal), string.Concat(lines).Replace(" ", string.Empty, StringComparison.Ordinal)); + Assert.HasCount(2, PdfTextLayout.Wrap("riga uno\nriga due", PdfFont.Helvetica, 10, 500)); + StringAssert.EndsWith(PdfTextLayout.Fit("Descrizione molto lunga di un articolo", PdfFont.Helvetica, 10, 60), "…"); + } + + private static async Task WriteAsync(Func draw, bool compress = true) + { + var output = new AsyncOnlyStream(); + var pdf = new PdfWriter(output, new PdfDocumentInfo { Title = "Prova" }, leaveOpen: true) { CompressContent = compress }; + await using (pdf) + { + await draw(pdf); + await pdf.CloseAsync(); + } + + return output.ToArray(); + } + + /// The header of a JPEG file built by hand: SOI, APP0 (JFIF), optional APP14 (Adobe), SOF0, EOI. No pixels. + private static byte[] TinyJpeg(int width, int height, int components, bool adobe = false) + { + var bytes = new List { 0xFF, 0xD8 }; + bytes.AddRange([0xFF, 0xE0, 0x00, 0x10, (byte)'J', (byte)'F', (byte)'I', (byte)'F', 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00]); + if (adobe) + { + bytes.AddRange([0xFF, 0xEE, 0x00, 0x0E, (byte)'A', (byte)'d', (byte)'o', (byte)'b', (byte)'e', 0x00, 0x64, 0x00, 0x00, 0x00, 0x00, 0x02]); + } + + var length = 8 + (3 * components); + bytes.AddRange([0xFF, 0xC0, (byte)(length >> 8), (byte)length, 0x08, (byte)(height >> 8), (byte)height, (byte)(width >> 8), (byte)width, (byte)components]); + for (var c = 1; c <= components; c++) + { + bytes.AddRange([(byte)c, 0x11, 0x00]); + } + + bytes.AddRange([0xFF, 0xD9]); + return [.. bytes]; + } + + [GeneratedRegex(@"/Type /Page /Parent")] + private static partial Regex PageObject(); + + [GeneratedRegex(@"startxref\n(\d+)\n%%EOF")] + private static partial Regex StartXref(); + + [GeneratedRegex(@"xref\n0 (\d+)\n")] + private static partial Regex XrefHeader(); + + [GeneratedRegex(@"(\d{10}) (\d{5}) ([nf])\r\n")] + private static partial Regex XrefEntry(); + + [GeneratedRegex(@"<< /Length (\d+) /Filter /FlateDecode >>\nstream\n")] + private static partial Regex FlateStream(); +} diff --git a/tests/Khaemhat.Infrastructure.Tests/Files/SpreadsheetWritersTests.cs b/tests/Khaemhat.Infrastructure.Tests/Files/SpreadsheetWritersTests.cs new file mode 100644 index 0000000..c57bd33 --- /dev/null +++ b/tests/Khaemhat.Infrastructure.Tests/Files/SpreadsheetWritersTests.cs @@ -0,0 +1,213 @@ +using System.IO.Compression; +using System.Text; +using System.Xml; +using Khaemhat.Infrastructure.Files; + +namespace Khaemhat.Infrastructure.Tests.Files; + +/// CSV, ZIP and XLSX written in house (SPEC §2 "PDF e file", issue #34). +[TestClass] +public sealed class SpreadsheetWritersTests +{ + private const string Main = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"; + + [TestMethod] + [DataRow("semplice", "semplice")] + [DataRow("con;separatore", "\"con;separatore\"")] + [DataRow("con \"virgolette\"", "\"con \"\"virgolette\"\"\"")] + [DataRow("a capo\nqui", "\"a capo\nqui\"")] + [DataRow(" spazio", "\" spazio\"")] + [DataRow("=SUM(A1:A9)", "'=SUM(A1:A9)")] + [DataRow("+39 333", "'+39 333")] + [DataRow("-2+3", "'-2+3")] + [DataRow("@cmd", "'@cmd")] + [DataRow("\tTab", "'\tTab")] + [DataRow("=1;2", "\"'=1;2\"")] + public void Csv_TextIsQuotedAndProtected(string value, string expected) => + Assert.AreEqual(expected, CsvWriter.FormatValue(value, CsvOptions.Italian)); + + [TestMethod] + public void Csv_NumbersAreNotProtected_AndFollowTheFormat() + { + Assert.AreEqual("-1234,5", CsvWriter.FormatValue(-1234.5m, CsvOptions.Italian)); + Assert.AreEqual("-1234.5", CsvWriter.FormatValue(-1234.5m, CsvOptions.Invariant)); + Assert.AreEqual("\"0,25\"", CsvWriter.FormatValue(0.25m, CsvOptions.Italian with { Separator = ',' })); + Assert.AreEqual("11/11/2026", CsvWriter.FormatValue(new DateOnly(2026, 11, 11), CsvOptions.Italian)); + Assert.AreEqual("2026-11-11", CsvWriter.FormatValue(new DateTime(2026, 11, 11), CsvOptions.Invariant)); + Assert.AreEqual("VERO", CsvWriter.FormatValue(true, CsvOptions.Italian)); + Assert.AreEqual(string.Empty, CsvWriter.FormatValue(null, CsvOptions.Italian)); + Assert.AreEqual("-5", CsvWriter.FormatValue(-5, CsvOptions.Italian)); + Assert.AreEqual("'-5", CsvWriter.FormatValue("-5", CsvOptions.Italian)); + Assert.AreEqual("-5", CsvWriter.FormatValue("-5", CsvOptions.Italian with { ProtectFormulas = false })); + } + + [TestMethod] + public async Task Csv_StreamsRowsWithBom_AndOnlyAsynchronousWrites() + { + var output = new AsyncOnlyStream(); + await using (var csv = new CsvWriter(output, leaveOpen: true)) + { + await csv.WriteRowAsync(["Descrizione", "Importo"]); + for (var i = 0; i < 2000; i++) + { + await csv.WriteRowAsync(["Riga è più lunga; con separatore", 1234.5m + i]); + } + + Assert.AreEqual(2001, csv.RowCount); + } + + var bytes = output.ToArray(); + CollectionAssert.AreEqual(new byte[] { 0xEF, 0xBB, 0xBF }, bytes[..3]); + var lines = Encoding.UTF8.GetString(bytes, 3, bytes.Length - 3).Split("\r\n"); + Assert.AreEqual("Descrizione;Importo", lines[0]); + Assert.AreEqual("\"Riga è più lunga; con separatore\";1234,5", lines[1]); + Assert.AreEqual(string.Empty, lines[^1]); + Assert.HasCount(2002, lines); + Assert.IsFalse(output.WasDisposed); + } + + [TestMethod] + public void Csv_InvariantOptions_HaveNoBom() + { + using var output = new MemoryStream(); + using (var csv = new CsvWriter(output, CsvOptions.Invariant, leaveOpen: true)) + { + csv.WriteRow("a,b", 1.5m); + } + + Assert.AreEqual("\"a,b\",1.5\r\n", Encoding.UTF8.GetString(output.ToArray())); + } + + [TestMethod] + public async Task Zip_WritesToANonSeekableStream_WithCleanUniqueNames() + { + var output = new AsyncOnlyStream(); + await using (var zip = await ZipStreamWriter.CreateAsync(output, leaveOpen: true)) + { + Assert.AreEqual("fattura.pdf", await zip.AddAsync("fattura.pdf", "uno"u8.ToArray())); + Assert.AreEqual("FATTURA (2).pdf", await zip.AddAsync("FATTURA.pdf", new MemoryStream("due"u8.ToArray()))); + Assert.AreEqual("cartella/file_.txt", await zip.AddAsync("..\\..\\cartella/file?.txt", "tre"u8.ToArray())); + var (name, entry) = await zip.OpenEntryAsync("scritto.txt"); + await using (entry) + { + await entry.WriteAsync("quattro"u8.ToArray()); + } + + Assert.AreEqual("scritto.txt", name); + Assert.AreEqual(4, zip.Count); + } + + using var archive = new ZipArchive(new MemoryStream(output.ToArray()), ZipArchiveMode.Read); + CollectionAssert.AreEqual(new[] { "fattura.pdf", "FATTURA (2).pdf", "cartella/file_.txt", "scritto.txt" }, archive.Entries.Select(e => e.FullName).ToArray()); + using var reader = new StreamReader(archive.GetEntry("FATTURA (2).pdf")!.Open()); + Assert.AreEqual("due", reader.ReadToEnd()); + } + + [TestMethod] + [DataRow("Righe", "Righe")] + [DataRow("a[b]c:d*e?f/g\\h", "abcdefgh")] + [DataRow("'quoted'", "quoted")] + [DataRow("", "Foglio1")] + [DataRow("Un nome di foglio davvero troppo lungo per Excel", "Un nome di foglio davvero tropp")] + public void Xlsx_SheetNamesAreCleaned(string name, string expected) => + Assert.AreEqual(expected, XlsxWriter.CleanSheetName(name, [])); + + [TestMethod] + public void Xlsx_SheetNamesAreUnique_AndColumnsAreLettered() + { + Assert.AreEqual("righe (2)", XlsxWriter.CleanSheetName("righe", ["Righe"])); + Assert.AreEqual(31, XlsxWriter.CleanSheetName(new string('x', 40), [new string('x', 31)]).Length); + Assert.AreEqual("A", XlsxWriter.ColumnName(0)); + Assert.AreEqual("Z", XlsxWriter.ColumnName(25)); + Assert.AreEqual("AA", XlsxWriter.ColumnName(26)); + Assert.AreEqual("XFD", XlsxWriter.ColumnName(16383)); + Assert.AreEqual(46337, XlsxWriter.ToSerialDate(new DateTime(2026, 11, 11))); + } + + [TestMethod] + [DataRow(false)] + [DataRow(true)] + public async Task Xlsx_HasTheRequiredParts_AndTheCellsReadBack(bool sharedStrings) + { + var output = new AsyncOnlyStream(); + await using (var xlsx = await XlsxWriter.CreateAsync(output, new XlsxOptions { UseSharedStrings = sharedStrings }, leaveOpen: true)) + { + await xlsx.StartSheetAsync("Righe/2026", [new("Codice", 12), new("Descrizione", 40), new("Importo", 14, XlsxFormat.Euro), new("Data"), new("Ok")]); + await xlsx.WriteRowAsync(["A1", " Vite à testa piatta ", 1234.5m, new DateTime(2026, 11, 11), true]); + await xlsx.WriteRowAsync(["B2", null, -3, new DateOnly(2026, 1, 1), false]); + await xlsx.StartSheetAsync("Altro"); + await xlsx.WriteRowAsync(["solo testo\u0001"]); + } + + using var archive = new ZipArchive(new MemoryStream(output.ToArray()), ZipArchiveMode.Read); + var parts = archive.Entries.Select(e => e.FullName).ToHashSet(); + foreach (var part in new[] { "[Content_Types].xml", "_rels/.rels", "xl/workbook.xml", "xl/_rels/workbook.xml.rels", "xl/styles.xml", "xl/worksheets/sheet1.xml", "xl/worksheets/sheet2.xml" }) + { + Assert.Contains(part, parts); + } + + Assert.AreEqual(sharedStrings, parts.Contains("xl/sharedStrings.xml")); + var shared = sharedStrings ? ReadSharedStrings(archive) : []; + var cells = ReadCells(archive, "xl/worksheets/sheet1.xml", shared); + + Assert.AreEqual(("Codice", "1"), (cells["A1"].Value, cells["A1"].Style)); + Assert.AreEqual(" Vite à testa piatta ", cells["B2"].Value); + Assert.AreEqual(("1234.5", "6"), (cells["C2"].Value, cells["C2"].Style)); + Assert.AreEqual(("46337", "2"), (cells["D2"].Value, cells["D2"].Style)); + Assert.AreEqual(("1", "b"), (cells["E2"].Value, cells["E2"].Type)); + Assert.IsFalse(cells.ContainsKey("B3"), "A null leaves the cell empty."); + Assert.AreEqual("-3", cells["C3"].Value); + Assert.AreEqual("0", cells["E3"].Value); + Assert.AreEqual("solo testo", ReadCells(archive, "xl/worksheets/sheet2.xml", shared)["A1"].Value); + + var workbook = Read(archive, "xl/workbook.xml"); + StringAssert.Contains(workbook, "name=\"Righe2026\""); + StringAssert.Contains(workbook, "name=\"Altro\""); + StringAssert.Contains(Read(archive, "xl/worksheets/sheet1.xml"), "state=\"frozen\""); + StringAssert.Contains(Read(archive, "xl/worksheets/sheet1.xml"), "customWidth=\"1\""); + } + + private static string Read(ZipArchive archive, string part) + { + using var reader = new StreamReader(archive.GetEntry(part)!.Open()); + return reader.ReadToEnd(); + } + + private static List ReadSharedStrings(ZipArchive archive) + { + var strings = new List(); + using var reader = XmlReader.Create(archive.GetEntry("xl/sharedStrings.xml")!.Open()); + while (reader.ReadToFollowing("t", Main)) + { + strings.Add(reader.ReadElementContentAsString()); + } + + return strings; + } + + private static Dictionary ReadCells(ZipArchive archive, string part, List shared) + { + var cells = new Dictionary(); + using var reader = XmlReader.Create(archive.GetEntry(part)!.Open()); + while (reader.ReadToFollowing("c", Main)) + { + var reference = reader.GetAttribute("r")!; + var style = reader.GetAttribute("s"); + var type = reader.GetAttribute("t"); + using var cell = reader.ReadSubtree(); + var value = string.Empty; + while (cell.Read()) + { + if (cell.NodeType == XmlNodeType.Element && cell.LocalName is "v" or "t") + { + value = cell.ReadElementContentAsString(); + break; + } + } + + cells[reference] = (type == "s" ? shared[int.Parse(value, System.Globalization.CultureInfo.InvariantCulture)] : value, style, type); + } + + return cells; + } +} diff --git a/tests/Khaemhat.Infrastructure.Tests/Files/VolumeFileStoreTests.cs b/tests/Khaemhat.Infrastructure.Tests/Files/VolumeFileStoreTests.cs new file mode 100644 index 0000000..2373800 --- /dev/null +++ b/tests/Khaemhat.Infrastructure.Tests/Files/VolumeFileStoreTests.cs @@ -0,0 +1,145 @@ +using System.Security.Cryptography; +using Khaemhat.Core.Files; +using Khaemhat.Infrastructure.Files; + +namespace Khaemhat.Infrastructure.Tests.Files; + +/// The file store on the data volume (SPEC §9.4, issue #34). +[TestClass] +public sealed class VolumeFileStoreTests +{ + private const string Company = "ACME"; + private string _root = string.Empty; + + [TestInitialize] + public void CreateRoot() => _root = Path.Combine(Path.GetTempPath(), "khaemhat-tests", "files-" + Guid.NewGuid().ToString("N")); + + [TestCleanup] + public void DeleteRoot() + { + if (Directory.Exists(_root)) + { + Directory.Delete(_root, recursive: true); + } + } + + [TestMethod] + public async Task Save_StoresUnderCompanyAndYear_WithSizeAndSha256() + { + var store = NewStore(); + var content = RandomNumberGenerator.GetBytes(200_000); + + var stored = await store.SaveAsync("acme", new MemoryStream(content)); + + StringAssert.Matches(stored.Key, new System.Text.RegularExpressions.Regex("^2026/[0-9a-f]{32}$")); + Assert.AreEqual(content.Length, stored.Size); + Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(content)), stored.Sha256); + Assert.IsTrue(File.Exists(Path.Combine(_root, Company, "2026", stored.Key[5..]))); + Assert.IsEmpty(Directory.GetFiles(_root, "*.part", SearchOption.AllDirectories)); + + await using (var read = store.OpenRead(Company, stored.Key)) + { + using var copy = new MemoryStream(); + await read.CopyToAsync(copy); + CollectionAssert.AreEqual(content, copy.ToArray()); + } + + var usage = await store.GetUsageAsync(Company); + Assert.AreEqual((1L, (long)content.Length), (usage.Files, usage.Bytes)); + Assert.IsTrue(store.Delete(Company, stored.Key)); + Assert.IsFalse(store.Delete(Company, stored.Key)); + Assert.ThrowsExactly(() => store.OpenRead(Company, stored.Key)); + } + + [TestMethod] + public async Task TooLarge_IsRefused_AndLeavesNothingBehind() + { + var store = NewStore(new FileStoreOptions(_root) { MaxFileBytes = 1000 }); + + var error = await Assert.ThrowsExactlyAsync(() => store.SaveAsync(Company, new MemoryStream(new byte[1001]))); + + Assert.AreEqual(FileStoreException.TooLarge, error.Code); + Assert.IsEmpty(Directory.GetFiles(_root, "*", SearchOption.AllDirectories)); + Assert.AreEqual(1000, (await store.SaveAsync(Company, new MemoryStream(new byte[1000]))).Size); + Assert.AreEqual(5000, (await store.SaveAsync(Company, new MemoryStream(new byte[5000]), FileLimits.None)).Size); + } + + [TestMethod] + public async Task Quota_IsCheckedPerCompany() + { + var store = NewStore(); + var limits = new FileLimits(0, 1500); + await store.SaveAsync(Company, new MemoryStream(new byte[1000]), limits); + + var error = await Assert.ThrowsExactlyAsync(() => store.SaveAsync(Company, new MemoryStream(new byte[600]), limits)); + + Assert.AreEqual(FileStoreException.QuotaExceeded, error.Code); + await store.SaveAsync("OTHER", new MemoryStream(new byte[600]), limits); + var usage = await store.GetUsageAsync(Company, 1500); + Assert.AreEqual(500, usage.RemainingBytes); + Assert.IsFalse(usage.IsOverQuota); + } + + [TestMethod] + public async Task Scanner_CanRejectAFile() + { + var store = new VolumeFileStore(new FileStoreOptions(_root), new RejectingScanner(), new FixedClock()); + + var error = await Assert.ThrowsExactlyAsync(() => store.SaveAsync(Company, new MemoryStream("X5O!EICAR"u8.ToArray()))); + + Assert.AreEqual(FileStoreException.Rejected, error.Code); + StringAssert.Contains(error.Message, "EICAR"); + Assert.IsEmpty(Directory.GetFiles(_root, "*", SearchOption.AllDirectories)); + } + + [TestMethod] + public async Task Writer_NotCommitted_IsDiscarded_AndKeysCannotEscapeTheCompanyFolder() + { + var store = NewStore(); + await using (var writer = await store.CreateAsync(Company)) + { + await writer.Content.WriteAsync(new byte[10]); + Assert.HasCount(1, Directory.GetFiles(_root, "*.part", SearchOption.AllDirectories)); + } + + Assert.IsEmpty(Directory.GetFiles(_root, "*", SearchOption.AllDirectories)); + Assert.ThrowsExactly(() => store.OpenRead(Company, "../OTHER/2026/" + new string('a', 32))); + Assert.ThrowsExactly(() => store.Exists(Company, "2026/x")); + Assert.ThrowsExactly(() => store.OpenRead("../etc", "2026/" + new string('a', 32))); + } + + [TestMethod] + public void AbandonedParts_AreRemoved() + { + var store = NewStore(); + var folder = Directory.CreateDirectory(Path.Combine(_root, Company, "2026")).FullName; + var old = Path.Combine(folder, Guid.NewGuid().ToString("N") + ".part"); + File.WriteAllBytes(old, [1, 2, 3]); + File.SetLastWriteTimeUtc(old, new DateTime(2026, 11, 1, 0, 0, 0, DateTimeKind.Utc)); + var recent = Path.Combine(folder, Guid.NewGuid().ToString("N") + ".part"); + File.WriteAllBytes(recent, [1]); + File.SetLastWriteTimeUtc(recent, new DateTime(2026, 11, 11, 9, 0, 0, DateTimeKind.Utc)); + + Assert.AreEqual(1, store.DeleteAbandonedParts(Company, TimeSpan.FromDays(1))); + Assert.IsFalse(File.Exists(old)); + Assert.IsTrue(File.Exists(recent)); + } + + private VolumeFileStore NewStore(FileStoreOptions? options = null) => + new(options ?? new FileStoreOptions(_root), new NoOpFileScanner(), new FixedClock()); + + private sealed class FixedClock : TimeProvider + { + public override DateTimeOffset GetUtcNow() => new(2026, 11, 11, 10, 0, 0, TimeSpan.Zero); + } + + private sealed class RejectingScanner : IFileScanner + { + public async ValueTask ScanAsync(string companyCode, Stream content, CancellationToken cancellationToken = default) + { + using var reader = new StreamReader(content); + var text = await reader.ReadToEndAsync(cancellationToken); + return text.Contains("EICAR", StringComparison.Ordinal) ? new FileScanResult(false, "EICAR test signature") : FileScanResult.Ok; + } + } +} diff --git a/tests/Khaemhat.Web.Tests/Files/AttachmentServiceTests.cs b/tests/Khaemhat.Web.Tests/Files/AttachmentServiceTests.cs new file mode 100644 index 0000000..57bcd67 --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Files/AttachmentServiceTests.cs @@ -0,0 +1,254 @@ +using System.IO.Compression; +using System.Security.Cryptography; +using Khaemhat.Application.Audit; +using Khaemhat.Application.Files; +using Khaemhat.Application.Instance; +using Khaemhat.Application.Jobs; +using Khaemhat.Application.Security; +using Khaemhat.Core.Files; +using Khaemhat.Core.Instance; +using Khaemhat.Core.Security; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Infrastructure.Files; +using Khaemhat.Web.Tests.Hosting; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; + +namespace Khaemhat.Web.Tests.Files; + +/// +/// Attachments and generated files on a real instance (issue #34): versions, download, trash and purge, locks, limits. +/// +[TestClass] +public sealed class AttachmentServiceTests +{ + private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null); + + [TestMethod] + public async Task GeneratedAttachment_IsVersioned_AndRegenerateAddsTheNextVersion() + { + await using var fixture = await Fixture.StartAsync(); + var (attachments, generation, company) = (fixture.Attachments, fixture.Generation, fixture.Company); + + CollectionAssert.AreEqual( + new[] { DemoCsvGenerator.GeneratorCode, DemoPdfGenerator.GeneratorCode, DemoXlsxGenerator.GeneratorCode }, + generation.AvailableFor(DemoDocument.Entity).Select(g => g.Code).ToArray()); + Assert.IsEmpty(generation.AvailableFor("sales.invoice")); + + var v1 = await generation.GenerateAsync(Root, company, DemoDocument.Entity, 7, DemoPdfGenerator.GeneratorCode); + var v2 = await generation.GenerateAsync(Root, company, DemoDocument.Entity, 7, DemoPdfGenerator.GeneratorCode); + await generation.GenerateAsync(Root, company, DemoDocument.Entity, 7, DemoCsvGenerator.GeneratorCode); + await generation.GenerateAsync(Root, company, DemoDocument.Entity, 7, DemoXlsxGenerator.GeneratorCode); + + Assert.AreEqual((1, AttachmentKind.Generated, "documento-di-prova-7.pdf"), (v1.Version, v1.Kind, v1.FileName)); + Assert.AreEqual((2, "v2", "documento-di-prova-7_v2.pdf"), (v2.Version, v2.VersionLabel, v2.FileName)); + Assert.AreEqual((PdfWriter.MediaType, AttachmentPreview.Pdf, DemoPdfGenerator.GeneratorCode), (v2.Mime, v2.Preview, v2.GeneratedBy)); + Assert.AreEqual(TestInstance.SuperUser, v2.CreatedBy); + + var latest = await attachments.ListAsync(Root, company, DemoDocument.Entity, 7); + Assert.HasCount(3, latest); + Assert.AreEqual(v2.Id, latest.Single(a => a.GeneratedBy == DemoPdfGenerator.GeneratorCode).Id); + Assert.IsTrue(latest.All(a => a.IsLatest)); + Assert.AreEqual(3, await attachments.CountAsync(Root, company, DemoDocument.Entity, 7)); + + var all = await attachments.ListAsync(Root, company, DemoDocument.Entity, 7, includeOlderVersions: true); + Assert.HasCount(4, all); + Assert.IsFalse(all.Single(a => a.Id == v1.Id).IsLatest); + Assert.IsEmpty(await attachments.ListAsync(Root, company, DemoDocument.Entity, 8), "Attachments belong to one record only."); + + // The generated PDF is a PDF, and the history records the insert. + await using (var pdf = await attachments.OpenAsync(Root, company, v2.Id)) + { + using var reader = new StreamReader(pdf.Content); + var text = await reader.ReadToEndAsync(); + StringAssert.StartsWith(text, "%PDF-1.7"); + StringAssert.EndsWith(text, "%%EOF\n"); + } + + await using var unitOfWork = await fixture.Factory.CreateAsync(DatabaseScope.Company(company)); + Assert.HasCount(1, await AuditTrail.HistoryAsync(unitOfWork, nameof(Attachment), v2.Id.ToString(System.Globalization.CultureInfo.InvariantCulture))); + Assert.ThrowsExactly(() => generation.GenerateAsync(Root, company, "sales.invoice", 7, DemoPdfGenerator.GeneratorCode).GetAwaiter().GetResult()); + } + + [TestMethod] + public async Task Upload_ThenDownload_ReturnsTheSameBytes() + { + await using var fixture = await Fixture.StartAsync(); + var (attachments, company) = (fixture.Attachments, fixture.Company); + var content = RandomNumberGenerator.GetBytes(300_000); + + var uploaded = await attachments.UploadAsync(Root, company, "sales.invoice", 15, "C:\\Documenti\\ordine cliente.PDF", "text/html", new MemoryStream(content)); + var again = await attachments.UploadAsync(Root, company, "sales.invoice", 15, "Ordine Cliente.pdf", null, new MemoryStream(content[..1000])); + + Assert.AreEqual(("ordine cliente.PDF", MediaTypes.Pdf, AttachmentKind.Uploaded, 1), (uploaded.Name, uploaded.Mime, uploaded.Kind, uploaded.Version)); + Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(content)), uploaded.Sha256); + Assert.AreEqual(content.Length, uploaded.Size); + Assert.AreEqual(2, again.Version, "A file with the same name becomes the next version."); + + await using var download = await attachments.OpenAsync(Root, company, uploaded.Id); + using var copy = new MemoryStream(); + await download.Content.CopyToAsync(copy); + CollectionAssert.AreEqual(content, copy.ToArray()); + Assert.AreEqual(uploaded.Sha256, Convert.ToHexStringLower(SHA256.HashData(copy.ToArray()))); + + // "Scarica tutto": a ZIP with the latest versions. + var csv = await attachments.UploadAsync(Root, company, "sales.invoice", 15, "righe.csv", null, new MemoryStream("a;b\r\n"u8.ToArray())); + using var zipped = new MemoryStream(); + Assert.AreEqual(2, await attachments.WriteZipAsync(Root, company, "sales.invoice", 15, zipped)); + using var zip = new ZipArchive(new MemoryStream(zipped.ToArray()), ZipArchiveMode.Read); + CollectionAssert.AreEquivalent(new[] { "Ordine Cliente_v2.pdf", "righe.csv" }, zip.Entries.Select(e => e.FullName).ToArray()); + Assert.AreEqual(AttachmentPreview.Csv, csv.Preview); + } + + [TestMethod] + public async Task DeletingTheDocument_MovesAttachmentsToTheTrash_AndThePurgeRemovesThemAfter30Days() + { + await using var fixture = await Fixture.StartAsync(); + var (attachments, generation, company) = (fixture.Attachments, fixture.Generation, fixture.Company); + var pdf = await generation.GenerateAsync(Root, company, DemoDocument.Entity, 3, DemoPdfGenerator.GeneratorCode); + var photo = await attachments.UploadAsync(Root, company, DemoDocument.Entity, 3, "foto.jpg", null, new MemoryStream(new byte[100])); + var keys = await fixture.StorageKeysAsync(); + Assert.IsTrue(keys.All(k => fixture.Store.Exists(company, k))); + + Assert.AreEqual(2, await attachments.TrashForEntityAsync(Root, company, DemoDocument.Entity, 3)); + + Assert.IsEmpty(await attachments.ListAsync(Root, company, DemoDocument.Entity, 3)); + CollectionAssert.AreEquivalent(new[] { pdf.Id, photo.Id }, (await attachments.ListTrashAsync(Root, company)).Select(a => a.Id).ToArray()); + await Assert.ThrowsExactlyAsync(() => attachments.OpenAsync(Root, company, pdf.Id)); + + // Restorable within 30 days; deleting one attachment also goes through the trash. + Assert.AreEqual(2, await attachments.RestoreForEntityAsync(Root, company, DemoDocument.Entity, 3)); + await attachments.DeleteAsync(Root, company, photo.Id); + await attachments.RestoreAsync(Root, company, photo.Id); + Assert.HasCount(2, await attachments.ListAsync(Root, company, DemoDocument.Entity, 3)); + await attachments.TrashForEntityAsync(Root, company, DemoDocument.Entity, 3); + + fixture.Clock.Advance(TimeSpan.FromDays(29)); + Assert.AreEqual(0, await attachments.PurgeTrashAsync(company)); + fixture.Clock.Advance(TimeSpan.FromDays(2)); + Assert.AreEqual(2, await attachments.PurgeTrashAsync(company)); + + Assert.IsEmpty(await fixture.StorageKeysAsync()); + Assert.IsTrue(keys.All(k => !fixture.Store.Exists(company, k))); + Assert.IsEmpty(await attachments.ListTrashAsync(Root, company)); + } + + [TestMethod] + public async Task LockedAttachment_CannotBeDeleted_NorItsDocument() + { + await using var fixture = await Fixture.StartAsync(); + var (attachments, company) = (fixture.Attachments, fixture.Company); + var xml = await attachments.AddAsync( + Root, company, "sales.invoice", 21, new AttachmentFile(AttachmentKind.EInvoice, "IT01234567890_00001.xml"), + (output, ct) => output.WriteAsync(""u8.ToArray(), ct).AsTask()); + var other = await attachments.UploadAsync(Root, company, "sales.invoice", 21, "nota.txt", null, new MemoryStream("x"u8.ToArray())); + + await attachments.LockAsync(Root, company, xml.Id); + + Assert.IsTrue((await attachments.GetAsync(Root, company, xml.Id))!.Locked); + Assert.AreEqual((MediaTypes.Xml, AttachmentPreview.Xml), (xml.Mime, xml.Preview)); + var error = await Assert.ThrowsExactlyAsync(() => attachments.DeleteAsync(Root, company, xml.Id)); + CollectionAssert.Contains(error.Errors.ToList(), AttachmentService.LockedError); + await Assert.ThrowsExactlyAsync(() => attachments.TrashForEntityAsync(Root, company, "sales.invoice", 21)); + Assert.HasCount(2, await attachments.ListAsync(Root, company, "sales.invoice", 21), "A refused deletion changes nothing."); + await attachments.DeleteAsync(Root, company, other.Id); + Assert.HasCount(1, await attachments.ListAsync(Root, company, "sales.invoice", 21)); + } + + [TestMethod] + public async Task SizeLimit_IsEnforced_AndUsersStayInTheirCompany() + { + await using var fixture = await Fixture.StartAsync(); + var (attachments, company) = (fixture.Attachments, fixture.Company); + var settings = fixture.App.Services.GetRequiredService(); + Assert.AreEqual(FileLimits.DefaultMaxBytes, (await attachments.GetLimitsAsync()).MaxBytes); + await settings.SetAsync(AttachmentService.MaxUploadSetting, "1"); + + var error = await Assert.ThrowsExactlyAsync( + () => attachments.UploadAsync(Root, company, "sales.invoice", 1, "grande.pdf", null, new MemoryStream(new byte[(1024 * 1024) + 1]))); + + CollectionAssert.Contains(error.Errors.ToList(), AttachmentService.TooLargeError); + Assert.IsEmpty(await attachments.ListAsync(Root, company, "sales.invoice", 1)); + Assert.AreEqual(0, (await attachments.GetUsageAsync(Root, company)).Files); + await attachments.UploadAsync(Root, company, "sales.invoice", 1, "giusto.pdf", null, new MemoryStream(new byte[1024 * 1024])); + await Assert.ThrowsExactlyAsync( + () => attachments.UploadAsync(Root, company, "sales.invoice", 1, "vuoto.pdf", null, new MemoryStream())); + await Assert.ThrowsExactlyAsync( + () => attachments.UploadAsync(Root, company, "Not An Entity", 1, "a.pdf", null, new MemoryStream(new byte[1]))); + + var stranger = new Actor("mario", UserLevel.Standard, null, 1, "ALTRA"); + await Assert.ThrowsExactlyAsync(() => attachments.ListAsync(stranger, company, "sales.invoice", 1)); + var withoutRoles = new Actor("lucia", UserLevel.Standard, null, 999, company); + await Assert.ThrowsExactlyAsync(() => attachments.ListAsync(withoutRoles, company, "sales.invoice", 1)); + await settings.SetAsync(AttachmentService.MaxUploadSetting, null); + } + + [TestMethod] + public async Task TrashPurge_IsASystemTask() + { + await using var fixture = await Fixture.StartAsync(); + var scheduler = fixture.App.Services.GetRequiredService(); + await scheduler.EnsureSystemTasksAsync(); + + Assert.AreEqual(JobOutcome.Succeeded, await scheduler.RunAsync("system.attachments-trash")); + } + + /// A started instance with an attachment service on a clock the test moves. + private sealed class Fixture : IAsyncDisposable + { + private Fixture(WebApplication app, string company) + { + App = app; + Company = company; + var services = app.Services; + Factory = services.GetRequiredService(); + Store = services.GetRequiredService(); + Attachments = new AttachmentService( + Factory, Store, services.GetRequiredService(), services.GetRequiredService(), + services.GetRequiredService(), services.GetRequiredService(), Clock); + Generation = new FileGenerationService(services.GetRequiredService(), Attachments, services.GetRequiredService(), Clock); + } + + public WebApplication App { get; } + + public string Company { get; } + + public MovableClock Clock { get; } = new(); + + public IUnitOfWorkFactory Factory { get; } + + public IFileStore Store { get; } + + public AttachmentService Attachments { get; } + + public FileGenerationService Generation { get; } + + public static async Task StartAsync() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + return new Fixture(app, company); + } + + public async Task> StorageKeysAsync() + { + await using var unitOfWork = await Factory.CreateAsync(DatabaseScope.Company(Company)); + return (await unitOfWork.Repository().ListAsync(Query.For())).Items.Select(a => a.StorageKey).ToList(); + } + + public async ValueTask DisposeAsync() + { + await App.StopAsync(); + await App.DisposeAsync(); + } + } + + private sealed class MovableClock : TimeProvider + { + private DateTimeOffset _now = DateTimeOffset.UtcNow; + + public void Advance(TimeSpan time) => _now += time; + + public override DateTimeOffset GetUtcNow() => _now; + } +}