FileProvider.swift 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  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. self.uploading = self.uploading.filter() { $0 != identifier.rawValue }
  246. if let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account = %@ AND serverUrl = %@", account, serverUrl)) {
  247. let itemDirectory = NSFileProviderItemIdentifier(directory.fileID)
  248. NSFileProviderManager.default.signalEnumerator(for: itemDirectory, completionHandler: { (error) in
  249. print("send signal")
  250. })
  251. }
  252. }, failure: { (message, errorCode) in
  253. self.uploading = self.uploading.filter() { $0 != identifier.rawValue }
  254. })
  255. }
  256. } else {
  257. let fileSize = (try! FileManager.default.attributesOfItem(atPath: url.path)[FileAttributeKey.size] as! NSNumber).uint64Value
  258. NSLog("[LOG] Item changed at URL %@ %lu", url as NSURL, fileSize)
  259. guard let account = NCManageDatabase.sharedInstance.getAccountActive() else {
  260. self.stopProvidingItem(at: url)
  261. return
  262. }
  263. guard let fileName = CCUtility.getFileNameExt() else {
  264. self.stopProvidingItem(at: url)
  265. return
  266. }
  267. // -------> Fix : Clear FileName for twice Office 365
  268. CCUtility.setFileNameExt("")
  269. // --------------------------------------------------
  270. if (fileName != url.lastPathComponent) {
  271. self.stopProvidingItem(at: url)
  272. return
  273. }
  274. guard let serverUrl = CCUtility.getServerUrlExt() else {
  275. self.stopProvidingItem(at: url)
  276. return
  277. }
  278. guard let directoryID = NCManageDatabase.sharedInstance.getDirectoryID(serverUrl) else {
  279. self.stopProvidingItem(at: url)
  280. return
  281. }
  282. let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileName == %@ AND directoryID == %@", fileName, directoryID))
  283. if metadata != nil {
  284. // Update
  285. let uploadID = k_uploadSessionID + CCUtility.createRandomString(16)
  286. let directoryUser = CCUtility.getDirectoryActiveUser(account.user, activeUrl: account.url)
  287. let destinationDirectoryUser = "\(directoryUser!)/\(uploadID)"
  288. // copy sourceURL on directoryUser
  289. do {
  290. try FileManager.default.removeItem(atPath: destinationDirectoryUser)
  291. } catch _ {
  292. print("file do not exists")
  293. }
  294. do {
  295. try FileManager.default.copyItem(atPath: url.path, toPath: destinationDirectoryUser)
  296. } catch _ {
  297. print("file do not exists")
  298. self.stopProvidingItem(at: url)
  299. return
  300. }
  301. // Prepare for send Metadata
  302. metadata!.sessionID = uploadID
  303. metadata!.session = k_upload_session
  304. metadata!.sessionTaskIdentifier = Int(k_taskIdentifierWaitStart)
  305. _ = NCManageDatabase.sharedInstance.updateMetadata(metadata!)
  306. } else {
  307. // New
  308. let directoryUser = CCUtility.getDirectoryActiveUser(account.user, activeUrl: account.url)
  309. let destinationDirectoryUser = "\(directoryUser!)/\(fileName)"
  310. do {
  311. try FileManager.default.removeItem(atPath: destinationDirectoryUser)
  312. } catch _ {
  313. print("file do not exists")
  314. }
  315. do {
  316. try FileManager.default.copyItem(atPath: url.path, toPath: destinationDirectoryUser)
  317. } catch _ {
  318. print("file do not exists")
  319. self.stopProvidingItem(at: url)
  320. return
  321. }
  322. CCNetworking.shared().uploadFile(fileName, serverUrl: serverUrl, session: k_upload_session, taskStatus: Int(k_taskStatusResume), selector: nil, selectorPost: nil, errorCode: 0, delegate: self)
  323. }
  324. self.stopProvidingItem(at: url)
  325. }
  326. }
  327. override func stopProvidingItem(at url: URL) {
  328. // 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.
  329. // Care should be taken that the corresponding placeholder file stays behind after the content file has been deleted.
  330. // 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.
  331. // TODO: look up whether the file has local changes
  332. let fileHasLocalChanges = false
  333. if !fileHasLocalChanges {
  334. // remove the existing file to free up space
  335. do {
  336. _ = try FileManager.default.removeItem(at: url)
  337. } catch {
  338. // Handle error
  339. }
  340. // write out a placeholder to facilitate future property lookups
  341. self.providePlaceholder(at: url, completionHandler: { error in
  342. // TODO: handle any error, do any necessary cleanup
  343. })
  344. }
  345. }
  346. // MARK: - Actions
  347. /* TODO: implement the actions for items here
  348. each of the actions follows the same pattern:
  349. - make a note of the change in the local model
  350. - schedule a server request as a background task to inform the server of the change
  351. - call the completion block with the modified item in its post-modification state
  352. */
  353. // MARK: - Enumeration
  354. override func enumerator(for containerItemIdentifier: NSFileProviderItemIdentifier) throws -> NSFileProviderEnumerator {
  355. let maybeEnumerator = FileProviderEnumerator(enumeratedItemIdentifier: containerItemIdentifier)
  356. return maybeEnumerator
  357. }
  358. override func fetchThumbnails(for itemIdentifiers: [NSFileProviderItemIdentifier], requestedSize size: CGSize, perThumbnailCompletionHandler: @escaping (NSFileProviderItemIdentifier, Data?, Error?) -> Void, completionHandler: @escaping (Error?) -> Void) -> Progress {
  359. /* ONLY iOS 11*/
  360. guard #available(iOS 11, *) else {
  361. return Progress(totalUnitCount:0)
  362. }
  363. let progress = Progress(totalUnitCount: Int64(itemIdentifiers.count))
  364. var counterProgress: Int64 = 0
  365. for item in itemIdentifiers {
  366. if let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, item.rawValue)) {
  367. if (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video) {
  368. let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID)
  369. let fileName = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: serverUrl, activeUrl: accountUrl)
  370. let fileNameLocal = metadata.fileID
  371. ocNetworking?.downloadThumbnail(withDimOfThumbnail: "m", fileName: fileName, fileNameLocal: fileNameLocal, success: {
  372. do {
  373. let url = URL.init(fileURLWithPath: "\(directoryUser)/\(item.rawValue).ico")
  374. let data = try Data.init(contentsOf: url)
  375. perThumbnailCompletionHandler(item, data, nil)
  376. } catch {
  377. perThumbnailCompletionHandler(item, nil, NSFileProviderError(.noSuchItem))
  378. }
  379. counterProgress += 1
  380. if (counterProgress == progress.totalUnitCount) {
  381. completionHandler(nil)
  382. }
  383. }, failure: { (message, errorCode) in
  384. perThumbnailCompletionHandler(item, nil, NSFileProviderError(.serverUnreachable))
  385. counterProgress += 1
  386. if (counterProgress == progress.totalUnitCount) {
  387. completionHandler(nil)
  388. }
  389. })
  390. } else {
  391. counterProgress += 1
  392. if (counterProgress == progress.totalUnitCount) {
  393. completionHandler(nil)
  394. }
  395. }
  396. } else {
  397. counterProgress += 1
  398. if (counterProgress == progress.totalUnitCount) {
  399. completionHandler(nil)
  400. }
  401. }
  402. }
  403. return progress
  404. }
  405. override func createDirectory(withName directoryName: String, inParentItemIdentifier parentItemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
  406. /* ONLY iOS 11*/
  407. guard #available(iOS 11, *) else {
  408. return
  409. }
  410. guard let directoryParent = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, parentItemIdentifier.rawValue)) else {
  411. completionHandler(nil, NSFileProviderError(.noSuchItem))
  412. return
  413. }
  414. ocNetworking?.createFolder(directoryName, serverUrl: directoryParent.serverUrl, account: account, success: { (fileID, date) in
  415. guard let newTableDirectory = NCManageDatabase.sharedInstance.addDirectory(encrypted: false, favorite: false, fileID: fileID, permissions: nil, serverUrl: directoryParent.serverUrl+"/"+directoryName) else {
  416. completionHandler(nil, NSFileProviderError(.noSuchItem))
  417. return
  418. }
  419. let metadata = tableMetadata()
  420. metadata.account = account
  421. metadata.directory = true
  422. metadata.directoryID = newTableDirectory.directoryID
  423. metadata.fileID = fileID!
  424. metadata.fileName = directoryName
  425. metadata.fileNameView = directoryName
  426. metadata.typeFile = k_metadataTypeFile_directory
  427. let item = FileProviderItem(metadata: metadata, serverUrl: directoryParent.serverUrl)
  428. completionHandler(item, nil)
  429. }, failure: { (message, errorCode) in
  430. completionHandler(nil, NSFileProviderError(.serverUnreachable))
  431. })
  432. }
  433. override func importDocument(at fileURL: URL, toParentItemIdentifier parentItemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
  434. /* ONLY iOS 11*/
  435. guard #available(iOS 11, *) else {
  436. return
  437. }
  438. let fileName = fileURL.lastPathComponent
  439. let fileCoordinator = NSFileCoordinator()
  440. var error: NSError?
  441. var directoryPredicate: NSPredicate
  442. if parentItemIdentifier == .rootContainer {
  443. directoryPredicate = NSPredicate(format: "account = %@ AND serverUrl = %@", account, homeServerUrl)
  444. } else {
  445. directoryPredicate = NSPredicate(format: "account = %@ AND fileID = %@", account, parentItemIdentifier.rawValue)
  446. }
  447. guard let directoryParent = NCManageDatabase.sharedInstance.getTableDirectory(predicate: directoryPredicate) else {
  448. completionHandler(nil, NSFileProviderError(.noSuchItem))
  449. return
  450. }
  451. if fileURL.startAccessingSecurityScopedResource() == false {
  452. completionHandler(nil, NSFileProviderError(.noSuchItem))
  453. return
  454. }
  455. let fileNameLocalPath = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileURL.lastPathComponent)!
  456. fileCoordinator.coordinate(readingItemAt: fileURL, options: NSFileCoordinator.ReadingOptions.withoutChanges, error: &error) { (url) in
  457. do {
  458. try FileManager.default.removeItem(atPath: fileNameLocalPath.path)
  459. } catch _ {
  460. print("file do not exists")
  461. }
  462. do {
  463. try FileManager.default.copyItem(atPath: url.path, toPath: fileNameLocalPath.path)
  464. } catch _ {
  465. print("file do not exists")
  466. }
  467. }
  468. fileURL.stopAccessingSecurityScopedResource()
  469. _ = ocNetworking?.uploadFileNameServerUrl(directoryParent.serverUrl+"/"+fileName, fileNameLocalPath: fileNameLocalPath.path, success: { (fileID, etag, date) in
  470. let metadata = tableMetadata()
  471. metadata.account = account
  472. metadata.date = date! as NSDate
  473. metadata.directory = false
  474. metadata.directoryID = directoryParent.directoryID
  475. metadata.etag = etag!
  476. metadata.fileID = fileID!
  477. metadata.fileName = fileName
  478. metadata.fileNameView = fileName
  479. do {
  480. let attributes = try FileManager.default.attributesOfItem(atPath: fileURL.path)
  481. metadata.size = attributes[FileAttributeKey.size] as! Double
  482. } catch {
  483. }
  484. CCUtility.insertTypeFileIconName(fileName, metadata: metadata)
  485. guard let metadataDB = NCManageDatabase.sharedInstance.addMetadata(metadata) else {
  486. completionHandler(nil, NSFileProviderError(.noSuchItem))
  487. return
  488. }
  489. // Copy on ItemIdentifier path
  490. let identifierPathUrl = groupURL!.appendingPathComponent("File Provider Storage").appendingPathComponent(metadata.fileID)
  491. let toPath = "\(identifierPathUrl.path)/\(metadata.fileNameView)"
  492. if !FileManager.default.fileExists(atPath: identifierPathUrl.path) {
  493. do {
  494. try FileManager.default.createDirectory(atPath: identifierPathUrl.path, withIntermediateDirectories: true, attributes: nil)
  495. } catch let error {
  496. print("error creating filepath: \(error)")
  497. }
  498. }
  499. try? FileManager.default.removeItem(atPath: toPath)
  500. try? FileManager.default.copyItem(atPath: fileNameLocalPath.path, toPath: toPath)
  501. // add item
  502. let item = FileProviderItem(metadata: metadataDB, serverUrl: directoryParent.serverUrl)
  503. completionHandler(item, nil)
  504. }, failure: { (message, errorCode) in
  505. completionHandler(nil, NSFileProviderError(.serverUnreachable))
  506. })
  507. }
  508. }