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 8.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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_promises.js"),
  28. log = require("./log.js").log,
  29. path = require("path"),
  30. config = require("./configuration.js");
  31. /**
  32. * Represents a board.
  33. * @class
  34. * @constructor
  35. * @param {string} name
  36. */
  37. var BoardData = function (name) {
  38. this.name = name;
  39. /** @type {{[name: string]: {[object_id:string]: any}}} */
  40. this.board = {};
  41. this.file = path.join(
  42. config.HISTORY_DIR,
  43. "board-" + encodeURIComponent(name) + ".json"
  44. );
  45. this.lastSaveDate = Date.now();
  46. this.users = new Set();
  47. };
  48. /** Adds data to the board */
  49. BoardData.prototype.set = function (id, data) {
  50. //KISS
  51. data.time = Date.now();
  52. this.validate(data);
  53. this.board[id] = data;
  54. this.delaySave();
  55. };
  56. /** Adds a child to an element that is already in the board
  57. * @param {string} id - Identifier of the parent element.
  58. * @param {object} child - Object containing the the values to update.
  59. * @param {boolean} [create=true] - Whether to create an empty parent if it doesn't exist
  60. * @returns {boolean} - True if the child was added, else false
  61. */
  62. BoardData.prototype.addChild = function (parentId, child) {
  63. var obj = this.board[parentId];
  64. if (typeof obj !== "object") return false;
  65. if (Array.isArray(obj._children)) obj._children.push(child);
  66. else obj._children = [child];
  67. this.validate(obj);
  68. this.delaySave();
  69. return true;
  70. };
  71. /** Update the data in the board
  72. * @param {string} id - Identifier of the data to update.
  73. * @param {object} data - Object containing the values to update.
  74. * @param {boolean} create - True if the object should be created if it's not currently in the DB.
  75. */
  76. BoardData.prototype.update = function (id, data, create) {
  77. delete data.type;
  78. delete data.tool;
  79. var obj = this.board[id];
  80. if (typeof obj === "object") {
  81. for (var i in data) {
  82. obj[i] = data[i];
  83. }
  84. } else if (create || obj !== undefined) {
  85. this.board[id] = data;
  86. }
  87. this.delaySave();
  88. };
  89. /** Removes data from the board
  90. * @param {string} id - Identifier of the data to delete.
  91. */
  92. BoardData.prototype.delete = function (id) {
  93. //KISS
  94. delete this.board[id];
  95. this.delaySave();
  96. };
  97. /** Reads data from the board
  98. * @param {string} id - Identifier of the element to get.
  99. * @returns {object} The element with the given id, or undefined if no element has this id
  100. */
  101. BoardData.prototype.get = function (id, children) {
  102. return this.board[id];
  103. };
  104. /** Reads data from the board
  105. * @param {string} [id] - Identifier of the first element to get.
  106. * @param {BoardData~processData} callback - Function to be called with each piece of data read
  107. */
  108. BoardData.prototype.getAll = function (id) {
  109. var results = [];
  110. for (var i in this.board) {
  111. if (!id || i > id) {
  112. results.push(this.board[i]);
  113. }
  114. }
  115. return results;
  116. };
  117. /**
  118. * This callback is displayed as part of the BoardData class.
  119. * Describes a function that processes data that comes from the board
  120. * @callback BoardData~processData
  121. * @param {object} data
  122. */
  123. /** Delays the triggering of auto-save by SAVE_INTERVAL seconds
  124. */
  125. BoardData.prototype.delaySave = function (file) {
  126. if (this.saveTimeoutId !== undefined) clearTimeout(this.saveTimeoutId);
  127. this.saveTimeoutId = setTimeout(this.save.bind(this), config.SAVE_INTERVAL);
  128. if (Date.now() - this.lastSaveDate > config.MAX_SAVE_DELAY)
  129. setTimeout(this.save.bind(this), 0);
  130. };
  131. /** Saves the data in the board to a file.
  132. * @param {string} [file=this.file] - Path to the file where the board data will be saved.
  133. */
  134. BoardData.prototype.save = async function (file) {
  135. this.lastSaveDate = Date.now();
  136. this.clean();
  137. if (!file) file = this.file;
  138. var tmp_file = backupFileName(file);
  139. var board_txt = JSON.stringify(this.board);
  140. if (board_txt === "{}") {
  141. // empty board
  142. try {
  143. await fs.promises.unlink(file);
  144. log("removed empty board", { name: this.name });
  145. } catch (err) {
  146. if (err.code !== "ENOENT") {
  147. // If the file already wasn't saved, this is not an error
  148. log("board deletion error", { err: err.toString() });
  149. }
  150. }
  151. } else {
  152. try {
  153. await fs.promises.writeFile(tmp_file, board_txt);
  154. await fs.promises.rename(tmp_file, file);
  155. log("saved board", {
  156. name: this.name,
  157. size: board_txt.length,
  158. delay_ms: Date.now() - this.lastSaveDate,
  159. });
  160. } catch (err) {
  161. log("board saving error", {
  162. err: err.toString(),
  163. tmp_file: tmp_file,
  164. });
  165. return;
  166. }
  167. }
  168. };
  169. /** Remove old elements from the board */
  170. BoardData.prototype.clean = function cleanBoard() {
  171. var board = this.board;
  172. var ids = Object.keys(board);
  173. if (ids.length > config.MAX_ITEM_COUNT) {
  174. var toDestroy = ids
  175. .sort(function (x, y) {
  176. return (board[x].time | 0) - (board[y].time | 0);
  177. })
  178. .slice(0, -config.MAX_ITEM_COUNT);
  179. for (var i = 0; i < toDestroy.length; i++) delete board[toDestroy[i]];
  180. log("cleaned board", { removed: toDestroy.length, board: this.name });
  181. }
  182. };
  183. /** Reformats an item if necessary in order to make it follow the boards' policy
  184. * @param {object} item The object to edit
  185. * @param {object} parent The parent of the object to edit
  186. */
  187. BoardData.prototype.validate = function validate(item, parent) {
  188. if (item.hasOwnProperty("size")) {
  189. item.size = parseInt(item.size) || 1;
  190. item.size = Math.min(Math.max(item.size, 1), 50);
  191. }
  192. if (item.hasOwnProperty("x") || item.hasOwnProperty("y")) {
  193. item.x = parseFloat(item.x) || 0;
  194. item.x = Math.min(Math.max(item.x, 0), config.MAX_BOARD_SIZE);
  195. item.x = Math.round(10 * item.x) / 10;
  196. item.y = parseFloat(item.y) || 0;
  197. item.y = Math.min(Math.max(item.y, 0), config.MAX_BOARD_SIZE);
  198. item.y = Math.round(10 * item.y) / 10;
  199. }
  200. if (item.hasOwnProperty("opacity")) {
  201. item.opacity = Math.min(Math.max(item.opacity, 0.1), 1) || 1;
  202. if (item.opacity === 1) delete item.opacity;
  203. }
  204. if (item.hasOwnProperty("_children")) {
  205. if (!Array.isArray(item._children)) item._children = [];
  206. if (item._children.length > config.MAX_CHILDREN)
  207. item._children.length = config.MAX_CHILDREN;
  208. for (var i = 0; i < item._children.length; i++) {
  209. this.validate(item._children[i]);
  210. }
  211. }
  212. };
  213. /** Load the data in the board from a file.
  214. * @param {string} name - name of the board
  215. */
  216. BoardData.load = async function loadBoard(name) {
  217. var boardData = new BoardData(name),
  218. data;
  219. try {
  220. data = await fs.promises.readFile(boardData.file);
  221. boardData.board = JSON.parse(data);
  222. for (id in boardData.board) boardData.validate(boardData.board[id]);
  223. log("disk load", { board: boardData.name });
  224. } catch (e) {
  225. log("empty board creation", {
  226. board: boardData.name,
  227. // If the file doesn't exist, this is not an error
  228. error: e.code !== "ENOENT" && e.toString(),
  229. });
  230. boardData.board = {};
  231. if (data) {
  232. // There was an error loading the board, but some data was still read
  233. var backup = backupFileName(boardData.file);
  234. log("Writing the corrupted file to " + backup);
  235. try {
  236. await fs.promises.writeFile(backup, data);
  237. } catch (err) {
  238. log("Error writing " + backup + ": " + err);
  239. }
  240. }
  241. }
  242. return boardData;
  243. };
  244. /**
  245. * Given a board file name, return a name to use for temporary data saving.
  246. * @param {string} baseName
  247. */
  248. function backupFileName(baseName) {
  249. var date = new Date().toISOString().replace(/:/g, "");
  250. return baseName + "." + date + ".bak";
  251. }
  252. module.exports.BoardData = BoardData;