-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
190 lines (142 loc) · 5.58 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
const express = require('express')
const expressLayouts = require('express-ejs-layouts')
const mongoose = require('mongoose')
const flash = require('connect-flash')
const session = require('express-session')
const passport = require('passport')
const path = require('path')
const http = require('http')
const socketio = require('socket.io')
const formatMessage = require('./util/messages')
const {userJoin, getCurrentUser, userLeave, getRoomUsers} = require('./util/users')
const moment = require('moment')
const MessagesSchema = require('./models/Messages')
const errorController = require('./controllers/error');
const app = express()
const server = http.createServer(app)
const io = socketio(server)
//Passport Config
require('./config/passport')(passport)
//DB Config
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true })
.then(() => console.log('MongoDB Connected!'))
.catch(err => console.log(err));
//EJS
app.use(expressLayouts)
app.set('view engine', 'ejs')
app.set('views', 'views');
//BodyParser
app.use(express.json())
app.use(express.urlencoded({extended: false}))
//Express Session
app.use(session({
secret: 'mosa3da', resave: true, saveUninitialized: true
}))
//Passport Middleware
app.use(passport.initialize())
app.use(passport.session())
//Folders configs
app.use(express.static(path.join(__dirname, 'public')));
app.use('/images', express.static(path.join(__dirname, 'images')));
app.use('/cvs', express.static(path.join(__dirname, './cvs')));
app.use(express.static(path.join(__dirname, 'views')));
//Connect Flash
app.use(flash())
// VARS
app.use((req, res, next) => {
res.locals.success_msg = req.flash('success_msg')
res.locals.err_msg = req.flash('err_msg')
res.locals.error = req.flash('error')
res.locals.isAuthenticated = req.isAuthenticated()
next()
})
app.locals.moment = require('moment');
//Routes
app.use('/', require('./routes/index'))
app.use('/', require('./routes/users'))
app.use('/', require('./routes/book'))
app.use('/', require('./routes/admin'))
app.get('/500', errorController.get500);
app.use(errorController.get404);
io.on('connection', socket => {
socket.on('joinRoom', ({patient, room}) => {
const user = userJoin(socket.id, patient, room)
socket.join(user.room)
// Load old Messages
MessagesSchema.findOne({roomId: room})
.then(room1 => {
if(room1) {
if(room1.messages.message.length > 0) {
for(let i = 0; i<room1.messages.message.length; i++) {
socket.emit('message', {username: room1.messages.message[i].sender, text:room1.messages.message[i].message, time:room1.messages.message[i].time})
}
}
}
})
// Welcome User
socket.emit('message', formatMessage('Mosa3da Bot', 'Welcome to Mosa3da Messages!'))
// Broadcast when a User connects
socket.broadcast.to(user.room).emit('message', formatMessage('Mosa3da Bot', `${user.username} Joined!`))
//Room and Users info
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getRoomUsers(user.room)
})
//Typing Status
socket.on("typing", (name) => {
socket.broadcast.to(user.room).emit("typing", name)
})
})
socket.on('chatMessage', msg => {
const user = getCurrentUser(socket.id);
io.to(user.room).emit('message', formatMessage(`${user.username}` ,msg ))
// Create new Room in database if it doesn't exist
MessagesSchema.findOne({roomId: user.room})
.then(room1 => {
if(!room1) {
const newRoom = new MessagesSchema({
roomId: user.room
})
const newMessage = [...newRoom.messages.message]
newMessage.push({sender: user.username, message: msg, time: moment().format('h:mm a')})
const updatedMessage = {message: newMessage};
newRoom.messages = updatedMessage
newRoom
.save()
.then(result => {
console.log("Room Created.");
})
} else if(room1) {
const newMessage = [...room1.messages.message]
newMessage.push({sender: user.username, message: msg, time: moment().format('h:mm a')})
const updatedMessage = {message: newMessage};
room1.messages = updatedMessage
room1
.save()
.then(result => {
console.log("Room Created.");
})
}
})
})
socket.on('disconnect', () => {
const user = userLeave(socket.id)
if(user){
io.to(user.room).emit('message', formatMessage('Mosa3da Bot', `${user.username} Left!`))
//Room and Users info
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getRoomUsers(user.room)
})
}
})
socket.on('join-room', (roomId, userId) => {
socket.join(roomId)
socket.broadcast.to(roomId).emit('user-connected', userId)
socket.on('disconnect', () => {
socket.broadcast.to(roomId).emit('user-disconnected', userId)
})
})
})
const PORT = process.env.PORT
server.listen(PORT, console.log('Connected!'))