server/utils/content_types.ts

65 lines
1.6 KiB
TypeScript
Raw Normal View History

import type { ContentFormat } from "@versia/federation/types";
2024-04-10 04:05:02 +02:00
import { lookup } from "mime-types";
import { config } from "~/packages/config-manager";
export const getBestContentType = (content?: ContentFormat | null) => {
if (!content) {
return { content: "", format: "text/plain" };
}
2024-04-10 04:05:02 +02:00
const bestFormatsRanked = [
"text/x.misskeymarkdown",
"text/html",
"text/markdown",
"text/plain",
];
for (const format of bestFormatsRanked) {
if (content[format]) {
2024-04-10 04:05:02 +02:00
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): ContentFormat | null => {
if (!url) {
return null;
}
2024-04-10 04:05:02 +02:00
if (url.startsWith("https://api.dicebear.com/")) {
return {
"image/svg+xml": {
content: url,
remote: true,
2024-04-10 04:05:02 +02:00
},
};
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,
remote: true,
2024-04-10 04:05:02 +02:00
},
};
};
export const mimeLookup = (url: string): Promise<string> => {
const naiveLookup = lookup(url.replace(new URL(url).search, ""));
if (naiveLookup) {
return Promise.resolve(naiveLookup);
}
const fetchLookup = fetch(url, {
method: "HEAD",
2024-08-26 18:15:14 +02:00
// @ts-expect-error Proxy is a Bun-specific feature
proxy: config.http.proxy.address,
}).then((response) => response.headers.get("content-type") || "");
return fetchLookup;
};