FileProviderExtension.swift 21 KB

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