-
Notifications
You must be signed in to change notification settings - Fork 229
/
server.js
363 lines (340 loc) · 12.6 KB
/
server.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
var express = require('express')
, app = express()
, server = require('http').createServer(app)
, io = require("socket.io").listen(server)
, npid = require("npid")
, uuid = require('node-uuid')
, Room = require('./room.js')
, _ = require('underscore')._;
app.configure(function() {
app.set('port', process.env.OPENSHIFT_NODEJS_PORT || 3000);
app.set('ipaddr', process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1");
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(__dirname + '/public'));
app.use('/components', express.static(__dirname + '/components'));
app.use('/js', express.static(__dirname + '/js'));
app.use('/icons', express.static(__dirname + '/icons'));
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
/* Store process-id (as priviledged user) */
try {
npid.create('/var/run/advanced-chat.pid', true);
} catch (err) {
console.log(err);
//process.exit(1);
}
});
app.get('/', function(req, res) {
res.render('index.html');
});
server.listen(app.get('port'), app.get('ipaddr'), function(){
console.log('Express server listening on IP: ' + app.get('ipaddr') + ' and port ' + app.get('port'));
});
io.set("log level", 1);
var people = {};
var rooms = {};
var sockets = [];
var chatHistory = {};
function purge(s, action) {
/*
The action will determine how we deal with the room/user removal.
These are the following scenarios:
if the user is the owner and (s)he:
1) disconnects (i.e. leaves the whole server)
- advise users
- delete user from people object
- delete room from rooms object
- delete chat history
- remove all users from room that is owned by disconnecting user
2) removes the room
- same as above except except not removing user from the people object
3) leaves the room
- same as above
if the user is not an owner and (s)he's in a room:
1) disconnects
- delete user from people object
- remove user from room.people object
2) removes the room
- produce error message (only owners can remove rooms)
3) leaves the room
- same as point 1 except not removing user from the people object
if the user is not an owner and not in a room:
1) disconnects
- same as above except not removing user from room.people object
2) removes the room
- produce error message (only owners can remove rooms)
3) leaves the room
- n/a
*/
if (people[s.id].inroom) { //user is in a room
var room = rooms[people[s.id].inroom]; //check which room user is in.
if (s.id === room.owner) { //user in room and owns room
if (action === "disconnect") {
io.sockets.in(s.room).emit("update", "The owner (" +people[s.id].name + ") has left the server. The room is removed and you have been disconnected from it as well.");
var socketids = [];
for (var i=0; i<sockets.length; i++) {
socketids.push(sockets[i].id);
if(_.contains((socketids)), room.people) {
sockets[i].leave(room.name);
}
}
if(_.contains((room.people)), s.id) {
for (var i=0; i<room.people.length; i++) {
people[room.people[i]].inroom = null;
}
}
room.people = _.without(room.people, s.id); //remove people from the room:people{}collection
delete rooms[people[s.id].owns]; //delete the room
delete people[s.id]; //delete user from people collection
delete chatHistory[room.name]; //delete the chat history
sizePeople = _.size(people);
sizeRooms = _.size(rooms);
io.sockets.emit("update-people", {people: people, count: sizePeople});
io.sockets.emit("roomList", {rooms: rooms, count: sizeRooms});
var o = _.findWhere(sockets, {'id': s.id});
sockets = _.without(sockets, o);
} else if (action === "removeRoom") { //room owner removes room
io.sockets.in(s.room).emit("update", "The owner (" +people[s.id].name + ") has removed the room. The room is removed and you have been disconnected from it as well.");
var socketids = [];
for (var i=0; i<sockets.length; i++) {
socketids.push(sockets[i].id);
if(_.contains((socketids)), room.people) {
sockets[i].leave(room.name);
}
}
if(_.contains((room.people)), s.id) {
for (var i=0; i<room.people.length; i++) {
people[room.people[i]].inroom = null;
}
}
delete rooms[people[s.id].owns];
people[s.id].owns = null;
room.people = _.without(room.people, s.id); //remove people from the room:people{}collection
delete chatHistory[room.name]; //delete the chat history
sizeRooms = _.size(rooms);
io.sockets.emit("roomList", {rooms: rooms, count: sizeRooms});
} else if (action === "leaveRoom") { //room owner leaves room
io.sockets.in(s.room).emit("update", "The owner (" +people[s.id].name + ") has left the room. The room is removed and you have been disconnected from it as well.");
var socketids = [];
for (var i=0; i<sockets.length; i++) {
socketids.push(sockets[i].id);
if(_.contains((socketids)), room.people) {
sockets[i].leave(room.name);
}
}
if(_.contains((room.people)), s.id) {
for (var i=0; i<room.people.length; i++) {
people[room.people[i]].inroom = null;
}
}
delete rooms[people[s.id].owns];
people[s.id].owns = null;
room.people = _.without(room.people, s.id); //remove people from the room:people{}collection
delete chatHistory[room.name]; //delete the chat history
sizeRooms = _.size(rooms);
io.sockets.emit("roomList", {rooms: rooms, count: sizeRooms});
}
} else {//user in room but does not own room
if (action === "disconnect") {
io.sockets.emit("update", people[s.id].name + " has disconnected from the server.");
if (_.contains((room.people), s.id)) {
var personIndex = room.people.indexOf(s.id);
room.people.splice(personIndex, 1);
s.leave(room.name);
}
delete people[s.id];
sizePeople = _.size(people);
io.sockets.emit("update-people", {people: people, count: sizePeople});
var o = _.findWhere(sockets, {'id': s.id});
sockets = _.without(sockets, o);
} else if (action === "removeRoom") {
s.emit("update", "Only the owner can remove a room.");
} else if (action === "leaveRoom") {
if (_.contains((room.people), s.id)) {
var personIndex = room.people.indexOf(s.id);
room.people.splice(personIndex, 1);
people[s.id].inroom = null;
io.sockets.emit("update", people[s.id].name + " has left the room.");
s.leave(room.name);
}
}
}
} else {
//The user isn't in a room, but maybe he just disconnected, handle the scenario:
if (action === "disconnect") {
io.sockets.emit("update", people[s.id].name + " has disconnected from the server.");
delete people[s.id];
sizePeople = _.size(people);
io.sockets.emit("update-people", {people: people, count: sizePeople});
var o = _.findWhere(sockets, {'id': s.id});
sockets = _.without(sockets, o);
}
}
}
io.sockets.on("connection", function (socket) {
socket.on("joinserver", function(name, device) {
var exists = false;
var ownerRoomID = inRoomID = null;
_.find(people, function(key,value) {
if (key.name.toLowerCase() === name.toLowerCase())
return exists = true;
});
if (exists) {//provide unique username:
var randomNumber=Math.floor(Math.random()*1001)
do {
proposedName = name+randomNumber;
_.find(people, function(key,value) {
if (key.name.toLowerCase() === proposedName.toLowerCase())
return exists = true;
});
} while (!exists);
socket.emit("exists", {msg: "The username already exists, please pick another one.", proposedName: proposedName});
} else {
people[socket.id] = {"name" : name, "owns" : ownerRoomID, "inroom": inRoomID, "device": device};
socket.emit("update", "You have connected to the server.");
io.sockets.emit("update", people[socket.id].name + " is online.")
sizePeople = _.size(people);
sizeRooms = _.size(rooms);
io.sockets.emit("update-people", {people: people, count: sizePeople});
socket.emit("roomList", {rooms: rooms, count: sizeRooms});
socket.emit("joined"); //extra emit for GeoLocation
sockets.push(socket);
}
});
socket.on("getOnlinePeople", function(fn) {
fn({people: people});
});
socket.on("countryUpdate", function(data) { //we know which country the user is from
country = data.country.toLowerCase();
people[socket.id].country = country;
io.sockets.emit("update-people", {people: people, count: sizePeople});
});
socket.on("typing", function(data) {
if (typeof people[socket.id] !== "undefined")
io.sockets.in(socket.room).emit("isTyping", {isTyping: data, person: people[socket.id].name});
});
socket.on("send", function(msTime, msg) {
//process.exit(1);
var re = /^[w]:.*:/;
var whisper = re.test(msg);
var whisperStr = msg.split(":");
var found = false;
if (whisper) {
var whisperTo = whisperStr[1];
var keys = Object.keys(people);
if (keys.length != 0) {
for (var i = 0; i<keys.length; i++) {
if (people[keys[i]].name === whisperTo) {
var whisperId = keys[i];
found = true;
if (socket.id === whisperId) { //can't whisper to ourselves
socket.emit("update", "You can't whisper to yourself.");
}
break;
}
}
}
if (found && socket.id !== whisperId) {
var whisperTo = whisperStr[1];
var whisperMsg = whisperStr[2];
socket.emit("whisper", {name: "You"}, whisperMsg);
io.sockets.socket(whisperId).emit("whisper", msTime, people[socket.id], whisperMsg);
} else {
socket.emit("update", "Can't find " + whisperTo);
}
} else {
if (io.sockets.manager.roomClients[socket.id]['/'+socket.room] !== undefined ) {
io.sockets.in(socket.room).emit("chat", msTime, people[socket.id], msg);
socket.emit("isTyping", false);
if (_.size(chatHistory[socket.room]) > 10) {
chatHistory[socket.room].splice(0,1);
} else {
chatHistory[socket.room].push(people[socket.id].name + ": " + msg);
}
} else {
socket.emit("update", "Please connect to a room.");
}
}
});
socket.on("disconnect", function() {
if (typeof people[socket.id] !== "undefined") { //this handles the refresh of the name screen
purge(socket, "disconnect");
}
});
//Room functions
socket.on("createRoom", function(name) {
if (people[socket.id].inroom) {
socket.emit("update", "You are in a room. Please leave it first to create your own.");
} else if (!people[socket.id].owns) {
var id = uuid.v4();
var room = new Room(name, id, socket.id);
rooms[id] = room;
sizeRooms = _.size(rooms);
io.sockets.emit("roomList", {rooms: rooms, count: sizeRooms});
//add room to socket, and auto join the creator of the room
socket.room = name;
socket.join(socket.room);
people[socket.id].owns = id;
people[socket.id].inroom = id;
room.addPerson(socket.id);
socket.emit("update", "Welcome to " + room.name + ".");
socket.emit("sendRoomID", {id: id});
chatHistory[socket.room] = [];
} else {
socket.emit("update", "You have already created a room.");
}
});
socket.on("check", function(name, fn) {
var match = false;
_.find(rooms, function(key,value) {
if (key.name === name)
return match = true;
});
fn({result: match});
});
socket.on("removeRoom", function(id) {
var room = rooms[id];
if (socket.id === room.owner) {
purge(socket, "removeRoom");
} else {
socket.emit("update", "Only the owner can remove a room.");
}
});
socket.on("joinRoom", function(id) {
if (typeof people[socket.id] !== "undefined") {
var room = rooms[id];
if (socket.id === room.owner) {
socket.emit("update", "You are the owner of this room and you have already been joined.");
} else {
if (_.contains((room.people), socket.id)) {
socket.emit("update", "You have already joined this room.");
} else {
if (people[socket.id].inroom !== null) {
socket.emit("update", "You are already in a room ("+rooms[people[socket.id].inroom].name+"), please leave it first to join another room.");
} else {
room.addPerson(socket.id);
people[socket.id].inroom = id;
socket.room = room.name;
socket.join(socket.room);
user = people[socket.id];
io.sockets.in(socket.room).emit("update", user.name + " has connected to " + room.name + " room.");
socket.emit("update", "Welcome to " + room.name + ".");
socket.emit("sendRoomID", {id: id});
var keys = _.keys(chatHistory);
if (_.contains(keys, socket.room)) {
socket.emit("history", chatHistory[socket.room]);
}
}
}
}
} else {
socket.emit("update", "Please enter a valid name first.");
}
});
socket.on("leaveRoom", function(id) {
var room = rooms[id];
if (room)
purge(socket, "leaveRoom");
});
});