Skip to content
This repository has been archived by the owner on Apr 2, 2024. It is now read-only.

Commit

Permalink
Delete dropy & Unblock user
Browse files Browse the repository at this point in the history
  • Loading branch information
celian-rib committed Aug 24, 2022
1 parent bae36df commit aab5f2e
Show file tree
Hide file tree
Showing 9 changed files with 155 additions and 12 deletions.
22 changes: 22 additions & 0 deletions src/controllers/dropy.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,25 @@ export async function getDropy(req: AuthenticatedRequest, res: Response, next: N
next(error);
}
}

export async function userEmittedDropies(req: AuthenticatedRequest, res: Response, next: NextFunction): Promise<void> {
try {
const drops = await dropyService.userEmittedDropies(req.user);
res.status(200).json(drops);
} catch (error) {
next(error);
}
}

export async function deleteDropy(req: AuthenticatedRequest, res: Response, next: NextFunction): Promise<void> {
try {
const dropyId = Number(req.params.id);
utils.throwIfNotNumber(dropyId);

await dropyService.deleteDropy(dropyId, req.user);

res.status(200).json(`Dropy with id ${dropyId} deleted`);
} catch (error) {
next(error);
}
}
30 changes: 30 additions & 0 deletions src/controllers/users.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import * as userService from '@services/users.service';
import * as utils from '@/utils/controller.utils';
import { User } from '@prisma/client';
import { UploadedFile } from 'express-fileupload';
import { HttpException } from '@/exceptions/HttpException';

