| 1 | import Foundation |
| 2 | import UniformTypeIdentifiers |
| 3 | |
| 4 | // 🤖 Preparing a received attachment to hand to the OS (Quick Look, the Files |
| 5 | // app, the share sheet). The blob's original name + MIME ride INSIDE the |
| 6 | // encrypted payload — never server metadata — so a safe on-disk filename is |
| 7 | // derived here from what the sender supplied. Native-only: the web leans on the |
| 8 | // browser's `<a download>` for the name and extension, so there's no JS mirror |
| 9 | // to keep in lockstep with (unlike AttachmentFormat's helpers). |
| 10 | public enum AttachmentDownload { |
| 11 | /// A safe local filename for saving/previewing an attachment. Strips any |
| 12 | /// directory path from the sender-controlled name, falls back to "file" |
| 13 | /// when it's missing or empty, and appends an extension derived from the |
| 14 | /// MIME type when the name carries none — so Quick Look and the share sheet |
| 15 | /// can pick the right handler. |
| 16 | public static func safeFilename(name: String?, mime: String?) -> String { |
| 17 | // lastPathComponent drops separators (a name like "../../etc/passwd" |
| 18 | // collapses to "passwd"); an all-dots/-slashes name yields "" and takes |
| 19 | // the fallback. |
| 20 | let raw = (name ?? "").trimmingCharacters(in: .whitespacesAndNewlines) |
| 21 | var base = (raw as NSString).lastPathComponent |
| 22 | if base.isEmpty || base == "." || base == ".." { base = "file" } |
| 23 | // Keep the sender's extension when present; otherwise borrow one from |
| 24 | // the MIME type so an extensionless upload still opens in the right app. |
| 25 | let hasExt = !(base as NSString).pathExtension.isEmpty |
| 26 | if !hasExt, let mime, !mime.isEmpty, |
| 27 | let ext = UTType(mimeType: mime)?.preferredFilenameExtension { |
| 28 | base += "." + ext |
| 29 | } |
| 30 | return base |
| 31 | } |
| 32 | } |
| 33 | |