Skip to content

Commit

Permalink
sync
Browse files Browse the repository at this point in the history
  • Loading branch information
Saad eddyne El abdari committed Nov 4, 2023
1 parent ee9ec10 commit 4dc4c94
Show file tree
Hide file tree
Showing 7 changed files with 268 additions and 43 deletions.
45 changes: 45 additions & 0 deletions backend/code/seeder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ class dataSeeder extends PrismaClient {
const registeredUsers = await this.registerUser(users);
await this.makeFriendship(registeredUsers);
await this.makeMatch(registeredUsers);
await this.createRoom(registeredUsers);
await this.$disconnect();
}

Expand Down Expand Up @@ -110,6 +111,50 @@ class dataSeeder extends PrismaClient {
bio: faker.person.bio(),
};
}

private async createRoom(users: User[]) {
const owner = users[Math.floor(Math.random() * users.length)];
const roomData = {
name: faker.lorem.word(),
ownerId: owner.userId,
};

// add random users to the room
const filtredUsers = users.filter((user) => user.userId !== owner.userId);
const randomUsers = filtredUsers.slice(
0,
Math.floor(Math.random() * filtredUsers.length),
);

const room = await this.room.create({
data: {
name: roomData.name,
ownerId: roomData.ownerId,
type: 'public',
},
});

for await (const user of randomUsers) {
await this.roomMember.create({
data: {
userId: user.userId,
roomId: room.id,
is_admin: Math.random() > 0.8 ? true : false,
},
});
}
await this.roomMember.create({
data: {
userId: owner.userId,
roomId: room.id,
is_admin: true,
},
});

console.log("roomid: ", room.id)
console.log("ownerid: ", owner.userId)
console.log("randomUsers: ", randomUsers)
}
}

