Skip to content

Commit f9c1f87

Browse files
committed
Update history service and exitButton with dummy input
1 parent 46fa287 commit f9c1f87

File tree

7 files changed

+95
-103
lines changed

7 files changed

+95
-103
lines changed

Backend/CollabService/utils/roomManager.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ function manageRoom(ws, roomId, userId, type) {
1212
// userIds -> track users in room
1313
// matchedUserIds -> check authorized users
1414
if (!rooms[roomId]) {
15-
rooms[roomId] = { sockets: [], userIds: [], matchedUserIds: []};
15+
rooms[roomId] = { sockets: [], userIds: [], matchedUserIds: [], startTime: new Date().toISOString()};
1616
}
1717

1818
console.log(`BEFORE room Info: userIds[${rooms[roomId].userIds}] || matchedusers[${rooms[roomId].matchedUserIds}]`)
@@ -114,6 +114,16 @@ function manageRoom(ws, roomId, userId, type) {
114114
}
115115
})
116116
}
117+
118+
119+
function broadcastRoomStartTime(ws, roomId) {
120+
const startTime = rooms[roomId].startTime;
121+
122+
ws.send(JSON.stringify({
123+
type: 'roomStartTime',
124+
startTime: startTime
125+
}));
126+
}
117127
}
118128

