forked from codingmonk-yt/Chat-App-Backend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
479 lines (379 loc) · 13.7 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
const mongoose = require("mongoose");
const jwt = require("jsonwebtoken");
const dotenv = require("dotenv");
dotenv.config({ path: "./config.env" });
process.on("uncaughtException", (err) => {
console.log(err);
console.log("UNCAUGHT Exception! Shutting down ...");
process.exit(1); // Exit Code 1 indicates that a container shut down, either because of an application failure.
});
const app = require("./app");
const http = require("http");
const server = http.createServer(app);
const { Server } = require("socket.io"); // Add this
const { promisify } = require("util");
const User = require("./models/user");
const FriendRequest = require("./models/friendRequest");
const OneToOneMessage = require("./models/OneToOneMessage");
const AudioCall = require("./models/audioCall");
const VideoCall = require("./models/videoCall");
// Add this
// Create an io server and allow for CORS from http://localhost:3000 with GET and POST methods
const io = new Server(server, {
cors: {
origin: "*",
methods: ["GET", "POST"],
},
});
const DB = process.env.DATABASE.replace(
"<PASSWORD>",
process.env.DATABASE_PASSWORD
);
mongoose
.connect(DB, {
// useNewUrlParser: true, // The underlying MongoDB driver has deprecated their current connection string parser. Because this is a major change, they added the useNewUrlParser flag to allow users to fall back to the old parser if they find a bug in the new parser.
// useCreateIndex: true, // Again previously MongoDB used an ensureIndex function call to ensure that Indexes exist and, if they didn't, to create one. This too was deprecated in favour of createIndex . the useCreateIndex option ensures that you are using the new function calls.
// useFindAndModify: false, // findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.
// useUnifiedTopology: true, // Set to true to opt in to using the MongoDB driver's new connection management engine. You should set this option to true , except for the unlikely case that it prevents you from maintaining a stable connection.
})
.then((con) => {
console.log("DB Connection successful");
});
const port = process.env.PORT || 8000;
server.listen(port, () => {
console.log(`App running on port ${port} ...`);
});
// Add this
// Listen for when the client connects via socket.io-client
io.on("connection", async (socket) => {
console.log(JSON.stringify(socket.handshake.query));
const user_id = socket.handshake.query["user_id"];
console.log(`User connected ${socket.id}`);
if (user_id != null && Boolean(user_id)) {
try {
User.findByIdAndUpdate(user_id, {
socket_id: socket.id,
status: "Online",
});
} catch (e) {
console.log(e);
}
}
// We can write our socket event listeners in here...
socket.on("friend_request", async (data) => {
const to = await User.findById(data.to).select("socket_id");
const from = await User.findById(data.from).select("socket_id");
// create a friend request
await FriendRequest.create({
sender: data.from,
recipient: data.to,
});
// emit event request received to recipient
io.to(to?.socket_id).emit("new_friend_request", {
message: "New friend request received",
});
io.to(from?.socket_id).emit("request_sent", {
message: "Request Sent successfully!",
});
});
socket.on("accept_request", async (data) => {
// accept friend request => add ref of each other in friends array
console.log(data);
const request_doc = await FriendRequest.findById(data.request_id);
console.log(request_doc);
const sender = await User.findById(request_doc.sender);
const receiver = await User.findById(request_doc.recipient);
sender.friends.push(request_doc.recipient);
receiver.friends.push(request_doc.sender);
await receiver.save({ new: true, validateModifiedOnly: true });
await sender.save({ new: true, validateModifiedOnly: true });
await FriendRequest.findByIdAndDelete(data.request_id);
// delete this request doc
// emit event to both of them
// emit event request accepted to both
io.to(sender?.socket_id).emit("request_accepted", {
message: "Friend Request Accepted",
});
io.to(receiver?.socket_id).emit("request_accepted", {
message: "Friend Request Accepted",
});
});
socket.on("get_direct_conversations", async ({ user_id }, callback) => {
const existing_conversations = await OneToOneMessage.find({
participants: { $all: [user_id] },
}).populate("participants", "firstName lastName avatar _id email status");
// db.books.find({ authors: { $elemMatch: { name: "John Smith" } } })
console.log(existing_conversations);
callback(existing_conversations);
});
socket.on("start_conversation", async (data) => {
// data: {to: from:}
const { to, from } = data;
// check if there is any existing conversation
const existing_conversations = await OneToOneMessage.find({
participants: { $size: 2, $all: [to, from] },
}).populate("participants", "firstName lastName _id email status");
console.log(existing_conversations[0], "Existing Conversation");
// if no => create a new OneToOneMessage doc & emit event "start_chat" & send conversation details as payload
if (existing_conversations.length === 0) {
let new_chat = await OneToOneMessage.create({
participants: [to, from],
});
new_chat = await OneToOneMessage.findById(new_chat).populate(
"participants",
"firstName lastName _id email status"
);
console.log(new_chat);
socket.emit("start_chat", new_chat);
}
// if yes => just emit event "start_chat" & send conversation details as payload
else {
socket.emit("start_chat", existing_conversations[0]);
}
});
socket.on("get_messages", async (data, callback) => {
try {
const { messages } = await OneToOneMessage.findById(
data.conversation_id
).select("messages");
callback(messages);
} catch (error) {
console.log(error);
}
});
// Handle incoming text/link messages
socket.on("text_message", async (data) => {
console.log("Received message:", data);
// data: {to, from, text}
const { message, conversation_id, from, to, type } = data;
const to_user = await User.findById(to);
const from_user = await User.findById(from);
// message => {to, from, type, created_at, text, file}
const new_message = {
to: to,
from: from,
type: type,
created_at: Date.now(),
text: message,
};
// fetch OneToOneMessage Doc & push a new message to existing conversation
const chat = await OneToOneMessage.findById(conversation_id);
chat.messages.push(new_message);
// save to db`
await chat.save({ new: true, validateModifiedOnly: true });
// emit incoming_message -> to user
io.to(to_user?.socket_id).emit("new_message", {
conversation_id,
message: new_message,
});
// emit outgoing_message -> from user
io.to(from_user?.socket_id).emit("new_message", {
conversation_id,
message: new_message,
});
});
// handle Media/Document Message
socket.on("file_message", (data) => {
console.log("Received message:", data);
// data: {to, from, text, file}
// Get the file extension
const fileExtension = path.extname(data.file.name);
// Generate a unique filename
const filename = `${Date.now()}_${Math.floor(
Math.random() * 10000
)}${fileExtension}`;
// upload file to AWS s3
// create a new conversation if its dosent exists yet or add a new message to existing conversation
// save to db
// emit incoming_message -> to user
// emit outgoing_message -> from user
});
// -------------- HANDLE AUDIO CALL SOCKET EVENTS ----------------- //
// handle start_audio_call event
socket.on("start_audio_call", async (data) => {
const { from, to, roomID } = data;
const to_user = await User.findById(to);
const from_user = await User.findById(from);
console.log("to_user", to_user);
// send notification to receiver of call
io.to(to_user?.socket_id).emit("audio_call_notification", {
from: from_user,
roomID,
streamID: from,
userID: to,
userName: to,
});
});
// handle audio_call_not_picked
socket.on("audio_call_not_picked", async (data) => {
console.log(data);
// find and update call record
const { to, from } = data;
const to_user = await User.findById(to);
await AudioCall.findOneAndUpdate(
{
participants: { $size: 2, $all: [to, from] },
},
{ verdict: "Missed", status: "Ended", endedAt: Date.now() }
);
// TODO => emit call_missed to receiver of call
io.to(to_user?.socket_id).emit("audio_call_missed", {
from,
to,
});
});
// handle audio_call_accepted
socket.on("audio_call_accepted", async (data) => {
const { to, from } = data;
const from_user = await User.findById(from);
// find and update call record
await AudioCall.findOneAndUpdate(
{
participants: { $size: 2, $all: [to, from] },
},
{ verdict: "Accepted" }
);
// TODO => emit call_accepted to sender of call
io.to(from_user?.socket_id).emit("audio_call_accepted", {
from,
to,
});
});
// handle audio_call_denied
socket.on("audio_call_denied", async (data) => {
// find and update call record
const { to, from } = data;
await AudioCall.findOneAndUpdate(
{
participants: { $size: 2, $all: [to, from] },
},
{ verdict: "Denied", status: "Ended", endedAt: Date.now() }
);
const from_user = await User.findById(from);
// TODO => emit call_denied to sender of call
io.to(from_user?.socket_id).emit("audio_call_denied", {
from,
to,
});
});
// handle user_is_busy_audio_call
socket.on("user_is_busy_audio_call", async (data) => {
const { to, from } = data;
// find and update call record
await AudioCall.findOneAndUpdate(
{
participants: { $size: 2, $all: [to, from] },
},
{ verdict: "Busy", status: "Ended", endedAt: Date.now() }
);
const from_user = await User.findById(from);
// TODO => emit on_another_audio_call to sender of call
io.to(from_user?.socket_id).emit("on_another_audio_call", {
from,
to,
});
});
// --------------------- HANDLE VIDEO CALL SOCKET EVENTS ---------------------- //
// handle start_video_call event
socket.on("start_video_call", async (data) => {
const { from, to, roomID } = data;
console.log(data);
const to_user = await User.findById(to);
const from_user = await User.findById(from);
console.log("to_user", to_user);
// send notification to receiver of call
io.to(to_user?.socket_id).emit("video_call_notification", {
from: from_user,
roomID,
streamID: from,
userID: to,
userName: to,
});
});
// handle video_call_not_picked
socket.on("video_call_not_picked", async (data) => {
console.log(data);
// find and update call record
const { to, from } = data;
const to_user = await User.findById(to);
await VideoCall.findOneAndUpdate(
{
participants: { $size: 2, $all: [to, from] },
},
{ verdict: "Missed", status: "Ended", endedAt: Date.now() }
);
// TODO => emit call_missed to receiver of call
io.to(to_user?.socket_id).emit("video_call_missed", {
from,
to,
});
});
// handle video_call_accepted
socket.on("video_call_accepted", async (data) => {
const { to, from } = data;
const from_user = await User.findById(from);
// find and update call record
await VideoCall.findOneAndUpdate(
{
participants: { $size: 2, $all: [to, from] },
},
{ verdict: "Accepted" }
);
// TODO => emit call_accepted to sender of call
io.to(from_user?.socket_id).emit("video_call_accepted", {
from,
to,
});
});
// handle video_call_denied
socket.on("video_call_denied", async (data) => {
// find and update call record
const { to, from } = data;
await VideoCall.findOneAndUpdate(
{
participants: { $size: 2, $all: [to, from] },
},
{ verdict: "Denied", status: "Ended", endedAt: Date.now() }
);
const from_user = await User.findById(from);
// TODO => emit call_denied to sender of call
io.to(from_user?.socket_id).emit("video_call_denied", {
from,
to,
});
});
// handle user_is_busy_video_call
socket.on("user_is_busy_video_call", async (data) => {
const { to, from } = data;
// find and update call record
await VideoCall.findOneAndUpdate(
{
participants: { $size: 2, $all: [to, from] },
},
{ verdict: "Busy", status: "Ended", endedAt: Date.now() }
);
const from_user = await User.findById(from);
// TODO => emit on_another_video_call to sender of call
io.to(from_user?.socket_id).emit("on_another_video_call", {
from,
to,
});
});
// -------------- HANDLE SOCKET DISCONNECTION ----------------- //
socket.on("end", async (data) => {
// Find user by ID and set status as offline
if (data.user_id) {
await User.findByIdAndUpdate(data.user_id, { status: "Offline" });
}
// broadcast to all conversation rooms of this user that this user is offline (disconnected)
console.log("closing connection");
socket.disconnect(0);
});
});
process.on("unhandledRejection", (err) => {
console.log(err);
console.log("UNHANDLED REJECTION! Shutting down ...");
server.close(() => {
process.exit(1); // Exit Code 1 indicates that a container shut down, either because of an application failure.
});
});