feat: 自动代理改为向接口领取,去掉 ProxyHub 和代理列表
This commit is contained in:
+146
-18
@@ -936,7 +936,7 @@ class StudySession:
|
||||
|
||||
def __init__(self, token: str, cookies: list[tuple[str, str, str, str]],
|
||||
proxy: str | None = None, employee_id: str = "",
|
||||
use_pool: bool = False) -> None:
|
||||
use_pool: bool = False, password: str = "") -> None:
|
||||
from euniv.proxy import parse_proxy
|
||||
|
||||
self._token = token
|
||||
@@ -948,7 +948,8 @@ class StudySession:
|
||||
self._submit_logs = 0
|
||||
self._proxy_lock: asyncio.Lock | None = None
|
||||
self._closing: list[httpx.AsyncClient] = []
|
||||
self._switches = 0
|
||||
self._password = password
|
||||
self._gave_direct = False
|
||||
self._client: httpx.AsyncClient | None = None
|
||||
|
||||
async def __aenter__(self) -> "StudySession":
|
||||
@@ -976,7 +977,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, retire_if_dead
|
||||
from euniv.proxy_pool import acquire, retire_if_dead
|
||||
|
||||
if self._proxy_lock is None:
|
||||
self._proxy_lock = asyncio.Lock()
|
||||
@@ -984,15 +985,12 @@ class StudySession:
|
||||
async with self._proxy_lock:
|
||||
if failed != self._proxy:
|
||||
return True
|
||||
if self._switches >= MAX_SWITCHES:
|
||||
if self._gave_direct:
|
||||
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(retire_if_dead, self._employee_id, failed)
|
||||
nxt = await asyncio.to_thread(acquire, self._employee_id)
|
||||
parsed = parse_proxy(nxt)
|
||||
if parsed == failed:
|
||||
if nxt and parsed == failed:
|
||||
return False
|
||||
client = async_httpx_client(
|
||||
parsed,
|
||||
@@ -1011,6 +1009,9 @@ class StudySession:
|
||||
_load_cookies(client, cookies)
|
||||
self._client = client
|
||||
self._proxy = parsed
|
||||
if not parsed:
|
||||
self._gave_direct = True
|
||||
_set_user_status(self._employee_id, message="正在直连")
|
||||
return True
|
||||
|
||||
async def _http(self, method: str, url: str, **kw: object) -> httpx.Response:
|
||||
@@ -1040,6 +1041,46 @@ class StudySession:
|
||||
"User-Agent": USER_AGENT,
|
||||
}
|
||||
|
||||
def _logged_out(self, resp: httpx.Response) -> bool:
|
||||
if resp.status_code == 401:
|
||||
return True
|
||||
if resp.headers.get("content-type", "").startswith("application/json"):
|
||||
try:
|
||||
payload = resp.json()
|
||||
except (json.JSONDecodeError, ValueError):
|
||||
payload = None
|
||||
if isinstance(payload, dict) and str(payload.get("code")) == "401":
|
||||
return True
|
||||
return False
|
||||
|
||||
async def _switch_direct_login(self) -> bool:
|
||||
"""经代理访问时像是未登录。先用保存的凭据走直连复查,还有效就继续,不再登录。"""
|
||||
if self._gave_direct or not self._proxy:
|
||||
return False
|
||||
self._gave_direct = True
|
||||
packed = await asyncio.to_thread(_continue_direct, self._employee_id, self._password)
|
||||
token, _user_id, _org_id, cookies, _proxy, reason = packed
|
||||
if reason or not token:
|
||||
return False
|
||||
from euniv.proxy import async_httpx_client
|
||||
|
||||
client = async_httpx_client(
|
||||
None,
|
||||
timeout=30,
|
||||
follow_redirects=True,
|
||||
headers={"User-Agent": USER_AGENT},
|
||||
event_hooks={"request": [guard_https_async]},
|
||||
)
|
||||
_load_cookies(client, cookies)
|
||||
if self._client is not None:
|
||||
self._closing.append(self._client)
|
||||
self._client = client
|
||||
self._initial_cookies = cookies
|
||||
self._proxy = None
|
||||
self._token = token
|
||||
_set_user_status(self._employee_id, message="正在直连")
|
||||
return True
|
||||
|
||||
async def _api(self, method: str, url: str, **kw: object) -> httpx.Response:
|
||||
assert self._client is not None
|
||||
headers = self._api_headers()
|
||||
@@ -1047,6 +1088,11 @@ class StudySession:
|
||||
if extra and isinstance(extra, dict):
|
||||
headers.update(extra)
|
||||
resp = await self._http(method, url, headers=headers, **kw)
|
||||
if self._logged_out(resp) and await self._switch_direct_login():
|
||||
headers = self._api_headers()
|
||||
if extra and isinstance(extra, dict):
|
||||
headers.update(extra)
|
||||
resp = await self._http(method, url, headers=headers, **kw)
|
||||
refreshed = resp.headers.get("token") or resp.headers.get("Token")
|
||||
if refreshed:
|
||||
self._token = refreshed
|
||||
@@ -1222,6 +1268,13 @@ class StudySession:
|
||||
headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"},
|
||||
)
|
||||
html = resp.text
|
||||
if _page_is_login(html) and await self._switch_direct_login():
|
||||
resp = await self._http(
|
||||
"GET",
|
||||
f"{EUNIV}{path}",
|
||||
headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"},
|
||||
)
|
||||
html = resp.text
|
||||
if _page_is_login(html):
|
||||
raise SessionExpired("学习平台登录已失效")
|
||||
from euniv.encrypt import note_play_html
|
||||
@@ -1726,6 +1779,81 @@ async def _study_package(session: StudySession, kid: str,
|
||||
|
||||
# ── 同步准备:用 EunivClient 建立会话,导出 cookies ──
|
||||
|
||||
def _session_export(client: EunivClient, proxy: str | None) -> tuple[str, str, str, list[tuple[str, str, str, str]], str | None, str]:
|
||||
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, proxy, ""
|
||||
|
||||
|
||||
def _stored_credential(employee_id: str) -> dict:
|
||||
"""从账号记录里取出已保存的登录凭据。"""
|
||||
import json
|
||||
|
||||
from euniv.crypto import decrypt_secret
|
||||
from euniv.db import SessionLocal
|
||||
from euniv.models import Account
|
||||
|
||||
with SessionLocal() as db:
|
||||
account = db.get(Account, (employee_id or "").strip())
|
||||
raw = account.credential_cipher if account is not None else ""
|
||||
if not raw:
|
||||
return {}
|
||||
try:
|
||||
data = json.loads(decrypt_secret(raw))
|
||||
except Exception:
|
||||
log.warning("用户 %s 的已保存凭据无法读取", employee_id, exc_info=True)
|
||||
return {}
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def _login_direct_client(client: EunivClient, employee_id: str, password: str
|
||||
) -> tuple[str, str, str, list[tuple[str, str, str, str]], str | None, str]:
|
||||
from euniv.client import LoginRejected, ManualJigsaw
|
||||
from euniv.db import SessionLocal
|
||||
from euniv.service import _persist
|
||||
|
||||
if not password:
|
||||
return "", "", "", [], None, "expired"
|
||||
try:
|
||||
profile = client.login(manual=False)
|
||||
with SessionLocal() as db:
|
||||
_persist(db, employee_id, password, client, profile)
|
||||
log.info("用户 %s 直连复查确认凭据已失效,已用本机网络重新登录", employee_id)
|
||||
return _session_export(client, None)
|
||||
except (SessionExpired, LoginRejected, ManualJigsaw, RuntimeError) as exc:
|
||||
log.warning("用户 %s 直连重新登录失败: %s", employee_id, exc)
|
||||
return "", "", "", [], None, "expired"
|
||||
|
||||
|
||||
def _continue_direct(employee_id: str, password: str
|
||||
) -> tuple[str, str, str, list[tuple[str, str, str, str]], str | None, str]:
|
||||
"""代理上像是未登录。用账号里的凭据走本机网络再查一次,还有效就继续,不再登录。"""
|
||||
from euniv.proxy_pool import force_direct
|
||||
|
||||
force_direct(employee_id)
|
||||
credential = _stored_credential(employee_id)
|
||||
client = EunivClient(employee_id, password, proxy=None)
|
||||
try:
|
||||
if credential.get("yxt_token") or credential.get("ucs_token"):
|
||||
client.restore(credential)
|
||||
try:
|
||||
alive = client.credential_alive()
|
||||
except Exception as exc:
|
||||
log.warning("用户 %s 直连复查凭据失败: %s", employee_id, exc)
|
||||
return "", "", "", [], None, "network"
|
||||
if alive:
|
||||
client._ensure_site()
|
||||
log.info("用户 %s 凭据经直连复查仍然有效,改为直连继续,不重新登录", employee_id)
|
||||
return _session_export(client, None)
|
||||
return _login_direct_client(client, employee_id, password)
|
||||
finally:
|
||||
client.close()
|
||||
|
||||
|
||||
def _prepare_session(employee_id: str, password: str,
|
||||
credential: dict, proxy: str | None = None,
|
||||
use_pool: bool = False
|
||||
@@ -1740,16 +1868,14 @@ def _prepare_session(employee_id: str, password: str,
|
||||
try:
|
||||
client.restore(credential)
|
||||
if not client.credential_alive():
|
||||
if use_pool and current:
|
||||
return _continue_direct(employee_id, password)
|
||||
return "", "", "", [], current, "expired"
|
||||
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, ""
|
||||
return _session_export(client, current)
|
||||
except SessionExpired:
|
||||
if use_pool and current:
|
||||
return _continue_direct(employee_id, password)
|
||||
return "", "", "", [], current, "expired"
|
||||
except Exception as exc:
|
||||
log.warning("用户 %s 准备会话失败: %s", employee_id, exc)
|
||||
@@ -2007,8 +2133,9 @@ class AutoStudyWorker:
|
||||
_set_user_status(employee_id, state="已停止")
|
||||
return
|
||||
if use_pool:
|
||||
from euniv.proxy_pool import acquire
|
||||
from euniv.proxy_pool import acquire, reset_budget
|
||||
|
||||
await asyncio.to_thread(reset_budget, employee_id)
|
||||
proxy = await asyncio.to_thread(acquire, employee_id)
|
||||
if user_stop.is_set():
|
||||
_set_user_status(employee_id, state="已停止")
|
||||
@@ -2035,7 +2162,8 @@ class AutoStudyWorker:
|
||||
return
|
||||
|
||||
async with StudySession(
|
||||
token, cookies, proxy=proxy, employee_id=employee_id, use_pool=use_pool
|
||||
token, cookies, proxy=proxy, employee_id=employee_id, use_pool=use_pool,
|
||||
password=password,
|
||||
) as session:
|
||||
if user_stop.is_set():
|
||||
_set_user_status(employee_id, state="已停止")
|
||||
|
||||
Reference in New Issue
Block a user