-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathapp.js
263 lines (219 loc) · 7.43 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
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var bodyParser = require('body-parser');
var fs = require('fs');
// var schedule = require('node-schedule');
var antiSpam = require('socket-anti-spam');
var watchr = require('watchr');
var touch = require("touch")
var routes = require('./routes');
// var topicHandler = require(path.resolve(__dirname, 'lib', 'topic_handler.js'));
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
// topicsLocation = path.resolve(__dirname, 'lib', 'topics.json');
// manualTopicsLocation = path.resolve(__dirname, 'lib', 'manual-topics.json');
spamStringsLocation = path.resolve(__dirname, 'lib', 'spam-strings');
// currTopic = {
// "topic": "Loading...",
// "url": null
// };
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', routes.index);
var antiSpam = new antiSpam({
spamCheckInterval: 3000,
spamMinusPointsPerInterval: 3,
spamMaxPointsBeforeKick: 9,
spamEnableTempBan: true,
spamKicksBeforeTempBan: 3,
spamTempBanInMinutes: 120,
removeKickCountAfter: 1,
});
// Spam strings file management
var spamStrings = [];
// touch.sync(spamStringsLocation);
fs.readFile(spamStringsLocation, function(err, data) {
if (err) throw err;
spamStrings = data.toString().split("\n");
});
watchr.watch({
path: spamStringsLocation,
listener: function() {
fs.readFile(spamStringsLocation, function(err, data) {
if (err) throw err;
spamStrings = data.toString().split("\n");
});
}
});
var recentMessageTimes = {}; // Recent message timestamps by socket ID
var lastMessages = {}; // Last message by user
var greyListStatuses = {}; // Timestamps of too much spamming by socket ID
var connectionsByIP = {}; // Number of connections by IP
var usertags = {}; // Nicknames by socket.id
numOfUsers = 0;
var messageColors = ["#FFFFFF", "#044B7F"];
io.on('connection', function(socket) {
var userIp = socket.client.request.headers['x-forwarded-for'];
for (var id in usertags) {
if (socket.handshake.query.tag.length > 0 && usertags[id] ===
socket.handshake.query.tag) {
socket.disconnect();
return;
}
}
var tag = socket.handshake.query.tag.trim().replace(/\s/g, '');
tag = tag.substr(0, 10);
// Creates new number of connections for new users
if (connectionsByIP[userIp]) {
connectionsByIP[userIp]++;
// If user connects 4th time with same IP, disallow
if (connectionsByIP[userIp] > 3) {
connectionsByIP[userIp]--;
socket.disconnect();
return;
}
}
// Or simply increments number of connections
else
connectionsByIP[userIp] = 1;
usertags[socket.id] = tag;
antiSpam.onConnect(socket);
recentMessageTimes[socket.id] = [];
greyListStatuses[socket.id] = [];
numOfUsers++;
io.emit('user count', numOfUsers);
console.log("User connected, total: " + numOfUsers);
socket.on("new message", function(message) {
if (typeof(message) != 'string') {
socket.disconnect();
return;
}
var spamCheckMessage = message.toLowerCase().trim();
if (spamStrings.indexOf(spamCheckMessage) > -1) {
socket.disconnect();
return;
}
for (i = 0; i < spamStrings.length; i++) {
if (spamStrings[i].length && spamCheckMessage.indexOf(
spamStrings[i]) > -1) {
socket.disconnect();
return;
}
}
// Soft anti-spam measures
var recent = recentMessageTimes[socket.id];
if (recent.length == 5 && recent[0] > Date.now() - 5000) {
var greyListStatus = greyListStatuses[socket.id];
if (greyListStatus.length == 5 && greyListStatus[0] >
Date.now() - 5000) {
console.log("Stop spamming");
delete greyListStatuses[socket.id];
socket.disconnect();
} else {
greyListStatus.push(new Date());
if (greyListStatus.length > 5)
greyListStatus.shift();
}
console.log(greyListStatuses)
return;
}
if (lastMessages[socket.id] == message)
return;
else
lastMessages[socket.id] = message;
// Message validation, randomized styling and broadcasts
if (message.length > 0 && message.length < 100) {
var top = getRandomInt(10, 85);
var left = getRandomInt(2, 90);
var fontSize = (message.length < 25) ?
getRandomFloat(1, 2) : getRandomFloat(0.8, 1.3);
var randomColorInd = getRandomInt(0, 1);
var color = [messageColors[randomColorInd],
messageColors[(randomColorInd) ? 0 : 1]
];
var thisUsertag = usertags[socket.id];
io.emit('new message', {
"msg": message,
"cssTop": top,
"cssLeft": left,
"cssFontSize": fontSize,
"cssColor": color,
"usertag": thisUsertag
});
// console.log("New message: " + message);
}
recent.push(new Date());
if (recent.length > 5) {
recent.shift();
}
});
// On user disconnect
socket.on('disconnect', function() {
connectionsByIP[userIp]--;
numOfUsers--;
io.emit('user count', numOfUsers);
console.log("User disconnected, total: " + numOfUsers);
delete recentMessageTimes[socket.id];
delete greyListStatuses[socket.id];
delete lastMessages[socket.id];
delete usertags[socket.id];
});
});
// topicHandler.firstTimeSetup();
// topicHandler.topicsScheduler(function() {
// broadcastTopic(topicHandler.getNextTopic());
// });
// var rule = new schedule.RecurrenceRule();
// rule.minute = [0, 15, 30, 45];
// var j = schedule.scheduleJob(rule, function() {
// broadcastTopic(topicHandler.getNextTopic());
// });
// Some helper functions
// function broadcastTopic(topicObj) {
// currTopic = topicObj;
// io.emit('new topic', currTopic);
// console.log("New topic: " + currTopic.title);
// }
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function getRandomFloat(min, max) {
return (Math.random() * (max - min) + min).toFixed(1);
}
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = server;