FileProvider.swift 57 KB

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