增加了代理平台和日志
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
"""代理平台适配器注册表与工厂函数。
|
||||
|
||||
新增平台适配器:
|
||||
1. 在 proxy_platforms/ 下创建 <platform>.py,继承 BaseWhitelistAdapter
|
||||
2. 在本文件导入并注册到 _PLATFORM_REGISTRY
|
||||
3. 在 _PLATFORM_CREDENTIAL_FIELDS 中定义凭据字段
|
||||
"""
|
||||
|
||||
from typing import Optional, Type
|
||||
|
||||
from .base import BaseWhitelistAdapter, get_exit_ip_via_proxy
|
||||
from .xiequ import XiequAdapter
|
||||
from .xkdaili import XkdailiAdapter
|
||||
|
||||
# ── 平台注册表 ──
|
||||
_PLATFORM_REGISTRY: dict[str, Type[BaseWhitelistAdapter]] = {
|
||||
"xiequ": XiequAdapter,
|
||||
"xkdaili": XkdailiAdapter,
|
||||
}
|
||||
|
||||
# ── 平台凭据字段定义(前端动态渲染用)──
|
||||
_PLATFORM_CREDENTIAL_FIELDS: dict[str, list[dict]] = {
|
||||
"xiequ": [
|
||||
{"key": "uid", "label": "UID", "placeholder": "如: 99769"},
|
||||
{"key": "ukey", "label": "UKEY", "placeholder": "如: C99371082B965B70F46DCAA87A04618B"},
|
||||
],
|
||||
"xkdaili": [
|
||||
{"key": "apikey", "label": "API Key", "placeholder": "如: XK86872CC0C85A415461"},
|
||||
{"key": "wl_sign", "label": "白名单签名(Sign)", "placeholder": "白名单接口专用,如: 8953b3082173aa4188e7403e81249027"},
|
||||
{"key": "flag", "label": "Flag", "placeholder": "套餐标识,如: 8"},
|
||||
],
|
||||
}
|
||||
|
||||
# ── 平台显示名 ──
|
||||
_PLATFORM_LABELS: dict[str, str] = {
|
||||
name: cls(dict()).platform_label
|
||||
for name, cls in _PLATFORM_REGISTRY.items()
|
||||
}
|
||||
|
||||
|
||||
def create_adapter(platform: str, credentials: dict) -> Optional[BaseWhitelistAdapter]:
|
||||
"""根据平台标识符和凭据创建适配器实例。"""
|
||||
cls = _PLATFORM_REGISTRY.get(platform)
|
||||
if not cls:
|
||||
return None
|
||||
return cls(credentials)
|
||||
|
||||
|
||||
def get_platform_names() -> list[str]:
|
||||
"""获取所有已注册平台标识符。"""
|
||||
return list(_PLATFORM_REGISTRY.keys())
|
||||
|
||||
|
||||
def get_platform_labels() -> dict[str, str]:
|
||||
"""获取所有平台标识符到中文显示名的映射。"""
|
||||
return dict(_PLATFORM_LABELS)
|
||||
|
||||
|
||||
def get_credential_fields(platform: str) -> list[dict]:
|
||||
"""获取指定平台的凭据字段定义。"""
|
||||
return _PLATFORM_CREDENTIAL_FIELDS.get(platform, [])
|
||||
@@ -0,0 +1,193 @@
|
||||
"""代理平台白名单适配器基类。
|
||||
|
||||
所有平台适配器继承 BaseWhitelistAdapter,实现平台特定的 API 调用。
|
||||
基类提供通用的 sync_ip 逻辑,子类只需实现增删查等原子操作。
|
||||
"""
|
||||
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Optional
|
||||
|
||||
import requests
|
||||
from loguru import logger
|
||||
|
||||
# 全局锁:防止并发白名单同步触发代理服务商限流
|
||||
_whitelist_sync_lock = threading.Lock()
|
||||
|
||||
|
||||
class BaseWhitelistAdapter(ABC):
|
||||
"""白名单适配器基类。
|
||||
|
||||
子类必须实现:
|
||||
- platform_name / platform_label 属性
|
||||
- add_ip / delete_ip / get_whitelist / test_connection 方法
|
||||
基类提供:
|
||||
- sync_ip 通用同步逻辑
|
||||
- get_local_exit_ip 静态方法
|
||||
"""
|
||||
|
||||
MEMO_PREFIX = "douyu_auto"
|
||||
|
||||
@property
|
||||
def memo(self) -> str:
|
||||
return self.MEMO_PREFIX
|
||||
|
||||
@property
|
||||
@abstractmethod
|
||||
def platform_name(self) -> str:
|
||||
"""平台标识符,如 'xiequ', 'xkdaili'"""
|
||||
...
|
||||
|
||||
@property
|
||||
@abstractmethod
|
||||
def platform_label(self) -> str:
|
||||
"""平台中文显示名,如 '协固', '星客'"""
|
||||
...
|
||||
|
||||
@abstractmethod
|
||||
def add_ip(self, ip: str) -> tuple[bool, str]:
|
||||
"""添加IP到白名单。返回 (是否成功, 消息)"""
|
||||
...
|
||||
|
||||
@abstractmethod
|
||||
def delete_ip(self, ip: str) -> tuple[bool, str]:
|
||||
"""删除白名单IP。返回 (是否成功, 消息)"""
|
||||
...
|
||||
|
||||
@abstractmethod
|
||||
def get_whitelist(self) -> list[dict]:
|
||||
"""获取白名单列表。返回 [{"ip": "x.x.x.x", "memo": "备注"}, ...]
|
||||
|
||||
如果平台不支持查询接口,返回空列表。
|
||||
"""
|
||||
...
|
||||
|
||||
@abstractmethod
|
||||
def test_connection(self) -> tuple[bool, str]:
|
||||
"""测试API连接。返回 (是否成功, 消息)"""
|
||||
...
|
||||
|
||||
def sync_ip(self, current_ip: str, keep_recent: int = 3) -> tuple[bool, str]:
|
||||
"""
|
||||
通用白名单同步逻辑(线程安全)。
|
||||
|
||||
策略:
|
||||
- 当前IP已在白名单(同备注),无需操作
|
||||
- 当前IP不在白名单,添加
|
||||
- 超过 keep_recent 个同备注IP时,删除最老的
|
||||
- 当前IP已存在但备注不同,不处理
|
||||
|
||||
Args:
|
||||
current_ip: 当前出口IP
|
||||
keep_recent: 保留的同备注IP数量上限
|
||||
|
||||
Returns:
|
||||
(是否成功, 消息)
|
||||
"""
|
||||
with _whitelist_sync_lock:
|
||||
try:
|
||||
records = self.get_whitelist()
|
||||
|
||||
# 不支持查询的平台,直接尝试添加
|
||||
if records is None:
|
||||
ok, msg = self.add_ip(current_ip)
|
||||
if ok:
|
||||
return True, f"白名单IP已添加: {current_ip}"
|
||||
# 添加失败但提示已存在,视为成功
|
||||
if "已存在" in msg or "exist" in msg.lower():
|
||||
return True, f"白名单IP已存在: {current_ip}"
|
||||
return False, f"白名单添加失败: {msg}"
|
||||
|
||||
memo_records = [r for r in records if r.get("memo") == self.memo]
|
||||
memo_ips = [r.get("ip") for r in memo_records]
|
||||
|
||||
# 当前IP已在白名单(同备注),无需操作
|
||||
if current_ip in memo_ips:
|
||||
msg = f"白名单IP已是最新的: {current_ip}"
|
||||
logger.info(msg)
|
||||
return True, msg
|
||||
|
||||
# 当前IP已存在但备注不同,不处理
|
||||
if any(r.get('ip') == current_ip for r in records):
|
||||
logger.info(f"白名单IP {current_ip} 已存在(备注不同),无需重复添加")
|
||||
return True, f"白名单IP已存在: {current_ip}"
|
||||
|
||||
# 超过上限,删除最老的
|
||||
if len(memo_ips) >= keep_recent:
|
||||
to_delete = memo_ips[:len(memo_ips) - keep_recent + 1]
|
||||
for old_ip in to_delete:
|
||||
logger.info(f"白名单同备注IP超限,删除旧的: {old_ip}")
|
||||
self.delete_ip(old_ip)
|
||||
time.sleep(1)
|
||||
|
||||
# 添加新IP
|
||||
logger.info(f"白名单添加新出口IP: {current_ip} (当前 {len(memo_ips)} 个同备注)")
|
||||
ok, resp = self.add_ip(current_ip)
|
||||
if ok:
|
||||
msg = f"白名单IP已添加: {current_ip}"
|
||||
logger.info(msg)
|
||||
return True, msg
|
||||
|
||||
return False, f"白名单添加失败,API响应: {resp}"
|
||||
|
||||
except Exception as e:
|
||||
msg = f"白名单同步失败: {e}"
|
||||
logger.error(msg)
|
||||
return False, msg
|
||||
|
||||
@staticmethod
|
||||
def get_local_exit_ip() -> Optional[str]:
|
||||
"""获取本机当前公网出口IP(不走代理)。"""
|
||||
return _get_local_exit_ip()
|
||||
|
||||
|
||||
def _get_local_exit_ip() -> Optional[str]:
|
||||
"""获取本机当前公网出口IP(不走代理)。"""
|
||||
targets = [
|
||||
"https://myip.ipip.net",
|
||||
"https://4.ipw.cn",
|
||||
"https://api.ipify.org",
|
||||
]
|
||||
for url in targets:
|
||||
try:
|
||||
response = requests.get(url, timeout=8, headers={"User-Agent": "Mozilla/5.0"})
|
||||
response.raise_for_status()
|
||||
text = response.text.strip()
|
||||
match = re.search(r'(\d{1,3}(?:\.\d{1,3}){3})', text)
|
||||
if match:
|
||||
return match.group(1)
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def get_exit_ip_via_proxy(proxy: str) -> Optional[str]:
|
||||
"""通过代理获取出口IP。"""
|
||||
targets = [
|
||||
"https://qifu-api.baidubce.com/ip/local/geo/v1/district",
|
||||
"https://myip.ipip.net",
|
||||
"https://4.ipw.cn",
|
||||
]
|
||||
proxies = {"http": proxy, "https": proxy}
|
||||
for url in targets:
|
||||
try:
|
||||
response = requests.get(
|
||||
url, proxies=proxies, timeout=6,
|
||||
headers={"User-Agent": "Mozilla/5.0"},
|
||||
)
|
||||
response.raise_for_status()
|
||||
content_type = response.headers.get("content-type", "").lower()
|
||||
if "json" in content_type:
|
||||
data = response.json()
|
||||
ip = data.get("ip") or data.get("origin")
|
||||
if ip:
|
||||
return str(ip).split(",")[0].strip()
|
||||
text = response.text.strip()
|
||||
match = re.search(r"(\d{1,3}(?:\.\d{1,3}){3})", text)
|
||||
if match:
|
||||
return match.group(1)
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
@@ -0,0 +1,159 @@
|
||||
"""携趣代理(xiequ)白名单适配器。
|
||||
|
||||
从 core.douyu.whitelist.WhitelistManager 迁移而来。
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import requests
|
||||
from loguru import logger
|
||||
|
||||
from .base import BaseWhitelistAdapter
|
||||
|
||||
|
||||
class XiequAdapter(BaseWhitelistAdapter):
|
||||
"""携趣代理白名单适配器。
|
||||
|
||||
API格式:
|
||||
基础URL: http://op.xiequ.cn/IpWhiteList.aspx
|
||||
认证参数: uid + ukey
|
||||
操作区分: act=add / del / getjson
|
||||
"""
|
||||
|
||||
BASE_URL = "http://op.xiequ.cn/IpWhiteList.aspx"
|
||||
|
||||
def __init__(self, credentials: dict):
|
||||
self.uid = credentials.get("uid", "")
|
||||
self.ukey = credentials.get("ukey", "")
|
||||
|
||||
@property
|
||||
def platform_name(self) -> str:
|
||||
return "xiequ"
|
||||
|
||||
@property
|
||||
def platform_label(self) -> str:
|
||||
return "携趣"
|
||||
|
||||
def _build_url(self, **params) -> str:
|
||||
"""构建请求URL"""
|
||||
base_params = {"uid": self.uid, "ukey": self.ukey}
|
||||
base_params.update(params)
|
||||
return f"{self.BASE_URL}?{urlencode(base_params)}"
|
||||
|
||||
def get_whitelist(self) -> list[dict]:
|
||||
"""
|
||||
获取白名单列表。
|
||||
|
||||
协固原始格式: [{"IP": "x.x.x.x", "MEMO": "备注"}, ...]
|
||||
统一格式: [{"ip": "x.x.x.x", "memo": "备注"}, ...]
|
||||
"""
|
||||
try:
|
||||
url = self._build_url(act="getjson")
|
||||
response = requests.get(url, timeout=10)
|
||||
response.raise_for_status()
|
||||
|
||||
text = response.text.strip()
|
||||
if not text or text == "[]":
|
||||
return []
|
||||
|
||||
data = json.loads(text)
|
||||
if isinstance(data, dict):
|
||||
data = data.get("data", [])
|
||||
if not isinstance(data, list):
|
||||
return []
|
||||
|
||||
# 映射到统一格式
|
||||
return [
|
||||
{"ip": r.get("IP", r.get("ip", "")), "memo": r.get("MEMO", r.get("memo", ""))}
|
||||
for r in data
|
||||
if r.get("IP") or r.get("ip")
|
||||
]
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"获取白名单失败: {e}")
|
||||
return []
|
||||
|
||||
def add_ip(self, ip: str, retry: bool = True) -> tuple[bool, str]:
|
||||
"""添加IP到白名单。"""
|
||||
try:
|
||||
url = self._build_url(act="add", ip=ip, meno=self.memo)
|
||||
response = requests.get(url, timeout=10)
|
||||
response.raise_for_status()
|
||||
|
||||
text = response.text.strip()
|
||||
logger.debug(f"添加白名单响应: {text}")
|
||||
|
||||
if "ok" in text.lower() or "success" in text.lower() or "添加成功" in text:
|
||||
logger.info(f"白名单添加成功: {ip} (备注: {self.memo})")
|
||||
return True, text
|
||||
|
||||
if "已存在" in text or "exist" in text.lower() or "IpRep" in text:
|
||||
logger.info(f"白名单已存在: {ip}")
|
||||
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, text
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"添加白名单失败: {e}")
|
||||
return False, str(e)
|
||||
|
||||
def delete_ip(self, ip: str) -> tuple[bool, str]:
|
||||
"""删除白名单IP。"""
|
||||
try:
|
||||
url = self._build_url(act="del", ip=ip)
|
||||
response = requests.get(url, timeout=10)
|
||||
response.raise_for_status()
|
||||
|
||||
text = response.text.strip()
|
||||
logger.debug(f"删除白名单响应: {text}")
|
||||
|
||||
if "ok" in text.lower() or "success" in text.lower() or "删除成功" in text:
|
||||
logger.info(f"白名单删除成功: {ip}")
|
||||
return True, text
|
||||
|
||||
logger.warning(f"白名单删除结果: {text}")
|
||||
return False, text
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"删除白名单失败: {e}")
|
||||
return False, str(e)
|
||||
|
||||
def test_connection(self) -> tuple[bool, str]:
|
||||
"""测试白名单API连接。"""
|
||||
try:
|
||||
records = self.get_whitelist()
|
||||
count = len(records)
|
||||
my_records = [r for r in records if r.get("memo", "").startswith(self.MEMO_PREFIX)]
|
||||
|
||||
msg = f"连接成功,白名单共 {count} 条记录,其中本机相关 {len(my_records)} 条"
|
||||
logger.info(msg)
|
||||
return True, msg
|
||||
|
||||
except Exception as e:
|
||||
msg = f"连接失败: {e}"
|
||||
logger.error(msg)
|
||||
return False, msg
|
||||
@@ -0,0 +1,162 @@
|
||||
"""星空代理(xkdaili)白名单适配器。
|
||||
|
||||
API格式:
|
||||
基础URL: http://api2.xkdaili.com/tools/XApi.ashx
|
||||
白名单认证参数: apikey + sign(白名单专用) + flag
|
||||
获取代理认证参数: apikey + sign(提取专用) — 由用户在代理API地址中填写完整URL
|
||||
|
||||
白名单接口的 sign 和获取代理的 sign 不同!
|
||||
|
||||
响应格式:
|
||||
status=100: 操作成功
|
||||
status=508: 白名单已存在(视为成功)
|
||||
status=202: 秘钥验证失败
|
||||
status=808: 其它错误
|
||||
|
||||
注意:没有查询白名单列表的接口
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
import requests
|
||||
from loguru import logger
|
||||
|
||||
from .base import BaseWhitelistAdapter
|
||||
|
||||
|
||||
class XkdailiAdapter(BaseWhitelistAdapter):
|
||||
"""星空代理(xkdaili)白名单适配器。"""
|
||||
|
||||
BASE_URL = "http://api2.xkdaili.com/tools/XApi.ashx"
|
||||
|
||||
def __init__(self, credentials: dict):
|
||||
self.apikey = credentials.get("apikey", "")
|
||||
self.wl_sign = credentials.get("wl_sign", "")
|
||||
self.flag = credentials.get("flag", "")
|
||||
|
||||
@property
|
||||
def platform_name(self) -> str:
|
||||
return "xkdaili"
|
||||
|
||||
@property
|
||||
def platform_label(self) -> str:
|
||||
return "星空"
|
||||
|
||||
def _build_url(self, **params) -> str:
|
||||
"""构建白名单请求URL"""
|
||||
base_params = {
|
||||
"apikey": self.apikey,
|
||||
"sign": self.wl_sign,
|
||||
"flag": self.flag,
|
||||
}
|
||||
base_params.update(params)
|
||||
from urllib.parse import urlencode
|
||||
return f"{self.BASE_URL}?{urlencode(base_params)}"
|
||||
|
||||
def _parse_response(self, text: str) -> tuple[bool, str]:
|
||||
"""解析星空API响应。
|
||||
|
||||
status=100: 成功
|
||||
status=508: 白名单已存在(视为成功)
|
||||
status=202: 秘钥验证失败
|
||||
status=808: 其它错误
|
||||
"""
|
||||
try:
|
||||
data = json.loads(text)
|
||||
status = data.get("status", -1)
|
||||
info = data.get("info", "")
|
||||
|
||||
# 100=成功
|
||||
if status == 100:
|
||||
return True, info
|
||||
|
||||
# 508=已存在,视为成功
|
||||
if status == 508:
|
||||
return True, info
|
||||
|
||||
# 202=秘钥验证失败
|
||||
if status == 202:
|
||||
return False, f"认证失败: {info}"
|
||||
|
||||
# 其他错误
|
||||
return False, f"失败(status={status}): {info}"
|
||||
|
||||
except (json.JSONDecodeError, ValueError):
|
||||
# 非JSON响应,按文本判断
|
||||
if "成功" in text or "ok" in text.lower():
|
||||
return True, text
|
||||
if "已存在" in text:
|
||||
return True, text
|
||||
return False, text
|
||||
|
||||
def get_whitelist(self) -> list[dict]:
|
||||
"""
|
||||
星空不支持查询白名单列表,返回空列表。
|
||||
|
||||
sync_ip 会检测到空列表后直接走添加逻辑。
|
||||
"""
|
||||
return []
|
||||
|
||||
def add_ip(self, ip: str) -> tuple[bool, str]:
|
||||
"""添加IP到白名单。多个IP用英文逗号隔开。"""
|
||||
try:
|
||||
url = self._build_url(type="addwhiteip", ip=ip)
|
||||
response = requests.get(url, timeout=10)
|
||||
response.raise_for_status()
|
||||
|
||||
text = response.text.strip()
|
||||
logger.debug(f"星空添加白名单响应: {text}")
|
||||
|
||||
ok, msg = self._parse_response(text)
|
||||
if ok:
|
||||
logger.info(f"星空白名单添加成功: {ip} - {msg}")
|
||||
else:
|
||||
logger.warning(f"星空白名单添加失败: {msg}")
|
||||
return ok, msg
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"星空添加白名单失败: {e}")
|
||||
return False, str(e)
|
||||
|
||||
def delete_ip(self, ip: str) -> tuple[bool, str]:
|
||||
"""删除白名单IP。多个IP用英文逗号隔开。"""
|
||||
try:
|
||||
url = self._build_url(type="delwhiteip", ip=ip)
|
||||
response = requests.get(url, timeout=10)
|
||||
response.raise_for_status()
|
||||
|
||||
text = response.text.strip()
|
||||
logger.debug(f"星空删除白名单响应: {text}")
|
||||
|
||||
ok, msg = self._parse_response(text)
|
||||
if ok:
|
||||
logger.info(f"星空白名单删除成功: {ip} - {msg}")
|
||||
else:
|
||||
logger.warning(f"星空白名单删除失败: {msg}")
|
||||
return ok, msg
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"星空删除白名单失败: {e}")
|
||||
return False, str(e)
|
||||
|
||||
def test_connection(self) -> tuple[bool, str]:
|
||||
"""测试白名单API连接。"""
|
||||
try:
|
||||
# 尝试添加无效IP来验证认证
|
||||
url = self._build_url(type="addwhiteip", ip="0.0.0.0")
|
||||
response = requests.get(url, timeout=10)
|
||||
response.raise_for_status()
|
||||
|
||||
text = response.text.strip()
|
||||
ok, msg = self._parse_response(text)
|
||||
|
||||
if ok:
|
||||
return True, "连接成功,API认证正常"
|
||||
# 认证失败
|
||||
if "认证失败" in msg:
|
||||
return False, msg
|
||||
# 其他错误(如无效IP),说明认证通过了
|
||||
return True, f"连接成功,API可访问: {msg}"
|
||||
|
||||
except Exception as e:
|
||||
return False, f"连接失败: {e}"
|
||||
Reference in New Issue
Block a user