Network.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. //
  2. // Network.swift
  3. // Runner
  4. //
  5. // Created by Yayan Dwi on 20/04/20.
  6. // Copyright © 2020 The Chromium Authors. All rights reserved.
  7. //
  8. import Foundation
  9. import Alamofire
  10. public class Network {
  11. let uploadGroup = DispatchGroup()
  12. private var path = ""
  13. private var fileId = ""
  14. private var fileSize = 0
  15. private var isCancel = false
  16. private var progress = 0.0
  17. private var CHUNK_SIZE = 200 * 1024
  18. public init() {}
  19. public func upload(name: String, completion: @escaping (Bool, Double)->()) {
  20. DispatchQueue(label: "Network").async {
  21. do {
  22. let fileManager = FileManager.default
  23. let documentDir = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
  24. let fileDir = documentDir.appendingPathComponent(name)
  25. let path = fileDir.path
  26. if FileManager.default.fileExists(atPath: path) {
  27. let attrib = try FileManager.default.attributesOfItem(atPath: path)
  28. let fileSize = attrib[.size] as! Int
  29. let fileName = (path as NSString).lastPathComponent
  30. print("file exists: \(path) -> \(fileSize)")
  31. if (fileSize > self.CHUNK_SIZE) {
  32. Nexilis.putUploadFile(forKey: fileName, uploader: self)
  33. print("[bytes_processing] Size: " + String(fileSize))
  34. var totalPart = fileSize / self.CHUNK_SIZE
  35. if (fileSize % self.CHUNK_SIZE > 0) {
  36. totalPart += 1
  37. }
  38. do {
  39. let outputFileHandle = try FileHandle(forReadingFrom: URL(fileURLWithPath: path))
  40. var data = outputFileHandle.readData(ofLength: self.CHUNK_SIZE)
  41. var index = 0
  42. while !data.isEmpty {
  43. if self.isCancel {
  44. completion(false, Double(0))
  45. break
  46. }
  47. self.uploadGroup.enter()
  48. print("[bytes_processing] Sending bytes part #" + String(index + 1) + " of " + String(totalPart) + " --> " + String(data.count))
  49. let message = CoreMessage_TMessageBank.getUploadFile(p_image_id: fileName, file_size: String(fileSize), part_of: String(index), part_size: String(totalPart), p_file: [UInt8] (data))
  50. if let response = Nexilis.write(message: message), response.isEmpty {
  51. completion(false, self.progress)
  52. break
  53. }
  54. print("[bytes_processing] part #" + String(index + 1) + " of " + String(totalPart) + " uploading...")
  55. let wait = self.uploadGroup.wait(timeout: .now() + 30)
  56. print("[bytes_processing] part #" + String(index + 1) + " of " + String(totalPart) + " wait!", wait)
  57. if wait == DispatchTimeoutResult.timedOut {
  58. completion(false, self.progress)
  59. Nexilis.removeUploadFile(forKey: fileName)
  60. self.uploadGroup.leave()
  61. break
  62. }
  63. self.progress = Double(index + 1) / Double(totalPart) * 100
  64. completion(true, self.progress)
  65. print("[bytes_processing] part #" + String(index + 1) + " of " + String(totalPart) + " uploaded!")
  66. data = outputFileHandle.readData(ofLength: self.CHUNK_SIZE)
  67. index = index + 1
  68. }
  69. outputFileHandle.closeFile()
  70. _ = Nexilis.removeUploadFile(forKey: fileName)
  71. } catch {
  72. print(error.localizedDescription)
  73. }
  74. }
  75. else {
  76. let data = try Data(contentsOf: URL(fileURLWithPath: path))
  77. let message = CoreMessage_TMessageBank.getUploadFile(p_image_id: fileName, file_size: String(fileSize), part_of: "0", part_size: "0", p_file: [UInt8] (data))
  78. guard let response = Nexilis.write(message: message), !response.isEmpty else {
  79. completion(false, self.progress)
  80. return
  81. }
  82. print("[bytes_processing] File uploaded!")
  83. completion(response.count > 1, 100)
  84. }
  85. } else {
  86. print("file not exists \(name)")
  87. completion(false, 0)
  88. }
  89. } catch {
  90. print(error.localizedDescription)
  91. }
  92. }
  93. }
  94. public func upload(fileUrl: URL, completion: @escaping (Bool, Double)->()) {
  95. DispatchQueue(label: "Network").async {
  96. do {
  97. if FileManager.default.fileExists(atPath: fileUrl.path) {
  98. let path = fileUrl.path
  99. let attrib = try FileManager.default.attributesOfItem(atPath: path)
  100. let fileSize = attrib[.size] as! Int
  101. let fileName = (path as NSString).lastPathComponent
  102. print("file exists: \(path) -> \(fileSize)")
  103. if (fileSize > self.CHUNK_SIZE) {
  104. Nexilis.putUploadFile(forKey: fileName, uploader: self)
  105. print("[bytes_processing] Size: " + String(fileSize))
  106. var totalPart = fileSize / self.CHUNK_SIZE
  107. if (fileSize % self.CHUNK_SIZE > 0) {
  108. totalPart += 1
  109. }
  110. do {
  111. let outputFileHandle = try FileHandle(forReadingFrom: URL(fileURLWithPath: path))
  112. var data = outputFileHandle.readData(ofLength: self.CHUNK_SIZE)
  113. var index = 0
  114. while !data.isEmpty {
  115. if self.isCancel {
  116. completion(false, Double(0))
  117. break
  118. }
  119. self.uploadGroup.enter()
  120. print("[bytes_processing] Sending bytes part #" + String(index + 1) + " of " + String(totalPart) + " --> " + String(data.count))
  121. let message = CoreMessage_TMessageBank.getUploadFile(p_image_id: fileName, file_size: String(fileSize), part_of: String(index), part_size: String(totalPart), p_file: [UInt8] (data))
  122. if let response = Nexilis.write(message: message), response.isEmpty {
  123. completion(false, self.progress)
  124. break
  125. }
  126. print("[bytes_processing] part #" + String(index + 1) + " of " + String(totalPart) + " uploading...")
  127. let wait = self.uploadGroup.wait(timeout: .now() + 30)
  128. print("[bytes_processing] part #" + String(index + 1) + " of " + String(totalPart) + " wait!", wait)
  129. if wait == DispatchTimeoutResult.timedOut {
  130. completion(false, self.progress)
  131. Nexilis.removeUploadFile(forKey: fileName)
  132. self.uploadGroup.leave()
  133. break
  134. }
  135. self.progress = Double(index + 1) / Double(totalPart) * 100
  136. completion(true, self.progress)
  137. print("[bytes_processing] part #" + String(index + 1) + " of " + String(totalPart) + " uploaded!")
  138. data = outputFileHandle.readData(ofLength: self.CHUNK_SIZE)
  139. index = index + 1
  140. }
  141. outputFileHandle.closeFile()
  142. _ = Nexilis.removeUploadFile(forKey: fileName)
  143. } catch {
  144. print(error.localizedDescription)
  145. }
  146. }
  147. else {
  148. let data = try Data(contentsOf: URL(fileURLWithPath: path))
  149. let message = CoreMessage_TMessageBank.getUploadFile(p_image_id: fileName, file_size: String(fileSize), part_of: "0", part_size: "0", p_file: [UInt8] (data))
  150. guard let response = Nexilis.write(message: message), !response.isEmpty else {
  151. completion(false, self.progress)
  152. return
  153. }
  154. print("[bytes_processing] File uploaded!")
  155. completion(response.count > 1, 100)
  156. }
  157. } else {
  158. print("file not exists \(fileUrl)")
  159. completion(false, 0)
  160. }
  161. } catch {
  162. print(error.localizedDescription)
  163. }
  164. }
  165. }
  166. public func uploadHTTP(_ endUrl: String, files: [URL] = [], filename: [String] = [], parameters: [String : Any] = [:], onCompletion: (([String : Any]) -> Void)? = nil, onError: (() -> Void)? = nil, onProgress: ((Progress) -> Void)? = nil){
  167. guard filename.isEmpty else {
  168. let fileManager = FileManager.default
  169. let documentDir = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
  170. for name in filename {
  171. let fileDir = documentDir.appendingPathComponent(name)
  172. files.append(fileDir)
  173. }
  174. }
  175. AF.upload(multipartFormData: { (multipartFormData: MultipartFormData) in
  176. for (key, value) in parameters {
  177. multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
  178. print(multipartFormData)
  179. }
  180. for i in 0..<files.count {
  181. multipartFormData.append(files[i], withName: "file\(i+1)")
  182. print(multipartFormData)
  183. }
  184. }, to: endUrl)
  185. .responseJSON { result in
  186. if let successResponse = result.value as? [String:Any] {
  187. print("Response success")
  188. onCompletion?(successResponse)
  189. }
  190. else {
  191. let statusCode = result.response?.statusCode
  192. print("Response fail: \(statusCode)")
  193. onError?()
  194. }
  195. }
  196. .uploadProgress { progress in
  197. if isCancel {
  198. progress
  199. }
  200. onProgress?(progress)
  201. }
  202. }
  203. public func cancel() {
  204. self.isCancel = true
  205. }
  206. }