119129
function getRoom(roomId) {
Lines changed: 16 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,6 @@
11
const historyRouter = require('express').Router();
22
const HistoryModel = require('../models/Histories');
33

4-
// Get all history for the logged-in user
5-
// historyRouter.get("/", async (req, res) => {
6-
// const userId = req.user.id; // Assuming you're using authentication middleware
7-
8-
// try {
9-
// // Fetch all history entries for the logged-in user
10-
// const history = await HistoryModel.find({ user: userId })
11-
// .populate('question matchedUser') // Populating question and matchedUser details
12-
// .exec();
13-
// res.status(200).json(history);
14-
// } catch (error) {
15-
// res.status(500).json({ error: error.message });
16-
// }
17-
// });
18-
194
// Assuming Express.js
205
historyRouter.get('/user/:userId', async (req, res) => {
216
const { userId } = req.params;
@@ -28,34 +13,25 @@ historyRouter.get('/user/:userId', async (req, res) => {
2813
});
2914

3015

31-
// // Post a new history entry when a user exits a session
32-
// historyRouter.post("/", async (req, res) => {
33-
// const { user, matchedUser, question, duration, code } = req.body;
34-
35-
// try {
36-
// const newHistory = new HistoryModel({
37-
// user,
38-
// matchedUser,
39-
// question,
40-
// duration,
41-
// code
42-
// });
16+
// Post a new history entry when a user exits a session
17+
historyRouter.post("/", async (req, res) => {
18+
const { user, matchedUsername, questionTitle, startTime, duration, code } = req.body;
4319

44-
// await newHistory.save();
45-
// res.status(201).json(newHistory);
46-
// } catch (error) {
47-
// res.status(500).json({ error: error.message });
48-
// }
49-
// });
50-
51-
historyRouter.post('/', async (req, res) => {
5220
try {
53-
const newSession = new HistoryModel(req.body);
54-
await newSession.save();
55-
res.status(201).json({ message: 'Session saved successfully' });
21+
const newHistory = new HistoryModel({
22+
user,
23+
matchedUsername,
24+
questionTitle,
25+
startTime,
26+
duration,
27+
code
28+
});
29+
30+
await newHistory.save();
31+
res.status(201).json(newHistory);
5632
} catch (error) {
57-
res.status(500).json({ error: 'Failed to save session data' });
33+
res.status(500).json({ error: error.message });
5834
}
59-
});
35+
});
6036

6137
module.exports = historyRouter;

Frontend/src/components/collab/CollaborationSpace.jsx

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,14 @@ import React, { useEffect, useState, useRef } from 'react';
22
import { useParams, useNavigate } from 'react-router-dom';
33
import * as Y from 'yjs';
44
import { WebsocketProvider } from 'y-websocket';
5-
import { getUserFromToken } from '../user/userAvatarBox';
5+
import { getUserFromToken } from '../user/utils/authUtils';
66
import QuestionDisplay from './QuestionDisplay';
77
import Chat from './Chat';
88
import CollabNavigationBar from './CollabNavigationBar';
99
import CodeSpace from './CodeSpace';
1010
import { Container, Row, Col } from 'react-bootstrap';
1111
import collabService from '../../services/collab';
12+
import historyService from '../../services/history';
1213
import Toast from 'react-bootstrap/Toast';
1314
import ToastContainer from 'react-bootstrap/ToastContainer';
1415
import Spinner from 'react-bootstrap/Spinner';
@@ -21,7 +22,9 @@ const CollaborationSpace = () => {
2122
const [provider, setProvider] = useState(null);
2223
const [code, setCode] = useState('');
2324
const [users, setUsers] = useState([]); // track users in the room
25+
const [usersSave, setUsersSave] = useState([]); // for saving users in the room; getting matched user's username
2426
const [userId, setUserId] = useState(""); // current user
27+
const [username, setUsername] = useState(""); // current user
2528
const [language, setLanguage] = useState("python") // set default language to python
2629
const [output, setOutput] = useState("")
2730
const [messages, setMessages] = useState([])
@@ -62,7 +65,8 @@ const CollaborationSpace = () => {
6265
const fetchUser = async () => {
6366
const user = await getUserFromToken();
6467
if (user !== "No User") {
65-
setUserId(user.username); // Set the username in state
68+
setUserId(user.userId); // Set the username in state
69+
setUsername(user.username); // Set the username in state
6670
initiateWebSocket(user.username);
6771
} else {
6872
setUserId("Guest"); // Fallback in case no user is found
@@ -85,6 +89,12 @@ const CollaborationSpace = () => {
8589
console.log("Messages state updated:", messages);
8690
}, [messages]);
8791

92+
useEffect(() => {
93+
if (users.length == 2) {
94+
setUsersSave(users)
95+
}
96+
}, [users])
97+
8898
const initiateWebSocket = (userId) => {
8999
if (websocketRef.current) return; // Prevent duplicate connections
90100

@@ -156,6 +166,31 @@ const CollaborationSpace = () => {
156166
};
157167

158168
const handleExit = () => {
169+
try {
170+
// Filter out the current user from the usersSave array to find the matched user
171+
const matchedUser = usersSave.filter(user => user !== username)[0]; // Assuming usersSave contains objects with userId property
172+
173+
if (!matchedUser) {
174+
throw new Error("No matched user found");
175+
}
176+
const sessionData = {
177+
user: userId,
178+
matchedUsername: matchedUser, // Assuming user[1] is the matched user
179+
questionTitle: 'BFS', // This ID should be available in context or passed down
180+
// questionTitle: questionTitle, // This ID should be available in context or passed down
181+
// startTime: roomCreationTime,
182+
startTime: new Date(),
183+
// duration: new Date().getTime() - new Date(roomCreationTime).getTime(),
184+
duration: 10,
185+
code: '1'
186+
}
187+
188+
historyService.createHistoryAttempt(sessionData)
189+
// Navigate away or perform any additional actions on success
190+
} catch (error) {
191+
console.error("Failed to save session history:", error)
192+
}
193+
159194
if (websocketRef.current) websocketRef.current.send(JSON.stringify({ type: 'leaveRoom', roomId, userId }));
160195

161196
// Clean up Yjs document and provider before going back to home
Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
1-
import React from 'react'
1+
import React, { useEffect, useState } from 'react'
22
import { Card } from 'react-bootstrap'
33

4-
const QuestionDisplay = () => {
4+
const QuestionDisplay = ({ title, description}) => {
5+
56
return (
67
<Card>
7-
<Card.Header>Question Title</Card.Header>
8-
<Card.Body>
9-
<p>Question Description Placeholder</p>
10-
</Card.Body>
8+
<Card.Header>{title || "Loading..."}</Card.Header>
9+
<Card.Body>
10+
<p>{description || "Loading question details..."}</p>
11+
</Card.Body>
1112
</Card>
1213
)
1314
}
1415

15-
export default QuestionDisplay
16+
export default QuestionDisplay

Frontend/src/components/user/HistoryAttempt.jsx

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,22 @@
22
import React from 'react';
33

44
const HistoryAttempt = ({ attempt }) => {
5-
const { matchedUser, question, startTime, duration, codeFile } = attempt;
5+
const { matchedUsername, questionTitle, startTime, duration, code } = attempt;
66

77
return (
8-
<div className="history-attempt">
9-
<h3>Attempt with {matchedUser}</h3>
10-
<p>Question: {question.title}</p>
11-
<p>Start Time: {new Date(startTime).toLocaleString()}</p>
12-
<p>Duration: {duration} minutes</p>
13-
<button onClick={() => downloadCode(codeFile)}>Download Code</button>
14-
</div>
8+
<tr>
9+
<td>{matchedUsername}</td>
10+
<td>{questionTitle}</td>
11+
<td>{new Date(startTime).toLocaleString()}</td>
12+
<td>{duration} minutes</td>
13+
{/* <td>
14+
{/* <button onClick={() => downloadCode(codeFile)} className="btn btn-sm btn-primary">
15+
Download Code
16+
</button> }
17+
</td>*/}
18+
<td>{code} dummy file content</td>
19+
20+
</tr>
1521
);
1622
};
1723

Frontend/src/components/user/HistoryPage.jsx

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,22 @@ import HistoryTable from './HistoryTable';
44
import ProfileSidebar from './ProfileSidebar';
55
import { getUserFromToken } from "./utils/authUtils";
66

7+
// get question title and create current time
8+
// get request successful
9+
10+
711
function HistoryPage() {
812
const [userID, setUserID] = useState(null);
13+
const [username, setUsername] = useState(null);
914

1015
useEffect(() => {
1116
async function fetchData() {
1217
try {
1318
const user = await getUserFromToken();
1419
if (user) {
1520
setUserID(user.userId); // asynchronous
16-
console.log(`I have gotten the user id in history page: ${user.userId}`)
21+
setUsername(user.username); // asynchronous
22+
console.log(`I have gotten the user id in history page: ${user.userId} ${user.username}`)
1723
}
1824
} catch (error) {
1925
console.error('Error fetching user ID in history page component:', error);
@@ -29,7 +35,7 @@ function HistoryPage() {
2935
<NavigationBar/>
3036
<div className="row">
3137
<div className="Navbar col-2">
32-
<ProfileSidebar userID={userID}/>
38+
<ProfileSidebar userID={userID} username={username} />
3339
</div>
3440
<div className="col-10">
3541
<HistoryTable userID={userID}/>

Frontend/src/components/user/HistoryTable.jsx

Lines changed: 1 addition & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -2,53 +2,11 @@
22
import React, { useState, useEffect } from 'react';
33
import HistoryAttempt from './HistoryAttempt';
44
import historyService from "../../services/history";
5-
import { getUserFromToken } from "./utils/authUtils";
6-
// import {jwtDecode} from "jwt-decode";
7-
// import userService from "../../services/users";
8-
9-
// export async function getUserFromToken() {
10-
// const jwtToken = sessionStorage.getItem('jwt_token');
11-
// if (jwtToken) {
12-
// const decodedToken = jwtDecode(jwtToken);
13-
// try {
14-
// // decodedToken has an id field in auth-controller.js
15-
// // user fetched by id has a username field in user-model.js
16-
// const id = decodedToken.id;
17-
// const user = await userService.getUser(
18-
// decodedToken.id, {headers: {Authorization: `Bearer ${jwtToken}`}})
19-
// // getUser return an Object with data, message, and type
20-
// // The user data is nested in Object.data and hence we need a double .data to access it
21-
// return {id: id, username: user.data.data.username};
22-
// } catch (error) {
23-
// console.error(error);
24-
// return "No User";
25-
// }
26-
// }
27-
// return "No User";
28-
// }
295

306

317
const HistoryTable = ({userID}) => {
32-
// const [userID, setUserID] = useState(null);
338
const [history, setHistory] = useState([]);
349

35-
// useEffect(() => {
36-
// async function fetchData() {
37-
// try {
38-
// const user = await getUserFromToken();
39-
// if (user) {
40-
// setUserID(user.userId); // asynchronous
41-
// const result = await historyService.getHistoryByUserId(user.userId);
42-
// setHistory(result.data);
43-
// console.log(`I have gotten the user id: ${user.userId}`)
44-
// }
45-
// } catch (error) {
46-
// console.error('Error fetching attempt history:', error);
47-
// }
48-
// }
49-
// fetchData();
50-
// }, []);
51-
5210
useEffect(() => {
5311
async function fetchData() {
5412
try {
@@ -62,7 +20,7 @@ const HistoryTable = ({userID}) => {
6220
}
6321
}
6422
fetchData();
65-
}, []);
23+
}, [userID]);
6624

6725
return (
6826
<div className="history-table">

0 commit comments

Comments
 (0)