Merge branch 'reborn' into phoenix

This commit is contained in:
Lara REALI 2023-06-28 16:37:14 +02:00
commit 3eca00e7af
22 changed files with 88 additions and 437 deletions

View File

@ -6,7 +6,7 @@
/* By: apommier <apommier@student.42.fr> +#+ +:+ +#+ */ /* By: apommier <apommier@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2023/06/17 01:00:00 by apommier #+# #+# */ /* Created: 2023/06/17 01:00:00 by apommier #+# #+# */
/* Updated: 2023/06/26 10:16:19 by apommier ### ########.fr */ /* Updated: 2023/06/28 13:57:06 by apommier ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
@ -198,6 +198,24 @@ export class AppController {
//======================================================================================================== //========================================================================================================
//======================================================================================================== //========================================================================================================
@UseGuards(JwtAuthGuard)
@Post('/addGame')
async addGame(@Request() req, @Body() data: any) {
const user = await this.userService.findOne(req.user.username);
user.gameSession += 1;
await this.userService.save(user);
}
@UseGuards(JwtAuthGuard)
@Post('/rmGame')
async removeGame(@Request() req, @Body() data: any) {
const user = await this.userService.findOne(req.user.username);
user.gameSession -= 1;
if (user.gameSession === 0)
user.status = 1;
await this.userService.save(user);
}
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Post('/win') @Post('/win')
async addWin(@Request() req, @Body() data: any) { async addWin(@Request() req, @Body() data: any) {

View File

@ -63,6 +63,7 @@ export class loginClass {
blocked: null, blocked: null,
photo: null, photo: null,
sessionNumber: 0, sessionNumber: 0,
gameSession: 0,
}; };
await this.usersService.create(user); await this.usersService.create(user);
} }

View File

@ -50,6 +50,9 @@ export class User {
@Column({ default: 0 }) @Column({ default: 0 })
sessionNumber: number; sessionNumber: number;
@Column({ default: 0 })
gameSession: number;
@Column({ default: 0 }) @Column({ default: 0 })
rank: number; rank: number;

View File

@ -1,14 +1,14 @@
REACT_APP_BASE_URL=localhost:8080 REACT_APP_BASE_URL=paul-f4Ar4s3:8080
REACT_APP_SOCKET_URL=localhost REACT_APP_SOCKET_URL=paul-f4Ar4s3
REACT_APP_API_SECRET=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 REACT_APP_API_SECRET=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
REACT_APP_CLIENT_UID=u-s4t2ud-6d29dfa49ba7146577ffd8bf595ae8d9e5aaa3e0a9615df18777171ebf836a41 REACT_APP_CLIENT_UID=u-s4t2ud-2bd3c5d4f41e776f2e3d5d699d2a8421f6d0c0468ec882516d9ca89b0c211789
# REACT_APP_BASE_URL=92.143.191.152 # REACT_APP_BASE_URL=92.143.191.152
# REACT_APP_BASE_URL=192.168.1.19 # REACT_APP_BASE_URL=192.168.1.19
REACT_APP_INTRA_URL="https://api.intra.42.fr/oauth/authorize?client_id=u-s4t2ud-6d29dfa49ba7146577ffd8bf595ae8d9e5aaa3e0a9615df18777171ebf836a41&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fapi%2Fauth%2Flogin&response_type=code" REACT_APP_INTRA_URL="https://api.intra.42.fr/oauth/authorize?client_id=u-s4t2ud-2bd3c5d4f41e776f2e3d5d699d2a8421f6d0c0468ec882516d9ca89b0c211789&redirect_uri=http%3A%2F%2Fpaul-f4Ar4s3%3A8080%2Fapi%2Fauth%2Flogin&response_type=code"
# REACT_APP_BASE_URL=92.143.191.152 # REACT_APP_BASE_URL=92.143.191.152
# REACT_APP_BASE_URL=192.168.1.19 # REACT_APP_BASE_URL=192.168.1.19

View File

@ -17,6 +17,7 @@ export interface User {
friends: string[]; friends: string[];
blocked: string[]; blocked: string[];
sessionNumber: number; sessionNumber: number;
gameSession : number;
} }
export interface Conv { export interface Conv {

View File

@ -1,4 +1,4 @@
import React, { useEffect } from "react"; import React, { useEffect, useState } from "react";
import { Routes, Route, Navigate } from 'react-router-dom'; import { Routes, Route, Navigate } from 'react-router-dom';
import HomeLogin from "../pages/LoginButton.tsx"; import HomeLogin from "../pages/LoginButton.tsx";
@ -23,16 +23,17 @@ import api from "../script/axiosApi.tsx"
function AnimatedRoute() { function AnimatedRoute() {
useEffect(() => { useEffect(() => {
const handleBeforeUnload = async (event: { preventDefault: () => void; returnValue: string; }) => { // const handleBeforeUnload = async (event: { preventDefault: () => void; returnValue: string; }) => {
console.log("git ") // console.log("git ")
if (!localStorage.getItem('token')) // if (!localStorage.getItem('token'))
return; // return;
try { // try {
await api.post("/quit"); // await api.post("/quit");
} catch (err) { // // navigator.sendBeacon("http://" + process.env.REACT_APP_BASE_URL + "/api/quit", {username: user.username})
console.log(err); // } catch (err) {
} // console.log(err);
}; // }
// };
const handleLoad = async () => { const handleLoad = async () => {
if (!localStorage.getItem('token')) if (!localStorage.getItem('token'))
@ -45,9 +46,17 @@ function AnimatedRoute() {
}; };
handleLoad(); handleLoad();
window.addEventListener('beforeunload', handleBeforeUnload);
window.addEventListener("beforeunload", async (event) => {
await api.post("/quit");
});
window.addEventListener("unload", async (event) => {
await api.post("/quit");
});
return () => { return () => {
window.removeEventListener('beforeunload', handleBeforeUnload); // window.removeEventListener('beforeunload', handleBeforeUnload);
}; };
}, []); }, []);

View File

@ -1,5 +1,4 @@
import React from 'react'; import React from 'react';
// import './Header.scss';
function Footer() { function Footer() {
return ( return (

View File

@ -4,23 +4,13 @@ import {Link} from 'react-router-dom';
import DefaultPicture from '../assets/profile.jpg' import DefaultPicture from '../assets/profile.jpg'
import { motion, AnimatePresence } from 'framer-motion' import { motion, AnimatePresence } from 'framer-motion'
import Modal from './Sidebar/Modal.tsx'; import Modal from './Sidebar/Modal.tsx';
import YellowAlert from './Alert/YellowAlert.tsx';
import '../styles/Header.css'; import '../styles/Header.css';
import api from '../script/axiosApi.tsx'; import api from '../script/axiosApi.tsx';
import { MdQrCodeScanner } from 'react-icons/md';
import { GiWingedSword, GiCrownedSkull } from 'react-icons/gi';
function Header() { function Header() {
// const [sidebar, setSidebar] = useState(false);
// const showSidebar = () => setSidebar(!sidebar);
const [modalOpen, setModalOpen] = useState(false); const [modalOpen, setModalOpen] = useState(false);
const close = () => setModalOpen(false); const close = () => setModalOpen(false);
const open = () => setModalOpen(true); const open = () => setModalOpen(true);
const [success, setSuccess] = useState([]);
const [profilePicture, setProfilePicture] = useState(''); const [profilePicture, setProfilePicture] = useState('');
useEffect(() => { useEffect(() => {
@ -29,9 +19,6 @@ function Header() {
const user = await api.get("/profile"); const user = await api.get("/profile");
const pic = await api.post("/getPicture", {username: user.data.username}) const pic = await api.post("/getPicture", {username: user.data.username})
setProfilePicture(pic.data); setProfilePicture(pic.data);
// console.log("test ===", user.data)
setSuccess(user.data);
// console.log(`profile pic222= ${pic.data}`)
} catch (error) { } catch (error) {
console.error('Error fetching profile picture:', error); console.error('Error fetching profile picture:', error);
} }
@ -54,9 +41,7 @@ function Header() {
<div> <div>
{profilePicture ? ( {profilePicture ? (
// <img className='Header-pic' src={profilePicture} alt="Profile Picture" />
<img className='Header-pic' src={`data:image/jpeg;base64,${profilePicture}`} /> <img className='Header-pic' src={`data:image/jpeg;base64,${profilePicture}`} />
// <img className='Header-pic' src={`data:image/jpeg;base64,${profilePicture.data}`} alt="Profile Picture" />
) : ( ) : (
<img className='Header-pic' src={DefaultPicture} alt="Default Profile Picture" /> <img className='Header-pic' src={DefaultPicture} alt="Default Profile Picture" />
)} )}

View File

@ -110,7 +110,6 @@ const Modal = ({handleClose}: ModalProps) => {
members: selectedOptions, members: selectedOptions,
} }
try{ try{
// test
await api.post("/conv", data); await api.post("/conv", data);
handleClose(); handleClose();
window.location.reload(); window.location.reload();

View File

@ -1,7 +1,4 @@
import { AnimatePresence, motion } from "framer-motion" import { AnimatePresence, motion } from "framer-motion"
// import Backdrop from "../Sidebar/Backdrop"
import { Link } from 'react-router-dom';
// import { UserProfile } from "../../DataBase/DataUserProfile";
import { useState } from 'react'; import { useState } from 'react';
import "../../styles/Profile.css" import "../../styles/Profile.css"
@ -21,14 +18,7 @@ const dropIn = {
}, },
} }
// const changeName = ({handleclose, name}) => {
// return (
// UserProfile.UserName = name
// )
// }
const ModalEdit = () => { const ModalEdit = () => {
// let new_name = "";
const [nickname, setNickname] = useState(""); const [nickname, setNickname] = useState("");
const [errTaken, setErrTaken] = useState(false); const [errTaken, setErrTaken] = useState(false);
const closeTaken = () => setErrTaken(false); const closeTaken = () => setErrTaken(false);
@ -37,56 +27,28 @@ const ModalEdit = () => {
const handler = (e: { target: { value: React.SetStateAction<string>; }; }) => { const handler = (e: { target: { value: React.SetStateAction<string>; }; }) => {
setNickname(e.target.value); setNickname(e.target.value);
console.log("testeeeee")
const postNickname = async () => {
// try{
// await api.post("/nickname", {nickname: nickname})
// // setUser(tmpUser.data);
// // setIsLoading(false)
// }
// catch(err){
// console.log(err);
// }
};
postNickname();
} }
const handlePostNickname = async () => { const handlePostNickname = async () => {
console.log("nickname=", nickname) console.log("nickname=", nickname)
try { try {
// console.log("cest ici = ",ret);
// if (!ret)
// console.log("test ret =", ret.data);
if (nickname.length > 3) { if (nickname.length > 3) {
const ret = await api.post("/nickname", { nickname: nickname }); const ret = await api.post("/nickname", { nickname: nickname });
if (ret.data) { if (ret.data) {
console.log("ici error = ", ret.data);
window.location.reload(); window.location.reload();
} }
else { else {
console.log("nickname already set = ", ret.data);
setErrTaken(true); setErrTaken(true);
} }
} }
else if (nickname.length < 3) else if (nickname.length < 3)
{
setErrTooShort(true); setErrTooShort(true);
}
// setUser(tmpUser.data);
// setIsLoading(false)
} }
catch (err) { catch (err) {
console.log(err); console.log(err);
} }
} }
// function handleClose(){
// //do nothing
// }
return ( return (
<motion.div <motion.div
className="modal" className="modal"
@ -99,7 +61,6 @@ const ModalEdit = () => {
<div> <div>
<div className="button" onClick={handlePostNickname}> <div className="button" onClick={handlePostNickname}>
change change
{/* <Link className="button" to={""}>change</Link> */}
</div> </div>
<AnimatePresence initial={false} onExitComplete={() => null}> <AnimatePresence initial={false} onExitComplete={() => null}>
{ {

View File

@ -16,10 +16,6 @@ function Logout(){
logout(); logout();
localStorage.clear(); localStorage.clear();
const path = 'http://' + process.env.REACT_APP_BASE_URL + '/'; const path = 'http://' + process.env.REACT_APP_BASE_URL + '/';
// history(path, { replace: true });
// window.location.replace(path);
// window.history.pushState({}, '', path);
window.history.pushState({}, '', path); window.history.pushState({}, '', path);
window.location.reload(); window.location.reload();
return (<></>) return (<></>)

View File

@ -1,50 +1,5 @@
// import PropTypes from "prop-types"
// import styled from 'styled-components';
// import '../DataBase/DummyDBWinLoss.js'
// import '../DataBase/DataProfileUser.js'
// import { DBWinLoss } from '../../DataBase/DummyDBWinLoss.js';
import '../../styles/Win_Loss.css' import '../../styles/Win_Loss.css'
import { User, Matchlog } from "../../../interfaces.tsx" import { User, Matchlog } from "../../../interfaces.tsx"
// import { UserProfile } from '../../DataBase/DataUserProfile';
// import color from '../../utils/style/color.js';
// const CardWrapper = styled.div`
// display: flex;
// flex-direction: column;
// padding: 15px;
// background-color: black;
// border-radius: 30px;
// width: 350px;
// transition: 200ms;
// margin-top: 50px;
// &:hover {
// cursor: pointer;
// box-shadow: 2px 2px 10px #b6b6b6;
// }
// `
// const CardLabel1 = styled.h1`
// color: #5843e4;
// // font-size: 22px;
// font-weight: bold;
// margin-bottom: 25px;
// `
// const CardLabel2 = styled.span`
// color: #5843e4;
// font-size: 22px;
// font-weight: bold;
// display: flex;
// flex-direction: column;
// `
// const CardImage = styled.img`
// heigh: 80px;
// width: 80px;
// border-radius: 50%;
// `
import React, { useState, useEffect, useRef } from "react"; import React, { useState, useEffect, useRef } from "react";
import { useParams } from 'react-router-dom'; import { useParams } from 'react-router-dom';
import api from '../../script/axiosApi.tsx'; import api from '../../script/axiosApi.tsx';
@ -61,7 +16,6 @@ function WinLoss() {
useEffect(()=> { useEffect(()=> {
const getUser = async ()=>{ const getUser = async ()=>{
try{ try{
// const tmpUser = await api.get("/profile")
console.log("username win loss=", username) console.log("username win loss=", username)
let tmpUser; let tmpUser;
let tmpHistory; let tmpHistory;
@ -87,23 +41,10 @@ function WinLoss() {
getUser(); getUser();
}, []) }, [])
// console.log(`user= ${user.children}`)
return ( return (
// <div>
// {isLoading ? (
// <h1>Loading...</h1>
// ) : (
// <h1>{user.username}</h1>
// )}
// </div>
<div className='tab'> <div className='tab'>
{isLoading || !history || !user ? ( {isLoading || !history || !user ? (
<h1>Loading...</h1> <h1>Loading...</h1>
// <span>Loading...</span>
) : ( ) : (
<div className='scroll'> <div className='scroll'>
<h2 className='title'>Match history {user.win}/{user.loss}</h2> <h2 className='title'>Match history {user.win}/{user.loss}</h2>
@ -111,41 +52,17 @@ function WinLoss() {
return ( return (
<div key={index} className='elements'> <div key={index} className='elements'>
<li key={index}> <li key={index}>
{/* <h4 className='content'>{c.id}</h4> */}
<div className='content2nd'> <div className='content2nd'>
<h4 className='me'>{user.username}</h4> <h4 className='score'>{c.myScore} - {c.opScore} </h4> <h4 className="opponent">{c.opponent}</h4> <h4 className='me'>{user.username}</h4> <h4 className='score'>{c.myScore} - {c.opScore} </h4> <h4 className="opponent">{c.opponent}</h4>
</div> </div>
{/* <h4 className='content'>{c.openent}</h4> */}
</li> </li>
</div> </div>
) )
})} })}
</div> </div>
// <div>
// <h1>User: {user.name}</h1>
// <div>
// <h2>Children:</h2>
// {history.map((child) => (
// <div key={child.id}>
// <p>Child ID: {child.id}</p>
// <p>Child Name: {child.name}</p>
// {/* Render other child properties as needed */}
// </div>
// ))}
// </div>
// </div>
)} )}
</div> </div>
) )
} }
// Card.propTypes = {
// label: PropTypes.string,
// title: PropTypes.string.isRequired,
// picture: PropTypes.string,
// }
export default WinLoss export default WinLoss

View File

@ -1,4 +1,4 @@
import React, { MouseEventHandler, ReactNode, HTMLAttributes } from "react"; import React, { ReactNode } from "react";
import { motion } from "framer-motion" import { motion } from "framer-motion"
import "../../styles/Header.css" import "../../styles/Header.css"

View File

@ -3,7 +3,6 @@ import api from '../script/axiosApi.tsx';
const DoubleAuth = () => { const DoubleAuth = () => {
// const [imageSrc, setImageSrc] = useState('');
const [imageSrc, setImageSrc] = useState<string | ArrayBuffer | null>(''); const [imageSrc, setImageSrc] = useState<string | ArrayBuffer | null>('');
useEffect(() => { useEffect(() => {

View File

@ -3,7 +3,7 @@ import DrawCanvas from './canvas.tsx';
import queryString from 'query-string'; import queryString from 'query-string';
import '../styles/field.css'; import '../styles/field.css';
import React from 'react'; import React from 'react';
import api from '../script/axiosApi.tsx';
interface GameProps { interface GameProps {
privateParty: boolean, privateParty: boolean,
@ -13,6 +13,34 @@ interface GameProps {
function Field() function Field()
{ {
useEffect(() => {
const addGameSession = async () => {
try {
await api.post("/addGame");
} catch (err) {
console.log(err);
}
};
addGameSession();
const handleBeforeUnload = async () => {
try {
await api.post("/rmGame");
} catch (err) {
console.log(err);
}
};
window.addEventListener('beforeunload', handleBeforeUnload);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
};
}, []);
useEffect(() => { useEffect(() => {
const queryParams = queryString.parse(window.location.search); const queryParams = queryString.parse(window.location.search);

View File

@ -6,7 +6,7 @@
/* By: apommier <apommier@student.42.fr> +#+ +:+ +#+ */ /* By: apommier <apommier@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2023/06/09 08:19:04 by apommier #+# #+# */ /* Created: 2023/06/09 08:19:04 by apommier #+# #+# */
/* Updated: 2023/06/26 07:06:35 by apommier ### ########.fr */ /* Updated: 2023/06/26 11:31:57 by apommier ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
@ -41,14 +41,11 @@ function Profile () {
const [profilePicture, setProfilePicture] = useState(''); const [profilePicture, setProfilePicture] = useState('');
const handleFileChange = async (event: { target: { files: any; }; }) => { const handleFileChange = async (event: { target: { files: any; }; }) => {
const photo = (event.target.files[0]); const photo = (event.target.files[0]);
console.log("file selected")
if (photo) { if (photo) {
console.log("selected photo")
const formData = new FormData(); const formData = new FormData();
formData.append('photo', photo); formData.append('photo', photo);
try { try {
await api.post('/picture', formData); await api.post('/picture', formData);
console.log('File uploaded successfully');
window.location.reload(); window.location.reload();
} catch (error) { } catch (error) {
setError(true); setError(true);

View File

@ -6,7 +6,6 @@ function HomeLogin()
{ {
const handleButtonClick = () => { const handleButtonClick = () => {
const token = localStorage.getItem('token') const token = localStorage.getItem('token')
console.log(`token type= ${typeof token}`);
if (token !== null && typeof token === 'string') if (token !== null && typeof token === 'string')
return ; return ;
let path = process.env.REACT_APP_INTRA_URL || ""; let path = process.env.REACT_APP_INTRA_URL || "";

View File

@ -1,4 +1,4 @@
import { useEffect } from 'react'; // import { useEffect } from 'react';
import api from '../script/axiosApi.tsx'; import api from '../script/axiosApi.tsx';
import io from 'socket.io-client'; import io from 'socket.io-client';
@ -10,51 +10,20 @@ interface GameProps {
function DrawCanvas(option: number, gameParam: GameProps) { function DrawCanvas(option: number, gameParam: GameProps) {
useEffect(() => {
const handleBeforeUnload = async (event: { preventDefault: () => void; returnValue: string; }) => {
try {
await api.post("/status", {status: 1});
} catch (err) {
console.log(err);
}
};
window.addEventListener('beforeunload', handleBeforeUnload);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
};
}, []);
console.log(`option= ${option}`);
const superpowerModifier = option & 1; // Retrieves the superpower modifier const superpowerModifier = option & 1; // Retrieves the superpower modifier
const obstacleModifier = (option >> 1) & 1; // Retrieves the obstacle modifier const obstacleModifier = (option >> 1) & 1; // Retrieves the obstacle modifier
const speedModifier = (option >> 2) & 1; // Retrieves the speed modifier const speedModifier = (option >> 2) & 1; // Retrieves the speed modifier
console.log(`superpowerModifier = ${superpowerModifier}`);
console.log(`obstacleModifier = ${obstacleModifier}`);
console.log(`speedModifier = ${speedModifier}`);
function launchGame() function launchGame()
{ {
if (!gameParam.privateParty) if (!gameParam.privateParty)
{
console.log("laucnh matchmaking")
matchmaking(); matchmaking();
}
else if (!gameParam.gameId) else if (!gameParam.gameId)
{
console.log("laucnh private")
privateParty(); privateParty();
}
else else
{
console.log("join private")
joinPrivateParty(); joinPrivateParty();
}
} }
console.log("start function");
const canvas = document.getElementById('myCanvas') as HTMLCanvasElement | null; const canvas = document.getElementById('myCanvas') as HTMLCanvasElement | null;
if (!canvas) if (!canvas)
return ; return ;
@ -131,13 +100,9 @@ function DrawCanvas(option: number, gameParam: GameProps) {
socket.on('pong:win', async () => { socket.on('pong:win', async () => {
myScore = maxScore; myScore = maxScore;
console.log("instant win opponent disconnect")
console.log("after request1")
await api.post('/status', {status: 1}); await api.post('/status', {status: 1});
console.log("after request2")
running = false; running = false;
socket.emit('pong:disconnect', {id: myId}); socket.emit('pong:disconnect', {id: myId});
console.log("before reload")
return ; return ;
}); });
@ -152,19 +117,13 @@ socket.on('pong:privateId', async (data) => {
}); });
socket.on('pong:gameId', async (data) => { socket.on('pong:gameId', async (data) => {
console.log("gameId received");
gameId = data.gameId; gameId = data.gameId;
console.log("gameid = ", gameId);
console.log("data gameid = ", data);
try { try {
let response = await api.get('/profile'); let response = await api.get('/profile');
const myName = response.data.username; const myName = response.data.username;
response = await api.get('/rank'); response = await api.get('/rank');
await api.post('/status', {status: 2}); await api.post('/status', {status: 2});
opRank = response.data opRank = response.data
console.log(`rank= ${opRank}`);
console.log(`myname= ${myName}`);
const info = { const info = {
id: myId, id: myId,
@ -173,18 +132,11 @@ socket.on('pong:gameId', async (data) => {
rank: opRank, rank: opRank,
}; };
console.log("emit to name");
socket.emit('pong:name', info); socket.emit('pong:name', info);
if (data.id === myId) if (data.id === myId)
{
console.log("myId= true")
vX = 0.0005; vX = 0.0005;
}
else else
{
console.log("myId= false")
vX = -0.0005; vX = -0.0005;
}
} catch (error) { } catch (error) {
console.log(error); console.log(error);
return; return;
@ -193,7 +145,6 @@ socket.on('pong:gameId', async (data) => {
socket.on('pong:name', (data) => { socket.on('pong:name', (data) => {
opName = data.name; opName = data.name;
console.log(`opponent Name= ${opName}`)
}); });
socket.on('connect', () => { socket.on('connect', () => {
@ -201,9 +152,7 @@ socket.on('connect', () => {
}); });
socket.on('pong:clientId', (data) => { socket.on('pong:clientId', (data) => {
console.log("receive id")
myId = data; myId = data;
console.log(`id is= ${myId}`)
launchGame(); launchGame();
}); });
@ -217,12 +166,10 @@ socket.on('pong:info', (data) => {
}); });
socket.on('pong:paddle', (data) => { socket.on('pong:paddle', (data) => {
console.log("paddle info receive")
oPaddleY = (data.paddleY / data.height) * canvas.height oPaddleY = (data.paddleY / data.height) * canvas.height
}); });
socket.on('pong:power', (data) => { socket.on('pong:power', (data) => {
console.log("paddle info receive")
oPaddleY = 0; oPaddleY = 0;
opPaddleHeight = canvas.height; opPaddleHeight = canvas.height;
@ -230,12 +177,10 @@ socket.on('pong:power', (data) => {
setTimeout(() => { setTimeout(() => {
opPaddleHeight = canvas.height * 0.25; opPaddleHeight = canvas.height * 0.25;
oPaddleY = canvas.height / 2 - paddleHeight / 2; oPaddleY = canvas.height / 2 - paddleHeight / 2;
console.log('Cinq secondes se sont écoulées.');
}, 5000); }, 5000);
}); });
socket.on('pong:point', (data) => { socket.on('pong:point', (data) => {
console.log("gain point");
myScore = data.point; myScore = data.point;
vX = -0.0005; vX = -0.0005;
vY = 0; vY = 0;
@ -244,7 +189,6 @@ socket.on('pong:point', (data) => {
}); });
socket.on('pong:hisPoint', (data) => { socket.on('pong:hisPoint', (data) => {
console.log("myPointawdawdawdawd point");
hisScore = data.point; hisScore = data.point;
vX = -0.0005; vX = -0.0005;
vY = 0; vY = 0;
@ -260,7 +204,6 @@ socket.on('pong:hisPoint', (data) => {
function matchmaking() function matchmaking()
{ {
console.log(`id ion matcj= ${myId}`)
const info = { const info = {
id: myId, id: myId,
option: option, option: option,
@ -270,7 +213,6 @@ socket.on('pong:hisPoint', (data) => {
function privateParty() function privateParty()
{ {
console.log(`id private party= ${myId}`)
const info = { const info = {
id: myId, id: myId,
option: option, option: option,
@ -280,7 +222,6 @@ socket.on('pong:hisPoint', (data) => {
function joinPrivateParty() function joinPrivateParty()
{ {
console.log(`id private party= ${myId}`)
const info = { const info = {
id: myId, id: myId,
gameId: gameParam.gameId, gameId: gameParam.gameId,
@ -311,7 +252,6 @@ socket.on('pong:hisPoint', (data) => {
{ {
if (!gameId || !canvas) if (!gameId || !canvas)
return ; return ;
console.log("send point");
const info = { const info = {
id: myId, id: myId,
gameId: gameId, gameId: gameId,
@ -391,7 +331,6 @@ socket.on('pong:hisPoint', (data) => {
function drawcenter() function drawcenter()
{ {
// ctx.restore();
if (!ctx || !canvas) if (!ctx || !canvas)
return ; return ;
ctx.fillStyle = 'white'; ctx.fillStyle = 'white';
@ -459,18 +398,14 @@ socket.on('pong:hisPoint', (data) => {
opRank: opRank, opRank: opRank,
}; };
await api.post('/loss', data); await api.post('/loss', data);
// await api.post('/status', {status: 1});
} }
//here
socket.emit('pong:disconnect', {id: myId}); socket.emit('pong:disconnect', {id: myId});
window.location.replace("http://" + process.env.REACT_APP_BASE_URL + "/pong"); window.location.replace("http://" + process.env.REACT_APP_BASE_URL + "/pong");
}; };
async function draw(timestamp: number) async function draw(timestamp: number)
{ {
console.log("turning, running= ", running);
if (!running) if (!running)
{ {
window.location.replace("http://" + process.env.REACT_APP_BASE_URL + "/pong") window.location.replace("http://" + process.env.REACT_APP_BASE_URL + "/pong")
@ -483,7 +418,6 @@ async function draw(timestamp: number)
} }
if (myScore === maxScore || hisScore === maxScore) if (myScore === maxScore || hisScore === maxScore)
{ {
console.log("maxScore!!!!")
const data = { const data = {
myScore: myScore, myScore: myScore,
opScore: hisScore, opScore: hisScore,
@ -495,14 +429,12 @@ async function draw(timestamp: number)
await api.post('/win', data); await api.post('/win', data);
await api.post('/status', {status: 1}); await api.post('/status', {status: 1});
socket.emit('pong:disconnect', {id: myId}); socket.emit('pong:disconnect', {id: myId});
console.log("send all ?? win");
} }
else else
{ {
await api.post('/loss', data); await api.post('/loss', data);
await api.post('/status', {status: 1}); await api.post('/status', {status: 1});
socket.emit('pong:disconnect', {id: myId}); socket.emit('pong:disconnect', {id: myId});
console.log("send loose");
} }
window.location.replace("http://" + process.env.REACT_APP_BASE_URL + "/pong"); window.location.replace("http://" + process.env.REACT_APP_BASE_URL + "/pong");
return ; return ;
@ -567,10 +499,7 @@ async function draw(timestamp: number)
if (ballY <= paddleY + paddleHeight + ballRadius && ballY >= paddleY - ballRadius)//touch paddle if (ballY <= paddleY + paddleHeight + ballRadius && ballY >= paddleY - ballRadius)//touch paddle
{ {
if (ballX + ballRadius > paddleX && ballX - ballRadius < paddleX + paddleWidth) if (ballX + ballRadius > paddleX && ballX - ballRadius < paddleX + paddleWidth)
{
console.log("hehe here")
ballX = paddleX + paddleWidth + ballRadius; ballX = paddleX + paddleWidth + ballRadius;
}
updateVector(); updateVector();
} }
send_info(); send_info();
@ -594,7 +523,6 @@ async function draw(timestamp: number)
{ {
if (ballY <= paddleY + paddleHeight + ballRadius && ballY >= paddleY - ballRadius) if (ballY <= paddleY + paddleHeight + ballRadius && ballY >= paddleY - ballRadius)
{ {
console.log('true hehe');
ballX = paddleX + paddleWidth + ballRadius; ballX = paddleX + paddleWidth + ballRadius;
updateVector(); updateVector();
return ; return ;
@ -607,11 +535,7 @@ async function draw(timestamp: number)
send_point(); send_point();
} }
if (ballX > (canvas.width * 1.2) && ballX - (vX * 2) > canvas.width) if (ballX > (canvas.width * 1.2) && ballX - (vX * 2) > canvas.width)
{
console.log("ball out win point pls")
send_my_point(); send_my_point();
}
} }
@ -672,7 +596,6 @@ async function draw(timestamp: number)
setTimeout(() => { setTimeout(() => {
paddleHeight = canvas.height * 0.25; paddleHeight = canvas.height * 0.25;
paddleY = canvas.height / 2 - paddleHeight / 2; paddleY = canvas.height / 2 - paddleHeight / 2;
console.log('Cinq secondes se sont écoulées.');
}, 5000); }, 5000);
date = new Date(); date = new Date();
lastPower = date.getTime(); lastPower = date.getTime();
@ -680,7 +603,6 @@ async function draw(timestamp: number)
}); });
requestAnimationFrame(draw); requestAnimationFrame(draw);
console.log("retuuuuuuuuuuurn")
return (stopDrawCanvas); return (stopDrawCanvas);
} }

View File

@ -11,20 +11,9 @@ function getToken() {
console.log(`getToken = ${getToken()}`) console.log(`getToken = ${getToken()}`)
console.log(`Bearer ${localStorage.getItem("token")}`) console.log(`Bearer ${localStorage.getItem("token")}`)
// const test = "192.168.1.19"
// const url = 'http://' + process.env.REACT_APP_BASE_URL + '/api'
// const url = 'http://' + test + '/api'
// console.log("url= ", url)
// console.log("test= ", test)
// console.log("env= ", process.env.REACT_APP_BASE_URL)
let api = axios.create({ let api = axios.create({
// baseURL: 'http://localhost/api',
baseURL: 'http://' + process.env.REACT_APP_BASE_URL + '/api', baseURL: 'http://' + process.env.REACT_APP_BASE_URL + '/api',
headers: { headers: {
// Authorization: `Bearer ${getToken()}`,
Authorization : `Bearer ${localStorage.getItem("token")}` Authorization : `Bearer ${localStorage.getItem("token")}`
}, },
withCredentials: true, withCredentials: true,

View File

@ -1,13 +0,0 @@
// export const login()
// {
// alert("Le bouton a été cliqué !");
// var formulaire = document.getElementById("loginForm");
// formulaire.submit();
// }
export const login = () => {
console.log('Hello from myFunction');
// alert("Le bouton a été cliqué !");
var formulaire = document.getElementById("loginForm");
formulaire.submit();
}

View File

@ -1,7 +0,0 @@
// function setupLogin()
// {
// // alert("Le bouton a été cliqué !");
// console.log('Hello from login42');
// }
// export default setupLogin;

View File

@ -1,11 +1,10 @@
import { useLocation } from 'react-router-dom'; import { useLocation } from 'react-router-dom';
import { useState, useEffect } from 'react' import { useState, useEffect } from 'react'
import queryString from 'query-string'; import queryString from 'query-string';
import api from "./axiosApi.tsx";
import axios from 'axios'; import axios from 'axios';
import React from 'react'; import React from 'react';
import {Matchlog, User} from "../../interfaces.tsx" import {User} from "../../interfaces.tsx"
function SuccessToken() { function SuccessToken() {
const location = useLocation(); const location = useLocation();
@ -41,14 +40,9 @@ function SuccessToken() {
}, [data]); }, [data]);
const handleKeyPress = async (e: { key: string; })=>{ const handleKeyPress = async (e: { key: string; })=>{
// console.log(`e in press= ${e.key}`)
if (e.key !== "Enter") if (e.key !== "Enter")
return ; return ;
try{ try{
console.log("code= ", code)
// const res = await api.post("/verifyOtp", {token: code})
const res = await axios({ const res = await axios({
method: 'POST', method: 'POST',
url: 'http://' + process.env.REACT_APP_BASE_URL + '/api/verifyOtp', url: 'http://' + process.env.REACT_APP_BASE_URL + '/api/verifyOtp',
@ -59,28 +53,13 @@ function SuccessToken() {
data: { token: code } data: { token: code }
}); });
console.log("res= ", res.data)
console.log("res= ", res)
if (res.data === 1) if (res.data === 1)
{ {
console.log("registered")
// history.push('/login')
localStorage.setItem('token', `${cleanData}`); localStorage.setItem('token', `${cleanData}`);
console.log(`prout token2= ${localStorage.getItem('token')}`);
window.location.replace("http://" + process.env.REACT_APP_BASE_URL + "/pong"); window.location.replace("http://" + process.env.REACT_APP_BASE_URL + "/pong");
// const path = 'http://' + process.env.REACT_APP_BASE_URL + '/';
// window.history.pushState({}, '', path);
// window.location.reload();
} }
else else
{
console.log("bad code") console.log("bad code")
//alert ?? retry
}
// redirect('/test')
} }
catch(err){ catch(err){
console.log(err) console.log(err)
@ -90,7 +69,6 @@ function SuccessToken() {
if (!user) { if (!user) {
// Render a loading indicator or return null while user is being fetched
return <h1>Loading...</h1>; return <h1>Loading...</h1>;
} }
if (!data) if (!data)
@ -98,9 +76,7 @@ function SuccessToken() {
const cleanData = data.slice(1, -1); // Declare cleanData here as well const cleanData = data.slice(1, -1); // Declare cleanData here as well
if (!user.otp_verified) { if (!user.otp_verified) {
console.log("false");
localStorage.setItem('token', `${cleanData}`); localStorage.setItem('token', `${cleanData}`);
console.log(`prout token2= ${localStorage.getItem('token')}`);
window.location.replace("http://" + process.env.REACT_APP_BASE_URL + "/pong"); window.location.replace("http://" + process.env.REACT_APP_BASE_URL + "/pong");
return null; // or return a message or component indicating not verified return null; // or return a message or component indicating not verified
} }
@ -121,131 +97,3 @@ function SuccessToken() {
} }
export default SuccessToken; export default SuccessToken;
// function SuccessToken() {
// const location = useLocation();
// const { data } = queryString.parse(location.search);
// if ( !data)
// {
// console.log("no data")
// return ;
// }
// const cleanData = data.slice(1, -1);
// const [code, setCode] = useState('');
// const [user, setUser] = useState(false);
// useEffect(()=> {
// const getUser = async ()=>{
// try {
// // const tmpUser = await api.get("/profile");
// const tmpUser = await axios({
// method: 'GET',
// url: 'http://' + process.env.REACT_APP_BASE_URL + '/api/profile',
// headers: {
// Authorization: `Bearer ${cleanData}`,
// },
// withCredentials: true,
// });
// setUser(tmpUser.data);
// // setUser(tmpUser.data);
// // if (tmpUser.data.otp_verified)
// // {
// // console.log("true");
// // return (
// // <>
// // <h1>Double Auth</h1>
// // <input
// // onKeyDown={handleKeyPress}
// // type="text"
// // className="qr"
// // placeholder="6 Digits Code"
// // value={code}
// // onChange={(e) => setCode(e.target.value)}
// // />
// // </>
// // )
// // }
// // else
// // {
// // console.log("false");
// // localStorage.setItem('token', `${cleanData}`);
// // console.log(`prout token2= ${localStorage.getItem('token')}`)
// // window.location.replace("http://" + process.env.REACT_APP_BASE_URL + "/pong");
// // }
// } catch(err) {
// console.log(err)
// }
// }
// getUser();
// }, []);
// const handleKeyPress = async (e)=>{
// // console.log(`e in press= ${e.key}`)
// if (e.key !== "Enter")
// return ;
// try{
// console.log("code= ", code)
// const res = await api.post("/verifyOtp", {token: code})
// console.log("res= ", res.data)
// console.log("res= ", res)
// if (res.data === 1)
// {
// console.log("registered")
// // history.push('/login')
// const path = 'http://' + process.env.REACT_APP_BASE_URL + '/';
// window.history.pushState({}, '', path);
// window.location.reload();
// }
// else
// {
// console.log("bad code")
// //alert ?? retry
// }
// // redirect('/test')
// }
// catch(err){
// console.log(err)
// }
// }
// console.log("start while...")
// while(user === false)
// ;
// console.log("end while")
// if (!user.otp_verified)
// {
// console.log("false");
// localStorage.setItem('token', `${cleanData}`);
// console.log(`prout token2= ${localStorage.getItem('token')}`)
// window.location.replace("http://" + process.env.REACT_APP_BASE_URL + "/pong");
// return ;
// }
// return (
// <>
// <h1>Double Auth</h1>
// <input
// onKeyDown={handleKeyPress}
// type="text"
// className="qr"
// placeholder="6 Digits Code"
// value={code}
// onChange={(e) => setCode(e.target.value)}
// />
// </>
// )
// }
// export default SuccessToken;