FileProviderExtension.swift 20 KB

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