Ajout de roomID

This commit is contained in:
NouhailaAater 2025-02-09 16:10:25 -05:00
parent 0febb5a394
commit 369cc218f7
11 changed files with 509 additions and 547 deletions

59
.gitignore vendored
View file

@ -129,3 +129,62 @@ dist
.yarn/install-state.gz
.pnp.*
db-backup/
# Node.js / React (évite de versionner les dépendances)
node_modules/
package-lock.json
yarn.lock
npm-debug.log
.DS_Store
# Dossier de sortie du build (React/Vite/Webpack)
dist/
build/
# Fichiers environnement (ne pas exposer tes variables sensibles)
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
# Visual Studio & VS Code (évite les fichiers temporaires et caches)
.vscode/
.vs/
*.code-workspace
*.suo
*.user
*.cache
*.log
# Fichiers spécifiques de Visual Studio
FileContentIndex/
*.vsidx
.vsconfig
slnx.sqlite
VSWorkspaceState.json
ProjectSettings.json
DocumentLayout*.json
# Logs et fichiers temporaires
logs/
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Ignorer les fichiers de tests/jest
coverage/
*.test.js
*.test.ts
*.test.tsx
jest.config.js
# Ignorer les fichiers de dépendances frontend (si utilisés)
.bower_components/
jspm_packages/
# Cache TypeScript et fichiers de sortie (évite les fichiers générés)
*.tsbuildinfo
*.tscache
*.d.ts

300
client/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -18,11 +18,11 @@
"@fortawesome/fontawesome-svg-core": "^6.6.0",
"@fortawesome/free-solid-svg-icons": "^6.4.2",
"@fortawesome/react-fontawesome": "^0.2.0",
"@mui/icons-material": "^6.4.1",
"@mui/icons-material": "^6.4.3",
"@mui/lab": "^5.0.0-alpha.153",
"@mui/material": "^6.1.0",
"@mui/material": "^6.4.3",
"@types/uuid": "^9.0.7",
"axios": "^1.6.7",
"axios": "^1.7.9",
"dompurify": "^3.2.3",
"esbuild": "^0.23.1",
"gift-pegjs": "^2.0.0-beta.1",
@ -33,9 +33,9 @@
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-modal": "^3.16.1",
"react-router-dom": "^6.26.2",
"react-router-dom": "^6.29.0",
"remark-math": "^6.0.0",
"socket.io-client": "^4.7.2",
"socket.io-client": "^4.8.1",
"ts-node": "^10.9.1",
"uuid": "^9.0.1",
"vite-plugin-checker": "^0.8.0"

View file

