FileProvider.swift 53 KB

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