forked from quoid/userscripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtilities.swift
More file actions
168 lines (155 loc) · 5 KB
/
Copy pathUtilities.swift
File metadata and controls
168 lines (155 loc) · 5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import SwiftUI
let bundleIdentifier = Bundle.main.bundleIdentifier!
let groupIdentifier = Bundle.main.infoDictionary!["US_SHARED_GID"] as! String
let extIdentifier = Bundle.main.infoDictionary?["US_EXT_IDENTIFIER"] as! String
let projectName = "Userscripts"
//let projectName = Bundle.main.infoDictionary!["PROJECT_NAME"] as! String
private let logger = USLogger(#fileID)
func getPlatform() -> String {
#if os(macOS)
return "macos"
#elseif os(iOS)
// https://developer.apple.com/documentation/uikit/uiuserinterfaceidiom
// There is no reliable way to detect visionOS for now, will match `.phone` in Apple Vision (Designed for iPad) mode
switch UIDevice.current.userInterfaceIdiom {
case .phone:
return "ios"
case .pad, .mac:
return "ipados"
case .vision:
return "visionos"
case .tv:
return "tvos"
case .carPlay:
return "carplay"
case .unspecified:
return "unspecified"
@unknown default:
return "unknown"
}
#endif
}
func directoryExists(path: String) -> Bool {
var isDirectory = ObjCBool(true)
let exists = FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory)
let inTrash = path.contains(".Trash") ? false : true
return exists && inTrash && isDirectory.boolValue
}
func directoryEmpty(at url: URL) -> Bool? {
// get a list of non-hidden files
guard let contents = try? FileManager.default.contentsOfDirectory(
at: url,
includingPropertiesForKeys: [],
options: .skipsHiddenFiles
) else {
logger?.error("\(#function, privacy: .public) - failed get contentsOfDirectory")
return nil
}
return contents.isEmpty
}
func getDocumentsDirectory() -> URL {
let fm = FileManager.default
let paths = fm.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
func getProjectSharedDirectoryURL(path: String? = nil) -> URL? {
// https://developer.apple.com/documentation/foundation/filemanager/1412643-containerurl/
guard let sharedContainerURL = FileManager.default.containerURL(
forSecurityApplicationGroupIdentifier: groupIdentifier
) else {
logger?.error("\(#function, privacy: .public) - Failed get sharedContainerURL")
return nil
}
guard let path = path else {
return sharedContainerURL
}
if #available(macOS 13.0, iOS 16.0, *) {
return sharedContainerURL.appending(path: path, directoryHint: .isDirectory)
} else {
return sharedContainerURL.appendingPathComponent(path, isDirectory: true)
}
}
func getDefaultScriptsDirectoryUrl() -> URL {
#if os(iOS)
return URL(string: "default://uninitialized")!
#elseif os(macOS)
var url: URL
if #available(macOS 13.0, iOS 16.0, *) {
url = getDocumentsDirectory().appending(path: "scripts")
} else {
url = getDocumentsDirectory().appendingPathComponent("scripts")
}
// if not in safari extension environment, replace with extension path
if bundleIdentifier != extIdentifier {
var path: String
if #available(macOS 13.0, iOS 16.0, *) {
path = url.path(percentEncoded: false)
} else {
path = url.path.removingPercentEncoding ?? url.path
}
let truePath = path.replacingOccurrences(of: bundleIdentifier, with: extIdentifier)
url = URL(fileURLWithPath: truePath, isDirectory: true)
}
return url
#endif
}
#if os(iOS)
// Initialization directory is only required in iOS
func isCurrentDefaultScriptsDirectory() -> Bool {
return Preferences.scriptsDirectoryUrl == getDefaultScriptsDirectoryUrl()
}
#endif
// For mac, the initial directory is Ext-Documents (default directory)
// For ios, the initial directory is App-Documents
// In ios only App-Documents can be displayed in Files App
func isCurrentInitialScriptsDirectory() -> Bool {
let url = Preferences.scriptsDirectoryUrl.standardizedFileURL
#if os(iOS)
return url == getDocumentsDirectory().standardizedFileURL
#elseif os(macOS)
return url == getDefaultScriptsDirectoryUrl().standardizedFileURL
#endif
}
func getCurrentScriptsDirectoryString() -> String {
if isCurrentInitialScriptsDirectory() {
return "Userscripts App Documents"
}
let url = Preferences.scriptsDirectoryUrl.standardizedFileURL
if #available(macOS 13.0, iOS 16.0, *) {
return url.path(percentEncoded: false)
} else {
return url.path.removingPercentEncoding ?? url.path
}
}
func getSaveLocation() -> URL? {
#if os(iOS)
if isCurrentDefaultScriptsDirectory() {
logger?.info("\(#function, privacy: .public) - Uninitialized save location")
return nil
}
#endif
let url = Preferences.scriptsDirectoryUrl
logger?.debug("\(#function, privacy: .public) - \(url, privacy: .public)")
return url
}
func openSaveLocation() -> Bool {
#if os(macOS)
guard let saveLocation = getSaveLocation() else {
return false
}
let didStartAccessing = saveLocation.startAccessingSecurityScopedResource()
defer {
if didStartAccessing {saveLocation.stopAccessingSecurityScopedResource()}
}
NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: saveLocation.path)
#endif
return true
}
func resetSaveLocation() {
logger?.info("\(#function, privacy: .public) - Reset save location")
#if os(iOS)
Preferences.scriptsDirectoryUrl = getDocumentsDirectory()
#elseif os(macOS)
#endif
}