(async () => {
Expand Down
196 changes: 157 additions & 39 deletions backend/code/src/app.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,88 +38,206 @@ export class AppController {
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.socket.io/4.4.1/socket.io.js"></script>
<title>Socket.io Example</title>
</head>
<body>
<h1>Socket.io Example</h1>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}
<!-- Connect to the socket server -->
<script src="https://cdn.socket.io/4.4.1/socket.io.js"></script>
h1 {
text-align: center;
background-color: #333;
color: #fff;
padding: 10px;
margin: 0;
}
#container {
max-width: 800px;
margin: 20px auto;
padding: 20px;
background-color: #fff;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
ul {
list-style: none;
padding: 0;
}
li {
margin: 10px 0;
padding: 10px;
background-color: #e6e6e6;
border-radius: 5px;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}
input[type="text"], button {
display: block;
width: 100%;
padding: 10px;
margin: 5px 0;
border: 1px solid #ccc;
border-radius: 3px;
}
button {
background-color: #333;
color: #fff;
border: none;
cursor: pointer;
}
form {
margin-top: 20px;
}
label {
display: block;
margin-top: 10px;
font-weight: bold;
}
</style>
<script>
// Socket.io script
const socket = io("http://localhost:3004", {
transports: ['websocket'],
withCredentials: true,
});
// Function to send a message
// Functions defined here
function start() {
// Emit event to startGame
console.log('start');
socket.emit("startGame");
}
</script>
<input type="text" id="messageInput" onkeydown="streamMessage(event)">
<button onclick="start()">start</button>
<ul id="messageList"></ul> <!-- Container for displaying messages -->
<!-- Form to send a POST request to ban a member -->
<form onsubmit="banMember(event)">
<label for="roomId">Room ID:</label>
<input type="text" id="roomIdInput" name="roomId" required>
<label for="memberId">Member ID:</label>
<input type="text" id="memberIdInput" name="memberId" required>
<button type="submit">Ban Member</button>
</form>
<script>
function streamMessage(event) {
if (event.key === "ArrowUp") {
socket.emit("move");
}
}
// Listen for events from the server
socket.on("message", (data) => {
console.log("Received from server:", data);
// Display the message in the DOM
displayMessage(data);
});
function displayMessage(data) {
const messageList = document.getElementById("messageList");
const messageItem = document.createElement("li");
messageItem.textContent = "ID: " + data.id + ", Content: " + data.content + ", Time: " + data.time;
messageList.appendChild(messageItem);
}
function banMember(event) {
event.preventDefault();
function banMember() {
const roomId = document.getElementById("roomIdInput").value;
const memberId = document.getElementById("memberIdInput").value;
fetch("http://localhost:3001/rooms/ban", {
method: "POST",
body: JSON.stringify({ roomId, memberId }),
body: JSON.stringify({ roomId: roomId, memberId: memberId }),
headers: {
"Content-Type": "application/json",
},
})
.then((response) => {
.then(function(response) {
if (response.ok) {
// Request was successful, emit "roomDeparture" event to the server
socket.emit("roomDeparture", { roomId, memberId });
socket.emit("roomDeparture", { roomId: roomId, memberId: memberId });
} else {
console.error("Ban request failed");
}
})
.catch((error) => {
console.error("Error:", error);
.catch(function(error) {
console.error("Error: " + error);
});
}
function sendMessageToRoom() {
const roomId = document.getElementById("roomIdInput").value;
const message = document.getElementById("newMessageInput").value;
const raw = JSON.stringify({"content": message});
fetch("http://localhost:3001/messages/room/" + roomId, {
method: "POST",
body: raw,
headers: {
"Content-Type": "application/json",
},
})
.then(function(response) {
if (response.ok) {
console.log("Message sent to room " + roomId + ": " + message);
} else {
console.error("Message sending failed");
}
})
.catch(function(error) {
console.error("Error: " + error);
});
}
function unbanMember() {
const roomIdUnban = document.getElementById("roomIdUnbanInput").value;
const memberIdUnban = document.getElementById("memberIdUnbanInput").value;
fetch("http://localhost:3001/rooms/unban", {
method: "POST",
body: JSON.stringify({ roomId: roomIdUnban, memberId: memberIdUnban }),
headers: {
"Content-Type": "application/json",
},
})
.then(function(response) {
if (response.ok) {
console.log("Member unbanned successfully.");
} else {
console.error("Unban request failed");
}
})
.catch(function(error) {
console.error("Error: " + error);
});
}
// Listening for the "message" event and displaying messages
socket.on("message", function(data) {
displayMessage(data);
});
</script>
</head>
<body>
<h1>Socket.io Example</h1>
<div id="container">
<input type="text" id="messageInput" onkeydown="streamMessage(event)" placeholder="Press Arrow Up to Stream Message">
<button type="button" onclick="start()">Start</button>
<ul id="messageList"></ul> <!-- Container for displaying messages -->
<!-- Form to send a POST request to ban a member -->
<form onsubmit="banMember(event)">
<label for="roomId">Room ID:</label>
<input type="text" id="roomIdInput" name="roomId" required>
<label for="memberId">Member ID:</label>
<input type="text" id="memberIdInput" name="memberId" required>
<button type="button" onclick="banMember()">Ban Member</button>
</form>
<!-- New message area and button -->
<input type="text" id="newMessageInput" placeholder="Enter a Message">
<button type="button" onclick="sendMessageToRoom()">Send Message</button>
<!-- Unban Member button -->
<form onsubmit="unbanMember(event)">
<label for="roomIdUnban">Room ID (Unban):</label>
<input type="text" id="roomIdUnbanInput" name="roomIdUnban" required>
<label for="memberIdUnban">Member ID (Unban):</label>
<input type="text" id="memberIdUnbanInput" name="memberIdUnban" required>
<button type="button" onclick="unbanMember()">Unban Member</button>
</form>
</div>
</body>
</html>
`;
Expand Down
2 changes: 1 addition & 1 deletion backend/code/src/game/game.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export class GameService {
private readonly prisma: PrismaService,
private eventEmitter: EventEmitter2,
) {
this.launchGame();
// this.launchGame();
}

private waitingPlayers: Socket[] = [];
Expand Down
17 changes: 15 additions & 2 deletions backend/code/src/gateways/gateways.gateway.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
MessageBody,
OnGatewayConnection,
SubscribeMessage,
WebSocketGateway,
Expand Down Expand Up @@ -41,6 +42,7 @@ export class Gateways implements OnGatewayConnection {
rooms.then((rooms) => {
rooms.forEach((room) => {
client.join(`Romm:${room.room.id}`);
console.log(`Romm:${room.room.id}`);
});
});
client.join(`notif:${userId}`);
Expand Down Expand Up @@ -89,7 +91,18 @@ export class Gateways implements OnGatewayConnection {
}

@SubscribeMessage('roomDeparture')
hundleDeparture(client: Socket, data: { roomid: string; message: string }) {
console.log(data);
async hundleDeparture(
@MessageBody() data: { roomId: string; memberId: string },
) {
const clients = await this.server.in(`Romm:${data.roomId}`).fetchSockets();
console.log(`Romm:${data.roomId}`);
const clientToBan = clients.find(
(client) => client.data.user.sub === data.memberId,
);
if (clientToBan) {
clientToBan.leave(`Romm:${data.roomId}`);
} else {
console.log('client not found');
}
}
}
5 changes: 4 additions & 1 deletion backend/code/src/messages/messages.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export class MessagesService {
) {}

async sendMessages(userId: string, channelId: string, messageDto: any) {
console.log(messageDto);
if (messageDto.content.length > 1000) {
throw new HttpException('Message is too long', HttpStatus.BAD_REQUEST);
}
Expand All @@ -27,7 +28,9 @@ export class MessagesService {
},
},
});

if (!room) {
throw new HttpException('Room not found', HttpStatus.NOT_FOUND);
}
if (room.type === 'dm') {
const blocked = await this.prisma.blockedUsers.findFirst({
where: {
Expand Down
10 changes: 10 additions & 0 deletions backend/code/src/rooms/rooms.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,4 +207,14 @@ export class RoomsController {
) {
return this.roomsService.listRooms(userId, offset, limit, joined);
}

@Get('dms')
@HttpCode(HttpStatus.OK)
@UseGuards(AtGuard)
async getDMs(
@GetCurrentUser('userId') userId: string,
@Query() { offset, limit }: QueryOffsetDto,
) {
return this.roomsService.getDMs(userId, offset, limit);
}
}
Loading

0 comments on commit 4dc4c94

Please sign in to comment.