Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
281 lines (225 loc) · 8.87 KB
/
Copy pathserver.js
File metadata and controls
281 lines (225 loc) · 8.87 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
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const dotenv = require('dotenv');
const { Server } = require('socket.io');
const http = require('http');
const Question = require('./models/Question.js');
const UserRouter = require('./routes/UserRoutes.js');
const QuizRouter = require('./routes/QuizRoutes.js');
const QuestionRouter = require('./routes/QuestionRoutes.js');
dotenv.config();
const app = express();
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: ["http://localhost:5173", "https://quizcrash.senani.online"],
methods: ["GET", "POST", "PUT", "DELETE", "PATCH"],
credentials: true
}
});
app.set("io", io);
const PORT = process.env.PORT || 4001;
// CORS configuration
const corsOptions = {
origin: ["http://localhost:5173", "http://localhost:5174", "https://quizcrash.senani.online"],
methods: ["GET", "POST", "PUT", "DELETE", "PATCH"],
credentials: true,
};
app.use(cors(corsOptions));
app.use(express.json());
const connectDb = async () => {
try {
await mongoose.connect(process.env.MONGO);
console.log("✅ Connected to MongoDB");
} catch (error) {
console.error("❌ MongoDB connection error:", error);
process.exit(1);
}
};
mongoose.connection.on("disconnected", () => {
console.log("⚠️ Disconnected from MongoDB");
});
// API Routes
app.use("/api/user", UserRouter);
app.use("/api/quiz", QuizRouter);
app.use("/api/question", QuestionRouter);
const rooms = new Map();
const roomWorkers = new Map(); // Store room workers
app.set("rooms", rooms);
app.set("roomWorkers", roomWorkers);
io.on("connection", (socket) => {
console.log(`🔵 New client connected: ${socket.id}`);
socket.on("join-room", ({ roomId, username }) => {
// First check if room exists
if (!rooms.has(roomId)) {
socket.emit("room-error", { message: "Room does not exist" });
return;
}
const room = rooms.get(roomId);
const user = { id: socket.id, username };
room.participants.push(user);
socket.join(roomId);
console.log(`👤 ${username} joined Room ${roomId}`);
let threadId = null;
if (roomWorkers.has(roomId)) {
const worker = roomWorkers.get(roomId);
threadId = worker.threadId;
}
io.to(roomId).emit("room-details", {
quizId: room.quizId,
threadId: threadId,
hostId: room.hostId,
});
io.to(roomId).emit("user-joined", { participants: room.participants });
});
socket.on("start-quiz", async ({ roomId }) => {
const room = rooms.get(roomId);
if (room) {
const questions = await Question.find({ quizId: room.quizId });
if (!questions || questions.length === 0) {
socket.emit("quiz-error", { message: "Cannot start quiz without questions!" });
return;
}
room.questions = questions;
room.currentQuestionIndex = 0;
room.questionStartTime = Date.now();
room.leaderboard = new Map();
room.roundScores = [];
room.questionTimer = setTimeout(() => {
handleQuestionTimeout(roomId, io);
}, 30000);
io.to(roomId).emit("question", {
question: {
questionText: questions[0].questionText,
options: questions[0].options,
questionNumber: 1,
totalQuestions: questions.length,
timeLimit: 30
}
});
}
});
socket.on("submit-answer", ({ roomId, answer }) => {
const room = rooms.get(roomId);
if (room) {
const currentQuestion = room.questions[room.currentQuestionIndex];
const timeTaken = (Date.now() - room.questionStartTime) / 1000;
const isCorrect = currentQuestion.options[currentQuestion.correctOption] === answer;
const score = isCorrect ? Math.max(1000 - Math.floor(timeTaken * 10), 100) : 0;
const currentTotal = room.leaderboard.get(socket.id) || 0;
room.leaderboard.set(socket.id, currentTotal + score);
if (!room.roundScores[room.currentQuestionIndex]) {
room.roundScores[room.currentQuestionIndex] = [];
}
room.roundScores[room.currentQuestionIndex].push({
participantId: socket.id,
username: room.participants.find(p => p.id === socket.id)?.username,
timeTaken,
score,
isCorrect
});
// Track answered participants
if (!room.answeredParticipants) {
room.answeredParticipants = new Set();
}
room.answeredParticipants.add(socket.id);
// Emit quiz status update to the host
io.to(roomId).emit("quiz-status-update", {
totalParticipants: room.participants.length,
answeredCount: room.answeredParticipants.size,
timeRemaining: Math.max(0, 30 - timeTaken)
});
socket.emit("answer-result", { isCorrect, score, timeTaken });
}
});
socket.on("next-question", ({ roomId }) => {
const room = rooms.get(roomId);
if (room && room.currentQuestionIndex < room.questions.length - 1) {
moveToNextQuestion(roomId, io);
} else if (room) {
const finalLeaderboard = Array.from(room.leaderboard.entries())
.map(([id, score]) => ({
username: room.participants.find(p => p.id === id)?.username,
totalScore: score
}))
.sort((a, b) => b.totalScore - a.totalScore)
.slice(0, 3);
io.to(roomId).emit("quiz-completed", { finalLeaderboard });
}
});
socket.on("disconnect", () => {
console.log(`🔴 Client disconnected: ${socket.id}`);
rooms.forEach((room, roomId) => {
room.participants = room.participants.filter(p => p.id !== socket.id);
io.to(roomId).emit("user-joined", { participants: room.participants });
// Notify the worker thread
if (roomWorkers.has(roomId)) {
roomWorkers.get(roomId).postMessage({
type: "REMOVE_PARTICIPANT",
data: { id: socket.id },
});
}
});
});
});
function handleQuestionTimeout(roomId, io) {
const room = rooms.get(roomId);
if (room) {
clearTimeout(room.questionTimer);
// Ensure roundScores array exists
if (!room.roundScores) {
room.roundScores = [];
}
if (room.currentQuestionIndex === undefined) {
room.currentQuestionIndex = 0;
}
if (!room.roundScores[room.currentQuestionIndex]) {
room.roundScores[room.currentQuestionIndex] = [];
}
const roundResults = room.roundScores[room.currentQuestionIndex]
.sort((a, b) => b.score - a.score)
.slice(0, 10);
io.to(roomId).emit("round-results", {
roundLeaderboard: roundResults,
correctAnswer: room.questions[room.currentQuestionIndex]?.options[room.questions[room.currentQuestionIndex]?.correctOption] || "N/A"
});
// Reset answered participants for the next question
room.answeredParticipants = new Set();
}
}
function moveToNextQuestion(roomId, io) {
const room = rooms.get(roomId);
if (room) {
// Reset answered participants for the next question
room.answeredParticipants = new Set();
// Move to the next question
room.currentQuestionIndex++;
room.questionStartTime = Date.now();
// Set a new timer for the next question
room.questionTimer = setTimeout(() => {
handleQuestionTimeout(roomId, io);
}, 30000);
// Emit the next question to all participants
const currentQuestion = room.questions[room.currentQuestionIndex];
io.to(roomId).emit("question", {
question: {
questionText: currentQuestion.questionText,
options: currentQuestion.options,
questionNumber: room.currentQuestionIndex + 1,
totalQuestions: room.questions.length,
timeLimit: 30
}
});
// Emit an initial quiz status update with answeredCount reset to 0
io.to(roomId).emit("quiz-status-update", {
totalParticipants: room.participants.length,
answeredCount: 0, // Reset answered count
timeRemaining: 30 // Reset time remaining
});
}
}
server.listen(PORT, async () => {
await connectDb();
console.log(`🚀 Server is running on port ${PORT}`);
});