| 1 | import Foundation |
| 2 | import ImageIO |
| 3 | |
| 4 | public struct FileAttachment: Sendable, Identifiable { |
| 5 | public let id: UUID |
| 6 | public let url: URL |
| 7 | public let name: String |
| 8 | public let mediaType: String |
| 9 | public let width: Int |
| 10 | public let height: Int |
| 11 | } |
| 12 | extension AttachmentFile { |
| 13 | /// Copy while the provider's URL and security scope are valid. Bounded chunks, |
| 14 | /// no mmap or whole-original allocation; caller runs serially off the main actor. |
| 15 | public static func stage(_ source: URL, directory: URL, maximumBytes: Int = AttachmentLimits.maxInputBytes, |
| 16 | access: any AttachmentFileAccess = SystemAttachmentFileAccess()) throws -> URL { |
| 17 | guard source.isFileURL else { throw AttachmentFailure.type } |
| 18 | let started = access.start(source); defer { if started { access.stop(source) } } |
| 19 | guard try access.isRegularFile(source) else { throw AttachmentFailure.type } |
| 20 | try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) |
| 21 | let target = directory.appendingPathComponent(UUID().uuidString).appendingPathExtension(source.pathExtension) |
| 22 | var attributes: [FileAttributeKey: Any] = [.posixPermissions: 0o600] |
| 23 | #if os(iOS) |
| 24 | attributes[.protectionKey] = FileProtectionType.complete |
| 25 | #endif |
| 26 | guard FileManager.default.createFile(atPath: target.path, contents: nil, attributes: attributes) else { throw AttachmentFailure.type } |
| 27 | var completed = false |
| 28 | defer { if !completed { try? FileManager.default.removeItem(at: target) } } |
| 29 | let input = try FileHandle(forReadingFrom: source); defer { try? input.close() } |
| 30 | let output = try FileHandle(forWritingTo: target); defer { try? output.close() } |
| 31 | var count = 0 |
| 32 | while let chunk = try input.read(upToCount: 64 * 1024), !chunk.isEmpty { |
| 33 | try Task.checkCancellation() |
| 34 | count += chunk.count |
| 35 | guard count <= maximumBytes else { throw AttachmentFailure.tooLarge } |
| 36 | try output.write(contentsOf: chunk) |
| 37 | } |
| 38 | guard count > 0 else { throw AttachmentFailure.type } |
| 39 | completed = true |
| 40 | return target |
| 41 | } |
| 42 | public static func prepareFile(_ source: URL, directory: URL, name: String? = nil, |
| 43 | access: any AttachmentFileAccess = SystemAttachmentFileAccess()) throws -> FileAttachment { |
| 44 | let staged = try stage(source, directory: directory, access: access) |
| 45 | defer { try? FileManager.default.removeItem(at: staged) } |
| 46 | func boundedData() throws -> Data { |
| 47 | let handle = try FileHandle(forReadingFrom: staged); defer { try? handle.close() } |
| 48 | let data = try handle.read(upToCount: AttachmentLimits.maxBytes + 1) ?? Data() |
| 49 | guard data.count <= AttachmentLimits.maxBytes else { throw AttachmentFailure.tooLarge } |
| 50 | return data |
| 51 | } |
| 52 | let filename = URL(fileURLWithPath: name ?? source.lastPathComponent).lastPathComponent |
| 53 | let file: AttachmentFile |
| 54 | if let image = CGImageSourceCreateWithURL(staged as CFURL, [kCGImageSourceShouldCache: false] as CFDictionary), |
| 55 | let prepared = try prepareImage(image, name: filename, maximumBytes: AttachmentLimits.maxBytes, original: boundedData) { |
| 56 | file = prepared |
| 57 | } else { file = try prepare(boundedData(), name: filename) } |
| 58 | try Task.checkCancellation() |
| 59 | guard file.data.count <= AttachmentLimits.maxBytes else { throw AttachmentFailure.tooLarge } |
| 60 | let id = UUID(), destination = directory.appendingPathComponent(UUID().uuidString) |
| 61 | #if os(iOS) |
| 62 | try file.data.write(to: destination, options: [.atomic, .completeFileProtection]) |
| 63 | #else |
| 64 | try file.data.write(to: destination, options: .atomic) |
| 65 | #endif |
| 66 | return FileAttachment(id: id, url: destination, name: file.name, mediaType: file.mediaType, width: file.width, height: file.height) |
| 67 | } |
| 68 | } |
| 69 | |