feat: 维护中国代理池并支持账号自动均匀使用

This commit is contained in:
2026-11-15 02:18:17 +08:00
parent aa26d00c60
commit ce2d6e08dd
20 changed files with 1733 additions and 162 deletions
+6
View File
@@ -64,13 +64,19 @@ async def lifespan(_app: FastAPI):
load_admin_identity()
stop_refresh = None
study_worker = None
stop_pool = None
if os.environ.get("EUNIV_DISABLE_REFRESH") != "1":
stop_refresh = start_credential_refresh()
from euniv.autostudy import start_autostudy
from euniv.proxy_pool import start_proxy_pool
study_worker = start_autostudy()
stop_pool = start_proxy_pool()
yield
if study_worker is not None:
study_worker.stop()
if stop_pool is not None:
stop_pool.set()
if stop_refresh is not None:
stop_refresh.set()
+143 -58
View File
@@ -27,6 +27,7 @@ from sqlalchemy import select
from euniv.client import EUNIV, STUDY_API, USER_AGENT, EunivClient, SessionExpired, _load_cookies
from euniv.course_workers import of as course_workers_of
from euniv.models import Account, Course
from euniv.proxy import bind_url, is_proxy_failure, uses_pool
from euniv.study_window import window_open
log = logging.getLogger(__name__)
@@ -175,12 +176,15 @@ class StudySession:
"""
def __init__(self, token: str, cookies: list[tuple[str, str, str, str]],
proxy: str | None = None) -> None:
proxy: str | None = None, employee_id: str = "",
use_pool: bool = False) -> None:
from euniv.proxy import parse_proxy
self._token = token
self._initial_cookies = cookies
self._proxy = parse_proxy(proxy)
self._employee_id = employee_id
self._use_pool = use_pool
self._client: httpx.AsyncClient | None = None
async def __aenter__(self) -> "StudySession":
@@ -197,6 +201,43 @@ class StudySession:
if self._client:
await self._client.aclose()
async def _rotate_proxy(self) -> bool:
if not self._use_pool:
return False
from euniv.proxy import parse_proxy
from euniv.proxy_pool import acquire, mark_failed
old = self._proxy
await asyncio.to_thread(mark_failed, self._employee_id, old)
nxt = await asyncio.to_thread(acquire, self._employee_id)
parsed = parse_proxy(nxt)
if parsed == old:
return False
client = httpx.AsyncClient(
timeout=30,
follow_redirects=True,
proxy=parsed,
headers={"User-Agent": USER_AGENT},
)
_load_cookies(client, self._initial_cookies)
prev = self._client
self._client = client
self._proxy = parsed
if prev is not None:
await prev.aclose()
return True
async def _http(self, method: str, url: str, **kw: object) -> httpx.Response:
assert self._client is not None
try:
return await self._client.request(method, url, **kw)
except Exception as exc:
if self._use_pool and self._proxy and is_proxy_failure(exc):
if await self._rotate_proxy():
assert self._client is not None
return await self._client.request(method, url, **kw)
raise
def _api_headers(self) -> dict[str, str]:
return {
"Accept": "application/json, text/plain, */*",
@@ -214,7 +255,7 @@ class StudySession:
extra = kw.pop("headers", None)
if extra and isinstance(extra, dict):
headers.update(extra)
resp = await self._client.request(method, url, headers=headers, **kw)
resp = await self._http(method, url, headers=headers, **kw)
refreshed = resp.headers.get("token") or resp.headers.get("Token")
if refreshed:
self._token = refreshed
@@ -243,9 +284,18 @@ class StudySession:
async def get_encrypt_request(self, body_json: str) -> str:
from euniv.encrypt import fetch_encryption_async
assert self._client is not None
return await fetch_encryption_async(
self._client, body_json, origin=EUNIV, user_agent=USER_AGENT
)
try:
return await fetch_encryption_async(
self._client, body_json, origin=EUNIV, user_agent=USER_AGENT
)
except Exception as exc:
if self._use_pool and self._proxy and is_proxy_failure(exc):
if await self._rotate_proxy():
assert self._client is not None
return await fetch_encryption_async(
self._client, body_json, origin=EUNIV, user_agent=USER_AGENT
)
raise
async def submit_video_heartbeat(self, kid: str, pkg_id: str,
study_time: int, view_schedule: int) -> dict:
@@ -323,7 +373,8 @@ class StudySession:
async def course_page_params(self, path: str) -> dict:
assert self._client is not None
resp = await self._client.get(
resp = await self._http(
"GET",
f"{EUNIV}{path}",
headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"},
)
@@ -346,7 +397,7 @@ class StudySession:
async def scorm_extract_answers(self, kid: str) -> list[dict]:
assert self._client is not None
index_url = f"https://cdn-cos-file.yunxuetang.cn/zt/scorm/{kid}/h5/js/index-scorm.js"
resp = await self._client.get(index_url, headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"})
resp = await self._http("GET", index_url, headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"})
urls: list[str] = []
for m in re.finditer(r'["\']([^"\']+\.oss\.js)["\']', resp.text):
raw = m.group(1)
@@ -361,7 +412,7 @@ class StudySession:
answers: list[dict] = []
for url in urls:
try:
r = await self._client.get(url, headers={"User-Agent": USER_AGENT})
r = await self._http("GET", url, headers={"User-Agent": USER_AGENT})
for block in re.finditer(r'单选题([\s\S]*?)正确答案[::]\s*([A-D])', r.text):
answers.append({"page_url": url, "answer": block.group(2)})
except Exception:
@@ -370,7 +421,8 @@ class StudySession:
async def month_hours_text(self) -> str:
assert self._client is not None
resp = await self._client.get(
resp = await self._http(
"GET",
f"{EUNIV}/study/myperiod.htm",
headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/sty/index.htm"},
)
@@ -524,24 +576,40 @@ async def _study_package(session: StudySession, kid: str, intervals: dict,
# ── 同步准备:用 EunivClient 建立会话,导出 cookies ──
def _prepare_session(employee_id: str, password: str,
credential: dict, proxy: str | None = None
) -> tuple[str, str, str, list[tuple[str, str, str, str]]]:
"""同步:恢复会话并导出 token + cookies。返回 (token, user_id, org_id, cookies)。"""
client = EunivClient(employee_id, password, proxy=proxy)
try:
client.restore(credential)
if not client.credential_alive():
return "", "", "", []
client._ensure_site()
token = client.session_token()
user_id = str(client._profile.get("userId") or "")
org_id = str(client._profile.get("accountId") or "")
cookies: list[tuple[str, str, str, str]] = []
for cookie in client.client.cookies.jar:
cookies.append((cookie.name, cookie.value or "", cookie.domain or "", cookie.path or "/"))
return token, user_id, org_id, cookies
finally:
client.close()
credential: dict, proxy: str | None = None,
use_pool: bool = False
) -> tuple[str, str, str, list[tuple[str, str, str, str]], str | None]:
"""同步:恢复会话并导出 cookies。返回 (token, user_id, org_id, cookies, proxy)。"""
from euniv.proxy_pool import MAX_SWITCHES, acquire, mark_failed
current = proxy
last_exc: BaseException | None = None
for _ in range(MAX_SWITCHES + 1):
client = EunivClient(employee_id, password, proxy=current)
try:
client.restore(credential)
if not client.credential_alive():
return "", "", "", [], current
client._ensure_site()
token = client.session_token()
user_id = str(client._profile.get("userId") or "")
org_id = str(client._profile.get("accountId") or "")
cookies: list[tuple[str, str, str, str]] = []
for cookie in client.client.cookies.jar:
cookies.append((cookie.name, cookie.value or "", cookie.domain or "", cookie.path or "/"))
return token, user_id, org_id, cookies, current
except Exception as exc:
last_exc = exc
if use_pool and current and is_proxy_failure(exc):
mark_failed(employee_id, current, str(exc)[:200])
current = acquire(employee_id)
continue
return "", "", "", [], current
finally:
client.close()
if last_exc is not None:
log.warning("用户 %s 准备会话失败: %s", employee_id, last_exc)
return "", "", "", [], current
# ── Worker 主循环 ──
@@ -603,8 +671,6 @@ class AutoStudyWorker:
}
with SessionLocal() as db:
from euniv.proxy import url_of
users = db.scalars(
select(Account)
.where(Account.credential_cipher != "")
@@ -625,11 +691,19 @@ class AutoStudyWorker:
try:
password = decrypt_secret(row.password_cipher)
credential = json.loads(decrypt_secret(row.credential_cipher))
proxy = url_of(row)
proxy = bind_url(row)
except Exception:
continue
eligible.append(
(row.employee_id, target, password, credential, proxy, course_workers_of(row))
(
row.employee_id,
target,
password,
credential,
proxy,
course_workers_of(row),
uses_pool(row),
)
)
if not course_list:
@@ -647,8 +721,11 @@ class AutoStudyWorker:
sem = asyncio.Semaphore(_MAX_CONCURRENT_USERS)
tasks = [
self._study_user(emp_id, target, pw, cred, proxy, workers, course_list, intervals, auto_mode, sem)
for emp_id, target, pw, cred, proxy, workers in eligible
self._study_user(
emp_id, target, pw, cred, proxy, workers, use_pool,
course_list, intervals, auto_mode, sem,
)
for emp_id, target, pw, cred, proxy, workers, use_pool in eligible
]
results = await asyncio.gather(*tasks, return_exceptions=True)
for emp_id_tuple, result in zip(eligible, results):
@@ -660,34 +737,42 @@ class AutoStudyWorker:
async def _study_user(self, employee_id: str, target: int,
password: str, credential: dict, proxy: str | None,
workers: int, course_list: list, intervals: dict,
workers: int, use_pool: bool, course_list: list, intervals: dict,
auto_mode: bool, sem: asyncio.Semaphore) -> None:
assert self._async_stop is not None
async with sem:
_set_user_status(employee_id, state="准备", course="")
loop = asyncio.get_event_loop()
token, user_id, org_id, cookies = await loop.run_in_executor(
None, _prepare_session, employee_id, password, credential, proxy)
if not token:
_set_user_status(employee_id, state="会话失效")
return
async with StudySession(token, cookies, proxy=proxy) as session:
session._employee_id = employee_id # type: ignore[attr-defined]
_set_user_status(employee_id, state="学习中")
user_stop = asyncio.Event()
hours = HoursWatcher(session, employee_id, target, user_stop)
if await hours.refresh():
try:
async with sem:
_set_user_status(employee_id, state="准备", course="")
loop = asyncio.get_event_loop()
token, user_id, org_id, cookies, proxy = await loop.run_in_executor(
None, _prepare_session, employee_id, password, credential, proxy, use_pool)
if not token:
_set_user_status(employee_id, state="会话失效")
return
ticker = asyncio.create_task(hours.ticker(self._async_stop))
try:
await self._study_courses(
session, employee_id, course_list, intervals,
auto_mode, hours, user_id, org_id, workers)
finally:
ticker.cancel()
with contextlib.suppress(asyncio.CancelledError):
await ticker
async with StudySession(
token, cookies, proxy=proxy, employee_id=employee_id, use_pool=use_pool
) as session:
session._employee_id = employee_id # type: ignore[attr-defined]
_set_user_status(employee_id, state="学习中")
user_stop = asyncio.Event()
hours = HoursWatcher(session, employee_id, target, user_stop)
if await hours.refresh():
return
ticker = asyncio.create_task(hours.ticker(self._async_stop))
try:
await self._study_courses(
session, employee_id, course_list, intervals,
auto_mode, hours, user_id, org_id, workers)
finally:
ticker.cancel()
with contextlib.suppress(asyncio.CancelledError):
await ticker
finally:
if use_pool:
from euniv.proxy_pool import release
release(employee_id)
async def _study_courses(self, session: StudySession, employee_id: str,
course_list: list, intervals: dict,
+214
View File
@@ -0,0 +1,214 @@
"""代理上游采集。新增平台时实现 Collector 并 register。"""
from __future__ import annotations
import json
import logging
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
import httpx
from euniv.proxy import SCHEMES
log = logging.getLogger(__name__)
CHINA = {"cn", "chn", "china", "中国"}
_SOURCE_TITLES = {"proxyhub": "ProxyHub"}
@dataclass(frozen=True)
class ProxyCandidate:
scheme: str
host: str
port: int
country: str = ""
anonymity: str = ""
source: str = ""
class Collector:
name = ""
def collect(self) -> list[ProxyCandidate]:
raise NotImplementedError
_REGISTRY: list[Collector] = []
def register(collector: Collector) -> None:
if collector not in _REGISTRY:
_REGISTRY.append(collector)
def collectors() -> list[Collector]:
return list(_REGISTRY)
def source_title(name: str) -> str:
key = (name or "").strip()
return _SOURCE_TITLES.get(key, key or "未知")
def is_china(country: str | None) -> bool:
text = (country or "").strip()
if not text:
return False
lower = text.lower()
return lower in CHINA or "中国" in text
def collect_all() -> list[ProxyCandidate]:
items: list[ProxyCandidate] = []
seen: set[tuple[str, str, int]] = set()
for collector in collectors():
try:
batch = collector.collect()
except Exception:
log.warning("上游 %s 没有获取到", collector.name, exc_info=True)
continue
for item in batch:
if not is_china(item.country):
continue
key = (item.scheme, item.host, item.port)
if key in seen:
continue
seen.add(key)
items.append(item)
return items
def _normalize_scheme(value: object) -> str:
kind = str(value or "").strip().lower()
if kind == "socks":
kind = "socks5"
return kind if kind in SCHEMES else ""
def _normalize_host(value: object) -> str:
host = str(value or "").strip()
if not host or "://" in host or any(ch.isspace() for ch in host):
return ""
return host[:255]
def _normalize_port(value: object) -> int | None:
try:
port = int(value) # type: ignore[arg-type]
except (TypeError, ValueError):
return None
if not 1 <= port <= 65535:
return None
return port
def parse_proxy_rows(rows: object, source: str) -> list[ProxyCandidate]:
if not isinstance(rows, list):
return []
items: list[ProxyCandidate] = []
for row in rows:
if not isinstance(row, dict):
continue
scheme = _normalize_scheme(row.get("type") or row.get("scheme"))
host = _normalize_host(row.get("ip") or row.get("host"))
port = _normalize_port(row.get("port"))
if not scheme or not host or port is None:
continue
items.append(
ProxyCandidate(
scheme=scheme,
host=host,
port=port,
country=str(row.get("country") or "").strip(),
anonymity=str(row.get("anonymity") or "").strip().lower(),
source=source,
)
)
return items
def parse_proxyhub_result(payload: object) -> list[ProxyCandidate]:
if not isinstance(payload, dict):
return []
result = payload.get("result")
if not isinstance(result, dict) or result.get("isError") is True:
return []
data = result.get("structuredContent")
rows = data.get("proxies") if isinstance(data, dict) else None
if isinstance(rows, list):
return parse_proxy_rows(rows, "proxyhub")
content = result.get("content")
if not isinstance(content, list):
return []
for block in content:
if not isinstance(block, dict):
continue
text = block.get("text")
if not isinstance(text, str) or not text.strip():
continue
try:
nested = json.loads(text)
except json.JSONDecodeError:
continue
if isinstance(nested, dict):
return parse_proxy_rows(nested.get("proxies"), "proxyhub")
return []
def _read_mcp(response: httpx.Response) -> dict:
ctype = (response.headers.get("content-type") or "").lower()
if "json" in ctype:
payload = response.json()
return payload if isinstance(payload, dict) else {}
for line in response.text.splitlines():
if line.startswith("data:"):
payload = json.loads(line[5:].strip() or "{}")
return payload if isinstance(payload, dict) else {}
payload = json.loads(response.text or "{}")
return payload if isinstance(payload, dict) else {}
class ProxyHubCollector(Collector):
name = "proxyhub"
url = "https://proxyhub.me/api/mcp"
types = ("http", "https", "socks4", "socks5")
limit = 100
def collect(self) -> list[ProxyCandidate]:
items: list[ProxyCandidate] = []
with ThreadPoolExecutor(max_workers=len(self.types)) as pool:
futures = [pool.submit(self._list, kind) for kind in self.types]
for future in as_completed(futures):
items.extend(future.result())
return items
def _list(self, kind: str) -> list[ProxyCandidate]:
body = {
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "list_proxies",
"arguments": {"country": "cn", "type": kind, "limit": self.limit},
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {},
"io.modelcontextprotocol/clientInfo": {"name": "eunivtools", "version": "1.0.0"},
},
},
}
headers = {
"Accept": "application/json, text/event-stream",
"Content-Type": "application/json",
"MCP-Protocol-Version": "2026-07-28",
"Mcp-Method": "tools/call",
"Mcp-Name": "list_proxies",
}
with httpx.Client(timeout=20, follow_redirects=True) as client:
response = client.post(self.url, headers=headers, json=body)
response.raise_for_status()
return parse_proxyhub_result(_read_mcp(response))
register(ProxyHubCollector())
+23 -10
View File
@@ -173,18 +173,31 @@ def _fetch_and_store(trigger: str) -> bool:
return False
password = decrypt_secret(account.password_cipher)
credential = json.loads(decrypt_secret(account.credential_cipher))
from euniv.proxy import url_of
from euniv.proxy import bind_url, is_proxy_failure, uses_pool
from euniv.proxy_pool import MAX_SWITCHES, mark_failed
proxy = url_of(account)
client = EunivClient(employee_id, password, proxy=proxy)
try:
client.restore(credential)
if not client.credential_alive():
proxy = bind_url(account)
courses = None
last_exc: BaseException | None = None
for _ in range(MAX_SWITCHES + 1):
client = EunivClient(employee_id, password, proxy=proxy)
try:
client.restore(credential)
if not client.credential_alive():
return False
courses = client.list_courses()
last_exc = None
break
except Exception as exc:
last_exc = exc
if uses_pool(account) and proxy and is_proxy_failure(exc):
mark_failed(employee_id, proxy, str(exc)[:200])
proxy = bind_url(account)
continue
return False
courses = client.list_courses()
finally:
client.close()
if not courses:
finally:
client.close()
if last_exc is not None or not courses:
return False
with SessionLocal() as db:
db.execute(delete(Course))
+34 -1
View File
@@ -4,7 +4,7 @@ from __future__ import annotations
from datetime import datetime
from sqlalchemy import Boolean, DateTime, String, Text, false as sql_false
from sqlalchemy import Boolean, DateTime, String, Text, UniqueConstraint, false as sql_false
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
@@ -57,3 +57,36 @@ class Account(Base):
study_start_minute: Mapped[int] = mapped_column(nullable=False, default=0, server_default="0")
study_start_second: Mapped[int] = mapped_column(nullable=False, default=0, server_default="0")
course_workers: Mapped[int] = mapped_column(nullable=False, default=1, server_default="1")
use_proxy_pool: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=sql_false())
class ProxyNode(Base):
__tablename__ = "proxy_nodes"
__table_args__ = (UniqueConstraint("scheme", "host", "port", name="uq_proxy_node_addr"),)
id: Mapped[int] = mapped_column(primary_key=True)
scheme: Mapped[str] = mapped_column(String(16), nullable=False)
host: Mapped[str] = mapped_column(String(255), nullable=False)
port: Mapped[int] = mapped_column(nullable=False)
country: Mapped[str] = mapped_column(String(32), nullable=False, default="", server_default="")
anonymity: Mapped[str] = mapped_column(String(32), nullable=False, default="", server_default="")
source: Mapped[str] = mapped_column(String(64), nullable=False, default="", server_default="")
status: Mapped[str] = mapped_column(String(16), nullable=False, default="new", server_default="new")
latency_ms: Mapped[int | None] = mapped_column(nullable=True)
last_checked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
last_ok_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
fail_reason: Mapped[str] = mapped_column(String(200), nullable=False, default="", server_default="")
assigns: Mapped[int] = mapped_column(nullable=False, default=0, server_default="0")
class ProxyPoolSync(Base):
__tablename__ = "proxy_pool_sync"
id: Mapped[int] = mapped_column(primary_key=True)
fetched_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
checked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
running: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=sql_false())
message: Mapped[str] = mapped_column(String(200), nullable=False, default="", server_default="")
alive_count: Mapped[int] = mapped_column(nullable=False, default=0, server_default="0")
dead_count: Mapped[int] = mapped_column(nullable=False, default=0, server_default="0")
new_count: Mapped[int] = mapped_column(nullable=False, default=0, server_default="0")
+59 -4
View File
@@ -1,11 +1,14 @@
"""账号级 HTTP/HTTPS/SOCKS4/SOCKS5 代理。账号密码可选。"""
"""账号级 HTTP/HTTPS/SOCKS4/SOCKS5 代理。账号密码可选。也可使用代理池。"""
from __future__ import annotations
from urllib.parse import quote, urlparse
import httpx
SCHEMES = ("http", "https", "socks4", "socks5", "socks5h")
OFF_SCHEMES = ("", "off", "none", "direct", "close")
POOL_SCHEMES = ("pool", "auto")
class ProxyError(ValueError):
@@ -66,12 +69,31 @@ def is_off(scheme: str | None) -> bool:
return (scheme or "").strip().lower() in OFF_SCHEMES
def is_pool(scheme: str | None) -> bool:
return (scheme or "").strip().lower() in POOL_SCHEMES
def uses_pool(account) -> bool:
return bool(getattr(account, "use_proxy_pool", False))
def enabled(account) -> bool:
if uses_pool(account):
return True
return bool(account.proxy_scheme and account.proxy_host and account.proxy_port)
def view_of(account) -> dict:
on = enabled(account)
if uses_pool(account):
return {
"enabled": True,
"scheme": "pool",
"host": "",
"port": None,
"username": "",
"has_password": False,
}
on = bool(account.proxy_scheme and account.proxy_host and account.proxy_port)
return {
"enabled": on,
"scheme": account.proxy_scheme if on else "off",
@@ -83,13 +105,15 @@ def view_of(account) -> dict:
def summary_of(account) -> str:
if not enabled(account):
if uses_pool(account):
return "自动"
if not (account.proxy_scheme and account.proxy_host and account.proxy_port):
return ""
return f"{account.proxy_scheme.upper()} {account.proxy_host}:{account.proxy_port}"
def url_of(account) -> str | None:
if not enabled(account):
if uses_pool(account) or not (account.proxy_scheme and account.proxy_host and account.proxy_port):
return None
password = ""
if account.proxy_password_cipher:
@@ -109,6 +133,16 @@ def apply(account, scheme: str, host: str = "", port: object = None, username: s
if is_off(scheme):
clear(account)
return
if is_pool(scheme):
clear(account)
account.use_proxy_pool = True
return
employee_id = getattr(account, "employee_id", "")
if uses_pool(account) and employee_id:
from euniv.proxy_pool import release
release(str(employee_id))
account.use_proxy_pool = False
kind, address, number, user = validate_parts(scheme, host, port, username)
if password is not None and len(str(password)) > 256:
raise ProxyError("代理密码过长")
@@ -132,3 +166,24 @@ def clear(account) -> None:
account.proxy_port = None
account.proxy_username = ""
account.proxy_password_cipher = ""
account.use_proxy_pool = False
employee_id = getattr(account, "employee_id", "")
if employee_id:
from euniv.proxy_pool import release
release(str(employee_id))
def bind_url(account) -> str | None:
if uses_pool(account):
from euniv.proxy_pool import acquire
return acquire(str(account.employee_id))
return url_of(account)
def is_proxy_failure(exc: BaseException) -> bool:
if isinstance(exc, (httpx.ProxyError, httpx.ConnectError, httpx.ConnectTimeout)):
return True
text = f"{type(exc).__name__} {exc}".lower()
return "proxy" in text or "socks" in text
+452
View File
@@ -0,0 +1,452 @@
"""自有代理池:多上游汇聚、延迟检测、均匀分配、失效剔除。"""
from __future__ import annotations
import logging
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timezone
from urllib.parse import urlparse
import httpx
from sqlalchemy import case, func, select
from sqlalchemy.orm import Session
from euniv.client import EUNIV, USER_AGENT
from euniv.collectors import collect_all, is_china, source_title
from euniv.db import SessionLocal
from euniv.models import ProxyNode, ProxyPoolSync
from euniv.proxy import build_proxy_url
log = logging.getLogger(__name__)
FETCH_INTERVAL = 300
LATENCY_LIMIT = 3.0
LATENCY_LIMIT_MS = 3000
PROBE_CONCURRENCY = 16
MAX_PROBES = 80
MAX_SWITCHES = 8
PROBE_URL = EUNIV + "/"
STATUS_ALIVE = "alive"
STATUS_DEAD = "dead"
STATUS_NEW = "new"
_ANONYMITY = {"elite": "高匿名", "anonymous": "匿名", "transparent": "透明"}
_STATUS = {STATUS_ALIVE: "可用", STATUS_DEAD: "失效", STATUS_NEW: "待检测"}
_assign_lock = threading.Lock()
_holds: dict[str, int] = {}
_refresh_lock = threading.Lock()
_stop: threading.Event | None = None
def _now() -> datetime:
return datetime.now(timezone.utc)
def _url(node: ProxyNode) -> str:
return build_proxy_url(node.scheme, node.host, int(node.port))
def _sync_row(db: Session) -> ProxyPoolSync:
row = db.get(ProxyPoolSync, 1)
if row is None:
row = ProxyPoolSync(id=1)
db.add(row)
db.flush()
return row
def _counts(db: Session) -> tuple[int, int, int]:
rows = db.execute(select(ProxyNode.status, func.count()).group_by(ProxyNode.status)).all()
tallies = {str(status): int(count) for status, count in rows}
return tallies.get(STATUS_ALIVE, 0), tallies.get(STATUS_DEAD, 0), tallies.get(STATUS_NEW, 0)
def _store_counts(db: Session, sync: ProxyPoolSync) -> None:
sync.alive_count, sync.dead_count, sync.new_count = _counts(db)
def _iso(value: datetime | None) -> str | None:
if value is None:
return None
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
return value.isoformat()
def _anonymity_label(value: str) -> str:
return _ANONYMITY.get((value or "").strip().lower(), value or "—")
def _country_label(value: str) -> str:
text = (value or "").strip()
if not text:
return "—"
if text.lower() in {"cn", "chn", "china"} or "中国" in text:
return "中国"
return text
def _status_label(value: str) -> str:
return _STATUS.get(value, value or "—")
def view_item(node: ProxyNode) -> dict:
return {
"id": node.id,
"scheme": node.scheme,
"host": node.host,
"port": int(node.port),
"country": _country_label(node.country),
"anonymity": _anonymity_label(node.anonymity),
"source": source_title(node.source),
"status": node.status,
"status_text": _status_label(node.status),
"latency_ms": node.latency_ms,
"last_checked_at": _iso(node.last_checked_at),
"last_ok_at": _iso(node.last_ok_at),
"note": node.fail_reason or "",
}
def sync_view(db: Session) -> dict:
sync = _sync_row(db)
alive, dead, pending = _counts(db)
return {
"fetched_at": _iso(sync.fetched_at),
"checked_at": _iso(sync.checked_at),
"running": bool(sync.running),
"message": sync.message or "",
"alive": alive,
"dead": dead,
"pending": pending,
"total": alive + dead + pending,
}
def page(db: Session, q: str = "", status: str = "", offset: int = 0, limit: int = 50) -> dict:
bounded = min(max(int(limit), 1), 100)
start = max(int(offset), 0)
query = select(ProxyNode)
count_query = select(func.count()).select_from(ProxyNode)
kind = (status or "").strip().lower()
if kind in {STATUS_ALIVE, STATUS_DEAD, STATUS_NEW}:
query = query.where(ProxyNode.status == kind)
count_query = count_query.where(ProxyNode.status == kind)
text = (q or "").strip()
if text:
like = f"%{text}%"
query = query.where(ProxyNode.host.like(like))
count_query = count_query.where(ProxyNode.host.like(like))
rank = case((ProxyNode.status == STATUS_ALIVE, 0), (ProxyNode.status == STATUS_NEW, 1), else_=2)
query = query.order_by(rank, ProxyNode.latency_ms.is_(None), ProxyNode.latency_ms, ProxyNode.id)
total = int(db.scalar(count_query) or 0)
nodes = db.scalars(query.offset(start).limit(bounded)).all()
payload = sync_view(db)
payload["items"] = [view_item(node) for node in nodes]
payload["total"] = total
payload["offset"] = start
payload["limit"] = bounded
return payload
def probe(scheme: str, host: str, port: int) -> tuple[bool, int, str]:
url = build_proxy_url(scheme, host, port)
started = time.perf_counter()
try:
with httpx.Client(
proxy=url,
timeout=LATENCY_LIMIT,
follow_redirects=True,
headers={"User-Agent": USER_AGENT},
) as client:
response = client.get(PROBE_URL)
latency = int((time.perf_counter() - started) * 1000)
if latency > LATENCY_LIMIT_MS:
return False, latency, "超时"
if response.status_code >= 500:
return False, latency, f"HTTP {response.status_code}"
return True, latency, ""
except Exception as exc:
latency = int((time.perf_counter() - started) * 1000)
return False, latency, _short_reason(exc)
def _short_reason(exc: BaseException) -> str:
if isinstance(exc, (httpx.ConnectTimeout, httpx.TimeoutException)):
return "超时"
if isinstance(exc, (httpx.ProxyError, httpx.ConnectError)):
return "无法连接"
text = str(exc).strip() or type(exc).__name__
return text[:200]
def _find_node(db: Session, scheme: str, host: str, port: int) -> ProxyNode | None:
return db.scalars(
select(ProxyNode).where(
ProxyNode.scheme == scheme,
ProxyNode.host == host,
ProxyNode.port == port,
)
).first()
def _parse_proxy_url(value: str | None) -> tuple[str, str, int] | None:
text = (value or "").strip()
if not text:
return None
parsed = urlparse(text)
host = parsed.hostname
if not host or parsed.port is None:
return None
return (parsed.scheme or "http").lower(), host, int(parsed.port)
def _evict_node(node_id: int) -> None:
for employee_id, held in list(_holds.items()):
if held == node_id:
_holds.pop(employee_id, None)
def acquire(employee_id: str) -> str | None:
key = (employee_id or "").strip()
if not key:
return None
with SessionLocal() as db, _assign_lock:
held_id = _holds.get(key)
if held_id:
held = db.get(ProxyNode, held_id)
if held is not None and held.status == STATUS_ALIVE:
return _url(held)
_holds.pop(key, None)
nodes = list(db.scalars(select(ProxyNode).where(ProxyNode.status == STATUS_ALIVE)).all())
if not nodes:
return None
load = {node.id: 0 for node in nodes}
for node_id in _holds.values():
if node_id in load:
load[node_id] += 1
nodes.sort(key=lambda node: (load[node.id], node.assigns, node.id))
pick = nodes[0]
_holds[key] = pick.id
pick.assigns = int(pick.assigns or 0) + 1
db.commit()
return _url(pick)
def release(employee_id: str) -> None:
with _assign_lock:
_holds.pop((employee_id or "").strip(), None)
def mark_failed(employee_id: str, proxy_url: str | None = None, reason: str = "") -> None:
key = (employee_id or "").strip()
parsed = _parse_proxy_url(proxy_url)
with SessionLocal() as db, _assign_lock:
node = None
node_id = _holds.pop(key, None)
if node_id:
node = db.get(ProxyNode, node_id)
if node is None and parsed is not None:
node = _find_node(db, parsed[0], parsed[1], parsed[2])
if node is None:
return
node.status = STATUS_DEAD
node.fail_reason = (reason or "失效")[:200]
node.last_checked_at = _now()
_evict_node(node.id)
db.commit()
def refresh_once() -> dict:
if not _refresh_lock.acquire(blocking=False):
with SessionLocal() as db:
return sync_view(db)
try:
return _refresh_body()
finally:
_refresh_lock.release()
def _refresh_body() -> dict:
with SessionLocal() as db:
sync = _sync_row(db)
sync.running = True
sync.message = ""
db.commit()
try:
candidates = collect_all()
with SessionLocal() as db:
sync = _sync_row(db)
sync.fetched_at = _now()
existing = {
(node.scheme, node.host, int(node.port)): node
for node in db.scalars(select(ProxyNode)).all()
}
new_ids: list[int] = []
alive_ids: list[int] = []
for item in candidates:
if not is_china(item.country):
continue
key = (item.scheme, item.host, item.port)
node = existing.get(key)
if node is None:
node = ProxyNode(
scheme=item.scheme,
host=item.host,
port=item.port,
country=item.country,
anonymity=item.anonymity,
source=item.source,
status=STATUS_NEW,
)
db.add(node)
db.flush()
existing[key] = node
new_ids.append(node.id)
continue
node.country = item.country or node.country
node.anonymity = item.anonymity or node.anonymity
node.source = item.source or node.source
if node.status == STATUS_DEAD:
continue
if node.status == STATUS_NEW:
new_ids.append(node.id)
elif node.status == STATUS_ALIVE:
alive_ids.append(node.id)
for node in existing.values():
if node.status == STATUS_ALIVE and node.id not in alive_ids and node.id not in new_ids:
alive_ids.append(node.id)
db.commit()
probe_ids = _pick_probe_ids(db, new_ids, alive_ids)
nodes = [db.get(ProxyNode, node_id) for node_id in probe_ids]
snapshot = [
(node.id, node.scheme, node.host, int(node.port))
for node in nodes
if node is not None
]
results = _probe_many(snapshot)
with SessionLocal() as db, _assign_lock:
sync = _sync_row(db)
for node_id, ok, latency, reason in results:
node = db.get(ProxyNode, node_id)
if node is None:
continue
if node.status == STATUS_DEAD:
continue
node.last_checked_at = _now()
node.latency_ms = latency
if ok:
node.status = STATUS_ALIVE
node.last_ok_at = node.last_checked_at
node.fail_reason = ""
else:
node.status = STATUS_DEAD
node.fail_reason = reason or "失效"
_evict_node(node.id)
sync.checked_at = _now()
sync.running = False
_store_counts(db, sync)
if sync.alive_count:
sync.message = ""
elif not candidates:
sync.message = "没有获取到可用代理"
else:
sync.message = "当前没有可用代理"
db.commit()
return sync_view(db)
except Exception:
log.exception("代理池更新失败")
with SessionLocal() as db:
sync = _sync_row(db)
sync.running = False
sync.message = "没有更新"
db.commit()
return sync_view(db)
def _pick_probe_ids(db: Session, new_ids: list[int], alive_ids: list[int]) -> list[int]:
ordered: list[int] = []
seen: set[int] = set()
for node_id in new_ids:
if node_id not in seen:
seen.add(node_id)
ordered.append(node_id)
if len(ordered) >= MAX_PROBES:
return ordered[:MAX_PROBES]
alive_nodes = [
node
for node in (db.get(ProxyNode, node_id) for node_id in alive_ids)
if node is not None
]
alive_nodes.sort(key=lambda node: (node.last_checked_at is not None, node.last_checked_at or _now(), node.id))
for node in alive_nodes:
if node.id in seen:
continue
seen.add(node.id)
ordered.append(node.id)
if len(ordered) >= MAX_PROBES:
break
return ordered
def _probe_many(nodes: list[tuple[int, str, str, int]]) -> list[tuple[int, bool, int, str]]:
if not nodes:
return []
workers = min(PROBE_CONCURRENCY, len(nodes))
results: list[tuple[int, bool, int, str]] = []
with ThreadPoolExecutor(max_workers=workers) as pool:
futures = {
pool.submit(probe, scheme, host, port): node_id
for node_id, scheme, host, port in nodes
}
for future in as_completed(futures):
node_id = futures[future]
try:
ok, latency, reason = future.result()
except Exception as exc:
ok, latency, reason = False, LATENCY_LIMIT_MS, _short_reason(exc)
results.append((node_id, ok, latency, reason))
return results
def request_refresh() -> dict:
with SessionLocal() as db:
sync = _sync_row(db)
already = bool(sync.running)
if not already:
sync.running = True
sync.message = ""
db.commit()
payload = sync_view(db)
else:
payload = sync_view(db)
if not already:
threading.Thread(target=refresh_once, name="euniv-proxy-pool-once", daemon=True).start()
payload["running"] = True
return payload
def start_proxy_pool() -> threading.Event:
global _stop
stop = threading.Event()
_stop = stop
def loop() -> None:
if stop.wait(8):
return
while not stop.is_set():
started = time.monotonic()
try:
refresh_once()
except Exception:
log.exception("代理池更新失败")
delay = max(1.0, FETCH_INTERVAL - (time.monotonic() - started))
if stop.wait(delay):
return
threading.Thread(target=loop, name="euniv-proxy-pool", daemon=True).start()
return stop
+123 -62
View File
@@ -69,15 +69,28 @@ def _persist(db: Session, employee_id: str, password: str, client: EunivClient,
def _client(factory, employee_id: str, password: str, account: Account | None = None):
from euniv.proxy import url_of
from euniv.proxy import bind_url
proxy = url_of(account) if account is not None else None
proxy = bind_url(account) if account is not None else None
try:
return factory(employee_id, password, proxy)
except TypeError:
return factory(employee_id, password)
def _switch_proxy(account: Account | None, client, exc: BaseException) -> bool:
from euniv.proxy import is_proxy_failure, uses_pool
from euniv.proxy_pool import mark_failed
if account is None or not uses_pool(account):
return False
proxy = getattr(client, "proxy", None)
if not proxy or not is_proxy_failure(exc):
return False
mark_failed(account.employee_id, proxy, str(exc)[:200])
return True
def login_and_store(
db: Session,
employee_id: str,
@@ -93,33 +106,55 @@ def login_and_store(
_request_course_sync(employee_id)
return {"employee_id": employee_id}
_drop_employee(employee_id)
client = _client(client_factory, employee_id, password, account)
from euniv.proxy_pool import MAX_SWITCHES
held = False
client = None
last_exc: BaseException | None = None
try:
try:
profile = client.login(manual=manual, auto_attempts=auto_attempts)
except ManualJigsaw as exc:
attempt_id = secrets.token_urlsafe(18)
_pending[attempt_id] = PendingLogin(client, employee_id, password, time.time())
held = True
return {"attempt_id": attempt_id, "jigsaw": exc.puzzle}
_persist(db, employee_id, password, client, profile)
_request_course_sync(employee_id)
return {"employee_id": employee_id}
for _ in range(MAX_SWITCHES + 1):
client = _client(client_factory, employee_id, password, account)
try:
profile = client.login(manual=manual, auto_attempts=auto_attempts)
except ManualJigsaw as exc:
attempt_id = secrets.token_urlsafe(18)
_pending[attempt_id] = PendingLogin(client, employee_id, password, time.time())
held = True
return {"attempt_id": attempt_id, "jigsaw": exc.puzzle}
except Exception as exc:
last_exc = exc
if _switch_proxy(account, client, exc):
client.close()
client = None
continue
raise
_persist(db, employee_id, password, client, profile)
_request_course_sync(employee_id)
return {"employee_id": employee_id}
if last_exc is not None:
raise last_exc
raise RuntimeError("登录失败")
finally:
if not held:
if client is not None and not held:
client.close()
def _credential_still_valid(account: Account, client_factory) -> bool:
client = _client(client_factory, account.employee_id, decrypt_secret(account.password_cipher), account)
try:
client.restore(json.loads(decrypt_secret(account.credential_cipher)))
return bool(client.credential_alive())
except Exception:
return False
finally:
client.close()
from euniv.proxy_pool import MAX_SWITCHES
password = decrypt_secret(account.password_cipher)
for _ in range(MAX_SWITCHES + 1):
client = _client(client_factory, account.employee_id, password, account)
try:
client.restore(json.loads(decrypt_secret(account.credential_cipher)))
return bool(client.credential_alive())
except Exception as exc:
if _switch_proxy(account, client, exc):
continue
return False
finally:
client.close()
return False
def submit_jigsaw(db: Session, attempt_id: str, offset: int) -> dict:
@@ -177,39 +212,54 @@ def _auto_attempts(db: Session) -> int:
def _live(db: Session, employee_id: str, client_factory, read):
from euniv.proxy_pool import MAX_SWITCHES
account = db.get(Account, employee_id)
if account is None:
raise RuntimeError("请先登录")
credential = json.loads(decrypt_secret(account.credential_cipher)) if account.credential_cipher else {}
attempts = _auto_attempts(db)
client = _client(client_factory, employee_id, decrypt_secret(account.password_cipher), account)
try:
if credential.get("yxt_token"):
client.restore(credential)
else:
try:
client.authorize(client.login(manual=False, auto_attempts=attempts))
except ManualJigsaw:
raise RuntimeError("登录需要重新验证,请重新登录") from None
password = decrypt_secret(account.password_cipher)
last_exc: BaseException | None = None
for _ in range(MAX_SWITCHES + 1):
client = _client(client_factory, employee_id, password, account)
try:
data = read(client)
except SessionExpired:
if credential.get("yxt_token"):
client.restore(credential)
else:
try:
client.authorize(client.login(manual=False, auto_attempts=attempts))
except ManualJigsaw:
raise RuntimeError("登录需要重新验证,请重新登录") from None
try:
client.authorize(client.login(manual=False, auto_attempts=attempts))
except ManualJigsaw:
raise RuntimeError("登录需要重新验证,请重新登录") from None
data = read(client)
updated = client.export_credential()
with _credential_lock(employee_id):
db.refresh(account)
current_raw = account.credential_cipher
current = json.loads(decrypt_secret(current_raw)) if current_raw else {}
if _dump(updated) != _dump(current) and _dump(current) == _dump(credential):
account.credential_cipher = encrypt_secret(_dump(updated))
db.commit()
return data
finally:
client.close()
data = read(client)
except SessionExpired:
try:
client.authorize(client.login(manual=False, auto_attempts=attempts))
except ManualJigsaw:
raise RuntimeError("登录需要重新验证,请重新登录") from None
data = read(client)
updated = client.export_credential()
with _credential_lock(employee_id):
db.refresh(account)
current_raw = account.credential_cipher
current = json.loads(decrypt_secret(current_raw)) if current_raw else {}
if _dump(updated) != _dump(current) and _dump(current) == _dump(credential):
account.credential_cipher = encrypt_secret(_dump(updated))
db.commit()
return data
except RuntimeError:
raise
except Exception as exc:
last_exc = exc
if _switch_proxy(account, client, exc):
continue
raise
finally:
client.close()
if last_exc is not None:
raise last_exc
raise RuntimeError("请先登录")
def revoke_credential(db: Session, employee_id: str) -> None:
@@ -245,22 +295,33 @@ def _refresh_one(employee_id: str, attempts: int, client_factory) -> None:
checked_alive = False
hours = ""
try:
from euniv.proxy_pool import MAX_SWITCHES
password = decrypt_secret(account.password_cipher)
previous = json.loads(decrypt_secret(account.credential_cipher))
client = _client(client_factory, employee_id, password, account)
client.restore(previous)
if client.credential_alive():
updated = client.export_credential()
if _dump(updated) != _dump(previous):
account.credential_cipher = encrypt_secret(_dump(updated))
valid = True
checked_alive = True
else:
profile = client.login(manual=False, auto_attempts=attempts)
_persist(db, employee_id, password, client, profile)
valid = True
if valid:
hours = _month_hours(client)
for _ in range(MAX_SWITCHES + 1):
client = _client(client_factory, employee_id, password, account)
try:
client.restore(previous)
if client.credential_alive():
updated = client.export_credential()
if _dump(updated) != _dump(previous):
account.credential_cipher = encrypt_secret(_dump(updated))
valid = True
checked_alive = True
else:
profile = client.login(manual=False, auto_attempts=attempts)
_persist(db, employee_id, password, client, profile)
valid = True
if valid:
hours = _month_hours(client)
break
except Exception as exc:
if _switch_proxy(account, client, exc):
client.close()
client = None
continue
raise
except Exception:
db.rollback()
valid = False