import Foundation import ImageIO public struct FileAttachment: Sendable, Identifiable { public let id: UUID public let url: URL public let name: String public let mediaType: String public let width: Int public let height: Int } extension AttachmentFile { /// Copy while the provider's URL and security scope are valid. Bounded chunks, /// no mmap or whole-original allocation; caller runs serially off the main actor. public static func stage(_ source: URL, directory: URL, maximumBytes: Int = AttachmentLimits.maxInputBytes, access: any AttachmentFileAccess = SystemAttachmentFileAccess()) throws -> URL { guard source.isFileURL else { throw AttachmentFailure.type } let started = access.start(source); defer { if started { access.stop(source) } } guard try access.isRegularFile(source) else { throw AttachmentFailure.type } try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) let target = directory.appendingPathComponent(UUID().uuidString).appendingPathExtension(source.pathExtension) var attributes: [FileAttributeKey: Any] = [.posixPermissions: 0o600] #if os(iOS) attributes[.protectionKey] = FileProtectionType.complete #endif guard FileManager.default.createFile(atPath: target.path, contents: nil, attributes: attributes) else { throw AttachmentFailure.type } var completed = false defer { if !completed { try? FileManager.default.removeItem(at: target) } } let input = try FileHandle(forReadingFrom: source); defer { try? input.close() } let output = try FileHandle(forWritingTo: target); defer { try? output.close() } var count = 0 while let chunk = try input.read(upToCount: 64 * 1024), !chunk.isEmpty { try Task.checkCancellation() count += chunk.count guard count <= maximumBytes else { throw AttachmentFailure.tooLarge } try output.write(contentsOf: chunk) } guard count > 0 else { throw AttachmentFailure.type } completed = true return target } public static func prepareFile(_ source: URL, directory: URL, name: String? = nil, access: any AttachmentFileAccess = SystemAttachmentFileAccess()) throws -> FileAttachment { let staged = try stage(source, directory: directory, access: access) defer { try? FileManager.default.removeItem(at: staged) } func boundedData() throws -> Data { let handle = try FileHandle(forReadingFrom: staged); defer { try? handle.close() } let data = try handle.read(upToCount: AttachmentLimits.maxBytes + 1) ?? Data() guard data.count <= AttachmentLimits.maxBytes else { throw AttachmentFailure.tooLarge } return data } let filename = URL(fileURLWithPath: name ?? source.lastPathComponent).lastPathComponent let file: AttachmentFile if let image = CGImageSourceCreateWithURL(staged as CFURL, [kCGImageSourceShouldCache: false] as CFDictionary), let prepared = try prepareImage(image, name: filename, maximumBytes: AttachmentLimits.maxBytes, original: boundedData) { file = prepared } else { file = try prepare(boundedData(), name: filename) } try Task.checkCancellation() guard file.data.count <= AttachmentLimits.maxBytes else { throw AttachmentFailure.tooLarge } let id = UUID(), destination = directory.appendingPathComponent(UUID().uuidString) #if os(iOS) try file.data.write(to: destination, options: [.atomic, .completeFileProtection]) #else try file.data.write(to: destination, options: .atomic) #endif return FileAttachment(id: id, url: destination, name: file.name, mediaType: file.mediaType, width: file.width, height: file.height) } }