-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
executable file
·537 lines (465 loc) · 12.4 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
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
'use strict';
// for our server we use both express and socket.io
// express is used for serving our static content
// socket.io is used for all messages, in and out
const
express = require('express'),
app = express(),
http = require('http').Server(app),
io = require('socket.io')(http),
mongo = require('mongodb').MongoClient,
bcrypt = require('bcrypt'),
jwt = require('jwt-simple'),
helmet = require('helmet'),
cors = require('cors'),
ObjectId = require('mongodb').ObjectId;
// set this here or as an environment variable
var JWT_SECRET = process.env.JWT_SECRET || 'change-me-please!';
var users = [];
var db = null;
// connect to the database
mongo.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/ionic-video-chat', (err, d) => {
if (err) {
return console.log(err);
}
console.log('Connected to mongo');
db = d;
});
// basic setup
app.use(helmet());
app.use(cors());
app.use(express.static('www'));
// home
app.get('/', (req, res) => {
res.sendfile('index.html');
});
// generate random names. borrowed from Project Karma at http://karma.vg
var names = {
first: ['chocolate','red','blue','pink','grey','purple','black','white','green','fast','slow','sleepy','naked','cooked','silly','yummy','running','flying','sitting',],
last: ['bunny','penguin','otter','wombat','sloth','koala','panther','shrimp','crab','tuna','salmon','cod','python','flamingo','moose','hawk','eagle','racoon','star','robin','lobster', 'monkey', 'octopus', 'owl', 'panda', 'pig', 'puppy', 'rabbit']
};
var Name = {
random: () => {
var first = names.first[Math.floor(Math.random() * names.first.length)];
var last = names.last[Math.floor(Math.random() * names.last.length)];
return first.charAt(0).toUpperCase() + first.slice(1) + ' ' + last.charAt(0).toUpperCase() + last.slice(1);
}
}
// setup socket.io
io.on('connection', socket => {
// pluck the current logged in user from the users array
let checkUser = () => {
for (let i in users) {
if (socket.id == users[i].socket) {
return users[i];
}
}
return false;
}
// pluck the users connection by id
let getSocket = user => {
for (let i in users) {
console.log('want id ', user)
if (user == users[i].id) {
return users[i];
}
}
return false;
}
/*
let exportUser = user => {
let usr = {
name: user.name,
username: user.username,
image: user.image,
id: user.id || (user._id + '')
};
};
*/
// log a user in
let logUserIn = user => {
let usr = {
name: user.name,
username: user.username,
image: user.image,
id: user._id + '',
online: true
};
users.push({
id: usr.id,
user: usr,
socket: socket.id
});
// @todo: needs to work
let us = users.map(u => {
if (u.id != user.id) {
return u.user;
} else {
return null;
}
});
console.log(us);
// create the jwt
var token = jwt.encode(usr, JWT_SECRET, 'HS512');
/*
// im not sure if its more effecient to use promise.all or to emit them separatly. you decide
Promise.all([getChats(user), getContacts(user)]).then(data => {
socket.emit('login_successful', usr, chats, contacts, token);
});
*/
socket.emit('login_successful', usr, token);
getContacts(user).then(contacts => {
socket.emit('contacts', contacts);
getChats(usr.id).then(chats => {
socket.emit('chats', chats);
});
});
socket.broadcast.emit('online', usr);
console.log(usr.username + ' logged in');
};
socket.on('chats', request => {
let currentUser = checkUser();
if (!currentUser) return;
getChats(currentUser.id).then(chats => {
socket.emit((request && request.responseName) || 'chats', chats);
});
});
// recieve a jwt from the client and authenticate them
socket.on('auth', token => {
try {
var decoded = jwt.decode(token, JWT_SECRET);
} catch (e) {
return socket.emit('auth_error');
}
if (!decoded || !decoded.id || decoded.id == 'undefined') {
return socket.emit('auth_error');
}
// this is optional. you can typicaly assume the token is valid if you prefer and skip this additinal lookup
db.collection('users').find({
_id: ObjectId(decoded.id)
}).toArray((err, data) => {
if (err) {
socket.emit('auth_error', 'Error');
return console.log(err);
}
if (!data || !data[0] || !data[0]._id) {
socket.emit('auth_error', 'Error');
return console.log('data', data);
}
return logUserIn(data[0]);
});
});
// log a client in by credentials
socket.on('login', authUser => {
if (!authUser) {
return;
}
// if this socket is already connected,
// send a failed login message
let currentUser = checkUser();
if (currentUser) {
socket.emit('login_error', 'You are already connected.');
return;
}
db.collection('users').find({
username: authUser.username
}).toArray((err, data) => {
if (err) {
socket.emit('login_error', 'Error');
return console.log(err);
}
if (!data.length) {
if (!authUser.username || !authUser.password) {
return socket.emit('login_error', 'Username and Password required');
}
bcrypt.hash(authUser.password, 10, (err, hash) => {
if (err) {
socket.emit('login_error', 'Error');
return console.log(err);
}
let avatar = (Math.floor(Math.random() * (17 - 1 + 1)) + 1) + '';
avatar = '00'.substring(0, '00'.length - avatar.length) + avatar;
db.collection('users').insert({
name: Name.random(),
username: authUser.username,
password: hash,
image: '1-81-' + avatar + '.svg'
}, (err, data) => {
if (err) {
socket.emit('login_error', 'Error');
return console.log(err);
}
console.log('adding user', data.ops[0]);
logUserIn(data.ops[0]);
});
});
} else {
bcrypt.compare(authUser.password, data[0].password, (err, compare) => {
if (err) {
return socket.emit('login_error', 'Incorrect username or password');
}
logUserIn(data[0]);
});
}
});
});
let getChat = userId => {
return new Promise((resolve, reject) => {
let currentUser = checkUser();
db.collection('chats').find({
$or: [
{users: [ObjectId(currentUser.id), ObjectId(userId)]},
{users: [ObjectId(userId), ObjectId(currentUser.id)]}
]
}).limit(1).next((err, data) => {
if (data && data._id) {
resolve(data);
return;
}
db.collection('chats').insert({
users: [ObjectId(currentUser.id), ObjectId(userId)],
startDate: new Date,
lastDate: new Date,
lastMessage: null
}, (err, data) => {
if (err) return console.log(err);
resolve(data.ops[0]);
});
});
});
}
let formatChat = chat => {
return {
id: chat._id + '',
lastDate: chat.lastDate,
lastMessage: chat.lastMessage,
startDate: chat.startDate,
users: chat.users.map(user => {return user + ''})
}
}
// recieve an event to send a message to another user
socket.on('get-contact-chat', request => {
let currentUser = checkUser();
if (!currentUser) return;
getChat(request.id).then(chat => {
socket.emit(request.responseName || 'got-chat', formatChat(chat));
});
});
// recieve an event to send a message to another user
socket.on('message', (chatId, message) => {
let currentUser = checkUser();
if (!currentUser) return;
// @todo: add rate limiting
console.log('recieved message for ' , chatId, message)
db.collection('chats').find({
_id: ObjectId(chatId)
}).limit(1).next((err, chat) => {
if (!chat || !chat._id) {
console.log('Not a valid chat to send to', chatId);
return;
}
updateChat(chat);
addMessage(chat);
});
var updateChat = chat => {
db.collection('chats').update(
{_id: chat._id},
{
lastDate: new Date,
lastMessage: message,
users: chat.users,
startDate: chat.startDate
},
(err, data) => {
if (err) return console.log(err);
});
};
var addMessage = (chat) => {
db.collection('messages').insert({
from: currentUser.id,
date: new Date,
message: message,
chat: chat._id
}, (err, data) => {
if (err) {
return console.log(err);
}
data = data.ops[0];
let send = {
date: data.date,
id: data._id + '',
chat: data.chat + '',
from: data.from,
message: data.message
};
// send connection the notifications
for (let contact of chat.users) {
if (contact == currentUser.id) {
continue;
}
let connection = getSocket(contact);
console.log('message: from ' + currentUser.id + ' to ' + contact);
io.to(connection.socket).emit('chat-message', currentUser.id, send);
}
});
};
});
// add a user to the chat
socket.on('add-to-chat', request => {
let currentUser = checkUser();
if (!currentUser) return;
db.collection('chats').find({
_id: ObjectId(request.chat)
}).limit(1).next((err, chat) => {
if (err || !chat) return;
if (chat.users.indexOf(ObjectId(request.contact)) > -1) {
return;
}
chat.users.push(ObjectId(request.contact));
db.collection('chats').update(
{_id: chat._id},
{
lastDate: chat.lastDate,
lastMessage: chat.lastMessage,
users: chat.users,
startDate: chat.startDate
},
(err, data) => {
if (err) return console.log(err);
chatMessages(chat).then(messages => {
for (let contact of chat.users) {
let connection = getSocket(contact);
console.log('adding user to chat ' + request.chat + ' / ' + request.contact);
io.to(connection.socket).emit('chat', messages);
}
});
});
});
});
let chatMessages = chat => {
return new Promise((resolve, reject) => {
db.collection('messages').find({
chat: chat._id
}).toArray((err, messages) => {
if (err) {
return reject(err);
}
let c = formatChat(chat);
c.messages = messages;
resolve(c);
});
});
}
// get a list of messages for that chat
socket.on('chat', request => {
let currentUser = checkUser();
if (!currentUser) return;
db.collection('chats').find({
_id: ObjectId(request.chat)
}).limit(1).next((err, chat) => {
if (err || !chat) return;
chatMessages(chat).then(messages => {
socket.emit(request.responseName || 'chat_messages', messages);
});
});
});
// get chats for current user
let getChats = user => {
return new Promise((resolve, reject) => {
db.collection('chats').find({
users: ObjectId(user)
}).toArray((err, data) => {
console.log('chats', data)
if (err) {
reject();
return console.log(err);
}
if (!data || !data[0]) {
resolve([]);
return;
}
data = data.map(chat => {
return formatChat(chat);
});
resolve(data);
});
});
}
// get a list of contacts for the current user
let getContacts = currentUser => {
return new Promise((resolve, reject) => {
db.collection('users').find({
}).toArray((err, data) => {
if (err) {
reject();
return console.log(err);
}
if (!data || !data[0]) {
resolve([]);
return;
}
let contacts = data.map(contact => {
let online = false;
for (let x in users) {
if (users[x].id == contact._id) {
online = true;
break;
}
}
return {
id: contact._id + '',
name: contact.name,
username: contact.username,
image: contact.image,
online: online
};
});
resolve(contacts);
});
});
};
// for now, all users are your contacts
socket.on('contacts', userId => {
let currentUser = checkUser();
if (!currentUser) return;
getContacts(currentUser).then(contacts => {
socket.emit('contacts', contacts);
});
});
// recieve a message to send to another client
socket.on('sendMessage', (userId, message) => {
let currentUser = checkUser();
if (!currentUser) return;
var contact;
users.forEach(usr => {
if (usr.id == userId) {
contact = usr;
}
});
if (!contact) {
return;
}
console.log('sendMessage: from ' + currentUser.id + ' to ' + contact.id);
io.to(contact.socket).emit('messageReceived', currentUser.id, message);
});
// remove a connected user from the list of online users
var disconnect = () => {
for (var x in users) {
if (users[x].socket == socket.id) {
if (!users[x]) {
socket.broadcast.emit('offline', users[x].user);
console.log(users[x].user.username, ' disconnected');
}
users.splice(x, 1);
return;
}
}
console.log(socket.id + ' could not fully disconnect.');
};
socket.on('logout', disconnect);
socket.on('disconnect', disconnect);
});
const port = process.env.PORT || 9000;
http.listen(port, () => {
console.log('listening on port', port);
});