From 871b1c4d9d3dea39f8d80483c3f7dfd77b55eeea Mon Sep 17 00:00:00 2001 From: soruly Date: Sat, 8 Aug 2020 21:38:27 +0800 Subject: Support Content-Type detection --- api/image-proxy.ts | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) (limited to 'api') diff --git a/api/image-proxy.ts b/api/image-proxy.ts index cf71ac9..3bd88c8 100644 --- a/api/image-proxy.ts +++ b/api/image-proxy.ts @@ -26,11 +26,28 @@ export default async (request: NowRequest, response: NowResponse) => { return response.status(res.status).send(await res.text()); } - if (!["image", "video"].includes(res.headers.get("Content-Type").split("/")[0].toLowerCase())) { - return response.status(400).send("Error: Content-Type is not image or video"); + if (["image", "video"].includes(res.headers.get("Content-Type").split("/")[0].toLowerCase())) { + response.setHeader("Content-Type", res.headers.get("Content-Type")); + } else if (res.headers.get("Content-Type").toLowerCase() === "application/octet-stream") { + const match = imageURL.match(/\.(\w{3,4})($|\?)/); + if (!match) return response.status(400).send("Error: Cannot determine Content-Type"); + const contentType = { + mp4: "video/mp4", + mpeg: "video/mpeg", + webm: "video/webm", + mkv: "video/x-matroska", + bmp: "image/bmp", + gif: "image/gif", + jpg: "image/jpeg", + jpeg: "image/jpeg", + png: "image/png", + webp: "image/webp", + }[match[1]]; + if (!contentType) return response.status(400).send("Error: Unknown Content-Type"); + response.setHeader("Content-Type", contentType); + } else { + return response.status(400).send("Error: Unsupported Content-Type"); } - response.setHeader("Content-Type", res.headers.get("Content-Type")); - return response.status(200).send(await res.buffer()); }; -- cgit v1.2.3