1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
async function getWikipediaInfo(url: string) {
// Extract the title from the URL
const title = url.split("/wiki/")[1];
// Construct the API URL
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();
// Extract page info
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" },
});
}