-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocket.js
87 lines (84 loc) · 3.31 KB
/
socket.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
var question = require('./queries/question');
var answer = require('./queries/answer');
module.exports = function (server, jwt, secret) {
var io = require('socket.io')(server);
io.on('connection', function (socket) {
var ipAddr = socket.request.connection.remoteAddress;
socket.on('join', function (token, gid, callback) {
jwt.verify(token, secret, function (err, decoded) {
if (err) {
callback(err.message);
return;
}
if (gid) {
var roomID = gid.toString();
} else if (decoded.gid) {
var roomID = decoded.gid.toString();
} else {
err = new Error('Group ID undefined');
callback(err);
return;
}
socket.join(roomID);
console.log(decoded.displayName + ' (' + ipAddr + ') joined room ID: ' + roomID);
if (decoded.role == 0) {
socket.on('ask', function (qid, qsid) {
question.ask(qid, function (err, row) {
if (err) {
console.log(err);
return;
}
var choices = JSON.parse(row.choices);
shuffle(choices);
io.to(roomID).emit('question', {qsid: qsid, question: row.question, choices: choices});
});
});
socket.on('solve', function (qid) {
question.solve(qid, function (err, row) {
if (err) {
console.log(err);
return;
}
var choices = JSON.parse(row.choices);
var answer = choices[row.answer];
io.to(roomID).emit('solve-question', answer);
});
});
socket.on('list-answer', function (qsid, callback) {
answer.list(qsid, function (err, rows) {
if (err) {
callback(err.message, null);
return;
}
callback(null, rows);
});
});
}
socket.on('answer', function (qsid, answerText, callback) {
answer.add(qsid, decoded.uid, answerText, function (err, result) {
if (err) {
callback(err.message);
return;
}
callback(null);
io.to(roomID).emit('answer-question', result);
});
});
callback(null);
});
});
});
}
/**
* Shuffles array in place.
* @param {Array} a items The array containing the items.
*/
function shuffle(a) {
var j, x, i;
for (i = a.length; i; i -= 1) {
j = Math.floor(Math.random() * i);
x = a[i - 1];
a[i - 1] = a[j];
a[j] = x;
}
}