async function getWikipediaInfo(url: string) {
const title = url.split("/wiki/")[1];
const apiUrl =
`https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts|pageimages&exintro=1&explaintext=1&titles=${title}&pithumbsize=300`;
try {
const response = await fetch(apiUrl);
const data = await response.json();
const page = Object.values(data.query.pages)[0] as any;
return {
title: page.title,
description: page.extract,
imageUrl: page.thumbnail?.source || null,
};
} catch (error) {
console.error("Error fetching Wikipedia data:", error);
return null;
}
}
export default async function(req: Request): Promise<Response> {
const url = new URL(req.url);
const path = url.pathname.replace(/^\/proxy/, "");
const wikipediaUrl = `https://en.wikipedia.org${path}`;
const { title, description, imageUrl } = await getWikipediaInfo(wikipediaUrl);
const ogMetaTags = `
<meta property="twitter:title" content="${title}">
<meta property="og:type" content="article">
<meta property="og:description" content="">
<meta property="twitter:description" content="${description}">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://upload.wikimedia.org/wikipedia/commons/thumb/8/80/Wikipedia-logo-v2.svg/300px-Wikipedia-logo-v2.svg.png">
<meta property="og:site_name" content="Wikipedia">
<meta property="og:image" content="https://upload.wikimedia.org/wikipedia/commons/thumb/8/80/Wikipedia-logo-v2.svg/300px-Wikipedia-logo-v2.svg.png">
<meta property="og:url" content="${wikipediaUrl}">
<link rel="canonical" href="${wikipediaUrl}">
<meta name="description" content="${description}">
`;
const redirectHtml = `
<html>
<head>
${ogMetaTags}
<script type="text/javascript">
setTimeout(function() {
window.location.href = "${wikipediaUrl}";
}, 0);
</script>
</head>
<body>
Redirecting...
</body>
</html>
`;
return new Response(redirectHtml, {
headers: { "Content-Type": "text/html" },
});
}