forked from sirDonovan/Cassius
-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage.js
105 lines (93 loc) · 2.62 KB
/
storage.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/**
* Storage
* Cassius - https://github.com/sirDonovan/Cassius
*
* This file handles the storage of room databases
*
* @license MIT license
*/
'use strict';
const fs = require('fs');
const BACKUP_INTERVAL = 60 * 60 * 1000;
class Storage {
constructor() {
this.databases = {};
this.globalDatabase = {};
this.backupInterval = setInterval(() => this.exportDatabases(), BACKUP_INTERVAL);
}
/**
* @param {string} roomid
* @returns {AnyObject}
*/
getDatabase(roomid) {
if (!(roomid in this.databases)) this.databases[roomid] = {};
// sync database properties
if (roomid === 'global' && !this.databases[roomid].mail) this.databases[roomid].mail = {};
return this.databases[roomid];
}
/**
* @param {string} roomid
*/
importDatabase(roomid) {
let file = '{}';
try {
file = fs.readFileSync('./databases/' + roomid + '.json').toString();
} catch (e) {}
this.databases[roomid] = JSON.parse(file);
}
/**
* @param {string} roomid
*/
exportDatabase(roomid) {
if (!(roomid in this.databases)) return;
fs.writeFileSync('./databases/' + roomid + '.json', JSON.stringify(this.databases[roomid]));
}
importDatabases() {
let databases = fs.readdirSync('./databases');
for (let i = 0, len = databases.length; i < len; i++) {
let file = databases[i];
if (!file.endsWith('.json')) continue;
this.importDatabase(file.substr(0, file.indexOf('.json')));
}
}
exportDatabases() {
for (let roomid in this.databases) {
this.exportDatabase(roomid);
}
}
/**
* @param {number} points
* @param {User} user
* @param {string} roomid
*/
addPoints(points, user, roomid) {
if (isNaN(points)) return;
if (!(roomid in this.databases)) this.databases[roomid] = {};
let database = this.databases[roomid];
if (!('leaderboard' in database)) database.leaderboard = {};
if (!(user.id in database.leaderboard)) database.leaderboard[user.id] = {points: 0};
database.leaderboard[user.id].points += points;
let name = Tools.toAlphaNumeric(user.name);
if (database.leaderboard[user.id].name !== name) database.leaderboard[user.id].name = name;
}
/**
* @param {number} points
* @param {User} user
* @param {string} roomid
*/
removePoints(points, user, roomid) {
this.addPoints(-points, user, roomid);
}
/**
* @param {User} user
* @param {string} roomid
*/
getPoints(user, roomid) {
if (!(roomid in this.databases)) this.databases[roomid] = {};
let database = this.databases[roomid];
if (!('leaderboard' in database)) database.leaderboard = {};
if (!(user.id in database.leaderboard)) return 0;
return database.leaderboard[user.id].points;
}
}
module.exports = new Storage();