summary refs log tree commit diff
path: root/api/src/routes/channels
diff options
context:
space:
mode:
authorAlTech98 <altech123159@gmail.com>2021-09-16 21:33:36 +0200
committerAlTech98 <altech123159@gmail.com>2021-09-16 21:33:36 +0200
commit4f87fd742f25a25782afb20131200bcff81b50f7 (patch)
tree9588f6319e6b21eb4415e796a690a57b6e7ecb50 /api/src/routes/channels
parentDummy sticker-packs routes (diff)
downloadserver-4f87fd742f25a25782afb20131200bcff81b50f7.tar.xz
Implemented DMs and group DMs
Diffstat (limited to 'api/src/routes/channels')
-rw-r--r--api/src/routes/channels/#channel_id/index.ts28
-rw-r--r--api/src/routes/channels/#channel_id/messages/#message_id/ack.ts2
-rw-r--r--api/src/routes/channels/#channel_id/messages/index.ts46
-rw-r--r--api/src/routes/channels/#channel_id/recipients.ts56
4 files changed, 113 insertions, 19 deletions
diff --git a/api/src/routes/channels/#channel_id/index.ts b/api/src/routes/channels/#channel_id/index.ts
index 02ac9884..e836622b 100644
--- a/api/src/routes/channels/#channel_id/index.ts
+++ b/api/src/routes/channels/#channel_id/index.ts
@@ -1,6 +1,7 @@
-import { ChannelDeleteEvent, Channel, ChannelUpdateEvent, emitEvent, ChannelType, ChannelPermissionOverwriteType } from "@fosscord/util";
-import { Router, Response, Request } from "express";
+import { Channel, ChannelDeleteEvent, ChannelPermissionOverwriteType, ChannelService, ChannelType, ChannelUpdateEvent, emitEvent, Recipient } from "@fosscord/util";
+import { Request, Response, Router } from "express";
 import { route } from "@fosscord/api";
+
 const router: Router = Router();
 // TODO: delete channel
 // TODO: Get channel
