feat: 登录后进入实时首页,并加密保存可刷新的登录凭证

This commit is contained in:
2026-10-26 18:12:00 +08:00
parent eaad01d5a8
commit 91707f959f
14 changed files with 748 additions and 136 deletions
+121
View File
@@ -76,11 +76,17 @@ def jigsaw_offset(big_png: bytes, small_png: bytes, top: int) -> int:
return best_x
class SessionExpired(RuntimeError):
"""学习平台凭证失效,需要重新登录。"""
class EunivClient:
def __init__(self, login_name: str, password: str) -> None:
self.login_name = login_name.strip()
self.password = password
self.client = httpx.Client(timeout=30, follow_redirects=True, headers={"User-Agent": USER_AGENT})
self._profile: dict = {}
self._yxt_token = ""
def close(self) -> None:
self.client.close()
@@ -220,14 +226,72 @@ class EunivClient:
if code != "0000" or not isinstance(redirect_url, str):
raise RuntimeError(f"申请学习平台授权码失败:{message}")
self.client.get(redirect_url, headers={"Referer": PORTAL + "/", "User-Agent": USER_AGENT})
self._profile = {
"token": str(profile.get("token") or ""),
"accountId": account_id,
"userId": user_id,
"ssoinfo": str(profile.get("ssoinfo") or ""),
"unionId": str(profile.get("unionId") or ""),
}
self._yxt_token = ""
self.session_token()
def export_credential(self) -> dict:
profile = self._profile
return {
"ucs_token": str(profile.get("token") or ""),
"ucs_account_id": str(profile.get("accountId") or ""),
"ucs_user_id": str(profile.get("userId") or ""),
"ucs_ssoinfo": str(profile.get("ssoinfo") or ""),
"ucs_union_id": str(profile.get("unionId") or ""),
"yxt_token": self.session_token(),
}
def restore(self, credential: dict) -> None:
self._profile = {
"token": str(credential.get("ucs_token") or ""),
"accountId": str(credential.get("ucs_account_id") or ""),
"userId": str(credential.get("ucs_user_id") or ""),
"ssoinfo": str(credential.get("ucs_ssoinfo") or ""),
"unionId": str(credential.get("ucs_union_id") or ""),
}
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="/")
def session_token(self) -> str:
for cookie in self.client.cookies.jar:
if cookie.name == "ELEARNING_00024" and cookie.value:
self._yxt_token = cookie.value
return cookie.value
if self._yxt_token:
return self._yxt_token
names = sorted({cookie.name for cookie in self.client.cookies.jar})
raise RuntimeError("学习平台没有返回登录会话,现有 Cookie 名称:" + ", ".join(names))
def _request(self, method: str, url: str, **kwargs) -> httpx.Response:
headers = self.api_headers()
extra = kwargs.pop("headers", None)
if extra:
headers.update(extra)
response = self.client.request(method, url, headers=headers, **kwargs)
refreshed = response.headers.get("token") or response.headers.get("Token")
if refreshed:
self._yxt_token = refreshed
self.client.cookies.set("ELEARNING_00024", refreshed, domain="euniv.zte.com.cn", path="/")
for cookie in self.client.cookies.jar:
if cookie.name == "ELEARNING_00024" and cookie.value:
self._yxt_token = cookie.value
if response.status_code in (401, 403):
raise SessionExpired("学习平台登录已失效")
if response.headers.get("content-type", "").startswith("application/json"):
payload = response.json()
if isinstance(payload, dict) and str(payload.get("code")) in {"401", "403"}:
raise SessionExpired("学习平台登录已失效")
return response
def user_info(self) -> dict:
response = self.client.post(
f"{YXT_API}/v1/customdiy/user/getuserinfobyid",
@@ -292,6 +356,63 @@ class EunivClient:
"class_count": class_count,
}
def home_snapshot(self) -> dict:
"""实时读取首页要展示的个人信息,调用方不得把结果写入数据库。"""
info_resp = self._request("POST", f"{YXT_API}/v1/customdiy/user/getuserinfobyid", content=b"")
info = info_resp.json()
if not isinstance(info, dict) or "cnName" not in info:
raise RuntimeError("用户信息返回无法识别")
period_resp = self._request("GET", f"{STUDY_API}/v1/frw/user/info")
period = period_resp.json()
if not isinstance(period, dict) or "yearScores" not in period:
raise RuntimeError("本年和本月学分返回无法识别")
score_resp = self._request("POST", f"{YXT_API}/v1/customapiforweb/getscoreorpointorhour", json={})
score_payload = score_resp.json()
score = score_payload.get("data") or {}
if score_payload.get("code") not in (None, "0", 0):
raise RuntimeError(score_payload.get("message") or "学时学分查询失败")
today_resp = self._request("GET", f"{STUDY_API}/v1/studyapi/studyhour/todayscorehours")
today = today_resp.json()
exam_resp = self._request("POST", f"{YXT_API}/v1/user/getmyexamcountnew", content=b"")
exam_payload = exam_resp.json()
exam = exam_payload.get("data") or {}
pending_count = int(exam.get("preExamCount") or 0)
return {
"name": info.get("cnName") or "",
"avatar": info.get("headPictureUrl") or "",
"department": info.get("departmentName") or "",
"level": period.get("levelName") or info.get("userClassLevelName") or "",
"year_score": period.get("yearScores") or "0.00",
"month_score": period.get("monthScores") or "0.00",
"total_hours": score.get("actualStudyHour") or "",
"total_score": score.get("actualStudyScore") or period.get("totalScores") or "",
"today_hours": today.get("studyHours"),
"today_score": today.get("studyScore"),
"pending_exam_count": pending_count,
"pending_exams": self._pending_exams(pending_count),
}
def _pending_exams(self, count: int) -> list[dict]:
if count <= 0:
return []
response = self._request(
"GET",
f"{EUNIV}/exam/userallexam.htm",
headers={"Accept": "text/html,application/xhtml+xml"},
)
names = []
for match in response.text.split("lblExamName"):
if ">" not in match:
continue
text = match.split(">", 1)[1].split("<", 1)[0].strip()
if text:
names.append(text)
return [{"name": name, "deadline": ""} for name in names]
def open_session(self) -> dict:
profile = self.login()
self.authorize(profile)