FileProviderExtension.swift 20 KB

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