Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

boardData.js 8.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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 = async function (file) {
  146. this.lastSaveDate = Date.now();
  147. this.clean();
  148. if (!file) file = this.file;
  149. var tmp_file = backupFileName(file);
  150. var board_txt = JSON.stringify(this.board);
  151. if (board_txt === "{}") { // empty board
  152. try {
  153. await fs.promises.unlink(file);
  154. log("removed empty board", { 'name': this.name });
  155. } catch (err) {
  156. if (err.code !== "ENOENT") {
  157. // If the file already wasn't saved, this is not an error
  158. log("board deletion error", { "e": err })
  159. }
  160. }
  161. } else {
  162. try {
  163. await fs.promises.writeFile(tmp_file, board_txt);
  164. await fs.promises.rename(tmp_file, file);
  165. log("saved board", {
  166. 'name': this.name,
  167. 'size': board_txt.length,
  168. 'delay_ms': (Date.now() - this.lastSaveDate),
  169. });
  170. } catch (err) {
  171. log("board saving error", {
  172. 'err': err.toString(),
  173. 'tmp_file': tmp_file,
  174. });
  175. return;
  176. }
  177. }
  178. };
  179. /** Remove old elements from the board */
  180. BoardData.prototype.clean = function cleanBoard() {
  181. var board = this.board;
  182. var ids = Object.keys(board);
  183. if (ids.length > MAX_ITEM_COUNT) {
  184. var toDestroy = ids.sort(function (x, y) {
  185. return (board[x].time | 0) - (board[y].time | 0);
  186. }).slice(0, -MAX_ITEM_COUNT);
  187. for (var i = 0; i < toDestroy.length; i++) delete board[toDestroy[i]];
  188. log("cleaned board", { 'removed': toDestroy.length, "board": this.name });
  189. }
  190. }
  191. /** Reformats an item if necessary in order to make it follow the boards' policy
  192. * @param {object} item The object to edit
  193. * @param {object} parent The parent of the object to edit
  194. */
  195. BoardData.prototype.validate = function validate(item, parent) {
  196. if (item.hasOwnProperty("size")) {
  197. item.size = parseInt(item.size) || 1;
  198. item.size = Math.min(Math.max(item.size, 1), 50);
  199. }
  200. if (item.hasOwnProperty("x") || item.hasOwnProperty("y")) {
  201. item.x = parseFloat(item.x) || 0;
  202. item.x = Math.min(Math.max(item.x, 0), MAX_BOARD_SIZE);
  203. item.x = Math.round(10 * item.x) / 10;
  204. item.y = parseFloat(item.y) || 0;
  205. item.y = Math.min(Math.max(item.y, 0), MAX_BOARD_SIZE);
  206. item.y = Math.round(10 * item.y) / 10;
  207. }
  208. if (item.hasOwnProperty("opacity")) {
  209. item.opacity = Math.min(Math.max(item.opacity, 0.1), 1) || 1;
  210. if (item.opacity === 1) delete item.opacity;
  211. }
  212. if (item.hasOwnProperty("_children")) {
  213. if (!Array.isArray(item._children)) item._children = [];
  214. if (item._children.length > MAX_CHILDREN) item._children.length = MAX_CHILDREN;
  215. for (var i = 0; i < item._children.length; i++) {
  216. this.validate(item._children[i]);
  217. }
  218. }
  219. }
  220. /** Load the data in the board from a file.
  221. * @param {string} file - Path to the file where the board data will be read.
  222. */
  223. BoardData.load = async function loadBoard(name) {
  224. var boardData = new BoardData(name), data;
  225. try {
  226. data = await fs.promises.readFile(boardData.file);
  227. boardData.board = JSON.parse(data);
  228. for (id in boardData.board) boardData.validate(boardData.board[id]);
  229. log('disk load', { 'board': boardData.name });
  230. } catch (e) {
  231. log('empty board creation', {
  232. 'board': boardData.name,
  233. // If the file doesn't exist, this is not an error
  234. "error": e.code !== "ENOENT" && e.toString(),
  235. });
  236. boardData.board = {}
  237. if (data) {
  238. // There was an error loading the board, but some data was still read
  239. var backup = backupFileName(boardData.file);
  240. log("Writing the corrupted file to " + backup);
  241. try {
  242. await fs.promises.writeFile(backup, data);
  243. } catch (err) {
  244. log("Error writing " + backup + ": " + err);
  245. }
  246. }
  247. }
  248. return boardData;
  249. };
  250. function backupFileName(baseName) {
  251. var date = new Date().toISOString().replace(/:/g, '');
  252. return baseName + '.' + date + '.bak';
  253. }
  254. module.exports.BoardData = BoardData;