-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
518 lines (467 loc) · 14.9 KB
/
index.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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
//Used modules
var http = require('http');
var path = require('path');
var fs = require('fs');
var express = require('express');
var EventManager = require('./eventmanager').EventManager;
//Express init
//var app = express();
var app = express.createServer();
//Websockets init thorough express
//var server = http.createServer(app);
var io = require('socket.io').listen(app);
io.set('log level', 1);
//Database connection for events
var eventManager = new EventManager('localhost', 27017);
//Use express config
app.configure(function(){
app.use(express.methodOverride());
app.use(express.bodyParser());
app.use(app.router);
});
/*
* HTTP server init
*/
var serve_http = function(request, response){
//console.log('requester IP:'+request.connection.remoteAddress);
//console.log('requesting file:'+request.url);
var filePath = '.' + request.url;
if(filePath.indexOf('?')!=-1) filePath = filePath.substr(0,filePath.indexOf('?'));
if (filePath.substr(-1)==('/')) filePath += 'index.html';
var extname = path.extname(filePath);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
case '.png':
contentType = 'image/png';
break;
case '.gif':
contentType = 'imge/gif';
break;
case '.jpg':
contentType = 'image/jpeg';
break;
case '.ico':
contentType = 'image/x-icon';
break;
case '.svg':
contentType = 'image/svg+xml';
break;
case '.swf':
contentType = 'application/x-shockwave-flash';
break;
case '.ogg':
contentType = 'application/ogg';
break;
}
path.exists(filePath, function(exists) {
if (exists) {
fs.readFile(filePath, function(error, content) {
if (error) {
response.writeHead(500);
response.end();
} else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
});
} else {
response.writeHead(404);
response.end();
}
});
};
var show_stats = function(request, response){
}
app.get('/student/*', function (request, response) {
serve_http(request, response);
});
app.get('/CSS/*', function (request, response) {
serve_http(request, response);
});
app.get('/teacher/*', function (request, response) {
serve_http(request, response);
});
app.get('/users/photos/*', function (request, response) {
serve_http(request, response);
});
app.get('/stats', function (request, response){
show_stats(request, response);
});
/*
* HTTP server end
*/
//sessions: list of users in the session, including their status
//queues: list of the users in the waiting queue (identified by IP)
/* session_item = {
username: ["username", ..],
exercise: 0,
help: false,
IP: "IP"
}
queue_item = IPs
question_item = {
description: "blah",
votes: ["user1", "user2"]
}
*/
var sessions = {};
var queues = {};
var questions = {};
function getSession(id){
if(sessions[id]==undefined) sessions[id] = [];
return sessions[id];
}
function getQueue(id){
if(queues[id]==undefined) queues[id] = [];
return queues[id];
}
function getQuestions(id){
if(questions[id]==undefined) questions[id] = [];
return questions[id];
}
//User manager
function getUserByParam(userParams, handler){
var mongodb = require('mongodb');
var server = new mongodb.Server("127.0.0.1", 27017);
new mongodb.Db('classon', server, {safe:false}).open(function (error, client) {
if (error) throw error;
var collection = new mongodb.Collection(client, 'users');
collection.find(userParams).toArray(function(err, docs) {
handler(err, docs);
client.close();
});
});
}
//Get user info of an array of users
function getUsersByUsername(usernameArray, userInfoArray, handler){
if(usernameArray.length>0){
var username = usernameArray.pop();
getUserByParam({username: username}, function(error, userInfo){
if(!error && userInfo.length>0){
userInfoArray.push(userInfo[0]);
getUsersByUsername(usernameArray, userInfoArray, handler);
}else{
handler("error");
}
});
}else{
handler(null, userInfoArray);
}
}
//Send event to teacher
function sendEventToSession(event, sessionType){
var clients = io.sockets.clients();
for(var i=0; i<clients.length; i++){
clients[i].get(sessionType, function(err, session){
if(session == event.session){//Check the teacher
clients[i].emit('event', event);
console.log('emit new event to teacher in session:'+session);
}
});
}
}
//Send queue position to connected students
function sendQueuePositions(userIPs, solvedIP){
var clients = io.sockets.clients();
for(var i=0; i<clients.length; i++){
//fakeIP
//clients[i].get("fakeIP", function(err, fakeIP){
var clientIP = clients[i].handshake.address.address;
//clientIP = fakeIP;
var position = userIPs.indexOf(clientIP);
//console.log('sendQueuePositions: check '+userIPs+' and '+fakeIP);
if(position!=-1){
clients[i].emit('update queue', position+1);
//console.log('emitted update queue to: '+fakeIP);
}
if(solvedIP){
if(solvedIP==clientIP){
clients[i].emit('update queue', 0);
//console.log('emitted update queue to: '+fakeIP);
}
}
//});
}
}
//To be refactorized
function sendQuestions(event, sessionType){
var clients = io.sockets.clients();
for(var i=0; i<clients.length; i++){
clients[i].get(sessionType, function(err, session){
if(session == event.session){
clients[i].emit('update questions', event.questions);
console.log('emit new questions to session:'+session);
}
});
}
}
function findLastQuestion(questions, username){
for(var i=questions.length-1; i>=0;i--){
if(questions[i].votes[0]==username){
//console.log('found user question in position '+i);
return i;
}
}
//console.log('user question not found');
return -1;
}
//Connection of the new websocket client
io.sockets.on('connection', function (socket) {
//Event to request user list (TEACHER)
socket.on('userList', function (userParams) {
//console.log('userList:'+JSON.stringify(userParams));
getUserByParam(userParams, function(err, docs){
if(err){
console.log('Error: while retrieveing user list');
socket.emit('userListResp', []);
}else{
//console.log('docs:'+JSON.stringify(docs));
socket.emit('userListResp', docs);
}
});
});
//Learning event (STUDENT)
socket.on('new event', function(event){
eventManager.save(event, function(error, events){
var event = events[0];
//fakeIP
event.IP = socket.handshake.address.address;
console.log('new event:'+JSON.stringify(event));
//Forward event to the teachers + other students: old
//socket.broadcast.emit('event', event);
if(event.eventType == "vote"){
var my_questions = getQuestions(event.session);
my_questions[event.qid].votes.push(event.user[0]);
event.questions = my_questions;
sendQuestions(event, "sessionStudent");
sendQuestions(event, "sessionTeacher");
}else{
var my_session = getSession(event.session);
var my_queue = getQueue(event.session);
//console.log('new event(my_session):'+JSON.stringify(my_session));
//console.log('new event(my_queue):'+JSON.stringify(my_queue));
//console.log('new event(sessions):'+JSON.stringify(sessions));
//console.log('new event(queues):'+JSON.stringify(queues));
var students = event.user;
//for(var i=0; i<students.length; i++){
var found = false;
for(var j=0; j<my_session.length; j++){
//check by first username only
if(my_session[j].username.indexOf(students[0])!=-1){
switch(event.eventType){
case "connection":
break;
case "finishSection":
my_session[j].exercise +=1;
break;
case "undoFinishSection":
my_session[j].exercise -=1;
break;
case "help":
my_session[j].help = true;
my_session[j].description = event.description;
//Update questions
var my_questions = getQuestions(event.session);
my_questions.push({description: event.description, votes: [event.user[0]]});
event.questions = my_questions;
sendQuestions(event, "sessionStudent");
sendQuestions(event, "sessionTeacher");
//Update queue
my_queue.push(event.IP);
//Send event to this group
socket.emit("update queue", my_queue.length);
break;
case "solved":
//update question to add answer
var my_questions = getQuestions(event.session);
var qid = findLastQuestion(my_questions, event.user[0]);
if(qid!=-1){
my_questions[qid].answer = {description: event.description};
}
event.questions = my_questions;
sendQuestions(event, "sessionStudent");
sendQuestions(event, "sessionTeacher");
//Update the rest
my_session[j].help = false;
if(my_queue.indexOf(event.IP)!=-1){
my_queue.splice(my_queue.indexOf(event.IP),1);
}
sendQueuePositions(my_queue);
break;
}
found = true;
break;
}
}
if(!found){
//Error situation: Not found!
console.log("Error: not found info about students "+students.join(","));
my_session.push({
username: students,
exercise: 0,
help: false,
IP: event.IP
});
}
//}
console.log("sessions after the event:");
console.log(my_session);
console.log("queue after the event:");
console.log(my_queue);
sendEventToSession(event, "sessionTeacher");
/*
//Test retransmission of messages:done
var clients = io.sockets.clients();
//console.log('sockets:'+clients);
//console.log('sockets:'+JSON.stringify(clients));
//console.log('sockets.length:'+clients.length);
//console.log(clients[0]);
//io.sockets.emit('event', event);
for(var i=0; i<clients.length; i++){
//console.log('sockets[i]:'+JSON.stringify(io.sockets[i]));
clients[i].get("session", function(err, teacher_session){
if(teacher_session == event.session){//Check the teacher
clients[i].emit('event', event);
//clients[i].emit('init', {session: my_session, queue: my_queue});
console.log('emit new event to teacher in session:'+teacher_session);
//console.log(event);
//console.log(my_session);
//console.log(my_queue);
}
});
}
*/
}
});
});
//End help event (TEACHER)
socket.on('teacher event', function(event){
if(event.eventType=="endHelp" && event.user){
var IP = event.IP;
delete event.IP;
var my_session = getSession(event.session);
var my_queue = getQueue(event.session);
//console.log('teacher event before loop'+JSON.stringify(event));
var students = event.user;
//for(var i=0; i<students.length; i++){
for(var j=0; j<my_session.length; j++){
//check by first username only
if(my_session[j].username.indexOf(students[0])!=-1){
//console.log('teacher event found student for'+students[i]);
my_session[j].help = false;
if(my_queue.indexOf(IP)!=-1){
my_queue.splice(my_queue.indexOf(IP),1);
}
sendQueuePositions(my_queue, IP);
break;
}
}
//}
console.log("sessions after the event:");
console.log(my_session);
console.log("queue after the event:");
console.log(my_queue);
}
eventManager.save(event, function(error, events){
var event = events[0];
console.log('teacher event'+JSON.stringify(event));
});
});
//New student event (STUDENT)
socket.on("new student", function(users){
students = users.user;
console.log('new student:'+students.join(","));
//Check info of the first student, suppose the second is in the same group
//Slice is used to make a copy of the array
getUsersByUsername(students.slice(0), [], function(error, userInfoArray){
if(error){
console.log('student registered: error emitted');
socket.emit('student registered',{error:error});
}else{
if(userInfoArray.length==0) return;
var my_session = getSession(userInfoArray[0].group+users.session);
var my_queue = getQueue(userInfoArray[0].group+users.session);
var my_questions = getQuestions(userInfoArray[0].group+users.session);
//console.log('new student:'+students.join(","));
//console.log('new student(userInfoArray):'+userInfoArray);
//for(var i=0; i<students.length; i++){
var found = false;
for(var j=0; j<my_session.length; j++){
//check by first username only
if(my_session[j].username.indexOf(students[0])!=-1){
console.log('student '+students+' found in session');
var my_queue_pos = my_queue.indexOf(socket.handshake.address.address);
//fakeIP
//my_queue_pos = my_queue.indexOf(users.IP);
//console.log("Position("+my_queue_pos+") of "+socket.handshake.address.address+" in queue "+my_queue);
socket.emit('student registered', {
userInfoArray : userInfoArray,
exercise: my_session[j].exercise,
help: (my_queue_pos===-1)?false:(my_queue_pos+1),
questions: my_questions
});
found = true;
break;
}
}
if(!found){
//Not found
my_session.push({
username: students,
exercise: 0,
help: false,
//fakeIP
//IP: users.IP
IP: socket.handshake.address.address
});
console.log('new student '+students+' registered on session:');
//console.log(my_session);
socket.emit('student registered', {
userInfoArray : userInfoArray,
questions: my_questions
});
}
//Save session name to the socket
socket.set("sessionStudent", userInfoArray[0].group+users.session);
//fakeIP
//socket.set("fakeIP", users.IP);
//}
}
});
});
//New teacher event (TEACHER)
socket.on("new teacher", function(session){
var my_session = getSession(session.session);
var my_queue = getQueue(session.session);
var my_questions = getQuestions(session.session);
//console.log('new event(my_session):'+JSON.stringify(my_session));
//console.log('new event(my_queue):'+JSON.stringify(my_queue));
//Save session name to the socket
socket.set("sessionTeacher", session.session);
socket.emit('init', {session: my_session, queue: my_queue, questions: my_questions});
console.log('new teacher: at session '+session.session);
});
//Client disconnected!
socket.on("disconnect", function(){
/*
socket.get('username', function(err, students){
var index = 0; //Grupo 66
if(students_66.indexOf(students[0])==-1){//67
index = 1;
}
for(var i=0; i<students.length; i++){
sessions[index].splice(sessions[index].indexOf(students[i]),1);
}
});
*/
});
});
//Launch app
app.listen(80);
console.log('Server running...');