NCNetworkingChunkedUpload.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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, userId: String, start: @escaping () -> Void, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  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.getDAV() + "/uploads/" + userId + "/" + chunkFolder
  31. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  32. let chunkSize = CCUtility.getChunkSize()
  33. var uploadErrorCode: Int = 0
  34. var uploadErrorDescription: String = ""
  35. var filesNames = NCManageDatabase.shared.getChunks(account: metadata.account, ocId: metadata.ocId)
  36. if filesNames.count == 0 {
  37. if let chunkedFilesNames = NCCommunicationCommon.shared.chunkedFile(path: directoryProviderStorageOcId, fileName: metadata.fileName, outPath: directoryProviderStorageOcId, sizeInMB: chunkSize) {
  38. filesNames = chunkedFilesNames
  39. NCManageDatabase.shared.addChunks(account: metadata.account, ocId: metadata.ocId, chunkFolder: chunkFolder, fileNames: filesNames)
  40. } else {
  41. NCContentPresenter.shared.messageNotification("_error_", description: "_err_file_not_found_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode:NCGlobal.shared.errorReadFile, forced: true)
  42. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  43. completion(uploadErrorCode, uploadErrorDescription)
  44. return
  45. }
  46. } else {
  47. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource, userInfo: ["serverUrl":metadata.serverUrl])
  48. }
  49. NCContentPresenter.shared.noteTop(text: NSLocalizedString("_upload_chunk_", comment: ""), image: nil, type: NCContentPresenter.messageType.info, delay: NCGlobal.shared.dismissAfterSecond, name: nil)
  50. createChunkedFolder(chunkFolderPath: chunkFolderPath, account: metadata.account) { (errorCode, errorDescription) in
  51. start()
  52. if errorCode == 0 {
  53. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadStartFile, userInfo: ["ocId": metadata.ocId])
  54. DispatchQueue.global(qos: .background).async {
  55. for fileName in filesNames {
  56. let counterString = (fileName as NSString).pathExtension
  57. let counter = Int64(counterString) ?? 0
  58. let serverUrlFileName = chunkFolderPath + "/" + fileName
  59. let fileNameChunkLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: fileName)!
  60. let chunkSize = NCUtilityFileSystem.shared.getFileSize(filePath: fileNameChunkLocalPath)
  61. let semaphore = Semaphore()
  62. NCCommunication.shared.upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameChunkLocalPath, requestHandler: { (request) in
  63. self.uploadRequest[fileNameLocalPath] = request
  64. let chunksremains = NCManageDatabase.shared.getChunks(account: metadata.account, ocId: metadata.ocId).count
  65. let totalBytes = (counter + 1) * chunkSize
  66. let totalBytesExpected: Int64 = metadata.size
  67. var progress: Float = 0
  68. if chunksremains == 1 {
  69. progress = 1
  70. } else {
  71. progress = Float(totalBytes) / Float(totalBytesExpected)
  72. }
  73. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterProgressTask, userInfo: ["account":metadata.account, "ocId":metadata.ocId, "serverUrl":metadata.serverUrl, "status":NSNumber(value: NCGlobal.shared.metadataStatusInUpload), "progress":NSNumber(value: progress), "totalBytes":NSNumber(value: totalBytes), "totalBytesExpected":NSNumber(value: totalBytesExpected)])
  74. }, taskHandler: { (task) in
  75. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, sessionError: "", sessionTaskIdentifier: task.taskIdentifier, status: NCGlobal.shared.metadataStatusUploading)
  76. }, progressHandler: { (_) in
  77. }) { (_, _, _, _, _, _, _, errorCode, errorDescription) in
  78. self.uploadRequest[fileNameLocalPath] = nil
  79. uploadErrorCode = errorCode
  80. uploadErrorDescription = errorDescription
  81. semaphore.continue()
  82. }
  83. semaphore.wait()
  84. if uploadErrorCode == 0 {
  85. NCManageDatabase.shared.deleteChunk(account: metadata.account, ocId: metadata.ocId, fileName: fileName)
  86. } else {
  87. break
  88. }
  89. }
  90. if uploadErrorCode == 0 {
  91. // Assembling the chunks
  92. let serverUrlFileNameSource = chunkFolderPath + "/.file"
  93. let pathServerUrl = CCUtility.returnPathfromServerUrl(metadata.serverUrl, urlBase: metadata.urlBase, account: metadata.account)!
  94. let serverUrlFileNameDestination = metadata.urlBase + "/" + NCUtilityFileSystem.shared.getDAV() + "/files/" + userId + pathServerUrl + "/" + metadata.fileName
  95. var addCustomHeaders: [String:String] = [:]
  96. let creationDate = "\(metadata.creationDate.timeIntervalSince1970)"
  97. let modificationDate = "\(metadata.date.timeIntervalSince1970)"
  98. addCustomHeaders["X-OC-CTime"] = creationDate
  99. addCustomHeaders["X-OC-MTime"] = modificationDate
  100. NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: true, addCustomHeaders: addCustomHeaders) { (_, errorCode, errorDescription) in
  101. if errorCode == 0 {
  102. let serverUrl = metadata.serverUrl
  103. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  104. NCManageDatabase.shared.deleteChunks(account: metadata.account, ocId: metadata.ocId)
  105. NCUtilityFileSystem.shared.deleteFile(filePath: directoryProviderStorageOcId)
  106. self.readFile(serverUrlFileName: serverUrlFileNameDestination, account: metadata.account) { (_, metadata, _, _) in
  107. if errorCode == 0, let metadata = metadata {
  108. NCManageDatabase.shared.addMetadata(metadata)
  109. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource, userInfo: ["serverUrl":serverUrl])
  110. } else {
  111. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced, userInfo: ["serverUrl": serverUrl])
  112. }
  113. completion(errorCode, errorDescription)
  114. }
  115. } else {
  116. self.uploadChunkFileError(metadata: metadata, chunkFolderPath: chunkFolderPath, directoryProviderStorageOcId: directoryProviderStorageOcId, errorCode: errorCode, errorDescription: errorDescription)
  117. completion(errorCode, errorDescription)
  118. }
  119. }
  120. } else {
  121. self.uploadChunkFileError(metadata: metadata, chunkFolderPath: chunkFolderPath, directoryProviderStorageOcId: directoryProviderStorageOcId, errorCode: uploadErrorCode, errorDescription: uploadErrorDescription)
  122. completion(errorCode, errorDescription)
  123. }
  124. }
  125. } else {
  126. self.uploadChunkFileError(metadata: metadata, chunkFolderPath: chunkFolderPath, directoryProviderStorageOcId: directoryProviderStorageOcId, errorCode: errorCode, errorDescription: errorDescription)
  127. completion(errorCode, errorDescription)
  128. }
  129. }
  130. }
  131. private func createChunkedFolder(chunkFolderPath: String, account: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  132. NCCommunication.shared.readFileOrFolder(serverUrlFileName: chunkFolderPath, depth: "0", showHiddenFiles: CCUtility.getShowHiddenFiles()) { (_, _, _, errorCode, errorDescription) in
  133. if errorCode == 0 {
  134. completion(0, "")
  135. } else if errorCode == NCGlobal.shared.errorResourceNotFound {
  136. NCCommunication.shared.createFolder(chunkFolderPath) { (_, _, _, errorCode, errorDescription) in
  137. completion(errorCode, errorDescription)
  138. }
  139. } else {
  140. completion(errorCode, errorDescription)
  141. }
  142. }
  143. }
  144. private func uploadChunkFileError(metadata: tableMetadata, chunkFolderPath: String, directoryProviderStorageOcId: String, errorCode: Int, errorDescription: String) {
  145. var errorDescription = errorDescription
  146. if errorCode == NSURLErrorCancelled || errorCode == NCGlobal.shared.errorRequestExplicityCancelled {
  147. // Delete chunk folder
  148. NCCommunication.shared.deleteFileOrFolder(chunkFolderPath) { (_, _, _) in }
  149. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  150. NCManageDatabase.shared.deleteChunks(account: metadata.account, ocId: metadata.ocId)
  151. NCUtilityFileSystem.shared.deleteFile(filePath: directoryProviderStorageOcId)
  152. NCCommunication.shared.deleteFileOrFolder(chunkFolderPath) { (_, _, _) in }
  153. } else {
  154. // NO report for the connection lost
  155. if errorCode == NCGlobal.shared.errorConnectionLost {
  156. errorDescription = ""
  157. } else {
  158. let description = errorDescription + " code: \(errorCode)"
  159. NCContentPresenter.shared.messageNotification("_error_", description: description, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorInternalError, forced: true)
  160. }
  161. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: errorDescription, sessionTaskIdentifier: NCGlobal.shared.metadataStatusNormal, status: NCGlobal.shared.metadataStatusUploadError)
  162. }
  163. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource, userInfo: ["serverUrl":metadata.serverUrl])
  164. }
  165. }