summary refs log tree commit diff
path: root/api/src/util
diff options
context:
space:
mode:
authorFlam3rboy <34555296+Flam3rboy@users.noreply.github.com>2021-08-31 18:10:36 +0200
committerGitHub <noreply@github.com>2021-08-31 18:10:36 +0200
commitef5df63501fa6ffee170150816878a14cd8a6cdc (patch)
tree1c9708b20b8e49d0cae48cba1030558dbbb07db8 /api/src/util
parentCreated list of all possible api errors and made them throwable in routes code (diff)
parentMerge branch 'typeorm' of https://github.com/fosscord/fosscord-api into typeorm (diff)
downloadserver-ef5df63501fa6ffee170150816878a14cd8a6cdc.tar.xz
Merge branch 'typeorm' into typeorm
Diffstat (limited to 'api/src/util')
-rw-r--r--api/src/util/Channel.ts52
-rw-r--r--api/src/util/Message.ts95
2 files changed, 64 insertions, 83 deletions
diff --git a/api/src/util/Channel.ts b/api/src/util/Channel.ts
deleted file mode 100644
index bc9217ce..00000000
--- a/api/src/util/Channel.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import { ChannelCreateEvent, Channel, ChannelType, emitEvent, getPermission, Snowflake } from "@fosscord/util";
-import { HTTPError } from "lambert-server";
-
-// TODO: DM channel
-export async function createChannel(
-	channel: Partial<Channel>,
-	user_id: string = "0",
-	opts?: {
-		keepId?: boolean;
-		skipExistsCheck?: boolean;
-	}
-) {
-	// Always check if user has permission first
-	const permissions = await getPermission(user_id, channel.guild_id);
-	permissions.hasThrow("MANAGE_CHANNELS");
-
-	switch (channel.type) {
-		case ChannelType.GUILD_TEXT:
-		case ChannelType.GUILD_VOICE:
-			if (channel.parent_id && !opts?.skipExistsCheck) {
-				const exists = await Channel.findOneOrFail({ id: channel.parent_id });
-				if (!exists) throw new HTTPError("Parent id channel doesn't exist", 400);
-				if (exists.guild_id !== channel.guild_id) throw new HTTPError("The category channel needs to be in the guild");
-			}
-			break;
-		case ChannelType.GUILD_CATEGORY:
-			break;
-		case ChannelType.DM:
-		case ChannelType.GROUP_DM:
-			throw new HTTPError("You can't create a dm channel in a guild");
-		// TODO: check if guild is community server
-		case ChannelType.GUILD_STORE:
-		case ChannelType.GUILD_NEWS:
-		default:
-			throw new HTTPError("Not yet supported");
-	}
-
-	if (!channel.permission_overwrites) channel.permission_overwrites = [];
-	// TODO: auto generate position
-
-	channel = await new Channel({
-		...channel,
-		...(!opts?.keepId && { id: Snowflake.generate() }),
-		created_at: new Date(),
-		// @ts-ignore
-		recipient_ids: null
-	}).save();
-
-	await emitEvent({ event: "CHANNEL_CREATE", data: channel, guild_id: channel.guild_id } as ChannelCreateEvent);
-
-	return channel;
-}
diff --git a/api/src/util/Message.ts b/api/src/util/Message.ts
index 70989301..fea553bc 100644
--- a/api/src/util/Message.ts
+++ b/api/src/util/Message.ts
@@ -13,11 +13,16 @@ import {
 	Role,
 	EVERYONE_MENTION,
 	HERE_MENTION,
-	MessageType
+	MessageType,
+	User,
+	Application,
+	Webhook,
+	Attachment
 } from "@fosscord/util";
 import { HTTPError } from "lambert-server";
 import fetch from "node-fetch";
 import cheerio from "cheerio";
+import { MessageCreateSchema } from "../schema/Message";
 
 // TODO: check webhook, application, system author
 
@@ -34,17 +39,37 @@ const DEFAULT_FETCH_OPTIONS: any = {
 	method: "GET"
 };
 
