FileProvider.swift 54 KB

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