FileProvider.swift 39 KB

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