FileProvider.swift 44 KB

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