feat: 维护中国代理池并支持账号自动均匀使用
This commit is contained in:
+143
-58
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user