Sources/OrgApp/AttachActions.swift

06941b2cf25c6ccc1629723cd7951910ce15e67a
orgstar/Sources/OrgApp/AttachActions.swift history · blame · raw

213 lines · 9425 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    public var apply: (String) -> Void
 11    public var show: (String) -> Void
 12    public var ask: (Prompt, @escaping (String?) -> Void) -> Void
 13    public var storeLink: (StoredLink) -> Void
 14    /// Opens a file as following a `file:` link does.
 15    public var open: (String) -> Void
 16    /// Shows a folder in the system's file browser.
 17    public var reveal: (String) -> Void
 18    /// Asks for files to attach with a method.
 19    public var pick: (Attachments.Method) -> Void
 20
 21    public init(
 22        entry: @escaping () -> Attachments.Entry?, apply: @escaping (String) -> Void, show: @escaping (String) -> Void,
 23        ask: @escaping (Prompt, @escaping (String?) -> Void) -> Void, storeLink: @escaping (StoredLink) -> Void,
 24        open: @escaping (String) -> Void, reveal: @escaping (String) -> Void, pick: @escaping (Attachments.Method) -> Void
 25    ) {
 26        self.entry = entry
 27        self.apply = apply
 28        self.show = show
 29        self.ask = ask
 30        self.storeLink = storeLink
 31        self.open = open
 32        self.reveal = reveal
 33        self.pick = pick
 34    }
 35
 36    public static let methods: [String: Attachments.Method] = [
 37        "app.attach.attach": .cp, "app.attach.move": .mv, "app.attach.link": .ln, "app.attach.symlink": .lns,
 38    ]
 39
 40    private func yes(_ question: String, _ then: @escaping (Bool) -> Void) {
 41        ask(Prompt(key: "confirm", message: question + " (yes or no)", choices: ["yes", "no"])) { then($0 == "yes") }
 42    }
 43
 44    /// Runs `body` on the entry and applies its text, or shows what went wrong.
 45    private func change(_ body: (inout Attachments.Entry) throws -> String?) {
 46        guard var entry = entry() else { return show("No file is open") }
 47        let original = entry.text
 48        do {
 49            let message = try body(&entry)
 50            if entry.text != original { apply(entry.text) }
 51            if let message { show(message) }
 52        } catch {
 53            if entry.text != original { apply(entry.text) }
 54            show((error as? Attachments.Failure)?.description ?? error.localizedDescription)
 55        }
 56    }
 57
 58    public func run(_ id: String) {
 59        if let method = Self.methods[id] { return pick(method) }
 60        switch id {
 61        case "app.attach.url":
 62            ask(Prompt(key: "url", message: "URL of the file to attach:")) { answer in
 63                guard let answer, !answer.isEmpty else { return }
 64                download(answer)
 65            }
 66        case "app.attach.new":
 67            ask(Prompt(key: "name", message: "Create attachment named:")) { name in
 68                guard let name, !name.isEmpty else { return }
 69                var file: String?
 70                change { entry in
 71                    file = try Attachments.create(name, in: &entry)
 72                    return "New attachment \(name)"
 73                }
 74                if let file { open(file) }
 75            }
 76        case "app.attach.sync":
 77            var empty: String?
 78            change { entry in
 79                empty = Attachments.sync(&entry)
 80                return nil
 81            }
 82            if let empty {
 83                yes("Attachment directory is empty.  Delete?") { delete in
 84                    if delete { try? FileManager.default.removeItem(atPath: empty) }
 85                }
 86            }
 87        case "app.attach.open":
 88            guard let entry = entry() else { return show("No file is open") }
 89            guard let dir = Attachments.directory(entry) else { return show("No attachment directory exist") }
 90            let files = Attachments.files(in: dir)
 91            if files.count == 1 { return open((dir as NSString).appendingPathComponent(files[0])) }
 92            guard !files.isEmpty else { return show("No attachments in \(dir)") }
 93            ask(Prompt(key: "file", message: "Open attachment:", choices: files)) { file in
 94                if let file { open((dir as NSString).appendingPathComponent(file)) }
 95            }
 96        case "app.attach.reveal":
 97            var dir: String?
 98            change { entry in
 99                dir = try Attachments.directoryCreating(&entry)
100                return nil
101            }
102            if let dir { reveal(dir) }
103        case "app.attach.delete":
104            guard let entry = entry() else { return show("No file is open") }
105            guard let dir = Attachments.directory(entry) else { return show("No attachment directory exist") }
106            ask(Prompt(key: "file", message: "Delete attachment:", choices: Attachments.files(in: dir))) { file in
107                guard let file else { return }
108                change { entry in
109                    try Attachments.delete(file, in: entry)
110                    return "Deleted attachment \(file)"
111                }
112            }
113        case "app.attach.delete-all":
114            guard let entry = entry() else { return show("No file is open") }
115            guard Attachments.directory(entry) != nil else { return show("No attachment directory exist") }
116            yes("Really remove all attachments of this entry?") { remove in
117                guard remove else { return }
118                change { entry in
119                    try Attachments.deleteAll(&entry)
120                    return "Attachment directory removed"
121                }
122            }
123        case "app.attach.set-directory":
124            guard let entry = entry() else { return show("No file is open") }
125            let current = OrgAttach.dirProperty(tree: OrgParser.parse(entry.text), at: entry.offset)
126            ask(Prompt(key: "dir", message: "Attachment directory:", initial: current ?? "", requireMatch: false)) { answer in
127                guard let answer, !answer.isEmpty else { return }
128                var moved: (new: String, old: String?)?
129                change { entry in
130                    moved = Attachments.setDirectory(answer, in: &entry)
131                    return nil
132                }
133                if let moved, let old = moved.old { offerMove(from: old, to: moved.new) }
134            }
135        case "app.attach.unset-directory":
136            var moved: (old: String?, new: String?)?
137            change { entry in
138                moved = Attachments.unsetDirectory(&entry)
139                return nil
140            }
141            if let moved, let old = moved.old { offerMove(from: old, to: moved.new) }
142        default:
143            show("Unknown attachment command \(id)")
144        }
145    }
146
147    /// `org-attach-set-directory`'s questions after the folder changes.
148    private func offerMove(from old: String, to new: String?) {
149        func offerDelete() {
150            yes("Delete \(old)") { delete in
151                if delete { try? FileManager.default.removeItem(atPath: old) }
152            }
153        }
154        guard let new else { return offerDelete() }
155        yes("Copy over attachments from old directory?") { copy in
156            if copy {
157                do { try Attachments.copyContents(of: old, to: new) } catch { return show(error.localizedDescription) }
158            }
159            offerDelete()
160        }
161    }
162
163    /// `org-attach-attach` for each picked file.
164    public func attach(_ urls: [URL], method: Attachments.Method) {
165        change { entry in
166            var names: [String] = []
167            for url in urls {
168                let scoped = url.startAccessingSecurityScopedResource()
169                defer { if scoped { url.stopAccessingSecurityScopedResource() } }
170                let link = try Attachments.attach(url, method: method, to: &entry)
171                storeLink(link)
172                names.append(link.description ?? url.lastPathComponent)
173            }
174            return Self.attached(names)
175        }
176    }
177
178    /// `data` attached as `name`, as a photo or a download is.
179    public func attach(_ data: Data, named name: String) {
180        change { entry in
181            let link = try Attachments.attach(data, named: name, to: &entry)
182            storeLink(link)
183            return Self.attached([name])
184        }
185    }
186
187    static func attached(_ names: [String]) -> String? {
188        switch names.count {
189        case 0: nil
190        case 1: "File \"\(names[0])\" is now an attachment"
191        default: "\(names.count) files are now attachments"
192        }
193    }
194
195    /// `org-attach-url`: the file downloaded, then attached as the URL's last part.
196    private func download(_ address: String) {
197        guard let url = URL(string: address), url.scheme != nil else { return show("Not a URL: \(address)") }
198        let name = Attachments.name(ofURL: address)
199        guard !name.isEmpty else { return show("No file name in \(address)") }
200        show("Downloading \(address)…")
201        Task { @MainActor in
202            do {
203                let (data, response) = try await URLSession.shared.data(from: url)
204                if let http = response as? HTTPURLResponse, !(200..<300).contains(http.statusCode) {
205                    return show("Can't download \(address): HTTP \(http.statusCode)")
206                }
207                attach(data, named: name)
208            } catch {
209                show("Can't download \(address): \(error.localizedDescription)")
210            }
211        }
212    }
213}