FileProvider.swift 35 KB

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