FileProviderExtension.swift 19 KB

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