summary refs log tree commit diff
path: root/src/api/routes/channels/#channel_id/messages
diff options
context:
space:
mode:
Diffstat (limited to 'src/api/routes/channels/#channel_id/messages')
-rw-r--r--src/api/routes/channels/#channel_id/messages/#message_id/ack.ts33
-rw-r--r--src/api/routes/channels/#channel_id/messages/#message_id/crosspost.ts28
-rw-r--r--src/api/routes/channels/#channel_id/messages/#message_id/index.ts199
-rw-r--r--src/api/routes/channels/#channel_id/messages/#message_id/reactions.ts185
-rw-r--r--src/api/routes/channels/#channel_id/messages/bulk-delete.ts43
-rw-r--r--src/api/routes/channels/#channel_id/messages/index.ts241
6 files changed, 729 insertions, 0 deletions
diff --git a/src/api/routes/channels/#channel_id/messages/#message_id/ack.ts b/src/api/routes/channels/#channel_id/messages/#message_id/ack.ts
new file mode 100644
index 00000000..041f4d5e
--- /dev/null
+++ b/src/api/routes/channels/#channel_id/messages/#message_id/ack.ts
@@ -0,0 +1,33 @@
+import { emitEvent, getPermission, MessageAckEvent, ReadState, Snowflake } from "@fosscord/util";
+import { Request, Response, Router } from "express";
+import { route } from "@fosscord/api";
+import { OrmUtils } from "@fosscord/util";
+
+const router = Router();
+
+router.post("/", route({ body: "MessageAcknowledgeSchema" }), async (req: Request, res: Response) => {
+	const { channel_id, message_id } = req.params;
+
+	const permission = await getPermission(req.user_id, undefined, channel_id);
+	permission.hasThrow("VIEW_CHANNEL");
+
+	let read_state = await ReadState.findOne({ where: { user_id: req.user_id, channel_id } });
+	if (!read_state) read_state = OrmUtils.mergeDeep(new ReadState(), { user_id: req.user_id, channel_id }) as ReadState;
+	read_state.last_message_id = message_id;
+
+	await read_state.save();
+
+	await emitEvent({
+		event: "MESSAGE_ACK",
+		user_id: req.user_id,
+		data: {
+			channel_id,
+			message_id,
+			version: 3763
+		}
+	} as MessageAckEvent);
+
+	res.sendStatus(204);
+});
+
+export default router;
diff --git a/src/api/routes/channels/#channel_id/messages/#message_id/crosspost.ts b/src/api/routes/channels/#channel_id/messages/#message_id/crosspost.ts
new file mode 100644
index 00000000..b2cb6763
--- /dev/null
+++ b/src/api/routes/channels/#channel_id/messages/#message_id/crosspost.ts
@@ -0,0 +1,28 @@
+import { Router, Response, Request } from "express";
+import { route } from "@fosscord/api";
+
+const router = Router();
+
+router.post("/", route({ permission: "MANAGE_MESSAGES" }), (req: Request, res: Response) => {
+	// TODO:
+	res.json({
+		id: "",
+		type: 0,
+		content: "",
+		channel_id: "",
+		author: { id: "", username: "", avatar: "", discriminator: "", public_flags: 64 },
+		attachments: [],
+		embeds: [],
+		mentions: [],
+		mention_roles: [],
+		pinned: false,
+		mention_everyone: false,
+		tts: false,
+		timestamp: "",
+		edited_timestamp: null,
+		flags: 1,
+		components: []
+	}).status(200);
+});
+
+export default router;
diff --git a/src/api/routes/channels/#channel_id/messages/#message_id/index.ts b/src/api/routes/channels/#channel_id/messages/#message_id/index.ts
new file mode 100644
index 00000000..d7e27062
--- /dev/null
+++ b/src/api/routes/channels/#channel_id/messages/#message_id/index.ts
@@ -0,0 +1,199 @@
+import {
+	Attachment,
+	Channel,
+	Embed,
+	DiscordApiErrors,
+	emitEvent,
+	FosscordApiErrors,
+	getPermission,
+	getRights,
+ 	Message,
+	MessageCreateEvent,
+	MessageDeleteEvent,
+	MessageUpdateEvent,
+	Snowflake,
+	uploadFile, 
+	MessageCreateSchema
+} from "@fosscord/util";
+import { Router, Response, Request } from "express";
+import multer from "multer";
+import { route } from "@fosscord/api";
+import { handleMessage, postHandleMessage } from "@fosscord/api";
+import { HTTPError } from "@fosscord/util";
+
+const router = Router();
+// TODO: message content/embed string length limit
+
+const messageUpload = multer({
+	limits: {
+		fileSize: 1024 * 1024 * 100,
+		fields: 10,
+		files: 1
+	},
+	storage: multer.memoryStorage()
+}); // max upload 50 mb
+
+router.patch("/", route({ body: "MessageCreateSchema", permission: "SEND_MESSAGES", right: "SEND_MESSAGES" }), async (req: Request, res: Response) => {
+	const { message_id, channel_id } = req.params;
+	let body = req.body as MessageCreateSchema;
+
+	const message = await Message.findOneOrFail({ where: { id: message_id, channel_id }, relations: ["attachments"] });
+
+	const permissions = await getPermission(req.user_id, undefined, channel_id);
+	
+	const rights = await getRights(req.user_id);
+
+	if ((req.user_id !== message.author_id)) {
+		if (!rights.has("MANAGE_MESSAGES")) {
+			permissions.hasThrow("MANAGE_MESSAGES");
+			body = { flags: body.flags };
+// guild admins can only suppress embeds of other messages, no such restriction imposed to instance-wide admins
+		}
+	} else rights.hasThrow("SELF_EDIT_MESSAGES");
+
+	const new_message = await handleMessage({
+		...message,
+		// TODO: should message_reference be overridable?
+		// @ts-ignore
+		message_reference: message.message_reference,
+		...body,
+		author_id: message.author_id,
+		channel_id,
+		id: message_id,
+		edited_timestamp: new Date()
+	});
+
+	await Promise.all([
+		new_message!.save(),
+		await emitEvent({
+			event: "MESSAGE_UPDATE",
+			channel_id,
+			data: { ...new_message, nonce: undefined }
+		} as MessageUpdateEvent)
+	]);
+
+	postHandleMessage(message);
+
+	return res.json(message);
+});
+
+
+// Backfill message with specific timestamp
+router.put(
+	"/",
+	messageUpload.single("file"),
+	async (req, res, next) => {
+		if (req.body.payload_json) {
+			req.body = JSON.parse(req.body.payload_json);
+		}
+
+		next();
+	},
+	route({ body: "MessageCreateSchema", permission: "SEND_MESSAGES", right: "SEND_BACKDATED_EVENTS" }),
+	async (req: Request, res: Response) => {
+		const { channel_id, message_id } = req.params;
+		let body = req.body as MessageCreateSchema;
+		const attachments: Attachment[] = [];
+		
+		const rights = await getRights(req.user_id);
+		rights.hasThrow("SEND_MESSAGES");
+
+		// regex to check if message contains anything other than numerals ( also no decimals )
+		if (!message_id.match(/^\+?\d+$/)) {
+			throw new HTTPError("Message IDs must be positive integers", 400);
+		}
+
+		const snowflake = Snowflake.deconstruct(message_id)
+		if (Date.now() < snowflake.timestamp) {
+			// message is in the future
+			throw FosscordApiErrors.CANNOT_BACKFILL_TO_THE_FUTURE;
+		}
+
+		const exists = await Message.findOne({ where: { id: message_id, channel_id: channel_id }});
+		if (exists) {
+			throw FosscordApiErrors.CANNOT_REPLACE_BY_BACKFILL;
+		}
+
+		if (req.file) {
+			try {
+				const file: any = await uploadFile(`/attachments/${req.params.channel_id}`, req.file);
+				attachments.push({ ...file, proxy_url: file.url });
+			} catch (error) {
+				return res.status(400).json(error);
+			}
+		}
+		const channel = await Channel.findOneOrFail({ where: { id: channel_id }, relations: ["recipients", "recipients.user"] });
+
+		const embeds = body.embeds || [];
+		if (body.embed) embeds.push(body.embed);
+		let message = await handleMessage({
+			...body,
+			type: 0,
+			pinned: false,
+			author_id: req.user_id,
+			id: message_id,
+			embeds,
+			channel_id,
+			attachments,
+			edited_timestamp: undefined,
+			timestamp: new Date(snowflake.timestamp),
+		});
+
+		//Fix for the client bug
+		delete message.member
+		
+		await Promise.all([
+			message.save(),
+			emitEvent({ event: "MESSAGE_CREATE", channel_id: channel_id, data: message } as MessageCreateEvent),
+			channel.save()
+		]);
+
+		postHandleMessage(message).catch((e) => { }); // no await as it shouldnt block the message send function and silently catch error
+
+		return res.json(message);
+	}
+);
+
+router.get("/", route({ permission: "VIEW_CHANNEL" }), async (req: Request, res: Response) => {
+	const { message_id, channel_id } = req.params;
+
+	const message = await Message.findOneOrFail({ where: { id: message_id, channel_id }, relations: ["attachments"] });
+
+	const permissions = await getPermission(req.user_id, undefined, channel_id);
+	
+	if (message.author_id !== req.user_id) permissions.hasThrow("READ_MESSAGE_HISTORY");
+
+	return res.json(message);
+});
+
+router.delete("/", route({}), async (req: Request, res: Response) => {
+	const { message_id, channel_id } = req.params;
+
+	const channel = await Channel.findOneOrFail({ where: { id: channel_id } });
+	const message = await Message.findOneOrFail({ where: { id: message_id } });
+	
+	const rights = await getRights(req.user_id);
+
+	if ((message.author_id !== req.user_id)) {
+		if (!rights.has("MANAGE_MESSAGES")) {
+			const permission = await getPermission(req.user_id, channel.guild_id, channel_id);
+			permission.hasThrow("MANAGE_MESSAGES");
+		}
+	} else rights.hasThrow("SELF_DELETE_MESSAGES");
+
+	await Message.delete({ id: message_id });
+
+	await emitEvent({
+		event: "MESSAGE_DELETE",
+		channel_id,
+		data: {
+			id: message_id,
+			channel_id,
+			guild_id: channel.guild_id
+		}
+	} as MessageDeleteEvent);
+
+	res.sendStatus(204);
+});
+
+export default router;
diff --git a/src/api/routes/channels/#channel_id/messages/#message_id/reactions.ts b/src/api/routes/channels/#channel_id/messages/#message_id/reactions.ts
new file mode 100644
index 00000000..d0ab35bb
--- /dev/null
+++ b/src/api/routes/channels/#channel_id/messages/#message_id/reactions.ts
@@ -0,0 +1,185 @@
+import {
+	Channel,
+	emitEvent,
+	Emoji,
+	getPermission,
+	Member,
+	Message,
+	MessageReactionAddEvent,
+	MessageReactionRemoveAllEvent,
+	MessageReactionRemoveEmojiEvent,
+	MessageReactionRemoveEvent,
+	PartialEmoji,
+	PublicUserProjection,
+	User
+} from "@fosscord/util";
+import { route } from "@fosscord/api";
+import { Router, Response, Request } from "express";
+import { HTTPError } from "@fosscord/util";
+import { In } from "typeorm";
+
+const router = Router();
+// TODO: check if emoji is really an unicode emoji or a prperly encoded external emoji
+
+function getEmoji(emoji: string): PartialEmoji {
+	emoji = decodeURIComponent(emoji);
+	const parts = emoji.includes(":") && emoji.split(":");
+	if (parts)
+		return {
+			name: parts[0],
+			id: parts[1]
+		};
+
+	return {
+		id: undefined,
+		name: emoji
+	};
+}
+
+router.delete("/", route({ permission: "MANAGE_MESSAGES" }), async (req: Request, res: Response) => {
+	const { message_id, channel_id } = req.params;
+
+	const channel = await Channel.findOneOrFail({ where: { id: channel_id } });
+
+	await Message.update({ id: message_id, channel_id }, { reactions: [] });
+
+	await emitEvent({
+		event: "MESSAGE_REACTION_REMOVE_ALL",
+		channel_id,
+		data: {
+			channel_id,
+			message_id,
+			guild_id: channel.guild_id
+		}
+	} as MessageReactionRemoveAllEvent);
+
+	res.sendStatus(204);
+});
+
+router.delete("/:emoji", route({ permission: "MANAGE_MESSAGES" }), async (req: Request, res: Response) => {
+	const { message_id, channel_id } = req.params;
+	const emoji = getEmoji(req.params.emoji);
+
+	const message = await Message.findOneOrFail({ where: { id: message_id, channel_id } });
+
+	const already_added = message.reactions.find((x) => (x.emoji.id === emoji.id && emoji.id) || x.emoji.name === emoji.name);
+	if (!already_added) throw new HTTPError("Reaction not found", 404);
+	message.reactions.remove(already_added);
+
+	await Promise.all([
+		message.save(),
+		emitEvent({
+			event: "MESSAGE_REACTION_REMOVE_EMOJI",
+			channel_id,
+			data: {
+				channel_id,
+				message_id,
+				guild_id: message.guild_id,
+				emoji
+			}
+		} as MessageReactionRemoveEmojiEvent)
+	]);
+
+	res.sendStatus(204);
+});
+
+router.get("/:emoji", route({ permission: "VIEW_CHANNEL" }), async (req: Request, res: Response) => {
+	const { message_id, channel_id } = req.params;
+	const emoji = getEmoji(req.params.emoji);
+
+	const message = await Message.findOneOrFail({ where: { id: message_id, channel_id } });
+	const reaction = message.reactions.find((x) => (x.emoji.id === emoji.id && emoji.id) || x.emoji.name === emoji.name);
+	if (!reaction) throw new HTTPError("Reaction not found", 404);
+
+	const users = await User.find({
+		where: {
+			id: In(reaction.user_ids)
+		},
+		select: PublicUserProjection
+	});
+
+	res.json(users);
+});
+
+router.put("/:emoji/:user_id", route({ permission: "READ_MESSAGE_HISTORY", right: "SELF_ADD_REACTIONS" }), async (req: Request, res: Response) => {
+	const { message_id, channel_id, user_id } = req.params;
+	if (user_id !== "@me") throw new HTTPError("Invalid user");
+	const emoji = getEmoji(req.params.emoji);
+
+	const channel = await Channel.findOneOrFail({ where: { id: channel_id } });
+	const message = await Message.findOneOrFail({ where: { id: message_id, channel_id } });
+	const already_added = message.reactions.find((x) => (x.emoji.id === emoji.id && emoji.id) || x.emoji.name === emoji.name);
+
+	if (!already_added) req.permission!.hasThrow("ADD_REACTIONS");
+
+	if (emoji.id) {
+		const external_emoji = await Emoji.findOneOrFail({ where: { id: emoji.id } });
+		if (!already_added) req.permission!.hasThrow("USE_EXTERNAL_EMOJIS");
+		emoji.animated = external_emoji.animated;
+		emoji.name = external_emoji.name;
+	}
+
+	if (already_added) {
+		if (already_added.user_ids.includes(req.user_id)) return res.sendStatus(204); // Do not throw an error ¯\_(ツ)_/¯ as discord also doesn't throw any error
+		already_added.count++;
+	} else message.reactions.push({ count: 1, emoji, user_ids: [req.user_id] });
+
+	await message.save();
+
+	const member = channel.guild_id && (await Member.findOneOrFail({ where: { id: req.user_id } }));
+
+	await emitEvent({
+		event: "MESSAGE_REACTION_ADD",
+		channel_id,
+		data: {
+			user_id: req.user_id,
+			channel_id,
+			message_id,
+			guild_id: channel.guild_id,
+			emoji,
+			member
+		}
+	} as MessageReactionAddEvent);
+
+	res.sendStatus(204);
+});
+
+router.delete("/:emoji/:user_id", route({}), async (req: Request, res: Response) => {
+	let { message_id, channel_id, user_id } = req.params;
+
+	const emoji = getEmoji(req.params.emoji);
+
+	const channel = await Channel.findOneOrFail({ where: { id: channel_id } });
+	const message = await Message.findOneOrFail({ where: { id: message_id, channel_id } });
+
+	if (user_id === "@me") user_id = req.user_id;
+	else {
+		const permissions = await getPermission(req.user_id, undefined, channel_id);
+		permissions.hasThrow("MANAGE_MESSAGES");
+	}
+
+	const already_added = message.reactions.find((x) => (x.emoji.id === emoji.id && emoji.id) || x.emoji.name === emoji.name);
+	if (!already_added || !already_added.user_ids.includes(user_id)) throw new HTTPError("Reaction not found", 404);
+
+	already_added.count--;
+
+	if (already_added.count <= 0) message.reactions.remove(already_added);
+
+	await message.save();
+
+	await emitEvent({
+		event: "MESSAGE_REACTION_REMOVE",
+		channel_id,
+		data: {
+			user_id: req.user_id,
+			channel_id,
+			message_id,
+			guild_id: channel.guild_id,
+			emoji
+		}
+	} as MessageReactionRemoveEvent);
+
+	res.sendStatus(204);
+});
+
+export default router;
diff --git a/src/api/routes/channels/#channel_id/messages/bulk-delete.ts b/src/api/routes/channels/#channel_id/messages/bulk-delete.ts
new file mode 100644
index 00000000..af44b522
--- /dev/null
+++ b/src/api/routes/channels/#channel_id/messages/bulk-delete.ts
@@ -0,0 +1,43 @@
+import { Router, Response, Request } from "express";
+import { Channel, Config, emitEvent, getPermission, getRights, MessageDeleteBulkEvent, Message } from "@fosscord/util";
+import { HTTPError } from "@fosscord/util";
+import { route } from "@fosscord/api";
+import { In } from "typeorm";
+
+const router: Router = Router();
+
+export default router;
+
+// should users be able to bulk delete messages or only bots? ANSWER: all users
+// should this request fail, if you provide messages older than 14 days/invalid ids? ANSWER: NO
+// https://discord.com/developers/docs/resources/channel#bulk-delete-messages
+router.post("/", route({ body: "BulkDeleteSchema" }), async (req: Request, res: Response) => {
+	const { channel_id } = req.params;
+	const channel = await Channel.findOneOrFail({where:{ id: channel_id} });
+	if (!channel.guild_id) throw new HTTPError("Can't bulk delete dm channel messages", 400);
+
+	const rights = await getRights(req.user_id);
+	rights.hasThrow("SELF_DELETE_MESSAGES");
+
+	let superuser = rights.has("MANAGE_MESSAGES");
+	const permission = await getPermission(req.user_id, channel?.guild_id, channel_id);
+
+	const { maxBulkDelete } = Config.get().limits.message;
+
+	const { messages } = req.body as { messages: string[] };
+	if (messages.length === 0) throw new HTTPError("You must specify messages to bulk delete");
+	if (!superuser) {
+		permission.hasThrow("MANAGE_MESSAGES");
+		if (messages.length > maxBulkDelete) throw new HTTPError(`You cannot delete more than ${maxBulkDelete} messages`);
+	}
+
+	await Message.delete({ id: In(messages) });
+
+	await emitEvent({
+		event: "MESSAGE_DELETE_BULK",
+		channel_id,
+		data: { ids: messages, channel_id, guild_id: channel.guild_id }
+	} as MessageDeleteBulkEvent);
+
+	res.sendStatus(204);
+});
diff --git a/src/api/routes/channels/#channel_id/messages/index.ts b/src/api/routes/channels/#channel_id/messages/index.ts
new file mode 100644
index 00000000..9ab0d97d
--- /dev/null
+++ b/src/api/routes/channels/#channel_id/messages/index.ts
@@ -0,0 +1,241 @@
+import { Router, Response, Request } from "express";
+import {
+	Attachment,
+	Channel,
+	ChannelType,
+	Config,
+	DmChannelDTO,
+	emitEvent,
+	getPermission,
+	getRights,
+	Message,
+	MessageCreateEvent,
+	Snowflake,
+	uploadFile,
+	Member,
+	MessageCreateSchema
+} from "@fosscord/util";
+import { HTTPError } from "@fosscord/util";
+import { handleMessage, postHandleMessage, route } from "@fosscord/api";
+import multer from "multer";
+import { FindManyOptions, LessThan, MoreThan } from "typeorm";
+import { URL } from "url";
+
+const router: Router = Router();
+
+export default router;
+
+export function isTextChannel(type: ChannelType): boolean {
+	switch (type) {
+		case ChannelType.GUILD_STORE:
+		case ChannelType.GUILD_VOICE:
+		case ChannelType.GUILD_STAGE_VOICE:
+		case ChannelType.GUILD_CATEGORY:
+		case ChannelType.GUILD_FORUM:
+		case ChannelType.DIRECTORY:
+			throw new HTTPError("not a text channel", 400);
+		case ChannelType.DM:
+		case ChannelType.GROUP_DM:
+		case ChannelType.GUILD_NEWS:
+		case ChannelType.GUILD_NEWS_THREAD:
+		case ChannelType.GUILD_PUBLIC_THREAD:
+		case ChannelType.GUILD_PRIVATE_THREAD:
+		case ChannelType.GUILD_TEXT:
+		case ChannelType.ENCRYPTED:
+		case ChannelType.ENCRYPTED_THREAD:
+			return true;
+		default:
+			throw new HTTPError("unimplemented", 400);
+	}
+}
+
+// https://discord.com/developers/docs/resources/channel#create-message
+// get messages
+router.get("/", async (req: Request, res: Response) => {
+	const channel_id = req.params.channel_id;
+	const channel = await Channel.findOneOrFail({ where: { id: channel_id } });
+	if (!channel) throw new HTTPError("Channel not found", 404);
+
+	isTextChannel(channel.type);
+	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", 422);
+
+	let halfLimit = Math.floor(limit / 2);
+
+	const permissions = await getPermission(req.user_id, channel.guild_id, channel_id);
+	permissions.hasThrow("VIEW_CHANNEL");
+	if (!permissions.has("READ_MESSAGE_HISTORY")) return res.json([]);
+
+	let query: FindManyOptions<Message> & { where: { id?: any; }; } = {
+		order: { id: "DESC" },
+		take: limit,
+		where: { channel_id },
+		relations: ["author", "webhook", "application", "mentions", "mention_roles", "mention_channels", "sticker_items", "attachments"]
+	};
+	
+
+	if (after) {
+		if (after > new Snowflake()) return res.status(422);
+		query.where.id = MoreThan(after);
+	}
+	else if (before) { 
+		if (before < req.params.channel_id) return res.status(422);
+		query.where.id = LessThan(before);
+	}
+	else if (around) {
+		query.where.id = [
+			MoreThan((BigInt(around) - BigInt(halfLimit)).toString()),
+			LessThan((BigInt(around) + BigInt(halfLimit)).toString())
+		];
+	}
+
+	const messages = await Message.find(query);
+	const endpoint = Config.get().cdn.endpointPublic;
+
+	return res.json(
+		messages.map((x: any) => {
+			(x.reactions || []).forEach((x: any) => {
+				// @ts-ignore
+				if ((x.user_ids || []).includes(req.user_id)) x.me = true;
+				// @ts-ignore
+				delete x.user_ids;
+			});
+			// @ts-ignore
+			if (!x.author) x.author = { id: "4", discriminator: "0000", username: "Fosscord Ghost", public_flags: "0", avatar: null };
+			x.attachments?.forEach((y: any) => {
+				// dynamically set attachment proxy_url in case the endpoint changed
+				const uri = y.proxy_url.startsWith("http") ? y.proxy_url : `https://example.org${y.proxy_url}`;
+				y.proxy_url = `${endpoint == null ? "" : endpoint}${new URL(uri).pathname}`;
+			});
+			
+			/**
+			Some clients ( discord.js ) only check if a property exists within the response,
+			which causes erorrs when, say, the `application` property is `null`.
+			**/
+			
+			for (let curr in x) {
+				if (x[curr] === null)
+					delete x[curr];
+			}
+
+			return x;
+		})
+	);
+});
+
+// TODO: config max upload size
+const messageUpload = multer({
+	limits: {
+		fileSize: 1024 * 1024 * 100,
+		fields: 10,
+		// files: 1
+	},
+	storage: multer.memoryStorage()
+}); // max upload 50 mb
+/**
+ TODO: dynamically change limit of MessageCreateSchema with config
+
+ https://discord.com/developers/docs/resources/channel#create-message
+ TODO: text channel slowdown (per-user and across-users)
+ Q: trim and replace message content and every embed field A: NO, given this cannot be implemented in E2EE channels
+ TODO: only dispatch notifications for mentions denoted in allowed_mentions
+**/
+// Send message
+router.post(
+	"/",
+	messageUpload.any(),
+	async (req, res, next) => {
+		if (req.body.payload_json) {
+			req.body = JSON.parse(req.body.payload_json);
+		}
+
+		next();
+	},
+	route({ body: "MessageCreateSchema", permission: "SEND_MESSAGES", right: "SEND_MESSAGES" }),
+	async (req: Request, res: Response) => {
+		const { channel_id } = req.params;
+		let body = req.body as MessageCreateSchema;
+		const attachments: Attachment[] = [];
+
+		const channel = await Channel.findOneOrFail({ where: { id: channel_id }, relations: ["recipients", "recipients.user"] });
+		if (!channel.isWritable()) {
+			throw new HTTPError(`Cannot send messages to channel of type ${channel.type}`, 400)
+		}
+
+		const files = req.files as Express.Multer.File[] ?? [];
+		for (let currFile of files) {
+			try {
+				const file: any = await uploadFile(`/attachments/${channel.id}`, currFile);
+				attachments.push({ ...file, proxy_url: file.url });
+			}
+			catch (error) {
+				return res.status(400).json(error);
+			}
+		}
+
+		const embeds = body.embeds || [];
+		if (body.embed) embeds.push(body.embed);
+		let message = await handleMessage({
+			...body,
+			type: 0,
+			pinned: false,
+			author_id: req.user_id,
+			embeds,
+			channel_id,
+			attachments,
+			edited_timestamp: undefined,
+			timestamp: new Date()
+		});
+
+		channel.last_message_id = message.id;
+
+		if (channel.isDm()) {
+			const channel_dto = await DmChannelDTO.from(channel);
+
+			// Only one recipients should be closed here, since in group DMs the recipient is deleted not closed
+			Promise.all(
+				channel.recipients!.map((recipient) => {
+					if (recipient.closed) {
+						recipient.closed = false;
+						return Promise.all([
+							recipient.save(),
+							emitEvent({
+								event: "CHANNEL_CREATE",
+								data: channel_dto.excludedRecipients([recipient.user_id]),
+								user_id: recipient.user_id
+							})
+						]);
+					}
+				})
+			);
+		}
+	
+	    //Defining member fields
+		var member = await Member.findOneOrFail({ where: { id: req.user_id }, relations: ["roles"] });
+		// TODO: This doesn't work either
+        // member.roles = member.roles.filter((role) => {
+		// 	return role.id !== role.guild_id;
+		// }).map((role) => {
+		// 	return role.id;
+		// });
+		message.member = member;
+		// TODO: Figure this out
+		// delete message.member.last_message_id;
+		// delete message.member.index;
+		
+		await Promise.all([
+			message.save(),
+			emitEvent({ event: "MESSAGE_CREATE", channel_id: channel_id, data: message } as MessageCreateEvent),
+			message.guild_id ? Member.update({ id: req.user_id, guild_id: message.guild_id }, { last_message_id: message.id }) : null,
+			channel.save()
+		]);
+
+		postHandleMessage(message).catch((e) => { }); // no await as it shouldnt block the message send function and silently catch error
+
+		return res.json(message);
+	}
+);
+