-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
72 lines (55 loc) · 2.54 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
const path = require('path');
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const formatMessage = require('./utils/message');
const {userJoin, getCurrentUser, userDisconnect, getRoomUsers, getUser} = require('./utils/user');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
const botName = 'Chatbot';
// Setting static folder
app.use(express.static(path.join(__dirname, 'public')));
io.on('connection', socket => {
// handle new user joining a room
socket.on('joinRoom', ({username, room}) => {
const user = userJoin(socket.id, username, room);
socket.join(user.room);
// Emit welcome message to single new connection
socket.emit('message', formatMessage(botName, `Welcome to Chat ${user.username}!`));
// Emit to all connections on new user
socket.broadcast.to(user.room).emit('message', formatMessage(user.username, `${user.username} has joined the chat!`));
// Emit users and room info
io.to(user.room).emit('roomUsers', {room: user.room, users: getRoomUsers(user.room), userId: user.id});
// Emit when user leaves
socket.on('disconnect', () => {
const user = userDisconnect(socket.id);
if (user){
io.to(user.room).emit('message', formatMessage(botName, `${user.username} has left the chat`));
io.to(user.room).emit('roomUsers', {room: user.room, users: getRoomUsers(user.room)});
}
});
// Handle when user sends a new chat message
socket.on('chatMessage', (msg) => {
const user = getCurrentUser(socket.id);
if (user) io.to(user.room).emit('message', formatMessage(user.username, msg));
});
socket.on('privateMessage', ({username, msg}) => {
let receivingUser = getUser(username);
console.log(`receivingUser: ${JSON.stringify(receivingUser)}`)
if (receivingUser){
socket.broadcast.to(receivingUser.id).emit('privateMessage', {msg: formatMessage(getCurrentUser(socket.id).username, msg)});
const formattedMsg = formatMessage(getCurrentUser(socket.id).username, msg);
socket.emit('message', formattedMsg);
}else {
socket.emit('message', formatMessage(botName, `Failed to send message`));
}
});
socket.on('publicMessage', ({username, msg}) => {
const user = getCurrentUser(socket.id);
io.to(user.room).emit('publicMessage', formatMessage(user.username, msg));
})
});
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Server running on PORT: ${PORT}`));