-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
85 lines (68 loc) · 2.15 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
require('dotenv').config();
const path = require('path');
// Const { v4: uuidv4 } = require('uuid');
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const {
hset
} = require('./utils/redis');
const formatMessage = require('./utils/messages.js');
const {
userJoin,
getCurrentUser,
userLeave,
getRoomUsers
} = require('./utils/users.js');
const PORT = process.env.PORT || 8080;
const app = express();
const server = http.createServer(app);
const io = socketio(server);
const botName = '';
// Use all files in "public" as static content
app.use(express.static(`${__dirname}/public`));
// Run when client connects
io.on('connection', socket => {
socket.on('joinRoom', async data => {
const room = data.roomName;
const username = data.username;
const user = await userJoin(socket.id, username, room).catch(console.error);
socket.join(user.room);
// Broadcast when a user connects
socket.broadcast
.to(user.room)
.emit('message', formatMessage(botName, `${user.username} has joined`, 'join'));
// Send users and room info
io.to(user.room).emit('roomUsers', {
room: user.room,
users: await getRoomUsers(user.room).catch(console.error)
});
});
// Runs when client disconnects
socket.on('disconnecting', async () => {
const user = await userLeave(socket.id).catch(console.error);
if (user) {
io.to(user.room).emit('message', formatMessage(botName, `${user.username} has left`, 'leave'));
// Send users and room info
io.to(user.room).emit('roomUsers', {
room: user.room,
users: await getRoomUsers(user.room).catch(console.error)
});
}
});
// Listen for chatMessage
socket.on('chatMessage', async msg => {
const user = await getCurrentUser(socket.id);
io.to(user.room).emit('message', formatMessage(user.username, msg));
});
// Listen for canvas updates (draw)
socket.on('draw', data => {
io.emit('draw', data);
});
// Listen for room settings
socket.on('room-settings', data => {
hset(data.room, 'numImposters', data.numImposters);
hset(data.room, 'noundTime', data.roundTime);
});
});
server.listen(PORT, () => console.log('Active on port:', PORT));