FileProviderExtension.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. //
  2. // FileProviderExtension.swift
  3. // Files
  4. //
  5. // Created by Marino Faggiana on 26/03/18.
  6. // Copyright © 2018 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  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. import NCCommunication
  25. import Alamofire
  26. /* -----------------------------------------------------------------------------------------------------------------------------------------------
  27. STRUCT item
  28. -----------------------------------------------------------------------------------------------------------------------------------------------
  29. itemIdentifier = NSFileProviderItemIdentifier.rootContainer.rawValue --> root
  30. parentItemIdentifier = NSFileProviderItemIdentifier.rootContainer.rawValue --> root
  31. itemIdentifier = metadata.ocId (ex. 00ABC1) --> func getItemIdentifier(metadata: tableMetadata) -> NSFileProviderItemIdentifier
  32. parentItemIdentifier = NSFileProviderItemIdentifier.rootContainer.rawValue --> func getParentItemIdentifier(metadata: tableMetadata) -> NSFileProviderItemIdentifier?
  33. itemIdentifier = metadata.ocId (ex. 00CCC) --> func getItemIdentifier(metadata: tableMetadata) -> NSFileProviderItemIdentifier
  34. parentItemIdentifier = parent itemIdentifier (00ABC1) --> func getParentItemIdentifier(metadata: tableMetadata) -> NSFileProviderItemIdentifier?
  35. itemIdentifier = metadata.ocId (ex. 000DD) --> func getItemIdentifier(metadata: tableMetadata) -> NSFileProviderItemIdentifier
  36. parentItemIdentifier = parent itemIdentifier (00CCC) --> func getParentItemIdentifier(metadata: tableMetadata) -> NSFileProviderItemIdentifier?
  37. -------------------------------------------------------------------------------------------------------------------------------------------- */
  38. class FileProviderExtension: NSFileProviderExtension, NCNetworkingDelegate {
  39. var outstandingSessionTasks: [URL: URLSessionTask] = [:]
  40. var outstandingOcIdTemp: [String: String] = [:]
  41. override init() {
  42. super.init()
  43. // Create directory File Provider Storage
  44. CCUtility.getDirectoryProviderStorage()
  45. // Configure URLSession
  46. _ = NCNetworking.shared.sessionManagerBackgroundExtension
  47. }
  48. deinit {
  49. print("")
  50. }
  51. // MARK: - Enumeration
  52. override func enumerator(for containerItemIdentifier: NSFileProviderItemIdentifier) throws -> NSFileProviderEnumerator {
  53. var maybeEnumerator: NSFileProviderEnumerator? = nil
  54. if (containerItemIdentifier != NSFileProviderItemIdentifier.workingSet) {
  55. if fileProviderData.shared.setupAccount(domain: domain, providerExtension: self) == nil {
  56. throw NSError(domain: NSFileProviderErrorDomain, code: NSFileProviderError.notAuthenticated.rawValue, userInfo:[:])
  57. }
  58. }
  59. if (containerItemIdentifier == NSFileProviderItemIdentifier.rootContainer) {
  60. maybeEnumerator = FileProviderEnumerator(enumeratedItemIdentifier: containerItemIdentifier)
  61. } else if (containerItemIdentifier == NSFileProviderItemIdentifier.workingSet) {
  62. maybeEnumerator = FileProviderEnumerator(enumeratedItemIdentifier: containerItemIdentifier)
  63. } else {
  64. // determine if the item is a directory or a file
  65. // - for a directory, instantiate an enumerator of its subitems
  66. // - for a file, instantiate an enumerator that observes changes to the file
  67. let item = try self.item(for: containerItemIdentifier)
  68. if item.typeIdentifier == kUTTypeFolder as String {
  69. maybeEnumerator = FileProviderEnumerator(enumeratedItemIdentifier: containerItemIdentifier)
  70. } else {
  71. maybeEnumerator = FileProviderEnumerator(enumeratedItemIdentifier: containerItemIdentifier)
  72. }
  73. }
  74. guard let enumerator = maybeEnumerator else {
  75. throw NSError(domain: NSCocoaErrorDomain, code: NSFeatureUnsupportedError, userInfo:[:])
  76. }
  77. return enumerator
  78. }
  79. // MARK: - Item
  80. override func item(for identifier: NSFileProviderItemIdentifier) throws -> NSFileProviderItem {
  81. if identifier == .rootContainer {
  82. let metadata = tableMetadata()
  83. metadata.account = fileProviderData.shared.account
  84. metadata.directory = true
  85. metadata.ocId = NSFileProviderItemIdentifier.rootContainer.rawValue
  86. metadata.fileName = "root"
  87. metadata.fileNameView = "root"
  88. metadata.serverUrl = fileProviderData.shared.homeServerUrl
  89. metadata.typeFile = NCBrandGlobal.shared.metadataTypeFileDirectory
  90. return FileProviderItem(metadata: metadata, parentItemIdentifier: NSFileProviderItemIdentifier(NSFileProviderItemIdentifier.rootContainer.rawValue))
  91. } else {
  92. guard let metadata = fileProviderUtility.shared.getTableMetadataFromItemIdentifier(identifier) else {
  93. throw NSFileProviderError(.noSuchItem)
  94. }
  95. guard let parentItemIdentifier = fileProviderUtility.shared.getParentItemIdentifier(metadata: metadata) else {
  96. throw NSFileProviderError(.noSuchItem)
  97. }
  98. let item = FileProviderItem(metadata: metadata, parentItemIdentifier: parentItemIdentifier)
  99. return item
  100. }
  101. }
  102. override func urlForItem(withPersistentIdentifier identifier: NSFileProviderItemIdentifier) -> URL? {
  103. // resolve the given identifier to a file on disk
  104. guard let item = try? item(for: identifier) else {
  105. return nil
  106. }
  107. var url = fileProviderData.shared.fileProviderManager.documentStorageURL.appendingPathComponent(identifier.rawValue, isDirectory: true)
  108. if item.typeIdentifier == (kUTTypeFolder as String) {
  109. url = url.appendingPathComponent(item.filename, isDirectory:true)
  110. } else {
  111. url = url.appendingPathComponent(item.filename, isDirectory:false)
  112. }
  113. return url
  114. }
  115. override func persistentIdentifierForItem(at url: URL) -> NSFileProviderItemIdentifier? {
  116. // resolve the given URL to a persistent identifier using a database
  117. let pathComponents = url.pathComponents
  118. // exploit the fact that the path structure has been defined as
  119. // <base storage directory>/<item identifier>/<item file name> above
  120. assert(pathComponents.count > 2)
  121. let itemIdentifier = NSFileProviderItemIdentifier(pathComponents[pathComponents.count - 2])
  122. return itemIdentifier
  123. }
  124. override func providePlaceholder(at url: URL, completionHandler: @escaping (Error?) -> Void) {
  125. guard let identifier = persistentIdentifierForItem(at: url) else {
  126. completionHandler(NSFileProviderError(.noSuchItem))
  127. return
  128. }
  129. do {
  130. let fileProviderItem = try item(for: identifier)
  131. let placeholderURL = NSFileProviderManager.placeholderURL(for: url)
  132. try NSFileProviderManager.writePlaceholder(at: placeholderURL,withMetadata: fileProviderItem)
  133. completionHandler(nil)
  134. } catch {
  135. completionHandler(error)
  136. }
  137. }
  138. override func startProvidingItem(at url: URL, completionHandler: @escaping ((_ error: Error?) -> Void)) {
  139. let pathComponents = url.pathComponents
  140. let identifier = NSFileProviderItemIdentifier(pathComponents[pathComponents.count - 2])
  141. if let _ = outstandingSessionTasks[url] {
  142. completionHandler(nil)
  143. return
  144. }
  145. guard let metadata = fileProviderUtility.shared.getTableMetadataFromItemIdentifier(identifier) else {
  146. completionHandler(NSFileProviderError(.noSuchItem))
  147. return
  148. }
  149. let tableLocalFile = NCManageDatabase.shared.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  150. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) && tableLocalFile?.etag == metadata.etag {
  151. completionHandler(nil)
  152. return
  153. }
  154. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  155. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileName)!
  156. // Update status
  157. NCManageDatabase.shared.setMetadataStatus(ocId: metadata.ocId, status: NCBrandGlobal.shared.metadataStatusDownloading)
  158. fileProviderData.shared.signalEnumerator(ocId: metadata.ocId, update: true)
  159. NCCommunication.shared.download(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, requestHandler: { (request) in
  160. }, taskHandler: { (task) in
  161. self.outstandingSessionTasks[url] = task
  162. fileProviderData.shared.fileProviderManager.register(task, forItemWithIdentifier: NSFileProviderItemIdentifier(identifier.rawValue)) { (error) in }
  163. }, progressHandler: { (_) in
  164. }) { (account, etag, date, length, allHeaderFields, error, errorCode, errorDescription) in
  165. self.outstandingSessionTasks.removeValue(forKey: url)
  166. guard var metadata = fileProviderUtility.shared.getTableMetadataFromItemIdentifier(identifier) else {
  167. completionHandler(NSFileProviderError(.noSuchItem))
  168. return
  169. }
  170. metadata = tableMetadata.init(value: metadata)
  171. if errorCode == 0 {
  172. metadata.status = NCBrandGlobal.shared.metadataStatusNormal
  173. metadata.date = date ?? NSDate()
  174. metadata.etag = etag ?? ""
  175. NCManageDatabase.shared.addLocalFile(metadata: metadata)
  176. NCManageDatabase.shared.addMetadata(metadata)
  177. completionHandler(nil)
  178. } else if errorCode == 200 {
  179. NCManageDatabase.shared.setMetadataStatus(ocId: metadata.ocId, status: NCBrandGlobal.shared.metadataStatusNormal)
  180. completionHandler(nil)
  181. } else {
  182. metadata.status = NCBrandGlobal.shared.metadataStatusDownloadError
  183. metadata.sessionError = errorDescription
  184. NCManageDatabase.shared.addMetadata(metadata)
  185. completionHandler(NSFileProviderError(.noSuchItem))
  186. }
  187. fileProviderData.shared.signalEnumerator(ocId: metadata.ocId, update: true)
  188. }
  189. }
  190. override func itemChanged(at url: URL) {
  191. let pathComponents = url.pathComponents
  192. assert(pathComponents.count > 2)
  193. let itemIdentifier = NSFileProviderItemIdentifier(pathComponents[pathComponents.count - 2])
  194. let fileName = pathComponents[pathComponents.count - 1]
  195. var ocId = itemIdentifier.rawValue
  196. // Temp ocId ?
  197. if outstandingOcIdTemp[ocId] != nil && outstandingOcIdTemp[ocId] != ocId {
  198. ocId = outstandingOcIdTemp[ocId]!
  199. let atPath = CCUtility.getDirectoryProviderStorageOcId(itemIdentifier.rawValue, fileNameView: fileName)
  200. let toPath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName)
  201. CCUtility.copyFile(atPath: atPath, toPath: toPath)
  202. }
  203. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) else { return }
  204. let serverUrlFileName = metadata.serverUrl + "/" + fileName
  205. let fileNameLocalPath = url.path
  206. if let task = NCCommunicationBackground.shared.upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, dateCreationFile: nil, dateModificationFile: nil, description: metadata.ocId, session: NCNetworking.shared.sessionManagerBackgroundExtension) {
  207. fileProviderData.shared.fileProviderManager.register(task, forItemWithIdentifier: NSFileProviderItemIdentifier(metadata.fileId)) { (error) in }
  208. }
  209. }
  210. override func stopProvidingItem(at url: URL) {
  211. let fileHasLocalChanges = false
  212. if !fileHasLocalChanges {
  213. // remove the existing file to free up space
  214. do {
  215. _ = try fileProviderUtility.shared.fileManager.removeItem(at: url)
  216. } catch let error {
  217. print("error: \(error)")
  218. }
  219. // write out a placeholder to facilitate future property lookups
  220. self.providePlaceholder(at: url, completionHandler: { error in
  221. // handle any error, do any necessary cleanup
  222. })
  223. }
  224. // Download task
  225. if let downloadTask = outstandingSessionTasks[url] {
  226. downloadTask.cancel()
  227. outstandingSessionTasks.removeValue(forKey: url)
  228. }
  229. }
  230. override func importDocument(at fileURL: URL, toParentItemIdentifier parentItemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
  231. DispatchQueue.main.async {
  232. autoreleasepool {
  233. var size = 0 as Int64
  234. var error: NSError?
  235. guard let tableDirectory = fileProviderUtility.shared.getTableDirectoryFromParentItemIdentifier(parentItemIdentifier, account: fileProviderData.shared.account, homeServerUrl: fileProviderData.shared.homeServerUrl) else {
  236. completionHandler(nil, NSFileProviderError(.noSuchItem))
  237. return
  238. }
  239. _ = fileURL.startAccessingSecurityScopedResource()
  240. // typefile directory ? (NOT PERMITTED)
  241. do {
  242. let attributes = try fileProviderUtility.shared.fileManager.attributesOfItem(atPath: fileURL.path)
  243. size = attributes[FileAttributeKey.size] as! Int64
  244. let typeFile = attributes[FileAttributeKey.type] as! FileAttributeType
  245. if typeFile == FileAttributeType.typeDirectory {
  246. completionHandler(nil, NSFileProviderError(.noSuchItem))
  247. return
  248. }
  249. } catch {
  250. completionHandler(nil, NSFileProviderError(.noSuchItem))
  251. return
  252. }
  253. let fileName = NCUtilityFileSystem.shared.createFileName(fileURL.lastPathComponent, serverUrl: tableDirectory.serverUrl, account: fileProviderData.shared.account)
  254. let ocIdTemp = NSUUID().uuidString.lowercased()
  255. NSFileCoordinator().coordinate(readingItemAt: fileURL, options: .withoutChanges, error: &error) { (url) in
  256. _ = fileProviderUtility.shared.copyFile(url.path, toPath: CCUtility.getDirectoryProviderStorageOcId(ocIdTemp, fileNameView: fileName))
  257. }
  258. fileURL.stopAccessingSecurityScopedResource()
  259. let metadata = NCManageDatabase.shared.createMetadata(account: fileProviderData.shared.account, fileName: fileName, ocId: ocIdTemp, serverUrl: tableDirectory.serverUrl, urlBase: fileProviderData.shared.accountUrlBase, url: "", contentType: "", livePhoto: false)
  260. metadata.session = NCNetworking.shared.sessionIdentifierBackgroundExtension
  261. metadata.size = size
  262. metadata.status = NCBrandGlobal.shared.metadataStatusUploading
  263. NCManageDatabase.shared.addMetadata(metadata)
  264. let serverUrlFileName = tableDirectory.serverUrl + "/" + fileName
  265. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(ocIdTemp, fileNameView: fileName)!
  266. if let task = NCCommunicationBackground.shared.upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, dateCreationFile: nil, dateModificationFile: nil, description: ocIdTemp, session: NCNetworking.shared.sessionManagerBackgroundExtension) {
  267. self.outstandingSessionTasks[URL(fileURLWithPath: fileNameLocalPath)] = task as URLSessionTask
  268. fileProviderData.shared.fileProviderManager.register(task, forItemWithIdentifier: NSFileProviderItemIdentifier(ocIdTemp)) { (error) in }
  269. }
  270. let item = FileProviderItem(metadata: tableMetadata.init(value: metadata), parentItemIdentifier: parentItemIdentifier)
  271. completionHandler(item, nil)
  272. }
  273. }
  274. }
  275. func uploadComplete(fileName: String, serverUrl: String, ocId: String?, etag: String?, date: NSDate?, size: Int64, description: String?, task: URLSessionTask, errorCode: Int, errorDescription: String) {
  276. guard let ocIdTemp = description else { return }
  277. guard let metadataTemp = NCManageDatabase.shared.getMetadataFromOcId(ocIdTemp) else { return }
  278. let metadata = tableMetadata.init(value: metadataTemp)
  279. let url = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(ocIdTemp, fileNameView: fileName))
  280. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  281. self.outstandingSessionTasks.removeValue(forKey: url)
  282. }
  283. outstandingOcIdTemp[ocIdTemp] = ocId
  284. if errorCode == 0 {
  285. // New file
  286. if ocId != ocIdTemp {
  287. // Signal update
  288. fileProviderData.shared.signalEnumerator(ocId: metadata.ocId, delete: true)
  289. }
  290. metadata.fileName = fileName
  291. metadata.serverUrl = serverUrl
  292. if let etag = etag { metadata.etag = etag }
  293. if let ocId = ocId { metadata.ocId = ocId }
  294. if let date = date { metadata.date = date }
  295. metadata.permissions = "RGDNVW"
  296. metadata.session = ""
  297. metadata.size = size
  298. metadata.status = NCBrandGlobal.shared.metadataStatusNormal
  299. NCManageDatabase.shared.addMetadata(metadata)
  300. NCManageDatabase.shared.addLocalFile(metadata: metadata)
  301. // New file
  302. if ocId != ocIdTemp {
  303. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocIdTemp))
  304. // File system
  305. let atPath = CCUtility.getDirectoryProviderStorageOcId(ocIdTemp)
  306. let toPath = CCUtility.getDirectoryProviderStorageOcId(ocId)
  307. CCUtility.copyFile(atPath: atPath, toPath: toPath)
  308. }
  309. fileProviderData.shared.signalEnumerator(ocId: metadata.ocId, update: true)
  310. } else {
  311. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocIdTemp))
  312. fileProviderData.shared.signalEnumerator(ocId: ocIdTemp, delete: true)
  313. }
  314. }
  315. }