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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
| const HEADERS = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36 (check-flink/1.0; +https://绑定的域名/bot)", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Language": "zh-CN,zh;q=0.9", "Accept-Encoding": "gzip, deflate, br", "Connection": "keep-alive", "X-Check-Flink": "1.0" };
const SOURCE_HEADERS = { "Accept": "application/json", "Referer": "https://绑定的域名/", "Origin": "https://绑定的域名", "Accept-Language": "zh-CN,zh;q=0.9", "sec-ch-ua": "\"Chromium\";v=\"122\", \"Not(A:Brand\";v=\"24\", \"Google Chrome\";v=\"122\"", "sec-ch-ua-mobile": "?0", "sec-ch-ua-platform": "\"Windows\"", "X-Check-Flink": "1.0" };
const RAW_HEADERS = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 (check-flink/1.0; +https://link.ityr.xyz/bot)", "Accept": "application/json", "X-Check-Flink": "1.0" };
const SOURCE_URL = '你的json文件'; const CACHE_KEY = 'latest_status'; const FAIL_COUNT_KEY = 'fail_counts'; const CF_STATUS_KEY = 'cloudflare_status'; const XIAOXIAO_STATUS_KEY = 'xiaoxiao_status';
function formatShanghaiTime(date) { const shanghaiDate = new Date(date); shanghaiDate.setHours(shanghaiDate.getHours() + 8); const year = shanghaiDate.getFullYear(); const month = String(shanghaiDate.getMonth() + 1).padStart(2, '0'); const day = String(shanghaiDate.getDate()).padStart(2, '0'); const hours = String(shanghaiDate.getHours()).padStart(2, '0'); const minutes = String(shanghaiDate.getMinutes()).padStart(2, '0'); const seconds = String(shanghaiDate.getSeconds()).padStart(2, '0'); return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`; }
async function fetchSourceLinks() { try { const response = await fetch(SOURCE_URL, { headers: SOURCE_HEADERS, redirect: 'follow' }); if (!response.ok) { throw new Error(`获取源数据失败: HTTP ${response.status}`); } const data = await response.json(); return data; } catch (error) { console.error(`fetchSourceLinks 错误: ${error.message}`); throw new Error(`获取源数据失败: ${error.message}`); } }
async function checkLinkDirectly(url) { try { const startTime = Date.now(); const response = await fetch(url, { headers: HEADERS, redirect: 'follow', cf: { cacheTtl: 0 } }); const latency = Math.round((Date.now() - startTime) / 10) / 100; return { success: response.status === 200, latency: response.status === 200 ? latency : -1, status: response.status }; } catch (error) { console.error(`checkLinkDirectly 错误 (${url}): ${error.message}`); return { success: false, latency: -1, status: 0, error: error.message }; } }
async function batchProcess(items, batchSize, processor) { const results = []; for (let i = 0; i < items.length; i += batchSize) { const batch = items.slice(i, i + batchSize); const batchResults = await Promise.all(batch.map(processor)); results.push(...batchResults); if (i + batchSize < items.length) { await new Promise(resolve => setTimeout(resolve, 200)); } } return results; }
async function checkWithAPI(items) { const results = []; const xiaoxiaoStatus = {}; const batchSize = 10; const processItem = async (item) => { const url = item.link; if (!url) { return { ...item, success: false, latency: -1, needDirectCheck: true }; }
try { const apiUrl = `https://v2.xxapi.cn/api/status?url=${encodeURIComponent(url)}`; const response = await fetch(apiUrl, { headers: SOURCE_HEADERS, timeout: 30000, cf: { cacheTtl: 0 } });
if (response.ok) { const data = await response.json(); const statusCode = parseInt(data.data); const success = parseInt(data.code) === 200 && (statusCode >= 200 && statusCode < 400); xiaoxiaoStatus[url] = { success, status: statusCode, apiStatus: parseInt(data.code), latency: success ? (data.latency || 0) : -1, timestamp: formatShanghaiTime(new Date()) };
const needDirectCheck = !success;
return { ...item, success, latency: success ? (data.latency || 0) : -1, needDirectCheck }; } else { xiaoxiaoStatus[url] = { success: false, status: 0, apiStatus: response.status, latency: -1, timestamp: formatShanghaiTime(new Date()) }; return { ...item, success: false, latency: -1, needDirectCheck: true }; } } catch (error) { console.error(`checkWithAPI 错误 (${url}): ${error.message}`); xiaoxiaoStatus[url] = { success: false, status: 0, apiStatus: 0, latency: -1, error: error.message, timestamp: formatShanghaiTime(new Date()) }; return { ...item, success: false, latency: -1, needDirectCheck: true }; } };
const processedResults = await batchProcess(items, batchSize, processItem); results.push(...processedResults); return { results, xiaoxiaoStatus }; }
async function checkAllLinks(env) { try { const sourceData = await fetchSourceLinks(); if (!sourceData || !sourceData.link_list || !Array.isArray(sourceData.link_list)) { throw new Error('源数据格式错误'); }
let failCounts = {}; try { const storedFailCounts = await env["links-status"].get(FAIL_COUNT_KEY); if (storedFailCounts) { failCounts = JSON.parse(storedFailCounts); } } catch (error) { console.error(`获取失败计数错误: ${error.message}`); failCounts = {}; }
const linksToCheck = sourceData.link_list; const cfStatus = {}; const { results: apiResults, xiaoxiaoStatus } = await checkWithAPI(linksToCheck); const needDirectCheck = apiResults.filter(item => item.needDirectCheck); const batchSize = 10; const processDirectCheck = async (item) => { const result = await checkLinkDirectly(item.link); cfStatus[item.link] = { success: result.success, status: result.status, latency: result.latency, error: result.error, timestamp: formatShanghaiTime(new Date()) };
return { name: item.name, link: item.link, latency: result.latency, success: result.success, fail_count: failCounts[item.link] || 0 }; };
const directResults = needDirectCheck.length > 0 ? await batchProcess(needDirectCheck, batchSize, processDirectCheck) : [];
const finalResults = apiResults.map(item => { if (!item.needDirectCheck) { return { name: item.name, link: item.link, latency: item.latency, fail_count: item.success ? 0 : (failCounts[item.link] || 0) + 1 }; } else { const directResult = directResults.find(r => r.link === item.link); if (directResult) { return { name: item.name, link: item.link, latency: directResult.latency, fail_count: directResult.success ? 0 : (failCounts[item.link] || 0) + 1 }; } return { name: item.name, link: item.link, latency: -1, fail_count: (failCounts[item.link] || 0) + 1 }; } });
finalResults.forEach(item => { if (item.fail_count > 0) { failCounts[item.link] = item.fail_count; } else { delete failCounts[item.link]; } });
const now = new Date();
await Promise.all([ env["links-status"].put(FAIL_COUNT_KEY, JSON.stringify(failCounts)), env["links-status"].put(CF_STATUS_KEY, JSON.stringify(cfStatus)), env["links-status"].put(XIAOXIAO_STATUS_KEY, JSON.stringify(xiaoxiaoStatus)) ]);
const accessible = finalResults.filter(r => r.fail_count === 0).length; const resultData = { timestamp: formatShanghaiTime(now), accessible_count: accessible, inaccessible_count: finalResults.length - accessible, total_count: finalResults.length, link_status: finalResults }; return resultData; } catch (error) { console.error(`checkAllLinks 错误: ${error.message}`); throw error; } }
async function handleScheduled(env) { try { const result = await checkAllLinks(env); await env["links-status"].put(CACHE_KEY, JSON.stringify(result)); return result; } catch (error) { console.error(`定时任务错误: ${error.message}`); return { error: `定时任务失败: ${error.message}` }; } }
async function handleRequest(request, env) { try { const url = new URL(request.url); if (url.pathname === '/') { const responseData = { code: 200, msg: "获取成功", data: { "/status": "检测返回", "/status/cf": "CF检测返回", "/status/xiaoxiao": "API检测返回", "/health": "运行状态" } }; return new Response( JSON.stringify(responseData), { status: 200, headers: { "Content-Type": "application/json", "Cache-Control": "no-cache" } } ); } if (url.pathname === '/health') { return new Response('OK', { status: 200 }); } if (url.pathname === '/status') { const cachedResult = await env["links-status"].get(CACHE_KEY); if (!cachedResult) { const result = await handleScheduled(env); if (result.error) { throw new Error(result.error); } return new Response(JSON.stringify(result), { headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-cache' } }); } return new Response(cachedResult, { headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-cache' } }); }
if (url.pathname === '/status/cf') { const cfStatus = await env["links-status"].get(CF_STATUS_KEY); return new Response(cfStatus || '{}', { headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-cache' } }); }
if (url.pathname === '/status/xiaoxiao') { const xiaoxiaoStatus = await env["links-status"].get(XIAOXIAO_STATUS_KEY); return new Response(xiaoxiaoStatus || '{}', { headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-cache' } }); } return new Response('Not Found', { status: 404 }); } catch (error) { console.error(`handleRequest 错误: ${error.message}`); return new Response(JSON.stringify({ error: '处理请求失败', detail: error.message }), { status: 500, headers: { 'Content-Type': 'application/json' } }); } }
export default { async fetch(request, env, ctx) { return handleRequest(request, env); }, async scheduled(event, env, ctx) { return handleScheduled(env); } };
|