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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. * @typedef {{
  105. * id:string,
  106. * type: "delete" | "update" | "child",
  107. * parent?: string,
  108. * _children?: BoardMessage[],
  109. * } & BoardElem } BoardMessage
  110. * @param {BoardMessage[]} children array of messages to be delegated to the other methods
  111. */
  112. processMessageBatch(children) {
  113. for (const message of children) {
  114. this.processMessage(message);
  115. }
  116. }
  117. /** Process a single message
  118. * @param {BoardMessage} message instruction to apply to the board
  119. */
  120. processMessage(message) {
  121. if (message._children) return this.processMessageBatch(message._children);
  122. let id = message.id;
  123. switch (message.type) {
  124. case "delete":
  125. if (id) this.delete(id);
  126. break;
  127. case "update":
  128. if (id) this.update(id, message);
  129. break;
  130. case "child":
  131. this.addChild(message.parent, message);
  132. break;
  133. default:
  134. //Add data
  135. if (!id) throw new Error("Invalid message: ", message);
  136. this.set(id, message);
  137. }
  138. }
  139. /** Reads data from the board
  140. * @param {string} id - Identifier of the element to get.
  141. * @returns {BoardElem} The element with the given id, or undefined if no element has this id
  142. */
  143. get(id) {
  144. return this.board[id];
  145. }
  146. /** Reads data from the board
  147. * @param {string} [id] - Identifier of the first element to get.
  148. * @returns {BoardElem[]}
  149. */
  150. getAll(id) {
  151. return Object.entries(this.board)
  152. .filter(([i]) => !id || i > id)
  153. .map(([_, elem]) => elem);
  154. }
  155. /** Delays the triggering of auto-save by SAVE_INTERVAL seconds */
  156. delaySave() {
  157. if (this.saveTimeoutId !== undefined) clearTimeout(this.saveTimeoutId);
  158. this.saveTimeoutId = setTimeout(this.save.bind(this), config.SAVE_INTERVAL);
  159. if (Date.now() - this.lastSaveDate > config.MAX_SAVE_DELAY)
  160. setTimeout(this.save.bind(this), 0);
  161. }
  162. /** Saves the data in the board to a file. */
  163. async save() {
  164. // The mutex prevents multiple save operation to happen simultaneously
  165. this.saveMutex.runExclusive(this._unsafe_save.bind(this));
  166. }
  167. /** Save the board to disk without preventing multiple simultaneaous saves. Use save() instead */
  168. async _unsafe_save() {
  169. this.lastSaveDate = Date.now();
  170. this.clean();
  171. var file = this.file;
  172. var tmp_file = backupFileName(file);
  173. var board_txt = JSON.stringify(this.board);
  174. if (board_txt === "{}") {
  175. // empty board
  176. try {
  177. await fs.promises.unlink(file);
  178. log("removed empty board", { name: this.name });
  179. } catch (err) {
  180. if (err.code !== "ENOENT") {
  181. // If the file already wasn't saved, this is not an error
  182. log("board deletion error", { err: err.toString() });
  183. }
  184. }
  185. } else {
  186. try {
  187. await fs.promises.writeFile(tmp_file, board_txt, { flag: "wx" });
  188. await fs.promises.rename(tmp_file, file);
  189. log("saved board", {
  190. name: this.name,
  191. size: board_txt.length,
  192. delay_ms: Date.now() - this.lastSaveDate,
  193. });
  194. } catch (err) {
  195. log("board saving error", {
  196. err: err.toString(),
  197. tmp_file: tmp_file,
  198. });
  199. return;
  200. }
  201. }
  202. }
  203. /** Remove old elements from the board */
  204. clean() {
  205. var board = this.board;
  206. var ids = Object.keys(board);
  207. if (ids.length > config.MAX_ITEM_COUNT) {
  208. var toDestroy = ids
  209. .sort(function (x, y) {
  210. return (board[x].time | 0) - (board[y].time | 0);
  211. })
  212. .slice(0, -config.MAX_ITEM_COUNT);
  213. for (var i = 0; i < toDestroy.length; i++) delete board[toDestroy[i]];
  214. log("cleaned board", { removed: toDestroy.length, board: this.name });
  215. }
  216. }
  217. /** Reformats an item if necessary in order to make it follow the boards' policy
  218. * @param {object} item The object to edit
  219. */
  220. validate(item) {
  221. if (item.hasOwnProperty("size")) {
  222. item.size = parseInt(item.size) || 1;
  223. item.size = Math.min(Math.max(item.size, 1), 50);
  224. }
  225. if (item.hasOwnProperty("x") || item.hasOwnProperty("y")) {
  226. item.x = parseFloat(item.x) || 0;
  227. item.x = Math.min(Math.max(item.x, 0), config.MAX_BOARD_SIZE);
  228. item.x = Math.round(10 * item.x) / 10;
  229. item.y = parseFloat(item.y) || 0;
  230. item.y = Math.min(Math.max(item.y, 0), config.MAX_BOARD_SIZE);
  231. item.y = Math.round(10 * item.y) / 10;
  232. }
  233. if (item.hasOwnProperty("opacity")) {
  234. item.opacity = Math.min(Math.max(item.opacity, 0.1), 1) || 1;
  235. if (item.opacity === 1) delete item.opacity;
  236. }
  237. if (item.hasOwnProperty("_children")) {
  238. if (!Array.isArray(item._children)) item._children = [];
  239. if (item._children.length > config.MAX_CHILDREN)
  240. item._children.length = config.MAX_CHILDREN;
  241. for (var i = 0; i < item._children.length; i++) {
  242. this.validate(item._children[i]);
  243. }
  244. }
  245. }
  246. /** Load the data in the board from a file.
  247. * @param {string} name - name of the board
  248. */
  249. static async load(name) {
  250. var boardData = new BoardData(name),
  251. data;
  252. try {
  253. data = await fs.promises.readFile(boardData.file);
  254. boardData.board = JSON.parse(data);
  255. for (const id in boardData.board) boardData.validate(boardData.board[id]);
  256. log("disk load", { board: boardData.name });
  257. } catch (e) {
  258. // If the file doesn't exist, this is not an error
  259. if (e.code === "ENOENT") {
  260. log("empty board creation", { board: boardData.name });
  261. } else {
  262. log("board load error", {
  263. board: name,
  264. error: e.toString(),
  265. stack: e.stack,
  266. });
  267. }
  268. boardData.board = {};
  269. if (data) {
  270. // There was an error loading the board, but some data was still read
  271. var backup = backupFileName(boardData.file);
  272. log("Writing the corrupted file to " + backup);
  273. try {
  274. await fs.promises.writeFile(backup, data);
  275. } catch (err) {
  276. log("Error writing " + backup + ": " + err);
  277. }
  278. }
  279. }
  280. return boardData;
  281. }
  282. }
  283. /**
  284. * Given a board file name, return a name to use for temporary data saving.
  285. * @param {string} baseName
  286. */
  287. function backupFileName(baseName) {
  288. var date = new Date().toISOString().replace(/:/g, "");
  289. return baseName + "." + date + ".bak";
  290. }
  291. module.exports.BoardData = BoardData;