app.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. /*global require:true, __dirname:true */
  2. var conf = {
  3. port: 8888,
  4. debug: false,
  5. dbPort: 6379,
  6. dbHost: '127.0.0.1',
  7. };
  8. var express = require('express');
  9. var http = require('http');
  10. var path = require('path');
  11. var bodyParser = require('body-parser');
  12. var events = require('events');
  13. var _ = require('underscore');
  14. var sanitize = require('validator').sanitize;
  15. var app = express(),
  16. server = http.createServer(app);
  17. server.listen(conf.port);
  18. app.use(bodyParser.json());
  19. app.use(bodyParser.urlencoded({ extended: false }));
  20. app.use(express.static(path.join(__dirname, 'app')));
  21. var io = require('socket.io')(server);
  22. var redis = require('socket.io-redis');
  23. io.adapter(redis({ host: conf.dbHost, port: conf.dbPort }));
  24. var db = require('redis').createClient(conf.dbPort,conf.dbHost);
  25. var logger = new events.EventEmitter();
  26. logger.on('newEvent', function(event, data) {
  27. console.log('%s: %s', event, JSON.stringify(data));
  28. });
  29. // ***************************************************************************
  30. // Express routes helpers
  31. // ***************************************************************************
  32. // Only authenticated users should be able to use protected methods
  33. var requireAuthentication = function(req, res, next) {
  34. // TODO
  35. next();
  36. };
  37. // Sanitize message to avoid security problems
  38. var sanitizeMessage = function(req, res, next) {
  39. if (req.body.msg) {
  40. req.sanitizedMessage = sanitize(req.body.msg).xss();
  41. next();
  42. } else {
  43. res.send(400, "No message provided");
  44. }
  45. };
  46. // Send a message to all active rooms
  47. var sendBroadcast = function(text) {
  48. _.each(io.nsps['/'].adapter.rooms, function(room) {
  49. if (room) {
  50. var message = {'room':room, 'username':'ServerBot', 'msg':text, 'date':new Date()};
  51. io.to(room).emit('newMessage', message);
  52. }
  53. });
  54. logger.emit('newEvent', 'newBroadcastMessage', {'msg':text});
  55. };
  56. // ***************************************************************************
  57. // Express routes
  58. // ***************************************************************************
  59. // Welcome message
  60. app.get('/', function(req, res) {
  61. res.send(200, "Welcome to chat server");
  62. });
  63. // Broadcast message to all connected users
  64. app.post('/api/broadcast/', requireAuthentication, sanitizeMessage, function(req, res) {
  65. sendBroadcast(req.sanitizedMessage);
  66. res.send(201, "Message sent to all rooms");
  67. });
  68. // ***************************************************************************
  69. // Socket.io events
  70. // ***************************************************************************
  71. io.sockets.on('connection', function(socket) {
  72. // Welcome message on connection
  73. socket.emit('connected', 'Welcome to the chat server');
  74. logger.emit('newEvent', 'userConnected', {'socket':socket.id});
  75. // Store user data in db
  76. db.hset([socket.id, 'connectionDate', new Date()], redis.print);
  77. db.hset([socket.id, 'socketID', socket.id], redis.print);
  78. db.hset([socket.id, 'username', 'anonymous'], redis.print);
  79. // Join user to 'MainRoom'
  80. socket.join(conf.mainroom);
  81. logger.emit('newEvent', 'userJoinsRoom', {'socket':socket.id, 'room':conf.mainroom});
  82. // Confirm subscription to user
  83. socket.emit('subscriptionConfirmed', {'room':conf.mainroom});
  84. // Notify subscription to all users in room
  85. var data = {'room':conf.mainroom, 'username':'anonymous', 'msg':'----- Joined the room -----', 'id':socket.id};
  86. io.to(conf.mainroom).emit('userJoinsRoom', data);
  87. // User wants to subscribe to [data.rooms]
  88. socket.on('subscribe', function(data) {
  89. // Get user info from db
  90. db.hget([socket.id, 'username'], function(err, username) {
  91. // Subscribe user to chosen rooms
  92. _.each(data.rooms, function(room) {
  93. room = room.replace(" ","");
  94. socket.join(room);
  95. logger.emit('newEvent', 'userJoinsRoom', {'socket':socket.id, 'username':username, 'room':room});
  96. // Confirm subscription to user
  97. socket.emit('subscriptionConfirmed', {'room': room});
  98. // Notify subscription to all users in room
  99. var message = {'room':room, 'username':username, 'msg':'----- Joined the room -----', 'id':socket.id};
  100. io.to(room).emit('userJoinsRoom', message);
  101. });
  102. });
  103. });
  104. // User wants to unsubscribe from [data.rooms]
  105. socket.on('unsubscribe', function(data) {
  106. // Get user info from db
  107. db.hget([socket.id, 'username'], function(err, username) {
  108. // Unsubscribe user from chosen rooms
  109. _.each(data.rooms, function(room) {
  110. if (room != conf.mainroom) {
  111. socket.leave(room);
  112. logger.emit('newEvent', 'userLeavesRoom', {'socket':socket.id, 'username':username, 'room':room});
  113. // Confirm unsubscription to user
  114. socket.emit('unsubscriptionConfirmed', {'room': room});
  115. // Notify unsubscription to all users in room
  116. var message = {'room':room, 'username':username, 'msg':'----- Left the room -----', 'id': socket.id};
  117. io.to(room).emit('userLeavesRoom', message);
  118. }
  119. });
  120. });
  121. });
  122. // User wants to know what rooms he has joined
  123. socket.on('getRooms', function(data) {
  124. socket.emit('roomsReceived', socket.rooms);
  125. logger.emit('newEvent', 'userGetsRooms', {'socket':socket.id});
  126. });
  127. // Get users in given room
  128. socket.on('getUsersInRoom', function(data) {
  129. var usersInRoom = [];
  130. var socketsInRoom = _.keys(io.nsps['/'].adapter.rooms[data.room]);
  131. for (var i=0; i<socketsInRoom.length; i++) {
  132. db.hgetall(socketsInRoom[i], function(err, obj) {
  133. usersInRoom.push({'room':data.room, 'username':obj.username, 'id':obj.socketID});
  134. // When we've finished with the last one, notify user
  135. if (usersInRoom.length == socketsInRoom.length) {
  136. socket.emit('usersInRoom', {'users':usersInRoom});
  137. }
  138. });
  139. }
  140. });
  141. // User wants to change his nickname
  142. socket.on('setNickname', function(data) {
  143. // Get user info from db
  144. db.hget([socket.id, 'username'], function(err, username) {
  145. // Store user data in db
  146. db.hset([socket.id, 'username', data.username], redis.print);
  147. logger.emit('newEvent', 'userSetsNickname', {'socket':socket.id, 'oldUsername':username, 'newUsername':data.username});
  148. // Notify all users who belong to the same rooms that this one
  149. _.each(socket.rooms, function(room) {
  150. if (room) {
  151. var info = {'room':room, 'oldUsername':username, 'newUsername':data.username, 'id':socket.id};
  152. io.to(room).emit('userNicknameUpdated', info);
  153. }
  154. });
  155. });
  156. });
  157. // New message sent to group
  158. socket.on('newMessage', function(data) {
  159. db.hgetall(socket.id, function(err, obj) {
  160. if (err) return logger.emit('newEvent', 'error', err);
  161. // Check if user is subscribed to room before sending his message
  162. if (_.contains(_.values(socket.rooms), data.room)) {
  163. var message = {'room':data.room, 'username':obj.username, 'msg':data.msg, 'date':new Date()};
  164. // Send message to room
  165. io.to(data.room).emit('newMessage', message);
  166. logger.emit('newEvent', 'newMessage', message);
  167. }
  168. });
  169. });
  170. // Clean up on disconnect
  171. socket.on('disconnect', function() {
  172. // Get current rooms of user
  173. var rooms = socket.rooms;
  174. // Get user info from db
  175. db.hgetall(socket.id, function(err, obj) {
  176. if (err) return logger.emit('newEvent', 'error', err);
  177. logger.emit('newEvent', 'userDisconnected', {'socket':socket.id, 'username':obj.username});
  178. // Notify all users who belong to the same rooms that this one
  179. _.each(rooms, function(room) {
  180. if (room) {
  181. var message = {'room':room, 'username':obj.username, 'msg':'----- Left the room -----', 'id':obj.socketID};
  182. io.to(room).emit('userLeavesRoom', message);
  183. }
  184. });
  185. });
  186. // Delete user from db
  187. db.del(socket.id, redis.print);
  188. });
  189. });
  190. // Automatic message generation (for testing purposes)
  191. if (conf.debug) {
  192. setInterval(function() {
  193. var text = 'Testing rooms';
  194. sendBroadcast(text);
  195. }, 60000);
  196. }