FileProvider.swift 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199
  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(FILEID_IMPORT_METADATA_TEMP) {
  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. metadataNet.account = account
  272. metadataNet.assetLocalIdentifier = FILEID_IMPORT_METADATA_TEMP + metadata.directoryID + fileName
  273. metadataNet.fileName = fileName
  274. metadataNet.path = url.path
  275. metadataNet.selector = selectorUploadFile
  276. metadataNet.selectorPost = ""
  277. metadataNet.serverUrl = serverUrl
  278. metadataNet.session = k_upload_session_extension
  279. metadataNet.taskStatus = Int(k_taskStatusResume)
  280. _ = NCManageDatabase.sharedInstance.addQueueUpload(metadataNet: metadataNet)
  281. self.uploadFile()
  282. } else {
  283. let fileSize = (try! fileManagerExtension.attributesOfItem(atPath: url.path)[FileAttributeKey.size] as! NSNumber).uint64Value
  284. NSLog("[LOG] Item changed at URL %@ %lu", url as NSURL, fileSize)
  285. guard let account = NCManageDatabase.sharedInstance.getAccountActive() else {
  286. self.stopProvidingItem(at: url)
  287. return
  288. }
  289. guard let fileName = CCUtility.getFileNameExt() else {
  290. self.stopProvidingItem(at: url)
  291. return
  292. }
  293. // -------> Fix : Clear FileName for twice Office 365
  294. CCUtility.setFileNameExt("")
  295. // --------------------------------------------------
  296. if (fileName != url.lastPathComponent) {
  297. self.stopProvidingItem(at: url)
  298. return
  299. }
  300. guard let serverUrl = CCUtility.getServerUrlExt() else {
  301. self.stopProvidingItem(at: url)
  302. return
  303. }
  304. guard let directoryID = NCManageDatabase.sharedInstance.getDirectoryID(serverUrl) else {
  305. self.stopProvidingItem(at: url)
  306. return
  307. }
  308. let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileName == %@ AND directoryID == %@", fileName, directoryID))
  309. if metadata != nil {
  310. // Update
  311. let uploadID = k_uploadSessionID + CCUtility.createRandomString(16)
  312. let directoryUser = CCUtility.getDirectoryActiveUser(account.user, activeUrl: account.url)
  313. let destinationDirectoryUser = "\(directoryUser!)/\(uploadID)"
  314. // copy sourceURL on directoryUser
  315. _ = self.copyFile(url.path, toPath: destinationDirectoryUser)
  316. // Prepare for send Metadata
  317. metadata!.sessionID = uploadID
  318. metadata!.session = k_upload_session
  319. metadata!.sessionTaskIdentifier = Int(k_taskIdentifierWaitStart)
  320. _ = NCManageDatabase.sharedInstance.updateMetadata(metadata!)
  321. } else {
  322. // New
  323. let directoryUser = CCUtility.getDirectoryActiveUser(account.user, activeUrl: account.url)
  324. let destinationDirectoryUser = "\(directoryUser!)/\(fileName)"
  325. _ = self.copyFile(url.path, toPath: destinationDirectoryUser)
  326. CCNetworking.shared().uploadFile(fileName, serverUrl: serverUrl, assetLocalIdentifier: nil, session: k_upload_session, taskStatus: Int(k_taskStatusResume), selector: nil, selectorPost: nil, errorCode: 0, delegate: self)
  327. }
  328. self.stopProvidingItem(at: url)
  329. }
  330. }
  331. override func stopProvidingItem(at url: URL) {
  332. // 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.
  333. // Care should be taken that the corresponding placeholder file stays behind after the content file has been deleted.
  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. // look up whether the file has local changes
  336. let fileHasLocalChanges = false
  337. if !fileHasLocalChanges {
  338. // remove the existing file to free up space
  339. do {
  340. _ = try fileManagerExtension.removeItem(at: url)
  341. } catch let error {
  342. print("error: \(error)")
  343. }
  344. // write out a placeholder to facilitate future property lookups
  345. self.providePlaceholder(at: url, completionHandler: { error in
  346. // handle any error, do any necessary cleanup
  347. })
  348. }
  349. }
  350. // MARK: - Accessing Thumbnails
  351. override func fetchThumbnails(for itemIdentifiers: [NSFileProviderItemIdentifier], requestedSize size: CGSize, perThumbnailCompletionHandler: @escaping (NSFileProviderItemIdentifier, Data?, Error?) -> Void, completionHandler: @escaping (Error?) -> Void) -> Progress {
  352. /* ONLY iOS 11*/
  353. guard #available(iOS 11, *) else {
  354. return Progress(totalUnitCount:0)
  355. }
  356. let progress = Progress(totalUnitCount: Int64(itemIdentifiers.count))
  357. var counterProgress: Int64 = 0
  358. for itemIdentifier in itemIdentifiers {
  359. if let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, itemIdentifier.rawValue)) {
  360. if (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video) {
  361. let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID)
  362. let fileName = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: serverUrl, activeUrl: accountUrl)
  363. let fileNameLocal = metadata.fileID
  364. ocNetworking?.downloadThumbnail(withDimOfThumbnail: "m", fileName: fileName, fileNameLocal: fileNameLocal, success: {
  365. do {
  366. let url = URL.init(fileURLWithPath: "\(directoryUser)/\(itemIdentifier.rawValue).ico")
  367. let data = try Data.init(contentsOf: url)
  368. perThumbnailCompletionHandler(itemIdentifier, data, nil)
  369. } catch let error {
  370. print("error: \(error)")
  371. perThumbnailCompletionHandler(itemIdentifier, nil, NSFileProviderError(.noSuchItem))
  372. }
  373. counterProgress += 1
  374. if (counterProgress == progress.totalUnitCount) {
  375. completionHandler(nil)
  376. }
  377. }, failure: { (errorMessage, errorCode) in
  378. perThumbnailCompletionHandler(itemIdentifier, nil, NSFileProviderError(.serverUnreachable))
  379. counterProgress += 1
  380. if (counterProgress == progress.totalUnitCount) {
  381. completionHandler(nil)
  382. }
  383. })
  384. } else {
  385. counterProgress += 1
  386. if (counterProgress == progress.totalUnitCount) {
  387. completionHandler(nil)
  388. }
  389. }
  390. } else {
  391. counterProgress += 1
  392. if (counterProgress == progress.totalUnitCount) {
  393. completionHandler(nil)
  394. }
  395. }
  396. }
  397. return progress
  398. }
  399. // MARK: - Actions
  400. override func createDirectory(withName directoryName: String, inParentItemIdentifier parentItemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
  401. /* ONLY iOS 11*/
  402. guard #available(iOS 11, *) else {
  403. return
  404. }
  405. var serverUrl = ""
  406. if parentItemIdentifier == .rootContainer {
  407. serverUrl = homeServerUrl
  408. } else {
  409. guard let directoryParent = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, parentItemIdentifier.rawValue)) else {
  410. completionHandler(nil, NSFileProviderError(.noSuchItem))
  411. return
  412. }
  413. serverUrl = directoryParent.serverUrl
  414. }
  415. ocNetworking?.createFolder(directoryName, serverUrl: serverUrl, account: account, success: { (fileID, date) in
  416. let metadata = tableMetadata()
  417. metadata.account = account
  418. metadata.directory = true
  419. metadata.directoryID = NCManageDatabase.sharedInstance.getDirectoryID(serverUrl)!
  420. metadata.fileID = fileID!
  421. metadata.fileName = directoryName
  422. metadata.fileNameView = directoryName
  423. metadata.typeFile = k_metadataTypeFile_directory
  424. // METADATA
  425. guard let metadataDB = NCManageDatabase.sharedInstance.addMetadata(metadata) else {
  426. completionHandler(nil, NSFileProviderError(.noSuchItem))
  427. return
  428. }
  429. // DIRECTORY
  430. guard let _ = NCManageDatabase.sharedInstance.addDirectory(encrypted: false, favorite: false, fileID: fileID!, permissions: nil, serverUrl: serverUrl + "/" + directoryName) else {
  431. completionHandler(nil, NSFileProviderError(.noSuchItem))
  432. return
  433. }
  434. let item = FileProviderItem(metadata: metadataDB, serverUrl: serverUrl)
  435. completionHandler(item, nil)
  436. }, failure: { (errorMessage, errorCode) in
  437. completionHandler(nil, NSFileProviderError(.serverUnreachable))
  438. })
  439. }
  440. override func deleteItem(withIdentifier itemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (Error?) -> Void) {
  441. /* ONLY iOS 11*/
  442. guard #available(iOS 11, *) else {
  443. return
  444. }
  445. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, itemIdentifier.rawValue)) else {
  446. completionHandler(nil)
  447. return
  448. }
  449. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  450. completionHandler(nil)
  451. return
  452. }
  453. ocNetworking?.deleteFileOrFolder(metadata.fileName, serverUrl: serverUrl, success: {
  454. let fileNamePath = directoryUser + "/" + metadata.fileID
  455. do {
  456. try fileManagerExtension.removeItem(atPath: fileNamePath)
  457. } catch let error {
  458. print("error: \(error)")
  459. }
  460. do {
  461. try fileManagerExtension.removeItem(atPath: fileNamePath + ".ico")
  462. } catch let error {
  463. print("error: \(error)")
  464. }
  465. do {
  466. try fileManagerExtension.removeItem(atPath: fileProviderStorageURL!.path + "/" + metadata.fileID)
  467. } catch let error {
  468. print("error: \(error)")
  469. }
  470. if metadata.directory {
  471. let dirForDelete = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)
  472. NCManageDatabase.sharedInstance.deleteDirectoryAndSubDirectory(serverUrl: dirForDelete!)
  473. }
  474. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  475. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID), clearDateReadDirectoryID: nil)
  476. completionHandler(nil)
  477. }, failure: { (errorMessage, errorCode) in
  478. if errorCode == 404 {
  479. completionHandler(nil)
  480. } else {
  481. completionHandler(NSFileProviderError(.serverUnreachable))
  482. }
  483. })
  484. }
  485. override func reparentItem(withIdentifier itemIdentifier: NSFileProviderItemIdentifier, toParentItemWithIdentifier parentItemIdentifier: NSFileProviderItemIdentifier, newName: String?, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
  486. /* ONLY iOS 11*/
  487. guard #available(iOS 11, *) else {
  488. return
  489. }
  490. var serverUrlTo = ""
  491. var fileNameTo = ""
  492. var directoryIDTo = ""
  493. guard let itemFrom = try? item(for: itemIdentifier) else {
  494. completionHandler(nil, NSFileProviderError(.noSuchItem))
  495. return
  496. }
  497. guard let metadataFrom = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, itemIdentifier.rawValue)) else {
  498. completionHandler(nil, NSFileProviderError(.noSuchItem))
  499. return
  500. }
  501. guard let serverUrlFrom = NCManageDatabase.sharedInstance.getServerUrl(metadataFrom.directoryID) else {
  502. completionHandler(nil, NSFileProviderError(.noSuchItem))
  503. return
  504. }
  505. let fileNameFrom = serverUrlFrom + "/" + itemFrom.filename
  506. if parentItemIdentifier == NSFileProviderItemIdentifier.rootContainer {
  507. serverUrlTo = homeServerUrl
  508. } else {
  509. guard let metadataTo = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, parentItemIdentifier.rawValue)) else {
  510. completionHandler(nil, NSFileProviderError(.noSuchItem))
  511. return
  512. }
  513. serverUrlTo = NCManageDatabase.sharedInstance.getServerUrl(metadataTo.directoryID)! + "/" + metadataTo.fileName
  514. }
  515. directoryIDTo = NCManageDatabase.sharedInstance.getDirectoryID(serverUrlTo)!
  516. fileNameTo = serverUrlTo + "/" + itemFrom.filename
  517. ocNetworking?.moveFileOrFolder(fileNameFrom, fileNameTo: fileNameTo, success: {
  518. if metadataFrom.directory {
  519. NCManageDatabase.sharedInstance.deleteDirectoryAndSubDirectory(serverUrl: serverUrlFrom)
  520. NCManageDatabase.sharedInstance.moveMetadata(fileName: metadataFrom.fileName, directoryID: metadataFrom.directoryID, directoryIDTo: directoryIDTo)
  521. _ = NCManageDatabase.sharedInstance.addDirectory(encrypted: false, favorite: false, fileID: nil, permissions: nil, serverUrl: serverUrlTo)
  522. } else {
  523. NCManageDatabase.sharedInstance.moveMetadata(fileName: metadataFrom.fileName, directoryID: metadataFrom.directoryID, directoryIDTo: directoryIDTo)
  524. }
  525. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, itemIdentifier.rawValue)) else {
  526. completionHandler(nil, NSFileProviderError(.noSuchItem))
  527. return
  528. }
  529. let item = FileProviderItem(metadata: metadata, serverUrl: serverUrlTo)
  530. completionHandler(item, nil)
  531. }, failure: { (errorMessage, errorCode) in
  532. completionHandler(nil, NSFileProviderError(.serverUnreachable))
  533. })
  534. }
  535. override func renameItem(withIdentifier itemIdentifier: NSFileProviderItemIdentifier, toName itemName: String, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
  536. /* ONLY iOS 11*/
  537. guard #available(iOS 11, *) else {
  538. return
  539. }
  540. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, itemIdentifier.rawValue)) else {
  541. completionHandler(nil, NSFileProviderError(.noSuchItem))
  542. return
  543. }
  544. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  545. completionHandler(nil, NSFileProviderError(.noSuchItem))
  546. return
  547. }
  548. guard let directoryTable = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "serverUrl = %@", serverUrl)) else {
  549. completionHandler(nil, NSFileProviderError(.noSuchItem))
  550. return
  551. }
  552. let fileNameFrom = metadata.fileNameView
  553. let fileNamePathFrom = serverUrl + "/" + fileNameFrom
  554. let fileNamePathTo = serverUrl + "/" + itemName
  555. ocNetworking?.moveFileOrFolder(fileNamePathFrom, fileNameTo: fileNamePathTo, success: {
  556. metadata.fileName = itemName
  557. metadata.fileNameView = itemName
  558. guard let metadata = NCManageDatabase.sharedInstance.addMetadata(metadata) else {
  559. completionHandler(nil, NSFileProviderError(.noSuchItem))
  560. return
  561. }
  562. if metadata.directory {
  563. NCManageDatabase.sharedInstance.setDirectory(serverUrl: fileNamePathFrom, serverUrlTo: fileNamePathTo, etag: nil, fileID: nil, encrypted: directoryTable.e2eEncrypted)
  564. } else {
  565. do {
  566. try fileManagerExtension.moveItem(atPath: fileProviderStorageURL!.path + "/" + metadata.fileID + "/" + fileNameFrom, toPath: fileProviderStorageURL!.path + "/" + metadata.fileID + "/" + itemName)
  567. NCManageDatabase.sharedInstance.setLocalFile(fileID: metadata.fileID, date: nil, exifDate: nil, exifLatitude: nil, exifLongitude: nil, fileName: itemName, etag: nil, etagFPE: nil)
  568. } catch { }
  569. }
  570. let item = FileProviderItem(metadata: metadata, serverUrl: serverUrl)
  571. completionHandler(item, nil)
  572. }, failure: { (errorMessage, errorCode) in
  573. completionHandler(nil, NSFileProviderError(.serverUnreachable))
  574. })
  575. }
  576. override func setFavoriteRank(_ favoriteRank: NSNumber?, forItemIdentifier itemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
  577. /* ONLY iOS 11*/
  578. guard #available(iOS 11, *) else {
  579. return
  580. }
  581. completionHandler(nil, nil)
  582. /*
  583. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, itemIdentifier.rawValue)) else {
  584. completionHandler(nil, NSFileProviderError(.noSuchItem))
  585. return
  586. }
  587. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  588. completionHandler(nil, NSFileProviderError(.noSuchItem))
  589. return
  590. }
  591. // Refresh Favorite Identifier Rank
  592. listFavoriteIdentifierRank = NCManageDatabase.sharedInstance.getTableMetadatasDirectoryFavoriteIdentifierRank()
  593. if favoriteRank == nil {
  594. listFavoriteIdentifierRank.removeValue(forKey: itemIdentifier.rawValue)
  595. } else {
  596. let rank = listFavoriteIdentifierRank[itemIdentifier.rawValue]
  597. if rank == nil {
  598. listFavoriteIdentifierRank[itemIdentifier.rawValue] = favoriteRank//NSNumber(value: Int64(newRank))
  599. }
  600. favorite = true
  601. }
  602. // Call the completion handler before performing any network activity or other long-running tasks. Defer these tasks to the background
  603. let item = FileProviderItem(metadata: metadata, serverUrl: serverUrl)
  604. completionHandler(item, nil)
  605. // Change Status ? Call API Nextcloud Network
  606. if (favorite == true && metadata.favorite == false) || (favorite == false && metadata.favorite == true) {
  607. DispatchQueue(label: "com.nextcloud", qos: .background, attributes: .concurrent, autoreleaseFrequency: .inherit, target: nil).async {
  608. ocNetworking?.settingFavorite(metadata.fileName, serverUrl: serverUrl, favorite: favorite, success: {
  609. // Change DB
  610. metadata.favorite = favorite
  611. _ = NCManageDatabase.sharedInstance.addMetadata(metadata)
  612. // Refresh Favorite Identifier Rank
  613. listFavoriteIdentifierRank = NCManageDatabase.sharedInstance.getTableMetadatasDirectoryFavoriteIdentifierRank()
  614. // Refresh Item
  615. self.refreshEnumerator(identifier: itemIdentifier, serverUrl: serverUrl)
  616. }, failure: { (errorMessage, errorCode) in
  617. print("errorMessage")
  618. })
  619. }
  620. }
  621. */
  622. }
  623. override func setLastUsedDate(_ lastUsedDate: Date?, forItemIdentifier itemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
  624. print("[LOG] setLastUsedDate")
  625. completionHandler(nil, nil)
  626. }
  627. override func setTagData(_ tagData: Data?, forItemIdentifier itemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
  628. /* ONLY iOS 11*/
  629. guard #available(iOS 11, *) else {
  630. return
  631. }
  632. // Add, Remove (nil)
  633. NCManageDatabase.sharedInstance.addTag(itemIdentifier.rawValue, tagIOS: tagData)
  634. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, itemIdentifier.rawValue)) else {
  635. completionHandler(nil, NSFileProviderError(.noSuchItem))
  636. return
  637. }
  638. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  639. completionHandler(nil, NSFileProviderError(.noSuchItem))
  640. return
  641. }
  642. let item = FileProviderItem(metadata: metadata, serverUrl: serverUrl)
  643. completionHandler(item, nil)
  644. self.refreshEnumerator(identifier: itemIdentifier, serverUrl: "WorkingSet")
  645. }
  646. /*
  647. override func trashItem(withIdentifier itemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
  648. print("[LOG] trashitem")
  649. completionHandler(nil, nil)
  650. }
  651. override func untrashItem(withIdentifier itemIdentifier: NSFileProviderItemIdentifier, toParentItemIdentifier parentItemIdentifier: NSFileProviderItemIdentifier?, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
  652. print("[LOG] untrashitem")
  653. completionHandler(nil, nil)
  654. }
  655. */
  656. override func importDocument(at fileURL: URL, toParentItemIdentifier parentItemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
  657. /* ONLY iOS 11*/
  658. guard #available(iOS 11, *) else {
  659. return
  660. }
  661. let fileCoordinator = NSFileCoordinator()
  662. var error: NSError?
  663. var directoryPredicate: NSPredicate
  664. var size = 0 as Double
  665. let metadata = tableMetadata()
  666. if parentItemIdentifier == .rootContainer {
  667. directoryPredicate = NSPredicate(format: "account = %@ AND serverUrl = %@", account, homeServerUrl)
  668. } else {
  669. directoryPredicate = NSPredicate(format: "account = %@ AND fileID = %@", account, parentItemIdentifier.rawValue)
  670. }
  671. guard let directoryParent = NCManageDatabase.sharedInstance.getTableDirectory(predicate: directoryPredicate) else {
  672. completionHandler(nil, NSFileProviderError(.noSuchItem))
  673. return
  674. }
  675. let serverUrl = directoryParent.serverUrl
  676. // --------------------------------------------- Copy file here with security access
  677. if fileURL.startAccessingSecurityScopedResource() == false {
  678. completionHandler(nil, NSFileProviderError(.noSuchItem))
  679. return
  680. }
  681. let fileName = createFileName(fileURL.lastPathComponent, directoryID: directoryParent.directoryID, serverUrl: serverUrl)
  682. let fileNamePathDirectory = fileProviderStorageURL!.path + "/" + FILEID_IMPORT_METADATA_TEMP + directoryParent.directoryID + fileName
  683. fileCoordinator.coordinate(readingItemAt: fileURL, options: NSFileCoordinator.ReadingOptions.withoutChanges, error: &error) { (url) in
  684. do {
  685. try FileManager.default.createDirectory(atPath: fileNamePathDirectory, withIntermediateDirectories: true, attributes: nil)
  686. } catch { }
  687. _ = self.copyFile(url.path, toPath: fileNamePathDirectory + "/" + fileName)
  688. }
  689. fileURL.stopAccessingSecurityScopedResource()
  690. // ---------------------------------------------------------------------------------
  691. do {
  692. let attributes = try fileManagerExtension.attributesOfItem(atPath: fileNamePathDirectory + "/" + fileName)
  693. size = attributes[FileAttributeKey.size] as! Double
  694. } catch let error {
  695. print("error: \(error)")
  696. }
  697. // Metadata TEMP
  698. metadata.account = account
  699. metadata.date = NSDate()
  700. metadata.directory = false
  701. metadata.directoryID = directoryParent.directoryID
  702. metadata.etag = ""
  703. metadata.fileID = FILEID_IMPORT_METADATA_TEMP + directoryParent.directoryID + fileName
  704. metadata.size = size
  705. metadata.status = Double(k_metadataStatusHide)
  706. metadata.fileName = fileURL.lastPathComponent
  707. metadata.fileNameView = fileURL.lastPathComponent
  708. CCUtility.insertTypeFileIconName(fileName, metadata: metadata)
  709. if (size > 0) {
  710. let metadataNet = CCMetadataNet()
  711. metadataNet.account = account
  712. metadataNet.assetLocalIdentifier = FILEID_IMPORT_METADATA_TEMP + directoryParent.directoryID + fileName
  713. metadataNet.fileName = fileName
  714. metadataNet.path = fileNamePathDirectory + "/" + fileName
  715. metadataNet.selector = selectorUploadFile
  716. metadataNet.selectorPost = ""
  717. metadataNet.serverUrl = serverUrl
  718. metadataNet.session = k_upload_session_extension
  719. metadataNet.taskStatus = Int(k_taskStatusResume)
  720. _ = NCManageDatabase.sharedInstance.addQueueUpload(metadataNet: metadataNet)
  721. }
  722. guard let metadataDB = NCManageDatabase.sharedInstance.addMetadata(metadata) else {
  723. completionHandler(nil, NSFileProviderError(.noSuchItem))
  724. return
  725. }
  726. let item = FileProviderItem(metadata: metadataDB, serverUrl: serverUrl)
  727. completionHandler(item, nil)
  728. }
  729. // --------------------------------------------------------------------------------------------
  730. // MARK: - Upload
  731. // --------------------------------------------------------------------------------------------
  732. func uploadFileSuccessFailure(_ fileName: String!, fileID: String!, assetLocalIdentifier: String!, serverUrl: String!, selector: String!, selectorPost: String!, errorMessage: String!, errorCode: Int) {
  733. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID = %@", assetLocalIdentifier), clearDateReadDirectoryID: nil)
  734. if errorCode == 0 {
  735. NCManageDatabase.sharedInstance.deleteQueueUpload(assetLocalIdentifier: assetLocalIdentifier, selector: selector)
  736. if let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, fileID)) {
  737. // Rename directory file
  738. if fileManagerExtension.fileExists(atPath: fileProviderStorageURL!.path + "/" + assetLocalIdentifier) {
  739. _ = moveFile(fileProviderStorageURL!.path + "/" + assetLocalIdentifier, toPath: fileProviderStorageURL!.path + "/" + fileID)
  740. }
  741. NCManageDatabase.sharedInstance.setLocalFile(fileID: fileID, date: nil, exifDate: nil, exifLatitude: nil, exifLongitude: nil, fileName: nil, etag: metadata.etag, etagFPE: metadata.etag)
  742. let item = FileProviderItem(metadata: metadata, serverUrl: serverUrl)
  743. self.refreshEnumerator(identifier: item.itemIdentifier, serverUrl: serverUrl)
  744. }
  745. } else {
  746. NCManageDatabase.sharedInstance.unlockQueueUpload(assetLocalIdentifier: assetLocalIdentifier)
  747. }
  748. uploadFile()
  749. }
  750. func uploadFile() {
  751. let queueInLock = NCManageDatabase.sharedInstance.getQueueUploadInLock()
  752. if queueInLock != nil && queueInLock!.count == 0 {
  753. let metadataNetQueue = NCManageDatabase.sharedInstance.getQueueUploadLock(selector: selectorUploadFile, withPath: true)
  754. if metadataNetQueue != nil {
  755. if self.copyFile(metadataNetQueue!.path, toPath: directoryUser + "/" + metadataNetQueue!.fileName) == nil {
  756. 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)
  757. } else {
  758. // file not present, delete record Upload Queue
  759. NCManageDatabase.sharedInstance.deleteQueueUpload(path: metadataNetQueue!.path)
  760. }
  761. }
  762. }
  763. }
  764. func verifyUploadQueueInLock() {
  765. let tasks = CCNetworking.shared().getUploadTasksExtensionSession()
  766. if tasks!.count == 0 {
  767. let records = NCManageDatabase.sharedInstance.getQueueUpload(predicate: NSPredicate(format: "account = %@ AND selector = %@ AND lock == true AND path != nil", account, selectorUploadFile))
  768. if records != nil && records!.count > 0 {
  769. NCManageDatabase.sharedInstance.unlockAllQueueUploadInPath()
  770. }
  771. }
  772. }
  773. // --------------------------------------------------------------------------------------------
  774. // MARK: - User Function
  775. // --------------------------------------------------------------------------------------------
  776. func refreshEnumerator(identifier: NSFileProviderItemIdentifier, serverUrl: String) {
  777. /* ONLY iOS 11*/
  778. guard #available(iOS 11, *) else {
  779. return
  780. }
  781. let item = try? self.item(for: identifier)
  782. if item != nil {
  783. var found = false
  784. for updateItem in listUpdateItems {
  785. if updateItem.itemIdentifier.rawValue == identifier.rawValue {
  786. found = true
  787. }
  788. }
  789. if !found {
  790. listUpdateItems.append(item!)
  791. }
  792. }
  793. if serverUrl == homeServerUrl {
  794. NSFileProviderManager.default.signalEnumerator(for: .rootContainer, completionHandler: { (error) in
  795. print("send signal rootContainer")
  796. })
  797. } else if serverUrl == "WorkingSet" {
  798. NSFileProviderManager.default.signalEnumerator(for: .workingSet, completionHandler: { (error) in
  799. print("send signal workingSet")
  800. })
  801. } else {
  802. if let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account = %@ AND serverUrl = %@", account, serverUrl)) {
  803. let itemDirectory = NSFileProviderItemIdentifier(directory.fileID)
  804. NSFileProviderManager.default.signalEnumerator(for: itemDirectory, completionHandler: { (error) in
  805. print("send signal")
  806. })
  807. }
  808. }
  809. }
  810. func copyFile(_ atPath: String, toPath: String) -> Error? {
  811. var errorResult: Error?
  812. do {
  813. try fileManagerExtension.removeItem(atPath: toPath)
  814. } catch let error {
  815. print("error: \(error)")
  816. }
  817. do {
  818. try fileManagerExtension.copyItem(atPath: atPath, toPath: toPath)
  819. } catch let error {
  820. errorResult = error
  821. }
  822. return errorResult
  823. }
  824. func moveFile(_ atPath: String, toPath: String) -> Error? {
  825. var errorResult: Error?
  826. do {
  827. try fileManagerExtension.removeItem(atPath: toPath)
  828. } catch let error {
  829. print("error: \(error)")
  830. }
  831. do {
  832. try fileManagerExtension.moveItem(atPath: atPath, toPath: toPath)
  833. } catch let error {
  834. errorResult = error
  835. }
  836. return errorResult
  837. }
  838. func deleteFile(_ atPath: String) -> Error? {
  839. var errorResult: Error?
  840. do {
  841. try fileManagerExtension.removeItem(atPath: atPath)
  842. } catch let error {
  843. errorResult = error
  844. }
  845. return errorResult
  846. }
  847. func createFileName(_ fileName: String, directoryID: String, serverUrl: String) -> String {
  848. let serialQueue = DispatchQueue(label: "queueCreateFileName")
  849. var resultFileName = fileName
  850. serialQueue.sync {
  851. var exitLoop = false
  852. while exitLoop == false {
  853. if NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileNameView = %@ AND directoryID = %@", account, resultFileName, directoryID)) != nil || fileNamePathImport.contains(serverUrl+"/"+resultFileName) {
  854. var name = NSString(string: resultFileName).deletingPathExtension
  855. let ext = NSString(string: resultFileName).pathExtension
  856. let characters = Array(name)
  857. if characters.count < 2 {
  858. resultFileName = name + " " + "1" + "." + ext
  859. } else {
  860. let space = characters[characters.count-2]
  861. let numChar = characters[characters.count-1]
  862. var num = Int(String(numChar))
  863. if (space == " " && num != nil) {
  864. name = String(name.dropLast())
  865. num = num! + 1
  866. resultFileName = name + "\(num!)" + "." + ext
  867. } else {
  868. resultFileName = name + " " + "1" + "." + ext
  869. }
  870. }
  871. } else {
  872. exitLoop = true
  873. }
  874. }
  875. // add fileNamePathImport
  876. fileNamePathImport.append(serverUrl+"/"+resultFileName)
  877. }
  878. return resultFileName
  879. }
  880. }
  881. // --------------------------------------------------------------------------------------------
  882. // MARK: - Setup Active Accont
  883. // --------------------------------------------------------------------------------------------
  884. func setupActiveAccount() {
  885. guard let activeAccount = NCManageDatabase.sharedInstance.getAccountActive() else {
  886. return
  887. }
  888. account = activeAccount.account
  889. accountUser = activeAccount.user
  890. accountUserID = activeAccount.userID
  891. accountPassword = activeAccount.password
  892. accountUrl = activeAccount.url
  893. homeServerUrl = CCUtility.getHomeServerUrlActiveUrl(activeAccount.url)
  894. directoryUser = CCUtility.getDirectoryActiveUser(activeAccount.user, activeUrl: activeAccount.url)
  895. ocNetworking = OCnetworking.init(delegate: nil, metadataNet: nil, withUser: accountUser, withUserID: accountUserID, withPassword: accountPassword, withUrl: accountUrl)
  896. groupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.sharedInstance.capabilitiesGroups)
  897. fileProviderStorageURL = groupURL!.appendingPathComponent(k_assetLocalIdentifierFileProviderStorage)
  898. // Create dir File Provider Storage
  899. do {
  900. try FileManager.default.createDirectory(atPath: fileProviderStorageURL!.path, withIntermediateDirectories: true, attributes: nil)
  901. } catch let error as NSError {
  902. NSLog("Unable to create directory \(error.debugDescription)")
  903. }
  904. }
  905. func createFileIdentifier(itemIdentifier: String, fileName: String) {
  906. let identifierPath = fileProviderStorageURL!.path + "/" + itemIdentifier
  907. let fileIdentifier = identifierPath + "/" + fileName
  908. do {
  909. try fileManagerExtension.createDirectory(atPath: identifierPath, withIntermediateDirectories: true, attributes: nil)
  910. } catch { }
  911. // If do not exists create file with size = 0
  912. if fileManagerExtension.fileExists(atPath: fileIdentifier) == false {
  913. fileManagerExtension.createFile(atPath: fileIdentifier, contents: nil, attributes: nil)
  914. }
  915. }