2019-06-06 19:22:43 +02:00
|
|
|
const ColorEncoder = require("./ColorEncoder.js");
|
2019-06-14 18:30:28 +02:00
|
|
|
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;
|
2019-06-14 18:30:28 +02:00
|
|
|
this.userdb = userdb;
|
|
|
|
this.default_db = {};
|
2019-06-06 19:22:43 +02:00
|
|
|
}
|
|
|
|
async getUserData() {
|
2019-06-14 18:30:28 +02:00
|
|
|
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);
|
2019-06-14 18:30:28 +02:00
|
|
|
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();
|
|
|
|
}
|
2019-06-14 18:30:28 +02:00
|
|
|
let user = userdb.get(_id);
|
2019-06-06 19:22:43 +02:00
|
|
|
return {
|
|
|
|
"color": user.color,
|
|
|
|
"name": user.name,
|
|
|
|
"_id": user._id,
|
|
|
|
}
|
|
|
|
}
|
2019-06-14 18:30:28 +02:00
|
|
|
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
|
|
|
}
|
2019-06-14 18:30:28 +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")) {
|
2019-06-14 18:30:28 +02:00
|
|
|
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 {
|
2019-06-14 18:30:28 +02:00
|
|
|
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) {
|
2019-06-14 18:30:28 +02:00
|
|
|
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;
|