-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
416 lines (360 loc) · 15.8 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
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const cors = require('cors');
const webpush = require('web-push');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
require('./model/user');
require('./model/interests');
require('./model/userInterests');
require('./model/room');
require('./model/chat');
require('./model/report');
const keys = require('./config/keys');
const cookieSession = require('cookie-session');
require('./config/passport-setup');
const passport = require('passport');
mongoose.connect(keys.mongoURI, { useNewUrlParser: true, useUnifiedTopology: true });
//import routes
const authRoutes = require("./routes/auth-routes");
const databaseApiRoutes = require("./routes/database-api-routes");
const { addUser, removeUser, getUser, getUsersInRoom } = require('./users');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
const corsOptions = {
credentials: true,
origin: true
}
/*************************************** web-push ********************************************/
const publicVapidKey='BIOPEVktdDV7JzYMMB6Vf9MsrOx3uFBgDc4utrurfNYwf30SnvRzm34DRkUcTdNFdUqY069QE90MUCcxVJPxS2A';
const privateVapidKey='vriGRMGLFjNBd_s30lG6v6FY8cn6ES1rmb_siuqwDAY';
webpush.setVapidDetails("mailto:[email protected]", publicVapidKey, privateVapidKey);
// Subscribe Route
app.post("/subscribe", (req, res) => {
// Get pushSubscription object
const subscription = req.body;
// Send 201 - resource created
res.status(201).json({});
// Create payload
const payload = JSON.stringify({ title: "Push Test" });
// Pass object into sendNotification
webpush
.sendNotification(subscription, payload)
.catch(err => console.error(err));
});
/*
=======================================
Public Key:
BIOPEVktdDV7JzYMMB6Vf9MsrOx3uFBgDc4utrurfNYwf30SnvRzm34DRkUcTdNFdUqY069QE90MUCcxVJPxS2A
Private Key:
vriGRMGLFjNBd_s30lG6v6FY8cn6ES1rmb_siuqwDAY
*/
/********************************************************************************************************************/
const {ObjectId} = require('mongodb');
var Room = mongoose.model('Room');
var Chat = mongoose.model('Chat');
var noOfUserOnline = 0;
var $ipsConnected = [];
var deleteRoomTimeout = []; //array for room delete timeout var
app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieSession({
name: 'login',
maxAge: 60*60*1000*24, // 7*24* add later after completion of site
keys: [keys.session.cookieKey]
}));
app.use(passport.initialize());
app.use(passport.session());
//set up routes
app.use('/api', authRoutes);
app.use('/api', databaseApiRoutes);
app.get('/', (req, res) => res.redirect(process.env.CLIENT_URI || 'http://localhost:3000'));
app.get('/interests', (req, res) => res.redirect(process.env.CLIENT_URI || 'http://localhost:3000/interests'));
io.on('connect', (socket) => {
//user count on the basis of ip address of the user
var $ipAddress = socket.handshake.address;
if (!$ipsConnected.hasOwnProperty($ipAddress)) {
$ipsConnected[$ipAddress] = 1;
noOfUserOnline++;
socket.emit('onlineUser', { onlineUser: noOfUserOnline});
}
var roomLanguage; //var for room language
//socket connect/join function
function socketJoinFun(roomId, msgWelcome, msgJoined) {
//add messages in chat collection to the particular room
Chat.updateOne({roomId: ObjectId(roomId)}, {$push: {chat: {user: 'admin', text: msgWelcome, replyUser: '', replyText: '', replyMsgId: -1}}}, function(err, chat) {
if (err) {
//response.status(500).send({error: "Could not update the menu"});
console.log('error occurred while sending msg');
}
});
Chat.updateOne({roomId: ObjectId(roomId)}, {$push: {chat: {user: 'admin', text: msgJoined, replyUser: '', replyText: '', replyMsgId: -1}}}, function(err, chat) {
if (err) {
console.log('error occurred while sending msg');
}
});
socket.emit('message', { user: 'admin', text: msgWelcome});
socket.broadcast.to(roomId).emit('message', { user: 'admin', text: msgWelcome});
socket.broadcast.to(roomId).emit('message', { user: 'admin', text: msgJoined });
socket.emit('message', { user: 'admin', text: msgJoined});
}
//socket disconnect function
function socketDisconnectFun(roomId, msgLeft) {
//add messages in chat collection to the particular room
Chat.updateOne({roomId: ObjectId(roomId)}, {$push: {chat: {user: 'admin', text: msgLeft, replyUser: '', replyText: '', replyMsgId: -1}}}, function(err, chat) {
if (err) {
//response.status(500).send({error: "Could not update the menu"});
console.log('error occurred while sending msg');
}
});
io.to(roomId).emit('message', { user: 'admin', text: msgLeft });
}
socket.on('join', async ({ userName, room, roomId }, callback) => {
try {
//check the url for changes made by users
var errorOccured = new Promise((resolve, reject) => {
resolve(Room.find({_id: ObjectId(roomId)}, function(err, roomArr) {
if(err) {
console.log("Can't find the room");
}
return roomArr;
})
)
});
var temp = await errorOccured;
if(temp.length > 0) {
if(temp[0].title !== room) return callback("room doesn't exist, pls check url.");
else{roomLanguage = (temp[0].language).trim().toLowerCase();}
} else {
return callback("room doesn't exist, pls check url.");
}
} catch(e) {
return callback("room doesn't exist, pls check url.");
}
const { error, user } = addUser({ id: socket.id, userName, roomId, room });
if(error) return callback(error);
socket.join(user.roomId);
//clear the timeout for delete setTimeOut for a particular room
clearTimeout(deleteRoomTimeout[user.roomId]);
//update members in room when somebody joins the room
Room.updateOne({_id: ObjectId(user.roomId)}, {$set: {"members": getUsersInRoom(user.roomId).length}}, function(err, status) {
if (err) {
console.log('some error occured while updating members');
} else {
//console.log('members updated');
}
});
//switch cases for different languages while joining
switch(roomLanguage) {
case 'english':
socketJoinFun(user.roomId, `${user.name}, welcome to room ${user.room}.`, `${user.name} has joined!`);
break;
case 'mandarin':
socketJoinFun(user.roomId, `${user.name}, welcome to room ${user.room}.`, `${user.name} has joined!`);
break;
case 'hindi':
socketJoinFun(user.roomId, `${user.name}, आपका रूम ${user.room} मे स्वागत है`, `${user.name} रूम मे शामिल हो गए है`);
break;
case 'spanish':
socketJoinFun(user.roomId, `${user.name}, welcome to room ${user.room}.`, `${user.name} has joined!`);
break;
case 'french':
socketJoinFun(user.roomId, `${user.name}, welcome to room ${user.room}.`, `${user.name} has joined!`);
break;
case 'arabic':
socketJoinFun(user.roomId, `${user.name}, welcome to room ${user.room}.`, `${user.name} has joined!`);
break;
case 'bengali':
socketJoinFun(user.roomId, `${user.name}, আপনাক ${user.room} রুম মে স্বাগত জানাই ।`, `${user.name} রুমে যুক্ত হযে গেছেন ।`);
break;
case 'russian':
socketJoinFun(user.roomId, `${user.name}, welcome to room ${user.room}.`, `${user.name} has joined!`);
break;
case 'portuguese':
socketJoinFun(user.roomId, `${user.name}, welcome to room ${user.room}.`, `${user.name} has joined!`);
break;
case 'indonesian':
socketJoinFun(user.roomId, `${user.name}, welcome to room ${user.room}.`, `${user.name} has joined!`);
break;
case 'urdu':
socketJoinFun(user.roomId, `${user.name}, welcome to room ${user.room}.`, `${user.name} has joined!`);
break;
case 'german':
socketJoinFun(user.roomId, `${user.name}, welcome to room ${user.room}.`, `${user.name} has joined!`);
break;
case 'japanese':
socketJoinFun(user.roomId, `${user.name}, welcome to room ${user.room}.`, `${user.name} has joined!`);
break;
case 'swahili':
socketJoinFun(user.roomId, `${user.name}, welcome to room ${user.room}.`, `${user.name} has joined!`);
break;
case 'marathi':
socketJoinFun(user.roomId, `${user.name}, स्वागत आहे रूम ${user.room} मधे`, `${user.name} आला`);
break;
case 'telugu':
socketJoinFun(user.roomId, `${user.name}, welcome to room ${user.room}.`, `${user.name} has joined!`);
break;
case 'punjabi':
socketJoinFun(user.roomId, `${user.name}, ਕਮਰੇ ${user.room} ਵਿੱਚ ਤੁਹਾਡਾ ਸਵਾਗਤ ਹੈ`, `${user.name} ਸ਼ਾਮਲ ਹੋ ਗਿਆ ਹੈ`);
break;
case 'tamil':
socketJoinFun(user.roomId, `${user.name}, ${user.room} அறைக்குள் வருக`, `${user.name} சேர்ந்துகொண்டார்!`);
break;
case 'turkish':
socketJoinFun(user.roomId, `${user.name}, welcome to room ${user.room}.`, `${user.name} has joined!`);
break;
case 'odia':
socketJoinFun(user.roomId, `${user.name}, ଆପଣଙ୍କ ${user.room} ନାମକ ରୁମ୍ ରେ ସ୍ବାଗତ ।`, `${user.name} ରୁମ୍ ରେ ସାମିଲ୍ ହେଲେ ।`);
break;
default:
socketJoinFun(user.roomId, `${user.name}, welcome to room ${user.room}.`, `${user.name} has joined!`);
}
io.to(user.roomId).emit('roomData', { room: user.roomId, users: getUsersInRoom(user.roomId) });
callback();
});
socket.on('sendMessage', ({message, messageReply}, callback) => {
const user = getUser(socket.id);
if(user) {
//add messages in chat collection to the particular room
Chat.updateOne({roomId: ObjectId(user.roomId)}, {$push: {chat: {user: user.name, text: message, replyUser: messageReply.user, replyText: messageReply.text, replyMsgId: messageReply.id}}}, function(err, chat) {
if (err) {
//response.status(500).send({error: "Could not update the menu"});
console.log('error occurred while sending msg');
} else {
//response.send(chat);
//console.log('message sent');
}
});
io.to(user.roomId).emit('message', { user: user.name, text: message , replyUser: messageReply.user, replyText: messageReply.text, replyMsgId: messageReply.id});
}
callback();
});
//typing event for, typing status
socket.on('typing', (data, callback) => {
const user = getUser(socket.id);
if(user) {socket.broadcast.to(user.roomId).emit('typingStatus', data);}
//io.to(user.roomId).emit('typingStatus', data);
//callback();
});
socket.on('disconnect', () => {
const user = removeUser(socket.id);
if(user) {
if(getUsersInRoom(user.roomId).length <=0) {
//update members in room when somebody leaves the room and if it is not the last person
Room.updateOne({_id: ObjectId(user.roomId)}, {$set: {"members": getUsersInRoom(user.roomId).length}}, function(err, status) {
if (err) {
//response.status(500).send({error: "Could not update room members"});
console.log('some errore occured while updating members');
} else {
//console.log('members updated');
}
})
//set 30 sec timeout for deleting room
deleteRoomTimeout[user.roomId] = setTimeout(function() {
//remove the room when room is empty
Room.deleteOne({_id: ObjectId(user.roomId)}, function(err, status) {
if (err) {
//response.status(500).send({error: "Could not remove the room"});
console.log('some errore occured');
} else {
//remove chat
Chat.deleteOne({roomId: ObjectId(user.roomId)}, function(err, status) {
if (err) {
//response.status(500).send({error: "Could not remove the chat for this room"});
} else {
//response.send(status);
}
})
}
})
}, 30000);
} else {
//update members in room when somebody leaves the room and if it is not the last person
Room.updateOne({_id: ObjectId(user.roomId)}, {$set: {"members": getUsersInRoom(user.roomId).length}}, function(err, status) {
if (err) {
//response.status(500).send({error: "Could not update room members"});
console.log('some errore occured while updating members');
} else {
//console.log('members updated');
}
})
}
//switch cases for different languages while socket disconnect
switch(roomLanguage) {
case 'english':
socketDisconnectFun(user.roomId, `${user.name} has left.`);
break;
case 'mandarin':
socketDisconnectFun(user.roomId, `${user.name} has left.`);
break;
case 'hindi':
socketDisconnectFun(user.roomId, `${user.name} ने रूम छोड़ दिया है`);
break;
case 'spanish':
socketDisconnectFun(user.roomId, `${user.name} has left.`);
break;
case 'french':
socketDisconnectFun(user.roomId, `${user.name} has left.`);
break;
case 'arabic':
socketDisconnectFun(user.roomId, `${user.name} has left.`);
break;
case 'bengali':
socketDisconnectFun(user.roomId, `${user.name} রুম ছেড়ে দিয়েছেন ।`);
break;
case 'russian':
socketDisconnectFun(user.roomId, `${user.name} has left.`);
break;
case 'portuguese':
socketDisconnectFun(user.roomId, `${user.name} has left.`);
break;
case 'indonesian':
socketDisconnectFun(user.roomId, `${user.name} has left.`);
break;
case 'urdu':
socketDisconnectFun(user.roomId, `${user.name} has left.`);
break;
case 'german':
socketDisconnectFun(user.roomId, `${user.name} has left.`);
break;
case 'japanese':
socketDisconnectFun(user.roomId, `${user.name} has left.`);
break;
case 'swahili':
socketDisconnectFun(user.roomId, `${user.name} has left.`);
break;
case 'marathi':
socketDisconnectFun(user.roomId, `${user.name} सोडुन गेला`);
break;
case 'telugu':
socketDisconnectFun(user.roomId, `${user.name} has left.`);
break;
case 'punjabi':
socketDisconnectFun(user.roomId, `${user.name} ਛੱਡ ਗਿਆ ਹੈ`);
break;
case 'tamil':
socketDisconnectFun(user.roomId, `${user.name} விட்டுவிட்டார்`);
break;
case 'turkish':
socketDisconnectFun(user.roomId, `${user.name} has left.`);
break;
case 'odia':
socketDisconnectFun(user.roomId, `${user.name} ରୁମ୍ ଛାଡ଼ି ଦେଲେ।`);
break;
default:
socketDisconnectFun(user.roomId, `${user.name} has left.`);
}
io.to(user.roomId).emit('roomData', { room: user.roomId, users: getUsersInRoom(user.roomId)});
} else {
if ($ipsConnected.hasOwnProperty($ipAddress)) {
delete $ipsConnected[$ipAddress];
noOfUserOnline--;
socket.emit('onlineUser', { onlineUser: noOfUserOnline});
}
}
})
});
server.listen(process.env.PORT || 8000, () => console.log(`Server has started.`));