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.

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