Optimize network latency acquisition and improve the judgment threshold of Chinese users

This commit is contained in:
Tlntin
2023-04-29 10:45:47 +08:00
parent d8091184e5
commit d86a35c25b
3 changed files with 2334 additions and 2296 deletions

47
bin/utils/ip_addr.ts vendored
View File

@@ -1,6 +1,28 @@
import { exec } from 'child_process';
import { promisify } from 'util';
import logger from '@/options/logger.js';
import dns from 'dns';
import http from 'http';
const ping = async (host: string) => {
const lookup = promisify(dns.lookup);
const ip = await lookup(host);
const start = new Date();
return new Promise<number>((resolve, reject) => {
const req = http.get(`http://${ip.address}`, (res) => {
const delay = new Date().getTime() - start.getTime();
res.resume();
resolve(delay);
});
req.on('error', (err) => {
reject(err);
});
});
};
const resolve = promisify(dns.resolve);
@@ -8,27 +30,28 @@ async function isChinaDomain(domain: string): Promise<boolean> {
try {
// 解析域名为IP地址
const [ip] = await resolve(domain);
return await isChinaIP(ip);
return await isChinaIP(ip, domain);
} catch (error) {
// 域名无法解析返回false
logger.info(`${domain} can't be parse, is not in China!`);
return false;
}
}
async function isChinaIP(ip: string): Promise<boolean> {
async function isChinaIP(ip: string, domain: string): Promise<boolean> {
return new Promise((resolve, reject) => {
exec(`ping -c 1 -w 1 ${ip}`, (error, stdout, stderr) => {
if (error) {
// exec(`ping -c -w 1 ${ip}`, (error, stdout, stderr) => {
ping(ip)
.then((declay)=>{
logger.info(`${domain} latency is ${declay} ms`);
// 判断延迟是否超过500ms
resolve(declay > 500);
})
.catch((error)=>{
// 命令执行出错返回false
logger.info(`ping ${domain} failed!, is not in China!`);
resolve(false);
} else {
// 解析输出信息,提取延迟值
const match = stdout.match(/time=(\d+\.\d+) ms/);
const latency = match ? parseFloat(match[1]) : 0;
// 判断延迟是否超过100ms
resolve(latency > 100);
}
});
})
});
}