2020-10-01 01:43:38 +03:00
|
|
|
import { downloadFile } from "../../utils";
|
2020-07-22 22:33:10 +02:00
|
|
|
import fs from "fs";
|
2021-06-01 04:33:02 +02:00
|
|
|
import { MessageAttachment, MessageOptions, TextChannel } from "discord.js";
|
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-01 04:33:02 +02:00
|
|
|
const content: MessageOptions = { content: `Rehost of attachment ${attachment.id}`, files: [{ name: attachment.name ? attachment.name : undefined, attachment: await fsp.readFile(downloaded.path)}]}
|
|
|
|
const rehostMessage = await targetChannel.send({ content, split: false });
|
|
|
|
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";
|
|
|
|
}
|
|
|
|
}
|