fix: 补齐审查清单里还没落地的交互和代理复测
This commit is contained in:
@@ -34,6 +34,7 @@ from euniv.client import (
|
||||
_load_cookies,
|
||||
as_uuid,
|
||||
compact_id,
|
||||
guard_https,
|
||||
play_page_params,
|
||||
study_progress_fields,
|
||||
)
|
||||
@@ -665,14 +666,12 @@ class HoursWatcher:
|
||||
target: int,
|
||||
user_stop: asyncio.Event,
|
||||
interval: float = _HOURS_REFRESH_SECONDS,
|
||||
source: str = "api",
|
||||
) -> None:
|
||||
self.session = session
|
||||
self.employee_id = employee_id
|
||||
self.target = target
|
||||
self.user_stop = user_stop
|
||||
self.interval = interval
|
||||
self.source = source if source in ("api", "history") else "api"
|
||||
self._lock = asyncio.Lock()
|
||||
self.reached = False
|
||||
from euniv.study_window import month_key
|
||||
@@ -764,6 +763,7 @@ class StudySession:
|
||||
timeout=30,
|
||||
follow_redirects=True,
|
||||
headers={"User-Agent": USER_AGENT},
|
||||
event_hooks={"request": [guard_https]},
|
||||
)
|
||||
_load_cookies(self._client, self._initial_cookies)
|
||||
self._proxy_lock = asyncio.Lock()
|
||||
@@ -780,7 +780,7 @@ class StudySession:
|
||||
if not self._use_pool:
|
||||
return False
|
||||
from euniv.proxy import async_httpx_client, parse_proxy
|
||||
from euniv.proxy_pool import MAX_SWITCHES, acquire, mark_failed
|
||||
from euniv.proxy_pool import MAX_SWITCHES, acquire, retire_if_dead
|
||||
|
||||
if self._proxy_lock is None:
|
||||
self._proxy_lock = asyncio.Lock()
|
||||
@@ -790,8 +790,10 @@ class StudySession:
|
||||
return True
|
||||
if self._switches >= MAX_SWITCHES:
|
||||
return False
|
||||
dead = await asyncio.to_thread(retire_if_dead, self._employee_id, failed)
|
||||
if not dead:
|
||||
return True
|
||||
self._switches += 1
|
||||
await asyncio.to_thread(mark_failed, self._employee_id, failed)
|
||||
nxt = await asyncio.to_thread(acquire, self._employee_id)
|
||||
parsed = parse_proxy(nxt)
|
||||
if parsed == failed:
|
||||
@@ -801,6 +803,7 @@ class StudySession:
|
||||
timeout=30,
|
||||
follow_redirects=True,
|
||||
headers={"User-Agent": USER_AGENT},
|
||||
event_hooks={"request": [guard_https]},
|
||||
)
|
||||
cookies = self._initial_cookies
|
||||
if self._client is not None:
|
||||
@@ -1454,7 +1457,7 @@ def _prepare_session(employee_id: str, password: str,
|
||||
use_pool: bool = False
|
||||
) -> tuple[str, str, str, list[tuple[str, str, str, str]], str | None, str]:
|
||||
"""同步:恢复会话并导出 cookies。最后一项是 expired 或 network。"""
|
||||
from euniv.proxy_pool import MAX_SWITCHES, acquire, mark_failed
|
||||
from euniv.proxy_pool import MAX_SWITCHES, acquire, retire_if_dead
|
||||
|
||||
current = proxy
|
||||
last_reason = "network"
|
||||
@@ -1477,9 +1480,8 @@ def _prepare_session(employee_id: str, password: str,
|
||||
except Exception as exc:
|
||||
log.warning("用户 %s 准备会话失败: %s", employee_id, exc)
|
||||
if use_pool and current and is_proxy_failure(exc):
|
||||
mark_failed(employee_id, current, str(exc)[:200])
|
||||
current = acquire(employee_id)
|
||||
last_reason = "network"
|
||||
if retire_if_dead(employee_id, current, str(exc)[:200]):
|
||||
current = acquire(employee_id)
|
||||
continue
|
||||
last_reason = "expired" if isinstance(exc, SessionExpired) else "network"
|
||||
return "", "", "", [], current, last_reason
|
||||
@@ -1748,7 +1750,7 @@ class AutoStudyWorker:
|
||||
_set_user_status(employee_id, state="已停止")
|
||||
return
|
||||
_set_user_status(employee_id, state="学习中")
|
||||
hours = HoursWatcher(session, employee_id, target, user_stop, source=hours_source)
|
||||
hours = HoursWatcher(session, employee_id, target, user_stop)
|
||||
if await hours.refresh():
|
||||
return
|
||||
ticker = asyncio.create_task(hours.ticker(self._async_stop))
|
||||
|
||||
+11
-6
@@ -755,9 +755,14 @@ class QrWaiting(Exception):
|
||||
"""二维码尚未扫过或还在等待确认。"""
|
||||
|
||||
|
||||
def _https_only(request: httpx.Request) -> None:
|
||||
def guard_https(request: httpx.Request) -> None:
|
||||
if request.url.scheme != "https":
|
||||
raise RuntimeError("只允许 https 请求")
|
||||
host = (request.url.host or "").rstrip(".").lower()
|
||||
if host in {"zte.com.cn", "yunxuetang.cn"} or host.endswith((".zte.com.cn", ".yunxuetang.cn")):
|
||||
return
|
||||
request.headers.pop("token", None)
|
||||
request.headers.pop("Token", None)
|
||||
|
||||
|
||||
def _login_secret_too_long(value: str) -> bool:
|
||||
@@ -776,7 +781,7 @@ class EunivClient:
|
||||
timeout=30,
|
||||
follow_redirects=True,
|
||||
headers={"User-Agent": USER_AGENT},
|
||||
event_hooks={"request": [_https_only]},
|
||||
event_hooks={"request": [guard_https]},
|
||||
)
|
||||
self._profile: dict = {}
|
||||
self._yxt_token = ""
|
||||
@@ -992,7 +997,7 @@ class EunivClient:
|
||||
if profile.get("unionId"):
|
||||
jar["iuacUnionId"] = str(profile["unionId"])
|
||||
for name, value in jar.items():
|
||||
self.client.cookies.set(name, value, domain=domain, path="/")
|
||||
self.client.cookies.set(name, value, domain=domain, path="/", secure=True)
|
||||
|
||||
self._uac_post(
|
||||
"/authentication/token/verify.serv",
|
||||
@@ -1057,8 +1062,8 @@ class EunivClient:
|
||||
token = str(credential.get("yxt_token") or "")
|
||||
self._yxt_token = token
|
||||
if token:
|
||||
self.client.cookies.set("ELEARNING_00024", token, domain="euniv.zte.com.cn", path="/")
|
||||
self.client.cookies.set("ELEARNING_00024", token, domain=".yunxuetang.cn", path="/")
|
||||
self.client.cookies.set("ELEARNING_00024", token, domain="euniv.zte.com.cn", path="/", secure=True)
|
||||
self.client.cookies.set("ELEARNING_00024", token, domain=".yunxuetang.cn", path="/", secure=True)
|
||||
|
||||
def session_token(self) -> str:
|
||||
for cookie in self.client.cookies.jar:
|
||||
@@ -1081,7 +1086,7 @@ class EunivClient:
|
||||
if refreshed:
|
||||
self._yxt_token = refreshed
|
||||
for domain in ("euniv.zte.com.cn", ".yunxuetang.cn"):
|
||||
self.client.cookies.set("ELEARNING_00024", refreshed, domain=domain, path="/")
|
||||
self.client.cookies.set("ELEARNING_00024", refreshed, domain=domain, path="/", secure=True)
|
||||
if response.status_code == 401:
|
||||
raise SessionExpired("学习平台登录已失效")
|
||||
if response.status_code == 403:
|
||||
|
||||
@@ -201,7 +201,7 @@ def _fetch_and_store(trigger: str) -> bool:
|
||||
password = decrypt_secret(account.password_cipher)
|
||||
credential = json.loads(decrypt_secret(account.credential_cipher))
|
||||
from euniv.proxy import bind_url, is_proxy_failure, uses_pool
|
||||
from euniv.proxy_pool import MAX_SWITCHES, mark_failed
|
||||
from euniv.proxy_pool import MAX_SWITCHES, retire_if_dead
|
||||
|
||||
proxy = bind_url(account)
|
||||
courses = None
|
||||
@@ -219,8 +219,8 @@ def _fetch_and_store(trigger: str) -> bool:
|
||||
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)
|
||||
if retire_if_dead(employee_id, proxy, str(exc)[:200]):
|
||||
proxy = bind_url(account)
|
||||
continue
|
||||
_cool_failed_sync(employee_id)
|
||||
return False
|
||||
|
||||
@@ -332,6 +332,9 @@ def is_proxy_failure(exc: BaseException) -> bool:
|
||||
httpx.ProxyError,
|
||||
httpx.ConnectError,
|
||||
httpx.ConnectTimeout,
|
||||
httpx.ReadTimeout,
|
||||
httpx.ReadError,
|
||||
httpx.RemoteProtocolError,
|
||||
SocksProxyError,
|
||||
ProxyConnectionError,
|
||||
ProxyTimeoutError,
|
||||
|
||||
@@ -332,6 +332,19 @@ def release(employee_id: str) -> None:
|
||||
db.commit()
|
||||
|
||||
|
||||
def retire_if_dead(employee_id: str, proxy_url: str | None, reason: str = "") -> bool:
|
||||
"""立刻复测当前节点。还通就继续用;不通就标死。"""
|
||||
parsed = _parse_proxy_url(proxy_url)
|
||||
if parsed is None:
|
||||
mark_failed(employee_id, proxy_url, reason)
|
||||
return True
|
||||
ok, _latency, why = probe(parsed[0], parsed[1], parsed[2])
|
||||
if ok:
|
||||
return False
|
||||
mark_failed(employee_id, proxy_url, why or reason)
|
||||
return True
|
||||
|
||||
|
||||
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)
|
||||
|
||||
@@ -181,14 +181,14 @@ def _client(factory, employee_id: str, password: str, account: Account | None =
|
||||
|
||||
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
|
||||
from euniv.proxy_pool import retire_if_dead
|
||||
|
||||
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])
|
||||
retire_if_dead(account.employee_id, proxy, str(exc)[:200])
|
||||
return True
|
||||
|
||||
|
||||
|
||||
@@ -28,6 +28,16 @@ _last_flush: dict[str, float] = {}
|
||||
|
||||
def attach_loop(loop: asyncio.AbstractEventLoop) -> None:
|
||||
global _loop
|
||||
if _loop is loop:
|
||||
return
|
||||
for handle in list(_pending.values()):
|
||||
handle.cancel()
|
||||
_pending.clear()
|
||||
_inflight.clear()
|
||||
_dirty.clear()
|
||||
_urgent.clear()
|
||||
_last_flush.clear()
|
||||
_clients.clear()
|
||||
_loop = loop
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user