Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 49 additions & 1 deletion YStemAndChess/src/app/pages/play-mentor/play-mentor.component.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,58 @@
import { CookieService } from 'ngx-cookie-service';
import { SocketService } from '../../services/socket/socket.service';
import { Component, OnInit } from '@angular/core';
import { environment } from 'src/environments/environment';

@Component({
selector: 'app-play-mentor',
templateUrl: './play-mentor.component.html',
styleUrls: ['./play-mentor.component.scss']
})
export class PlayMentorComponent implements OnInit {

meetingId;
displayMoves = [];
constructor(private socket: SocketService, private cookie: CookieService) { }

ngOnInit(): void {
let userContent;
if (this.cookie.check('login')) {
userContent = JSON.parse(atob(this.cookie.get('login').split('.')[1]));
this.httpGetAsync(
`${environment.urls.middlewareURL}/meetings/inMeeting`,
'GET',
(response) => {
if (
JSON.parse(response) ===
'There are no current meetings with this user.'
) {
return;
}
let responseText = JSON.parse(response)[0];
this.meetingId = responseText.meetingId;
}
);
}
}
getMovesList = () => {
let url: string = '';
url = `${environment.urls.middlewareURL}/meetings/getBoardState?meetingId=${this.meetingId}`;
this.httpGetAsync(url, 'GET', (response) => {
response = JSON.parse(response);
this.displayMoves = response.moves || [];
});
};
private httpGetAsync(theUrl: string, method: string = 'POST', callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
};
xmlHttp.open(method, theUrl, true); // true for asynchronous
xmlHttp.setRequestHeader(
'Authorization',
`Bearer ${this.cookie.get('login')}`
);
xmlHttp.send(null);
}

public flipBoard() {
Expand All @@ -22,6 +63,13 @@ export class PlayMentorComponent implements OnInit {
public newGame() {
let userContent = JSON.parse(atob(this.cookie.get("login").split(".")[1]));
this.socket.emitMessage("createNewGame", JSON.stringify({username: userContent.username}));
this.getMovesList();
let url: string;
url = `${environment.urls.middlewareURL}/meetings/newBoardState?meetingId=${this.meetingId}`;
this.httpGetAsync(url, 'POST', (response) => {
response = JSON.parse(response);
this.displayMoves = response.moves || [];
});
}

}
24 changes: 12 additions & 12 deletions YStemAndChess/src/app/pages/play/play.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -14,47 +14,47 @@
<span>Steps</span>
</div>
<div class="fwd-btns">
<p (click)="setMove(0)" [ngClass]="currentStep === 0 && 'isBlur'">
<p (click)="setMove(0,'backward')" [ngClass]="currentStep === 0 && 'isBlur'">
<img src="../../../assets/images/moves/icons8-rewind-100.png" />
</p>
<p
(click)="setMove(currentStep - 1)"
(click)="setMove(currentStep - 1,'backward')"
[ngClass]="currentStep <= 0 && 'isBlur'"
>
<img src="../../../assets/images/moves/icons8-less-than-60.png" />
</p>
<p
(click)="setMove(currentStep + 1)"
(click)="setMove(currentStep + 1,'forward')"
[ngClass]="currentStep === displayMoves.length - 1 && 'isBlur'"
>
<img src="../../../assets/images/moves/icons8-more-than-60.png" />
</p>
<p
(click)="setMove(displayMoves.length - 1)"
(click)="setMove(displayMoves.length - 1,'forward')"
[ngClass]="currentStep === displayMoves.length - 1 && 'isBlur'"
>
<img src="../../../assets/images/moves/icons8-fast-forward-100.png" />
</p>
</div>
<div class="display-step" (scroll)="scrolled($event)" #scrollframe>
<div class="table-moves" #item>
<div>
<div style="width: 100px">
<div
*ngFor="let item of displayMoves; let i = index"
(click)="setMove(i)"
(click)="setMove(i,'direct')"
>
<p *ngIf="i % 2 === 0">
<img [src]="imgPos(i)" alt="" width="40%" /> {{ item.pos }}
<p *ngIf="i % 2 === 0" [class.tableMove-selected]="i == currentStep">
<img [src]="imgPos(i)" alt="" class="imgRes" /> {{ item.pos }}
</p>
</div>
</div>
<div>
<div style="width: 100px">
<div
*ngFor="let item of displayMoves; let i = index"
(click)="setMove(i)"
(click)="setMove(i,'direct')"
>
<p *ngIf="i % 2 !== 0">
<img [src]="imgPos(i)" alt="" width="40%" />{{ item.pos }}
<p *ngIf="i % 2 !== 0" [class.tableMove-selected]="i == currentStep">
<img [src]="imgPos(i)" alt="" class="imgRes" />{{ item.pos }}
</p>
</div>
</div>
Expand Down
11 changes: 11 additions & 0 deletions YStemAndChess/src/app/pages/play/play.component.scss
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,24 @@
justify-content: center;
align-items: center;
}
.tableMove-selected {
background-color: white !important;
}
.imgRes {
height: 30px !important;
width: 30px !important;
margin: 0px 0px 8px;
padding: 3.2px;
}

