FileProvider.swift 54 KB

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