add chat app (nothing done), before merge with syd's front

This commit is contained in:
kinou-p 2023-05-02 15:21:22 +02:00
parent da6a8041c7
commit 19684001f5
30 changed files with 8814 additions and 100 deletions

9
.gitignore vendored
View File

@ -1,2 +1,9 @@
#.env
backend/node_modules/
backend/node_modules/
backend/dist/
pong/node_modules/
pong/dist/
*/node_modules/
*/dist/

View File

@ -1,4 +1,4 @@
import { Body, Controller, Get, Post, Query, InternalServerErrorException } from '@nestjs/common';
import { Body, Controller, Get, Param, Post, Query, InternalServerErrorException } from '@nestjs/common';
// import { AppService } from './app.service.js';
import { UsersService } from './app.service';
import { User } from './model/item.entity';
@ -52,4 +52,10 @@ export class AppController
{
return this.usersService.create(user);
}
@Get('user/:id')
async getUser(@Param('id') id: number)
{
return this.usersService.findOne(id);
}
}

View File

@ -39,7 +39,8 @@ export class UsersService {
return await this.userRepository.find();
}
// async findOne(id: number): Promise<User> {
// return await this.usersRepository.findOne(id);
// }
async findOne(id: number): Promise<User> {
return await this.userRepository.findOneBy({id: id});
}
}

25
chat/.eslintrc.js Normal file
View File

@ -0,0 +1,25 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
tsconfigRootDir: __dirname,
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};

35
chat/.gitignore vendored Normal file
View File

@ -0,0 +1,35 @@
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-debug.log*
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json

4
chat/.prettierrc Normal file
View File

@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}

73
chat/README.md Normal file
View File

@ -0,0 +1,73 @@
<p align="center">
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="200" alt="Nest Logo" /></a>
</p>
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master" target="_blank"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9" alt="Coverage" /></a>
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg"/></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow"></a>
</p>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
## Description
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
## Installation
```bash
$ npm install
```
## Running the app
```bash
# development
$ npm run start
# watch mode
$ npm run start:dev
# production mode
$ npm run start:prod
```
## Test
```bash
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
```
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
## Stay in touch
- Author - [Kamil Myśliwiec](https://kamilmysliwiec.com)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](LICENSE).

8
chat/nest-cli.json Normal file
View File

@ -0,0 +1,8 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}

8346
chat/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

72
chat/package.json Normal file
View File

@ -0,0 +1,72 @@
{
"name": "chat",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@nestjs/common": "^9.0.0",
"@nestjs/core": "^9.0.0",
"@nestjs/platform-express": "^9.0.0",
"@nestjs/websockets": "^9.4.0",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.2.0",
"socket.io": "^4.6.1",
"uuid": "^9.0.0"
},
"devDependencies": {
"@nestjs/cli": "^9.0.0",
"@nestjs/schematics": "^9.0.0",
"@nestjs/testing": "^9.0.0",
"@types/express": "^4.17.13",
"@types/jest": "29.5.0",
"@types/node": "18.15.11",
"@types/supertest": "^2.0.11",
"@typescript-eslint/eslint-plugin": "^5.0.0",
"@typescript-eslint/parser": "^5.0.0",
"eslint": "^8.0.1",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"jest": "29.5.0",
"prettier": "^2.3.2",
"source-map-support": "^0.5.20",
"supertest": "^6.1.3",
"ts-jest": "29.0.5",
"ts-loader": "^9.2.3",
"ts-node": "^10.0.0",
"tsconfig-paths": "4.2.0",
"typescript": "^4.7.4"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}

View File

@ -0,0 +1,22 @@
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!');
});
});
});

View File

@ -0,0 +1,12 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}

11
chat/src/app.module.ts Normal file
View File

@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ChatGateway } from './chat/chat.gateway';
@Module({
imports: [],
controllers: [AppController],
providers: [AppService, ChatGateway],
})
export class AppModule {}

8
chat/src/app.service.ts Normal file
View File

@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}

View File

