Skip to content

Commit

Permalink
Merge pull request #16 from La-404-Devinci/features/classement
Browse files Browse the repository at this point in the history
Features/classement
  • Loading branch information
Charles-Chrismann authored Feb 19, 2024
2 parents c1ccbc7 + 452d0bc commit 72880fb
Show file tree
Hide file tree
Showing 12 changed files with 150 additions and 12 deletions.
5 changes: 4 additions & 1 deletion backend/controllers/Chat.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import type { Socket } from "socket.io";
import ChatMessagePayload from "../../common/requests/ChatMessagePayload";

class ChatController {
/**
* Broadcasts a message to all connected clients
Expand All @@ -6,7 +9,7 @@ class ChatController {
* @param data The message data
* @param socket The client socket
*/
public static async broadcastMessage(data: ChatMessagePayload, socket: SocketIO.Socket) {
public static async broadcastMessage(data: ChatMessagePayload, socket: Socket) {
// TODO: Broadcast the message to all clients
/**
* VALIDATION
Expand Down
2 changes: 2 additions & 0 deletions backend/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ WSS.io.on("connection", (socket: Socket) => {
const userAgent = socket.handshake.headers["user-agent"];
console.log(`Socket connected from ${ip} using ${userAgent}`);

WSS.updateClassement(socket);

socket.on("place-pixel", (data) => CanvasController.placePixel(data, socket));
socket.on("message", (data) => ChatController.broadcastMessage(data, socket));

Expand Down
3 changes: 2 additions & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
"build": "tsc",
"start": "node index.js",
"lint": "eslint . --ext .ts",
"format": "prettier --write ."
"format": "prettier --write .",
"seed": "ts-node prisma/seed.ts"
},
"author": "",
"license": "ISC",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
Warnings:
- A unique constraint covering the columns `[devinciEmail]` on the table `Account` will be added. If there are existing duplicate values, this will fail.
*/
-- CreateIndex
CREATE UNIQUE INDEX `Account_devinciEmail_key` ON `Account`(`devinciEmail`);
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/*
Warnings:
- The `lastPixelTime` column on the `Account` table would be dropped and recreated. This will lead to data loss if there is data in the column.
*/
-- AlterTable
ALTER TABLE `Account` MODIFY `isMuted` BOOLEAN NOT NULL DEFAULT false,
MODIFY `isBanned` BOOLEAN NOT NULL DEFAULT false,
MODIFY `isAdmin` BOOLEAN NOT NULL DEFAULT false,
MODIFY `placedPixels` INTEGER NOT NULL DEFAULT 0,
MODIFY `timeAlive` INTEGER NULL,
DROP COLUMN `lastPixelTime`,
ADD COLUMN `lastPixelTime` DATETIME(3) NULL,
MODIFY `lastSentMessageTimes` JSON NULL;
16 changes: 8 additions & 8 deletions backend/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@ datasource db {

model Account {
id Int @id @default(autoincrement())
devinciEmail String
isMuted Boolean
isBanned Boolean
isAdmin Boolean
placedPixels Int
timeAlive Int
lastPixelTime Int
lastSentMessageTimes Json
devinciEmail String @unique()
isMuted Boolean @default(false)
isBanned Boolean @default(false)
isAdmin Boolean @default(false)
placedPixels Int @default(0)
timeAlive Int?
lastPixelTime DateTime?
lastSentMessageTimes Json?
}

model LogEntry {
Expand Down
34 changes: 34 additions & 0 deletions backend/prisma/seed.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

async function main() {
const userCount = Number(process.argv.find(arg => arg.startsWith("userCount="))?.replace(/^userCount=/, "")) ?? 10;
const usersPromise = [] as Promise<unknown>[];
for(let i = 1; i <= userCount; i++) {
const user = prisma.account.upsert({
where: {
devinciEmail: `user_${i}@edu.devinci.fr`
},
update: {
placedPixels: Math.floor(Math.random() * 3000)
},
create: {
devinciEmail: `user_${i}@edu.devinci.fr`,
placedPixels: Math.floor(Math.random() * 3000)
}
});
usersPromise.push(user);
}
await Promise.all(usersPromise);
}

main()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});
31 changes: 29 additions & 2 deletions backend/server/Websocket.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,38 @@
import type http from "http";
import SocketIO from "socket.io";
import type { Server, Socket } from "socket.io";
import { PrismaClient } from "@prisma/client";

const client = new PrismaClient();

class WSS {
public static io: SocketIO.Server;
public static io: Server;

public static init(server: http.Server) {
WSS.io = new SocketIO.Server(server);
WSS.io = new SocketIO.Server(server, {
cors: {
origin: process.env.NODE_ENV === "production" ? undefined : "http://localhost:5173"
}
});
}

/**
* Sends an 'updateClassement' event to one socket if provided. \
* If no socket is provided, broadcast the event to all connected clients.
* @param socket
*/
static async updateClassement(socket?: Socket) {
const classement = await client.account.findMany({
select: {
devinciEmail: true,
placedPixels: true
},
orderBy: {
placedPixels: "desc"
}
});
if(!socket) this.io.emit("classementUpdate", classement);
else socket.emit("classementUpdate", classement);
}
}

Expand Down
6 changes: 6 additions & 0 deletions common/interfaces/classementItem.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
interface classementItem {
devinciEmail: string;
placedPixels: number;
}

export default classementItem
5 changes: 5 additions & 0 deletions common/requests/ChatMessagePayload.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
interface ChatMessagePayload {
[index: string] : Record<string, any>
}

export default ChatMessagePayload
31 changes: 31 additions & 0 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,39 @@
// import { useState } from 'react'
import { useEffect, useState } from 'react';
import './App.css'
import LoginComponent from './pages/login'
import { socket } from './socket';
import classementItem from '../../common/interfaces/classementItem.interface'

function App() {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [classement, setClassement] = useState<classementItem[]>([])
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [isConnected, setIsConnected] = useState(socket.connected);

useEffect(() => {
function onConnect() {
setIsConnected(true);
}

function onDisconnect() {
setIsConnected(false);
}

function onclassementUpdate(data: classementItem[]) {
setClassement(data)
}

socket.on('connect', onConnect);
socket.on('disconnect', onDisconnect);
socket.on('classementUpdate', onclassementUpdate);

return () => {
socket.off('connect', onConnect);
socket.off('disconnect', onDisconnect);
socket.off('classementUpdate', onclassementUpdate);
};
}, []);

// affichage (render)
return (
Expand Down
6 changes: 6 additions & 0 deletions frontend/src/socket.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { io } from 'socket.io-client';

// "undefined" means the URL will be computed from the `window.location` object
const URL = process.env.NODE_ENV === 'production' ? undefined : 'http://localhost:3000';

export const socket = io(URL);

0 comments on commit 72880fb

Please sign in to comment.