优化代理配置

This commit is contained in:
yml2213
2026-06-22 13:59:03 +08:00
parent 63c1ffa046
commit b08f0a647d
10 changed files with 577 additions and 197 deletions
+34 -12
View File
@@ -2,6 +2,7 @@
import json
import re
import time
from typing import Optional
from urllib.parse import urlencode
@@ -65,12 +66,12 @@ class WhitelistManager:
logger.error(f"获取白名单失败: {e}")
return []
def add_ip(self, ip: str) -> bool:
def add_ip(self, ip: str, retry: bool = True) -> tuple[bool, str]:
"""
添加IP到白名单
Args:
ip: 要添加的IP地址
Returns:
(是否成功, API原始响应)
"""
try:
url = self._build_url(act="add", ip=ip, meno=self._memo)
@@ -80,22 +81,40 @@ class WhitelistManager:
text = response.text.strip()
logger.debug(f"添加白名单响应: {text}")
# 成功通常返回 "ok" 或类似信息
if "ok" in text.lower() or "success" in text.lower() or "添加成功" in text:
logger.info(f"白名单添加成功: {ip} (备注: {self._memo})")
return True
return True, text
# 检查是否已存在
if "已存在" in text or "exist" in text.lower():
if "已存在" in text or "exist" in text.lower() or "IpRep" in text:
logger.info(f"白名单已存在: {ip}")
return True
return True, text
# 频率限制,等待后重试一次
if retry and ("频率过快" in text or "稍后" in text):
wait = 5
match = re.search(r'(\d+)\s*秒', text)
if match:
wait = int(match.group(1))
logger.info(f"白名单添加被限流,等待 {wait} 秒后重试...")
time.sleep(wait)
return self.add_ip(ip, retry=False)
# UKEY 错误
if "Err:Key" in text:
logger.error("白名单UKEY错误,请检查配置")
return False, "UKEY错误,请检查白名单配置"
# 超出白名单数量限制
if "Err:Max" in text or "超过" in text or "上限" in text:
logger.error(f"白名单数量超限: {text}")
return False, f"白名单数量超限: {text}"
logger.warning(f"白名单添加结果: {text}")
return False
return False, text
except Exception as e:
logger.error(f"添加白名单失败: {e}")
return False
return False, str(e)
def delete_ip(self, ip: str) -> bool:
"""
@@ -175,15 +194,18 @@ class WhitelistManager:
if existing_ip:
logger.info(f"白名单IP变化: {existing_ip} -> {current_ip}")
self.delete_ip(existing_ip)
time.sleep(1)
# IP已存在但备注不同(或备注为空),先删除后重新添加
records = self.get_whitelist_json()
if any(r.get('IP') == current_ip for r in records):
logger.info(f"白名单IP {current_ip} 已存在但备注不同,删除后重新添加")
self.delete_ip(current_ip)
time.sleep(1)
# 添加新IP
if self.add_ip(current_ip):
ok, resp = self.add_ip(current_ip)
if ok:
if existing_ip:
msg = f"白名单IP已更新: {existing_ip} -> {current_ip}"
else:
@@ -191,7 +213,7 @@ class WhitelistManager:
logger.info(msg)
return True, msg
return False, "白名单添加失败"
return False, f"白名单添加失败API响应: {resp}"
except Exception as e:
msg = f"白名单同步失败: {e}"