friend request start

This commit is contained in:
kinou-p 2023-06-09 17:09:08 +02:00
parent 2248b4e89e
commit 7085fc1f8d
5 changed files with 213 additions and 50 deletions

View File

@ -68,6 +68,15 @@ export class AppController {
return await this.userService.addFriend(user, data.username); return await this.userService.addFriend(user, data.username);
} }
@UseGuards(JwtAuthGuard)
@Get('/invite')
async getInvite(@Request() req) {
// return await this.userService.getFriends(req.user.username);
console.log(`useawdawd\n\n\nr= ${req.user.username}`)
// const user = await this.userService.findOne(req.user.username)
return await this.userService.getInvite(req.user.username);
}
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Post('/status') @Post('/status')
async setStatus(@Request() req, @Body() data: any) { async setStatus(@Request() req, @Body() data: any) {

View File

@ -43,7 +43,19 @@ export class UsersService {
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]);
console.log(friends)
return (friends)
}
async getInvite(username: string) {
const user = await this.findOne(username)
let friendsTab = user.friendRequest
// console.log(friendsTab[0])
// console.log(friendsTab[1])
console.log(friendsTab)
// 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]);
console.log(friends) console.log(friends)
return (friends) return (friends)

View File

@ -8,7 +8,7 @@ export class PongGateway implements OnGatewayInit, OnGatewayConnection, OnGatewa
private clients: Record<string, Socket> = {}; private clients: Record<string, Socket> = {};
private waitingClients: Set<Socket> = new Set(); private waitingClients: Set<{ client: Socket, option: number }> = new Set();
// private waitingClients: Set<Socket> = new Set(); // Utilisateurs cherchant un match // 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
@ -32,24 +32,72 @@ export class PongGateway implements OnGatewayInit, OnGatewayConnection, OnGatewa
handleDisconnect(client: Socket) handleDisconnect(client: Socket)
{ {
console.log(`Client disconnected: ${client.id}`); console.log(`Client disconnected: ${client.id}`);
this.waitingClients.delete(client); // this.waitingClients.delete(client);
this.waitingClients.forEach((waitingClient) => {
if (waitingClient.client === client) {
this.waitingClients.delete(waitingClient);
}})
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}`);
} }
@SubscribeMessage('pong:matchmaking') // @SubscribeMessage('pong:matchmaking')
addMatchmaking(client: Socket, payload: any): void // addMatchmaking(client: Socket, payload: any): void
{ // {
// console.log("matchmaking");
// console.log(payload);
// // this.waitingClients.add(client);
// this.waitingClients.add(client);
// console.log("Adding client to waiting list...");
// if (this.waitingClients.size >= 2) {
// console.log("Creating new game...");
// const players = Array.from(this.waitingClients).slice(0, 2);
// players.forEach((player) => {
// this.waitingClients.delete(player);
// });
// const gameId = uuidv4();
// this.games.set(gameId, players);
// players.forEach((player) => {
// player.join(gameId);
// console.log(`Player ${player.id} joined game ${gameId}`);
// });
// players.forEach((player) => {
// // const playersIds = game.map(socket => socket.id);
// player.emit('pong:gameId', gameId);
// });
// }
// // console.log(`from: ${client.id}`);
// }
@SubscribeMessage('pong:matchmaking')
addMatchmaking(client: Socket, payload: any): void {
console.log("matchmaking"); console.log("matchmaking");
console.log(payload); console.log(payload);
// this.waitingClients.add(client); // Add the client to the waitingClients set along with their chosen option
this.waitingClients.add(client); this.waitingClients.add({ client, option: payload.option });
console.log("Adding client to waiting list..."); console.log("Adding client to waiting list...");
if (this.waitingClients.size >= 2) {
// Filter the waitingClients set to find clients with the same option
const matchingClients = Array.from(this.waitingClients).filter(
(waitingClient) =>
waitingClient.option === payload.option && waitingClient.client !== client
);
if (matchingClients.length > 0) {
console.log("Creating new game..."); console.log("Creating new game...");
const players = Array.from(this.waitingClients).slice(0, 2); const players = [matchingClients[0].client, client]; // Add the current client to the players array
players.forEach((player) => { players.forEach((player) => {
this.waitingClients.delete(player); // this.waitingClients.delete(
// this.waitingClients.find(
// (waitingClient) => waitingClient.client === player
// )
// );
const matchingClient = Array.from(this.waitingClients).find(
(waitingClient) => waitingClient.client === player
);
if (matchingClient) {
this.waitingClients.delete(matchingClient);
}
}); });
const gameId = uuidv4(); const gameId = uuidv4();
this.games.set(gameId, players); this.games.set(gameId, players);
@ -58,12 +106,11 @@ export class PongGateway implements OnGatewayInit, OnGatewayConnection, OnGatewa
console.log(`Player ${player.id} joined game ${gameId}`); console.log(`Player ${player.id} joined game ${gameId}`);
}); });
players.forEach((player) => { players.forEach((player) => {
// const playersIds = game.map(socket => socket.id);
player.emit('pong:gameId', gameId); player.emit('pong:gameId', gameId);
}); });
} }
// console.log(`from: ${client.id}`); // console.log(`from: ${client.id}`);
} }
// @SubscribeMessage('pong:message') // @SubscribeMessage('pong:message')
// handleMessage(client: Socket, payload: any): void // handleMessage(client: Socket, payload: any): void

View File

@ -0,0 +1,104 @@
import { useEffect, useState } from "react";
import api from '../../script/axiosApi';
import DefaultPicture from '../../assets/profile.jpg'
import styled from "styled-components";
import { RxCheckCircled, RxCircleBackslash } from "react-icons/rx";
const UserChat = styled.div `
padding: 5px;
display: flex;
align-items: center;
gap: 5px;
color: white;
cursor: pointer;
&:hover{
background-color: #3e3c61;
}
`
const SideP = styled.p`
font-size: 14px;
color: lightgray;
margin-left: 15px;
`
export default function Friend({currentUser})
{
const [profilePicture, setProfilePicture] = useState('');
const [request, setRequest] = useState('');
useEffect(() => {
const fetchProfilePicture = async () => {
try {
// const user = await api.get("/profile");
const pic = await api.post("/getPicture", {username: currentUser.username})
const tmpRequest = await api.post("/user", {username: currentUser.username})
setRequest(tmpRequest.data);
// console.log(`user naem profile pic222= ${currentUser.username}`)
// console.log(` profile pic222= ${pic.data}`)
setProfilePicture(pic.data);
} catch (error) {
console.error('Error fetching profile picture:', error);
}
};
fetchProfilePicture();
})
function getStatus(friend)
{
let status = friend.status
console.log(`status= ${status}`)
let statusColor;
if (status === 0)
statusColor = 'grey';
else if (status === 1)
statusColor = 'green';
else if (status === 2)
statusColor = 'blue';
return statusColor;
}
const handleSpectate = (user) => {
//socket connection and add to party with one with username
console.log(`spectate hehe`)
console.log(`user= ${user}`)
};
const handleButtonClick = (user) => {
let path = `http://localhost/profile/${user.username}`;
// history(path, { replace: true });
// window.location.replace(path);
window.history.pushState({}, null, path);
window.location.reload(false);
};
const Accept = (user) => {
console.log("accept")
}
const Refuse = (user) => {
console.log("refuse")
}
return (
<UserChat>
{profilePicture ? (
<img className="pic-user" src={`data:image/jpeg;base64,${profilePicture}`} />
) : (
<img className="pic-user" src={DefaultPicture} alt="Default Profile Picture" />
)}
<div className="infoSideBar">
<span onClick={() => handleButtonClick(currentUser)}>{currentUser.nickname}</span>
<RxCheckCircled onClick={() => Accept(request)} color={'green'}/>
<RxCircleBackslash onClick={() => Refuse(request)} color={'red'}/>
</div>
</UserChat>
)
}

