FileProvider.swift 29 KB

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