-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.swift
403 lines (352 loc) · 12.4 KB
/
request.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//
// <class>.swift
// <class>
//
// Created by Vmlweb on 27/05/2015.
// Copyright (c) 2015 Vmlweb. All rights reserved.
//
import Foundation
import AFNetworking
import SwiftyJSON
import CocoaAsyncSocket
class <class> : NSObject, GCDAsyncSocketDelegate, GCDAsyncUdpSocketDelegate{
//Hostnames
var hostnames = Dictionary<String, String>()
override init() {
//hostnames["_METHOD_"] = "_URL_"
<hostnames>
}
//Route Request
func sendRequest(name: String, methods: Array<String>, params: [String : AnyObject],
callback: (success: Bool, message: String, output: JSON?)->(),
uploading: ((size: Double, remaining: Double, percentage: Double)->Void)?,
downloading: ((size: Double, remaining: Double, percentage: Double)->Void)?, stream: NSOutputStream?){
//Methods
let http = [ "POST", "OPTIONS", "GET", "HEAD", "PUT", "PATCH", "DELETE", "TRACE", "CONNECT" ]
for method in methods{
//Route
if method == "UDP" && hostnames["udp"] != nil{
return dingleUDP(name, params: params, callback: callback)
}else if method == "TCP" && hostnames["udp"] != nil{
return dingleTCP(name, params: params, callback: callback)
}else if contains(http, method) && (hostnames["https"] != nil || hostnames["http"] != nil){
return dingleHTTP(name, method: method, params: params, callback: callback, uploading: uploading, downloading: downloading, stream: stream)
}else{
return callback(success: false, message: "Could not find method to call", output: nil)
}
}
}
//Cancel
func cancelAll(){
httpManager.operationQueue.cancelAllOperations()
tcpClose()
udpClose()
}
//HTTP
var httpManager = AFURLSessionManager(sessionConfiguration: NSURLSessionConfiguration.defaultSessionConfiguration())
func dingleHTTP(name: String, method: String, params: [String : AnyObject],
callback: (success: Bool, message: String, output: JSON?)->(),
uploading: ((size: Double, remaining: Double, percentage: Double)->Void)?,
downloading: ((size: Double, remaining: Double, percentage: Double)->Void)?, stream: NSOutputStream?){
//Setup
var serializer = AFHTTPRequestSerializer()
var error: NSError? = nil
//Check Params
var files = [String : NSURL?]()
var strings = [String : String]()
for (key, value) in params{
//Check if file
if value is NSURL{
files[key] = value as? NSURL
}else{
strings[key] = "\(value)"
}
}
//Hostname
var hostname : String
if let connection = hostnames["https"]{
hostname = "https://\(connection)/"
}else if let connection = hostnames["http"]{
hostname = "http://\(connection)/"
}else{
callback(success: false, message: "Could not find HTTP or HTTPS hostname", output: nil)
return
}
//Make request
var url = hostname + name + "/"
var request : NSMutableURLRequest
if method == "POST"{
request = serializer.multipartFormRequestWithMethod(method, URLString: url, parameters: strings, constructingBodyWithBlock: { (form) -> Void in
//Add files
for (key, value) in files{
if let file = value{
form.appendPartWithFileURL(file, name: key, error: &error)
}
}
}, error: &error)
}else{
request = serializer.requestWithMethod(method, URLString: url, parameters: strings, error: &error)
}
//Error
if let error = error{
callback(success: false, message: error.localizedDescription, output: nil)
}
//Make Operation
var operation = AFHTTPRequestOperation(request: request)
operation.securityPolicy.allowInvalidCertificates = true
if let stream = stream{
operation.outputStream = stream
}
//Completed
operation.setCompletionBlockWithSuccess({ (request, object) -> Void in
if let type = request.response.allHeaderFields["Content-Disposition"] as? String{
//Download
if let stream = stream{
callback(success: true, message: "Response written to stream", output: ["stream":stream])
}else{
callback(success: false, message: "Stream required to download this file", output: nil)
}
}else{
//Stream
if let stream = stream{
callback(success: true, message: "Response written to stream", output: ["stream":stream])
}else{
//JSON?
if let data = object as? NSData{
//Read JSON
let json = JSON(data: data)
let success = json["success"].boolValue
let message = json["message"].stringValue
callback(success: success, message: message, output: json["output"])
}else{
callback(success: false, message: "Invalid JSON response", output: nil)
}
}
}
}, failure: { (request, error) -> Void in
if error.code == -1009{
callback(success: false, message: "Could not find server, please check your internet connection", output: nil)
}else if error.code == -1004{
callback(success: false, message: "Could not connect to server, please contact administrator", output: nil)
}else{
callback(success: false, message: error.localizedDescription, output: nil)
}
})
//Downloading
operation.setDownloadProgressBlock { (read, total, expected) -> Void in
if let downloading = downloading{
var expected = Double(expected)
var total = Double(total)
downloading(size: expected, remaining: total, percentage: total / expected)
}
}
//Uploading
operation.setUploadProgressBlock { (read, total, expected) -> Void in
if let uploading = uploading{
var expected = Double(expected)
var total = Double(total)
uploading(size: expected, remaining: total, percentage: total / expected)
}
}
operation.start()
}
//TCP
var tcpSocket : GCDAsyncSocket!
var tcpCallback : ((success: Bool, message: String, output: JSON?)->())?
func dingleTCP(name: String, params: [String : AnyObject], callback: (success: Bool, message: String, output: JSON?)->()){
var error : NSError?
//Connection
var hostname : String
var port : UInt16
if let connection = hostnames["tcp"]{
//Hostname
if let hostname_check = find(connection, ":"){
hostname = connection.substringToIndex(hostname_check)
}else{
callback(success: false, message: "Could not find a TCP hostname", output: nil)
return
}
//Port
if let port_check = find(connection, ":"){
var port_string = connection.substringFromIndex(port_check)
port_string.removeAtIndex(port_string.startIndex)
port = UInt16(port_string.toInt()!)
}else{
callback(success: false, message: "Could not find a TCP port", output: nil)
return
}
}else{
callback(success: false, message: "Could not find TCP hostname", output: nil)
return
}
//Setup socket
tcpSocket = GCDAsyncSocket(delegate:self, delegateQueue: dispatch_get_main_queue())
tcpSocket.connectToHost(hostname, onPort: port, error: &error)
tcpCallback = callback
//Error
if let error = error {
callback(success: false, message: error.localizedDescription, output: nil)
return
}
//Send
var name = "/\(name)/"
var message = name.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
tcpSocket.writeData(message, withTimeout: -1, tag: 0)
tcpSocket.readDataWithTimeout(-1, tag: 0)
NSTimer.scheduledTimerWithTimeInterval(4, target: self, selector: Selector("tcpTimeout"), userInfo: nil, repeats: false)
}
func tcpTimeout(){
if let callback = tcpCallback{
callback(success: false, message: "Could not find server, please check your internet connection", output: nil)
tcpClose()
}
}
func tcpClose(){
if let socket = tcpSocket{
socket.disconnect()
}
tcpSocket = nil
tcpCallback = nil
}
func socketDidDisconnect(sock: GCDAsyncSocket!, withError err: NSError!) {
if let callback = tcpCallback{
if err.code == 8{
callback(success: false, message: "Could not find server, please check your internet connection", output: nil)
}else if err.code == 61{
callback(success: false, message: "Could not connect to server, please contact administrator", output: nil)
}else{
callback(success: false, message: err.localizedDescription, output: nil)
}
tcpClose()
}
}
func socket(sock: GCDAsyncSocket!, didReadData data: NSData!, withTag tag: Int) {
if let callback = tcpCallback{
//JSON?
if let data = data{
//Read JSON?
let json = JSON(data: data)
let success = json["success"].boolValue
let message = json["message"].stringValue
callback(success: success, message: message, output: json["output"])
tcpClose()
}else{
callback(success: false, message: "Invalid JSON response", output: nil)
tcpClose()
}
}
}
//UDP
var udpSocket : GCDAsyncUdpSocket!
var udpCallback : ((success: Bool, message: String, output: JSON?)->())?
func dingleUDP(name: String, params: [String : AnyObject], callback: (success: Bool, message: String, output: JSON?)->()){
var error : NSError?
//Connection
var hostname : String
var port : UInt16
if let connection = hostnames["udp"]{
//Hostname
if let hostname_check = find(connection, ":"){
hostname = connection.substringToIndex(hostname_check)
}else{
callback(success: false, message: "Could not find a UDP hostname", output: nil)
return
}
//Port
if let port_check = find(connection, ":"){
var port_string = connection.substringFromIndex(port_check)
port_string.removeAtIndex(port_string.startIndex)
port = UInt16(port_string.toInt()!)
}else{
callback(success: false, message: "Could not find a UDP port", output: nil)
return
}
}else{
callback(success: false, message: "Could not find UDP hostname", output: nil)
return
}
//Setup socket
udpSocket = GCDAsyncUdpSocket(delegate:self, delegateQueue: dispatch_get_main_queue())
udpSocket.bindToPort(0, error: &error)
udpSocket.connectToHost(hostname, onPort: port, error: &error)
udpSocket.beginReceiving(&error)
udpCallback = callback
//Error
if let error = error {
callback(success: false, message: error.localizedDescription, output: nil)
return
}
//Send
var message = "/\(name)/".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
udpSocket.sendData(message, withTimeout: -1, tag: 0)
NSTimer.scheduledTimerWithTimeInterval(4, target: self, selector: Selector("udpTimeout"), userInfo: nil, repeats: false)
}
func udpTimeout(){
if let callback = udpCallback{
callback(success: false, message: "Could not connect to server, please contact administrator", output: nil)
udpClose()
}
}
func udpClose(){
if let socket = udpSocket{
socket.close()
}
udpSocket = nil
udpCallback = nil
}
func udpSocket(sock: GCDAsyncUdpSocket!, didNotConnect error: NSError!) {
if let callback = udpCallback{
if error.code == 8{
callback(success: false, message: "Could not find server, please check your internet connection", output: nil)
}else{
callback(success: false, message: error.localizedDescription, output: nil)
}
udpClose()
}
}
func udpSocket(sock: GCDAsyncUdpSocket!, didNotSendDataWithTag tag: Int, dueToError error: NSError!) {
if let callback = udpCallback{
callback(success: false, message: error.localizedDescription, output: nil)
udpClose()
}
}
func udpSocket(sock: GCDAsyncUdpSocket!, didReceiveData data: NSData!, fromAddress address: NSData!, withFilterContext filterContext: AnyObject!) {
if let callback = udpCallback{
//JSON?
if let data = data{
//Read JSON?
let json = JSON(data: data)
let success = json["success"].boolValue
let message = json["message"].stringValue
callback(success: success, message: message, output: json["output"])
udpClose()
}else{
callback(success: false, message: "Invalid JSON response", output: nil)
udpClose()
}
}
}
//Request Functions
/*
func _NAME_(_PARAMS_, callback: (success: Bool, message: String, output: JSON?)->()){
_NAME_(_PARAMS_, callback: callback, uploading: nil, downloading: nil, stream: nil)
}
func _NAME_(_PARAMS_,
callback: (success: Bool, message: String, output: JSON?)->(),
uploading: ((size: Double, remaining: Double, percentage: Double)->Void)?,
downloading: ((size: Double, remaining: Double, percentage: Double)->Void)?, stream: NSOutputStream?){
//Parameters
var params = [String : AnyObject]()
if let value = _PARAM_{
if value is NSURL{
params["_PARAM_"] = value as? NSURL
}else{
params["_PARAM_"] = "\(value)"
}
}
//Execute
sendRequest("_NAME_", methods: [ "_METHODS_" ], params: params, callback: callback, uploading: uploading, downloading: downloading, stream: stream)
}
*/
<functions>
}