-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
61 lines (52 loc) · 1.87 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
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const slashCommand = require('slash-command');
server.listen(3000);
app.use(express.static(`${__dirname}/dist`));
app.get('/', (req, res) => {
res.sendFile(`${__dirname}/dist/index.html`);
});
io.on('connection', (socket) => {
const clients = io.sockets.sockets;
const clientIds = Object.keys(clients);
if (clientIds.length > 2) {
// we should only allow 2 users in each chat
console.log('Room is full');
socket.emit('room_full', { message: 'Chat full!' });
socket.disconnect();
} else {
// broadcast new user to all but sender
const user = JSON.parse(socket.handshake.query.user);
const userModel = { id: socket.id, ...user };
socket.user = userModel;
socket.broadcast.emit('new_user', userModel);
// tell new user about the other if logged on
const otherUser = clientIds.filter(c => c !== socket.id)[0];
const otherUserData = clients[otherUser] && clients[otherUser].user;
if (otherUserData) socket.emit('new_user', { ...otherUserData });
// listen for new messages
socket.on('message', (data) => {
const { slashcommand, body } = slashCommand(data.message);
switch (slashcommand) {
case '/nick':
socket.user.nickname = body;
socket.broadcast.emit('new_user', { id: socket.id, nickname: body });
break;
case '/oops':
io.emit('delete_last');
break;
case '/fadelast':
io.emit('fade_last');
break;
case '/countdown':
const settings = body.split(' ');
socket.broadcast.emit('countdown', { time: settings[0], url: settings[1] });
break;
default:
io.emit('message', { from: { ...socket.user }, ...data });
}
});
}
});