-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket.js
More file actions
79 lines (77 loc) · 2.91 KB
/
socket.js
File metadata and controls
79 lines (77 loc) · 2.91 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
import cookie from "cookie";
import jwt from "jsonwebtoken";
import { AvailableChatEvents, ChatEventEnum,SocketEvent } from "./services/Constants.js";
import User from "./models/userModel.js";
import { sendPushNotification } from "./services/firebaseService.js";
export const onlineUsers = new Set();
const mountJoinChatEvent = (socket) => {
socket.on(ChatEventEnum.JOIN_CHAT_EVENT, (chatId) => {
console.log(`User joined the chat 🤝. chatId: `, chatId);
socket.join(chatId);
});
};
const mountParticipantTypingEvent = (socket) => {
socket.on(ChatEventEnum.TYPING_EVENT, (chatId) => {
socket.in(chatId).emit(ChatEventEnum.TYPING_EVENT, chatId);
});
};
const mountParticipantStoppedTypingEvent = (socket) => {
socket.on(ChatEventEnum.STOP_TYPING_EVENT, (chatId) => {
socket.in(chatId).emit(ChatEventEnum.STOP_TYPING_EVENT, chatId);
});
};
const initializeSocketIO = (io) => {
return io.on("connection", async (socket) => {
try {
const cookies = cookie.parse(socket.handshake.headers?.cookie || "");
let token = cookies?.accessToken;
if (!token) {
token = socket.handshake.auth?.token;
}
if (!token) {
console.log("Token Empty socket")
}
// console.log(token)
const decodedToken = jwt.verify(token, process.env.JWT_SECRET); // decode the token
if(!decodedToken){
console.log("Invalid jwt token")
}
const user = await User.findById(decodedToken?._id).select(
"-password -__v"
);
if (!user) {
console.log(56)
}
// const user = req.user;
socket.user = user;
socket.join(user._id.toString());
socket.emit(SocketEvent.CONNECTED_EVENT);
User.findByIdAndUpdate(user._id,{isOnline:true});
console.log("User connected 🗼. userId: ", user._id.toString());
onlineUsers.add(user._id.toString());
io.emit(SocketEvent.ONLINE_USERS, Array.from(onlineUsers));
mountJoinChatEvent(socket);
mountParticipantTypingEvent(socket);
mountParticipantStoppedTypingEvent(socket);
socket.on(SocketEvent.DISCONNECTED_EVENT, () => {
User.findByIdAndUpdate(user._id,{isOnline:false});
console.log("user has disconnected 🚫. userId: " + socket.user?._id);
onlineUsers.delete(socket.user?._id.toString());
io.emit(SocketEvent.ONLINE_USERS, Array.from(onlineUsers));
if (socket.user?._id) {
socket.leave(socket.user._id);
}
});
} catch (error) {
console.log("Error",error)
socket.emit(
ChatEventEnum.SOCKET_ERROR_EVENT,
error?.message || "Something went wrong while connecting to the socket."
);
}
});
};
const emitSocketEvent = async(req, roomId, event, payload,sender) => {
req.app.get("io").in(roomId).emit(event, {payload,sender});
};
export { initializeSocketIO, emitSocketEvent };