-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
244 lines (215 loc) · 5.68 KB
/
app.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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
const express = require('express');
const path = require('path')
const expressValidator = require('express-validator');
const session = require('express-session');
const passport = require('passport')
const LocalStrategy = require('passport-strategy').Strategy;
const bodyParser = require('body-parser');
const flash = require('connect-flash')
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io').listen(server);
const cookieParser = require('cookie-parser');
const ejs = require('ejs')
require('dotenv').config();
const Config = require('./config');
Config(process.env.NODE_ENV)
const Message = require('./Models/Message');
const User = require('./Models/User')
const Notification = require('./Models/Notification')
const Group = require('./Models/Group')
app.use(express.static(path.join(__dirname, 'public')));
const socketusers = [];
const connections = [];
const routes = require('./routes/index');
const users = require('./routes/users')
//view engine
app.set('view engine', 'ejs');
//static folder
app.use(express.static(path.join(__dirname, 'public')));
//cookie-parser
app.use(cookieParser());
//bodyparser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
//express-session middleware
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}))
//passport middleware
app.use(passport.initialize())
app.use(passport.session());
//express-validator middleware
app.use(expressValidator({
errorFormatter: function (param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while (namespace.length) {
formParam = '[' + namespace.shift() + ']';
}
return {
param: formParam,
msg: msg,
value: value
};
}
}));
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.location('/users/login');
res.redirect('/users/login');
}
//connnect-flash
app.use(flash());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
})
app.get('*', (req, res, next) => {
res.locals.user = req.user || null;
next();
})
app.get('/chats', ensureAuthenticated, (req, res) =>{
const loggedInUser = req.user;
const onlineFriends = [];
User.findById(loggedInUser._id)
.then(user => {
const friendNames = [];
user.friends.forEach(friend => {
friendNames.push(friend.username);
})
socketusers.forEach(onlineUser => {
if (friendNames.includes(onlineUser)){
onlineFriends.push(onlineUser);
}
})
res.render('index', {
onlineFriends:onlineFriends
})
})
})
app.use('/', routes);
app.use('/users', users);
io.sockets.on('connection', function (socket) {
connections.push(socket);
socket.on('disconnect', function (data) {
if (!socket.username) return;
socketusers.splice(socketusers.indexOf(socket.username), 1);
updateUsernames();
connections.splice(connections.indexOf(socket), 1);
})
//event Listener for send message emitted from the client
socket.on('send message', function (data) {
//'emit new message event' to all sockets
io.sockets.emit('new message', {
msg: data.msg,
user: socket.username,
receiver: data.receiver
});
const newMessage = {
sillyId: `${socket.username} ${data.receiver}`,
message: {
msg: data.msg,
type:"text"
},
sender: socket.username,
receiver: data.receiver,
date: new Date().toLocaleString(),
datesecs: Date.now(),
msgtype:"private"
}
Message.create(newMessage)
.then(result => {
User.findOne({username: data.receiver})
.then(resp => {
resp.messages += 1;
resp.save();
})
}).catch((err) => {
console.log(err.message)
})
})
socket.on('group message', function(data){
const groupid = data.receiver;
Group.findById(groupid).populate('users')
.then(group => {
let groupusers = [];
group.users.forEach(user => {
groupusers.push(user.username);
});
io.sockets.emit('newgroup message', {
msg: data.msg,
user: socket.username,
receiver: data.receiver,
groupusers: groupusers
})
Message.create({
sillyId: `${socket.username} ${data.receiver}`,
message: {
msg: data.msg,
type:"text"
},
sender: socket.username,
receiver: data.receiver,
date: new Date().toLocaleString(),
datesecs: Date.now(),
msgtype:"group",
groupname: group.name,
groupid: group._id
}).then(message => {
Group.findById(groupid).populate('users')
.then(group => {
group.messages.push(message)
group.save();
group.users.forEach(member => {
User.findOne({username: member.username})
.then(respUser => {
respUser.messages += 1;
respUser.save();
})
});
})
})
})
})
//image message
socket.on('image msg', function(data){
io.sockets.emit("newimage msg", {
imageurl: data.url,
receiver: data.receiver,
user: data.user,
type: data.type
})
})
//new user
socket.on('new user', function (data, callback) {
callback(true)
socket.username = data;
if (!socketusers.includes(socket.username)) {
socketusers.push(socket.username);
updateUsernames();
}
})
function updateUsernames() {
io.sockets.emit('get user', socketusers)
}
});
app.use((req, res, next) => {
const error = new Error('Not found');
error.status = 404;
next(error);
});
//renders 404 page
app.use((error, req, res, next) => {
res.status(error.status || 500);
res.render('404');
});
server.listen(process.env.PORT || 5000, () => {
console.log('server started...');
});
module.exports = app;