Merge branch 'master' of bitbucket.org:LuckyLaszlo/ft_transcendence

This commit is contained in:
simplonco
2023-01-16 09:19:13 +01:00
11 changed files with 212 additions and 306 deletions

View File

@@ -15,14 +15,13 @@ export class FriendshipController {
@UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard)
findOne(@Query('username') otherUsername: string, @Req() req) {
console.log('GET myfriends')
// console.log('GET myfriends')
const user = req.user;
if (otherUsername !== undefined) {
console.log('my friend: ' + otherUsername)
// console.log('my friend: ' + otherUsername)
return this.friendshipService.findOneRelationshipByUsername(otherUsername, user.username);
}
return this.friendshipService.findAllFriendships(user.id);
// return this.friendshipService.findAllFriends(user.id);
}
// POST http://transcendance:8080/api/v2/network/relations
@@ -31,10 +30,10 @@ export class FriendshipController {
@UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard)
create(@Body() createFriendshipDto: CreateFriendshipDto, @Req() req) {
console.log('friendship.service create')
// console.log('friendship.service create')
const user = req.user;
if (user.username !== createFriendshipDto.receiverUsername) {
console.log('friendship.service create have a receiver name')
// console.log('friendship.service create have a receiver name')
return this.friendshipService.create(createFriendshipDto, user);
}
return new HttpException('You can\'t request a frienship to yourself', HttpStatus.BAD_REQUEST);
@@ -73,7 +72,7 @@ export class FriendshipController {
@UseGuards(TwoFactorGuard)
remove(@Param('relationshipId') relationshipId: number, @Req() req) {
const user : User = req.user;
console.log('deleting a friendship')
// console.log('deleting a friendship')
return this.friendshipService.removeFriendship(relationshipId, user);
}
@@ -100,21 +99,13 @@ export class FriendshipController {
@UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard)
findBlocked(@Query('relationshipId') relationshipId: number, @Req() req) {
console.log('friendship.controller fetching blocked users')
console.log(relationshipId)
// console.log('friendship.controller fetching blocked users')
// console.log(relationshipId)
const user = req.user;
// if (relationshipId === undefined)
if (Number.isNaN(relationshipId))
return this.friendshipService.findAllBlockedFriends(user.id);
else
return this.friendshipService.findOneBlocked(relationshipId, user.id);
}
// @Get('blocked/:relationshipId')
// @UseGuards(AuthenticateGuard)
// @UseGuards(TwoFactorGuard)
// findOneBlocked(@Param('relationshipId') relationshipId: string, @Req() req) {
// const user = req.user;
// return this.friendshipService.findOneBlocked(relationshipId, user.username);
// }
}

View File

@@ -1,7 +1,9 @@
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from 'src/users/entities/user.entity';
import { SendableUser } from 'src/users/sendableUsers';
import { Repository, Brackets } from 'typeorm';
import { CreateFriendshipDto } from './dto/create-friendship.dto';
import { Friendship, FriendshipStatus } from './entities/friendship.entity';
@@ -17,20 +19,6 @@ export class FriendshipService {
private readonly userRepository: Repository<User>,
) { }
// createSendableFriendship(friendship: Friendship): SendableFriendship {
// let ret = new SendableFriendship;
// ret.id = friendship.id;
// ret.date = friendship.date
// ret.senderUsername = friendship.sender.username;
// ret.senderId = friendship.sender.id;
// ret.receiverUsername = friendship.receiver.username;
// ret.receiverId = friendship.receiver.id;
// ret.status = friendship.status;
// return ret;
// };
//kinda useless but someone else might use it
async findOneRelationshipById(friendId : number, userId : number) {
const friendship = await this.friendshipRepository
@@ -49,6 +37,7 @@ export class FriendshipService {
new Brackets((subBQb) => {
subBQb.where('sender.id = :friendId2', {friendId2 : friendId})
.andWhere('receiver.id = :userId2', {userId2 : userId})
.andWhere('friendship.status != :status', {status : FriendshipStatus.BLOCKED})
})
)
}),
@@ -56,14 +45,12 @@ export class FriendshipService {
// .andWhere('friendship.status != :status', {status : FriendshipStatus.BLOCKED})
.getOne()
console.log('END Find one friend by ID: ')
console.log({...friendship})
// console.log('END Find one friend by ID: ')
// console.log({...friendship})
if (!friendship) {
throw new HttpException(`There is no such friendship`, HttpStatus.NOT_FOUND);
}
// return friendship;
// return this.createSendableFriendship(friendship);
return new SendableFriendship(friendship);
}
@@ -85,6 +72,7 @@ export class FriendshipService {
new Brackets((subBQb) => {
subBQb.where('sender.username = :friendUsername2', {friendUsername2 : friendUsername})
.andWhere('receiver.username = :username2', {username2 : username})
.andWhere('friendship.status != :status', {status : FriendshipStatus.BLOCKED})
})
)
}),
@@ -92,18 +80,15 @@ export class FriendshipService {
// .andWhere('friendship.status != :status', {status : FriendshipStatus.BLOCKED})
.getOne()
console.log('END Find one friend by username: ')
console.log({...friendship})
// console.log('END Find one friend by username: ')
// console.log({...friendship})
if (!friendship) {
throw new HttpException(`There is no such friendship`, HttpStatus.NOT_FOUND);
}
// return friendship;
return new SendableFriendship(friendship);
}
// maybe i should be returning a list of users not a list of friendships
// async findAllFriends(userId: number) {
async findAllFriendships(userId: number) {
const friendships = await this.friendshipRepository
.createQueryBuilder('friendship')
@@ -114,35 +99,17 @@ export class FriendshipService {
.orWhere('sender.id = :requester', { requester: userId })
.andWhere('friendship.status = :status', { status: FriendshipStatus.ACCEPTED })
.getMany();
// for (const friend of friendship)
// console.log("FRIENDSHIP : " + friend.status);
// return friendship;
let sendFrienships: SendableFriendship[] = [];
for (const friendship of friendships) {
sendFrienships.push(new SendableFriendship(friendship));
}
// return new SendableFriendship(friendship);
console.log('friendship.service my friends:')
console.log({...sendFrienships})
// console.log('friendship.service my friends:')
// console.log({...sendFrienships})
return sendFrienships;
// let sendFriends: SendableUser[] = [];
// for (const friendship of friendships) {
// let user: User;
// if (friendship.sender.id !== userId)
// user = friendship.sender;
// else
// user = friendship.receiver;
// sendFriends.push(new SendableUser(user));
// }
// console.log('friendship.service my friends as Users:')
// console.log({...sendFriends})
// return sendFriends;
}
async findOneBlocked(friendshipId: number, userId: number) {
// const friendship = await this.friendshipRepository.findOneBy({ id: friendshipId, sender.id: userId, status: FriendshipStatus.BLOCKED });
const friendship = await this.friendshipRepository
.createQueryBuilder('friendship')
.leftJoinAndSelect('friendship.sender', 'sender')
@@ -153,11 +120,9 @@ export class FriendshipService {
.getOne();
if (!friendship)
throw new HttpException(`The requested blocked not found.`, HttpStatus.NOT_FOUND);
// return friendship;
return new SendableFriendship(friendship);
}
async findOneBlockedByUsername(blockedUsername : string, userId : number) {
const friendship = await this.friendshipRepository
.createQueryBuilder('friendship')
@@ -181,21 +146,20 @@ export class FriendshipService {
.where('sender.id = :requestee', { requestee: userId })
.andWhere('friendship.status = :status', { status: FriendshipStatus.BLOCKED })
.getMany();
// let partialFriendship : Partial<Friendship>[] = [];
// for (const friendship of friendships) {
// partialFriendship.push({id: friendship.id, date: friendship.date, senderUsername: friendship.senderUsername, receiverUsername: friendship.receiverUsername, status: friendship.status});
// }
console.log('friendship.service findAllBlockedFriends, friendships:')
console.log({...friendships})
console.log('friendship.service findAllBlockedFriends, partial friendship:')
// console.log({...partialFriendship})
// console.log('friendship.service findAllBlockedFriends, friendships:')
// console.log({...friendships})
// console.log('friendship.service findAllBlockedFriends, partial friendship:')
// return partialFriendship;
// return friendships;
let sendFrienships: SendableFriendship[] = []
for (const friendship of friendships) {
sendFrienships.push(new SendableFriendship(friendship));
}
// return new SendableFriendship(friendship);
return sendFrienships;
}
@@ -208,8 +172,8 @@ export class FriendshipService {
.andWhere('friendship.status = :status', { status: FriendshipStatus.REQUESTED })
.getMany();
console.log('friendships services pendant friendships:')
console.log({...friendships})
// console.log('friendships services pendant friendships:')
// console.log({...friendships})
let sendFrienships: SendableFriendship[] = []
for (const friendship of friendships) {
@@ -227,8 +191,8 @@ export class FriendshipService {
.andWhere('friendship.status = :status', { status: FriendshipStatus.REQUESTED })
.getMany();
console.log('friendship service received requests')
console.log({...friendships})
// console.log('friendship service received requests')
// console.log({...friendships})
let sendFrienships: SendableFriendship[] = []
for (const friendship of friendships) {
@@ -237,22 +201,16 @@ export class FriendshipService {
return sendFrienships;
}
// this is no longer the right return
// async create(createFriendshipDto: CreateFriendshipDto, creator : User) : Promise <Partial<Friendship>> {
async create(createFriendshipDto: CreateFriendshipDto, creator : User) {
console.log("DTO : \n")
console.log({...createFriendshipDto})
// console.log("DTO : \n")
// console.log({...createFriendshipDto})
// These throws don't seem to work...
const receiver = await this.userRepository.findOneBy({username: createFriendshipDto.receiverUsername});
// console.log('receiver: ')
// console.log({...receiver})
if (!receiver)
throw new HttpException(`The addressee does not exist.`, HttpStatus.NOT_FOUND);
if (createFriendshipDto.status !== FriendshipStatus.REQUESTED && createFriendshipDto.status !== FriendshipStatus.BLOCKED)
throw new HttpException(`The status is not valid.`, HttpStatus.NOT_FOUND);
// const friendship = await this.friendshipRepository.findOneBy({ sender: creator, receiver: receiver });
const friendship = await this.friendshipRepository
.createQueryBuilder('friendship')
@@ -260,54 +218,45 @@ export class FriendshipService {
.leftJoinAndSelect('friendship.receiver', 'receiver')
.where('sender.id = :senderId', {senderId: creator.id})
.andWhere('receiver.id = :receiverId', {receiverId: receiver.id})
.orWhere('sender.id = :senderId2', {senderId2: receiver.id})
.andWhere('receiver.id = :receiverId2', {receiverId2: creator.id})
.getOne();
console.log('friendship.service create, friendship: \n\n\n')
// console.log('friendship.service create, friendship: \n\n\n')
// console.log({...friendship})
if (friendship) {
console.log('there is already a friend request')
// console.log('there is already a friend request')
if (friendship.status && friendship.status === FriendshipStatus.ACCEPTED)
throw new HttpException(`The friendship request has already been accepted.`, HttpStatus.OK);
else if (friendship.status && friendship.status === FriendshipStatus.REQUESTED)
throw new HttpException(`The friendship request has already been sent the ${friendship.date}.`, HttpStatus.OK);
else if (friendship.status && friendship.status === FriendshipStatus.BLOCKED)
else if (friendship.status && friendship.status === FriendshipStatus.REQUESTED) {
if (friendship && friendship.sender && friendship.sender.id === creator.id) {
throw new HttpException(`The friendship request has already been sent the ${friendship.date}.`, HttpStatus.OK);
} else {
// console.log('the friend request is being updated to Accepted')
friendship.status = FriendshipStatus.ACCEPTED;
const saveAFriendship = await this.friendshipRepository.save(friendship);
return new SendableFriendship(saveAFriendship);
}
} else if (friendship.status && friendship.status === FriendshipStatus.BLOCKED)
throw new HttpException(`We can't do that`, HttpStatus.OK);
else if (friendship.status && friendship.status === FriendshipStatus.DECLINED)
throw new HttpException(`The request has been declined.`, HttpStatus.OK);
}
console.log('friendship.service create, we are still saving a new friendship')
// console.log('friendship.service create, we are still saving a new friendship')
const newFriendship = new Friendship();
newFriendship.sender = creator;
// newFriendship.senderUsername = creator.username;
// newFriendship.senderId = creator.id;
newFriendship.receiver = receiver;
// newFriendship.receiverUsername = receiver.username;
// newFriendship.receiverId = receiver.id;
newFriendship.status = createFriendshipDto.status;
const savedFriendship = await this.friendshipRepository.save(newFriendship);
// const partialFriendship : Partial<Friendship> = {
// id : (await savedFriendship).id,
// date : (await savedFriendship).date,
// receiverUsername: (await savedFriendship).receiverUsername,
// receiverId: (await savedFriendship).receiverId,
// status : (await savedFriendship).status
// }
// console.log('friendship.service create friendship, partial friendship')
// console.log({...partialFriendship})
// console.log('friendship.service create friendship, NEW friendship')
// console.log({...newFriendship})
// console.log('friendship.service create friendship, SAVED friendship')
// console.log({...savedFriendship})
// return partialFriendship;
return new SendableFriendship(savedFriendship);
}
async acceptFriendship(relationshipId: number, user: User) {
// const relation = await this.friendshipRepository.findOneBy({id: relationshipId });
const relation = await this.friendshipRepository
.createQueryBuilder('friendship')
.leftJoinAndSelect('friendship.sender', 'sender')
@@ -315,8 +264,9 @@ export class FriendshipService {
.where('friendship.id = :friendshipId', { friendshipId: relationshipId })
.getOne();
console.log('.service accept friendship')
console.log({...relation})
// console.log('.service accept friendship')
// console.log({...relation})
if (!relation)
throw new HttpException(`The requested relationship not found.`, HttpStatus.NOT_FOUND);
if (relation.sender.id === user.id) {
@@ -324,17 +274,6 @@ export class FriendshipService {
}
relation.status = FriendshipStatus.ACCEPTED;
const savedFriendship = await this.friendshipRepository.save(relation);
// const partialFriendship : Partial<Friendship> = {
// id : (await savedFriendship).id,
// date : (await savedFriendship).date,
// receiverUsername: (await savedFriendship).receiverUsername,
// receiverId: (await savedFriendship).receiverId,
// status : (await savedFriendship).status
// }
// console.log('.service accept friendship END')
// console.log({...partialFriendship})
// return partialFriendship;
return new SendableFriendship(savedFriendship);
}
@@ -355,45 +294,28 @@ export class FriendshipService {
return new SendableFriendship(savedFriendship);
}
// Ok i decided you can't block someone who has already blocked you (cuz then you could unblock them and then they're blocking you would no longer apply, in a way negating their blocking of you.
async blockFriendship(relationshipId: number, user: User) {
const relation = await this.friendshipRepository
.createQueryBuilder('friendship')
.leftJoinAndSelect('friendship.sender', 'sender')
.leftJoinAndSelect('friendship.receiver', 'receiver')
.where('friendship.id = :friendshipId', { friendshipId: relationshipId })
.andWhere('friendship.status != :friendshipStatus', { friendshipStatus: FriendshipStatus.BLOCKED })
.getOne();
if (!relation)
throw new HttpException(`The requested relationship not found.`, HttpStatus.NOT_FOUND);
// do i need to check if they've already been blocked?
if (relation.receiver.id === user.id) {
// throw new HttpException(`You can't block yourself.`, HttpStatus.NOT_FOUND);
console.log('friendship.service blockFriendship trying to delete and recreate a friendship with block')
console.log({...relation})
// const newFriendshipDto = new CreateFriendshipDto(relation[0].receiver, FriendshipStatus.BLOCKED)
// const newFriendshipDto = new CreateFriendshipDto({"receiverUsername": relation[0].receiver, "status": "R"})
// we create a new one where you are the sender
// in the case where you RECEIVED the friendship but now want to block that person
if (relation.receiver && relation.receiver.id === user.id) {
// console.log('friendship.service blockFriendship trying to delete and recreate a friendship with block')
// console.log({...relation})
const newFriendshipDto = {"receiverUsername": relation.sender.username, "receiverId": relation.sender.id, "status": FriendshipStatus.BLOCKED};
// can't do it this way cuz READONLY
// const newFriendshipDto = new CreateFriendshipDto();
// newFriendshipDto.receiverUsername = relation[0].sender.username;
// newFriendshipDto.status = FriendshipStatus.BLOCKED;
// we delete that relation
await this.removeFriendship(relationshipId, user);
// we set it to blocked like we do below...
return await this.create(newFriendshipDto, user);
} else {
relation.status = FriendshipStatus.BLOCKED;
const savedFriendship = await this.friendshipRepository.save(relation);
// const partialFriendship : Partial<Friendship> = {
// id : (await savedFriendship).id,
// date : (await savedFriendship).date,
// receiverUsername: (await savedFriendship).receiverUsername,
// receiverId: (await savedFriendship).receiverId,
// status : (await savedFriendship).status
// }
// return partialFriendship
return new SendableFriendship(savedFriendship);
}
}
@@ -405,25 +327,21 @@ export class FriendshipService {
.leftJoinAndSelect('friendship.receiver', 'receiver')
.where('friendship.id = :friendshipId', { friendshipId: relationshipId })
.getOne();
console.log('deleting a friendship .service')
console.log({...friendship})
console.log('who is the user')
console.log({...user})
if (!friendship)
throw new HttpException(`Your friend could not be deleted.`, HttpStatus.NOT_FOUND);
if (friendship.sender.id !== user.id && friendship.receiver.id !== user.id) {
throw new HttpException(`You can't do that.`, HttpStatus.FORBIDDEN);
}
console.log('.service deleted a friendship')
}
// console.log('.service deleted a friendship')
return this.friendshipRepository.remove(friendship);
// what is the return here? am i getting something right?
}
// ok for some reason this isn't working...
async findIfUserIsBlockedOrHasBlocked(userConnectedId: number, userToFindId: number) {
console.log("finding if user is blocked")
console.log('user connected: ' + userConnectedId)
console.log('user to find: ' + userToFindId)
// console.log("finding if user is blocked")
// console.log('user connected: ' + userConnectedId)
// console.log('user to find: ' + userToFindId)
const friendship = await this.friendshipRepository
.createQueryBuilder('friendship')
@@ -449,13 +367,16 @@ export class FriendshipService {
.getOne()
console.log('printing friendship queried')
console.log({...friendship})
// console.log('printing friendship queried')
// console.log({...friendship})
if (friendship) {
console.log('we are blocked in friendship.service')
return true;
}
console.log('we are not blocked in friendship service')
// console.log('we are not blocked in friendship service')
return false;
}
}

View File

@@ -37,24 +37,7 @@ export class UsersController {
* car un utilisateur est crée à la première connexion avec l'Oauth de 42.
*/
// actually fucking useless now...
// similar to @Get('myfriends/:friendUsername') but doesn't return a friendship just returns the user profile
// GET http://transcendance:8080/user?username=NomDuUser
// @UseGuards(AuthenticateGuard)
// @UseGuards(TwoFactorGuard)
// @Get()
// findOne(@Query('id') toFindId: number, @Req() req) {
// if (toFindId === undefined) {
// console.log("Backend Getting current user");
// return this.usersService.findOne(req.user.id);
// } else {
// const user : User = req.user;
// console.log('we have a query: ' + toFindId)
// return this.usersService.findOneById(user.id, toFindId);
// }
// }
// GET http://transcendance:8080/user
@UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard)
@Get()
@@ -69,16 +52,6 @@ export class UsersController {
return this.usersService.findOne(usernameToFind);
}
// also seems useless...
// GET http://transcendance:8080/user/stats
// @UseGuards(AuthenticateGuard)
// @UseGuards(TwoFactorGuard)
// @Get('stats')
// getStats(@Req() request) {
// return this.usersService.getStats(request.user.id);
// }
// PATCH http://transcendance:8080/user
@UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard)

View File

@@ -22,23 +22,25 @@ export class UsersService {
const user = await this.userRepository.findOneBy({fortyTwoId: fortytwo_id});
if (!user)
{
console.log(`The requested user not found.`);
// console.log(`The requested user not found.`);
return null;
}
console.log(`The requested user found.`);
// console.log(`The requested user found.`);
return user;
}
async findOne(username: string) {
console.log(`FIND ONE USER SERVICE Find user ${username}`);
// console.log(`FIND ONE USER SERVICE Find user ${username}`);
const user = await this.userRepository.createQueryBuilder('user')
.leftJoinAndSelect('user.stats', 'stats')
.where('user.username = :username', { username: username })
.getOne();
if (!user)
throw new NotFoundException(`The requested user not found.`);
console.log(`FIND ONE USER SERVICE The requested user found. ` + user.username + " "
+ user.stats.id + user.stats.winGame + user.stats.loseGame + user.stats.drawGame + user.stats.totalGame);
// console.log(`FIND ONE USER SERVICE The requested user found. ` + user.username + " " + user.stats.id + user.stats.winGame + user.stats.loseGame + user.stats.drawGame + user.stats.totalGame);
const partialUser : Partial<User> = {
username: user.username,
image_url: user.image_url,
@@ -46,21 +48,25 @@ export class UsersService {
status: user.status,
stats: user.stats,
};
console.log(`Returned Partial User.` + partialUser.username + user.username);
// console.log(`Returned Partial User.` + partialUser.username + user.username);
return partialUser;
}
async isUsernameExists(usernameToSearch: string): Promise<boolean> {
console.log('searching for username: ' + usernameToSearch)
// console.log('searching for username: ' + usernameToSearch)
const user = await this.userRepository.findOneBy({username : usernameToSearch});
console.log({...user})
// console.log({...user})
if (!user)
return false;
return true;
}
async findAll(currentUser: User) {
// const otherUsers = await this.userRepository.find({where: {id: Not(+currentUser.id)}, order: {username: "ASC"}, skip: offset, take: limit,});
const otherUsers = await this.userRepository.find({where: {id: Not(+currentUser.id)}, order: {username: "ASC"}});
let partialUsers : Partial<User>[] = [];
@@ -76,8 +82,10 @@ export class UsersService {
partialUsers.push({username: otherUser.username, image_url: otherUser.image_url, status: otherUser.status, stats: otherUser.stats});
}
}
console.log('user.services findAll, partialUsers:')
console.log({...partialUsers})
// console.log('user.services findAll, partialUsers:')
// console.log({...partialUsers})
return partialUsers;
}
@@ -97,7 +105,7 @@ export class UsersService {
// console.log(`Update user ${id} with ${updateUserDto.isEnabledTwoFactorAuth}`);
// console.log({...updateUserDto})
if (await this.isUsernameExists(updateUserDto.username) === true) {
console.log('updating username ' + updateUserDto.username + ' but it already is in use')
// console.log('updating username ' + updateUserDto.username + ' but it already is in use')
throw new HttpException(`The username is already in use.`,HttpStatus.CONFLICT);
}
const user = await this.userRepository.preload(
@@ -140,7 +148,6 @@ export class UsersService {
}
// doing search with username not id because userService.findOne doesn't return an Id anymore, just username... fuck this architecture is big trash...
// async getAvatarUrl(id: number) {
async getAvatarUrl(username: string) {
const user = await this.userRepository.findOneBy({username: username});
if (!user)