@ -0,0 +1,19 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ChatGateway } from './chat.gateway';
describe('ChatGateway', () => {
let gateway: ChatGateway;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [ChatGateway],
}).compile();
gateway = module.get<ChatGateway>(ChatGateway);
});
it('should be defined', () => {
expect(gateway).toBeDefined();
});
});
4

View File

@ -0,0 +1,45 @@
import { SubscribeMessage, WebSocketGateway, OnGatewayInit, WebSocketServer, OnGatewayConnection, OnGatewayDisconnect } from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { v4 as uuidv4 } from 'uuid';
@WebSocketGateway({ cors: true })
export class ChatGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
private clients: Record<string, Socket> = {};
afterInit(server: Server)
{
console.log('ChatGateway initialized');
}
handleConnection(client: Socket, ...args: any[])
{
console.log(`Client connected: ${client.id}`);
const clientId = uuidv4();
this.clients[clientId] = client;
client.emit('chat:clientId', clientId);
console.log(`Total connected clients: ${Object.keys(this.clients).length}`);
}
handleDisconnect(client: Socket)
{
console.log(`Client disconnected: ${client.id}`);
const disconnectedClientId = Object.keys(this.clients).find(clientId => this.clients[clientId] === client);
if (disconnectedClientId)
{
delete this.clients[disconnectedClientId];
console.log(`Client disconnected: ${disconnectedClientId}`);
console.log(`Total connected clients: ${Object.keys(this.clients).length}`);
}
}
@SubscribeMessage('message')
handleMessage(client: any, payload: any): string {
return 'Hello world!';
}
}

36
chat/src/main.ts Normal file
View File

@ -0,0 +1,36 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as socketio from 'socket.io';
async function bootstrap() {
const app = await NestFactory.create(AppModule, {
cors:
{
origin: '*',
methods: '*',
allowedHeaders: '*',
},
});
const httpServer = app.getHttpServer();
const io = new socketio.Server(httpServer);
io.on('connection', (socket) => {
console.log('Client connected:', socket.id);
// Gestion des événements personnalisés ici
socket.on('customEvent', (data) => {
console.log('Custom event received:', data);
// Exemple de réponse à un événement personnalisé
socket.emit('customEventResponse', { message: 'Event processed.' });
});
socket.on('disconnect', () => {
console.log('Client disconnected:', socket.id);
});
});
await app.listen(4001);
}
bootstrap();

24
chat/test/app.e2e-spec.ts Normal file
View File

@ -0,0 +1,24 @@
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from './../src/app.module';
describe('AppController (e2e)', () => {
let app: INestApplication;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
});
});

9
chat/test/jest-e2e.json Normal file
View File

@ -0,0 +1,9 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}

4
chat/tsconfig.build.json Normal file
View File

@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}

21
chat/tsconfig.json Normal file
View File

@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": false,
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false
}
}

View File

@ -1,44 +1,11 @@
# server {
# location / {
# proxy_set_header Host $host;
# proxy_set_header X-Real-IP $remote_addr;
# proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# proxy_set_header X-Forwarded-Proto $scheme;
# proxy_pass http://backend:5000;
# }
# }
server {
# listen 443 ssl;
# listen 80 ssl;
# listen 443 ssl;
listen 80;
# server_name homemadePong.42.fr;
# ssl_protocols TLSv1.3;
# ssl_certificate /etc/ssl/certs/nginx-selfsigned.crt;
# ssl_certificate_key /etc/ssl/private/nginx-selfsigned.key;
# root /var/www/html;
# index index.html;
# autoindex on;
# root /var/www/html;
# location / {
# index index.html;
# }
# location / {
# # root /var/www/html;
# index /var/www/html/index.html;
# # index pong/pong.html;
# autoindex on;
# # try_files /pong/pong.html;
# }
location /{
# index /
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
@ -55,36 +22,4 @@ server {
proxy_pass http://backend:3000/api;
}
# location /api {
# proxy_set_header Host $host;
# proxy_set_header X-Real-IP $remote_addr;
# proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# proxy_set_header X-Forwarded-Proto $scheme;
# proxy_pass http://backend:3000/api;
# }
#proxy_pass http://localhost:5000
}
# server {
# listen 80;
# server_name localhost;
# }
# upstream loadbalancer {
# server backend:5000;
# }
# server {
# listen 80;
# server_name localhost;
# location / {
# proxy_pass http://loadbalancer;
# }
# }
}

