FileProvider.swift 50 KB

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