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.1KB

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