diff options
author | Diego Magdaleno <diegomagdaleno@protonmail.com> | 2021-05-22 15:55:45 -0500 |
---|---|---|
committer | Diego Magdaleno <diegomagdaleno@protonmail.com> | 2021-05-22 15:55:45 -0500 |
commit | e4a4759e971387675d127990b53dfd8b3a443d82 (patch) | |
tree | 8f4e8101fafc01492ace38a5fa51e32f07b85e1d /src/routes | |
parent | Config: Refactor config to be be in separate classes (diff) | |
download | server-e4a4759e971387675d127990b53dfd8b3a443d82.tar.xz |
Fix merge issues, update to reflect config changes and package.json
Diffstat (limited to 'src/routes')
20 files changed, 694 insertions, 295 deletions
diff --git a/src/routes/channels/#channel_id/invites.ts b/src/routes/channels/#channel_id/invites.ts index 10d6ae3f..457e78ca 100644 --- a/src/routes/channels/#channel_id/invites.ts +++ b/src/routes/channels/#channel_id/invites.ts @@ -24,16 +24,19 @@ router.post("/", check(InviteCreateSchema), async (req: Request, res: Response) const permission = await getPermission(user_id, guild_id); permission.hasThrow("CREATE_INSTANT_INVITE"); + const expires_at = new Date(req.body.max_age * 1000 + Date.now()); + const invite = { code: random(), temporary: req.body.temporary, uses: 0, max_uses: req.body.max_uses, max_age: req.body.max_age, + expires_at, created_at: new Date(), guild_id, channel_id: channel_id, - inviter_id: user_id, + inviter_id: user_id }; await new InviteModel(invite).save(); diff --git a/src/routes/channels/#channel_id/messages/#message_id/ack.ts b/src/routes/channels/#channel_id/messages/#message_id/ack.ts new file mode 100644 index 00000000..9782365f --- /dev/null +++ b/src/routes/channels/#channel_id/messages/#message_id/ack.ts @@ -0,0 +1,29 @@ +import { getPermission } from "@fosscord/server-util"; +import { MessageModel } from "@fosscord/server-util"; +import { Event } from "@fosscord/server-util"; +import { ChannelModel } from "@fosscord/server-util"; +import { Request, Response, Router } from "express"; +import { HTTPError } from "lambert-server"; +import { emitEvent } from "../../../../../util/Event"; + +const router = Router(); + +// router.pot("/", async (req: Request, res: Response) => { +// const { channel_id, message_id } = req.params; + +// const permission = await getPermission(req.user_id, channel?.guild_id, channel_id, { channel }); +// permission.hasThrow("MANAGE_MESSAGES"); + +// await emitEvent({ +// event: "MESSAGE_ACK", +// channel_id, +// data: { +// channel_id, +// message_id +// } +// } as MessageAckEvent); + +// res.sendStatus(204); +// }); + +export default router; diff --git a/src/routes/channels/#channel_id/messages/#message_id/index.ts b/src/routes/channels/#channel_id/messages/#message_id/index.ts index 19efc823..5a61b4ad 100644 --- a/src/routes/channels/#channel_id/messages/#message_id/index.ts +++ b/src/routes/channels/#channel_id/messages/#message_id/index.ts @@ -1,20 +1,58 @@ -import { ChannelModel, getPermission, MessageDeleteEvent, MessageModel } from "@fosscord/server-util"; +import { ChannelModel, getPermission, MessageDeleteEvent, MessageModel, MessageUpdateEvent, toObject } from "@fosscord/server-util"; import { Router } from "express"; import { HTTPError } from "lambert-server"; +import { MessageCreateSchema } from "../../../../../schema/Message"; import { emitEvent } from "../../../../../util/Event"; import { check } from "../../../../../util/instanceOf"; +import { handleMessage } from "../../../../../util/Message"; const router = Router(); -// TODO: + +router.patch("/", check(MessageCreateSchema), async (req, res) => { + 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(); + if (!message) throw new HTTPError("Message not found", 404); + + 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, + author_id: message.author_id, + channel_id, + id: message_id, + edited_timestamp: new Date() + }); + + message = await MessageModel.findOneAndUpdate({ id: message_id }, opts).populate("author").exec(); + if (!message) throw new HTTPError("Message not found", 404); + + await emitEvent({ + event: "MESSAGE_UPDATE", + channel_id, + guild_id: message.guild_id, + data: { ...toObject(message), nonce: undefined } + } as MessageUpdateEvent); + + return res.json(toObject(message)); +}); router.delete("/", async (req, res) => { const { message_id, channel_id } = req.params; const channel = await ChannelModel.findOne({ id: channel_id }, { guild_id: true }); - if (!channel) throw new HTTPError("Channel doesn't exist", 404); + if (!channel) throw new HTTPError("Channel not found", 404); + const message = await MessageModel.findOne({ id: message_id }, { author_id: true }).exec(); + if (!message) throw new HTTPError("Message not found", 404); const permission = await getPermission(req.user_id, channel.guild_id, channel_id); - permission.hasThrow("MANAGE_MESSAGES"); + if (message.author_id !== req.user_id) permission.hasThrow("MANAGE_MESSAGES"); await MessageModel.deleteOne({ id: message_id }).exec(); @@ -25,8 +63,8 @@ router.delete("/", async (req, res) => { data: { id: message_id, channel_id, - guild_id: channel.guild_id, - }, + guild_id: channel.guild_id + } } as MessageDeleteEvent); res.sendStatus(204); diff --git a/src/routes/channels/#channel_id/messages/#message_id/reactions.ts b/src/routes/channels/#channel_id/messages/#message_id/reactions.ts index 014daee7..1bfaae39 100644 --- a/src/routes/channels/#channel_id/messages/#message_id/reactions.ts +++ b/src/routes/channels/#channel_id/messages/#message_id/reactions.ts @@ -1,6 +1,206 @@ +import { + ChannelModel, + EmojiModel, + getPermission, + MemberModel, + MessageModel, + MessageReactionAddEvent, + MessageReactionRemoveAllEvent, + MessageReactionRemoveEmojiEvent, + MessageReactionRemoveEvent, + PartialEmoji, + PublicUserProjection, + toObject, + UserModel +} from "@fosscord/server-util"; import { Router } from "express"; +import { HTTPError } from "lambert-server"; +import { emitEvent } from "../../../../../util/Event"; const router = Router(); -// TODO: +// 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("/", async (req, res) => { + const { message_id, channel_id } = req.params; + + const channel = await ChannelModel.findOne({ id: channel_id }, { guild_id: true }).exec(); + if (!channel) throw new HTTPError("Channel not found", 404); + + const permissions = await getPermission(req.user_id, undefined, channel_id); + permissions.hasThrow("MANAGE_MESSAGES"); + + const message = await MessageModel.findOneAndUpdate({ id: message_id, channel_id }, { reactions: [] }).exec(); + if (!message) throw new HTTPError("Message not found", 404); + + await emitEvent({ + event: "MESSAGE_REACTION_REMOVE_ALL", + channel_id, + guild_id: channel.guild_id, + data: { + channel_id, + message_id, + guild_id: channel.guild_id + } + } as MessageReactionRemoveAllEvent); + + res.sendStatus(204); +}); + +router.delete("/:emoji", async (req, res) => { + const { message_id, channel_id } = req.params; + const emoji = getEmoji(req.params.emoji); + + const channel = await ChannelModel.findOne({ id: channel_id }, { guild_id: true }).exec(); + if (!channel) throw new HTTPError("Channel not found", 404); + + const permissions = await getPermission(req.user_id, undefined, channel_id); + permissions.hasThrow("MANAGE_MESSAGES"); + + const message = await MessageModel.findOne({ id: message_id, channel_id }).exec(); + if (!message) throw new HTTPError("Message not found", 404); + + 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 MessageModel.updateOne({ id: message_id, channel_id }, message).exec(); + + await emitEvent({ + event: "MESSAGE_REACTION_REMOVE_EMOJI", + channel_id, + guild_id: channel.guild_id, + data: { + channel_id, + message_id, + guild_id: channel.guild_id, + emoji + } + } as MessageReactionRemoveEmojiEvent); + + res.sendStatus(204); +}); + +router.get("/:emoji", async (req, res) => { + const { message_id, channel_id } = req.params; + const emoji = getEmoji(req.params.emoji); + + const message = await MessageModel.findOne({ id: message_id, channel_id }).exec(); + if (!message) throw new HTTPError("Message not found", 404); + 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 permissions = await getPermission(req.user_id, undefined, channel_id); + permissions.hasThrow("VIEW_CHANNEL"); + + const users = await UserModel.find({ id: { $in: reaction.user_ids } }, PublicUserProjection).exec(); + + res.json(toObject(users)); +}); + +router.put("/:emoji/:user_id", async (req, res) => { + 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 ChannelModel.findOne({ id: channel_id }, { guild_id: true }).exec(); + if (!channel) throw new HTTPError("Channel not found", 404); + + const message = await MessageModel.findOne({ id: message_id, channel_id }).exec(); + if (!message) throw new HTTPError("Message not found", 404); + const already_added = message.reactions.find((x) => (x.emoji.id === emoji.id && emoji.id) || x.emoji.name === emoji.name); + + const permissions = await getPermission(req.user_id, undefined, channel_id); + permissions.hasThrow("READ_MESSAGE_HISTORY"); + if (!already_added) permissions.hasThrow("ADD_REACTIONS"); + + if (emoji.id) { + const external_emoji = await EmojiModel.findOne({ id: emoji.id }).exec(); + if (!external_emoji) throw new HTTPError("Emoji not found", 404); + if (!already_added) permissions.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 MessageModel.updateOne({ id: message_id, channel_id }, message).exec(); + + const member = channel.guild_id && (await MemberModel.findOne({ id: req.user_id }).exec()); + + await emitEvent({ + event: "MESSAGE_REACTION_ADD", + channel_id, + guild_id: channel.guild_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", async (req, res) => { + var { message_id, channel_id, user_id } = req.params; + + const emoji = getEmoji(req.params.emoji); + + const channel = await ChannelModel.findOne({ id: channel_id }, { guild_id: true }).exec(); + if (!channel) throw new HTTPError("Channel not found", 404); + + const message = await MessageModel.findOne({ id: message_id, channel_id }).exec(); + if (!message) throw new HTTPError("Message not found", 404); + + const permissions = await getPermission(req.user_id, undefined, channel_id); + + if (user_id === "@me") user_id = req.user_id; + else 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 MessageModel.updateOne({ id: message_id, channel_id }, message).exec(); + + await emitEvent({ + event: "MESSAGE_REACTION_REMOVE", + channel_id, + guild_id: channel.guild_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/routes/channels/#channel_id/messages/bulk-delete.ts b/src/routes/channels/#channel_id/messages/bulk-delete.ts index c70e7ac1..8a11475e 100644 --- a/src/routes/channels/#channel_id/messages/bulk-delete.ts +++ b/src/routes/channels/#channel_id/messages/bulk-delete.ts @@ -13,7 +13,7 @@ export default router; // TODO: should this request fail, if you provide messages older than 14 days/invalid ids? // https://discord.com/developers/docs/resources/channel#bulk-delete-messages router.post("/", check({ messages: [String] }), async (req, res) => { - const channel_id = req.params.channel_id; + const { channel_id } = req.params; const channel = await ChannelModel.findOne({ id: channel_id }, { permission_overwrites: true, guild_id: true }).exec(); if (!channel?.guild_id) throw new HTTPError("Can't bulk delete dm channel messages", 400); @@ -31,7 +31,7 @@ router.post("/", check({ messages: [String] }), async (req, res) => { await emitEvent({ event: "MESSAGE_DELETE_BULK", channel_id, - data: { ids: messages, channel_id, guild_id: channel.guild_id }, + data: { ids: messages, channel_id, guild_id: channel.guild_id } } as MessageDeleteBulkEvent); res.sendStatus(204); diff --git a/src/routes/channels/#channel_id/messages/index.ts b/src/routes/channels/#channel_id/messages/index.ts index b186343e..7fdff809 100644 --- a/src/routes/channels/#channel_id/messages/index.ts +++ b/src/routes/channels/#channel_id/messages/index.ts @@ -8,7 +8,7 @@ import { MessageDocument, MessageModel, Snowflake, - toObject, + toObject } from "@fosscord/server-util"; import { HTTPError } from "lambert-server"; import { MessageCreateSchema } from "../../../../schema/Message"; @@ -18,6 +18,7 @@ import multer from "multer"; import { emitEvent } from "../../../../util/Event"; import { Query } from "mongoose"; import { PublicMemberProjection } from "../../../../util/Member"; +import { sendMessage } from "../../../../util/Message"; const router: Router = Router(); export default router; @@ -48,7 +49,7 @@ router.get("/", async (req, res) => { try { instanceOf({ $around: String, $after: String, $before: String, $limit: new Length(Number, 1, 100) }, req.query, { path: "query", - req, + req }); } catch (error) { return res.status(400).json({ code: 50035, message: "Invalid Query", success: false, errors: error }); @@ -67,7 +68,7 @@ router.get("/", async (req, res) => { else if (around) query = MessageModel.find({ channel_id, - id: { $gt: (BigInt(around) - BigInt(halfLimit)).toString(), $lt: (BigInt(around) + BigInt(halfLimit)).toString() }, + id: { $gt: (BigInt(around) - BigInt(halfLimit)).toString(), $lt: (BigInt(around) + BigInt(halfLimit)).toString() } }); else { query = MessageModel.find({ channel_id }).sort({ id: -1 }); @@ -75,7 +76,18 @@ router.get("/", async (req, res) => { const messages = await query.limit(limit).exec(); - return res.json(toObject(messages)); + return res.json( + toObject(messages).map((x) => { + (x.reactions || []).forEach((x) => { + // @ts-ignore + if ((x.user_ids || []).includes(req.user_id)) x.me = true; + // @ts-ignore + delete x.user_ids; + }); + + return x; + }) + ); }); // TODO: config max upload size @@ -89,52 +101,12 @@ const messageUpload = multer({ limits: { fieldSize: 1024 * 1024 * 1024 * 50 } }) // TODO: trim and replace message content and every embed field // Send message router.post("/", check(MessageCreateSchema), async (req, res) => { - const channel_id = req.params.channel_id; + const { channel_id } = req.params; const body = req.body as MessageCreateSchema; - const channel = await ChannelModel.findOne({ id: channel_id }, { guild_id: true, type: true, permission_overwrites: true }).exec(); - if (!channel) throw new HTTPError("Channel not found", 404); - // TODO: are tts messages allowed in dm channels? should permission be checked? - - const permissions = await getPermission(req.user_id, channel.guild_id, channel_id, { channel }); - permissions.hasThrow("SEND_MESSAGES"); - if (body.tts) permissions.hasThrow("SEND_TTS_MESSAGES"); - if (body.message_reference) { - permissions.hasThrow("READ_MESSAGE_HISTORY"); - if (body.message_reference.guild_id !== channel.guild_id) throw new HTTPError("You can only reference messages from this guild"); - } - - if (body.message_reference) { - if (body.message_reference.channel_id !== channel_id) throw new HTTPError("You can only reference messages from this channel"); - // TODO: should be checked if the referenced message exists? - } - const embeds = []; if (body.embed) embeds.push(body.embed); - - // TODO: check and put it all in the body - const message: Message = { - id: Snowflake.generate(), - channel_id, - guild_id: channel.guild_id, - author_id: req.user_id, - content: body.content, - timestamp: new Date(), - mention_channels_ids: [], - mention_role_ids: [], - mention_user_ids: [], - attachments: [], - embeds: [], - reactions: [], - type: 0, - tts: body.tts, - nonce: body.nonce, - pinned: false, - }; - - const data = toObject(await new MessageModel(message).populate({ path: "member", select: PublicMemberProjection }).save()); - - await emitEvent({ event: "MESSAGE_CREATE", channel_id, data, guild_id: channel.guild_id } as MessageCreateEvent); + const data = await sendMessage({ ...body, type: 0, pinned: false, author_id: req.user_id, embeds, channel_id }); return res.send(data); }); diff --git a/src/routes/channels/#channel_id/pins.ts b/src/routes/channels/#channel_id/pins.ts index 4d8f53b1..ccb909b8 100644 --- a/src/routes/channels/#channel_id/pins.ts +++ b/src/routes/channels/#channel_id/pins.ts @@ -1,10 +1,10 @@ -import { ChannelModel, getPermission, MessageModel, toObject } from "@fosscord/server-util"; +import { ChannelModel, ChannelPinsUpdateEvent, getPermission, MessageModel, MessageUpdateEvent, toObject } from "@fosscord/server-util"; import { Router, Request, Response } from "express"; import * as Config from "../../../util/Config"; import { HTTPError } from "lambert-server"; +import { emitEvent } from "../../../util/Event"; const router: Router = Router(); - // TODO: auto throw error if findOne doesn't find anything router.put("/:message_id", async (req: Request, res: Response) => { @@ -22,6 +22,59 @@ router.put("/:message_id", async (req: Request, res: Response) => { if (pinned_count >= maxPins) throw new HTTPError("Max pin count reached: " + maxPins); await MessageModel.updateOne({ id: message_id }, { pinned: true }).exec(); + const message = toObject(await MessageModel.findOne({ id: message_id }).exec()); + if (!message) throw new HTTPError("Message not found", 404); + + await emitEvent({ + event: "MESSAGE_UPDATE", + channel_id, + guild_id: channel.guild_id, + data: message + } as MessageUpdateEvent); + + await emitEvent({ + event: "CHANNEL_PINS_UPDATE", + channel_id, + guild_id: channel.guild_id, + data: { + channel_id, + guild_id: channel.guild_id, + last_pin_timestamp: undefined + } + } as ChannelPinsUpdateEvent); + + res.sendStatus(204); +}); + +router.delete("/:message_id", async (req, res) => { + const { channel_id, message_id } = req.params; + + const channel = await ChannelModel.findOne({ id: channel_id }).exec(); + if (!channel) throw new HTTPError("Channel not found", 404); + + const permission = await getPermission(req.user_id, channel.guild_id, channel_id); + permission.hasThrow("VIEW_CHANNEL"); + if (channel.guild_id) permission.hasThrow("MANAGE_MESSAGES"); + + const message = toObject(await MessageModel.findOneAndUpdate({ id: message_id }, { pinned: false }).exec()); + + await emitEvent({ + event: "MESSAGE_UPDATE", + channel_id, + guild_id: channel.guild_id, + data: message + } as MessageUpdateEvent); + + await emitEvent({ + event: "CHANNEL_PINS_UPDATE", + channel_id, + guild_id: channel.guild_id, + data: { + channel_id, + guild_id: channel.guild_id, + last_pin_timestamp: undefined + } + } as ChannelPinsUpdateEvent); res.sendStatus(204); }); diff --git a/src/routes/guilds/#guild_id/channels.ts b/src/routes/guilds/#guild_id/channels.ts index 9e8d3506..9d8a95b0 100644 --- a/src/routes/guilds/#guild_id/channels.ts +++ b/src/routes/guilds/#guild_id/channels.ts @@ -1,9 +1,19 @@ import { Router } from "express"; -import { ChannelCreateEvent, ChannelModel, ChannelType, GuildModel, Snowflake, toObject, ChannelUpdateEvent } from "@fosscord/server-util"; +import { + ChannelCreateEvent, + ChannelModel, + ChannelType, + GuildModel, + Snowflake, + toObject, + ChannelUpdateEvent, + AnyChannel +} from "@fosscord/server-util"; import { HTTPError } from "lambert-server"; import { ChannelModifySchema } from "../../../schema/Channel"; import { emitEvent } from "../../../util/Event"; import { check } from "../../../util/instanceOf"; +import { createChannel } from "../../../util/Channel"; const router = Router(); router.get("/", async (req, res) => { @@ -17,40 +27,7 @@ router.post("/", check(ChannelModifySchema), async (req, res) => { const { guild_id } = req.params; const body = req.body as ChannelModifySchema; - if (!body.permission_overwrites) body.permission_overwrites = []; - if (!body.topic) body.topic = ""; - if (!body.rate_limit_per_user) body.rate_limit_per_user = 0; - - switch (body.type) { - case ChannelType.DM: - case ChannelType.GROUP_DM: - throw new HTTPError("You can't create a dm channel in a guild"); - // TODO: - case ChannelType.GUILD_STORE: - throw new HTTPError("Not yet supported"); - case ChannelType.GUILD_NEWS: - // TODO: check if guild is community server - } - - if (body.parent_id) { - const exists = await ChannelModel.findOne({ id: body.parent_id }, { guild_id: true }).exec(); - if (!exists) throw new HTTPError("Parent id channel doesn't exist", 400); - if (exists.guild_id !== guild_id) throw new HTTPError("The category channel needs to be in the guild"); - } - - const guild = await GuildModel.findOne({ id: guild_id }, { id: true }).exec(); - if (!guild) throw new HTTPError("Guild not found", 404); - - const channel = { - ...body, - id: Snowflake.generate(), - created_at: new Date(), - guild_id - }; - - await new ChannelModel(channel).save(); - - await emitEvent({ event: "CHANNEL_CREATE", data: channel, guild_id } as ChannelCreateEvent); + const channel = await createChannel({ ...body, guild_id }, req.user_id); res.json(channel); }); diff --git a/src/routes/guilds/#guild_id/delete.ts b/src/routes/guilds/#guild_id/delete.ts new file mode 100644 index 00000000..5d4db816 --- /dev/null +++ b/src/routes/guilds/#guild_id/delete.ts @@ -0,0 +1,45 @@ +import { + ChannelModel, + EmojiModel, + GuildDeleteEvent, + GuildModel, + InviteModel, + MessageModel, + RoleModel, + UserModel +} from "@fosscord/server-util"; +import { Router, Request, Response } from "express"; +import { HTTPError } from "lambert-server"; +import { emitEvent } from "../../../util/Event"; + +const router = Router(); + +// discord prefixes this route with /delete instead of using the delete method +// docs are wrong https://discord.com/developers/docs/resources/guild#delete-guild +router.post("/", async (req: Request, res: Response) => { + var { guild_id } = req.params; + + const guild = await GuildModel.findOne({ id: guild_id }, "owner_id").exec(); + if (!guild) throw new HTTPError("This guild does not exist", 404); + if (guild.owner_id !== req.user_id) throw new HTTPError("You are not the owner of this guild", 401); + + await emitEvent({ + event: "GUILD_DELETE", + data: { + id: guild_id + }, + guild_id: guild_id + } as GuildDeleteEvent); + + await GuildModel.deleteOne({ id: guild_id }).exec(); + await UserModel.updateMany({ guilds: guild_id }, { $pull: { guilds: guild_id } }).exec(); + await RoleModel.deleteMany({ guild_id }).exec(); + await ChannelModel.deleteMany({ guild_id }).exec(); + await EmojiModel.deleteMany({ guild_id }).exec(); + await InviteModel.deleteMany({ guild_id }).exec(); + await MessageModel.deleteMany({ guild_id }).exec(); + + return res.sendStatus(204); +}); + +export default router; diff --git a/src/routes/guilds/#guild_id/index.ts b/src/routes/guilds/#guild_id/index.ts index 18e6372e..9ef0127a 100644 --- a/src/routes/guilds/#guild_id/index.ts +++ b/src/routes/guilds/#guild_id/index.ts @@ -11,7 +11,7 @@ import { MessageModel, RoleModel, toObject, - UserModel, + UserModel } from "@fosscord/server-util"; import { HTTPError } from "lambert-server"; import { GuildUpdateSchema } from "../../../schema/Guild"; @@ -54,43 +54,4 @@ router.patch("/", check(GuildUpdateSchema), async (req: Request, res: Response) return res.send(data); }); -// discord prefixes this route with /delete instead of using the delete method -// docs are wrong https://discord.com/developers/docs/resources/guild#delete-guild -router.post("/delete", async (req: Request, res: Response) => { - var { guild_id } = req.params; - - const guild = await GuildModel.findOne({ id: guild_id }, "owner_id").exec(); - if (!guild) throw new HTTPError("This guild does not exist", 404); - if (guild.owner_id !== req.user_id) throw new HTTPError("You are not the owner of this guild", 401); - - await emitEvent({ - event: "GUILD_DELETE", - data: { - id: guild_id, - }, - guild_id: guild_id, - } as GuildDeleteEvent); - - await GuildModel.deleteOne({ id: guild_id }).exec(); - await UserModel.updateMany({ guilds: guild_id }, { $pull: { guilds: guild_id } }).exec(); - await RoleModel.deleteMany({ guild_id }).exec(); - await ChannelModel.deleteMany({ guild_id }).exec(); - await EmojiModel.deleteMany({ guild_id }).exec(); - await InviteModel.deleteMany({ guild_id }).exec(); - await MessageModel.deleteMany({ guild_id }).exec(); - - return res.sendStatus(204); -}); - -router.get("/vanity-url", async (req: Request, res: Response) => { - const { guild_id } = req.params; - - const guild = await GuildModel.findOne({ id: guild_id }).exec(); - if (!guild) throw new HTTPError("Guild does not exist", 404); - - if(!guild.vanity_url) throw new HTTPError("This guild has no vanity url", 204) - - return res.json(guild.vanity_url); -}); - export default router; diff --git a/src/routes/guilds/#guild_id/members.ts b/src/routes/guilds/#guild_id/members.ts deleted file mode 100644 index 4dd8f013..00000000 --- a/src/routes/guilds/#guild_id/members.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { Request, Response, Router } from "express"; -import { - GuildModel, - MemberModel, - UserModel, - toObject, - GuildMemberAddEvent, - getPermission, - PermissionResolvable, -} from "@fosscord/server-util"; -import { HTTPError } from "lambert-server"; -import { instanceOf, Length, check } from "../../../util/instanceOf"; -import { PublicMemberProjection, addMember, removeMember, addRole, removeRole, changeNickname, isMember } from "../../../util/Member"; -import { emitEvent } from "../../../util/Event"; -import { MemberNickChangeSchema } from "../../../schema/Member"; -import { getPublicUser } from "../../../util/User"; - -const router = Router(); - -// TODO: not allowed for user -> only allowed for bots with privileged intents -// TODO: send over websocket -router.get("/", async (req: Request, res: Response) => { - const { guild_id } = req.params; - const guild = await GuildModel.findOne({ id: guild_id }).exec(); - if (!guild) throw new HTTPError("Guild not found", 404); - await isMember(req.user_id, guild_id); - - try { - instanceOf({ $limit: new Length(Number, 1, 1000), $after: String }, req.query, { - path: "query", - req, - ref: { obj: null, key: "" }, - }); - } catch (error) { - return res.status(400).json({ code: 50035, message: "Invalid Query", success: false, errors: error }); - } - - // @ts-ignore - if (!req.query.limit) req.query.limit = 1; - const { limit, after } = (<unknown>req.query) as { limit: number; after: string }; - const query = after ? { id: { $gt: after } } : {}; - - var members = await MemberModel.find({ guild_id, ...query }, PublicMemberProjection) - .limit(limit) - .exec(); - - return res.json(toObject(members)); -}); - -router.get("/:member_id", async (req: Request, res: Response) => { - const { guild_id, member_id } = req.params; - await isMember(req.user_id, guild_id); - - const member = await MemberModel.findOne({ id: member_id, guild_id }).exec(); - if (!member) throw new HTTPError("Member not found", 404); - - return res.json(toObject(member)); -}); - -router.put("/:member_id", async (req: Request, res: Response) => { - const { guild_id, member_id } = req.params; - - throw new HTTPError("Maintenance: Currently you can't add a member", 403) - // TODO: only for oauth2 applications - await addMember(member_id, guild_id); - res.sendStatus(204) -}); - -router.delete("/:member_id", async (req: Request, res: Response) => { - const { guild_id, member_id } = req.params; - - const perms = await getPermission(req.user_id, guild_id); - perms.hasThrow("KICK_MEMBERS"); - - await removeMember(member_id, guild_id); - res.sendStatus(204) -}); - -router.delete("/:member_id/roles/:role_id", async (req: Request, res: Response) => { - const { guild_id, role_id, member_id } = req.params; - - const perms = await getPermission(req.user_id, guild_id); - perms.hasThrow("MANAGE_ROLES"); - - await removeRole(member_id, guild_id, role_id); - res.sendStatus(204); -}); - -router.put("/:member_id/roles/:role_id", async (req: Request, res: Response) => { - const { guild_id, role_id, member_id } = req.params; - - const perms = await getPermission(req.user_id, guild_id); - perms.hasThrow("MANAGE_ROLES"); - - await addRole(member_id, guild_id, role_id); - res.sendStatus(204); -}); - -router.patch("/:member_id/nick", check(MemberNickChangeSchema), async (req: Request, res: Response) => { - var { guild_id, member_id } = req.params; - var permissionString: PermissionResolvable = "MANAGE_NICKNAMES"; - if (member_id === "@me") { - member_id = req.user_id; - permissionString = "CHANGE_NICKNAME"; - } - - const perms = await getPermission(req.user_id, guild_id); - perms.hasThrow(permissionString); - - await changeNickname(member_id, guild_id, req.body.nickname); - res.status(204); -}); - -export default router; diff --git a/src/routes/guilds/#guild_id/members/#member_id/index.ts b/src/routes/guilds/#guild_id/members/#member_id/index.ts new file mode 100644 index 00000000..e9356c0d --- /dev/null +++ b/src/routes/guilds/#guild_id/members/#member_id/index.ts @@ -0,0 +1,70 @@ +import { Request, Response, Router } from "express"; +import { + GuildModel, + MemberModel, + UserModel, + toObject, + GuildMemberAddEvent, + getPermission, + PermissionResolvable, + RoleModel, + GuildMemberUpdateEvent +} from "@fosscord/server-util"; +import { HTTPError } from "lambert-server"; +import { addMember, isMember, removeMember } from "../../../../../util/Member"; +import { check } from "../../../../../util/instanceOf"; +import { MemberChangeSchema } from "../../../../../schema/Member"; +import { emitEvent } from "../../../../../util/Event"; + +const router = Router(); + +router.get("/", async (req: Request, res: Response) => { + const { guild_id, member_id } = req.params; + await isMember(req.user_id, guild_id); + + const member = await MemberModel.findOne({ id: member_id, guild_id }).exec(); + if (!member) throw new HTTPError("Member not found", 404); + + return res.json(toObject(member)); +}); + +router.patch("/", check(MemberChangeSchema), async (req, res) => { + const { guild_id, member_id } = req.params; + const body = req.body as MemberChangeSchema; + if (body.roles) { + const roles = await RoleModel.find({ id: { $in: body.roles } }).exec(); + if (body.roles.length !== roles.length) throw new HTTPError("Roles not found", 404); + // TODO: check if user has permission to add role + } + + const member = await MemberModel.findOneAndUpdate({ id: member_id, guild_id }, body).exec(); + + await emitEvent({ + event: "GUILD_MEMBER_UPDATE", + guild_id, + data: toObject(member) + } as GuildMemberUpdateEvent); + + res.json(toObject(member)); +}); + +router.put("/", async (req: Request, res: Response) => { + const { guild_id, member_id } = req.params; + + throw new HTTPError("Maintenance: Currently you can't add a member", 403); + // TODO: only for oauth2 applications + await addMember(member_id, guild_id); + res.sendStatus(204); +}); + +router.delete("/", async (req: Request, res: Response) => { + const { guild_id, member_id } = req.params; + + const perms = await getPermission(req.user_id, guild_id); + perms.hasThrow("KICK_MEMBERS"); + + await removeMember(member_id, guild_id); + res.sendStatus(204); +}); + +export default router; diff --git a/src/routes/guilds/#guild_id/members/#member_id/nick.ts b/src/routes/guilds/#guild_id/members/#member_id/nick.ts new file mode 100644 index 00000000..9078409d --- /dev/null +++ b/src/routes/guilds/#guild_id/members/#member_id/nick.ts @@ -0,0 +1,24 @@ +import { getPermission, PermissionResolvable } from "@fosscord/server-util"; +import { Request, Response, Router } from "express"; +import { check } from "lambert-server"; +import { MemberNickChangeSchema } from "../../../../../schema/Member"; +import { changeNickname } from "../../../../../util/Member"; + +const router = Router(); + +router.patch("/", check(MemberNickChangeSchema), async (req: Request, res: Response) => { + var { guild_id, member_id } = req.params; + var permissionString: PermissionResolvable = "MANAGE_NICKNAMES"; + if (member_id === "@me") { + member_id = req.user_id; + permissionString = "CHANGE_NICKNAME"; + } + + const perms = await getPermission(req.user_id, guild_id); + perms.hasThrow(permissionString); + + await changeNickname(member_id, guild_id, req.body.nickname); + res.status(204); +}); + +export default router; diff --git a/src/routes/guilds/#guild_id/members/#member_id/roles/#role_id/index.ts b/src/routes/guilds/#guild_id/members/#member_id/roles/#role_id/index.ts new file mode 100644 index 00000000..b7a43c74 --- /dev/null +++ b/src/routes/guilds/#guild_id/members/#member_id/roles/#role_id/index.ts @@ -0,0 +1,27 @@ +import { getPermission } from "@fosscord/server-util"; +import { Request, Response, Router } from "express"; +import { addRole, removeRole } from "../../../../../../../util/Member"; + +const router = Router(); + +router.delete("/:member_id/roles/:role_id", async (req: Request, res: Response) => { + const { guild_id, role_id, member_id } = req.params; + + const perms = await getPermission(req.user_id, guild_id); + perms.hasThrow("MANAGE_ROLES"); + + await removeRole(member_id, guild_id, role_id); + res.sendStatus(204); +}); + +router.put("/:member_id/roles/:role_id", async (req: Request, res: Response) => { + const { guild_id, role_id, member_id } = req.params; + + const perms = await getPermission(req.user_id, guild_id); + perms.hasThrow("MANAGE_ROLES"); + + await addRole(member_id, guild_id, role_id); + res.sendStatus(204); +}); + +export default router; diff --git a/src/routes/guilds/#guild_id/members/index.ts b/src/routes/guilds/#guild_id/members/index.ts new file mode 100644 index 00000000..1ec21226 --- /dev/null +++ b/src/routes/guilds/#guild_id/members/index.ts @@ -0,0 +1,39 @@ +import { Request, Response, Router } from "express"; +import { GuildModel, MemberModel, toObject } from "@fosscord/server-util"; +import { HTTPError } from "lambert-server"; +import { instanceOf, Length } from "../../../../util/instanceOf"; +import { PublicMemberProjection, isMember } from "../../../../util/Member"; + +const router = Router(); + +// TODO: not allowed for user -> only allowed for bots with privileged intents +// TODO: send over websocket +router.get("/", async (req: Request, res: Response) => { + const { guild_id } = req.params; + const guild = await GuildModel.findOne({ id: guild_id }).exec(); + if (!guild) throw new HTTPError("Guild not found", 404); + await isMember(req.user_id, guild_id); + + try { + instanceOf({ $limit: new Length(Number, 1, 1000), $after: String }, req.query, { + path: "query", + req, + ref: { obj: null, key: "" } + }); + } catch (error) { + return res.status(400).json({ code: 50035, message: "Invalid Query", success: false, errors: error }); + } + + // @ts-ignore + if (!req.query.limit) req.query.limit = 1; + const { limit, after } = (<unknown>req.query) as { limit: number; after: string }; + const query = after ? { id: { $gt: after } } : {}; + + var members = await MemberModel.find({ guild_id, ...query }, PublicMemberProjection) + .limit(limit) + .exec(); + + return res.json(toObject(members)); +}); + +export default router; diff --git a/src/routes/guilds/#guild_id/roles.ts b/src/routes/guilds/#guild_id/roles.ts index 9e42f8d9..e9360847 100644 --- a/src/routes/guilds/#guild_id/roles.ts +++ b/src/routes/guilds/#guild_id/roles.ts @@ -1,28 +1,38 @@ import { Request, Response, Router } from "express"; -import { RoleModel, GuildModel, getPermission, toObject, UserModel, Snowflake, MemberModel } from "@fosscord/server-util"; +import { + RoleModel, + GuildModel, + getPermission, + toObject, + UserModel, + Snowflake, + MemberModel, + GuildRoleCreateEvent, + GuildRoleUpdateEvent, + GuildRoleDeleteEvent +} from "@fosscord/server-util"; import { HTTPError } from "lambert-server"; import { emitEvent } from "../../../util/Event"; import { check } from "../../../util/instanceOf"; -import { RoleCreateSchema, RoleModifySchema } from "../../../schema/Roles"; +import { RoleModifySchema } from "../../../schema/Roles"; import { getPublicUser } from "../../../util/User"; +import { isMember } from "../../../util/Member"; const router: Router = Router(); router.get("/", async (req: Request, res: Response) => { const guild_id = req.params.guild_id; - const guild = await GuildModel.exists({ id: guild_id }); - if (!guild) throw new HTTPError("Guild not found", 404); + await isMember(req.user_id, guild_id); + + const roles = await RoleModel.find({ guild_id: guild_id }).exec(); - var roles = await RoleModel.find({ guild_id: guild_id }).exec(); - if(!roles) res.send("No roles"); return res.json(toObject(roles)); }); -router.post("/", check(RoleCreateSchema), async (req: Request, res: Response) => { - - const guild_id = req.params.guild_id; - const body = req.body as RoleCreateSchema; +router.post("/", check(RoleModifySchema), async (req: Request, res: Response) => { + const guild_id = req.params.guild_id; + const body = req.body as RoleModifySchema; const guild = await GuildModel.findOne({ id: guild_id }, { id: true }).exec(); if (!guild) throw new HTTPError("Guild not found", 404); @@ -31,29 +41,34 @@ router.post("/", check(RoleCreateSchema), async (req: Request, res: Response) => if (!user) throw new HTTPError("User not found", 404); const perms = await getPermission(req.user_id, guild_id); + perms.hasThrow("MANAGE_ROLES"); + if (!body.name) throw new HTTPError("You need to specify a name"); - if (!perms.has("MANAGE_ROLES")) - throw new HTTPError("You missing the MANAGE_ROLES permission", 401); - - const role_id = Snowflake.generate(); - - var role = { + const role = await new RoleModel({ ...body, - id: role_id, + id: Snowflake.generate(), guild_id: guild_id, managed: false, position: 0, tags: null, - } - - const roleNew = await new RoleModel(role).save(); - res.json(toObject(roleNew)).send(); + permissions: body.permissions || 0n + }).save(); + + await emitEvent({ + event: "GUILD_ROLE_CREATE", + guild_id, + data: { + guild_id, + role: toObject(role) + } + } as GuildRoleCreateEvent); + + res.json(toObject(role)); }); router.delete("/:role_id", async (req: Request, res: Response) => { - - const guild_id = req.params.guild_id; - const { role_id } = req.params; + const guild_id = req.params.guild_id; + const { role_id } = req.params; const guild = await GuildModel.findOne({ id: guild_id }, { id: true }).exec(); if (!guild) throw new HTTPError("Guild not found", 404); @@ -64,21 +79,31 @@ router.delete("/:role_id", async (req: Request, res: Response) => { const perms = await getPermission(req.user_id, guild_id); - if (!perms.has("MANAGE_ROLES")) - throw new HTTPError("You missing the MANAGE_ROLES permission", 401); + if (!perms.has("MANAGE_ROLES")) throw new HTTPError("You missing the MANAGE_ROLES permission", 401); await RoleModel.findOneAndDelete({ id: role_id, guild_id: guild_id }).exec(); - res.send("Deleted"); + await emitEvent({ + event: "GUILD_ROLE_DELETE", + guild_id, + data: { + guild_id, + role_id + } + } as GuildRoleDeleteEvent); + + res.sendStatus(204); }); +// TODO: check role hierarchy router.patch("/:role_id", check(RoleModifySchema), async (req: Request, res: Response) => { - const guild_id = req.params.guild_id; - const { role_id } = req.params; + const guild_id = req.params.guild_id; + const { role_id } = req.params; + const body = req.body as RoleModifySchema; const guild = await GuildModel.findOne({ id: guild_id }, { id: true }).exec(); if (!guild) throw new HTTPError("Guild not found", 404); @@ -87,20 +112,28 @@ router.patch("/:role_id", check(RoleModifySchema), async (req: Request, res: Res const user = await UserModel.findOne({ id: req.user_id }).exec(); if (!user) throw new HTTPError("User not found", 404); - const role = await RoleModel.findOne({ id: role_id, guild_id: guild_id }).exec(); - if (!role) throw new HTTPError("role not found", 404); - const perms = await getPermission(req.user_id, guild_id); - - if (!perms.has("MANAGE_ROLES")) - throw new HTTPError("You missing the MANAGE_ROLES permission", 401); - - var roleObj = await RoleModel.findOneAndUpdate({ - id: role_id, guild_id: guild_id - }, ...req.body).exec(); - - res.json(toObject(roleObj)).send(); + perms.hasThrow("MANAGE_ROLES"); + + const role = await RoleModel.findOneAndUpdate( + { + id: role_id, + guild_id: guild_id + }, + // @ts-ignore + body + ).exec(); + + await emitEvent({ + event: "GUILD_ROLE_UPDATE", + guild_id, + data: { + guild_id, + role + } + } as GuildRoleUpdateEvent); + + res.json(toObject(role)); }); - export default router; diff --git a/src/routes/guilds/#guild_id/vanity-url.ts b/src/routes/guilds/#guild_id/vanity-url.ts new file mode 100644 index 00000000..052a638f --- /dev/null +++ b/src/routes/guilds/#guild_id/vanity-url.ts @@ -0,0 +1,18 @@ +import { GuildModel } from "@fosscord/server-util"; +import { Router, Request, Response } from "express"; +import { HTTPError } from "lambert-server"; + +const router = Router(); + +router.get("/", async (req: Request, res: Response) => { + const { guild_id } = req.params; + + const guild = await GuildModel.findOne({ id: guild_id }).exec(); + if (!guild) throw new HTTPError("Guild does not exist", 404); + + if (!guild.vanity_url) throw new HTTPError("This guild has no vanity url", 204); + + return res.json({ vanity_ur: guild.vanity_url }); +}); + +export default router; diff --git a/src/routes/guilds/index.ts b/src/routes/guilds/index.ts index e1fbd180..8860bcdf 100644 --- a/src/routes/guilds/index.ts +++ b/src/routes/guilds/index.ts @@ -6,6 +6,7 @@ import { GuildCreateSchema } from "../../schema/Guild"; import * as Config from "../../util/Config"; import { getPublicUser } from "../../util/User"; import { addMember } from "../../util/Member"; +import { createChannel } from "../../util/Channel"; const router: Router = Router(); @@ -80,7 +81,8 @@ router.post("/", check(GuildCreateSchema), async (req: Request, res: Response) = }).save() ]); - await addMember(req.user_id, guild_id, { guild: guild_doc }); + await createChannel({ name: "general", type: 0, guild_id, position: 0, permission_overwrites: [] }, req.user_id); + await addMember(req.user_id, guild_id); res.status(201).json({ id: guild.id }); }); diff --git a/src/routes/invites/index.ts b/src/routes/invites/index.ts index 7f4ff59b..8c04713c 100644 --- a/src/routes/invites/index.ts +++ b/src/routes/invites/index.ts @@ -1,19 +1,31 @@ import { Router, Request, Response } from "express"; import { getPermission, InviteModel, toObject } from "@fosscord/server-util"; import { HTTPError } from "lambert-server"; +import { addMember } from "../../util/Member"; const router: Router = Router(); -router.get("/:invite_code", async (req: Request, res: Response) => { - const { invite_code: code } = req.params; +router.get("/:code", async (req: Request, res: Response) => { + const { code } = req.params; const invite = await InviteModel.findOne({ code }).exec(); + if (!invite) throw new HTTPError("Unknown Invite", 404); + + res.status(200).send(toObject(invite)); +}); + +router.post("/:code", async (req: Request, res: Response) => { + const { code } = req.params; + const invite = await InviteModel.findOneAndUpdate({ code }, { $inc: { uses: 1 } }).exec(); if (!invite) throw new HTTPError("Unknown Invite", 404); - res.status(200).send({ invite: toObject(invite) }); + + await addMember(req.user_id, invite.guild_id); + + res.status(200).send(toObject(invite)); }); -router.delete("/:invite_code", async (req: Request, res: Response) => { - const { invite_code: code } = req.params; +router.delete("/:code", async (req: Request, res: Response) => { + const { code } = req.params; const invite = await InviteModel.findOne({ code }).exec(); if (!invite) throw new HTTPError("Unknown Invite", 404); diff --git a/src/routes/users/@me/affinities/user.ts b/src/routes/users/@me/affinities/user.ts new file mode 100644 index 00000000..2e435995 --- /dev/null +++ b/src/routes/users/@me/affinities/user.ts @@ -0,0 +1,10 @@ +import { Router } from "express"; + +const router = Router(); + +router.get("/", (req, res) => { + // TODO: + res.status(200).send({ user_affinities: [], inverse_user_affinities: [] }); +}); + +export default router; |