FileProvider.swift 52 KB

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