server/utils/content_types.ts

55 lines
1.3 KiB
TypeScript
Raw Normal View History

2024-04-10 04:05:02 +02:00
import type * as Lysand from "lysand-types";
import { lookup } from "mime-types";
2024-04-10 04:05:02 +02:00
export const getBestContentType = (content?: Lysand.ContentFormat) => {
if (!content) return { content: "", format: "text/plain" };
const bestFormatsRanked = [
"text/x.misskeymarkdown",
"text/html",
"text/markdown",
"text/plain",
];
for (const format of bestFormatsRanked) {
if (content[format])
return { content: content[format].content, format };
2024-04-07 07:30:49 +02:00
}
2024-04-10 04:05:02 +02:00
return { content: "", format: "text/plain" };
};
export const urlToContentFormat = (
url: string,
): Lysand.ContentFormat | null => {
if (!url) return null;
if (url.startsWith("https://api.dicebear.com/")) {
return {
"image/svg+xml": {
content: url,
},
};
2024-04-07 07:30:49 +02:00
}
2024-04-10 04:05:02 +02:00
const mimeType =
lookup(url.replace(new URL(url).search, "")) ||
"application/octet-stream";
return {
[mimeType]: {
content: url,
},
};
};
export const mimeLookup = async (url: string) => {
const naiveLookup = lookup(url.replace(new URL(url).search, ""));
if (naiveLookup) return naiveLookup;
const fetchLookup = fetch(url, { method: "HEAD" }).then(
(response) => response.headers.get("content-type") || "",
);
return fetchLookup;
};