switch from Content-Length to Range

This commit is contained in:
Amia 2024-05-24 17:15:53 +02:00
parent d96ff463f5
commit 7c62039a09
No known key found for this signature in database
GPG key ID: 9B2D60034D0730F2

View file

@ -35,24 +35,30 @@ const URL_REGEX = new RegExp(
); );
// Cache to avoid excessive requests in component updates // Cache to avoid excessive requests in component updates
const FileSizeCache: Map<string, number> = new Map(); const FileSizeCache: Map<string, boolean> = new Map();
async function getFileSize(url: string) { async function checkFileSize(url: string) {
if (FileSizeCache.has(url)) { if (FileSizeCache.has(url)) {
return FileSizeCache.get(url); return FileSizeCache.get(url);
} }
let size = 0; let belowMaxSize = false;
try { try {
const res = await fetch(url, { method: "HEAD" }); // We cannot check Content-Length due to Access-Control-Expose-Headers.
const contentLength = res.headers.get("Content-Length"); // Instead, we request 1 byte past the size limit, and see if it succeeds.
const res = await fetch(url, {
method: "HEAD",
headers: {
Range: `bytes=${MAX_SVG_SIZE_MB * 1024 * 1024}-${MAX_SVG_SIZE_MB * 1024 * 1024 + 1}`
}
});
if (contentLength) { if (res.status === 416) {
size = parseInt(contentLength); belowMaxSize = true;
} }
} catch (ex) { } } catch (ex) { }
FileSizeCache.set(url, size); FileSizeCache.set(url, belowMaxSize);
return size; return belowMaxSize;
} }
async function getSVGDimensions(svgUrl: string) { async function getSVGDimensions(svgUrl: string) {
@ -168,14 +174,8 @@ export default definePlugin({
if (imageEmbedsCount >= MAX_EMBEDS_PER_MESSAGE) break; if (imageEmbedsCount >= MAX_EMBEDS_PER_MESSAGE) break;
if (existingUrls.has(url)) continue; if (existingUrls.has(url)) continue;
// Check size of files on the cdn. const belowMaxSize = await checkFileSize(url);
// The files under https://discord.com/assets/* don't return Content-Length if (!belowMaxSize) continue;
// but they don't really have to be checked.
const domain = new URL(url).hostname;
if (domain === "cdn.discordapp.com") {
const size = await getFileSize(url);
if (!size || size / 1024 / 1024 > MAX_SVG_SIZE_MB) continue;
}
const { width, height } = await getSVGDimensions(url); const { width, height } = await getSVGDimensions(url);
// @ts-ignore // @ts-ignore