@@ -16,14 +17,27 @@ router.get("/", route({ permission: "VIEW_CHANNEL" }), async (req: Request, res:
 router.delete("/", route({ permission: "MANAGE_CHANNELS" }), async (req: Request, res: Response) => {
 	const { channel_id } = req.params;
 
-	const channel = await Channel.findOneOrFail({ id: channel_id });
+	const channel = await Channel.findOneOrFail({ where: { id: channel_id }, relations: ["recipients"] });
 
-	// TODO: Dm channel "close" not delete
-	const data = channel;
+	if (channel.type === ChannelType.DM) {
+		const recipient = await Recipient.findOneOrFail({ where: { channel_id: channel_id, user_id: req.user_id } })
+		recipient.closed = true
+		await Promise.all([
+			recipient.save(),
+			emitEvent({ event: "CHANNEL_DELETE", data: channel, user_id: req.user_id } as ChannelDeleteEvent)
+		]);
 
-	await Promise.all([emitEvent({ event: "CHANNEL_DELETE", data, channel_id } as ChannelDeleteEvent), Channel.delete({ id: channel_id })]);
+	} else if (channel.type === ChannelType.GROUP_DM) {
+		await ChannelService.removeRecipientFromChannel(channel, req.user_id)
+	} else {
+		//TODO messages in this channel should be deleted before deleting the channel
+		await Promise.all([
+			Channel.delete({ id: channel_id }),
+			emitEvent({ event: "CHANNEL_DELETE", data: channel, channel_id } as ChannelDeleteEvent)
+		]);
+	}
 
-	res.send(data);
+	res.send(channel);
 });
 
 export interface ChannelModifySchema {
diff --git a/api/src/routes/channels/#channel_id/messages/#message_id/ack.ts b/api/src/routes/channels/#channel_id/messages/#message_id/ack.ts
index 97d1d19e..786e4581 100644
--- a/api/src/routes/channels/#channel_id/messages/#message_id/ack.ts
+++ b/api/src/routes/channels/#channel_id/messages/#message_id/ack.ts
@@ -26,7 +26,7 @@ router.post("/", route({ body: "MessageAcknowledgeSchema" }), async (req: Reques
 		data: {
 			channel_id,
 			message_id,
-			version: 496
+			version: 3763
 		}
 	} as MessageAckEvent);
 
diff --git a/api/src/routes/channels/#channel_id/messages/index.ts b/api/src/routes/channels/#channel_id/messages/index.ts
index ec93649e..bb610a6a 100644
--- a/api/src/routes/channels/#channel_id/messages/index.ts
+++ b/api/src/routes/channels/#channel_id/messages/index.ts
@@ -1,9 +1,8 @@
 import { Router, Response, Request } from "express";
-import { Attachment, Channel, ChannelType, Embed, getPermission, Message } from "@fosscord/util";
+import { Attachment, Channel, ChannelType, DmChannelDTO, Embed, emitEvent, getPermission, Message, MessageCreateEvent } from "@fosscord/util";
 import { HTTPError } from "lambert-server";
-import { route } from "@fosscord/api";
+import { handleMessage, postHandleMessage, route } from "@fosscord/api";
 import multer from "multer";
-import { sendMessage } from "@fosscord/api";
 import { uploadFile } from "@fosscord/api";
 import { FindManyOptions, LessThan, MoreThan } from "typeorm";
 
@@ -62,9 +61,9 @@ router.get("/", async (req: Request, res: Response) => {
 	if (!channel) throw new HTTPError("Channel not found", 404);
 
 	isTextChannel(channel.type);
-	const around = `${req.query.around}`;
-	const before = `${req.query.before}`;
-	const after = `${req.query.after}`;
+	const around = req.query.around ? `${req.query.around}` : undefined;
+	const before = req.query.before ? `${req.query.before}` : undefined;
+	const after = req.query.after ? `${req.query.after}` : undefined;
 	const limit = Number(req.query.limit) || 50;
 	if (limit < 1 || limit > 100) throw new HTTPError("limit must be between 1 and 100");
 
@@ -151,10 +150,12 @@ router.post(
 				return res.status(400).json(error);
 			}
 		}
+		//TODO querying the DB at every message post should be avoided, caching maybe?
+		const channel = await Channel.findOneOrFail({ where: { id: channel_id }, relations: ["recipients", "recipients.user"] })
 
 		const embeds = [];
 		if (body.embed) embeds.push(body.embed);
-		const data = await sendMessage({
+		let message = await handleMessage({
 			...body,
 			type: 0,
 			pinned: false,
@@ -162,9 +163,36 @@ router.post(
 			embeds,
 			channel_id,
 			attachments,
-			edited_timestamp: undefined
+			edited_timestamp: undefined,
+			timestamp: new Date()
 		});
 
-		return res.json(data);
+		message = await message.save()
+
+		await channel.assign({ last_message_id: message.id }).save()
+
+		if (channel.isDm()) {
+			const channel_dto = await DmChannelDTO.from(channel)
+
+			for (let recipient of channel.recipients!) {
+				if (recipient.closed) {
+					await emitEvent({
+						event: "CHANNEL_CREATE",
+						data: channel_dto.excludedRecipients([recipient.user_id]),
+						user_id: recipient.user_id
+					})
+				}
+			}
+
+			await Promise.all(channel.recipients!.map(async r => {
+				r.closed = false;
+				return await r.save()
+			}));
+		}
+
+		await emitEvent({ event: "MESSAGE_CREATE", channel_id: channel_id, data: message } as MessageCreateEvent)
+		postHandleMessage(message).catch((e) => {}); // no await as it shouldnt block the message send function and silently catch error
+
+		return res.json(message);
 	}
 );
diff --git a/api/src/routes/channels/#channel_id/recipients.ts b/api/src/routes/channels/#channel_id/recipients.ts
index ea6bc563..d88b38f3 100644
--- a/api/src/routes/channels/#channel_id/recipients.ts
+++ b/api/src/routes/channels/#channel_id/recipients.ts
@@ -1,5 +1,57 @@
-import { Router, Response, Request } from "express";
+import { Request, Response, Router } from "express";
+import { Channel, ChannelRecipientAddEvent, ChannelService, ChannelType, DiscordApiErrors, DmChannelDTO, emitEvent, PublicUserProjection, Recipient, User } from "@fosscord/util";
+
 const router: Router = Router();
-// TODO:
+
+router.put("/:user_id", async (req: Request, res: Response) => {
+	const { channel_id, user_id } = req.params;
+	const channel = await Channel.findOneOrFail({ where: { id: channel_id }, relations: ["recipients"] });
+
+	if (channel.type !== ChannelType.GROUP_DM) {
+		const recipients = [
+			...channel.recipients!.map(r => r.user_id),
+			user_id
+		].unique()
+
+		const new_channel = await ChannelService.createDMChannel(recipients, req.user_id)
+		return res.status(201).json(new_channel);
+	} else {
+		if (channel.recipients!.map(r => r.user_id).includes(user_id)) {
+			throw DiscordApiErrors.INVALID_RECIPIENT //TODO is this the right error?
+		}
+
+		channel.recipients!.push(new Recipient({ channel_id: channel_id, user_id: user_id }));
+		await channel.save()
+
+		await emitEvent({
+			event: "CHANNEL_CREATE",
+			data: await DmChannelDTO.from(channel, [user_id]),
+			user_id: user_id
+		});
+
+		await emitEvent({
+			event: "CHANNEL_RECIPIENT_ADD", data: {
+				channel_id: channel_id,
+				user: await User.findOneOrFail({ where: { id: user_id }, select: PublicUserProjection })
+			}, channel_id: channel_id
+		} as ChannelRecipientAddEvent);
+		return res.sendStatus(204);
+	}
+});
+
+router.delete("/:user_id", async (req: Request, res: Response) => {
+	const { channel_id, user_id } = req.params;
+	const channel = await Channel.findOneOrFail({ where: { id: channel_id }, relations: ["recipients"] });
+	if (!(channel.type === ChannelType.GROUP_DM && (channel.owner_id === req.user_id || user_id === req.user_id)))
+		throw DiscordApiErrors.MISSING_PERMISSIONS
+
+	if (!channel.recipients!.map(r => r.user_id).includes(user_id)) {
+		throw DiscordApiErrors.INVALID_RECIPIENT //TODO is this the right error?
+	}
+
+	await ChannelService.removeRecipientFromChannel(channel, user_id)
+
+	return res.sendStatus(204);
+});
 
 export default router;