-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket.js
More file actions
97 lines (82 loc) · 2.68 KB
/
socket.js
File metadata and controls
97 lines (82 loc) · 2.68 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
// socket.js
import { Server } from "socket.io";
import { getRedisClient, initRedis } from "./config/redis.js";
import LiveCode from "./models/LiveCode.js";
export const setupSocketIO = (server) => {
const io = new Server(server, {
cors: {
origin: "*",
methods: ["GET", "POST"],
},
});
io.on("connection", async (socket) => {
const userId = socket.handshake.query.userId;
if (!userId) return socket.disconnect();
try {
await initRedis();
} catch (err) {
console.error("❌ Redis init failed on socket connection:", err.message);
}
const redisClient = getRedisClient();
if (!redisClient) {
console.warn("⚠️ Redis unavailable, continuing without Redis features");
}
if (redisClient) {
await redisClient.sAdd("onlineUsers", userId);
}
console.log(`✅ User ${userId} connected`);
socket.broadcast.emit("user-online", userId);
// ========== Chat Events ==========
socket.on("join-chat", (chatId) => {
socket.join(chatId);
console.log(`📥 User ${userId} joined chat ${chatId}`);
});
socket.on("send-message", (data) => {
const { chatId, message } = data;
socket.to(chatId).emit("receive-message", message);
});
socket.on("group-message", (data) => {
const { chatId, message } = data;
io.to(chatId).emit("receive-message", message);
});
socket.on("typing", (chatId) => {
socket.to(chatId).emit("typing", userId);
});
socket.on("stop-typing", (chatId) => {
socket.to(chatId).emit("stop-typing", userId);
});
// ========== Live Code Editor ==========
socket.on("join-live-code", async ({ chatId }) => {
socket.join(`live-${chatId}`);
const doc = await LiveCode.findOne({ chatId });
if (doc) {
socket.emit("load-code", doc);
}
});
socket.on(
"code-change",
async ({ chatId, code, language, fileName, userId }) => {
await LiveCode.findOneAndUpdate(
{ chatId },
{ code, language, fileName, updatedBy: userId },
{ upsert: true }
);
socket
.to(`live-${chatId}`)
.emit("code-update", { code, language, fileName });
}
);
// ========== Notifications ==========
socket.on("send-notification", ({ toUserId, notification }) => {
io.to(toUserId).emit("receive-notification", notification);
});
// ========== Disconnect ==========
socket.on("disconnect", async () => {
if (redisClient) {
await redisClient.sRem("onlineUsers", userId);
}
socket.broadcast.emit("user-offline", userId);
console.log(`❌ User ${userId} disconnected`);
});
});
};