Sources/OrgApp/SubtreeShare.swift
117 lines · 6770 bytes
1import Foundation
2import OrgCore
3
4/// Share Subtree…: the entry at the caret as an org file of its own or as text, with the files
5/// attached to it and to the entries under it. The entry is taken as the file holds it, so an
6/// encrypted entry is shared encrypted.
7public struct SubtreeShare: Sendable, Identifiable {
8 public let id = UUID()
9 /// The entry with the file's keyword lines, as `ExportScope.entry` gives it.
10 public let text: String
11 /// The `.org` file's name: the heading's title.
12 public let fileName: String
13 /// Files in the attachment folders of the entry and the entries under it.
14 public let attachments: [URL]
15
16 /// The entry at `offset` in `text`, the file at `path`; nil before the first heading.
17 /// `idDir` and `inherit` are `org-attach-id-dir` and `org-attach-use-inheritance`.
18 public init?(text: String, at offset: Int, path: String, settings: OrgSettings = .default,
19 idDir: String = OrgPreferences.attachIDDir(), inherit: Bool? = OrgPreferences.attachUseInheritance()) {
20 guard let entry = ExportScope.entry(text, at: offset, settings: settings) else { return nil }
21 self.text = entry.text
22 let tree = OrgParser.parse(text, defaults: settings)
23 let headings = DocumentModel(tree: tree).headings.filter { entry.range.contains($0.headingRange.lowerBound) }
24 fileName = Self.fileName(entry.title)
25 var folders: [String] = []
26 for heading in headings {
27 guard let dir = OrgAttach.directory(tree: tree, at: heading.headingRange.lowerBound, path: path, idDir: idDir, inherit: inherit, isDirectory: Attachments.isDirectory),
28 !folders.contains(dir) else { continue }
29 folders.append(dir)
30 }
31 // Files only: hidden files and folders inside stay behind.
32 attachments = folders.flatMap { dir in
33 Attachments.files(in: dir).filter { !$0.hasPrefix(".") }.map { URL(fileURLWithPath: dir).appendingPathComponent($0) }
34 .filter { !Attachments.isDirectory($0.path) }
35 }
36 }
37
38 /// `title` as a file name: characters other systems refuse replaced, at most 80 long, with
39 /// `.org`.
40 static func fileName(_ title: String) -> String {
41 var name = title.components(separatedBy: CharacterSet(charactersIn: "/\\:*?\"<>|").union(.newlines).union(.controlCharacters))
42 .joined(separator: "-").trimmingCharacters(in: .whitespaces)
43 while name.hasPrefix(".") { name.removeFirst() }
44 if name.count > 80 { name = String(name.prefix(80)).trimmingCharacters(in: .whitespaces) }
45 return (name.isEmpty ? "Subtree" : name) + ".org"
46 }
47
48 /// Writes the entry as `fileName` in a new temporary folder; its URL.
49 public func writeFile() throws -> URL {
50 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("share-" + id.uuidString)
51 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
52 let url = folder.appendingPathComponent(fileName)
53 try Data(text.utf8).write(to: url, options: .atomic)
54 return url
55 }
56
57 /// What the share sheet sends: the written file and, when asked, the attachments, each as
58 /// an item of its own.
59 public func files(file: URL, withAttachments: Bool) -> [URL] {
60 [file] + (withAttachments ? attachments : [])
61 }
62}
63
64extension DocumentSession {
65 /// Share Subtree… for the entry at `offset` in the open file at `path`, as it is on disk:
66 /// its tagged entries encrypted; a heading inside an encrypted entry as an entry of its own,
67 /// "Encrypted entry" with the tag, whose one message holds the whole subtree. Nil when
68 /// there's no entry there, or `refusesSubtreeShare`.
69 public func subtreeShare(_ path: String, at offset: Int) -> SubtreeShare? {
70 guard case .success(let source) = shareSource(path, at: offset) else { return nil }
71 return SubtreeShare(text: source.text, at: source.offset, path: path, settings: defaults)
72 }
73
74 /// Why the entry at `offset` in `path` isn't shared: its file is encrypted, or what's
75 /// encrypted on disk can't be encrypted in the copy (no passphrase, or one that fails).
76 public func refusesSubtreeShare(_ path: String, at offset: Int) -> String? {
77 if case .failure(let refusal) = shareSource(path, at: offset) { return refusal.message }
78 return nil
79 }
80
81 struct ShareRefusal: Error {
82 let message: String
83 }
84
85 /// The text to share the entry at `offset` from, and where in it.
86 private func shareSource(_ path: String, at offset: Int) -> Result<(text: String, offset: Int), ShareRefusal> {
87 let name = (path as NSString).lastPathComponent
88 if Self.isEncryptedFile(path) { return .failure(ShareRefusal(message: String(localized: "\(name) is encrypted; its entries aren't shared."))) }
89 guard let text = document(of: path)?.text else { return .success((text: "", offset: offset)) }
90 guard crypt.sealsEntries(for: path), let heading = OrgCrypt.heading(text, at: offset), let range = subtreeRange(text, at: offset) else {
91 return .success((text, offset))
92 }
93 let needsPassphrase = ShareRefusal(message: String(localized: "Tagged entries in the subtree aren't encrypted; give the passphrase with Encrypt… first."))
94 if OrgCrypt.isInTaggedText(text, at: heading, tag: cryptTag) {
95 guard let passphrase = crypt.passphrase(for: path) else { return .failure(needsPassphrase) }
96 let subtree = (text as NSString).substring(with: NSRange(range))
97 do {
98 let message = try OpenPGP.encrypt(Data((subtree.hasSuffix("\n") ? subtree : subtree + "\n").utf8), passphrase: passphrase)
99 return .success(("* " + String(localized: "Encrypted entry") + " :" + cryptTag + ":\n" + message, 0))
100 } catch {
101 return .failure(ShareRefusal(message: error.localizedDescription))
102 }
103 }
104 guard !OrgCrypt.unencrypted(text, tag: cryptTag, within: range).isEmpty else { return .success((text, offset)) }
105 guard let passphrase = crypt.passphrase(for: path) else { return .failure(needsPassphrase) }
106 do {
107 return .success((try OrgCrypt.seal(text, passphrase: passphrase, tag: cryptTag, within: range).text, heading))
108 } catch {
109 return .failure(ShareRefusal(message: error.localizedDescription))
110 }
111 }
112
113 private func subtreeRange(_ text: String, at offset: Int) -> Range<Int>? {
114 guard let heading = OrgCrypt.heading(text, at: offset) else { return nil }
115 return heading..<max(heading + 1, OrgCrypt.bodyRange(text, at: heading)?.upperBound ?? heading)
116 }
117}