NCNetworkingChunkedUpload.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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)->()) {
  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. 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. do {
  38. try filesNames = chunkedFile(inputDirectory: directoryProviderStorageOcId, outputDirectory: directoryProviderStorageOcId, fileName: metadata.fileName, chunkSizeMB: chunkSize)
  39. NCManageDatabase.shared.addChunks(account: metadata.account, ocId: metadata.ocId, chunkFolder: chunkFolder, fileNames: filesNames)
  40. } catch {
  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. return completion(uploadErrorCode, uploadErrorDescription)
  44. }
  45. /*
  46. if let chunkedFilesNames = NCCommunicationCommon.shared.chunkedFile(path: directoryProviderStorageOcId, fileName: metadata.fileName, outPath: directoryProviderStorageOcId, sizeInMB: chunkSize) {
  47. filesNames = chunkedFilesNames
  48. NCManageDatabase.shared.addChunks(account: metadata.account, ocId: metadata.ocId, chunkFolder: chunkFolder, fileNames: filesNames)
  49. } else {
  50. NCContentPresenter.shared.messageNotification("_error_", description: "_err_file_not_found_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode:NCGlobal.shared.errorReadFile, forced: true)
  51. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  52. return completion(uploadErrorCode, uploadErrorDescription)
  53. }
  54. */
  55. } else {
  56. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource, userInfo: ["serverUrl":metadata.serverUrl])
  57. }
  58. NCContentPresenter.shared.noteTop(text: NSLocalizedString("_upload_chunk_", comment: ""), image: nil, type: NCContentPresenter.messageType.info, delay: NCGlobal.shared.dismissAfterSecond, name: nil)
  59. createChunkedFolder(chunkFolderPath: chunkFolderPath, account: metadata.account) { (errorCode, errorDescription) in
  60. start()
  61. if errorCode == 0 {
  62. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadStartFile, userInfo: ["ocId": metadata.ocId])
  63. DispatchQueue.global(qos: .background).async {
  64. for fileName in filesNames {
  65. let serverUrlFileName = chunkFolderPath + "/" + fileName
  66. let fileNameChunkLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: fileName)!
  67. var size: Int64?
  68. if let tableChunk = NCManageDatabase.shared.getChunk(account: metadata.account, fileName: fileName) {
  69. size = tableChunk.size - NCUtilityFileSystem.shared.getFileSize(filePath: fileNameChunkLocalPath)
  70. }
  71. let semaphore = Semaphore()
  72. NCCommunication.shared.upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameChunkLocalPath, requestHandler: { (request) in
  73. self.uploadRequest[fileNameLocalPath] = request
  74. }, taskHandler: { (task) in
  75. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, sessionError: "", sessionTaskIdentifier: task.taskIdentifier, status: NCGlobal.shared.metadataStatusUploading)
  76. }, progressHandler: { (progress) in
  77. if let size = size {
  78. let totalBytesExpected = size + progress.completedUnitCount
  79. let totalBytes = metadata.size
  80. let fractionCompleted = Float(totalBytesExpected) / Float(totalBytes)
  81. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterProgressTask, object: nil, userInfo: ["account":metadata.account, "ocId":metadata.ocId, "fileName":metadata.fileName, "serverUrl":metadata.serverUrl, "status":NSNumber(value: NCGlobal.shared.metadataStatusInUpload), "progress":NSNumber(value: fractionCompleted), "totalBytes":NSNumber(value: totalBytes), "totalBytesExpected":NSNumber(value: totalBytesExpected)])
  82. }
  83. }) { (_, _, _, _, _, _, _, errorCode, errorDescription) in
  84. self.uploadRequest[fileNameLocalPath] = nil
  85. uploadErrorCode = errorCode
  86. uploadErrorDescription = errorDescription
  87. semaphore.continue()
  88. }
  89. semaphore.wait()
  90. if uploadErrorCode == 0 {
  91. NCManageDatabase.shared.deleteChunk(account: metadata.account, ocId: metadata.ocId, fileName: fileName)
  92. } else {
  93. break
  94. }
  95. }
  96. if uploadErrorCode == 0 {
  97. // Assembling the chunks
  98. let serverUrlFileNameSource = chunkFolderPath + "/.file"
  99. let pathServerUrl = CCUtility.returnPathfromServerUrl(metadata.serverUrl, urlBase: metadata.urlBase, account: metadata.account)!
  100. let serverUrlFileNameDestination = metadata.urlBase + "/" + NCUtilityFileSystem.shared.getWebDAV(account: metadata.account) + "/files/" + metadata.userId + pathServerUrl + "/" + metadata.fileName
  101. var addCustomHeaders: [String:String] = [:]
  102. let creationDate = "\(metadata.creationDate.timeIntervalSince1970)"
  103. let modificationDate = "\(metadata.date.timeIntervalSince1970)"
  104. addCustomHeaders["X-OC-CTime"] = creationDate
  105. addCustomHeaders["X-OC-MTime"] = modificationDate
  106. NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: true, addCustomHeaders: addCustomHeaders) { (_, errorCode, errorDescription) in
  107. if errorCode == 0 {
  108. let serverUrl = metadata.serverUrl
  109. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  110. NCManageDatabase.shared.deleteChunks(account: metadata.account, ocId: metadata.ocId)
  111. NCUtilityFileSystem.shared.deleteFile(filePath: directoryProviderStorageOcId)
  112. self.readFile(serverUrlFileName: serverUrlFileNameDestination, account: metadata.account) { (_, metadata, _, _) in
  113. if errorCode == 0, let metadata = metadata {
  114. NCManageDatabase.shared.addMetadata(metadata)
  115. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource, userInfo: ["serverUrl":serverUrl])
  116. } else {
  117. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced, userInfo: ["serverUrl": serverUrl])
  118. }
  119. completion(errorCode, errorDescription)
  120. }
  121. } else {
  122. self.uploadChunkFileError(metadata: metadata, chunkFolderPath: chunkFolderPath, directoryProviderStorageOcId: directoryProviderStorageOcId, errorCode: errorCode, errorDescription: errorDescription)
  123. completion(errorCode, errorDescription)
  124. }
  125. }
  126. } else {
  127. self.uploadChunkFileError(metadata: metadata, chunkFolderPath: chunkFolderPath, directoryProviderStorageOcId: directoryProviderStorageOcId, errorCode: uploadErrorCode, errorDescription: uploadErrorDescription)
  128. completion(errorCode, errorDescription)
  129. }
  130. }
  131. } else {
  132. self.uploadChunkFileError(metadata: metadata, chunkFolderPath: chunkFolderPath, directoryProviderStorageOcId: directoryProviderStorageOcId, errorCode: errorCode, errorDescription: errorDescription)
  133. completion(errorCode, errorDescription)
  134. }
  135. }
  136. }
  137. private func createChunkedFolder(chunkFolderPath: String, account: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  138. NCCommunication.shared.readFileOrFolder(serverUrlFileName: chunkFolderPath, depth: "0", showHiddenFiles: CCUtility.getShowHiddenFiles()) { (_, _, _, errorCode, errorDescription) in
  139. if errorCode == 0 {
  140. completion(0, "")
  141. } else if errorCode == NCGlobal.shared.errorResourceNotFound {
  142. NCCommunication.shared.createFolder(chunkFolderPath) { (_, _, _, errorCode, errorDescription) in
  143. completion(errorCode, errorDescription)
  144. }
  145. } else {
  146. completion(errorCode, errorDescription)
  147. }
  148. }
  149. }
  150. private func uploadChunkFileError(metadata: tableMetadata, chunkFolderPath: String, directoryProviderStorageOcId: String, errorCode: Int, errorDescription: String) {
  151. var errorDescription = errorDescription
  152. if errorCode == NSURLErrorCancelled || errorCode == NCGlobal.shared.errorRequestExplicityCancelled {
  153. // Delete chunk folder
  154. NCCommunication.shared.deleteFileOrFolder(chunkFolderPath) { (_, _, _) in }
  155. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  156. NCManageDatabase.shared.deleteChunks(account: metadata.account, ocId: metadata.ocId)
  157. NCUtilityFileSystem.shared.deleteFile(filePath: directoryProviderStorageOcId)
  158. NCCommunication.shared.deleteFileOrFolder(chunkFolderPath) { (_, _, _) in }
  159. } else {
  160. // NO report for the connection lost
  161. if errorCode == NCGlobal.shared.errorConnectionLost {
  162. errorDescription = ""
  163. } else {
  164. let description = errorDescription + " code: \(errorCode)"
  165. NCContentPresenter.shared.messageNotification("_error_", description: description, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorInternalError, forced: true)
  166. }
  167. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: errorDescription, sessionTaskIdentifier: NCGlobal.shared.metadataStatusNormal, status: NCGlobal.shared.metadataStatusUploadError)
  168. }
  169. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource, userInfo: ["serverUrl":metadata.serverUrl])
  170. }
  171. @objc func chunkedFile(inputDirectory: String, outputDirectory: String, fileName: String, chunkSizeMB:Int, bufferSize: Int = 1000000) throws-> [String] {
  172. let fileManager: FileManager = .default
  173. var isDirectory: ObjCBool = false
  174. let chunkSize = chunkSizeMB * 1000000
  175. var outputFilesName: [String] = []
  176. let reader: FileHandle = try .init(forReadingFrom: URL(fileURLWithPath: inputDirectory + "/" + fileName))
  177. var writer: FileHandle?
  178. var buffer: Data?
  179. var chunk: Int = 0
  180. var counter: Int = 0
  181. if !fileManager.fileExists(atPath:outputDirectory, isDirectory:&isDirectory) {
  182. try fileManager.createDirectory(atPath: outputDirectory, withIntermediateDirectories: true, attributes: nil)
  183. }
  184. repeat {
  185. if chunk >= chunkSize {
  186. writer?.closeFile()
  187. writer = nil
  188. chunk = 0
  189. counter += 1
  190. }
  191. let chunkRemaining: Int = chunkSize - chunk
  192. buffer = reader.readData(ofLength: min(bufferSize, chunkRemaining))
  193. if let buffer = buffer {
  194. if writer == nil {
  195. let fileNameChunk = fileName + String(format: "%010d", counter)
  196. let outputFileName = outputDirectory + "/" + fileNameChunk
  197. fileManager.createFile(atPath: outputFileName, contents: nil, attributes: nil)
  198. writer = try .init(forWritingTo: URL(fileURLWithPath: outputFileName))
  199. outputFilesName.append(fileNameChunk)
  200. }
  201. writer?.write(buffer)
  202. chunk = chunk + buffer.count
  203. }
  204. } while buffer?.count ?? 0 > 0
  205. writer?.closeFile()
  206. reader.closeFile()
  207. return outputFilesName
  208. }
  209. }