NCNetworking.swift 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  1. //
  2. // NCNetworking.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 23/10/19.
  6. // Copyright © 2019 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  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 Foundation
  24. import OpenSSL
  25. import NCCommunication
  26. import Alamofire
  27. @objc public protocol NCNetworkingDelegate {
  28. @objc optional func downloadProgress(_ progress: Double, totalBytes: Int64, totalBytesExpected: Int64, fileName: String, serverUrl: String, session: URLSession, task: URLSessionTask)
  29. @objc optional func uploadProgress(_ progress: Double, totalBytes: Int64, totalBytesExpected: Int64, fileName: String, serverUrl: String, session: URLSession, task: URLSessionTask)
  30. @objc optional func downloadComplete(fileName: String, serverUrl: String, etag: String?, date: NSDate?, dateLastModified: NSDate?, length: Double, description: String?, task: URLSessionTask, errorCode: Int, errorDescription: String)
  31. @objc optional func uploadComplete(fileName: String, serverUrl: String, ocId: String?, etag: String?, date: NSDate?, size: Int64, description: String?, task: URLSessionTask, errorCode: Int, errorDescription: String)
  32. }
  33. @objc class NCNetworking: NSObject, NCCommunicationCommonDelegate {
  34. @objc public static let shared: NCNetworking = {
  35. let instance = NCNetworking()
  36. return instance
  37. }()
  38. var delegate: NCNetworkingDelegate?
  39. var lastReachability: Bool = true
  40. var downloadRequest: [String: DownloadRequest] = [:]
  41. var uploadRequest: [String: UploadRequest] = [:]
  42. //MARK: - Communication Delegate
  43. func networkReachabilityObserver(_ typeReachability: NCCommunicationCommon.typeReachability) {
  44. #if !EXTENSION
  45. if typeReachability == NCCommunicationCommon.typeReachability.reachableCellular || typeReachability == NCCommunicationCommon.typeReachability.reachableEthernetOrWiFi {
  46. if !lastReachability {
  47. NCService.shared.startRequestServicesServer()
  48. }
  49. lastReachability = true
  50. } else {
  51. if lastReachability {
  52. NCContentPresenter.shared.messageNotification("_network_not_available_", description: nil, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: -1009)
  53. }
  54. lastReachability = false
  55. }
  56. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_setTitleMain)
  57. #endif
  58. }
  59. func authenticationChallenge(_ challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  60. if NCNetworking.shared.checkTrustedChallenge(challenge: challenge, directoryCertificate: CCUtility.getDirectoryCerificates()) {
  61. completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential.init(trust: challenge.protectionSpace.serverTrust!))
  62. } else {
  63. completionHandler(URLSession.AuthChallengeDisposition.performDefaultHandling, nil)
  64. }
  65. }
  66. func downloadProgress(_ progress: Double, totalBytes: Int64, totalBytesExpected: Int64, fileName: String, serverUrl: String, session: URLSession, task: URLSessionTask) {
  67. delegate?.downloadProgress?(progress, totalBytes: totalBytes, totalBytesExpected: totalBytesExpected, fileName: fileName, serverUrl: serverUrl, session: session, task: task)
  68. }
  69. func downloadComplete(fileName: String, serverUrl: String, etag: String?, date: NSDate?, dateLastModified: NSDate?, length: Double, description: String?, task: URLSessionTask, errorCode: Int, errorDescription: String) {
  70. delegate?.downloadComplete?(fileName: fileName, serverUrl: serverUrl, etag: etag, date: date, dateLastModified: dateLastModified, length: length, description: description, task: task, errorCode: errorCode, errorDescription: errorDescription)
  71. }
  72. //MARK: - Pinning check
  73. @objc func checkTrustedChallenge(challenge: URLAuthenticationChallenge, directoryCertificate: String) -> Bool {
  74. var trusted = false
  75. let protectionSpace: URLProtectionSpace = challenge.protectionSpace
  76. let directoryCertificateUrl = URL.init(fileURLWithPath: directoryCertificate)
  77. if let trust: SecTrust = protectionSpace.serverTrust {
  78. saveX509Certificate(trust, certName: "tmp.der", directoryCertificate: directoryCertificate)
  79. do {
  80. let directoryContents = try FileManager.default.contentsOfDirectory(at: directoryCertificateUrl, includingPropertiesForKeys: nil)
  81. let certTmpPath = directoryCertificate+"/"+"tmp.der"
  82. for file in directoryContents {
  83. let certPath = file.path
  84. if certPath == certTmpPath { continue }
  85. if FileManager.default.contentsEqual(atPath:certTmpPath, andPath: certPath) {
  86. trusted = true
  87. break
  88. }
  89. }
  90. } catch { print(error) }
  91. }
  92. return trusted
  93. }
  94. @objc func wrtiteCertificate(directoryCertificate: String) {
  95. let certificateAtPath = directoryCertificate + "/tmp.der"
  96. let certificateToPath = directoryCertificate + "/" + CCUtility.getTimeIntervalSince197() + ".der"
  97. do {
  98. try FileManager.default.moveItem(atPath: certificateAtPath, toPath: certificateToPath)
  99. } catch { }
  100. }
  101. private func saveX509Certificate(_ trust: SecTrust, certName: String, directoryCertificate: String) {
  102. let currentServerCert = secTrustGetLeafCertificate(trust)
  103. let certNamePath = directoryCertificate + "/" + certName
  104. let data: CFData = SecCertificateCopyData(currentServerCert!)
  105. let mem = BIO_new_mem_buf(CFDataGetBytePtr(data), Int32(CFDataGetLength(data)))
  106. let x509cert = d2i_X509_bio(mem, nil)
  107. BIO_free(mem)
  108. if x509cert == nil {
  109. print("[LOG] OpenSSL couldn't parse X509 Certificate")
  110. } else {
  111. if FileManager.default.fileExists(atPath: certNamePath) {
  112. do {
  113. try FileManager.default.removeItem(atPath: certNamePath)
  114. } catch { }
  115. }
  116. let file = fopen(certNamePath, "w")
  117. if file != nil {
  118. PEM_write_X509(file, x509cert);
  119. }
  120. fclose(file);
  121. X509_free(x509cert);
  122. }
  123. }
  124. private func secTrustGetLeafCertificate(_ trust: SecTrust) -> SecCertificate? {
  125. let result: SecCertificate?
  126. if SecTrustGetCertificateCount(trust) > 0 {
  127. result = SecTrustGetCertificateAtIndex(trust, 0)!
  128. assert(result != nil);
  129. } else {
  130. result = nil
  131. }
  132. return result
  133. }
  134. //MARK: - Download
  135. @objc func cancelDownload(metadata: tableMetadata) {
  136. guard let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileName) else { return }
  137. if let request = downloadRequest[fileNameLocalPath] {
  138. request.cancel()
  139. } else {
  140. if let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId)) {
  141. metadata.session = ""
  142. metadata.sessionError = ""
  143. metadata.status = Int(k_metadataStatusNormal)
  144. NCManageDatabase.sharedInstance.addMetadata(metadata)
  145. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl])
  146. }
  147. }
  148. }
  149. @objc func download(metadata: tableMetadata, selector: String, setFavorite: Bool = false, completion: @escaping (_ errorCode: Int)->()) {
  150. var metadata = metadata
  151. let serverUrl = metadata.serverUrl
  152. let serverUrlFileName = serverUrl + "/" + metadata.fileName
  153. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileName)!
  154. if metadata.status == Int(k_metadataStatusInDownload) || metadata.status == Int(k_metadataStatusDownloading) { return }
  155. metadata.status = Int(k_metadataStatusInDownload)
  156. metadata.session = NCCommunicationCommon.shared.sessionIdentifierDownload
  157. if let result = NCManageDatabase.sharedInstance.addMetadata(metadata) { metadata = result }
  158. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, object: nil, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl])
  159. NCCommunication.shared.download(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, requestHandler: { (request) in
  160. self.downloadRequest[fileNameLocalPath] = request
  161. metadata.status = Int(k_metadataStatusDownloading)
  162. if let result = NCManageDatabase.sharedInstance.addMetadata(metadata) { metadata = result }
  163. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_downloadFileStart, userInfo: ["ocId":metadata.ocId, "serverUrl":serverUrl, "account":metadata.account])
  164. }, progressHandler: { (progress) in
  165. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_progressTask, object: nil, userInfo: ["account":metadata.account, "ocId":metadata.ocId, "serverUrl":serverUrl, "status":NSNumber(value: k_metadataStatusInDownload), "progress":NSNumber(value: progress.fractionCompleted), "totalBytes":NSNumber(value: progress.totalUnitCount), "totalBytesExpected":NSNumber(value: progress.completedUnitCount)])
  166. }) { (account, etag, date, length, error, errorCode, errorDescription) in
  167. self.downloadRequest[fileNameLocalPath] = nil
  168. if errorCode == 0 {
  169. metadata.etag = etag ?? ""
  170. if setFavorite { metadata.favorite = true }
  171. metadata.session = ""
  172. metadata.sessionError = ""
  173. metadata.status = Int(k_metadataStatusNormal)
  174. NCManageDatabase.sharedInstance.addLocalFile(metadata: metadata)
  175. if let result = NCManageDatabase.sharedInstance.addMetadata(metadata) { metadata = result }
  176. #if !EXTENSION
  177. if let result = NCManageDatabase.sharedInstance.getE2eEncryption(predicate: NSPredicate(format: "fileNameIdentifier == %@ AND serverUrl == %@", metadata.fileName, serverUrl)) {
  178. NCEndToEndEncryption.sharedManager()?.decryptFileName(metadata.fileName, fileNameView: metadata.fileNameView, ocId: metadata.ocId, key: result.key, initializationVector: result.initializationVector, authenticationTag: result.authenticationTag)
  179. }
  180. #endif
  181. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_downloadedFile, userInfo: ["metadata":metadata, "selector":selector, "errorCode":errorCode, "errorDescription":errorDescription])
  182. } else if error?.isExplicitlyCancelledError ?? false {
  183. metadata.session = ""
  184. metadata.sessionError = ""
  185. metadata.status = Int(k_metadataStatusNormal)
  186. if let result = NCManageDatabase.sharedInstance.addMetadata(metadata) { metadata = result }
  187. } else {
  188. metadata.session = ""
  189. metadata.sessionError = errorDescription
  190. metadata.status = Int(k_metadataStatusDownloadError)
  191. if let result = NCManageDatabase.sharedInstance.addMetadata(metadata) { metadata = result }
  192. #if !EXTENSION
  193. if errorCode == 401 || errorCode == 403 {
  194. NCNetworkingCheckRemoteUser.shared.checkRemoteUser(account: metadata.account)
  195. } else if errorCode == Int(CFNetworkErrors.cfurlErrorServerCertificateUntrusted.rawValue) {
  196. CCUtility.setCertificateError(metadata.account, error: true)
  197. }
  198. #endif
  199. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_downloadedFile, userInfo: ["metadata":metadata, "selector":selector, "errorCode":errorCode, "errorDescription":errorDescription])
  200. }
  201. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl])
  202. completion(errorCode)
  203. }
  204. }
  205. //MARK: - Upload
  206. @objc func cancelUpload(metadata: tableMetadata) {
  207. guard let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileName) else { return }
  208. if let request = uploadRequest[fileNameLocalPath] {
  209. request.cancel()
  210. } else {
  211. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  212. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  213. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":metadata.serverUrl])
  214. }
  215. }
  216. @objc func upload(metadata: tableMetadata, background: Bool = true, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  217. var metadataForUpload: tableMetadata?
  218. var e2eEncrypted = false
  219. let internalContenType = NCCommunicationCommon.shared.getInternalContenType(fileName: metadata.fileNameView, contentType: metadata.contentType, directory: false)
  220. var fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  221. guard let account = NCManageDatabase.sharedInstance.getAccount(predicate: NSPredicate(format: "account == %@", metadata.account)) else {
  222. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_uploadedFile, userInfo: ["metadata":metadata, "errorCode":k_CCErrorInternalError, "errorDescription":"Internal error"])
  223. completion(Int(k_CCErrorInternalError), "Internal error")
  224. return
  225. }
  226. if CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account) {
  227. e2eEncrypted = true
  228. }
  229. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  230. metadata.contentType = internalContenType.contentType
  231. metadata.iconName = internalContenType.iconName
  232. metadata.typeFile = internalContenType.typeFile
  233. if let date = NCUtilityFileSystem.shared.getFileCreationDate(filePath: fileNameLocalPath) {
  234. metadata.creationDate = date
  235. }
  236. if let date = NCUtilityFileSystem.shared.getFileModificationDate(filePath: fileNameLocalPath) {
  237. metadata.date = date
  238. }
  239. metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNameLocalPath)
  240. if metadata.size > Double(k_max_filesize_E2EE) {
  241. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_uploadedFile, userInfo: ["metadata":metadata, "errorCode":k_CCErrorInternalError, "errorDescription":"E2E Error file too big"])
  242. completion(Int(k_CCErrorInternalError), "E2E Error file too big")
  243. return
  244. }
  245. metadataForUpload = NCManageDatabase.sharedInstance.addMetadata(metadata)
  246. if e2eEncrypted {
  247. #if !EXTENSION
  248. NCNetworkingE2EE.shared.upload(metadata: metadataForUpload!, account: account, completion: completion)
  249. #endif
  250. } else if background {
  251. uploadFileInBackground(metadata: metadataForUpload!, account: account, completion: completion)
  252. }
  253. } else {
  254. CCUtility.extractImageVideoFromAssetLocalIdentifier(forUpload: metadata, notification: true) { (extractMetadata, fileNamePath) in
  255. guard let extractMetadata = extractMetadata else {
  256. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  257. completion(Int(k_CCErrorInternalError), "Internal error")
  258. return
  259. }
  260. fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(extractMetadata.ocId, fileNameView: extractMetadata.fileNameView)
  261. CCUtility.moveFile(atPath: fileNamePath, toPath: fileNameLocalPath)
  262. if e2eEncrypted && (extractMetadata.size > Double(k_max_filesize_E2EE)) {
  263. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_uploadedFile, userInfo: ["metadata":metadata, "errorCode":k_CCErrorInternalError, "errorDescription":"E2E Error file too big"])
  264. completion(Int(k_CCErrorInternalError), "E2E Error file too big")
  265. return
  266. }
  267. metadataForUpload = NCManageDatabase.sharedInstance.addMetadata(extractMetadata)
  268. if e2eEncrypted {
  269. #if !EXTENSION
  270. NCNetworkingE2EE.shared.upload(metadata: metadataForUpload!, account: account, completion: completion)
  271. #endif
  272. } else if background {
  273. self.uploadFileInBackground(metadata: metadataForUpload!, account: account, completion: completion)
  274. }
  275. }
  276. }
  277. }
  278. private func uploadFileInBackground(metadata: tableMetadata, account: tableAccount, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  279. var session: URLSession?
  280. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  281. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  282. if metadata.session == NCCommunicationCommon.shared.sessionIdentifierBackground || metadata.session == NCCommunicationCommon.shared.sessionIdentifierExtension {
  283. session = NCCommunicationBackground.shared.sessionManagerTransfer
  284. } else if metadata.session == NCCommunicationCommon.shared.sessionIdentifierBackgroundWWan {
  285. session = NCCommunicationBackground.shared.sessionManagerTransferWWan
  286. }
  287. if let task = NCCommunicationBackground.shared.upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, dateCreationFile: metadata.creationDate as Date, dateModificationFile: metadata.date as Date, description: "", session: session!) {
  288. metadata.status = Int(k_metadataStatusUploading)
  289. metadata.sessionError = ""
  290. metadata.sessionTaskIdentifier = task.taskIdentifier
  291. NCManageDatabase.sharedInstance.addMetadata(metadata)
  292. #if !EXTENSION
  293. CCGraphics.createNewImage(from: metadata.fileNameView, ocId: metadata.ocId, typeFile: metadata.typeFile)
  294. #endif
  295. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_uploadFileStart, userInfo: ["ocId":metadata.ocId, "task":task, "serverUrl":metadata.serverUrl, "account":metadata.account])
  296. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl])
  297. completion(0, "")
  298. } else {
  299. completion(Int(k_CCErrorInternalError), "task null")
  300. }
  301. }
  302. func uploadProgress(_ progress: Double, totalBytes: Int64, totalBytesExpected: Int64, fileName: String, serverUrl: String, session: URLSession, task: URLSessionTask) {
  303. delegate?.uploadProgress?(progress, totalBytes: totalBytes, totalBytesExpected: totalBytesExpected, fileName: fileName, serverUrl: serverUrl, session: session, task: task)
  304. if let metadata = NCManageDatabase.sharedInstance.getMetadataInSessionFromFileName(fileName, serverUrl: serverUrl, taskIdentifier: task.taskIdentifier) {
  305. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_progressTask, userInfo: ["account":metadata.account, "ocId":metadata.ocId, "serverUrl":serverUrl, "status":NSNumber(value: k_metadataStatusInUpload), "progress":NSNumber(value: progress), "totalBytes":NSNumber(value: totalBytes), "totalBytesExpected":NSNumber(value: totalBytesExpected)])
  306. }
  307. }
  308. func uploadComplete(fileName: String, serverUrl: String, ocId: String?, etag: String?, date: NSDate?, size: Int64, description: String?, task: URLSessionTask, errorCode: Int, errorDescription: String) {
  309. if delegate != nil {
  310. delegate?.uploadComplete?(fileName: fileName, serverUrl: serverUrl, ocId: ocId, etag: etag, date: date, size:size, description: description, task: task, errorCode: errorCode, errorDescription: errorDescription)
  311. } else {
  312. guard var metadata = NCManageDatabase.sharedInstance.getMetadataInSessionFromFileName(fileName, serverUrl: serverUrl, taskIdentifier: task.taskIdentifier) else {
  313. return
  314. }
  315. guard let tableAccount = NCManageDatabase.sharedInstance.getAccount(predicate: NSPredicate(format: "account == %@", metadata.account)) else { return }
  316. if errorCode == 0 && ocId != nil {
  317. CCUtility.moveFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId), toPath: CCUtility.getDirectoryProviderStorageOcId(ocId))
  318. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  319. metadata.uploadDate = date ?? NSDate()
  320. metadata.etag = etag ?? ""
  321. metadata.ocId = ocId!
  322. metadata.session = ""
  323. metadata.sessionError = ""
  324. metadata.sessionTaskIdentifier = 0
  325. metadata.status = Int(k_metadataStatusNormal)
  326. // Delete Asset on Photos album
  327. if tableAccount.autoUploadDeleteAssetLocalIdentifier && metadata.assetLocalIdentifier != "" && metadata.sessionSelector == selectorUploadAutoUpload {
  328. metadata.deleteAssetLocalIdentifier = true;
  329. }
  330. if let result = NCManageDatabase.sharedInstance.addMetadata(metadata) { metadata = result }
  331. if CCUtility.getDisableLocalCacheAfterUpload() {
  332. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  333. } else {
  334. NCManageDatabase.sharedInstance.addLocalFile(metadata: metadata)
  335. }
  336. #if !EXTENSION
  337. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_uploadedFile, userInfo: ["metadata":metadata, "errorCode":errorCode, "errorDescription":""])
  338. #endif
  339. } else if errorCode == NSURLErrorCancelled {
  340. if metadata.status == k_metadataStatusUploadForcedStart {
  341. metadata.session = NCCommunicationCommon.shared.sessionIdentifierBackground
  342. metadata.sessionError = ""
  343. metadata.sessionTaskIdentifier = 0
  344. metadata.status = Int(k_metadataStatusInUpload)
  345. if let result = NCManageDatabase.sharedInstance.addMetadata(metadata) { metadata = result }
  346. NCNetworking.shared.upload(metadata: metadata) { (_, _) in }
  347. } else {
  348. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  349. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  350. }
  351. } else if errorCode == 401 || errorCode == 403 {
  352. #if !EXTENSION
  353. NCNetworkingCheckRemoteUser.shared.checkRemoteUser(account: metadata.account)
  354. #endif
  355. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  356. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  357. } else if errorCode == Int(CFNetworkErrors.cfurlErrorServerCertificateUntrusted.rawValue) {
  358. CCUtility.setCertificateError(metadata.account, error: true)
  359. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  360. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  361. } else {
  362. metadata.session = ""
  363. metadata.sessionError = errorDescription
  364. metadata.sessionTaskIdentifier = 0
  365. metadata.status = Int(k_metadataStatusUploadError)
  366. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_uploadedFile, userInfo: ["metadata":metadata, "errorCode":errorCode, "errorDescription":errorDescription])
  367. if let result = NCManageDatabase.sharedInstance.addMetadata(metadata) { metadata = result }
  368. }
  369. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl])
  370. }
  371. }
  372. //MARK: - Download / Upload
  373. @objc func verifyTransfer() {
  374. var session: URLSession?
  375. // download
  376. if let metadatas = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "status == %d", Int(k_metadataStatusDownloading)), sorted: nil, ascending: true) {
  377. for metadata in metadatas {
  378. guard let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileName) else { continue }
  379. let request = downloadRequest[fileNameLocalPath]
  380. if request == nil {
  381. metadata.session = ""
  382. metadata.sessionError = ""
  383. metadata.status = Int(k_metadataStatusNormal)
  384. NCManageDatabase.sharedInstance.addMetadata(metadata)
  385. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl])
  386. }
  387. }
  388. }
  389. // upload
  390. if let metadatas = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "session == %@ AND status == %d", NCCommunicationCommon.shared.sessionIdentifierUpload ,Int(k_metadataStatusUploading)), sorted: nil, ascending: true) {
  391. for metadata in metadatas {
  392. guard let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileName) else { continue }
  393. let request = uploadRequest[fileNameLocalPath]
  394. if request == nil {
  395. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  396. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  397. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":metadata.serverUrl])
  398. }
  399. }
  400. }
  401. // k_metadataStatusUploading (BACKGROUND)
  402. let sessionBackground = NCCommunicationCommon.shared.sessionIdentifierBackground
  403. let sessionBackgroundWWan = NCCommunicationCommon.shared.sessionIdentifierBackgroundWWan
  404. if let metadatas = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "(session == %@ OR session == %@) AND status == %d", sessionBackground, sessionBackgroundWWan, k_metadataStatusUploading), sorted: nil, ascending: true) {
  405. for metadata in metadatas {
  406. if metadata.session == NCCommunicationCommon.shared.sessionIdentifierBackground {
  407. session = NCCommunicationBackground.shared.sessionManagerTransfer
  408. } else if metadata.session == NCCommunicationCommon.shared.sessionIdentifierBackgroundWWan {
  409. session = NCCommunicationBackground.shared.sessionManagerTransferWWan
  410. } else if metadata.session == NCCommunicationCommon.shared.sessionIdentifierExtension {
  411. session = NCCommunicationBackground.shared.sessionManagerTransferExtension
  412. }
  413. var findTask = false
  414. session?.getAllTasks(completionHandler: { (tasks) in
  415. for task in tasks {
  416. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  417. findTask = true
  418. }
  419. }
  420. if !findTask {
  421. DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
  422. if let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@ AND status == %d", metadata.ocId, k_metadataStatusUploading)) {
  423. metadata.session = NCCommunicationCommon.shared.sessionIdentifierBackground
  424. metadata.sessionError = ""
  425. metadata.sessionTaskIdentifier = 0
  426. metadata.status = Int(k_metadataStatusWaitUpload)
  427. NCManageDatabase.sharedInstance.addMetadata(metadata)
  428. }
  429. }
  430. }
  431. })
  432. }
  433. }
  434. // verify k_metadataStatusInUpload (BACKGROUND)
  435. if let metadatas = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "(session == %@ OR session == %@) AND status == %d AND sessionTaskIdentifier == 0", sessionBackground, sessionBackgroundWWan, k_metadataStatusInUpload), sorted: nil, ascending: true) {
  436. for metadata in metadatas {
  437. DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
  438. if let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@ AND status == %d AND sessionTaskIdentifier == 0", metadata.ocId, k_metadataStatusInUpload)) {
  439. metadata.session = NCCommunicationCommon.shared.sessionIdentifierBackground
  440. metadata.sessionError = ""
  441. metadata.sessionTaskIdentifier = 0
  442. metadata.status = Int(k_metadataStatusWaitUpload)
  443. NCManageDatabase.sharedInstance.addMetadata(metadata)
  444. }
  445. }
  446. }
  447. }
  448. }
  449. //MARK: - WebDav Read file, folder
  450. @objc func readFolder(serverUrl: String, account: String, completion: @escaping (_ account: String, _ metadataFolder: tableMetadata?, _ metadatas: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String)->()) {
  451. NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrl, depth: "1", showHiddenFiles: CCUtility.getShowHiddenFiles()) { (account, files, responseData, errorCode, errorDescription) in
  452. if errorCode == 0 && files != nil {
  453. NCManageDatabase.sharedInstance.convertNCCommunicationFilesToMetadatas(files!, useMetadataFolder: true, account: account) { (metadataFolder, metadatasFolder, metadatas) in
  454. // Add directory
  455. NCManageDatabase.sharedInstance.addDirectory(encrypted: metadataFolder.e2eEncrypted, favorite: metadataFolder.favorite, ocId: metadataFolder.ocId, fileId: metadataFolder.fileId, etag: metadataFolder.etag, permissions: metadataFolder.permissions, serverUrl: serverUrl, richWorkspace: metadataFolder.richWorkspace, account: account)
  456. // Add other directories
  457. for metadata in metadatasFolder {
  458. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  459. NCManageDatabase.sharedInstance.addDirectory(encrypted: metadata.e2eEncrypted, favorite: metadata.favorite, ocId: metadata.ocId, fileId: metadata.fileId, etag: nil, permissions: metadata.permissions, serverUrl: serverUrl, richWorkspace: metadata.richWorkspace, account: account)
  460. }
  461. // Save status transfer metadata
  462. let metadatasInDownload = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND (status == %d OR status == %d OR status == %d OR status == %d)", account, serverUrl, k_metadataStatusWaitDownload, k_metadataStatusInDownload, k_metadataStatusDownloading, k_metadataStatusDownloadError), sorted: nil, ascending: false)
  463. let metadatasInUpload = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND (status == %d OR status == %d OR status == %d OR status == %d)", account, serverUrl, k_metadataStatusWaitUpload, k_metadataStatusInUpload, k_metadataStatusUploading, k_metadataStatusUploadError), sorted: nil, ascending: false)
  464. // Delete metadata
  465. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND status == %d", account, serverUrl, k_metadataStatusNormal))
  466. // Add metadata
  467. let metadataFolderInserted = NCManageDatabase.sharedInstance.addMetadata(metadataFolder)
  468. let metadatasInserted = NCManageDatabase.sharedInstance.addMetadatas(metadatas)
  469. if metadatasInDownload != nil {
  470. NCManageDatabase.sharedInstance.addMetadatas(metadatasInDownload!)
  471. }
  472. if metadatasInUpload != nil {
  473. NCManageDatabase.sharedInstance.addMetadatas(metadatasInUpload!)
  474. }
  475. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":serverUrl])
  476. completion(account, metadataFolderInserted, metadatasInserted, errorCode, "")
  477. }
  478. } else {
  479. #if !EXTENSION
  480. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  481. #endif
  482. completion(account, nil, nil, errorCode, errorDescription)
  483. }
  484. }
  485. }
  486. @objc func readFile(serverUrlFileName: String, account: String, completion: @escaping (_ account: String, _ metadata: tableMetadata?, _ errorCode: Int, _ errorDescription: String)->()) {
  487. NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrlFileName, depth: "0", showHiddenFiles: CCUtility.getShowHiddenFiles()) { (account, files, responseData, errorCode, errorDescription) in
  488. if errorCode == 0 && files != nil {
  489. if files?.count ?? 0 == 1 {
  490. let file = files![0]
  491. let isEncrypted = CCUtility.isFolderEncrypted(file.serverUrl, e2eEncrypted:file.e2eEncrypted, account: account)
  492. let metadata = NCManageDatabase.sharedInstance.convertNCFileToMetadata(file, isEncrypted: isEncrypted, account: account)
  493. completion(account, metadata, errorCode, "")
  494. } else {
  495. completion(account, nil, errorCode, "")
  496. }
  497. } else {
  498. completion(account, nil, errorCode, errorDescription)
  499. }
  500. }
  501. }
  502. //MARK: - WebDav Create Folder
  503. @objc func createFolder(fileName: String, serverUrl: String, account: String, url: String, overwrite: Bool = false, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  504. let isDirectoryEncrypted = CCUtility.isFolderEncrypted(serverUrl, e2eEncrypted: false, account: account)
  505. if isDirectoryEncrypted {
  506. #if !EXTENSION
  507. NCNetworkingE2EE.shared.createFolder(fileName: fileName, serverUrl: serverUrl, account: account, url: url, completion: completion)
  508. #endif
  509. } else {
  510. createFolderPlain(fileName: fileName, serverUrl: serverUrl, account: account, url: url, overwrite: overwrite, completion: completion)
  511. }
  512. }
  513. @objc func createFolderPlain(fileName: String, serverUrl: String, account: String, url: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  514. var fileNameFolder = CCUtility.removeForbiddenCharactersServer(fileName)!
  515. if (!overwrite) {
  516. fileNameFolder = NCUtility.sharedInstance.createFileName(fileNameFolder, serverUrl: serverUrl, account: account)
  517. }
  518. if fileNameFolder.count == 0 {
  519. self.NotificationPost(name: k_notificationCenter_createFolder, userInfo: ["fileName": fileName, "serverUrl": serverUrl, "errorCode": Int(0)], errorDescription: "", completion: completion)
  520. return
  521. }
  522. let fileNameFolderUrl = serverUrl + "/" + fileNameFolder
  523. NCCommunication.shared.createFolder(fileNameFolderUrl) { (account, ocId, date, errorCode, errorDescription) in
  524. if errorCode == 0 {
  525. self.readFile(serverUrlFileName: fileNameFolderUrl, account: account) { (account, metadataFolder, errorCode, errorDescription) in
  526. if errorCode == 0 {
  527. // Add Metadata
  528. NCManageDatabase.sharedInstance.addMetadata(metadataFolder!)
  529. // Add folder
  530. NCManageDatabase.sharedInstance.addDirectory(encrypted: metadataFolder!.e2eEncrypted, favorite: metadataFolder!.favorite, ocId: metadataFolder!.ocId, fileId: metadataFolder!.fileId, etag: nil, permissions: metadataFolder!.permissions, serverUrl: fileNameFolderUrl, richWorkspace: metadataFolder!.richWorkspace, account: account)
  531. self.NotificationPost(name: k_notificationCenter_createFolder, userInfo: ["fileName": fileName, "serverUrl": serverUrl, "errorCode": errorCode], errorDescription: errorDescription, completion: completion)
  532. } else {
  533. self.NotificationPost(name: k_notificationCenter_createFolder, userInfo: ["fileName": fileName, "serverUrl": serverUrl, "errorCode": errorCode], errorDescription: errorDescription, completion: completion)
  534. }
  535. }
  536. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":serverUrl])
  537. } else if errorCode == 405 && overwrite {
  538. self.NotificationPost(name: k_notificationCenter_createFolder, userInfo: ["fileName": fileName, "serverUrl": serverUrl, "errorCode": 0], errorDescription: "", completion: completion)
  539. } else {
  540. self.NotificationPost(name: k_notificationCenter_createFolder, userInfo: ["fileName": fileName, "serverUrl": serverUrl, "errorCode": errorCode], errorDescription: errorDescription, completion: completion)
  541. }
  542. }
  543. }
  544. //MARK: - WebDav Delete
  545. @objc func deleteMetadata(_ metadata: tableMetadata, account: String, url: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  546. let isDirectoryEncrypted = CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account)
  547. let metadataLive = NCManageDatabase.sharedInstance.isLivePhoto(metadata: metadata)
  548. if isDirectoryEncrypted {
  549. #if !EXTENSION
  550. if metadataLive == nil {
  551. NCNetworkingE2EE.shared.deleteMetadata(metadata, url: url, completion: completion)
  552. } else {
  553. NCNetworkingE2EE.shared.deleteMetadata(metadataLive!, url: url) { (errorCode, errorDescription) in
  554. if errorCode == 0 {
  555. NCNetworkingE2EE.shared.deleteMetadata(metadata, url: url, completion: completion)
  556. } else {
  557. completion(errorCode, errorDescription)
  558. }
  559. }
  560. }
  561. #endif
  562. } else {
  563. if metadataLive == nil {
  564. self.deleteMetadataPlain(metadata, addCustomHeaders: nil, completion: completion)
  565. } else {
  566. self.deleteMetadataPlain(metadataLive!, addCustomHeaders: nil) { (errorCode, errorDescription) in
  567. if errorCode == 0 {
  568. self.deleteMetadataPlain(metadata, addCustomHeaders: nil, completion: completion)
  569. } else {
  570. completion(errorCode, errorDescription)
  571. }
  572. }
  573. }
  574. }
  575. }
  576. func deleteMetadataPlain(_ metadata: tableMetadata, addCustomHeaders: [String: String]?, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  577. // verify permission
  578. let permission = NCUtility.sharedInstance.permissionsContainsString(metadata.permissions, permissions: k_permission_can_delete)
  579. if metadata.permissions != "" && permission == false {
  580. self.NotificationPost(name: k_notificationCenter_deleteFile, userInfo: ["metadata": metadata, "errorCode": Int(k_CCErrorNotPermission)], errorDescription: "_no_permission_delete_file_", completion: completion)
  581. return
  582. }
  583. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  584. NCCommunication.shared.deleteFileOrFolder(serverUrlFileName, customUserAgent: nil, addCustomHeaders: addCustomHeaders) { (account, errorCode, errorDescription) in
  585. if errorCode == 0 || errorCode == 404 {
  586. do {
  587. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  588. } catch { }
  589. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  590. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  591. if metadata.directory {
  592. NCManageDatabase.sharedInstance.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName), account: metadata.account)
  593. }
  594. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":metadata.serverUrl])
  595. }
  596. self.NotificationPost(name: k_notificationCenter_deleteFile, userInfo: ["metadata": metadata, "errorCode": errorCode], errorDescription: errorDescription, completion: completion)
  597. }
  598. }
  599. //MARK: - WebDav Favorite
  600. @objc func favoriteMetadata(_ metadata: tableMetadata, url: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  601. if let metadataLive = NCManageDatabase.sharedInstance.isLivePhoto(metadata: metadata) {
  602. favoriteMetadataPlain(metadataLive, url: url) { (errorCode, errorDescription) in
  603. if errorCode == 0 {
  604. self.favoriteMetadataPlain(metadata, url: url, completion: completion)
  605. } else {
  606. completion(errorCode, errorDescription)
  607. }
  608. }
  609. } else {
  610. favoriteMetadataPlain(metadata, url: url, completion: completion)
  611. }
  612. }
  613. @objc func favoriteMetadataPlain(_ metadata: tableMetadata, url: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  614. let fileName = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, activeUrl: url)!
  615. let favorite = !metadata.favorite
  616. NCCommunication.shared.setFavorite(fileName: fileName, favorite: favorite) { (account, errorCode, errorDescription) in
  617. if errorCode == 0 && metadata.account == account {
  618. NCManageDatabase.sharedInstance.setMetadataFavorite(ocId: metadata.ocId, favorite: favorite)
  619. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl])
  620. }
  621. self.NotificationPost(name: k_notificationCenter_favoriteFile, userInfo: ["metadata": metadata, "favorite": favorite, "errorCode": errorCode], errorDescription: errorDescription, completion: completion)
  622. }
  623. }
  624. //MARK: - WebDav Rename
  625. @objc func renameMetadata(_ metadata: tableMetadata, fileNameNew: String, url: String, viewController: UIViewController?, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  626. let isDirectoryEncrypted = CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account)
  627. let metadataLive = NCManageDatabase.sharedInstance.isLivePhoto(metadata: metadata)
  628. let fileNameNewLive = (fileNameNew as NSString).deletingPathExtension + ".mov"
  629. if isDirectoryEncrypted {
  630. #if !EXTENSION
  631. if metadataLive == nil {
  632. NCNetworkingE2EE.shared.renameMetadata(metadata, fileNameNew: fileNameNew, url: url, completion: completion)
  633. } else {
  634. NCNetworkingE2EE.shared.renameMetadata(metadataLive!, fileNameNew: fileNameNewLive, url: url) { (errorCode, errorDescription) in
  635. if errorCode == 0 {
  636. NCNetworkingE2EE.shared.renameMetadata(metadata, fileNameNew: fileNameNew, url: url, completion: completion)
  637. } else {
  638. completion(errorCode, errorDescription)
  639. }
  640. }
  641. }
  642. #endif
  643. } else {
  644. if metadataLive == nil {
  645. renameMetadataPlain(metadata, fileNameNew: fileNameNew, completion: completion)
  646. } else {
  647. renameMetadataPlain(metadataLive!, fileNameNew: fileNameNewLive) { (errorCode, errorDescription) in
  648. if errorCode == 0 {
  649. self.renameMetadataPlain(metadata, fileNameNew: fileNameNew, completion: completion)
  650. } else {
  651. completion(errorCode, errorDescription)
  652. }
  653. }
  654. }
  655. }
  656. }
  657. private func renameMetadataPlain(_ metadata: tableMetadata, fileNameNew: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  658. let permission = NCUtility.sharedInstance.permissionsContainsString(metadata.permissions, permissions: k_permission_can_rename)
  659. if !(metadata.permissions == "") && !permission {
  660. self.NotificationPost(name: k_notificationCenter_renameFile, userInfo: ["metadata": metadata, "errorCode": Int(k_CCErrorInternalError)], errorDescription: "_no_permission_modify_file_", completion: completion)
  661. return
  662. }
  663. guard let fileNameNew = CCUtility.removeForbiddenCharactersServer(fileNameNew) else {
  664. self.NotificationPost(name: k_notificationCenter_renameFile, userInfo: ["metadata": metadata, "errorCode": Int(0)], errorDescription: "", completion: completion)
  665. return
  666. }
  667. if fileNameNew.count == 0 || fileNameNew == metadata.fileNameView {
  668. self.NotificationPost(name: k_notificationCenter_renameFile, userInfo: ["metadata": metadata, "errorCode": Int(0)], errorDescription: "", completion: completion)
  669. return
  670. }
  671. let fileNamePath = metadata.serverUrl + "/" + metadata.fileName
  672. let fileNameToPath = metadata.serverUrl + "/" + fileNameNew
  673. NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: fileNamePath, serverUrlFileNameDestination: fileNameToPath, overwrite: false) { (account, errorCode, errorDescription) in
  674. if errorCode == 0 {
  675. NCManageDatabase.sharedInstance.renameMetadata(fileNameTo: fileNameNew, ocId: metadata.ocId)
  676. if metadata.directory {
  677. let serverUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  678. let serverUrlTo = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: fileNameNew)!
  679. if let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata.account, metadata.serverUrl)) {
  680. NCManageDatabase.sharedInstance.setDirectory(serverUrl: serverUrl, serverUrlTo: serverUrlTo, etag: "", ocId: nil, fileId: nil, encrypted: directory.e2eEncrypted, richWorkspace: nil, account: metadata.account)
  681. }
  682. } else {
  683. NCManageDatabase.sharedInstance.setLocalFile(ocId: metadata.ocId, date: nil, exifDate: nil, exifLatitude: nil, exifLongitude: nil, fileName: fileNameNew, etag: nil)
  684. // Move file system
  685. let atPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + metadata.fileName
  686. let toPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + fileNameNew
  687. let atPathPreview = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, fileNameView: metadata.fileName)!
  688. let toPathPreview = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, fileNameView: fileNameNew)!
  689. let atPathIcon = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileName)!
  690. let toPathIcon = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: fileNameNew)!
  691. do {
  692. try FileManager.default.moveItem(atPath: atPath, toPath: toPath)
  693. try FileManager.default.moveItem(atPath: atPathPreview, toPath: toPathPreview)
  694. try FileManager.default.moveItem(atPath: atPathIcon, toPath: toPathIcon)
  695. } catch { }
  696. }
  697. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl])
  698. }
  699. self.NotificationPost(name: k_notificationCenter_renameFile, userInfo: ["metadata": metadata, "errorCode": errorCode], errorDescription: errorDescription, completion: completion)
  700. }
  701. }
  702. //MARK: - WebDav Move
  703. @objc func moveMetadata(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  704. if let metadataLive = NCManageDatabase.sharedInstance.isLivePhoto(metadata: metadata) {
  705. moveMetadataPlain(metadataLive, serverUrlTo: serverUrlTo, overwrite: overwrite) { (errorCode, errorDescription) in
  706. if errorCode == 0 {
  707. self.moveMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  708. } else {
  709. completion(errorCode, errorDescription)
  710. }
  711. }
  712. } else {
  713. moveMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  714. }
  715. }
  716. @objc func moveMetadataPlain(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  717. let permission = NCUtility.sharedInstance.permissionsContainsString(metadata.permissions, permissions: k_permission_can_rename)
  718. if !(metadata.permissions == "") && !permission {
  719. self.NotificationPost(name: k_notificationCenter_renameFile, userInfo: ["metadata": metadata, "serverUrlTo": serverUrlTo, "errorCode": Int(k_CCErrorInternalError)], errorDescription: "_no_permission_modify_file_", completion: completion)
  720. return
  721. }
  722. let serverUrlFileNameSource = metadata.serverUrl + "/" + metadata.fileName
  723. let serverUrlFileNameDestination = serverUrlTo + "/" + metadata.fileName
  724. NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: overwrite) { (account, errorCode, errorDescription) in
  725. var metadataNew = tableMetadata()
  726. if errorCode == 0 {
  727. if metadata.directory {
  728. NCManageDatabase.sharedInstance.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName), account: account)
  729. }
  730. if let metadataMove = NCManageDatabase.sharedInstance.moveMetadata(ocId: metadata.ocId, serverUrlTo: serverUrlTo) {
  731. metadataNew = metadataMove
  732. }
  733. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":metadata.serverUrl])
  734. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":serverUrlTo])
  735. }
  736. self.NotificationPost(name: k_notificationCenter_moveFile, userInfo: ["metadata": metadata, "metadataNew": metadataNew, "errorCode": errorCode], errorDescription: errorDescription, completion: completion)
  737. }
  738. }
  739. //MARK: - WebDav Copy
  740. @objc func copyMetadata(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  741. if let metadataLive = NCManageDatabase.sharedInstance.isLivePhoto(metadata: metadata) {
  742. copyMetadataPlain(metadataLive, serverUrlTo: serverUrlTo, overwrite: overwrite) { (errorCode, errorDescription) in
  743. if errorCode == 0 {
  744. self.copyMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  745. } else {
  746. completion(errorCode, errorDescription)
  747. }
  748. }
  749. } else {
  750. copyMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  751. }
  752. }
  753. @objc func copyMetadataPlain(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  754. let permission = NCUtility.sharedInstance.permissionsContainsString(metadata.permissions, permissions: k_permission_can_rename)
  755. if !(metadata.permissions == "") && !permission {
  756. self.NotificationPost(name: k_notificationCenter_renameFile, userInfo: ["metadata": metadata, "serverUrlTo": serverUrlTo, "errorCode": Int(k_CCErrorInternalError)], errorDescription: "_no_permission_modify_file_", completion: completion)
  757. return
  758. }
  759. let serverUrlFileNameSource = metadata.serverUrl + "/" + metadata.fileName
  760. let serverUrlFileNameDestination = serverUrlTo + "/" + metadata.fileName
  761. NCCommunication.shared.copyFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: overwrite) { (account, errorCode, errorDescription) in
  762. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":serverUrlTo])
  763. self.NotificationPost(name: k_notificationCenter_copyFile, userInfo: ["metadata": metadata, "errorCode": errorCode], errorDescription: errorDescription, completion: completion)
  764. }
  765. }
  766. //MARK: - Notification Post
  767. private func NotificationPost(name: String, userInfo: [AnyHashable : Any], errorDescription: Any?, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  768. var userInfo = userInfo
  769. DispatchQueue.main.async {
  770. if errorDescription == nil { userInfo["errorDescription"] = "" }
  771. else { userInfo["errorDescription"] = NSLocalizedString(errorDescription as! String, comment: "") }
  772. NotificationCenter.default.postOnMainThread(name: name, userInfo: userInfo)
  773. completion(userInfo["errorCode"] as! Int, userInfo["errorDescription"] as! String)
  774. }
  775. }
  776. }