forked from MatthewLavine/NodeJS-Chat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
executable file
·424 lines (378 loc) · 13.7 KB
/
app.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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
var config = require('./config.js');
var ip = config.ip;
var port = config.port;
var express = require('express');
var app = express();
var server = app.listen(port);
var moment = require('moment');
var ejs = require('ejs');
var url = require('url');
var bbcode = require('bbcode');
var io = require('socket.io').listen(server);
io.set('log level', 1);
var sys = require('sys');
var exec = require('child_process').exec;
app.set("view options", {layout: false});
app.use(express.json());
app.use(express.static(__dirname + '/public'));
process.on('SIGINT', function() {
console.log( "\nShutting down from manual SIGINT (Ctrl-C), NOW." );
io.sockets.emit('annouce', {message : '<span class="adminMessage">SHUTTING DOWN, NOW!</span>'});
process.exit();
});
process.once('SIGUSR2', function () {
gracefulShutdown(function () {
process.kill(process.pid, 'SIGUSR2');
});
});
function gracefulShutdown(kill){
console.log( "\nShutting down from nodemon SIGUSR2 (RESTART) in 10 seconds..." );
io.sockets.emit('annouce', {message : '<span class="adminMessage">RESTARTING IN 10 SECONDS!</span>'});
setTimeout(function(){kill()}, 10000);
}
app.post('/gitpull', function(req, res) {
var parsedUrl = url.parse(req.url, true);
if(parsedUrl.query['secret_key'] != config.secret_key) {
console.log("[warning] Unauthorized request " + req.url);
res.writeHead(401, "Not Authorized", {'Content-Type': 'text/html'});
res.end('401 - Not Authorized');
return;
}
res.end();
io.sockets.emit('annouce', {message : '<span class="adminMessage">SYSTEM UPDATE INITIATED...</span>'});
function puts(error, stdout, stderr) {sys.puts(stdout)}
exec("git reset --hard HEAD", puts);
exec("git pull", puts);
var arr = req.body.commits[0].modified;
if((arr.join(',').indexOf("app.min.js") > -1) || (arr.join(',').indexOf("app.min.css") > -1) || (arr.join(',').indexOf("index.ejs") > -1)){
io.sockets.emit('annouce', {message : '<span class="adminMessage">SYSTEM UPDATE COMPLETE, BROWSER RELOAD IS NECCESARY.</span>'});
} else {
io.sockets.emit('annouce', {message : '<span class="adminMessage">SYSTEM UPDATE COMPLETE, BROWSER RELOAD IS NOT NECCESARY.</span>'});
}
});
app.post('/gitcommit', function(req, res) {
// var parsedUrl = url.parse(req.url, true);
// if(parsedUrl.query['secret_key'] != config.secret_key) {
// console.log("[warning] Unauthorized request " + req.url);
// res.writeHead(401, "Not Authorized", {'Content-Type': 'text/html'});
// res.end('401 - Not Authorized');
// return;
// }
res.end();
io.sockets.emit('annouce', {message : '<span class="adminMessage">SYSTEM UPDATE INITIATED...</span>'});
function puts(error, stdout, stderr) {sys.puts(stdout)}
exec("git reset --hard HEAD", puts);
exec("git pull", puts);
io.sockets.emit('annouce', {message : '<span class="adminMessage">SYSTEM UPDATE COMPLETE, BROWSER RELOAD MAY BE NECCESARY.</span>'});
// var arr = req.body.commits[0].modified;
// if((arr.join(',').indexOf("app.min.js") > -1) || (arr.join(',').indexOf("app.min.css") > -1) || (arr.join(',').indexOf("index.ejs") > -1)){
// io.sockets.emit('annouce', {message : '<span class="adminMessage">SYSTEM UPDATE COMPLETE, BROWSER RELOAD IS NECCESARY.</span>'});
// } else {
// io.sockets.emit('annouce', {message : '<span class="adminMessage">SYSTEM UPDATE COMPLETE, BROWSER RELOAD IS NOT NECCESARY.</span>'});
// }
});
app.get('*', function(req, res) {
res.render('index.ejs', {
ip: ip
});
});
var users = [];
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function (chunk) {
chunk = chomp(chunk)
if(chunk[0] == "/") {
parseAdminCommand(chunk);
} else {
io.sockets.emit('annouce', {message : '<span class="adminMessage">' + chunk.toUpperCase() + '</span>'});
}
});
function chomp(raw_text) {
return raw_text.replace(/(\n|\r)+$/, '');
}
function findSocket(user) {
for(var i = users.length; i--;) {
if(users[i][0] == user) {
return users[i][1];
}
}
return 0;
}
function parseAdminCommand(data) {
var res = data.trim().split(" ");
if(res[0].toLowerCase() == "/kick" && res.length >= 2){
kick(res[1], res.slice(2,res.length).join(' '));
return;
}
if(res[0].toLowerCase() == "/restart" && res.length == 1){
process.kill(process.pid, 'SIGUSR2');
return;
}
if(res[0].toLowerCase() == "/shutdown" && res.length == 1){
console.log( "\nShutting down from manual SIGINT (/shutdown), NOW." );
io.sockets.emit('annouce', {message : '<span class="adminMessage">SHUTTING DOWN, NOW!</span>'});
process.exit();
return;
}
console.log('Unknown command \'' + data + '\'');
console.log('Available commands are: \n /kick user reason\n message\n /restart\n /shutdown\n');
}
function kick(data, reason) {
if(!findUser(data)) {
console.log('No such user \'' + data + '\'');
return;
}
var victim = io.sockets.socket(findSocket(data));
var msg = '<span class="adminMessage">YOU HAVE BEEN KICKED BY THE ADMIN. ';
if(reason !== undefined && reason != null && reason != ''){
msg += 'REASON: ' + reason;
}
msg += '</span>';
victim.emit('annouce', {message : msg});
removeItem(users, [data]);
victim.disconnect();
console.log('\'' + data + '\' has been kicked.');
}
var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
function escapeHtml(string) {
return String(string).replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
});
}
function removeItem(arr, item) {
for(var i = arr.length; i--;) {
if(arr[i][0].toString() === item[0].toString()) {
arr.splice(i, 1);
}
}
}
function findUser(user) {
for(var i = users.length; i--;) {
if(users[i][0] == user) {
return true;
}
}
return false;
}
io.sockets.on('connection', function (socket) {
var name = '';
var lastMessage = moment();
var rateLimitWarns = 0;
var banFrom = moment();
function broadcast(data) {
io.sockets.emit('annouce', {message : data});
}
function parseServerCommand(data) {
var res = data.message.trim().split(" ");
if(res[0].toLowerCase() == "/nick"){
updateName(res.slice(1,res.length).join(' '));
return;
}
if(res[0].toLowerCase() == "/pm"){
if(res.length >= 3){
if(res[1] == 'SERVER'){
var help = "<span class='serverMessage'>You cannot PM the server.</span>";
socket.emit('annouce', {message : help});
return;
}
if(findUser(res[1])){
pm(res[1], res.slice(2, res.length).join(' '));
return;
} else if (findUser(res.slice(1 ,3).join(' '))){
pm(res.slice(1 ,3).join(' '), res.slice(3, res.length).join(' '));
return;
} else {
var help = "<span class='serverMessage'>User not found for command '" + res.join(' ') + "'</span>";
socket.emit('annouce', {message : help});
}
} else {
var help = "<span class='serverMessage'>You must add a PM message.</span>";
socket.emit('annouce', {message : help});
}
}
if(res[0].toLowerCase() == "/disconnect"){
socket.disconnect();
}
if(res[0].toLowerCase() == "/help"){
sendHelp();
return;
}
unrecognized(res[0]);
sendHelp();
}
function pm(dest, data){
if(dest == name){
var help = "<span class='serverMessage'>You cannot PM yourself.</span>";
socket.emit('annouce', {message : help});
return;
}
data = '<span class="pm"><to ' + dest + '> ' + data + '</span';
io.sockets.socket(findSocket(dest)).emit('broadcast', {client : name, message : data});
socket.emit('pm', {client : name, message : data});
}
function updateName(data){
data = escapeHtml(data).trim();
if(typeof data != 'string') {
socket.emit('annouce', {message : "<span class='serverMessage'>That nick is not a string!</span>"});
return;
}
if(!isLetter(data)){
socket.emit('annouce', {message : "<span class='serverMessage'>No special characters or spaces in Nicks!</span>"});
return;
}
if(findUser(data)){
socket.emit('annouce', {message : "<span class='serverMessage'>The nick '" + data + "' is taken!</span>"});
return;
}
if(data.toLowerCase() == "admin" || data.toLowerCase() == "server"){
socket.emit('annouce', {message : "<span class='serverMessage'>That nick is reserved!</span>"});
return;
}
if(data.toLowerCase().length > 25){
socket.emit('annouce', {message : "<span class='serverMessage'>That nick is too long!</span>"});
return;
}
if(data.toLowerCase().length == 0){
socket.emit('annouce', {message : "<span class='serverMessage'>That nick is too short!</span>"});
return;
}
oldName = name;
name = escapeHtml(data);
removeItem(users, [oldName, socket.id]);
users.push([name, socket.id, true]);
io.sockets.emit('users', users);
socket.emit('name', {name : name});
broadcast('<span class="serverMessage">' + oldName + ' has changed name to ' + data + '.</span>');
}
function disconnect(data){
socket.disconnect();
}
function unrecognized(data){
var help = "<span class='serverMessage'>Unknown command '" + data + "'.</span>";
socket.emit('annouce', {message : help});
}
function sendHelp(){
var help = "<span class='serverMessage'>HardOrange IRC Help - Commands:<br>/nick nick<br>/pm nick message<br>/clear<br>/disconnect<br>/help</span>";
socket.emit('annouce', {message : help});
}
function multiArrayIndex(arr, item){
for(var i = 0; i < arr.length; i++) {
if(arr[i][0].toString() == item[0].toString()) {
return i;
}
}
return -1;
}
function isLetter(s)
{
return s.match("^[a-zA-Z\(\)]+$");
}
//Begin Handlers
sendHelp();
var didConfig = false;
socket.on('config', function (data){
if(didConfig){
return;
} else {
didConfig = true;
}
if(data === undefined || data === null || data.name === undefined || data.name === null){
console.log('Malformed Config Packet');
return;
}
do {
name = 'Guest' + Math.floor(1000 + Math.random() * 9000);
} while (findUser(name));
var error = false;
if(data.name != ''){
if(typeof data.name != 'string') {
socket.emit('annouce', {message : "<span class='serverMessage'>That nick is not a string!</span>"});
error = true;
}
if(!error && !isLetter(data.name)){
socket.emit('annouce', {message : "<span class='serverMessage'>No special characters or spaces in Nicks!</span>"});
error = true;
}
if(!error && data.name.toLowerCase() == "admin" || data.name.toLowerCase() == "server"){
socket.emit('annouce', {message : "<span class='serverMessage'>That nick is reserved!</span>"});
error = true;
}
if(!error && data.name.toLowerCase().length > 25){
socket.emit('annouce', {message : "<span class='serverMessage'>That nick is too long!</span>"});
error = true;
}
if(!error && data.name.toLowerCase().length == 0){
socket.emit('annouce', {message : "<span class='serverMessage'>That nick is too short!</span>"});
error = true;
}
if(!error && findUser(data.name)){
socket.emit('annouce', {message : "<span class='serverMessage'>The nick '" + data.name + "' is taken!</span>"});
error = true;
}
if(!error) {
name = escapeHtml(data.name);
}
}
broadcast('<span class="serverMessage">' + name + ' has entered chat.</span>');
users.push([name, socket.id, true]);
io.sockets.emit('users', users);
socket.emit('name', {name : name});
//All Other Handlers
socket.on('broadcast', function (data) {
if(data === undefined || data === null || data.message === undefined || data.message === null || typeof data.message != 'string'){
console.log('Malformed Broadcast Packet');
return;
}
if(data.message.length > 500) {
var help = "<span class='serverMessage'>Your message was too long (500 character limit).</span>";
socket.emit('annouce', {message : help});
return;
}
if(moment().diff(banFrom, 'seconds') <= 30 && rateLimitWarns == 3){
var help = "<span class='serverMessage'>You are sending too many messages, 30 second ban!</span>";
socket.emit('annouce', {message : help});
return;
}
if(moment().diff(lastMessage, 'seconds') < 0.5) {
var help = "<span class='serverMessage'>You are sending too many messages!</span>";
socket.emit('annouce', {message : help});
rateLimitWarns++;
if(rateLimitWarns == 3){
banFrom = moment();
}
return;
}
lastMessage = moment();
rateLimitWarns=0;
if(data.message[0] == "/") {
parseServerCommand(data);
} else {
bbcode.parse(escapeHtml(data.message), function(content){
io.sockets.emit('broadcast', {client : name, message : content});
});
}
});
socket.on('status', function (data) {
if(data === undefined || data === null || data.status === undefined || data.status === null){
console.log('Malformed Status Packet');
return;
}
var index = multiArrayIndex(users, [name, socket.id, !data.status]);
if(index == -1){console.log('missing user: ' + name);return;}
users[index][2] = data.status;
io.sockets.emit('users', users);
});
socket.on('disconnect', function (data) {
removeItem(users, [name, socket.id]);
io.sockets.emit('users', users);
broadcast('<span class="serverMessage">' + name + ' has exited chat.</span>');
});
});
});