-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathWebServer.j
269 lines (230 loc) · 11.4 KB
/
WebServer.j
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
/*
* Created by Martin Carlberg on January 27, 2016.
* Copyright 2016, Martin Carlberg All rights reserved.
*/
@import <Foundation/CPObject.j>
@import "HTTPRequest.j"
@import "HTTPResponse.j"
@import "BackendFunctionRetrievemodel.j"
@import "BackendFunctionFetch.j"
@import "BackendFunctionModify.j"
@global require
@global BackendDocumentRootPath
@global BackendOptions
var url = require('url')
var fs = require('fs');
var _sharedInstance = nil;
@implementation WebServer : CPObject {
CPInteger port;
}
+ (WebServer) sharedInstance {
if (!_sharedInstance) {
_sharedInstance = [[WebServer alloc] init];
}
return _sharedInstance;
}
- (id)init {
self = [super init];
if (self) {
port = 1337;
}
return self;
}
- (void)startWebServer {
var http = require('http');
var databaseStore = [CPMutableDictionary dictionary];
var server = http.createServer(function (req, res) {
// req is an http.IncomingMessage, which is a Readable Stream
// res is an http.ServerResponse, which is a Writable Stream
var method = req.method;
var body = '';
// we want to get the data as utf8 strings
// If you don't set an encoding, then you'll get Buffer objects
req.setEncoding('utf8');
// Readable streams emit 'data' events once a listener is added
req.on('data', function (chunk) {
body += chunk;
});
// the end event tells you that you have entire body
req.on('end', function () {
switch (method) {
case "GET":
[self handleHttpGETRequest:req completionHandler:function(httpResponse) {
if ([httpResponse respondsToSelector:@selector(status)]) {
res.statusCode = [httpResponse status];
}
if ([httpResponse respondsToSelector:@selector(httpHeaders)]) {
[[httpResponse httpHeaders] enumerateKeysAndObjectsUsingBlock:function(headerName, headerValue) {
res.setHeader(headerName, headerValue);
}];
}
var data = [httpResponse readDataOfLength:[httpResponse contentLength]];
if (data != nil) {
// If we have a 'isa' property it is a CPData. Should be a Buffer if not and we can write a string or a Buffer
res.write(data.isa ? [data rawString] : data);
}
res.end();
}];
break;
case "POST":
[self handleHttpPOSTRequest:req body:body completionHandler:function(httpResponse) {
if ([httpResponse respondsToSelector:@selector(status)]) {
res.statusCode = [httpResponse status];
}
if ([httpResponse respondsToSelector:@selector(httpHeaders)]) {
[[httpResponse httpHeaders] enumerateKeysAndObjectsUsingBlock:function(headerName, headerValue) {
res.setHeader(headerName, headerValue);
}];
}
var data = [httpResponse readDataOfLength:[httpResponse contentLength]];
if (data != nil) {
// If we have a 'isa' property it is a CPData. Should be a Buffer if not and we can write a string or a Buffer
res.write(data.isa ? [data rawString] : data);
}
res.end();
}];
break;
default:
res.statusCode = 400;
res.write('error: Unsupported method ' + method);
res.end();
}
});
});
server.listen(port);
console.log("Webserver started on port " + port);
}
- (void)handleHttpGETRequest:(HTTPRequest)request completionHandler:(Function/*(CPObject<HTTPResponse>)*/)completionBlock {
var /*CPString*/ path = request.url;
var /*CPArray*/ pathComponents = [path pathComponents];
var /*CPMutableArray*/ unqualifiedComponents = [pathComponents mutableCopy];
var /*CPString*/ subpath;
var /*CPString*/ sessionKey;
var /*CPString*/ functionName;
var /*Class*/ functionClass = nil;
var /*CPDictionary*/ getQuery;
var /*CPMutableDictionary*/ parameters;
var urlParts = url.parse(path);
var pathname = urlParts.pathname;
if (pathname.startsWith("/backend")) {
try {
while (([unqualifiedComponents count] > 0) && ([[unqualifiedComponents lastObject] rangeOfString:@"="].location != CPNotFound)) {
[unqualifiedComponents removeLastObject];
}
switch ([unqualifiedComponents count]) {
case 0:
case 1:
// Path is invalid
return completionBlock([[UnauthorizedHTTPResponse alloc] initWithFunction:@"-"]);
case 2:
// Path contains only a function name
functionName = [unqualifiedComponents objectAtIndex:1];
functionClass = [self functionClassForName:functionName];
sessionKey = nil;
subpath = @"";
break;
default:
functionName = [unqualifiedComponents objectAtIndex:1];
functionClass = [self functionClassForName:functionName];
if (functionClass == nil) {
// Path contains a session key
sessionKey = [unqualifiedComponents objectAtIndex:1];
functionName = [unqualifiedComponents objectAtIndex:2];
functionClass = [self functionClassForName:functionName];
subpath = [[pathComponents subarrayWithRange:CPMakeRange(3, [pathComponents count] - 3)] componentsJoinedByString:@"/"];
/* if (functionClass == nil) {
// Path contains a session key, and an entity name
functionName = @"fetch";
functionClass = [BackendFunctionFetch class];
subpath = [[pathComponents subarrayWithRange:CPMakeRange(2, [pathComponents count] - 2)] componentsJoinedByString:@"/"];
}*/
} else {
// Path contains a function name and a subpath
subpath = [[pathComponents subarrayWithRange:CPMakeRange(2, [pathComponents count] - 2)] componentsJoinedByString:@"/"];
}
break;
}
parameters = [[request allHeaderFields] mutableCopy];
getQuery = [request parseGetParams];
if (getQuery != nil) {
parameters[@"getQuery"] = getQuery;
}
var /*CPObject <BackendFunction>*/ aFunction = [[functionClass alloc] initWithSubpath:subpath parameters:parameters];
if (aFunction) {
var parameterError = [aFunction parameterError];
if (parameterError) {
console.log("parameterError: " + [parameterError userInfo]);
}
if (!aFunction) {
return completionBlock([[UnauthorizedHTTPResponse alloc] initWithFunction:functionName]);
}
if (/*Authority check*/true) {
return [aFunction responseWithCompletionHandler:function(httpResponse) {
return completionBlock(httpResponse);
}];
} else {
return completionBlock([[UnauthorizedHTTPResponse alloc] initWithFunction:functionName]);
}
}
} catch (exception) {
return completionBlock([[ExceptionHTTPResponse alloc] initWithException:exception]);
}
} else if (BackendDocumentRootPath) {
// Ok, here we simulate a webserver as the request is not from the LightObject framework.
// Sometimes it is complicated to setup a webserver to make it run, this will make it very easy to start.
fs.readFile([BackendDocumentRootPath stringByAppendingPathComponent:pathname], function(err, data) {
if (err) {
if (BackendOptions.verbose) console.log("Accessing: " + [BackendDocumentRootPath stringByAppendingPathComponent:pathname] + " Not Found: " + err);
return completionBlock([[NotFoundHTTPResponse alloc] init]);
}
if (BackendOptions.verbose) console.log("Accessing: " + [BackendDocumentRootPath stringByAppendingPathComponent:pathname] + " with length: " + data.length);
var pathExtension = [pathname pathExtension];
if (pathExtension === @"html" || pathExtension === @"htm") {
return completionBlock([[HtmlHTTPResponse alloc] initWithBytes:data]);
}
return completionBlock([[BufferHTTPResponse alloc] initWithBytes:data]);
});
}
}
- (CPObject<HTTPResponse>)handleHttpPOSTRequest:(HTTPRequest)request body:(CPString)data completionHandler:(Function/*(CPObject<HTTPResponse>)*/)completionBlock {
var /*CPString*/ path = request.url;
var /*CPData*/ body = request.body;
var /*CPArray*/ pathComponents = [path pathComponents];
var /*CPString*/ sessionKey;
var /*CPString*/ functionName = [pathComponents count] > 0 ? [pathComponents objectAtIndex:2] : nil;
var /*Class*/ functionClass = nil;
var /*CPObject <BackendFunction>*/ aFunction;
// var /*CPObject <HTTPResponse>*/ response;
var jsonObject = [data objectFromJSON];
var /*CPMutableDictionary*/ parameters = [CPMutableDictionary dictionaryWithJSObject:jsonObject recursively:YES];
functionClass = [self functionClassForName:functionName];
// if (!jsonObject) {
// return [[ErrorHTTPResponse alloc] initWithError:postBodyJSONError session:nil];
// }
if ([pathComponents count] < 3) {
aFunction = [[functionClass alloc] initWithSubpath:nil parameters:parameters];
} else {
aFunction = [[functionClass alloc] initWithSubpath:[CPString pathWithComponents:[pathComponents subarrayWithRange:CPMakeRange (2, [pathComponents count] - 2)]] parameters:parameters];
}
var parameterError = [aFunction parameterError];
if (parameterError) {
console.log("parameterError: " + [parameterError userInfo]);
}
if (/*Authority check*/true) {
return [aFunction responseWithCompletionHandler:function(httpResponse) {
return completionBlock(httpResponse);
}];
} else {
return completionBlock([[UnauthorizedHTTPResponse alloc] initWithFunction:functionName]);
}
}
- (Class)functionClassForName:(CPString)functionName {
//if ([functionName rangeOfCharacterFromSet:[[CPCharacterSet letterCharacterSet] invertedSet]].location === CPNotFound)
// As above function is missing in Cappuccino we split the string to check if string contains invalid characters
if ([[functionName componentsSeparatedByCharactersInSet:[[CPCharacterSet letterCharacterSet] invertedSet]] count] === 1) {
return CPClassFromString([CPString stringWithFormat:@"BackendFunction%@", [functionName capitalizedString]]);
} else {
return nil;
}
}
@end