NCNetworkingChunkedUpload.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. //
  2. // NCNetworkingUploadChunk.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 05/04/21.
  6. // Copyright © 2021 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 UIKit
  24. import NCCommunication
  25. import Queuer
  26. extension NCNetworking {
  27. internal func uploadChunkedFile(metadata: tableMetadata, start: @escaping () -> Void, completion: @escaping (_ errorCode: Int, _ errorDescription: String) -> Void) {
  28. let directoryProviderStorageOcId = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId)!
  29. let chunkFolder = NCManageDatabase.shared.getChunkFolder(account: metadata.account, ocId: metadata.ocId)
  30. let chunkFolderPath = metadata.urlBase + "/" + NCUtilityFileSystem.shared.getWebDAV(account: metadata.account) + "/uploads/" + metadata.userId + "/" + chunkFolder
  31. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  32. let chunkSize = CCUtility.getChunkSize()
  33. let fileSizeInGB = Double(metadata.size) / 1e9
  34. var uploadErrorCode: Int = 0
  35. var uploadErrorDescription: String = ""
  36. var filesNames = NCManageDatabase.shared.getChunks(account: metadata.account, ocId: metadata.ocId)
  37. if filesNames.count == 0 {
  38. NCContentPresenter.shared.noteTop(text: NSLocalizedString("_upload_chunk_", comment: ""), image: nil, type: NCContentPresenter.messageType.info, delay: .infinity, priority: .max)
  39. filesNames = NCCommunicationCommon.shared.chunkedFile(inputDirectory: directoryProviderStorageOcId, outputDirectory: directoryProviderStorageOcId, fileName: metadata.fileName, chunkSizeMB: chunkSize)
  40. if filesNames.count > 0 {
  41. NCManageDatabase.shared.addChunks(account: metadata.account, ocId: metadata.ocId, chunkFolder: chunkFolder, fileNames: filesNames)
  42. } else {
  43. NCContentPresenter.shared.dismiss(after: 0)
  44. NCContentPresenter.shared.messageNotification("_error_", description: "_err_file_not_found_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorReadFile)
  45. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  46. return completion(uploadErrorCode, uploadErrorDescription)
  47. }
  48. } else {
  49. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource, userInfo: ["serverUrl": metadata.serverUrl])
  50. }
  51. createChunkedFolder(chunkFolderPath: chunkFolderPath, account: metadata.account) { errorCode, errorDescription in
  52. NCContentPresenter.shared.dismiss(after: NCGlobal.shared.dismissAfterSecond)
  53. start()
  54. guard errorCode == 0 else {
  55. self.uploadChunkFileError(metadata: metadata, chunkFolderPath: chunkFolderPath, directoryProviderStorageOcId: directoryProviderStorageOcId, errorCode: errorCode, errorDescription: errorDescription)
  56. completion(errorCode, errorDescription)
  57. return
  58. }
  59. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadStartFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account])
  60. for fileName in filesNames {
  61. let serverUrlFileName = chunkFolderPath + "/" + fileName
  62. let fileNameChunkLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: fileName)!
  63. var size: Int64?
  64. if let tableChunk = NCManageDatabase.shared.getChunk(account: metadata.account, fileName: fileName) {
  65. size = tableChunk.size - NCUtilityFileSystem.shared.getFileSize(filePath: fileNameChunkLocalPath)
  66. }
  67. let semaphore = Semaphore()
  68. NCCommunication.shared.upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameChunkLocalPath, requestHandler: { request in
  69. self.uploadRequest[fileNameLocalPath] = request
  70. }, taskHandler: { task in
  71. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, sessionError: "", sessionTaskIdentifier: task.taskIdentifier, status: NCGlobal.shared.metadataStatusUploading)
  72. NCCommunicationCommon.shared.writeLog("Upload chunk: " + fileName)
  73. }, progressHandler: { progress in
  74. if let size = size {
  75. let totalBytesExpected = metadata.size
  76. let totalBytes = size + progress.completedUnitCount
  77. let fractionCompleted = Float(totalBytes) / Float(totalBytesExpected)
  78. NotificationCenter.default.postOnMainThread(
  79. name: NCGlobal.shared.notificationCenterProgressTask,
  80. object: nil,
  81. userInfo: [
  82. "account": metadata.account,
  83. "ocId": metadata.ocId,
  84. "fileName": metadata.fileName,
  85. "serverUrl": metadata.serverUrl,
  86. "status": NSNumber(value: NCGlobal.shared.metadataStatusInUpload),
  87. "progress": NSNumber(value: fractionCompleted),
  88. "totalBytes": NSNumber(value: totalBytes),
  89. "totalBytesExpected": NSNumber(value: totalBytesExpected)])
  90. }
  91. }) { _, _, _, _, _, _, _, errorCode, errorDescription in
  92. self.uploadRequest.removeValue(forKey: fileNameLocalPath)
  93. uploadErrorCode = errorCode
  94. uploadErrorDescription = errorDescription
  95. semaphore.continue()
  96. }
  97. semaphore.wait()
  98. if uploadErrorCode == 0 {
  99. NCManageDatabase.shared.deleteChunk(account: metadata.account, ocId: metadata.ocId, fileName: fileName)
  100. } else {
  101. break
  102. }
  103. }
  104. guard uploadErrorCode == 0 else {
  105. self.uploadChunkFileError(metadata: metadata, chunkFolderPath: chunkFolderPath, directoryProviderStorageOcId: directoryProviderStorageOcId, errorCode: uploadErrorCode, errorDescription: uploadErrorDescription)
  106. completion(errorCode, errorDescription)
  107. return
  108. }
  109. // Assembling the chunks
  110. let serverUrlFileNameSource = chunkFolderPath + "/.file"
  111. let pathServerUrl = CCUtility.returnPathfromServerUrl(metadata.serverUrl, urlBase: metadata.urlBase, account: metadata.account)!
  112. let serverUrlFileNameDestination = metadata.urlBase + "/" + NCUtilityFileSystem.shared.getWebDAV(account: metadata.account) + "/files/" + metadata.userId + pathServerUrl + "/" + metadata.fileName
  113. var addCustomHeaders: [String: String] = [:]
  114. let creationDate = "\(metadata.creationDate.timeIntervalSince1970)"
  115. let modificationDate = "\(metadata.date.timeIntervalSince1970)"
  116. addCustomHeaders["X-OC-CTime"] = creationDate
  117. addCustomHeaders["X-OC-MTime"] = modificationDate
  118. // Calculate Assemble Timeout
  119. let ASSEMBLE_TIME_PER_GB: Double = 3 * 60 // 3 min
  120. let ASSEMBLE_TIME_MIN: Double = 60 // 60 sec
  121. let ASSEMBLE_TIME_MAX: Double = 30 * 60 // 30 min
  122. let timeout = max(ASSEMBLE_TIME_MIN, min(ASSEMBLE_TIME_PER_GB * fileSizeInGB, ASSEMBLE_TIME_MAX))
  123. NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: true, addCustomHeaders: addCustomHeaders, timeout: timeout, queue: DispatchQueue.global(qos: .background)) { _, errorCode, errorDescription in
  124. NCCommunicationCommon.shared.writeLog("Assembling chunk with error code: \(errorCode)")
  125. guard uploadErrorCode == 0 else {
  126. self.uploadChunkFileError(metadata: metadata, chunkFolderPath: chunkFolderPath, directoryProviderStorageOcId: directoryProviderStorageOcId, errorCode: errorCode, errorDescription: errorDescription)
  127. completion(errorCode, errorDescription)
  128. return
  129. }
  130. let serverUrl = metadata.serverUrl
  131. let assetLocalIdentifier = metadata.assetLocalIdentifier
  132. let isLivePhoto = metadata.livePhoto
  133. let isE2eEncrypted = metadata.e2eEncrypted
  134. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  135. NCManageDatabase.shared.deleteChunks(account: metadata.account, ocId: metadata.ocId)
  136. NCUtilityFileSystem.shared.deleteFile(filePath: directoryProviderStorageOcId)
  137. self.readFile(serverUrlFileName: serverUrlFileNameDestination) { (_, metadata, _, _) in
  138. if errorCode == 0, let metadata = metadata {
  139. metadata.assetLocalIdentifier = assetLocalIdentifier
  140. metadata.e2eEncrypted = isE2eEncrypted
  141. metadata.livePhoto = isLivePhoto
  142. // Delete Asset on Photos album
  143. if CCUtility.getRemovePhotoCameraRoll() && !metadata.assetLocalIdentifier.isEmpty {
  144. metadata.deleteAssetLocalIdentifier = true
  145. }
  146. NCManageDatabase.shared.addMetadata(metadata)
  147. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource, userInfo: ["serverUrl": serverUrl])
  148. } else {
  149. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced, userInfo: ["serverUrl": serverUrl])
  150. }
  151. completion(errorCode, errorDescription)
  152. }
  153. }
  154. }
  155. }
  156. private func createChunkedFolder(chunkFolderPath: String, account: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String) -> Void) {
  157. NCCommunication.shared.readFileOrFolder(serverUrlFileName: chunkFolderPath, depth: "0", showHiddenFiles: CCUtility.getShowHiddenFiles(), queue: NCCommunicationCommon.shared.backgroundQueue) { _, _, _, errorCode, errorDescription in
  158. if errorCode == 0 {
  159. completion(0, "")
  160. } else if errorCode == NCGlobal.shared.errorResourceNotFound {
  161. NCCommunication.shared.createFolder(chunkFolderPath, queue: NCCommunicationCommon.shared.backgroundQueue) { _, _, _, errorCode, errorDescription in
  162. completion(errorCode, errorDescription)
  163. }
  164. } else {
  165. completion(errorCode, errorDescription)
  166. }
  167. }
  168. }
  169. private func uploadChunkFileError(metadata: tableMetadata, chunkFolderPath: String, directoryProviderStorageOcId: String, errorCode: Int, errorDescription: String) {
  170. var errorDescription = errorDescription
  171. NCCommunicationCommon.shared.writeLog("Upload chunk error code: \(errorCode)")
  172. if errorCode == NSURLErrorCancelled || errorCode == NCGlobal.shared.errorRequestExplicityCancelled {
  173. // Delete chunk folder
  174. NCCommunication.shared.deleteFileOrFolder(chunkFolderPath) { _, _, _ in }
  175. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  176. NCManageDatabase.shared.deleteChunks(account: metadata.account, ocId: metadata.ocId)
  177. NCUtilityFileSystem.shared.deleteFile(filePath: directoryProviderStorageOcId)
  178. NCCommunication.shared.deleteFileOrFolder(chunkFolderPath) { _, _, _ in }
  179. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadCancelFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account])
  180. } else {
  181. // NO report for the connection lost
  182. if errorCode == NCGlobal.shared.errorConnectionLost {
  183. errorDescription = ""
  184. } else {
  185. let description = errorDescription + " code: \(errorCode)"
  186. NCContentPresenter.shared.messageNotification("_error_", description: description, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorInternalError)
  187. }
  188. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: errorDescription, sessionTaskIdentifier: NCGlobal.shared.metadataStatusNormal, status: NCGlobal.shared.metadataStatusUploadError)
  189. }
  190. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account, "ocIdTemp": metadata.ocId, "errorCode": errorCode, "errorDescription": ""])
  191. }
  192. }