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.

boardData.js 7.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. /**
  2. * WHITEBOPHIR SERVER
  3. *********************************************************
  4. * @licstart The following is the entire license notice for the
  5. * JavaScript code in this page.
  6. *
  7. * Copyright (C) 2013-2014 Ophir LOJKINE
  8. *
  9. *
  10. * The JavaScript code in this page is free software: you can
  11. * redistribute it and/or modify it under the terms of the GNU
  12. * General Public License (GNU GPL) as published by the Free Software
  13. * Foundation, either version 3 of the License, or (at your option)
  14. * any later version. The code is distributed WITHOUT ANY WARRANTY;
  15. * without even the implied warranty of MERCHANTABILITY or FITNESS
  16. * FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
  17. *
  18. * As additional permission under GNU GPL version 3 section 7, you
  19. * may distribute non-source (e.g., minimized or compacted) forms of
  20. * that code without the copy of the GNU GPL normally required by
  21. * section 4, provided you include this license notice and a URL
  22. * through which recipients can access the Corresponding Source.
  23. *
  24. * @licend
  25. * @module boardData
  26. */
  27. var fs = require('fs')
  28. , log = require("./log.js").log
  29. , path = require("path");
  30. /** @constant
  31. @type {string}
  32. @default
  33. Path to the file where boards will be saved by default
  34. */
  35. var HISTORY_DIR = path.join(__dirname, "../server-data/");
  36. /** @constant
  37. @type {Number}
  38. @default
  39. Number of seconds of inactivity after which the board should be saved to a file
  40. */
  41. var SAVE_INTERVAL = 1000 * 2; // Save after 2 seconds of inactivity
  42. var MAX_SAVE_DELAY = 1000 * 60; // Save after 60 seconds even if there is still activity
  43. var MAX_ITEM_COUNT = 32768; // Max number of items to keep in the board
  44. var MAX_CHILDREN = 128; // Max number of subitems in an item
  45. var MAX_BOARD_SIZE = 65536; // Maximum value for any x or y on the board
  46. /**
  47. * Represents a board.
  48. * @constructor
  49. */
  50. var BoardData = function (name) {
  51. this.name = name;
  52. this.board = {};
  53. this.file = path.join(HISTORY_DIR, "board-" + encodeURIComponent(name) + ".json");
  54. this.lastSaveDate = Date.now();
  55. this.users = new Set();
  56. };
  57. /** Adds data to the board */
  58. BoardData.prototype.set = function (id, data) {
  59. //KISS
  60. data.time = Date.now();
  61. this.validate(data);
  62. this.board[id] = data;
  63. this.delaySave();
  64. };
  65. /** Adds a child to an element that is already in the board
  66. * @param {string} id - Identifier of the parent element.
  67. * @param {object} child - Object containing the the values to update.
  68. * @param {boolean} [create=true] - Whether to create an empty parent if it doesn't exist
  69. * @returns {boolean} - True if the child was added, else false
  70. */
  71. BoardData.prototype.addChild = function (parentId, child) {
  72. var obj = this.board[parentId];
  73. if (typeof obj !== "object") return false;
  74. if (Array.isArray(obj._children)) obj._children.push(child);
  75. else obj._children = [child];
  76. this.validate(obj);
  77. this.delaySave();
  78. return true;
  79. };
  80. /** Update the data in the board
  81. * @param {string} id - Identifier of the data to update.
  82. * @param {object} data - Object containing the the values to update.
  83. * @param {boolean} create - True if the object should be created if it's not currently in the DB.
  84. */
  85. BoardData.prototype.update = function (id, data, create) {
  86. var obj = this.board[id];
  87. if (typeof obj === "object") {
  88. for (var i in data) {
  89. obj[i] = data[i];
  90. }
  91. } else if (create || obj !== undefined) {
  92. this.board[id] = data;
  93. }
  94. this.delaySave();
  95. };
  96. /** Removes data from the board
  97. * @param {string} id - Identifier of the data to delete.
  98. */
  99. BoardData.prototype.delete = function (id) {
  100. //KISS
  101. delete this.board[id];
  102. this.delaySave();
  103. };
  104. /** Reads data from the board
  105. * @param {string} id - Identifier of the element to get.
  106. * @returns {object} The element with the given id, or undefined if no element has this id
  107. */
  108. BoardData.prototype.get = function (id, children) {
  109. return this.board[id];
  110. };
  111. /** Reads data from the board
  112. * @param {string} [id] - Identifier of the first element to get.
  113. * @param {BoardData~processData} callback - Function to be called with each piece of data read
  114. */
  115. BoardData.prototype.getAll = function (id) {
  116. var results = [];
  117. for (var i in this.board) {
  118. if (!id || i > id) {
  119. results.push(this.board[i]);
  120. }
  121. }
  122. return results;
  123. };
  124. /**
  125. *
  126. */
  127. BoardData.prototype.addUser = function addUser(userId) {
  128. }
  129. /**
  130. * This callback is displayed as part of the BoardData class.
  131. * Describes a function that processes data that comes from the board
  132. * @callback BoardData~processData
  133. * @param {object} data
  134. */
  135. /** Delays the triggering of auto-save by SAVE_INTERVAL seconds
  136. */
  137. BoardData.prototype.delaySave = function (file) {
  138. if (this.saveTimeoutId !== undefined) clearTimeout(this.saveTimeoutId);
  139. this.saveTimeoutId = setTimeout(this.save.bind(this), SAVE_INTERVAL);
  140. if (Date.now() - this.lastSaveDate > MAX_SAVE_DELAY) setTimeout(this.save.bind(this), 0);
  141. };
  142. /** Saves the data in the board to a file.
  143. * @param {string} [file=this.file] - Path to the file where the board data will be saved.
  144. */
  145. BoardData.prototype.save = function (file) {
  146. this.lastSaveDate = Date.now();
  147. this.clean();
  148. if (!file) file = this.file;
  149. var board_txt = JSON.stringify(this.board);
  150. var that = this;
  151. fs.writeFile(file, board_txt, function onBoardSaved(err) {
  152. if (err) {
  153. console.trace(new Error("Unable to save the board: " + err));
  154. } else {
  155. log("saved board", { 'name': that.name });
  156. }
  157. });
  158. };
  159. /** Remove old elements from the board */
  160. BoardData.prototype.clean = function cleanBoard() {
  161. var board = this.board;
  162. var ids = Object.keys(board);
  163. if (ids.length > MAX_ITEM_COUNT) {
  164. var toDestroy = ids.sort(function (x, y) {
  165. return (board[x].time | 0) - (board[y].time | 0);
  166. }).slice(0, -MAX_ITEM_COUNT);
  167. for (var i = 0; i < toDestroy.length; i++) delete board[toDestroy[i]];
  168. log("cleaned board", { 'removed': toDestroy.length, "board": this.name });
  169. }
  170. }
  171. /** Reformats an item if necessary in order to make it follow the boards' policy
  172. * @param {object} item The object to edit
  173. * @param {object} parent The parent of the object to edit
  174. */
  175. BoardData.prototype.validate = function validate(item, parent) {
  176. if (item.hasOwnProperty("size")) {
  177. item.size = parseInt(item.size) || 1;
  178. item.size = Math.min(Math.max(item.size, 1), 50);
  179. }
  180. if (item.hasOwnProperty("x") || item.hasOwnProperty("y")) {
  181. item.x = parseFloat(item.x) || 0;
  182. item.x = Math.min(Math.max(item.x, 0), MAX_BOARD_SIZE);
  183. item.x = Math.round(10 * item.x) / 10;
  184. item.y = parseFloat(item.y) || 0;
  185. item.y = Math.min(Math.max(item.y, 0), MAX_BOARD_SIZE);
  186. item.y = Math.round(10 * item.y) / 10;
  187. }
  188. if (item.hasOwnProperty("opacity")) {
  189. item.opacity = Math.min(Math.max(item.opacity, 0.1), 1) || 1;
  190. if (item.opacity === 1) delete item.opacity;
  191. }
  192. if (item.hasOwnProperty("_children")) {
  193. if (!Array.isArray(item._children)) item._children = [];
  194. if (item._children.length > MAX_CHILDREN) item._children.length = MAX_CHILDREN;
  195. for (var i = 0; i < item._children.length; i++) {
  196. this.validate(item._children[i]);
  197. }
  198. }
  199. }
  200. /** Load the data in the board from a file.
  201. * @param {string} file - Path to the file where the board data will be read.
  202. */
  203. BoardData.load = function loadBoard(name) {
  204. var boardData = new BoardData(name);
  205. return new Promise((accept) => {
  206. fs.readFile(boardData.file, function (err, data) {
  207. try {
  208. if (err) throw err;
  209. boardData.board = JSON.parse(data);
  210. for (id in boardData.board) boardData.validate(boardData.board[id]);
  211. log('disk load', { 'board': boardData.name });
  212. } catch (e) {
  213. console.error("Unable to read history from " + boardData.file + ". The following error occured: " + e);
  214. log('empty board creation', { 'board': boardData.name });
  215. boardData.board = {}
  216. }
  217. accept(boardData);
  218. });
  219. });
  220. };
  221. module.exports.BoardData = BoardData;