FileProvider.swift 51 KB

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