View File

@ -5,6 +5,7 @@ import styled from "styled-components";
import Friend from './Friend.jsx'; import Friend from './Friend.jsx';
import FriendRequest from './FriendRequest.jsx';
import { ImBlocked } from 'react-icons/im'; import { ImBlocked } from 'react-icons/im';
import { MdOutlineGroupAdd } from 'react-icons/md'; import { MdOutlineGroupAdd } from 'react-icons/md';
@ -32,6 +33,7 @@ const TouchDiv = styled.div`
function Social (){ function Social (){
const [friends, setFriends] = useState([]); const [friends, setFriends] = useState([]);
const [invite, setInvite] = useState([]);
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
const [user, setUser] = useState(null); const [user, setUser] = useState(null);
const [profilePicture, setProfilePicture] = useState(''); const [profilePicture, setProfilePicture] = useState('');
@ -42,7 +44,10 @@ function Social (){
try{ try{
const tmpFriends = await api.get("/friends") const tmpFriends = await api.get("/friends")
const tmpUser = await api.get("/profile") const tmpUser = await api.get("/profile")
const tmpInv = await api.get("/invite")
const pic = await api.post("/getPicture", {username: tmpUser.data.username}) const pic = await api.post("/getPicture", {username: tmpUser.data.username})
setInvite(tmpInv.data);
setProfilePicture(pic.data); setProfilePicture(pic.data);
setUser(tmpUser.data); setUser(tmpUser.data);
setFriends(tmpFriends.data); setFriends(tmpFriends.data);
@ -105,28 +110,14 @@ function Social (){
</div> </div>
</div> </div>
{/* map with fiend request */}
{invite.map(c=> (
<FriendRequest currentUser={c}/>
))}
{friends.map(c=> ( {friends.map(c=> (
<Friend currentUser={c}/> <Friend currentUser={c}/>
// <UserChat>
// {profilePicture ? (
// <img className="pic-user" src={`data:image/jpeg;base64,${profilePicture}`} />
// ) : (
// <img className="pic-user" src={DefaultPicture} alt="Default Profile Picture" />
// )}
// <div className="infoSideBar">
// <span onClick={() => handleButtonClick(c)}>{c.nickname}</span>
// <RxCircle icon={RxCircle} color={getStatus(c)} />
// <button onClick={() => handleSpectate(c)} >Invite</button>
// {getStatus(c) !== 'blue' ? (
// <></>
// ) : (
// <button onClick={() => handleSpectate(c)} >Spectate</button>
// )}
// </div>
// </UserChat>
// </div>
))} ))}
</div> </div>
) )