FileProvider.swift 51 KB

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