Merge attachments and file writers (#34) into the M3 branch
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> # Conflicts: # src/Khaemhat.Web/Hosting/KhaemhatServices.cs
This commit is contained in:
commit
d0f9d0e651
26 files changed
+5319
-2
No files matched your search
@@ -701,6 +701,36 @@ Migrazioni applicate in ordine:
|
|||||||
- `core` 20261111004 `create_audit_log` (M20261111_004_CreateAuditLog)
|
- `core` 20261111004 `create_audit_log` (M20261111_004_CreateAuditLog)
|
||||||
- `core` 20261111005 `create_notifications` (M20261111_005_CreateNotifications)
|
- `core` 20261111005 `create_notifications` (M20261111_005_CreateNotifications)
|
||||||
- `core` 20261111006 `create_user_settings` (M20261111_006_CreateUserSettings)
|
- `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`
|
#### `audit_log`
|
||||||
|
|
||||||
|
|||||||
@@ -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 `<KHAEMHAT_DATA_DIR>/files/<AZIENDA>/<aaaa>/<guid>`. Ogni file è scritto
|
||||||
|
prima come `<guid>.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:<codice>`), per gli altri il nome in minuscolo (`name:<nome>`). 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`.
|
||||||
@@ -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;
|
||||||
|
|
||||||
|
/// <summary>An attachment as the interface shows it.</summary>
|
||||||
|
/// <param name="Id">The identifier.</param>
|
||||||
|
/// <param name="Entity">The entity of the owning record.</param>
|
||||||
|
/// <param name="EntityId">The owning record.</param>
|
||||||
|
/// <param name="Kind">Uploaded, generated, e-invoice or notification.</param>
|
||||||
|
/// <param name="Name">The name.</param>
|
||||||
|
/// <param name="FileName">The download name, with the version suffix from v2 (<c>fattura_v2.pdf</c>).</param>
|
||||||
|
/// <param name="Mime">The media type.</param>
|
||||||
|
/// <param name="Size">The size in bytes.</param>
|
||||||
|
/// <param name="Sha256">The SHA-256 of the content.</param>
|
||||||
|
/// <param name="Version">The version, from 1.</param>
|
||||||
|
/// <param name="GeneratedBy">The generator code (generated files).</param>
|
||||||
|
/// <param name="Locked">Whether it is locked (cannot be deleted).</param>
|
||||||
|
/// <param name="IsLatest">Whether it is the latest version of its series.</param>
|
||||||
|
/// <param name="CreatedAt">When it was uploaded or generated (UTC).</param>
|
||||||
|
/// <param name="CreatedBy">Who uploaded or generated it.</param>
|
||||||
|
/// <param name="DeletedAt">When it was moved to the trash; <see langword="null"/> if in use.</param>
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
/// <summary>How the interface can preview the file.</summary>
|
||||||
|
public AttachmentPreview Preview => MediaTypes.PreviewOf(Mime);
|
||||||
|
|
||||||
|
/// <summary>The version label, <c>v1</c>, <c>v2</c>...</summary>
|
||||||
|
public string VersionLabel => "v" + Version.ToString(CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
|
/// <summary>The view of a row.</summary>
|
||||||
|
/// <param name="row">The row.</param>
|
||||||
|
/// <param name="isLatest">Whether it is the latest of its series.</param>
|
||||||
|
/// <returns>The view.</returns>
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>An open attachment: its description and its content. Dispose it to close the file.</summary>
|
||||||
|
/// <param name="attachment">The attachment.</param>
|
||||||
|
/// <param name="content">The content, a read-only seekable stream.</param>
|
||||||
|
public sealed class AttachmentContent(AttachmentView attachment, Stream content) : IAsyncDisposable, IDisposable
|
||||||
|
{
|
||||||
|
/// <summary>The attachment.</summary>
|
||||||
|
public AttachmentView Attachment { get; } = attachment;
|
||||||
|
|
||||||
|
/// <summary>The content.</summary>
|
||||||
|
public Stream Content { get; } = content;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public ValueTask DisposeAsync() => Content.DisposeAsync();
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public void Dispose() => Content.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A file to attach that is not uploaded by a user: an e-invoice, a notification, a file from a procedure.</summary>
|
||||||
|
/// <param name="Kind">The kind.</param>
|
||||||
|
/// <param name="FileName">The file name.</param>
|
||||||
|
/// <param name="Mime">The media type; from the extension when <see langword="null"/>.</param>
|
||||||
|
/// <param name="GeneratedBy">The procedure that produced it: the versions count per this code when set, per name otherwise.</param>
|
||||||
|
/// <param name="Locked">Whether it is locked from the start (for example the XML sent to the SDI).</param>
|
||||||
|
public sealed record AttachmentFile(AttachmentKind Kind, string FileName, string? Mime = null, string? GeneratedBy = null, bool Locked = false);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The attachments of the company records (SPEC §9.4; wiki <i>Allegati e file</i>): upload, generated files with
|
||||||
|
/// versions, list, download, ZIP of all, lock, trash and restore. An attachment belongs to exactly one record
|
||||||
|
/// (<c>entity</c> + <c>entity_id</c>); its bytes are in the <see cref="IFileStore"/>, its row in <c>attachments</c>,
|
||||||
|
/// and every change writes the history (<see cref="AuditTrail"/>).
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// Permissions: reading needs <c>attachments.read</c>, uploading, generating and locking <c>attachments.write</c>,
|
||||||
|
/// deleting and restoring <c>attachments.delete</c>. 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; <see cref="PurgeTrashAsync"/> removes rows and files 30 days later.
|
||||||
|
/// </remarks>
|
||||||
|
public sealed partial class AttachmentService
|
||||||
|
{
|
||||||
|
/// <summary>Permission to see and download attachments.</summary>
|
||||||
|
public const string ReadPermission = "attachments.read";
|
||||||
|
|
||||||
|
/// <summary>Permission to upload and generate attachments.</summary>
|
||||||
|
public const string WritePermission = "attachments.write";
|
||||||
|
|
||||||
|
/// <summary>Permission to delete and restore attachments.</summary>
|
||||||
|
public const string DeletePermission = "attachments.delete";
|
||||||
|
|
||||||
|
/// <summary>The instance setting with the largest upload in MB (default 25).</summary>
|
||||||
|
public const string MaxUploadSetting = "files.max-upload-mb";
|
||||||
|
|
||||||
|
/// <summary>The instance setting with the space each company may use in MB (default: no quota).</summary>
|
||||||
|
public const string CompanyQuotaSetting = "files.company-quota-mb";
|
||||||
|
|
||||||
|
/// <summary>Error: no such attachment (or not in this company).</summary>
|
||||||
|
public const string NotFoundError = "attachments.not_found";
|
||||||
|
|
||||||
|
/// <summary>Error: the attachment is locked.</summary>
|
||||||
|
public const string LockedError = "attachments.locked";
|
||||||
|
|
||||||
|
/// <summary>Error: the file is larger than the limit.</summary>
|
||||||
|
public const string TooLargeError = "attachments.file_too_large";
|
||||||
|
|
||||||
|
/// <summary>Error: the company has no space left.</summary>
|
||||||
|
public const string QuotaError = "attachments.quota_exceeded";
|
||||||
|
|
||||||
|
/// <summary>Error: the scanner rejected the file.</summary>
|
||||||
|
public const string RejectedError = "attachments.file_rejected";
|
||||||
|
|
||||||
|
/// <summary>Error: the entity or record is not valid.</summary>
|
||||||
|
public const string InvalidOwnerError = "attachments.owner_invalid";
|
||||||
|
|
||||||
|
/// <summary>Error: the file is empty.</summary>
|
||||||
|
public const string EmptyError = "attachments.file_empty";
|
||||||
|
|
||||||
|
/// <summary>How long attachments stay in the trash.</summary>
|
||||||
|
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;
|
||||||
|
|
||||||
|
/// <summary>Creates the service.</summary>
|
||||||
|
/// <param name="factory">Opens the company databases.</param>
|
||||||
|
/// <param name="store">The file store.</param>
|
||||||
|
/// <param name="permissions">Checks permissions.</param>
|
||||||
|
/// <param name="audit">Writes the history.</param>
|
||||||
|
/// <param name="settings">Reads the limits set by the administrators.</param>
|
||||||
|
/// <param name="options">The default limits.</param>
|
||||||
|
/// <param name="clock">The clock (trash dates).</param>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The limits in force: the instance settings, else the store defaults (25 MB, no quota).</summary>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The limits for uploads.</returns>
|
||||||
|
public async Task<FileLimits> 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Uploads a file to a record (streaming; the size limit and the quota apply).</summary>
|
||||||
|
/// <param name="actor">Who uploads.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="entity">The entity of the record, for example <c>sales.invoice</c>.</param>
|
||||||
|
/// <param name="entityId">The record.</param>
|
||||||
|
/// <param name="fileName">The file name as received.</param>
|
||||||
|
/// <param name="declaredMime">The type declared by the client (used only when the extension is unknown).</param>
|
||||||
|
/// <param name="content">The content.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The new attachment; a file with the same name as an existing one becomes its next version.</returns>
|
||||||
|
/// <exception cref="AccessDeniedException">The actor may not upload.</exception>
|
||||||
|
/// <exception cref="ValidationFailedException">The file is empty, too large, over quota or rejected.</exception>
|
||||||
|
public async Task<AttachmentView> 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Adds a file produced by Khaemhat, written by <paramref name="write"/> straight into the store. Each call adds
|
||||||
|
/// the next version of the series of <see cref="AttachmentFile.GeneratedBy"/> (or of the name): this is "Rigenera".
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="actor">Who generates.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="entity">The entity of the record.</param>
|
||||||
|
/// <param name="entityId">The record.</param>
|
||||||
|
/// <param name="file">Kind, name, type, generator, lock.</param>
|
||||||
|
/// <param name="write">Writes the content to the stream it receives (write-only, not seekable).</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The new attachment.</returns>
|
||||||
|
/// <exception cref="AccessDeniedException">The actor may not add attachments.</exception>
|
||||||
|
/// <exception cref="ValidationFailedException">The company has no space left, or the file is empty.</exception>
|
||||||
|
public async Task<AttachmentView> AddAsync(
|
||||||
|
Actor actor, string companyCode, string entity, long entityId, AttachmentFile file, Func<Stream, CancellationToken, Task> 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The attachments of a record, newest first (trash excluded).</summary>
|
||||||
|
/// <param name="actor">Who reads.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="entity">The entity.</param>
|
||||||
|
/// <param name="entityId">The record.</param>
|
||||||
|
/// <param name="includeOlderVersions">Whether to list the earlier versions too (marked not <see cref="AttachmentView.IsLatest"/>).</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The attachments.</returns>
|
||||||
|
public async Task<IReadOnlyList<AttachmentView>> 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>How many attachments a record has (latest versions only): the number on the toolbar icon.</summary>
|
||||||
|
/// <param name="actor">Who reads.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="entity">The entity.</param>
|
||||||
|
/// <param name="entityId">The record.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The count.</returns>
|
||||||
|
public async Task<int> CountAsync(Actor actor, string companyCode, string entity, long entityId, CancellationToken cancellationToken = default) =>
|
||||||
|
(await ListAsync(actor, companyCode, entity, entityId, false, cancellationToken).ConfigureAwait(false)).Count;
|
||||||
|
|
||||||
|
/// <summary>One attachment, in use or in the trash.</summary>
|
||||||
|
/// <param name="actor">Who reads.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="attachmentId">The attachment.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The attachment, or <see langword="null"/>.</returns>
|
||||||
|
public async Task<AttachmentView?> 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Opens an attachment for download or preview.</summary>
|
||||||
|
/// <param name="actor">Who reads.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="attachmentId">The attachment.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The attachment and its content; dispose it.</returns>
|
||||||
|
/// <exception cref="KeyNotFoundException">No such attachment in use, or its file is missing.</exception>
|
||||||
|
public async Task<AttachmentContent> 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Writes a ZIP with the latest version of every attachment of a record ("Scarica tutto"), streaming: the output
|
||||||
|
/// can be the HTTP response.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="actor">Who downloads.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="entity">The entity.</param>
|
||||||
|
/// <param name="entityId">The record.</param>
|
||||||
|
/// <param name="output">The stream that receives the ZIP; it is left open.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>How many files were written.</returns>
|
||||||
|
public async Task<int> 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Locks an attachment: from now on it cannot be deleted (for example the XML sent to the SDI). Locks are permanent.</summary>
|
||||||
|
/// <param name="actor">Who locks.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="attachmentId">The attachment.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>A task.</returns>
|
||||||
|
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);
|
||||||
|
|
||||||
|
/// <summary>Moves one attachment to the company trash (restorable for 30 days).</summary>
|
||||||
|
/// <param name="actor">Who deletes.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="attachmentId">The attachment.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>A task.</returns>
|
||||||
|
/// <exception cref="ValidationFailedException">The attachment is locked (<see cref="LockedError"/>).</exception>
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Takes an attachment back from the trash.</summary>
|
||||||
|
/// <param name="actor">Who restores.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="attachmentId">The attachment.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>A task.</returns>
|
||||||
|
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);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="actor">Who deletes the record.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="entity">The entity.</param>
|
||||||
|
/// <param name="entityId">The record.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>How many attachments were moved.</returns>
|
||||||
|
/// <exception cref="ValidationFailedException">An attachment is locked (<see cref="LockedError"/>).</exception>
|
||||||
|
public Task<int> TrashForEntityAsync(Actor actor, string companyCode, string entity, long entityId, CancellationToken cancellationToken = default) =>
|
||||||
|
ChangeEntityAsync(actor, companyCode, entity, entityId, toTrash: true, cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>Takes back from the trash every attachment of a record (the record was restored).</summary>
|
||||||
|
/// <param name="actor">Who restores.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="entity">The entity.</param>
|
||||||
|
/// <param name="entityId">The record.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>How many attachments were restored.</returns>
|
||||||
|
public Task<int> RestoreForEntityAsync(Actor actor, string companyCode, string entity, long entityId, CancellationToken cancellationToken = default) =>
|
||||||
|
ChangeEntityAsync(actor, companyCode, entity, entityId, toTrash: false, cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>The company trash, most recently deleted first.</summary>
|
||||||
|
/// <param name="actor">Who looks (needs <c>attachments.delete</c>).</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The attachments in the trash.</returns>
|
||||||
|
public async Task<IReadOnlyList<AttachmentView>> 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<Attachment, long>().ListAsync(
|
||||||
|
Query.For<Attachment>().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();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The space the company uses in the file store, with the quota in force.</summary>
|
||||||
|
/// <param name="actor">Who looks.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The usage.</returns>
|
||||||
|
public async Task<FileUsage> 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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 <see cref="AttachmentTrashPurgeJob"/>.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>How many attachments were removed.</returns>
|
||||||
|
public async Task<int> 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<Attachment, long>();
|
||||||
|
var rows = (await repository.ListAsync(Query.For<Attachment>().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<AttachmentView> Views(IReadOnlyList<Attachment> 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<bool> IsLatestAsync(IUnitOfWork unitOfWork, Attachment row, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var (entity, id, key, version) = (row.Entity, row.EntityId, row.VersionKey, row.Version);
|
||||||
|
return await unitOfWork.Repository<Attachment, long>().CountAsync(
|
||||||
|
Query.For<Attachment>().Where(a => a.Entity == entity && a.EntityId == id && a.VersionKey == key && a.Version > version),
|
||||||
|
cancellationToken).ConfigureAwait(false) == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<bool> StorageKeyInUseAsync(IRepository<Attachment, long> repository, string key, CancellationToken cancellationToken) =>
|
||||||
|
await repository.CountAsync(Query.For<Attachment>().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<string> 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<long?> 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<StoredFile> StoreAsync(string company, FileLimits limits, Func<Stream, CancellationToken, Task> 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<AttachmentView> 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<AttachmentView> 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, long>();
|
||||||
|
Attachment? row = null;
|
||||||
|
await unitOfWork.InTransactionAsync(
|
||||||
|
async ct =>
|
||||||
|
{
|
||||||
|
var last = await repository.FindAsync(
|
||||||
|
Query.For<Attachment>().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<Attachment, bool> 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<Attachment, long>();
|
||||||
|
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<int> 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<Attachment, long>();
|
||||||
|
await unitOfWork.InTransactionAsync(
|
||||||
|
async ct =>
|
||||||
|
{
|
||||||
|
var query = toTrash
|
||||||
|
? Query.For<Attachment>().Where(a => a.Entity == entity && a.EntityId == entityId && a.DeletedAt == null)
|
||||||
|
: Query.For<Attachment>().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<IReadOnlyList<Attachment>> 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<Attachment, long>().ListAsync(
|
||||||
|
Query.For<Attachment>().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<Attachment, long>().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,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Khaemhat.Application.Jobs;
|
||||||
|
using Khaemhat.Core.Instance;
|
||||||
|
using Khaemhat.Data.Companies;
|
||||||
|
|
||||||
|
namespace Khaemhat.Application.Files;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="attachments">The attachments.</param>
|
||||||
|
/// <param name="companies">The companies.</param>
|
||||||
|
public sealed class AttachmentTrashPurgeJob(AttachmentService attachments, ICompanyRegistry companies) : IScheduledJob
|
||||||
|
{
|
||||||
|
/// <summary>The job type.</summary>
|
||||||
|
public const string JobType = "system.attachments-trash";
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string Type => JobType;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<string?> 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.");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,238 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Khaemhat.Infrastructure.Files;
|
||||||
|
|
||||||
|
namespace Khaemhat.Application.Files;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The <i>documento di prova</i> of issue #34: a clearly fictitious document (entity <see cref="Entity"/>) used to try
|
||||||
|
/// attachments, generation, versions and print preview before the real documents exist (M5). Every value is invented.
|
||||||
|
/// </summary>
|
||||||
|
public static class DemoDocument
|
||||||
|
{
|
||||||
|
/// <summary>The entity of the test document.</summary>
|
||||||
|
public const string Entity = "demo.document";
|
||||||
|
|
||||||
|
/// <summary>The title printed on the test document.</summary>
|
||||||
|
public const string Title = "Documento di prova";
|
||||||
|
|
||||||
|
/// <summary>The fictitious lines: code, description, quantity, unit price.</summary>
|
||||||
|
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),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>The headers of the line table.</summary>
|
||||||
|
public static IReadOnlyList<string> Headers { get; } = ["Codice", "Descrizione", "Quantità", "Prezzo unitario", "Importo"];
|
||||||
|
|
||||||
|
/// <summary>The amount of a line.</summary>
|
||||||
|
/// <param name="line">The line.</param>
|
||||||
|
/// <returns>Quantity times unit price, rounded to cents.</returns>
|
||||||
|
public static decimal Amount((string Code, string Description, decimal Quantity, decimal UnitPrice) line) =>
|
||||||
|
Math.Round(line.Quantity * line.UnitPrice, 2, MidpointRounding.AwayFromZero);
|
||||||
|
|
||||||
|
/// <summary>The total of the lines.</summary>
|
||||||
|
public static decimal Total => Lines.Sum(Amount);
|
||||||
|
|
||||||
|
/// <summary>An amount in euro as Italians write it: <c>€ 1.234,56</c>.</summary>
|
||||||
|
/// <param name="value">The amount.</param>
|
||||||
|
/// <param name="culture">The culture (it-IT).</param>
|
||||||
|
/// <returns>The text.</returns>
|
||||||
|
public static string Euro(decimal value, CultureInfo culture) =>
|
||||||
|
(value < 0 ? "-€ " : "€ ") + Math.Abs(value).ToString("N2", culture);
|
||||||
|
|
||||||
|
/// <summary>The file name stem for a record.</summary>
|
||||||
|
/// <param name="context">The record.</param>
|
||||||
|
/// <returns>For example <c>documento-di-prova-7</c>.</returns>
|
||||||
|
public static string Stem(FileGenerationContext context)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(context);
|
||||||
|
return "documento-di-prova-" + context.EntityId.ToString(CultureInfo.InvariantCulture);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The test PDF of the test document: title, a paragraph and the table of lines with amounts aligned right.</summary>
|
||||||
|
public sealed class DemoPdfGenerator : IFileGenerator
|
||||||
|
{
|
||||||
|
/// <summary>The generator code.</summary>
|
||||||
|
public const string GeneratorCode = "demo.test-pdf";
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string Code => GeneratorCode;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string TitleKey => "files.generators.demo_pdf";
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string MediaType => PdfWriter.MediaType;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string Extension => ".pdf";
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public bool Supports(string entity) => entity == DemoDocument.Entity;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string FileName(FileGenerationContext context) => DemoDocument.Stem(context) + Extension;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The lines of the test document as CSV (Italian Excel: <c>;</c>, decimal comma, BOM).</summary>
|
||||||
|
public sealed class DemoCsvGenerator : IFileGenerator
|
||||||
|
{
|
||||||
|
/// <summary>The generator code.</summary>
|
||||||
|
public const string GeneratorCode = "demo.test-csv";
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string Code => GeneratorCode;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string TitleKey => "files.generators.demo_csv";
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string MediaType => MediaTypes.Csv;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string Extension => ".csv";
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public bool Supports(string entity) => entity == DemoDocument.Entity;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string FileName(FileGenerationContext context) => DemoDocument.Stem(context) + "-righe" + Extension;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The lines of the test document as an XLSX sheet with bold header and euro amounts.</summary>
|
||||||
|
public sealed class DemoXlsxGenerator : IFileGenerator
|
||||||
|
{
|
||||||
|
/// <summary>The generator code.</summary>
|
||||||
|
public const string GeneratorCode = "demo.test-xlsx";
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string Code => GeneratorCode;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string TitleKey => "files.generators.demo_xlsx";
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string MediaType => XlsxWriter.MediaType;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string Extension => ".xlsx";
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public bool Supports(string entity) => entity == DemoDocument.Entity;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string FileName(FileGenerationContext context) => DemoDocument.Stem(context) + "-righe" + Extension;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Khaemhat.Application.Security;
|
||||||
|
using Khaemhat.Core.Files;
|
||||||
|
using Khaemhat.Data;
|
||||||
|
|
||||||
|
namespace Khaemhat.Application.Files;
|
||||||
|
|
||||||
|
/// <summary>What a generator receives besides the output stream.</summary>
|
||||||
|
/// <param name="Actor">Who asked for the file (the generator reads data on its behalf).</param>
|
||||||
|
/// <param name="CompanyCode">The company.</param>
|
||||||
|
/// <param name="Entity">The entity of the record, for example <c>sales.invoice</c>.</param>
|
||||||
|
/// <param name="EntityId">The record.</param>
|
||||||
|
/// <param name="Culture">The culture of numbers, dates and texts (it-IT).</param>
|
||||||
|
/// <param name="Now">When the file is generated (UTC).</param>
|
||||||
|
public sealed record FileGenerationContext(Actor Actor, string CompanyCode, string Entity, long EntityId, CultureInfo Culture, DateTime Now);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// An output of the <i>Genera file</i> section (SPEC §9.4): print PDF, XML FatturaPA, rows in XLSX/CSV, courtesy ZIP...
|
||||||
|
/// Modules register theirs as <see cref="IFileGenerator"/> singletons; <see cref="FileGenerationService"/> runs them.
|
||||||
|
/// </summary>
|
||||||
|
public interface IFileGenerator
|
||||||
|
{
|
||||||
|
/// <summary>The unique code, also written in <c>attachments.generated_by</c> (versions count per code), for example <c>sales.invoice.pdf</c>.</summary>
|
||||||
|
string Code { get; }
|
||||||
|
|
||||||
|
/// <summary>The text key of the label shown in the interface (Italian text in the Web resources).</summary>
|
||||||
|
string TitleKey { get; }
|
||||||
|
|
||||||
|
/// <summary>The media type of the output.</summary>
|
||||||
|
string MediaType { get; }
|
||||||
|
|
||||||
|
/// <summary>The extension of the output, with the dot (<c>.pdf</c>).</summary>
|
||||||
|
string Extension { get; }
|
||||||
|
|
||||||
|
/// <summary>Whether the generator applies to records of an entity.</summary>
|
||||||
|
/// <param name="entity">The entity.</param>
|
||||||
|
/// <returns><see langword="true"/> if it does.</returns>
|
||||||
|
bool Supports(string entity);
|
||||||
|
|
||||||
|
/// <summary>The file name for a record, with extension (for example <c>Fattura-2026-15.pdf</c>).</summary>
|
||||||
|
/// <param name="context">The record.</param>
|
||||||
|
/// <returns>The file name.</returns>
|
||||||
|
string FileName(FileGenerationContext context);
|
||||||
|
|
||||||
|
/// <summary>Writes the file. The stream is write-only and not seekable; write with asynchronous calls.</summary>
|
||||||
|
/// <param name="context">The record.</param>
|
||||||
|
/// <param name="output">The stream that receives the file; do not close it.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>A task.</returns>
|
||||||
|
Task GenerateAsync(FileGenerationContext context, Stream output, CancellationToken cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The registered generators, by code.</summary>
|
||||||
|
public sealed class FileGeneratorRegistry
|
||||||
|
{
|
||||||
|
private readonly Dictionary<string, IFileGenerator> _byCode;
|
||||||
|
|
||||||
|
/// <summary>Creates the registry.</summary>
|
||||||
|
/// <param name="generators">The generators (codes must be unique).</param>
|
||||||
|
public FileGeneratorRegistry(IEnumerable<IFileGenerator> generators)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(generators);
|
||||||
|
_byCode = new Dictionary<string, IFileGenerator>(StringComparer.Ordinal);
|
||||||
|
foreach (var generator in generators)
|
||||||
|
{
|
||||||
|
if (!_byCode.TryAdd(generator.Code, generator))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException($"Two file generators have code {generator.Code}.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Every generator, by code.</summary>
|
||||||
|
public IReadOnlyCollection<IFileGenerator> All => _byCode.Values;
|
||||||
|
|
||||||
|
/// <summary>The generator with a code.</summary>
|
||||||
|
/// <param name="code">The code.</param>
|
||||||
|
/// <returns>The generator, or <see langword="null"/>.</returns>
|
||||||
|
public IFileGenerator? Find(string code) => _byCode.GetValueOrDefault(code);
|
||||||
|
|
||||||
|
/// <summary>The generators that apply to an entity, by code.</summary>
|
||||||
|
/// <param name="entity">The entity.</param>
|
||||||
|
/// <returns>The generators.</returns>
|
||||||
|
public IReadOnlyList<IFileGenerator> For(string entity) =>
|
||||||
|
_byCode.Values.Where(g => g.Supports(entity)).OrderBy(g => g.Code, StringComparer.Ordinal).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Runs the generators (SPEC §9.4): <see cref="GenerateAsync"/> writes the file straight into the file store and
|
||||||
|
/// records it as a generated attachment of the record, with the next version (<c>v1</c>, <c>v2</c>... "Rigenera");
|
||||||
|
/// <see cref="WriteAsync"/> writes it to any stream without keeping it (print preview, direct download).
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="registry">The generators.</param>
|
||||||
|
/// <param name="attachments">Records the generated files.</param>
|
||||||
|
/// <param name="permissions">Checks permissions for <see cref="WriteAsync"/>.</param>
|
||||||
|
/// <param name="clock">The clock.</param>
|
||||||
|
public sealed class FileGenerationService(FileGeneratorRegistry registry, AttachmentService attachments, PermissionService permissions, TimeProvider clock)
|
||||||
|
{
|
||||||
|
/// <summary>Error: no generator with that code applies to the record.</summary>
|
||||||
|
public const string UnknownGeneratorError = "attachments.generator_unknown";
|
||||||
|
|
||||||
|
private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT");
|
||||||
|
|
||||||
|
/// <summary>The generators that apply to an entity (the <i>Genera file</i> list).</summary>
|
||||||
|
/// <param name="entity">The entity.</param>
|
||||||
|
/// <returns>The generators.</returns>
|
||||||
|
public IReadOnlyList<IFileGenerator> AvailableFor(string entity) => registry.For(entity);
|
||||||
|
|
||||||
|
/// <summary>Generates a file and attaches it to the record as the next version of the generator's series.</summary>
|
||||||
|
/// <param name="actor">Who generates (needs <c>attachments.write</c>).</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="entity">The entity.</param>
|
||||||
|
/// <param name="entityId">The record.</param>
|
||||||
|
/// <param name="generatorCode">The generator.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The new attachment.</returns>
|
||||||
|
/// <exception cref="ValidationFailedException">No such generator for the entity (<see cref="UnknownGeneratorError"/>).</exception>
|
||||||
|
public Task<AttachmentView> 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Generates a file into a stream without attaching it (print preview, report download).</summary>
|
||||||
|
/// <param name="actor">Who asks (needs <c>attachments.read</c>).</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="entity">The entity.</param>
|
||||||
|
/// <param name="entityId">The record.</param>
|
||||||
|
/// <param name="generatorCode">The generator.</param>
|
||||||
|
/// <param name="output">The stream; left open.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The file name and media type of what was written.</returns>
|
||||||
|
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);
|
||||||
|
}
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace Khaemhat.Application.Files;
|
||||||
|
|
||||||
|
/// <summary>How the interface can show a file in the preview (SPEC §9.4: PDF, images, XML, CSV/XLSX).</summary>
|
||||||
|
public enum AttachmentPreview
|
||||||
|
{
|
||||||
|
/// <summary>No preview: the file can only be downloaded.</summary>
|
||||||
|
None = 0,
|
||||||
|
|
||||||
|
/// <summary>The integrated PDF viewer.</summary>
|
||||||
|
Pdf = 1,
|
||||||
|
|
||||||
|
/// <summary>An image, at full size with zoom.</summary>
|
||||||
|
Image = 2,
|
||||||
|
|
||||||
|
/// <summary>XML, formatted and indented.</summary>
|
||||||
|
Xml = 3,
|
||||||
|
|
||||||
|
/// <summary>CSV, as a grid.</summary>
|
||||||
|
Csv = 4,
|
||||||
|
|
||||||
|
/// <summary>XLSX, as a grid.</summary>
|
||||||
|
Xlsx = 5,
|
||||||
|
|
||||||
|
/// <summary>Plain text.</summary>
|
||||||
|
Text = 6,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public static class MediaTypes
|
||||||
|
{
|
||||||
|
/// <summary>The type of unknown content.</summary>
|
||||||
|
public const string OctetStream = "application/octet-stream";
|
||||||
|
|
||||||
|
/// <summary>PDF.</summary>
|
||||||
|
public const string Pdf = "application/pdf";
|
||||||
|
|
||||||
|
/// <summary>CSV.</summary>
|
||||||
|
public const string Csv = "text/csv";
|
||||||
|
|
||||||
|
/// <summary>XLSX.</summary>
|
||||||
|
public const string Xlsx = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
|
||||||
|
|
||||||
|
/// <summary>ZIP.</summary>
|
||||||
|
public const string Zip = "application/zip";
|
||||||
|
|
||||||
|
/// <summary>XML.</summary>
|
||||||
|
public const string Xml = "application/xml";
|
||||||
|
|
||||||
|
/// <summary>The longest file name kept.</summary>
|
||||||
|
public const int MaxFileNameLength = 255;
|
||||||
|
|
||||||
|
private static readonly Dictionary<string, string> 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",
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>The media type of a file: from its extension when known, else the declared type when well formed.</summary>
|
||||||
|
/// <param name="fileName">The file name.</param>
|
||||||
|
/// <param name="declared">The type declared by the client, if any.</param>
|
||||||
|
/// <returns>The media type.</returns>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>How a file can be previewed.</summary>
|
||||||
|
/// <param name="mime">The media type.</param>
|
||||||
|
/// <returns>The preview.</returns>
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Cleans a file name: no folders, no control characters or characters Windows refuses, at most 255 characters
|
||||||
|
/// keeping the extension; <c>file</c> when nothing is left.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="fileName">The name as received.</param>
|
||||||
|
/// <returns>The clean name.</returns>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The download name of a version: <c>name.pdf</c> for v1, <c>name_v2.pdf</c> after.</summary>
|
||||||
|
/// <param name="name">The attachment name.</param>
|
||||||
|
/// <param name="version">The version.</param>
|
||||||
|
/// <returns>The file name.</returns>
|
||||||
|
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 '-');
|
||||||
|
}
|
||||||
@@ -49,12 +49,13 @@ public sealed record SystemTaskDefinition(string Code, string Name, string JobTy
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class JobScheduler
|
public sealed class JobScheduler
|
||||||
{
|
{
|
||||||
/// <summary>The system tasks of M2.</summary>
|
/// <summary>The system tasks (M2, attachments trash from M3).</summary>
|
||||||
public static readonly IReadOnlyList<SystemTaskDefinition> SystemTasks =
|
public static readonly IReadOnlyList<SystemTaskDefinition> SystemTasks =
|
||||||
[
|
[
|
||||||
new("system.sessions-cleanup", "Pulizia sessioni scadute", SessionCleanupJob.JobType, "15 * * * *", 300),
|
new("system.sessions-cleanup", "Pulizia sessioni scadute", SessionCleanupJob.JobType, "15 * * * *", 300),
|
||||||
new("system.license-check", "Verifica licenza", LicenseCheckJob.JobType, "0 * * * *", 120),
|
new("system.license-check", "Verifica licenza", LicenseCheckJob.JobType, "0 * * * *", 120),
|
||||||
new("system.log-retention", "Conservazione del log", LogRetentionJob.JobType, "30 3 * * *", 1800),
|
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;
|
private readonly IUnitOfWorkFactory _factory;
|
||||||
|
|||||||
@@ -0,0 +1,80 @@
|
|||||||
|
using Khaemhat.Core.Entities;
|
||||||
|
|
||||||
|
namespace Khaemhat.Core.Files;
|
||||||
|
|
||||||
|
/// <summary>Where an attachment comes from (SPEC §9.4).</summary>
|
||||||
|
public enum AttachmentKind
|
||||||
|
{
|
||||||
|
/// <summary>A file uploaded by a user (the customer's order, a photo, a spreadsheet).</summary>
|
||||||
|
Uploaded = 0,
|
||||||
|
|
||||||
|
/// <summary>A file produced by Khaemhat (print PDF, exported rows, courtesy ZIP).</summary>
|
||||||
|
Generated = 1,
|
||||||
|
|
||||||
|
/// <summary>An electronic invoice (FatturaPA XML, P7M) issued or received.</summary>
|
||||||
|
EInvoice = 2,
|
||||||
|
|
||||||
|
/// <summary>A notification of the exchange system (SDI receipts).</summary>
|
||||||
|
Notification = 3,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A file that belongs to exactly one record of the company (<c>attachments</c>, 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
|
||||||
|
/// <see cref="StorageKey"/>; the row keeps name, type, size, SHA-256 and version.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// Versions are numbered per <see cref="VersionKey"/> inside the record: a generated file counts per generator code
|
||||||
|
/// (<see cref="GeneratedBy"/>), so "Rigenera" adds <c>v2</c>, <c>v3</c>...; 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).
|
||||||
|
/// </remarks>
|
||||||
|
public sealed class Attachment : Entity<long>
|
||||||
|
{
|
||||||
|
/// <summary>The entity of the owning record, for example <c>sales.invoice</c> or <c>parties.party</c>.</summary>
|
||||||
|
public string Entity { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>The identifier of the owning record.</summary>
|
||||||
|
public long EntityId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Where the file comes from.</summary>
|
||||||
|
public AttachmentKind Kind { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The file name shown and used for downloads (without the version suffix).</summary>
|
||||||
|
public string Name { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>The media type, for example <c>application/pdf</c>.</summary>
|
||||||
|
public string Mime { get; set; } = "application/octet-stream";
|
||||||
|
|
||||||
|
/// <summary>The size in bytes.</summary>
|
||||||
|
public long Size { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The SHA-256 of the content, 64 lowercase hexadecimal characters.</summary>
|
||||||
|
public string Sha256 { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>The version inside <see cref="VersionKey"/>, from 1.</summary>
|
||||||
|
public int Version { get; set; } = 1;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The series the version counts in: <c>gen:<generator code></c> for generated files, <c>name:<lowercase
|
||||||
|
/// name></c> otherwise. Unique with the record and <see cref="Version"/>.
|
||||||
|
/// </summary>
|
||||||
|
public string VersionKey { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>The template or procedure that produced the file (generated files), for example <c>demo.test-pdf</c>.</summary>
|
||||||
|
public string? GeneratedBy { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Where the bytes are in the company folder of the file store (<c>yyyy/guid</c>).</summary>
|
||||||
|
public string StorageKey { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Who uploaded or generated the file (the actor of the service call). The audit column <c>created_by</c> knows
|
||||||
|
/// the user only inside an HTTP request; this one is always set.
|
||||||
|
/// </summary>
|
||||||
|
public string? UserName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>A locked file (for example the XML sent to the SDI) cannot be deleted or replaced.</summary>
|
||||||
|
public bool Locked { get; set; }
|
||||||
|
|
||||||
|
/// <summary>When the attachment was moved to the company trash; <see langword="null"/> while it is in use.</summary>
|
||||||
|
public DateTime? DeletedAt { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
namespace Khaemhat.Core.Files;
|
||||||
|
|
||||||
|
/// <summary>A file saved in the store.</summary>
|
||||||
|
/// <param name="Key">Where it is in the company folder (<c>yyyy/guid</c>); keep it to open or delete the file.</param>
|
||||||
|
/// <param name="Size">The size in bytes.</param>
|
||||||
|
/// <param name="Sha256">The SHA-256 of the content, lowercase hexadecimal.</param>
|
||||||
|
public sealed record StoredFile(string Key, long Size, string Sha256);
|
||||||
|
|
||||||
|
/// <summary>The space a company uses in the store.</summary>
|
||||||
|
/// <param name="Files">How many files.</param>
|
||||||
|
/// <param name="Bytes">Their total size.</param>
|
||||||
|
/// <param name="QuotaBytes">The quota of the company; 0 means no quota.</param>
|
||||||
|
public sealed record FileUsage(long Files, long Bytes, long QuotaBytes)
|
||||||
|
{
|
||||||
|
/// <summary>The bytes still available; <see cref="long.MaxValue"/> without quota.</summary>
|
||||||
|
public long RemainingBytes => QuotaBytes <= 0 ? long.MaxValue : Math.Max(0, QuotaBytes - Bytes);
|
||||||
|
|
||||||
|
/// <summary>Whether the company uses more than its quota.</summary>
|
||||||
|
public bool IsOverQuota => QuotaBytes > 0 && Bytes > QuotaBytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The limits applied while a file is written.</summary>
|
||||||
|
/// <param name="MaxBytes">The largest file accepted; 0 means no limit.</param>
|
||||||
|
/// <param name="QuotaBytes">The space a company may use in all; 0 means no quota.</param>
|
||||||
|
public sealed record FileLimits(long MaxBytes, long QuotaBytes)
|
||||||
|
{
|
||||||
|
/// <summary>The default size limit of an uploaded file (SPEC §9.4): 25 MB.</summary>
|
||||||
|
public const long DefaultMaxBytes = 25L * 1024 * 1024;
|
||||||
|
|
||||||
|
/// <summary>No limit at all (generated files are bounded by their generator).</summary>
|
||||||
|
public static FileLimits None { get; } = new(0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Why the store refused a file. <see cref="Code"/> is one of the constants of this class.</summary>
|
||||||
|
public sealed class FileStoreException : Exception
|
||||||
|
{
|
||||||
|
/// <summary>The file is larger than <see cref="FileLimits.MaxBytes"/>.</summary>
|
||||||
|
public const string TooLarge = "file_too_large";
|
||||||
|
|
||||||
|
/// <summary>The file would take the company over its quota.</summary>
|
||||||
|
public const string QuotaExceeded = "file_quota_exceeded";
|
||||||
|
|
||||||
|
/// <summary>The scanner (<see cref="IFileScanner"/>) rejected the file.</summary>
|
||||||
|
public const string Rejected = "file_rejected";
|
||||||
|
|
||||||
|
/// <summary>The file does not exist in the store.</summary>
|
||||||
|
public const string NotFound = "file_not_found";
|
||||||
|
|
||||||
|
/// <summary>Creates the exception.</summary>
|
||||||
|
public FileStoreException()
|
||||||
|
: this(NotFound, "File store error.")
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Creates the exception.</summary>
|
||||||
|
/// <param name="message">The message.</param>
|
||||||
|
public FileStoreException(string message)
|
||||||
|
: this(NotFound, message)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Creates the exception.</summary>
|
||||||
|
/// <param name="message">The message.</param>
|
||||||
|
/// <param name="innerException">The cause.</param>
|
||||||
|
public FileStoreException(string message, Exception innerException)
|
||||||
|
: base(message, innerException) => Code = NotFound;
|
||||||
|
|
||||||
|
/// <summary>Creates the exception.</summary>
|
||||||
|
/// <param name="code">The error code.</param>
|
||||||
|
/// <param name="message">The message.</param>
|
||||||
|
public FileStoreException(string code, string message)
|
||||||
|
: base(message) => Code = code;
|
||||||
|
|
||||||
|
/// <summary>The error code.</summary>
|
||||||
|
public string Code { get; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A file being written to the store: write the content to <see cref="Content"/>, then call
|
||||||
|
/// <see cref="CommitAsync"/>. Disposing without committing discards what was written.
|
||||||
|
/// </summary>
|
||||||
|
public interface IFileStoreWriter : IAsyncDisposable
|
||||||
|
{
|
||||||
|
/// <summary>The write-only, non-seekable stream that receives the content (it counts bytes and computes SHA-256).</summary>
|
||||||
|
/// <exception cref="FileStoreException">Writing goes past <see cref="FileLimits.MaxBytes"/> (code <see cref="FileStoreException.TooLarge"/>).</exception>
|
||||||
|
Stream Content { get; }
|
||||||
|
|
||||||
|
/// <summary>Completes the file: checks quota and scanner, then makes it visible under its key.</summary>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The stored file.</returns>
|
||||||
|
/// <exception cref="FileStoreException">The file is refused.</exception>
|
||||||
|
Task<StoredFile> CommitAsync(CancellationToken cancellationToken = default);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public interface IFileStore
|
||||||
|
{
|
||||||
|
/// <summary>Saves a file read from a stream.</summary>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="content">The content, read to the end.</param>
|
||||||
|
/// <param name="limits">The limits; <see langword="null"/> for the store defaults.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The stored file.</returns>
|
||||||
|
/// <exception cref="FileStoreException">The file is refused (size, quota, scanner).</exception>
|
||||||
|
Task<StoredFile> SaveAsync(string companyCode, Stream content, FileLimits? limits = null, CancellationToken cancellationToken = default);
|
||||||
|
|
||||||
|
/// <summary>Starts a file that the caller writes (generators, ZIP packages).</summary>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="limits">The limits; <see langword="null"/> for the store defaults.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The writer; dispose it in every case.</returns>
|
||||||
|
Task<IFileStoreWriter> CreateAsync(string companyCode, FileLimits? limits = null, CancellationToken cancellationToken = default);
|
||||||
|
|
||||||
|
/// <summary>Opens a file for reading.</summary>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="key">The key returned when the file was saved.</param>
|
||||||
|
/// <returns>A read-only seekable stream; dispose it.</returns>
|
||||||
|
/// <exception cref="FileStoreException">The file does not exist (code <see cref="FileStoreException.NotFound"/>).</exception>
|
||||||
|
Stream OpenRead(string companyCode, string key);
|
||||||
|
|
||||||
|
/// <summary>Whether a file exists.</summary>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="key">The key.</param>
|
||||||
|
/// <returns><see langword="true"/> if it exists.</returns>
|
||||||
|
bool Exists(string companyCode, string key);
|
||||||
|
|
||||||
|
/// <summary>Deletes a file; nothing happens when it does not exist.</summary>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="key">The key.</param>
|
||||||
|
/// <returns><see langword="true"/> if a file was deleted.</returns>
|
||||||
|
bool Delete(string companyCode, string key);
|
||||||
|
|
||||||
|
/// <summary>The space the company uses, with its quota.</summary>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="quotaBytes">The quota to report; <see langword="null"/> for the store default.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The usage.</returns>
|
||||||
|
Task<FileUsage> GetUsageAsync(string companyCode, long? quotaBytes = null, CancellationToken cancellationToken = default);
|
||||||
|
|
||||||
|
/// <summary>Removes the partial files (<c>.part</c>) left by writes interrupted more than <paramref name="olderThan"/> ago.</summary>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="olderThan">How old a partial file must be.</param>
|
||||||
|
/// <returns>How many were removed.</returns>
|
||||||
|
int DeleteAbandonedParts(string companyCode, TimeSpan olderThan);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The verdict of a scanner.</summary>
|
||||||
|
/// <param name="Clean">Whether the file may be stored.</param>
|
||||||
|
/// <param name="Reason">Why it was refused (for example the name of the threat).</param>
|
||||||
|
public sealed record FileScanResult(bool Clean, string? Reason = null)
|
||||||
|
{
|
||||||
|
/// <summary>The file may be stored.</summary>
|
||||||
|
public static FileScanResult Ok { get; } = new(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public interface IFileScanner
|
||||||
|
{
|
||||||
|
/// <summary>Scans a file.</summary>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="content">The content, readable from the start.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The verdict.</returns>
|
||||||
|
ValueTask<FileScanResult> ScanAsync(string companyCode, Stream content, CancellationToken cancellationToken = default);
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using Khaemhat.Core.Files;
|
||||||
using Khaemhat.Core.Instance;
|
using Khaemhat.Core.Instance;
|
||||||
using Khaemhat.Core.Security;
|
using Khaemhat.Core.Security;
|
||||||
using Khaemhat.Data.Mapping;
|
using Khaemhat.Data.Mapping;
|
||||||
@@ -106,3 +107,21 @@ public sealed class UserSettingMap : EntityMap<UserSetting>
|
|||||||
Map(x => x.Key).MaxLength(200);
|
Map(x => x.Key).MaxLength(200);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Map of <see cref="Attachment"/> to <c>attachments</c>.</summary>
|
||||||
|
public sealed class AttachmentMap : EntityMap<Attachment>
|
||||||
|
{
|
||||||
|
/// <summary>Creates the map.</summary>
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
using Khaemhat.Data.Migrations;
|
||||||
|
using Khaemhat.Data.Schema;
|
||||||
|
|
||||||
|
namespace Khaemhat.Data.CompanyDatabase.Migrations;
|
||||||
|
|
||||||
|
/// <summary>The attachments of the company records, uploaded and generated (SPEC §9.4, ADR 0021).</summary>
|
||||||
|
[Migration(20261111_007, "create_attachments")]
|
||||||
|
public sealed class M20261111_007_CreateAttachments : IMigration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
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");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
namespace Khaemhat.Infrastructure.Files;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Sits between <see cref="System.IO.Compression.ZipArchive"/> 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 <see cref="DrainAsync"/>, while
|
||||||
|
/// the bulk of the data, written asynchronously, goes straight through. Memory stays bounded by the small synchronous
|
||||||
|
/// pieces, so archives are still streamed.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="output">The real output.</param>
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Sends the bytes written synchronously to the output.</summary>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>A task.</returns>
|
||||||
|
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<byte> 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<byte> buffer, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
await DrainAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
await output.WriteAsync(buffer, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Does nothing: synchronous flushes would reach the output synchronously.</summary>
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,310 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace Khaemhat.Infrastructure.Files;
|
||||||
|
|
||||||
|
/// <summary>How numbers and dates are written in a CSV file.</summary>
|
||||||
|
public enum CsvNumberFormat
|
||||||
|
{
|
||||||
|
/// <summary>Italian Excel: decimal comma (<c>1234,5</c>), dates <c>dd/MM/yyyy</c>, booleans <c>VERO</c>/<c>FALSO</c>.</summary>
|
||||||
|
Italian = 0,
|
||||||
|
|
||||||
|
/// <summary>Machine readable: decimal point (<c>1234.5</c>), ISO 8601 dates, booleans <c>true</c>/<c>false</c>.</summary>
|
||||||
|
Invariant = 1,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The options of a <see cref="CsvWriter"/>. The defaults suit Excel in Italian (ADR 0021).</summary>
|
||||||
|
public sealed record CsvOptions
|
||||||
|
{
|
||||||
|
/// <summary>The field separator: <c>;</c> by default, because Italian Excel uses the comma for decimals.</summary>
|
||||||
|
public char Separator { get; init; } = ';';
|
||||||
|
|
||||||
|
/// <summary>Whether the file starts with the UTF-8 byte order mark, which Excel needs to read accented letters.</summary>
|
||||||
|
public bool WriteByteOrderMark { get; init; } = true;
|
||||||
|
|
||||||
|
/// <summary>How numbers, dates and booleans are formatted.</summary>
|
||||||
|
public CsvNumberFormat NumberFormat { get; init; } = CsvNumberFormat.Italian;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Whether text cells that a spreadsheet would read as a formula (starting with <c>=</c>, <c>+</c>, <c>-</c>,
|
||||||
|
/// <c>@</c>, tab or carriage return) get a leading apostrophe (CSV injection, OWASP). Numbers are never changed.
|
||||||
|
/// </summary>
|
||||||
|
public bool ProtectFormulas { get; init; } = true;
|
||||||
|
|
||||||
|
/// <summary>The line terminator: CRLF as RFC 4180 says.</summary>
|
||||||
|
public string NewLine { get; init; } = "\r\n";
|
||||||
|
|
||||||
|
/// <summary>The Italian Excel defaults.</summary>
|
||||||
|
public static CsvOptions Italian { get; } = new();
|
||||||
|
|
||||||
|
/// <summary>Comma separator, invariant numbers, no byte order mark: for other programs.</summary>
|
||||||
|
public static CsvOptions Invariant { get; } = new() { Separator = ',', NumberFormat = CsvNumberFormat.Invariant, WriteByteOrderMark = false };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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
|
||||||
|
/// <c>Async</c> methods when the stream is an HTTP response, where synchronous writes are not allowed.
|
||||||
|
/// </summary>
|
||||||
|
/// <example>
|
||||||
|
/// <code>
|
||||||
|
/// await using var csv = new CsvWriter(response.Body);
|
||||||
|
/// await csv.WriteRowAsync(["Codice", "Descrizione", "Importo"]);
|
||||||
|
/// await csv.WriteRowAsync(["A1", "Vite M4", 12.5m]);
|
||||||
|
/// </code>
|
||||||
|
/// </example>
|
||||||
|
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;
|
||||||
|
|
||||||
|
/// <summary>Creates a writer.</summary>
|
||||||
|
/// <param name="output">The stream that receives the file.</param>
|
||||||
|
/// <param name="options">The options; <see langword="null"/> for <see cref="CsvOptions.Italian"/>.</param>
|
||||||
|
/// <param name="leaveOpen">Whether to leave <paramref name="output"/> open on dispose.</param>
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The options.</summary>
|
||||||
|
public CsvOptions Options { get; }
|
||||||
|
|
||||||
|
/// <summary>The number of rows completed.</summary>
|
||||||
|
public long RowCount { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>Formats a text field: formula protection, then quoting when needed.</summary>
|
||||||
|
/// <param name="value">The text.</param>
|
||||||
|
/// <param name="options">The options.</param>
|
||||||
|
/// <returns>The field as written in the file.</returns>
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Formats a value as it would be written (numbers and dates by <see cref="CsvOptions.NumberFormat"/>).</summary>
|
||||||
|
/// <param name="value">The value.</param>
|
||||||
|
/// <param name="options">The options.</param>
|
||||||
|
/// <returns>The field as written in the file.</returns>
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Adds a field to the current row.</summary>
|
||||||
|
/// <param name="value">Text, number, date, boolean or <see langword="null"/> (empty field).</param>
|
||||||
|
/// <returns>This writer.</returns>
|
||||||
|
public CsvWriter WriteField(object? value)
|
||||||
|
{
|
||||||
|
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||||
|
if (_rowHasFields)
|
||||||
|
{
|
||||||
|
_buffer.Append(Options.Separator);
|
||||||
|
}
|
||||||
|
|
||||||
|
_buffer.Append(FormatValue(value, Options));
|
||||||
|
_rowHasFields = true;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Ends the current row; writes to the stream synchronously when the buffer is large.</summary>
|
||||||
|
public void EndRow()
|
||||||
|
{
|
||||||
|
CompleteRow();
|
||||||
|
if (_buffer.Length >= FlushThreshold)
|
||||||
|
{
|
||||||
|
Flush();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Ends the current row; writes to the stream when the buffer is large.</summary>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>A task.</returns>
|
||||||
|
public async ValueTask EndRowAsync(CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
CompleteRow();
|
||||||
|
if (_buffer.Length >= FlushThreshold)
|
||||||
|
{
|
||||||
|
await FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Writes a whole row (synchronous stream).</summary>
|
||||||
|
/// <param name="values">The fields.</param>
|
||||||
|
public void WriteRow(params IEnumerable<object?> values)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(values);
|
||||||
|
foreach (var value in values)
|
||||||
|
{
|
||||||
|
WriteField(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
EndRow();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Writes a whole row.</summary>
|
||||||
|
/// <param name="values">The fields.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>A task.</returns>
|
||||||
|
public ValueTask WriteRowAsync(IEnumerable<object?> values, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(values);
|
||||||
|
foreach (var value in values)
|
||||||
|
{
|
||||||
|
WriteField(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
return EndRowAsync(cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Writes the buffered rows to the stream synchronously.</summary>
|
||||||
|
public void Flush()
|
||||||
|
{
|
||||||
|
var bytes = TakeBytes();
|
||||||
|
if (bytes.Length > 0)
|
||||||
|
{
|
||||||
|
_output.Write(bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
_output.Flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Writes the buffered rows to the stream.</summary>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>A task.</returns>
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Ends a pending row, writes the buffer synchronously and closes the stream unless left open.</summary>
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
if (_disposed)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_rowHasFields)
|
||||||
|
{
|
||||||
|
CompleteRow();
|
||||||
|
}
|
||||||
|
|
||||||
|
Flush();
|
||||||
|
_disposed = true;
|
||||||
|
if (!_leaveOpen)
|
||||||
|
{
|
||||||
|
_output.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Ends a pending row, writes the buffer and closes the stream unless left open.</summary>
|
||||||
|
/// <returns>A task.</returns>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,317 @@
|
|||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace Khaemhat.Infrastructure.Files;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The standard Type1 fonts every PDF reader has (PDF 1.7 §9.6.2.2), with <c>WinAnsiEncoding</c> so that Italian
|
||||||
|
/// letters and the euro sign print. Symbol and ZapfDingbats are not offered: they have no Latin encoding.
|
||||||
|
/// </summary>
|
||||||
|
public enum PdfFont
|
||||||
|
{
|
||||||
|
/// <summary>Helvetica.</summary>
|
||||||
|
Helvetica = 0,
|
||||||
|
|
||||||
|
/// <summary>Helvetica bold.</summary>
|
||||||
|
HelveticaBold = 1,
|
||||||
|
|
||||||
|
/// <summary>Helvetica oblique.</summary>
|
||||||
|
HelveticaOblique = 2,
|
||||||
|
|
||||||
|
/// <summary>Helvetica bold oblique.</summary>
|
||||||
|
HelveticaBoldOblique = 3,
|
||||||
|
|
||||||
|
/// <summary>Times roman.</summary>
|
||||||
|
TimesRoman = 4,
|
||||||
|
|
||||||
|
/// <summary>Times bold (measured with the Times roman widths).</summary>
|
||||||
|
TimesBold = 5,
|
||||||
|
|
||||||
|
/// <summary>Times italic (measured with the Times roman widths).</summary>
|
||||||
|
TimesItalic = 6,
|
||||||
|
|
||||||
|
/// <summary>Times bold italic (measured with the Times roman widths).</summary>
|
||||||
|
TimesBoldItalic = 7,
|
||||||
|
|
||||||
|
/// <summary>Courier: every character is 600/1000 em wide.</summary>
|
||||||
|
Courier = 8,
|
||||||
|
|
||||||
|
/// <summary>Courier bold.</summary>
|
||||||
|
CourierBold = 9,
|
||||||
|
|
||||||
|
/// <summary>Courier oblique.</summary>
|
||||||
|
CourierOblique = 10,
|
||||||
|
|
||||||
|
/// <summary>Courier bold oblique.</summary>
|
||||||
|
CourierBoldOblique = 11,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Text measuring and line breaking for the standard fonts, from the Adobe font metrics (AFM) widths in thousandths of
|
||||||
|
/// an em, and the <c>WinAnsiEncoding</c> (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.
|
||||||
|
/// </summary>
|
||||||
|
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<char, byte> 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,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>The PostScript name of a font, as written in <c>/BaseFont</c>.</summary>
|
||||||
|
/// <param name="font">The font.</param>
|
||||||
|
/// <returns>The name, for example <c>Helvetica-Bold</c>.</returns>
|
||||||
|
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."),
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Encodes text in <c>WinAnsiEncoding</c>: ASCII, Latin-1 letters (àèéìòù...), the euro sign and the typographic
|
||||||
|
/// quotes and dashes. Line breaks and tabs become spaces; characters the encoding lacks become <c>?</c>.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="text">The text.</param>
|
||||||
|
/// <returns>One byte per character.</returns>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The width of a character code in thousandths of an em.</summary>
|
||||||
|
/// <param name="code">The <c>WinAnsiEncoding</c> code.</param>
|
||||||
|
/// <param name="font">The font.</param>
|
||||||
|
/// <returns>The width.</returns>
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>The width of a text in points.</summary>
|
||||||
|
/// <param name="text">The text.</param>
|
||||||
|
/// <param name="font">The font.</param>
|
||||||
|
/// <param name="size">The font size in points.</param>
|
||||||
|
/// <returns>The width.</returns>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Breaks a text into lines no wider than <paramref name="maxWidth"/>: at line breaks, then between words; a word
|
||||||
|
/// longer than a line is cut.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="text">The text.</param>
|
||||||
|
/// <param name="font">The font.</param>
|
||||||
|
/// <param name="size">The font size.</param>
|
||||||
|
/// <param name="maxWidth">The line width in points.</param>
|
||||||
|
/// <returns>The lines (one empty line for an empty text).</returns>
|
||||||
|
public static IReadOnlyList<string> Wrap(string? text, PdfFont font, double size, double maxWidth)
|
||||||
|
{
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxWidth);
|
||||||
|
var lines = new List<string>();
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Shortens a text with an ellipsis so that it fits a width (table cells).</summary>
|
||||||
|
/// <param name="text">The text.</param>
|
||||||
|
/// <param name="font">The font.</param>
|
||||||
|
/// <param name="size">The font size.</param>
|
||||||
|
/// <param name="maxWidth">The width in points.</param>
|
||||||
|
/// <returns>The text, shortened if needed.</returns>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,679 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.IO.Compression;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace Khaemhat.Infrastructure.Files;
|
||||||
|
|
||||||
|
/// <summary>An RGB colour.</summary>
|
||||||
|
/// <param name="R">Red, 0-255.</param>
|
||||||
|
/// <param name="G">Green, 0-255.</param>
|
||||||
|
/// <param name="B">Blue, 0-255.</param>
|
||||||
|
public readonly record struct PdfColor(byte R, byte G, byte B)
|
||||||
|
{
|
||||||
|
/// <summary>Black.</summary>
|
||||||
|
public static PdfColor Black { get; } = new(0, 0, 0);
|
||||||
|
|
||||||
|
/// <summary>White.</summary>
|
||||||
|
public static PdfColor White { get; } = new(255, 255, 255);
|
||||||
|
|
||||||
|
/// <summary>A grey.</summary>
|
||||||
|
/// <param name="level">0 (black) to 255 (white).</param>
|
||||||
|
/// <returns>The colour.</returns>
|
||||||
|
public static PdfColor Gray(byte level) => new(level, level, level);
|
||||||
|
|
||||||
|
/// <summary>A colour from <c>#RRGGBB</c>.</summary>
|
||||||
|
/// <param name="hex">The colour, with or without <c>#</c>.</param>
|
||||||
|
/// <returns>The colour.</returns>
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The document information dictionary.</summary>
|
||||||
|
public sealed record PdfDocumentInfo
|
||||||
|
{
|
||||||
|
/// <summary>The title.</summary>
|
||||||
|
public string? Title { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The author (the company or the user).</summary>
|
||||||
|
public string? Author { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The subject.</summary>
|
||||||
|
public string? Subject { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Keywords.</summary>
|
||||||
|
public string? Keywords { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The program that created the content.</summary>
|
||||||
|
public string Creator { get; init; } = "Khaemhat";
|
||||||
|
|
||||||
|
/// <summary>When the document was created; now when omitted.</summary>
|
||||||
|
public DateTimeOffset? CreationDate { get; init; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>What the header of a JPEG file says.</summary>
|
||||||
|
/// <param name="Width">Width in pixels.</param>
|
||||||
|
/// <param name="Height">Height in pixels.</param>
|
||||||
|
/// <param name="Components">1 (grey), 3 (RGB/YCbCr) or 4 (CMYK).</param>
|
||||||
|
/// <param name="BitsPerComponent">Bits per component, normally 8.</param>
|
||||||
|
/// <param name="AdobeInverted">An Adobe CMYK JPEG, whose components are stored inverted.</param>
|
||||||
|
public sealed record JpegInfo(int Width, int Height, int Components, int BitsPerComponent, bool AdobeInverted)
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="jpeg">The file.</param>
|
||||||
|
/// <returns>The header.</returns>
|
||||||
|
/// <exception cref="InvalidDataException">The data is not a JPEG file the PDF can embed.</exception>
|
||||||
|
public static JpegInfo Read(ReadOnlySpan<byte> 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).");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>An image added to a document; draw it on any page with <see cref="PdfPage.DrawImage"/>.</summary>
|
||||||
|
public sealed class PdfImage
|
||||||
|
{
|
||||||
|
internal PdfImage(int objectNumber, string name, JpegInfo info)
|
||||||
|
{
|
||||||
|
ObjectNumber = objectNumber;
|
||||||
|
Name = name;
|
||||||
|
Info = info;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Width in pixels.</summary>
|
||||||
|
public int Width => Info.Width;
|
||||||
|
|
||||||
|
/// <summary>Height in pixels.</summary>
|
||||||
|
public int Height => Info.Height;
|
||||||
|
|
||||||
|
/// <summary>The JPEG header.</summary>
|
||||||
|
public JpegInfo Info { get; }
|
||||||
|
|
||||||
|
internal int ObjectNumber { get; }
|
||||||
|
|
||||||
|
internal string Name { get; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A page being drawn. Coordinates are PDF points (1/72 inch) from the <b>bottom-left</b> corner; text is placed by
|
||||||
|
/// its baseline. Use <see cref="PdfTextLayout"/> to measure and wrap text.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class PdfPage
|
||||||
|
{
|
||||||
|
private readonly StringBuilder _content = new();
|
||||||
|
|
||||||
|
internal PdfPage(int number, double width, double height)
|
||||||
|
{
|
||||||
|
Number = number;
|
||||||
|
Width = width;
|
||||||
|
Height = height;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The page number, from 1.</summary>
|
||||||
|
public int Number { get; }
|
||||||
|
|
||||||
|
/// <summary>The width in points.</summary>
|
||||||
|
public double Width { get; }
|
||||||
|
|
||||||
|
/// <summary>The height in points.</summary>
|
||||||
|
public double Height { get; }
|
||||||
|
|
||||||
|
internal SortedSet<PdfFont> Fonts { get; } = [];
|
||||||
|
|
||||||
|
internal SortedDictionary<string, int> Images { get; } = new(StringComparer.Ordinal);
|
||||||
|
|
||||||
|
internal bool IsClosed { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Writes a line of text.</summary>
|
||||||
|
/// <param name="text">The text (one line; see <see cref="PdfTextLayout.Wrap"/>).</param>
|
||||||
|
/// <param name="x">The left edge.</param>
|
||||||
|
/// <param name="y">The baseline.</param>
|
||||||
|
/// <param name="font">The font.</param>
|
||||||
|
/// <param name="size">The size in points.</param>
|
||||||
|
/// <param name="color">The colour; black when omitted.</param>
|
||||||
|
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");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Writes a line of text ending at <paramref name="right"/> (amounts in a column).</summary>
|
||||||
|
/// <param name="text">The text.</param>
|
||||||
|
/// <param name="right">The right edge.</param>
|
||||||
|
/// <param name="y">The baseline.</param>
|
||||||
|
/// <param name="font">The font.</param>
|
||||||
|
/// <param name="size">The size.</param>
|
||||||
|
/// <param name="color">The colour.</param>
|
||||||
|
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);
|
||||||
|
|
||||||
|
/// <summary>Writes a line of text centred on <paramref name="center"/>.</summary>
|
||||||
|
/// <param name="text">The text.</param>
|
||||||
|
/// <param name="center">The centre.</param>
|
||||||
|
/// <param name="y">The baseline.</param>
|
||||||
|
/// <param name="font">The font.</param>
|
||||||
|
/// <param name="size">The size.</param>
|
||||||
|
/// <param name="color">The colour.</param>
|
||||||
|
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);
|
||||||
|
|
||||||
|
/// <summary>Writes a paragraph wrapped to a width, from a first baseline downwards.</summary>
|
||||||
|
/// <param name="text">The text.</param>
|
||||||
|
/// <param name="x">The left edge.</param>
|
||||||
|
/// <param name="y">The first baseline.</param>
|
||||||
|
/// <param name="width">The width.</param>
|
||||||
|
/// <param name="font">The font.</param>
|
||||||
|
/// <param name="size">The size.</param>
|
||||||
|
/// <param name="lineHeight">The distance between baselines; 1.2 times the size when omitted.</param>
|
||||||
|
/// <param name="color">The colour.</param>
|
||||||
|
/// <returns>The baseline after the last line.</returns>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Draws a line.</summary>
|
||||||
|
/// <param name="x1">Start x.</param>
|
||||||
|
/// <param name="y1">Start y.</param>
|
||||||
|
/// <param name="x2">End x.</param>
|
||||||
|
/// <param name="y2">End y.</param>
|
||||||
|
/// <param name="lineWidth">The width in points.</param>
|
||||||
|
/// <param name="color">The colour; black when omitted.</param>
|
||||||
|
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");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Draws a rectangle, filled and/or outlined.</summary>
|
||||||
|
/// <param name="x">The left edge.</param>
|
||||||
|
/// <param name="y">The bottom edge.</param>
|
||||||
|
/// <param name="width">The width.</param>
|
||||||
|
/// <param name="height">The height.</param>
|
||||||
|
/// <param name="stroke">The outline colour, or <see langword="null"/> for none.</param>
|
||||||
|
/// <param name="fill">The fill colour, or <see langword="null"/> for none.</param>
|
||||||
|
/// <param name="lineWidth">The outline width.</param>
|
||||||
|
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");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Draws an image scaled to a box.</summary>
|
||||||
|
/// <param name="image">The image, from <see cref="PdfWriter.AddJpeg"/>.</param>
|
||||||
|
/// <param name="x">The left edge.</param>
|
||||||
|
/// <param name="y">The bottom edge.</param>
|
||||||
|
/// <param name="width">The width.</param>
|
||||||
|
/// <param name="height">The height.</param>
|
||||||
|
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.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Writes PDF 1.7 documents (SPEC §2 "PDF e file"), written in house: the 12 standard Latin Type1 fonts with
|
||||||
|
/// <c>WinAnsiEncoding</c>, 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.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// TODO (FatturaPA courtesy copies, SPEC §2): PDF/A-3 with embedded XML attachments (<c>PdfA3Embedder</c>) needs
|
||||||
|
/// embedded fonts, an XMP metadata stream and an output intent; this first version does not produce PDF/A.
|
||||||
|
/// </remarks>
|
||||||
|
/// <example>
|
||||||
|
/// <code>
|
||||||
|
/// 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();
|
||||||
|
/// </code>
|
||||||
|
/// </example>
|
||||||
|
public sealed class PdfWriter : IAsyncDisposable
|
||||||
|
{
|
||||||
|
/// <summary>The media type of a PDF file.</summary>
|
||||||
|
public const string MediaType = "application/pdf";
|
||||||
|
|
||||||
|
/// <summary>The width of an A4 page in points.</summary>
|
||||||
|
public const double A4Width = 595.28;
|
||||||
|
|
||||||
|
/// <summary>The height of an A4 page in points.</summary>
|
||||||
|
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<long> _offsets = [0, -1, -1, -1];
|
||||||
|
private readonly List<int> _pageObjects = [];
|
||||||
|
private readonly Dictionary<PdfFont, int> _fontObjects = [];
|
||||||
|
private long _flushed;
|
||||||
|
private int _images;
|
||||||
|
private PdfPage? _page;
|
||||||
|
private bool _closed;
|
||||||
|
|
||||||
|
/// <summary>Starts a document.</summary>
|
||||||
|
/// <param name="output">The stream that receives the file; it need not be seekable.</param>
|
||||||
|
/// <param name="info">The document information; <see langword="null"/> for none but the creator.</param>
|
||||||
|
/// <param name="leaveOpen">Whether to leave <paramref name="output"/> open on dispose.</param>
|
||||||
|
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']);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Whether content streams are Flate-compressed (turn it off only to inspect the output).</summary>
|
||||||
|
public bool CompressContent { get; init; } = true;
|
||||||
|
|
||||||
|
/// <summary>The number of pages started.</summary>
|
||||||
|
public int PageCount => _pageObjects.Count + (_page is null ? 0 : 1);
|
||||||
|
|
||||||
|
/// <summary>The current page, or <see langword="null"/> before the first.</summary>
|
||||||
|
public PdfPage? CurrentPage => _page;
|
||||||
|
|
||||||
|
/// <summary>Finishes the current page (writing it to the output) and starts a new one.</summary>
|
||||||
|
/// <param name="width">The width in points; A4 when omitted.</param>
|
||||||
|
/// <param name="height">The height in points; A4 when omitted.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The new page.</returns>
|
||||||
|
public async Task<PdfPage> 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Adds a JPEG image to the document (embedded as is, <c>DCTDecode</c>).</summary>
|
||||||
|
/// <param name="jpeg">The JPEG file.</param>
|
||||||
|
/// <returns>The image, to draw on any page.</returns>
|
||||||
|
/// <exception cref="InvalidDataException">The data is not a JPEG file the PDF can embed.</exception>
|
||||||
|
public PdfImage AddJpeg(ReadOnlySpan<byte> 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Writes what is buffered to the output.</summary>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>A task.</returns>
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Finishes the document: the last page, fonts, page tree, catalogue, information, cross-reference table and
|
||||||
|
/// trailer. A document without pages gets one blank page.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>A task.</returns>
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Closes the document if it is still open.</summary>
|
||||||
|
/// <returns>A task.</returns>
|
||||||
|
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";
|
||||||
|
|
||||||
|
/// <summary>A text string: ASCII as a literal, anything else as UTF-16BE with byte order mark.</summary>
|
||||||
|
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 "<FEFF" + Convert.ToHexString(Encoding.BigEndianUnicode.GetBytes(value)) + ">";
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
|
||||||
|
/// <summary>Where the store keeps files and the default limits.</summary>
|
||||||
|
/// <param name="RootDirectory">The root folder, <c><KHAEMHAT_DATA_DIR>/files</c>.</param>
|
||||||
|
public sealed record FileStoreOptions(string RootDirectory)
|
||||||
|
{
|
||||||
|
/// <summary>The largest file accepted when the caller gives no limit (25 MB).</summary>
|
||||||
|
public long MaxFileBytes { get; init; } = FileLimits.DefaultMaxBytes;
|
||||||
|
|
||||||
|
/// <summary>The space each company may use when the caller gives no quota; 0 means no quota.</summary>
|
||||||
|
public long CompanyQuotaBytes { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The options for a data folder: files in <c><dataDir>/files</c>.</summary>
|
||||||
|
/// <param name="dataDirectory">The value of <c>KHAEMHAT_DATA_DIR</c>.</param>
|
||||||
|
/// <returns>The options.</returns>
|
||||||
|
public static FileStoreOptions ForDataDirectory(string dataDirectory)
|
||||||
|
{
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(dataDirectory);
|
||||||
|
return new FileStoreOptions(Path.Combine(dataDirectory, "files"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The limits used when the caller gives none.</summary>
|
||||||
|
public FileLimits DefaultLimits => new(MaxFileBytes, CompanyQuotaBytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The scanner used when no antivirus is plugged in: every file is accepted.</summary>
|
||||||
|
public sealed class NoOpFileScanner : IFileScanner
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public ValueTask<FileScanResult> ScanAsync(string companyCode, Stream content, CancellationToken cancellationToken = default) =>
|
||||||
|
ValueTask.FromResult(FileScanResult.Ok);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The file store on the data volume (SPEC §9.4): <c><root>/<COMPANY>/<yyyy>/<guid></c>. A file is
|
||||||
|
/// written to <c><guid>.part</c> 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.
|
||||||
|
/// </summary>
|
||||||
|
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;
|
||||||
|
|
||||||
|
/// <summary>Creates the store.</summary>
|
||||||
|
/// <param name="options">The root folder and the default limits.</param>
|
||||||
|
/// <param name="scanner">The antivirus hook.</param>
|
||||||
|
/// <param name="clock">The clock (the year folder).</param>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The root folder.</summary>
|
||||||
|
public string RootDirectory => _options.RootDirectory;
|
||||||
|
|
||||||
|
/// <summary>Whether a key has the form the store produces (<c>yyyy/guid</c>).</summary>
|
||||||
|
/// <param name="key">The key.</param>
|
||||||
|
/// <returns><see langword="true"/> if valid.</returns>
|
||||||
|
public static bool IsValidKey(string? key) => key is not null && KeyPattern().IsMatch(key);
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<StoredFile> 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public Task<IFileStoreWriter> 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<IFileStoreWriter>(writer);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
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}.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public bool Exists(string companyCode, string key) => File.Exists(PathOf(companyCode, key));
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public bool Delete(string companyCode, string key)
|
||||||
|
{
|
||||||
|
var path = PathOf(companyCode, key);
|
||||||
|
if (!File.Exists(path))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
File.Delete(path);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public Task<FileUsage> 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));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
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();
|
||||||
|
|
||||||
|
/// <summary>A file being written: the <c>.part</c> file and the counting stream over it.</summary>
|
||||||
|
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<StoredFile> 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A write-only stream that enforces the size limit and computes SHA-256 on the way.</summary>
|
||||||
|
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<byte> 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<byte> 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<byte> 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,753 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.IO.Compression;
|
||||||
|
using System.Text;
|
||||||
|
using System.Xml;
|
||||||
|
|
||||||
|
namespace Khaemhat.Infrastructure.Files;
|
||||||
|
|
||||||
|
/// <summary>The number format of a spreadsheet column.</summary>
|
||||||
|
public enum XlsxFormat
|
||||||
|
{
|
||||||
|
/// <summary>By value: dates get a date format, everything else the general one.</summary>
|
||||||
|
General = 0,
|
||||||
|
|
||||||
|
/// <summary>Whole numbers with thousands separator (<c>#,##0</c>).</summary>
|
||||||
|
WholeNumber = 1,
|
||||||
|
|
||||||
|
/// <summary>Two decimals with thousands separator (<c>#,##0.00</c>).</summary>
|
||||||
|
TwoDecimals = 2,
|
||||||
|
|
||||||
|
/// <summary>Euro amounts (<c>#,##0.00 €</c>).</summary>
|
||||||
|
Euro = 3,
|
||||||
|
|
||||||
|
/// <summary>Percentages with two decimals; the value 0.22 shows as 22,00%.</summary>
|
||||||
|
Percent = 4,
|
||||||
|
|
||||||
|
/// <summary>Dates.</summary>
|
||||||
|
Date = 5,
|
||||||
|
|
||||||
|
/// <summary>Dates with time.</summary>
|
||||||
|
DateTime = 6,
|
||||||
|
|
||||||
|
/// <summary>Text: numbers typed later in the cell stay text.</summary>
|
||||||
|
Text = 7,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A column of a sheet.</summary>
|
||||||
|
/// <param name="Header">The header, written in bold in the first row; <see langword="null"/> for no header.</param>
|
||||||
|
/// <param name="Width">The width in characters; <see langword="null"/> for the spreadsheet default.</param>
|
||||||
|
/// <param name="Format">The number format of the cells.</param>
|
||||||
|
public sealed record XlsxColumn(string? Header, double? Width = null, XlsxFormat Format = XlsxFormat.General);
|
||||||
|
|
||||||
|
/// <summary>The options of an <see cref="XlsxWriter"/>.</summary>
|
||||||
|
public sealed record XlsxOptions
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 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).
|
||||||
|
/// </summary>
|
||||||
|
public bool UseSharedStrings { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Whether the header row stays visible while scrolling.</summary>
|
||||||
|
public bool FreezeHeaderRow { get; init; } = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Writes Office Open XML spreadsheets (<c>.xlsx</c>, SPEC §2, §9.4) with <see cref="ZipArchive"/> and
|
||||||
|
/// <see cref="XmlWriter"/>, 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.
|
||||||
|
/// </summary>
|
||||||
|
/// <example>
|
||||||
|
/// <code>
|
||||||
|
/// 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();
|
||||||
|
/// </code>
|
||||||
|
/// </example>
|
||||||
|
public sealed class XlsxWriter : IAsyncDisposable
|
||||||
|
{
|
||||||
|
/// <summary>The media type of an <c>.xlsx</c> file.</summary>
|
||||||
|
public const string MediaType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
|
||||||
|
|
||||||
|
/// <summary>The longest sheet name Excel accepts.</summary>
|
||||||
|
public const int MaxSheetNameLength = 31;
|
||||||
|
|
||||||
|
/// <summary>The longest text a cell holds.</summary>
|
||||||
|
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<string> _sheetNames = [];
|
||||||
|
private readonly Dictionary<string, int> _sharedIndex = new(StringComparer.Ordinal);
|
||||||
|
private readonly List<string> _shared = [];
|
||||||
|
private Stream? _sheetStream;
|
||||||
|
private XmlWriter? _sheet;
|
||||||
|
private IReadOnlyList<XlsxColumn> _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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The names of the sheets started so far (after cleaning).</summary>
|
||||||
|
public IReadOnlyList<string> SheetNames => _sheetNames;
|
||||||
|
|
||||||
|
/// <summary>Starts a workbook.</summary>
|
||||||
|
/// <param name="output">The stream that receives the file; it need not be seekable.</param>
|
||||||
|
/// <param name="options">The options.</param>
|
||||||
|
/// <param name="leaveOpen">Whether to leave <paramref name="output"/> open on dispose.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The writer; complete or dispose it.</returns>
|
||||||
|
public static async Task<XlsxWriter> 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());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Makes a valid sheet name: without <c>[ ] : * ? / \</c>, without apostrophes at the ends, at most 31 characters,
|
||||||
|
/// different (ignoring case) from the names already used.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="name">The wanted name.</param>
|
||||||
|
/// <param name="used">The names already in the workbook.</param>
|
||||||
|
/// <returns>The name.</returns>
|
||||||
|
public static string CleanSheetName(string? name, IReadOnlyCollection<string> 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The spreadsheet serial number of a date (days since 1899-12-30, time as fraction).</summary>
|
||||||
|
/// <param name="value">The date.</param>
|
||||||
|
/// <returns>The serial number.</returns>
|
||||||
|
public static double ToSerialDate(DateTime value) => (value - Epoch).TotalDays;
|
||||||
|
|
||||||
|
/// <summary>The letters of a column: 0 is <c>A</c>, 26 is <c>AA</c>.</summary>
|
||||||
|
/// <param name="index">The zero-based column.</param>
|
||||||
|
/// <returns>The letters.</returns>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Starts a sheet (ending the previous one); with column headers the first row is the bold header.</summary>
|
||||||
|
/// <param name="name">The sheet name, cleaned by <see cref="CleanSheetName"/>.</param>
|
||||||
|
/// <param name="columns">The columns, or <see langword="null"/>.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>A task.</returns>
|
||||||
|
public async Task StartSheetAsync(string name, IReadOnlyList<XlsxColumn>? 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Writes a row in the current sheet (a sheet <c>Foglio1</c> is started if none is).</summary>
|
||||||
|
/// <param name="values">
|
||||||
|
/// The cells: <see cref="string"/>, numbers, <see cref="DateTime"/>, <see cref="DateOnly"/>, <see cref="bool"/>;
|
||||||
|
/// <see langword="null"/> leaves the cell empty; anything else is written as text.
|
||||||
|
/// </param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>A task.</returns>
|
||||||
|
public async Task WriteRowAsync(IEnumerable<object?> 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Ends the last sheet and writes workbook, styles, shared strings, relationships and content types.</summary>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>A task.</returns>
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Completes the workbook if needed and closes the stream unless left open.</summary>
|
||||||
|
/// <returns>A task.</returns>
|
||||||
|
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<object?> 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<XmlWriter, Task> 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,188 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.IO.Compression;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace Khaemhat.Infrastructure.Files;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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
|
||||||
|
/// <see cref="ZipArchive"/> in <see cref="ZipArchiveMode.Create"/> mode that only uses its asynchronous API, cleans
|
||||||
|
/// entry names and makes duplicates unique (<c>fattura.pdf</c>, <c>fattura (2).pdf</c>).
|
||||||
|
/// </summary>
|
||||||
|
/// <example>
|
||||||
|
/// <code>
|
||||||
|
/// 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);
|
||||||
|
/// </code>
|
||||||
|
/// </example>
|
||||||
|
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<string> _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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The number of entries written.</summary>
|
||||||
|
public int Count => _names.Count;
|
||||||
|
|
||||||
|
/// <summary>Starts an archive.</summary>
|
||||||
|
/// <param name="output">The stream that receives the archive.</param>
|
||||||
|
/// <param name="leaveOpen">Whether to leave <paramref name="output"/> open on dispose.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The writer; dispose it to write the central directory.</returns>
|
||||||
|
public static async Task<ZipStreamWriter> 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Cleans an entry name: forward slashes for folders, no drive, no <c>..</c>, no leading slash, no characters that
|
||||||
|
/// Windows refuses, at most 200 characters.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="name">The name.</param>
|
||||||
|
/// <returns>The clean name (<c>file</c> when nothing is left).</returns>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Adds an entry with the content of a stream, read to the end.</summary>
|
||||||
|
/// <param name="entryName">The entry name.</param>
|
||||||
|
/// <param name="content">The content.</param>
|
||||||
|
/// <param name="lastWrite">The date shown for the entry; now when omitted.</param>
|
||||||
|
/// <param name="level">The compression: <see cref="CompressionLevel.NoCompression"/> suits files already compressed (JPEG, ZIP, P7M).</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The name actually used (made unique).</returns>
|
||||||
|
public async Task<string> 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Adds an entry with the given bytes.</summary>
|
||||||
|
/// <param name="entryName">The entry name.</param>
|
||||||
|
/// <param name="content">The content.</param>
|
||||||
|
/// <param name="lastWrite">The date shown for the entry; now when omitted.</param>
|
||||||
|
/// <param name="level">The compression.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The name actually used (made unique).</returns>
|
||||||
|
public async Task<string> AddAsync(
|
||||||
|
string entryName, ReadOnlyMemory<byte> 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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).
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="entryName">The entry name.</param>
|
||||||
|
/// <param name="lastWrite">The date shown for the entry; now when omitted.</param>
|
||||||
|
/// <param name="level">The compression.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The name actually used and the entry stream.</returns>
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Writes the central directory and closes the stream unless left open.</summary>
|
||||||
|
/// <returns>A task.</returns>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using Khaemhat.Application.Audit;
|
using Khaemhat.Application.Audit;
|
||||||
using Khaemhat.Application.Configuration;
|
using Khaemhat.Application.Configuration;
|
||||||
|
using Khaemhat.Application.Files;
|
||||||
using Khaemhat.Application.Instance;
|
using Khaemhat.Application.Instance;
|
||||||
using Khaemhat.Application.Jobs;
|
using Khaemhat.Application.Jobs;
|
||||||
using Khaemhat.Application.Licensing;
|
using Khaemhat.Application.Licensing;
|
||||||
@@ -10,6 +11,7 @@ using Khaemhat.Application.Notifications;
|
|||||||
using Khaemhat.Application.Preferences;
|
using Khaemhat.Application.Preferences;
|
||||||
using Khaemhat.Application.Security;
|
using Khaemhat.Application.Security;
|
||||||
using Khaemhat.Core.Caching;
|
using Khaemhat.Core.Caching;
|
||||||
|
using Khaemhat.Core.Files;
|
||||||
using Khaemhat.Core.Logging;
|
using Khaemhat.Core.Logging;
|
||||||
using Khaemhat.Core.Security;
|
using Khaemhat.Core.Security;
|
||||||
using Khaemhat.Data;
|
using Khaemhat.Data;
|
||||||
@@ -20,6 +22,7 @@ using Khaemhat.Data.Migrations;
|
|||||||
using Khaemhat.Data.PostgreSql;
|
using Khaemhat.Data.PostgreSql;
|
||||||
using Khaemhat.Data.Sqlite;
|
using Khaemhat.Data.Sqlite;
|
||||||
using Khaemhat.Infrastructure.Caching;
|
using Khaemhat.Infrastructure.Caching;
|
||||||
|
using Khaemhat.Infrastructure.Files;
|
||||||
using Khaemhat.Infrastructure.Licensing;
|
using Khaemhat.Infrastructure.Licensing;
|
||||||
using Khaemhat.Infrastructure.Logging;
|
using Khaemhat.Infrastructure.Logging;
|
||||||
using Khaemhat.Infrastructure.Security;
|
using Khaemhat.Infrastructure.Security;
|
||||||
@@ -146,6 +149,18 @@ internal static class KhaemhatServices
|
|||||||
services.AddScoped<ToastService>();
|
services.AddScoped<ToastService>();
|
||||||
services.AddScoped<DialogService>();
|
services.AddScoped<DialogService>();
|
||||||
services.AddScoped<DrawerService>();
|
services.AddScoped<DrawerService>();
|
||||||
|
|
||||||
|
// Files and attachments (#34): store on the data volume, antivirus hook, attachments, generators, trash job.
|
||||||
|
services.AddSingleton(FileStoreOptions.ForDataDirectory(options.DataDir));
|
||||||
|
services.AddSingleton<IFileScanner, NoOpFileScanner>();
|
||||||
|
services.AddSingleton<IFileStore, VolumeFileStore>();
|
||||||
|
services.AddSingleton<AttachmentService>();
|
||||||
|
services.AddSingleton<IFileGenerator, DemoPdfGenerator>();
|
||||||
|
services.AddSingleton<IFileGenerator, DemoCsvGenerator>();
|
||||||
|
services.AddSingleton<IFileGenerator, DemoXlsxGenerator>();
|
||||||
|
services.AddSingleton<FileGeneratorRegistry>();
|
||||||
|
services.AddSingleton<FileGenerationService>();
|
||||||
|
services.AddSingleton<IScheduledJob, AttachmentTrashPurgeJob>();
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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_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",
|
"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());
|
CollectionAssert.AreEquivalent(expected, registry.Maps.Select(m => m.Table).ToArray());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
namespace Khaemhat.Infrastructure.Tests.Files;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
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<byte> 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<byte> 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
|
||||||
|
/// <summary>The in-house PDF writer, first version (SPEC §2 "PDF e file", issue #34).</summary>
|
||||||
|
[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 <FEFF0053006F0063006900650074" + "00E0");
|
||||||
|
StringAssert.Contains(text, "/Creator (Khaemhat)");
|
||||||
|
StringAssert.Contains(text, "/CreationDate (D:20261111103000Z)");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task EmptyDocument_GetsOneBlankPage()
|
||||||
|
{
|
||||||
|
var text = Latin1.GetString(await WriteAsync(_ => 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<InvalidDataException>(() => JpegInfo.Read("not a jpeg"u8));
|
||||||
|
Assert.ThrowsExactly<InvalidDataException>(() => 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<byte[]> WriteAsync(Func<PdfWriter, Task> 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();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The header of a JPEG file built by hand: SOI, APP0 (JFIF), optional APP14 (Adobe), SOF0, EOI. No pixels.</summary>
|
||||||
|
private static byte[] TinyJpeg(int width, int height, int components, bool adobe = false)
|
||||||
|
{
|
||||||
|
var bytes = new List<byte> { 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();
|
||||||
|
}
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
using System.IO.Compression;
|
||||||
|
using System.Text;
|
||||||
|
using System.Xml;
|
||||||
|
using Khaemhat.Infrastructure.Files;
|
||||||
|
|
||||||
|
namespace Khaemhat.Infrastructure.Tests.Files;
|
||||||
|
|
||||||
|
/// <summary>CSV, ZIP and XLSX written in house (SPEC §2 "PDF e file", issue #34).</summary>
|
||||||
|
[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<string> ReadSharedStrings(ZipArchive archive)
|
||||||
|
{
|
||||||
|
var strings = new List<string>();
|
||||||
|
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<string, (string Value, string? Style, string? Type)> ReadCells(ZipArchive archive, string part, List<string> shared)
|
||||||
|
{
|
||||||
|
var cells = new Dictionary<string, (string, string?, string?)>();
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
using System.Security.Cryptography;
|
||||||
|
using Khaemhat.Core.Files;
|
||||||
|
using Khaemhat.Infrastructure.Files;
|
||||||
|
|
||||||
|
namespace Khaemhat.Infrastructure.Tests.Files;
|
||||||
|
|
||||||
|
/// <summary>The file store on the data volume (SPEC §9.4, issue #34).</summary>
|
||||||
|
[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<FileStoreException>(() => 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<FileStoreException>(() => 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<FileStoreException>(() => 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<FileStoreException>(() => 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<ArgumentException>(() => store.OpenRead(Company, "../OTHER/2026/" + new string('a', 32)));
|
||||||
|
Assert.ThrowsExactly<ArgumentException>(() => store.Exists(Company, "2026/x"));
|
||||||
|
Assert.ThrowsExactly<ArgumentException>(() => 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<FileScanResult> 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Attachments and generated files on a real instance (issue #34): versions, download, trash and purge, locks, limits.
|
||||||
|
/// </summary>
|
||||||
|
[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<ValidationFailedException>(() => 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<KeyNotFoundException>(() => 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("<FatturaElettronica/>"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<ValidationFailedException>(() => attachments.DeleteAsync(Root, company, xml.Id));
|
||||||
|
CollectionAssert.Contains(error.Errors.ToList(), AttachmentService.LockedError);
|
||||||
|
await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => 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<SystemSettingsStore>();
|
||||||
|
Assert.AreEqual(FileLimits.DefaultMaxBytes, (await attachments.GetLimitsAsync()).MaxBytes);
|
||||||
|
await settings.SetAsync(AttachmentService.MaxUploadSetting, "1");
|
||||||
|
|
||||||
|
var error = await Assert.ThrowsExactlyAsync<ValidationFailedException>(
|
||||||
|
() => 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<ValidationFailedException>(
|
||||||
|
() => attachments.UploadAsync(Root, company, "sales.invoice", 1, "vuoto.pdf", null, new MemoryStream()));
|
||||||
|
await Assert.ThrowsExactlyAsync<ValidationFailedException>(
|
||||||
|
() => 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<AccessDeniedException>(() => attachments.ListAsync(stranger, company, "sales.invoice", 1));
|
||||||
|
var withoutRoles = new Actor("lucia", UserLevel.Standard, null, 999, company);
|
||||||
|
await Assert.ThrowsExactlyAsync<AccessDeniedException>(() => 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<JobScheduler>();
|
||||||
|
await scheduler.EnsureSystemTasksAsync();
|
||||||
|
|
||||||
|
Assert.AreEqual(JobOutcome.Succeeded, await scheduler.RunAsync("system.attachments-trash"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A started instance with an attachment service on a clock the test moves.</summary>
|
||||||
|
private sealed class Fixture : IAsyncDisposable
|
||||||
|
{
|
||||||
|
private Fixture(WebApplication app, string company)
|
||||||
|
{
|
||||||
|
App = app;
|
||||||
|
Company = company;
|
||||||
|
var services = app.Services;
|
||||||
|
Factory = services.GetRequiredService<IUnitOfWorkFactory>();
|
||||||
|
Store = services.GetRequiredService<IFileStore>();
|
||||||
|
Attachments = new AttachmentService(
|
||||||
|
Factory, Store, services.GetRequiredService<PermissionService>(), services.GetRequiredService<AuditTrail>(),
|
||||||
|
services.GetRequiredService<SystemSettingsStore>(), services.GetRequiredService<FileStoreOptions>(), Clock);
|
||||||
|
Generation = new FileGenerationService(services.GetRequiredService<FileGeneratorRegistry>(), Attachments, services.GetRequiredService<PermissionService>(), 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<Fixture> StartAsync()
|
||||||
|
{
|
||||||
|
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
||||||
|
return new Fixture(app, company);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<List<string>> StorageKeysAsync()
|
||||||
|
{
|
||||||
|
await using var unitOfWork = await Factory.CreateAsync(DatabaseScope.Company(Company));
|
||||||
|
return (await unitOfWork.Repository<Attachment, long>().ListAsync(Query.For<Attachment>())).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;
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user