|
| 1 | +import Foundation |
| 2 | +import os |
| 3 | + |
| 4 | +struct SharedDefaults { |
| 5 | + static let suiteName = "group.com.userscripts.macos" |
| 6 | + static let keyName = "hostSelectedSaveLocation" |
| 7 | +} |
| 8 | + |
| 9 | +func err(_ message: String) { |
| 10 | + let log = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "general") |
| 11 | + os_log("%{public}@", log: log, type: .error, "Error: \(message)") |
| 12 | +} |
| 13 | + |
| 14 | +func getDocumentsDirectory() -> URL { |
| 15 | + let fm = FileManager.default |
| 16 | + let paths = fm.urls(for: .documentDirectory, in: .userDomainMask) |
| 17 | + let documentsDirectory = paths[0] |
| 18 | + return documentsDirectory |
| 19 | +} |
| 20 | + |
| 21 | +func saveBookmark(url: URL, isShared: Bool, keyName: String, isSecure: Bool) -> Bool { |
| 22 | + let options:URL.BookmarkCreationOptions = isSecure ? [.withSecurityScope] : [] |
| 23 | + do { |
| 24 | + let bookmark = try url.bookmarkData( |
| 25 | + options: options, |
| 26 | + includingResourceValuesForKeys: nil, |
| 27 | + relativeTo: nil |
| 28 | + ) |
| 29 | + if isShared { |
| 30 | + UserDefaults(suiteName: SharedDefaults.suiteName)?.set(bookmark, forKey: keyName) |
| 31 | + } else { |
| 32 | + UserDefaults.standard.set(bookmark, forKey: keyName) |
| 33 | + } |
| 34 | + return true |
| 35 | + } catch let error { |
| 36 | + err("\(error)") |
| 37 | + return false |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +func readBookmark(data: Data, isSecure: Bool) -> URL? { |
| 42 | + let options:URL.BookmarkResolutionOptions = isSecure ? [.withSecurityScope] : [] |
| 43 | + do { |
| 44 | + var bookmarkIsStale = false |
| 45 | + let url = try URL( |
| 46 | + resolvingBookmarkData: data, |
| 47 | + options: options, |
| 48 | + relativeTo: nil, |
| 49 | + bookmarkDataIsStale: &bookmarkIsStale |
| 50 | + ) |
| 51 | + if bookmarkIsStale { |
| 52 | + NSLog("Stale bookmark, renewing it \(url)") |
| 53 | + if saveBookmark(url: url, isShared: true, keyName: SharedDefaults.keyName, isSecure: false) { |
| 54 | + NSLog("Successfully renewed stale bookmark - \(url)") |
| 55 | + } else { |
| 56 | + NSLog("Could not renew stale bookmark - \(url)") |
| 57 | + } |
| 58 | + } |
| 59 | + return url |
| 60 | + } catch let error { |
| 61 | + err("Error: \(error)") |
| 62 | + return nil |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +func directoryExists(path: String) -> Bool { |
| 67 | + var isDirectory = ObjCBool(true) |
| 68 | + let exists = FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) |
| 69 | + let inTrash = path.contains(".Trash") ? false : true |
| 70 | + return exists && inTrash && isDirectory.boolValue |
| 71 | +} |
0 commit comments