summary refs log tree commit diff
path: root/api/src/routes/channels/#channel_id/messages/#message_id/index.ts
blob: 6337a1b79991221d7259d5235a24fc54547faae2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { ChannelModel, emitEvent, getPermission, MessageDeleteEvent, MessageModel, MessageUpdateEvent, toObject } from "@fosscord/util";
import { Router, Response, Request } from "express";
import { HTTPError } from "lambert-server";
import { MessageCreateSchema } from "../../../../../schema/Message";

import { check } from "../../../../../util/instanceOf";
import { handleMessage, postHandleMessage } from "../../../../../util/Message";

const router = Router();

router.patch("/", check(MessageCreateSchema), async (req: Request, res: Response) => {
	const { message_id, channel_id } = req.params;
	var body = req.body as MessageCreateSchema;

	var message = await MessageModel.findOne({ id: message_id, channel_id }, { author_id: true }).exec();

	const permissions = await getPermission(req.user_id, undefined, channel_id);

	if (req.user_id !== message.author_id) {
		permissions.hasThrow("MANAGE_MESSAGES");
		body = { flags: body.flags };
	}

	const opts = await handleMessage({
		...body,
		...message,
		edited_timestamp: new Date()
	});

	// @ts-ignore
	message = await MessageModel.findOneAndUpdate({ id: message_id }, opts).populate("author").exec();

	await emitEvent({
		event: "MESSAGE_UPDATE",
		channel_id,
		data: { ...toObject(message), nonce: undefined }
	} as MessageUpdateEvent);

	postHandleMessage(message);

	return res.json(toObject(message));
});

// TODO: delete attachments in message

router.delete("/", async (req: Request, res: Response) => {
	const { message_id, channel_id } = req.params;

	const channel = await ChannelModel.findOne({ id: channel_id }, { guild_id: true });
	const message = await MessageModel.findOne({ id: message_id }, { author_id: true }).exec();

	const permission = await getPermission(req.user_id, channel.guild_id, channel_id);
	if (message.author_id !== req.user_id) permission.hasThrow("MANAGE_MESSAGES");

	await MessageModel.deleteOne({ id: message_id }).exec();

	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;