NCNetworkingE2EEUpload.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. import JGProgressHUD
  28. protocol uploadE2EEDelegate: AnyObject {
  29. func start()
  30. func uploadE2EEProgress(_ totalBytesExpected: Int64, _ totalBytes: Int64, _ fractionCompleted: Double)
  31. }
  32. extension uploadE2EEDelegate {
  33. func start() { }
  34. func uploadE2EEProgress(_ totalBytesExpected: Int64, _ totalBytes: Int64, _ fractionCompleted: Double) {}
  35. }
  36. class NCNetworkingE2EEUpload: NSObject {
  37. let networkingE2EE = NCNetworkingE2EE()
  38. let utilityFileSystem = NCUtilityFileSystem()
  39. let utility = NCUtility()
  40. var numChunks: Int = 0
  41. func upload(metadata: tableMetadata, uploadE2EEDelegate: uploadE2EEDelegate? = nil, hudView: UIView?, hud: JGProgressHUD?) async -> NKError {
  42. var metadata = metadata
  43. let ocIdTemp = metadata.ocId
  44. if let result = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "serverUrl == %@ AND fileNameView == %@ AND ocId != %@", metadata.serverUrl, metadata.fileNameView, metadata.ocId)) {
  45. metadata.fileName = result.fileName
  46. } else {
  47. metadata.fileName = networkingE2EE.generateRandomIdentifier()
  48. }
  49. metadata.session = NextcloudKit.shared.nkCommonInstance.sessionIdentifierUpload
  50. metadata.sessionError = ""
  51. guard let result = NCManageDatabase.shared.addMetadata(metadata),
  52. let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata.account, metadata.serverUrl)) else {
  53. return NKError(errorCode: NCGlobal.shared.errorUnexpectedResponseFromDB, errorDescription: NSLocalizedString("_e2e_error_", comment: ""))
  54. }
  55. metadata = result
  56. func sendE2ee(e2eToken: String, fileId: String) async -> NKError {
  57. var key: NSString?, initializationVector: NSString?, authenticationTag: NSString?
  58. var method = "POST"
  59. // ENCRYPT FILE
  60. //
  61. if NCEndToEndEncryption.sharedManager()?.encryptFile(metadata.fileNameView, fileNameIdentifier: metadata.fileName, directory: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId), key: &key, initializationVector: &initializationVector, authenticationTag: &authenticationTag) == false {
  62. return NKError(errorCode: NCGlobal.shared.errorE2EEEncryptFile, errorDescription: NSLocalizedString("_e2e_error_", comment: ""))
  63. }
  64. guard let key = key as? String, let initializationVector = initializationVector as? String else {
  65. return NKError(errorCode: NCGlobal.shared.errorE2EEEncodedKey, errorDescription: NSLocalizedString("_e2e_error_", comment: ""))
  66. }
  67. // DOWNLOAD METADATA
  68. //
  69. let errorDownloadMetadata = await networkingE2EE.downloadMetadata(account: metadata.account, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, userId: metadata.userId, fileId: fileId, e2eToken: e2eToken)
  70. if errorDownloadMetadata == .success {
  71. method = "PUT"
  72. } else if errorDownloadMetadata.errorCode != NCGlobal.shared.errorResourceNotFound {
  73. return errorDownloadMetadata
  74. }
  75. // CREATE E2E METADATA
  76. //
  77. NCManageDatabase.shared.deleteE2eEncryption(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileName == %@", metadata.account, metadata.serverUrl, metadata.fileNameView))
  78. let object = tableE2eEncryption.init(account: metadata.account, ocIdServerUrl: directory.ocId, fileNameIdentifier: metadata.fileName)
  79. if let results = NCManageDatabase.shared.getE2eEncryption(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata.account, metadata.serverUrl)) {
  80. object.metadataKey = results.metadataKey
  81. object.metadataKeyIndex = results.metadataKeyIndex
  82. } else {
  83. guard let key = NCEndToEndEncryption.sharedManager()?.generateKey() as NSData? else {
  84. return NKError(errorCode: NCGlobal.shared.errorE2EEGenerateKey, errorDescription: NSLocalizedString("_e2e_error_", comment: ""))
  85. }
  86. object.metadataKey = key.base64EncodedString()
  87. object.metadataKeyIndex = 0
  88. }
  89. object.authenticationTag = authenticationTag! as String
  90. object.fileName = metadata.fileNameView
  91. object.key = key
  92. object.initializationVector = initializationVector
  93. object.mimeType = metadata.contentType
  94. object.serverUrl = metadata.serverUrl
  95. NCManageDatabase.shared.addE2eEncryption(object)
  96. // UPLOAD METADATA
  97. //
  98. let uploadMetadataError = await networkingE2EE.uploadMetadata(account: metadata.account,
  99. serverUrl: metadata.serverUrl,
  100. ocIdServerUrl: directory.ocId,
  101. fileId: fileId,
  102. userId: metadata.userId,
  103. e2eToken: e2eToken,
  104. method: method)
  105. return uploadMetadataError
  106. }
  107. // LOCK
  108. //
  109. let resultsLock = await networkingE2EE.lock(account: metadata.account, serverUrl: metadata.serverUrl)
  110. guard let e2eToken = resultsLock.e2eToken, let fileId = resultsLock.fileId, resultsLock.error == .success else {
  111. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocIdTemp))
  112. NotificationCenter.default.post(
  113. name: Notification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile),
  114. object: nil,
  115. userInfo: ["ocId": metadata.ocId,
  116. "serverUrl": metadata.serverUrl,
  117. "account": metadata.account,
  118. "fileName": metadata.fileName,
  119. "ocIdTemp": ocIdTemp,
  120. "error": NKError(errorCode: NCGlobal.shared.errorE2EELock, errorDescription: NSLocalizedString("_e2e_error_", comment: ""))])
  121. return NKError(errorCode: NCGlobal.shared.errorE2EELock, errorDescription: NSLocalizedString("_e2e_error_", comment: ""))
  122. }
  123. // HUD ENCRYPTION
  124. //
  125. if let hudView {
  126. DispatchQueue.main.async {
  127. hud?.textLabel.text = NSLocalizedString("_wait_file_encryption_", comment: "")
  128. hud?.show(in: hudView)
  129. }
  130. }
  131. // SEND NEW METADATA
  132. //
  133. let sendE2eeError = await sendE2ee(e2eToken: e2eToken, fileId: fileId)
  134. guard sendE2eeError == .success else {
  135. DispatchQueue.main.async { hud?.dismiss() }
  136. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocIdTemp))
  137. NotificationCenter.default.post(
  138. name: Notification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile),
  139. object: nil,
  140. userInfo: ["ocId": metadata.ocId,
  141. "serverUrl": metadata.serverUrl,
  142. "account": metadata.account,
  143. "fileName": metadata.fileName,
  144. "ocIdTemp": ocIdTemp,
  145. "error": sendE2eeError])
  146. await networkingE2EE.unlock(account: metadata.account, serverUrl: metadata.serverUrl)
  147. return sendE2eeError
  148. }
  149. // HUD CHUNK
  150. //
  151. if hudView != nil {
  152. DispatchQueue.main.async {
  153. if let hud {
  154. hud.indicatorView = JGProgressHUDRingIndicatorView()
  155. if let indicatorView = hud.indicatorView as? JGProgressHUDRingIndicatorView {
  156. indicatorView.ringWidth = 1.5
  157. }
  158. hud.tapOnHUDViewBlock = { _ in
  159. NotificationCenter.default.postOnMainThread(name: "NextcloudKit.chunkedFile.stop")
  160. }
  161. hud.textLabel.text = NSLocalizedString("_wait_file_preparation_", comment: "")
  162. hud.detailTextLabel.text = NSLocalizedString("_tap_to_cancel_", comment: "")
  163. }
  164. }
  165. }
  166. // UPLOAD
  167. //
  168. let resultsSendFile = await sendFile(metadata: metadata, e2eToken: e2eToken, hud: hud, uploadE2EEDelegate: uploadE2EEDelegate)
  169. // UNLOCK
  170. //
  171. await networkingE2EE.unlock(account: metadata.account, serverUrl: metadata.serverUrl)
  172. if let afError = resultsSendFile.afError, afError.isExplicitlyCancelledError {
  173. utilityFileSystem.removeFile(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId))
  174. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  175. NotificationCenter.default.post(
  176. name: Notification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile),
  177. object: nil,
  178. userInfo: ["ocId": metadata.ocId,
  179. "serverUrl": metadata.serverUrl,
  180. "account": metadata.account,
  181. "fileName": metadata.fileName,
  182. "ocIdTemp": ocIdTemp,
  183. "error": resultsSendFile.error])
  184. } else if resultsSendFile.error == .success, let ocId = resultsSendFile.ocId {
  185. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  186. utilityFileSystem.moveFileInBackground(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId), toPath: utilityFileSystem.getDirectoryProviderStorageOcId(ocId))
  187. metadata.date = resultsSendFile.date ?? NSDate()
  188. metadata.etag = resultsSendFile.etag ?? ""
  189. metadata.ocId = ocId
  190. metadata.chunk = 0
  191. metadata.session = ""
  192. metadata.sessionError = ""
  193. metadata.status = NCGlobal.shared.metadataStatusNormal
  194. NCManageDatabase.shared.addMetadata(metadata)
  195. NCManageDatabase.shared.addLocalFile(metadata: metadata)
  196. utility.createImageFrom(fileNameView: metadata.fileNameView, ocId: metadata.ocId, etag: metadata.etag, classFile: metadata.classFile)
  197. NotificationCenter.default.post(
  198. name: Notification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile),
  199. object: nil,
  200. userInfo: ["ocId": metadata.ocId,
  201. "serverUrl": metadata.serverUrl,
  202. "account": metadata.account,
  203. "fileName": metadata.fileName,
  204. "ocIdTemp": ocIdTemp,
  205. "error": resultsSendFile.error])
  206. } else {
  207. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId,
  208. sessionError: resultsSendFile.error.errorDescription,
  209. status: NCGlobal.shared.metadataStatusUploadError,
  210. errorCode: resultsSendFile.error.errorCode)
  211. NotificationCenter.default.post(
  212. name: Notification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile),
  213. object: nil,
  214. userInfo: ["ocId": metadata.ocId,
  215. "serverUrl": metadata.serverUrl,
  216. "account": metadata.account,
  217. "fileName": metadata.fileName,
  218. "ocIdTemp": ocIdTemp,
  219. "error": resultsSendFile.error])
  220. }
  221. return (resultsSendFile.error)
  222. }
  223. // BRIDGE for chunk
  224. //
  225. private func sendFile(metadata: tableMetadata, e2eToken: String, hud: JGProgressHUD?, uploadE2EEDelegate: uploadE2EEDelegate? = nil) async -> (ocId: String?, etag: String?, date: NSDate?, afError: AFError?, error: NKError) {
  226. if metadata.chunk > 0 {
  227. return await withCheckedContinuation({ continuation in
  228. NCNetworking.shared.uploadChunkFile(metadata: metadata, withUploadComplete: false, customHeaders: ["e2e-token": e2eToken]) { num in
  229. self.numChunks = num
  230. } counterChunk: { counter in
  231. DispatchQueue.main.async { hud?.progress = Float(counter) / Float(self.numChunks) }
  232. } start: {
  233. DispatchQueue.main.async { hud?.dismiss() }
  234. uploadE2EEDelegate?.start()
  235. } progressHandler: {totalBytesExpected, totalBytes, fractionCompleted in
  236. uploadE2EEDelegate?.uploadE2EEProgress(totalBytesExpected, totalBytes, fractionCompleted)
  237. } completion: { _, file, afError, error in
  238. DispatchQueue.main.async { hud?.dismiss() }
  239. continuation.resume(returning: (ocId: file?.ocId, etag: file?.etag, date: file?.date, afError: afError, error: error))
  240. }
  241. })
  242. } else {
  243. let fileNameLocalPath = utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileName)
  244. return await withCheckedContinuation({ continuation in
  245. NCNetworking.shared.uploadFile(metadata: metadata, fileNameLocalPath: fileNameLocalPath, withUploadComplete: false, customHeaders: ["e2e-token": e2eToken]) {
  246. DispatchQueue.main.async { hud?.dismiss() }
  247. uploadE2EEDelegate?.start()
  248. } progressHandler: { totalBytesExpected, totalBytes, fractionCompleted in
  249. uploadE2EEDelegate?.uploadE2EEProgress(totalBytesExpected, totalBytes, fractionCompleted)
  250. } completion: { _, ocId, etag, date, _, _, afError, error in
  251. continuation.resume(returning: (ocId: ocId, etag: etag, date: date, afError: afError, error: error))
  252. }
  253. })
  254. }
  255. }
  256. }