Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Https connections on weekend main branch #14

Merged
merged 22 commits into from
Nov 13, 2023
Merged
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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,6 @@
./backend/node_modules
./frontend/node_modules
./data/*
data/
certificate.cert
certificate.key
10 changes: 9 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ endif

### ### RULES ### ###
#Build changes or all if nothing is builded and run
all: ip
all: ip certs
@mkdir -p backend frontend data $(DB_D) data/myadmin data/mysql data/pgadmin
ifeq ($(OS), Darwin)
-@bash -c "chmod 600 data/pgadmin/pgadmin4.db || chown -R ${USER}:2021_heilbronn data/pgadmin"
Expand All @@ -42,6 +42,12 @@ else
sed -i -e 's/^VUE_APP_BACKEND_IP=.*/VUE_APP_BACKEND_IP=127.0.0.1/' ./frontend/.env
endif

# create https certificates
certs:
@if [ ! -e ./certificate.cert ] || [ ! -e ./certificate.key ] ; then \
openssl req -newkey rsa:4096 -x509 -sha256 -days 365 -nodes -out ./certificate.cert -keyout ./certificate.key -subj "/C=DE/ST=Baden-Wuerttemberg/L=Heilbronn/O=42Heilbronn/"; \
fi

up: all

down: stop
Expand Down Expand Up @@ -86,3 +92,5 @@ endif

#stop all containers, force rebuild and start it
re: stop fclean all

.phony: sclean clean status build check down up ip postgre
18 changes: 9 additions & 9 deletions NOTICE
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
//PGADMIN
http://localhost:5050/
https://localhost:5050/

//Swagger
http://localhost:9090/swagger/
http://localhost:3000/api/docs
http://localhost:9090
https://localhost:9090/swagger/
https://localhost:3000/api/docs
https://localhost:9090

//Frontend
http://localhost:8080
https://localhost:8080



//PHPMYADMIN
http://localhost:7070
https://localhost:7070


//Other Ports:

//API-BACKEND
http://localhost:3000
https://localhost:3000

//POSTGRESQL
http://localhost:5432
https://localhost:5432



//MYSQL
http://localhost:3306
https://localhost:3306
14 changes: 0 additions & 14 deletions backend/Dockerfile

This file was deleted.

13 changes: 0 additions & 13 deletions backend/entrypoint.sh

This file was deleted.

1 change: 0 additions & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,3 @@
"testEnvironment": "node"
}
}

2 changes: 1 addition & 1 deletion backend/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@ import { TournamentModule } from './tournament/tournament.module';
TournamentModule],
controllers: [AppController, TournamentController],
providers: [AppService, TournamentService],

})
export class AppModule {}
18 changes: 9 additions & 9 deletions backend/src/game/GameState.ts
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

user.dot vs auth.dto both necessary? shouldn't we have only one?

Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Injectable } from '@nestjs/common';
import { UserDto } from '../user/dto';
import { User } from 'src/user/User';
import { sharedEventEmitter } from './game.events';
import { GameService } from './game.service';

