FileProviderExtension.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. //
  2. // FileProviderExtension.swift
  3. // Files
  4. //
  5. // Created by Marino Faggiana on 26/03/18.
  6. // Copyright © 2018 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import FileProvider
  24. /* -----------------------------------------------------------------------------------------------------------------------------------------------
  25. STRUCT item
  26. -----------------------------------------------------------------------------------------------------------------------------------------------
  27. itemIdentifier = NSFileProviderItemIdentifier.rootContainer.rawValue --> root
  28. parentItemIdentifier = NSFileProviderItemIdentifier.rootContainer.rawValue --> root
  29. itemIdentifier = metadata.fileID (ex. 00ABC1) --> func getItemIdentifier(metadata: tableMetadata) -> NSFileProviderItemIdentifier
  30. parentItemIdentifier = NSFileProviderItemIdentifier.rootContainer.rawValue --> func getParentItemIdentifier(metadata: tableMetadata) -> NSFileProviderItemIdentifier?
  31. itemIdentifier = metadata.fileID (ex. 00CCC) --> func getItemIdentifier(metadata: tableMetadata) -> NSFileProviderItemIdentifier
  32. parentItemIdentifier = parent itemIdentifier (00ABC1) --> func getParentItemIdentifier(metadata: tableMetadata) -> NSFileProviderItemIdentifier?
  33. itemIdentifier = metadata.fileID (ex. 000DD) --> func getItemIdentifier(metadata: tableMetadata) -> NSFileProviderItemIdentifier
  34. parentItemIdentifier = parent itemIdentifier (00CCC) --> func getParentItemIdentifier(metadata: tableMetadata) -> NSFileProviderItemIdentifier?
  35. -------------------------------------------------------------------------------------------------------------------------------------------- */
  36. class FileProviderExtension: NSFileProviderExtension, CCNetworkingDelegate {
  37. var providerData = FileProviderData()
  38. var outstandingDownloadTasks = [URL: URLSessionTask]()
  39. lazy var fileCoordinator: NSFileCoordinator = {
  40. if #available(iOSApplicationExtension 11.0, *) {
  41. let fileCoordinator = NSFileCoordinator()
  42. fileCoordinator.purposeIdentifier = NSFileProviderManager.default.providerIdentifier
  43. return fileCoordinator
  44. } else {
  45. return NSFileCoordinator()
  46. }
  47. }()
  48. override init() {
  49. super.init()
  50. _ = providerData.setupActiveAccount()
  51. if #available(iOSApplicationExtension 11.0, *) {
  52. self.uploadFileImportDocument()
  53. } else {
  54. NSFileCoordinator().coordinate(writingItemAt: self.documentStorageURL, options: [], error: nil, byAccessor: { newURL in
  55. do {
  56. try providerData.fileManager.createDirectory(at: newURL, withIntermediateDirectories: true, attributes: nil)
  57. } catch let error {
  58. print("error: \(error)")
  59. }
  60. })
  61. }
  62. }
  63. // MARK: - Enumeration
  64. override func enumerator(for containerItemIdentifier: NSFileProviderItemIdentifier) throws -> NSFileProviderEnumerator {
  65. /* ONLY iOS 11*/
  66. guard #available(iOS 11, *) else { throw NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError, userInfo:[:]) }
  67. var maybeEnumerator: NSFileProviderEnumerator? = nil
  68. // Check account
  69. if (containerItemIdentifier != NSFileProviderItemIdentifier.workingSet) {
  70. if providerData.setupActiveAccount() == false {
  71. throw NSError(domain: NSFileProviderErrorDomain, code: NSFileProviderError.notAuthenticated.rawValue, userInfo:[:])
  72. }
  73. }
  74. if (containerItemIdentifier == NSFileProviderItemIdentifier.rootContainer) {
  75. maybeEnumerator = FileProviderEnumerator(enumeratedItemIdentifier: containerItemIdentifier, providerData: providerData)
  76. } else if (containerItemIdentifier == NSFileProviderItemIdentifier.workingSet) {
  77. maybeEnumerator = FileProviderEnumerator(enumeratedItemIdentifier: containerItemIdentifier, providerData: providerData)
  78. } else {
  79. // determine if the item is a directory or a file
  80. // - for a directory, instantiate an enumerator of its subitems
  81. // - for a file, instantiate an enumerator that observes changes to the file
  82. let item = try self.item(for: containerItemIdentifier)
  83. if item.typeIdentifier == kUTTypeFolder as String {
  84. maybeEnumerator = FileProviderEnumerator(enumeratedItemIdentifier: containerItemIdentifier, providerData: providerData)
  85. } else {
  86. maybeEnumerator = FileProviderEnumerator(enumeratedItemIdentifier: containerItemIdentifier, providerData: providerData)
  87. }
  88. }
  89. guard let enumerator = maybeEnumerator else {
  90. throw NSError(domain: NSCocoaErrorDomain, code: NSFeatureUnsupportedError, userInfo:[:])
  91. }
  92. return enumerator
  93. }
  94. // Convinent method to signal the enumeration for containers.
  95. //
  96. func signalEnumerator(for containerItemIdentifiers: [NSFileProviderItemIdentifier]) {
  97. /* ONLY iOS 11*/
  98. guard #available(iOS 11, *) else { return }
  99. providerData.currentAnchor += 1
  100. for containerItemIdentifier in containerItemIdentifiers {
  101. NSFileProviderManager.default.signalEnumerator(for: containerItemIdentifier) { error in
  102. if let error = error {
  103. print("SignalEnumerator for \(containerItemIdentifier) returned error: \(error)")
  104. }
  105. }
  106. }
  107. }
  108. // MARK: - Item
  109. override func item(for identifier: NSFileProviderItemIdentifier) throws -> NSFileProviderItem {
  110. /* ONLY iOS 11*/
  111. guard #available(iOS 11, *) else { throw NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError, userInfo:[:]) }
  112. if identifier == .rootContainer {
  113. if let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account = %@ AND serverUrl = %@", providerData.account, providerData.homeServerUrl)) {
  114. let metadata = tableMetadata()
  115. metadata.account = providerData.account
  116. metadata.directory = true
  117. metadata.directoryID = directory.directoryID
  118. metadata.fileID = NSFileProviderItemIdentifier.rootContainer.rawValue
  119. metadata.fileName = ""
  120. metadata.fileNameView = ""
  121. metadata.typeFile = k_metadataTypeFile_directory
  122. return FileProviderItem(metadata: metadata, parentItemIdentifier: NSFileProviderItemIdentifier(NSFileProviderItemIdentifier.rootContainer.rawValue), providerData: providerData)
  123. }
  124. } else {
  125. guard let metadata = providerData.getTableMetadataFromItemIdentifier(identifier) else {
  126. throw NSFileProviderError(.noSuchItem)
  127. }
  128. guard let parentItemIdentifier = providerData.getParentItemIdentifier(metadata: metadata) else {
  129. throw NSFileProviderError(.noSuchItem)
  130. }
  131. let item = FileProviderItem(metadata: metadata, parentItemIdentifier: parentItemIdentifier, providerData: providerData)
  132. return item
  133. }
  134. throw NSFileProviderError(.noSuchItem)
  135. }
  136. override func urlForItem(withPersistentIdentifier identifier: NSFileProviderItemIdentifier) -> URL? {
  137. /* ONLY iOS 11*/
  138. guard #available(iOS 11, *) else { return nil }
  139. // resolve the given identifier to a file on disk
  140. guard let item = try? item(for: identifier) else {
  141. return nil
  142. }
  143. // in this implementation, all paths are structured as <base storage directory>/<item identifier>/<item file name>
  144. let manager = NSFileProviderManager.default
  145. var url = manager.documentStorageURL.appendingPathComponent(identifier.rawValue, isDirectory: true)
  146. if item.typeIdentifier == (kUTTypeFolder as String) {
  147. url = url.appendingPathComponent(item.filename, isDirectory:true)
  148. } else {
  149. url = url.appendingPathComponent(item.filename, isDirectory:false)
  150. }
  151. return url
  152. }
  153. override func persistentIdentifierForItem(at url: URL) -> NSFileProviderItemIdentifier? {
  154. // resolve the given URL to a persistent identifier using a database
  155. let pathComponents = url.pathComponents
  156. // exploit the fact that the path structure has been defined as
  157. // <base storage directory>/<item identifier>/<item file name> above
  158. assert(pathComponents.count > 2)
  159. let itemIdentifier = NSFileProviderItemIdentifier(pathComponents[pathComponents.count - 2])
  160. return itemIdentifier
  161. }
  162. // MARK: -
  163. override func providePlaceholder(at url: URL, completionHandler: @escaping (Error?) -> Void) {
  164. if #available(iOSApplicationExtension 11.0, *) {
  165. guard let identifier = persistentIdentifierForItem(at: url) else {
  166. completionHandler(NSFileProviderError(.noSuchItem))
  167. return
  168. }
  169. do {
  170. let fileProviderItem = try item(for: identifier)
  171. let placeholderURL = NSFileProviderManager.placeholderURL(for: url)
  172. try NSFileProviderManager.writePlaceholder(at: placeholderURL,withMetadata: fileProviderItem)
  173. completionHandler(nil)
  174. } catch let error {
  175. print("error: \(error)")
  176. completionHandler(error)
  177. }
  178. } else {
  179. let fileName = url.lastPathComponent
  180. let placeholderURL = NSFileProviderExtension.placeholderURL(for: self.documentStorageURL.appendingPathComponent(fileName))
  181. let fileSize = 0
  182. let metadata = [AnyHashable(URLResourceKey.fileSizeKey): fileSize]
  183. do {
  184. try NSFileProviderExtension.writePlaceholder(at: placeholderURL, withMetadata: metadata as! [URLResourceKey : Any])
  185. } catch let error {
  186. print("error: \(error)")
  187. }
  188. completionHandler(nil)
  189. }
  190. }
  191. override func startProvidingItem(at url: URL, completionHandler: @escaping ((_ error: Error?) -> Void)) {
  192. if #available(iOSApplicationExtension 11.0, *) {
  193. let pathComponents = url.pathComponents
  194. let identifier = NSFileProviderItemIdentifier(pathComponents[pathComponents.count - 2])
  195. var fileSize = 0 as Double
  196. var localEtag = ""
  197. var localEtagFPE = ""
  198. // Check account
  199. if providerData.setupActiveAccount() == false {
  200. completionHandler(NSFileProviderError(.notAuthenticated))
  201. return
  202. }
  203. guard let metadata = providerData.getTableMetadataFromItemIdentifier(identifier) else {
  204. completionHandler(NSFileProviderError(.noSuchItem))
  205. return
  206. }
  207. // is Upload [Office 365 !!!]
  208. if metadata.sessionTaskIdentifier > 0 || metadata.fileID.contains(k_uploadSessionID) {
  209. completionHandler(nil)
  210. return
  211. }
  212. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "account = %@ AND fileID = %@", providerData.account, metadata.fileID))
  213. if tableLocalFile != nil {
  214. localEtag = tableLocalFile!.etag
  215. localEtagFPE = tableLocalFile!.etagFPE
  216. }
  217. if (localEtagFPE != "") {
  218. // Verify last version on "Local Table"
  219. if localEtag != localEtagFPE {
  220. if providerData.copyFile(providerData.directoryUser+"/"+metadata.fileID, toPath: url.path) == nil {
  221. NCManageDatabase.sharedInstance.setLocalFile(fileID: metadata.fileID, date: nil, exifDate: nil, exifLatitude: nil, exifLongitude: nil, fileName: nil, etag: nil, etagFPE: localEtag)
  222. }
  223. }
  224. do {
  225. let attributes = try providerData.fileManager.attributesOfItem(atPath: url.path)
  226. fileSize = attributes[FileAttributeKey.size] as! Double
  227. } catch let error {
  228. print("error: \(error)")
  229. }
  230. if (fileSize > 0) {
  231. completionHandler(nil)
  232. return
  233. }
  234. }
  235. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  236. completionHandler(NSFileProviderError(.noSuchItem))
  237. return
  238. }
  239. // delete prev file + ico on Directory User
  240. _ = providerData.deleteFile("\(providerData.directoryUser)/\(metadata.fileID)")
  241. _ = providerData.deleteFile("\(providerData.directoryUser)/\(metadata.fileID).ico")
  242. let ocNetworking = OCnetworking.init(delegate: nil, metadataNet: nil, withUser: providerData.accountUser, withUserID: providerData.accountUserID, withPassword: providerData.accountPassword, withUrl: providerData.accountUrl)
  243. let task = ocNetworking?.downloadFileNameServerUrl("\(serverUrl)/\(metadata.fileName)", fileNameLocalPath: "\(providerData.directoryUser)/\(metadata.fileID)", communication: CCNetworking.shared().sharedOCCommunicationExtensionDownload(), success: { (lenght, etag, date) in
  244. // remove Task
  245. self.outstandingDownloadTasks.removeValue(forKey: url)
  246. // copy download file to url
  247. _ = self.providerData.copyFile("\(self.providerData.directoryUser)/\(metadata.fileID)", toPath: url.path)
  248. // update DB Local
  249. metadata.date = date! as NSDate
  250. metadata.etag = etag!
  251. NCManageDatabase.sharedInstance.addLocalFile(metadata: metadata)
  252. NCManageDatabase.sharedInstance.setLocalFile(fileID: metadata.fileID, date: date! as NSDate, exifDate: nil, exifLatitude: nil, exifLongitude: nil, fileName: nil, etag: etag, etagFPE: etag)
  253. // Update DB Metadata
  254. _ = NCManageDatabase.sharedInstance.addMetadata(metadata)
  255. completionHandler(nil)
  256. return
  257. }, failure: { (errorMessage, errorCode) in
  258. // remove task
  259. self.outstandingDownloadTasks.removeValue(forKey: url)
  260. if errorCode == Int(CFNetworkErrors.cfurlErrorCancelled.rawValue) {
  261. completionHandler(NSFileProviderError(.noSuchItem))
  262. } else {
  263. completionHandler(NSFileProviderError(.serverUnreachable))
  264. }
  265. return
  266. })
  267. // Add and register task
  268. if task != nil {
  269. outstandingDownloadTasks[url] = task
  270. NSFileProviderManager.default.register(task!, forItemWithIdentifier: NSFileProviderItemIdentifier(identifier.rawValue)) { (error) in }
  271. }
  272. } else {
  273. guard let fileData = try? Data(contentsOf: url) else {
  274. completionHandler(nil)
  275. return
  276. }
  277. do {
  278. _ = try fileData.write(to: url, options: NSData.WritingOptions())
  279. completionHandler(nil)
  280. } catch let error {
  281. print("error: \(error)")
  282. completionHandler(error)
  283. }
  284. }
  285. }
  286. override func itemChanged(at url: URL) {
  287. if #available(iOSApplicationExtension 11.0, *) {
  288. let pathComponents = url.pathComponents
  289. assert(pathComponents.count > 2)
  290. let itemIdentifier = NSFileProviderItemIdentifier(pathComponents[pathComponents.count - 2])
  291. uploadFileItemChanged(for: itemIdentifier, url: url)
  292. } else {
  293. let fileSize = (try! providerData.fileManager.attributesOfItem(atPath: url.path)[FileAttributeKey.size] as! NSNumber).uint64Value
  294. NSLog("[LOG] Item changed at URL %@ %lu", url as NSURL, fileSize)
  295. guard let account = NCManageDatabase.sharedInstance.getAccountActive() else {
  296. self.stopProvidingItem(at: url)
  297. return
  298. }
  299. guard let fileName = CCUtility.getFileNameExt() else {
  300. self.stopProvidingItem(at: url)
  301. return
  302. }
  303. // -------> Fix : Clear FileName for twice Office 365
  304. CCUtility.setFileNameExt("")
  305. // --------------------------------------------------
  306. if (fileName != url.lastPathComponent) {
  307. self.stopProvidingItem(at: url)
  308. return
  309. }
  310. guard let serverUrl = CCUtility.getServerUrlExt() else {
  311. self.stopProvidingItem(at: url)
  312. return
  313. }
  314. guard let directoryID = NCManageDatabase.sharedInstance.getDirectoryID(serverUrl) else {
  315. self.stopProvidingItem(at: url)
  316. return
  317. }
  318. let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileName == %@ AND directoryID == %@", fileName, directoryID))
  319. if metadata != nil {
  320. // Update
  321. let uploadID = k_uploadSessionID + CCUtility.createRandomString(16)
  322. let directoryUser = CCUtility.getDirectoryActiveUser(account.user, activeUrl: account.url)
  323. let destinationDirectoryUser = "\(directoryUser!)/\(uploadID)"
  324. // copy sourceURL on directoryUser
  325. _ = providerData.copyFile(url.path, toPath: destinationDirectoryUser)
  326. // Prepare for send Metadata
  327. metadata!.sessionID = uploadID
  328. metadata!.session = k_upload_session
  329. metadata!.sessionTaskIdentifier = Int(k_taskIdentifierWaitStart)
  330. _ = NCManageDatabase.sharedInstance.updateMetadata(metadata!)
  331. } else {
  332. // New
  333. let directoryUser = CCUtility.getDirectoryActiveUser(account.user, activeUrl: account.url)
  334. let destinationDirectoryUser = "\(directoryUser!)/\(fileName)"
  335. _ = providerData.copyFile(url.path, toPath: destinationDirectoryUser)
  336. CCNetworking.shared().uploadFile(fileName, serverUrl: serverUrl, fileID: nil, assetLocalIdentifier: nil, session: k_upload_session, taskStatus: Int(k_taskStatusResume), selector: nil, selectorPost: nil, errorCode: 0, delegate: self)
  337. }
  338. self.stopProvidingItem(at: url)
  339. }
  340. }
  341. override func stopProvidingItem(at url: URL) {
  342. // Called after the last claim to the file has been released. At this point, it is safe for the file provider to remove the content file.
  343. // Care should be taken that the corresponding placeholder file stays behind after the content file has been deleted.
  344. // Called after the last claim to the file has been released. At this point, it is safe for the file provider to remove the content file.
  345. // look up whether the file has local changes
  346. let fileHasLocalChanges = false
  347. if !fileHasLocalChanges {
  348. // remove the existing file to free up space
  349. do {
  350. _ = try providerData.fileManager.removeItem(at: url)
  351. } catch let error {
  352. print("error: \(error)")
  353. }
  354. // write out a placeholder to facilitate future property lookups
  355. self.providePlaceholder(at: url, completionHandler: { error in
  356. // handle any error, do any necessary cleanup
  357. })
  358. }
  359. // Download task
  360. if let downloadTask = outstandingDownloadTasks[url] {
  361. downloadTask.cancel()
  362. outstandingDownloadTasks.removeValue(forKey: url)
  363. }
  364. }
  365. }