@ -1,4 +1,3 @@
// QuizType.tsx
export interface QuizType {
_id: string;
folderId: string;
@ -6,6 +5,7 @@ export interface QuizType {
userId: string;
title: string;
content: string[];
roomId: string;
created_at: Date;
updated_at: Date;
}

View file

@ -10,9 +10,10 @@ interface Props {
students: StudentType[];
launchQuiz: () => void;
setQuizMode: (mode: 'student' | 'teacher') => void;
isSocketConnected?: boolean;
}
const StudentWaitPage: React.FC<Props> = ({ students, launchQuiz, setQuizMode }) => {
const StudentWaitPage: React.FC<Props> = ({ students, launchQuiz, setQuizMode, isSocketConnected = true }) => {
const [isDialogOpen, setIsDialogOpen] = useState<boolean>(false);
return (
@ -25,7 +26,7 @@ const StudentWaitPage: React.FC<Props> = ({ students, launchQuiz, setQuizMode })
fullWidth
sx={{ fontWeight: 600, fontSize: 20 }}
>
Lancer
{isSocketConnected ? 'Lancer' : 'En attente de connexion...'}
</Button>
</div>

View file

@ -1,11 +1,9 @@
// ManageRoom.tsx
import React, { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { Socket } from 'socket.io-client';
import { ParsedGIFTQuestion, BaseQuestion, parse, Question } from 'gift-pegjs';
import { isSimpleNumericalAnswer, isRangeNumericalAnswer, isHighLowNumericalAnswer } from "gift-pegjs/typeGuards";
import LiveResultsComponent from 'src/components/LiveResults/LiveResults';
// import { QuestionService } from '../../../services/QuestionService';
import webSocketService, { AnswerReceptionFromBackendType } from '../../../services/WebsocketService';
import { QuizType } from '../../../Types/QuizType';
import GroupIcon from '@mui/icons-material/Group';
@ -18,14 +16,12 @@ import LoadingCircle from 'src/components/LoadingCircle/LoadingCircle';
import { Refresh, Error } from '@mui/icons-material';
import StudentWaitPage from 'src/components/StudentWaitPage/StudentWaitPage';
import DisconnectButton from 'src/components/DisconnectButton/DisconnectButton';
//import QuestionNavigation from 'src/components/QuestionNavigation/QuestionNavigation';
import QuestionDisplay from 'src/components/QuestionsDisplay/QuestionDisplay';
import ApiService from '../../../services/ApiService';
import { QuestionType } from 'src/Types/QuestionType';
const ManageRoom: React.FC = () => {
const navigate = useNavigate();
const [roomName, setRoomName] = useState<string>('');
const [socket, setSocket] = useState<Socket | null>(null);
const [students, setStudents] = useState<StudentType[]>([]);
const quizId = useParams<{ id: string }>();
@ -35,11 +31,13 @@ const ManageRoom: React.FC = () => {
const [connectingError, setConnectingError] = useState<string>('');
const [currentQuestion, setCurrentQuestion] = useState<QuestionType | undefined>(undefined);
const [quizStarted, setQuizStarted] = useState(false);
const [isSocketConnected, setIsSocketConnected] = useState(false);
useEffect(() => {
if (quizId.id) {
const fetchquiz = async () => {
try {
const quiz = await ApiService.getQuiz(quizId.id as string);
if (!quiz) {
@ -49,16 +47,23 @@ const ManageRoom: React.FC = () => {
return;
}
if ((quiz as QuizType).roomId) {
setQuiz(quiz as QuizType);
if (!socket) {
console.log(`no socket in ManageRoom, creating one.`);
createWebSocketRoom();
console.log('Initializing WebSocket connection...');
initializeWebSocketConnection((quiz as QuizType).roomId);
}
} else {
console.error('Quiz data is not valid, roomId is missing.');
navigate('/teacher/dashboard');
}
// return () => {
// webSocketService.disconnect();
// };
} catch (error) {
console.error('Failed to load quiz:', error);
setConnectingError('Erreur de chargement du quiz');
navigate('/teacher/dashboard');
}
};
fetchquiz();
@ -72,74 +77,83 @@ const ManageRoom: React.FC = () => {
}, [quizId]);
const disconnectWebSocket = () => {
if (socket) {
webSocketService.endQuiz(roomName);
if (socket && quiz) {
webSocketService.endQuiz(quiz.roomId);
webSocketService.disconnect();
setSocket(null);
setQuizQuestions(undefined);
setCurrentQuestion(undefined);
setStudents(new Array<StudentType>());
setRoomName('');
}
};
const createWebSocketRoom = () => {
console.log('Creating WebSocket room...');
setConnectingError('');
const initializeWebSocketConnection = (roomId: string) => {
console.log('Initializing WebSocket for room:', roomId);
const socket = webSocketService.connect(ENV_VARIABLES.VITE_BACKEND_SOCKET_URL);
console.log('Socket connection status:', webSocketService.isConnected());
socket.on('connect', () => {
webSocketService.createRoom();
console.log('WebSocket connected, joining room:', roomId);
setIsSocketConnected(true);
webSocketService.joinRoom(roomId, 'Teacher');
});
socket.on('connect_error', (error) => {
setConnectingError('Erreur lors de la connexion... Veuillez réessayer');
console.error('ManageRoom: WebSocket connection error:', error);
});
socket.on('create-success', (roomName: string) => {
setRoomName(roomName);
});
socket.on('create-failure', () => {
console.log('Error creating room.');
console.error('Connection error:', error);
});
socket.on('user-joined', (student: StudentType) => {
console.log(`Student joined: name = ${student.name}, id = ${student.id}`);
setStudents((prevStudents) => [...prevStudents, student]);
if (quiz && socket.connected) {
if (quizMode === 'teacher') {
webSocketService.nextQuestion(roomName, currentQuestion);
webSocketService.nextQuestion(quiz.roomId, currentQuestion);
} else if (quizMode === 'student') {
webSocketService.launchStudentModeQuiz(roomName, quizQuestions);
webSocketService.launchStudentModeQuiz(quiz.roomId, quizQuestions);
}
} else {
console.error("Quiz data is not available or Socket is not connected.");
}
});
socket.on('join-failure', (message) => {
setConnectingError(message);
setSocket(null);
setIsSocketConnected(false);
});
socket.on('user-disconnected', (userId: string) => {
console.log(`Student left: id = ${userId}`);
setStudents((prevUsers) => prevUsers.filter((user) => user.id !== userId));
});
socket.on('disconnect', () => {
console.log('WebSocket disconnected');
setIsSocketConnected(false);
});
setSocket(socket);
};
useEffect(() => {
// This is here to make sure the correct value is sent when user join
if (socket) {
console.log(`Listening for user-joined in room ${roomName}`);
if (socket && quiz?.roomId) {
console.log(`Listening for user-joined in room ${quiz.roomId}`);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
socket.on('user-joined', (_student: StudentType) => {
if (quizMode === 'teacher') {
webSocketService.nextQuestion(roomName, currentQuestion);
webSocketService.nextQuestion(quiz.roomId, currentQuestion);
} else if (quizMode === 'student') {
webSocketService.launchStudentModeQuiz(roomName, quizQuestions);
webSocketService.launchStudentModeQuiz(quiz.roomId, quizQuestions);
}
});
}
if (socket) {
// handle the case where user submits an answer
console.log(`Listening for submit-answer-room in room ${roomName}`);
console.log(`Listening for submit-answer-room in room ${quiz?.roomId}`);
socket.on('submit-answer-room', (answerData: AnswerReceptionFromBackendType) => {
const { answer, idQuestion, idUser, username } = answerData;
console.log(`Received answer from ${username} for question ${idQuestion}: ${answer}`);
@ -189,70 +203,6 @@ const ManageRoom: React.FC = () => {
}, [socket, currentQuestion, quizQuestions]);
// useEffect(() => {
// if (socket) {
// const submitAnswerHandler = (answerData: answerSubmissionType) => {
// const { answer, idQuestion, username } = answerData;
// console.log(`Received answer from ${username} for question ${idQuestion}: ${answer}`);
// // print the list of current student names
// console.log('Current students:');
// students.forEach((student) => {
// console.log(student.name);
// });
// // Update the students state using the functional form of setStudents
// setStudents((prevStudents) => {
// let foundStudent = false;
// const updatedStudents = prevStudents.map((student) => {
// if (student.id === username) {
// foundStudent = true;
// const updatedAnswers = student.answers.map((ans) => {
// const newAnswer: Answer = { answer, isCorrect: checkIfIsCorrect(answer, idQuestion, quizQuestions!), idQuestion };
// console.log(`Updating answer for ${student.name} for question ${idQuestion} to ${answer}`);
// return (ans.idQuestion === idQuestion ? { ...ans, newAnswer } : ans);
// }
// );
// return { ...student, answers: updatedAnswers };
// }
// return student;
// });
// if (!foundStudent) {
// console.log(`Student ${username} not found in the list of students in LiveResults`);
// }
// return updatedStudents;
// });
// // make a copy of the students array so we can update it
// // const updatedStudents = [...students];
// // const student = updatedStudents.find((student) => student.id === idUser);
// // if (!student) {
// // // this is a bad thing if an answer was submitted but the student isn't in the list
// // console.log(`Student ${idUser} not found in the list of students in LiveResults`);
// // return;
// // }
// // const isCorrect = checkIfIsCorrect(answer, idQuestion);
// // const newAnswer: Answer = { answer, isCorrect, idQuestion };
// // student.answers.push(newAnswer);
// // // print list of answers
// // console.log('Answers:');
// // student.answers.forEach((answer) => {
// // console.log(answer.answer);
// // });
// // setStudents(updatedStudents); // update the state
// };
// socket.on('submit-answer', submitAnswerHandler);
// return () => {
// socket.off('submit-answer');
// };
// }
// }, [socket]);
const nextQuestion = () => {
if (!quizQuestions || !currentQuestion || !quiz?.content) return;
@ -261,7 +211,7 @@ const ManageRoom: React.FC = () => {
if (nextQuestionIndex === undefined || nextQuestionIndex > quizQuestions.length - 1) return;
setCurrentQuestion(quizQuestions[nextQuestionIndex]);
webSocketService.nextQuestion(roomName, quizQuestions[nextQuestionIndex]);
webSocketService.nextQuestion(quiz.roomId, quizQuestions[nextQuestionIndex]);
};
const previousQuestion = () => {
@ -271,7 +221,7 @@ const ManageRoom: React.FC = () => {
if (prevQuestionIndex === undefined || prevQuestionIndex < 0) return;
setCurrentQuestion(quizQuestions[prevQuestionIndex]);
webSocketService.nextQuestion(roomName, quizQuestions[prevQuestionIndex]);
webSocketService.nextQuestion(quiz.roomId, quizQuestions[prevQuestionIndex]);
};
const initializeQuizQuestion = () => {
@ -291,37 +241,37 @@ const ManageRoom: React.FC = () => {
const launchTeacherMode = () => {
const quizQuestions = initializeQuizQuestion();
console.log('launchTeacherMode - quizQuestions:', quizQuestions);
if (!quizQuestions) {
console.log('Error launching quiz (launchTeacherMode). No questions found.');
return;
}
if (quizQuestions && quiz?.roomId) {
setCurrentQuestion(quizQuestions[0]);
webSocketService.nextQuestion(roomName, quizQuestions[0]);
webSocketService.nextQuestion(quiz.roomId, quizQuestions[0]);
}
};
const launchStudentMode = () => {
const quizQuestions = initializeQuizQuestion();
console.log('launchStudentMode - quizQuestions:', quizQuestions);
if (!quizQuestions) {
console.log('Error launching quiz (launchStudentMode). No questions found.');
return;
}
if (quizQuestions && quiz?.roomId) {
setQuizQuestions(quizQuestions);
webSocketService.launchStudentModeQuiz(roomName, quizQuestions);
webSocketService.launchStudentModeQuiz(quiz.roomId, quizQuestions);
}
};
const launchQuiz = () => {
if (!socket || !roomName || !quiz?.content || quiz?.content.length === 0) {
// TODO: This error happens when token expires! Need to handle it properly
console.log(`Error launching quiz. socket: ${socket}, roomName: ${roomName}, quiz: ${quiz}`);
setQuizStarted(true);
const launchQuiz = async () => {
if (!isSocketConnected) {
console.log("Waiting for socket connection...");
window.alert("En attente de la connexion au serveur... Veuillez réessayer dans quelques secondes.");
return;
}
if (!quiz?.roomId) {
console.error("Room ID is missing.");
return;
}
if (!quiz?.content || quiz.content.length === 0) {
console.error("Quiz content is missing or empty.");
return;
}
switch (quizMode) {
case 'student':
setQuizStarted(true);
@ -329,7 +279,9 @@ const ManageRoom: React.FC = () => {
case 'teacher':
setQuizStarted(true);
return launchTeacherMode();
default:
console.error("Invalid quiz mode.");
return;
}
};
@ -338,7 +290,7 @@ const ManageRoom: React.FC = () => {
setCurrentQuestion(quizQuestions[questionIndex]);
if (quizMode === 'teacher') {
webSocketService.nextQuestion(roomName, quizQuestions[questionIndex]);
webSocketService.nextQuestion(quiz.roomId, quizQuestions[questionIndex]);
}
}
};
@ -403,11 +355,11 @@ const ManageRoom: React.FC = () => {
}
if (!roomName) {
if (!quiz || !quiz?.roomId) {
return (
<div className="center">
{!connectingError ? (
<LoadingCircle text="Veuillez attendre la connexion au serveur..." />
<LoadingCircle text="Chargement du quiz..." />
) : (
<div className="center-v-align">
<Error sx={{ padding: 0 }} />
@ -415,7 +367,13 @@ const ManageRoom: React.FC = () => {
<Button
variant="contained"
startIcon={<Refresh />}
onClick={createWebSocketRoom}
onClick={() => {
if (quiz?.roomId) {
initializeWebSocketConnection(quiz.roomId);
} else {
console.error("Room ID is not available");
}
}}
>
Reconnecter
</Button>
@ -439,7 +397,7 @@ const ManageRoom: React.FC = () => {
<div className='headerContent' style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', width: '100%' }}>
<div style={{ flex: 1, display: 'flex', justifyContent: 'center' }}>
<div className='title'>Salle: {roomName}</div>
<div className='title'>Salle: {quiz?.roomId}</div>
</div>
{quizStarted && (
<div className='userCount subtitle smallText' style={{ display: 'flex', alignItems: 'center' }}>
@ -526,6 +484,7 @@ const ManageRoom: React.FC = () => {
students={students}
launchQuiz={launchQuiz}
setQuizMode={setQuizMode}
isSocketConnected={isSocketConnected}
/>
)}

View file

@ -18,21 +18,21 @@ class QuizController {
throw new AppError(MISSING_REQUIRED_PARAMETER);
}
// Is this folder mine
const owner = await this.folders.getOwner(folderId);
if (owner != req.user.userId) {
throw new AppError(FOLDER_NOT_FOUND);
}
const result = await this.quizzes.create(title, content, folderId, req.user.userId);
const roomId = this.generateRoomId();
const result = await this.quizzes.create(title, content, folderId, req.user.userId, roomId);
if (!result) {
throw new AppError(QUIZ_ALREADY_EXISTS);
}
return res.status(200).json({
message: 'Quiz créé avec succès.'
message: 'Quiz créé avec succès.',
roomId: roomId,
});
} catch (error) {
@ -40,6 +40,27 @@ class QuizController {
}
};
getRoomID = async (req, res, next) => {
try {
const { quizId } = req.params;
if (!quizId) {
throw new AppError(MISSING_REQUIRED_PARAMETER);
}
const roomId = await this.quizzes.getRoomID(quizId);
if (!roomId) {
throw new AppError(QUIZ_NOT_FOUND);
}
return res.status(200).json({
roomId: roomId
});
} catch (error) {
return next(error);
}
};
get = async (req, res, next) => {
try {
const { quizId } = req.params;
@ -54,7 +75,6 @@ class QuizController {
throw new AppError(GETTING_QUIZ_ERROR);
}
// Is this quiz mine
if (content.userId != req.user.userId) {
throw new AppError(QUIZ_NOT_FOUND);
}
@ -76,7 +96,6 @@ class QuizController {
throw new AppError(MISSING_REQUIRED_PARAMETER);
}
// Is this quiz mine
const owner = await this.quizzes.getOwner(quizId);
if (owner != req.user.userId) {
@ -106,7 +125,6 @@ class QuizController {
throw new AppError(MISSING_REQUIRED_PARAMETER);
}
// Is this quiz mine
const owner = await this.quizzes.getOwner(quizId);
if (owner != req.user.userId) {
@ -136,14 +154,12 @@ class QuizController {
throw new AppError(MISSING_REQUIRED_PARAMETER);
}
// Is this quiz mine
const quizOwner = await this.quizzes.getOwner(quizId);
if (quizOwner != req.user.userId) {
throw new AppError(QUIZ_NOT_FOUND);
}
// Is this folder mine
const folderOwner = await this.folders.getOwner(newFolderId);
if (folderOwner != req.user.userId) {
@ -312,6 +328,14 @@ class QuizController {
}
};
generateRoomId(length = 6) {
const characters = "0123456789";
let result = "";
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * characters.length));
}
return result;
}
}
module.exports = QuizController;

View file

@ -1,8 +1,9 @@
class AppError extends Error {
constructor (errorCode) {
super(errorCode.message)
this.statusCode = errorCode.code;
this.isOperational = true; // Optional: to distinguish operational errors from programming errors
constructor(errorCode = { message: "Something went wrong", code: 500 }) {
super(errorCode.message);
this.statusCode = errorCode.code || 500;
this.isOperational = true;
Error.captureStackTrace(this, this.constructor);
}
}

View file

@ -2,20 +2,21 @@ const { ObjectId } = require('mongodb');
const { generateUniqueTitle } = require('./utils');
class Quiz {
constructor(db) {
// console.log("Quiz constructor: db", db)
this.db = db;
}
async create(title, content, folderId, userId) {
// console.log(`quizzes: create title: ${title}, folderId: ${folderId}, userId: ${userId}`);
async create(title, content, folderId, userId, roomId) {
await this.db.connect()
const conn = this.db.getConnection();
const quizCollection = conn.collection('files');
const existingQuiz = await quizCollection.findOne({ title: title, folderId: folderId, userId: userId })
const existingQuiz = await quizCollection.findOne({
title: title,
folderId: folderId,
userId: userId
});
if (existingQuiz) {
throw new Error(`Quiz already exists with title: ${title}, folderId: ${folderId}, userId: ${userId}`);
@ -26,13 +27,12 @@ class Quiz {
userId: userId,
title: title,
content: content,
roomId: roomId,
created_at: new Date(),
updated_at: new Date()
}
const result = await quizCollection.insertOne(newQuiz);
// console.log("quizzes: create insertOne result", result);
return result.insertedId;
}
@ -58,6 +58,14 @@ class Quiz {
return quiz;
}
async getRoomID(quizId) {
await this.db.connect()
const conn = this.db.getConnection();
const quizCollection = conn.collection('files');
const quiz = await quizCollection.findOne({ _id: ObjectId.createFromHexString(quizId) });
return quiz.roomId;
}
async delete(quizId) {
await this.db.connect()
const conn = this.db.getConnection();
@ -149,7 +157,6 @@ class Quiz {
return existingFolder !== null;
}
}
module.exports = Quiz;

View file

@ -10,6 +10,7 @@ if (!quizzes) {
router.post("/create", jwt.authenticate, asyncHandler(quizzes.create));
router.get("/get/:quizId", jwt.authenticate, asyncHandler(asyncHandler(quizzes.get)));
router.get('/getRoomID/:quizId', jwt.authenticate, asyncHandler(quizzes.getRoomID));
router.delete("/delete/:quizId", jwt.authenticate, asyncHandler(quizzes.delete));
router.put("/update", jwt.authenticate, asyncHandler(quizzes.update));
router.put("/move", jwt.authenticate, asyncHandler(quizzes.move));

View file

@ -23,26 +23,6 @@ const setupWebsocket = (io) => {
totalConnections
);
socket.on("create-room", (sentRoomName) => {
if (sentRoomName) {
const roomName = sentRoomName.toUpperCase();
if (!io.sockets.adapter.rooms.get(roomName)) {
socket.join(roomName);
socket.emit("create-success", roomName);
} else {
socket.emit("create-failure");
}
} else {
const roomName = generateRoomName();
if (!io.sockets.adapter.rooms.get(roomName)) {
socket.join(roomName);
socket.emit("create-success", roomName);
} else {
socket.emit("create-failure");
}
}
});
socket.on("join-room", ({ enteredRoomName, username }) => {
if (io.sockets.adapter.rooms.has(enteredRoomName)) {
const clientsInRoom =
@ -68,7 +48,6 @@ const setupWebsocket = (io) => {
});
socket.on("next-question", ({ roomName, question }) => {
// console.log("next-question", roomName, question);
socket.to(roomName).emit("next-question", question);
});
@ -109,17 +88,6 @@ const setupWebsocket = (io) => {
});
});
});
const generateRoomName = (length = 6) => {
const characters = "0123456789";
let result = "";
for (let i = 0; i < length; i++) {
result += characters.charAt(
Math.floor(Math.random() * characters.length)
);
}
return result;
};
};
module.exports = { setupWebsocket };