.display-step {
display: block;
height: 20rem;
overflow: hidden scroll;
cursor: pointer;
background-color: lightgray;
padding: 7%;
width: fit-content;
}
table {
text-align: center;
Expand Down
50 changes: 37 additions & 13 deletions YStemAndChess/src/app/pages/play/play.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,14 +210,14 @@ export class PlayComponent implements OnInit {
this.getMovesList();
setTimeout(()=>{
this.scrollToBottom();
}, 500);
}, 1000);
}, 1000);
if (this.isReady && this.isStepLast) {
let newData = JSON.parse(<string>data);
var chessBoard = (<HTMLFrameElement>(
document.getElementById('chessBd')
)).contentWindow;
this.getMovesList();
// this.getMovesList();
chessBoard.postMessage(
JSON.stringify({
boardState: newData.boardState,
Expand Down Expand Up @@ -317,7 +317,12 @@ export class PlayComponent implements OnInit {
url = `${environment.urls.middlewareURL}/meetings/getBoardState?meetingId=${this.meetingId}`;
this.httpGetAsync(url, 'GET', (response) => {
response = JSON.parse(response);
this.displayMoves = response.moves || [];
let finalMove =
response.moves.length > 0
? response.moves[response.moves.length - 1]
: response.moves;
this.displayMoves = finalMove || [];
this.currentStep = finalMove.length > 0 ? finalMove.length - 1 : 0;
});
};
private sendFromQueue() {
Expand Down Expand Up @@ -372,12 +377,16 @@ export class PlayComponent implements OnInit {
'newState',
JSON.stringify({ boardState: data, username: userContent.username })
);
this.getMovesList();
// this.getMovesList();
let url: string;
url = `${environment.urls.middlewareURL}/meetings/boardState?meetingId=${this.meetingId}&fen=${data}&pos=${this.move}&image=${this.pieceImage}`;
this.httpGetAsync(url, 'POST', (response) => {
response = JSON.parse(response);
this.displayMoves = response.moves || [];
let finalMove =
response.moves.length > 0
? response.moves[response.moves.length - 1]
: response.moves;
this.displayMoves = finalMove || [];
this.scrollToBottom();
});
setTimeout(()=>{
Expand All @@ -403,20 +412,35 @@ export class PlayComponent implements OnInit {
JSON.stringify({ username: userContent.username })
);
}
setMove(index) {
setMove(index,direction) {
this.currentStep =
index <= 0
? 0
: index > this.displayMoves.length - 1
? this.displayMoves.length - 1
: index;
if (this.displayMoves.length - 1 === index) {
this.isStepLast = true;
this.reload();
} else {
this.isStepLast = false;
if (direction != 'backward') {
if (this.displayMoves.length - 1 === index) {
this.isStepLast = true;
this.reload();
} else {
this.isStepLast = false;
}
} else {
if (this.displayMoves.length <= index) {
this.isStepLast = true;
this.reload();
} else {
this.isStepLast = false;
}
}
let movePos = 0;
if (index <= 0) {
movePos = 0;
} else {
movePos = index - 1;
}
this.changeBoardState(this.displayMoves[index]?.fen);
this.changeBoardState(this.displayMoves[movePos]?.fen);
if (this.isNearBottom) {
this.scrollToBottom();
}
Expand All @@ -430,7 +454,7 @@ export class PlayComponent implements OnInit {
}

private scrollToBottom(): void {
this.scrollContainer = this.scrollFrame.nativeElement;
this.scrollContainer = this.scrollFrame?.nativeElement;
this.scrollContainer?.scroll({
top: this.scrollContainer?.scrollHeight,
left: 0,
Expand Down
38 changes: 29 additions & 9 deletions middlewareNode/routes/meetings.js
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,6 @@ router.post("/queue", passport.authenticate("jwt"), async (req, res) => {
// @access Public with jwt Authentication
router.post("/pairUp", passport.authenticate("jwt"), async (req, res) => {
try {
console.log("pairup api called");
const { role, username, firstName, lastName } = req.user;
let studentInfo = {};
let mentorInfo = {};
Expand All @@ -246,14 +245,12 @@ router.post("/pairUp", passport.authenticate("jwt"), async (req, res) => {
{},
{ sort: { created_at: 1 } }
);
console.log("waitingQueuestudent: ", waitingQueue);
} else if (role === "mentor") {
waitingQueue = await waitingStudents.findOne(
{},
{},
{ sort: { created_at: 1 } }
);
console.log("waitingQueuementor: ", waitingQueue);
} else {
return res
.status(404)
Expand All @@ -268,7 +265,6 @@ router.post("/pairUp", passport.authenticate("jwt"), async (req, res) => {
}

const response = await inMeeting(role, username); //Check if user is in a meeting
console.log("response: ", response);

//Check if the user waiting for a game is in a meeting already
const secondResponse = await inMeeting(
Expand Down Expand Up @@ -447,7 +443,6 @@ router.delete("/dequeue", passport.authenticate("jwt"), async (req, res) => {

//Async function to check whether a username is in a current meeting
const inMeeting = async (role, username) => {
console.log("in meeting function called");
let filters = { CurrentlyOngoing: true };
if (role === "student") {
filters.studentUsername = username;
Expand All @@ -457,7 +452,6 @@ const inMeeting = async (role, username) => {
return "Please be either a student or a mentor.";
}
const foundMeeting = await meetings.find(filters);
console.log("foundMeeting: ", foundMeeting);
if (foundMeeting.length !== 0) {
await deleteUser(role, username);
return foundMeeting;
Expand Down Expand Up @@ -513,7 +507,6 @@ const getMoves = async (meetingId) => {
meetingId: meetingId,
CurrentlyOngoing: true,
});
console.log("moves", moves);
return moves;
};
//Async function to store moves in the database
Expand All @@ -529,13 +522,20 @@ router.post("/boardState", passport.authenticate("jwt"), async (req, res) => {
try {
const { meetingId, fen, pos, image } = req.query;
let meeting = await getMoves(meetingId);
let oldMovesArr = meeting.moves;
let moveArray = meeting.moves;
let oldMovesArr = [];
let moveArrayLength = moveArray.length;
if (moveArray.length > 0) {
oldMovesArr = moveArray[moveArrayLength - 1];
moveArrayLength = moveArray.length - 1;
}
if (
oldMovesArr.length === 0 ||
oldMovesArr[oldMovesArr.length - 1]?.fen !== fen
) {
fen && oldMovesArr.push({ fen, pos, image });
let updatedMove = await updateMoves(meetingId, oldMovesArr);
moveArray[moveArrayLength] = oldMovesArr;
let updatedMove = await updateMoves(meetingId, moveArray);
res.status(200).send(updatedMove);
} else {
res.status(202).send(oldMovesArr);
Expand All @@ -557,4 +557,24 @@ router.get("/getBoardState", passport.authenticate("jwt"), async (req, res) => {
}
});

router.post(
"/newBoardState",
passport.authenticate("jwt"),
async (req, res) => {
try {
const { meetingId } = req.query;
let meeting = await getMoves(meetingId);
let moveArray = meeting.moves;
let oldMovesArr = [];
let moveArrayLength = moveArray.length;
moveArray[moveArrayLength] = oldMovesArr;
let updatedMove = await updateMoves(meetingId, moveArray);
res.status(200).send(updatedMove);
} catch (error) {
console.error(error.message);
res.status(500).json("Server error");
}
}
);

module.exports = router;