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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. * @typedef {{[object_id:string]: any}} BoardElem
  34. */
  35. class BoardData {
  36. /**
  37. * @param {string} name
  38. */
  39. constructor(name) {
  40. this.name = name;
  41. /** @type {{[name: string]: BoardElem}} */
  42. this.board = {};
  43. this.file = path.join(
  44. config.HISTORY_DIR,
  45. "board-" + encodeURIComponent(name) + ".json"
  46. );
  47. this.lastSaveDate = Date.now();
  48. this.users = new Set();
  49. }
  50. /** Adds data to the board
  51. * @param {string} id
  52. * @param {BoardElem} data
  53. */
  54. set(id, data) {
  55. //KISS
  56. data.time = Date.now();
  57. this.validate(data);
  58. this.board[id] = data;
  59. this.delaySave();
  60. }
  61. /** Adds a child to an element that is already in the board
  62. * @param {string} parentId - Identifier of the parent element.
  63. * @param {BoardElem} child - Object containing the the values to update.
  64. * @returns {boolean} - True if the child was added, else false
  65. */
  66. addChild(parentId, child) {
  67. var obj = this.board[parentId];
  68. if (typeof obj !== "object") return false;
  69. if (Array.isArray(obj._children)) obj._children.push(child);
  70. else obj._children = [child];
  71. this.validate(obj);
  72. this.delaySave();
  73. return true;
  74. }
  75. /** Update the data in the board
  76. * @param {string} id - Identifier of the data to update.
  77. * @param {BoardElem} data - Object containing the values to update.
  78. * @param {boolean} create - True if the object should be created if it's not currently in the DB.
  79. */
  80. update(id, data, create) {
  81. delete data.type;
  82. delete data.tool;
  83. var obj = this.board[id];
  84. if (typeof obj === "object") {
  85. for (var i in data) {
  86. obj[i] = data[i];
  87. }
  88. } else if (create || obj !== undefined) {
  89. this.board[id] = data;
  90. }
  91. this.delaySave();
  92. }
  93. /** Removes data from the board
  94. * @param {string} id - Identifier of the data to delete.
  95. */
  96. delete(id) {
  97. //KISS
  98. delete this.board[id];
  99. this.delaySave();
  100. }
  101. /** Reads data from the board
  102. * @param {string} id - Identifier of the element to get.
  103. * @returns {BoardElem} The element with the given id, or undefined if no element has this id
  104. */
  105. get(id) {
  106. return this.board[id];
  107. }
  108. /** Reads data from the board
  109. * @param {string} [id] - Identifier of the first element to get.
  110. * @returns {BoardElem[]}
  111. */
  112. getAll(id) {
  113. return Object.entries(this.board)
  114. .filter(([i]) => !id || i > id)
  115. .map(([_, elem]) => elem);
  116. }
  117. /** Delays the triggering of auto-save by SAVE_INTERVAL seconds
  118. */
  119. delaySave() {
  120. if (this.saveTimeoutId !== undefined) clearTimeout(this.saveTimeoutId);
  121. this.saveTimeoutId = setTimeout(this.save.bind(this), config.SAVE_INTERVAL);
  122. if (Date.now() - this.lastSaveDate > config.MAX_SAVE_DELAY)
  123. setTimeout(this.save.bind(this), 0);
  124. }
  125. /** Saves the data in the board to a file.
  126. * @param {string} [file=this.file] - Path to the file where the board data will be saved.
  127. */
  128. async save(file) {
  129. this.lastSaveDate = Date.now();
  130. this.clean();
  131. if (!file) file = this.file;
  132. var tmp_file = backupFileName(file);
  133. var board_txt = JSON.stringify(this.board);
  134. if (board_txt === "{}") {
  135. // empty board
  136. try {
  137. await fs.promises.unlink(file);
  138. log("removed empty board", { name: this.name });
  139. } catch (err) {
  140. if (err.code !== "ENOENT") {
  141. // If the file already wasn't saved, this is not an error
  142. log("board deletion error", { err: err.toString() });
  143. }
  144. }
  145. } else {
  146. try {
  147. await fs.promises.writeFile(tmp_file, board_txt);
  148. await fs.promises.rename(tmp_file, file);
  149. log("saved board", {
  150. name: this.name,
  151. size: board_txt.length,
  152. delay_ms: Date.now() - this.lastSaveDate,
  153. });
  154. } catch (err) {
  155. log("board saving error", {
  156. err: err.toString(),
  157. tmp_file: tmp_file,
  158. });
  159. return;
  160. }
  161. }
  162. }
  163. /** Remove old elements from the board */
  164. clean() {
  165. var board = this.board;
  166. var ids = Object.keys(board);
  167. if (ids.length > config.MAX_ITEM_COUNT) {
  168. var toDestroy = ids
  169. .sort(function (x, y) {
  170. return (board[x].time | 0) - (board[y].time | 0);
  171. })
  172. .slice(0, -config.MAX_ITEM_COUNT);
  173. for (var i = 0; i < toDestroy.length; i++) delete board[toDestroy[i]];
  174. log("cleaned board", { removed: toDestroy.length, board: this.name });
  175. }
  176. }
  177. /** Reformats an item if necessary in order to make it follow the boards' policy
  178. * @param {object} item The object to edit
  179. */
  180. validate(item) {
  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)
  200. item._children.length = config.MAX_CHILDREN;
  201. for (var i = 0; i < item._children.length; i++) {
  202. this.validate(item._children[i]);
  203. }
  204. }
  205. }
  206. /** Load the data in the board from a file.
  207. * @param {string} name - name of the board
  208. */
  209. static async load(name) {
  210. var boardData = new BoardData(name),
  211. 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. }
  238. /**
  239. * Given a board file name, return a name to use for temporary data saving.
  240. * @param {string} baseName
  241. */
  242. function backupFileName(baseName) {
  243. var date = new Date().toISOString().replace(/:/g, "");
  244. return baseName + "." + date + ".bak";
  245. }
  246. module.exports.BoardData = BoardData;