-export async function handleMessage(opts: Partial<Message>): Promise<Message> {
-	const channel = await Channel.findOneOrFail(
-		{ id: opts.channel_id },
-		{ select: ["guild_id", "type", "permission_overwrites", "recipient_ids", "owner_id"] }
-	); // lean is needed, because we don't want to populate .recipients that also auto deletes .recipient_ids
+export async function handleMessage(opts: MessageOptions): Promise<Message> {
+	const channel = await Channel.findOneOrFail({ where: { id: opts.channel_id }, relations: ["recipients"] });
 	if (!channel || !opts.channel_id) throw new HTTPError("Channel not found", 404);
+
+	const message = new Message({
+		...opts,
+		guild_id: channel.guild_id,
+		channel_id: opts.channel_id,
+		attachments: opts.attachments || [],
+		embeds: opts.embeds || [],
+		reactions: /*opts.reactions ||*/ [],
+		type: opts.type ?? 0
+	});
+
 	// TODO: are tts messages allowed in dm channels? should permission be checked?
+	if (opts.author_id) {
+		message.author = await User.getPublicUser(opts.author_id);
+	}
+	if (opts.application_id) {
+		message.application = await Application.findOneOrFail({ id: opts.application_id });
+	}
+	if (opts.webhook_id) {
+		message.webhook = await Webhook.findOneOrFail({ id: opts.webhook_id });
+	}
 
-	// @ts-ignore
-	const permission = await getPermission(opts.author_id, channel.guild_id, opts.channel_id, { channel });
+	const permission = await getPermission(opts.author_id, channel.guild_id, opts.channel_id);
 	permission.hasThrow("SEND_MESSAGES");
+	if (permission.cache.member) {
+		message.member = permission.cache.member;
+	}
+
 	if (opts.tts) permission.hasThrow("SEND_TTS_MESSAGES");
 	if (opts.message_reference) {
 		permission.hasThrow("READ_MESSAGE_HISTORY");
@@ -52,10 +77,11 @@ export async function handleMessage(opts: Partial<Message>): Promise<Message> {
 		if (opts.message_reference.channel_id !== opts.channel_id) throw new HTTPError("You can only reference messages from this channel");
 		// TODO: should be checked if the referenced message exists?
 		// @ts-ignore
-		opts.type = MessageType.REPLY;
+		message.type = MessageType.REPLY;
 	}
 
-	if (!opts.content && !opts.embeds?.length && !opts.attachments?.length && !opts.stickers?.length && !opts.activity) {
+	// TODO: stickers/activity
+	if (!opts.content && !opts.embeds?.length && !opts.attachments?.length) {
 		throw new HTTPError("Empty messages are not allowed", 50006);
 	}
 
@@ -64,10 +90,9 @@ export async function handleMessage(opts: Partial<Message>): Promise<Message> {
 	var mention_role_ids = [] as string[];
 	var mention_user_ids = [] as string[];
 	var mention_everyone = false;
-	var mention_everyone = false;
 
 	if (content) {
-		content = content.trim();
+		message.content = content.trim();
 		for (const [_, mention] of content.matchAll(CHANNEL_MENTION)) {
 			if (!mention_channel_ids.includes(mention)) mention_channel_ids.push(mention);
 		}
@@ -90,21 +115,14 @@ export async function handleMessage(opts: Partial<Message>): Promise<Message> {
 		}
 	}
 
+	message.mention_channels = mention_channel_ids.map((x) => new Channel({ id: x }));
+	message.mention_roles = mention_role_ids.map((x) => new Role({ id: x }));
+	message.mentions = mention_user_ids.map((x) => new User({ id: x }));
+	message.mention_everyone = mention_everyone;
+
 	// TODO: check and put it all in the body
 
-	return {
-		...opts,
-		guild_id: channel.guild_id,
-		channel_id: opts.channel_id,
-		mention_channel_ids,
-		mention_role_ids,
-		mention_user_ids,
-		mention_everyone,
-		attachments: opts.attachments || [],
-		embeds: opts.embeds || [],
-		reactions: opts.reactions || [],
-		type: opts.type ?? 0
-	} as Message;
+	return message;
 }
 
 // TODO: cache link result in db
@@ -160,14 +178,29 @@ export async function postHandleMessage(message: Message) {
 	]);
 }
 
-export async function sendMessage(opts: Partial<Message>) {
-	const message = await handleMessage({ ...opts, id: Snowflake.generate(), timestamp: new Date() });
+export async function sendMessage(opts: MessageOptions) {
+	const message = await handleMessage({ ...opts, timestamp: new Date() });
 
-	const data = await new Message(message).save();
+	await Promise.all([
+		message.save(),
+		emitEvent({ event: "MESSAGE_CREATE", channel_id: opts.channel_id, data: message.toJSON() } as MessageCreateEvent)
+	]);
 
-	await emitEvent({ event: "MESSAGE_CREATE", channel_id: opts.channel_id, data } as MessageCreateEvent);
+	postHandleMessage(message).catch((e) => {}); // no await as it shouldnt block the message send function and silently catch error
 
-	postHandleMessage(data).catch((e) => {}); // no await as it shouldnt block the message send function and silently catch error
+	return message;
+}
 
-	return data;
+interface MessageOptions extends MessageCreateSchema {
+	id?: string;
+	type?: MessageType;
+	pinned?: boolean;
+	author_id?: string;
+	webhook_id?: string;
+	application_id?: string;
+	embeds?: Embed[];
+	channel_id?: string;
+	attachments?: Attachment[];
+	edited_timestamp?: Date;
+	timestamp?: Date;
 }