802 lines
32 KiB
Python
802 lines
32 KiB
Python
"""自动学习:asyncio 并发遍历用户和课程,发送心跳积累学时。
|
||
|
||
架构:
|
||
- 一个后台线程运行独立的 asyncio 事件循环
|
||
- 每个用户一个协程,asyncio.gather 并行
|
||
- 全局 Semaphore 控制总并发,避免压爆上游
|
||
- 每个用户一个 StudySession(httpx.AsyncClient),代理仅 HTTP/HTTPS/SOCKS4/SOCKS5
|
||
- 每个用户可配置同时学几门课(当前默认 1,结构已预留)
|
||
- 心跳间隔用 asyncio.sleep,不占线程
|
||
- 本月学时:看完一门视频后刷新,学习过程中每 5 分钟刷新;达到阈值即停止该账号
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
import contextlib
|
||
import hashlib
|
||
import json
|
||
import logging
|
||
import random
|
||
import re
|
||
import threading
|
||
from datetime import datetime, timezone
|
||
|
||
import httpx
|
||
from sqlalchemy import select
|
||
|
||
from euniv.client import EUNIV, STUDY_API, USER_AGENT, EunivClient, SessionExpired
|
||
from euniv.models import Account, Course
|
||
|
||
log = logging.getLogger(__name__)
|
||
|
||
_SCORM_MD5_KEY = "60db8c0a-72d8-4b8f-bb45-c4c3f29a2696"
|
||
_MAX_CONCURRENT_USERS = 8
|
||
_MAX_COURSE_PER_USER = 1
|
||
_HOURS_REFRESH_SECONDS = 300.0
|
||
|
||
_lock = threading.Lock()
|
||
_status: dict = {"running": False, "users": {}, "message": "", "updated_at": ""}
|
||
|
||
|
||
def autostudy_status() -> dict:
|
||
with _lock:
|
||
return dict(_status)
|
||
|
||
|
||
def _set_status(**kw: object) -> None:
|
||
with _lock:
|
||
_status.update(kw)
|
||
_status["updated_at"] = datetime.now(timezone.utc).isoformat()
|
||
|
||
|
||
def _set_user_status(employee_id: str, **kw: object) -> None:
|
||
with _lock:
|
||
users = _status.setdefault("users", {})
|
||
info = users.setdefault(employee_id, {})
|
||
info.update(kw)
|
||
_status["updated_at"] = datetime.now(timezone.utc).isoformat()
|
||
|
||
|
||
def _clear_user_status(employee_id: str) -> None:
|
||
with _lock:
|
||
_status.get("users", {}).pop(employee_id, None)
|
||
|
||
|
||
# ── 课程路径解析 ──
|
||
|
||
_ID_RE = re.compile(r"([0-9a-fA-F]{32})")
|
||
|
||
|
||
def _knowledge_id_from_path(path: str) -> str:
|
||
m = _ID_RE.search(path.replace("-", "").split(".")[0].split("/")[-1])
|
||
return m.group(1) if m else ""
|
||
|
||
|
||
def _course_type(kind: str, path: str) -> str:
|
||
if kind == "课程包" or "/package/" in path:
|
||
return "package"
|
||
if kind == "课程" or "/scorm/" in path:
|
||
return "scorm"
|
||
if kind == "视频" or "/video/" in path:
|
||
return "video"
|
||
if kind in ("文档", "") or "/document/" in path:
|
||
return "document"
|
||
return "unknown"
|
||
|
||
|
||
def _play_path(kind: str, path: str, kid: str) -> str:
|
||
ctype = _course_type(kind, path)
|
||
if ctype == "video":
|
||
return f"/kng/view/video/{kid}.html"
|
||
if ctype == "document":
|
||
return f"/kng/view/document/{kid}.html"
|
||
if ctype == "scorm":
|
||
return f"/kng/view/scorm/{kid}.html"
|
||
return path
|
||
|
||
|
||
def _jitter(seconds: int) -> float:
|
||
delta = random.uniform(-3.0, 3.0)
|
||
return max(5.0, seconds + delta)
|
||
|
||
|
||
def _scorm_md5(body_json: str) -> str:
|
||
return hashlib.md5((body_json + _SCORM_MD5_KEY).encode("utf-8")).hexdigest()
|
||
|
||
|
||
def _parse_minutes(value: str) -> int:
|
||
if not value:
|
||
return 0
|
||
m = re.search(r"(\d+)", value)
|
||
return int(m.group(1)) if m else 0
|
||
|
||
|
||
async def wait_stop(timeout: float, *events: asyncio.Event) -> bool:
|
||
"""等到任一事件触发或超时。触发返回 True,超时返回 False。"""
|
||
if any(event.is_set() for event in events):
|
||
return True
|
||
if timeout <= 0:
|
||
return False
|
||
tasks = [asyncio.create_task(event.wait()) for event in events]
|
||
done, pending = await asyncio.wait(tasks, timeout=timeout, return_when=asyncio.FIRST_COMPLETED)
|
||
for task in pending:
|
||
task.cancel()
|
||
if pending:
|
||
await asyncio.gather(*pending, return_exceptions=True)
|
||
return bool(done)
|
||
|
||
|
||
class HoursWatcher:
|
||
"""刷新本月学时。看完视频或每 5 分钟查一次,达标后停止该账号。"""
|
||
|
||
def __init__(
|
||
self,
|
||
session: "StudySession",
|
||
employee_id: str,
|
||
target: int,
|
||
user_stop: asyncio.Event,
|
||
interval: float = _HOURS_REFRESH_SECONDS,
|
||
) -> None:
|
||
self.session = session
|
||
self.employee_id = employee_id
|
||
self.target = target
|
||
self.user_stop = user_stop
|
||
self.interval = interval
|
||
self._lock = asyncio.Lock()
|
||
self.reached = False
|
||
|
||
async def refresh(self) -> bool:
|
||
async with self._lock:
|
||
if self.reached or self.user_stop.is_set():
|
||
return True
|
||
try:
|
||
text = await self.session.month_hours_text()
|
||
current = _parse_minutes(text)
|
||
if text:
|
||
await asyncio.to_thread(_update_month_hours, self.employee_id, text)
|
||
if current >= self.target:
|
||
self.reached = True
|
||
self.user_stop.set()
|
||
_set_user_status(self.employee_id, state="已达标")
|
||
return True
|
||
except Exception:
|
||
log.warning("用户 %s 刷新本月学时失败", self.employee_id, exc_info=True)
|
||
return False
|
||
|
||
async def ticker(self, global_stop: asyncio.Event) -> None:
|
||
while not global_stop.is_set() and not self.user_stop.is_set():
|
||
if await wait_stop(self.interval, global_stop, self.user_stop):
|
||
return
|
||
await self.refresh()
|
||
|
||
|
||
# ── Async 学习会话 ──
|
||
|
||
class StudySession:
|
||
"""一个用户的异步学习会话。包装 httpx.AsyncClient,提供心跳提交方法。
|
||
|
||
proxy 为 httpx URL,仅 HTTP/HTTPS/SOCKS4/SOCKS5。空值直连。
|
||
"""
|
||
|
||
def __init__(self, token: str, cookies: list[tuple[str, str, str, str]],
|
||
proxy: str | None = None) -> None:
|
||
from euniv.proxy import parse_proxy
|
||
|
||
self._token = token
|
||
self._initial_cookies = cookies
|
||
self._proxy = parse_proxy(proxy)
|
||
self._client: httpx.AsyncClient | None = None
|
||
|
||
async def __aenter__(self) -> "StudySession":
|
||
self._client = httpx.AsyncClient(
|
||
timeout=30,
|
||
follow_redirects=True,
|
||
proxy=self._proxy,
|
||
headers={"User-Agent": USER_AGENT},
|
||
)
|
||
for name, value, domain, path in self._initial_cookies:
|
||
self._client.cookies.set(name, value, domain=domain, path=path)
|
||
return self
|
||
|
||
async def __aexit__(self, *args: object) -> None:
|
||
if self._client:
|
||
await self._client.aclose()
|
||
|
||
def _api_headers(self) -> dict[str, str]:
|
||
return {
|
||
"Accept": "application/json, text/plain, */*",
|
||
"Content-Type": "application/json",
|
||
"Origin": EUNIV,
|
||
"Referer": EUNIV + "/",
|
||
"source": "501",
|
||
"token": self._token,
|
||
"User-Agent": USER_AGENT,
|
||
}
|
||
|
||
async def _api(self, method: str, url: str, **kw: object) -> httpx.Response:
|
||
assert self._client is not None
|
||
headers = self._api_headers()
|
||
extra = kw.pop("headers", None)
|
||
if extra and isinstance(extra, dict):
|
||
headers.update(extra)
|
||
resp = await self._client.request(method, url, headers=headers, **kw)
|
||
refreshed = resp.headers.get("token") or resp.headers.get("Token")
|
||
if refreshed:
|
||
self._token = refreshed
|
||
if resp.status_code in (401, 403):
|
||
raise SessionExpired("学习平台登录已失效")
|
||
if resp.headers.get("content-type", "").startswith("application/json"):
|
||
try:
|
||
payload = resp.json()
|
||
if isinstance(payload, dict) and str(payload.get("code")) in {"401", "403"}:
|
||
raise SessionExpired("学习平台登录已失效")
|
||
except (json.JSONDecodeError, ValueError):
|
||
pass
|
||
return resp
|
||
|
||
async def update_progress(self, kid: str, pkg_id: str = "") -> dict:
|
||
resp = await self._api("POST", f"{STUDY_API}/v1/study/updateprogress",
|
||
json={"knowledgeId": kid, "packageId": pkg_id,
|
||
"masterId": "", "masterType": ""})
|
||
return resp.json()
|
||
|
||
async def sync_package(self, kid: str) -> dict:
|
||
resp = await self._api("GET", f"{STUDY_API}/v1/uk/syncpackage",
|
||
params={"knowledgeId": kid, "sourceType": "SingleStudy", "masterId": ""})
|
||
return resp.json()
|
||
|
||
async def get_encrypt_request(self, body_json: str) -> str:
|
||
assert self._client is not None
|
||
resp = await self._client.post(
|
||
f"{EUNIV}/kng/services/KngComService.svc/GetEncryptRequest",
|
||
json={"body": body_json},
|
||
headers={"Content-Type": "text/json", "User-Agent": USER_AGENT},
|
||
)
|
||
data = resp.json()
|
||
if isinstance(data, str):
|
||
data = json.loads(data)
|
||
if data.get("Status") == "OK":
|
||
return str(data["Data"])
|
||
raise RuntimeError(f"GetEncryptRequest 失败: {data}")
|
||
|
||
async def submit_video_heartbeat(self, kid: str, pkg_id: str,
|
||
study_time: int, view_schedule: int) -> dict:
|
||
param = {
|
||
"knowledgeId": kid, "masterId": "", "masterType": "",
|
||
"packageId": pkg_id, "pageSize": 1, "studySize": 1,
|
||
"studyTime": study_time, "type": 0, "offLine": False,
|
||
"end": False, "care": True, "deviceId": "",
|
||
"studyChapterIds": "", "viewSchedule": view_schedule,
|
||
}
|
||
encrypt_body = json.dumps(param, separators=(",", ":"))
|
||
encryption = await self.get_encrypt_request(encrypt_body)
|
||
param["encryption"] = encryption
|
||
param["multiple"] = 1
|
||
param["realHour"] = study_time
|
||
resp = await self._api("POST", f"{STUDY_API}/v1/study/submitpro",
|
||
content=json.dumps(param, separators=(",", ":")))
|
||
text = resp.text.strip()
|
||
return resp.json() if text else {}
|
||
|
||
async def submit_document_heartbeat(self, kid: str, pkg_id: str,
|
||
page_size: int, study_time: int,
|
||
view_schedule: int) -> None:
|
||
param = {
|
||
"knowledgeId": kid, "masterId": "", "masterType": "",
|
||
"packageId": pkg_id, "pageSize": page_size, "studySize": page_size,
|
||
"studyTime": study_time, "type": 1, "offLine": False,
|
||
"end": False, "care": True, "deviceId": "",
|
||
"studyChapterIds": "", "viewSchedule": view_schedule,
|
||
}
|
||
encrypt_body = json.dumps(param, separators=(",", ":"))
|
||
encryption = await self.get_encrypt_request(encrypt_body)
|
||
param["multiple"] = 1
|
||
param["realHour"] = study_time
|
||
await self._api("POST", f"{STUDY_API}/v1/study/submit?encryption={encryption}",
|
||
content=json.dumps(param, separators=(",", ":")))
|
||
|
||
async def submit_scorm_heartbeat(self, kid: str, pkg_id: str,
|
||
study_time: int, sco_id: str = "",
|
||
end: bool = False) -> None:
|
||
param = {
|
||
"knowledgeId": kid, "masterId": "", "masterType": "",
|
||
"packageId": pkg_id,
|
||
"pageSize": -1 if end else 1, "studySize": -1 if end else 1,
|
||
"studyTime": study_time, "type": 2, "offLine": False,
|
||
"end": end, "care": True, "deviceId": "",
|
||
"studyChapterIds": sco_id, "viewSchedule": 0,
|
||
}
|
||
if end:
|
||
encryption = _scorm_md5(json.dumps(param, separators=(",", ":")))
|
||
else:
|
||
encrypt_body = json.dumps(param, separators=(",", ":"))
|
||
encryption = await self.get_encrypt_request(encrypt_body)
|
||
param["multiple"] = 1
|
||
param["realHour"] = study_time
|
||
await self._api("POST", f"{STUDY_API}/v1/study/submit?encryption={encryption}",
|
||
content=json.dumps(param, separators=(",", ":")))
|
||
|
||
async def scorm_count(self, kid: str) -> int:
|
||
resp = await self._api("GET", f"{STUDY_API}/v1/kng/scorm/count/",
|
||
params={"knowledgeId": kid})
|
||
return int(resp.json().get("scocnt") or 1)
|
||
|
||
async def scorm_get(self, user_id: str, sco_id: str) -> dict:
|
||
resp = await self._api("GET", f"https://api-mall.yxt.com/v1/scormstudy/{user_id}/{sco_id}")
|
||
text = resp.text.strip()
|
||
return resp.json() if text else {}
|
||
|
||
async def scorm_save(self, session_id: str, org_id: str, user_id: str,
|
||
scorm_id: str, scorm_id_ori: str, sco_cnt: int,
|
||
pkg_id: str, data: dict) -> None:
|
||
await self._api("POST", "https://api-mall.yxt.com/v1/scormstudy", json={
|
||
"sessionId": session_id, "orgId": org_id, "userId": user_id,
|
||
"scormId": scorm_id, "scormIdOri": scorm_id_ori,
|
||
"masterId": "", "masterType": "", "packageId": pkg_id,
|
||
"scocnt": sco_cnt, "data": data,
|
||
})
|
||
|
||
async def course_page_params(self, path: str) -> dict:
|
||
assert self._client is not None
|
||
resp = await self._client.get(
|
||
f"{EUNIV}{path}",
|
||
headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"},
|
||
)
|
||
html = resp.text
|
||
|
||
def _var(name: str, default: str = "") -> str:
|
||
m = re.search(rf'(?:var\s+)?{name}\s*=\s*["\']?([^"\';\r\n]+)', html)
|
||
return m.group(1).strip() if m else default
|
||
|
||
return {
|
||
"submitProTimes": int(_var("submitProTimes", "30") or 30),
|
||
"validtimeSpan": int(_var("validtimeSpan", "120") or 120),
|
||
"pageSize": int(_var("pageSize", "1") or 1),
|
||
"userID": _var("userID"),
|
||
"orgID": _var("orgID"),
|
||
}
|
||
|
||
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 + "/"})
|
||
urls: list[str] = []
|
||
for m in re.finditer(r'["\']([^"\']+\.oss\.js)["\']', resp.text):
|
||
raw = m.group(1)
|
||
if raw.startswith("http"):
|
||
urls.append(raw)
|
||
elif raw.startswith("//"):
|
||
urls.append("https:" + raw)
|
||
elif raw.startswith("/"):
|
||
urls.append(f"https://cdn-cos-file.yunxuetang.cn{raw}")
|
||
else:
|
||
urls.append(f"https://cdn-cos-file.yunxuetang.cn/zt/scorm/{kid}/h5/js/{raw}")
|
||
answers: list[dict] = []
|
||
for url in urls:
|
||
try:
|
||
r = await self._client.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:
|
||
continue
|
||
return answers
|
||
|
||
async def month_hours_text(self) -> str:
|
||
assert self._client is not None
|
||
resp = await self._client.get(
|
||
f"{EUNIV}/study/myperiod.htm",
|
||
headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/sty/index.htm"},
|
||
)
|
||
m = re.search(r'id="spMonthlyPeriod" title="(\d+)分钟"', resp.text)
|
||
return m.group(1) if m else ""
|
||
|
||
|
||
# ── 单门课程的学习协程 ──
|
||
|
||
def _halted(global_stop: asyncio.Event, hours: HoursWatcher) -> bool:
|
||
return global_stop.is_set() or hours.user_stop.is_set()
|
||
|
||
|
||
async def _study_video(session: StudySession, kid: str, pkg_id: str,
|
||
interval: int, stop: asyncio.Event, hours: HoursWatcher) -> None:
|
||
view = 0
|
||
started = False
|
||
while not _halted(stop, hours):
|
||
progress = await session.update_progress(kid, pkg_id)
|
||
schedule = float(progress.get("studyschedule", 0))
|
||
if schedule >= 100:
|
||
if started:
|
||
await hours.refresh()
|
||
return
|
||
started = True
|
||
view = int(progress.get("viewSchedule", view))
|
||
view += interval
|
||
result = await session.submit_video_heartbeat(kid, pkg_id, interval, view)
|
||
new_schedule = result.get("studySchedule")
|
||
if new_schedule is not None and float(new_schedule) >= 100:
|
||
await hours.refresh()
|
||
return
|
||
await wait_stop(_jitter(interval), stop, hours.user_stop)
|
||
|
||
|
||
async def _study_document(session: StudySession, kid: str, pkg_id: str,
|
||
page_size: int, interval: int, stop: asyncio.Event,
|
||
hours: HoursWatcher) -> None:
|
||
view = 1
|
||
while not _halted(stop, hours):
|
||
progress = await session.update_progress(kid, pkg_id)
|
||
if float(progress.get("studyschedule", 0)) >= 100:
|
||
return
|
||
await session.submit_document_heartbeat(kid, pkg_id, page_size, interval, view)
|
||
await wait_stop(_jitter(interval), stop, hours.user_stop)
|
||
|
||
|
||
async def _study_scorm(session: StudySession, kid: str, pkg_id: str,
|
||
interval: int, stop: asyncio.Event, hours: HoursWatcher,
|
||
user_id: str, org_id: str) -> None:
|
||
import uuid as _uuid
|
||
sco_cnt = await session.scorm_count(kid)
|
||
session_id = str(_uuid.uuid4())
|
||
sco_id = kid
|
||
|
||
existing = await session.scorm_get(user_id, sco_id)
|
||
scorm_data = existing.get("data") if existing else None
|
||
if not scorm_data or not isinstance(scorm_data, dict):
|
||
scorm_data = {
|
||
"cmi__core__lesson_status": "completed",
|
||
"cmi__core__lesson_location": "1",
|
||
"cmi__core__lesson_progress": "1.00",
|
||
"cmi__core__session_time": "00:00:01",
|
||
"cmi__core__exit": "suspend",
|
||
"cmi__suspend_data": "",
|
||
}
|
||
else:
|
||
scorm_data["cmi__core__lesson_status"] = "completed"
|
||
scorm_data["cmi__core__lesson_progress"] = "1.00"
|
||
|
||
answers = await session.scorm_extract_answers(kid)
|
||
total_pages = max(len(answers), 10)
|
||
|
||
for page_idx in range(total_pages):
|
||
if _halted(stop, hours):
|
||
return
|
||
scorm_data["cmi__core__lesson_location"] = str(page_idx + 1)
|
||
scorm_data["cmi__core__session_time"] = "00:00:01"
|
||
await session.scorm_save(
|
||
session_id=session_id, org_id=org_id, user_id=user_id,
|
||
scorm_id=sco_id, scorm_id_ori=kid, sco_cnt=sco_cnt,
|
||
pkg_id=pkg_id, data=scorm_data,
|
||
)
|
||
await session.submit_scorm_heartbeat(kid, pkg_id, interval, sco_id=sco_id, end=True)
|
||
progress = await session.update_progress(kid, pkg_id)
|
||
if float(progress.get("studyschedule", 0)) >= 100:
|
||
return
|
||
await wait_stop(_jitter(min(interval, 5)), stop, hours.user_stop)
|
||
|
||
while not _halted(stop, hours):
|
||
progress = await session.update_progress(kid, pkg_id)
|
||
if float(progress.get("studyschedule", 0)) >= 100:
|
||
return
|
||
await session.submit_scorm_heartbeat(kid, pkg_id, interval, sco_id=sco_id, end=False)
|
||
await wait_stop(_jitter(interval), stop, hours.user_stop)
|
||
|
||
|
||
async def _study_package(session: StudySession, kid: str, intervals: dict,
|
||
auto_mode: bool, stop: asyncio.Event, hours: HoursWatcher,
|
||
user_id: str, org_id: str) -> None:
|
||
pkg = await session.sync_package(kid)
|
||
chapters = pkg.get("userKnowledgeList") or []
|
||
for ch in chapters:
|
||
if _halted(stop, hours):
|
||
return
|
||
if float(ch.get("studySchedule", 0)) >= 100:
|
||
continue
|
||
ch_kid = str(ch.get("knowledgeId") or "").replace("-", "")
|
||
ch_title = ch.get("title") or ch_kid
|
||
if not ch_kid:
|
||
continue
|
||
_set_user_status(session._employee_id, course=ch_title)
|
||
|
||
is_video = "Video" in str(ch.get("knowledgeType") or "")
|
||
ch_type = "video" if is_video else "document"
|
||
ch_interval = intervals.get(ch_type, 30 if is_video else 120)
|
||
page_size = 1
|
||
|
||
if auto_mode:
|
||
try:
|
||
params = await session.course_page_params(
|
||
f"/kng/course/package/{ch_type}/{kid}_{ch_kid}.html")
|
||
ch_interval = params.get("submitProTimes" if is_video else "validtimeSpan", ch_interval)
|
||
page_size = params.get("pageSize", 1)
|
||
except Exception:
|
||
pass
|
||
|
||
if is_video:
|
||
await _study_video(session, ch_kid, kid, ch_interval, stop, hours)
|
||
else:
|
||
await _study_document(session, ch_kid, kid, page_size, ch_interval, stop, hours)
|
||
|
||
|
||
# ── 同步准备:用 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()
|
||
|
||
|
||
# ── Worker 主循环 ──
|
||
|
||
class AutoStudyWorker:
|
||
"""后台 asyncio 事件循环,管理所有用户的自动学习。"""
|
||
|
||
def __init__(self) -> None:
|
||
self._stop_flag = threading.Event()
|
||
self._thread: threading.Thread | None = None
|
||
self._loop: asyncio.AbstractEventLoop | None = None
|
||
self._async_stop: asyncio.Event | None = None
|
||
|
||
def start(self) -> None:
|
||
self._thread = threading.Thread(target=self._run_thread, name="euniv-autostudy", daemon=True)
|
||
self._thread.start()
|
||
|
||
def stop(self) -> None:
|
||
self._stop_flag.set()
|
||
if self._loop and self._async_stop:
|
||
self._loop.call_soon_threadsafe(self._async_stop.set)
|
||
|
||
def _run_thread(self) -> None:
|
||
self._loop = asyncio.new_event_loop()
|
||
asyncio.set_event_loop(self._loop)
|
||
self._async_stop = asyncio.Event()
|
||
try:
|
||
self._loop.run_until_complete(self._main_loop())
|
||
finally:
|
||
self._loop.close()
|
||
|
||
async def _main_loop(self) -> None:
|
||
assert self._async_stop is not None
|
||
await asyncio.sleep(15)
|
||
while not self._async_stop.is_set():
|
||
try:
|
||
await self._run_cycle()
|
||
except Exception as exc:
|
||
log.exception("自动学习周期异常: %s", exc)
|
||
_set_status(message=f"异常: {exc}")
|
||
try:
|
||
await asyncio.wait_for(self._async_stop.wait(), timeout=random.uniform(300, 600))
|
||
return
|
||
except asyncio.TimeoutError:
|
||
pass
|
||
|
||
async def _run_cycle(self) -> None:
|
||
assert self._async_stop is not None
|
||
from admin.settings import heartbeat_intervals
|
||
from euniv.crypto import decrypt_secret
|
||
from euniv.db import SessionLocal
|
||
|
||
intervals_cfg = heartbeat_intervals()
|
||
auto_mode = intervals_cfg["mode"] == "auto"
|
||
intervals = {
|
||
"video": intervals_cfg["video"],
|
||
"document": intervals_cfg["document"],
|
||
"scorm": intervals_cfg["scorm"],
|
||
}
|
||
|
||
with SessionLocal() as db:
|
||
users = db.execute(
|
||
select(Account.employee_id, Account.monthly_target, Account.month_hours,
|
||
Account.credential_cipher, Account.password_cipher)
|
||
.where(Account.credential_cipher != "")
|
||
.where(Account.credential_valid == True)
|
||
.order_by(Account.employee_id)
|
||
).all()
|
||
courses = db.scalars(select(Course).order_by(Course.title)).all()
|
||
course_list = [(c.path, c.title, c.kind) for c in courses]
|
||
|
||
if not users or not course_list:
|
||
_set_status(running=False, message="没有可用的用户或课程")
|
||
return
|
||
|
||
eligible = []
|
||
for row in users:
|
||
target = row.monthly_target or 600
|
||
current = _parse_minutes(row.month_hours)
|
||
if target > 0 and current < target:
|
||
try:
|
||
password = decrypt_secret(row.password_cipher)
|
||
credential = json.loads(decrypt_secret(row.credential_cipher))
|
||
except Exception:
|
||
continue
|
||
eligible.append((row.employee_id, target, password, credential))
|
||
|
||
if not eligible:
|
||
_set_status(running=False, message="所有用户已达标或无有效凭据")
|
||
return
|
||
|
||
_set_status(running=True, message=f"本轮 {len(eligible)} 个用户")
|
||
|
||
sem = asyncio.Semaphore(_MAX_CONCURRENT_USERS)
|
||
tasks = [
|
||
self._study_user(emp_id, target, pw, cred, course_list, intervals, auto_mode, sem)
|
||
for emp_id, target, pw, cred in eligible
|
||
]
|
||
results = await asyncio.gather(*tasks, return_exceptions=True)
|
||
for emp_id_tuple, result in zip(eligible, results):
|
||
if isinstance(result, Exception):
|
||
log.warning("用户 %s 自动学习失败: %s", emp_id_tuple[0], result)
|
||
_clear_user_status(emp_id_tuple[0])
|
||
|
||
_set_status(running=False, message="本轮完成")
|
||
|
||
async def _study_user(self, employee_id: str, target: int,
|
||
password: str, credential: dict,
|
||
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="")
|
||
|
||
# 后续从账号读取 HTTP/SOCKS 代理 URL 和同时学习门数
|
||
from euniv.proxy import parse_proxy
|
||
|
||
proxy = None
|
||
max_courses = _MAX_COURSE_PER_USER
|
||
try:
|
||
proxy = parse_proxy(proxy)
|
||
except ValueError:
|
||
_set_user_status(employee_id, state="代理无效")
|
||
return
|
||
|
||
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():
|
||
return
|
||
ticker = asyncio.create_task(hours.ticker(self._async_stop))
|
||
try:
|
||
if max_courses <= 1:
|
||
await self._study_courses_serial(
|
||
session, employee_id, course_list, intervals,
|
||
auto_mode, hours, user_id, org_id)
|
||
else:
|
||
await self._study_courses_parallel(
|
||
session, employee_id, course_list, intervals,
|
||
auto_mode, hours, user_id, org_id, max_courses)
|
||
finally:
|
||
ticker.cancel()
|
||
with contextlib.suppress(asyncio.CancelledError):
|
||
await ticker
|
||
|
||
async def _study_courses_serial(self, session: StudySession, employee_id: str,
|
||
course_list: list, intervals: dict,
|
||
auto_mode: bool, hours: HoursWatcher,
|
||
user_id: str, org_id: str) -> None:
|
||
assert self._async_stop is not None
|
||
for path, title, kind in course_list:
|
||
if _halted(self._async_stop, hours):
|
||
return
|
||
await self._study_one_course(
|
||
session, employee_id, path, title, kind,
|
||
intervals, auto_mode, hours, user_id, org_id)
|
||
|
||
async def _study_courses_parallel(self, session: StudySession, employee_id: str,
|
||
course_list: list, intervals: dict,
|
||
auto_mode: bool, hours: HoursWatcher,
|
||
user_id: str, org_id: str,
|
||
max_courses: int) -> None:
|
||
"""同一用户同时学多门课。共享会话和学时监视。"""
|
||
assert self._async_stop is not None
|
||
course_sem = asyncio.Semaphore(max_courses)
|
||
|
||
async def guarded(path: str, title: str, kind: str) -> None:
|
||
if _halted(self._async_stop, hours):
|
||
return
|
||
async with course_sem:
|
||
await self._study_one_course(
|
||
session, employee_id, path, title, kind,
|
||
intervals, auto_mode, hours, user_id, org_id)
|
||
|
||
tasks = [guarded(p, t, k) for p, t, k in course_list]
|
||
await asyncio.gather(*tasks, return_exceptions=True)
|
||
|
||
async def _study_one_course(self, session: StudySession, employee_id: str,
|
||
path: str, title: str, kind: str,
|
||
intervals: dict, auto_mode: bool,
|
||
hours: HoursWatcher, user_id: str, org_id: str) -> None:
|
||
assert self._async_stop is not None
|
||
if _halted(self._async_stop, hours):
|
||
return
|
||
ctype = _course_type(kind, path)
|
||
if ctype == "unknown":
|
||
return
|
||
kid = _knowledge_id_from_path(path)
|
||
if not kid:
|
||
return
|
||
|
||
_set_user_status(employee_id, course=title)
|
||
|
||
try:
|
||
if ctype == "package":
|
||
await _study_package(session, kid, intervals, auto_mode,
|
||
self._async_stop, hours, user_id, org_id)
|
||
else:
|
||
progress = await session.update_progress(kid, "")
|
||
if float(progress.get("studyschedule", 0)) >= 100:
|
||
return
|
||
|
||
interval = intervals.get(ctype, 120)
|
||
page_size = 1
|
||
if auto_mode:
|
||
try:
|
||
params = await session.course_page_params(_play_path(kind, path, kid))
|
||
if ctype == "video":
|
||
interval = params.get("submitProTimes", interval)
|
||
else:
|
||
interval = params.get("validtimeSpan", interval)
|
||
page_size = params.get("pageSize", 1)
|
||
except Exception:
|
||
pass
|
||
|
||
if ctype == "video":
|
||
await _study_video(session, kid, "", interval, self._async_stop, hours)
|
||
elif ctype == "document":
|
||
await _study_document(session, kid, "", page_size, interval, self._async_stop, hours)
|
||
elif ctype == "scorm":
|
||
await _study_scorm(session, kid, "", interval, self._async_stop, hours,
|
||
user_id, org_id)
|
||
except SessionExpired:
|
||
_set_user_status(employee_id, state="会话过期")
|
||
log.info("用户 %s 会话过期", employee_id)
|
||
except Exception as exc:
|
||
log.warning("用户 %s 课程 %s 异常: %s", employee_id, title, exc)
|
||
|
||
|
||
# ── 数据库更新 ──
|
||
|
||
def _update_month_hours(employee_id: str, hours: str) -> None:
|
||
from euniv.db import SessionLocal
|
||
with SessionLocal() as db:
|
||
account = db.get(Account, employee_id)
|
||
if account:
|
||
account.month_hours = hours
|
||
db.commit()
|
||
|
||
|
||
# ── 启动入口 ──
|
||
|
||
_worker: AutoStudyWorker | None = None
|
||
|
||
|
||
def start_autostudy() -> AutoStudyWorker:
|
||
global _worker
|
||
w = AutoStudyWorker()
|
||
_worker = w
|
||
w.start()
|
||
return w
|