You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

sockets.js 4.1KB

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