View File

@ -18,7 +18,7 @@ function Field()
// };
return (
<div class="field" id="canvas_container">
<div className="field" id="canvas_container">
<canvas id="myCanvas"></canvas>
{/* <button onClick={handleButtonClick}>Draw on Canvas</button> */}
{/* {buttonClicked && <canvas id="myCanvas"></canvas>}

View File

@ -1,15 +1,15 @@
function Head()
{
return (
<head>
<meta charset="utf-8"></meta>
<div>
<meta charSet="utf-8"></meta>
<link href="./css/header.css" rel="stylesheet"></link>
<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.gstatic.com" crossorigin></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>
</head>
</div>
);
}

View File

@ -5,15 +5,15 @@ import logo from '../logo.svg';
function Header()
{
return (
<div class="header">
<a href="http://localhost" class="box menu"> <p class="userTxt">Menu</p> </a>
<div class="box headerName">
<div className="header">
<a href="http://localhost" className="box menu"> <p className="userTxt">Menu</p> </a>
<div className="box headerName">
<a href="https://api.intra.42.fr/oauth/authorize?client_id=u-s4t2ud-6d29dfa49ba7146577ffd8bf595ae8d9e5aaa3e0a9615df18777171ebf836a41&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Flogin42&response_type=code"
class="center pong">PONG</a>
className="center pong">PONG</a>
</div>
<a href="http://localhost/pong" class="box username">
<p class="userTxt">Play</p>
{/* <img class="pp center" src="../../public/logo192.png" alt="profile picture"> */}
<a href="http://localhost/pong" className="box username">
<p className="userTxt">Play</p>
{/* <img className="pp center" src="../../public/logo192.png" alt="profile picture"> */}
<img src={logo} className="pp center" alt="logo" />
</a>
</div>

View File

@ -4,12 +4,12 @@ import { login } from '../script/login.js'
function Home()
{
return (
<div class ="login">
<form id="loginForm" method="post" name="login" action="http://localhost/api/login" class ="loginForm">
<p class="loginHere">Login Here</p>
<div className ="login">
<form id="loginForm" method="post" name="login" action="http://localhost/api/login" className ="loginForm">
<p className="loginHere">Login Here</p>
<input type="text" name="nickname" placeholder="login"></input>
<input type="text" name="password" placeholder="password"></input>
<button class="submit" onClick={login}>LOGIN</button>
<button className="submit" onClick={login}>LOGIN</button>
</form>
{/* <button></button> */}
</div>

View File

@ -8,6 +8,7 @@ import io from 'socket.io-client';
export function drawCanvas() {
const socket = io('http://localhost:4000');
// const socket = io()
console.log("start function");
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

View File

@ -23,7 +23,6 @@ root.render(
<Route exact path="/pong" element={<PlayButton />}/>
<Route exact path="/pong/play" element={<Field />}/>
<Route exact path="/login42" element={<Login42 />}/>
{/* <Route exact path="/chat" element={<Field />}/> */}
</Routes>
</BrowserRouter>
</>

View File

@ -11,8 +11,6 @@
font-size: 300%;
}
.clicked{
/* justify-content: center; */
/* display: flex;

View File

@ -32,16 +32,9 @@ export class PongGateway implements OnGatewayInit, OnGatewayConnection, OnGatewa
handleDisconnect(client: Socket)
{
console.log(`Client disconnected: ${client.id}`);
const disconnectedClientId = Object.keys(this.clients).find(clientId => this.clients[clientId] === client);
if (disconnectedClientId)
{
delete this.clients[disconnectedClientId];
console.log(`Client disconnected: ${disconnectedClientId}`);
console.log(`Total connected clients: ${Object.keys(this.clients).length}`);
}
// console.log(`Total connected clients: ${this.clients.size}`);
this.waitingClients.delete(client);
delete this.clients[client.id];
console.log(`Total connected clients: ${Object.keys(this.clients).length}`);
}
@SubscribeMessage('pong:matchmaking')