FileProvider.swift 47 KB

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