SPB Git

Repository Public

MailLogic.swift 10.8 KB 211 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Lou-Ka Admin iOS9// File             : LouKaAdmin/Core/MailLogic.swift10// Description      : courrier, fonctions pures — noms, destinataires, sujet et11//                    citation d'une réponse, texte d'un message qui n'a qu'une12//                    version HTML (lu sans rien exécuter ni charger), document13//                    isolé pour « Afficher la mise en forme », tailles. Mêmes14//                    règles que l'administration du site.15// Module           : LouKaAdmin16// Repository       : https://git.spboucher.ai/lou-ka-admin-ios17// Project Website  : https://www.lou-ka.com18// Created          : 2026-11-3019// Last Modified    : 2026-11-3020//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author           : Simon-Pierre Boucher26// Position         : Professor of Finance27// Institution      : Université du Québec en Outaouais (UQO)28// Department       : Département des sciences administratives29// Organization     : SP Boucher30//31// Website          : https://spboucher.ai32// Git              : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General          : info@spboucher.ai39// Professional     : contact@spboucher.ai40// Direct           : simon@spboucher.ai41// Research         : research@spboucher.ai42// Development      : dev@spboucher.ai43// Support          : support@spboucher.ai44// Security/Admin   : admin@spboucher.ai45// Notifications    : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification   : Public72// Distribution     : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License          : None specified (no license file in this repository)86// Maintainer       : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import Foundation9495enum MailLogic {96    static func label(_ p: MailPerson?) -> String {97        guard let p else { return "Expéditeur inconnu" }98        if let n = p.name?.trimmingCharacters(in: .whitespaces), !n.isEmpty { return n }99        return p.email.isEmpty ? "Expéditeur inconnu" : p.email100    }101102    static func full(_ p: MailPerson) -> String {103        if let n = p.name?.trimmingCharacters(in: .whitespaces), !n.isEmpty { return "\(n) <\(p.email)>" }104        return p.email105    }106107    /// « a@x.ca, B@y.ca ; Nom <c@z.ca> » → adresses en minuscules, sans doublon, dans l'ordre.108    static func parseRecipients(_ value: String) -> [String] {109        var out: [String] = []110        for part in value.split(whereSeparator: { $0 == "," || $0 == ";" || $0.isNewline }) {111            var s = String(part).trimmingCharacters(in: .whitespaces)112            if let a = s.firstIndex(of: "<"), let b = s.lastIndex(of: ">"), a < b { s = String(s[s.index(after: a)..<b]) }113            for token in s.split(separator: " ") {114                let email = token.trimmingCharacters(in: .whitespaces).lowercased()115                if !email.isEmpty, !out.contains(email) { out.append(email) }116            }117        }118        return out119    }120121    static func looksLikeEmail(_ s: String) -> Bool {122        guard s.count <= 254, !s.contains(where: { $0.isWhitespace || $0 == "<" || $0 == ">" }) else { return false }123        let parts = s.split(separator: "@", omittingEmptySubsequences: false)124        guard parts.count == 2, !parts[0].isEmpty, let dot = parts[1].lastIndex(of: "."), dot != parts[1].startIndex else { return false }125        return parts[1].distance(from: dot, to: parts[1].endIndex) > 2126    }127128    /// « Re: sujet », sans doubler un « Re: » déjà là.129    static func replySubject(_ subject: String?) -> String {130        let s = (subject ?? "").trimmingCharacters(in: .whitespaces)131        if s.range(of: #"^re\s*:"#, options: [.regularExpression, .caseInsensitive]) != nil { return s }132        return "Re: \(s)".trimmingCharacters(in: .whitespaces)133    }134135    /// Texte cité d'une réponse : chaque ligne précédée de « > ».136    static func quote(_ m: MailMessage, when: String) -> String {137        let body = (bodyText(m)).replacingOccurrences(of: "\r\n", with: "\n")138            .replacingOccurrences(of: #"\s+$"#, with: "", options: .regularExpression)139            .split(separator: "\n", omittingEmptySubsequences: false).map { $0.isEmpty ? ">" : "> \($0)" }.joined(separator: "\n")140        return "\n\n\(when.isEmpty ? "" : "Le \(when), ")\(label(m.from.first)) a écrit :\n\(body)"141    }142143    /// Brouillon d'une réponse : l'expéditeur est la boîte qui a reçu le message, le destinataire est144    /// l'adresse de réponse si le message en nomme une.145    static func replyDraft(_ m: MailMessage, when: String) -> MailDraft {146        let target = m.replyTo.first ?? m.from.first147        return MailDraft(from: m.mailbox, to: target.map { [$0.email.lowercased()] } ?? [], cc: nil, subject: replySubject(m.subject),148                         text: quote(m, when: when), replyToMessageID: m.id)149    }150151    /// Ce qui se lit d'un message : sa version texte, sinon le texte tiré de sa version HTML.152    static func bodyText(_ m: MailMessage) -> String {153        if let t = m.text, !t.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { return t }154        return m.html.map(htmlToText) ?? ""155    }156157    /// Texte d'un message HTML, sans rien exécuter ni charger : balises retirées, scripts et styles écartés,158    /// entités courantes décodées. Aucun moteur de rendu n'est utilisé.159    static func htmlToText(_ html: String) -> String {160        var s = html161        func strip(_ pattern: String, _ with: String = "") { s = s.replacingOccurrences(of: pattern, with: with, options: [.regularExpression, .caseInsensitive]) }162        strip(#"<!--[\s\S]*?-->"#)163        strip(#"<(script|style|head|template)\b[\s\S]*?</\1\s*>"#)164        strip(#"<br\s*/?>"#, "\n")165        strip(#"</(p|div|tr|li|h[1-6]|blockquote|table)\s*>"#, "\n")166        strip(#"<[^>]*>"#)167        for (entity, char) in ["&nbsp;": " ", "&lt;": "<", "&gt;": ">", "&quot;": "\"", "&#39;": "'", "&apos;": "'", "&rsquo;": "’", "&laquo;": "«", "&raquo;": "»", "&eacute;": "é", "&egrave;": "è", "&agrave;": "à", "&amp;": "&"] {168            s = s.replacingOccurrences(of: entity, with: char)169        }170        s = s.replacingOccurrences(of: #"[ \t]+\n"#, with: "\n", options: .regularExpression)171        s = s.replacingOccurrences(of: #"\n{3,}"#, with: "\n\n", options: .regularExpression)172        return s.trimmingCharacters(in: .whitespacesAndNewlines)173    }174175    /// Document remis à la vue isolée pour montrer la mise en forme d'un courriel. Sa propre politique interdit176    /// tout chargement (images distantes, polices, scripts, feuilles de style externes, formulaires) : seuls les177    /// styles en ligne et les images intégrées au message passent.178    static func isolatedHTMLDocument(_ html: String) -> String {179        "<!doctype html><html><head><meta charset=\"utf-8\">"180            + "<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; style-src 'unsafe-inline'; img-src data:; form-action 'none'; base-uri 'none'\">"181            + "<meta name=\"referrer\" content=\"no-referrer\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"182            + "<style>html{color-scheme:light}body{margin:12px;font:16px/1.5 -apple-system,system-ui,sans-serif;color:#181c1a;background:#fff;overflow-wrap:anywhere}img,table{max-width:100%}a{color:inherit;text-decoration:underline;pointer-events:none}</style>"183            + "</head><body>" + html + "</body></html>"184    }185186    static func size(_ bytes: Int?) -> String {187        guard let bytes, bytes > 0 else { return "" }188        if bytes < 1024 { return "\(bytes) o" }189        if bytes < 1024 * 1024 { return "\(Int((Double(bytes) / 1024).rounded())) Ko" }190        return String(format: "%.1f Mo", Double(bytes) / 1024 / 1024).replacingOccurrences(of: ".", with: ",")191    }192193    /// Nom de fichier sûr d'une pièce jointe (aucun séparateur de chemin).194    static func fileName(_ a: MailAttachment) -> String {195        var base = (a.name ?? "").replacingOccurrences(of: "/", with: "-").replacingOccurrences(of: "\\", with: "-").replacingOccurrences(of: ":", with: "-")196        while base.contains("..") { base = base.replacingOccurrences(of: "..", with: ".") }197        base = base.trimmingCharacters(in: CharacterSet(charactersIn: ".- ").union(.whitespacesAndNewlines).union(.controlCharacters))198        if !base.isEmpty { return String(base.prefix(120)) }199        let ext: String200        switch a.type {201        case "application/pdf": ext = "pdf"202        case "image/jpeg": ext = "jpg"203        case "image/png": ext = "png"204        case "message/rfc822": ext = "eml"205        case "text/plain", "message/delivery-status": ext = "txt"206        default: ext = "bin"207        }208        return "piece-jointe.\(ext)"209    }210}211
Files main
Menu

Theme