|
| 1 | +import Foundation |
| 2 | + |
| 3 | +enum MultipartFormError: Swift.Error, LocalizedError { |
| 4 | + case inaccessbileFile(underlyingError: Error) |
| 5 | + case impossible |
| 6 | + |
| 7 | + var errorDescription: String? { |
| 8 | + switch self { |
| 9 | + case let .inaccessbileFile(underlyingError: underlyingError): |
| 10 | + return underlyingError.localizedDescription |
| 11 | + case .impossible: |
| 12 | + return "An unknown error occurred." |
| 13 | + } |
| 14 | + } |
| 15 | +} |
| 16 | + |
| 17 | +enum MultipartFormContent { |
| 18 | + case inMemory(Data) |
| 19 | + case onDisk(URL) |
| 20 | + |
| 21 | + func asInputStream() -> InputStream { |
| 22 | + switch self { |
| 23 | + case let .inMemory(data): |
| 24 | + return InputStream(data: data) |
| 25 | + case let .onDisk(url): |
| 26 | + precondition(url.isFileURL && FileManager.default.fileExists(atPath: url.path)) |
| 27 | + return InputStream(fileAtPath: url.path)! |
| 28 | + } |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +struct MultipartFormField { |
| 33 | + let name: String |
| 34 | + let filename: String? |
| 35 | + let mimeType: String? |
| 36 | + let bytes: UInt64 |
| 37 | + |
| 38 | + fileprivate let inputStream: InputStream |
| 39 | + |
| 40 | + init(text: String, name: String, filename: String? = nil, mimeType: String? = nil) { |
| 41 | + self.init(data: text.data(using: .utf8)!, name: name, filename: filename, mimeType: mimeType) |
| 42 | + } |
| 43 | + |
| 44 | + init(data: Data, name: String, filename: String? = nil, mimeType: String? = nil) { |
| 45 | + self.inputStream = InputStream(data: data) |
| 46 | + self.name = name |
| 47 | + self.filename = filename |
| 48 | + self.bytes = UInt64(data.count) |
| 49 | + self.mimeType = mimeType |
| 50 | + } |
| 51 | + |
| 52 | + init(fileAtPath path: String, name: String, filename: String? = nil, mimeType: String? = nil) throws { |
| 53 | + let attrs: [FileAttributeKey: Any] |
| 54 | + do { |
| 55 | + attrs = try FileManager.default.attributesOfItem(atPath: path) |
| 56 | + } catch { |
| 57 | + throw MultipartFormError.inaccessbileFile(underlyingError: error) |
| 58 | + } |
| 59 | + |
| 60 | + guard let inputStream = InputStream(fileAtPath: path), |
| 61 | + let bytes = (attrs[FileAttributeKey.size] as? NSNumber)?.uint64Value |
| 62 | + else { |
| 63 | + // Given we can successfully read the file attributes, the above calls should never fail. |
| 64 | + throw MultipartFormError.impossible |
| 65 | + } |
| 66 | + |
| 67 | + self.inputStream = inputStream |
| 68 | + self.name = name |
| 69 | + self.filename = filename ?? path.split(separator: "/").last.flatMap({ String($0) }) |
| 70 | + self.bytes = bytes |
| 71 | + self.mimeType = mimeType |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +extension Array where Element == MultipartFormField { |
| 76 | + private func multipartFormDestination( |
| 77 | + forceWriteToFile: Bool |
| 78 | + ) throws -> (outputStream: OutputStream, tempFilePath: String?) { |
| 79 | + let dest: OutputStream |
| 80 | + let tempFilePath: String? |
| 81 | + |
| 82 | + // Build the form data in memory if the content is estimated to be less than 10 MB. |
| 83 | + // Otherwise, use a temporary file. |
| 84 | + let thresholdBytesForUsingTmpFile = 10_000_000 |
| 85 | + let estimatedFormDataBytes = reduce(0) { $0 + $1.bytes } |
| 86 | + if forceWriteToFile || estimatedFormDataBytes > thresholdBytesForUsingTmpFile { |
| 87 | + let tempFile = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString).path |
| 88 | + guard let stream = OutputStream(toFileAtPath: tempFile, append: false) else { |
| 89 | + // This error should never occurr, because the `tempFile` is in a temporary directory |
| 90 | + // and is guranteed to be writable. |
| 91 | + throw MultipartFormError.impossible |
| 92 | + } |
| 93 | + dest = stream |
| 94 | + tempFilePath = tempFile |
| 95 | + } else { |
| 96 | + dest = OutputStream.toMemory() |
| 97 | + tempFilePath = nil |
| 98 | + } |
| 99 | + |
| 100 | + return (dest, tempFilePath) |
| 101 | + } |
| 102 | + |
| 103 | + func multipartFormDataStream(boundary: String, forceWriteToFile: Bool = false) throws -> MultipartFormContent { |
| 104 | + guard !isEmpty else { |
| 105 | + return .inMemory(Data()) |
| 106 | + } |
| 107 | + |
| 108 | + let (dest, tempFilePath) = try multipartFormDestination(forceWriteToFile: forceWriteToFile) |
| 109 | + |
| 110 | + // Build the form content |
| 111 | + do { |
| 112 | + dest.open() |
| 113 | + defer { dest.close() } |
| 114 | + |
| 115 | + writeMultipartFormData(destination: dest, boundary: boundary) |
| 116 | + } |
| 117 | + |
| 118 | + // Return the result as `InputStream` |
| 119 | + if let tempFilePath { |
| 120 | + return .onDisk(URL(fileURLWithPath: tempFilePath)) |
| 121 | + } |
| 122 | + |
| 123 | + if let data = dest.property(forKey: .dataWrittenToMemoryStreamKey) as? Data { |
| 124 | + return .inMemory(data) |
| 125 | + } |
| 126 | + |
| 127 | + throw MultipartFormError.impossible |
| 128 | + } |
| 129 | + |
| 130 | + private func writeMultipartFormData(destination dest: OutputStream, boundary: String) { |
| 131 | + for field in self { |
| 132 | + dest.writeMultipartForm(boundary: boundary, isEnd: false) |
| 133 | + |
| 134 | + // Write headers |
| 135 | + var disposition = ["form-data", "name=\"\(field.name)\""] |
| 136 | + if let filename = field.filename { |
| 137 | + disposition += ["filename=\"\(filename)\""] |
| 138 | + } |
| 139 | + dest.writeMultipartFormHeader(name: "Content-Disposition", value: disposition.joined(separator: "; ")) |
| 140 | + |
| 141 | + if let mimeType = field.mimeType { |
| 142 | + dest.writeMultipartFormHeader(name: "Content-Type", value: mimeType) |
| 143 | + } |
| 144 | + |
| 145 | + // Write a linebreak between header and content |
| 146 | + dest.writeMultipartFormLineBreak() |
| 147 | + |
| 148 | + // Write content |
| 149 | + field.inputStream.open() |
| 150 | + defer { |
| 151 | + field.inputStream.close() |
| 152 | + } |
| 153 | + let maxLength = 1024 |
| 154 | + var buffer = [UInt8](repeating: 0, count: maxLength) |
| 155 | + while field.inputStream.hasBytesAvailable { |
| 156 | + let bytes = field.inputStream.read(&buffer, maxLength: maxLength) |
| 157 | + dest.write(data: Data(bytesNoCopy: &buffer, count: bytes, deallocator: .none)) |
| 158 | + } |
| 159 | + |
| 160 | + dest.writeMultipartFormLineBreak() |
| 161 | + } |
| 162 | + |
| 163 | + dest.writeMultipartForm(boundary: boundary, isEnd: true) |
| 164 | + } |
| 165 | +} |
| 166 | + |
| 167 | +private let multipartFormDataLineBreak = "\r\n" |
| 168 | +private extension OutputStream { |
| 169 | + func write(data: Data) { |
| 170 | + let count = data.count |
| 171 | + guard count > 0 else { return } |
| 172 | + |
| 173 | + _ = data.withUnsafeBytes { (ptr: UnsafeRawBufferPointer) in |
| 174 | + write(ptr.bindMemory(to: UInt8.self).baseAddress!, maxLength: count) |
| 175 | + } |
| 176 | + } |
| 177 | + |
| 178 | + func writeMultipartForm(lineContent: String) { |
| 179 | + write(data: "\(lineContent)\(multipartFormDataLineBreak)".data(using: .utf8)!) |
| 180 | + } |
| 181 | + |
| 182 | + func writeMultipartFormLineBreak() { |
| 183 | + write(data: multipartFormDataLineBreak.data(using: .utf8)!) |
| 184 | + } |
| 185 | + |
| 186 | + func writeMultipartFormHeader(name: String, value: String) { |
| 187 | + writeMultipartForm(lineContent: "\(name): \(value)") |
| 188 | + } |
| 189 | + |
| 190 | + func writeMultipartForm(boundary: String, isEnd: Bool) { |
| 191 | + if isEnd { |
| 192 | + writeMultipartForm(lineContent: "--\(boundary)--") |
| 193 | + } else { |
| 194 | + writeMultipartForm(lineContent: "--\(boundary)") |
| 195 | + } |
| 196 | + } |
| 197 | +} |
0 commit comments