-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket.js
More file actions
200 lines (161 loc) · 5.83 KB
/
socket.js
File metadata and controls
200 lines (161 loc) · 5.83 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
194
195
196
197
198
199
200
require("dotenv").config();
let io;
function initSocket(server) {
const { Server } = require("socket.io");
io = new Server(server, {
cors: {
origin: process.env.FRONTEND_URL,
methods: ["GET", "POST", "DELETE"],
credentials: true,
},
});
io.on("connection", (socket) => {
console.log("User connected:", socket.id);
// ========= Collaboration: Room Join/Leave =========
socket.on("join-room", ({ roomId, user }) => {
socket.join(roomId);
socket.data.user = user;
const socketsInRoom = Array.from(io.sockets.adapter.rooms.get(roomId) || []);
const users = socketsInRoom
.map((id) => io.sockets.sockets.get(id)?.data?.user)
.filter(Boolean);
io.to(roomId).emit("room-members", users);
});
socket.on("leave-room", (roomId) => {
socket.leave(roomId);
const socketsInRoom = Array.from(io.sockets.adapter.rooms.get(roomId) || []);
const users = socketsInRoom
.map((id) => io.sockets.sockets.get(id)?.data?.user)
.filter(Boolean);
io.to(roomId).emit("room-members", users);
});
// ========= Code Collaboration =========
socket.on("code-change", ({ roomId, code }) => {
socket.to(roomId).emit("code-change", code);
});
socket.on("language-change", ({ roomId, language }) => {
socket.to(roomId).emit("language-change", language);
});
socket.on("run-code", async ({ roomId, code, language }) => {
try {
console.log(code)
const response = await fetch("https://emkc.org/api/v2/piston/execute", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
language,
version: "*",
files: [{ name: "main", content: code }],
}),
});
console.log(data)
const data = await response.json();
const output = data?.run?.output || "No output";
console.log(output)
io.to(roomId).emit("code-output", { output });
} catch (err) {
io.to(roomId).emit("code-output", { output: "Execution failed." });
}
});
// ========= Chat =========
socket.on("chat-message", ({ roomId, user, message }) => {
io.to(roomId).emit("chat-message", { user, message });
});
// ========= WebRTC Video/Audio Signaling =========
socket.on("join-video-room", ({ roomId, user }) => {
socket.join(roomId);
socket.data.user = user;
const socketsInRoom = Array.from(io.sockets.adapter.rooms.get(roomId) || []);
const otherUsers = socketsInRoom.filter((id) => id !== socket.id);
// Notify others of new participant
otherUsers.forEach((id) => {
socket.to(id).emit("new-participant", { from: socket.id, user });
});
// Step 1: Get current media states in room
const mediaStates = socketsInRoom
.map((id) => {
const sock = io.sockets.sockets.get(id);
if (sock) {
return {
socketId: id,
isVideoOn: sock.data.isVideoOn ?? true,
isAudioOn: sock.data.isAudioOn ?? true,
};
}
return null;
})
.filter(Boolean);
// Step 2: Send media-sync to newly joined user
io.to(socket.id).emit("media-sync", mediaStates);
});
socket.on("offer", ({ to, sdp }) => {
const user = socket.data.user;
io.to(to).emit("offer", { from: socket.id, sdp, user });
});
socket.on("answer", ({ to, sdp }) => {
io.to(to).emit("answer", { from: socket.id, sdp });
});
socket.on("ice-candidate", ({ to, candidate }) => {
io.to(to).emit("ice-candidate", { from: socket.id, candidate });
});
// ========= Media Sync (Video/Audio Toggle) =========
socket.on("media-toggle", ({ roomId, userId, email, isVideoOn, isAudioOn }) => {
socket.data.mediaState = { isVideoOn, isAudioOn }; // Store media state
socket.to(roomId).emit("media-updated", {
socketId: socket.id,
userId,
email,
isVideoOn,
isAudioOn,
});
});
socket.on("media-sync", (mediaStates) => {
mediaStates.forEach(({ socketId, isVideoOn, isAudioOn }) => {
setPeers((prev) => {
const updated = { ...prev };
if (updated[socketId]) {
updated[socketId].isVideoOn = isVideoOn;
updated[socketId].isAudioOn = isAudioOn;
}
return updated;
});
});
});
socket.on("media-state-changed", ({ roomId, socketId, isVideoOn, isAudioOn }) => {
socket.data.isVideoOn = isVideoOn;
socket.data.isAudioOn = isAudioOn;
socket.to(roomId).emit("media-state-changed", {
socketId,
isVideoOn,
isAudioOn,
});
});
socket.on("video-toggle", ({ roomId, userId, enabled }) => {
socket.to(roomId).emit("video-toggle", { userId, enabled });
});
socket.on("audio-toggle", ({ roomId, userId, enabled }) => {
socket.to(roomId).emit("audio-toggle", { userId, enabled });
});
// ========= Disconnect Cleanup =========
socket.on("disconnecting", () => {
for (const roomId of socket.rooms) {
if (roomId !== socket.id) {
const remainingUsers = Array.from(io.sockets.adapter.rooms.get(roomId) || [])
.filter((id) => id !== socket.id)
.map((id) => io.sockets.sockets.get(id)?.data?.user)
.filter(Boolean);
socket.to(roomId).emit("room-members", remainingUsers);
socket.to(roomId).emit("user-left", socket.id);
}
}
});
socket.on("disconnect", () => {
console.log("User disconnected:", socket.id);
});
});
}
function getIO() {
if (!io) throw new Error("Socket.io not initialized");
return io;
}
module.exports = { initSocket, getIO };