import HOME_HTML from './home.html'; import SCREENSHOT_HTML from './screenshot.html'; export default { async fetch(request, env, ctx) { // 获取请求的 URL 和路径 const url = new URL(request.url); const path = url.pathname; // 路由不同的 API 接口 if (path.startsWith('/api/screenshot')) { return handleScreenshotRequest(url); } // 处理主页的请求 if (path === '/') { return new Response(HOME_HTML, { status: 200, headers: { "content-type": "text/html" } }); } if (path === '/screenshot') { return new Response(SCREENSHOT_HTML, { status: 200, headers: { "content-type": "text/html" } }); } return new Response('Invalid API endpoint', { status: 404 }); } } // 处理 /api/screenshot 请求 async function handleScreenshotRequest(url) { const targetUrl = url.searchParams.get('url') || 'https://www.liushen.fun/'; const width = url.searchParams.get('width') || 400; const height = url.searchParams.get('height') || 250; const method = url.searchParams.get('method') || '1'; // 默认为 mshot 方法 console.log(targetUrl, width, height, method); // 构造第一个截图 API 请求地址 (mshots) const screenshotUrl1 = `https://s0.wp.com/mshots/v1/${encodeURIComponent(targetUrl)}?w=${width}&h=${height}`; // 构造第二个截图 API 请求地址 (urlscan) const screenshotUrl2 = `https://urlscan.io/liveshot/?width=${width}&height=${height}&url=${encodeURIComponent(targetUrl)}`; try { let response; // 根据 method 参数选择首选的截图方式 if (method === '1') { // 请求 mshot response = await fetchWithUA(screenshotUrl1); if (!response.ok) { console.log("mshots failed, trying urlscan"); response = await fetchWithUA(screenshotUrl2); // 如果 mshots 失败,尝试 urlscan } } else { // 请求 urlscan response = await fetchWithUA(screenshotUrl2); if (!response.ok) { console.log("urlscan failed, trying mshots"); response = await fetchWithUA(screenshotUrl1); // 如果 urlscan 失败,尝试 mshots } } // 如果两个 API 都失败,返回 403 错误 if (!response.ok) { console.log("Both APIs failed, returning 403"); return new Response("Both screenshot APIs failed.", { status: 403 }); } return new Response(response.body, response); } catch (error) { // 捕获异常并返回 403 错误 console.log("Error occurred:", error); return new Response("Error occurred while processing the request.", { status: 403 }); } } // 添加带有 User-Agent 的 fetch 方法 async function fetchWithUA(url) { return await fetch(url, { headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' } }); }