Files
live-hub-py/core/douyu/proxy_platforms/base.py
T
2026-08-31 10:55:44 +08:00

205 lines
6.9 KiB
Python

"""代理平台白名单适配器基类。
所有平台适配器继承 BaseWhitelistAdapter,实现平台特定的 API 调用。
基类提供通用的 sync_ip 逻辑,子类只需实现增删查等原子操作。
"""
import re
import threading
import time
from abc import ABC, abstractmethod
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:
if not old_ip:
continue
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: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
msg = f"白名单同步失败: {e}"
logger.error(msg)
return False, msg
@staticmethod
def get_local_exit_ip() -> str | None:
"""获取本机当前公网出口IP(不走代理)。"""
return _get_local_exit_ip()
def _get_local_exit_ip() -> str | None:
"""获取本机当前公网出口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 as exc: # noqa: BLE001
logger.debug(f"本机出口 IP 查询失败: {url}: {exc}")
continue
return None
def get_exit_ip_via_proxy(proxy: str) -> str | None:
"""通过代理获取出口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 as exc: # noqa: BLE001
logger.debug(f"代理出口 IP 查询失败: {url}: {exc}")
continue
return None