FileProvider.swift 53 KB

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