Repository Public
1// SP Notes Core2// File: Sources/SPNotesAPI/MultipartForm.swift3// Description: multipart/form-data body written to a file on disk (text fields + one file part copied in chunks), so4// that a 200 MB attachment is never held in memory.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910/// Builder of a `multipart/form-data` body with one file part, streamed to disk.11public struct MultipartForm: Sendable, Equatable {12 public struct Field: Sendable, Equatable {13 public var name: String14 public var value: String15 public init(_ name: String, _ value: String) {16 self.name = name17 self.value = value18 }19 }2021 public let boundary: String2223 /// - Parameter boundary: only ASCII letters, digits, `-` and `_` are kept; a random one is generated by default.24 public init(boundary: String = "spnotes-" + UUID().uuidString.lowercased()) {25 let kept = boundary.unicodeScalars.filter { $0.isASCII && (CharacterSet.alphanumerics.contains($0) || $0 == "-" || $0 == "_") }26 let cleaned = String(String.UnicodeScalarView(kept).prefix(70))27 self.boundary = cleaned.isEmpty ? "spnotes-boundary" : cleaned28 }2930 /// Value of the `Content-Type` request header.31 public var contentType: String { "multipart/form-data; boundary=\(boundary)" }3233 /// Escapes a field name or a file name for a `Content-Disposition` parameter the way browsers do34 /// (WHATWG HTML, multipart/form-data encoding): `"` → `%22`, CR → `%0D`, LF → `%0A`. Other characters stay UTF-8.35 public static func escape(_ text: String) -> String {36 text.replacingOccurrences(of: "\r", with: "%0D")37 .replacingOccurrences(of: "\n", with: "%0A")38 .replacingOccurrences(of: "\"", with: "%22")39 }4041 /// Everything that precedes the bytes of the file: the text fields, then the headers of the file part.42 public func preamble(fields: [Field], fileField: String, filename: String, mimeType: String) -> Data {43 var text = ""44 for field in fields {45 text += "--\(boundary)\r\n"46 text += "Content-Disposition: form-data; name=\"\(Self.escape(field.name))\"\r\n\r\n"47 text += field.value48 text += "\r\n"49 }50 let safeMime = mimeType.unicodeScalars.allSatisfy { $0.isASCII && $0.value > 0x20 && $0.value != 0x7F } && !mimeType.isEmpty ? mimeType : "application/octet-stream"51 text += "--\(boundary)\r\n"52 text += "Content-Disposition: form-data; name=\"\(Self.escape(fileField))\"; filename=\"\(Self.escape(filename))\"\r\n"53 text += "Content-Type: \(safeMime)\r\n\r\n"54 return Data(text.utf8)55 }5657 /// Everything that follows the bytes of the file.58 public var epilogue: Data { Data("\r\n--\(boundary)--\r\n".utf8) }5960 /// Writes the complete body to `destination` (created or replaced), copying `source` in 1 MB chunks.61 /// Checks for task cancellation between chunks.62 /// - Returns: the size of the body in bytes.63 @discardableResult64 public func write(fields: [Field], fileField: String = "file", filename: String, mimeType: String, source: URL, to destination: URL) throws -> Int64 {65 let fm = FileManager.default66 let input: FileHandle67 do { input = try FileHandle(forReadingFrom: source) } catch { throw APIError.file("cannot read \(source.lastPathComponent): \(error.localizedDescription)") }68 defer { try? input.close() }69 guard fm.createFile(atPath: destination.path, contents: nil) else { throw APIError.file("cannot create the upload body") }70 do {71 let output = try FileHandle(forWritingTo: destination)72 defer { try? output.close() }73 var total: Int64 = 074 let head = preamble(fields: fields, fileField: fileField, filename: filename, mimeType: mimeType)75 try output.write(contentsOf: head)76 total += Int64(head.count)77 while true {78 try Task.checkCancellation()79 guard let chunk = try input.read(upToCount: 1 << 20), !chunk.isEmpty else { break }80 try output.write(contentsOf: chunk)81 total += Int64(chunk.count)82 }83 let tail = epilogue84 try output.write(contentsOf: tail)85 total += Int64(tail.count)86 return total87 } catch {88 try? fm.removeItem(at: destination)89 if error is CancellationError { throw APIError.cancelled }90 if let e = error as? APIError { throw e }91 throw APIError.file("cannot write the upload body: \(error.localizedDescription)")92 }93 }9495 /// A reasonable MIME type from a file extension (the server sniffs and validates on its side).96 public static func mimeType(forFilename filename: String) -> String {97 let ext = (filename as NSString).pathExtension.lowercased()98 return mimeTypes[ext] ?? "application/octet-stream"99 }100101 private static let mimeTypes: [String: String] = [102 "png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg", "gif": "image/gif", "webp": "image/webp",103 "heic": "image/heic", "heif": "image/heif", "svg": "image/svg+xml", "tif": "image/tiff", "tiff": "image/tiff",104 "pdf": "application/pdf", "txt": "text/plain", "md": "text/markdown", "csv": "text/csv", "json": "application/json",105 "rtf": "application/rtf", "xml": "application/xml", "zip": "application/zip",106 "doc": "application/msword", "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",107 "xls": "application/vnd.ms-excel", "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",108 "ppt": "application/vnd.ms-powerpoint", "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",109 "mp3": "audio/mpeg", "m4a": "audio/mp4", "wav": "audio/wav", "aac": "audio/aac", "caf": "audio/x-caf",110 "mp4": "video/mp4", "mov": "video/quicktime", "m4v": "video/x-m4v",111 "pkdrawing": "application/octet-stream",112 ]113}114