| 1 | import AppKit |
| 2 | import EquipoKit |
| 3 | |
| 4 | /// Each accepted drop owns a private directory for the lifetime of its readers. |
| 5 | /// Read inside NSFilePromiseReceiver's coordinated callback, then hand bytes to |
| 6 | /// the draft so retry does not depend on the temporary file remaining on disk. |
| 7 | private final class PromiseDirectory: @unchecked Sendable { |
| 8 | let url: URL |
| 9 | init() throws { |
| 10 | url = FileManager.default.temporaryDirectory.appendingPathComponent("equipo-drop-" + UUID().uuidString, isDirectory: true) |
| 11 | try FileManager.default.createDirectory(at: url, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) |
| 12 | } |
| 13 | deinit { try? FileManager.default.removeItem(at: url) } |
| 14 | } |
| 15 | |
| 16 | extension MacComposer { |
| 17 | func receive(_ promises: [NSFilePromiseReceiver], into draft: AttachmentDraft) { |
| 18 | do { |
| 19 | let directory = try PromiseDirectory() |
| 20 | let queue = OperationQueue(); queue.maxConcurrentOperationCount = 1 |
| 21 | for promise in promises { |
| 22 | promise.receivePromisedFiles(atDestination: directory.url, options: [:], operationQueue: queue) { [directory] url, error in |
| 23 | let result = Result<Data, Error> { |
| 24 | if let error { throw error } |
| 25 | guard url.isFileURL, |
| 26 | url.standardizedFileURL.deletingLastPathComponent() == directory.url.standardizedFileURL, |
| 27 | (try url.resourceValues(forKeys: [.isRegularFileKey])).isRegularFile == true else { throw AttachmentFailure.type } |
| 28 | return try AttachmentFile.read(url) |
| 29 | } |
| 30 | if url.standardizedFileURL.deletingLastPathComponent() == directory.url.standardizedFileURL { try? FileManager.default.removeItem(at: url) } |
| 31 | Task { @MainActor in |
| 32 | switch result { |
| 33 | case .success(let data): await draft.add(data: data, name: url.lastPathComponent) |
| 34 | case .failure: draft.refuseFile() |
| 35 | } |
| 36 | } |
| 37 | } |
| 38 | } |
| 39 | } catch { draft.refuseFile() } |
| 40 | } |
| 41 | } |
| 42 | |