FileProvider.swift 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204
  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. var fileManagerExtension = FileManager()
  45. class FileProvider: NSFileProviderExtension, CCNetworkingDelegate {
  46. override init() {
  47. super.init()
  48. setupActiveAccount()
  49. verifyUploadQueueInLock()
  50. if #available(iOSApplicationExtension 11.0, *) {
  51. listFavoriteIdentifierRank = NCManageDatabase.sharedInstance.getTableMetadatasDirectoryFavoriteIdentifierRank()
  52. // Timer for upload
  53. if timerUpload == nil {
  54. timerUpload = Timer.init(timeInterval: TimeInterval(k_timerProcessAutoDownloadUpload), repeats: true, block: { (Timer) in
  55. self.uploadFile()
  56. })
  57. RunLoop.main.add(timerUpload!, forMode: .defaultRunLoopMode)
  58. }
  59. } else {
  60. NSFileCoordinator().coordinate(writingItemAt: self.documentStorageURL, options: [], error: nil, byAccessor: { newURL in
  61. do {
  62. try fileManagerExtension.createDirectory(at: newURL, withIntermediateDirectories: true, attributes: nil)
  63. } catch let error {
  64. print("error: \(error)")
  65. }
  66. })
  67. }
  68. }
  69. // MARK: - Enumeration
  70. override func enumerator(for containerItemIdentifier: NSFileProviderItemIdentifier) throws -> NSFileProviderEnumerator {
  71. /* ONLY iOS 11*/
  72. guard #available(iOS 11, *) else {
  73. throw NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError, userInfo:[:])
  74. }
  75. var maybeEnumerator: NSFileProviderEnumerator? = nil
  76. if (containerItemIdentifier == NSFileProviderItemIdentifier.rootContainer) {
  77. maybeEnumerator = FileProviderEnumerator(enumeratedItemIdentifier: containerItemIdentifier)
  78. } else if (containerItemIdentifier == NSFileProviderItemIdentifier.workingSet) {
  79. maybeEnumerator = FileProviderEnumeratorWorkingSet(enumeratedItemIdentifier: containerItemIdentifier)
  80. } else {
  81. // determine if the item is a directory or a file
  82. // - for a directory, instantiate an enumerator of its subitems
  83. // - for a file, instantiate an enumerator that observes changes to the file
  84. let item = try self.item(for: containerItemIdentifier)
  85. if item.typeIdentifier == kUTTypeFolder as String {
  86. maybeEnumerator = FileProviderEnumerator(enumeratedItemIdentifier: containerItemIdentifier)
  87. } else {
  88. maybeEnumerator = FileProviderEnumeratorFile(enumeratedItemIdentifier: containerItemIdentifier)
  89. }
  90. }
  91. guard let enumerator = maybeEnumerator else {
  92. throw NSError(domain: NSCocoaErrorDomain, code: NSFeatureUnsupportedError, userInfo:[:])
  93. }
  94. return enumerator
  95. }
  96. // MARK: - Item
  97. override func item(for identifier: NSFileProviderItemIdentifier) throws -> NSFileProviderItem {
  98. /* ONLY iOS 11*/
  99. guard #available(iOS 11, *) else {
  100. throw NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError, userInfo:[:])
  101. }
  102. if identifier == .rootContainer {
  103. if let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account = %@ AND serverUrl = %@", account, homeServerUrl)) {
  104. let metadata = tableMetadata()
  105. metadata.account = account
  106. metadata.directory = true
  107. metadata.directoryID = directory.directoryID
  108. metadata.fileID = identifier.rawValue
  109. metadata.fileName = NCBrandOptions.sharedInstance.brand
  110. metadata.fileNameView = NCBrandOptions.sharedInstance.brand
  111. metadata.typeFile = k_metadataTypeFile_directory
  112. return FileProviderItem(metadata: metadata, serverUrl: homeServerUrl)
  113. }
  114. } else {
  115. if let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, identifier.rawValue)) {
  116. if let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account = %@ AND directoryID = %@", account, metadata.directoryID)) {
  117. return FileProviderItem(metadata: metadata, serverUrl: directory.serverUrl)
  118. }
  119. }
  120. }
  121. // implement the actual lookup
  122. throw NSFileProviderError(.noSuchItem)
  123. }
  124. override func urlForItem(withPersistentIdentifier identifier: NSFileProviderItemIdentifier) -> URL? {
  125. /* ONLY iOS 11*/
  126. guard #available(iOS 11, *) else {
  127. return nil
  128. }
  129. // resolve the given identifier to a file on disk
  130. guard let item = try? item(for: identifier) else {
  131. return nil
  132. }
  133. // in this implementation, all paths are structured as <base storage directory>/<item identifier>/<item file name>
  134. let manager = NSFileProviderManager.default
  135. var url = manager.documentStorageURL.appendingPathComponent(identifier.rawValue, isDirectory: true)
  136. if item.typeIdentifier == (kUTTypeFolder as String) {
  137. url = url.appendingPathComponent(item.filename, isDirectory:true)
  138. } else {
  139. url = url.appendingPathComponent(item.filename, isDirectory:false)
  140. }
  141. return url
  142. }
  143. override func persistentIdentifierForItem(at url: URL) -> NSFileProviderItemIdentifier? {
  144. // resolve the given URL to a persistent identifier using a database
  145. let pathComponents = url.pathComponents
  146. // exploit the fact that the path structure has been defined as
  147. // <base storage directory>/<item identifier>/<item file name> above
  148. assert(pathComponents.count > 2)
  149. let itemIdentifier = NSFileProviderItemIdentifier(pathComponents[pathComponents.count - 2])
  150. return itemIdentifier
  151. }
  152. // MARK: - Managing Shared Files
  153. override func providePlaceholder(at url: URL, completionHandler: @escaping (Error?) -> Void) {
  154. if #available(iOSApplicationExtension 11.0, *) {
  155. guard let identifier = persistentIdentifierForItem(at: url) else {
  156. completionHandler(NSFileProviderError(.noSuchItem))
  157. return
  158. }
  159. do {
  160. let fileProviderItem = try item(for: identifier)
  161. let placeholderURL = NSFileProviderManager.placeholderURL(for: url)
  162. try NSFileProviderManager.writePlaceholder(at: placeholderURL,withMetadata: fileProviderItem)
  163. completionHandler(nil)
  164. } catch let error {
  165. print("error: \(error)")
  166. completionHandler(error)
  167. }
  168. } else {
  169. let fileName = url.lastPathComponent
  170. let placeholderURL = NSFileProviderExtension.placeholderURL(for: self.documentStorageURL.appendingPathComponent(fileName))
  171. let fileSize = 0
  172. let metadata = [AnyHashable(URLResourceKey.fileSizeKey): fileSize]
  173. do {
  174. try NSFileProviderExtension.writePlaceholder(at: placeholderURL, withMetadata: metadata as! [URLResourceKey : Any])
  175. } catch let error {
  176. print("error: \(error)")
  177. }
  178. completionHandler(nil)
  179. }
  180. }
  181. override func startProvidingItem(at url: URL, completionHandler: @escaping ((_ error: Error?) -> Void)) {
  182. if #available(iOSApplicationExtension 11.0, *) {
  183. let pathComponents = url.pathComponents
  184. let identifier = NSFileProviderItemIdentifier(pathComponents[pathComponents.count - 2])
  185. var fileSize = 0 as Double
  186. var localEtag = ""
  187. var localEtagFPE = ""
  188. // If identifier is a temp return
  189. if identifier.rawValue.contains(k_uploadSessionID) {
  190. completionHandler(nil)
  191. return
  192. }
  193. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, identifier.rawValue)) else {
  194. completionHandler(NSFileProviderError(.noSuchItem))
  195. return
  196. }
  197. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, identifier.rawValue))
  198. if tableLocalFile != nil {
  199. localEtag = tableLocalFile!.etag
  200. localEtagFPE = tableLocalFile!.etagFPE
  201. }
  202. if (localEtagFPE != "") {
  203. // Verify last version on "Local Table"
  204. if localEtag != localEtagFPE {
  205. if self.copyFile("\(directoryUser)/\(identifier.rawValue)", toPath: url.path) == nil {
  206. NCManageDatabase.sharedInstance.setLocalFile(fileID: identifier.rawValue, date: nil, exifDate: nil, exifLatitude: nil, exifLongitude: nil, fileName: nil, etag: nil, etagFPE: localEtag)
  207. }
  208. }
  209. do {
  210. let attributes = try fileManagerExtension.attributesOfItem(atPath: url.path)
  211. fileSize = attributes[FileAttributeKey.size] as! Double
  212. } catch let error {
  213. print("error: \(error)")
  214. }
  215. if (fileSize > 0) {
  216. completionHandler(nil)
  217. return
  218. }
  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! fileManagerExtension.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 fileManagerExtension.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 fileManagerExtension.removeItem(atPath: fileNamePath)
  459. } catch let error {
  460. print("error: \(error)")
  461. }
  462. do {
  463. try fileManagerExtension.removeItem(atPath: fileNamePath + ".ico")
  464. } catch let error {
  465. print("error: \(error)")
  466. }
  467. do {
  468. try fileManagerExtension.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. }
  517. directoryIDTo = NCManageDatabase.sharedInstance.getDirectoryID(serverUrlTo)!
  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. let fileNameFrom = metadata.fileNameView
  555. let fileNamePathFrom = serverUrl + "/" + fileNameFrom
  556. let fileNamePathTo = serverUrl + "/" + itemName
  557. ocNetworking?.moveFileOrFolder(fileNamePathFrom, fileNameTo: fileNamePathTo, success: {
  558. metadata.fileName = itemName
  559. metadata.fileNameView = itemName
  560. guard let metadata = NCManageDatabase.sharedInstance.addMetadata(metadata) else {
  561. completionHandler(nil, NSFileProviderError(.noSuchItem))
  562. return
  563. }
  564. if metadata.directory {
  565. NCManageDatabase.sharedInstance.setDirectory(serverUrl: fileNamePathFrom, serverUrlTo: fileNamePathTo, etag: nil, fileID: nil, encrypted: directoryTable.e2eEncrypted)
  566. } else {
  567. do {
  568. try fileManagerExtension.moveItem(atPath: fileProviderStorageURL!.path + "/" + metadata.fileID + "/" + fileNameFrom, toPath: fileProviderStorageURL!.path + "/" + metadata.fileID + "/" + itemName)
  569. NCManageDatabase.sharedInstance.setLocalFile(fileID: metadata.fileID, date: nil, exifDate: nil, exifLatitude: nil, exifLongitude: nil, fileName: itemName, etag: nil, etagFPE: nil)
  570. } catch { }
  571. }
  572. let item = FileProviderItem(metadata: metadata, serverUrl: serverUrl)
  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. completionHandler(item, nil)
  646. self.refreshEnumerator(identifier: itemIdentifier, serverUrl: "WorkingSet")
  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. let fileNamePathDirectory = fileProviderStorageURL!.path + "/" + FILEID_IMPORT_METADATA_TEMP + directoryParent.directoryID + fileName
  685. fileCoordinator.coordinate(readingItemAt: fileURL, options: NSFileCoordinator.ReadingOptions.withoutChanges, error: &error) { (url) in
  686. do {
  687. try FileManager.default.createDirectory(atPath: fileNamePathDirectory, withIntermediateDirectories: true, attributes: nil)
  688. } catch { }
  689. _ = self.copyFile(url.path, toPath: fileNamePathDirectory + "/" + fileName)
  690. }
  691. fileURL.stopAccessingSecurityScopedResource()
  692. // ---------------------------------------------------------------------------------
  693. do {
  694. let attributes = try fileManagerExtension.attributesOfItem(atPath: fileNamePathDirectory + "/" + 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 + directoryParent.directoryID + fileName
  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 = FILEID_IMPORT_METADATA_TEMP + directoryParent.directoryID + fileName
  715. metadataNet.fileName = fileName
  716. metadataNet.path = fileNamePathDirectory + "/" + 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. }
  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.deleteMetadata(predicate: NSPredicate(format: "fileID = %@", assetLocalIdentifier), clearDateReadDirectoryID: nil)
  736. if errorCode == 0 {
  737. NCManageDatabase.sharedInstance.deleteQueueUpload(assetLocalIdentifier: assetLocalIdentifier, selector: selector)
  738. if let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, fileID)) {
  739. // Rename directory file
  740. if fileManagerExtension.fileExists(atPath: fileProviderStorageURL!.path + "/" + assetLocalIdentifier) {
  741. _ = moveFile(fileProviderStorageURL!.path + "/" + assetLocalIdentifier, toPath: fileProviderStorageURL!.path + "/" + fileID)
  742. } else {
  743. print("aia")
  744. }
  745. NCManageDatabase.sharedInstance.setLocalFile(fileID: fileID, date: nil, exifDate: nil, exifLatitude: nil, exifLongitude: nil, fileName: nil, etag: metadata.etag, etagFPE: metadata.etag)
  746. let item = FileProviderItem(metadata: metadata, serverUrl: serverUrl)
  747. self.refreshEnumerator(identifier: item.itemIdentifier, serverUrl: serverUrl)
  748. }
  749. } else {
  750. NCManageDatabase.sharedInstance.unlockQueueUpload(assetLocalIdentifier: assetLocalIdentifier)
  751. }
  752. uploadFile()
  753. }
  754. func uploadFile() {
  755. let queueInLock = NCManageDatabase.sharedInstance.getQueueUploadInLock()
  756. if queueInLock != nil && queueInLock!.count == 0 {
  757. let metadataNetQueue = NCManageDatabase.sharedInstance.getQueueUploadLock(selector: selectorUploadFile, withPath: true)
  758. if metadataNetQueue != nil {
  759. if self.copyFile(metadataNetQueue!.path, toPath: directoryUser + "/" + metadataNetQueue!.fileName) == nil {
  760. 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)
  761. } else {
  762. // file not present, delete record Upload Queue
  763. NCManageDatabase.sharedInstance.deleteQueueUpload(path: metadataNetQueue!.path)
  764. }
  765. }
  766. }
  767. }
  768. func verifyUploadQueueInLock() {
  769. let tasks = CCNetworking.shared().getUploadTasksExtensionSession()
  770. if tasks!.count == 0 {
  771. let records = NCManageDatabase.sharedInstance.getQueueUpload(predicate: NSPredicate(format: "account = %@ AND selector = %@ AND lock == true AND path != nil", account, selectorUploadFile))
  772. if records != nil && records!.count > 0 {
  773. NCManageDatabase.sharedInstance.unlockAllQueueUploadInPath()
  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 fileManagerExtension.removeItem(atPath: toPath)
  818. } catch let error {
  819. print("error: \(error)")
  820. }
  821. do {
  822. try fileManagerExtension.copyItem(atPath: atPath, toPath: toPath)
  823. } catch let error {
  824. errorResult = error
  825. }
  826. return errorResult
  827. }
  828. func moveFile(_ atPath: String, toPath: String) -> Error? {
  829. var errorResult: Error?
  830. do {
  831. try fileManagerExtension.removeItem(atPath: toPath)
  832. } catch let error {
  833. print("error: \(error)")
  834. }
  835. do {
  836. try fileManagerExtension.moveItem(atPath: atPath, toPath: toPath)
  837. } catch let error {
  838. errorResult = error
  839. }
  840. return errorResult
  841. }
  842. func deleteFile(_ atPath: String) -> Error? {
  843. var errorResult: Error?
  844. do {
  845. try fileManagerExtension.removeItem(atPath: atPath)
  846. } catch let error {
  847. errorResult = error
  848. }
  849. return errorResult
  850. }
  851. func createFileName(_ fileName: String, directoryID: String, serverUrl: String) -> String {
  852. let serialQueue = DispatchQueue(label: "queueCreateFileName")
  853. var resultFileName = fileName
  854. serialQueue.sync {
  855. var exitLoop = false
  856. while exitLoop == false {
  857. if NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileNameView = %@ AND directoryID = %@", account, resultFileName, directoryID)) != nil || fileNamePathImport.contains(serverUrl+"/"+resultFileName) {
  858. var name = NSString(string: resultFileName).deletingPathExtension
  859. let ext = NSString(string: resultFileName).pathExtension
  860. let characters = Array(name)
  861. if characters.count < 2 {
  862. resultFileName = name + " " + "1" + "." + ext
  863. } else {
  864. let space = characters[characters.count-2]
  865. let numChar = characters[characters.count-1]
  866. var num = Int(String(numChar))
  867. if (space == " " && num != nil) {
  868. name = String(name.dropLast())
  869. num = num! + 1
  870. resultFileName = name + "\(num!)" + "." + ext
  871. } else {
  872. resultFileName = name + " " + "1" + "." + ext
  873. }
  874. }
  875. } else {
  876. exitLoop = true
  877. }
  878. }
  879. // add fileNamePathImport
  880. fileNamePathImport.append(serverUrl+"/"+resultFileName)
  881. }
  882. return resultFileName
  883. }
  884. }
  885. // --------------------------------------------------------------------------------------------
  886. // MARK: - Setup Active Accont
  887. // --------------------------------------------------------------------------------------------
  888. func setupActiveAccount() {
  889. guard let activeAccount = NCManageDatabase.sharedInstance.getAccountActive() else {
  890. return
  891. }
  892. account = activeAccount.account
  893. accountUser = activeAccount.user
  894. accountUserID = activeAccount.userID
  895. accountPassword = activeAccount.password
  896. accountUrl = activeAccount.url
  897. homeServerUrl = CCUtility.getHomeServerUrlActiveUrl(activeAccount.url)
  898. directoryUser = CCUtility.getDirectoryActiveUser(activeAccount.user, activeUrl: activeAccount.url)
  899. ocNetworking = OCnetworking.init(delegate: nil, metadataNet: nil, withUser: accountUser, withUserID: accountUserID, withPassword: accountPassword, withUrl: accountUrl)
  900. groupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.sharedInstance.capabilitiesGroups)
  901. fileProviderStorageURL = groupURL!.appendingPathComponent(k_assetLocalIdentifierFileProviderStorage)
  902. // Create dir File Provider Storage
  903. do {
  904. try FileManager.default.createDirectory(atPath: fileProviderStorageURL!.path, withIntermediateDirectories: true, attributes: nil)
  905. } catch let error as NSError {
  906. NSLog("Unable to create directory \(error.debugDescription)")
  907. }
  908. }
  909. func createFileIdentifier(itemIdentifier: String, fileName: String) {
  910. let identifierPath = fileProviderStorageURL!.path + "/" + itemIdentifier
  911. let fileIdentifier = identifierPath + "/" + fileName
  912. do {
  913. try fileManagerExtension.createDirectory(atPath: identifierPath, withIntermediateDirectories: true, attributes: nil)
  914. } catch { }
  915. // If do not exists create file with size = 0
  916. if fileManagerExtension.fileExists(atPath: fileIdentifier) == false {
  917. fileManagerExtension.createFile(atPath: fileIdentifier, contents: nil, attributes: nil)
  918. }
  919. }