Skip to content

Commit

Permalink
Fixing bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
ismail-kharrobi committed Nov 16, 2023
1 parent 705a4fc commit 24c5294
Show file tree
Hide file tree
Showing 46 changed files with 1,284 additions and 1,293 deletions.
2 changes: 1 addition & 1 deletion backend/code/accountPickerCli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ var requestOptions = {
redirect: 'follow'
};
fetch("http://localhost:3001/auth/login", requestOptions)
fetch("http://test.reversablecode.com:3001/auth/login", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));`;
Expand Down
13 changes: 13 additions & 0 deletions backend/code/prisma/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
FROM node:18

# Create app directory
WORKDIR /app

# Install prisma for the migration
RUN npm install -g prisma --unsafe-perm

# Copy schema and migration folder
ADD ./ ./prisma/

# Run migration
CMD ["prisma", "migrate", "deploy"]
8 changes: 6 additions & 2 deletions backend/code/prisma/dbml/schema.dbml
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,14 @@ Table blocked_friends {
createdAt DateTime [default: `now()`, not null]
id String [pk]
Blcoked_by users [not null]
blocked_by_id String [unique, not null]
blocked_by_id String [not null]
Blocked users [not null]
blocked_id String [unique, not null]
blocked_id String [not null]
dmRoomId String

indexes {
(blocked_by_id, blocked_id) [unique]
}
}

Table matches {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/*
Warnings:
- A unique constraint covering the columns `[blocked_by_id,blocked_id]` on the table `blocked_friends` will be added. If there are existing duplicate values, this will fail.
*/
-- DropIndex
DROP INDEX "blocked_friends_blocked_by_id_key";

-- DropIndex
DROP INDEX "blocked_friends_blocked_id_key";

-- CreateIndex
CREATE UNIQUE INDEX "blocked_friends_blocked_by_id_blocked_id_key" ON "blocked_friends"("blocked_by_id", "blocked_id");
5 changes: 3 additions & 2 deletions backend/code/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,12 @@ model BlockedUsers {
id String @id
Blcoked_by User @relation("blocked_by", fields: [blocked_by_id], references: [userId], onDelete: Cascade)
blocked_by_id String @unique
blocked_by_id String
Blocked User @relation("blocked", fields: [blocked_id], references: [userId], onDelete: Cascade)
blocked_id String @unique
blocked_id String
dmRoomId String?
@@unique([blocked_by_id, blocked_id], name: "unique_block")
@@map("blocked_friends")
}

Expand Down
10 changes: 5 additions & 5 deletions backend/code/src/app.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ export class AppController {
</style>
<script>
// Socket.io script
const socket = io("http://localhost:3004", {
const socket = io("http://test.reversablecode.com:3004", {
transports: ['websocket'],
withCredentials: true,
});
Expand Down Expand Up @@ -134,7 +134,7 @@ export class AppController {
const roomId = document.getElementById("roomIdInput").value;
const memberId = document.getElementById("memberIdInput").value;
fetch("http://localhost:3001/rooms/ban", {
fetch("http://test.reversablecode.com:3001/rooms/ban", {
method: "POST",
body: JSON.stringify({ roomId: roomId, memberId: memberId }),
headers: {
Expand All @@ -159,7 +159,7 @@ export class AppController {
const raw = JSON.stringify({"content": message});
fetch("http://localhost:3001/messages/room/" + roomId, {
fetch("http://test.reversablecode.com:3001/messages/room/" + roomId, {
method: "POST",
body: raw,
headers: {
Expand All @@ -182,7 +182,7 @@ const raw = JSON.stringify({"content": message});
const roomIdUnban = document.getElementById("roomIdUnbanInput").value;
const memberIdUnban = document.getElementById("memberIdUnbanInput").value;
fetch("http://localhost:3001/rooms/unban", {
fetch("http://test.reversablecode.com:3001/rooms/unban", {
method: "POST",
body: JSON.stringify({ roomId: roomIdUnban, memberId: memberIdUnban }),
headers: {
Expand All @@ -209,7 +209,7 @@ const raw = JSON.stringify({"content": message});
function sendFriendRequest() {
const friendId = document.getElementById("friendIdInput").value;
fetch("http://localhost:3001/friends/add", {
fetch("http://test.reversablecode.com:3001/friends/add", {
method: "POST",
body: JSON.stringify({ friendId: friendId }),
headers: {
Expand Down
30 changes: 24 additions & 6 deletions backend/code/src/gateways/gateways.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { MessageFormatDto } from 'src/messages/dto/message-format.dto';
import {} from '@nestjs/platform-socket.io';
import { } from '@nestjs/platform-socket.io';
import { EventEmitter2, OnEvent } from '@nestjs/event-emitter';
import { PrismaService } from 'src/prisma/prisma.service';
import { Game } from 'src/game/game';
Expand All @@ -26,7 +26,7 @@ interface GameInvite {

@WebSocketGateway(3004, {
cors: {
origin: ['http://localhost:3001'],
origin: ['http://test.reversablecode.com:3001'],
},
transports: ['websocket'],
})
Expand All @@ -35,7 +35,7 @@ export class Gateways implements OnGatewayConnection, OnGatewayDisconnect {
private prisma: PrismaService,
private readonly eventEmitter: EventEmitter2,
private readonly usersService: UsersService,
) {}
) { }

@WebSocketServer() private server: Server;
private games_map = new Map<string, Game>();
Expand Down Expand Up @@ -78,9 +78,23 @@ export class Gateways implements OnGatewayConnection, OnGatewayDisconnect {
}

@OnEvent('sendMessages')
sendMessage(message: MessageFormatDto) {
async sendMessage(message: MessageFormatDto, blockedRoomMembersIds?: string[]) {
const chanellname: string = `Room:${message.roomId}`;
this.server.to(chanellname).emit('message', message);
if (!blockedRoomMembersIds) {
this.server.to(chanellname).emit('message', message);
} else {
const sockets = await this.server.in(chanellname).fetchSockets();
for await (const socket of sockets) {
if (!blockedRoomMembersIds.includes(socket.data.user.sub)) {
socket.emit('message', message);
} else {
socket.emit('message', {
...message,
content: '[REDACTED]',
});
}
}
}
}

private async createNotification(notif: Partial<Notification>) {
Expand Down Expand Up @@ -113,7 +127,7 @@ export class Gateways implements OnGatewayConnection, OnGatewayDisconnect {
}

@OnEvent('sendNotification')
async sendNotification(notif: Partial<Notification>) {
async sendNotification(notif: Partial<Notification>, blockedRoomMembersIds?: string[]) {
// create the notification on the database
switch (notif.type) {
case $Enums.NotifType.acceptFriend:
Expand Down Expand Up @@ -165,6 +179,10 @@ export class Gateways implements OnGatewayConnection, OnGatewayDisconnect {
.in(`Room:${message.roomId}`)
.fetchSockets();
for await (const member of roomMembers) {
if (blockedRoomMembersIds?.includes(member.userId)) {
continue;
}

let found = false;
for await (const clientSocket of clientsSockets) {
if (clientSocket.data.user.sub === member.userId) {
Expand Down
6 changes: 3 additions & 3 deletions backend/code/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ async function bootstrap() {
const app = await NestFactory.create(AppModule);
const corsOptions = {
origin: [
'http://localhost:9000',
'http://localhost:8000',
'http://localhost:3000',
'http://test.reversablecode.com:9000',
'http://test.reversablecode.com:8000',
'http://test.reversablecode.com:3000',
'http://142.93.161.63',
'http://164.92.243.105',
],
Expand Down
44 changes: 29 additions & 15 deletions backend/code/src/messages/messages.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,9 @@ export class MessagesService {
constructor(
private prisma: PrismaService,
private eventEmitter: EventEmitter2,
) {}
) { }

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 Down Expand Up @@ -40,8 +39,8 @@ export class MessagesService {
});
if (blocked) {
throw new HttpException(
'You are blocked from this dm',
HttpStatus.UNAUTHORIZED,
'You are blocked from sending messages to this user',
HttpStatus.FORBIDDEN,
);
}
}
Expand All @@ -50,22 +49,22 @@ export class MessagesService {

if (!roomMember) {
throw new HttpException(
'User is not in channel',
HttpStatus.UNAUTHORIZED,
'You are not in this channel',
HttpStatus.FORBIDDEN,
);
}

if (roomMember.is_banned) {
throw new HttpException(
'you are banned from this channel',
HttpStatus.UNAUTHORIZED,
'You are banned from this channel',
HttpStatus.FORBIDDEN,
);
}

if (roomMember.is_mueted) {
const now = new Date();
if (now < roomMember.mute_expires) {
throw new HttpException('User is muted', HttpStatus.UNAUTHORIZED);
throw new HttpException(`You are muted for ${Math.round((roomMember.mute_expires.valueOf() - now.valueOf()) / 1000)} seconds`, HttpStatus.FORBIDDEN);
}
await this.prisma.roomMember.update({
where: {
Expand Down Expand Up @@ -99,14 +98,29 @@ export class MessagesService {
},
});

const roomMembersIds = await this.prisma.roomMember.findMany({
where: { roomId: channelId, NOT: { userId } },
select: { userId: true }
});
const blockedUsersIds = await this.prisma.blockedUsers.findMany({
where: { OR: [{ blocked_by_id: userId }, { blocked_id: userId }] },
select: { blocked_by_id: true, blocked_id: true }
});

const blockedRoomMembersIds = roomMembersIds.filter((member) => {
return blockedUsersIds.some((blocked) => {
return blocked.blocked_by_id === member.userId || blocked.blocked_id === member.userId;
});
}).map((member) => member.userId);

const responseMessage: MessageFormatDto = new MessageFormatDto(messageData, messageDto.clientMessageId);
this.eventEmitter.emit('sendNotification', {
actorId: userId,
type: $Enums.NotifType.message,
entityId: messageData.id,
entity_type: 'message',
});
this.eventEmitter.emit('sendMessages', responseMessage);
}, blockedRoomMembersIds.length ? blockedRoomMembersIds : undefined);
this.eventEmitter.emit('sendMessages', responseMessage, blockedRoomMembersIds.length ? blockedRoomMembersIds : undefined);
return responseMessage;
}

Expand All @@ -125,8 +139,8 @@ export class MessagesService {

if (!roomMember) {
throw new HttpException(
'User is not in channel',
HttpStatus.UNAUTHORIZED,
'You are not in this channel',
HttpStatus.FORBIDDEN,
);
}
const messages = await this.prisma.message.findMany({
Expand Down Expand Up @@ -175,7 +189,7 @@ export class MessagesService {
if (blocked) {
messages.forEach((message) => {
if (message.authorId !== userId) {
message.content = '[REDUCTED]';
message.content = '[REDACTED]';
}
});
}
Expand All @@ -200,7 +214,7 @@ export class MessagesService {
);
messages.forEach((message) => {
if (blockedUsersIds.includes(message.authorId)) {
message.content = '[REDUCTED]';
message.content = '[REDACTED]';
}
});
}
Expand Down
8 changes: 5 additions & 3 deletions backend/code/src/profile/dto/update-profile.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
IsNotEmpty,
IsOptional,
IsString,
MinLength,
Length,
} from 'class-validator';

export class UpdateProfileDto {
Expand All @@ -28,20 +28,21 @@ export class UpdateProfileDto {
@IsOptional()
@IsString()
@IsNotEmpty()
@MinLength(4)
@Length(4, 50)
firstName?: string;

@ApiProperty({ required: false })
@IsOptional()
@IsString()
@IsNotEmpty()
@MinLength(4)
@Length(4, 50)
lastName?: string;

@ApiProperty({ required: false })
@IsOptional()
@IsString()
@IsNotEmpty()
@Length(4, 50)
discreption?: string;

@ApiProperty({ required: true })
Expand All @@ -53,5 +54,6 @@ export class UpdateProfileDto {
@IsOptional()
@IsString()
@IsNotEmpty()
@Length(4, 50)
Username: string;
}
1 change: 1 addition & 0 deletions backend/code/src/rooms/dto/create-room.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export class CreateRoomDto {
@ApiProperty({ description: 'name of the room required if type is not dm' })
@IsString()
@IsNotEmpty()
@Length(4, 20)
@ValidateIf((o) => o.type !== 'dm')
name: string;

Expand Down
Loading

0 comments on commit 24c5294

Please sign in to comment.