-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
56 lines (50 loc) · 1.35 KB
/
index.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
if (process.env.NODE_ENV !== "production") {
require("dotenv").config();
}
const io = require("socket.io")(process.env.PORT, {
cors: {
origin: process.env.ORIGIN,
methods: ["GET", "POST"],
},
});
const regexExp =
/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/gi;
function getActiveRooms(io) {
const arr = Array.from(io.sockets.adapter.rooms);
const filtered = arr.filter(
(room) => !room[1].has(room[0]) && !regexExp.test(room[1])
);
const res = filtered.map((i) => i[0]);
return res;
}
const connectedSockets = {};
io.on("connection", (socket) => {
const { userId, username } = socket.handshake.query;
socket.join(userId);
if (userId !== "null") {
connectedSockets[userId] = username;
}
socket.on("disconnect", (reason) => {
if (connectedSockets[userId]) {
delete connectedSockets[userId];
}
});
socket.on("send-message", (message, room) => {
if (room === "") {
socket.broadcast.emit("message", message);
} else {
socket.to(room).emit("message", message);
}
});
socket.on("join-room", (room, cb) => {
socket.join(room);
cb();
});
});
const socketInterval = setInterval(() => {
const roomData = getActiveRooms(io);
const activeRooms = roomData.filter(
(room) => connectedSockets[room] === undefined && room !== ""
);
io.emit("chat-data", connectedSockets, activeRooms);
}, 2000);