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