Sources/OrgApp/AttachActions.swift

264 lines · 12375 bytes

  1import Foundation
  2import OrgCore
  3
  4/// The `app.attach.` commands for the entry at the caret, with the platform's questions,
  5/// file picker and file opening.
  6@MainActor
  7public struct AttachActions {
  8    /// The open file's entry at the caret; nil when no file is open.
  9    public var entry: () -> Attachments.Entry?
 10    /// The buffer's new text, and where the caret goes; nil keeps it where it is.
 11    public var apply: (String, Int?) -> Void
 12    public var show: (String) -> Void
 13    public var ask: (Prompt, @escaping (String?) -> Void) -> Void
 14    public var storeLink: (StoredLink) -> Void
 15    /// Opens a file as following a `file:` link does.
 16    public var open: (String) -> Void
 17    /// Shows a folder in the system's file browser.
 18    public var reveal: (String) -> Void
 19    /// Asks for files to attach with a method.
 20    public var pick: (Attachments.Method) -> Void
 21
 22    public init(
 23        entry: @escaping () -> Attachments.Entry?, apply: @escaping (String, Int?) -> Void, show: @escaping (String) -> Void,
 24        ask: @escaping (Prompt, @escaping (String?) -> Void) -> Void, storeLink: @escaping (StoredLink) -> Void,
 25        open: @escaping (String) -> Void, reveal: @escaping (String) -> Void, pick: @escaping (Attachments.Method) -> Void
 26    ) {
 27        self.entry = entry
 28        self.apply = apply
 29        self.show = show
 30        self.ask = ask
 31        self.storeLink = storeLink
 32        self.open = open
 33        self.reveal = reveal
 34        self.pick = pick
 35    }
 36
 37    public static let methods: [String: Attachments.Method] = [
 38        "app.attach.attach": .cp, "app.attach.move": .mv, "app.attach.link": .ln, "app.attach.symlink": .lns,
 39    ]
 40
 41    private func yes(_ question: String, _ then: @escaping (Bool) -> Void) {
 42        ask(Prompt(key: "confirm", message: question + " (yes or no)", choices: ["yes", "no"])) { then($0 == "yes") }
 43    }
 44
 45    /// Runs `body` on the entry and applies its text, or shows what went wrong.
 46    private func change(_ body: (inout Attachments.Entry) throws -> String?) {
 47        guard var entry = entry() else { return show("No file is open") }
 48        let original = entry.text
 49        do {
 50            let message = try body(&entry)
 51            if entry.text != original { apply(entry.text, nil) }
 52            if let message { show(message) }
 53        } catch {
 54            if entry.text != original { apply(entry.text, nil) }
 55            show((error as? Attachments.Failure)?.description ?? error.localizedDescription)
 56        }
 57    }
 58
 59    public func run(_ id: String) {
 60        if let method = Self.methods[id] { return pick(method) }
 61        switch id {
 62        case "app.attach.url":
 63            ask(Prompt(key: "url", message: "URL of the file to attach:")) { answer in
 64                guard let answer, !answer.isEmpty else { return }
 65                download(answer)
 66            }
 67        case "app.attach.new":
 68            ask(Prompt(key: "name", message: "Create attachment named:")) { name in
 69                guard let name, !name.isEmpty else { return }
 70                var file: String?
 71                change { entry in
 72                    file = try Attachments.create(name, in: &entry)
 73                    return "New attachment \(name)"
 74                }
 75                if let file { open(file) }
 76            }
 77        case "app.attach.sync":
 78            var empty: String?
 79            change { entry in
 80                empty = Attachments.sync(&entry)
 81                return nil
 82            }
 83            if let empty {
 84                yes("Attachment directory is empty.  Delete?") { delete in
 85                    if delete { try? FileManager.default.removeItem(atPath: empty) }
 86                }
 87            }
 88        case "app.attach.open":
 89            guard let entry = entry() else { return show("No file is open") }
 90            guard let dir = Attachments.directory(entry) else { return show("No attachment directory exist") }
 91            let files = Attachments.files(in: dir)
 92            if files.count == 1 { return open((dir as NSString).appendingPathComponent(files[0])) }
 93            guard !files.isEmpty else { return show("No attachments in \(dir)") }
 94            ask(Prompt(key: "file", message: "Open attachment:", choices: files)) { file in
 95                if let file { open((dir as NSString).appendingPathComponent(file)) }
 96            }
 97        case "app.attach.reveal":
 98            var dir: String?
 99            change { entry in
100                dir = try Attachments.directoryCreating(&entry)
101                return nil
102            }
103            if let dir { reveal(dir) }
104        case "app.attach.delete":
105            guard let entry = entry() else { return show("No file is open") }
106            guard let dir = Attachments.directory(entry) else { return show("No attachment directory exist") }
107            ask(Prompt(key: "file", message: "Delete attachment:", choices: Attachments.files(in: dir))) { file in
108                guard let file else { return }
109                change { entry in
110                    try Attachments.delete(file, in: entry)
111                    return "Deleted attachment \(file)"
112                }
113            }
114        case "app.attach.delete-all":
115            guard let entry = entry() else { return show("No file is open") }
116            guard Attachments.directory(entry) != nil else { return show("No attachment directory exist") }
117            yes("Really remove all attachments of this entry?") { remove in
118                guard remove else { return }
119                change { entry in
120                    try Attachments.deleteAll(&entry)
121                    return "Attachment directory removed"
122                }
123            }
124        case "app.attach.set-directory":
125            guard let entry = entry() else { return show("No file is open") }
126            let current = OrgAttach.dirProperty(tree: OrgParser.parse(entry.text), at: entry.offset)
127            ask(Prompt(key: "dir", message: "Attachment directory:", initial: current ?? "", requireMatch: false)) { answer in
128                guard let answer, !answer.isEmpty else { return }
129                var moved: (new: String, old: String?)?
130                change { entry in
131                    moved = Attachments.setDirectory(answer, in: &entry)
132                    return nil
133                }
134                if let moved, let old = moved.old { offerMove(from: old, to: moved.new) }
135            }
136        case "app.attach.unset-directory":
137            var moved: (old: String?, new: String?)?
138            change { entry in
139                moved = Attachments.unsetDirectory(&entry)
140                return nil
141            }
142            if let moved, let old = moved.old { offerMove(from: old, to: moved.new) }
143        default:
144            show("Unknown attachment command \(id)")
145        }
146    }
147
148    /// `org-attach-set-directory`'s questions after the folder changes.
149    private func offerMove(from old: String, to new: String?) {
150        func offerDelete() {
151            yes("Delete \(old)") { delete in
152                if delete { try? FileManager.default.removeItem(atPath: old) }
153            }
154        }
155        guard let new else { return offerDelete() }
156        yes("Copy over attachments from old directory?") { copy in
157            if copy {
158                do { try Attachments.copyContents(of: old, to: new) } catch { return show(error.localizedDescription) }
159            }
160            offerDelete()
161        }
162    }
163
164    /// `org-attach-attach` for each picked file.
165    public func attach(_ urls: [URL], method: Attachments.Method) {
166        change { entry in
167            var names: [String] = []
168            for url in urls {
169                let scoped = url.startAccessingSecurityScopedResource()
170                defer { if scoped { url.stopAccessingSecurityScopedResource() } }
171                let link = try Attachments.attach(url, method: method, to: &entry)
172                storeLink(link)
173                names.append(link.description ?? url.lastPathComponent)
174            }
175            return Self.attached(names)
176        }
177    }
178
179    /// `data` attached as `name`, as a photo or a download is.
180    public func attach(_ data: Data, named name: String) {
181        change { entry in
182            let link = try Attachments.attach(data, named: name, to: &entry)
183            storeLink(link)
184            return Self.attached([name])
185        }
186    }
187
188    /// Runs `body` on the entry and puts the links it returns at the caret.
189    private func insert(_ body: (inout Attachments.Entry) throws -> [String]) {
190        guard var entry = entry() else { return show("No file is open") }
191        let original = entry.text
192        do {
193            let links = try body(&entry)
194            guard !links.isEmpty else { return }
195            let (text, caret) = ImageYank.inserting(links, into: entry.text, at: ImageYank.map(entry.offset, from: original, to: entry.text))
196            apply(text, caret)
197            let names = links.compactMap { $0.firstMatch(of: /^\[\[attachment:(.*)\]\]$/).map { String($0.1) } }
198            if let message = Self.attached(names) { show(message) }
199        } catch {
200            if entry.text != original { apply(entry.text, nil) }
201            show((error as? Attachments.Failure)?.description ?? error.localizedDescription)
202        }
203    }
204
205    /// `yank-media` with an image: `data` saved as `org-yank-image-save-method` says, with
206    /// extension `ext`, and its link at the caret. `prefix` replaces "clipboard" in the name.
207    public func yankImage(_ data: Data, ext: String, prefix: String = "clipboard") {
208        let method = ImageYank.SaveMethod(OrgPreferences.yankImageSaveMethod())
209        insert { entry in [try ImageYank.save(data, ext: ext, method: method, in: &entry, prefix: prefix)] }
210    }
211
212    /// Files dropped or pasted, as `org-yank-dnd-method` says: attached with `attachMethod`,
213    /// opened, or linked; their links at the caret.
214    public func drop(_ files: [URL], method: ImageYank.DropMethod = OrgPreferences.yankDndMethod(), attachMethod: Attachments.Method = .cp) {
215        guard !files.isEmpty else { return }
216        switch method {
217        case .ask:
218            ask(Prompt(key: "dnd", message: "What to do with file?", choices: ["attach", "open", "insert file: link"])) { answer in
219                switch answer {
220                case "attach": drop(files, method: .attach, attachMethod: attachMethod)
221                case "open": drop(files, method: .open, attachMethod: attachMethod)
222                case "insert file: link": drop(files, method: .fileLink, attachMethod: attachMethod)
223                default: break
224                }
225            }
226        case .open:
227            for file in files { open(file.path) }
228        case .attach, .fileLink:
229            let saveMethod = ImageYank.SaveMethod(OrgPreferences.yankImageSaveMethod())
230            insert { entry in
231                let scoped = files.map { $0.startAccessingSecurityScopedResource() }
232                defer { for (file, on) in zip(files, scoped) where on { file.stopAccessingSecurityScopedResource() } }
233                return try ImageYank.drop(files, method: method, attachMethod: attachMethod, saveMethod: saveMethod, in: &entry)
234            }
235        }
236    }
237
238    static func attached(_ names: [String]) -> String? {
239        switch names.count {
240        case 0: nil
241        case 1: "File \"\(names[0])\" is now an attachment"
242        default: "\(names.count) files are now attachments"
243        }
244    }
245
246    /// `org-attach-url`: the file downloaded, then attached as the URL's last part.
247    private func download(_ address: String) {
248        guard let url = URL(string: address), url.scheme != nil else { return show("Not a URL: \(address)") }
249        let name = Attachments.name(ofURL: address)
250        guard !name.isEmpty else { return show("No file name in \(address)") }
251        show("Downloading \(address)…")
252        Task { @MainActor in
253            do {
254                let (data, response) = try await URLSession.shared.data(from: url)
255                if let http = response as? HTTPURLResponse, !(200..<300).contains(http.statusCode) {
256                    return show("Can't download \(address): HTTP \(http.statusCode)")
257                }
258                attach(data, named: name)
259            } catch {
260                show("Can't download \(address): \(error.localizedDescription)")
261            }
262        }
263    }
264}