-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
193 lines (169 loc) · 5.39 KB
/
server.js
File metadata and controls
193 lines (169 loc) · 5.39 KB
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
const { log } = require("console");
const express = require("express");
const cors = require("cors");
const DBCon = require("./config/db/DBCon");
const notFound = require("./middlewares/Err/notFound");
const errorHandler = require("./middlewares/Err/errorHandler");
const UserRoute = require("./routes/UserRoutes");
const ChatRoute = require("./routes/ChatRoutes");
const MessageRoute = require("./routes/MessageRoutes");
const Server = require("socket.io");
const expressAsyncHandler = require("express-async-handler");
const User = require("./models/UserModel");
require("dotenv").config();
const app = express();
const port = process.env.PORT || 4000;
// DB Connection
DBCon();
//regular middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());
// User routes
app.use("/api/user/", UserRoute);
app.use("/api/chat/", ChatRoute);
app.use("/api/msg/", MessageRoute);
// Error Handlers
app.use(notFound);
app.use(errorHandler);
const server = app.listen(port, () => {
log(`App is listening on port ${port}`);
});
// const io = new Server(server, {
const io = Server(server, {
pingTimeout: 30000,
cors: {
origin: ["http://127.0.0.1:5173", "http://localhost:5173"],
},
});
// for keeping track of users' stats
const onlineUsers = [];
io.on("connection", (socket) => {
// This socket is trying to create/join a new room with the socket id assigned to the user whose data is getting passed from the client side.
socket.on(
"setup",
expressAsyncHandler(async (user) => {
// created/joined the user's own room
socket.join(user._id);
// setting user online
const userId = user._id;
const validId = await User.findById(userId);
if (!validId) throw new Error("User doesn't exist");
try {
await User.findByIdAndUpdate(
userId,
{
isOnline: true,
},
{
new: true,
timestamps: true,
}
);
} catch (error) {
// console.error("Error updating user model", error);
throw new Error(error);
}
// if user is already online then don't add them again to the list
if (
!onlineUsers.find((u) => {
if (u.userId === userId) return true;
})
) {
onlineUsers.push({ userId, socketId: socket.id });
}
io.emit("connected", { isOnline: true, onlineUsers });
// console.log(onlineUsers);
})
);
// This socket is trying to join a room to start comms with the users in that particular room or only with the room owner privately.
socket.on("join room", (room) => {
// the room here is basically the chat id of the selected user or the group chat id
socket.join(room._id);
});
// These two sockets is to check whether anyone is typing or not
socket.on("typing", (room) => {
socket.in(room._id).emit("typing");
});
socket.on("stop typing", (room) => {
socket.in(room._id).emit("stop typing");
});
// This socket is trying receive the data/msg from the client in order to emit/send the data/msg to the supposed receiver
socket.on("sendMsg", (newMsg) => {
let { chat } = newMsg;
if (!chat.users) throw error("Chat users undefined!");
chat.users.forEach((u) => {
if (u._id === newMsg.sender._id) return;
if (newMsg.chat.isGroupChat) {
socket.to(u._id).emit("receiveMsg", newMsg);
} else {
socket.to(chat._id).to(u._id).emit("receiveMsg", newMsg);
}
});
});
socket.on(
"logout",
expressAsyncHandler(async (userId) => {
socket.leave(userId);
const offlineUser = onlineUsers.find((user) => user.userId === userId);
if (offlineUser) {
const { userId } = offlineUser;
// setting user offline
const validId = await User.findById(userId);
if (!validId) throw new Error("User doesn't exist");
try {
await User.findByIdAndUpdate(
userId,
{
isOnline: false,
lastSeen: new Date(),
},
{
new: true,
timestamps: true,
}
);
} catch (error) {
// console.error("Error updating user model", error);
throw new Error(error);
}
onlineUsers.splice(onlineUsers.indexOf(offlineUser), 1);
// console.log("User logged out");
io.emit("disconnected", { isOnline: false, onlineUsers });
}
})
);
socket.on(
"disconnect",
expressAsyncHandler(async () => {
const offlineUser = onlineUsers.find(
(user) => user.socketId === socket.id
);
if (offlineUser) {
const { userId } = offlineUser;
// setting user offline
const validId = await User.findById(userId);
if (!validId) throw new Error("User doesn't exist");
try {
await User.findByIdAndUpdate(
userId,
{
isOnline: false,
lastSeen: new Date(),
},
{
new: true,
timestamps: true,
}
);
} catch (error) {
// console.error("Error updating user model", error);
throw new Error(error);
}
onlineUsers.splice(onlineUsers.indexOf(offlineUser), 1);
// console.log("User is disconnected");
io.emit("disconnected", { isOnline: false, onlineUsers });
}
})
);
});