Expand All @@ -8,8 +8,8 @@ export class GameState {
gameId: string;
intervalId: NodeJS.Timeout | null;

user1: UserDto;
user2: UserDto;
user1: User;
user2: User;
scorePlayer1: number;
scorePlayer2: number;
winningPlayer: String;
Expand Down Expand Up @@ -109,26 +109,26 @@ export class GameState {
return id;
}

movePaddleUp(playerNumber: number) {
if (playerNumber == 1) {
movePaddleUp(player: User) {
if (player === this.user1) {
if (this.leftPosition > 0) {
this.leftPosition -= 10;
}
}
else if (playerNumber == 2) {
else if (player === this.user2) {
if (this.rightPosition > 10) {
this.rightPosition -= 10;
}
}
}

movePaddleDown(playerNumber: number) {
if (playerNumber == 1) {
movePaddleDown(player: User) {
if (player === this.user1) {
if (this.leftPosition + this.paddlesHeight < this.fieldHeight) {
this.leftPosition += 10;
}
}
else if (playerNumber == 2) {
else if (player === this.user2) {
if (this.rightPosition + this.paddlesHeight < this.fieldHeight) {
this.rightPosition += 10;
}
Expand Down
48 changes: 23 additions & 25 deletions backend/src/game/game.gateway.ts
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cool stuff here would be great to review together and learn from it

Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,18 @@ import {
WebSocketServer,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { ConsoleLogger, OnModuleInit } from '@nestjs/common';
import { GameService } from './game.service';
import { UserDto } from 'src/user/dto';
import { User } from 'src/user/User';
import { GameState} from './GameState';
import * as https from 'https';
import * as fs from 'fs';

// can enter a port in the brackets
@WebSocketGateway()
export class GameGateway implements OnModuleInit {
@WebSocketGateway({ server: https.createServer({
key: fs.readFileSync('/certificates/certificate.key'),
cert: fs.readFileSync('/certificates/certificate.cert'),
})})
export class GameGateway {
@WebSocketServer()
server: Server;

Expand All @@ -40,19 +44,13 @@ export class GameGateway implements OnModuleInit {
});
}

/* New client connected. */
onModuleInit() {
this.server.on('connection', (socket) => {
console.log('Client connected:', socket.id);
handleConnection(socket: any) {
console.log("Client connected:", socket.id);

// save new user to users array in GameService
const user = new UserDto();
user.socket = socket;
this.gameService.users.set(socket.id, user);
});
this.server.on('close', () => {
console.log('Client disconnected');
});
// MISSING: TOKEN authentication, database pull and check if user is already connected
const user = new User();
user.socket = socket;
this.gameService.users.set(socket.id, user);
}

handleDisconnect(socket: any) {
Expand All @@ -62,9 +60,9 @@ export class GameGateway implements OnModuleInit {
const user = this.gameService.users.get(socket.id);
if (user && user.inGame) {
// get the active game of the user
const activeGameId = user.gamesPlayed[user.gamesPlayed.length - 1];
const activeGame = user.gamesPlayed[user.gamesPlayed.length - 1];
// stop the game
if (activeGameId) this.gameService.stopGame(activeGameId);
if (activeGame) this.gameService.stopGame(activeGame);
}
// delete the socket id
user.socket = null;
Expand Down Expand Up @@ -132,19 +130,19 @@ export class GameGateway implements OnModuleInit {

// listen for paddle updates
@SubscribeMessage('paddleUp')
leftPaddleUp(@MessageBody() { gameId, playerNumber }: { gameId: string; playerNumber: number }) {

if (gameId) {
const game = this.gameService.paddleUp(gameId, playerNumber);
leftPaddleUp(@MessageBody() { gameId }: { gameId: string }, @ConnectedSocket() socket: Socket) {
const user = this.gameService.users.get(socket.id);
if (gameId && user) {
const game = this.gameService.paddleUp(gameId, user);
if (game) this.sendPaddleUpdate(game);
}
}

@SubscribeMessage('paddleDown')
PaddleDown(@MessageBody() { gameId, playerNumber }: { gameId: string; playerNumber: number }) {

PaddleDown(@MessageBody() { gameId }: { gameId: string }, @ConnectedSocket() socket: Socket) {
const user = this.gameService.users.get(socket.id);
if (gameId) {
const game = this.gameService.paddleDown(gameId, playerNumber);
const game = this.gameService.paddleDown(gameId, user);
if (game) this.sendPaddleUpdate(game);
}
}
Expand Down
55 changes: 33 additions & 22 deletions backend/src/game/game.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,29 @@ import { clearInterval } from 'timers';
import { sharedEventEmitter } from './game.events';
import { GameState } from './GameState';
import { Injectable } from '@nestjs/common';
import { UserDto } from 'src/user/dto';
import { User } from 'src/user/User';
import { Socket } from 'socket.io';

@Injectable()
export class GameService {
// user array
// should probably be saved elsewhere, idk
users: Map<string, UserDto> = new Map(); // socket.id -> user
queue: UserDto[] = [];
users: Map<string, User> = new Map(); // user.id -> user
games: Map<string, GameState> = new Map(); // gamestate.gameid -> gamestate
queue: User[] = [];

/* A new user is added to the game queue */
addToQueue(socket: Socket) {
// find the matching user
const user = this.users.get(socket.id);

// check if user already is in queue
// REPLACE socket id with working user id
if (!user || this.queue.find(queuedUser => queuedUser.socket.id === user.socket.id)) return;
// check if user already is in an active game
if (user.inGame) {
console.log("Client is already playing");
return;
}
if (!user || this.queue.find(queuedUser => queuedUser.id === user.id)) return;
// check if user already is in an active game
if (user.inGame) {
console.log("Client is already playing");
return;
}

console.log(`Client ${socket.id} entered game queue`);
this.queue.push(user);
Expand All @@ -36,8 +35,10 @@ export class GameService {

/* Remove a user from the game queue */
removeFromQueue(socket: Socket) {
// Find the user in the queue based on socket.id
const userToRemove = this.queue.find(queuedUser => queuedUser.socket.id === socket.id);
// find the matching user
const user = this.users.get(socket.id);
// Find the user in the queue
const userToRemove = this.queue.find(queuedUser => queuedUser.id === user.id);

if (userToRemove) {
// Remove the user from the queue
Expand All @@ -63,8 +64,9 @@ export class GameService {
game.user1.inGame = true;
game.user2.inGame = true;

game.user1.gamesPlayed.push(game.gameId);
game.user2.gamesPlayed.push(game.gameId);
// REPLACE this with a database call
game.user1.gamesPlayed.push(game); // this is a reference, not a new object
game.user2.gamesPlayed.push(game);

this.games.set(game.gameId, game);
sharedEventEmitter.emit('prepareGame', game);
Expand All @@ -77,13 +79,20 @@ export class GameService {
sharedEventEmitter.emit('startGame', game);
}

stopGame(gameId: string) {
// search the right game
const game = this.games.get(gameId);
// function overload
stopGame(gameState: GameState): void;
stopGame(gameId: string): void;
stopGame(arg: GameState | string): void {
let game: GameState;

if (typeof arg === 'string') game = this.games.get(arg);
else game = arg;

if (!game) {
console.error('StopGame: Game not found.');
return;
}

console.log('Stopping game', game.gameId);
clearInterval(game.intervalId);
game.intervalId = null;
Expand All @@ -92,21 +101,23 @@ export class GameService {
if (game.user2) game.user2.inGame = false;

// save persistent game stuff to database here if you like
// this.games.delete(gameId);
this.games.delete(game.gameId); // this only deletes the reference
}

paddleUp(gameId: string, playerNumber: number) {
paddleUp(gameId: string, player: User) {
const game = this.games.get(gameId);

if (game && game.isRunning()) {
game.movePaddleUp(playerNumber);
game.movePaddleUp(player);
}
return game;
}

paddleDown(gameId: string, playerNumber: number) {
paddleDown(gameId: string, player: User) {
const game = this.games.get(gameId);

if (game && game.isRunning()) {
game.movePaddleDown(playerNumber);
game.movePaddleDown(player);
}
return game;
}
Expand Down
Loading