-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
602 lines (509 loc) · 17.4 KB
/
Copy pathserver.js
File metadata and controls
602 lines (509 loc) · 17.4 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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
const express = require('express');
const http = require('http');
const path = require('path');
const cors = require('cors');
const { Server } = require('socket.io');
require('dotenv').config();
const connectDB = require('./config/db');
const authRoutes = require('./routes/authRoutes');
const notificationRoutes = require('./routes/notificationRoutes');
const roomRoutes = require('./routes/roomRoutes');
const Room = require('./models/Room');
const { createNotification } = require('./utils/notificationService');
const ACTIONS = require('./src/Actions');
const app = express();
const server = http.createServer(app);
const allowedOrigins = [
process.env.CLIENT_URL,
process.env.FRONTEND_URL,
'http://localhost:3000',
'http://127.0.0.1:3000',
'http://localhost:5001',
'http://127.0.0.1:5001',
].filter(Boolean);
const io = new Server(server, {
cors: {
origin: allowedOrigins.length ? allowedOrigins : '*',
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
},
});
const corsOptions = {
origin: allowedOrigins.length ? allowedOrigins : '*',
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
optionsSuccessStatus: 200,
};
app.use(cors(corsOptions));
app.options(/.*/, cors(corsOptions));
app.use(express.json({ limit: '1mb' }));
app.use(express.static('build'));
app.get('/api/health', (req, res) => {
res.status(200).json({ status: 'ok' });
});
app.use('/api/auth', authRoutes);
app.use('/api/notifications', notificationRoutes);
app.use('/api/rooms', roomRoutes);
app.post('/api/execute', async (req, res) => {
const compiledLanguageMap = {
python: 'python-3.14',
c: 'gcc-15',
cpp: 'g++-15',
};
const requestedLanguage = typeof req.body?.language === 'string' ? req.body.language : 'javascript';
const language = Object.prototype.hasOwnProperty.call(compiledLanguageMap, requestedLanguage)
? requestedLanguage
: 'javascript';
const source = typeof req.body?.code === 'string' ? req.body.code : '';
const input = typeof req.body?.input === 'string' ? req.body.input : '';
if (!source.trim()) {
return res.status(400).json({
message: language !== 'javascript'
? `${language === 'cpp' ? 'C++' : language.toUpperCase()} code is required to run the program.`
: 'JavaScript code is required to run the program.',
});
}
try {
if (language !== 'javascript') {
const onlineCompilerApiKey = process.env.ONLINE_COMPILER_API_KEY;
const onlineCompilerUrl = process.env.ONLINE_COMPILER_URL || 'https://api.onlinecompiler.io/api/run-code-sync/';
if (!onlineCompilerApiKey) {
return res.status(500).json({
message: 'ONLINE_COMPILER_API_KEY is missing on the server.',
});
}
const executionResponse = await fetch(onlineCompilerUrl, {
method: 'POST',
headers: {
Authorization: onlineCompilerApiKey,
'Content-Type': 'application/json',
},
body: JSON.stringify({
compiler: req.body?.compiler || compiledLanguageMap[language],
code: source,
input,
}),
});
const rawBody = await executionResponse.text();
let payload = {};
try {
payload = rawBody ? JSON.parse(rawBody) : {};
} catch {
payload = { message: rawBody || 'Execution service returned an unreadable response.' };
}
if (!executionResponse.ok) {
return res.status(executionResponse.status).json({
message: payload?.message || 'Execution service failed to run the code.',
details: payload,
});
}
return res.json({
output: payload?.output || '',
error: payload?.error || '',
status: payload?.status || 'unknown',
exitCode: payload?.exit_code,
signal: payload?.signal ?? null,
time: payload?.time || '',
total: payload?.total || '',
memory: payload?.memory || '',
details: payload,
});
}
const executionResponse = await fetch('https://emacs.piston.rs/api/v2/execute', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
language: 'javascript',
version: '18.15.0',
files: [{ content: source }],
}),
});
const rawBody = await executionResponse.text();
let payload = {};
try {
payload = rawBody ? JSON.parse(rawBody) : {};
} catch {
payload = { message: rawBody || 'Execution service returned an unreadable response.' };
}
if (!executionResponse.ok) {
return res.status(executionResponse.status).json({
message: payload?.message || 'Execution service failed to run the code.',
details: payload,
});
}
const output =
payload?.run?.output ||
payload?.message ||
payload?.compile?.stderr ||
payload?.run?.stderr ||
'Execution finished with no output.';
return res.json({
output,
error: payload?.compile?.stderr || payload?.run?.stderr || '',
status: 'success',
exitCode: payload?.run?.code ?? 0,
signal: payload?.run?.signal ?? null,
time: '',
total: '',
memory: '',
details: payload,
});
} catch (error) {
return res.status(502).json({
message: 'Unable to reach the execution service.',
details: error.message,
});
}
});
app.use('/api', (req, res) => {
res.status(404).json({
message: 'API route not found.',
method: req.method,
path: req.originalUrl,
});
});
const userSocketMap = {};
const roomStateMap = {};
function getNamespaceAdapterRoom(namespace, roomId) {
return io.of(namespace).adapter.rooms.get(roomId);
}
function getAllConnectedClients(roomId, namespace) {
return Array.from(getNamespaceAdapterRoom(namespace, roomId) || []).flatMap((socketId) => {
const info = userSocketMap[socketId];
if (!info) {
return [];
}
return [{
socketId,
username: info.username,
role: info.role,
participantId: info.participantId,
isLeader: info.isLeader,
userId: info.userId,
}];
});
}
function getRoomState(roomId) {
if (!roomStateMap[roomId]) {
roomStateMap[roomId] = {
leaderParticipantId: null,
pendingClients: [],
leaderReconnectTimer: null,
};
}
return roomStateMap[roomId];
}
function getPendingClients(roomId) {
return getRoomState(roomId).pendingClients;
}
function emitJoinRequest(roomId) {
const roomState = getRoomState(roomId);
const clients = getAllConnectedClients(roomId, '/js');
const leader = clients.find((client) => client.participantId === roomState.leaderParticipantId && client.isLeader);
if (!leader) {
return;
}
io.of('/js').to(leader.socketId).emit(ACTIONS.JOIN_REQUEST, {
pendingClients: roomState.pendingClients,
});
}
function broadcastRoomSnapshot(roomId, trigger = {}) {
const clients = getAllConnectedClients(roomId, '/js');
const pendingClients = getPendingClients(roomId);
clients.forEach(({ socketId: clientId }) => {
io.of('/js').to(clientId).emit(ACTIONS.JOINED, {
clients,
pendingClients,
...trigger,
});
});
}
function promoteNextLeader(roomId) {
const roomState = roomStateMap[roomId];
if (!roomState) {
return;
}
const clients = getAllConnectedClients(roomId, '/js');
const nextLeader = clients[0];
roomState.leaderParticipantId = nextLeader ? nextLeader.participantId : null;
clients.forEach((client) => {
const info = userSocketMap[client.socketId];
if (info) {
info.isLeader = client.participantId === roomState.leaderParticipantId;
}
});
}
function cancelLeaderPromotion(roomState) {
if (roomState?.leaderReconnectTimer) {
clearTimeout(roomState.leaderReconnectTimer);
roomState.leaderReconnectTimer = null;
}
}
function scheduleLeaderPromotion(roomId) {
const roomState = roomStateMap[roomId];
if (!roomState || roomState.leaderReconnectTimer) {
return;
}
roomState.leaderReconnectTimer = setTimeout(() => {
roomState.leaderReconnectTimer = null;
const leaderReconnected = getAllConnectedClients(roomId, '/js')
.some((client) => client.participantId === roomState.leaderParticipantId);
if (!leaderReconnected) {
promoteNextLeader(roomId);
}
broadcastRoomSnapshot(roomId);
emitJoinRequest(roomId);
cleanupRoomIfEmpty(roomId);
}, 5000);
}
function cleanupRoomIfEmpty(roomId) {
const clients = getAllConnectedClients(roomId, '/js');
const roomState = roomStateMap[roomId];
if (!roomState) {
return;
}
if (clients.length === 0 && roomState.pendingClients.length === 0 && !roomState.leaderReconnectTimer) {
delete roomStateMap[roomId];
}
}
async function syncRoomActivity(roomId, activeUsers) {
try {
await Room.findOneAndUpdate(
{ roomId },
{
activeUsers,
lastOpenedAt: new Date(),
}
);
} catch (error) {
console.error(`Failed to sync room activity for ${roomId}:`, error.message);
}
}
function setupNamespace(namespace) {
io.of(namespace).on('connection', (socket) => {
socket.on(ACTIONS.JOIN, ({ roomId, username, role, participantId, userId }) => {
if (namespace === '/js') {
const roomState = getRoomState(roomId);
const clientsInRoom = getNamespaceAdapterRoom(namespace, roomId);
const isFirst = !clientsInRoom || clientsInRoom.size === 0;
const isReturningLeader = roomState.leaderParticipantId === participantId;
if (!isFirst && !isReturningLeader) {
const alreadyPending = roomState.pendingClients.some((client) => client.participantId === participantId);
if (!alreadyPending) {
roomState.pendingClients.push({
socketId: socket.id,
username,
role,
participantId,
});
}
userSocketMap[socket.id] = { username, role, participantId, isLeader: false, userId: userId || null };
socket.emit(ACTIONS.JOIN_PENDING, {
pendingClients: roomState.pendingClients,
});
emitJoinRequest(roomId);
return;
}
if (isFirst || isReturningLeader) {
roomState.leaderParticipantId = participantId;
cancelLeaderPromotion(roomState);
}
}
const roomState = getRoomState(roomId);
const isLeader = namespace === '/js'
? participantId === roomState.leaderParticipantId
: false;
userSocketMap[socket.id] = { username, role, participantId, isLeader, userId: userId || null };
socket.join(roomId);
const clients = getAllConnectedClients(roomId, namespace);
if (namespace === '/js') {
syncRoomActivity(roomId, clients.length);
}
clients.forEach(({ socketId: clientId }) => {
io.of(namespace).to(clientId).emit(ACTIONS.JOINED, {
clients,
pendingClients: namespace === '/js' ? roomState.pendingClients : [],
username,
socketId: socket.id,
participantId,
});
});
});
socket.on(ACTIONS.CODE_CHANGE, ({ roomId, code, editorType }) => {
socket.in(roomId).emit(ACTIONS.CODE_CHANGE, { code, editorType });
});
socket.on(ACTIONS.SYNC_CODE, ({ socketId, code, editorType }) => {
io.of(namespace).to(socketId).emit(ACTIONS.CODE_CHANGE, { code, editorType });
});
socket.on('cursor-change', ({ roomId, username, color, cursor, editorType }) => {
socket.in(roomId).emit('cursor-change', {
socketId: socket.id,
username,
color,
cursor,
editorType,
});
});
socket.on(ACTIONS.UPDATE_ROLE, async ({ roomId, participantId, role }) => {
const requester = userSocketMap[socket.id];
const roomState = getRoomState(roomId);
if (namespace !== '/js' || !requester?.isLeader || requester.participantId !== roomState.leaderParticipantId) {
return;
}
let targetUsername = '';
let targetUserId = null;
for (const [, info] of Object.entries(userSocketMap)) {
if (info.participantId === participantId) {
info.role = role;
targetUsername = info.username;
targetUserId = info.userId;
}
}
const room = await Room.findOne({ roomId }).select('roomId title');
await createNotification({
recipientUser: targetUserId,
actorUser: requester.userId || null,
actorName: requester.username,
roomId: room?.roomId || roomId,
roomTitle: room?.title || '',
type: 'role_change',
title: 'Room role updated',
message: `${requester.username} changed your role to ${role} in ${room?.title || 'a room'}.`,
metadata: {
role,
participantId,
},
});
const clients = getAllConnectedClients(roomId, namespace);
io.of(namespace).to(roomId).emit(ACTIONS.ROLE_CHANGED, {
clients,
pendingClients: roomState.pendingClients,
participantId,
role,
username: targetUsername,
});
});
socket.on(ACTIONS.ADMIT_PARTICIPANT, async ({ roomId, participantId }) => {
if (namespace !== '/js') {
return;
}
const requester = userSocketMap[socket.id];
const roomState = getRoomState(roomId);
if (!requester?.isLeader || requester.participantId !== roomState.leaderParticipantId) {
return;
}
const pendingIndex = roomState.pendingClients.findIndex((client) => client.participantId === participantId);
if (pendingIndex === -1) {
return;
}
const [pendingClient] = roomState.pendingClients.splice(pendingIndex, 1);
const pendingInfo = userSocketMap[pendingClient.socketId];
if (!pendingInfo) {
emitJoinRequest(roomId);
broadcastRoomSnapshot(roomId);
return;
}
pendingInfo.isLeader = false;
const pendingSocket = io.of('/js').sockets.get(pendingClient.socketId);
if (!pendingSocket) {
emitJoinRequest(roomId);
broadcastRoomSnapshot(roomId);
return;
}
pendingSocket.join(roomId);
io.of('/js').to(pendingClient.socketId).emit(ACTIONS.JOIN_APPROVED, {
roomId,
});
const room = await Room.findOne({ roomId }).select('roomId title');
await createNotification({
recipientUser: pendingInfo.userId,
actorUser: requester.userId || null,
actorName: requester.username,
roomId: room?.roomId || roomId,
roomTitle: room?.title || '',
type: 'join_request_approved',
title: 'Join request approved',
message: `${requester.username} approved your request to join ${room?.title || 'the room'}.`,
});
broadcastRoomSnapshot(roomId, {
username: pendingClient.username,
socketId: pendingClient.socketId,
participantId: pendingClient.participantId,
});
emitJoinRequest(roomId);
});
socket.on('send-message', (payload = {}) => {
if (!payload.roomId) {
return;
}
const { roomId, ...messagePayload } = payload;
socket.in(roomId).emit('receive-message', messagePayload);
});
socket.on('code-output', ({ roomId, ...payload }) => {
socket.in(roomId).emit('code-output', payload);
});
socket.on('disconnecting', () => {
const rooms = [...socket.rooms];
const info = userSocketMap[socket.id] || {};
Object.entries(roomStateMap).forEach(([roomId, roomState]) => {
const pendingIndex = roomState.pendingClients.findIndex((client) => client.socketId === socket.id);
if (pendingIndex !== -1) {
roomState.pendingClients.splice(pendingIndex, 1);
emitJoinRequest(roomId);
broadcastRoomSnapshot(roomId);
cleanupRoomIfEmpty(roomId);
}
});
rooms.forEach((roomId) => {
if (roomId === socket.id) {
return;
}
const roomState = getRoomState(roomId);
const wasLeader = info.participantId && roomState.leaderParticipantId === info.participantId && namespace === '/js';
delete userSocketMap[socket.id];
if (wasLeader) {
const leaderStillConnected = getAllConnectedClients(roomId, namespace)
.some((client) => client.participantId === roomState.leaderParticipantId);
if (!leaderStillConnected) {
scheduleLeaderPromotion(roomId);
}
}
const clients = namespace === '/js' ? getAllConnectedClients(roomId, namespace) : undefined;
const pendingClients = namespace === '/js' ? getPendingClients(roomId) : undefined;
if (namespace === '/js') {
syncRoomActivity(roomId, clients?.length || 0);
}
socket.in(roomId).emit(ACTIONS.DISCONNECTED, {
socketId: socket.id,
username: info.username,
clients,
pendingClients,
});
if (namespace === '/js') {
emitJoinRequest(roomId);
cleanupRoomIfEmpty(roomId);
}
});
delete userSocketMap[socket.id];
});
});
}
setupNamespace('/');
setupNamespace('/js');
setupNamespace('/html');
setupNamespace('/css');
app.use((req, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
const PORT = process.env.SERVER_PORT || process.env.PORT || 5000;
connectDB()
.then(() => {
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
})
.catch((error) => {
console.error('Failed to start server:', error.message);
process.exit(1);
});