NCNetworking.swift 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  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(ocId: String, serverUrl:String, fileNameView: String) {
  136. guard let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView) else { return }
  137. if let request = downloadRequest[fileNameLocalPath] {
  138. request.cancel()
  139. } else {
  140. NCManageDatabase.sharedInstance.setMetadataSession(ocId: ocId, session: "", sessionError: "", sessionSelector: "", sessionTaskIdentifier: 0, status: Int(k_metadataStatusNormal))
  141. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["ocId":ocId, "serverUrl":serverUrl])
  142. }
  143. }
  144. @objc func download(ocId: String, selector: String, setFavorite: Bool = false, completion: @escaping (_ errorCode: Int)->()) {
  145. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@", ocId), freeze: true) else {
  146. completion(Int(k_CCErrorInternalError))
  147. return
  148. }
  149. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  150. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileName)!
  151. if metadata.status == Int(k_metadataStatusInDownload) || metadata.status == Int(k_metadataStatusDownloading) { return }
  152. NCManageDatabase.sharedInstance.setMetadataSession(ocId: ocId, session: NCCommunicationCommon.shared.sessionIdentifierDownload, sessionError: "", sessionSelector: selector, sessionTaskIdentifier: 0, status: Int(k_metadataStatusInDownload))
  153. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, object: nil, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl])
  154. NCCommunication.shared.download(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, requestHandler: { (request) in
  155. self.downloadRequest[fileNameLocalPath] = request
  156. NCManageDatabase.sharedInstance.setMetadataSession(ocId: ocId, status: Int(k_metadataStatusDownloading))
  157. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_downloadFileStart, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl, "account":metadata.account])
  158. }, progressHandler: { (progress) in
  159. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_progressTask, object: nil, userInfo: ["account":metadata.account, "ocId":metadata.ocId, "serverUrl":metadata.serverUrl, "status":NSNumber(value: k_metadataStatusInDownload), "progress":NSNumber(value: progress.fractionCompleted), "totalBytes":NSNumber(value: progress.totalUnitCount), "totalBytesExpected":NSNumber(value: progress.completedUnitCount)])
  160. }) { (account, etag, date, length, error, errorCode, errorDescription) in
  161. if error?.isExplicitlyCancelledError ?? false {
  162. NCManageDatabase.sharedInstance.setMetadataSession(ocId: ocId, session: "", sessionError: "", sessionSelector: selector, sessionTaskIdentifier: 0, status: Int(k_metadataStatusNormal))
  163. } else if errorCode == 0 {
  164. NCManageDatabase.sharedInstance.setMetadataSession(ocId: ocId, session: "", sessionError: "", sessionSelector: selector, sessionTaskIdentifier: 0, status: Int(k_metadataStatusNormal), etag: etag, setFavorite: setFavorite)
  165. NCManageDatabase.sharedInstance.addLocalFile(metadata: metadata)
  166. #if !EXTENSION
  167. if let result = NCManageDatabase.sharedInstance.getE2eEncryption(predicate: NSPredicate(format: "fileNameIdentifier == %@ AND serverUrl == %@", metadata.fileName, metadata.serverUrl)) {
  168. NCEndToEndEncryption.sharedManager()?.decryptFileName(metadata.fileName, fileNameView: metadata.fileNameView, ocId: metadata.ocId, key: result.key, initializationVector: result.initializationVector, authenticationTag: result.authenticationTag)
  169. }
  170. #endif
  171. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_downloadedFile, userInfo: ["metadata":metadata, "selector":selector, "errorCode":errorCode, "errorDescription":errorDescription])
  172. } else {
  173. NCManageDatabase.sharedInstance.setMetadataSession(ocId: ocId, session: "", sessionError: errorDescription, sessionSelector: selector, sessionTaskIdentifier: 0, status: Int(k_metadataStatusDownloadError))
  174. #if !EXTENSION
  175. if errorCode == 401 || errorCode == 403 {
  176. NCNetworkingCheckRemoteUser.shared.checkRemoteUser(account: metadata.account)
  177. } else if errorCode == Int(CFNetworkErrors.cfurlErrorServerCertificateUntrusted.rawValue) {
  178. CCUtility.setCertificateError(metadata.account, error: true)
  179. }
  180. #endif
  181. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_downloadedFile, userInfo: ["metadata":metadata, "selector":selector, "errorCode":errorCode, "errorDescription":errorDescription])
  182. }
  183. self.downloadRequest[fileNameLocalPath] = nil
  184. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl])
  185. completion(errorCode)
  186. }
  187. }
  188. //MARK: - Upload
  189. @objc func cancelUpload(ocId: String) {
  190. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@", ocId), freeze: true) else { return }
  191. guard let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) else { return }
  192. if let request = uploadRequest[fileNameLocalPath] {
  193. request.cancel()
  194. } else {
  195. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  196. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  197. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":metadata.serverUrl])
  198. }
  199. }
  200. @objc func upload(metadata: tableMetadata, background: Bool = true, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  201. var metadataForUpload: tableMetadata?
  202. var e2eEncrypted = false
  203. let internalContenType = NCCommunicationCommon.shared.getInternalContenType(fileName: metadata.fileNameView, contentType: metadata.contentType, directory: false)
  204. var fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  205. guard let account = NCManageDatabase.sharedInstance.getAccount(predicate: NSPredicate(format: "account == %@", metadata.account)) else {
  206. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_uploadedFile, userInfo: ["metadata":metadata, "errorCode":k_CCErrorInternalError, "errorDescription":"Internal error"])
  207. completion(Int(k_CCErrorInternalError), "Internal error")
  208. return
  209. }
  210. if CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account) {
  211. e2eEncrypted = true
  212. }
  213. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  214. metadata.contentType = internalContenType.contentType
  215. metadata.iconName = internalContenType.iconName
  216. metadata.typeFile = internalContenType.typeFile
  217. if let date = NCUtilityFileSystem.shared.getFileCreationDate(filePath: fileNameLocalPath) {
  218. metadata.creationDate = date
  219. }
  220. if let date = NCUtilityFileSystem.shared.getFileModificationDate(filePath: fileNameLocalPath) {
  221. metadata.date = date
  222. }
  223. metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNameLocalPath)
  224. if metadata.size > Double(k_max_filesize_E2EE) {
  225. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_uploadedFile, userInfo: ["metadata":metadata, "errorCode":k_CCErrorInternalError, "errorDescription":"E2E Error file too big"])
  226. completion(Int(k_CCErrorInternalError), "E2E Error file too big")
  227. return
  228. }
  229. metadataForUpload = NCManageDatabase.sharedInstance.addMetadata(metadata)
  230. if e2eEncrypted {
  231. #if !EXTENSION
  232. NCNetworkingE2EE.shared.upload(metadata: metadataForUpload!, account: account, completion: completion)
  233. #endif
  234. } else if background {
  235. uploadFileInBackground(ocId: metadataForUpload!.ocId, account: account, completion: completion)
  236. } else {
  237. uploadFile(metadata: metadataForUpload!, account: account, completion: completion)
  238. }
  239. } else {
  240. CCUtility.extractImageVideoFromAssetLocalIdentifier(forUpload: metadata, notification: true) { (extractMetadata, fileNamePath) in
  241. guard let extractMetadata = extractMetadata else {
  242. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  243. completion(Int(k_CCErrorInternalError), "Internal error")
  244. return
  245. }
  246. fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(extractMetadata.ocId, fileNameView: extractMetadata.fileNameView)
  247. CCUtility.moveFile(atPath: fileNamePath, toPath: fileNameLocalPath)
  248. if e2eEncrypted && (extractMetadata.size > Double(k_max_filesize_E2EE)) {
  249. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_uploadedFile, userInfo: ["metadata":metadata, "errorCode":k_CCErrorInternalError, "errorDescription":"E2E Error file too big"])
  250. completion(Int(k_CCErrorInternalError), "E2E Error file too big")
  251. return
  252. }
  253. metadataForUpload = NCManageDatabase.sharedInstance.addMetadata(extractMetadata)
  254. if e2eEncrypted {
  255. #if !EXTENSION
  256. NCNetworkingE2EE.shared.upload(metadata: metadataForUpload!, account: account, completion: completion)
  257. #endif
  258. } else if background {
  259. self.uploadFileInBackground(ocId: metadataForUpload!.ocId, account: account, completion: completion)
  260. } else {
  261. self.uploadFile(metadata: metadataForUpload!, account: account, completion: completion)
  262. }
  263. }
  264. }
  265. }
  266. //
  267. private func uploadFile(metadata: tableMetadata, account: tableAccount, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  268. completion(0, "")
  269. }
  270. private func uploadFileInBackground(ocId: String, account: tableAccount, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  271. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@", ocId), freeze: true) else {
  272. completion(0, "")
  273. return
  274. }
  275. var session: URLSession?
  276. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  277. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  278. if metadata.session == NCCommunicationCommon.shared.sessionIdentifierBackground || metadata.session == NCCommunicationCommon.shared.sessionIdentifierExtension {
  279. session = NCCommunicationBackground.shared.sessionManagerTransfer
  280. } else if metadata.session == NCCommunicationCommon.shared.sessionIdentifierBackgroundWWan {
  281. session = NCCommunicationBackground.shared.sessionManagerTransferWWan
  282. }
  283. if let task = NCCommunicationBackground.shared.upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, dateCreationFile: metadata.creationDate as Date, dateModificationFile: metadata.date as Date, description: "", session: session!) {
  284. NCManageDatabase.sharedInstance.setMetadataSession(ocId: ocId, sessionError: "", sessionTaskIdentifier: task.taskIdentifier, status: Int(k_metadataStatusUploading))
  285. #if !EXTENSION
  286. CCGraphics.createNewImage(from: metadata.fileNameView, ocId: metadata.ocId, typeFile: metadata.typeFile)
  287. #endif
  288. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_uploadFileStart, userInfo: ["ocId":metadata.ocId, "task":task, "serverUrl":metadata.serverUrl, "account":metadata.account])
  289. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl])
  290. completion(0, "")
  291. } else {
  292. completion(Int(k_CCErrorInternalError), "task null")
  293. }
  294. }
  295. func uploadProgress(_ progress: Double, totalBytes: Int64, totalBytesExpected: Int64, fileName: String, serverUrl: String, session: URLSession, task: URLSessionTask) {
  296. delegate?.uploadProgress?(progress, totalBytes: totalBytes, totalBytesExpected: totalBytesExpected, fileName: fileName, serverUrl: serverUrl, session: session, task: task)
  297. if let metadata = NCManageDatabase.sharedInstance.getMetadataInSessionFromFileName(fileName, serverUrl: serverUrl, taskIdentifier: task.taskIdentifier, freeze: true) {
  298. 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)])
  299. }
  300. }
  301. func uploadComplete(fileName: String, serverUrl: String, ocId: String?, etag: String?, date: NSDate?, size: Int64, description: String?, task: URLSessionTask, errorCode: Int, errorDescription: String) {
  302. if delegate != nil {
  303. delegate?.uploadComplete?(fileName: fileName, serverUrl: serverUrl, ocId: ocId, etag: etag, date: date, size:size, description: description, task: task, errorCode: errorCode, errorDescription: errorDescription)
  304. } else {
  305. guard var metadata = NCManageDatabase.sharedInstance.getMetadataInSessionFromFileName(fileName, serverUrl: serverUrl, taskIdentifier: task.taskIdentifier, freeze: false) else {
  306. return
  307. }
  308. guard let tableAccount = NCManageDatabase.sharedInstance.getAccount(predicate: NSPredicate(format: "account == %@", metadata.account)) else { return }
  309. if errorCode == 0 && ocId != nil {
  310. CCUtility.moveFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId), toPath: CCUtility.getDirectoryProviderStorageOcId(ocId))
  311. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  312. metadata.uploadDate = date ?? NSDate()
  313. metadata.etag = etag ?? ""
  314. metadata.ocId = ocId!
  315. metadata.session = ""
  316. metadata.sessionError = ""
  317. metadata.sessionTaskIdentifier = 0
  318. metadata.status = Int(k_metadataStatusNormal)
  319. // Delete Asset on Photos album
  320. if tableAccount.autoUploadDeleteAssetLocalIdentifier && metadata.assetLocalIdentifier != "" && metadata.sessionSelector == selectorUploadAutoUpload {
  321. metadata.deleteAssetLocalIdentifier = true;
  322. }
  323. if let result = NCManageDatabase.sharedInstance.addMetadata(metadata) { metadata = result }
  324. if CCUtility.getDisableLocalCacheAfterUpload() {
  325. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  326. } else {
  327. NCManageDatabase.sharedInstance.addLocalFile(metadata: metadata)
  328. }
  329. #if !EXTENSION
  330. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_uploadedFile, userInfo: ["metadata":metadata, "errorCode":errorCode, "errorDescription":""])
  331. #endif
  332. } else if errorCode == NSURLErrorCancelled {
  333. if metadata.status == k_metadataStatusUploadForcedStart {
  334. NCManageDatabase.sharedInstance.setMetadataSession(ocId: ocId!, session: NCCommunicationCommon.shared.sessionIdentifierBackground, sessionError: "", sessionTaskIdentifier: 0, status: Int(k_metadataStatusInUpload))
  335. NCNetworking.shared.upload(metadata: metadata) { (_, _) in }
  336. } else {
  337. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  338. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  339. }
  340. } else if errorCode == 401 || errorCode == 403 {
  341. #if !EXTENSION
  342. NCNetworkingCheckRemoteUser.shared.checkRemoteUser(account: metadata.account)
  343. #endif
  344. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  345. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  346. } else if errorCode == Int(CFNetworkErrors.cfurlErrorServerCertificateUntrusted.rawValue) {
  347. CCUtility.setCertificateError(metadata.account, error: true)
  348. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  349. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  350. } else {
  351. NCManageDatabase.sharedInstance.setMetadataSession(ocId: ocId!, session: "", sessionError: errorDescription, sessionTaskIdentifier: 0, status: Int(k_metadataStatusUploadError))
  352. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_uploadedFile, userInfo: ["metadata":metadata, "errorCode":errorCode, "errorDescription":errorDescription])
  353. if let result = NCManageDatabase.sharedInstance.addMetadata(metadata) { metadata = result }
  354. }
  355. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl])
  356. }
  357. }
  358. //MARK: - Download / Upload
  359. @objc func verifyTransfer() {
  360. var session: URLSession?
  361. // download
  362. if let metadatas = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "status == %d", Int(k_metadataStatusDownloading)), sorted: nil, ascending: true) {
  363. for metadata in metadatas {
  364. guard let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) else { continue }
  365. let request = downloadRequest[fileNameLocalPath]
  366. if request == nil {
  367. metadata.session = ""
  368. metadata.sessionError = ""
  369. metadata.status = Int(k_metadataStatusNormal)
  370. NCManageDatabase.sharedInstance.addMetadata(metadata)
  371. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl])
  372. }
  373. }
  374. }
  375. // upload
  376. if let metadatas = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "session == %@ AND status == %d", NCCommunicationCommon.shared.sessionIdentifierUpload ,Int(k_metadataStatusUploading)), sorted: nil, ascending: true) {
  377. for metadata in metadatas {
  378. guard let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) else { continue }
  379. let request = uploadRequest[fileNameLocalPath]
  380. if request == nil {
  381. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  382. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  383. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":metadata.serverUrl])
  384. }
  385. }
  386. }
  387. // k_metadataStatusUploading (BACKGROUND)
  388. let sessionBackground = NCCommunicationCommon.shared.sessionIdentifierBackground
  389. let sessionBackgroundWWan = NCCommunicationCommon.shared.sessionIdentifierBackgroundWWan
  390. if let metadatas = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "(session == %@ OR session == %@) AND status == %d", sessionBackground, sessionBackgroundWWan, k_metadataStatusUploading), sorted: nil, ascending: true) {
  391. for metadata in metadatas {
  392. if metadata.session == NCCommunicationCommon.shared.sessionIdentifierBackground {
  393. session = NCCommunicationBackground.shared.sessionManagerTransfer
  394. } else if metadata.session == NCCommunicationCommon.shared.sessionIdentifierBackgroundWWan {
  395. session = NCCommunicationBackground.shared.sessionManagerTransferWWan
  396. } else if metadata.session == NCCommunicationCommon.shared.sessionIdentifierExtension {
  397. session = NCCommunicationBackground.shared.sessionManagerTransferExtension
  398. }
  399. var findTask = false
  400. session?.getAllTasks(completionHandler: { (tasks) in
  401. for task in tasks {
  402. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  403. findTask = true
  404. }
  405. }
  406. if !findTask {
  407. DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
  408. if let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@ AND status == %d", metadata.ocId, k_metadataStatusUploading)) {
  409. metadata.session = NCCommunicationCommon.shared.sessionIdentifierBackground
  410. metadata.sessionError = ""
  411. metadata.sessionTaskIdentifier = 0
  412. metadata.status = Int(k_metadataStatusWaitUpload)
  413. NCManageDatabase.sharedInstance.addMetadata(metadata)
  414. }
  415. }
  416. }
  417. })
  418. }
  419. }
  420. // verify k_metadataStatusInUpload (BACKGROUND)
  421. 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) {
  422. for metadata in metadatas {
  423. DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
  424. if let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@ AND status == %d AND sessionTaskIdentifier == 0", metadata.ocId, k_metadataStatusInUpload)) {
  425. metadata.session = NCCommunicationCommon.shared.sessionIdentifierBackground
  426. metadata.sessionError = ""
  427. metadata.sessionTaskIdentifier = 0
  428. metadata.status = Int(k_metadataStatusWaitUpload)
  429. NCManageDatabase.sharedInstance.addMetadata(metadata)
  430. }
  431. }
  432. }
  433. }
  434. }
  435. //MARK: - WebDav Read file, folder
  436. @objc func readFolder(serverUrl: String, account: String, completion: @escaping (_ account: String, _ metadataFolder: tableMetadata?, _ metadatas: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String)->()) {
  437. NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrl, depth: "1", showHiddenFiles: CCUtility.getShowHiddenFiles()) { (account, files, responseData, errorCode, errorDescription) in
  438. if errorCode == 0 && files != nil {
  439. NCManageDatabase.sharedInstance.convertNCCommunicationFilesToMetadatas(files!, useMetadataFolder: true, account: account) { (metadataFolder, metadatasFolder, metadatas) in
  440. // Add directory
  441. 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)
  442. // Add other directories
  443. for metadata in metadatasFolder {
  444. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  445. 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)
  446. }
  447. // Save status transfer metadata
  448. 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)
  449. 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)
  450. // Delete metadata
  451. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND status == %d", account, serverUrl, k_metadataStatusNormal))
  452. // Add metadata
  453. let metadataFolderInserted = NCManageDatabase.sharedInstance.addMetadata(metadataFolder)
  454. let metadatasInserted = NCManageDatabase.sharedInstance.addMetadatas(metadatas)
  455. if metadatasInDownload != nil {
  456. NCManageDatabase.sharedInstance.addMetadatas(metadatasInDownload!)
  457. }
  458. if metadatasInUpload != nil {
  459. NCManageDatabase.sharedInstance.addMetadatas(metadatasInUpload!)
  460. }
  461. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":serverUrl])
  462. completion(account, metadataFolderInserted, metadatasInserted, errorCode, "")
  463. }
  464. } else {
  465. #if !EXTENSION
  466. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  467. #endif
  468. completion(account, nil, nil, errorCode, errorDescription)
  469. }
  470. }
  471. }
  472. @objc func readFile(serverUrlFileName: String, account: String, completion: @escaping (_ account: String, _ metadata: tableMetadata?, _ errorCode: Int, _ errorDescription: String)->()) {
  473. NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrlFileName, depth: "0", showHiddenFiles: CCUtility.getShowHiddenFiles()) { (account, files, responseData, errorCode, errorDescription) in
  474. if errorCode == 0 && files != nil {
  475. if files?.count ?? 0 == 1 {
  476. let file = files![0]
  477. let isEncrypted = CCUtility.isFolderEncrypted(file.serverUrl, e2eEncrypted:file.e2eEncrypted, account: account)
  478. let metadata = NCManageDatabase.sharedInstance.convertNCFileToMetadata(file, isEncrypted: isEncrypted, account: account)
  479. completion(account, metadata, errorCode, "")
  480. } else {
  481. completion(account, nil, errorCode, "")
  482. }
  483. } else {
  484. completion(account, nil, errorCode, errorDescription)
  485. }
  486. }
  487. }
  488. //MARK: - WebDav Create Folder
  489. @objc func createFolder(fileName: String, serverUrl: String, account: String, url: String, overwrite: Bool = false, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  490. let isDirectoryEncrypted = CCUtility.isFolderEncrypted(serverUrl, e2eEncrypted: false, account: account)
  491. if isDirectoryEncrypted {
  492. #if !EXTENSION
  493. NCNetworkingE2EE.shared.createFolder(fileName: fileName, serverUrl: serverUrl, account: account, url: url, completion: completion)
  494. #endif
  495. } else {
  496. createFolderPlain(fileName: fileName, serverUrl: serverUrl, account: account, url: url, overwrite: overwrite, completion: completion)
  497. }
  498. }
  499. @objc func createFolderPlain(fileName: String, serverUrl: String, account: String, url: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  500. var fileNameFolder = CCUtility.removeForbiddenCharactersServer(fileName)!
  501. if (!overwrite) {
  502. fileNameFolder = NCUtility.sharedInstance.createFileName(fileNameFolder, serverUrl: serverUrl, account: account)
  503. }
  504. if fileNameFolder.count == 0 {
  505. self.NotificationPost(name: k_notificationCenter_createFolder, userInfo: ["fileName": fileName, "serverUrl": serverUrl, "errorCode": Int(0)], errorDescription: "", completion: completion)
  506. return
  507. }
  508. let fileNameFolderUrl = serverUrl + "/" + fileNameFolder
  509. NCCommunication.shared.createFolder(fileNameFolderUrl) { (account, ocId, date, errorCode, errorDescription) in
  510. if errorCode == 0 {
  511. self.readFile(serverUrlFileName: fileNameFolderUrl, account: account) { (account, metadataFolder, errorCode, errorDescription) in
  512. if errorCode == 0 {
  513. // Add Metadata
  514. NCManageDatabase.sharedInstance.addMetadata(metadataFolder!)
  515. // Add folder
  516. 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)
  517. self.NotificationPost(name: k_notificationCenter_createFolder, userInfo: ["fileName": fileName, "serverUrl": serverUrl, "errorCode": errorCode], errorDescription: errorDescription, completion: completion)
  518. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":serverUrl])
  519. } else {
  520. self.NotificationPost(name: k_notificationCenter_createFolder, userInfo: ["fileName": fileName, "serverUrl": serverUrl, "errorCode": errorCode], errorDescription: errorDescription, completion: completion)
  521. }
  522. }
  523. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":serverUrl])
  524. } else if errorCode == 405 && overwrite {
  525. self.NotificationPost(name: k_notificationCenter_createFolder, userInfo: ["fileName": fileName, "serverUrl": serverUrl, "errorCode": 0], errorDescription: "", completion: completion)
  526. } else {
  527. self.NotificationPost(name: k_notificationCenter_createFolder, userInfo: ["fileName": fileName, "serverUrl": serverUrl, "errorCode": errorCode], errorDescription: errorDescription, completion: completion)
  528. }
  529. }
  530. }
  531. //MARK: - WebDav Delete
  532. @objc func deleteMetadata(_ metadata: tableMetadata, account: String, url: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  533. let isDirectoryEncrypted = CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account)
  534. let metadataLive = NCManageDatabase.sharedInstance.isLivePhoto(metadata: metadata)
  535. if isDirectoryEncrypted {
  536. #if !EXTENSION
  537. if metadataLive == nil {
  538. NCNetworkingE2EE.shared.deleteMetadata(metadata, url: url, completion: completion)
  539. } else {
  540. NCNetworkingE2EE.shared.deleteMetadata(metadataLive!, url: url) { (errorCode, errorDescription) in
  541. if errorCode == 0 {
  542. NCNetworkingE2EE.shared.deleteMetadata(metadata, url: url, completion: completion)
  543. } else {
  544. completion(errorCode, errorDescription)
  545. }
  546. }
  547. }
  548. #endif
  549. } else {
  550. if metadataLive == nil {
  551. self.deleteMetadataPlain(metadata, addCustomHeaders: nil, completion: completion)
  552. } else {
  553. self.deleteMetadataPlain(metadataLive!, addCustomHeaders: nil) { (errorCode, errorDescription) in
  554. if errorCode == 0 {
  555. self.deleteMetadataPlain(metadata, addCustomHeaders: nil, completion: completion)
  556. } else {
  557. completion(errorCode, errorDescription)
  558. }
  559. }
  560. }
  561. }
  562. }
  563. func deleteMetadataPlain(_ metadata: tableMetadata, addCustomHeaders: [String: String]?, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  564. // verify permission
  565. let permission = NCUtility.sharedInstance.permissionsContainsString(metadata.permissions, permissions: k_permission_can_delete)
  566. if metadata.permissions != "" && permission == false {
  567. self.NotificationPost(name: k_notificationCenter_deleteFile, userInfo: ["metadata": metadata, "errorCode": Int(k_CCErrorNotPermission)], errorDescription: "_no_permission_delete_file_", completion: completion)
  568. return
  569. }
  570. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  571. NCCommunication.shared.deleteFileOrFolder(serverUrlFileName, customUserAgent: nil, addCustomHeaders: addCustomHeaders) { (account, errorCode, errorDescription) in
  572. if errorCode == 0 || errorCode == 404 {
  573. do {
  574. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  575. } catch { }
  576. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  577. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  578. if metadata.directory {
  579. NCManageDatabase.sharedInstance.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName), account: metadata.account)
  580. }
  581. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":metadata.serverUrl])
  582. }
  583. self.NotificationPost(name: k_notificationCenter_deleteFile, userInfo: ["metadata": metadata, "errorCode": errorCode], errorDescription: errorDescription, completion: completion)
  584. }
  585. }
  586. //MARK: - WebDav Favorite
  587. @objc func favoriteMetadata(_ metadata: tableMetadata, url: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  588. if let metadataLive = NCManageDatabase.sharedInstance.isLivePhoto(metadata: metadata) {
  589. favoriteMetadataPlain(metadataLive, url: url) { (errorCode, errorDescription) in
  590. if errorCode == 0 {
  591. self.favoriteMetadataPlain(metadata, url: url, completion: completion)
  592. } else {
  593. completion(errorCode, errorDescription)
  594. }
  595. }
  596. } else {
  597. favoriteMetadataPlain(metadata, url: url, completion: completion)
  598. }
  599. }
  600. @objc func favoriteMetadataPlain(_ metadata: tableMetadata, url: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  601. let fileName = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, activeUrl: url)!
  602. let favorite = !metadata.favorite
  603. NCCommunication.shared.setFavorite(fileName: fileName, favorite: favorite) { (account, errorCode, errorDescription) in
  604. if errorCode == 0 && metadata.account == account {
  605. NCManageDatabase.sharedInstance.setMetadataFavorite(ocId: metadata.ocId, favorite: favorite)
  606. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl])
  607. }
  608. self.NotificationPost(name: k_notificationCenter_favoriteFile, userInfo: ["metadata": metadata, "favorite": favorite, "errorCode": errorCode], errorDescription: errorDescription, completion: completion)
  609. }
  610. }
  611. //MARK: - WebDav Rename
  612. @objc func renameMetadata(_ metadata: tableMetadata, fileNameNew: String, url: String, viewController: UIViewController?, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  613. let isDirectoryEncrypted = CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account)
  614. let metadataLive = NCManageDatabase.sharedInstance.isLivePhoto(metadata: metadata)
  615. let fileNameNewLive = (fileNameNew as NSString).deletingPathExtension + ".mov"
  616. if isDirectoryEncrypted {
  617. #if !EXTENSION
  618. if metadataLive == nil {
  619. NCNetworkingE2EE.shared.renameMetadata(metadata, fileNameNew: fileNameNew, url: url, completion: completion)
  620. } else {
  621. NCNetworkingE2EE.shared.renameMetadata(metadataLive!, fileNameNew: fileNameNewLive, url: url) { (errorCode, errorDescription) in
  622. if errorCode == 0 {
  623. NCNetworkingE2EE.shared.renameMetadata(metadata, fileNameNew: fileNameNew, url: url, completion: completion)
  624. } else {
  625. completion(errorCode, errorDescription)
  626. }
  627. }
  628. }
  629. #endif
  630. } else {
  631. if metadataLive == nil {
  632. renameMetadataPlain(metadata, fileNameNew: fileNameNew, completion: completion)
  633. } else {
  634. renameMetadataPlain(metadataLive!, fileNameNew: fileNameNewLive) { (errorCode, errorDescription) in
  635. if errorCode == 0 {
  636. self.renameMetadataPlain(metadata, fileNameNew: fileNameNew, completion: completion)
  637. } else {
  638. completion(errorCode, errorDescription)
  639. }
  640. }
  641. }
  642. }
  643. }
  644. private func renameMetadataPlain(_ metadata: tableMetadata, fileNameNew: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  645. let permission = NCUtility.sharedInstance.permissionsContainsString(metadata.permissions, permissions: k_permission_can_rename)
  646. if !(metadata.permissions == "") && !permission {
  647. self.NotificationPost(name: k_notificationCenter_renameFile, userInfo: ["metadata": metadata, "errorCode": Int(k_CCErrorInternalError)], errorDescription: "_no_permission_modify_file_", completion: completion)
  648. return
  649. }
  650. guard let fileNameNew = CCUtility.removeForbiddenCharactersServer(fileNameNew) else {
  651. self.NotificationPost(name: k_notificationCenter_renameFile, userInfo: ["metadata": metadata, "errorCode": Int(0)], errorDescription: "", completion: completion)
  652. return
  653. }
  654. if fileNameNew.count == 0 || fileNameNew == metadata.fileNameView {
  655. self.NotificationPost(name: k_notificationCenter_renameFile, userInfo: ["metadata": metadata, "errorCode": Int(0)], errorDescription: "", completion: completion)
  656. return
  657. }
  658. let fileNamePath = metadata.serverUrl + "/" + metadata.fileName
  659. let fileNameToPath = metadata.serverUrl + "/" + fileNameNew
  660. NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: fileNamePath, serverUrlFileNameDestination: fileNameToPath, overwrite: false) { (account, errorCode, errorDescription) in
  661. if errorCode == 0 {
  662. NCManageDatabase.sharedInstance.renameMetadata(fileNameTo: fileNameNew, ocId: metadata.ocId)
  663. if metadata.directory {
  664. let serverUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  665. let serverUrlTo = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: fileNameNew)!
  666. if let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata.account, metadata.serverUrl)) {
  667. NCManageDatabase.sharedInstance.setDirectory(serverUrl: serverUrl, serverUrlTo: serverUrlTo, etag: "", ocId: nil, fileId: nil, encrypted: directory.e2eEncrypted, richWorkspace: nil, account: metadata.account)
  668. }
  669. } else {
  670. NCManageDatabase.sharedInstance.setLocalFile(ocId: metadata.ocId, date: nil, exifDate: nil, exifLatitude: nil, exifLongitude: nil, fileName: fileNameNew, etag: nil)
  671. // Move file system
  672. let atPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + metadata.fileName
  673. let toPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + fileNameNew
  674. let atPathPreview = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, fileNameView: metadata.fileName)!
  675. let toPathPreview = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, fileNameView: fileNameNew)!
  676. let atPathIcon = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileName)!
  677. let toPathIcon = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: fileNameNew)!
  678. do {
  679. try FileManager.default.moveItem(atPath: atPath, toPath: toPath)
  680. try FileManager.default.moveItem(atPath: atPathPreview, toPath: toPathPreview)
  681. try FileManager.default.moveItem(atPath: atPathIcon, toPath: toPathIcon)
  682. } catch { }
  683. }
  684. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl])
  685. }
  686. self.NotificationPost(name: k_notificationCenter_renameFile, userInfo: ["metadata": metadata, "errorCode": errorCode], errorDescription: errorDescription, completion: completion)
  687. }
  688. }
  689. //MARK: - WebDav Move
  690. @objc func moveMetadata(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  691. if let metadataLive = NCManageDatabase.sharedInstance.isLivePhoto(metadata: metadata) {
  692. moveMetadataPlain(metadataLive, serverUrlTo: serverUrlTo, overwrite: overwrite) { (errorCode, errorDescription) in
  693. if errorCode == 0 {
  694. self.moveMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  695. } else {
  696. completion(errorCode, errorDescription)
  697. }
  698. }
  699. } else {
  700. moveMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  701. }
  702. }
  703. @objc func moveMetadataPlain(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  704. let permission = NCUtility.sharedInstance.permissionsContainsString(metadata.permissions, permissions: k_permission_can_rename)
  705. if !(metadata.permissions == "") && !permission {
  706. self.NotificationPost(name: k_notificationCenter_renameFile, userInfo: ["metadata": metadata, "serverUrlTo": serverUrlTo, "errorCode": Int(k_CCErrorInternalError)], errorDescription: "_no_permission_modify_file_", completion: completion)
  707. return
  708. }
  709. let serverUrlFileNameSource = metadata.serverUrl + "/" + metadata.fileName
  710. let serverUrlFileNameDestination = serverUrlTo + "/" + metadata.fileName
  711. NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: overwrite) { (account, errorCode, errorDescription) in
  712. var metadataNew = tableMetadata()
  713. if errorCode == 0 {
  714. if metadata.directory {
  715. NCManageDatabase.sharedInstance.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName), account: account)
  716. }
  717. if let metadataMove = NCManageDatabase.sharedInstance.moveMetadata(ocId: metadata.ocId, serverUrlTo: serverUrlTo) {
  718. metadataNew = metadataMove
  719. }
  720. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":metadata.serverUrl])
  721. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":serverUrlTo])
  722. }
  723. self.NotificationPost(name: k_notificationCenter_moveFile, userInfo: ["metadata": metadata, "metadataNew": metadataNew, "errorCode": errorCode], errorDescription: errorDescription, completion: completion)
  724. }
  725. }
  726. //MARK: - WebDav Copy
  727. @objc func copyMetadata(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  728. if let metadataLive = NCManageDatabase.sharedInstance.isLivePhoto(metadata: metadata) {
  729. copyMetadataPlain(metadataLive, serverUrlTo: serverUrlTo, overwrite: overwrite) { (errorCode, errorDescription) in
  730. if errorCode == 0 {
  731. self.copyMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  732. } else {
  733. completion(errorCode, errorDescription)
  734. }
  735. }
  736. } else {
  737. copyMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  738. }
  739. }
  740. @objc func copyMetadataPlain(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  741. let permission = NCUtility.sharedInstance.permissionsContainsString(metadata.permissions, permissions: k_permission_can_rename)
  742. if !(metadata.permissions == "") && !permission {
  743. self.NotificationPost(name: k_notificationCenter_renameFile, userInfo: ["metadata": metadata, "serverUrlTo": serverUrlTo, "errorCode": Int(k_CCErrorInternalError)], errorDescription: "_no_permission_modify_file_", completion: completion)
  744. return
  745. }
  746. let serverUrlFileNameSource = metadata.serverUrl + "/" + metadata.fileName
  747. let serverUrlFileNameDestination = serverUrlTo + "/" + metadata.fileName
  748. NCCommunication.shared.copyFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: overwrite) { (account, errorCode, errorDescription) in
  749. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":serverUrlTo])
  750. self.NotificationPost(name: k_notificationCenter_copyFile, userInfo: ["metadata": metadata, "errorCode": errorCode], errorDescription: errorDescription, completion: completion)
  751. }
  752. }
  753. //MARK: - Notification Post
  754. private func NotificationPost(name: String, userInfo: [AnyHashable : Any], errorDescription: Any?, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  755. var userInfo = userInfo
  756. DispatchQueue.main.async {
  757. if errorDescription == nil { userInfo["errorDescription"] = "" }
  758. else { userInfo["errorDescription"] = NSLocalizedString(errorDescription as! String, comment: "") }
  759. NotificationCenter.default.postOnMainThread(name: name, userInfo: userInfo)
  760. completion(userInfo["errorCode"] as! Int, userInfo["errorDescription"] as! String)
  761. }
  762. }
  763. }