FileProvider.swift 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  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. import UIKit
  25. import MobileCoreServices
  26. var ocNetworking: OCnetworking?
  27. var account = ""
  28. var accountUser = ""
  29. var accountUserID = ""
  30. var accountPassword = ""
  31. var accountUrl = ""
  32. var homeServerUrl = ""
  33. var directoryUser = ""
  34. var groupURL: URL?
  35. class FileProvider: NSFileProviderExtension {
  36. var uploading = [String]()
  37. override init() {
  38. super.init()
  39. guard let activeAccount = NCManageDatabase.sharedInstance.getAccountActive() else {
  40. return
  41. }
  42. account = activeAccount.account
  43. accountUser = activeAccount.user
  44. accountUserID = activeAccount.userID
  45. accountPassword = activeAccount.password
  46. accountUrl = activeAccount.url
  47. homeServerUrl = CCUtility.getHomeServerUrlActiveUrl(activeAccount.url)
  48. directoryUser = CCUtility.getDirectoryActiveUser(activeAccount.user, activeUrl: activeAccount.url)
  49. ocNetworking = OCnetworking.init(delegate: nil, metadataNet: nil, withUser: accountUser, withUserID: accountUserID, withPassword: accountPassword, withUrl: accountUrl)
  50. groupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.sharedInstance.capabilitiesGroups)
  51. if #available(iOSApplicationExtension 11.0, *) {
  52. // Only iOS 11
  53. } else {
  54. NSFileCoordinator().coordinate(writingItemAt: self.documentStorageURL, options: [], error: nil, byAccessor: { newURL in
  55. try? FileManager.default.createDirectory(at: newURL, withIntermediateDirectories: true, attributes: nil)
  56. })
  57. }
  58. }
  59. override func item(for identifier: NSFileProviderItemIdentifier) throws -> NSFileProviderItem {
  60. /* ONLY iOS 11*/
  61. guard #available(iOS 11, *) else {
  62. throw NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError, userInfo:[:])
  63. }
  64. if identifier == .rootContainer {
  65. if let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account = %@ AND serverUrl = %@", account, homeServerUrl)) {
  66. let metadata = tableMetadata()
  67. metadata.account = account
  68. metadata.directory = true
  69. metadata.directoryID = directory.directoryID
  70. metadata.fileID = identifier.rawValue
  71. metadata.fileName = NCBrandOptions.sharedInstance.brand
  72. metadata.fileNameView = NCBrandOptions.sharedInstance.brand
  73. metadata.typeFile = k_metadataTypeFile_directory
  74. return FileProviderItem(metadata: metadata, serverUrl: homeServerUrl)
  75. }
  76. } else {
  77. if let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, identifier.rawValue)) {
  78. if let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account = %@ AND directoryID = %@", account, metadata.directoryID)) {
  79. if (!metadata.directory) {
  80. let identifierPathUrl = groupURL!.appendingPathComponent("File Provider Storage").appendingPathComponent(metadata.fileID)
  81. let toPath = "\(identifierPathUrl.path)/\(metadata.fileNameView)"
  82. let atPath = "\(directoryUser)/\(metadata.fileID)"
  83. if !FileManager.default.fileExists(atPath: toPath) {
  84. try? FileManager.default.createDirectory(atPath: identifierPathUrl.path, withIntermediateDirectories: true, attributes: nil)
  85. if FileManager.default.fileExists(atPath: atPath) {
  86. try? FileManager.default.copyItem(atPath: atPath, toPath: toPath)
  87. } else {
  88. FileManager.default.createFile(atPath: toPath, contents: nil, attributes: nil)
  89. }
  90. }
  91. }
  92. return FileProviderItem(metadata: metadata, serverUrl: directory.serverUrl)
  93. }
  94. }
  95. }
  96. // TODO: implement the actual lookup
  97. throw NSFileProviderError(.noSuchItem)
  98. }
  99. override func urlForItem(withPersistentIdentifier identifier: NSFileProviderItemIdentifier) -> URL? {
  100. /* ONLY iOS 11*/
  101. guard #available(iOS 11, *) else {
  102. return nil
  103. }
  104. // resolve the given identifier to a file on disk
  105. guard let item = try? item(for: identifier) else {
  106. return nil
  107. }
  108. // in this implementation, all paths are structured as <base storage directory>/<item identifier>/<item file name>
  109. let manager = NSFileProviderManager.default
  110. var url = manager.documentStorageURL.appendingPathComponent(identifier.rawValue, isDirectory: true)
  111. if item.typeIdentifier == (kUTTypeFolder as String) {
  112. url = url.appendingPathComponent(item.filename, isDirectory:true)
  113. } else {
  114. url = url.appendingPathComponent(item.filename, isDirectory:false)
  115. }
  116. return url
  117. }
  118. override func persistentIdentifierForItem(at url: URL) -> NSFileProviderItemIdentifier? {
  119. // resolve the given URL to a persistent identifier using a database
  120. let pathComponents = url.pathComponents
  121. // exploit the fact that the path structure has been defined as
  122. // <base storage directory>/<item identifier>/<item file name> above
  123. assert(pathComponents.count > 2)
  124. let itemIdentifier = NSFileProviderItemIdentifier(pathComponents[pathComponents.count - 2])
  125. return itemIdentifier
  126. }
  127. override func providePlaceholder(at url: URL, completionHandler: @escaping (Error?) -> Void) {
  128. if #available(iOSApplicationExtension 11.0, *) {
  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 let error {
  139. completionHandler(error)
  140. }
  141. } else {
  142. let fileName = url.lastPathComponent
  143. let placeholderURL = NSFileProviderExtension.placeholderURL(for: self.documentStorageURL.appendingPathComponent(fileName))
  144. let fileSize = 0
  145. let metadata = [AnyHashable(URLResourceKey.fileSizeKey): fileSize]
  146. do {
  147. try NSFileProviderExtension.writePlaceholder(at: placeholderURL, withMetadata: metadata as! [URLResourceKey : Any])
  148. } catch {
  149. }
  150. completionHandler(nil)
  151. }
  152. }
  153. override func startProvidingItem(at url: URL, completionHandler: @escaping ((_ error: Error?) -> Void)) {
  154. if #available(iOSApplicationExtension 11.0, *) {
  155. var fileSize : UInt64 = 0
  156. do {
  157. let attr = try FileManager.default.attributesOfItem(atPath: url.path)
  158. fileSize = attr[FileAttributeKey.size] as! UInt64
  159. } catch {
  160. print("Error: \(error)")
  161. completionHandler(NSFileProviderError(.noSuchItem))
  162. }
  163. // Do not exists
  164. if fileSize == 0 {
  165. let pathComponents = url.pathComponents
  166. let identifier = pathComponents[pathComponents.count - 2]
  167. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, identifier)) else {
  168. completionHandler(NSFileProviderError(.noSuchItem))
  169. return
  170. }
  171. guard let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account = %@ AND directoryID = %@", account, metadata.directoryID)) else {
  172. completionHandler(NSFileProviderError(.noSuchItem))
  173. return
  174. }
  175. _ = ocNetworking?.downloadFileNameServerUrl("\(directory.serverUrl)/\(metadata.fileName)", fileNameLocalPath: "\(directoryUser)/\(metadata.fileID)", success: { (lenght) in
  176. if (lenght > 0) {
  177. // copy download file to url
  178. try? FileManager.default.removeItem(atPath: url.path)
  179. try? FileManager.default.copyItem(atPath: "\(directoryUser)/\(metadata.fileID)", toPath: url.path)
  180. // create thumbnail
  181. CCGraphics.createNewImage(from: metadata.fileID, directoryUser: directoryUser, fileNameTo: metadata.fileID, extension: (metadata.fileNameView as NSString).pathExtension, size: "m", imageForUpload: false, typeFile: metadata.typeFile, writePreview: true, optimizedFileName: CCUtility.getOptimizedPhoto())
  182. NCManageDatabase.sharedInstance.addLocalFile(metadata: metadata)
  183. if (metadata.typeFile == k_metadataTypeFile_image) {
  184. CCExifGeo.sharedInstance().setExifLocalTableEtag(metadata, directoryUser: directoryUser, activeAccount: account)
  185. }
  186. }
  187. completionHandler(nil)
  188. }, failure: { (message, errorCode) in
  189. completionHandler(NSFileProviderError(.serverUnreachable))
  190. })
  191. } else {
  192. // Exists
  193. completionHandler(nil)
  194. }
  195. } else {
  196. guard let fileData = try? Data(contentsOf: url) else {
  197. completionHandler(nil)
  198. return
  199. }
  200. do {
  201. _ = try fileData.write(to: url, options: NSData.WritingOptions())
  202. completionHandler(nil)
  203. } catch let error as NSError {
  204. print("error writing file to URL")
  205. completionHandler(error)
  206. }
  207. }
  208. }
  209. override func itemChanged(at url: URL) {
  210. if #available(iOSApplicationExtension 11.0, *) {
  211. let fileSize = (try! FileManager.default.attributesOfItem(atPath: url.path)[FileAttributeKey.size] as! NSNumber).uint64Value
  212. NSLog("[LOG] Item changed at URL %@ %lu", url as NSURL, fileSize)
  213. if (fileSize == 0) {
  214. return
  215. }
  216. let fileName = url.lastPathComponent
  217. let pathComponents = url.pathComponents
  218. assert(pathComponents.count > 2)
  219. let identifier = NSFileProviderItemIdentifier(pathComponents[pathComponents.count - 2])
  220. if (uploading.contains(identifier.rawValue) == true) {
  221. return
  222. }
  223. if let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, identifier.rawValue)) {
  224. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  225. return
  226. }
  227. uploading.append(identifier.rawValue)
  228. _ = ocNetworking?.uploadFileNameServerUrl(serverUrl+"/"+fileName, fileNameLocalPath: url.path, success: { (fileID, etag, date) in
  229. let toPath = "\(directoryUser)/\(metadata.fileID)"
  230. try? FileManager.default.removeItem(atPath: toPath)
  231. try? FileManager.default.copyItem(atPath: url.path, toPath: toPath)
  232. // create thumbnail
  233. CCGraphics.createNewImage(from: metadata.fileID, directoryUser: directoryUser, fileNameTo: metadata.fileID, extension: (metadata.fileNameView as NSString).pathExtension, size: "m", imageForUpload: false, typeFile: metadata.typeFile, writePreview: true, optimizedFileName: CCUtility.getOptimizedPhoto())
  234. metadata.date = date! as NSDate
  235. do {
  236. let attributes = try FileManager.default.attributesOfItem(atPath: url.path)
  237. metadata.size = attributes[FileAttributeKey.size] as! Double
  238. } catch {
  239. }
  240. guard let metadataDB = NCManageDatabase.sharedInstance.addMetadata(metadata) else {
  241. return
  242. }
  243. // item
  244. _ = FileProviderItem(metadata: metadataDB, serverUrl: serverUrl)
  245. //
  246. self.uploading = self.uploading.filter() { $0 != identifier.rawValue }
  247. // Refresh UI
  248. self.refreshCurrentEnumerator(serverUrl: serverUrl)
  249. }, failure: { (message, errorCode) in
  250. self.uploading = self.uploading.filter() { $0 != identifier.rawValue }
  251. })
  252. }
  253. } else {
  254. let fileSize = (try! FileManager.default.attributesOfItem(atPath: url.path)[FileAttributeKey.size] as! NSNumber).uint64Value
  255. NSLog("[LOG] Item changed at URL %@ %lu", url as NSURL, fileSize)
  256. guard let account = NCManageDatabase.sharedInstance.getAccountActive() else {
  257. self.stopProvidingItem(at: url)
  258. return
  259. }
  260. guard let fileName = CCUtility.getFileNameExt() else {
  261. self.stopProvidingItem(at: url)
  262. return
  263. }
  264. // -------> Fix : Clear FileName for twice Office 365
  265. CCUtility.setFileNameExt("")
  266. // --------------------------------------------------
  267. if (fileName != url.lastPathComponent) {
  268. self.stopProvidingItem(at: url)
  269. return
  270. }
  271. guard let serverUrl = CCUtility.getServerUrlExt() else {
  272. self.stopProvidingItem(at: url)
  273. return
  274. }
  275. guard let directoryID = NCManageDatabase.sharedInstance.getDirectoryID(serverUrl) else {
  276. self.stopProvidingItem(at: url)
  277. return
  278. }
  279. let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileName == %@ AND directoryID == %@", fileName, directoryID))
  280. if metadata != nil {
  281. // Update
  282. let uploadID = k_uploadSessionID + CCUtility.createRandomString(16)
  283. let directoryUser = CCUtility.getDirectoryActiveUser(account.user, activeUrl: account.url)
  284. let destinationDirectoryUser = "\(directoryUser!)/\(uploadID)"
  285. // copy sourceURL on directoryUser
  286. do {
  287. try FileManager.default.removeItem(atPath: destinationDirectoryUser)
  288. } catch _ {
  289. print("file do not exists")
  290. }
  291. do {
  292. try FileManager.default.copyItem(atPath: url.path, toPath: destinationDirectoryUser)
  293. } catch _ {
  294. print("file do not exists")
  295. self.stopProvidingItem(at: url)
  296. return
  297. }
  298. // Prepare for send Metadata
  299. metadata!.sessionID = uploadID
  300. metadata!.session = k_upload_session
  301. metadata!.sessionTaskIdentifier = Int(k_taskIdentifierWaitStart)
  302. _ = NCManageDatabase.sharedInstance.updateMetadata(metadata!)
  303. } else {
  304. // New
  305. let directoryUser = CCUtility.getDirectoryActiveUser(account.user, activeUrl: account.url)
  306. let destinationDirectoryUser = "\(directoryUser!)/\(fileName)"
  307. do {
  308. try FileManager.default.removeItem(atPath: destinationDirectoryUser)
  309. } catch _ {
  310. print("file do not exists")
  311. }
  312. do {
  313. try FileManager.default.copyItem(atPath: url.path, toPath: destinationDirectoryUser)
  314. } catch _ {
  315. print("file do not exists")
  316. self.stopProvidingItem(at: url)
  317. return
  318. }
  319. CCNetworking.shared().uploadFile(fileName, serverUrl: serverUrl, session: k_upload_session, taskStatus: Int(k_taskStatusResume), selector: nil, selectorPost: nil, errorCode: 0, delegate: self)
  320. }
  321. self.stopProvidingItem(at: url)
  322. }
  323. }
  324. override func stopProvidingItem(at url: URL) {
  325. // 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.
  326. // Care should be taken that the corresponding placeholder file stays behind after the content file has been deleted.
  327. // 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.
  328. // TODO: look up whether the file has local changes
  329. let fileHasLocalChanges = false
  330. if !fileHasLocalChanges {
  331. // remove the existing file to free up space
  332. do {
  333. _ = try FileManager.default.removeItem(at: url)
  334. } catch {
  335. // Handle error
  336. }
  337. // write out a placeholder to facilitate future property lookups
  338. self.providePlaceholder(at: url, completionHandler: { error in
  339. // TODO: handle any error, do any necessary cleanup
  340. })
  341. }
  342. }
  343. // MARK: - Actions
  344. /* TODO: implement the actions for items here
  345. each of the actions follows the same pattern:
  346. - make a note of the change in the local model
  347. - schedule a server request as a background task to inform the server of the change
  348. - call the completion block with the modified item in its post-modification state
  349. */
  350. // MARK: - Enumeration
  351. override func enumerator(for containerItemIdentifier: NSFileProviderItemIdentifier) throws -> NSFileProviderEnumerator {
  352. let maybeEnumerator = FileProviderEnumerator(enumeratedItemIdentifier: containerItemIdentifier)
  353. return maybeEnumerator
  354. }
  355. override func fetchThumbnails(for itemIdentifiers: [NSFileProviderItemIdentifier], requestedSize size: CGSize, perThumbnailCompletionHandler: @escaping (NSFileProviderItemIdentifier, Data?, Error?) -> Void, completionHandler: @escaping (Error?) -> Void) -> Progress {
  356. /* ONLY iOS 11*/
  357. guard #available(iOS 11, *) else {
  358. return Progress(totalUnitCount:0)
  359. }
  360. let progress = Progress(totalUnitCount: Int64(itemIdentifiers.count))
  361. var counterProgress: Int64 = 0
  362. for item in itemIdentifiers {
  363. if let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, item.rawValue)) {
  364. if (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video) {
  365. let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID)
  366. let fileName = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: serverUrl, activeUrl: accountUrl)
  367. let fileNameLocal = metadata.fileID
  368. ocNetworking?.downloadThumbnail(withDimOfThumbnail: "m", fileName: fileName, fileNameLocal: fileNameLocal, success: {
  369. do {
  370. let url = URL.init(fileURLWithPath: "\(directoryUser)/\(item.rawValue).ico")
  371. let data = try Data.init(contentsOf: url)
  372. perThumbnailCompletionHandler(item, data, nil)
  373. } catch {
  374. perThumbnailCompletionHandler(item, nil, NSFileProviderError(.noSuchItem))
  375. }
  376. counterProgress += 1
  377. if (counterProgress == progress.totalUnitCount) {
  378. completionHandler(nil)
  379. }
  380. }, failure: { (message, errorCode) in
  381. perThumbnailCompletionHandler(item, nil, NSFileProviderError(.serverUnreachable))
  382. counterProgress += 1
  383. if (counterProgress == progress.totalUnitCount) {
  384. completionHandler(nil)
  385. }
  386. })
  387. } else {
  388. counterProgress += 1
  389. if (counterProgress == progress.totalUnitCount) {
  390. completionHandler(nil)
  391. }
  392. }
  393. } else {
  394. counterProgress += 1
  395. if (counterProgress == progress.totalUnitCount) {
  396. completionHandler(nil)
  397. }
  398. }
  399. }
  400. return progress
  401. }
  402. override func createDirectory(withName directoryName: String, inParentItemIdentifier parentItemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
  403. /* ONLY iOS 11*/
  404. guard #available(iOS 11, *) else {
  405. return
  406. }
  407. var serverUrl = ""
  408. if parentItemIdentifier == .rootContainer {
  409. serverUrl = homeServerUrl
  410. } else {
  411. guard let directoryParent = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, parentItemIdentifier.rawValue)) else {
  412. completionHandler(nil, NSFileProviderError(.noSuchItem))
  413. return
  414. }
  415. serverUrl = directoryParent.serverUrl
  416. }
  417. ocNetworking?.createFolder(directoryName, serverUrl: serverUrl, account: account, success: { (fileID, date) in
  418. guard let newTableDirectory = NCManageDatabase.sharedInstance.addDirectory(encrypted: false, favorite: false, fileID: fileID, permissions: nil, serverUrl: serverUrl+"/"+directoryName) else {
  419. completionHandler(nil, NSFileProviderError(.noSuchItem))
  420. return
  421. }
  422. let metadata = tableMetadata()
  423. metadata.account = account
  424. metadata.directory = true
  425. metadata.directoryID = newTableDirectory.directoryID
  426. metadata.fileID = fileID!
  427. metadata.fileName = directoryName
  428. metadata.fileNameView = directoryName
  429. metadata.typeFile = k_metadataTypeFile_directory
  430. let item = FileProviderItem(metadata: metadata, serverUrl: serverUrl)
  431. completionHandler(item, nil)
  432. }, failure: { (message, errorCode) in
  433. completionHandler(nil, NSFileProviderError(.serverUnreachable))
  434. })
  435. }
  436. override func deleteItem(withIdentifier itemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (Error?) -> Void) {
  437. /* ONLY iOS 11*/
  438. guard #available(iOS 11, *) else {
  439. return
  440. }
  441. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, itemIdentifier.rawValue)) else {
  442. completionHandler(NSFileProviderError(.noSuchItem))
  443. return
  444. }
  445. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  446. completionHandler(NSFileProviderError(.noSuchItem))
  447. return
  448. }
  449. ocNetworking?.deleteFileOrFolder(metadata.fileName, serverUrl: serverUrl, success: {
  450. let fileNamePath = directoryUser + "/" + metadata.fileID
  451. try? FileManager.default.removeItem(atPath: fileNamePath)
  452. try? FileManager.default.removeItem(atPath: fileNamePath + ".ico")
  453. if metadata.directory {
  454. let dirForDelete = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)
  455. NCManageDatabase.sharedInstance.deleteDirectoryAndSubDirectory(serverUrl: dirForDelete!)
  456. }
  457. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  458. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID), clearDateReadDirectoryID: nil)
  459. completionHandler(nil)
  460. }, failure: { (error, errorCode) in
  461. completionHandler(NSFileProviderError(.serverUnreachable))
  462. })
  463. }
  464. override func importDocument(at fileURL: URL, toParentItemIdentifier parentItemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
  465. /* ONLY iOS 11*/
  466. guard #available(iOS 11, *) else {
  467. return
  468. }
  469. let fileName = fileURL.lastPathComponent
  470. let fileCoordinator = NSFileCoordinator()
  471. var error: NSError?
  472. var directoryPredicate: NSPredicate
  473. if parentItemIdentifier == .rootContainer {
  474. directoryPredicate = NSPredicate(format: "account = %@ AND serverUrl = %@", account, homeServerUrl)
  475. } else {
  476. directoryPredicate = NSPredicate(format: "account = %@ AND fileID = %@", account, parentItemIdentifier.rawValue)
  477. }
  478. guard let directoryParent = NCManageDatabase.sharedInstance.getTableDirectory(predicate: directoryPredicate) else {
  479. completionHandler(nil, NSFileProviderError(.noSuchItem))
  480. return
  481. }
  482. if fileURL.startAccessingSecurityScopedResource() == false {
  483. completionHandler(nil, NSFileProviderError(.noSuchItem))
  484. return
  485. }
  486. let fileNameLocalPath = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileURL.lastPathComponent)!
  487. fileCoordinator.coordinate(readingItemAt: fileURL, options: NSFileCoordinator.ReadingOptions.withoutChanges, error: &error) { (url) in
  488. do {
  489. try FileManager.default.removeItem(atPath: fileNameLocalPath.path)
  490. } catch _ {
  491. print("file do not exists")
  492. }
  493. do {
  494. try FileManager.default.copyItem(atPath: url.path, toPath: fileNameLocalPath.path)
  495. } catch _ {
  496. print("file do not exists")
  497. }
  498. }
  499. fileURL.stopAccessingSecurityScopedResource()
  500. _ = ocNetworking?.uploadFileNameServerUrl(directoryParent.serverUrl+"/"+fileName, fileNameLocalPath: fileNameLocalPath.path, success: { (fileID, etag, date) in
  501. let metadata = tableMetadata()
  502. metadata.account = account
  503. metadata.date = date! as NSDate
  504. metadata.directory = false
  505. metadata.directoryID = directoryParent.directoryID
  506. metadata.etag = etag!
  507. metadata.fileID = fileID!
  508. metadata.fileName = fileName
  509. metadata.fileNameView = fileName
  510. do {
  511. let attributes = try FileManager.default.attributesOfItem(atPath: fileURL.path)
  512. metadata.size = attributes[FileAttributeKey.size] as! Double
  513. } catch {
  514. }
  515. CCUtility.insertTypeFileIconName(fileName, metadata: metadata)
  516. guard let metadataDB = NCManageDatabase.sharedInstance.addMetadata(metadata) else {
  517. completionHandler(nil, NSFileProviderError(.noSuchItem))
  518. return
  519. }
  520. // Copy on ItemIdentifier path
  521. let identifierPathUrl = groupURL!.appendingPathComponent("File Provider Storage").appendingPathComponent(metadata.fileID)
  522. let toPath = "\(identifierPathUrl.path)/\(metadata.fileNameView)"
  523. if !FileManager.default.fileExists(atPath: identifierPathUrl.path) {
  524. do {
  525. try FileManager.default.createDirectory(atPath: identifierPathUrl.path, withIntermediateDirectories: true, attributes: nil)
  526. } catch let error {
  527. print("error creating filepath: \(error)")
  528. }
  529. }
  530. try? FileManager.default.removeItem(atPath: toPath)
  531. try? FileManager.default.copyItem(atPath: fileNameLocalPath.path, toPath: toPath)
  532. // add item
  533. let item = FileProviderItem(metadata: metadataDB, serverUrl: directoryParent.serverUrl)
  534. completionHandler(item, nil)
  535. }, failure: { (message, errorCode) in
  536. completionHandler(nil, NSFileProviderError(.serverUnreachable))
  537. })
  538. }
  539. //
  540. //
  541. //
  542. //
  543. func refreshCurrentEnumerator(serverUrl: String) {
  544. /* ONLY iOS 11*/
  545. guard #available(iOS 11, *) else {
  546. return
  547. }
  548. if serverUrl == homeServerUrl {
  549. NSFileProviderManager.default.signalEnumerator(for: .rootContainer, completionHandler: { (error) in
  550. print("send signal rootContainer")
  551. })
  552. } else {
  553. if let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account = %@ AND serverUrl = %@", account, serverUrl)) {
  554. let itemDirectory = NSFileProviderItemIdentifier(directory.fileID)
  555. NSFileProviderManager.default.signalEnumerator(for: itemDirectory, completionHandler: { (error) in
  556. print("send signal")
  557. })
  558. }
  559. }
  560. }
  561. }