-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
86 lines (75 loc) · 2.69 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
let config = require('config');
let app = require('express')();
let http = require('http').Server(app);
let io = require('socket.io')(http);
io.on('connection', socket => {
io.emit('usersL', Object.keys(io.sockets.clients().connected));
socket.on('message', msg => {
let asList = msg.msg.split(' ');
let targetSockets = [socket];
let joinSocketsToRoom = (room, sockets) => {
sockets.sort();
sockets.forEach(s => {
if (!Object.keys(s.rooms).includes(room)) s.join(room);
});
};
let sendMsgToRoom = (room, msg) => {
msg.private = true;
io.to(room).emit('message', msg);
};
switch (asList[0]) {
// SEND A PRIVATE MESSAGE
case '/m':
targetSockets.push(io.sockets.clients().connected[asList[1]]);
joinSocketsToRoom(targetSockets.join(''), targetSockets);
msg.msg = asList.slice(2).join(' ');
sendMsgToRoom(targetSockets.join(''), msg);
break;
// CREATE A PRIVATE ROOM W/ USERS
case '/r':
asList.slice(2).forEach(e => {
targetSockets.push(io.sockets.clients().connected[e]);
});
joinSocketsToRoom(asList[1], targetSockets);
break;
// SEND A MESSAGE TO A PRIVATE ROOM
case '/g':
msg.msg = asList.slice(2).join(' ');
sendMsgToRoom(asList[1], msg);
break;
default:
if (asList[0].startsWith('/')) {
socket.emit('message', {
id: 'Server',
date: Date.now(),
msg: asList[0] + ' is an unknown command ...',
private: false
});
} else {
io.emit('message', msg);
}
break;
}
});
socket.on('usersG', subTag => {
socket.emit('usersR', Object.keys(io.sockets.clients().connected).filter(s => s.includes(subTag) && s !== socket.id))
});
socket.on('disconnect', () => {
io.emit('usersL', Object.keys(io.sockets.clients().connected));
});
});
app.all('/', (req, res) => {
res.sendFile(__dirname + '/views/index.html');
});
app.use((err, req, res, next) => {
if (err) {
res.status(500).send("Your request " + req.method + " hasn't been processed.\n" + err);
}
next();
});
http.listen(config.get('server.port'), () => {
console.log(
'APP READY!:\n',
'• Listening on localhost:' + config.get('server.port') + '.\n'
);
});