summary refs log tree commit diff
path: root/api/src/util/Channel.ts
blob: ef04d521045e86291fa36d6450ab3a5cf358e80f (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
import {
	ChannelCreateEvent,
	ChannelModel,
	ChannelType,
	emitEvent,
	getPermission,
	GuildModel,
	Snowflake,
	TextChannel,
	toObject,
	VoiceChannel
} from "@fosscord/util";
import { HTTPError } from "lambert-server";

// TODO: DM channel
export async function createChannel(channel: Partial<TextChannel | VoiceChannel>, user_id: string = "0") {
	// 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) {
				const exists = await ChannelModel.findOne({ id: channel.parent_id }, { guild_id: true }).exec();
				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 ChannelModel({
		...channel,
		id: Snowflake.generate(),
		created_at: new Date(),
		// @ts-ignore
		recipient_ids: null
	}).save();

	await emitEvent({ event: "CHANNEL_CREATE", data: toObject(channel), guild_id: channel.guild_id } as ChannelCreateEvent);

	return channel;
}