NCNetworkingChunkedUpload.swift 14 KB

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