FileProvider.swift 42 KB

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