FileProvider.swift 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153
  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. NCManageDatabase.sharedInstance.setLocalFile(fileID: metadata.fileID, date: nil, exifDate: nil, exifLatitude: nil, exifLongitude: nil, fileName: itemName, etag: nil, etagFPE: nil)
  572. }
  573. completionHandler(item, nil)
  574. }, failure: { (errorMessage, errorCode) in
  575. completionHandler(nil, NSFileProviderError(.serverUnreachable))
  576. })
  577. }
  578. override func setFavoriteRank(_ favoriteRank: NSNumber?, forItemIdentifier itemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
  579. /* ONLY iOS 11*/
  580. guard #available(iOS 11, *) else {
  581. return
  582. }
  583. completionHandler(nil, nil)
  584. /*
  585. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, itemIdentifier.rawValue)) else {
  586. completionHandler(nil, NSFileProviderError(.noSuchItem))
  587. return
  588. }
  589. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  590. completionHandler(nil, NSFileProviderError(.noSuchItem))
  591. return
  592. }
  593. // Refresh Favorite Identifier Rank
  594. listFavoriteIdentifierRank = NCManageDatabase.sharedInstance.getTableMetadatasDirectoryFavoriteIdentifierRank()
  595. if favoriteRank == nil {
  596. listFavoriteIdentifierRank.removeValue(forKey: itemIdentifier.rawValue)
  597. } else {
  598. let rank = listFavoriteIdentifierRank[itemIdentifier.rawValue]
  599. if rank == nil {
  600. listFavoriteIdentifierRank[itemIdentifier.rawValue] = favoriteRank//NSNumber(value: Int64(newRank))
  601. }
  602. favorite = true
  603. }
  604. // Call the completion handler before performing any network activity or other long-running tasks. Defer these tasks to the background
  605. let item = FileProviderItem(metadata: metadata, serverUrl: serverUrl)
  606. completionHandler(item, nil)
  607. // Change Status ? Call API Nextcloud Network
  608. if (favorite == true && metadata.favorite == false) || (favorite == false && metadata.favorite == true) {
  609. DispatchQueue(label: "com.nextcloud", qos: .background, attributes: .concurrent, autoreleaseFrequency: .inherit, target: nil).async {
  610. ocNetworking?.settingFavorite(metadata.fileName, serverUrl: serverUrl, favorite: favorite, success: {
  611. // Change DB
  612. metadata.favorite = favorite
  613. _ = NCManageDatabase.sharedInstance.addMetadata(metadata)
  614. // Refresh Favorite Identifier Rank
  615. listFavoriteIdentifierRank = NCManageDatabase.sharedInstance.getTableMetadatasDirectoryFavoriteIdentifierRank()
  616. // Refresh Item
  617. self.refreshEnumerator(identifier: itemIdentifier, serverUrl: serverUrl)
  618. }, failure: { (errorMessage, errorCode) in
  619. print("errorMessage")
  620. })
  621. }
  622. }
  623. */
  624. }
  625. override func setLastUsedDate(_ lastUsedDate: Date?, forItemIdentifier itemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
  626. print("[LOG] setLastUsedDate")
  627. completionHandler(nil, nil)
  628. }
  629. override func setTagData(_ tagData: Data?, forItemIdentifier itemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
  630. /* ONLY iOS 11*/
  631. guard #available(iOS 11, *) else {
  632. return
  633. }
  634. // Add, Remove (nil)
  635. NCManageDatabase.sharedInstance.addTag(itemIdentifier.rawValue, tagIOS: tagData)
  636. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, itemIdentifier.rawValue)) else {
  637. completionHandler(nil, NSFileProviderError(.noSuchItem))
  638. return
  639. }
  640. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  641. completionHandler(nil, NSFileProviderError(.noSuchItem))
  642. return
  643. }
  644. let item = FileProviderItem(metadata: metadata, serverUrl: serverUrl)
  645. self.refreshEnumerator(identifier: itemIdentifier, serverUrl: "WorkingSet")
  646. completionHandler(item, nil)
  647. }
  648. /*
  649. override func trashItem(withIdentifier itemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
  650. print("[LOG] trashitem")
  651. completionHandler(nil, nil)
  652. }
  653. override func untrashItem(withIdentifier itemIdentifier: NSFileProviderItemIdentifier, toParentItemIdentifier parentItemIdentifier: NSFileProviderItemIdentifier?, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
  654. print("[LOG] untrashitem")
  655. completionHandler(nil, nil)
  656. }
  657. */
  658. override func importDocument(at fileURL: URL, toParentItemIdentifier parentItemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
  659. /* ONLY iOS 11*/
  660. guard #available(iOS 11, *) else {
  661. return
  662. }
  663. let fileCoordinator = NSFileCoordinator()
  664. var error: NSError?
  665. var directoryPredicate: NSPredicate
  666. var size = 0 as Double
  667. let metadata = tableMetadata()
  668. if parentItemIdentifier == .rootContainer {
  669. directoryPredicate = NSPredicate(format: "account = %@ AND serverUrl = %@", account, homeServerUrl)
  670. } else {
  671. directoryPredicate = NSPredicate(format: "account = %@ AND fileID = %@", account, parentItemIdentifier.rawValue)
  672. }
  673. guard let directoryParent = NCManageDatabase.sharedInstance.getTableDirectory(predicate: directoryPredicate) else {
  674. completionHandler(nil, NSFileProviderError(.noSuchItem))
  675. return
  676. }
  677. let serverUrl = directoryParent.serverUrl
  678. // --------------------------------------------- Copy file here with security access
  679. if fileURL.startAccessingSecurityScopedResource() == false {
  680. completionHandler(nil, NSFileProviderError(.noSuchItem))
  681. return
  682. }
  683. let fileName = createFileName(fileURL.lastPathComponent, directoryID: directoryParent.directoryID, serverUrl: serverUrl)
  684. fileCoordinator.coordinate(readingItemAt: fileURL, options: NSFileCoordinator.ReadingOptions.withoutChanges, error: &error) { (url) in
  685. _ = self.copyFile(url.path, toPath: fileProviderStorageURL!.path + "/" + fileName)
  686. _ = self.copyFile(url.path, toPath: fileProviderStorageURL!.path + "/" + fileURL.lastPathComponent)
  687. }
  688. fileURL.stopAccessingSecurityScopedResource()
  689. // ---------------------------------------------------------------------------------
  690. do {
  691. let attributes = try FileManager.default.attributesOfItem(atPath: fileProviderStorageURL!.path + "/" + fileName)
  692. size = attributes[FileAttributeKey.size] as! Double
  693. } catch let error {
  694. print("error: \(error)")
  695. }
  696. // Metadata TEMP
  697. metadata.account = account
  698. metadata.date = NSDate()
  699. metadata.directory = false
  700. metadata.directoryID = directoryParent.directoryID
  701. metadata.etag = ""
  702. metadata.fileID = FILEID_IMPORT_METADATA_TEMP
  703. metadata.size = size
  704. metadata.status = Double(k_metadataStatusHide)
  705. metadata.fileName = fileURL.lastPathComponent
  706. metadata.fileNameView = fileURL.lastPathComponent
  707. CCUtility.insertTypeFileIconName(fileName, metadata: metadata)
  708. if (size > 0) {
  709. let metadataNet = CCMetadataNet()
  710. metadataNet.account = account
  711. metadataNet.assetLocalIdentifier = k_assetLocalIdentifierFileProviderStorage + k_uploadSessionID + directoryParent.directoryID + fileName
  712. metadataNet.fileName = fileName
  713. metadataNet.path = fileProviderStorageURL!.path + "/" + fileName
  714. metadataNet.selector = selectorUploadFile
  715. metadataNet.selectorPost = ""
  716. metadataNet.serverUrl = serverUrl
  717. metadataNet.session = k_upload_session_extension
  718. metadataNet.taskStatus = Int(k_taskStatusResume)
  719. _ = NCManageDatabase.sharedInstance.addQueueUpload(metadataNet: metadataNet)
  720. self.uploadFile()
  721. } else {
  722. // OFFICE 365 LEN = 0
  723. }
  724. guard let metadataDB = NCManageDatabase.sharedInstance.addMetadata(metadata) else {
  725. completionHandler(nil, NSFileProviderError(.noSuchItem))
  726. return
  727. }
  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. NCManageDatabase.sharedInstance.deleteQueueUpload(assetLocalIdentifier: assetLocalIdentifier, selector: selector)
  736. if let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, fileID)) {
  737. if (errorCode == 0) {
  738. NCManageDatabase.sharedInstance.setLocalFile(fileID: fileID, date: nil, exifDate: nil, exifLatitude: nil, exifLongitude: nil, fileName: nil, etag: metadata.etag, etagFPE: metadata.etag)
  739. do {
  740. try FileManager.default.createDirectory(atPath: fileProviderStorageURL!.path + "/" + fileID, withIntermediateDirectories: true, attributes: nil)
  741. } catch let error {
  742. print("error: \(error)")
  743. }
  744. _ = copyFile(fileProviderStorageURL!.path + "/" + fileName, toPath: fileProviderStorageURL!.path + "/" + fileID + "/" + fileName)
  745. _ = deleteFile(fileProviderStorageURL!.path + "/" + fileName)
  746. let item = FileProviderItem(metadata: metadata, serverUrl: serverUrl)
  747. self.refreshEnumerator(identifier: item.itemIdentifier, serverUrl: serverUrl)
  748. }
  749. }
  750. uploadFile()
  751. }
  752. func uploadFile() {
  753. let queueInLock = NCManageDatabase.sharedInstance.getQueueUploadInLock()
  754. if queueInLock != nil && queueInLock!.count == 0 {
  755. let metadataNetQueue = NCManageDatabase.sharedInstance.getQueueUploadLock(selector: selectorUploadFile, withPath: true)
  756. if metadataNetQueue != nil {
  757. if self.copyFile(metadataNetQueue!.path, toPath: directoryUser + "/" + metadataNetQueue!.fileName) == nil {
  758. 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)
  759. } else {
  760. // file not present, delete record Upload Queue
  761. NCManageDatabase.sharedInstance.deleteQueueUpload(path: metadataNetQueue!.path)
  762. }
  763. }
  764. }
  765. }
  766. // --------------------------------------------------------------------------------------------
  767. // MARK: - User Function
  768. // --------------------------------------------------------------------------------------------
  769. func refreshEnumerator(identifier: NSFileProviderItemIdentifier, serverUrl: String) {
  770. /* ONLY iOS 11*/
  771. guard #available(iOS 11, *) else {
  772. return
  773. }
  774. let item = try? self.item(for: identifier)
  775. if item != nil {
  776. var found = false
  777. for updateItem in listUpdateItems {
  778. if updateItem.itemIdentifier.rawValue == identifier.rawValue {
  779. found = true
  780. }
  781. }
  782. if !found {
  783. listUpdateItems.append(item!)
  784. }
  785. }
  786. if serverUrl == homeServerUrl {
  787. NSFileProviderManager.default.signalEnumerator(for: .rootContainer, completionHandler: { (error) in
  788. print("send signal rootContainer")
  789. })
  790. } else if serverUrl == "WorkingSet" {
  791. NSFileProviderManager.default.signalEnumerator(for: .workingSet, completionHandler: { (error) in
  792. print("send signal workingSet")
  793. })
  794. } else {
  795. if let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account = %@ AND serverUrl = %@", account, serverUrl)) {
  796. let itemDirectory = NSFileProviderItemIdentifier(directory.fileID)
  797. NSFileProviderManager.default.signalEnumerator(for: itemDirectory, completionHandler: { (error) in
  798. print("send signal")
  799. })
  800. }
  801. }
  802. }
  803. func copyFile(_ atPath: String, toPath: String) -> Error? {
  804. var errorResult: Error?
  805. do {
  806. try FileManager.default.removeItem(atPath: toPath)
  807. } catch let error {
  808. print("error: \(error)")
  809. }
  810. do {
  811. try FileManager.default.copyItem(atPath: atPath, toPath: toPath)
  812. } catch let error {
  813. errorResult = error
  814. }
  815. return errorResult
  816. }
  817. func deleteFile(_ atPath: String) -> Error? {
  818. var errorResult: Error?
  819. do {
  820. try FileManager.default.removeItem(atPath: atPath)
  821. } catch let error {
  822. errorResult = error
  823. }
  824. return errorResult
  825. }
  826. func createFileName(_ fileName: String, directoryID: String, serverUrl: String) -> String {
  827. var resultFileName = fileName
  828. var exitLoop = false
  829. while exitLoop == false {
  830. if NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileNameView = %@ AND directoryID = %@", account, resultFileName, directoryID)) != nil || fileNamePathImport.contains(serverUrl+"/"+resultFileName) {
  831. var name = NSString(string: resultFileName).deletingPathExtension
  832. let ext = NSString(string: resultFileName).pathExtension
  833. let characters = Array(name)
  834. if characters.count < 2 {
  835. resultFileName = name + " " + "1" + "." + ext
  836. } else {
  837. let space = characters[characters.count-2]
  838. let numChar = characters[characters.count-1]
  839. var num = Int(String(numChar))
  840. if (space == " " && num != nil) {
  841. name = String(name.dropLast())
  842. num = num! + 1
  843. resultFileName = name + "\(num!)" + "." + ext
  844. } else {
  845. resultFileName = name + " " + "1" + "." + ext
  846. }
  847. }
  848. } else {
  849. exitLoop = true
  850. }
  851. }
  852. // add fileNamePathImport
  853. fileNamePathImport.append(serverUrl+"/"+resultFileName)
  854. return resultFileName
  855. }
  856. }
  857. // --------------------------------------------------------------------------------------------
  858. // MARK: - Setup Active Accont
  859. // --------------------------------------------------------------------------------------------
  860. func setupActiveAccount() {
  861. guard let activeAccount = NCManageDatabase.sharedInstance.getAccountActive() else {
  862. return
  863. }
  864. account = activeAccount.account
  865. accountUser = activeAccount.user
  866. accountUserID = activeAccount.userID
  867. accountPassword = activeAccount.password
  868. accountUrl = activeAccount.url
  869. homeServerUrl = CCUtility.getHomeServerUrlActiveUrl(activeAccount.url)
  870. directoryUser = CCUtility.getDirectoryActiveUser(activeAccount.user, activeUrl: activeAccount.url)
  871. ocNetworking = OCnetworking.init(delegate: nil, metadataNet: nil, withUser: accountUser, withUserID: accountUserID, withPassword: accountPassword, withUrl: accountUrl)
  872. groupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.sharedInstance.capabilitiesGroups)
  873. fileProviderStorageURL = groupURL!.appendingPathComponent(k_assetLocalIdentifierFileProviderStorage)
  874. // Create dir File Provider Storage
  875. do {
  876. try FileManager.default.createDirectory(atPath: fileProviderStorageURL!.path, withIntermediateDirectories: true, attributes: nil)
  877. } catch let error as NSError {
  878. NSLog("Unable to create directory \(error.debugDescription)")
  879. }
  880. }