2021-06-01 04:33:02 +02:00
|
|
|
import { MessageAttachment, MessageOptions, TextChannel } from "discord.js";
|
2021-06-06 23:51:32 +02:00
|
|
|
import fs from "fs";
|
|
|
|
import { downloadFile } from "../../utils";
|
2020-07-22 22:33:10 +02:00
|
|
|
const fsp = fs.promises;
|
|
|
|
|
|
|
|
const MAX_ATTACHMENT_REHOST_SIZE = 1024 * 1024 * 8;
|
|
|
|
|
2021-06-01 04:33:02 +02:00
|
|
|
export async function rehostAttachment(attachment: MessageAttachment, targetChannel: TextChannel): Promise<string> {
|
2020-07-22 22:33:10 +02:00
|
|
|
if (attachment.size > MAX_ATTACHMENT_REHOST_SIZE) {
|
|
|
|
return "Attachment too big to rehost";
|
|
|
|
}
|
|
|
|
|
|
|
|
let downloaded;
|
|
|
|
try {
|
|
|
|
downloaded = await downloadFile(attachment.url, 3);
|
2021-05-06 19:23:47 +01:00
|
|
|
} catch {
|
2020-07-22 22:33:10 +02:00
|
|
|
return "Failed to download attachment after 3 tries";
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
2021-06-02 04:07:50 +02:00
|
|
|
const content: MessageOptions = {
|
|
|
|
content: `Rehost of attachment ${attachment.id}`,
|
|
|
|
files: [{ name: attachment.name ? attachment.name : undefined, attachment: await fsp.readFile(downloaded.path) }],
|
|
|
|
};
|
2021-06-30 04:56:56 +02:00
|
|
|
const rehostMessage = await targetChannel.send(content);
|
2021-06-01 04:33:02 +02:00
|
|
|
return rehostMessage.attachments.values()[0].url;
|
2021-05-06 19:23:47 +01:00
|
|
|
} catch {
|
2020-07-22 22:33:10 +02:00
|
|
|
return "Failed to rehost attachment";
|
|
|
|
}
|
|
|
|
}
|