-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
253 lines (230 loc) · 7.94 KB
/
index.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
const express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var PORT = '8000';
server.listen(PORT, function() {
log('Listening on ' + PORT + '...');
});
app.use('/static', express.static('public'));
app.get('/', function(request, response) {
response.sendFile(__dirname + '/index.html');
});
const chatHistorySize = 250;
const usersList = {};
const chatHistory = [];
const systemName = 'Console';
const colors = ['black', 'silver', 'gray', 'white', 'maroon', 'red', 'purple', 'fuchsia', 'green',
'lime', 'olive', 'yellow', 'navy', 'blue', 'teal', 'aqua', 'orange', 'aliceblue', 'antiquewhite',
'aquamarine', 'azure', 'beige', 'bisque', 'blanchedalmond', 'blueviolet', 'brown', 'burlywood',
'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan',
'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki',
'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon',
'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise',
'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick',
'floralwhite', 'forestgreen', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'greenyellow',
'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush',
'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow',
'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue',
'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'limegreen', 'linen', 'magenta',
'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue',
'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose',
'moccasin', 'navajowhite', 'oldlace', 'olivedrab', 'orangered', 'orchid', 'palegoldenrod', 'palegreen',
'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue',
'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna',
'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'thistle',
'tomato', 'turquoise', 'violet', 'wheat', 'whitesmoke', 'yellowgreen'];
io.on('connection', function(socket) {
log('New user connected');
// initUser
socket.on('initUser', function (usernameCookie, colorCookie) {
var username = '';
var color = '';
if (usernameCookie && colorCookie) {
// returning user
if(usersList[usernameCookie]) {
// if name was taken
username = getUsername();
color = getColor();
logAndNotify(usernameCookie + "'s name was taken.\nNew name is: " + username,
socket);
} else {
username = usernameCookie;
color = colorCookie;
}
} else {
// new user
username = getUsername();
color = getColor();
logAndNotify('New user created: ' + username, socket);
}
// inform client
var user = {
username: username,
color: color,
};
socket.emit('initUser', user);
showHistory(socket);
log(username + ' connected');
// update user list
socket.username = username;
socket.color = color;
usersList[username] = username;
io.emit('usersList', usersList);
io.emit('onlineUsers', socket.conn.server.clientsCount);
});
// newMessage
socket.on('newMessage', function (msg) {
// Grab message from client
log(msg.username + ' sent: ' + msg.message);
var msgObj = {
time: getTime(),
username: msg.username,
color: msg.color,
message: msg.message,
};
// Emit message to all users
io.emit('clientMessage', msgObj);
saveMessage(msgObj);
});
// help request
socket.on('help', function() {
log(socket.username + ' asked for help');
var helpMsg = {
time: getTime(),
username: 'Helper!',
color: 'Indigo',
message: 'Type /nick newName to change your username. \
Type /nickcolor #hexcode or /nickcolor colorName to change your color.',
};
// Emit help to requesting user only
socket.emit('clientMessage', helpMsg);
});
// change username
socket.on('changeNick', function (msg) {
var newName = msg.message.slice(6).trim();
log(msg.username + ' asked to rename to: ' + newName);
if(newName == '') {
logAndNotify('Error: username can\'t be empty.', socket);
} else if(usersList[newName]) {
logAndNotify('Error: username taken.', socket);
} else if(newName.length > 16) {
logAndNotify('Error: username can\'t exceed 16 chars.', socket);
} else {
// update user list
delete usersList[socket.username];
socket.username = newName;
usersList[newName] = newName;
io.emit('usersList', usersList);
io.emit('onlineUsers', socket.conn.server.clientsCount);
// inform client
var user = {
username: socket.username,
color: socket.color,
};
socket.emit('initUser', user);
logAndNotify(msg.username + ' renamed to ' + socket.username, io);
}
});
// change color
socket.on('changeColor', function (msg) {
var newColor = msg.message.slice(10).trim();
log(msg.username + ' asked to recolor to: ' + newColor);
var validColor = isValidColor(newColor);
if(newColor == '') {
logAndNotify('Error: color can\'t be empty.', socket);
} else if(!validColor) {
logAndNotify('Error: invalid color.', socket);
} else if (validColor) {
if (!newColor.startsWith('#') && !colors.includes(newColor)) {
newColor = '#' + newColor;
}
socket.color = newColor;
// inform client
var user = {
username: socket.username,
color: socket.color,
};
socket.emit('initUser', user);
logAndNotify(msg.username + ' changed their color to: ' + socket.color, io);
}
});
// disconnect
socket.on('disconnect', function () {
if (socket.username !== 'undefined') {
logAndNotify(socket.username + ' disconnected', io);
}
delete usersList[socket.username];
io.emit('onlineUsers', socket.conn.server.clientsCount)
io.emit('usersList', usersList);
});
})
// return current time
function getTime() {
return new Date().toLocaleTimeString();
}
// return random username
function getUsername() {
var temp = 'user' + Math.floor((Math.random() * 1000) + 1);
while (usersList[temp]) {
temp = 'user' + Math.floor((Math.random() * 1000) + 1);
}
return temp;
}
// return true if color is valid
function isValidColor(newColor) {
var valid = false;
if (newColor.startsWith('#')) {
valid = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(newColor);
} else if (colors.includes(newColor)) {
valid = true;
} else {
newColor = '#' + newColor;
valid = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(newColor);
}
return valid;
}
// return random color
// Source: https://stackoverflow.com/questions/1484506/random-color-generator
function getColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
// log message
function saveMessage(msg) {
if(chatHistory.length >= chatHistorySize) {
chatHistory.shift();
}
chatHistory.push(msg);
}
// show chat history
function showHistory(socket) {
for(i in chatHistory) {
socket.emit('clientMessage', chatHistory[i]);
}
}
// Log msg and notify user with msg
function logAndNotify(msg, sock) {
sendSysMsg(msg, sock);
console.log(msg);
}
// Log msg
function log(msg) {
console.log(msg);
}
// send system message
// use socket to send to caller only
// use io to send to all users
function sendSysMsg(msg, sock) {
var msgObj = {
time: getTime(),
username: systemName,
message: msg,
};
sock.emit('sysMessage', msgObj);
log('sysMsg: ' + msg);
}