IPFS previews work without the extension

This commit is contained in:
Eric Allam
2022-06-07 13:37:43 +01:00
parent 2fb902ee01
commit 6df767080a
+24 -5
View File
@@ -37,7 +37,9 @@ async function getPeekalink(link: string): Promise<PreviewResult> {
}
export async function getUriPreview(uri: string): Promise<PreviewResult> {
const head = await headUri(uri);
const url = rewriteUrl(uri);
const head = await headUri(url.href);
// If the url is an image content type, return a preview image
if (
@@ -46,14 +48,14 @@ export async function getUriPreview(uri: string): Promise<PreviewResult> {
contentType.includes(head.contentType)
)
) {
const previewImage = createPreviewImage(uri, head);
const previewImage = createPreviewImage(url.href, head);
return previewImage;
}
// If the url is a json content type, attempt to request the json and return a preview json
if (head?.contentType.includes("application/json")) {
const response = await safeFetch(uri, {
const response = await safeFetch(url.href, {
headers: {
accept: "application/json",
},
@@ -65,10 +67,10 @@ export async function getUriPreview(uri: string): Promise<PreviewResult> {
const jsonBody = await response.json();
return createPreviewJson(uri, jsonBody);
return createPreviewJson(url.href, jsonBody);
}
const peekalinkResult = await getPeekalink(uri);
const peekalinkResult = await getPeekalink(url.href);
return peekalinkResult;
}
@@ -149,3 +151,20 @@ function createPreviewImage(uri: string, head: HeadInfo): PreviewImage {
size: head.contentLength,
};
}
// Rewrites the URL to convert an ipfs: url to use https://ipfs.io/ipfs/
function rewriteUrl(url: URL | string): URL {
const unmodifiedUrl =
typeof url === "string" ? new URL(url) : new URL(url.href);
// Rewrite the URL if it is a relative URL
if (unmodifiedUrl.protocol === "ipfs:") {
return new URL(
`https://ipfs.io/ipfs/${unmodifiedUrl.hostname}${
unmodifiedUrl.pathname.length > 0 ? `/${unmodifiedUrl.pathname}` : ""
}${unmodifiedUrl.search}`
);
}
return unmodifiedUrl;
}