forked from probablycorey/wax
/
wax_http_connection.m
304 lines (240 loc) · 8.59 KB
/
wax_http_connection.m
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
//
// wax_http_connection.m
// RentList
//
// Created by Corey Johnson on 8/9/09.
// Copyright 2009 ProbablyInteractive. All rights reserved.
//
#include <CommonCrypto/CommonDigest.h>
#import "lauxlib.h"
#import "wax_http_connection.h"
#import "wax_instance.h"
#import "wax_helpers.h"
#import "wax_json.h"
#ifdef WAX_XML_INCLUDED
#import "wax_xml.h"
#endif
@implementation wax_http_connection
@synthesize response=_response;
@synthesize format=_format;
@synthesize finished=_finished;
- (void)dealloc {
[_data release];
[_error release];
[_response release];
[_request release];
[_timeoutTimer release];
[super dealloc];
}
- (id)initWithRequest:(NSURLRequest *)urlRequest timeout:(NSTimeInterval)timeout luaState:(lua_State *)luaState {
self = [super initWithRequest:urlRequest delegate:self startImmediately:NO];
[self scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
L = luaState;
_data = [[NSMutableData alloc] init];
_request = [urlRequest retain];
_timeout = timeout;
_format = WAX_HTTP_UNKNOWN;
_canceled = NO;
return self;
}
- (void)timeoutHack {
NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorTimedOut userInfo:nil];
[self connection:self didFailWithError:error];
[self cancel];
}
- (void)start {
// Apple makes has a mandatory 240 second minimum timeout WTF? https://devforums.apple.com/thread/25282
// Because of this stupidity by Apple, we are forced to setup our own timeout
// using a timer.
_timeoutTimer = [[NSTimer scheduledTimerWithTimeInterval:_timeout target:self selector:@selector(timeoutHack) userInfo:nil repeats:NO] retain];
wax_log(LOG_NETWORK, @"HTTP(%@) %@", [_request HTTPMethod], [_request URL]);
[super start];
}
- (void)cancel {
wax_log(LOG_NETWORK, @"CANCELING (%@) %@", [_request HTTPMethod], [_request URL]);
[_timeoutTimer invalidate];
_canceled = YES;
[super cancel];
}
- (bool)isFinished {
return _canceled || _finished;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
if (response != _response) [_response release];
_response = [response retain];
}
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse {
if (redirectResponse) [self callRedirectCallback:redirectResponse];
return request;
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if (![self callLuaAuthCallback:challenge]) {
[[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_data appendData:data];
[self callLuaProgressCallback];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
if (!_canceled) {
_error = [error retain];
[_data release];
_data = nil;
[self callLuaCallback];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
if (!_canceled) {
[self callLuaCallback];
}
}
- (void)callRedirectCallback:(NSURLResponse *)redirectResponse {
BEGIN_STACK_MODIFY(L)
if (_canceled) {
assert("OH NO, URL CONNECTION WAS CANCELED BUT NOT CAUGHT");
}
wax_instance_pushUserdata(L, self);
lua_getfield(L, -1, WAX_HTTP_REDIRECT_CALLBACK_FUNCTION_NAME);
bool hasCallback = YES;
if (lua_isnil(L, -1)) {
hasCallback = NO;
lua_pop(L, 1);
}
wax_fromObjc(L, "@", &redirectResponse);
if (hasCallback && wax_pcall(L, 1, 0)) {
const char* error_string = lua_tostring(L, -1);
luaL_error(L, "Problem calling Lua function '%s' from wax_http.\n%s", WAX_HTTP_REDIRECT_CALLBACK_FUNCTION_NAME, error_string);
}
END_STACK_MODIFY(L, 0)
}
- (BOOL)callLuaAuthCallback:(NSURLAuthenticationChallenge *)challenge {
BEGIN_STACK_MODIFY(L)
if (_canceled) {
assert("OH NO, URL CONNECTION WAS CANCELED BUT NOT CAUGHT");
}
wax_instance_pushUserdata(L, self);
lua_getfield(L, -1, WAX_HTTP_AUTH_CALLBACK_FUNCTION_NAME);
bool hasCallback = YES;
if (lua_isnil(L, -1)) {
hasCallback = NO;
lua_pop(L, 1);
}
wax_fromObjc(L, "@", &challenge);
if (hasCallback && wax_pcall(L, 1, 0)) {
const char* error_string = lua_tostring(L, -1);
luaL_error(L, "Problem calling Lua function '%s' from wax_http.\n%s", WAX_HTTP_AUTH_CALLBACK_FUNCTION_NAME, error_string);
}
END_STACK_MODIFY(L, 0)
return hasCallback;
}
- (void)callLuaProgressCallback {
BEGIN_STACK_MODIFY(L)
if (_canceled) {
assert("OH NO, URL CONNECTION WAS CANCELED BUT NOT CAUGHT");
}
wax_instance_pushUserdata(L, self);
lua_getfield(L, -1, WAX_HTTP_PROGRESS_CALLBACK_FUNCTION_NAME);
if (lua_isnil(L, -1)) {
lua_pop(L, 1);
}
else {
float percentComplete = 0;
@try {
percentComplete = _data.length / [[[_response allHeaderFields] objectForKey:@"Content-Length"] floatValue];
}
@catch (NSException * e) {
NSLog(@"Error: Couldn't calculate percent Complete");
}
wax_fromObjc(L, "f", &percentComplete);
wax_fromObjc(L, "@", &_data);
if (wax_pcall(L, 2, 0)) {
const char* error_string = lua_tostring(L, -1);
luaL_error(L, "Problem calling Lua function '%s' from wax_http.\n%s", WAX_HTTP_PROGRESS_CALLBACK_FUNCTION_NAME, error_string);
}
}
END_STACK_MODIFY(L, 0)
}
- (void)callLuaCallback {
[_timeoutTimer invalidate];
BEGIN_STACK_MODIFY(L)
if (_canceled) {
assert("OH NO, URL CONNECTION WAS CANCELED BUT NOT CAUGHT");
}
wax_instance_pushUserdata(L, self);
lua_getfield(L, -1, WAX_HTTP_CALLBACK_FUNCTION_NAME);
bool hasCallback = YES;
if (lua_isnil(L, -1)) {
hasCallback = NO;
lua_pop(L, 1);
}
// Try and guess the format type
if (_format == WAX_HTTP_UNKNOWN) {
NSString *contentType = [[_response allHeaderFields] objectForKey:@"Content-Type"];
if ([contentType hasPrefix:@"application/xml"] ||
[contentType hasPrefix:@"text/xml"]) {
#ifdef WAX_XML_INCLUDED
_format = WAX_HTTP_XML;
#else
_format = WAX_HTTP_TEXT;
#endif
}
else if ([contentType hasPrefix:@"application/json"] ||
[contentType hasPrefix:@"text/json"] ||
[contentType hasPrefix:@"application/javascript"] ||
[contentType hasPrefix:@"text/javascript"]) {
_format = WAX_HTTP_JSON;
}
else if ([contentType hasPrefix:@"image/"] ||
[contentType hasPrefix:@"audio/"] ||
[contentType hasPrefix:@"application/octet-stream"]) {
_format = WAX_HTTP_BINARY;
}
else {
_format = WAX_HTTP_TEXT;
}
}
if (_error) {
lua_pushnil(L);
}
else if (_format == WAX_HTTP_TEXT || _format == WAX_HTTP_JSON || _format == WAX_HTTP_XML) {
NSString *string = [[NSString alloc] initWithData:_data encoding:NSUTF8StringEncoding];
if (!string) string = [[NSString alloc] initWithData:_data encoding:NSISOLatin1StringEncoding];
if (!string) string = [[NSString alloc] initWithData:_data encoding:NSNonLossyASCIIStringEncoding];
if (!string) string = [[NSString alloc] initWithData:_data encoding:NSNonLossyASCIIStringEncoding];
if (_format == WAX_HTTP_JSON) {
json_parseString(L, [string UTF8String]);
}
else if (_format == WAX_HTTP_XML){
#ifdef WAX_XML_INCLUDED
wax_xml_parseString(L, [string UTF8String]);
#else
luaL_error(L, "Trying to parse xml, but xml library not included.");
#endif
}
else {
wax_fromObjc(L, "@", &string);
}
[string release];
}
else if (_format == WAX_HTTP_BINARY) {
wax_fromObjc(L, "@", &_data);
}
else {
luaL_error(L, "wax_http: Unknown wax_http format '%d'", _format);
}
wax_fromObjc(L, "@", &_response);
if (_error) {
wax_fromObjc(L, "@", &_error);
}
else {
lua_pushnil(L);
}
if (hasCallback && wax_pcall(L, 3, 0)) {
const char* error_string = lua_tostring(L, -1);
luaL_error(L, "Problem calling Lua function '%s' from wax_http.\n%s", WAX_HTTP_CALLBACK_FUNCTION_NAME, error_string);
}
_finished = YES;
END_STACK_MODIFY(L, 3)
}
@end