2024-06-20 01:21:02 +02:00
|
|
|
import type { ContentFormat } from "@lysand-org/federation/types";
|
2024-04-10 04:05:02 +02:00
|
|
|
import { lookup } from "mime-types";
|
2023-11-05 00:59:55 +01:00
|
|
|
|
2024-06-20 01:21:02 +02:00
|
|
|
export const getBestContentType = (content?: ContentFormat) => {
|
2024-06-13 04:26:43 +02:00
|
|
|
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) {
|
2024-06-13 04:26:43 +02:00
|
|
|
if (content[format]) {
|
2024-04-10 04:05:02 +02:00
|
|
|
return { content: content[format].content, format };
|
2024-06-13 04:26:43 +02:00
|
|
|
}
|
2024-04-07 07:30:49 +02:00
|
|
|
}
|
2024-04-10 04:05:02 +02:00
|
|
|
|
|
|
|
|
return { content: "", format: "text/plain" };
|
|
|
|
|
};
|
|
|
|
|
|
2024-06-20 01:21:02 +02:00
|
|
|
export const urlToContentFormat = (url?: string): ContentFormat | null => {
|
2024-06-13 04:26:43 +02:00
|
|
|
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,
|
|
|
|
|
},
|
|
|
|
|
};
|
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,
|
|
|
|
|
},
|
|
|
|
|
};
|
2023-11-05 00:59:55 +01:00
|
|
|
};
|
2024-05-12 03:27:28 +02:00
|
|
|
|
|
|
|
|
export const mimeLookup = async (url: string) => {
|
|
|
|
|
const naiveLookup = lookup(url.replace(new URL(url).search, ""));
|
|
|
|
|
|
2024-06-13 04:26:43 +02:00
|
|
|
if (naiveLookup) {
|
|
|
|
|
return naiveLookup;
|
|
|
|
|
}
|
2024-05-12 03:27:28 +02:00
|
|
|
|
|
|
|
|
const fetchLookup = fetch(url, { method: "HEAD" }).then(
|
|
|
|
|
(response) => response.headers.get("content-type") || "",
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
return fetchLookup;
|
|
|
|
|
};
|