From d32526d244c78ae1b4f3ac3826fd170375181f31 Mon Sep 17 00:00:00 2001 From: BopItFreak Date: Fri, 14 Jun 2019 12:30:28 -0400 Subject: [PATCH] Fix user database, add nice async stuff --- src/User.js | 50 ++++++++++++++++++++++---------------------------- 1 file changed, 22 insertions(+), 28 deletions(-) diff --git a/src/User.js b/src/User.js index 8aebc0a..bd10b83 100644 --- a/src/User.js +++ b/src/User.js @@ -1,59 +1,53 @@ const ColorEncoder = require("./ColorEncoder.js"); +const { promisify } = require('util'); +let userdb; class User { constructor(cl) { this.cl = cl; - this.userdb; this.server = this.cl.server; - this.default_db = {} + this.userdb = userdb; + this.default_db = {}; } async getUserData() { - if (!this.userdb) { - this.setUpDb(); + if (!userdb || (userdb instanceof Map && [...userdb.entries()] == [])) { + await this.setUpDb(); } let _id = createKeccakHash('keccak256').update((this.cl.server._id_Private_Key + this.cl.ip)).digest('hex').substr(0, 24); - if (!this.userdb.get(_id)) { - this.userdb.set(_id, { + let usertofind = userdb.get(_id); + if (!usertofind) { + if (typeof usertofind == 'object' && (usertofind.hasOwnProperty('name') && usertofind.name != this.server.defaultUsername)) return; + userdb.set(_id, { "color": `#${ColorEncoder.intToRGB(ColorEncoder.hashCode(_id)).toLowerCase()}`, "name": this.server.defaultUsername, "_id": _id, "ip": this.cl.ip }); - console.log("Set database", _id) this.updatedb(); } - let user = this.userdb.get(_id); + let user = userdb.get(_id); return { "color": user.color, "name": user.name, "_id": user._id, } } - updatedb() { - fs.writeFileSync('src/db/users.json', JSON.stringify(User.strMapToObj(this.userdb), null, 2), (err) => { - if (err) { - throw err; - } - }); + async updatedb() { + const writeFile = promisify(fs.writeFile); + await writeFile('src/db/users.json', JSON.stringify(User.strMapToObj(userdb), null, 2)); } - setUpDb() { - let files = fs.readdirSync("src/db/"); + async setUpDb() { + const writeFile = promisify(fs.writeFile); + const readdir = promisify(fs.readdir); + let files = await readdir("src/db/"); if (!files.includes("users.json")) { - fs.writeFileSync('src/db/users.json', JSON.stringify(this.default_db, null, 2), (err) => { - if (err) { - throw err; - } - }); - this.userdb = new Map(Object.entries(require("./db/users.json"))); + await writeFile('src/db/users.json', JSON.stringify(this.default_db, null, 2)) + userdb = new Map(Object.entries(require("./db/users.json"))); } else { - this.userdb = new Map(Object.entries(require("./db/users.json"))); + userdb = new Map(Object.entries(require("./db/users.json"))); } } static strMapToObj(strMap) { - let obj = Object.create(null); - for (let [k, v] of strMap) { - obj[k] = v; - } - return obj; + return [...strMap.entries()].reduce((obj, [key, value]) => (obj[key] = value, obj), {}); } } module.exports = User; \ No newline at end of file