fixed 友联监测bug

This commit is contained in:
Vaica committed 2026-01-31 15:14:57 +08:00
1 parent d04f748e85
commit 39b17bc39d
5 files changed
+467 -385

No files matched your search

@@ -34,8 +34,9 @@ ai_comment: >-
这个脚本的核心逻辑是:
- 读取 `themes/Ying/data/links.yaml`。
- 开启 10 个并发线程池,提高检测效率。
- 复用 HTTP/HTTPS 连接(Keep-Alive),减少握手开销。
- 对每个链接发起 `HEAD` 请求(如果失败则重试 `GET`)。
- 如果状态码在 200-400 之间,判定为存活(True),否则为挂了(False)。
- 将结果保存为 `static/link_status.json`。
```javascript
@@ -43,40 +44,73 @@ const fs = require('fs');
const yaml = require('js-yaml');
const axios = require('axios');
const path = require('path');
const https = require('https');
const http = require('http');
// 配置文件路径
const linksPath = path.join(__dirname, '../themes/Ying/data/links.yaml');
// 输出结果路径(直接输出到 static 目录,Hugo 构建时会直接复制到根目录)
const outputPath = path.join(__dirname, '../static/link_status.json');
// 配置并发数和超时
const CONCURRENCY = 10;
const TIMEOUT = 10000;
// 优化 Axios 实例:开启 Keep-Alive 复用连接
const axiosInstance = axios.create({
timeout: TIMEOUT,
maxRedirects: 5,
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
},
validateStatus: (status) => status >= 200 && status < 400
});
async function checkUrl(url) {
try {
await axiosInstance.head(url);
return true;
} catch (error) {
try {
await axiosInstance.get(url);
return true;
} catch (err2) {
return false;
}
}
}
async function checkLinks() {
console.log('Starting link check...');
const start = Date.now();
try {
const fileContents = fs.readFileSync(linksPath, 'utf8');
const data = yaml.load(fileContents);
const blogs = data.blogs.filter(b => b.url);
const results = {};
// 遍历所有友链
const blogs = data.blogs;
for (const blog of blogs) {
try {
// 优先使用 HEAD 请求节省流量
await axios.head(blog.url, { timeout: 10000 });
results[blog.url] = true;
console.log(`[OK] ${blog.name}`);
} catch (error) {
// HEAD 失败尝试 GET
try {
await axios.get(blog.url, { timeout: 10000 });
results[blog.url] = true;
console.log(`[OK] ${blog.name} (GET)`);
} catch (err2) {
results[blog.url] = false;
console.log(`[FAIL] ${blog.name}`);
}
// 并发工作队列
async function worker() {
while (blogs.length > 0) {
const blog = blogs.shift(); // 取出一个任务
const status = await checkUrl(blog.url);
results[blog.url] = status;
console.log(`[${status ? 'OK' : 'FAIL'}] ${blog.name}`);
}
}
// 启动 10 个 Worker 并发处理
const workers = Array(Math.min(blogs.length, CONCURRENCY))
.fill(null)
.map(() => worker());
await Promise.all(workers);
fs.writeFileSync(outputPath, JSON.stringify(results, null, 2));
console.log(`✨ Check finished in ${((Date.now() - start) / 1000).toFixed(2)}s`);
} catch (e) {
console.error(e);
process.exit(1);