Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

sockets.js 3.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. var iolib = require('socket.io')
  2. , log = require("./log.js").log
  3. , BoardData = require("./boardData.js").BoardData;
  4. var MAX_EMIT_COUNT = 64; // Maximum number of draw operations before getting banned
  5. var MAX_EMIT_COUNT_PERIOD = 5000; // Duration (in ms) after which the emit count is reset
  6. // Map from name to *promises* of BoardData
  7. var boards = {};
  8. function noFail(fn) {
  9. return function noFailWrapped(arg) {
  10. try {
  11. return fn(arg);
  12. } catch (e) {
  13. console.trace(e);
  14. }
  15. }
  16. }
  17. function startIO(app) {
  18. io = iolib(app);
  19. io.on('connection', noFail(socketConnection));
  20. return io;
  21. }
  22. /** Returns a promise to a BoardData with the given name*/
  23. function getBoard(name) {
  24. if (boards.hasOwnProperty(name)) {
  25. return boards[name];
  26. } else {
  27. var board = BoardData.load(name);
  28. boards[name] = board;
  29. return board;
  30. }
  31. }
  32. function socketConnection(socket) {
  33. function joinBoard(name) {
  34. // Default to the public board
  35. if (!name) name = "anonymous";
  36. // Join the board
  37. socket.join(name);
  38. return getBoard(name).then(board => {
  39. board.users.add(socket.id);
  40. log('board joined', { 'board': board.name, 'users': board.users.size });
  41. return board;
  42. });
  43. }
  44. socket.on("error", noFail(function onError(error) {
  45. log("ERROR", error);
  46. }));
  47. socket.on("getboard", noFail(function onGetBoard(name) {
  48. joinBoard(name).then(board => {
  49. //Send all the board's data as soon as it's loaded
  50. socket.emit("broadcast", { _children: board.getAll() });
  51. });
  52. }));
  53. socket.on("joinboard", noFail(joinBoard));
  54. var lastEmitSecond = Date.now() / MAX_EMIT_COUNT_PERIOD | 0;
  55. var emitCount = 0;
  56. socket.on('broadcast', noFail(function onBroadcast(message) {
  57. var currentSecond = Date.now() / MAX_EMIT_COUNT_PERIOD | 0;
  58. if (currentSecond === lastEmitSecond) {
  59. emitCount++;
  60. if (emitCount > MAX_EMIT_COUNT) {
  61. var request = socket.client.request;
  62. log('BANNED', {
  63. user_agent: request.headers['user-agent'],
  64. original_ip: request.headers['x-forwarded-for'] || request.headers['forwarded'],
  65. emit_count: emitCount
  66. });
  67. return;
  68. }
  69. } else {
  70. emitCount = 0;
  71. lastEmitSecond = currentSecond;
  72. }
  73. var boardName = message.board || "anonymous";
  74. var data = message.data;
  75. if (!socket.rooms.hasOwnProperty(boardName)) socket.join(boardName);
  76. if (!data) {
  77. console.warn("Received invalid message: %s.", JSON.stringify(message));
  78. return;
  79. }
  80. //Send data to all other users connected on the same board
  81. socket.broadcast.to(boardName).emit('broadcast', data);
  82. // Save the message in the board
  83. saveHistory(boardName, data);
  84. }));
  85. socket.on('disconnecting', function onDisconnecting(reason) {
  86. Object.keys(socket.rooms).forEach(function disconnectFrom(room) {
  87. if (boards.hasOwnProperty(room)) {
  88. boards[room].then(board => {
  89. board.users.delete(socket.id);
  90. var userCount = board.users.size;
  91. log('disconnection', { 'board': board.name, 'users': board.users.size });
  92. if (userCount === 0) {
  93. board.save();
  94. delete boards[room];
  95. }
  96. });
  97. }
  98. });
  99. });
  100. }
  101. function saveHistory(boardName, message) {
  102. var id = message.id;
  103. getBoard(boardName).then(board => {
  104. switch (message.type) {
  105. case "delete":
  106. if (id) board.delete(id);
  107. break;
  108. case "update":
  109. delete message.type;
  110. if (id) board.update(id, message);
  111. break;
  112. case "child":
  113. board.addChild(message.parent, message);
  114. break;
  115. default: //Add data
  116. if (!id) throw new Error("Invalid message: ", message);
  117. board.set(id, message);
  118. }
  119. });
  120. }
  121. function generateUID(prefix, suffix) {
  122. var uid = Date.now().toString(36); //Create the uids in chronological order
  123. uid += (Math.round(Math.random() * 36)).toString(36); //Add a random character at the end
  124. if (prefix) uid = prefix + uid;
  125. if (suffix) uid = uid + suffix;
  126. return uid;
  127. }
  128. if (exports) {
  129. exports.start = startIO;
  130. }