Sources/OrgApp/FolderGrants.swift
58 lines · 2617 bytes
1import Foundation
2import OrgCore
3
4/// Bookmarks that give access back after relaunch: security-scoped in the Mac sandbox, plain
5/// elsewhere.
6public enum SecurityBookmark {
7 public static func make(_ url: URL, sandboxed: Bool = Sandbox.isActive) -> Data? {
8 try? url.bookmarkData(options: Sandbox.bookmarkCreationOptions(sandboxed: sandboxed))
9 }
10
11 /// The bookmarked URL with access to it started, and new data when the bookmark was stale.
12 public static func resolve(_ data: Data, sandboxed: Bool = Sandbox.isActive) -> (url: URL, renewed: Data?)? {
13 var stale = false
14 guard let url = try? URL(resolvingBookmarkData: data, options: Sandbox.bookmarkResolutionOptions(sandboxed: sandboxed), bookmarkDataIsStale: &stale) else { return nil }
15 _ = url.startAccessingSecurityScopedResource()
16 return (url, stale ? make(url, sandboxed: sandboxed) : nil)
17 }
18}
19
20/// Folders outside the sidebar's folders that the Mac sandbox let orgstar into through an open
21/// panel: setup files, includes, tangle and export targets and the like. Kept as bookmarks and
22/// started when the store is first used.
23@MainActor
24public final class FolderGrants {
25 public static let shared = FolderGrants()
26 static let key = "folderGrants"
27
28 private let defaults: UserDefaults
29 private let sandboxed: Bool
30 /// The granted folders, with access started.
31 public private(set) var folders: [URL] = []
32
33 init(defaults: UserDefaults = .standard, sandboxed: Bool = Sandbox.isActive) {
34 self.defaults = defaults
35 self.sandboxed = sandboxed
36 let saved = defaults.array(forKey: Self.key) as? [Data] ?? []
37 var kept: [Data] = []
38 for data in saved {
39 // One that doesn't resolve now (an unmounted volume) is kept for later.
40 guard let (url, renewed) = SecurityBookmark.resolve(data, sandboxed: sandboxed) else {
41 kept.append(data)
42 continue
43 }
44 folders.append(url)
45 kept.append(renewed ?? data)
46 }
47 if kept != saved { defaults.set(kept, forKey: Self.key) }
48 }
49
50 /// Keeps `url`, a folder from an open panel, and starts access to it.
51 public func add(_ url: URL) {
52 _ = url.startAccessingSecurityScopedResource()
53 guard !folders.contains(where: { $0.standardizedFileURL == url.standardizedFileURL }),
54 let data = SecurityBookmark.make(url, sandboxed: sandboxed) else { return }
55 folders.append(url)
56 defaults.set((defaults.array(forKey: Self.key) as? [Data] ?? []) + [data], forKey: Self.key)
57 }
58}