mpp-server-dev2/src/User.js

53 lines
2.0 KiB
JavaScript
Raw Normal View History

2019-06-06 19:22:43 +02:00
const ColorEncoder = require("./ColorEncoder.js");
const { promisify } = require('util');
let userdb;
2019-06-06 19:22:43 +02:00
class User {
constructor(cl) {
this.cl = cl;
this.server = this.cl.server;
this.userdb = userdb;
this.default_db = {};
2019-06-06 19:22:43 +02:00
}
async getUserData() {
if (!userdb || (userdb instanceof Map && [...userdb.entries()] == [])) {
await this.setUpDb();
2019-06-06 19:22:43 +02:00
}
let _id = createKeccakHash('keccak256').update((this.cl.server._id_Private_Key + this.cl.ip)).digest('hex').substr(0, 24);
let usertofind = userdb.get(_id);
if (!usertofind) {
if (typeof usertofind == 'object' && (usertofind.hasOwnProperty('name') && usertofind.name != this.server.defaultUsername)) return;
userdb.set(_id, {
2019-06-06 19:22:43 +02:00
"color": `#${ColorEncoder.intToRGB(ColorEncoder.hashCode(_id)).toLowerCase()}`,
"name": this.server.defaultUsername,
"_id": _id,
"ip": this.cl.ip
});
this.updatedb();
}
let user = userdb.get(_id);
2019-06-06 19:22:43 +02:00
return {
"color": user.color,
"name": user.name,
"_id": user._id,
}
}
async updatedb() {
const writeFile = promisify(fs.writeFile);
await writeFile('src/db/users.json', JSON.stringify(User.strMapToObj(userdb), null, 2));
2019-06-06 19:22:43 +02:00
}
async setUpDb() {
const writeFile = promisify(fs.writeFile);
const readdir = promisify(fs.readdir);
let files = await readdir("src/db/");
2019-06-06 19:22:43 +02:00
if (!files.includes("users.json")) {
await writeFile('src/db/users.json', JSON.stringify(this.default_db, null, 2))
userdb = new Map(Object.entries(require("./db/users.json")));
2019-06-06 19:22:43 +02:00
} else {
userdb = new Map(Object.entries(require("./db/users.json")));
2019-06-06 19:22:43 +02:00
}
}
2019-06-11 23:01:44 +02:00
static strMapToObj(strMap) {
return [...strMap.entries()].reduce((obj, [key, value]) => (obj[key] = value, obj), {});
2019-06-11 23:01:44 +02:00
}
2019-06-06 19:22:43 +02:00
}
module.exports = User;