NCNetworkingE2EEUpload.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. //
  2. // NCNetworkingE2EEUpload.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 09/11/22.
  6. // Copyright © 2022 Marino Faggiana. All rights reserved.
  7. //
  8. // This program is free software: you can redistribute it and/or modify
  9. // it under the terms of the GNU General Public License as published by
  10. // the Free Software Foundation, either version 3 of the License, or
  11. // (at your option) any later version.
  12. //
  13. // This program is distributed in the hope that it will be useful,
  14. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. // GNU General Public License for more details.
  17. //
  18. // You should have received a copy of the GNU General Public License
  19. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. //
  21. import UIKit
  22. import OpenSSL
  23. import NextcloudKit
  24. import CFNetwork
  25. import Alamofire
  26. import Foundation
  27. protocol uploadE2EEDelegate: AnyObject {
  28. func start()
  29. func uploadE2EEProgress(_ totalBytesExpected: Int64, _ totalBytes: Int64, _ fractionCompleted: Double)
  30. }
  31. extension uploadE2EEDelegate {
  32. func start() { }
  33. func uploadE2EEProgress(_ totalBytesExpected: Int64, _ totalBytes: Int64, _ fractionCompleted: Double) {}
  34. }
  35. class NCNetworkingE2EEUpload: NSObject {
  36. let networkingE2EE = NCNetworkingE2EE()
  37. func upload(metadata: tableMetadata, uploadE2EEDelegate: uploadE2EEDelegate? = nil) async -> NKError {
  38. var metadata = metadata
  39. let ocIdTemp = metadata.ocId
  40. if let result = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "serverUrl == %@ AND fileNameView == %@ AND ocId != %@", metadata.serverUrl, metadata.fileNameView, metadata.ocId)) {
  41. metadata.fileName = result.fileName
  42. } else {
  43. metadata.fileName = networkingE2EE.generateRandomIdentifier()
  44. }
  45. metadata.session = NextcloudKit.shared.nkCommonInstance.sessionIdentifierUpload
  46. metadata.sessionError = ""
  47. guard let result = NCManageDatabase.shared.addMetadata(metadata),
  48. let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata.account, metadata.serverUrl)) else {
  49. return NKError(errorCode: NCGlobal.shared.errorUnexpectedResponseFromDB, errorDescription: NSLocalizedString("_e2e_error_", comment: ""))
  50. }
  51. metadata = result
  52. func sendE2ee(e2eToken: String, fileId: String) async -> NKError {
  53. var key: NSString?, initializationVector: NSString?, authenticationTag: NSString?
  54. var method = "POST"
  55. // ENCRYPT FILE
  56. //
  57. if NCEndToEndEncryption.sharedManager()?.encryptFile(metadata.fileNameView, fileNameIdentifier: metadata.fileName, directory: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId), key: &key, initializationVector: &initializationVector, authenticationTag: &authenticationTag) == false {
  58. return NKError(errorCode: NCGlobal.shared.errorE2EEEncryptFile, errorDescription: NSLocalizedString("_e2e_error_", comment: ""))
  59. }
  60. guard let key = key as? String, let initializationVector = initializationVector as? String else {
  61. return NKError(errorCode: NCGlobal.shared.errorE2EEEncodedKey, errorDescription: NSLocalizedString("_e2e_error_", comment: ""))
  62. }
  63. // DOWNLOAD METADATA
  64. //
  65. let errorDownloadMetadata = await networkingE2EE.downloadMetadata(account: metadata.account, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, userId: metadata.userId, fileId: fileId, e2eToken: e2eToken)
  66. if errorDownloadMetadata == .success {
  67. method = "PUT"
  68. } else if errorDownloadMetadata.errorCode != NCGlobal.shared.errorResourceNotFound {
  69. return errorDownloadMetadata
  70. }
  71. // CREATE E2E METADATA
  72. //
  73. NCManageDatabase.shared.deleteE2eEncryption(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileName == %@", metadata.account, metadata.serverUrl, metadata.fileNameView))
  74. let object = tableE2eEncryption.init(account: metadata.account, ocIdServerUrl: directory.ocId, fileNameIdentifier: metadata.fileName)
  75. if let results = NCManageDatabase.shared.getE2eEncryption(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata.account, metadata.serverUrl)) {
  76. object.metadataKey = results.metadataKey
  77. object.metadataKeyIndex = results.metadataKeyIndex
  78. } else {
  79. guard let key = NCEndToEndEncryption.sharedManager()?.generateKey() as NSData? else {
  80. return NKError(errorCode: NCGlobal.shared.errorE2EEGenerateKey, errorDescription: NSLocalizedString("_e2e_error_", comment: ""))
  81. }
  82. object.metadataKey = key.base64EncodedString()
  83. object.metadataKeyIndex = 0
  84. }
  85. object.authenticationTag = authenticationTag! as String
  86. object.fileName = metadata.fileNameView
  87. object.key = key
  88. object.initializationVector = initializationVector
  89. object.mimeType = metadata.contentType
  90. object.serverUrl = metadata.serverUrl
  91. NCManageDatabase.shared.addE2eEncryption(object)
  92. // UPLOAD METADATA
  93. //
  94. let uploadMetadataError = await networkingE2EE.uploadMetadata(account: metadata.account,
  95. serverUrl: metadata.serverUrl,
  96. ocIdServerUrl: directory.ocId,
  97. fileId: fileId,
  98. userId: metadata.userId,
  99. e2eToken: e2eToken,
  100. method: method)
  101. return uploadMetadataError
  102. }
  103. // LOCK
  104. //
  105. let resultsLock = await networkingE2EE.lock(account: metadata.account, serverUrl: metadata.serverUrl)
  106. guard let e2eToken = resultsLock.e2eToken, let fileId = resultsLock.fileId, resultsLock.error == .success else {
  107. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocIdTemp))
  108. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account, "fileName": metadata.fileName, "ocIdTemp": ocIdTemp, "error": NKError(errorCode: NCGlobal.shared.errorE2EELock, errorDescription: NSLocalizedString("_e2e_error_", comment: ""))])
  109. return NKError(errorCode: NCGlobal.shared.errorE2EELock, errorDescription: NSLocalizedString("_e2e_error_", comment: ""))
  110. }
  111. // SEND NEW METADATA
  112. //
  113. let sendE2eeError = await sendE2ee(e2eToken: e2eToken, fileId: fileId)
  114. guard sendE2eeError == .success else {
  115. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocIdTemp))
  116. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account, "fileName": metadata.fileName, "ocIdTemp": ocIdTemp, "error": sendE2eeError])
  117. await networkingE2EE.unlock(account: metadata.account, serverUrl: metadata.serverUrl)
  118. return sendE2eeError
  119. }
  120. // UPLOAD
  121. //
  122. let resultsSendFile = await sendFile(metadata: metadata, e2eToken: e2eToken, uploadE2EEDelegate: uploadE2EEDelegate)
  123. // UNLOCK
  124. //
  125. await networkingE2EE.unlock(account: metadata.account, serverUrl: metadata.serverUrl)
  126. if let afError = resultsSendFile.afError, afError.isExplicitlyCancelledError {
  127. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  128. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  129. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account, "fileName": metadata.fileName, "ocIdTemp": ocIdTemp, "error": resultsSendFile.error])
  130. } else if resultsSendFile.error == .success, let ocId = resultsSendFile.ocId {
  131. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  132. NCUtilityFileSystem.shared.moveFileInBackground(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId), toPath: CCUtility.getDirectoryProviderStorageOcId(ocId))
  133. metadata.date = resultsSendFile.date ?? NSDate()
  134. metadata.etag = resultsSendFile.etag ?? ""
  135. metadata.ocId = ocId
  136. metadata.chunk = 0
  137. metadata.session = ""
  138. metadata.sessionError = ""
  139. metadata.sessionTaskIdentifier = 0
  140. metadata.status = NCGlobal.shared.metadataStatusNormal
  141. NCManageDatabase.shared.addMetadata(metadata)
  142. NCManageDatabase.shared.addLocalFile(metadata: metadata)
  143. NCUtility.shared.createImageFrom(fileNameView: metadata.fileNameView, ocId: metadata.ocId, etag: metadata.etag, classFile: metadata.classFile)
  144. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account, "fileName": metadata.fileName, "ocIdTemp": ocIdTemp, "error": resultsSendFile.error])
  145. } else {
  146. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: resultsSendFile.error.errorDescription, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusUploadError)
  147. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account, "fileName": metadata.fileName, "ocIdTemp": ocIdTemp, "error": resultsSendFile.error])
  148. }
  149. return (resultsSendFile.error)
  150. }
  151. private func sendFile(metadata: tableMetadata, e2eToken: String, uploadE2EEDelegate: uploadE2EEDelegate? = nil) async -> (ocId: String?, etag: String?, date: NSDate? ,afError: AFError?, error: NKError) {
  152. if metadata.chunk > 0 {
  153. return await withCheckedContinuation({ continuation in
  154. NCNetworking.shared.uploadChunkFile(metadata: metadata, withUploadComplete: false, addCustomHeaders: ["e2e-token": e2eToken]) {
  155. uploadE2EEDelegate?.start()
  156. } progressHandler: { totalBytesExpected, totalBytes, fractionCompleted in
  157. uploadE2EEDelegate?.uploadE2EEProgress(totalBytesExpected, totalBytes, fractionCompleted)
  158. } completion: { account, file, afError, error in
  159. continuation.resume(returning: (ocId: file?.ocId, etag: file?.etag, date: file?.date ,afError: afError, error: error))
  160. }
  161. })
  162. } else {
  163. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileName)!
  164. return await withCheckedContinuation({ continuation in
  165. NCNetworking.shared.uploadFile(metadata: metadata, fileNameLocalPath: fileNameLocalPath, withUploadComplete: false, addCustomHeaders: ["e2e-token": e2eToken]) {
  166. uploadE2EEDelegate?.start()
  167. } progressHandler: { totalBytesExpected, totalBytes, fractionCompleted in
  168. uploadE2EEDelegate?.uploadE2EEProgress(totalBytesExpected, totalBytes, fractionCompleted)
  169. } completion: { account, ocId, etag, date, size, allHeaderFields, afError, error in
  170. continuation.resume(returning: (ocId: ocId, etag: etag, date: date ,afError: afError, error: error))
  171. }
  172. })
  173. }
  174. }
  175. }