-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
SwiftFilePickerWritablePlugin.swift
371 lines (334 loc) · 15.8 KB
/
SwiftFilePickerWritablePlugin.swift
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
import Flutter
import UIKit
import MobileCoreServices
enum FilePickerError: Error {
case readError(message: String)
case invalidArguments(message: String)
}
public class SwiftFilePickerWritablePlugin: NSObject, FlutterPlugin {
private let _viewController: UIViewController
private let _channel: FlutterMethodChannel
private var _filePickerResult: FlutterResult?
private var _filePickerPath: String?
private var isInitialized = false
private var _initOpen: (url: URL, persistable: Bool)?
private var _eventSink: FlutterEventSink? = nil
private var _eventQueue: [[String: String]] = []
public static func register(with registrar: FlutterPluginRegistrar) {
guard let vc = UIApplication.shared.delegate?.window??.rootViewController else {
NSLog("PANIC - unable to initialize plugin, no view controller available.")
fatalError("No viewController available.")
}
_ = SwiftFilePickerWritablePlugin(viewController: vc, registrar: registrar)
}
public init(viewController: UIViewController, registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "design.codeux.file_picker_writable", binaryMessenger: registrar.messenger())
_viewController = viewController;
_channel = channel
super.init()
registrar.addMethodCallDelegate(self, channel: channel)
registrar.addApplicationDelegate(self)
let eventChannel = FlutterEventChannel(name: "design.codeux.file_picker_writable/events", binaryMessenger: registrar.messenger())
eventChannel.setStreamHandler(self)
}
private func logDebug(_ message: String) {
print("DEBUG", "FilePickerWritablePlugin:", message)
sendEvent(event: ["type": "log", "level": "DEBUG", "message": message])
}
private func logError(_ message: String) {
print("ERROR", "FilePickerWritablePlugin:", message)
sendEvent(event: ["type": "log", "level": "ERROR", "message": message])
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
do {
switch call.method {
case "init":
isInitialized = true
if let (openUrl, persistable) = _initOpen {
_handleUrl(url: openUrl, persistable: persistable)
_initOpen = nil
}
result(true)
case "openFilePicker":
openFilePicker(result: result)
case "openFilePickerForCreate":
guard
let args = call.arguments as? Dictionary<String, Any>,
let path = args["path"] as? String else {
throw FilePickerError.invalidArguments(message: "Expected 'args'")
}
openFilePickerForCreate(path: path, result: result)
case "readFileWithIdentifier":
guard
let args = call.arguments as? Dictionary<String, Any>,
let identifier = args["identifier"] as? String else {
throw FilePickerError.invalidArguments(message: "Expected 'identifier'")
}
try readFile(identifier: identifier, result: result)
case "writeFileWithIdentifier":
guard let args = call.arguments as? Dictionary<String, Any>,
let identifier = args["identifier"] as? String,
let path = args["path"] as? String else {
throw FilePickerError.invalidArguments(message: "Expected 'identifier' and 'path' arguments.")
}
try writeFile(identifier: identifier, path: path, result: result)
default:
result(FlutterMethodNotImplemented)
}
} catch let error as FilePickerError {
result(FlutterError(code: "FilePickerError", message: "\(error)", details: nil))
} catch let error {
result(FlutterError(code: "UnknownError", message: "\(error)", details: nil))
}
}
func readFile(identifier: String, result: @escaping FlutterResult) throws {
guard let bookmark = Data(base64Encoded: identifier) else {
result(FlutterError(code: "InvalidDataError", message: "Unable to decode bookmark.", details: nil))
return
}
var isStale: Bool = false
let url = try URL(resolvingBookmarkData: bookmark, bookmarkDataIsStale: &isStale)
logDebug("url: \(url) / isStale: \(isStale)");
let securityScope = url.startAccessingSecurityScopedResource()
defer {
if securityScope {
url.stopAccessingSecurityScopedResource()
}
}
if !securityScope {
logDebug("Warning: startAccessingSecurityScopedResource is false for \(url).")
}
let copiedFile = try _copyToTempDirectory(url: url)
result(_fileInfoResult(tempFile: copiedFile, originalURL: url, bookmark: bookmark))
}
func writeFile(identifier: String, path: String, result: @escaping FlutterResult) throws {
guard let bookmark = Data(base64Encoded: identifier) else {
throw FilePickerError.invalidArguments(message: "Unable to decode bookmark/identifier.")
}
var isStale: Bool = false
let url = try URL(resolvingBookmarkData: bookmark, bookmarkDataIsStale: &isStale)
logDebug("url: \(url) / isStale: \(isStale)");
try _writeFile(path: path, destination: url)
let sourceFile = URL(fileURLWithPath: path)
result(_fileInfoResult(tempFile: sourceFile, originalURL: url, bookmark: bookmark))
}
// TODO: skipDestinationStartAccess is not doing anything right now. maybe get rid of it.
private func _writeFile(path: String, destination: URL, skipDestinationStartAccess: Bool = false) throws {
let sourceFile = URL(fileURLWithPath: path)
let destAccess = destination.startAccessingSecurityScopedResource()
if !destAccess {
logDebug("Warning: startAccessingSecurityScopedResource is false for \(destination) (destination); skipDestinationStartAccess=\(skipDestinationStartAccess)")
// throw FilePickerError.invalidArguments(message: "Unable to access original url \(destination)")
}
let sourceAccess = sourceFile.startAccessingSecurityScopedResource()
if !sourceAccess {
logDebug("Warning: startAccessingSecurityScopedResource is false for \(sourceFile) (sourceFile)")
// throw FilePickerError.readError(message: "Unable to access source file \(sourceFile)")
}
defer {
if (destAccess) {
destination.stopAccessingSecurityScopedResource();
}
if (sourceAccess) {
sourceFile.stopAccessingSecurityScopedResource()
}
}
let data = try Data(contentsOf: sourceFile)
try data.write(to: destination, options: .atomicWrite)
}
func openFilePickerForCreate(path: String, result: @escaping FlutterResult) {
if (_filePickerResult != nil) {
result(FlutterError(code: "DuplicatedCall", message: "Only one file open call at a time.", details: nil))
return
}
_filePickerResult = result
_filePickerPath = path
let ctrl = UIDocumentPickerViewController(documentTypes: [kUTTypeFolder as String], in: UIDocumentPickerMode.open)
ctrl.delegate = self
ctrl.modalPresentationStyle = .currentContext
_viewController.present(ctrl, animated: true, completion: nil)
}
func openFilePicker(result: @escaping FlutterResult) {
if (_filePickerResult != nil) {
result(FlutterError(code: "DuplicatedCall", message: "Only one file open call at a time.", details: nil))
return
}
_filePickerResult = result
let ctrl = UIDocumentPickerViewController(documentTypes: [kUTTypeItem as String], in: UIDocumentPickerMode.open)
ctrl.delegate = self
ctrl.modalPresentationStyle = .currentContext
_viewController.present(ctrl, animated: true, completion: nil)
}
private func _copyToTempDirectory(url: URL) throws -> URL {
let tempDir = NSURL.fileURL(withPath: NSTemporaryDirectory(), isDirectory: true)
let tempFile = tempDir.appendingPathComponent("\(UUID().uuidString)_\(url.lastPathComponent)")
// Copy the file.
do {
try FileManager.default.copyItem(at: url, to: tempFile)
return tempFile
} catch let error {
NSLog("Unable to copy file: \(error)")
throw error
}
}
private func _prepareUrlForReading(url: URL, persistable: Bool) throws -> [String: String] {
let securityScope = url.startAccessingSecurityScopedResource()
defer {
if securityScope {
url.stopAccessingSecurityScopedResource()
}
}
if !securityScope {
logDebug("Warning: startAccessingSecurityScopedResource is false for \(url)")
}
let bookmark = try url.bookmarkData()
let tempFile = try _copyToTempDirectory(url: url)
return _fileInfoResult(tempFile: tempFile, originalURL: url, bookmark: bookmark, persistable: persistable)
}
private func _fileInfoResult(tempFile: URL, originalURL: URL, bookmark: Data, persistable: Bool = true) -> [String: String] {
let identifier = bookmark.base64EncodedString()
return [
"path": tempFile.path,
"identifier": identifier,
"persistable": "\(persistable)",
"uri": originalURL.absoluteString,
"fileName": originalURL.lastPathComponent,
]
}
private func _sendFilePickerResult(_ result: Any?) {
if let _result = _filePickerResult {
_result(result)
}
_filePickerResult = nil
}
}
extension SwiftFilePickerWritablePlugin : UIDocumentPickerDelegate {
public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
do {
if let path = _filePickerPath {
guard url.startAccessingSecurityScopedResource() else {
throw FilePickerError.readError(message: "Unnable to acquire acces to \(url)")
}
logDebug("Need to write \(path) to \(url)")
let sourceFile = URL(fileURLWithPath: path)
let targetFile = url.appendingPathComponent(sourceFile.lastPathComponent)
// if !targetFile.startAccessingSecurityScopedResource() {
// logDebug("Warning: Unnable to acquire acces to \(targetFile)")
// }
// defer {
// targetFile.stopAccessingSecurityScopedResource()
// }
try _writeFile(path: path, destination: targetFile, skipDestinationStartAccess: true)
let bookmark = try targetFile.bookmarkData()
let tempFile = try _copyToTempDirectory(url: targetFile)
_sendFilePickerResult(_fileInfoResult(tempFile: tempFile, originalURL: targetFile, bookmark: bookmark))
return
}
_sendFilePickerResult(try _prepareUrlForReading(url: url, persistable: true))
} catch {
_sendFilePickerResult(FlutterError(code: "ErrorProcessingResult", message: "Error handling result url \(url): \(error)", details: nil))
return
}
}
public func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
_sendFilePickerResult(nil)
}
}
// application delegate methods..
extension SwiftFilePickerWritablePlugin: FlutterApplicationLifeCycleDelegate {
public func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
logDebug("Opening URL \(url) - options: \(options)")
let persistable: Bool
if #available(iOS 9.0, *) {
// Will be true for files received by "Open in", false for "Copy to"
persistable = options[.openInPlace] as? Bool ?? false
} else {
// Prior to iOS 9.0 files must not be openable in-place?
persistable = false
}
return _handle(url: url, persistable: persistable)
}
public func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
logDebug("handleOpen for \(url)")
// This is an old API predating open-in-place support(?)
return _handle(url: url, persistable: false)
}
public func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]) -> Void) -> Bool {
// (handle universal links)
// Get URL components from the incoming user activity
guard userActivity.activityType == NSUserActivityTypeBrowsingWeb,
let incomingURL = userActivity.webpageURL else {
logDebug("Unsupported user activity. \(userActivity)")
return false
}
logDebug("continue userActivity webpageURL: \(incomingURL)")
// TODO: Confirm that persistable should be true here
return _handle(url: incomingURL, persistable: true)
}
private func _handle(url: URL, persistable: Bool) -> Bool {
// if (!url.isFileURL) {
// logDebug("url \(url) is not a file url. ignoring it for now.")
// return false
// }
if (!isInitialized) {
_initOpen = (url, persistable)
return true
}
_handleUrl(url: url, persistable: persistable)
return true
}
private func _handleUrl(url: URL, persistable: Bool) {
do {
if (url.isFileURL) {
_channel.invokeMethod("openFile", arguments: try _prepareUrlForReading(url: url, persistable: persistable)) { result in
guard !persistable else {
// Persistable files don't need cleanup
return
}
if self._isInboxFile(url) {
do {
try FileManager.default.removeItem(at: url)
} catch let error {
self.logError("Failed to delete inbox file \(url); error: \(error)")
}
} else {
self.logError("Unexpected non-persistable file \(url)")
}
}
} else {
_channel.invokeMethod("handleUri", arguments: url.absoluteString)
}
} catch let error {
logError("Error handling open url for \(url): \(error)")
}
}
private func _isInboxFile(_ url: URL) -> Bool {
let inboxes = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).map {
$0.resolvingSymlinksInPath().appendingPathComponent("Inbox").absoluteString
}
let resolvedUrl = url.resolvingSymlinksInPath().absoluteString
return inboxes.contains { resolvedUrl.starts(with: $0) }
}
}
extension SwiftFilePickerWritablePlugin: FlutterStreamHandler {
public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
_eventSink = events
let queue = _eventQueue
_eventQueue = []
for item in queue {
events(item)
}
return nil
}
public func onCancel(withArguments arguments: Any?) -> FlutterError? {
_eventSink = nil
return nil
}
private func sendEvent(event: [String: String]) {
if let _eventSink = _eventSink {
_eventSink(event)
} else {
_eventQueue.append(event)
}
}
}