mirror of
https://github.com/lovasoa/whitebophir
synced 2024-11-12 23:37:14 +00:00
Use the modern class syntax on the server
This commit is contained in:
parent
53c61ec16e
commit
de9f9725e9
1 changed files with 196 additions and 203 deletions
|
@ -32,231 +32,224 @@ var fs = require("./fs_promises.js"),
|
|||
|
||||
/**
|
||||
* Represents a board.
|
||||
* @class
|
||||
* @constructor
|
||||
* @param {string} name
|
||||
* @typedef {{[object_id:string]: any}} BoardElem
|
||||
*/
|
||||
var BoardData = function (name) {
|
||||
this.name = name;
|
||||
/** @type {{[name: string]: {[object_id:string]: any}}} */
|
||||
this.board = {};
|
||||
this.file = path.join(
|
||||
config.HISTORY_DIR,
|
||||
"board-" + encodeURIComponent(name) + ".json"
|
||||
);
|
||||
this.lastSaveDate = Date.now();
|
||||
this.users = new Set();
|
||||
};
|
||||
class BoardData {
|
||||
/**
|
||||
* @param {string} name
|
||||
*/
|
||||
constructor(name) {
|
||||
this.name = name;
|
||||
/** @type {{[name: string]: BoardElem}} */
|
||||
this.board = {};
|
||||
this.file = path.join(
|
||||
config.HISTORY_DIR,
|
||||
"board-" + encodeURIComponent(name) + ".json"
|
||||
);
|
||||
this.lastSaveDate = Date.now();
|
||||
this.users = new Set();
|
||||
}
|
||||
|
||||
/** Adds data to the board */
|
||||
BoardData.prototype.set = function (id, data) {
|
||||
//KISS
|
||||
data.time = Date.now();
|
||||
this.validate(data);
|
||||
this.board[id] = data;
|
||||
this.delaySave();
|
||||
};
|
||||
|
||||
/** Adds a child to an element that is already in the board
|
||||
* @param {string} id - Identifier of the parent element.
|
||||
* @param {object} child - Object containing the the values to update.
|
||||
* @param {boolean} [create=true] - Whether to create an empty parent if it doesn't exist
|
||||
* @returns {boolean} - True if the child was added, else false
|
||||
*/
|
||||
BoardData.prototype.addChild = function (parentId, child) {
|
||||
var obj = this.board[parentId];
|
||||
if (typeof obj !== "object") return false;
|
||||
if (Array.isArray(obj._children)) obj._children.push(child);
|
||||
else obj._children = [child];
|
||||
|
||||
this.validate(obj);
|
||||
this.delaySave();
|
||||
return true;
|
||||
};
|
||||
|
||||
/** Update the data in the board
|
||||
* @param {string} id - Identifier of the data to update.
|
||||
* @param {object} data - Object containing the values to update.
|
||||
* @param {boolean} create - True if the object should be created if it's not currently in the DB.
|
||||
*/
|
||||
BoardData.prototype.update = function (id, data, create) {
|
||||
delete data.type;
|
||||
delete data.tool;
|
||||
|
||||
var obj = this.board[id];
|
||||
if (typeof obj === "object") {
|
||||
for (var i in data) {
|
||||
obj[i] = data[i];
|
||||
}
|
||||
} else if (create || obj !== undefined) {
|
||||
/** Adds data to the board
|
||||
* @param {string} id
|
||||
* @param {BoardElem} data
|
||||
*/
|
||||
set(id, data) {
|
||||
//KISS
|
||||
data.time = Date.now();
|
||||
this.validate(data);
|
||||
this.board[id] = data;
|
||||
this.delaySave();
|
||||
}
|
||||
this.delaySave();
|
||||
};
|
||||
|
||||
/** Removes data from the board
|
||||
* @param {string} id - Identifier of the data to delete.
|
||||
*/
|
||||
BoardData.prototype.delete = function (id) {
|
||||
//KISS
|
||||
delete this.board[id];
|
||||
this.delaySave();
|
||||
};
|
||||
/** Adds a child to an element that is already in the board
|
||||
* @param {string} parentId - Identifier of the parent element.
|
||||
* @param {BoardElem} child - Object containing the the values to update.
|
||||
* @returns {boolean} - True if the child was added, else false
|
||||
*/
|
||||
addChild(parentId, child) {
|
||||
var obj = this.board[parentId];
|
||||
if (typeof obj !== "object") return false;
|
||||
if (Array.isArray(obj._children)) obj._children.push(child);
|
||||
else obj._children = [child];
|
||||
|
||||
/** Reads data from the board
|
||||
* @param {string} id - Identifier of the element to get.
|
||||
* @returns {object} The element with the given id, or undefined if no element has this id
|
||||
*/
|
||||
BoardData.prototype.get = function (id, children) {
|
||||
return this.board[id];
|
||||
};
|
||||
|
||||
/** Reads data from the board
|
||||
* @param {string} [id] - Identifier of the first element to get.
|
||||
* @param {BoardData~processData} callback - Function to be called with each piece of data read
|
||||
*/
|
||||
BoardData.prototype.getAll = function (id) {
|
||||
var results = [];
|
||||
for (var i in this.board) {
|
||||
if (!id || i > id) {
|
||||
results.push(this.board[i]);
|
||||
}
|
||||
this.validate(obj);
|
||||
this.delaySave();
|
||||
return true;
|
||||
}
|
||||
return results;
|
||||
};
|
||||
|
||||
/**
|
||||
* This callback is displayed as part of the BoardData class.
|
||||
* Describes a function that processes data that comes from the board
|
||||
* @callback BoardData~processData
|
||||
* @param {object} data
|
||||
*/
|
||||
/** Update the data in the board
|
||||
* @param {string} id - Identifier of the data to update.
|
||||
* @param {BoardElem} data - Object containing the values to update.
|
||||
* @param {boolean} create - True if the object should be created if it's not currently in the DB.
|
||||
*/
|
||||
update(id, data, create) {
|
||||
delete data.type;
|
||||
delete data.tool;
|
||||
|
||||
/** Delays the triggering of auto-save by SAVE_INTERVAL seconds
|
||||
*/
|
||||
BoardData.prototype.delaySave = function (file) {
|
||||
if (this.saveTimeoutId !== undefined) clearTimeout(this.saveTimeoutId);
|
||||
this.saveTimeoutId = setTimeout(this.save.bind(this), config.SAVE_INTERVAL);
|
||||
if (Date.now() - this.lastSaveDate > config.MAX_SAVE_DELAY)
|
||||
setTimeout(this.save.bind(this), 0);
|
||||
};
|
||||
|
||||
/** Saves the data in the board to a file.
|
||||
* @param {string} [file=this.file] - Path to the file where the board data will be saved.
|
||||
*/
|
||||
BoardData.prototype.save = async function (file) {
|
||||
this.lastSaveDate = Date.now();
|
||||
this.clean();
|
||||
if (!file) file = this.file;
|
||||
var tmp_file = backupFileName(file);
|
||||
var board_txt = JSON.stringify(this.board);
|
||||
if (board_txt === "{}") {
|
||||
// empty board
|
||||
try {
|
||||
await fs.promises.unlink(file);
|
||||
log("removed empty board", { name: this.name });
|
||||
} catch (err) {
|
||||
if (err.code !== "ENOENT") {
|
||||
// If the file already wasn't saved, this is not an error
|
||||
log("board deletion error", { err: err.toString() });
|
||||
var obj = this.board[id];
|
||||
if (typeof obj === "object") {
|
||||
for (var i in data) {
|
||||
obj[i] = data[i];
|
||||
}
|
||||
} else if (create || obj !== undefined) {
|
||||
this.board[id] = data;
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
await fs.promises.writeFile(tmp_file, board_txt);
|
||||
await fs.promises.rename(tmp_file, file);
|
||||
log("saved board", {
|
||||
name: this.name,
|
||||
size: board_txt.length,
|
||||
delay_ms: Date.now() - this.lastSaveDate,
|
||||
});
|
||||
} catch (err) {
|
||||
log("board saving error", {
|
||||
err: err.toString(),
|
||||
tmp_file: tmp_file,
|
||||
});
|
||||
return;
|
||||
}
|
||||
this.delaySave();
|
||||
}
|
||||
};
|
||||
|
||||
/** Remove old elements from the board */
|
||||
BoardData.prototype.clean = function cleanBoard() {
|
||||
var board = this.board;
|
||||
var ids = Object.keys(board);
|
||||
if (ids.length > config.MAX_ITEM_COUNT) {
|
||||
var toDestroy = ids
|
||||
.sort(function (x, y) {
|
||||
return (board[x].time | 0) - (board[y].time | 0);
|
||||
})
|
||||
.slice(0, -config.MAX_ITEM_COUNT);
|
||||
for (var i = 0; i < toDestroy.length; i++) delete board[toDestroy[i]];
|
||||
log("cleaned board", { removed: toDestroy.length, board: this.name });
|
||||
/** Removes data from the board
|
||||
* @param {string} id - Identifier of the data to delete.
|
||||
*/
|
||||
delete(id) {
|
||||
//KISS
|
||||
delete this.board[id];
|
||||
this.delaySave();
|
||||
}
|
||||
};
|
||||
|
||||
/** Reformats an item if necessary in order to make it follow the boards' policy
|
||||
* @param {object} item The object to edit
|
||||
* @param {object} parent The parent of the object to edit
|
||||
*/
|
||||
BoardData.prototype.validate = function validate(item, parent) {
|
||||
if (item.hasOwnProperty("size")) {
|
||||
item.size = parseInt(item.size) || 1;
|
||||
item.size = Math.min(Math.max(item.size, 1), 50);
|
||||
/** Reads data from the board
|
||||
* @param {string} id - Identifier of the element to get.
|
||||
* @returns {BoardElem} The element with the given id, or undefined if no element has this id
|
||||
*/
|
||||
get(id) {
|
||||
return this.board[id];
|
||||
}
|
||||
if (item.hasOwnProperty("x") || item.hasOwnProperty("y")) {
|
||||
item.x = parseFloat(item.x) || 0;
|
||||
item.x = Math.min(Math.max(item.x, 0), config.MAX_BOARD_SIZE);
|
||||
item.x = Math.round(10 * item.x) / 10;
|
||||
item.y = parseFloat(item.y) || 0;
|
||||
item.y = Math.min(Math.max(item.y, 0), config.MAX_BOARD_SIZE);
|
||||
item.y = Math.round(10 * item.y) / 10;
|
||||
}
|
||||
if (item.hasOwnProperty("opacity")) {
|
||||
item.opacity = Math.min(Math.max(item.opacity, 0.1), 1) || 1;
|
||||
if (item.opacity === 1) delete item.opacity;
|
||||
}
|
||||
if (item.hasOwnProperty("_children")) {
|
||||
if (!Array.isArray(item._children)) item._children = [];
|
||||
if (item._children.length > config.MAX_CHILDREN)
|
||||
item._children.length = config.MAX_CHILDREN;
|
||||
for (var i = 0; i < item._children.length; i++) {
|
||||
this.validate(item._children[i]);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/** Load the data in the board from a file.
|
||||
* @param {string} name - name of the board
|
||||
*/
|
||||
BoardData.load = async function loadBoard(name) {
|
||||
var boardData = new BoardData(name),
|
||||
data;
|
||||
try {
|
||||
data = await fs.promises.readFile(boardData.file);
|
||||
boardData.board = JSON.parse(data);
|
||||
for (id in boardData.board) boardData.validate(boardData.board[id]);
|
||||
log("disk load", { board: boardData.name });
|
||||
} catch (e) {
|
||||
log("empty board creation", {
|
||||
board: boardData.name,
|
||||
// If the file doesn't exist, this is not an error
|
||||
error: e.code !== "ENOENT" && e.toString(),
|
||||
});
|
||||
boardData.board = {};
|
||||
if (data) {
|
||||
// There was an error loading the board, but some data was still read
|
||||
var backup = backupFileName(boardData.file);
|
||||
log("Writing the corrupted file to " + backup);
|
||||
/** Reads data from the board
|
||||
* @param {string} [id] - Identifier of the first element to get.
|
||||
* @returns {BoardElem[]}
|
||||
*/
|
||||
getAll(id) {
|
||||
return Object.entries(this.board)
|
||||
.filter(([i]) => !id || i > id)
|
||||
.map(([_, elem]) => elem);
|
||||
}
|
||||
|
||||
/** Delays the triggering of auto-save by SAVE_INTERVAL seconds
|
||||
*/
|
||||
delaySave() {
|
||||
if (this.saveTimeoutId !== undefined) clearTimeout(this.saveTimeoutId);
|
||||
this.saveTimeoutId = setTimeout(this.save.bind(this), config.SAVE_INTERVAL);
|
||||
if (Date.now() - this.lastSaveDate > config.MAX_SAVE_DELAY)
|
||||
setTimeout(this.save.bind(this), 0);
|
||||
}
|
||||
|
||||
/** Saves the data in the board to a file.
|
||||
* @param {string} [file=this.file] - Path to the file where the board data will be saved.
|
||||
*/
|
||||
async save(file) {
|
||||
this.lastSaveDate = Date.now();
|
||||
this.clean();
|
||||
if (!file) file = this.file;
|
||||
var tmp_file = backupFileName(file);
|
||||
var board_txt = JSON.stringify(this.board);
|
||||
if (board_txt === "{}") {
|
||||
// empty board
|
||||
try {
|
||||
await fs.promises.writeFile(backup, data);
|
||||
await fs.promises.unlink(file);
|
||||
log("removed empty board", { name: this.name });
|
||||
} catch (err) {
|
||||
log("Error writing " + backup + ": " + err);
|
||||
if (err.code !== "ENOENT") {
|
||||
// If the file already wasn't saved, this is not an error
|
||||
log("board deletion error", { err: err.toString() });
|
||||
}
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
await fs.promises.writeFile(tmp_file, board_txt);
|
||||
await fs.promises.rename(tmp_file, file);
|
||||
log("saved board", {
|
||||
name: this.name,
|
||||
size: board_txt.length,
|
||||
delay_ms: Date.now() - this.lastSaveDate,
|
||||
});
|
||||
} catch (err) {
|
||||
log("board saving error", {
|
||||
err: err.toString(),
|
||||
tmp_file: tmp_file,
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
return boardData;
|
||||
};
|
||||
|
||||
/** Remove old elements from the board */
|
||||
clean() {
|
||||
var board = this.board;
|
||||
var ids = Object.keys(board);
|
||||
if (ids.length > config.MAX_ITEM_COUNT) {
|
||||
var toDestroy = ids
|
||||
.sort(function (x, y) {
|
||||
return (board[x].time | 0) - (board[y].time | 0);
|
||||
})
|
||||
.slice(0, -config.MAX_ITEM_COUNT);
|
||||
for (var i = 0; i < toDestroy.length; i++) delete board[toDestroy[i]];
|
||||
log("cleaned board", { removed: toDestroy.length, board: this.name });
|
||||
}
|
||||
}
|
||||
|
||||
/** Reformats an item if necessary in order to make it follow the boards' policy
|
||||
* @param {object} item The object to edit
|
||||
*/
|
||||
validate(item) {
|
||||
if (item.hasOwnProperty("size")) {
|
||||
item.size = parseInt(item.size) || 1;
|
||||
item.size = Math.min(Math.max(item.size, 1), 50);
|
||||
}
|
||||
if (item.hasOwnProperty("x") || item.hasOwnProperty("y")) {
|
||||
item.x = parseFloat(item.x) || 0;
|
||||
item.x = Math.min(Math.max(item.x, 0), config.MAX_BOARD_SIZE);
|
||||
item.x = Math.round(10 * item.x) / 10;
|
||||
item.y = parseFloat(item.y) || 0;
|
||||
item.y = Math.min(Math.max(item.y, 0), config.MAX_BOARD_SIZE);
|
||||
item.y = Math.round(10 * item.y) / 10;
|
||||
}
|
||||
if (item.hasOwnProperty("opacity")) {
|
||||
item.opacity = Math.min(Math.max(item.opacity, 0.1), 1) || 1;
|
||||
if (item.opacity === 1) delete item.opacity;
|
||||
}
|
||||
if (item.hasOwnProperty("_children")) {
|
||||
if (!Array.isArray(item._children)) item._children = [];
|
||||
if (item._children.length > config.MAX_CHILDREN)
|
||||
item._children.length = config.MAX_CHILDREN;
|
||||
for (var i = 0; i < item._children.length; i++) {
|
||||
this.validate(item._children[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Load the data in the board from a file.
|
||||
* @param {string} name - name of the board
|
||||
*/
|
||||
static async load(name) {
|
||||
var boardData = new BoardData(name),
|
||||
data;
|
||||
try {
|
||||
data = await fs.promises.readFile(boardData.file);
|
||||
boardData.board = JSON.parse(data);
|
||||
for (id in boardData.board) boardData.validate(boardData.board[id]);
|
||||
log("disk load", { board: boardData.name });
|
||||
} catch (e) {
|
||||
log("empty board creation", {
|
||||
board: boardData.name,
|
||||
// If the file doesn't exist, this is not an error
|
||||
error: e.code !== "ENOENT" && e.toString(),
|
||||
});
|
||||
boardData.board = {};
|
||||
if (data) {
|
||||
// There was an error loading the board, but some data was still read
|
||||
var backup = backupFileName(boardData.file);
|
||||
log("Writing the corrupted file to " + backup);
|
||||
try {
|
||||
await fs.promises.writeFile(backup, data);
|
||||
} catch (err) {
|
||||
log("Error writing " + backup + ": " + err);
|
||||
}
|
||||
}
|
||||
}
|
||||
return boardData;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a board file name, return a name to use for temporary data saving.
|
||||
|
|
Loading…
Reference in a new issue