FileProvider.swift 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198
  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: directoryUser + "/" + metadataNetQueue!.fileName)
  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 + directoryParent.directoryID + fileName
  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 if size > 0 [Office 365] ----------
  777. if (size > 0) {
  778. let metadataNet = CCMetadataNet()
  779. metadataNet.account = account
  780. metadataNet.assetLocalIdentifier = k_assetLocalIdentifierFileProviderStorage + metadata.fileID
  781. metadataNet.fileName = fileName
  782. metadataNet.path = importDocumentURL!.path + "/" + metadata.fileNameView
  783. metadataNet.selector = selectorUploadFile
  784. metadataNet.selectorPost = ""
  785. metadataNet.serverUrl = serverUrl
  786. metadataNet.session = k_upload_session
  787. metadataNet.taskStatus = Int(k_taskStatusResume)
  788. _ = NCManageDatabase.sharedInstance.addQueueUpload(metadataNet: metadataNet)
  789. }
  790. // self.refreshEnumerator(identifier: item.itemIdentifier, serverUrl: serverUrl)
  791. let item = FileProviderItem(metadata: metadataDB, serverUrl: serverUrl)
  792. completionHandler(item, nil)
  793. }
  794. // --------------------------------------------------------------------------------------------
  795. // MARK: - User Function
  796. // --------------------------------------------------------------------------------------------
  797. func refreshEnumerator(identifier: NSFileProviderItemIdentifier, serverUrl: String) {
  798. /* ONLY iOS 11*/
  799. guard #available(iOS 11, *) else {
  800. return
  801. }
  802. let item = try? self.item(for: identifier)
  803. if item != nil {
  804. var found = false
  805. for updateItem in listUpdateItems {
  806. if updateItem.itemIdentifier.rawValue == identifier.rawValue {
  807. found = true
  808. }
  809. }
  810. if !found {
  811. listUpdateItems.append(item!)
  812. }
  813. }
  814. if serverUrl == homeServerUrl {
  815. NSFileProviderManager.default.signalEnumerator(for: .rootContainer, completionHandler: { (error) in
  816. print("send signal rootContainer")
  817. })
  818. } else if serverUrl == "WorkingSet" {
  819. NSFileProviderManager.default.signalEnumerator(for: .workingSet, completionHandler: { (error) in
  820. print("send signal workingSet")
  821. })
  822. } else {
  823. if let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account = %@ AND serverUrl = %@", account, serverUrl)) {
  824. let itemDirectory = NSFileProviderItemIdentifier(directory.fileID)
  825. NSFileProviderManager.default.signalEnumerator(for: itemDirectory, completionHandler: { (error) in
  826. print("send signal")
  827. })
  828. }
  829. }
  830. }
  831. func copyFile(_ atPath: String, toPath: String) -> Error? {
  832. var errorResult: Error?
  833. do {
  834. try FileManager.default.removeItem(atPath: toPath)
  835. } catch let error {
  836. print("error: \(error)")
  837. }
  838. do {
  839. try FileManager.default.copyItem(atPath: atPath, toPath: toPath)
  840. } catch let error {
  841. errorResult = error
  842. }
  843. return errorResult
  844. }
  845. func deleteFile(_ atPath: String) -> Error? {
  846. var errorResult: Error?
  847. do {
  848. try FileManager.default.removeItem(atPath: atPath)
  849. } catch let error {
  850. errorResult = error
  851. }
  852. return errorResult
  853. }
  854. func createFileName(_ fileName: String, directoryID: String, serverUrl: String) -> String {
  855. var resultFileName = fileName
  856. var exitLoop = false
  857. while exitLoop == false {
  858. if NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileNameView = %@ AND directoryID = %@", account, resultFileName, directoryID)) != nil || fileNamePathImport.contains(serverUrl+"/"+resultFileName) {
  859. var name = NSString(string: resultFileName).deletingPathExtension
  860. let ext = NSString(string: resultFileName).pathExtension
  861. let characters = Array(name)
  862. if characters.count < 2 {
  863. resultFileName = name + " " + "1" + "." + ext
  864. } else {
  865. let space = characters[characters.count-2]
  866. let numChar = characters[characters.count-1]
  867. var num = Int(String(numChar))
  868. if (space == " " && num != nil) {
  869. name = String(name.dropLast())
  870. num = num! + 1
  871. resultFileName = name + "\(num!)" + "." + ext
  872. } else {
  873. resultFileName = name + " " + "1" + "." + ext
  874. }
  875. }
  876. } else {
  877. exitLoop = true
  878. }
  879. }
  880. // add fileNamePathImport
  881. fileNamePathImport.append(serverUrl+"/"+resultFileName)
  882. return resultFileName
  883. }
  884. }
  885. // --------------------------------------------------------------------------------------------
  886. // MARK: - Setup Active Accont
  887. // --------------------------------------------------------------------------------------------
  888. func setupActiveAccount() {
  889. guard let activeAccount = NCManageDatabase.sharedInstance.getAccountActive() else {
  890. return
  891. }
  892. account = activeAccount.account
  893. accountUser = activeAccount.user
  894. accountUserID = activeAccount.userID
  895. accountPassword = activeAccount.password
  896. accountUrl = activeAccount.url
  897. homeServerUrl = CCUtility.getHomeServerUrlActiveUrl(activeAccount.url)
  898. directoryUser = CCUtility.getDirectoryActiveUser(activeAccount.user, activeUrl: activeAccount.url)
  899. ocNetworking = OCnetworking.init(delegate: nil, metadataNet: nil, withUser: accountUser, withUserID: accountUserID, withPassword: accountPassword, withUrl: accountUrl)
  900. groupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.sharedInstance.capabilitiesGroups)
  901. fileProviderStorageURL = groupURL!.appendingPathComponent(k_assetLocalIdentifierFileProviderStorage)
  902. importDocumentURL = groupURL!.appendingPathComponent(k_assetLocalIdentifierFileProviderStorage).appendingPathComponent(k_fileProviderStorageImportDocument)
  903. changeDocumentURL = groupURL!.appendingPathComponent(k_assetLocalIdentifierFileProviderStorage).appendingPathComponent(k_fileProviderStorageChangeDocument)
  904. // Create dir File Provider Storage
  905. do {
  906. try FileManager.default.createDirectory(atPath: fileProviderStorageURL!.path, withIntermediateDirectories: true, attributes: nil)
  907. } catch let error as NSError {
  908. NSLog("Unable to create directory \(error.debugDescription)")
  909. }
  910. // Create dir for Upload
  911. do {
  912. try FileManager.default.createDirectory(atPath: importDocumentURL!.path, withIntermediateDirectories: true, attributes: nil)
  913. } catch let error as NSError {
  914. NSLog("Unable to create directory \(error.debugDescription)")
  915. }
  916. // Create dir for change document
  917. do {
  918. try FileManager.default.createDirectory(atPath: changeDocumentURL!.path, withIntermediateDirectories: true, attributes: nil)
  919. } catch let error as NSError {
  920. NSLog("Unable to create directory \(error.debugDescription)")
  921. }
  922. }