export async function updateDeviceToken(req: AuthenticatedRequest, res: Response, next: NextFunction): Promise<void> {
try {
Expand Down Expand Up @@ -113,6 +114,10 @@ export async function reportUser(req: AuthenticatedRequest, res: Response, next:
utils.throwIfNotNumber(dropyId);
}

if (parseInt(userId) === req.user.id) {
throw new HttpException(301, 'You cannot report yourself');
}

await userService.reportUser(parseInt(userId), req.user, dropyId);
res.status(200).json('User reported');
} catch (error) {
Expand All @@ -125,9 +130,34 @@ export async function blockUser(req: AuthenticatedRequest, res: Response, next:
const { userId } = req.params;
utils.throwIfNotNumber(userId);

if (parseInt(userId) === req.user.id) {
throw new HttpException(301, 'You cannot report block');
}

await userService.blockUser(parseInt(userId), req.user);
res.status(200).json('User blocked');
} catch (error) {
next(error);
}
}

export async function getBlockedUsers(req: AuthenticatedRequest, res: Response, next: NextFunction): Promise<void> {
try {
const blockedUsers = await userService.getBlockedUsers(req.user);
res.status(200).json(blockedUsers);
} catch (error) {
next(error);
}
}

export async function unblockUser(req: AuthenticatedRequest, res: Response, next: NextFunction): Promise<void> {
try {
const { userId } = req.params;
utils.throwIfNotNumber(userId);

await userService.unblockUser(parseInt(userId), req.user);
res.status(200).json('User unblocked');
} catch (error) {
next(error);
}
}
11 changes: 3 additions & 8 deletions src/interfaces/chat.interface.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import { DropyAround } from './dropy.interface';
import { SimplifiedUser } from './user.interface';

export interface UserConversation {
id: number;
user: {
displayName: string;
userId: number;
};
user: SimplifiedUser;
lastMessagePreview: string | null;
lastMessageDate: Date | null;
isOnline: boolean;
Expand All @@ -17,8 +15,5 @@ export interface UserMessage {
date: Date;
content: string | DropyAround;
read: boolean;
sender: {
displayName: string;
id: number;
};
sender: SimplifiedUser;
}
2 changes: 2 additions & 0 deletions src/interfaces/user.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,5 @@ export type Profile = Pick<
};

export type UpdatableProfileInfos = Pick<User, 'about' | 'pronouns' | 'displayName'>;

export type SimplifiedUser = Pick<User, 'id' | 'username' | 'displayName'>;
3 changes: 3 additions & 0 deletions src/routes/dropy.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ const path = '/dropy';
export function getRouter() {
const router = Router();

router.get(`${path}/userEmitted`, authMiddleware as any, dropyController.userEmittedDropies, errorMiddleware);
router.delete(`${path}/:id`, authMiddleware as any, dropyController.deleteDropy, errorMiddleware);

router.post(`${path}/add/:id/media`, authMiddleware as any, dropyController.createDropyMedia, errorMiddleware);
router.get(`${path}/:id/media`, authMiddleware as any, dropyController.getDropyMedia, errorMiddleware);
router.get(`${path}/:id`, authMiddleware as any, dropyController.getDropy, errorMiddleware);
Expand Down
2 changes: 2 additions & 0 deletions src/routes/users.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ export function getRouter() {

router.post(`${path}/report/:userId`, authMiddleware as any, usersController.reportUser, errorMiddleware);
router.post(`${path}/block/:userId`, authMiddleware as any, usersController.blockUser, errorMiddleware);
router.get(`${path}/blocked`, authMiddleware as any, usersController.getBlockedUsers, errorMiddleware);
router.post(`${path}/unblock/:userId`, authMiddleware as any, usersController.unblockUser, errorMiddleware);

return router;
}
31 changes: 28 additions & 3 deletions src/services/chat.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export async function getAllMessages(conversationId: number): Promise<UserMessag
read: message.read,
id: message.id,
sender: {
username: message.sender.username,
displayName: message.sender.displayName,
id: message.sender.id,
},
Expand All @@ -28,6 +29,17 @@ export async function getMessages(conversationId: number, offset: number, limit:
const chatMessages = await client.chatMessage.findMany({
where: {
conversationId: conversationId,
OR: [
{
AND: [{ NOT: { dropyId: null } }, { NOT: { content: null } }],
},
{
AND: [{ dropyId: null }, { NOT: { content: null } }],
},
{
AND: [{ NOT: { dropyId: null } }, { content: null }],
},
],
},
orderBy: {
date: 'desc',
Expand All @@ -43,6 +55,7 @@ export async function getMessages(conversationId: number, offset: number, limit:
read: message.read,
id: message.id,
sender: {
username: message.sender.username,
displayName: message.sender.displayName,
id: message.sender.id,
},
Expand All @@ -57,6 +70,11 @@ export async function closeConversation(conversationId: number): Promise<void> {
}

export async function addMessage(user: User, connectedUsers: User[], content: string, conversationId: number): Promise<UserMessage> {
const userWithBlockedUsers = await client.user.findUnique({
where: { id: user.id },
include: { blockedUsers: true },
});

const message = await client.chatMessage.create({
data: {
conversationId: conversationId,
Expand All @@ -74,15 +92,20 @@ export async function addMessage(user: User, connectedUsers: User[], content: st
return !connectedUsers.some(connectedUser => connectedUser.id === user.id);
});

const filteredDisconnectedUsers = disconnectedUsers.filter(userToFilter => {
return userWithBlockedUsers.blockedUsers.some(blockedUser => blockedUser.id === userToFilter.id);
});

sendPushNotification({
users: disconnectedUsers,
users: filteredDisconnectedUsers,
title: user.displayName,
body: decryptMessage(content),
sound: 'message_sound.mp3',
payload: {
id: conversation.id,
user: {
userId: user.id,
id: user.id,
username: user.username,
displayName: user.displayName,
},
} as UserConversation,
Expand All @@ -96,6 +119,7 @@ export async function addMessage(user: User, connectedUsers: User[], content: st
sender: {
displayName: user.displayName,
id: user.id,
username: user.username,
},
};
}
Expand Down Expand Up @@ -128,7 +152,8 @@ export async function getAllUserConversations(user: User): Promise<UserConversat
lastMessagePreview: lastMessage?.content ?? null,
lastMessageDate: lastMessage?.date ?? null,
user: {
userId: otherUser.id,
id: otherUser.id,
username: otherUser.username,
displayName: otherUser.displayName,
},
});
Expand Down
28 changes: 28 additions & 0 deletions src/services/dropy.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import client from '@/prisma/client';
import fs from 'fs';
import { HttpException } from '@/exceptions/HttpException';
import { DropyAround } from '@/interfaces/dropy.interface';
import { ChatConversation, Dropy, MediaType, User } from '@prisma/client';
Expand Down Expand Up @@ -195,3 +196,30 @@ const createOrUpdateChatConversation = async (dropy: Dropy): Promise<ChatConvers
return newConversation;
}
};

export async function userEmittedDropies(user: User): Promise<Dropy[]> {
const userDropies = await client.dropy.findMany({
where: { emitterId: user.id },
orderBy: { creationDate: 'desc' },
});

return userDropies;
}

export async function deleteDropy(dropyId: number, user: User): Promise<void> {
const dropy = await client.dropy.findUnique({ where: { id: dropyId } });

if (dropy == undefined) {
throw new HttpException(404, `Dropy with id ${dropyId} not found`);
}

if (user.id != dropy.emitterId) {
throw new HttpException(403, `You can't delete this dropy`);
}

if (dropy.mediaType === MediaType.PICTURE || dropy.mediaType === MediaType.VIDEO) {
fs.unlinkSync(dropy.filePath);
}

await client.dropy.delete({ where: { id: dropyId } });
}
38 changes: 37 additions & 1 deletion src/services/users.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import fs from 'fs';
import { sendPushNotification } from '../notification';
import client from '@/prisma/client';
import { getAvailableDropiesAroundLocation, getDistanceFromLatLonInMeters } from '@/utils/geolocation.utils';
import { Profile, UpdatableProfileInfos } from '@/interfaces/user.interface';
import { Profile, SimplifiedUser, UpdatableProfileInfos } from '@/interfaces/user.interface';
import { HttpException } from '@/exceptions/HttpException';
import { UploadedFile } from 'express-fileupload';

Expand Down Expand Up @@ -240,3 +240,39 @@ export async function blockUser(blockedId: number, sender: User): Promise<void>
data: { closed: true },
});
}

export async function getBlockedUsers(user: User): Promise<SimplifiedUser[]> {
const userWithBlockedUsers = await client.user.findUnique({
where: { id: user.id },
include: { blockedUsers: true },
});

const blockedProfiles = await userWithBlockedUsers.blockedUsers.map(blockedUser => {
return {
id: blockedUser.id,
username: blockedUser.username,
displayName: blockedUser.displayName,
};
});

return blockedProfiles;
}

export async function unblockUser(unblockedId: number, sender: User): Promise<void> {
const userToUnblock = await client.user.findUnique({ where: { id: unblockedId } });

if (userToUnblock == null) {
throw new HttpException(404, `User with id ${unblockedId} not found`);
}

await client.user.update({
where: { id: sender.id },
data: {
blockedUsers: {
disconnect: {
id: unblockedId,
},
},
},
});
}

0 comments on commit aab5f2e

Please sign in to comment.