-
Notifications
You must be signed in to change notification settings - Fork 20
/
main.js
308 lines (267 loc) · 8.53 KB
/
main.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
"use strict";
const path = require("path");
const sys = require("sys");
Array.prototype.sum = function() {
return this.reduce(function(pv, cv) {
return pv + cv;
}, 0);
}
Array.prototype.includes = function(item) {
return this.indexOf(item) > -1;
}
function runNpm(command) {
console.log("Running `npm " + command + "`...");
var child_process = require("child_process");
var npm = child_process.spawn("npm", [command]);
npm.stdout.on("data", function(data) {
process.stdout.write(data);
});
npm.stderr.on("data", function(data) {
process.stderr.write(data);
});
npm.on("close", function(code) {
if (!code) {
child_process.fork("main.js").disconnect();
}
});
}
// Check if everything that is needed is available
try {
require("sugar");
require("colors");
}
catch (e) {
console.log("Dependencies are not installed!");
return runNpm("install");
}
if (!Object.select) {
console.log("Node needs to be updated!");
return runNpm("update");
}
global.fs = require("fs");
global.toId = function(text, id) {
if (!text || typeof text !== "string") return "";
if (id) return text.toLowerCase().replace(/[^a-z0-9\-]/g, "");
return text.toLowerCase().replace(/[^a-z0-9]/g, "");
};
global.removeCommand = function(text) {
return text.replace(/^\//i, "//").replace(/^\!/i, " !").replace(/^[\>]{2,}/i, ">");
};
global.getEST = function(date) {
function isDst(tarDate) {
var deezNuts = new Date(tarDate);
var deezMonth = deezNuts.getMonth() + 1;
var deezDay = deezNuts.getDate() + 1;
var deezDayofWeek = deezNuts.getDay();
if (deezMonth > 11 || deezMonth < 3) {
return false;
}
if (deezMonth === 3) {
if (deezDay - deezDayofWeek > 7) {
return true;
}
return false;
}
if (deezMonth === 11) {
if (deezDay - deezDayofWeek > 0) {
return true
}
return false;
}
return true;
}
let d = (date ? date : Date.now()) + (new Date().getTimezoneOffset() * 60 * 1000) - (1000 * 60 * 60 * 5);
if (isDst(d)) d += 3600000;
return new Date(d).toLocaleString();
};
if (!fs.existsSync("./config/config.js")) {
console.log("config.js not found! - Creating with default settings...");
fs.writeFileSync("./config/config.js", fs.readFileSync('./config/config-example.js'));
}
global.Config = require("./config/config.js");
if (!Config.info.server || !Config.info.serverid || !Config.info.port) {
log("error", "You need to fill out the config file!");
}
if (Config.defaultCharacter.length === 0) {
Config.defaultCharacter.push("+");
}
global.log = function(item, text) {
if (!Config.logging || (Config.logging !== true && (typeof Config.logging && !Config.logging.includes(item)))) return false;
let d = getEST();
let fontColours = {
monitor: "red",
ok: "green",
error: "red",
">>": "yellow",
"<<": "yellow",
"join": "magenta",
"left": "magenta",
};
console.log("[" + d + "] " + item.toUpperCase()[fontColours[item] || "blue"] + " ".slice(item.length) + text);
}
//get the database
global.Db = require("origindb")("config/database-" + Config.info.serverid);
//check for bot auth;
if (!Object.keys(Db("ranks").object()).length) {
if (process.argv[2]) {
Db("ranks").set(toId(process.argv.slice(2).join("")), "~");
log("monitor", "Promoted " + process.argv.slice(2).join("").yellow + " to BotAdmin.")
}
else {
console.log("Please include the name of the bot admin. `node main.js [username]`");
process.exit(-1);
}
}
//globals
global.Parse = require("./parser.js").parse;
global.Tools = require("./tools.js").Tools;
global.Plugins = require("./plugins-parser").Plugins;
global.Monitor = require("./monitor.js").Monitor;
global.commandParser = require("./command-parser.js").commandParser;
global.Commands = require("./commands.js").commands;
global.Users = require("./users.js");
global.Rooms = require("./rooms.js");
function loadChatPlugins() {
let loaded = [];
let failed = [];
fs.readdirSync("./chat-plugins/").forEach(function(f) {
try {
Object.merge(Commands, require("./chat-plugins/" + f).commands);
loaded.push(f);
}
catch (e) {
console.log(e.stack);
failed.push(f)
}
})
if (loaded.length) {
log("info", "Loaded command files: " + loaded.join(", "));
}
if (failed.length) {
log("error", "Failed to load: " + failed.join(", "));
}
}
loadChatPlugins();
//globals
if (Config.watchConfig) {
fs.watchFile(path.resolve(__dirname, "config/config.js"), function(curr, prev) {
if (curr.mtime <= prev.mtime) return;
try {
delete require.cache[require.resolve("./config/config.js")];
global.Config = require('./config/config.js');
log("ok", 'Reloaded config/config.js');
}
catch (e) {}
});
}
log("ok", "starting server");
let WebSocketClient = require("websocket").client;
let connection = null;
let sendQueue = [];
let dequeuing = false;
let lastSent = 0;
function dequeue() {
if (sendQueue.length > 0) {
dequeuing = false;
let tempText = sendQueue.shift();
send(tempText[0], tempText[1], false, true);
}
}
global.send = function(text, user, priority, bypass) {
if (!connection.connected || !text) return false;
if (!user) {
user = toId(Config.bot.name);
}
if (Date.now() - lastSent < 650 && !bypass) {
if (!priority) {
sendQueue.push([text, user]);
}
else {
sendQueue = [
[text, user]
].concat(sendQueue);
}
if (!dequeuing) {
setTimeout(function() {
dequeue();
}, 650 - (Date.now() - lastSent));
dequeuing = true;
}
return false;
}
log(">>", text);
if (!Array.isArray(text)) text = [text.toString()];
text = JSON.stringify(text);
connection.send(text);
lastSent = Date.now();
if (sendQueue.length > 0) {
setTimeout(function() {
dequeue();
}, 650);
dequeuing = true;
}
};
global.clearQueue = function(user) {
if (!user) return false;
user = toId(user);
let newQueue = [];
for (let i = 0; i < sendQueue.length; i++) {
if (sendQueue[i][1] === user) {
continue;
}
newQueue.push(sendQueue[i])
}
sendQueue = newQueue;
}
let connect = function(retry) {
if (retry) {
log("info", "retrying...");
}
let ws = new WebSocketClient();
ws.on("connectFailed", function(err) {
log("error", "Could not connect to server " + Config.info.server + ": " + sys.inspect(err));
log("info", "retrying in 15 seconds");
setTimeout(function() {
connect(true);
}, 15000);
});
ws.on("connect", function(con) {
connection = con;
log("ok", "connected to server " + Config.info.server);
Parse.connectionDetails = {
firstConnect: true,
globallyBanned: false,
};
Rooms.rooms.forEach(function(value, key) {
log("info", "Deleting Room object for " + key);
Rooms.delete(key, true);
})
con.on("error", function(err) {
log("error", "connection error: " + sys.inspect(err));
});
con.on("close", function() {
// Is this always error or can this be intended...?
log("error", "connection closed: " + sys.inspect(arguments));
log("info", "retrying in one 15 seconds");
setTimeout(function() {
connect(true);
}, 15000);
});
con.on("message", function(message) {
if (message.type === "utf8") {
Parse.parseData(message.utf8Data);
}
});
});
// The connection itself
let id = ~~(Math.random() * 900) + 100;
let chars = "abcdefghijklmnopqrstuvwxyz0123456789_";
let str = "";
for (let i = 0, l = chars.length; i < 8; i++) {
str += chars.charAt(~~(Math.random() * l));
}
let conStr = "ws://" + Config.info.server + ":" + Config.info.port + "/showdown/" + id + "/" + str + "/websocket";
log("info", "connecting to " + conStr + " - secondary protocols: " + sys.inspect(Config.secprotocols));
ws.connect(conStr, Config.secprotocols);
};
connect();