-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplan9.js
More file actions
423 lines (393 loc) · 24 KB
/
plan9.js
File metadata and controls
423 lines (393 loc) · 24 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
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
var config = require('config')
, httpServer = require('http')
, app = require('./lib/server/app.js')
, twig = require('twig').twig
, socketIoAuthorization = require('./lib/server/socketio.js').socketIoAuthorization
, fs = require('fs')
, logger = require('./lib/modules').logger
, async = require('async')
, io = {}
, connector = require('./lib/server/connectors/' + config.server.connector)
, server = {}
, messageformatter = require('./lib/modules').messageFormatter
, highscoresTemplate
, badgeTemplate
, redisClient
, CbtCalcuclator = require('./lib/game/cbtcalculator')
, cbtcalculator
, socketIoRedisClient = require('socket.io-redis')
, CbtMessageCreator = require('./lib/game/cbt-message-creator')
, PlaygroundSolvedMessageCreator = require('./lib/game/playground-solved-message-creator')
, UpdateOverviewMessageCreator = require('./lib/game/update-overview-message-creator')
, controllers = require('./lib/controllers');
logger.logLevel = 'DEBUG';
///////////////////////////////
//
// Bootstrapping app
// Starting server and sockets
//
////////////////////////////////
async.series([
function(callback){
server = httpServer.createServer(app);
io = require('socket.io')(server, {
'match origin protocol': true,
'serveClient': false,
'transports': ['websocket', 'xhr-polling', 'polling']
});
io.adapter(socketIoRedisClient({host: config.redis.host, port: config.redis.port}));
process.nextTick(function() {callback(null); });
},
function(callback){
async.parallel([
//connect to Redis
function(callback) {
redisClient = app.redisClient;
redisClient.on('connect', function() {
logger.debug('Redis connection is ready to use.');
});
redisClient.on('error', function(err) {
logger.error('Redis connection error! Error thrown: ' + err);
});
cbtcalculator = new CbtCalcuclator(redisClient);
process.nextTick(function() {callback(null)});
},
function(callback) {
// startServer
server.listen(config.server.port, config.server.host);
process.nextTick(function() {callback(null)});
},
function(callback){
///////////////////////////////
// Routes and templates
////////////////////////////////
app.get('/connect', controllers.indexController().connectAction);
highscoresTemplate = twig({
id:'highscores',
path: __dirname + '/lib/server/views/highscores.html.twig'
});
badgeTemplate = twig({
id:'badge',
path: __dirname + '/lib/server/views/badge.html.twig'
});
process.nextTick(function() {callback(null)});
}
], function() {
process.nextTick(function() {callback(null)});
});
}
],
function(err){
if (!err) {
async.waterfall([
function(callback) {
///////////////////////////////
// Setup excahnges and queues
////////////////////////////////
connector.setExchangeName('plan9');
connector.setQueueName('plan9');
connector.connect(config, function(err, connectionHandler) {
if (err) {
process.nextTick(function() {throw 'error within amqp connection happend ' + err});
} else {
console.log('Connected to connector: ' + config.server.connector);
process.nextTick(function() {callback(null, connectionHandler); });
}
}, function(message) {
logger.debug('RECEIVEDNEWMESSAGE');
var rawMessageObj = message.data.toString();
logger.debug(rawMessageObj);
var messageObj = JSON.parse(rawMessageObj);
if (messageObj.hasOwnProperty('user')
&& messageObj.user.hasOwnProperty('user_id')
&& messageObj.hasOwnProperty('type')
&& messageObj.type == 'badge') {
//redisClient.publish('badge', rawMessageObj);
redisClient.HINCRBY('user_' + messageObj.user.user_id, 'points', parseInt(messageObj.points.increment), function(err, result) {
logger.debug('Incremented points by HINCRBY from badge message err: ', err);
logger.debug('Incremented points by HINCRBY from badge message result: ', result);
});
redisClient.HGET('user_' + messageObj.user.user_id , 'user_socket_id', function(err, result) {
logger.debug('Fetching user_socket_id by HGET err: ', err);
logger.debug('Fetching user_socket_id by HGET result: ', result);
if (!err && null != result) {
var socketId = result.toString();
logger.debug('User socket id: ', socketId);
console.log(io.of('/playground'));
io.of('/playground').connected[socketId].volatile.emit(
//socket.emit(
'command', {
payload: twig({
ref: 'badge',
async: false
}).render({
badge: messageObj.badge
}),
commandtype: 'showBadge'
}
);
} else {
logger.error('Cannot send badge to user: ' + user_id + ', because user_id => user_socket_id cannot be found');
}
});
} else {
logger.debug('This message is not supported. It does not contain a user_id or the correct type', messageObj);
}
});
},
function(connectionHandler, callback) {
///////////////////////////////
// socket io namespaces
////////////////////////////////
io.of('/overview').on('connection', function(socket) {
console.log('connected to overview socket by id: ' + socket.id);
});
io.of('/playground').use(socketIoAuthorization).on('connection', function (socket) {
console.log('connected to playground socket by id: ' + socket.id);
logger.debug('storing socketid for user: ' + socket.uuid);
// @todo: currently it is sent via socket connect. Should be received via session (security issue)
var userId = socket.uuid;
logger.debug('UserId = ' + userId);
// store user_id to socket_id
redisClient.HSET('user_' + userId, 'user_socket_id', socket.id, function(err, result) {
logger.debug('Stored socket_id to user_id err: ', err);
logger.debug('Stored socket_id to user_id result: ', result);
});
// @todo: Points have to be sent by socket connection from client (if avaiable)
redisClient.HSET('user_' + userId, 'points', 0, function(err, result) {
logger.debug('Stored points to user_id err: ', err);
logger.debug('Stored points to user_id result: ', result);
});
// send new cbt
sendCbtToUser(userId, socket, function(received) {
if (received) {
logger.debug('Cool. Client received the cbt');
}
});
socket.on('disconnect', function() {
cbtcalculator.removePixelsFromLocksForUser(userId, function(err) {
logger.debug(err);
})
});
// Fetch cbts
socket.on('logdata', function (data)
{
logger.debug('Receiving CBT from client');
async.waterfall([
//sanitize
function(callback) {
try {
var messages = JSON.parse(data).messages;
var cbtSolution = messages.body[0].value[0].payload;
logger.debug('CBT solution = ', cbtSolution);
process.nextTick(function() { callback(null, cbtSolution); });
} catch(e) {
process.nextTick(function() { callback("Sanitization exception with error: " + e); });
}
},
function(cbtSolution, callback) {
logger.debug('Calculating points and cbt.');
async.waterfall([
function(callback) {
var pointsIncrement = 0;
// calculate points
cbtcalculator.cbtHasBeenSolvedCorrectly(cbtSolution.cbt, function(err, isSolved, pixelResult){
if (!err) {
logger.debug('Calculate Points increment based on isSolved: ' + isSolved);
if (true == isSolved) {
pointsIncrement = 1;
} else {
pointsIncrement = -1;
}
logger.debug('Points increment isset to: ' + pointsIncrement);
process.nextTick(function() {callback(null, pointsIncrement, pixelResult, isSolved)});
} else {
process.nextTick(function() {callback(err)});
}
})
},
function(pointsIncrement, pixelResult, isSolved, callback) {
async.parallel([
function(callback) {
async.waterfall([
function(callback) {
var totalPoints = 0;
var multi = redisClient.multi();
multi.HINCRBY('user_' + userId, 'points', pointsIncrement);
// @todo: this should be a user name
multi.ZINCRBY('plan9_highscores', userId, pointsIncrement);
multi.EXEC(function(err, result) {
logger.debug('Incremented points by MULTI: ', err);
logger.debug('Incremented points by MULTI: ', result);
if (!err) {
totalPoints = result[0];
process.nextTick(function() {callback(null, pointsIncrement, totalPoints)});
} else {
process.nextTick(function() {callback(err)});
}
});
},
function(pointsIncrement, totalPoints, callback) {
var pointsMessage = {
type: "points",
user_src: {
user_id: userId
},
user_target: {
user_id: userId
},
timestamp: cbtSolution.timestamp,
version: cbtSolution.version,
points: {
total: totalPoints,
increment: pointsIncrement
}
};
logger.debug('Points message to send: ', pointsMessage);
connector.send(connectionHandler, new Buffer(JSON.stringify(pointsMessage)), config, function(err) {
logger.debug('SENDING points to amqp.' + err);
if (!err) {
socket.volatile.emit('command', {
payload: totalPoints,
commandtype: 'updatePoints'
});
process.nextTick(function() {callback(null); });
} else {
process.nextTick(function() {callback(err); });
}
}, 'points.plan9');
}
], function(err) {
logger.debug('Points area error?: ', err);
process.nextTick(function() {callback(err); });
});
},
function(callback) {
var cbtMessage = new CbtMessageCreator(cbtSolution, userId, isSolved, pixelResult).createMessage();
logger.debug('CBT message to send: ', cbtMessage);
connector.send(connectionHandler, new Buffer(JSON.stringify(cbtMessage)), config, function(err) {
if (!err) {
var playGroundSolvedMessage = new PlaygroundSolvedMessageCreator(isSolved, pixelResult).createMessage();
logger.debug('Playground solved message to send: ', playGroundSolvedMessage);
socket.volatile.emit('command', playGroundSolvedMessage);
var updateOverviewMessage = new UpdateOverviewMessageCreator(pixelResult, twig).createMessage();
logger.debug('Update Overview message to send: ', updateOverviewMessage);
// send to connected overview pages
io.of('/overview').emit('command', updateOverviewMessage);
process.nextTick(function() {callback(null); });
} else {
process.nextTick(function() {callback(err); });
}
}, 'cbt.plan9');
},
function(callback) {
logger.debug('decide what to do with given solution.');
if (isSolved) {
cbtcalculator.setPixelToSolved(userId, pixelResult.pixel, function(err) {
process.nextTick(function() {callback(err)});
});
} else {
process.nextTick(function() {callback(null); });
}
}
], function(err) {
logger.debug('Result of sending points and cbt messages to backend.', err);
process.nextTick(function() {callback(err); });
});
}
], function(err) {
logger.error('Error in sending points message: ' + err);
process.nextTick(function() {callback(null);});
});
},
function(callback) {
cbtcalculator.getCbtForUser(userId, function(err, cbt) {
if (!err && cbt) {
logger.debug('NOW Sending new cbt to user: ' + userId);
socket.emit('command', {
commandtype: 'setPlaygroundCbt',
payload: cbt
},function(received) {
if (received) {
logger.debug('NEW Cbt has been ack by client!');
process.nextTick(function() {callback(null, cbt)});
}
});
} else {
logger.debug('ERROR in sending new cbt to user: ', err);
process.nextTick(function() {callback(err)});
}
});
},
function(cbt, callback) {
redisClient.zrevrange('plan9_highscores','0','9', 'withscores', function(err, highscores) {
logger.debug('Getting highscores by zrevrange: ' + err);
logger.debug('Getting highscores by zrevrange: ' + highscores);
if (!err && highscores) {
logger.debug('Highscore is filled: ' + highscores);
var parsedHighscores = [];
for (var highscoreIndex in highscores) {
if (highscores.hasOwnProperty(highscoreIndex)) {
try {
logger.debug('PARSED highscore: ' + JSON.parse(highscores[highscoreIndex].toString()));
parsedHighscores.push(JSON.parse(highscores[highscoreIndex].toString()));
} catch(e) {
logger.debug('ERROR in parsing Highscore.');
}
}
}
var highscoreMarkup = twig({
ref: 'highscores',
async: false
}).render({
highscores: parsedHighscores
});
logger.debug('highscore markup', highscoreMarkup);
socket.volatile.emit('command', {
commandtype: 'updateHighScore',
payload: highscoreMarkup
});
} else {
if (!err) {
err = 'Highscores List is empty';
}
process.nextTick(function() {callback(err)});
}
});
}
], function(err) {
if (err) {
process.nextTick(function() {callback("Error in on connection async.waterfall: " + err); });
}
});
});
});
process.nextTick(function() {callback(null); });
}
], function (err) {
if (err) {
logger.error("Error of async.waterfall in end function after start series: " + err);
} else {
logger.info('Started data collector backend server.');
}
})
} else {
if (err) {
logger.error("Error in async.series: " + err);
}
}
});
function sendCbtToUser(userId, socket, callback) {
// create and send new cbt for user
cbtcalculator.getCbtForUser(userId, function(err, cbt) {
if (!err && cbt) {
logger.debug('NOW Sending new cbt to user: ' + userId);
socket.emit('command', {
commandtype: 'setPlaygroundCbt',
payload: cbt
},callback);
} else {
logger.debug('ERROR in sending new cbt to user: ', err);
}
});
}