FileProviderExtension.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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. // MARK: - Item
  95. override func item(for identifier: NSFileProviderItemIdentifier) throws -> NSFileProviderItem {
  96. /* ONLY iOS 11*/
  97. guard #available(iOS 11, *) else { throw NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError, userInfo:[:]) }
  98. if identifier == .rootContainer {
  99. if let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account = %@ AND serverUrl = %@", providerData.account, providerData.homeServerUrl)) {
  100. let metadata = tableMetadata()
  101. metadata.account = providerData.account
  102. metadata.directory = true
  103. metadata.directoryID = directory.directoryID
  104. metadata.fileID = NSFileProviderItemIdentifier.rootContainer.rawValue
  105. metadata.fileName = ""
  106. metadata.fileNameView = ""
  107. metadata.typeFile = k_metadataTypeFile_directory
  108. return FileProviderItem(metadata: metadata, parentItemIdentifier: NSFileProviderItemIdentifier(NSFileProviderItemIdentifier.rootContainer.rawValue), providerData: providerData)
  109. }
  110. } else {
  111. guard let metadata = providerData.getTableMetadataFromItemIdentifier(identifier) else {
  112. throw NSFileProviderError(.noSuchItem)
  113. }
  114. guard let parentItemIdentifier = providerData.getParentItemIdentifier(metadata: metadata) else {
  115. throw NSFileProviderError(.noSuchItem)
  116. }
  117. let item = FileProviderItem(metadata: metadata, parentItemIdentifier: parentItemIdentifier, providerData: providerData)
  118. return item
  119. }
  120. throw NSFileProviderError(.noSuchItem)
  121. }
  122. override func urlForItem(withPersistentIdentifier identifier: NSFileProviderItemIdentifier) -> URL? {
  123. /* ONLY iOS 11*/
  124. guard #available(iOS 11, *) else { return nil }
  125. // resolve the given identifier to a file on disk
  126. guard let item = try? item(for: identifier) else {
  127. return nil
  128. }
  129. // in this implementation, all paths are structured as <base storage directory>/<item identifier>/<item file name>
  130. let manager = NSFileProviderManager.default
  131. var url = manager.documentStorageURL.appendingPathComponent(identifier.rawValue, isDirectory: true)
  132. if item.typeIdentifier == (kUTTypeFolder as String) {
  133. url = url.appendingPathComponent(item.filename, isDirectory:true)
  134. } else {
  135. url = url.appendingPathComponent(item.filename, isDirectory:false)
  136. }
  137. return url
  138. }
  139. override func persistentIdentifierForItem(at url: URL) -> NSFileProviderItemIdentifier? {
  140. // resolve the given URL to a persistent identifier using a database
  141. let pathComponents = url.pathComponents
  142. // exploit the fact that the path structure has been defined as
  143. // <base storage directory>/<item identifier>/<item file name> above
  144. assert(pathComponents.count > 2)
  145. let itemIdentifier = NSFileProviderItemIdentifier(pathComponents[pathComponents.count - 2])
  146. return itemIdentifier
  147. }
  148. // MARK: -
  149. override func providePlaceholder(at url: URL, completionHandler: @escaping (Error?) -> Void) {
  150. if #available(iOSApplicationExtension 11.0, *) {
  151. guard let identifier = persistentIdentifierForItem(at: url) else {
  152. completionHandler(NSFileProviderError(.noSuchItem))
  153. return
  154. }
  155. do {
  156. let fileProviderItem = try item(for: identifier)
  157. let placeholderURL = NSFileProviderManager.placeholderURL(for: url)
  158. try NSFileProviderManager.writePlaceholder(at: placeholderURL,withMetadata: fileProviderItem)
  159. completionHandler(nil)
  160. } catch let error {
  161. print("error: \(error)")
  162. completionHandler(error)
  163. }
  164. } else {
  165. let fileName = url.lastPathComponent
  166. let placeholderURL = NSFileProviderExtension.placeholderURL(for: self.documentStorageURL.appendingPathComponent(fileName))
  167. let fileSize = 0
  168. let metadata = [AnyHashable(URLResourceKey.fileSizeKey): fileSize]
  169. do {
  170. try NSFileProviderExtension.writePlaceholder(at: placeholderURL, withMetadata: metadata as! [URLResourceKey : Any])
  171. } catch let error {
  172. print("error: \(error)")
  173. }
  174. completionHandler(nil)
  175. }
  176. }
  177. override func startProvidingItem(at url: URL, completionHandler: @escaping ((_ error: Error?) -> Void)) {
  178. if #available(iOSApplicationExtension 11.0, *) {
  179. let pathComponents = url.pathComponents
  180. let identifier = NSFileProviderItemIdentifier(pathComponents[pathComponents.count - 2])
  181. var fileSize = 0 as Double
  182. var localEtag = ""
  183. var localEtagFPE = ""
  184. // Check account
  185. if providerData.setupActiveAccount() == false {
  186. completionHandler(NSFileProviderError(.notAuthenticated))
  187. return
  188. }
  189. guard let metadata = providerData.getTableMetadataFromItemIdentifier(identifier) else {
  190. completionHandler(NSFileProviderError(.noSuchItem))
  191. return
  192. }
  193. // is Upload [Office 365 !!!]
  194. if metadata.sessionTaskIdentifier > 0 || metadata.fileID.contains(k_uploadSessionID) {
  195. completionHandler(nil)
  196. return
  197. }
  198. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "account = %@ AND fileID = %@", providerData.account, metadata.fileID))
  199. if tableLocalFile != nil {
  200. localEtag = tableLocalFile!.etag
  201. localEtagFPE = tableLocalFile!.etagFPE
  202. }
  203. if (localEtagFPE != "") {
  204. // Verify last version on "Local Table"
  205. if localEtag != localEtagFPE {
  206. if providerData.copyFile(providerData.directoryUser+"/"+metadata.fileID, toPath: url.path) == nil {
  207. NCManageDatabase.sharedInstance.setLocalFile(fileID: metadata.fileID, date: nil, exifDate: nil, exifLatitude: nil, exifLongitude: nil, fileName: nil, etag: nil, etagFPE: localEtag)
  208. }
  209. }
  210. do {
  211. let attributes = try providerData.fileManager.attributesOfItem(atPath: url.path)
  212. fileSize = attributes[FileAttributeKey.size] as! Double
  213. } catch let error {
  214. print("error: \(error)")
  215. }
  216. if (fileSize > 0) {
  217. completionHandler(nil)
  218. return
  219. }
  220. }
  221. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  222. completionHandler(NSFileProviderError(.noSuchItem))
  223. return
  224. }
  225. // delete prev file + ico on Directory User
  226. _ = providerData.deleteFile("\(providerData.directoryUser)/\(metadata.fileID)")
  227. _ = providerData.deleteFile("\(providerData.directoryUser)/\(metadata.fileID).ico")
  228. let ocNetworking = OCnetworking.init(delegate: nil, metadataNet: nil, withUser: providerData.accountUser, withUserID: providerData.accountUserID, withPassword: providerData.accountPassword, withUrl: providerData.accountUrl)
  229. let task = ocNetworking?.downloadFileNameServerUrl("\(serverUrl)/\(metadata.fileName)", fileNameLocalPath: "\(providerData.directoryUser)/\(metadata.fileID)", communication: CCNetworking.shared().sharedOCCommunicationExtensionDownload(), success: { (lenght, etag, date) in
  230. // remove Task
  231. self.outstandingDownloadTasks.removeValue(forKey: url)
  232. // copy download file to url
  233. _ = self.providerData.copyFile("\(self.providerData.directoryUser)/\(metadata.fileID)", toPath: url.path)
  234. // update DB Local
  235. metadata.date = date! as NSDate
  236. metadata.etag = etag!
  237. NCManageDatabase.sharedInstance.addLocalFile(metadata: metadata)
  238. NCManageDatabase.sharedInstance.setLocalFile(fileID: metadata.fileID, date: date! as NSDate, exifDate: nil, exifLatitude: nil, exifLongitude: nil, fileName: nil, etag: etag, etagFPE: etag)
  239. // Update DB Metadata
  240. _ = NCManageDatabase.sharedInstance.addMetadata(metadata)
  241. completionHandler(nil)
  242. return
  243. }, failure: { (errorMessage, errorCode) in
  244. // remove task
  245. self.outstandingDownloadTasks.removeValue(forKey: url)
  246. if errorCode == Int(CFNetworkErrors.cfurlErrorCancelled.rawValue) {
  247. completionHandler(NSFileProviderError(.noSuchItem))
  248. } else {
  249. completionHandler(NSFileProviderError(.serverUnreachable))
  250. }
  251. return
  252. })
  253. // Add and register task
  254. if task != nil {
  255. outstandingDownloadTasks[url] = task
  256. NSFileProviderManager.default.register(task!, forItemWithIdentifier: NSFileProviderItemIdentifier(identifier.rawValue)) { (error) in }
  257. }
  258. } else {
  259. guard let fileData = try? Data(contentsOf: url) else {
  260. completionHandler(nil)
  261. return
  262. }
  263. do {
  264. _ = try fileData.write(to: url, options: NSData.WritingOptions())
  265. completionHandler(nil)
  266. } catch let error {
  267. print("error: \(error)")
  268. completionHandler(error)
  269. }
  270. }
  271. }
  272. override func itemChanged(at url: URL) {
  273. if #available(iOSApplicationExtension 11.0, *) {
  274. let pathComponents = url.pathComponents
  275. assert(pathComponents.count > 2)
  276. let itemIdentifier = NSFileProviderItemIdentifier(pathComponents[pathComponents.count - 2])
  277. uploadFileItemChanged(for: itemIdentifier, url: url)
  278. } else {
  279. let fileSize = (try! providerData.fileManager.attributesOfItem(atPath: url.path)[FileAttributeKey.size] as! NSNumber).uint64Value
  280. NSLog("[LOG] Item changed at URL %@ %lu", url as NSURL, fileSize)
  281. guard let account = NCManageDatabase.sharedInstance.getAccountActive() else {
  282. self.stopProvidingItem(at: url)
  283. return
  284. }
  285. guard let fileName = CCUtility.getFileNameExt() else {
  286. self.stopProvidingItem(at: url)
  287. return
  288. }
  289. // -------> Fix : Clear FileName for twice Office 365
  290. CCUtility.setFileNameExt("")
  291. // --------------------------------------------------
  292. if (fileName != url.lastPathComponent) {
  293. self.stopProvidingItem(at: url)
  294. return
  295. }
  296. guard let serverUrl = CCUtility.getServerUrlExt() else {
  297. self.stopProvidingItem(at: url)
  298. return
  299. }
  300. guard let directoryID = NCManageDatabase.sharedInstance.getDirectoryID(serverUrl) else {
  301. self.stopProvidingItem(at: url)
  302. return
  303. }
  304. let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileName == %@ AND directoryID == %@", fileName, directoryID))
  305. if metadata != nil {
  306. // Update
  307. let uploadID = k_uploadSessionID + CCUtility.createRandomString(16)
  308. let directoryUser = CCUtility.getDirectoryActiveUser(account.user, activeUrl: account.url)
  309. let destinationDirectoryUser = "\(directoryUser!)/\(uploadID)"
  310. // copy sourceURL on directoryUser
  311. _ = providerData.copyFile(url.path, toPath: destinationDirectoryUser)
  312. // Prepare for send Metadata
  313. metadata!.sessionID = uploadID
  314. metadata!.session = k_upload_session
  315. metadata!.sessionTaskIdentifier = Int(k_taskIdentifierWaitStart)
  316. _ = NCManageDatabase.sharedInstance.updateMetadata(metadata!)
  317. } else {
  318. // New
  319. let directoryUser = CCUtility.getDirectoryActiveUser(account.user, activeUrl: account.url)
  320. let destinationDirectoryUser = "\(directoryUser!)/\(fileName)"
  321. _ = providerData.copyFile(url.path, toPath: destinationDirectoryUser)
  322. 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)
  323. }
  324. self.stopProvidingItem(at: url)
  325. }
  326. }
  327. override func stopProvidingItem(at url: URL) {
  328. // 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.
  329. // Care should be taken that the corresponding placeholder file stays behind after the content file has been deleted.
  330. // 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.
  331. // look up whether the file has local changes
  332. let fileHasLocalChanges = false
  333. if !fileHasLocalChanges {
  334. // remove the existing file to free up space
  335. do {
  336. _ = try providerData.fileManager.removeItem(at: url)
  337. } catch let error {
  338. print("error: \(error)")
  339. }
  340. // write out a placeholder to facilitate future property lookups
  341. self.providePlaceholder(at: url, completionHandler: { error in
  342. // handle any error, do any necessary cleanup
  343. })
  344. }
  345. // Download task
  346. if let downloadTask = outstandingDownloadTasks[url] {
  347. downloadTask.cancel()
  348. outstandingDownloadTasks.removeValue(forKey: url)
  349. }
  350. }
  351. }