-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
109 lines (95 loc) · 2.63 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
const express = require('express');
const http = require('http');
const app = express();
const server = http.createServer(app);
const expressEJS = require('express-ejs-layouts');
const bodyParser = require('body-parser');
const socketIo = require('socket.io');
const io = socketIo(server);
const moment = require('moment');
const { userJoin, userLeave, getUsers } = require('./utils/users');
//middleware for client area
app.use(expressEJS);
//setting view engine
app.set('view engine', 'ejs');
//join static path
app.use(express.static(__dirname + '/public'));
//middelware for json
app.use(bodyParser.json());
//global variables
app.use((req, res, next) => {
next();
});
//errors
let errors = [];
//creating routes
app.get('/', (req, res) => {
res.render('index', {
errors,
});
});
let username, userRoom;
//getting room details
app.get('/chat', (req, res, next) => {
const { name, room } = req.query;
errors = [];
if (!name) {
errors.push({ msg: 'Please enter your name' });
res.redirect('/');
} else {
username = name;
userRoom = room;
res.render('chat', {
name,
room,
});
}
});
const botName = 'Chatbot';
const time = moment().format('H:mm a');
io.on('connection', (socket) => {
socket.on('userJoin', () => {
const user = userJoin(socket.id, username, userRoom);
const roomUsers = getUsers(user.room);
socket.join(user.room);
socket.emit('message', {
user: botName,
message: 'Welcome to ChatRoom',
time: time,
});
socket.broadcast.to(user.room).emit('message', {
user: botName,
message: `${user.username} has joined`,
time: time,
});
io.to(user.room).emit('users', roomUsers);
});
socket.on('chatMessage', (chatMessage) => {
const message = chatMessage;
io.to(userRoom).emit('message', {
user: username,
message: message,
time: time,
});
});
socket.on('disconnect', () => {
const userLeaves = userLeave(socket.id);
const roomUsers = getUsers(userRoom);
if (userLeaves) {
io.to(userLeaves.room).emit('message', {
user: botName,
message: `${userLeaves.username} left the chat`,
time: time,
});
io.to(userLeaves.room).emit('users', roomUsers);
// // Send users and room info
// io.to(user.room).emit('roomUsers', {
// room: user.room,
// users: getRoomUsers(user.room),
// });
}
});
});
//port
const port = process.env.PORT || 5000;
server.listen(port, () => console.log(`server is running on port ${port}`));