diff --git a/src/api/util/handlers/Message.ts b/src/api/util/handlers/Message.ts
index e350fad76..7141ff178 100644
--- a/src/api/util/handlers/Message.ts
+++ b/src/api/util/handlers/Message.ts
@@ -47,28 +47,38 @@ import {
Permissions,
normalizeUrl,
Reaction,
+ MessageCreateCloudAttachment,
+ MessageCreateAttachment,
} from "@spacebar/util";
import { HTTPError } from "lambert-server";
import { In } from "typeorm";
import fetch from "node-fetch-commonjs";
+import { CloudAttachment } from "../../../util/entities/CloudAttachment";
const allow_empty = false;
// TODO: check webhook, application, system author, stickers
// TODO: embed gifs/videos/images
-const LINK_REGEX =
- /<?https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)>?/g;
+const LINK_REGEX = /<?https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)>?/g;
export async function handleMessage(opts: MessageOptions): Promise<Message> {
const channel = await Channel.findOneOrFail({
where: { id: opts.channel_id },
relations: ["recipients"],
});
- if (!channel || !opts.channel_id)
- throw new HTTPError("Channel not found", 404);
+ if (!channel || !opts.channel_id) throw new HTTPError("Channel not found", 404);
+
+ const stickers = opts.sticker_ids ? await Sticker.find({ where: { id: In(opts.sticker_ids) } }) : undefined;
+ // cloud attachments with indexes
+ const cloudAttachments = opts.attachments?.reduce(
+ (acc, att, index) => {
+ if ("uploaded_filename" in att) {
+ acc.push({ attachment: att, index });
+ }
+ return acc;
+ },
+ [] as { attachment: MessageCreateCloudAttachment; index: number }[],
+ );
- const stickers = opts.sticker_ids
- ? await Sticker.find({ where: { id: In(opts.sticker_ids) } })
- : undefined;
const message = Message.create({
...opts,
poll: opts.poll,
@@ -82,10 +92,54 @@ export async function handleMessage(opts: MessageOptions): Promise<Message> {
mentions: [],
});
- if (
- message.content &&
- message.content.length > Config.get().limits.message.maxCharacters
- ) {
+ if (cloudAttachments && cloudAttachments.length > 0) {
+ console.log("[Message] Processing attachments for message", message.id, ":", message.attachments);
+ const uploadedAttachments = await Promise.all(
+ cloudAttachments.map(async (att) => {
+ const cAtt = att.attachment;
+ const attEnt = await CloudAttachment.findOneOrFail({
+ where: {
+ uploadFilename: cAtt.uploaded_filename,
+ },
+ });
+
+ const cloneResponse = await fetch(`${Config.get().cdn.endpointPrivate}/attachments/${attEnt.uploadFilename}/clone_to_message/${message.id}`, {
+ method: "POST",
+ headers: {
+ "signature": Config.get().security.requestSignature || "",
+ },
+ });
+
+ if (!cloneResponse.ok) {
+ console.error(`[Message] Failed to clone attachment ${attEnt.userFilename} to message ${message.id}`);
+ throw new HTTPError("Failed to process attachment: " + (await cloneResponse.text()), 500);
+ }
+
+ const cloneRespBody = (await cloneResponse.json()) as { success: boolean; new_path: string };
+
+ const realAtt = Attachment.create({
+ filename: attEnt.userFilename,
+ url: `${Config.get().cdn.endpointPublic}/${cloneRespBody.new_path}`,
+ proxy_url: `${Config.get().cdn.endpointPublic}/${cloneRespBody.new_path}`,
+ size: attEnt.size,
+ height: attEnt.height,
+ width: attEnt.width,
+ content_type: attEnt.contentType || attEnt.userOriginalContentType,
+ });
+ await realAtt.save();
+ return { attachment: realAtt, index: att.index };
+ }),
+ );
+ console.log("[Message] Processed attachments for message", message.id, ":", message.attachments);
+
+ for (const att of uploadedAttachments) {
+ message.attachments![att.index] = att.attachment;
+ }
+ } else console.log("[Message] No cloud attachments to process for message", message.id, ":", message.attachments);
+
+ console.log("opts:", opts.attachments, "\nmessage:", message.attachments);
+
+ if (message.content && message.content.length > Config.get().limits.message.maxCharacters) {
throw new HTTPError("Content length over max character limit");
}
@@ -138,28 +192,15 @@ export async function handleMessage(opts: MessageOptions): Promise<Message> {
}
if (opts.avatar_url) {
const avatarData = await fetch(opts.avatar_url);
- const base64 = await avatarData
- .buffer()
- .then((x) => x.toString("base64"));
+ const base64 = await avatarData.buffer().then((x) => x.toString("base64"));
- const dataUri =
- "data:" +
- avatarData.headers.get("content-type") +
- ";base64," +
- base64;
+ const dataUri = "data:" + avatarData.headers.get("content-type") + ";base64," + base64;
- message.avatar = await handleFile(
- `/avatars/${opts.webhook_id}`,
- dataUri as string,
- );
+ message.avatar = await handleFile(`/avatars/${opts.webhook_id}`, dataUri as string);
message.author.avatar = message.avatar;
}
} else {
- permission = await getPermission(
- opts.author_id,
- channel.guild_id,
- opts.channel_id,
- );
+ permission = await getPermission(opts.author_id, channel.guild_id, opts.channel_id);
permission.hasThrow("SEND_MESSAGES");
if (permission.cache.member) {
message.member = permission.cache.member;
@@ -173,20 +214,12 @@ export async function handleMessage(opts: MessageOptions): Promise<Message> {
const guild = await Guild.findOneOrFail({
where: { id: channel.guild_id },
});
- if (!opts.message_reference.guild_id)
- opts.message_reference.guild_id = channel.guild_id;
- if (!opts.message_reference.channel_id)
- opts.message_reference.channel_id = opts.channel_id;
+ if (!opts.message_reference.guild_id) opts.message_reference.guild_id = channel.guild_id;
+ if (!opts.message_reference.channel_id) opts.message_reference.channel_id = opts.channel_id;
if (!guild.features.includes("CROSS_CHANNEL_REPLIES")) {
- if (opts.message_reference.guild_id !== channel.guild_id)
- throw new HTTPError(
- "You can only reference messages from this guild",
- );
- if (opts.message_reference.channel_id !== opts.channel_id)
- throw new HTTPError(
- "You can only reference messages from this channel",
- );
+ if (opts.message_reference.guild_id !== channel.guild_id) throw new HTTPError("You can only reference messages from this guild");
+ if (opts.message_reference.channel_id !== opts.channel_id) throw new HTTPError("You can only reference messages from this channel");
}
message.message_reference = opts.message_reference;
@@ -198,15 +231,7 @@ export async function handleMessage(opts: MessageOptions): Promise<Message> {
}
// TODO: stickers/activity
- if (
- !allow_empty &&
- !opts.content &&
- !opts.embeds?.length &&
- !opts.attachments?.length &&
- !opts.sticker_ids?.length &&
- !opts.poll &&
- !opts.components?.length
- ) {
+ if (!allow_empty && !opts.content && !opts.embeds?.length && !opts.attachments?.length && !opts.sticker_ids?.length && !opts.poll && !opts.components?.length) {
console.log("[Message] Rejecting empty message:", opts, message);
throw new HTTPError("Empty messages are not allowed", 50006);
}
@@ -230,31 +255,22 @@ export async function handleMessage(opts: MessageOptions): Promise<Message> {
}*/
for (const [, mention] of content.matchAll(USER_MENTION)) {
- if (!mention_user_ids.includes(mention))
- mention_user_ids.push(mention);
+ if (!mention_user_ids.includes(mention)) mention_user_ids.push(mention);
}
await Promise.all(
- Array.from(content.matchAll(ROLE_MENTION)).map(
- async ([, mention]) => {
- const role = await Role.findOneOrFail({
- where: { id: mention, guild_id: channel.guild_id },
- });
- if (
- role.mentionable ||
- opts.webhook_id ||
- permission?.has("MANAGE_ROLES")
- ) {
- mention_role_ids.push(mention);
- }
- },
- ),
+ Array.from(content.matchAll(ROLE_MENTION)).map(async ([, mention]) => {
+ const role = await Role.findOneOrFail({
+ where: { id: mention, guild_id: channel.guild_id },
+ });
+ if (role.mentionable || opts.webhook_id || permission?.has("MANAGE_ROLES")) {
+ mention_role_ids.push(mention);
+ }
+ }),
);
if (opts.webhook_id || permission?.has("MENTION_EVERYONE")) {
- mention_everyone =
- !!content.match(EVERYONE_MENTION) ||
- !!content.match(HERE_MENTION);
+ mention_everyone = !!content.match(EVERYONE_MENTION) || !!content.match(HERE_MENTION);
}
}
@@ -265,10 +281,7 @@ export async function handleMessage(opts: MessageOptions): Promise<Message> {
channel_id: message.channel_id,
},
});
- if (
- referencedMessage &&
- referencedMessage.author_id !== message.author_id
- ) {
+ if (referencedMessage && referencedMessage.author_id !== message.author_id) {
message.mentions.push(
User.create({
id: referencedMessage.author_id,
@@ -282,46 +295,12 @@ export async function handleMessage(opts: MessageOptions): Promise<Message> {
Channel.create({ id: x }),
);*/
message.mention_roles = mention_role_ids.map((x) => Role.create({ id: x }));
- message.mentions = [
- ...message.mentions,
- ...mention_user_ids.map((x) => User.create({ id: x })),
- ];
+ message.mentions = [...message.mentions, ...mention_user_ids.map((x) => User.create({ id: x }))];
message.mention_everyone = mention_everyone;
// TODO: check and put it all in the body
- if(message.attachments?.some(att => "uploaded_filename" in att)) {
- message.attachments = await Promise.all(message.attachments.map(async att => {
- if("uploaded_filename" in att) {
- const cloneResponse = await fetch(`${Config.get().cdn.endpointPrivate}/attachments/${att.uploaded_filename}/clone_to_message/${message.id}`, {
- method: "POST",
- headers: {
- "X-Signature": Config.get().security.requestSignature || "",
- },
- });
- if(!cloneResponse.ok) {
- console.error(`[Message] Failed to clone attachment ${att.uploaded_filename} to message ${message.id}`);
- throw new HTTPError("Failed to process attachment: " + await cloneResponse.text(), 500);
- }
-
- const cloneRespBody = await cloneResponse.json() as { success: boolean, new_path: string };
-
- return Attachment.create({
- id: att.id,
- filename: att.filename,
- url: `${Config.get().cdn.endpointPublic}/${cloneRespBody.new_path}`,
- proxy_url: `${Config.get().cdn.endpointPublic}/${cloneRespBody.new_path}`,
- size: att.size,
- height: att.height,
- width: att.width,
- content_type: att.content_type,
- });
- }
- return att;
- }));
- }
-
return message;
}
@@ -383,10 +362,7 @@ export async function postHandleMessage(message: Message) {
channel_id: message.channel_id,
data,
} as MessageUpdateEvent),
- Message.update(
- { id: message.id, channel_id: message.channel_id },
- { embeds: data.embeds },
- ),
+ Message.update({ id: message.id, channel_id: message.channel_id }, { embeds: data.embeds }),
]);
return;
}
@@ -415,12 +391,8 @@ export async function postHandleMessage(message: Message) {
}
// bit gross, but whatever!
- const endpointPublic =
- Config.get().cdn.endpointPublic || "http://127.0.0.1"; // lol
- const handler =
- url.hostname === new URL(endpointPublic).hostname
- ? EmbedHandlers["self"]
- : EmbedHandlers[url.hostname] || EmbedHandlers["default"];
+ const endpointPublic = Config.get().cdn.endpointPublic || "http://127.0.0.1"; // lol
+ const handler = url.hostname === new URL(endpointPublic).hostname ? EmbedHandlers["self"] : EmbedHandlers[url.hostname] || EmbedHandlers["default"];
try {
let res = await handler(url);
@@ -438,10 +410,7 @@ export async function postHandleMessage(message: Message) {
data.embeds.push(embed);
}
} catch (e) {
- console.error(
- `[Embeds] Error while generating embed for ${link}`,
- e,
- );
+ console.error(`[Embeds] Error while generating embed for ${link}`, e);
Sentry.captureException(e, (scope) => {
scope.clear();
scope.setContext("request", { url: link });
@@ -457,10 +426,7 @@ export async function postHandleMessage(message: Message) {
channel_id: message.channel_id,
data,
} as MessageUpdateEvent),
- Message.update(
- { id: message.id, channel_id: message.channel_id },
- { embeds: data.embeds },
- ),
+ Message.update({ id: message.id, channel_id: message.channel_id }, { embeds: data.embeds }),
...cachePromises,
]);
}
@@ -478,9 +444,7 @@ export async function sendMessage(opts: MessageOptions) {
]);
// no await as it should catch error non-blockingly
- postHandleMessage(message).catch((e) =>
- console.error("[Message] post-message handler failed", e),
- );
+ postHandleMessage(message).catch((e) => console.error("[Message] post-message handler failed", e));
return message;
}
@@ -495,7 +459,7 @@ interface MessageOptions extends MessageCreateSchema {
embeds?: Embed[];
reactions?: Reaction[];
channel_id?: string;
- attachments?: Attachment[]; // why are we masking this?
+ attachments?: (MessageCreateAttachment | MessageCreateCloudAttachment | Attachment)[]; // why are we masking this?
edited_timestamp?: Date;
timestamp?: Date;
username?: string;
|