-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathrun.js
414 lines (349 loc) · 12 KB
/
run.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
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
404
405
406
407
408
409
410
411
412
413
414
/* SERVER DEFAULT CONFIGURATION */
var serverConf= {
usedefaultuser: true,
defaultuser: 'admin',
dbsrc: '.sqldb',
port: 8081,
serverSecret: 'onlyMeAndGitHubUsersKnowIt! - Please,change this for your use'
}
/* DEFINITIONS */
var app = require('express')()
, bodyParser = require('body-parser')
, cookieParser = require('cookie-parser')
, expressSession = require('express-session')
, multipartParser = require('connect-multiparty')
, compression = require('compression')
, fs = require('fs')
, io = null
, _token= false
, server = null
, store = new expressSession.MemoryStore
, readline = require('readline')
, sqlite3 = require('sqlite3').verbose()
, db = null // ':memory:'
, rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
/* MIDLEWARES */
app.use(compression());
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(multipartParser({ uploadDir: '/ppw/tmp/' }));
app.use(expressSession({
secret: serverConf.serverSecret,
store: store
}));
/**
* Useful services to work with the API
*/
Services= (function(){
var listDir= function(path){
var files= fs.readdirSync(path);
var i= files.length-1;
var list= [];
do{
//while(i>=0 && --i){
if(files[i][0] != '.' && files[i] != 'README')
list.push(files[i]);
//}
}while(i--);
return list;
};
var deliver= function(url, req, res){
url= url.replace(/(\/\..*)|(\?.*)|(\#.*)/ig, '');
if(url[url.length-1] == '/')
url+= 'index.html';
fs.readFile(__dirname+url, function(err, data){
if (err) {
res.writeHead(500);
return res.end('Error loading: ' + __dirname + url);
}
if(url.match(/\.js(\?|$)/i)){
res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
}
if(url.match(/\.json(\?|$)/i)){
res.setHeader('Content-Type', 'text/json; charset=utf-8');
}
if(url.match(/\.html(\?|$)/i)){
res.setHeader('Content-Type', 'text/html; charset=utf-8');
}
if(url.match(/\.css$/i)){
res.setHeader('Content-Type', 'text/css; charset=utf-8');
}
if(url.match(/\.png$/i)){
res.setHeader('Content-Type', 'image/png');
}
if(url.match(/\.jpg$/i)){
res.setHeader('Content-Type', 'image/jpg');
}
if(url.match(/\.gif$/i)){
res.setHeader('Content-Type', 'image/gif');
}
res.writeHead(200);
// fixing a bug in nodejs, for empty files(explodes the gzip module!)
if(!data || !data.length)
data= "// Empty file!";
res.end(data);
});
};
var _logoff= function(req, res){
var data= { status: 'done' };
req.session.destroy();
res.writeHead(200);
res.end(JSON.stringify(data));
};
var _isLogged= function(req){
return req.session.auth? true: false;
};
var _login= function(req, res){
var token= req.body.token,
qr= "SELECT userid,\
username,\
usertoken\
FROM userdata\
WHERE usertoken= ?",
auth= false,
data= {};
// if already logged
if(_isLogged(req)){
res.writeHead(200);
res.end(JSON.stringify({auth: true, status: 200}));
return;
}
db.serialize(function(){
db.each(qr, token, function(err, row){
auth= row.usertoken;
return false;
}, function(){
if(auth){
data.auth= true;
data.status= 200;
req.session.token= token;
req.session.auth= true;
}else{
req.session= null;
data.status= 200;
data.auth= false;
}
res.writeHead(200);
res.end(JSON.stringify(data));
});
});
};
var _socketsEvents= function (socket) {
socket.on('listening', function (talk) {
console.log("someone joined =================== "+talk);
socket.set('watchingTo', talk);
socket.join(talk);
});
socket.on('remote-control-send', function (data) {
//socket.broadcast.emit('control-command', data); // IS WORKING!!!
socket.get('watchingTo', function(err, watchingTo){
socket.broadcast
.to( watchingTo )
.emit('control-command', data);
});
});
}
var _init= function(){
var url= "",
root= '/ppw/_tools/remote/index.html';
app.get('/run.js', function(req, res){
url= root;
deliver(url, req, res);
});
app.get('/', function(req, res){
url= root;
deliver(url, req, res);
});
// API - get
app.get('/api/:command', function(req, res){
var data= {
demos: [],
talks: [],
errors: [],
auth: _isLogged(req)
}
res.setHeader('Content-Type', 'text/json; charset=utf-8');
switch(req.params.command){
case "verifylogin":{
// will just return the data object as it is
break;
}
case "getTalksList":{
data.talks= Services.listDir('./talks/');
break;
}
case "getDemosList":{
data.demos= Services.listDir('./_demos/');
break;
}
case "logoff":{
_logoff(req, res);
return;
break;
}
case "remoteControl":{
//
break;
}
}
res.end(JSON.stringify(data));
});
// API - post
app.post('/api/:command', function(req, res){
var postData= req.body;
res.setHeader('Content-Type', 'text/json; charset=utf-8');
if(req.params.command == 'auth'){
_login(req, res);
return;
}
if(!_isLogged(req, res)){
return false;
}
/*switch(req.params.command){
case "broadcast":{
postData;
//io.sockets.in(postData.talk).send('control-command', postData);
('control-command', postData);
break;
}
}*/
//res.end(JSON.stringify(data));
});
// filtering only authenticated users
app.get(/^\/ppw\/_tools\/remote\/(basic|full)\/.*/, function(req, res){
if(_isLogged(req, res))
deliver(req.url, req, res);
else{
res.redirect('/');
}
});
// File deliveries
app.get(/^\/ppw\/.*/, function(req, res){
deliver(req.url, req, res);
});
app.get(/^\/talks\/.*/, function(req, res){
deliver(req.url, req, res);
});
app.get(/^\/_demos\/.*/, function(req, res){
deliver(req.url, req, res);
});
// listeners
server= app.listen(serverConf.port);
io= require('socket.io').listen(server);
io.sockets.on('connection', _socketsEvents);
// just announcing the server initialization...
console.log('[PPW] Listening on '+ server.address()? server.address(): '????');
if(_token)
console.log('[PPW] Your token is ' + _token);
console.log();
};
return {
init: _init,
listDir: listDir
}
})();
/**
* Asks for the token, on the CONSOLE, the first time the user runs it.
*/
var getToken= function(fn, repeat){
if(!repeat)
console.log("[PPW] It looks like it is your first time here!\n Please, define a secret token to identify the ADMIN user:");
rl.question("> ",
function(answer){
if(answer.length<3){
console.log("[PPW] At least 3 characters, please!");
getToken(fn, true);
return;
}else{
console.log("[PPW] Your token was set!\n You will use it to activate locked features.\n");
_token= answer;
if(fn && typeof fn == 'function'){
try{
fn(_token);
}catch(e){
console.log("[PPW][ERROR] Failed executing the callback for getToken!");
}
}
}
});
};
/**
* Verifies wether the database exists or not.
*
* In case it does not exist, it is created with its tables.
*/
var verifyDB= function(){
var stats = null;
try{
stats= fs.lstatSync(serverConf.dbsrc);
}catch(e){}
db= new sqlite3.Database(serverConf.dbsrc);
// DATABASE does not exist
if(!stats){
// must create the database
db.serialize(function(){
// TABLE SERVERCONFIG
db.run("CREATE TABLE serverconfig (confid INTEGER, usedefaultuser INTEGER, defaultuser TEXT)");
var stmt = db.prepare("INSERT INTO serverconfig VALUES (?, ?, ?)");
stmt.run(1, serverConf.usedefaultuser, serverConf.defaultuser);
stmt.finalize();
// TABLE USERDATA
db.run("CREATE TABLE userdata (userid INTEGER, username TEXT, usertoken TEXT)");
getToken(function(token){
var stmt = db.prepare("INSERT INTO userdata VALUES (?, ?, ?)");
stmt.run(1, serverConf.defaultuser, token);
stmt.finalize();
Services.init();
});
});
}else{
// database exists, let's verify the server config
db.each("SELECT confid, usedefaultuser, defaultuser FROM serverconfig", function(err, row) {
if(err){
console.log(err)
}else{
// if the server config has changed, let's update it.
if(serverConf.usedefaultuser != row.usedefaultuser
||
serverConf.defaultuser != row.defaultuser){
var stmt = db.prepare("UPDATE serverconfig SET usedefaultuser=?, defaultuser=? where confid=1");
stmt.run(serverConf.usedefaultuser, serverConf.defaultuser);
stmt.finalize();
}
if(process.argv.indexOf('renew') >= 0 ){
getToken(function(token){
var stmt = db.prepare("UPDATE userdata SET usertoken=? where username=?");
stmt.run(token, serverConf.defaultuser);
stmt.finalize();
Services.init();
});
}else{
Services.init();
}
}
});
}
}
/**
* Returns the current user(from session or from submited login).
*/
var getUser= function(req){
// if it should use a default user
// what means, no other users will work on this server
if(serverConf.usedefaultuser){
return serverConf.defaultuser;
}else{
// needs the req to work
if(!req || !req.session){
return false;
}
// returns the currently logged user
return req.session.username;
}
};
// initializing everything, starting by calling the verifyDB.
verifyDB();