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

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