mrmBot-Matrix/utils/image.js

54 lines
1.7 KiB
JavaScript
Raw Normal View History

import fetch from "node-fetch";
import fs from "fs";
import { fileTypeFromBuffer, fileTypeFromFile } from "file-type";
const formats = ["image/jpeg", "image/png", "image/webp", "image/gif", "video/mp4", "video/webm", "video/quicktime"];
export const jobs = {};
export const connections = new Map();
2022-07-26 15:38:42 +00:00
export const servers = JSON.parse(fs.readFileSync(new URL("../config/servers.json", import.meta.url), { encoding: "utf8" })).image;
export async function getType(image, extraReturnTypes) {
if (!image.startsWith("http")) {
const imageType = await fileTypeFromFile(image);
if (imageType && formats.includes(imageType.mime)) {
return imageType.mime;
}
return undefined;
}
let type;
const controller = new AbortController(); // eslint-disable-line no-undef
const timeout = setTimeout(() => {
controller.abort();
}, 25000);
try {
2021-05-22 15:10:42 +00:00
const imageRequest = await fetch(image, {
signal: controller.signal, headers: {
"Range": "bytes=0-1023"
}
});
clearTimeout(timeout);
const size = imageRequest.headers.has("Content-Range") ? imageRequest.headers.get("Content-Range").split("/")[1] : imageRequest.headers.get("Content-Length");
if (parseInt(size) > 26214400 && extraReturnTypes) { // 25 MB
2021-05-07 03:01:30 +00:00
type = "large";
return type;
}
2021-11-20 06:55:25 +00:00
const imageBuffer = await imageRequest.arrayBuffer();
const imageType = await fileTypeFromBuffer(imageBuffer);
if (imageType && formats.includes(imageType.mime)) {
type = imageType.mime;
}
} catch (error) {
if (error.name === "AbortError") {
throw Error("Timed out");
} else {
throw error;
}
} finally {
clearTimeout(timeout);
}
return type;
}