using System.Globalization; using System.Net.Security; using System.Net.Sockets; using System.Text.RegularExpressions; using Khaemhat.Fiscal.Abstractions; using Khaemhat.Infrastructure.Mail; namespace Khaemhat.Fiscal.Italy.Sdi; /// /// The PEC channel to the SDI (SPEC ยง11.9, issue #76): files go by certified mail to the address of the SDI /// (sdi01@pec.fatturapa.it the first time, then the sdiNN address the SDI writes from), receipts and /// supplier invoices are read from the mailbox by IMAP. /// /// /// Only messages whose sender contains fatturapa.it are read: the acceptance and delivery receipts of the /// PEC provider stay where they are. The files are the .xml and .p7m attachments of the original message /// (postacert.eml); daticert.xml and the signature of the provider are ignored. /// With an archive folder, processed messages are moved there and every message of the SDI still in the inbox is /// read again at the next poll (the services discard what they already have); without it, messages are marked as read /// and only unread ones are fetched, so a message opened in webmail before the poll is missed: the archive folder is /// the recommended setting. /// /// The clock (date of the messages sent). /// A custom check of the server certificates (tests only). public sealed partial class PecSdiTransport(TimeProvider? clock = null, RemoteCertificateValidationCallback? certificateValidation = null) : IEInvoiceTransport { /// The code of the channel. public const string ChannelCode = "PEC"; /// The address of the SDI for the first file. public const string FirstAddress = "sdi01@pec.fatturapa.it"; /// The most messages read in one poll. public const int MaxMessages = 200; private static readonly TimeSpan Timeout = TimeSpan.FromMinutes(2); private readonly TimeProvider _clock = clock ?? TimeProvider.System; /// public string Code => ChannelCode; /// public bool Polls => true; /// Whether an address is one the SDI writes from (sdiNN@pec.fatturapa.it). /// The address, possibly with a display name. /// The bare address when it is one, otherwise . public static string? SdiAddress(string? address) { var match = SdiAddressPattern().Match(address ?? string.Empty); return match.Success ? match.Value.ToLowerInvariant() : null; } /// public async Task SendAsync(EInvoiceChannelSettings settings, EInvoiceOutgoing file, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(settings); ArgumentNullException.ThrowIfNull(file); if (Missing(settings, smtp: true) is { } missing) { return new EInvoiceSendResult(false, null, null, missing); } var to = SdiAddress(settings.ExchangeAddress) ?? settings.ExchangeAddress ?? FirstAddress; var mediaType = file.FileName.EndsWith(".p7m", StringComparison.OrdinalIgnoreCase) ? "application/pkcs7-mime" : "application/xml"; var mail = new OutgoingMail([to], "Invio file " + file.FileName, "File " + file.FileName + (file.Reference is null ? string.Empty : " (" + file.Reference + ")") + ".") { Attachments = [new MailAttachment(file.FileName, mediaType, file.Content)], Reference = file.Reference, }; try { await new SmtpMailSender(Smtp(settings), _clock).SendAsync(mail, cancellationToken).ConfigureAwait(false); return new EInvoiceSendResult(true, null, null, null); } catch (MailException ex) { return new EInvoiceSendResult(false, null, null, ex.Message); } } /// public async Task FetchAsync(EInvoiceChannelSettings settings, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(settings); if (Missing(settings, smtp: false) is { } missing) { throw new MailException(missing); } using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); timeout.CancelAfter(Timeout); var token = timeout.Token; await using var imap = await OpenAsync(settings, token).ConfigureAwait(false); var criteria = (string.IsNullOrWhiteSpace(settings.ArchiveFolder) ? "UNSEEN " : string.Empty) + "FROM " + ImapClient.Quote("fatturapa.it"); var uids = (await imap.SearchAsync(criteria, token).ConfigureAwait(false)).Take(MaxMessages).ToList(); var files = new List(); var empty = new List(); string? exchange = null; foreach (var uid in uids) { var message = await imap.FetchAsync(uid, token).ConfigureAwait(false); if (message is null) { continue; } var (found, sender) = Files(message.Content, uid.ToString(CultureInfo.InvariantCulture), _clock.GetUtcNow()); exchange = SdiAddress(sender) ?? exchange; if (found.Count == 0) { empty.Add(uid); } files.AddRange(found); } // A message of the SDI with no file (rare: a notice) is done at once. foreach (var uid in empty) { await DoneAsync(imap, settings, uid, token).ConfigureAwait(false); } await imap.LogoutAsync(token).ConfigureAwait(false); var known = SdiAddress(settings.ExchangeAddress); return new EInvoiceFetchResult(files, uids.Count, exchange is not null && exchange != known ? exchange : null); } /// public async Task AcknowledgeAsync(EInvoiceChannelSettings settings, IReadOnlyCollection messageKeys, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(settings); ArgumentNullException.ThrowIfNull(messageKeys); var uids = messageKeys.Select(k => long.TryParse(k, NumberStyles.None, CultureInfo.InvariantCulture, out var uid) ? uid : -1).Where(u => u > 0).Distinct().ToList(); if (uids.Count == 0) { return; } using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); timeout.CancelAfter(Timeout); await using var imap = await OpenAsync(settings, timeout.Token).ConfigureAwait(false); foreach (var uid in uids) { await DoneAsync(imap, settings, uid, timeout.Token).ConfigureAwait(false); } await imap.LogoutAsync(timeout.Token).ConfigureAwait(false); } /// public async Task CheckAsync(EInvoiceChannelSettings settings, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(settings); if (Missing(settings, smtp: true) is { } missing) { return new EInvoiceChannelCheck(false, missing); } using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); timeout.CancelAfter(TimeSpan.FromSeconds(30)); try { int count; await using (var imap = await OpenAsync(settings, timeout.Token).ConfigureAwait(false)) { count = (await imap.SearchAsync("FROM " + ImapClient.Quote("fatturapa.it"), timeout.Token).ConfigureAwait(false)).Count; await imap.LogoutAsync(timeout.Token).ConfigureAwait(false); } using var smtp = new TcpClient(); await smtp.ConnectAsync(settings.SmtpHost!, settings.SmtpPort, timeout.Token).ConfigureAwait(false); return new EInvoiceChannelCheck(true, $"IMAP {settings.ImapHost}:{settings.ImapPort}: login OK, {count} SDI messages in the inbox; SMTP {settings.SmtpHost}:{settings.SmtpPort}: reachable."); } catch (Exception ex) when (ex is MailException or SocketException or IOException || (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested)) { return new EInvoiceChannelCheck(false, ex.Message); } } /// /// The files of the SDI in a message: the .xml and .p7m attachments of the original message of a /// certified mail (or of the message itself when it is not certified). /// /// The raw message. /// The key of the message. /// The time used when the message has no date. /// The files and the sender of the original message. public static (IReadOnlyList Files, string? Sender) Files(byte[] message, string key, DateTimeOffset now) { ArgumentNullException.ThrowIfNull(message); var root = MimeParser.Parse(message); var original = Original(root) ?? root; var sender = original.Header("from"); var date = DateTimeOffset.TryParse(Strip(original.Header("date")), CultureInfo.InvariantCulture, DateTimeStyles.None, out var parsed) ? parsed : now; var files = original.Attachments() .Where(a => a.FileName is { } name && IsSdiFile(name)) .Select(a => new EInvoiceIncoming(Path.GetFileName(a.FileName!), a.Body, date, key, SdiAddress(sender) ?? sender)) .ToList(); return (files, sender); } private static bool IsSdiFile(string name) => (name.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) || name.EndsWith(".p7m", StringComparison.OrdinalIgnoreCase)) && !name.Equals("daticert.xml", StringComparison.OrdinalIgnoreCase) && !name.Equals("smime.p7m", StringComparison.OrdinalIgnoreCase); // The message enclosed by the PEC provider (postacert.eml), searched in the parts of the envelope. private static MimePart? Original(MimePart part) { if (part.Enclosed is not null) { return part.Enclosed; } return part.Parts.Select(Original).FirstOrDefault(p => p is not null); } // "Thu, 12 Nov 2026 10:15:00 +0100 (CET)": the comment is not part of the date. private static string? Strip(string? date) { if (date is null) { return null; } var comment = date.IndexOf('(', StringComparison.Ordinal); return (comment < 0 ? date : date[..comment]).Trim(); } private static string? Missing(EInvoiceChannelSettings settings, bool smtp) { if (string.IsNullOrWhiteSpace(settings.ImapHost) || string.IsNullOrWhiteSpace(settings.User) || string.IsNullOrEmpty(settings.Password)) { return "The PEC channel needs the IMAP server, the user and the password."; } return smtp && (string.IsNullOrWhiteSpace(settings.SmtpHost) || string.IsNullOrWhiteSpace(settings.Mailbox)) ? "The PEC channel needs the SMTP server and the address of the mailbox." : null; } private static SmtpSettings Smtp(EInvoiceChannelSettings settings) => new( settings.SmtpHost, settings.SmtpPort, settings.User, settings.Password, settings.Mailbox, !settings.Tls ? SmtpTransportSecurity.None : settings.SmtpPort == 587 ? SmtpTransportSecurity.StartTls : SmtpTransportSecurity.Ssl); private async Task OpenAsync(EInvoiceChannelSettings settings, CancellationToken cancellationToken) { var imap = await ImapClient.ConnectAsync( new ImapSettings(settings.ImapHost!, settings.ImapPort, settings.Tls, settings.User!, settings.Password!), cancellationToken, certificateValidation).ConfigureAwait(false); try { await imap.LoginAsync(settings.User!, settings.Password!, cancellationToken).ConfigureAwait(false); await imap.SelectAsync("INBOX", cancellationToken).ConfigureAwait(false); return imap; } catch { await imap.DisposeAsync().ConfigureAwait(false); throw; } } private static Task DoneAsync(ImapClient imap, EInvoiceChannelSettings settings, long uid, CancellationToken cancellationToken) => string.IsNullOrWhiteSpace(settings.ArchiveFolder) ? imap.AddFlagsAsync(uid, @"\Seen", cancellationToken) : imap.MoveAsync(uid, settings.ArchiveFolder.Trim(), cancellationToken); [GeneratedRegex(@"sdi[0-9]{2}@pec\.fatturapa\.it", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)] private static partial Regex SdiAddressPattern(); }