123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231 |
- //
- // Network.swift
- // Runner
- //
- // Created by Yayan Dwi on 20/04/20.
- // Copyright © 2020 The Chromium Authors. All rights reserved.
- //
- import Foundation
- import Alamofire
- public class Network {
- let uploadGroup = DispatchGroup()
- private var path = ""
- private var fileId = ""
- private var fileSize = 0
- private var isCancel = false
- private var progress = 0.0
- private var CHUNK_SIZE = 200 * 1024
-
- public init() {}
-
- public func upload(name: String, completion: @escaping (Bool, Double)->()) {
- DispatchQueue(label: "Network").async {
- do {
- let fileManager = FileManager.default
- let documentDir = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
- let fileDir = documentDir.appendingPathComponent(name)
- let path = fileDir.path
- if FileManager.default.fileExists(atPath: path) {
- let attrib = try FileManager.default.attributesOfItem(atPath: path)
- let fileSize = attrib[.size] as! Int
- let fileName = (path as NSString).lastPathComponent
- print("file exists: \(path) -> \(fileSize)")
- if (fileSize > self.CHUNK_SIZE) {
- Nexilis.putUploadFile(forKey: fileName, uploader: self)
- print("[bytes_processing] Size: " + String(fileSize))
- var totalPart = fileSize / self.CHUNK_SIZE
- if (fileSize % self.CHUNK_SIZE > 0) {
- totalPart += 1
- }
-
- do {
- let outputFileHandle = try FileHandle(forReadingFrom: URL(fileURLWithPath: path))
- var data = outputFileHandle.readData(ofLength: self.CHUNK_SIZE)
- var index = 0
- while !data.isEmpty {
- if self.isCancel {
- completion(false, Double(0))
- break
- }
- self.uploadGroup.enter()
- print("[bytes_processing] Sending bytes part #" + String(index + 1) + " of " + String(totalPart) + " --> " + String(data.count))
-
- 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))
-
- if let response = Nexilis.write(message: message), response.isEmpty {
- completion(false, self.progress)
- break
- }
- print("[bytes_processing] part #" + String(index + 1) + " of " + String(totalPart) + " uploading...")
-
- let wait = self.uploadGroup.wait(timeout: .now() + 30)
- print("[bytes_processing] part #" + String(index + 1) + " of " + String(totalPart) + " wait!", wait)
- if wait == DispatchTimeoutResult.timedOut {
- completion(false, self.progress)
- Nexilis.removeUploadFile(forKey: fileName)
- self.uploadGroup.leave()
- break
- }
- self.progress = Double(index + 1) / Double(totalPart) * 100
- completion(true, self.progress)
-
- print("[bytes_processing] part #" + String(index + 1) + " of " + String(totalPart) + " uploaded!")
- data = outputFileHandle.readData(ofLength: self.CHUNK_SIZE)
- index = index + 1
- }
- outputFileHandle.closeFile()
- _ = Nexilis.removeUploadFile(forKey: fileName)
- } catch {
- print(error.localizedDescription)
- }
- }
- else {
- let data = try Data(contentsOf: URL(fileURLWithPath: path))
-
- let message = CoreMessage_TMessageBank.getUploadFile(p_image_id: fileName, file_size: String(fileSize), part_of: "0", part_size: "0", p_file: [UInt8] (data))
-
- guard let response = Nexilis.write(message: message), !response.isEmpty else {
- completion(false, self.progress)
- return
- }
- print("[bytes_processing] File uploaded!")
- completion(response.count > 1, 100)
- }
- } else {
- print("file not exists \(name)")
- completion(false, 0)
- }
- } catch {
- print(error.localizedDescription)
- }
- }
- }
-
- public func upload(fileUrl: URL, completion: @escaping (Bool, Double)->()) {
- DispatchQueue(label: "Network").async {
- do {
- if FileManager.default.fileExists(atPath: fileUrl.path) {
- let path = fileUrl.path
- let attrib = try FileManager.default.attributesOfItem(atPath: path)
- let fileSize = attrib[.size] as! Int
- let fileName = (path as NSString).lastPathComponent
- print("file exists: \(path) -> \(fileSize)")
- if (fileSize > self.CHUNK_SIZE) {
- Nexilis.putUploadFile(forKey: fileName, uploader: self)
- print("[bytes_processing] Size: " + String(fileSize))
- var totalPart = fileSize / self.CHUNK_SIZE
- if (fileSize % self.CHUNK_SIZE > 0) {
- totalPart += 1
- }
-
- do {
- let outputFileHandle = try FileHandle(forReadingFrom: URL(fileURLWithPath: path))
- var data = outputFileHandle.readData(ofLength: self.CHUNK_SIZE)
- var index = 0
- while !data.isEmpty {
- if self.isCancel {
- completion(false, Double(0))
- break
- }
- self.uploadGroup.enter()
- print("[bytes_processing] Sending bytes part #" + String(index + 1) + " of " + String(totalPart) + " --> " + String(data.count))
-
- 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))
-
- if let response = Nexilis.write(message: message), response.isEmpty {
- completion(false, self.progress)
- break
- }
- print("[bytes_processing] part #" + String(index + 1) + " of " + String(totalPart) + " uploading...")
-
- let wait = self.uploadGroup.wait(timeout: .now() + 30)
- print("[bytes_processing] part #" + String(index + 1) + " of " + String(totalPart) + " wait!", wait)
- if wait == DispatchTimeoutResult.timedOut {
- completion(false, self.progress)
- Nexilis.removeUploadFile(forKey: fileName)
- self.uploadGroup.leave()
- break
- }
- self.progress = Double(index + 1) / Double(totalPart) * 100
- completion(true, self.progress)
-
- print("[bytes_processing] part #" + String(index + 1) + " of " + String(totalPart) + " uploaded!")
- data = outputFileHandle.readData(ofLength: self.CHUNK_SIZE)
- index = index + 1
- }
- outputFileHandle.closeFile()
- _ = Nexilis.removeUploadFile(forKey: fileName)
- } catch {
- print(error.localizedDescription)
- }
- }
- else {
- let data = try Data(contentsOf: URL(fileURLWithPath: path))
-
- let message = CoreMessage_TMessageBank.getUploadFile(p_image_id: fileName, file_size: String(fileSize), part_of: "0", part_size: "0", p_file: [UInt8] (data))
-
- guard let response = Nexilis.write(message: message), !response.isEmpty else {
- completion(false, self.progress)
- return
- }
- print("[bytes_processing] File uploaded!")
- completion(response.count > 1, 100)
- }
- } else {
- print("file not exists \(fileUrl)")
- completion(false, 0)
- }
- } catch {
- print(error.localizedDescription)
- }
- }
- }
-
- public func uploadHTTP(_ endUrl: String, files: [URL] = [], filename: [String] = [], parameters: [String : Any] = [:], onCompletion: (([String : Any]) -> Void)? = nil, onError: (() -> Void)? = nil, onProgress: ((Progress) -> Void)? = nil){
-
- guard filename.isEmpty else {
- let fileManager = FileManager.default
- let documentDir = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
- for name in filename {
- let fileDir = documentDir.appendingPathComponent(name)
- files.append(fileDir)
- }
- }
-
- AF.upload(multipartFormData: { (multipartFormData: MultipartFormData) in
- for (key, value) in parameters {
- multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
- print(multipartFormData)
- }
-
- for i in 0..<files.count {
- multipartFormData.append(files[i], withName: "file\(i+1)")
- print(multipartFormData)
- }
-
- }, to: endUrl)
- .responseJSON { result in
- if let successResponse = result.value as? [String:Any] {
- print("Response success")
- onCompletion?(successResponse)
- }
- else {
- let statusCode = result.response?.statusCode
- print("Response fail: \(statusCode)")
- onError?()
- }
- }
- .uploadProgress { progress in
- if isCancel {
- progress
- }
- onProgress?(progress)
- }
- }
-
- public func cancel() {
- self.isCancel = true
- }
- }
|