diff options
Diffstat (limited to '')
-rw-r--r-- | src/api/routes/channels/#channel_id/messages/index.ts (renamed from api/src/routes/channels/#channel_id/messages/index.ts) | 122 |
1 files changed, 60 insertions, 62 deletions
diff --git a/api/src/routes/channels/#channel_id/messages/index.ts b/src/api/routes/channels/#channel_id/messages/index.ts index 34cc5ff8..9ab0d97d 100644 --- a/api/src/routes/channels/#channel_id/messages/index.ts +++ b/src/api/routes/channels/#channel_id/messages/index.ts @@ -5,16 +5,17 @@ import { ChannelType, Config, DmChannelDTO, - Embed, emitEvent, getPermission, getRights, Message, MessageCreateEvent, + Snowflake, uploadFile, - Member + Member, + MessageCreateSchema } from "@fosscord/util"; -import { HTTPError } from "lambert-server"; +import { HTTPError } from "@fosscord/util"; import { handleMessage, postHandleMessage, route } from "@fosscord/api"; import multer from "multer"; import { FindManyOptions, LessThan, MoreThan } from "typeorm"; @@ -30,6 +31,8 @@ export function isTextChannel(type: ChannelType): boolean { 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: @@ -46,37 +49,11 @@ export function isTextChannel(type: ChannelType): boolean { } } -export interface MessageCreateSchema { - content?: string; - nonce?: string; - tts?: boolean; - flags?: string; - embeds?: Embed[]; - embed?: Embed; - // TODO: ^ embed is deprecated in favor of embeds (https://discord.com/developers/docs/resources/channel#message-object) - allowed_mentions?: { - parse?: string[]; - roles?: string[]; - users?: string[]; - replied_user?: boolean; - }; - message_reference?: { - message_id: string; - channel_id: string; - guild_id?: string; - fail_if_not_exists?: boolean; - }; - payload_json?: string; - file?: any; - attachments?: any[]; //TODO we should create an interface for attachments - sticker_ids?: string[]; -} - // 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({ id: channel_id }); + const channel = await Channel.findOneOrFail({ where: { id: channel_id } }); if (!channel) throw new HTTPError("Channel not found", 404); isTextChannel(channel.type); @@ -84,23 +61,30 @@ router.get("/", async (req: Request, res: Response) => { 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"); + if (limit < 1 || limit > 100) throw new HTTPError("limit must be between 1 and 100", 422); - var halfLimit = Math.floor(limit / 2); + 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([]); - var query: FindManyOptions<Message> & { where: { id?: any; }; } = { + 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) query.where.id = MoreThan(after); - else if (before) query.where.id = LessThan(before); + 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()), @@ -126,10 +110,13 @@ router.get("/", async (req: Request, res: Response) => { 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 (var curr in x) { + + /** + 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]; } @@ -144,23 +131,22 @@ const messageUpload = multer({ limits: { fileSize: 1024 * 1024 * 100, fields: 10, - files: 1 + // files: 1 }, storage: multer.memoryStorage() }); // max upload 50 mb - -// TODO: dynamically change limit of MessageCreateSchema with config -// TODO: check: sum of all characters in an embed structure must not exceed instance limits - -// https://discord.com/developers/docs/resources/channel#create-message -// TODO: text channel slowdown -// TODO: trim and replace message content and every embed field -// TODO: check allowed_mentions - +/** + 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.single("file"), + messageUpload.any(), async (req, res, next) => { if (req.body.payload_json) { req.body = JSON.parse(req.body.payload_json); @@ -171,21 +157,24 @@ router.post( route({ body: "MessageCreateSchema", permission: "SEND_MESSAGES", right: "SEND_MESSAGES" }), async (req: Request, res: Response) => { const { channel_id } = req.params; - var body = req.body as MessageCreateSchema; + let body = req.body as MessageCreateSchema; const attachments: Attachment[] = []; - if (req.file) { + 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 = await uploadFile(`/attachments/${req.params.channel_id}`, req.file); + const file: any = await uploadFile(`/attachments/${channel.id}`, currFile); attachments.push({ ...file, proxy_url: file.url }); - } catch (error) { + } + catch (error) { return res.status(400).json(error); } } - 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 embeds = body.embeds || []; if (body.embed) embeds.push(body.embed); @@ -223,11 +212,19 @@ router.post( }) ); } - - - //Fix for the client bug - delete message.member + //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(), @@ -241,3 +238,4 @@ router.post( return res.json(message); } ); + |