FileProvider.swift 47 KB

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