NCNetworkingE2EEUpload.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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 NextcloudKit
  23. import CFNetwork
  24. import Alamofire
  25. import Foundation
  26. protocol uploadE2EEDelegate: AnyObject {
  27. func start()
  28. func uploadE2EEProgress(_ totalBytesExpected: Int64, _ totalBytes: Int64, _ fractionCompleted: Double)
  29. }
  30. extension uploadE2EEDelegate {
  31. func start() { }
  32. func uploadE2EEProgress(_ totalBytesExpected: Int64, _ totalBytes: Int64, _ fractionCompleted: Double) {}
  33. }
  34. class NCNetworkingE2EEUpload: NSObject {
  35. let networkingE2EE = NCNetworkingE2EE()
  36. let utilityFileSystem = NCUtilityFileSystem()
  37. let utility = NCUtility()
  38. let database = NCManageDatabase.shared
  39. var numChunks: Int = 0
  40. func upload(metadata: tableMetadata, uploadE2EEDelegate: uploadE2EEDelegate?, controller: UIViewController?) async -> NKError {
  41. var metadata = metadata
  42. let session = NCSession.shared.getSession(account: metadata.account)
  43. let hud = await NCHud(controller?.view)
  44. if let result = self.database.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 = NCNetworking.shared.sessionUpload
  50. metadata.sessionError = ""
  51. guard let result = self.database.createMetadata(metadata),
  52. let directory = self.database.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.shared().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(serverUrl: metadata.serverUrl, fileId: fileId, e2eToken: e2eToken, session: session)
  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. self.database.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 = self.database.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.shared().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. self.database.addE2eEncryption(object)
  96. // UPLOAD METADATA
  97. //
  98. let uploadMetadataError = await networkingE2EE.uploadMetadata(serverUrl: metadata.serverUrl,
  99. ocIdServerUrl: directory.ocId,
  100. fileId: fileId,
  101. e2eToken: e2eToken,
  102. method: method,
  103. session: session)
  104. return uploadMetadataError
  105. }
  106. // LOCK
  107. //
  108. let resultsLock = await networkingE2EE.lock(account: metadata.account, serverUrl: metadata.serverUrl)
  109. guard let e2eToken = resultsLock.e2eToken, let fileId = resultsLock.fileId, resultsLock.error == .success else {
  110. self.database.deleteMetadata(predicate: NSPredicate(format: "ocIdTransfer == %@", metadata.ocIdTransfer))
  111. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile,
  112. object: nil,
  113. userInfo: ["ocId": metadata.ocId,
  114. "ocIdTransfer": metadata.ocIdTransfer,
  115. "session": metadata.session,
  116. "serverUrl": metadata.serverUrl,
  117. "account": metadata.account,
  118. "fileName": metadata.fileName,
  119. "error": NKError(errorCode: NCGlobal.shared.errorE2EELock, errorDescription: NSLocalizedString("_e2e_error_", comment: ""))],
  120. second: 0.5)
  121. return NKError(errorCode: NCGlobal.shared.errorE2EELock, errorDescription: NSLocalizedString("_e2e_error_", comment: ""))
  122. }
  123. // HUD ENCRYPTION
  124. //
  125. hud.initHud(text: NSLocalizedString("_wait_file_encryption_", comment: ""))
  126. // SEND NEW METADATA
  127. //
  128. let sendE2eeError = await sendE2ee(e2eToken: e2eToken, fileId: fileId)
  129. guard sendE2eeError == .success else {
  130. hud.dismiss()
  131. self.database.deleteMetadata(predicate: NSPredicate(format: "ocIdTransfer == %@", metadata.ocIdTransfer))
  132. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile,
  133. object: nil,
  134. userInfo: ["ocId": metadata.ocId,
  135. "ocIdTransfer": metadata.ocIdTransfer,
  136. "session": metadata.session,
  137. "serverUrl": metadata.serverUrl,
  138. "account": metadata.account,
  139. "fileName": metadata.fileName,
  140. "error": sendE2eeError],
  141. second: 0.5)
  142. await networkingE2EE.unlock(account: metadata.account, serverUrl: metadata.serverUrl)
  143. return sendE2eeError
  144. }
  145. // HUD CHUNK
  146. //
  147. hud.initHudRing(text: NSLocalizedString("_wait_file_preparation_", comment: ""),
  148. tapToCancelDetailText: true) {
  149. NotificationCenter.default.postOnMainThread(name: "NextcloudKit.chunkedFile.stop")
  150. }
  151. // UPLOAD
  152. //
  153. let resultsSendFile = await sendFile(metadata: metadata, e2eToken: e2eToken, hud: hud, uploadE2EEDelegate: uploadE2EEDelegate, controller: controller)
  154. // UNLOCK
  155. //
  156. await networkingE2EE.unlock(account: metadata.account, serverUrl: metadata.serverUrl)
  157. if let afError = resultsSendFile.afError, afError.isExplicitlyCancelledError {
  158. utilityFileSystem.removeFile(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId))
  159. self.database.deleteMetadataOcId(metadata.ocId)
  160. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile,
  161. object: nil,
  162. userInfo: ["ocId": metadata.ocId,
  163. "ocIdTransfer": metadata.ocIdTransfer,
  164. "session": metadata.session,
  165. "serverUrl": metadata.serverUrl,
  166. "account": metadata.account,
  167. "fileName": metadata.fileName,
  168. "error": resultsSendFile.error],
  169. second: 0.5)
  170. } else if resultsSendFile.error == .success, let ocId = resultsSendFile.ocId {
  171. self.database.deleteMetadataOcId(metadata.ocId)
  172. utilityFileSystem.moveFileInBackground(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId), toPath: utilityFileSystem.getDirectoryProviderStorageOcId(ocId))
  173. metadata.date = (resultsSendFile.date as? NSDate) ?? NSDate()
  174. metadata.etag = resultsSendFile.etag ?? ""
  175. metadata.ocId = ocId
  176. metadata.chunk = 0
  177. metadata.session = ""
  178. metadata.sessionTaskIdentifier = 0
  179. metadata.sessionError = ""
  180. metadata.status = NCGlobal.shared.metadataStatusNormal
  181. self.database.addMetadata(metadata)
  182. self.database.addLocalFile(metadata: metadata)
  183. utility.createImageFileFrom(metadata: metadata)
  184. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile,
  185. object: nil,
  186. userInfo: ["ocId": metadata.ocId,
  187. "ocIdTransfer": metadata.ocIdTransfer,
  188. "session": metadata.session,
  189. "serverUrl": metadata.serverUrl,
  190. "account": metadata.account,
  191. "fileName": metadata.fileName,
  192. "error": resultsSendFile.error],
  193. second: 0.5)
  194. } else {
  195. self.database.setMetadataSession(ocId: metadata.ocId,
  196. sessionTaskIdentifier: 0,
  197. sessionError: resultsSendFile.error.errorDescription,
  198. status: NCGlobal.shared.metadataStatusUploadError,
  199. errorCode: resultsSendFile.error.errorCode)
  200. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile,
  201. object: nil,
  202. userInfo: ["ocId": metadata.ocId,
  203. "ocIdTransfer": metadata.ocIdTransfer,
  204. "session": metadata.session,
  205. "serverUrl": metadata.serverUrl,
  206. "account": metadata.account,
  207. "fileName": metadata.fileName,
  208. "error": resultsSendFile.error],
  209. second: 0.5)
  210. }
  211. return (resultsSendFile.error)
  212. }
  213. // BRIDGE for chunk
  214. //
  215. private func sendFile(metadata: tableMetadata, e2eToken: String, hud: NCHud?, uploadE2EEDelegate: uploadE2EEDelegate? = nil, controller: UIViewController?) async -> (ocId: String?, etag: String?, date: Date?, afError: AFError?, error: NKError) {
  216. if metadata.chunk > 0 {
  217. return await withCheckedContinuation({ continuation in
  218. NCNetworking.shared.uploadChunkFile(metadata: metadata, withUploadComplete: false, customHeaders: ["e2e-token": e2eToken]) { num in
  219. self.numChunks = num
  220. } counterChunk: { counter in
  221. hud?.progress(num: Float(counter), total: Float(self.numChunks))
  222. } start: {
  223. hud?.dismiss()
  224. uploadE2EEDelegate?.start()
  225. } progressHandler: {totalBytesExpected, totalBytes, fractionCompleted in
  226. uploadE2EEDelegate?.uploadE2EEProgress(totalBytesExpected, totalBytes, fractionCompleted)
  227. } completion: { _, file, afError, error in
  228. DispatchQueue.main.async { hud?.dismiss() }
  229. continuation.resume(returning: (ocId: file?.ocId, etag: file?.etag, date: file?.date, afError: afError, error: error))
  230. }
  231. })
  232. } else {
  233. let fileNameLocalPath = utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileName)
  234. return await withCheckedContinuation({ continuation in
  235. NCNetworking.shared.uploadFile(metadata: metadata, fileNameLocalPath: fileNameLocalPath, withUploadComplete: false, customHeaders: ["e2e-token": e2eToken], controller: controller) {
  236. DispatchQueue.main.async { hud?.dismiss() }
  237. uploadE2EEDelegate?.start()
  238. } progressHandler: { totalBytesExpected, totalBytes, fractionCompleted in
  239. uploadE2EEDelegate?.uploadE2EEProgress(totalBytesExpected, totalBytes, fractionCompleted)
  240. } completion: { _, ocId, etag, date, _, _, afError, error in
  241. continuation.resume(returning: (ocId: ocId, etag: etag, date: date, afError: afError, error: error))
  242. }
  243. })
  244. }
  245. }
  246. }