Skip to content

Commit

Permalink
使用Images.weserv.nl的服务中转图片
Browse files Browse the repository at this point in the history
  • Loading branch information
TransparentLC committed May 26, 2020
1 parent 7b3fe22 commit 758ec29
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 14 deletions.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@

由于自己的服务器用了 Cloudflare 的免费 CDN,然而最近分配到的 IPv4 地址被墙了,所以后端(在墙内)不能用了……

于是试着用 Cloudflare Worker 写了个简单的代理(参见文件 `cfworker_proxy.js`)解决之(〃′▽`)
于是试着用 Cloudflare Worker 写了个~~简单的代理~~(参见文件 `cfworker_proxy.js`)解决之(〃′▽`)~~

直接使用 [Images.weserv.nl](https://images.weserv.nl/) 的服务中转图片,就不需要部署后端了!

#### 2019.12.5

Expand Down
57 changes: 44 additions & 13 deletions cfworker_proxy.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,57 @@ addEventListener('fetch', event => {
* @param {Request} request
*/
async function handleRequest(request) {
let responseConfig = {
const result = {
success: false,
title: '',
cover: '',
};
const responseConfig = {
status: 200,
headers: {
'Access-Control-Allow-Origin': 'https://akarin.dev',
'Content-Type': 'application/json',
},
}
let articleURL = new URL(request.url).searchParams.get('url');
const articleURL = new URL(request.url).searchParams.get('url');

if (!articleURL || !articleURL.startsWith('https://mp.weixin.qq.com')) {
return new Response('{"success":false}', responseConfig);
}
try {
if (!articleURL || !articleURL.startsWith('https://mp.weixin.qq.com')) throw new Error('Invalid URL');

const articleContent = await (
await fetch(articleURL)
).text();

const match = articleContent.match(
/var msg_title = \'(?<title>[\S\s]*?)\'.html\(false\);[\S\s]*?var msg_cdn_url = "(?<cover>[\S\s]*?)";/
);
if (!match) throw new Error('Unable to match content');

let requestURL = new URL('https://i.akarin.dev/misc/get_article_info.php');
requestURL.searchParams.set('url', articleURL);
result.title = match.groups.title;
for (const [k, v] of Object.entries({
'&#96;': '`',
'&#39;': '\'',
'&quot;': '"',
'&nbsp;': ' ',
'&gt;': '>',
'&lt;': '<',
'&yen;': '¥',
})) result.title = result.title.replace(new RegExp(k, 'g'), v);

return new Response(
await (
await fetch(requestURL.toString())
).text(),
responseConfig
);
result.cover = new URL('https://images.weserv.nl');
for (const [k, v] of Object.entries({
url: match.groups.cover,
il: '',
we: '',
h: 360,
q: 70,
})) result.cover.searchParams.set(k, v);
result.cover = result.cover.toString();

result.success = true;
} catch (error) {
console.log(error);
}

return new Response(JSON.stringify(result), responseConfig);
}
1 change: 1 addition & 0 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -780,6 +780,7 @@ <h4>开源就是好</h4>
{
modal: true,
closeOnEsc: false,
history: false,
}
);

Expand Down

0 comments on commit 758ec29

Please sign in to comment.