clean chat api and pong from commentary
This commit is contained in:
parent
42cdd645c8
commit
b59e987c7d
@ -1,22 +0,0 @@
|
|||||||
import { Test, TestingModule } from '@nestjs/testing';
|
|
||||||
import { AppController } from './app.controller';
|
|
||||||
import { AppService } from './app.service';
|
|
||||||
|
|
||||||
describe('AppController', () => {
|
|
||||||
let appController: AppController;
|
|
||||||
|
|
||||||
beforeEach(async () => {
|
|
||||||
const app: TestingModule = await Test.createTestingModule({
|
|
||||||
controllers: [AppController],
|
|
||||||
providers: [AppService],
|
|
||||||
}).compile();
|
|
||||||
|
|
||||||
appController = app.get<AppController>(AppController);
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('root', () => {
|
|
||||||
it('should return "Hello World!"', () => {
|
|
||||||
expect(appController.getHello()).toBe('Hello World!');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@ -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 04:10:56 by apommier ### ########.fr */
|
/* Updated: 2023/06/26 06:49:15 by apommier ### ########.fr */
|
||||||
/* */
|
/* */
|
||||||
/* ************************************************************************** */
|
/* ************************************************************************** */
|
||||||
|
|
||||||
@ -183,15 +183,12 @@ export class AppController {
|
|||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@Post('/nickname')
|
@Post('/nickname')
|
||||||
async setNickname(@Request() req, @Body() data: any) {
|
async setNickname(@Request() req, @Body() data: any) {
|
||||||
// let user = req.user
|
|
||||||
// user.nickname = data.nickname
|
|
||||||
console.log(`user= ${req.user.username}`)
|
console.log(`user= ${req.user.username}`)
|
||||||
const taken = await this.userService.findNickname(data.nickname)
|
const taken = await this.userService.findNickname(data.nickname)
|
||||||
if (taken)
|
if (taken)
|
||||||
return (0);
|
return (0);
|
||||||
let user = await this.userService.findOne(req.user.username)
|
let user = await this.userService.findOne(req.user.username)
|
||||||
user.nickname = data.nickname;
|
user.nickname = data.nickname;
|
||||||
// return await this.userService.getFriends(req.user.username);
|
|
||||||
return await this.userService.save(user);
|
return await this.userService.save(user);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -210,14 +207,7 @@ export class AppController {
|
|||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@Post('/getPicture')
|
@Post('/getPicture')
|
||||||
async getProfilPicture(@Body() data: any) {
|
async getProfilPicture(@Body() data: any) {
|
||||||
// console.log(`dataaaaa= ${data.username}`)
|
|
||||||
return await this.userService.getPic(data.username)
|
return await this.userService.getPic(data.username)
|
||||||
|
|
||||||
// return user.photo
|
|
||||||
// const photoData = user.photo;
|
|
||||||
// Buffer.from(user.photo, 'binary').buffer;
|
|
||||||
// const arrayBuffer = ArrayBuffer.from(photoData, 'binary');
|
|
||||||
// return await this.userService.save(user);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//========================================================================================================
|
//========================================================================================================
|
||||||
@ -229,42 +219,27 @@ export class AppController {
|
|||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@Post('/win')
|
@Post('/win')
|
||||||
async addWin(@Request() req, @Body() data: any) {
|
async addWin(@Request() req, @Body() data: any) {
|
||||||
console.log("WIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIN: ", req.user.username)
|
|
||||||
const user = await this.userService.findOne(req.user.username);
|
const user = await this.userService.findOne(req.user.username);
|
||||||
console.log("User", user)
|
|
||||||
// const user2 = await this.userService.findOne(data.opName);
|
|
||||||
user.win++;
|
user.win++;
|
||||||
const Esp = 1 / (1 + Math.pow(10, (data.opRank - user.rank) / this.scaleFactor))
|
const Esp = 1 / (1 + Math.pow(10, (data.opRank - user.rank) / this.scaleFactor))
|
||||||
const newRank = user.rank + this.kFactor * (1 - Esp);
|
const newRank = user.rank + this.kFactor * (1 - Esp);
|
||||||
|
|
||||||
user.rank = newRank;
|
user.rank = newRank;
|
||||||
console.log(`win new rank= ${newRank}`);
|
|
||||||
console.log(`data win = ${data}`)
|
|
||||||
|
|
||||||
const newMatch = new MatchLog;
|
const newMatch = new MatchLog;
|
||||||
newMatch.myScore = data.myScore;
|
newMatch.myScore = data.myScore;
|
||||||
newMatch.opScore = data.opScore;
|
newMatch.opScore = data.opScore;
|
||||||
newMatch.opponent = data.opName;
|
newMatch.opponent = data.opName;
|
||||||
newMatch.parent = user;
|
newMatch.parent = user;
|
||||||
console.log(`newMatch WIIIN = ${newMatch}`);
|
|
||||||
await this.userService.saveChild(user, newMatch);
|
await this.userService.saveChild(user, newMatch);
|
||||||
}
|
}
|
||||||
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@Post('/loss')
|
@Post('/loss')
|
||||||
async addLoss(@Request() req, @Body() data: any) {
|
async addLoss(@Request() req, @Body() data: any) {
|
||||||
console.log("LOOOOOOOOOOOOOOOSE: ", req.user.username)
|
|
||||||
const user = await this.userService.findOne(req.user.username);
|
const user = await this.userService.findOne(req.user.username);
|
||||||
console.log("User", user)
|
|
||||||
user.loss++;
|
user.loss++;
|
||||||
|
|
||||||
const Esp = 1 / (1 + Math.pow(10, (data.opRank - user.rank) / this.scaleFactor))
|
const Esp = 1 / (1 + Math.pow(10, (data.opRank - user.rank) / this.scaleFactor))
|
||||||
const newRank = user.rank + this.kFactor * (0 - Esp);
|
const newRank = user.rank + this.kFactor * (0 - Esp);
|
||||||
|
|
||||||
user.rank = newRank;
|
user.rank = newRank;
|
||||||
console.log(`loss new rank= ${newRank}`);
|
|
||||||
console.log(`data loss = ${data}`)
|
|
||||||
|
|
||||||
const newMatch = new MatchLog;
|
const newMatch = new MatchLog;
|
||||||
newMatch.myScore = data.myScore;
|
newMatch.myScore = data.myScore;
|
||||||
newMatch.opScore = data.opScore;
|
newMatch.opScore = data.opScore;
|
||||||
@ -282,7 +257,6 @@ export class AppController {
|
|||||||
return user.rank;
|
return user.rank;
|
||||||
}
|
}
|
||||||
|
|
||||||
// @UseGuards(JwtAuthGuard)
|
|
||||||
@Get('/ranking')
|
@Get('/ranking')
|
||||||
async getRanking()
|
async getRanking()
|
||||||
{
|
{
|
||||||
@ -293,27 +267,18 @@ export class AppController {
|
|||||||
@Post('/partyInvite')
|
@Post('/partyInvite')
|
||||||
async partyInvite(@Request() req, @Body() data: any)
|
async partyInvite(@Request() req, @Body() data: any)
|
||||||
{
|
{
|
||||||
//find data.username and add invite to list
|
|
||||||
console.log("data post priv invite=", data);
|
|
||||||
const user = await this.userService.findOne(data.username);
|
const user = await this.userService.findOne(data.username);
|
||||||
user.partyInvite = user.partyInvite || [];
|
user.partyInvite = user.partyInvite || [];
|
||||||
user.partyInvite.push({ username: req.user.username, gameId: data.gameId });
|
user.partyInvite.push({ username: req.user.username, gameId: data.gameId });
|
||||||
console.log("usr === ", user)
|
|
||||||
await this.userService.save(user);
|
await this.userService.save(user);
|
||||||
// user.partyInvite.push(data);
|
|
||||||
console.log("invite === ", user.partyInvite)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@Get('/partyInvite')
|
@Get('/partyInvite')
|
||||||
async getPartyInvite(@Request() req, @Body() data: any)
|
async getPartyInvite(@Request() req)
|
||||||
{
|
{
|
||||||
//find data.username and add invite to list
|
|
||||||
const user = await this.userService.findOne(req.user.username);
|
const user = await this.userService.findOne(req.user.username);
|
||||||
user.partyInvite = user.partyInvite || [];
|
user.partyInvite = user.partyInvite || [];
|
||||||
// this.userService.save(user);
|
|
||||||
// user.partyInvite.push(data);
|
|
||||||
// console.log("data invite === ", data.username)
|
|
||||||
return user.partyInvite;
|
return user.partyInvite;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -321,14 +286,8 @@ export class AppController {
|
|||||||
@Post('/deleteInvite')
|
@Post('/deleteInvite')
|
||||||
async deleteInvite(@Request() req, @Body() data: any)
|
async deleteInvite(@Request() req, @Body() data: any)
|
||||||
{
|
{
|
||||||
console.log("delete invite user= ", data.username)
|
|
||||||
const user = await this.userService.findOne(req.user.username);
|
const user = await this.userService.findOne(req.user.username);
|
||||||
|
|
||||||
|
|
||||||
// user.partyInvite = user.partyInvite.filter(item => Object.values(item)[1] !== req.user.username);
|
|
||||||
console.log("user.partyInvite before", user.partyInvite)
|
|
||||||
user.partyInvite = user.partyInvite.filter((item) => Object.values(item)[1] !== data.username);
|
user.partyInvite = user.partyInvite.filter((item) => Object.values(item)[1] !== data.username);
|
||||||
console.log("user.partyInvite after", user.partyInvite)
|
|
||||||
this.userService.save(user);
|
this.userService.save(user);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -336,22 +295,7 @@ export class AppController {
|
|||||||
@Post('/history')
|
@Post('/history')
|
||||||
async getHistory(@Body() data: any)
|
async getHistory(@Body() data: any)
|
||||||
{
|
{
|
||||||
// const user = await this.userService.findOne(req.user.username);
|
|
||||||
// return user.rank;
|
|
||||||
return await this.userService.getHistory(data.username);
|
return await this.userService.getHistory(data.username);
|
||||||
|
|
||||||
// if (user) {
|
|
||||||
// const children = user.children;
|
|
||||||
// console.log(user);
|
|
||||||
// console.log(user.children); // or perform any operations with the children
|
|
||||||
// return children;
|
|
||||||
// // You can also access specific properties of each child
|
|
||||||
// // children.forEach((child) => {
|
|
||||||
// // console.log(child.id);
|
|
||||||
// // console.log(child.opponent);
|
|
||||||
// // // Access other child properties as needed
|
|
||||||
// // });
|
|
||||||
// }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -361,27 +305,15 @@ export class AppController {
|
|||||||
//========================================================================================================
|
//========================================================================================================
|
||||||
//========================================================================================================
|
//========================================================================================================
|
||||||
|
|
||||||
// import { Prisma } from "@prisma/client";
|
|
||||||
// import { Request, Response, NextFunction } from "express";
|
|
||||||
// import { prisma } from "../server";
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@Redirect('http://' + process.env.BASE_URL + '/token', 302)
|
@Redirect('http://' + process.env.BASE_URL + '/token', 302)
|
||||||
@Get('auth/login')
|
@Get('auth/login')
|
||||||
async login2(@Req() request: Request) {
|
async login2(@Req() request: Request) {
|
||||||
const url = request.url;
|
const url = request.url;
|
||||||
const user = await this.loginClass.Login42(url);
|
const user = await this.loginClass.Login42(url);
|
||||||
console.log(`user in auth/login= ${user}`);
|
|
||||||
console.log(`user in auth/login= ${user.username}`);
|
|
||||||
const data = await this.authService.login(user);
|
const data = await this.authService.login(user);
|
||||||
console.log(`all data in api = ${data}`);
|
|
||||||
const myJSON = JSON.stringify(data);
|
const myJSON = JSON.stringify(data);
|
||||||
console.log(`all data json version= ${myJSON}`);
|
const token = (await data).access_token;
|
||||||
console.log(`data in api = ${(await data).access_token}`);
|
|
||||||
// console.log(`data i = ${(await data).access_token}`)
|
|
||||||
const token = (await data).access_token;
|
|
||||||
// console
|
|
||||||
await this.userService.save(user);
|
await this.userService.save(user);
|
||||||
return { url: 'http://' + process.env.BASE_URL + `/token?data=${encodeURIComponent(JSON.stringify(token))}` };
|
return { url: 'http://' + process.env.BASE_URL + `/token?data=${encodeURIComponent(JSON.stringify(token))}` };
|
||||||
}
|
}
|
||||||
@ -394,16 +326,13 @@ export class AppController {
|
|||||||
return user.otp_enabled;
|
return user.otp_enabled;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@Post('/otp')
|
@Post('/otp')
|
||||||
async createOTP(@Request() req)
|
async createOTP(@Request() req)
|
||||||
{
|
{
|
||||||
const user = await this.userService.findOne(req.user.username);
|
const user = await this.userService.findOne(req.user.username);
|
||||||
// const user2 = await this.userService.findOne(req.user.username);
|
|
||||||
const res = await generateOTP(user);
|
const res = await generateOTP(user);
|
||||||
await this.userService.save(user);
|
await this.userService.save(user);
|
||||||
// console.log(user);
|
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -413,8 +342,6 @@ export class AppController {
|
|||||||
{
|
{
|
||||||
const user = await this.userService.findOne(req.user.username);
|
const user = await this.userService.findOne(req.user.username);
|
||||||
const res = await VerifyOTP(user, data.token)
|
const res = await VerifyOTP(user, data.token)
|
||||||
console.log('token in verify=', data.token)
|
|
||||||
console.log('res in verify=', res)
|
|
||||||
await this.userService.save(user);
|
await this.userService.save(user);
|
||||||
return res
|
return res
|
||||||
}
|
}
|
||||||
@ -425,7 +352,6 @@ export class AppController {
|
|||||||
{
|
{
|
||||||
const user = await this.userService.findOne(req.user.username);
|
const user = await this.userService.findOne(req.user.username);
|
||||||
const res = await ValidateOTP(user, data.token)
|
const res = await ValidateOTP(user, data.token)
|
||||||
// await this.userService.save(user);
|
|
||||||
return res
|
return res
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -436,22 +362,14 @@ export class AppController {
|
|||||||
const user = await this.userService.findOne(req.user.username);
|
const user = await this.userService.findOne(req.user.username);
|
||||||
user.otp_verified = false;
|
user.otp_verified = false;
|
||||||
await this.userService.save(user);
|
await this.userService.save(user);
|
||||||
// const res = await ValidateOTP(user, data.token)
|
|
||||||
// await this.userService.save(user);
|
|
||||||
// return res
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// @UseGuards(JwtAuthGuard)
|
|
||||||
// @Get('/QRcode')
|
|
||||||
// async createQrCode(@Request() req)
|
|
||||||
// {
|
|
||||||
// return (await generateQRcode(req));
|
|
||||||
// }
|
|
||||||
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@Post('/quit')
|
@Post('/quit')
|
||||||
async setOffline(@Request() req) {
|
async setOffline(@Request() req) {
|
||||||
const user = await this.userService.findOne(req.user.username);
|
const user = await this.userService.findOne(req.user.username);
|
||||||
|
if (!user)
|
||||||
|
return ;
|
||||||
user.sessionNumber-- ;
|
user.sessionNumber-- ;
|
||||||
if (!user.sessionNumber)
|
if (!user.sessionNumber)
|
||||||
user.status = 0;
|
user.status = 0;
|
||||||
@ -477,22 +395,14 @@ export class AppController {
|
|||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@Post('/conv')
|
@Post('/conv')
|
||||||
async createConv(@Request() req, @Body() data: any) {
|
async createConv(@Request() req, @Body() data: any) {
|
||||||
///create conv and return it ? id?
|
|
||||||
console.log(`data post /conv= ${data}`);
|
|
||||||
console.log(`data post /conv= ${data.members}`);
|
|
||||||
// console.log(`data post /conv= ${data.name}`);
|
|
||||||
|
|
||||||
// const param = data;
|
|
||||||
const amIhere = data.members.includes(req.user.username);
|
const amIhere = data.members.includes(req.user.username);
|
||||||
if (!amIhere)
|
if (!amIhere)
|
||||||
data.members.push(req.user.username)
|
data.members.push(req.user.username)
|
||||||
// let test = {id: 2, members: "cc"};
|
|
||||||
data.admin = []
|
data.admin = []
|
||||||
data.admin.push(req.user.username)
|
data.admin.push(req.user.username)
|
||||||
data.owner = req.user.username
|
data.owner = req.user.username
|
||||||
data.group = true;
|
data.group = true;
|
||||||
return await this.chatService.createConv(data);
|
return await this.chatService.createConv(data);
|
||||||
// res.json(messages);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@ -517,13 +427,11 @@ export class AppController {
|
|||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@Post('/message')
|
@Post('/message')
|
||||||
async postMessage(@Request() req, @Body() data: any) {
|
async postMessage(@Request() req, @Body() data: any) {
|
||||||
//if i can post post ?
|
|
||||||
let message =
|
let message =
|
||||||
{
|
{
|
||||||
convid: data.convId,
|
convid: data.convId,
|
||||||
sender: data.sender,
|
sender: data.sender,
|
||||||
text: data.text,
|
text: data.text,
|
||||||
// createdAt: null,
|
|
||||||
id: null,
|
id: null,
|
||||||
}
|
}
|
||||||
console.log(data);
|
console.log(data);
|
||||||
@ -541,24 +449,12 @@ export class AppController {
|
|||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@Post('/getMessage')
|
@Post('/getMessage')
|
||||||
async getMessage(@Body() data: any) {
|
async getMessage(@Body() data: any) {
|
||||||
console.log(data);
|
|
||||||
// console.log(req.query)
|
|
||||||
console.log(`data get /conv= ${data.convId}`);
|
|
||||||
// let test = {id: 2, members: "cc"};
|
|
||||||
|
|
||||||
|
|
||||||
return await this.chatService.getMessages(data.convId);
|
return await this.chatService.getMessages(data.convId);
|
||||||
// return await this.chatService.getConv(req.user.username);
|
|
||||||
|
|
||||||
|
|
||||||
// res.json(messages);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@Post('/name')
|
@Post('/name')
|
||||||
async setName(@Body() data: any) {
|
async setName(@Body() data: any) {
|
||||||
//find conv
|
|
||||||
// data.convId
|
|
||||||
return await this.chatService.setName(data.convId, data.name)
|
return await this.chatService.setName(data.convId, data.name)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -2,16 +2,8 @@ import { Module } from '@nestjs/common';
|
|||||||
import { AppController } from './app.controller';
|
import { AppController } from './app.controller';
|
||||||
import { AppService } from './app.service';
|
import { AppService } from './app.service';
|
||||||
import { AuthModule } from './auth/auth.module';
|
import { AuthModule } from './auth/auth.module';
|
||||||
|
|
||||||
import { loginClass } from './auth/login42';
|
import { loginClass } from './auth/login42';
|
||||||
// import { UsersService } from './users/users.service'; // in add
|
|
||||||
|
|
||||||
// import { TypeOrmModule } from '@nestjs/typeorm';
|
|
||||||
// import { getTypeOrmConfig } from './config/config.service';
|
|
||||||
// import { User } from './model/item.entity';
|
|
||||||
// import { UsersService } from './users/users.service';
|
|
||||||
import { UsersModule } from './users/users.module';
|
import { UsersModule } from './users/users.module';
|
||||||
// import { ChatService } from './chat/chat.service';
|
|
||||||
import { ChatModule } from './chat/chat.module';
|
import { ChatModule } from './chat/chat.module';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
@ -23,7 +15,5 @@ import { ChatModule } from './chat/chat.module';
|
|||||||
],
|
],
|
||||||
controllers: [AppController],
|
controllers: [AppController],
|
||||||
providers: [AppService, loginClass,],
|
providers: [AppService, loginClass,],
|
||||||
|
|
||||||
// providers: [AppService, UsersService],//in add
|
|
||||||
})
|
})
|
||||||
export class AppModule {}
|
export class AppModule {}
|
||||||
|
|||||||
@ -1,23 +1,8 @@
|
|||||||
// import { Module } from '@nestjs/common';
|
|
||||||
// import { AuthService } from './auth.service';
|
|
||||||
// import { UsersModule } from '../users/users.module';
|
|
||||||
// import { PassportModule } from '@nestjs/passport';
|
|
||||||
// import { LocalStrategy } from './local.strategy';
|
|
||||||
|
|
||||||
// @Module({
|
|
||||||
// imports: [UsersModule, PassportModule],
|
|
||||||
// providers: [AuthService, LocalStrategy],
|
|
||||||
// })
|
|
||||||
// export class AuthModule {}
|
|
||||||
|
|
||||||
|
|
||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
|
|
||||||
import { AuthService } from './auth.service';
|
import { AuthService } from './auth.service';
|
||||||
import { UsersModule } from '../users/users.module';
|
import { UsersModule } from '../users/users.module';
|
||||||
import { PassportModule } from '@nestjs/passport';
|
import { PassportModule } from '@nestjs/passport';
|
||||||
import { LocalStrategy } from './local.strategy';
|
import { LocalStrategy } from './local.strategy';
|
||||||
|
|
||||||
import { JwtModule } from '@nestjs/jwt';
|
import { JwtModule } from '@nestjs/jwt';
|
||||||
import { jwtConstants } from './constants';
|
import { jwtConstants } from './constants';
|
||||||
import { JwtStrategy } from './jwt.strategy';
|
import { JwtStrategy } from './jwt.strategy';
|
||||||
@ -28,7 +13,6 @@ import { JwtStrategy } from './jwt.strategy';
|
|||||||
PassportModule,
|
PassportModule,
|
||||||
JwtModule.register({
|
JwtModule.register({
|
||||||
secret: jwtConstants.secret,
|
secret: jwtConstants.secret,
|
||||||
// signOptions: { expiresIn: '60000s' },
|
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
providers: [AuthService, LocalStrategy, JwtStrategy],
|
providers: [AuthService, LocalStrategy, JwtStrategy],
|
||||||
|
|||||||
@ -1,4 +1,3 @@
|
|||||||
export const jwtConstants = {
|
export const jwtConstants = {
|
||||||
// secret: 'DO NOT USE THIS VALUE. INSTEAD, CREATE A COMPLEX SECRET AND KEEP IT SAFE OUTSIDE OF THE SOURCE CODE.',
|
|
||||||
secret: process.env.JWT_SECRET,
|
secret: process.env.JWT_SECRET,
|
||||||
};
|
};
|
||||||
@ -1,12 +1,7 @@
|
|||||||
// import React, { useEffect, useState } from 'react';
|
|
||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
import { UsersService } from '../users/users.service';
|
import { UsersService } from '../users/users.service';
|
||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
|
|
||||||
import { Repository } from 'typeorm';
|
|
||||||
|
|
||||||
import { MatchLog } from '../model/user.entity';
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class loginClass {
|
export class loginClass {
|
||||||
constructor(private readonly usersService: UsersService) {};
|
constructor(private readonly usersService: UsersService) {};
|
||||||
@ -22,11 +17,10 @@ export class loginClass {
|
|||||||
|
|
||||||
const data = {
|
const data = {
|
||||||
grant_type: 'authorization_code',
|
grant_type: 'authorization_code',
|
||||||
client_id: process.env.CLIENT_UID || 'u-s4t2ud-6d29dfa49ba7146577ffd8bf595ae8d9e5aaa3e0a9615df18777171ebf836a41',
|
client_id: process.env.CLIENT_UID,
|
||||||
// client_secret: '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',
|
|
||||||
client_secret: process.env.API_SECRET,
|
client_secret: process.env.API_SECRET,
|
||||||
code: code,
|
code: code,
|
||||||
redirect_uri: process.env.REDIRECT_URI || 'http://' + process.env.REACT_APP_BASE_URL + '/api/auth/login',
|
redirect_uri: process.env.REDIRECT_URI,
|
||||||
};
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@ -40,20 +34,14 @@ export class loginClass {
|
|||||||
});
|
});
|
||||||
userName = response2.data.login;
|
userName = response2.data.login;
|
||||||
userId = parseInt(response2.data.id, 10);
|
userId = parseInt(response2.data.id, 10);
|
||||||
// console.log(`all user data= ${response2.data}`)
|
|
||||||
// const myJSON = JSON.stringify(response2.data);
|
|
||||||
// console.log(`json version= ${myJSON}`)
|
|
||||||
}
|
}
|
||||||
catch(error)
|
catch(error)
|
||||||
{
|
{
|
||||||
console.log(error);
|
console.log(error);
|
||||||
return ;
|
return ;
|
||||||
}
|
}
|
||||||
console.log(`username before serach= ${userName}`)
|
|
||||||
console.log(`ID before serach= ${userId}`)
|
|
||||||
let user = await this.usersService.findOne(userName);
|
let user = await this.usersService.findOne(userName);
|
||||||
if (!user) {
|
if (!user) {
|
||||||
console.log(`no user, creating one`);
|
|
||||||
user = {
|
user = {
|
||||||
id: null,
|
id: null,
|
||||||
partyInvite: null,
|
partyInvite: null,
|
||||||
@ -78,15 +66,7 @@ export class loginClass {
|
|||||||
};
|
};
|
||||||
await this.usersService.create(user);
|
await this.usersService.create(user);
|
||||||
}
|
}
|
||||||
// if (user.status !== 2 || user.status === 0) //super
|
|
||||||
// user.status = 1;
|
|
||||||
// user.sessionNumber++;
|
|
||||||
// console.log(`in login42 user= ${user}`)
|
|
||||||
const myJSON = JSON.stringify(user);
|
const myJSON = JSON.stringify(user);
|
||||||
console.log(`in login42 user= ${myJSON}`)
|
|
||||||
|
|
||||||
console.log("end of login");
|
|
||||||
return (user);
|
return (user);
|
||||||
// return (await this.usersService.findOne(userName));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,8 +1,3 @@
|
|||||||
// import { Module } from '@nestjs/common';
|
|
||||||
|
|
||||||
// @Module({})
|
|
||||||
// export class ChatModule {}
|
|
||||||
|
|
||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { ChatService} from './chat.service';
|
import { ChatService} from './chat.service';
|
||||||
|
|
||||||
@ -17,7 +12,6 @@ import { Message } from '../model/chat.entity';
|
|||||||
TypeOrmModule.forRoot(getTypeOrmConfig()),
|
TypeOrmModule.forRoot(getTypeOrmConfig()),
|
||||||
TypeOrmModule.forFeature([Conv]),
|
TypeOrmModule.forFeature([Conv]),
|
||||||
TypeOrmModule.forFeature([Message]),
|
TypeOrmModule.forFeature([Message]),
|
||||||
// TypeOrmModule.forFeature([UserRepository]),
|
|
||||||
],
|
],
|
||||||
providers:[ChatService],
|
providers:[ChatService],
|
||||||
exports: [ChatService],
|
exports: [ChatService],
|
||||||
|
|||||||
@ -6,7 +6,7 @@
|
|||||||
/* By: apommier <apommier@student.42.fr> +#+ +:+ +#+ */
|
/* By: apommier <apommier@student.42.fr> +#+ +:+ +#+ */
|
||||||
/* +#+#+#+#+#+ +#+ */
|
/* +#+#+#+#+#+ +#+ */
|
||||||
/* Created: 2023/06/17 01:00:25 by apommier #+# #+# */
|
/* Created: 2023/06/17 01:00:25 by apommier #+# #+# */
|
||||||
/* Updated: 2023/06/26 05:09:02 by apommier ### ########.fr */
|
/* Updated: 2023/06/26 06:56:08 by apommier ### ########.fr */
|
||||||
/* */
|
/* */
|
||||||
/* ************************************************************************** */
|
/* ************************************************************************** */
|
||||||
|
|
||||||
@ -15,13 +15,8 @@ import { InjectRepository } from '@nestjs/typeorm';
|
|||||||
import { Repository } from 'typeorm';
|
import { Repository } from 'typeorm';
|
||||||
import { Conv } from '../model/chat.entity';
|
import { Conv } from '../model/chat.entity';
|
||||||
import { Message } from '../model/chat.entity';
|
import { Message } from '../model/chat.entity';
|
||||||
|
|
||||||
import * as bcrypt from 'bcrypt';
|
import * as bcrypt from 'bcrypt';
|
||||||
|
|
||||||
import { ArrayContains } from "typeorm"
|
|
||||||
import { query } from 'express';
|
|
||||||
import { InitializeOnPreviewAllowlist } from '@nestjs/core';
|
|
||||||
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class ChatService {
|
export class ChatService {
|
||||||
@ -43,13 +38,10 @@ async findAll(): Promise<Conv[]> {
|
|||||||
|
|
||||||
async getConv(username: string): Promise<Conv[]>{
|
async getConv(username: string): Promise<Conv[]>{
|
||||||
const convs = await this.chatRepository.query("SELECT * FROM \"conv\" WHERE $1 = ANY (ARRAY[members]);", [username])
|
const convs = await this.chatRepository.query("SELECT * FROM \"conv\" WHERE $1 = ANY (ARRAY[members]);", [username])
|
||||||
console.log(`convs= ${convs}`)
|
|
||||||
return convs;
|
return convs;
|
||||||
}
|
}
|
||||||
|
|
||||||
async findConv(number: number){
|
async findConv(number: number){
|
||||||
// username = "apommier"
|
|
||||||
console.log(`fincConv; ${number}`)
|
|
||||||
const conv = await this.chatRepository.findOneBy({id: number})
|
const conv = await this.chatRepository.findOneBy({id: number})
|
||||||
return conv;
|
return conv;
|
||||||
}
|
}
|
||||||
@ -109,31 +101,21 @@ async inviteUser(convId: number, username: string) {
|
|||||||
|
|
||||||
|
|
||||||
async setPassword(convId: number, password: string) {
|
async setPassword(convId: number, password: string) {
|
||||||
//verify is user is admin ?
|
|
||||||
const conv = await this.findConv(convId);
|
const conv = await this.findConv(convId);
|
||||||
const saltRounds = 10;
|
const saltRounds = 10;
|
||||||
const hashedPassword = await bcrypt.hash(password, saltRounds);
|
const hashedPassword = await bcrypt.hash(password, saltRounds);
|
||||||
// return hashedPassword;
|
|
||||||
conv.password = hashedPassword
|
conv.password = hashedPassword
|
||||||
this.save(conv);
|
this.save(conv);
|
||||||
}
|
}
|
||||||
|
|
||||||
async verifyPassword(convId: number, password: string) {
|
async verifyPassword(convId: number, password: string) {
|
||||||
//verify is user is admin ?
|
|
||||||
const conv = await this.findConv(convId);
|
const conv = await this.findConv(convId);
|
||||||
return await bcrypt.compare(password, conv.password);
|
return await bcrypt.compare(password, conv.password);
|
||||||
|
|
||||||
// conv.password = password
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async muteUser(convId: number, username: string, time: string) {
|
async muteUser(convId: number, username: string, time: string) {
|
||||||
const conv = await this.findConv(convId);
|
const conv = await this.findConv(convId);
|
||||||
|
|
||||||
console.log("MUTE USER");
|
|
||||||
console.log("time = ", time);
|
|
||||||
console.log("int time = ", parseInt(time));
|
|
||||||
const intTime = parseInt(time) * 1000;
|
const intTime = parseInt(time) * 1000;
|
||||||
console.log("intTime = ", intTime);
|
|
||||||
if (conv.owner === username)
|
if (conv.owner === username)
|
||||||
return (0);
|
return (0);
|
||||||
conv.muted = conv.muted || [];
|
conv.muted = conv.muted || [];
|
||||||
@ -146,7 +128,6 @@ async muteUser(convId: number, username: string, time: string) {
|
|||||||
conv.muted = conv.muted.filter((item) => item !== username)
|
conv.muted = conv.muted.filter((item) => item !== username)
|
||||||
this.save(conv);
|
this.save(conv);
|
||||||
}, intTime);
|
}, intTime);
|
||||||
console.log("END MUTE USER");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async setAdmin(convId: number, username: string) {
|
async setAdmin(convId: number, username: string) {
|
||||||
@ -173,10 +154,6 @@ async setPrivate(convId: number, bool: boolean) {
|
|||||||
const conv = await this.findConv(convId);
|
const conv = await this.findConv(convId);
|
||||||
console.log("bool= ", bool);
|
console.log("bool= ", bool);
|
||||||
conv.private = bool;
|
conv.private = bool;
|
||||||
// if (conv.private === true)
|
|
||||||
// conv.private = false;
|
|
||||||
// else
|
|
||||||
// conv.private = true;
|
|
||||||
this.save(conv);
|
this.save(conv);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -192,7 +169,6 @@ async joinChannel(convId: number, username: string) {
|
|||||||
if (conv.members.find(item => item === username))
|
if (conv.members.find(item => item === username))
|
||||||
return ;
|
return ;
|
||||||
conv.members.push(username);
|
conv.members.push(username);
|
||||||
// conv.name = name;
|
|
||||||
this.save(conv);
|
this.save(conv);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -6,20 +6,11 @@ import * as dotenv from 'dotenv';
|
|||||||
dotenv.config();
|
dotenv.config();
|
||||||
console.log(process.env);
|
console.log(process.env);
|
||||||
|
|
||||||
// async function bootstrap() {
|
|
||||||
// const app = await NestFactory.create(AppModule);
|
|
||||||
// await app.listen(3000);
|
|
||||||
// }
|
|
||||||
// bootstrap();
|
|
||||||
|
|
||||||
|
|
||||||
async function bootstrap() {
|
async function bootstrap() {
|
||||||
const app = await NestFactory.create(AppModule, {
|
const app = await NestFactory.create(AppModule, {
|
||||||
cors: {
|
cors: {
|
||||||
origin: '*',
|
origin: '*',
|
||||||
methods: '*',
|
methods: '*',
|
||||||
// preflightContinue: false,
|
|
||||||
// optionsSuccessStatus: 204,
|
|
||||||
credentials: true,
|
credentials: true,
|
||||||
allowedHeaders: '*',
|
allowedHeaders: '*',
|
||||||
},
|
},
|
||||||
|
|||||||
@ -6,7 +6,7 @@
|
|||||||
/* By: apommier <apommier@student.42.fr> +#+ +:+ +#+ */
|
/* By: apommier <apommier@student.42.fr> +#+ +:+ +#+ */
|
||||||
/* +#+#+#+#+#+ +#+ */
|
/* +#+#+#+#+#+ +#+ */
|
||||||
/* Created: 2023/06/17 01:00:20 by apommier #+# #+# */
|
/* Created: 2023/06/17 01:00:20 by apommier #+# #+# */
|
||||||
/* Updated: 2023/06/23 15:18:19 by apommier ### ########.fr */
|
/* Updated: 2023/06/26 06:55:03 by apommier ### ########.fr */
|
||||||
/* */
|
/* */
|
||||||
/* ************************************************************************** */
|
/* ************************************************************************** */
|
||||||
|
|
||||||
@ -29,9 +29,6 @@ import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, BaseEntity }
|
|||||||
@Column({ nullable: true })
|
@Column({ nullable: true })
|
||||||
private: boolean
|
private: boolean
|
||||||
|
|
||||||
// @Column()
|
|
||||||
// members: string;// arry ??? one to many ???
|
|
||||||
|
|
||||||
@Column('text', { array: true, nullable: true })
|
@Column('text', { array: true, nullable: true })
|
||||||
banned: string[];
|
banned: string[];
|
||||||
|
|
||||||
@ -49,18 +46,6 @@ import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, BaseEntity }
|
|||||||
|
|
||||||
@Column({ nullable: true })
|
@Column({ nullable: true })
|
||||||
messages: string;
|
messages: string;
|
||||||
|
|
||||||
// @CreateDateColumn()
|
|
||||||
// createdAt: Date;
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
//ban user
|
|
||||||
//user list
|
|
||||||
//blocked user (in user model ?)
|
|
||||||
//op list
|
|
||||||
//a way to stock conv ?
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Entity()
|
@Entity()
|
||||||
@ -77,7 +62,6 @@ import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, BaseEntity }
|
|||||||
@Column()
|
@Column()
|
||||||
text: string;
|
text: string;
|
||||||
|
|
||||||
|
|
||||||
@CreateDateColumn({ nullable: true })
|
@CreateDateColumn({ nullable: true })
|
||||||
createdAt?: Date;
|
createdAt?: Date;
|
||||||
|
|
||||||
|
|||||||
@ -20,9 +20,6 @@ export class User {
|
|||||||
@PrimaryGeneratedColumn()
|
@PrimaryGeneratedColumn()
|
||||||
id: number;
|
id: number;
|
||||||
|
|
||||||
// otp_enabled Boolean @default(false)
|
|
||||||
// otp_verified Boolean @default(false)
|
|
||||||
|
|
||||||
@Column({ default: false })
|
@Column({ default: false })
|
||||||
otp_enabled: boolean;
|
otp_enabled: boolean;
|
||||||
|
|
||||||
@ -62,18 +59,12 @@ export class User {
|
|||||||
@Column({ default: 0 })
|
@Column({ default: 0 })
|
||||||
userId: number;
|
userId: number;
|
||||||
|
|
||||||
// @Column({ default: 0 })
|
|
||||||
// doubleAuth: number;
|
|
||||||
|
|
||||||
@Column('text', { array: true, nullable: true })
|
@Column('text', { array: true, nullable: true })
|
||||||
friendRequest: string[];
|
friendRequest: string[];
|
||||||
|
|
||||||
@Column({ type: 'jsonb', nullable: true })
|
@Column({ type: 'jsonb', nullable: true })
|
||||||
partyInvite: Record<string, string>[];
|
partyInvite: Record<string, string>[];
|
||||||
|
|
||||||
// @Column('text', { array: true, nullable: true })
|
|
||||||
// friendRequest: string[];
|
|
||||||
|
|
||||||
@Column('text', { array: true, nullable: true })
|
@Column('text', { array: true, nullable: true })
|
||||||
friends: string[];
|
friends: string[];
|
||||||
|
|
||||||
|
|||||||
@ -1,18 +1,7 @@
|
|||||||
// import crypto from 'crypto';
|
|
||||||
import base32Decode from 'base32-decode';
|
|
||||||
|
|
||||||
import crypto from "crypto";
|
|
||||||
import * as OTPAuth from "otpauth";
|
import * as OTPAuth from "otpauth";
|
||||||
import { encode } from "hi-base32";
|
import { encode } from "hi-base32";
|
||||||
|
|
||||||
import * as qr from 'qrcode';
|
import * as qr from 'qrcode';
|
||||||
|
|
||||||
// [...] Register user
|
|
||||||
|
|
||||||
// [...] Login user
|
|
||||||
|
|
||||||
// [...] Generate OTP
|
|
||||||
|
|
||||||
const generateRandomBase32 = async () => {
|
const generateRandomBase32 = async () => {
|
||||||
const {randomBytes} = await import('crypto');
|
const {randomBytes} = await import('crypto');
|
||||||
const buffer = randomBytes(15);
|
const buffer = randomBytes(15);
|
||||||
@ -36,35 +25,22 @@ export const generateOTP = async (user) => {
|
|||||||
let otpauth_url = totp.toString();
|
let otpauth_url = totp.toString();
|
||||||
const qrCodeDataUrl = await qr.toDataURL(otpauth_url, { errorCorrectionLevel: 'H' });
|
const qrCodeDataUrl = await qr.toDataURL(otpauth_url, { errorCorrectionLevel: 'H' });
|
||||||
|
|
||||||
const filePath = 'qrcode.png'; // Specify the file path where the QR code should be saved
|
const filePath = 'qrcode.png';
|
||||||
|
|
||||||
qr.toFile(filePath, qrCodeDataUrl, (error) => {
|
qr.toFile(filePath, qrCodeDataUrl, (error) => {
|
||||||
if (error) {
|
if (error) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
// Handle the error appropriately
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// QR code image has been generated and saved to the file
|
|
||||||
// Or, you can create a buffer of the image data directly
|
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const res = {
|
const res = {
|
||||||
otpauth_url: otpauth_url,
|
otpauth_url: otpauth_url,
|
||||||
base32_secret: base32_secret
|
base32_secret: base32_secret
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log("res= ", res)
|
|
||||||
|
|
||||||
//update db with otp var
|
|
||||||
user.otp_enabled = true;
|
user.otp_enabled = true;
|
||||||
user.otp_base32 = base32_secret;
|
user.otp_base32 = base32_secret;
|
||||||
return (res)
|
return (res);
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(error)
|
console.log(error)
|
||||||
}
|
}
|
||||||
@ -84,13 +60,11 @@ export const generateOTP = async (user) => {
|
|||||||
let delta = totp.validate({ token });
|
let delta = totp.validate({ token });
|
||||||
|
|
||||||
if (delta === null) {
|
if (delta === null) {
|
||||||
console.log("error verify token")
|
|
||||||
return (0)
|
return (0)
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
user.otp_verified = true;
|
user.otp_verified = true;
|
||||||
console.log("token verified")
|
|
||||||
return (1)
|
return (1)
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@ -110,194 +84,11 @@ export const generateOTP = async (user) => {
|
|||||||
});
|
});
|
||||||
let delta = totp.validate({ token });
|
let delta = totp.validate({ token });
|
||||||
|
|
||||||
if (delta === null) {
|
if (delta === null)
|
||||||
console.log("error validate token")
|
|
||||||
return (0);
|
return (0);
|
||||||
}
|
|
||||||
else
|
else
|
||||||
{
|
|
||||||
// user.otp_verified = true;
|
|
||||||
console.log("token validated")
|
|
||||||
return (1);
|
return (1);
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(error)
|
console.log(error)
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// import { randomBytes} from 'crypto';
|
|
||||||
// import { promisify } from 'util';
|
|
||||||
|
|
||||||
// export function generateHOTP(secret, counter) {
|
|
||||||
// const decodedSecret = base32Decode(secret, 'RFC4648');
|
|
||||||
|
|
||||||
// const buffer = Buffer.alloc(8);
|
|
||||||
// for (let i = 0; i < 8; i++)
|
|
||||||
// {
|
|
||||||
// buffer[7 - i] = counter & 0xff;
|
|
||||||
// counter = counter >> 8;
|
|
||||||
// }
|
|
||||||
|
|
||||||
// // Step 1: Generate an HMAC-SHA-1 value
|
|
||||||
// const hmac = crypto.createHmac('sha1', Buffer.from(decodedSecret));
|
|
||||||
// hmac.update(buffer);
|
|
||||||
// const hmacResult = hmac.digest();
|
|
||||||
|
|
||||||
// // Step 2: Generate a 4-byte string (Dynamic Truncation)
|
|
||||||
// const offset = hmacResult[hmacResult.length - 1] & 0xf;
|
|
||||||
// const code =
|
|
||||||
// ((hmacResult[offset] & 0x7f) << 24) |
|
|
||||||
// ((hmacResult[offset + 1] & 0xff) << 16) |
|
|
||||||
// ((hmacResult[offset + 2] & 0xff) << 8) |
|
|
||||||
// (hmacResult[offset + 3] & 0xff);
|
|
||||||
|
|
||||||
// // Step 3: Compute an HOTP value
|
|
||||||
// return `${code % 10 ** 6}`.padStart(6, '0');
|
|
||||||
// }
|
|
||||||
|
|
||||||
// type QRcode = any;
|
|
||||||
|
|
||||||
// export function generateHOTP(secret, counter) {
|
|
||||||
// const decodedSecret = base32Decode(secret, 'RFC4648');
|
|
||||||
|
|
||||||
// const buffer = Buffer.alloc(8);
|
|
||||||
// for (let i = 0; i < 8; i++) {
|
|
||||||
// buffer[7 - i] = counter & 0xff;
|
|
||||||
// counter = counter >> 8;
|
|
||||||
// }
|
|
||||||
|
|
||||||
// // Step 1: Generate an HMAC-SHA-1 value
|
|
||||||
// const hmac = crypto.createHmac('sha1', Buffer.from(decodedSecret));
|
|
||||||
// hmac.update(buffer);
|
|
||||||
// const hmacResult = hmac.digest();
|
|
||||||
|
|
||||||
// // Step 2: Generate a 4-byte string (Dynamic Truncation)
|
|
||||||
// const offset = hmacResult[hmacResult.length - 1] & 0xf;
|
|
||||||
// const code =
|
|
||||||
// ((hmacResult[offset] & 0x7f) << 24) |
|
|
||||||
// ((hmacResult[offset + 1] & 0xff) << 16) |
|
|
||||||
// ((hmacResult[offset + 2] & 0xff) << 8) |
|
|
||||||
// (hmacResult[offset + 3] & 0xff);
|
|
||||||
|
|
||||||
// // Step 3: Compute an HOTP value
|
|
||||||
// return code % 10 ** 6;
|
|
||||||
// }
|
|
||||||
|
|
||||||
// export function generateTOTP(secret, window = 0)
|
|
||||||
// {
|
|
||||||
// const counter = Math.floor(Date.now() / 30000);
|
|
||||||
// return generateHOTP(secret, counter + window);
|
|
||||||
// }
|
|
||||||
|
|
||||||
// export function verifyTOTP(token, secret, window = 1)
|
|
||||||
// {
|
|
||||||
// for (let errorWindow = -window; errorWindow <= +window; errorWindow++)
|
|
||||||
// {
|
|
||||||
// const totp = generateTOTP(secret, errorWindow);
|
|
||||||
// if (token === totp)
|
|
||||||
// return true;
|
|
||||||
// }
|
|
||||||
// return false;
|
|
||||||
// }
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// import { initStorage, getUser, setUser } from './storage';
|
|
||||||
// import util from 'util';
|
|
||||||
// import qrcode from 'qrcode';
|
|
||||||
// // import base32Encode from 'base32-encode';
|
|
||||||
// import * as util from 'util';
|
|
||||||
// import * as qrcode from 'qrcode';
|
|
||||||
// import * as base32Encode from 'base32-encode';
|
|
||||||
|
|
||||||
// import * as util from 'util';
|
|
||||||
// import * as qrcode from 'qrcode';
|
|
||||||
// import * as crypto from 'crypto';
|
|
||||||
// import { Response } from 'express';
|
|
||||||
// import { Readable } from 'stream';
|
|
||||||
// import * as base32Encode from 'base32-encode';
|
|
||||||
// import { base32Encode } from 'base32-encode';
|
|
||||||
// import base32Encode from 'base32-encode';
|
|
||||||
// import { encode } from 'thirty-two';
|
|
||||||
|
|
||||||
// // ...
|
|
||||||
|
|
||||||
// import * as qrcode from 'qrcode';
|
|
||||||
// import * as fs from 'fs';
|
|
||||||
|
|
||||||
|
|
||||||
// import { nanoid } from "nanoid";
|
|
||||||
// // import * as nanoid from 'nanoid'
|
|
||||||
|
|
||||||
// export async function generateQRcode(req)
|
|
||||||
// {
|
|
||||||
// // const base32Encode = (await import('base32-encode'));
|
|
||||||
// // const nanoid = (await import('nanoid'));
|
|
||||||
|
|
||||||
// // const util = (await import('util'));
|
|
||||||
// // const qrcode = (await import('qrcode'));
|
|
||||||
|
|
||||||
// const user = req.user;
|
|
||||||
// let res;
|
|
||||||
// // For security, we no longer show the QR code after is verified
|
|
||||||
// // if (user.mfaEnabled) return res.status(404).end();
|
|
||||||
|
|
||||||
// // if (!user.mfaSecret) { //to do
|
|
||||||
// const buffer = nanoid(14);
|
|
||||||
// // generate unique secret for user
|
|
||||||
// // this secret will be used to check the verification code sent by user
|
|
||||||
// // const buffer = await util.promisify(crypto.randomBytes)(14);
|
|
||||||
// // const buffer = crypto.lib.WordArray.random(32)
|
|
||||||
// user.mfaSecret = encode(buffer).toString('utf8');
|
|
||||||
// // user.mfaSecret = base32Encoded(buffer, 'RFC4648', { padding: false });
|
|
||||||
|
|
||||||
// // setUser(user); // to do !!
|
|
||||||
|
|
||||||
|
|
||||||
// // }
|
|
||||||
|
|
||||||
// const issuer = 'Google';
|
|
||||||
// const algorithm = 'SHA1';
|
|
||||||
// const digits = '6';
|
|
||||||
// const period = '30';
|
|
||||||
// const otpType = 'totp';
|
|
||||||
// const configUri = `otpauth://${otpType}/${issuer}:${user.username}?algorithm=${algorithm}&digits=${digits}&period=${period}&issuer=${issuer}&secret=${user.mfaSecret}`;
|
|
||||||
|
|
||||||
// // res.setHeader('Content-Type', 'image/png');
|
|
||||||
// const QRCode = require('qrcode');
|
|
||||||
// console.log(`before done`);
|
|
||||||
// // QRCode.toFileStream(res, configUri);
|
|
||||||
// // const filePath = 'qrcode.png'; // Specify the file path where the QR code should be saved
|
|
||||||
|
|
||||||
|
|
||||||
// const qrCodeData = buffer; // Replace with your actual QR code data
|
|
||||||
// const filePath = 'qrcode.png'; // Specify the file path where the QR code should be saved
|
|
||||||
|
|
||||||
// qrcode.toFile(filePath, qrCodeData, (error) => {
|
|
||||||
// if (error) {
|
|
||||||
// console.error(error);
|
|
||||||
// // Handle the error appropriately
|
|
||||||
// return;
|
|
||||||
// }
|
|
||||||
// // QR code image has been generated and saved to the file
|
|
||||||
// // Or, you can create a buffer of the image data directly
|
|
||||||
// })
|
|
||||||
|
|
||||||
// // qrcode.toFile(filePath, configUri, (error) => {
|
|
||||||
// // if (error) {
|
|
||||||
// // console.error(error);
|
|
||||||
// // // Handle the error appropriately
|
|
||||||
// // return;
|
|
||||||
// // }
|
|
||||||
// // const readableStream = fs.createReadStream(filePath);
|
|
||||||
// // res.data = readableStream;
|
|
||||||
// // Use the readable stream as needed
|
|
||||||
// // });
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// // qrcode.toFileStream(res, configUri);
|
|
||||||
// console.log(`QRcode done`);
|
|
||||||
// return res;
|
|
||||||
// // return
|
|
||||||
// }
|
|
||||||
@ -11,7 +11,6 @@ import { MatchLog, User } from '../model/user.entity';
|
|||||||
TypeOrmModule.forRoot(getTypeOrmConfig()),
|
TypeOrmModule.forRoot(getTypeOrmConfig()),
|
||||||
TypeOrmModule.forFeature([User]),
|
TypeOrmModule.forFeature([User]),
|
||||||
TypeOrmModule.forFeature([MatchLog]),
|
TypeOrmModule.forFeature([MatchLog]),
|
||||||
// TypeOrmModule.forFeature([UserRepository]),
|
|
||||||
],
|
],
|
||||||
providers:[UsersService],
|
providers:[UsersService],
|
||||||
exports: [UsersService],
|
exports: [UsersService],
|
||||||
|
|||||||
@ -3,10 +3,10 @@
|
|||||||
/* ::: :::::::: */
|
/* ::: :::::::: */
|
||||||
/* users.service.ts :+: :+: :+: */
|
/* users.service.ts :+: :+: :+: */
|
||||||
/* +:+ +:+ +:+ */
|
/* +:+ +:+ +:+ */
|
||||||
/* By: sadjigui <sadjigui@student.42.fr> +#+ +:+ +#+ */
|
/* By: apommier <apommier@student.42.fr> +#+ +:+ +#+ */
|
||||||
/* +#+#+#+#+#+ +#+ */
|
/* +#+#+#+#+#+ +#+ */
|
||||||
/* Created: 2023/06/17 01:00:07 by apommier #+# #+# */
|
/* Created: 2023/06/17 01:00:07 by apommier #+# #+# */
|
||||||
/* Updated: 2023/06/26 02:23:16 by sadjigui ### ########.fr */
|
/* Updated: 2023/06/26 06:34:42 by apommier ### ########.fr */
|
||||||
/* */
|
/* */
|
||||||
/* ************************************************************************** */
|
/* ************************************************************************** */
|
||||||
|
|
||||||
@ -58,7 +58,7 @@ export class UsersService {
|
|||||||
|
|
||||||
async getFriends(username: string) {
|
async getFriends(username: string) {
|
||||||
const user = await this.findOne(username)
|
const user = await this.findOne(username)
|
||||||
let friendsTab = user.friends
|
let friendsTab = user.friends || [];
|
||||||
console.log(friendsTab)
|
console.log(friendsTab)
|
||||||
// friendsTab = ['apommier', 'syd']
|
// friendsTab = ['apommier', 'syd']
|
||||||
const friends = await this.userRepository.query("SELECT * FROM \"User\" WHERE username = ANY ($1);", [friendsTab]);
|
const friends = await this.userRepository.query("SELECT * FROM \"User\" WHERE username = ANY ($1);", [friendsTab]);
|
||||||
|
|||||||
@ -8,58 +8,35 @@ export class ChatGateway implements OnGatewayInit, OnGatewayConnection, OnGatewa
|
|||||||
@WebSocketServer()
|
@WebSocketServer()
|
||||||
server: Server;
|
server: Server;
|
||||||
|
|
||||||
|
|
||||||
private clients: Record<string, Socket> = {};
|
private clients: Record<string, Socket> = {};
|
||||||
// private clientsNames: Record<string, Socket[]> = {};
|
|
||||||
private clientsNames: Map<string, string[]> = new Map();
|
private clientsNames: Map<string, string[]> = new Map();
|
||||||
// private games: Map<string, Socket[]> = new Map();// Chat en cours, identifiées par un ID
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
afterInit(server: Server)
|
afterInit(server: Server)
|
||||||
{
|
{
|
||||||
console.log('ChatGateway initialized');
|
console.log('ChatGateway initialized');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
handleConnection(client: Socket, ...args: any[])
|
handleConnection(client: Socket, ...args: any[])
|
||||||
{
|
{
|
||||||
console.log(`Client connected: ${client.id}`);
|
console.log(`Client connected: ${client.id}`);
|
||||||
// console.log(`Client connected: ${args[0].username}`);
|
|
||||||
|
|
||||||
// const clientId = args[0].username;
|
|
||||||
const clientId = client.id;
|
const clientId = client.id;
|
||||||
this.clients[clientId] = client;
|
this.clients[clientId] = client;
|
||||||
// client.emit('chat:clientId', clientId);
|
|
||||||
console.log(`Total connected clients: ${Object.keys(this.clients).length}`);
|
console.log(`Total connected clients: ${Object.keys(this.clients).length}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
handleDisconnect(client: Socket)
|
handleDisconnect(client: Socket)
|
||||||
{
|
{
|
||||||
console.log(`Client want to deco: ${client.id}`);
|
|
||||||
|
|
||||||
// const disconnectedClientId = Object.keys(this.clients).find(clientId => this.clients[clientId] === client);
|
|
||||||
const disconnectedClientId = client.id
|
const disconnectedClientId = client.id
|
||||||
if (disconnectedClientId)
|
if (disconnectedClientId)
|
||||||
{
|
{
|
||||||
this.clientsNames.forEach((clientArray, clientName) =>
|
this.clientsNames.forEach((clientArray, clientName) =>
|
||||||
{
|
{
|
||||||
// clientArray.
|
|
||||||
console.log(`Clients with name ${clientName}:`);
|
|
||||||
console.log(`array= ${clientArray}`)
|
|
||||||
console.log(`lenght= ${clientArray.length}`)
|
|
||||||
clientArray.forEach((targetClient, index) =>
|
clientArray.forEach((targetClient, index) =>
|
||||||
{
|
{
|
||||||
console.log(`index= ${index}`)
|
|
||||||
console.log(`lenght2= ${clientArray.length}`)
|
|
||||||
if (targetClient === disconnectedClientId)
|
if (targetClient === disconnectedClientId)
|
||||||
{
|
{
|
||||||
console.log("find it")
|
|
||||||
console.log(`target= ${clientArray[index]}`)
|
|
||||||
// delete this.clientsNames[clientName][index];
|
|
||||||
if (clientArray.length === 1)
|
if (clientArray.length === 1)
|
||||||
{
|
{
|
||||||
console.log("delete true")
|
|
||||||
this.clientsNames.delete(clientName);
|
this.clientsNames.delete(clientName);
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -69,16 +46,11 @@ export class ChatGateway implements OnGatewayInit, OnGatewayConnection, OnGatewa
|
|||||||
this.clientsNames.delete(clientName);
|
this.clientsNames.delete(clientName);
|
||||||
this.clientsNames.set(clientName, newArray);
|
this.clientsNames.set(clientName, newArray);
|
||||||
}
|
}
|
||||||
//
|
|
||||||
// this.clientsNames[clientName].delete(index);
|
|
||||||
// else
|
|
||||||
|
|
||||||
return ;
|
return ;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
delete this.clients[disconnectedClientId];
|
delete this.clients[disconnectedClientId];
|
||||||
// delete this.clientsNames;
|
|
||||||
console.log(`Client disconnected: ${disconnectedClientId}`);
|
console.log(`Client disconnected: ${disconnectedClientId}`);
|
||||||
console.log(`Total connected clients: ${Object.keys(this.clients).length}`);
|
console.log(`Total connected clients: ${Object.keys(this.clients).length}`);
|
||||||
}
|
}
|
||||||
@ -86,22 +58,14 @@ export class ChatGateway implements OnGatewayInit, OnGatewayConnection, OnGatewa
|
|||||||
|
|
||||||
@SubscribeMessage('connection')
|
@SubscribeMessage('connection')
|
||||||
connectClient(client: any, payload: any): void {
|
connectClient(client: any, payload: any): void {
|
||||||
console.log("connect client")
|
|
||||||
console.log(`connect name: ${payload.username}`);
|
|
||||||
if (this.clientsNames.has(payload.username)) {
|
if (this.clientsNames.has(payload.username)) {
|
||||||
console.log("get it")
|
const clientArray = this.clientsNames.get(payload.username);
|
||||||
const clientArray = this.clientsNames.get(payload.username); // Retrieve the array
|
clientArray.push(client.id);
|
||||||
clientArray.push(client.id); // Add the new client to the array
|
|
||||||
} else {
|
} else {
|
||||||
console.log("create")
|
this.clientsNames.set(payload.username, [client.id]);
|
||||||
this.clientsNames.set(payload.username, [client.id]); // Create a new array with the new client as the value
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// @SubscribeMessage('socket.io')
|
|
||||||
// socketConnect(client: any, payload: any): void {
|
|
||||||
// console.log("/socket.io")
|
|
||||||
// }
|
|
||||||
|
|
||||||
@SubscribeMessage('ban')
|
@SubscribeMessage('ban')
|
||||||
banUser(client: any, payload: any): void {
|
banUser(client: any, payload: any): void {
|
||||||
@ -113,20 +77,9 @@ banUser(client: any, payload: any): void {
|
|||||||
const bannedClients = this.clientsNames.get(payload.username);
|
const bannedClients = this.clientsNames.get(payload.username);
|
||||||
bannedClients.forEach(client => {
|
bannedClients.forEach(client => {
|
||||||
console.log("Banning client:", client);
|
console.log("Banning client:", client);
|
||||||
// Perform ban operation on each client, e.g., emit a 'ban' event
|
|
||||||
console.log("clietn socket=", this.clients[client])
|
console.log("clietn socket=", this.clients[client])
|
||||||
this.clients[client].emit('ban', payload);
|
this.clients[client].emit('ban', payload);
|
||||||
});
|
});
|
||||||
// console.log("/ban")
|
|
||||||
// console.log("in ban username=", payload.username)
|
|
||||||
// if (!this.clientsNames[payload.username])
|
|
||||||
// {
|
|
||||||
// console.log("no user ??")
|
|
||||||
// return ;
|
|
||||||
// }
|
|
||||||
// this.clientsNames[payload.username].forEach()
|
|
||||||
// console.log("client=", this.clientsNames)
|
|
||||||
// this.clients[payload.username].emit('ban', payload)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@SubscribeMessage('mute')
|
@SubscribeMessage('mute')
|
||||||
@ -138,51 +91,28 @@ muteUser(client: any, payload: any): void {
|
|||||||
}
|
}
|
||||||
const mutedClients = this.clientsNames.get(payload.username);
|
const mutedClients = this.clientsNames.get(payload.username);
|
||||||
mutedClients.forEach(client => {
|
mutedClients.forEach(client => {
|
||||||
console.log("Banning client:", client);
|
|
||||||
// Perform ban operation on each client, e.g., emit a 'ban' event
|
|
||||||
console.log("clietn socket=", this.clients[client])
|
|
||||||
this.clients[client].emit('mute', payload);
|
this.clients[client].emit('mute', payload);
|
||||||
});
|
});
|
||||||
console.log("/mute")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@SubscribeMessage('sendMessage')
|
@SubscribeMessage('sendMessage')
|
||||||
handleMessage(client: Socket, payload: any): void {
|
handleMessage(client: Socket, payload: any): void {
|
||||||
// console.log(`message received: ${payload}`);
|
|
||||||
// console.log(`message sender: ${payload.sender}`);
|
|
||||||
// console.log(`client id: ${client.id}`);
|
|
||||||
// console.log(`conversation ID: ${payload.convId}`);
|
|
||||||
// console.log(`members: ${payload.members}`);
|
|
||||||
|
|
||||||
this.clientsNames.forEach((clientArray, clientName) =>
|
this.clientsNames.forEach((clientArray, clientName) =>
|
||||||
{
|
{
|
||||||
// console.log(` 5Clients with name ${clientName}:`);
|
|
||||||
if (payload.members.includes(clientName))
|
if (payload.members.includes(clientName))
|
||||||
{
|
{
|
||||||
clientArray.forEach((targetClient, index) =>
|
clientArray.forEach((targetClient, index) =>
|
||||||
{
|
{
|
||||||
// console.log(`client id: ${client.id}`);
|
|
||||||
// console.log(`target: ${targetClient}`);
|
|
||||||
// console.log(`target id: ${targetClient}`);
|
|
||||||
if (targetClient && targetClient !== client.id)
|
if (targetClient && targetClient !== client.id)
|
||||||
{
|
|
||||||
// console.log("Sending to someone");
|
|
||||||
// console.log(`index= ${index}`);
|
|
||||||
// console.log(`target: ${targetClient}`); // Perform actions on each target client
|
|
||||||
this.clients[targetClient].emit('message', payload)
|
this.clients[targetClient].emit('message', payload)
|
||||||
|
else
|
||||||
}
|
|
||||||
else {
|
|
||||||
console.log("not sending");
|
console.log("not sending");
|
||||||
}
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -13,25 +13,18 @@ async function bootstrap() {
|
|||||||
cors: {
|
cors: {
|
||||||
origin: '*',
|
origin: '*',
|
||||||
methods: '*',
|
methods: '*',
|
||||||
// preflightContinue: false,
|
|
||||||
// optionsSuccessStatus: 204,
|
|
||||||
// credentials: true,
|
|
||||||
allowedHeaders: '*',
|
allowedHeaders: '*',
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
// const app = await NestFactory.create(AppModule);
|
|
||||||
|
|
||||||
const httpServer = app.getHttpServer();
|
const httpServer = app.getHttpServer();
|
||||||
const io = new socketio.Server(httpServer);
|
const io = new socketio.Server(httpServer);
|
||||||
|
|
||||||
io.on('connection', (socket) => {
|
io.on('connection', (socket) => {
|
||||||
console.log('Client connected:', socket.id);
|
console.log('Client connected:', socket.id);
|
||||||
|
|
||||||
// Gestion des événements personnalisés ici
|
|
||||||
socket.on('customEvent', (data) => {
|
socket.on('customEvent', (data) => {
|
||||||
console.log('Custom event received:', data);
|
console.log('Custom event received:', data);
|
||||||
|
|
||||||
// Exemple de réponse à un événement personnalisé
|
|
||||||
socket.emit('customEventResponse', { message: 'Event processed.' });
|
socket.emit('customEventResponse', { message: 'Event processed.' });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@ -1,25 +1,5 @@
|
|||||||
// import { NestFactory } from '@nestjs/core';
|
|
||||||
// import { AppModule } from './app.module';
|
|
||||||
// import * as cors from 'cors';
|
|
||||||
|
|
||||||
// async function bootstrap() {
|
|
||||||
// const app = await NestFactory.create(AppModule);
|
|
||||||
|
|
||||||
// app.enableCors({
|
|
||||||
// origin: 'http://localhost:8080',
|
|
||||||
// methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
|
|
||||||
// allowedHeaders: ['Content-Type', 'Authorization'],
|
|
||||||
// credentials: true,
|
|
||||||
// });
|
|
||||||
|
|
||||||
// await app.listen(3000);
|
|
||||||
// }
|
|
||||||
// bootstrap();
|
|
||||||
|
|
||||||
import { NestFactory } from '@nestjs/core';
|
import { NestFactory } from '@nestjs/core';
|
||||||
import { AppModule } from './app.module';
|
import { AppModule } from './app.module';
|
||||||
import * as cors from 'cors';
|
|
||||||
import { Server } from 'socket.io';
|
|
||||||
import * as socketio from 'socket.io';
|
import * as socketio from 'socket.io';
|
||||||
import * as dotenv from 'dotenv';
|
import * as dotenv from 'dotenv';
|
||||||
|
|
||||||
@ -31,13 +11,9 @@ async function bootstrap() {
|
|||||||
cors: {
|
cors: {
|
||||||
origin: '*',
|
origin: '*',
|
||||||
methods: '*',
|
methods: '*',
|
||||||
// preflightContinue: false,
|
|
||||||
// optionsSuccessStatus: 204,
|
|
||||||
// credentials: true,
|
|
||||||
allowedHeaders: '*',
|
allowedHeaders: '*',
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
// const app = await NestFactory.create(AppModule);
|
|
||||||
|
|
||||||
const httpServer = app.getHttpServer();
|
const httpServer = app.getHttpServer();
|
||||||
const io = new socketio.Server(httpServer);
|
const io = new socketio.Server(httpServer);
|
||||||
|
|||||||
@ -6,12 +6,10 @@
|
|||||||
/* By: apommier <apommier@student.42.fr> +#+ +:+ +#+ */
|
/* By: apommier <apommier@student.42.fr> +#+ +:+ +#+ */
|
||||||
/* +#+#+#+#+#+ +#+ */
|
/* +#+#+#+#+#+ +#+ */
|
||||||
/* Created: 2023/06/19 15:18:38 by apommier #+# #+# */
|
/* Created: 2023/06/19 15:18:38 by apommier #+# #+# */
|
||||||
/* Updated: 2023/06/24 23:37:39 by apommier ### ########.fr */
|
/* Updated: 2023/06/26 07:04:47 by apommier ### ########.fr */
|
||||||
/* */
|
/* */
|
||||||
/* ************************************************************************** */
|
/* ************************************************************************** */
|
||||||
|
|
||||||
//0.0001
|
|
||||||
|
|
||||||
import { SubscribeMessage, WebSocketGateway, OnGatewayInit, WebSocketServer, OnGatewayConnection, OnGatewayDisconnect } from '@nestjs/websockets';
|
import { SubscribeMessage, WebSocketGateway, OnGatewayInit, WebSocketServer, OnGatewayConnection, OnGatewayDisconnect } from '@nestjs/websockets';
|
||||||
import { Server, Socket } from 'socket.io';
|
import { Server, Socket } from 'socket.io';
|
||||||
import { v4 as uuidv4 } from 'uuid';
|
import { v4 as uuidv4 } from 'uuid';
|
||||||
@ -30,7 +28,6 @@ export class PongGateway implements OnGatewayInit, OnGatewayConnection, OnGatewa
|
|||||||
private clients: Record<string, Socket> = {};
|
private clients: Record<string, Socket> = {};
|
||||||
|
|
||||||
private waitingClients: Set<{ client: Socket, option: number }> = new Set();
|
private waitingClients: Set<{ client: Socket, option: number }> = new Set();
|
||||||
// private waitingClients: Set<Socket> = new Set(); // Utilisateurs cherchant un match
|
|
||||||
private games: Map<string, Socket[]> = new Map(); // Parties en cours, identifiées par un ID
|
private games: Map<string, Socket[]> = new Map(); // Parties en cours, identifiées par un ID
|
||||||
|
|
||||||
afterInit(server: Server)
|
afterInit(server: Server)
|
||||||
@ -41,46 +38,31 @@ export class PongGateway implements OnGatewayInit, OnGatewayConnection, OnGatewa
|
|||||||
handleConnection(client: Socket, ...args: any[])
|
handleConnection(client: Socket, ...args: any[])
|
||||||
{
|
{
|
||||||
console.log(`Client connected: ${client.id}`);
|
console.log(`Client connected: ${client.id}`);
|
||||||
|
|
||||||
const clientId = client.id;
|
const clientId = client.id;
|
||||||
this.clients[clientId] = client;
|
this.clients[clientId] = client;
|
||||||
// client.emit('pong:clientId', clientId);
|
|
||||||
client.emit('pong:clientId', client.id);
|
client.emit('pong:clientId', client.id);
|
||||||
|
|
||||||
console.log(`Total connected clients: ${Object.keys(this.clients).length}`);
|
console.log(`Total connected clients: ${Object.keys(this.clients).length}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
handleDisconnect(client: Socket)
|
handleDisconnect(client: Socket)
|
||||||
{
|
{
|
||||||
console.log(`Normal disconnected: ${client.id}`);
|
|
||||||
|
|
||||||
this.waitingClients.forEach((item) => {
|
this.waitingClients.forEach((item) => {
|
||||||
if (item.client === client)
|
if (item.client === client)
|
||||||
this.waitingClients.delete(item);
|
this.waitingClients.delete(item);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Delete the socket from the 'games' map
|
|
||||||
this.games.forEach((sockets, gameId) => {
|
this.games.forEach((sockets, gameId) => {
|
||||||
const index = sockets.indexOf(client);
|
const index = sockets.indexOf(client);
|
||||||
if (index !== -1)
|
if (index !== -1)
|
||||||
{
|
{
|
||||||
if (index === 0)
|
if (index === 0)
|
||||||
{
|
|
||||||
console.log("emit boy1")
|
|
||||||
sockets[1].emit("pong:win")
|
sockets[1].emit("pong:win")
|
||||||
// sockets[0].emit("/win")
|
|
||||||
}
|
|
||||||
else
|
else
|
||||||
{
|
|
||||||
console.log("emit boy2")
|
|
||||||
sockets[0].emit("pong:win")
|
sockets[0].emit("pong:win")
|
||||||
// sockets[1].emit("/win")
|
|
||||||
}
|
|
||||||
this.games.delete(gameId);
|
this.games.delete(gameId);
|
||||||
delete this.clients[client.id];
|
delete this.clients[client.id];
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
console.log(`Total connected clients: ${Object.keys(this.clients).length}`);
|
console.log(`Total connected clients: ${Object.keys(this.clients).length}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -93,29 +75,19 @@ export class PongGateway implements OnGatewayInit, OnGatewayConnection, OnGatewa
|
|||||||
if (this.clients.hasOwnProperty(key) && this.clients[key] === client)
|
if (this.clients.hasOwnProperty(key) && this.clients[key] === client)
|
||||||
delete this.clients[key];
|
delete this.clients[key];
|
||||||
}
|
}
|
||||||
// Delete the socket from the 'waitingClients' set
|
|
||||||
this.waitingClients.forEach((item) => {
|
this.waitingClients.forEach((item) => {
|
||||||
if (item.client === client)
|
if (item.client === client)
|
||||||
this.waitingClients.delete(item);
|
this.waitingClients.delete(item);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Delete the socket from the 'games' map
|
|
||||||
this.games.forEach((sockets, gameId) => {
|
this.games.forEach((sockets, gameId) => {
|
||||||
const index = sockets.indexOf(client);
|
const index = sockets.indexOf(client);
|
||||||
if (index !== -1)
|
if (index !== -1)
|
||||||
{
|
{
|
||||||
if (index === 0)
|
if (index === 0)
|
||||||
{
|
|
||||||
console.log("emit boy1")
|
|
||||||
sockets[1].emit("pong:win")
|
sockets[1].emit("pong:win")
|
||||||
// sockets[0].emit("/win")
|
|
||||||
}
|
|
||||||
else
|
else
|
||||||
{
|
|
||||||
console.log("emit boy2")
|
|
||||||
sockets[0].emit("pong:win")
|
sockets[0].emit("pong:win")
|
||||||
// sockets[1].emit("/win")
|
|
||||||
}
|
|
||||||
this.games.delete(gameId);
|
this.games.delete(gameId);
|
||||||
delete this.clients[client.id];
|
delete this.clients[client.id];
|
||||||
}
|
}
|
||||||
@ -131,29 +103,18 @@ export class PongGateway implements OnGatewayInit, OnGatewayConnection, OnGatewa
|
|||||||
|
|
||||||
@SubscribeMessage('pong:matchmaking')
|
@SubscribeMessage('pong:matchmaking')
|
||||||
addMatchmaking(client: Socket, payload: any): void {
|
addMatchmaking(client: Socket, payload: any): void {
|
||||||
console.log("matchmaking");
|
|
||||||
console.log(payload);
|
|
||||||
console.log(`option= ${payload.option}`);
|
|
||||||
// Add the client to the waitingClients set along with their chosen option
|
|
||||||
this.waitingClients.add({ client, option: payload.option });
|
this.waitingClients.add({ client, option: payload.option });
|
||||||
console.log("Adding client to waiting list...");
|
console.log("Adding client to waiting list...");
|
||||||
|
|
||||||
// Filter the waitingClients set to find clients with the same option
|
|
||||||
const matchingClients = Array.from(this.waitingClients).filter(
|
const matchingClients = Array.from(this.waitingClients).filter(
|
||||||
(waitingClient) =>
|
(waitingClient) =>
|
||||||
waitingClient.option === payload.option && waitingClient.client !== client
|
waitingClient.option === payload.option && waitingClient.client !== client
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
||||||
if (matchingClients.length > 0) {
|
if (matchingClients.length > 0) {
|
||||||
console.log("Creating new game...");
|
console.log("Creating new game...");
|
||||||
const players = [matchingClients[0].client, client]; // Add the current client to the players array
|
const players = [matchingClients[0].client, client];
|
||||||
players.forEach((player) => {
|
players.forEach((player) => {
|
||||||
// this.waitingClients.delete(
|
|
||||||
// this.waitingClients.find(
|
|
||||||
// (waitingClient) => waitingClient.client === player
|
|
||||||
// )
|
|
||||||
// );
|
|
||||||
const matchingClient = Array.from(this.waitingClients).find(
|
const matchingClient = Array.from(this.waitingClients).find(
|
||||||
(waitingClient) => waitingClient.client === player
|
(waitingClient) => waitingClient.client === player
|
||||||
);
|
);
|
||||||
@ -172,8 +133,6 @@ addMatchmaking(client: Socket, payload: any): void {
|
|||||||
player.emit('pong:gameId', payload);
|
player.emit('pong:gameId', payload);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// console.log(`from: ${client.id}`);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -185,19 +144,8 @@ addMatchmaking(client: Socket, payload: any): void {
|
|||||||
//========================================================================================================
|
//========================================================================================================
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// @SubscribeMessage('pong:invite')
|
|
||||||
// createPrivateGame(client: Socket, payload: any): void {
|
|
||||||
// //after invite accepted ?
|
|
||||||
// //set the two user in a game ?
|
|
||||||
|
|
||||||
// }
|
|
||||||
|
|
||||||
|
|
||||||
@SubscribeMessage('pong:joinParty')
|
@SubscribeMessage('pong:joinParty')
|
||||||
joinPrivateParty(client: Socket, payload: any): void {
|
joinPrivateParty(client: Socket, payload: any): void {
|
||||||
console.log(" join PrivateParty")
|
|
||||||
|
|
||||||
const game = this.games.get(payload.gameId);
|
const game = this.games.get(payload.gameId);
|
||||||
if (game)
|
if (game)
|
||||||
{
|
{
|
||||||
@ -207,26 +155,16 @@ joinPrivateParty(client: Socket, payload: any): void {
|
|||||||
this.clients[playersIds[1]].emit('pong:gameId', payload);
|
this.clients[playersIds[1]].emit('pong:gameId', payload);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
|
||||||
console.log("emit else")
|
|
||||||
client.emit("pong:win")
|
client.emit("pong:win")
|
||||||
}
|
|
||||||
// console.log("no game ???")
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@SubscribeMessage('pong:privateParty')
|
@SubscribeMessage('pong:privateParty')
|
||||||
addPrivateParty(client: Socket, payload: any): void {
|
addPrivateParty(client: Socket, payload: any): void {
|
||||||
console.log("addPrivateParty")
|
|
||||||
|
|
||||||
const gameId = uuidv4();
|
const gameId = uuidv4();
|
||||||
const players = [client];
|
const players = [client];
|
||||||
this.games.set(gameId, players);
|
this.games.set(gameId, players);
|
||||||
console.log("game created private")
|
|
||||||
client.emit('pong:privateId', gameId);
|
client.emit('pong:privateId', gameId);
|
||||||
//create game
|
|
||||||
//emit private gameId to canvas (don't launch canvas)
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -247,7 +185,6 @@ addPrivateParty(client: Socket, payload: any): void {
|
|||||||
sendPower(client: Socket, payload: any): void
|
sendPower(client: Socket, payload: any): void
|
||||||
{
|
{
|
||||||
console.log(`from: ${client.id}`);
|
console.log(`from: ${client.id}`);
|
||||||
console.log(payload);
|
|
||||||
|
|
||||||
const game = this.games.get(payload.gameId);
|
const game = this.games.get(payload.gameId);
|
||||||
const playersIds = game.map(socket => socket.id);
|
const playersIds = game.map(socket => socket.id);
|
||||||
@ -255,14 +192,12 @@ addPrivateParty(client: Socket, payload: any): void {
|
|||||||
this.clients[playersIds[1]].emit('pong:power', payload);
|
this.clients[playersIds[1]].emit('pong:power', payload);
|
||||||
else if (playersIds[1] === payload.id)
|
else if (playersIds[1] === payload.id)
|
||||||
this.clients[playersIds[0]].emit('pong:power', payload);
|
this.clients[playersIds[0]].emit('pong:power', payload);
|
||||||
console.log("END OF HANDLE");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@SubscribeMessage('pong:message')
|
@SubscribeMessage('pong:message')
|
||||||
handleMessage(client: Socket, payload: any): void
|
handleMessage(client: Socket, payload: any): void
|
||||||
{
|
{
|
||||||
console.log(`from: ${client.id}`);
|
console.log(`from: ${client.id}`);
|
||||||
console.log(payload);
|
|
||||||
|
|
||||||
const game = this.games.get(payload.gameId);
|
const game = this.games.get(payload.gameId);
|
||||||
const playersIds = game.map(socket => socket.id);
|
const playersIds = game.map(socket => socket.id);
|
||||||
@ -276,20 +211,14 @@ addPrivateParty(client: Socket, payload: any): void {
|
|||||||
if (payload.ballX < payload.width / 2)
|
if (payload.ballX < payload.width / 2)
|
||||||
this.clients[playersIds[0]].emit('pong:info', payload);
|
this.clients[playersIds[0]].emit('pong:info', payload);
|
||||||
}
|
}
|
||||||
console.log("END OF HANDLE");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@SubscribeMessage('pong:forced')
|
@SubscribeMessage('pong:forced')
|
||||||
forcedMessage(client: Socket, payload: any): void
|
forcedMessage(client: Socket, payload: any): void
|
||||||
{
|
{
|
||||||
// console.log(`from: ${client.id}`);
|
|
||||||
// console.log(payload);
|
|
||||||
|
|
||||||
const game = this.games.get(payload.gameId);
|
const game = this.games.get(payload.gameId);
|
||||||
const playersIds = game.map(socket => socket.id);
|
const playersIds = game.map(socket => socket.id);
|
||||||
|
|
||||||
// console.log(`id of 0= ${playersIds[0]}`);
|
|
||||||
|
|
||||||
if (playersIds[0] === payload.id)
|
if (playersIds[0] === payload.id)
|
||||||
{
|
{
|
||||||
this.clients[playersIds[1]].emit('pong:info', payload);
|
this.clients[playersIds[1]].emit('pong:info', payload);
|
||||||
@ -298,20 +227,13 @@ addPrivateParty(client: Socket, payload: any): void {
|
|||||||
{
|
{
|
||||||
this.clients[playersIds[0]].emit('pong:info', payload);
|
this.clients[playersIds[0]].emit('pong:info', payload);
|
||||||
}
|
}
|
||||||
// console.log("END OF HANDLE");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@SubscribeMessage('pong:paddle')
|
@SubscribeMessage('pong:paddle')
|
||||||
handlePaddle(client: Socket, payload: any): void
|
handlePaddle(client: Socket, payload: any): void
|
||||||
{
|
{
|
||||||
// console.log(`from: ${client.id}`);
|
|
||||||
// console.log(payload);
|
|
||||||
|
|
||||||
const game = this.games.get(payload.gameId);
|
const game = this.games.get(payload.gameId);
|
||||||
const playersIds = game.map(socket => socket.id);
|
const playersIds = game.map(socket => socket.id);
|
||||||
|
|
||||||
// console.log(`id of 0= ${playersIds[0]}`);
|
|
||||||
|
|
||||||
if (playersIds[0] === payload.id)
|
if (playersIds[0] === payload.id)
|
||||||
{
|
{
|
||||||
this.clients[playersIds[1]].emit('pong:paddle', payload);
|
this.clients[playersIds[1]].emit('pong:paddle', payload);
|
||||||
@ -320,7 +242,6 @@ addPrivateParty(client: Socket, payload: any): void {
|
|||||||
{
|
{
|
||||||
this.clients[playersIds[0]].emit('pong:paddle', payload);
|
this.clients[playersIds[0]].emit('pong:paddle', payload);
|
||||||
}
|
}
|
||||||
// console.log("END OF HANDLE");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@SubscribeMessage('pong:point')
|
@SubscribeMessage('pong:point')
|
||||||
@ -348,14 +269,9 @@ addPrivateParty(client: Socket, payload: any): void {
|
|||||||
console.log(`id of 0 mypoint= ${playersIds[0]}`);
|
console.log(`id of 0 mypoint= ${playersIds[0]}`);
|
||||||
|
|
||||||
if (playersIds[0] === payload.id)
|
if (playersIds[0] === payload.id)
|
||||||
{
|
|
||||||
this.clients[playersIds[1]].emit('pong:hisPoint', payload);
|
this.clients[playersIds[1]].emit('pong:hisPoint', payload);
|
||||||
|
|
||||||
}
|
|
||||||
else if (playersIds[1] === payload.id)
|
else if (playersIds[1] === payload.id)
|
||||||
{
|
|
||||||
this.clients[playersIds[0]].emit('pong:hisPoint', payload);
|
this.clients[playersIds[0]].emit('pong:hisPoint', payload);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@SubscribeMessage('pong:name')
|
@SubscribeMessage('pong:name')
|
||||||
|
|||||||
@ -6,7 +6,6 @@ import Home from "../pages/Home.tsx";
|
|||||||
|
|
||||||
import PlayButton from "./Game/PlayButton.tsx";
|
import PlayButton from "./Game/PlayButton.tsx";
|
||||||
import Field from "../pages/Field.tsx";
|
import Field from "../pages/Field.tsx";
|
||||||
import Login42 from "../pages/Login42.tsx";
|
|
||||||
import Messages from "../pages/Messages.tsx";
|
import Messages from "../pages/Messages.tsx";
|
||||||
import QrCode from '../pages/QrCode.tsx'
|
import QrCode from '../pages/QrCode.tsx'
|
||||||
import { useLocation } from "react-router-dom";
|
import { useLocation } from "react-router-dom";
|
||||||
@ -23,10 +22,9 @@ import api from "../script/axiosApi.tsx"
|
|||||||
|
|
||||||
|
|
||||||
function AnimatedRoute () {
|
function AnimatedRoute () {
|
||||||
// const location = useLocation();
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const handleBeforeUnload = async (event: { preventDefault: () => void; returnValue: string; }) => {
|
const handleBeforeUnload = async (event: { preventDefault: () => void; returnValue: string; }) => {
|
||||||
|
console.log("git ")
|
||||||
if (!localStorage.getItem('token'))
|
if (!localStorage.getItem('token'))
|
||||||
return ;
|
return ;
|
||||||
try {
|
try {
|
||||||
@ -36,10 +34,17 @@ function AnimatedRoute () {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleLoad = async () => {
|
||||||
|
await api.post("/addSession")
|
||||||
|
console.log('Page loaded');
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener('load', handleLoad);
|
||||||
window.addEventListener('beforeunload', handleBeforeUnload);
|
window.addEventListener('beforeunload', handleBeforeUnload);
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
window.removeEventListener('beforeunload', handleBeforeUnload);
|
window.removeEventListener('beforeunload', handleBeforeUnload);
|
||||||
|
window.removeEventListener('load', handleLoad);
|
||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
@ -51,9 +56,6 @@ function AnimatedRoute () {
|
|||||||
<Routes location={location} key={location.pathname}>
|
<Routes location={location} key={location.pathname}>
|
||||||
<Route path="/" element={<HomeLogin/>}/>
|
<Route path="/" element={<HomeLogin/>}/>
|
||||||
<Route path="/token" element={<SuccessToken />}/>
|
<Route path="/token" element={<SuccessToken />}/>
|
||||||
|
|
||||||
{/* <Route path="/404" element={<HomeLogin/>} /> */}
|
|
||||||
{/* <Route path="*" element={<Navigate to="/404" />} /> */}
|
|
||||||
</Routes>
|
</Routes>
|
||||||
</AnimatePresence>
|
</AnimatePresence>
|
||||||
)
|
)
|
||||||
@ -62,26 +64,18 @@ function AnimatedRoute () {
|
|||||||
return (
|
return (
|
||||||
<AnimatePresence>
|
<AnimatePresence>
|
||||||
<Routes location={location} key={location.pathname}>
|
<Routes location={location} key={location.pathname}>
|
||||||
|
|
||||||
{/* <Route path="/login" element={<HomeLogin/>}/> */}
|
|
||||||
<Route path="/" element={<Home/>}/>
|
<Route path="/" element={<Home/>}/>
|
||||||
<Route path="/profile" element={<Home/>}/>
|
<Route path="/profile" element={<Home/>}/>
|
||||||
<Route path="/profile/:username" element={<Home/>}/>
|
<Route path="/profile/:username" element={<Home/>}/>
|
||||||
<Route path="/qr" element={<QrCode/>}/>
|
<Route path="/qr" element={<QrCode/>}/>
|
||||||
|
|
||||||
<Route path="/2fa" element={<DoubleAuth/>}/>
|
<Route path="/2fa" element={<DoubleAuth/>}/>
|
||||||
<Route path="/Social" element={<Social/>}/>
|
<Route path="/Social" element={<Social/>}/>
|
||||||
|
|
||||||
<Route path="/token" element={<SuccessToken />}/>
|
<Route path="/token" element={<SuccessToken />}/>
|
||||||
<Route path="/game" element={<PlayButton />}/>
|
<Route path="/game" element={<PlayButton />}/>
|
||||||
<Route path="/pong" element={<Game />}/>
|
<Route path="/pong" element={<Game />}/>
|
||||||
<Route path="/pong/play" element={<Field />}/>
|
<Route path="/pong/play" element={<Field />}/>
|
||||||
{/* <Route path="/profile" element={<PlayButton />}/> */}
|
|
||||||
|
|
||||||
<Route path="/login42" element={<Login42 />}/>
|
|
||||||
<Route path="/logout" element={<Logout />}/>
|
<Route path="/logout" element={<Logout />}/>
|
||||||
<Route path="/messages" element={<Messages />}/>
|
<Route path="/messages" element={<Messages />}/>
|
||||||
|
|
||||||
<Route path="/404" element={<PageNotFound />} />
|
<Route path="/404" element={<PageNotFound />} />
|
||||||
<Route path="*" element={<Navigate to="/404" />} />
|
<Route path="*" element={<Navigate to="/404" />} />
|
||||||
</Routes>
|
</Routes>
|
||||||
|
|||||||
@ -2,14 +2,12 @@ import React, { useState, useEffect, useRef } from "react";
|
|||||||
import io, { Socket } from 'socket.io-client';
|
import io, { Socket } from 'socket.io-client';
|
||||||
import '../../styles/Messages.css'
|
import '../../styles/Messages.css'
|
||||||
import styled from "styled-components";
|
import styled from "styled-components";
|
||||||
import DefaultPic from '../../assets/profile.jpg'
|
|
||||||
import api from '../../script/axiosApi.tsx';
|
import api from '../../script/axiosApi.tsx';
|
||||||
import { motion , AnimatePresence} from "framer-motion";
|
import { motion , AnimatePresence} from "framer-motion";
|
||||||
import Modal from "./Modal.tsx";
|
import Modal from "./Modal.tsx";
|
||||||
import GameModal from "./GameModal.tsx";
|
import GameModal from "./GameModal.tsx";
|
||||||
|
|
||||||
import Message from "./Message.tsx"
|
import Message from "./Message.tsx"
|
||||||
// import Input from "./Input";
|
|
||||||
|
|
||||||
//react icons
|
//react icons
|
||||||
import { TbSend } from 'react-icons/tb';
|
import { TbSend } from 'react-icons/tb';
|
||||||
@ -19,14 +17,11 @@ import { GrAdd } from 'react-icons/gr';
|
|||||||
import { RiListSettingsLine } from 'react-icons/ri'
|
import { RiListSettingsLine } from 'react-icons/ri'
|
||||||
import { HiChatBubbleLeft } from 'react-icons/hi2'
|
import { HiChatBubbleLeft } from 'react-icons/hi2'
|
||||||
|
|
||||||
// import { Rank } from "../../DataBase/DataRank";
|
|
||||||
import GreenAlert from "../Alert/GreenAlert.tsx";
|
import GreenAlert from "../Alert/GreenAlert.tsx";
|
||||||
import RedAlert from "../Alert/RedAlert.tsx";
|
import RedAlert from "../Alert/RedAlert.tsx";
|
||||||
import YellowAlert from "../Alert/YellowAlert";
|
|
||||||
import ModalSetting from "./ModalSetting.tsx";
|
import ModalSetting from "./ModalSetting.tsx";
|
||||||
import PartyInvite from "./PartyInvite.tsx";
|
import PartyInvite from "./PartyInvite.tsx";
|
||||||
|
|
||||||
// import {User, Conv, Message} from "../../../interfaces.tsx"
|
|
||||||
import {User, Conv} from "../../../interfaces.tsx"
|
import {User, Conv} from "../../../interfaces.tsx"
|
||||||
import { IoLogoOctocat } from "react-icons/io5";
|
import { IoLogoOctocat } from "react-icons/io5";
|
||||||
|
|
||||||
@ -59,11 +54,6 @@ const UserChat = styled.div `
|
|||||||
}
|
}
|
||||||
`
|
`
|
||||||
|
|
||||||
// const SideSpan = styled.span`
|
|
||||||
// font-size: 18px;
|
|
||||||
// font-weight: 500;
|
|
||||||
// `
|
|
||||||
|
|
||||||
const SideP = styled.p`
|
const SideP = styled.p`
|
||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
color: lightgray;
|
color: lightgray;
|
||||||
@ -92,15 +82,11 @@ function Chats(){
|
|||||||
const [user, setUser] = useState<User>();
|
const [user, setUser] = useState<User>();
|
||||||
const [currentChat, setCurrentChat] = useState<Conv>(); // false is good?
|
const [currentChat, setCurrentChat] = useState<Conv>(); // false is good?
|
||||||
const [isAdmin, setIsAdmin] = useState<boolean>(false); // false is good?
|
const [isAdmin, setIsAdmin] = useState<boolean>(false); // false is good?
|
||||||
// const [currentChat, setCurrentChat] = useState(false); // false is good?
|
|
||||||
const [messages, setMessage] = useState<MessageProps[]>([]);
|
const [messages, setMessage] = useState<MessageProps[]>([]);
|
||||||
const [newMessages, setNewMessage] = useState("");
|
const [newMessages, setNewMessage] = useState("");
|
||||||
const [incomingMessage, setIncomingMessage] = useState<MessageProps>();
|
const [incomingMessage, setIncomingMessage] = useState<MessageProps>();
|
||||||
|
|
||||||
// let socket: Socket;
|
|
||||||
const socket = useRef<Socket | null>(null);
|
const socket = useRef<Socket | null>(null);
|
||||||
// const socket = Socket<DefaultEventsMap, DefaultEventsMap> | null
|
|
||||||
// socket = useRef( useRef<SocketIOClient.Socket | null>(null));
|
|
||||||
|
|
||||||
|
|
||||||
useEffect(()=> {
|
useEffect(()=> {
|
||||||
@ -114,47 +100,38 @@ function Chats(){
|
|||||||
|
|
||||||
console.log(convs);
|
console.log(convs);
|
||||||
|
|
||||||
// console.log("invite data use effect= ", tmpInvite.data);
|
|
||||||
setPartyInvite(tmpInvite.data);
|
setPartyInvite(tmpInvite.data);
|
||||||
setUser(tmpUser.data);
|
setUser(tmpUser.data);
|
||||||
setConversation(convs.data);
|
setConversation(convs.data);
|
||||||
setUsers(tmpUsers.data);
|
setUsers(tmpUsers.data);
|
||||||
|
|
||||||
// console.log(`connection....`);
|
|
||||||
socket.current = io('http://' + process.env.REACT_APP_SOCKET_URL + ':4001', { transports: ['polling'] });
|
socket.current = io('http://' + process.env.REACT_APP_SOCKET_URL + ':4001', { transports: ['polling'] });
|
||||||
// console.log(`connection done`);
|
|
||||||
socket.current.emit('connection', {username: tmpUser.data.username})
|
socket.current.emit('connection', {username: tmpUser.data.username})
|
||||||
socket.current.on('message', (data) => { //data should be a message ?)
|
socket.current.on('message', (data) => { //data should be a message ?)
|
||||||
setIncomingMessage(data);
|
setIncomingMessage(data);
|
||||||
});
|
});
|
||||||
|
|
||||||
socket.current.on('ban', (data) => {
|
socket.current.on('ban', (data) => {
|
||||||
// setIncomingMessage(data);
|
|
||||||
console.log("banned hehe");
|
|
||||||
window.location.reload()
|
window.location.reload()
|
||||||
});
|
});
|
||||||
|
|
||||||
socket.current.on('mute', (data) => {
|
// socket.current.on('mute', (data) => {
|
||||||
console.log("muted hehe");
|
// console.log("muted hehe");
|
||||||
//set mute var to true and do nothing
|
// //set mute var to true and do nothing
|
||||||
});
|
// });
|
||||||
|
|
||||||
setIsLoading(false)
|
setIsLoading(false)
|
||||||
|
|
||||||
}
|
}
|
||||||
catch(err){
|
catch(err){
|
||||||
console.log("ERRORRRRR")
|
|
||||||
console.log(err);
|
console.log(err);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
getConv();
|
getConv();
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
console.log("Cleanup");
|
|
||||||
if (socket.current)
|
if (socket.current)
|
||||||
socket.current.disconnect();
|
socket.current.disconnect();
|
||||||
// cleanup(); // Call the cleanup function to stop the ongoing process or perform necessary cleanup tasks
|
|
||||||
// cleanup();
|
|
||||||
};
|
};
|
||||||
|
|
||||||
}, [])
|
}, [])
|
||||||
@ -162,14 +139,11 @@ function Chats(){
|
|||||||
useEffect(()=> {
|
useEffect(()=> {
|
||||||
|
|
||||||
const updateChat = async ()=> {
|
const updateChat = async ()=> {
|
||||||
// if (currentChat)
|
|
||||||
// console.log(currentChat.id)
|
|
||||||
if (currentChat)
|
if (currentChat)
|
||||||
{
|
{
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await api.post("/isAdmin", {convId: currentChat.id})
|
const res = await api.post("/isAdmin", {convId: currentChat.id})
|
||||||
console.log("isadmin= ", res.data)
|
|
||||||
setIsAdmin(res.data);
|
setIsAdmin(res.data);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log(err);
|
console.log(err);
|
||||||
@ -177,13 +151,7 @@ function Chats(){
|
|||||||
}
|
}
|
||||||
// console.log(`result1 = ${currentChat.id !== incomingMessage.convId}`)
|
// console.log(`result1 = ${currentChat.id !== incomingMessage.convId}`)
|
||||||
if (currentChat && incomingMessage && currentChat.id === incomingMessage.convId)
|
if (currentChat && incomingMessage && currentChat.id === incomingMessage.convId)
|
||||||
{
|
setMessage((prev) => [...prev, incomingMessage]);
|
||||||
console.log("incoming meaasge=",incomingMessage)
|
|
||||||
// if (user && !user.blocked.find(incomingMessage.sender))
|
|
||||||
// setMessage((prev) => [...prev, incomingMessage, key: incomingMessage.id]);
|
|
||||||
// setMessage((prev) => [...prev, { ...incomingMessage, key: incomingMessage.id }]);
|
|
||||||
setMessage((prev) => [...prev, incomingMessage]);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
updateChat();
|
updateChat();
|
||||||
|
|
||||||
@ -198,7 +166,6 @@ function Chats(){
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await api.post('/getMessage', data);
|
const res = await api.post('/getMessage', data);
|
||||||
console.log("message of conv=", res.data)
|
|
||||||
setMessage(res.data);
|
setMessage(res.data);
|
||||||
} catch(err) {
|
} catch(err) {
|
||||||
|
|
||||||
@ -209,10 +176,6 @@ function Chats(){
|
|||||||
|
|
||||||
const handleSubmit = async (e: { key?: any; preventDefault: any; })=>{
|
const handleSubmit = async (e: { key?: any; preventDefault: any; })=>{
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
// console.log(`e= ${e.key}`)
|
|
||||||
// console.log(`name= ${user.username}`)
|
|
||||||
// let message;
|
|
||||||
console.log("in handle");
|
|
||||||
if (!user || !currentChat)
|
if (!user || !currentChat)
|
||||||
return ;
|
return ;
|
||||||
const message = {
|
const message = {
|
||||||
@ -224,13 +187,8 @@ function Chats(){
|
|||||||
};
|
};
|
||||||
try{
|
try{
|
||||||
const allowed = await api.post('/allowed', {convId: currentChat.id});
|
const allowed = await api.post('/allowed', {convId: currentChat.id});
|
||||||
console.log("convid:", currentChat.id);
|
|
||||||
if (!allowed.data)
|
if (!allowed.data)
|
||||||
{
|
|
||||||
console.log("muted or banned");
|
|
||||||
return ;
|
return ;
|
||||||
}
|
|
||||||
console.log("not muted or banned");
|
|
||||||
const res = await api.post('/message', message);
|
const res = await api.post('/message', message);
|
||||||
const convMember = await api.post('/member', message);
|
const convMember = await api.post('/member', message);
|
||||||
message.members = convMember.data.members;
|
message.members = convMember.data.members;
|
||||||
@ -246,7 +204,6 @@ function Chats(){
|
|||||||
}
|
}
|
||||||
|
|
||||||
const handleKeyPress = async (e: { key?: any; preventDefault: () => void; })=> {
|
const handleKeyPress = async (e: { key?: any; preventDefault: () => void; })=> {
|
||||||
// console.log(`e in press= ${e.key}`)
|
|
||||||
if (e.key !== "Enter")
|
if (e.key !== "Enter")
|
||||||
return ;
|
return ;
|
||||||
handleSubmit(e);
|
handleSubmit(e);
|
||||||
@ -255,7 +212,6 @@ function Chats(){
|
|||||||
|
|
||||||
|
|
||||||
const [friend, setFriend] = useState("");
|
const [friend, setFriend] = useState("");
|
||||||
// const [modalOpen, setModalOpen] = useState(false);
|
|
||||||
const [addFriend, setAddFriend] = useState(false);
|
const [addFriend, setAddFriend] = useState(false);
|
||||||
const [block, setBlock] = useState(false);
|
const [block, setBlock] = useState(false);
|
||||||
|
|
||||||
@ -289,17 +245,8 @@ function Chats(){
|
|||||||
setNewConversationModalOpen(false);
|
setNewConversationModalOpen(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
// const close = () => setModalOpen(false);
|
|
||||||
// const open = () => setModalOpen(true);
|
|
||||||
// const closeAddFriend = () => setAddFriend(false);
|
|
||||||
// const closeBlock = () => setBlock(false);
|
|
||||||
const closeSetting = () => setSetting(false);
|
const closeSetting = () => setSetting(false);
|
||||||
|
|
||||||
|
|
||||||
// const closeAddFriend = () => setAddFriend(false);
|
|
||||||
// const closeBlock = () => setBlock(false);
|
|
||||||
|
|
||||||
|
|
||||||
const handleFriend = (event: { target: { value: React.SetStateAction<string>; }; }) => {
|
const handleFriend = (event: { target: { value: React.SetStateAction<string>; }; }) => {
|
||||||
setFriend(event.target.value);
|
setFriend(event.target.value);
|
||||||
};
|
};
|
||||||
@ -308,8 +255,6 @@ function Chats(){
|
|||||||
try{
|
try{
|
||||||
console.log("friend= ", friend);
|
console.log("friend= ", friend);
|
||||||
const res = await api.post("/invite", {username: friend})
|
const res = await api.post("/invite", {username: friend})
|
||||||
// if (res.data === 1)
|
|
||||||
// console.log("res in friend= ", res)
|
|
||||||
console.log("res in friend= ", res.data)
|
console.log("res in friend= ", res.data)
|
||||||
if(res.data === 1)
|
if(res.data === 1)
|
||||||
{
|
{
|
||||||
@ -335,7 +280,7 @@ function Chats(){
|
|||||||
if (res.data === 1)
|
if (res.data === 1)
|
||||||
{
|
{
|
||||||
setBlock(true);
|
setBlock(true);
|
||||||
setAddFriend(false); // Reset addFriend state
|
setAddFriend(false);
|
||||||
setShowAddFriendAlert(false);
|
setShowAddFriendAlert(false);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
@ -377,7 +322,6 @@ function Chats(){
|
|||||||
<div className="chat">
|
<div className="chat">
|
||||||
|
|
||||||
<div className='navbar'>
|
<div className='navbar'>
|
||||||
{/* <img src={DefaultPic} alt="profile" className="pic"/> */}
|
|
||||||
<IoLogoOctocat className="catchat"/>
|
<IoLogoOctocat className="catchat"/>
|
||||||
<span>
|
<span>
|
||||||
{isLoading || !user ? (
|
{isLoading || !user ? (
|
||||||
@ -386,50 +330,6 @@ function Chats(){
|
|||||||
<h2>Chat</h2>
|
<h2>Chat</h2>
|
||||||
)}
|
)}
|
||||||
</span>
|
</span>
|
||||||
{/* <div className="end">
|
|
||||||
<input className="lookForFriends" type="text" value={friend} onChange={handleFriend}/>
|
|
||||||
<TouchDiv>
|
|
||||||
<motion.div
|
|
||||||
onClick={() => (addFriend ? setAddFriend(false) : setAddFriend(true))}>
|
|
||||||
<MdOutlineGroupAdd/>
|
|
||||||
</motion.div>
|
|
||||||
<AnimatePresence
|
|
||||||
initial={false}
|
|
||||||
onExitComplete={() => null}
|
|
||||||
>
|
|
||||||
{addFriend && <GreenAlert handleClose={closeAddFriend} text={friend + " was successfuly added"}/>}
|
|
||||||
</AnimatePresence>
|
|
||||||
</TouchDiv>
|
|
||||||
<TouchDiv>
|
|
||||||
<motion.div
|
|
||||||
onClick={() => (block ? setBlock(false) : setBlock(true))}
|
|
||||||
>
|
|
||||||
<ImBlocked/>
|
|
||||||
<AnimatePresence
|
|
||||||
initial={false}
|
|
||||||
onExitComplete={() => null}
|
|
||||||
>
|
|
||||||
{block && <RedAlert handleClose={closeBlock} text={friend + " was successfuly blocked"}/>}
|
|
||||||
</AnimatePresence>
|
|
||||||
</motion.div>
|
|
||||||
</TouchDiv>
|
|
||||||
{currentChat ? (
|
|
||||||
|
|
||||||
<TouchDiv>
|
|
||||||
<motion.div
|
|
||||||
onClick={() => (setting ? setSetting(false) : setSetting(true))}
|
|
||||||
>
|
|
||||||
<RiListSettingsLine/>
|
|
||||||
<AnimatePresence
|
|
||||||
initial={false}
|
|
||||||
onExitComplete={() => null}
|
|
||||||
>
|
|
||||||
{setting && <ModalSetting handleClose={closeSetting} convId={currentChat.id}/>}
|
|
||||||
</AnimatePresence>
|
|
||||||
</motion.div>
|
|
||||||
</TouchDiv>
|
|
||||||
):("")}
|
|
||||||
</div> */}
|
|
||||||
|
|
||||||
<div className="end">
|
<div className="end">
|
||||||
{selectTags.map((selectTag) => (
|
{selectTags.map((selectTag) => (
|
||||||
@ -519,13 +419,6 @@ function Chats(){
|
|||||||
)}
|
)}
|
||||||
</UserChat>
|
</UserChat>
|
||||||
|
|
||||||
|
|
||||||
{/* {partyInvite.map((c) => {
|
|
||||||
return (
|
|
||||||
|
|
||||||
)})
|
|
||||||
} */}
|
|
||||||
|
|
||||||
{partyInvite.map( i =>(
|
{partyInvite.map( i =>(
|
||||||
<PartyInvite currentInvite={i}/>
|
<PartyInvite currentInvite={i}/>
|
||||||
))}
|
))}
|
||||||
@ -535,11 +428,9 @@ function Chats(){
|
|||||||
<div key={index}
|
<div key={index}
|
||||||
onClick={() => setCurrentChat(c)}>
|
onClick={() => setCurrentChat(c)}>
|
||||||
<UserChat>
|
<UserChat>
|
||||||
{/* <img className="pic-user" src={DefaultPic} alt="User" /> */}
|
|
||||||
<HiChatBubbleLeft className="catchat"/>
|
<HiChatBubbleLeft className="catchat"/>
|
||||||
<div className="infoSideBar">
|
<div className="infoSideBar">
|
||||||
<span>{c.name}</span>
|
<span>{c.name}</span>
|
||||||
{/* <SideP>Desc?</SideP> */}
|
|
||||||
</div>
|
</div>
|
||||||
</UserChat>
|
</UserChat>
|
||||||
</div>
|
</div>
|
||||||
@ -556,7 +447,6 @@ function Chats(){
|
|||||||
<Message key={m.id} message= {m} own={m.sender === user.username}/>
|
<Message key={m.id} message= {m} own={m.sender === user.username}/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
{/* <Input/> */}
|
|
||||||
<div className="input">
|
<div className="input">
|
||||||
<input
|
<input
|
||||||
onKeyDown={handleKeyPress}
|
onKeyDown={handleKeyPress}
|
||||||
@ -578,7 +468,6 @@ function Chats(){
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
// </div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -277,7 +277,7 @@ const ModalSetting = ({ handleClose, convId, socket }: ModalSettingProps) => {
|
|||||||
<input
|
<input
|
||||||
onChange={(e) => setNewName(e.target.value)}
|
onChange={(e) => setNewName(e.target.value)}
|
||||||
onKeyDown={handleName}
|
onKeyDown={handleName}
|
||||||
maxLength={25}
|
maxLength={20}
|
||||||
type="text"
|
type="text"
|
||||||
className="in"
|
className="in"
|
||||||
placeholder="New Name"
|
placeholder="New Name"
|
||||||
|
|||||||
@ -1,13 +1,9 @@
|
|||||||
import { useEffect } from 'react';
|
import { useEffect } from 'react';
|
||||||
// import { useState, useRef } from 'react';
|
|
||||||
import DrawCanvas from './canvas.tsx';
|
import DrawCanvas from './canvas.tsx';
|
||||||
import queryString from 'query-string';
|
import queryString from 'query-string';
|
||||||
import '../styles/field.css';
|
import '../styles/field.css';
|
||||||
|
|
||||||
import { useParams } from "react-router-dom";
|
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
|
|
||||||
// import { withRouter } from 'react-router-dom';
|
|
||||||
|
|
||||||
interface GameProps {
|
interface GameProps {
|
||||||
privateParty: boolean,
|
privateParty: boolean,
|
||||||
@ -18,7 +14,6 @@ interface GameProps {
|
|||||||
function Field()
|
function Field()
|
||||||
{
|
{
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// const location = useLocation();
|
|
||||||
const queryParams = queryString.parse(window.location.search);
|
const queryParams = queryString.parse(window.location.search);
|
||||||
|
|
||||||
console.log("launch canva hehe")
|
console.log("launch canva hehe")
|
||||||
@ -56,7 +51,6 @@ function Field()
|
|||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
console.log("Cleanup");
|
console.log("Cleanup");
|
||||||
// cleanup(); // Call the cleanup function to stop the ongoing process or perform necessary cleanup tasks
|
|
||||||
if (cleanup)
|
if (cleanup)
|
||||||
cleanup();
|
cleanup();
|
||||||
};
|
};
|
||||||
|
|||||||
@ -7,9 +7,7 @@ function Head()
|
|||||||
<meta charSet="utf-8"></meta>
|
<meta charSet="utf-8"></meta>
|
||||||
<link href="./css/header.css" rel="stylesheet"></link>
|
<link href="./css/header.css" rel="stylesheet"></link>
|
||||||
<title>BEST PONG EVER</title>
|
<title>BEST PONG EVER</title>
|
||||||
{/* <script src="./script/login.js"></script> */}
|
|
||||||
<link rel="preconnect" href="https://fonts.googleapis.com"></link>
|
<link rel="preconnect" href="https://fonts.googleapis.com"></link>
|
||||||
{/* <link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="true"></link> */}
|
|
||||||
<link href="https://fonts.googleapis.com/css2?family=Rubik+Iso&display=swap" rel="stylesheet"></link>
|
<link href="https://fonts.googleapis.com/css2?family=Rubik+Iso&display=swap" rel="stylesheet"></link>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@ -3,51 +3,30 @@
|
|||||||
/* ::: :::::::: */
|
/* ::: :::::::: */
|
||||||
/* Home.tsx :+: :+: :+: */
|
/* Home.tsx :+: :+: :+: */
|
||||||
/* +:+ +:+ +:+ */
|
/* +:+ +:+ +:+ */
|
||||||
/* By: sadjigui <sadjigui@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 04:03:16 by sadjigui ### ########.fr */
|
/* Updated: 2023/06/26 06:58:05 by apommier ### ########.fr */
|
||||||
/* */
|
/* */
|
||||||
/* ************************************************************************** */
|
/* ************************************************************************** */
|
||||||
|
|
||||||
// import { React, useState } from "react";
|
|
||||||
import '../styles/Profile.css'
|
import '../styles/Profile.css'
|
||||||
// import '../styles/App.css'
|
|
||||||
import RedAlert from "../components/Alert/RedAlert.tsx";
|
import RedAlert from "../components/Alert/RedAlert.tsx";
|
||||||
|
|
||||||
import DefaultPicture from "../assets/profile.jpg";
|
import DefaultPicture from "../assets/profile.jpg";
|
||||||
import WinLoss from "../components/Profile/Win_Loss.tsx";
|
import WinLoss from "../components/Profile/Win_Loss.tsx";
|
||||||
import { motion, AnimatePresence } from 'framer-motion'
|
import { motion, AnimatePresence } from 'framer-motion'
|
||||||
// import { AiFillEdit } from 'react-icons/ai'
|
|
||||||
// import { GrClose } from 'react-icons/gr'
|
|
||||||
import { Link } from "react-router-dom";
|
import { Link } from "react-router-dom";
|
||||||
import ModalEdit from "../components/Profile/EditName.tsx";
|
import ModalEdit from "../components/Profile/EditName.tsx";
|
||||||
import {AiOutlineCloseCircle, AiOutlineHistory} from 'react-icons/ai'
|
import {AiOutlineCloseCircle, AiOutlineHistory} from 'react-icons/ai'
|
||||||
import { MdQrCodeScanner, MdOutlinePhotoLibrary } from 'react-icons/md';
|
import { MdQrCodeScanner, MdOutlinePhotoLibrary } from 'react-icons/md';
|
||||||
import { GiWingedSword, GiCrownedSkull } from 'react-icons/gi';
|
import { GiWingedSword, GiCrownedSkull } from 'react-icons/gi';
|
||||||
|
|
||||||
// import { Link } from "react-router-dom";
|
|
||||||
// import {UserProfile} from "../DataBase/DataUserProfile";
|
|
||||||
// import axios from "axios";
|
|
||||||
import api from '../script/axiosApi.tsx';
|
import api from '../script/axiosApi.tsx';
|
||||||
import { CgEditMarkup } from 'react-icons/cg'
|
import { CgEditMarkup } from 'react-icons/cg'
|
||||||
import { IoCloseCircleOutline } from "react-icons/io5";
|
import { IoCloseCircleOutline } from "react-icons/io5";
|
||||||
|
import React, { useState, useEffect } from "react";
|
||||||
// import * as React from 'react';
|
|
||||||
// import { useState, useEffect, useParams} from "react";
|
|
||||||
import React, { useState, useEffect, useRef, ChangeEventHandler } from "react";
|
|
||||||
import { useParams } from 'react-router-dom';
|
import { useParams } from 'react-router-dom';
|
||||||
import {User, Conv} from "../../interfaces.tsx"
|
import {User} from "../../interfaces.tsx"
|
||||||
import YellowAlert from '../components/Alert/YellowAlert.tsx';
|
import YellowAlert from '../components/Alert/YellowAlert.tsx';
|
||||||
// axios.get("http://localhost/api")
|
|
||||||
// .then((response) => {
|
|
||||||
// response = response.json()
|
|
||||||
// response.then((result) => {
|
|
||||||
// console.log(result)
|
|
||||||
// console.log("ceci est un test")
|
|
||||||
// })
|
|
||||||
// })
|
|
||||||
|
|
||||||
|
|
||||||
function Profile () {
|
function Profile () {
|
||||||
const [user, setUser] = useState<User>();
|
const [user, setUser] = useState<User>();
|
||||||
@ -55,21 +34,12 @@ function Profile () {
|
|||||||
const [modalOpen, setModalOpen] = useState<boolean>(false);
|
const [modalOpen, setModalOpen] = useState<boolean>(false);
|
||||||
const [mine, setMine] = useState<boolean>(false);
|
const [mine, setMine] = useState<boolean>(false);
|
||||||
const [error, setError] = useState<boolean>(false);
|
const [error, setError] = useState<boolean>(false);
|
||||||
// const [visible, setVisible] = useState<boolean>(false);
|
|
||||||
const close = () => setModalOpen(false);
|
const close = () => setModalOpen(false);
|
||||||
const closeError = () => setError(false);
|
const closeError = () => setError(false);
|
||||||
const open = () => setModalOpen(true);
|
const open = () => setModalOpen(true);
|
||||||
|
|
||||||
const { username } = useParams();
|
const { username } = useParams();
|
||||||
|
|
||||||
// const [selectedPhoto, setSelectedPhoto] = useState();
|
|
||||||
// const [selectedPhoto, setSelectedPhoto] = useState(null);
|
|
||||||
|
|
||||||
const [profilePicture, setProfilePicture] = useState('');
|
const [profilePicture, setProfilePicture] = useState('');
|
||||||
|
|
||||||
const handleFileChange = async (event: { target: { files: any; }; }) => {
|
const handleFileChange = async (event: { target: { files: any; }; }) => {
|
||||||
// const files = event.target.files;
|
|
||||||
// if (files && files.length > 0) {
|
|
||||||
const photo = (event.target.files[0]);
|
const photo = (event.target.files[0]);
|
||||||
console.log("file selected")
|
console.log("file selected")
|
||||||
if (photo) {
|
if (photo) {
|
||||||
@ -85,13 +55,11 @@ function Profile () {
|
|||||||
console.error('Error uploading file:', error);
|
console.error('Error uploading file:', error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// }
|
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(()=> {
|
useEffect(()=> {
|
||||||
const getUser = async ()=>{
|
const getUser = async ()=>{
|
||||||
console.log(`username= ${username}`)
|
console.log(`username= ${username}`)
|
||||||
// const pic
|
|
||||||
let pic;
|
let pic;
|
||||||
try{
|
try{
|
||||||
console.log("before request")
|
console.log("before request")
|
||||||
@ -102,7 +70,6 @@ function Profile () {
|
|||||||
setUser(me.data);
|
setUser(me.data);
|
||||||
console.log(`mine= true = ${mine}`)
|
console.log(`mine= true = ${mine}`)
|
||||||
pic = await api.post("/getPicture", {username: me.data.username}) //good one?
|
pic = await api.post("/getPicture", {username: me.data.username}) //good one?
|
||||||
// username = me.data.username
|
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@ -111,9 +78,7 @@ function Profile () {
|
|||||||
pic = await api.post("/getPicture", {username: username}) //good one?
|
pic = await api.post("/getPicture", {username: username}) //good one?
|
||||||
|
|
||||||
}
|
}
|
||||||
// const pic = await api.get("/picture")//pic du user
|
|
||||||
setProfilePicture(pic.data);
|
setProfilePicture(pic.data);
|
||||||
// console.log(`user= ${tmpUser.data.username}`)
|
|
||||||
setIsLoading(false)
|
setIsLoading(false)
|
||||||
}
|
}
|
||||||
catch(err){
|
catch(err){
|
||||||
@ -125,8 +90,6 @@ function Profile () {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="profile">
|
<div className="profile">
|
||||||
{/* <img className="profile-pic" src={DefaultPicture} alt="Profile pic" />
|
|
||||||
*/}
|
|
||||||
{profilePicture ? (
|
{profilePicture ? (
|
||||||
<img className="profile-pic" src={`data:image/jpeg;base64,${profilePicture}`} />
|
<img className="profile-pic" src={`data:image/jpeg;base64,${profilePicture}`} />
|
||||||
) : (
|
) : (
|
||||||
@ -139,9 +102,6 @@ function Profile () {
|
|||||||
<h1 className='user_name'>{user.nickname}</h1>
|
<h1 className='user_name'>{user.nickname}</h1>
|
||||||
)}
|
)}
|
||||||
</span>
|
</span>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
{mine ? (
|
{mine ? (
|
||||||
<div>
|
<div>
|
||||||
<motion.div >
|
<motion.div >
|
||||||
@ -156,25 +116,14 @@ function Profile () {
|
|||||||
{error ? (
|
{error ? (
|
||||||
<RedAlert handleClose={closeError} text={'Error : upload failed'} />
|
<RedAlert handleClose={closeError} text={'Error : upload failed'} />
|
||||||
): ("")}
|
): ("")}
|
||||||
|
|
||||||
</AnimatePresence>
|
</AnimatePresence>
|
||||||
|
|
||||||
|
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</motion.div>
|
</motion.div>
|
||||||
|
|
||||||
{/* <div className="file-upload-container"> */}
|
|
||||||
{/* <button onClick={handleUpload} className="upload-button">Upload</button> */}
|
|
||||||
{/* <button onClick={handleUpload} className="upload-button">Upload</button> */}
|
|
||||||
{/* </div> */}
|
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<></>
|
<></>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
<AnimatePresence
|
<AnimatePresence
|
||||||
initial={false}
|
initial={false}
|
||||||
onExitComplete={() => null}>
|
onExitComplete={() => null}>
|
||||||
@ -187,7 +136,6 @@ function Profile () {
|
|||||||
function Home () {
|
function Home () {
|
||||||
const [move, setmove ] = useState(false);
|
const [move, setmove ] = useState(false);
|
||||||
const [user, setUser] = useState<User>();
|
const [user, setUser] = useState<User>();
|
||||||
|
|
||||||
const [successQr, setSuccessQr] = useState(false);
|
const [successQr, setSuccessQr] = useState(false);
|
||||||
const [successSword, setSuccessSword] = useState(false);
|
const [successSword, setSuccessSword] = useState(false);
|
||||||
const [successCrown, setSuccessCrown] = useState(false);
|
const [successCrown, setSuccessCrown] = useState(false);
|
||||||
@ -210,8 +158,6 @@ function Home () {
|
|||||||
const tmpUser = await api.post("/user", {username: username});
|
const tmpUser = await api.post("/user", {username: username});
|
||||||
setUser(tmpUser.data);
|
setUser(tmpUser.data);
|
||||||
}
|
}
|
||||||
// const tmpUser = await api.get("/profile");
|
|
||||||
// setUser(tmpUser.data);
|
|
||||||
}
|
}
|
||||||
catch (error)
|
catch (error)
|
||||||
{
|
{
|
||||||
@ -239,10 +185,6 @@ function Home () {
|
|||||||
</div>
|
</div>
|
||||||
<div className="home">
|
<div className="home">
|
||||||
<motion.div
|
<motion.div
|
||||||
// style={{
|
|
||||||
// backdropFilter: move ? "blur(10px)" : "none",
|
|
||||||
// WebkitBackdropFilter: move ? "blur(10px)" : "none"
|
|
||||||
// }}
|
|
||||||
animate={{x: move ? '-50%' : '25%'}}
|
animate={{x: move ? '-50%' : '25%'}}
|
||||||
transition={{type: "tween", duration: 0.5}}>
|
transition={{type: "tween", duration: 0.5}}>
|
||||||
<Profile/>
|
<Profile/>
|
||||||
@ -253,7 +195,6 @@ function Home () {
|
|||||||
</div>
|
</div>
|
||||||
<motion.div
|
<motion.div
|
||||||
className="div_history"
|
className="div_history"
|
||||||
// className="history"
|
|
||||||
onClick={ () => setmove(!move)}>
|
onClick={ () => setmove(!move)}>
|
||||||
<Link to="#" className="history"> {move ? (<AiOutlineCloseCircle/>):(<AiOutlineHistory/>)} Match History</Link>
|
<Link to="#" className="history"> {move ? (<AiOutlineCloseCircle/>):(<AiOutlineHistory/>)} Match History</Link>
|
||||||
</motion.div>
|
</motion.div>
|
||||||
|
|||||||
@ -1,47 +0,0 @@
|
|||||||
// import GoogleLogin from 'react-google-login';
|
|
||||||
import { useEffect } from 'react';
|
|
||||||
import axios from 'axios';
|
|
||||||
import React from 'react';
|
|
||||||
// import setupLogin from '../script/login42';
|
|
||||||
// import React, { useEffect } from 'react';
|
|
||||||
|
|
||||||
function Login42()
|
|
||||||
{
|
|
||||||
useEffect(() => {
|
|
||||||
console.log("you said yes to connect with 42");
|
|
||||||
const url = new URL(window.location.href);
|
|
||||||
// console.log(`url is= ${url}`);
|
|
||||||
const code = url.searchParams.get('code');
|
|
||||||
console.log(`code is= ${code}`);
|
|
||||||
|
|
||||||
const data = {
|
|
||||||
grant_type: 'authorization_code',
|
|
||||||
// client_id: 'u-s4t2ud-6d29dfa49ba7146577ffd8bf595ae8d9e5aaa3e0a9615df18777171ebf836a41',
|
|
||||||
// client_secret: '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',
|
|
||||||
client_id: process.env.REACT_APP_CLIENT_UID,
|
|
||||||
client_secret: process.env.REACT_APP_API_SECRET,
|
|
||||||
code: code,
|
|
||||||
redirect_uri: 'http://' + process.env.REACT_APP_BASE_URL + '/login42',
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
axios.post('https://api.intra.42.fr/oauth/token', data)
|
|
||||||
.then(response => {
|
|
||||||
// handle success response
|
|
||||||
console.log(response);
|
|
||||||
})
|
|
||||||
.catch(error => {
|
|
||||||
// handle error response
|
|
||||||
console.error(error);
|
|
||||||
});
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
<p>"COUCOU LOGIN" </p>
|
|
||||||
{/* <script src="../script/login42.js"></script> */}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export default Login42;
|
|
||||||
@ -1,35 +1,14 @@
|
|||||||
import '../styles/old.css';
|
import '../styles/old.css';
|
||||||
import '../styles/field.css';
|
import '../styles/field.css';
|
||||||
|
|
||||||
import { useLocation } from 'react-router-dom';
|
|
||||||
import api from '../script/axiosApi.tsx';
|
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
|
|
||||||
function HomeLogin()
|
function HomeLogin()
|
||||||
{
|
{
|
||||||
const login2 = () => {
|
|
||||||
console.log('Hello from myFunction');
|
|
||||||
api.get('/profile').then((response) => {
|
|
||||||
const data = response;
|
|
||||||
const myJSON = JSON.stringify(response.data);
|
|
||||||
console.log(`data response= ${myJSON}`)
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const location = useLocation();
|
|
||||||
|
|
||||||
const handleButtonClick = () => {
|
const handleButtonClick = () => {
|
||||||
const token = localStorage.getItem('token')
|
const token = localStorage.getItem('token')
|
||||||
console.log(`token type= ${typeof token}`);
|
console.log(`token type= ${typeof token}`);
|
||||||
if (token !== null && typeof token === 'string')
|
if (token !== null && typeof token === 'string')
|
||||||
{
|
|
||||||
console.log(`already token= ${localStorage.getItem('token')}`)
|
|
||||||
return ;
|
return ;
|
||||||
}
|
|
||||||
console.log("yrah im here bitch");
|
|
||||||
console.log("lien = ", process.env.REACT_APP_INTRA_URL);
|
|
||||||
// else
|
|
||||||
// let path = "https://api.intra.42.fr/oauth/authorize?client_id=u-s4t2ud-6d29dfa49ba7146577ffd8bf595ae8d9e5aaa3e0a9615df18777171ebf836a41&redirect_uri=http%3A%2F%2F" + process.env.REACT_APP_BASE_URL + "%3A80%2Fapi%2Fauth%2Flogin&response_type=code";
|
|
||||||
let path = process.env.REACT_APP_INTRA_URL || "";
|
let path = process.env.REACT_APP_INTRA_URL || "";
|
||||||
window.location.replace(path);
|
window.location.replace(path);
|
||||||
};
|
};
|
||||||
@ -37,15 +16,6 @@ function HomeLogin()
|
|||||||
return (
|
return (
|
||||||
<div className="notClicked">
|
<div className="notClicked">
|
||||||
<button onClick={handleButtonClick} className="playButton" >LOGIN</button>
|
<button onClick={handleButtonClick} className="playButton" >LOGIN</button>
|
||||||
{/* <div className ="loginForm">
|
|
||||||
<button className="submit" onClick={login2}>test button</button>
|
|
||||||
</div> */}
|
|
||||||
{/* <div className ="loginForm">
|
|
||||||
<button className="submit" onClick={() => api.post('/win')}>add win</button>
|
|
||||||
</div>
|
|
||||||
<div className ="loginForm">
|
|
||||||
<button className="submit" onClick={() => api.post('/loss')}>add loss</button>
|
|
||||||
</div> */}
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,29 +1,9 @@
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
// import Sidebar from '../components/Messages/Sidebar'
|
|
||||||
import Chats from "../components/Messages/Chats.tsx"
|
import Chats from "../components/Messages/Chats.tsx"
|
||||||
import '../styles/Messages.css'
|
import '../styles/Messages.css'
|
||||||
import { motion } from 'framer-motion'
|
import { motion } from 'framer-motion'
|
||||||
|
|
||||||
// import {io} from 'socket.io-client'
|
|
||||||
|
|
||||||
function Messages() {
|
function Messages() {
|
||||||
// const socket = useRef(io("ws://localhost:8900"))
|
|
||||||
|
|
||||||
// useEffect(() => {
|
|
||||||
// setSocket(io("ws://localhost:8900"))
|
|
||||||
// }, [])
|
|
||||||
// const socket = socketIO.connect('http://localhost:4000');
|
|
||||||
|
|
||||||
// axios.get('http://localhost/api/user/id')
|
|
||||||
// .then(function());
|
|
||||||
|
|
||||||
// console.log(socket)
|
|
||||||
// useEffect(() => {
|
|
||||||
// socket.current.emit("addUser", user._id);
|
|
||||||
// socket.current.on("getUsers", users=>{
|
|
||||||
// console.log(users)
|
|
||||||
// })
|
|
||||||
// }, [user])
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<motion.div className="home"
|
<motion.div className="home"
|
||||||
@ -31,7 +11,6 @@ function Messages() {
|
|||||||
animate={{opacity: 1}}
|
animate={{opacity: 1}}
|
||||||
exit={{opacity: 0}}>
|
exit={{opacity: 0}}>
|
||||||
<div className="container">
|
<div className="container">
|
||||||
{/* <Sidebar/> */}
|
|
||||||
<Chats/>
|
<Chats/>
|
||||||
</div>
|
</div>
|
||||||
</motion.div>
|
</motion.div>
|
||||||
|
|||||||
@ -1,6 +1,5 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import '../styles/field.css';
|
import '../styles/field.css';
|
||||||
// import { useHistory } from 'react-router-dom';
|
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
|
|
||||||
function PlayButton() {
|
function PlayButton() {
|
||||||
@ -15,8 +14,6 @@ function PlayButton() {
|
|||||||
return (
|
return (
|
||||||
<div className="notClicked" id="canvas_container">
|
<div className="notClicked" id="canvas_container">
|
||||||
<button onClick={handleButtonClick} className="playButton">Play</button>
|
<button onClick={handleButtonClick} className="playButton">Play</button>
|
||||||
{/* !buttonClicked && <button onClick={handleButtonClick}>Draw on Canvas</button> */}
|
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -14,7 +14,6 @@ import RedAlert from "../components/Alert/RedAlert.tsx";
|
|||||||
const qrCode = new QRCodeStyling({
|
const qrCode = new QRCodeStyling({
|
||||||
width: 300,
|
width: 300,
|
||||||
height: 300,
|
height: 300,
|
||||||
// image: "../assets/profile.jpg",
|
|
||||||
dotsOptions: {
|
dotsOptions: {
|
||||||
color: "black",
|
color: "black",
|
||||||
type: "rounded"
|
type: "rounded"
|
||||||
@ -29,8 +28,6 @@ const qrCode = new QRCodeStyling({
|
|||||||
});
|
});
|
||||||
|
|
||||||
function QrCode () {
|
function QrCode () {
|
||||||
// const url = "https://www.youtube.com";
|
|
||||||
// const ref = useRef(null);
|
|
||||||
const ref = useRef<HTMLDivElement>(null);
|
const ref = useRef<HTMLDivElement>(null);
|
||||||
const [user, setUser] = useState(false);
|
const [user, setUser] = useState(false);
|
||||||
const [url, setUrl] = useState("");
|
const [url, setUrl] = useState("");
|
||||||
@ -40,8 +37,6 @@ function QrCode () {
|
|||||||
const [err, setErr] = useState(false);
|
const [err, setErr] = useState(false);
|
||||||
const closeErr = () => setErr(false);
|
const closeErr = () => setErr(false);
|
||||||
|
|
||||||
// const history = useHistory();
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (ref.current)
|
if (ref.current)
|
||||||
qrCode.append(ref.current);
|
qrCode.append(ref.current);
|
||||||
|
|||||||
@ -1,12 +1,5 @@
|
|||||||
// import io from 'socket.io-client';
|
|
||||||
|
|
||||||
import api from '../script/axiosApi.tsx';
|
import api from '../script/axiosApi.tsx';
|
||||||
|
|
||||||
// import { useEffect, useRef } from 'react';
|
|
||||||
import io from 'socket.io-client';
|
import io from 'socket.io-client';
|
||||||
// const socket = io('http://192.168.1.14:4000');
|
|
||||||
// const socket = io('http://86.209.110.20:4000');
|
|
||||||
// const socket = io('http://172.29.113.91:4000');
|
|
||||||
|
|
||||||
interface GameProps {
|
interface GameProps {
|
||||||
privateParty: boolean,
|
privateParty: boolean,
|
||||||
@ -25,11 +18,6 @@ function DrawCanvas(option: number, gameParam: GameProps) {
|
|||||||
console.log(`obstacleModifier = ${obstacleModifier}`);
|
console.log(`obstacleModifier = ${obstacleModifier}`);
|
||||||
console.log(`speedModifier = ${speedModifier}`);
|
console.log(`speedModifier = ${speedModifier}`);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// const socketRef = useRef(null);
|
|
||||||
// socketRef.current = io('http://localhost:4000');
|
|
||||||
|
|
||||||
function launchGame()
|
function launchGame()
|
||||||
{
|
{
|
||||||
if (!gameParam.privateParty)
|
if (!gameParam.privateParty)
|
||||||
@ -49,10 +37,7 @@ function DrawCanvas(option: number, gameParam: GameProps) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// const socket = socketRef.current
|
|
||||||
console.log("start function");
|
console.log("start function");
|
||||||
|
|
||||||
// let canvas: HTMLElement | null;
|
|
||||||
const canvas = document.getElementById('myCanvas') as HTMLCanvasElement | null;;
|
const canvas = document.getElementById('myCanvas') as HTMLCanvasElement | null;;
|
||||||
if (!canvas)
|
if (!canvas)
|
||||||
return ;
|
return ;
|
||||||
@ -62,14 +47,6 @@ function DrawCanvas(option: number, gameParam: GameProps) {
|
|||||||
return ;
|
return ;
|
||||||
|
|
||||||
const socket = io('http://' + process.env.REACT_APP_SOCKET_URL + ':4000', { transports: ['polling'] });
|
const socket = io('http://' + process.env.REACT_APP_SOCKET_URL + ':4000', { transports: ['polling'] });
|
||||||
// useEffect(() => {
|
|
||||||
// console.log("useeffect?????????????????")
|
|
||||||
// return () => {
|
|
||||||
// console.log("000000000000000000000000000000000")
|
|
||||||
// socketRef.current.disconnect();
|
|
||||||
// };
|
|
||||||
// }, []);
|
|
||||||
|
|
||||||
|
|
||||||
//========================================================================================================
|
//========================================================================================================
|
||||||
//========================================================================================================
|
//========================================================================================================
|
||||||
@ -87,7 +64,6 @@ function DrawCanvas(option: number, gameParam: GameProps) {
|
|||||||
let running = true;
|
let running = true;
|
||||||
const scale = window.devicePixelRatio;
|
const scale = window.devicePixelRatio;
|
||||||
canvas.width = canvas.offsetWidth;
|
canvas.width = canvas.offsetWidth;
|
||||||
// canvas.height = canvas.width * 0.7
|
|
||||||
canvas.height = canvas.offsetHeight;
|
canvas.height = canvas.offsetHeight;
|
||||||
|
|
||||||
//paddle var
|
//paddle var
|
||||||
@ -139,25 +115,13 @@ 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("instant win opponent disconnect")
|
||||||
// const data = {
|
|
||||||
// myScore: myScore,
|
|
||||||
// opScore: hisScore,
|
|
||||||
// opName: opName,
|
|
||||||
// opRank: opRank,
|
|
||||||
// };
|
|
||||||
|
|
||||||
// await api.post('/win', data);
|
|
||||||
console.log("after request1")
|
console.log("after request1")
|
||||||
await api.post('/status', {status: 1});
|
await api.post('/status', {status: 1});
|
||||||
console.log("after request2")
|
console.log("after request2")
|
||||||
//disconnect ?
|
|
||||||
running = false;
|
running = false;
|
||||||
socket.emit('pong:disconnect', {id: myId});
|
socket.emit('pong:disconnect', {id: myId});
|
||||||
console.log("before reload")
|
console.log("before reload")
|
||||||
// window.location.replace("http://" + process.env.REACT_APP_BASE_URL + "/pong");
|
|
||||||
// window.location.reload();
|
|
||||||
return ;
|
return ;
|
||||||
// console.log("send all ?? win");
|
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -206,17 +170,12 @@ socket.on('pong:gameId', async (data) => {
|
|||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(error);
|
console.log(error);
|
||||||
// Handle error here
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
socket.on('pong:name', (data) => {
|
socket.on('pong:name', (data) => {
|
||||||
opName = data.name;
|
opName = data.name;
|
||||||
// if (data.myId === myId)
|
|
||||||
// vX = 0.0001;
|
|
||||||
// else
|
|
||||||
// vX = -0.0001;
|
|
||||||
console.log(`opponent Name= ${opName}`)
|
console.log(`opponent Name= ${opName}`)
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -252,22 +211,15 @@ socket.on('pong:power', (data) => {
|
|||||||
opPaddleHeight = canvas.height;
|
opPaddleHeight = canvas.height;
|
||||||
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
// code à exécuter après 5 secondes
|
|
||||||
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.');
|
console.log('Cinq secondes se sont écoulées.');
|
||||||
}, 5000);
|
}, 5000);
|
||||||
// oPaddleY = (data.paddleY / data.height) * canvas.height
|
|
||||||
});
|
});
|
||||||
|
|
||||||
socket.on('pong:point', (data) => {
|
socket.on('pong:point', (data) => {
|
||||||
// hisScore += 1;
|
|
||||||
console.log("gain point");
|
console.log("gain point");
|
||||||
// if (vX != 0)
|
|
||||||
// {
|
|
||||||
// console.log("up point");
|
|
||||||
myScore = data.point;
|
myScore = data.point;
|
||||||
// }
|
|
||||||
vX = -0.0005;
|
vX = -0.0005;
|
||||||
vY = 0;
|
vY = 0;
|
||||||
ballX = canvas.width / 2;
|
ballX = canvas.width / 2;
|
||||||
@ -275,18 +227,12 @@ socket.on('pong:point', (data) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
socket.on('pong:hisPoint', (data) => {
|
socket.on('pong:hisPoint', (data) => {
|
||||||
// hisScore += 1;
|
|
||||||
console.log("myPointawdawdawdawd point");
|
console.log("myPointawdawdawdawd point");
|
||||||
// if (vX != 0)
|
|
||||||
// {
|
|
||||||
// console.log("up point");
|
|
||||||
hisScore = data.point;
|
hisScore = data.point;
|
||||||
// }
|
|
||||||
vX = -0.0005;
|
vX = -0.0005;
|
||||||
vY = 0;
|
vY = 0;
|
||||||
ballX = canvas.width / 2;
|
ballX = canvas.width / 2;
|
||||||
ballY = canvas.height / 2;
|
ballY = canvas.height / 2;
|
||||||
// send_forced_info();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
//========================================================================================================
|
//========================================================================================================
|
||||||
@ -362,7 +308,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,
|
||||||
@ -384,7 +329,6 @@ socket.on('pong:hisPoint', (data) => {
|
|||||||
const info = {
|
const info = {
|
||||||
id: myId,
|
id: myId,
|
||||||
paddleY: paddleY,
|
paddleY: paddleY,
|
||||||
// width: canvas.width,
|
|
||||||
height: canvas.height,
|
height: canvas.height,
|
||||||
gameId: gameId,
|
gameId: gameId,
|
||||||
};
|
};
|
||||||
@ -437,7 +381,6 @@ socket.on('pong:hisPoint', (data) => {
|
|||||||
ctx.fillRect(canvas.width / 2 - ctx.lineWidth / 2, 0, canvas.width / 300, canvas.height);
|
ctx.fillRect(canvas.width / 2 - ctx.lineWidth / 2, 0, canvas.width / 300, canvas.height);
|
||||||
|
|
||||||
ctx.beginPath();
|
ctx.beginPath();
|
||||||
// ctx.lineWidth = 5;
|
|
||||||
ctx.arc(canvas.width / 2, canvas.height / 2, circleRadius, 0, 2 * Math.PI);
|
ctx.arc(canvas.width / 2, canvas.height / 2, circleRadius, 0, 2 * Math.PI);
|
||||||
ctx.strokeStyle = 'white'; // couleur de dessin
|
ctx.strokeStyle = 'white'; // couleur de dessin
|
||||||
ctx.stroke(); // dessin du contour
|
ctx.stroke(); // dessin du contour
|
||||||
@ -463,7 +406,6 @@ socket.on('pong:hisPoint', (data) => {
|
|||||||
return ;
|
return ;
|
||||||
ctx.beginPath();
|
ctx.beginPath();
|
||||||
ctx.arc(ballX, ballY, ballRadius, 0, 2 * Math.PI);
|
ctx.arc(ballX, ballY, ballRadius, 0, 2 * Math.PI);
|
||||||
// ctx.lineWidth = 2;
|
|
||||||
ctx.fillStyle = 'red ';
|
ctx.fillStyle = 'red ';
|
||||||
ctx.fill();
|
ctx.fill();
|
||||||
}
|
}
|
||||||
@ -475,11 +417,6 @@ socket.on('pong:hisPoint', (data) => {
|
|||||||
//========================================================================================================
|
//========================================================================================================
|
||||||
//========================================================================================================
|
//========================================================================================================
|
||||||
|
|
||||||
|
|
||||||
// while (!gameId)
|
|
||||||
// ;
|
|
||||||
|
|
||||||
// Define a function to stop the drawing process
|
|
||||||
const stopDrawCanvas = async () => {
|
const stopDrawCanvas = async () => {
|
||||||
running = false;
|
running = false;
|
||||||
|
|
||||||
@ -489,11 +426,6 @@ socket.on('pong:hisPoint', (data) => {
|
|||||||
{
|
{
|
||||||
console.log("stopDrawCanvas2")
|
console.log("stopDrawCanvas2")
|
||||||
try{
|
try{
|
||||||
// const info = {
|
|
||||||
// id: myId,
|
|
||||||
// option: option,
|
|
||||||
// };
|
|
||||||
// await api.post("status", {status: 1});
|
|
||||||
await api.post('/status', {status: 1});
|
await api.post('/status', {status: 1});
|
||||||
await api.post("deleteInvite", {username: gameParam.username})
|
await api.post("deleteInvite", {username: gameParam.username})
|
||||||
}
|
}
|
||||||
@ -503,9 +435,6 @@ socket.on('pong:hisPoint', (data) => {
|
|||||||
}
|
}
|
||||||
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");
|
||||||
// window.location.reload();
|
|
||||||
// Perform any necessary cleanup tasks
|
|
||||||
// ...
|
|
||||||
};
|
};
|
||||||
|
|
||||||
async function draw(timestamp: number)
|
async function draw(timestamp: number)
|
||||||
@ -518,7 +447,6 @@ async function draw(timestamp: number)
|
|||||||
}
|
}
|
||||||
if (!gameId || !canvas )
|
if (!gameId || !canvas )
|
||||||
{
|
{
|
||||||
// console.log("nogameid score= ", myScore);
|
|
||||||
requestAnimationFrame(draw);
|
requestAnimationFrame(draw);
|
||||||
return ;
|
return ;
|
||||||
}
|
}
|
||||||
@ -535,9 +463,7 @@ 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});
|
||||||
//disconnect ?
|
|
||||||
socket.emit('pong:disconnect', {id: myId});
|
socket.emit('pong:disconnect', {id: myId});
|
||||||
|
|
||||||
console.log("send all ?? win");
|
console.log("send all ?? win");
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
@ -545,11 +471,9 @@ async function draw(timestamp: number)
|
|||||||
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});
|
||||||
//disconnect ?
|
|
||||||
console.log("send loose");
|
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");
|
||||||
// window.location.reload();
|
|
||||||
return ;
|
return ;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -560,7 +484,6 @@ async function draw(timestamp: number)
|
|||||||
|
|
||||||
if (!ctx)
|
if (!ctx)
|
||||||
return ;
|
return ;
|
||||||
// requestAnimationFrame(draw);
|
|
||||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||||
drawPaddle();
|
drawPaddle();
|
||||||
drawcenter();
|
drawcenter();
|
||||||
@ -624,13 +547,11 @@ async function draw(timestamp: number)
|
|||||||
}
|
}
|
||||||
if (ballY - ballRadius - 2 <= 0 || ballY + ballRadius + 2 >= canvas.height) //touch up or down wall
|
if (ballY - ballRadius - 2 <= 0 || ballY + ballRadius + 2 >= canvas.height) //touch up or down wall
|
||||||
{
|
{
|
||||||
// if ()
|
|
||||||
vY = -vY;
|
vY = -vY;
|
||||||
if (ballY > (canvas.height / 2))//down wall
|
if (ballY > (canvas.height / 2))//down wall
|
||||||
ballY = canvas.height - ballRadius - 2
|
ballY = canvas.height - ballRadius - 2
|
||||||
else
|
else
|
||||||
ballY = ballRadius + 2
|
ballY = ballRadius + 2
|
||||||
// send_info();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -653,28 +574,11 @@ async function draw(timestamp: number)
|
|||||||
vY = 0;
|
vY = 0;
|
||||||
hisScore += 1;
|
hisScore += 1;
|
||||||
send_point();
|
send_point();
|
||||||
// send_forced_info();
|
|
||||||
}
|
}
|
||||||
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")
|
console.log("ball out win point pls")
|
||||||
send_my_point();
|
send_my_point();
|
||||||
// if (ballX > canvas.width * 2)
|
|
||||||
// console.log("win point")
|
|
||||||
// if (ballY <= paddleY + paddleHeight + ballRadius && ballY >= paddleY - ballRadius)
|
|
||||||
// {
|
|
||||||
// console.log('true hehe');
|
|
||||||
// ballX = paddleX + paddleWidth + ballRadius;
|
|
||||||
// updateVector();
|
|
||||||
// return ;
|
|
||||||
// }
|
|
||||||
// ballX = canvas.width / 2;
|
|
||||||
// ballY = canvas.height / 2;
|
|
||||||
// vX = 0;
|
|
||||||
// vY = 0;
|
|
||||||
// hisScore += 1;
|
|
||||||
// send_point();
|
|
||||||
// // send_forced_info();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@ -703,21 +607,14 @@ async function draw(timestamp: number)
|
|||||||
|
|
||||||
document.addEventListener("touchmove", event => {
|
document.addEventListener("touchmove", event => {
|
||||||
const touchY = event.touches[0].pageY;
|
const touchY = event.touches[0].pageY;
|
||||||
|
|
||||||
// if (!lastTouchY)
|
|
||||||
// {
|
|
||||||
// vX = -0.01;
|
|
||||||
// lastTouchY = touchY;
|
|
||||||
// return;
|
|
||||||
// }
|
|
||||||
const newY = touchY > lastTouchY ? paddleY - (lastTouchY - touchY) : paddleY + (touchY - lastTouchY);
|
const newY = touchY > lastTouchY ? paddleY - (lastTouchY - touchY) : paddleY + (touchY - lastTouchY);
|
||||||
|
|
||||||
updatePaddlePosition(newY);
|
updatePaddlePosition(newY);
|
||||||
lastTouchY = touchY;
|
lastTouchY = touchY;
|
||||||
send_paddle_info();
|
send_paddle_info();
|
||||||
});
|
});
|
||||||
|
|
||||||
document.addEventListener("keydown", event => {
|
document.addEventListener("keydown", event => {
|
||||||
// console.log(event.code);
|
|
||||||
if (event.code === "ArrowUp")
|
if (event.code === "ArrowUp")
|
||||||
{
|
{
|
||||||
if ((paddleY - paddleSpeed) > 0)
|
if ((paddleY - paddleSpeed) > 0)
|
||||||
@ -730,36 +627,6 @@ async function draw(timestamp: number)
|
|||||||
paddleY += paddleSpeed; // déplacer la raquette vers le bas
|
paddleY += paddleSpeed; // déplacer la raquette vers le bas
|
||||||
send_paddle_info();
|
send_paddle_info();
|
||||||
}
|
}
|
||||||
else if (event.code === "Space")//space
|
|
||||||
{
|
|
||||||
console.log('vx change to -1');
|
|
||||||
vX = -0.0001;
|
|
||||||
|
|
||||||
// ballSpeed = 0.0001;
|
|
||||||
vY = 0;
|
|
||||||
send_forced_info();
|
|
||||||
// vX = 0.0001;
|
|
||||||
}
|
|
||||||
else if (event.code === "KeyE")
|
|
||||||
{
|
|
||||||
// console.log('vx change to -1');
|
|
||||||
vX = 0;
|
|
||||||
vY = 0;
|
|
||||||
ballX = canvas.width / 2;
|
|
||||||
ballY = canvas.height / 2;
|
|
||||||
send_forced_info();
|
|
||||||
}
|
|
||||||
else if (event.code === "KeyQ" )
|
|
||||||
{
|
|
||||||
if (vX < 0.003 * canvas.width && vX > -0.003 * canvas.width)
|
|
||||||
{
|
|
||||||
if (vX > 0)
|
|
||||||
vX += 0.0001;
|
|
||||||
else
|
|
||||||
vX -= 0.0001;
|
|
||||||
}
|
|
||||||
send_forced_info();
|
|
||||||
}
|
|
||||||
else if (event.code === "KeyW")
|
else if (event.code === "KeyW")
|
||||||
{
|
{
|
||||||
let date = new Date();
|
let date = new Date();
|
||||||
@ -772,14 +639,12 @@ async function draw(timestamp: number)
|
|||||||
paddleHeight = canvas.height;
|
paddleHeight = canvas.height;
|
||||||
use_power();
|
use_power();
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
// code à exécuter après 5 secondes
|
|
||||||
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.');
|
console.log('Cinq secondes se sont écoulées.');
|
||||||
}, 5000);
|
}, 5000);
|
||||||
date = new Date();
|
date = new Date();
|
||||||
lastPower = date.getTime();
|
lastPower = date.getTime();
|
||||||
// console.log("date= ", date.getTime())
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user