forked from adamfowleruk/mljs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmljs-webserver.js
362 lines (279 loc) · 11.5 KB
/
mljs-webserver.js
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
var http = require('http'),
crypto = require('crypto'),
_und = require('underscore'),
mljs = require('mljs');
// Provides a set of classes and server framework to run MLJS powered HTML5 apps with WebSocket and alerting support in a Node.js web server.
var ConnectionManager = function() {
this.clients = new Array();
this.nextID = 1;
};
ConnectionManager.prototype.registerClient = function(websocket,securityInfo) {
var self = this;
var newID = "" + this.nextID++; // TODO add NOW timezone to id with hyphen
var client = {
id: newID,
security: securityInfo,
websocket: websocket
};
this.clients.push(client);
return client.id;
};
ConnectionManager.prototype.unregisterClient = function(id) {
var newClients = new Array();
for (var i = 0, max = this.clients.length,client;i < max;i++) {
client = this.clients[i];
if (id == client.id) {
// don't add
} else {
newClients.push(client);
}
}
this.clients = newClients;
};
ConnectionManager.prototype.getClient = function(id) {
for (var i = 0, max = this.clients.length,client;i < max;i++) {
client = this.clients[i];
if (id == client.id) {
return client;
}
}
return null;
};
var AlertServer = function(alertListenPort,connectionManager) {
this.port = alertListenPort;
this.manager = connectionManager;
// REST SERVER ENDPOINT for passing on alerts
var restify = require('restify');
var self = this;
function respond(req, res, next) {
//res.send('hello client ' + req.params.clientid);
//console.log("Received REST message");
// determine which node the message is for
var node = req.params.clientid;
var client = self.getClient(node);
if (null != client && undefined != client.websocket) {
//console.log("Sending client node '" + node + "' message: '" + req.body.toString() + "'") // TESTED - WORKS A TREAT!
client.websocket.sendUTF(JSON.stringify({response: "alert", content: req.body.toString()})); // TESTED - WORKS A TREAT! - TODO check this works fine for XML too
// TODO do we want to send a multipart that describes the data???
}
res.send("OK");
};
this.server = restify.createServer({name: "MLJSAlertServer"});
this.server.use(restify.bodyParser()); // { mapParams: false }
// Server request 1: handle echo directly to client
//server.get('/echo/:clientid', respond);
//server.head('/echo/:clientid', respond);
this.server.post('/alert/:clientid', respond);
var self = this;
this.server.listen(this.port, function() {
console.log((new Date()) + ' - MLJS Alert Receiving HTTP Server listening at %s', self.server.url);
});
};
AlertServer.prototype.close = function() {
this.server.close();
};
var WebServer = function(port,connectionManager,appBaseDirectory,restServer,restPort) {
this.port = port;
this.manager = connectionManager;
this.base = appBaseDirectory;
// require here in case some things aren't supported
var WebSocketServer = require('websocket').server;
var fs = require('fs');
var self = this;
// HTTP SERVER FIRST
var mimes = {
xml: "text/xml", txt: "text/plain", html: "text/html; charset=UTF-8", png: "image/png", jpg: "image/jpeg", gif: "image/gif", js: "text/javascript", css: "text/css"
}; // TODO get MIMEs supported from MarkLogic server
function parseCookies (request) {
var list = {},
rc = request.headers.cookie;
rc && rc.split(';').forEach(function( cookie ) {
var parts = cookie.split('=');
list[parts.shift().trim()] = unescape(parts.join('='));
});
return list;
};
this.httpServer = http.createServer(
// TODO handle AUTH immediately, shadowed from MarkLogic Server
function(request, res) {
console.log((new Date()) + ' Received request for ' + request.url);
// check and set cookie with client id
var cookies = parseCookies(request);
var cookie = cookies["mljsWebServerClientId"];
var clientid = cookie;
if (null == cookie) {
// create client reference
clientid = self.manager.registerClient(null,null); // TODO security auth info from HTTP auth call(s)
}
var client = self.manager.getClient(clientid);
if (0 == request.url.indexOf("/v1/")) { // TODO future proof versioned URLs
// forward on to REST API
// TODO USE MLJS INTERNAL CONNECTION MANAGERS TO HANDLE CONNECTION AND AUTH
// use connection to send request. Pass on response to listener
var options = {
host: restServer,
port: restPort,
path: request.url,
method: request.method
,headers: request.headers
};
console.log("Sending REST request to: " + options.method + " " + options.host + ":" + options.port + options.path);
// TODO if it's our MLJS alerts extension being called then add the server alert URL parameter encoded to the request URL (override one from app if present)
var creq = http.request(options,function (response) {
console.log("REST HTTP Request callback called");
var data = "";
response.on('data', function(chunk) {
console.log("REST proxy data(chunk): " + chunk);
data += chunk;
});
var complete = function() {
console.log("Got response from REST server: " + response.statusCode);
res.writeHead(response.statusCode, {
'Content-Type': response.headers["Content-Type"],
'Set-Cookie': 'mljsWebServerClientId=' + clientid
});
//console.log(data);
if (data.length > 0) {
console.log("writing data: " + data);
res.write(data);
}
res.end();
console.log("End of sending rest proxy response");
};
response.on('end', function() {
console.log("REST proxy end()");
complete();
}); // response end callback
response.on('close', function() {
console.log("REST proxy close()");
complete();
}); // response end callback
response.on('error', function() {
console.log("REST proxy error()");
complete();
}); // response end callback
if (options.method == "PUT" || options.method == "DELETE") {
// console.log("Forcing call to PUT or DELETE");
// complete();
}
}); // request response callback
// send request data as necessary
request.on('data', function(chunk) {
console.log('HTTP REST PROXY: GOT REQUEST DATA: Got %d bytes of data: ' + chunk, chunk.length);
creq.write(chunk);
});
creq.on("error",function(e) {
console.log("creq: REQUEST ERROR: " + e);
});
//creq.write("\n");
request.on("end", function() {
console.log("Calling REST client request.end()");
creq.end();
});
} else /* if (request.url.indexOf("/public/") == 0) */ {
console.log("Public files requested");
// get relative file path
var path = self.base + request.url;
// determine MIME from file ext
var dotpos = path.lastIndexOf(".");
var ext = path.substring(dotpos + 1);
var mime = mimes[ext];
// return file
console.log("Fetching file: " + path);
fs.readFile(path, function (err, data) {
if (err) {
console.log("404 File Not Found: " + path);
res.writeHead(404, {'Content-Type': 'text/html'});
res.write("<html><head><title>404 not found</title></head><body><h1>File Not Found</h1></body></html>");
res.end();
} else {
// write header and content type
res.writeHead(200, {
'Content-Type': mime,
'Transfer-Encoding': 'chunked',
'Set-Cookie': 'mljsWebServerClientId=' + clientid,
});
//console.log(data);
res.write(data);
res.end();
}
});
/*} else {
res.writeHead(404);
res.end();
*/
}
}
);
this.httpServer.listen(this.port, function() {
console.log((new Date()) + ' - MLJS Web Server is listening on port ' + self.port);
});
// WEBSOCKETS SERVER NOW
// SET UP CLIENT WEB SOCKETS SERVER
this.wsServer = new WebSocketServer({
httpServer: self.httpServer,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false
});
function originIsAllowed(origin) {
// TODO put logic here to detect whether the specified origin is allowed.
return true;
};
this.wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
// Make sure we only accept requests from an allowed origin
request.reject();
console.log((new Date()) + ' - MLJS Web Server Connection from origin ' + request.origin + ' rejected.');
return;
}
var socketClientConnection = request.accept('mljs-alerts', request.origin);
console.log((new Date()) + ' - MLJS Web Server Connection accepted.');
// TODO get client id from web server cookie (from http original page request)
// Client request type 1: Receive a random message - reflect back to client
socketClientConnection.on('message', function(message) {
if (message.type === 'utf8') {
// TODO handle combined query submitted as JSON document string {request: "search", content: combinedQueryJson}
// TODO also handle {request: "subscribe", content: combinedQueryJson}
// TODO handle {request: "test"}
var json = JSON.parse(message.stringData); // TODO verify this is right line
if ("test" == json.request) {
socketClientConnection.sendUTF(JSON.stringify({response:"test"}));
} else if ("subscribe" == json.request) {
// do via rest call instead?
} else if ("search" == json.request) {
// do via rest call instead?
}
}
else if (message.type === 'binary') {
console.log(' - MLJS Web Server Received Binary Message of ' + message.binaryData.length + ' bytes');
socketClientConnection.sendBytes(message.binaryData); // TODO why are we replaying this?
}
});
socketClientConnection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' - MLJS Web Server Peer ' + socketClientConnection.remoteAddress + ' disconnecting...');
// TODO Unsubscribe from ML location intel
console.log((new Date()) + ' - MLJS Web Server Peer ' + socketClientConnection.remoteAddress + ' disconnected.');
});
});
};
// now overall MLJSServer object
var MLJSWebServer = function(webPort,alertPort,appBaseDirectory,restServer,restPort) {
this.manager = new ConnectionManager();
this.webServer = new WebServer(webPort,this.manager,appBaseDirectory,restServer,restPort); // TODO support this
this.alertServer = new AlertServer(alertPort,this.manager);
};
MLJSWebServer.prototype.close = function() {
this.webServer.close();
this.alertServer.close();
};
module.exports =
{
MLJSWebServer: MLJSWebServer,
AlertServer: AlertServer,
WebServer: WebServer,
ConnectionManager: ConnectionManager
};