Skip to content

Commit

Permalink
Merge branch 'main' into DEV-TEST_BACKEND
Browse files Browse the repository at this point in the history
  • Loading branch information
ayoubessabiry authored Oct 23, 2023
2 parents 903f258 + 44a0340 commit 9fee980
Show file tree
Hide file tree
Showing 49 changed files with 871 additions and 207 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/automerge.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ jobs:
- name : run docker
run : docker compose up --build -d
label:
if : github.event.pull_request.user.login == 'ismail-kharrobi' || github.event.pull_request.user.login == 'Wadie-ess' || github.event.pull_request.user.login == 'sedeve'
if : github.event.pull_request.user.login == 'ismail-kharrobi' || github.event.pull_request.user.login == 'Wadie-ess' || github.event.pull_request.user.login == 'sedeve' || github.event.pull_request.user.login == 'ayoubessabiry'
runs-on: ubuntu-latest
permissions: write-all
needs: [front, back,docker]
Expand Down
2 changes: 1 addition & 1 deletion backend/Dockerfile.dev
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ RUN npm install

COPY ./code .

CMD ["sh", "-c","npx prisma db push --force-reset && npx prisma studio & npm run start:dev"]
CMD ["sh", "-c","npx prisma studio & npm run start:dev"]
5 changes: 3 additions & 2 deletions backend/code/prisma/dbml/schema.dbml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ Table users {
refreshedHash String
intraId String [unique]
profileFinished Boolean [not null, default: false]
Username String
Username String [unique]
firstName String
lastName String
discreption String [not null, default: '']
Expand Down Expand Up @@ -49,6 +49,7 @@ Table blocked_friends {
blocked_by_id String [unique, not null]
Blocked users [not null]
blocked_id String [unique, not null]
dmRoomId String
}

Table matches {
Expand Down Expand Up @@ -136,7 +137,7 @@ Ref: blocked_friends.blocked_id > users.userId

Ref: matches.participant1Id > users.userId

Ref: messages.roomId > rooms.id
Ref: messages.roomId > rooms.id [delete: Cascade]

Ref: rooms.ownerId > users.userId

Expand Down
5 changes: 3 additions & 2 deletions backend/code/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ model User {
intraId String? @unique
profileFinished Boolean @default(false)
Username String?
Username String? @unique
firstName String?
lastName String?
discreption String @default("")
Expand Down Expand Up @@ -66,6 +66,7 @@ model BlockedUsers {
blocked_by_id String @unique
Blocked User @relation("blocked", fields: [blocked_id], references: [userId])
blocked_id String @unique
dmRoomId String?
@@map("blocked_friends")
}
Expand All @@ -92,7 +93,7 @@ model Message {
id String @id @default(cuid())
authorId String
room Room @relation(fields: [roomId], references: [id])
room Room @relation(fields: [roomId], references: [id], onDelete: Cascade)
roomId String
content String?
Expand Down
2 changes: 2 additions & 0 deletions backend/code/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { CloudinaryModule } from './cloudinary/cloudinary.module';
import { MessagesModule } from './messages/messages.module';
import { EventEmitterModule } from '@nestjs/event-emitter';
import { Gateways } from './gateways/gateways.gateway';
import { GameModule } from './game/game.module';
import { LeaderBoardModule } from './leaderboard/leaderboard.module';

@Module({
Expand All @@ -24,6 +25,7 @@ import { LeaderBoardModule } from './leaderboard/leaderboard.module';
CloudinaryModule,
MessagesModule,
EventEmitterModule.forRoot(),
GameModule,
LeaderBoardModule,
],
controllers: [AppController],
Expand Down
2 changes: 1 addition & 1 deletion backend/code/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export class AuthController {
@ApiExcludeEndpoint()
@Get('login/42/return')
@UseGuards(FtOauthGuard)
@Redirect(process.env.FRONT_URL + '/Home')
@Redirect(process.env.FRONT_URL ? process.env.FRONT_URL + '/Home' : '/') //WARNING:
login42Return() {
return;
}
Expand Down
10 changes: 9 additions & 1 deletion backend/code/src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,21 @@ import { FtStrategy } from './stratgies/ft.strategy';
import { JwtUtilsModule } from './utils/jwt_utils/jwt_utils.module';
import { UsersService } from 'src/users/users.service';
import { JwtConsts } from './constants/constants';
import { CloudinaryService } from 'src/cloudinary/cloudinary.service';

@Module({
imports: [
JwtModule.register({ secret: JwtConsts.at_secret }),
JwtUtilsModule,
],
providers: [AuthService, AtStrategy, RtStrategy, FtStrategy, UsersService],
providers: [
AuthService,
AtStrategy,
RtStrategy,
FtStrategy,
UsersService,
CloudinaryService,
],
controllers: [AuthController],
})
export class AuthModule {}
15 changes: 15 additions & 0 deletions backend/code/src/auth/stratgies/ft.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ import { PassportStrategy } from '@nestjs/passport';
import { Strategy, Profile, VerifyCallback } from 'passport-42';
import { JwtUtils } from '../utils/jwt_utils/jwt_utils';
import { UsersService } from 'src/users/users.service';
import { CloudinaryService } from 'src/cloudinary/cloudinary.service';

@Injectable()
export class FtStrategy extends PassportStrategy(Strategy, '42') {
constructor(
private jwtUtils: JwtUtils,
private usersService: UsersService,
private cloudinaryService: CloudinaryService,
) {
super({
clientID: process.env.FT_CLIENT_ID,
Expand Down Expand Up @@ -46,16 +48,29 @@ export class FtStrategy extends PassportStrategy(Strategy, '42') {
email: profile._json.email,
firstName: profile.name.givenName,
lastName: profile.name.familyName,
Username: profile.username,
});

const avatarturl = `https://ui-avatars.com/api/?name=${new_user.firstName}-${new_user.lastName}&background=7940CF&color=fff`;
const result = await this.cloudinaryService.upload(
new_user.userId,
avatarturl,
);

await this.usersService.updateUser(new_user.userId, {
avatar: `v${result.version}/${result.public_id}.${result.format}`,
});

const tokens = await this.jwtUtils.generateTokens(
new_user.email,
new_user.userId,
);

await this.jwtUtils.updateRefreshedHash(
new_user.userId,
tokens.refresh_token,
);

res.cookie('X-Access-Token', tokens.access_token, { httpOnly: true });
res.cookie('X-Refresh-Token', tokens.refresh_token, { httpOnly: true });
return cb(null, profile);
Expand Down
11 changes: 7 additions & 4 deletions backend/code/src/cloudinary/cloudinary.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,14 @@ import { v2 as cloudinary } from 'cloudinary';
export class CloudinaryService {
constructor() {}

async upload(file: any) {
return await cloudinary.uploader.upload(file.path, {
folder: 'tran-avatar',
async upload(userId: string, url: string) {
return await cloudinary.uploader.upload(url, {
folder: 'nest-blog',
overwrite: true,
resource_type: 'auto',
resource_type: 'image',
unique_filename: false,
filename_override: userId,
use_filename: true,
});
}
}
30 changes: 30 additions & 0 deletions backend/code/src/friends/friends.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,18 +107,48 @@ export class FriendsService {
'You cannot block yourself',
HttpStatus.FORBIDDEN,
);

const commonRoom = await this.prisma.room.findFirst({
where: {
AND: [
{
type: 'dm',
},
{
members: {
some: {
userId: userId,
},
},
},
{
members: {
some: {
userId: friendId,
},
},
},
],
},
select: {
id: true,
},
});

const friendshipId = [userId, friendId].sort().join('-');
await this.prisma.friend.deleteMany({
where: {
id: friendshipId,
},
});

await this.prisma.blockedUsers.upsert({
where: {
id: friendshipId,
},
create: {
id: friendshipId,
...(commonRoom && { dmRoomId: commonRoom.id }),
Blcoked_by: {
connect: {
userId,
Expand Down
12 changes: 12 additions & 0 deletions backend/code/src/game/game.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Controller, Post } from '@nestjs/common';
import { GameService } from './game.service';

@Controller('game')
export class GameController {
constructor(private readonly gameService: GameService) {}

@Post('start')
startGame() {
// return this.gameService.startGame();
}
}
9 changes: 9 additions & 0 deletions backend/code/src/game/game.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { GameService } from './game.service';
import { GameController } from './game.controller';

@Module({
controllers: [GameController],
providers: [GameService],
})
export class GameModule {}
28 changes: 28 additions & 0 deletions backend/code/src/game/game.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { Injectable } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';

@Injectable()
export class GameService {
constructor() {
// this.launchGame();
}

private waitingPlayers: string[] = [];

@OnEvent('game.start')
handleGameStartEvent(client: any) {
this.waitingPlayers.push(client.id);
console.log('client subscribed to the queue');
}

private launchGame() {
setInterval(() => {
console.log('waitingPlayers');
if (this.waitingPlayers.length >= 2) {
console.log('Game launched!');
const two_players = this.waitingPlayers.splice(0, 2);
console.log(two_players);
}
}, 1000);
}
}
28 changes: 26 additions & 2 deletions backend/code/src/gateways/gateways.gateway.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import {
OnGatewayConnection,
SubscribeMessage,
WebSocketGateway,
WebSocketServer,
} 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 { OnEvent } from '@nestjs/event-emitter';
import { EventEmitter2, OnEvent } from '@nestjs/event-emitter';
import { PrismaService } from 'src/prisma/prisma.service';
@WebSocketGateway(3004, {
cors: {
Expand All @@ -15,7 +16,10 @@ import { PrismaService } from 'src/prisma/prisma.service';
transports: ['websocket'],
})
export class Gateways implements OnGatewayConnection {
constructor(private prisma: PrismaService) {}
constructor(
private prisma: PrismaService,
private readonly eventEmitter: EventEmitter2,
) {}
handleConnection(client: Socket) {
const userId = client.data.user.sub;
const rooms = this.prisma.roomMember.findMany({
Expand Down Expand Up @@ -46,9 +50,29 @@ export class Gateways implements OnGatewayConnection {
const chanellname: string = `Romm:${message.roomId}`;
this.server.to(chanellname).emit('message', message);
}

@OnEvent('addFriendNotif')
sendFriendReq(notif: any) {
const channellname: string = `notif:${notif.recipientId}`;
this.server.to(channellname).emit('message', notif);
}

@SubscribeMessage('startGame')
handleGameStartEvent(client: any) {
this.eventEmitter.emit('game.start', client);
}

@SubscribeMessage('movePaddle')
handleMovePaddleEvent(client: any, data: any) {
this.server.to(data.channel).emit('movePaddle', data);
}

@OnEvent('game.launched')
handleGameLaunchedEvent(clients: any) {
const game_channel = `Game:${clients[0].id}:${clients[1].id}`;
clients.forEach((client: any) => {
client.join(game_channel);
});
this.server.to(game_channel).emit('game.launched', game_channel);
}
}
7 changes: 4 additions & 3 deletions backend/code/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ async function bootstrap() {
const corsOptions = {
origin: [
'http://localhost:3000',
'http://142.93.161.63/',
'http://164.92.243.105/',
'http://142.93.161.63',
'http://164.92.243.105',
],
credentials: true,
};
Expand All @@ -41,9 +41,10 @@ async function bootstrap() {
.setDescription('The Transcendence API description')
.setVersion('1.0')
.addTag('Auth')
.addTag('friends')
.addTag('profile')
.addTag('friends')
.addTag('rooms')
.addTag('Messages')
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('api', app, document);
Expand Down
7 changes: 7 additions & 0 deletions backend/code/src/messages/dto/message-format.dto.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { ApiProperty } from '@nestjs/swagger';
import { Message } from '@prisma/client';

export class MessageFormatDto {
Expand All @@ -8,9 +9,15 @@ export class MessageFormatDto {
this.roomId = messageData.roomId;
this.authorId = messageData.authorId;
}

@ApiProperty({ example: 'clnx16e7a00003b6moh6yipir' })
id: string;
@ApiProperty({ example: 'Hello World' })
content: string;
@ApiProperty({ example: '2021-08-16T14:00:00.000Z' })
time: Date;
@ApiProperty({ example: 'clnx17wal00003b6leivni4oe' })
roomId: string;
@ApiProperty({ example: 'clnx18i8x00003b6lrp84ufb3' })
authorId: string;
}
Loading

0 comments on commit 9fee980

Please sign in to comment.