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

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