summary refs log tree commit diff
path: root/src/routes/guilds/templates/index.ts
blob: 2d8cdf0e1ae5eff0489899d3cef9c2893eb0e589 (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
import { Request, Response, Router } from "express";
const router: Router = Router();
import { TemplateModel, GuildModel, toObject, UserModel, RoleModel, Snowflake, Guild } from "@fosscord/server-util";
import { HTTPError } from "lambert-server";
import { GuildTemplateCreateSchema } from "../../../schema/Guild";
import { getPublicUser } from "../../../util/User";
import { check } from "../../../util/instanceOf";
import Config from "../../../util/Config";
import { addMember } from "../../../util/Member";

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

	const template = await TemplateModel.findOne({ id: code }).exec();
	if (!template) throw new HTTPError("template not found", 404);

	res.json(toObject(template)).send();
});

router.post("/:code", check(GuildTemplateCreateSchema), async (req: Request, res: Response) => {
	const { code } = req.params;
	const body = req.body as GuildTemplateCreateSchema;

	const { maxGuilds } = Config.get().limits.user;
	const user = await getPublicUser(req.user_id, { guilds: true });

	if (user.guilds.length >= maxGuilds) {
		throw new HTTPError(`Maximum number of guilds reached ${maxGuilds}`, 403);
	}

	const template = await TemplateModel.findOne({ code: code }).exec();
	if (!template) throw new HTTPError("template not found", 404);

	const guild_id = Snowflake.generate();

	const guild: Guild = {
		...body,
		...template.serialized_source_guild,
		id: guild_id,
		owner_id: req.user_id,
	};

	await Promise.all([
		new GuildModel(guild).save(),
		new RoleModel({
			id: guild_id,
			guild_id: guild_id,
			color: 0,
			hoist: false,
			managed: true,
			mentionable: true,
			name: "@everyone",
			permissions: 2251804225n,
			position: 0,
			tags: null,
		}).save(),
	]);
	await addMember(req.user_id, guild_id, { guild });

	res.status(201).json({ id: guild.id });
});

export default router;