-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
362 lines (345 loc) · 12.1 KB
/
server.js
File metadata and controls
362 lines (345 loc) · 12.1 KB
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
var sys = require("sys")
, http = require("http")
, path = require("path")
, url = require("url")
, qs = require("querystring")
, filesys = require("fs")
, crypto = require('crypto')
, shasum = crypto.createHash('sha1')
, $ = require('jquery')
;
function zfwService(){
// Members
/** \brief port
port that the server will listen to, use http://localhost:port to connect to this instance
*/
this.port = 2727;
/** \brief view root
path that contains viewscripts (should not be in static_root)
*/
this.view_root = 'views';
/** \brief controller root
path that contains controller-scripts (should not be in static_root)
*/
this.controller_root = 'controller';
/** \brief static root
path that contains viewscripts (should be a path that only contains public information)
*/
this.static_root = 'htdocs';
/** more service variables: suggestion **/
//INIT
var self = this;
//CODE
}
/** \brief default action
takes two parameters (user,password)
both parameters have to be set
*/
zfwService.prototype.main = function ( ){
//INIT
var self = this;
//CODE
http.createServer(function(request,response){
var body = '';
request.on('data', function (data) {
body += data;
if (body.length > self.max_data_item_size ) {
request.connection.destroy();
}
});
request.on('end', function () {
// extract data, only when not POST
var data = qs.parse(url.parse(request.url).query);
if ( body.length ){
// use POST DATA (rejects all request.url.query parameters)
var keypos = body.indexOf('key=') + 4;
var keyendpos = body.indexOf('&',keypos);
if ( keyendpos === -1 )
data.key = body.substr(keypos,body.length-keypos);
else
data.key = body.substr(keypos,keyendpos-keypos);
var bodypos = body.indexOf('body=') + 5;
if ( bodypos >= 0 ){
bdata = body.substr(bodypos,body.length - bodypos);
data.body = bdata;
}
}
self.route(request,response,data);
});
}).listen(self.port);
};
/** \brief error
create a error-message
*/
zfwService.prototype.error = function (/*JSObject*/ response, /*STRING*/ code, /*STRING*/ message){
//INIT
var self = this;
//CODE
response.writeHeader(code, {"Content-Type": "text/plain"});
response.write(message + "\n");
response.end();
console.error(message);
// throw message;
}
/** \brief processTemplate
load template by name, process template values, return (by promise) a processed view
*/
zfwService.prototype.processTemplate = function ( /*STRING*/ view_file, /*JSObject*/ js_data){
//INIT
var self = this;
var template_regexp = new RegExp("{(.*?)}",'g');
var template_code = view_file.match(template_regexp);
var template_dfd = $.Deferred();
var include_dfd = $.Deferred();
var include_count = 0;
var dfds = []; // JQueryDeferred
var index;
//CODE
// simple template values {name} - not
/*
for ( index in template_code ){
// scrope: this only trusted code ?
var template = template_code[index];
template = template.replace(/^{/,'controller.view.');
template = template.replace(/}/,';');
try {
result = eval(template);
console.log(template_code[index], result);
view_file = view_file.replace(template_code[index], result);
} catch ( e ){
console.warn('undefined view script variable:' + template);
}
}
*/
// complex viewscripts with include
template_regexp = new RegExp("<\\?js (.*?)\\?>",'g');
template_code = view_file.match(template_regexp);
// console.log(template_code);
for ( index in template_code ){
// scrope: this only trusted code ?
var template = template_code[index];
var template_result;
if ( template.indexOf('include(') >= 0 ) {
include_count = include_count + 1;
continue; // deferred later
}
template = template.replace(/^<\?js/,'{ var self = js_data; ');
template = template.replace(/return/g,'template_result =');
template = template.replace(/\?>$/,'}');
var my_self = self;
eval(template);
self = my_self;
// console.log(template,template_result,self);
if ( typeof template_result === 'undefined' )
template_result = '';
view_file = view_file.replace(template_code[index], template_result);
}
include_dfd.promise();
if ( include_count === 0 ){
include_dfd.resolve();
}else{
for ( var index in template_code ){
// scrope: this only trusted code ?
var template = template_code[index];
var template_result;
if ( template.indexOf('include') === -1) continue;
var include_file = template.replace(/.*include\('/,'').replace(/'\).*/,'');
// console.log('include: ' + include_file);
var dfd = $.Deferred();
var included_count = 0;
var update_fn = function(include_file_name,replacement_pattern){
//console.log(include_file_name);
self.readIncludeFile(include_file_name).done(function(include_file_data){
// console.log(include_file_data);
// console.log('---------- read include: ' + include_file_name + include_file_data.length);
self.processTemplate(include_file_data,js_data).done(function(transformed_include_file_data){
view_file = view_file.replace(replacement_pattern,transformed_include_file_data);
// console.log('---------- resolved include: ' + include_file_name + transformed_include_file_data.length);
included_count = included_count + 1;
if ( included_count == include_count ){
// console.log(view_file + '\n\n');
include_dfd.resolve(view_file);
}
}).fail(include_dfd.reject);
}).fail(include_dfd.reject);
};
update_fn(include_file,template_code[index]);
}
}
include_dfd.done(function(){
// console.log('---------- finish template ',arguments);
template_dfd.resolve(view_file);
})
.fail(template_dfd.reject);
return template_dfd.promise();
};
/** \brief route
extract parameters, load sub-scripts, execute view data
*/
zfwService.prototype.route = function ( /*JSObject*/ request, /*JSObject*/ response, /*STRING*/ data){
//INIT
var self = this;
var request_path = url.parse(request.url).pathname;
var remote_ip = 'localhost';
var server_name = 'http://localhost:' + self.port + '/';
var iso_date = '22/Jun/2013:22:12:50 +0000'; // TODO: use (new Date()).formatString('as iso like apache');
var client_id = 'Mozilla/5.0 (X11; Linux x86_64; rv:21.0) Gecko/20100101 Firefox/21.0'; // TODO: extract from request
var method = 'POST'; // TODO: extract from request
//CODE
try {
// try to return a file from the htdocs directory
self.routeFile(response,request_path).done(function(){
console.log( remote_ip + ' - - [' + iso_date + '] "' + method + ' ' + request.url + ' HTTP/1.1" 200 '
+ response.length + ' "' + server_name + '" "' + client_id + '"'
);
}).fail(function(){
self.routeController(request,response,data);
});
} catch ( e ){
response.end();
}
};
/** \brief routeController
extract parameters, load sub-scripts, execute view data
*/
zfwService.prototype.routeController = function ( /*JSObject*/ request, /*JSObject*/ response, /*STRING*/ data){
//INIT
var self = this;
var request_path = url.parse(request.url).pathname;
var control, action;
var request_path_elements = request_path.split(/\//);
//CODE
if ( request_path === '/' )
control = 'index';
else
control = request_path_elements[1];
if ( !control.indexOf(/[a-z0-9]*/) ){
return self.error(response,500,'invalid control');
}
// console.log(request_path_elements);
if ( request_path === '/'
|| request_path_elements.length < 3
|| request_path_elements[2] === '' // '/search/'
)
action = 'index';
else
action = request_path_elements[2];
if ( !action.indexOf(/[a-z0-9]*/) ){
return self.error(response,500,'invalid action');
}
var controller_script = self.controller_root + '/' + control + 'Controller.js';
var full_controller_path = process.cwd() + '/' + controller_script;
var view_script = self.view_root + '/scripts/' + control + '/' + action + '.html';
var full_view_path = process.cwd() + '/' + view_script;
filesys.exists(full_view_path,function(exists){
if ( ! exists )
return self.error(response,404,'view does not exist:' + control + ':' + full_view_path);
filesys.exists(full_controller_path,function(exists){
if ( ! exists )
return self.error(response,404,'controller does not exist:' + control + ':' + full_controller_path);
filesys.readFile(full_view_path, "binary", function(error, view_file) {
if ( error ) {
self.error(response,500,error);
} else {
// response.write(view_file, "binary");
// console.log(view_file, typeof view_file);
// TODO: force node.js to reload the file
var name = require.resolve('./' + controller_script);
delete require.cache[name];
var controller = require('./' + controller_script).controller;
controller.parameter = data;
controller.response = response;
if ( typeof controller.response.error === 'undefined' )
controller.response.error = function(code, message){
return self.error(response,code,message);
};
controller.view = {};
controller.model = { simple_store: self.simple_store }; // really: self.getModel()
controller[action + 'Action']();
// TODO: better view code
self.processTemplate(view_file,controller.view).done(function(transformed_file){
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(transformed_file, "binary");
response.end();
}).fail(function(){
response.end();
});
}
});
});
});
};
/** \brief route file
return a static file to the client
*/
zfwService.prototype.routeFile = function (/*JSObject*/ response, /*STRING*/ filename){
//INIT
var self = this;
var dfd = $.Deferred();
//CODE
if ( filename.indexOf('..') !== -1 ){
return dfd.promise().reject();
}
var full_path = process.cwd() + '/' + self.static_root + '/' + filename;
dfd.promise();
if ( filename === '/' )
return dfd.reject();
filesys.exists(full_path,function(exists){
if ( ! exists ){
// console.log('static file does not exist', full_path);
return dfd.reject();
}
// console.log(full_path);
filesys.readFile(full_path, 'binary', function(error, data_file) {
if ( error ) {
response.writeHeader(500, {'Content-Type': 'text/plain'});
response.write(error + "\n");
response.end();
dfd.reject(error);
return;
}
var content_type = 'text/plain';
if ( full_path.match(/\.js$/) || full_path.match(/\.js?.*/) )
content_type = 'text/javascript';
if ( full_path.match(/\.css$/) )
content_type = 'text/css';
if ( full_path.match(/\.png$/) )
content_type = 'image/png';
// console.log(content_type);
response.writeHeader(200, {'Content-Type': content_type});
response.write(data_file, "binary");
response.end();
delete data_file;
// console.log('static', full_path);
dfd.resolve();
});
});
return dfd.promise();
};
/** \brief read Include File
deferred reading of include-files required for template processing
*/
zfwService.prototype.readIncludeFile = function (/*STRING*/ filename){
//INIT
var self = this;
var dfd = $.Deferred();
//CODE
var full_path = process.cwd() + '/' + self.view_root + '/' + filename;
// console.log(full_path);
filesys.exists(full_path,function(exists){
if ( ! exists ){
console.error(full_path + ' does not exist for include');
return dfd.reject();
}
filesys.readFile(full_path, "binary", function(error, data_file) {
if ( error ) {
console.error(error);
return dfd.reject(error);
}
return dfd.resolve(data_file);
});
});
return dfd.promise();
};
var service = new zfwService();
service.main();