-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocketio.js
156 lines (142 loc) · 4.33 KB
/
socketio.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
const socketio = require("socket.io")
const cookie = require("cookie")
const jwt = require("jsonwebtoken")
const User = require("./models/userModel")
const ChatRoom = require("./models/chat/chatRoomModel")
const ChatMessage = require("./models/chat/chatMessageModel")
module.exports = (server) => {
const io = socketio(server, {
cors: {
origin: ["http://localhost:3000"],
methods: ["GET", "POST"],
credentials: true,
},
})
// io.engine.on("initial_headers", async (headers, req) => {
// headers["set-cookie"] = cookie.serialize(
// "cookie2",
// "lol nchofo cookie customization wala la?",
// {
// path: "/",
// maxAge: 60 * 30,
// }
// )
// console.log("khasna cookies", cookie.parse(req.headers.cookie).accessToken)
// })
io.on("connection", (socket) => {
// console.log("############################")
// console.log(socket.handshake.headers.cookie)
// console.log("############################")
// const tokenPayload = jwt.decode(socket.handshake.query.jwt)
const tokenPayload = jwt.decode(
cookie.parse(socket.handshake.headers.cookie).accessToken
)
console.log("user connected")
socket.emit("connected")
// console.log('TOKEN PAYlooold : ', tokenPayload)
// const user = await User.findById(tokenPayload?.id)
// .select("name avatar")
// .populate("avatar")
//
console.log("payload", tokenPayload.id)
socket.user = { id: tokenPayload?.id.toString() }
socket.emit("connected")
socket.on("ready", async () => {
///////OPEARTIONS AFTER CLIENT HAS CONNECTED
const rooms = await ChatRoom.find({
participants: { $elemMatch: { $in: [socket?.user?.id] } },
}).populate({
path : "participants",
select : "name avatar",
populate : {path : "avatar"}
})
// .cursor()
// .eachAsync(async (doc) => {
// doc._doc.messages = await ChatMessage.find({ room: doc.id })
// .populate("user", "name avatar")
// .sort({
// createdAt: 1,
// })
// rooms.push(doc)
// })
rooms.map((room) => socket.join(room._id.toString()))
socket.emit("join-rooms", rooms)
})
// GET MESSAGES OF CURRENT ROOM
socket.on("room-messages", async (room) => {
console.log("beep boop request room messages")
try {
const messages = await ChatMessage.find({ room })
.populate({
path : "user",
select : "name avatar",
populate : {path : "avatar"}
})
.sort({ createdAt: 1 })
socket.emit("room-messages", {
room,
messages,
})
} catch (err) {
console.log("room-messages error", err)
}
})
// NEW MESSAGE ON OLD ROOM
socket.on("new-message", async (msg) => {
console.log("new message from", socket.user.id)
try {
const newMessage = await ChatMessage.create({
body: msg.body,
room: msg.room,
user: socket.user.id,
})
await newMessage.populate({
path : "user",
select : "name avatar",
populate : {path : "avatar"}
})
io.to(msg.room._id.toString()).emit("new-message-room", newMessage)
} catch (err) {
console.log("new-message error", err)
}
})
// CREATE NEW ROOM THEN SEND ROOM INFO TO SOCKETS TO ASK TO JOIN
socket.on("create-room", (room) => {
console.log("i fired once", socket.id)
members = room.participants.split(",").map((val) => val.trim())
User.find({ email: { $in: members } })
.then((res) => {
res = res.map((elem) => elem.id)
res.push(socket.user.id)
room.participants = res
ChatRoom.create(room)
.then((room) => {
io.emit("new-room", {
id: room.id.toString(),
participants: room.participants,
})
})
.catch((err) => console.log("err create-room 1", err))
})
.catch((err) => console.log("err create-room 2"))
})
// emitted from client after receiving new-room event
socket.on("ask-join-room", async (room) => {
try {
if (!room.participants.find((val) => val == socket.user.id)) return
socket.join(room.id)
const roomQueried = await ChatRoom.findById(room.id).populate({
path : "participants",
select : "name avatar",
populate : {path : "avatar"}
})
roomQueried._doc.messages = []
socket.emit("room-joined", roomQueried)
} catch (err) {
console.log("error ask-join-room", err)
}
})
socket.on("disconnect", () => console.log("user disconnected"))
socket.on("end", () => socket.disconnect())
})
}