您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

boardData.js 7.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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. path = require("path"),
  29. util = require("util"),
  30. events = require("events");
  31. /** @constant
  32. @type {string}
  33. @default
  34. Path to the file where boards will be saved by default
  35. */
  36. var HISTORY_DIR = path.join(__dirname, "../server-data/");
  37. /** @constant
  38. @type {Number}
  39. @default
  40. Number of seconds of inactivity after which the board should be saved to a file
  41. */
  42. var SAVE_INTERVAL = 1000 * 2; // Save after 2 seconds of inactivity
  43. var MAX_SAVE_DELAY = 1000 * 60; // Save after 60 seconds even if there is still activity
  44. var MAX_ITEM_COUNT = 65536; // Max number of items to keep in the board
  45. var MAX_CHILDREN = 128; // Max number of subitems in an item
  46. var MAX_BOARD_SIZE = 65536; // Maximum value for any x or y on the board
  47. /**
  48. * Represents a board.
  49. * @constructor
  50. */
  51. var BoardData = function (name) {
  52. var that = this;
  53. this.name = name;
  54. this.board = {};
  55. this.ready = false;
  56. this.file = path.join(HISTORY_DIR, "board-" + encodeURIComponent(name) + ".json");
  57. this.lastSaveDate = Date.now();
  58. //Loads the file. This will emit the "ready" event
  59. this.load(this.file);
  60. this.on("ready", function () {
  61. that.ready = true;
  62. });
  63. };
  64. //Allows to use BoardData.emit() and BoardData.on()
  65. util.inherits(BoardData, events.EventEmitter);
  66. /** Adds data to the board */
  67. BoardData.prototype.set = function (id, data) {
  68. //KISS
  69. this.validate(data);
  70. this.board[id] = data;
  71. this.delaySave();
  72. };
  73. /** Adds a child to an element that is already in the board
  74. * @param {string} id - Identifier of the parent element.
  75. * @param {object} child - Object containing the the values to update.
  76. * @param {boolean} [create=true] - Whether to create an empty parent if it doesn't exist
  77. * @returns {boolean} - True if the child was added, else false
  78. */
  79. BoardData.prototype.addChild = function (parentId, child, create) {
  80. if (create === undefined) create = true;
  81. var obj = this.board[parentId];
  82. if (typeof obj !== "object") {
  83. if (create) obj = this.board[parentId] = {};
  84. else return false;
  85. }
  86. if (Array.isArray(obj._children)) obj._children.push(child);
  87. else obj._children = [child];
  88. this.validate(obj);
  89. this.delaySave();
  90. return true;
  91. };
  92. /** Update the data in the board
  93. * @param {string} id - Identifier of the data to update.
  94. * @param {object} data - Object containing the the values to update.
  95. * @param {boolean} create - True if the object should be created if it's not currently in the DB.
  96. */
  97. BoardData.prototype.update = function (id, data, create) {
  98. var obj = this.board[id];
  99. if (typeof obj === "object") {
  100. for (var i in data) {
  101. obj[i] = data[i];
  102. }
  103. } else if (create || obj !== undefined) {
  104. this.board[id] = data;
  105. }
  106. this.delaySave();
  107. };
  108. /** Removes data from the board
  109. * @param {string} id - Identifier of the data to delete.
  110. */
  111. BoardData.prototype.delete = function (id) {
  112. //KISS
  113. delete this.board[id];
  114. this.delaySave();
  115. };
  116. /** Reads data from the board
  117. * @param {string} id - Identifier of the element to get.
  118. * @returns {object} The element with the given id, or undefined if no element has this id
  119. */
  120. BoardData.prototype.get = function (id, children) {
  121. return this.board[id];
  122. };
  123. /** Reads data from the board
  124. * @param {string} [id] - Identifier of the first element to get.
  125. * @param {BoardData~processData} callback - Function to be called with each piece of data read
  126. */
  127. BoardData.prototype.getAll = function (id) {
  128. var results = [];
  129. for (var i in this.board) {
  130. if (!id || i > id) {
  131. results.push(this.board[i]);
  132. }
  133. }
  134. return results;
  135. };
  136. /**
  137. * This callback is displayed as part of the BoardData class.
  138. * Describes a function that processes data that comes from the board
  139. * @callback BoardData~processData
  140. * @param {object} data
  141. */
  142. /** Delays the triggering of auto-save by SAVE_INTERVAL seconds
  143. */
  144. BoardData.prototype.delaySave = function (file) {
  145. if (this.saveTimeoutId !== undefined) clearTimeout(this.saveTimeoutId);
  146. this.saveTimeoutId = setTimeout(this.save.bind(this), SAVE_INTERVAL);
  147. if (Date.now() - this.lastSaveDate > MAX_SAVE_DELAY) setTimeout(this.save.bind(this), 0);
  148. };
  149. /** Saves the data in the board to a file.
  150. * @param {string} [file=this.file] - Path to the file where the board data will be saved.
  151. */
  152. BoardData.prototype.save = function (file) {
  153. this.lastSaveDate = Date.now();
  154. this.clean();
  155. if (!file) file = this.file;
  156. var board_txt = JSON.stringify(this.board);
  157. var that = this;
  158. fs.writeFile(file, board_txt, function onBoardSaved(err) {
  159. if (err) {
  160. console.trace(new Error("Unable to save the board: " + err));
  161. } else {
  162. console.log("Successfully saved board: " + that.name);
  163. }
  164. });
  165. };
  166. /** Remove old elements from the board */
  167. BoardData.prototype.clean = function cleanBoard() {
  168. var toDestroy = Object.keys(this.board)
  169. .sort((x, y) => x.slice(1) < y.slice(1) ? -1 : 1)
  170. .slice(0, -MAX_ITEM_COUNT);
  171. for (var i = 0; i < toDestroy.length; i++) {
  172. delete this.board[toDestroy[i]];
  173. }
  174. if (toDestroy.length > 0) console.log("Cleaned " + toDestroy.length + " items in " + this.name);
  175. }
  176. /** Reformats an item if necessary in order to make it follow the boards' policy
  177. * @param {object} item The object to edit
  178. * @param {object} parent The parent of the object to edit
  179. */
  180. BoardData.prototype.validate = function validate(item, parent) {
  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 = parseInt(item.x) || 0;
  187. item.x = Math.min(Math.max(item.x, 0), MAX_BOARD_SIZE);
  188. item.y = parseInt(item.y) || 0;
  189. item.y = Math.min(Math.max(item.y, 0), MAX_BOARD_SIZE);
  190. }
  191. if (item.hasOwnProperty("_children")) {
  192. if (!Array.isArray(item._children)) item._children = [];
  193. if (item._children.length > MAX_CHILDREN) item._children.length = MAX_CHILDREN;
  194. for (var i = 0; i < item._children.length; i++) {
  195. this.validate(item._children[i]);
  196. }
  197. }
  198. }
  199. /** Load the data in the board from a file.
  200. * @param {string} file - Path to the file where the board data will be read.
  201. */
  202. BoardData.prototype.load = function (file) {
  203. var that = this;
  204. fs.readFile(file, function (err, data) {
  205. try {
  206. if (err) throw err;
  207. that.board = JSON.parse(data);
  208. for (id in that.board) that.validate(that.board[id]);
  209. console.log(that.name + " loaded from file.");
  210. } catch (e) {
  211. console.error("Unable to read history from " + file + ". The following error occured: " + e);
  212. console.log("Creating an empty board.");
  213. that.board = {}
  214. }
  215. that.emit("ready");
  216. });
  217. };
  218. module.exports.BoardData = BoardData;