Files
EnuivTools/backend/euniv/client.py
T

897 lines
36 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""登录中兴 e 学并查询学时、学分汇总。"""
from __future__ import annotations
import base64
import io
import random
import re
import threading
import time
import uuid
from datetime import datetime
from html import unescape
from urllib.parse import quote
import httpx
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding
from PIL import Image
PORTAL = "https://bmtucportal.zte.com.cn"
EUNIV = "https://euniv.zte.com.cn"
YXT_API = "https://api-qidacustomc1.yunxuetang.cn"
STUDY_API = "https://api-qidac1.yunxuetang.cn"
CLASS_API = "https://sdcs-api-ztec1.yunxuetang.cn"
REDIRECT_URI = f"{YXT_API}/v1/ztctech/sso"
CLIENT_ID = "30051"
TENANT_ID = "10001"
APP_ID = "10051"
USER_AGENT = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:158.0) "
"Gecko/20100101 Firefox/158.0"
)
def now_ms() -> int:
return int(time.time() * 1000)
def make_kid(prefix: str = "t") -> str:
return prefix + "".join(random.choice("1234567890") for _ in range(4))
def encrypt_password(public_key_b64: str, password: str) -> str:
key = serialization.load_der_public_key(base64.b64decode(public_key_b64))
cipher = key.encrypt(password.encode("utf-8"), padding.PKCS1v15())
return base64.b64encode(cipher).decode("ascii")
def decode_data_uri(value: str) -> bytes:
payload = value.split(",", 1)[1] if "," in value else value
return base64.b64decode(payload)
def data_uri(value: str) -> str:
if value.startswith("data:"):
return value
return "data:image/png;base64," + value
def training_form(page: str) -> dict[str, str]:
found: dict[str, str] = {}
for match in re.finditer(r"<input\b[^>]*>", page, re.I):
tag = match.group(0)
if re.search(r"""type=['"]submit['"]""", tag, re.I):
continue
name = re.search(r"""name=['"]([^'"]+)['"]""", tag)
if not name:
continue
value = re.search(r"""value=['"]([^'"]*)['"]""", tag)
raw = value.group(1) if value else ""
found[name.group(1)] = raw.replace("&amp;", "&").replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", '"')
return found
_authorize_guard = threading.Lock()
_authorize_locks: dict[str, threading.Lock] = {}
def _authorize_lock(account_id: str) -> threading.Lock:
with _authorize_guard:
lock = _authorize_locks.get(account_id)
if lock is None:
lock = threading.RLock()
_authorize_locks[account_id] = lock
return lock
_SITE_SHARE_SECONDS = 90
_site_sessions: dict[str, tuple[float, list[tuple[str, str, str, str]]]] = {}
def _remember_site(account_id: str, client: httpx.Client) -> None:
jar = getattr(getattr(client, "cookies", None), "jar", None)
if not account_id or jar is None:
return
dumped = []
for cookie in jar:
dumped.append((cookie.name, cookie.value or "", cookie.domain or "", cookie.path or "/"))
_site_sessions[account_id] = (time.time(), dumped)
def _load_cookies(client: httpx.Client, dumped: list[tuple[str, str, str, str]]) -> None:
for name, value, domain, path in dumped:
client.cookies.set(name, value, domain=domain, path=path)
def _by_closeness(items: list[dict], key: str) -> list[dict]:
ordered = sorted(items, key=lambda item: item.get(key, float("inf")))
for item in ordered:
item.pop(key, None)
return ordered
def parse_training_cards(page: str, status: str) -> list[dict]:
items = []
for block in re.findall(r"<li class='el-plan-li-3'[\s\S]*?</li>", page):
progress = re.search(r'progress="(\d+)"', block)
name = re.search(r'class="font-size-16 text-color6 ellipsis">\s*([^<]+)', block)
owner = re.search(r'<span class="mr10">\s*([^<]+)', block)
assigned = re.search(r"sty_lbl_assignedtime\"><span>([^<]+)", block)
credits = re.search(r"el-plan-time'><span>([^<]+)", block)
detail = re.search(r"""learningKnowledge\(['"](/plan/[0-9a-fA-F]{32}\.html)['"]\)""", block)
assigned_text = ""
if assigned:
assigned_text = assigned.group(1).replace("&nbsp;", " ").replace("\xa0", " ").strip()
items.append({
"name": (name.group(1).strip() if name else ""),
"status": status,
"progress": int(progress.group(1)) if progress else 0,
"owner": (owner.group(1).strip() if owner else ""),
"assigned": assigned_text,
"credits": (credits.group(1).strip() if credits else ""),
"detail": detail.group(1) if detail else "",
"sort_days": _leading_number(assigned_text),
})
return items
def parse_exam_cards(page: str) -> list[dict]:
items = []
for block in re.findall(r'<li name="userExam">[\s\S]*?</li>', page):
name = re.search(r'class="my-exam-title ellipsis">([^<]+)', block)
status_match = re.search(r'my-exam-btn[^"]*"[^>]*value="([^"]+)"', block)
start = re.search(r'sty_lbl_teststarttime"></span>:([^<&]+)', block)
link = re.search(r'href="(/exam/exampreview\.htm\?[^"]+)"', block)
status = status_match.group(1).strip() if status_match else ""
start_text = start.group(1).replace("&nbsp;", " ").strip() if start else ""
detail = unescape(link.group(1)) if link else ""
if not _exam_detail_path(detail):
detail = ""
items.append({
"name": (name.group(1).strip() if name else ""),
"status": status,
"result": _exam_result(block, status),
"start": start_text,
"detail": detail,
"sort_at": _clock_distance(start_text),
})
return items
def parse_exam_detail(page: str) -> dict:
if 'id="lblExamName"' not in page:
raise RuntimeError("考试明细没有获取到")
table = re.search(r'class="mt15 exam-history-table"[\s\S]*?</table>', page)
attempts = []
if table:
for row in re.findall(r"<tr>([\s\S]*?)</tr>", table.group(0))[1:]:
cells = [_plain(cell) for cell in re.findall(r"<td\b[^>]*>([\s\S]*?)</td>", row)]
if len(cells) >= 3 and cells[2] in {"通过", "未通过"}:
attempts.append({"submitted": cells[0], "score": cells[1], "result": cells[2]})
return {
"name": _field(page, "lblExamName"),
"total_score": _field(page, "lblMaxScore"),
"pass_score": _field(page, "lblPassScore"),
"questions": _field(page, "lblTotalQuestionQty"),
"window": _field(page, "lblControlDateTime"),
"times": _field(page, "lblExamTimes"),
"limit": _field(page, "lblExamLimit"),
"examinee": _field(page, "lblUserName"),
"view_policy": _field(page, "lblViewRestrict"),
"notice": _field(page, "lblMsg"),
"attempts": attempts,
}
def parse_training_detail(page: str) -> dict:
if "plandetailhead" not in page:
raise RuntimeError("培训明细没有获取到")
head = page.split('id="knowledgestudy"', 1)[0]
title = re.search(r'class="mb20 span-24 font-size-20">[\s\S]*?<span title="([^"]+)"', head)
rank = re.search(r'sty_lbl_ranknumber">([\s\S]*?)</label>\s*</label>\s*</label>', head)
progress = re.search(r'class="schedule1 floatleft">\s*([^<]+)', head)
deadline = re.search(r'mgt_lbl_requirecompletedate">\s*</label>\s*:\s*([^<\s]+)', head)
credits = re.findall(r">\s*([0-9]+(?:\.[0-9]+)?)\s*<span\s+data-localize=\"sty_lbl_point\"", head)
phases = []
for table in re.split(r'<th width="30"><span class="el-mixtrain-num">', page)[1:]:
phase_name = re.search(r'<th class="text-left">[\s\S]*?<span>([^<]+)</span>', table)
phase_hours = re.search(r":\s*([0-9]+(?:\.[0-9]+)?)\s*<span\s+data-localize=\"sty_lbl_minute\"", table)
phase_credits = re.search(r'common_lbl_totalscore"></span>[\s\S]*?:\s*([0-9]+(?:\.[0-9]+)?)', table)
tasks = []
for row in re.findall(r'<tr class="hand"[\s\S]*?</tr>', table):
task_name = re.search(r"""<span class="st" title=(['"])(.*?)\1""", row)
percents = re.findall(r">(\d+%)<", row)
score = re.search(
r'title="已获学分">\s*([^<]+?)\s*</span>\s*&nbsp;/\s*&nbsp;\s*<span class="fontnumber"\s+title="标准学分">\s*([^<]+)',
row,
)
hours = re.search(
r'core_lbl_knghours"></span>:\s*([^<&]+?)\s*&nbsp;/\s*&nbsp;\s*([^<&]+?)\s*<',
row,
)
tasks.append({
"name": task_name.group(2).strip() if task_name else "",
"progress": percents[-1] if percents else "",
"score": f"{score.group(1).strip()}/{score.group(2).strip()}" if score else "",
"hours": f"{hours.group(1).strip()}/{hours.group(2).strip()}" if hours else "",
})
phases.append({
"name": phase_name.group(1).strip() if phase_name else "",
"hours": phase_hours.group(1) if phase_hours else "",
"credits": phase_credits.group(1) if phase_credits else "",
"tasks": tasks,
})
return {
"name": title.group(1).strip() if title else "",
"owner": _field(head, "lblCertificate"),
"earned_hours": _field(head, "Span1"),
"actual_hours": _field(head, "lblTotalScore"),
"reward_hours": _field(head, "lblPassScore"),
"earned_credits": credits[0] if len(credits) > 0 else "",
"actual_credits": credits[1] if len(credits) > 1 else "",
"reward_credits": credits[2] if len(credits) > 2 else "",
"rank": _plain(rank.group(1)) if rank else "",
"progress": progress.group(1).strip() if progress else "",
"deadline": deadline.group(1) if deadline else "",
"phases": phases,
}
def _exam_result(block: str, status: str) -> str:
state = re.search(r"my-exam-state\s+([A-Za-z]+)", block)
if state and state.group(1).lower() == "pass":
return "已通过"
if state and state.group(1).lower() in {"notpass", "nopass", "fail", "unpass"}:
return "未通过"
if status in {"已完成", "已过期", "未参考"}:
return "未通过"
return ""
def _exam_detail_path(value: str) -> bool:
return bool(re.fullmatch(r"/exam/exampreview\.htm\?[A-Za-z0-9_=&%.\-]+", value)) and "xamArrangeID=" in value
def _field(page: str, element_id: str) -> str:
match = re.search(rf'id="{re.escape(element_id)}"[^>]*>([\s\S]*?)</span>', page)
return _plain(match.group(1)) if match else ""
def _plain(value: str) -> str:
text = re.sub(r"<[^>]+>", " ", value)
return re.sub(r"\s+", " ", text).replace("\xa0", " ").replace("&nbsp;", " ").strip()
_COURSE_KIND = {
"Knowledge_CoursePackage": "课程包",
"Knowledge_Course": "课程",
"Knowledge_Scorm": "课程",
"Knowledge_Video": "视频",
"Knowledge_Audio": "音频",
"Knowledge_Word": "文档",
"Knowledge_PPT": "文档",
"Knowledge_PDF": "文档",
"Knowledge_Excel": "文档",
"Knowledge_SourceCode": "压缩包",
"Knowledge_XuanYes": "微课",
}
def parse_course_page(page: str) -> dict:
total_match = re.search(r"共(\d+)条", page)
courses = []
for row in re.findall(r"<tr>\s*<td>[\s\S]*?</tr>", page):
link = re.search(r'href="(/(?:kng/view|knowledge)/[^"]+)"[^>]*title=\'([^\']*)\'', row)
if not link:
continue
kind = re.search(r'class="(Knowledge_[A-Za-z]+)"', row)
contributor = re.search(r"title='([^']*)'[^>]*href=\"/myhome\.htm", row)
numbers = re.findall(r'<td class="textcenter"\s*>\s*<span class="color5">([^<]*)</span>', row)
comments = re.search(r"<label>\((\d+)\)</label>", row)
courses.append({
"path": link.group(1),
"title": link.group(2).strip(),
"kind": _course_kind(kind.group(1) if kind else "", link.group(1)),
"contributor": contributor.group(1).strip() if contributor else "",
"recommend": numbers[0].strip() if len(numbers) > 0 else "",
"learners": numbers[1].strip() if len(numbers) > 1 else "",
"released_on": numbers[2].strip() if len(numbers) > 2 else "",
"updated_on": numbers[3].strip() if len(numbers) > 3 else "",
"comments": comments.group(1) if comments else "",
})
return {
"courses": courses,
"total": int(total_match.group(1)) if total_match else None,
}
def _course_kind(class_name: str, path: str) -> str:
named = _COURSE_KIND.get(class_name)
if named:
return named
if "/package/" in path:
return "课程包"
if "/scorm/" in path:
return "课程"
if "/video/" in path or "/audio/" in path:
return "视频" if "/video/" in path else "音频"
if "/document/" in path:
return "文档"
return ""
def _leading_number(value: str) -> float:
match = re.search(r"(\d+)", value)
return float(match.group(1)) if match else float("inf")
def _clock_distance(value: str) -> float:
match = re.search(r"(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})", value)
if not match:
return float("inf")
moment = datetime.strptime(match.group(1), "%Y-%m-%d %H:%M:%S")
return abs((moment - datetime.now()).total_seconds())
def jigsaw_offset(big_png: bytes, small_png: bytes, top: int) -> int:
"""返回滑块左边缘在底图上的横坐标。"""
big = Image.open(io.BytesIO(big_png)).convert("RGBA")
small = Image.open(io.BytesIO(small_png)).convert("RGBA")
width, height = big.size
piece_w, piece_h = small.size
mask: list[tuple[int, int, tuple[int, int, int]]] = []
for y in range(piece_h):
for x in range(piece_w):
red, green, blue, alpha = small.getpixel((x, y))
if alpha > 128:
mask.append((x, y, (red, green, blue)))
best_x = 0
best_score = None
limit = width - piece_w
for origin in range(max(limit, 0)):
score = 0
for x, y, color in mask:
pixel = big.getpixel((origin + x, top + y))
score += abs(pixel[0] - color[0]) + abs(pixel[1] - color[1]) + abs(pixel[2] - color[2])
if best_score is None or score < best_score:
best_score = score
best_x = origin
if top + piece_h > height:
raise RuntimeError("拼图纵坐标超出底图高度")
return best_x
class SessionExpired(RuntimeError):
"""学习平台凭证失效,需要重新登录。"""
class JigsawRejected(RuntimeError):
"""这次拼图位置不对,可以换一张再试。"""
class ManualJigsaw(Exception):
"""自动拼图已用完,把新拼图交给人来拖。"""
def __init__(self, puzzle: dict) -> None:
self.puzzle = puzzle
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 = ""
self._cipher = ""
self._kid = ""
self._puzzle: dict = {}
def close(self) -> None:
self.client.close()
def portal_headers(self) -> dict[str, str]:
referer = (
f"{PORTAL}/uc/{TENANT_ID}/oauthLogin?client_id={CLIENT_ID}"
f"&scope=profile&redirect_uri={quote(REDIRECT_URI, safe='')}"
"&response_type=code"
)
return {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json;charset=UTF-8",
"Origin": PORTAL,
"Referer": referer,
"X-App-Id": APP_ID,
"X-Device-Type": "pc",
"X-Itp-Value": "from=ucs-portal;client=pc;platform=portal",
"X-Lang-Id": "zh_CN",
"X-Tenant-Id": TENANT_ID,
"x_uuid": str(uuid.uuid4()),
}
def code_of(self, payload: dict) -> tuple[str, str, object]:
block = payload.get("code") or {}
return block.get("code") or "", block.get("msg") or "", payload.get("bo")
def login(self, manual: bool = False, auto_attempts: int = 3) -> dict:
self.client.get(EUNIV + "/")
self.client.post(
f"{PORTAL}/zte-bmt-ucs-portalbff/oauth/validate",
headers=self.portal_headers(),
json={
"clientId": CLIENT_ID,
"redirectUri": REDIRECT_URI,
"responseType": "code",
"scope": "profile",
"_t": now_ms(),
},
)
key_resp = self.client.post(
f"{PORTAL}/zte-bmt-ucs-portalbff/srv/password/publicKey/{TENANT_ID}",
headers=self.portal_headers(),
json={"_t": now_ms()},
)
key_code, key_message, public_key = self.code_of(key_resp.json())
if key_code != "0000" or not isinstance(public_key, str):
raise RuntimeError(f"获取密码公钥失败:{key_message or key_resp.status_code}")
check_resp = self.client.post(
f"{PORTAL}/zte-bmt-ucs-portalbff/srv/pas/securitycode/check",
headers=self.portal_headers(),
json={"accountId": self.login_name, "callerId": APP_ID, "_t": now_ms()},
)
check_code, check_message, needs_security_code = self.code_of(check_resp.json())
if check_code == "0000" and needs_security_code is True:
raise RuntimeError("这个账号开启了动态安全码,当前登录流程还不能提交安全码")
if check_code not in ("", "0000"):
raise RuntimeError(f"安全码检查失败:{check_message}")
self._cipher = encrypt_password(public_key, self.password)
return self._login_with_jigsaw(manual, auto_attempts)
def _login_with_jigsaw(self, manual: bool, auto_attempts: int) -> dict:
"""次数由调用方传入。只把拼图被拒绝计入自动次数,密码错误或网络失败不重试。"""
if manual:
self._load_jigsaw()
raise ManualJigsaw(self.current_puzzle())
for _ in range(auto_attempts):
big, small, top = self._load_jigsaw()
try:
return self.submit_jigsaw(jigsaw_offset(big, small, top))
except JigsawRejected:
continue
self._load_jigsaw()
raise ManualJigsaw(self.current_puzzle())
def _load_jigsaw(self) -> tuple[bytes, bytes, int]:
kid = make_kid("t")
image_resp = self.client.get(
f"{PORTAL}/zte-bmt-ucs-portalbff/srv/kaptcha/jigsaw",
params={"kid": kid, "_t": now_ms()},
headers=self.portal_headers(),
)
image_code, image_message, image = self.code_of(image_resp.json())
if image_code != "0000":
raise RuntimeError(f"获取拼图失败:{image_message}")
if not isinstance(image, dict):
raise RuntimeError("拼图返回无法识别")
big = decode_data_uri(image["bigImg"])
small = decode_data_uri(image["smallImg"])
big_size = Image.open(io.BytesIO(big)).size
small_size = Image.open(io.BytesIO(small)).size
top = int(image["yHeight"])
self._kid = kid
self._puzzle = {
"big_img": data_uri(image["bigImg"]),
"small_img": data_uri(image["smallImg"]),
"y": top,
"width": big_size[0],
"height": big_size[1],
"piece_width": small_size[0],
"piece_height": small_size[1],
}
return big, small, top
def next_jigsaw(self) -> dict:
self._load_jigsaw()
return self.current_puzzle()
def current_puzzle(self) -> dict:
return dict(self._puzzle)
def submit_jigsaw(self, offset: int) -> dict:
headers = self.portal_headers()
headers.update({"kcode": "", "kid": make_kid(""), "kskip": "true", "source": APP_ID})
login_resp = self.client.post(
f"{PORTAL}/zte-bmt-ucs-portalbff/srv/login",
headers=headers,
json={
"loginName": self.login_name,
"password": self._cipher,
"kid": self._kid,
"jigsawCode": int(offset),
"_t": now_ms(),
},
)
login_code, message, profile = self.code_of(login_resp.json())
if login_code == "0000" and isinstance(profile, dict):
return profile
if any(word in message for word in ("验证码", "拼图", "滑块")):
raise JigsawRejected(message or "拼图未通过")
raise RuntimeError(f"登录失败:{message}")
def authorize(self, profile: dict) -> None:
account_id = str(profile["accountId"])
user_id = str(profile["userId"])
token = str(profile["token"])
domain = "zte.com.cn"
jar = {
"UCSLoginName": account_id,
"UCSSSOAccount": account_id,
"UCSSSOUser": user_id,
"UCSSSOToken": token,
"UCSSSOInfo": str(profile.get("ssoinfo") or ""),
"UCSSSOLanguage": "zh_CN",
"UCSLoginTime": str(now_ms()),
"iAuthTenantId_prod": TENANT_ID,
"iAuthUserId_prod": user_id,
"iAuthUid_prod": account_id,
"iAuthTid_prod": token,
"iAuthLanguage_prod": "zh_CN",
}
if profile.get("unionId"):
jar["iuacUnionId"] = str(profile["unionId"])
for name, value in jar.items():
self.client.cookies.set(name, value, domain=domain, path="/")
response = self.client.post(
f"{PORTAL}/zte-bmt-ucs-portalbff/oauth/authorize",
params={
"redirect_uri": REDIRECT_URI,
"client_id": CLIENT_ID,
"response_type": "code",
"scope": "profile",
},
headers=self.portal_headers(),
json={"accountId": account_id, "token": token, "userId": user_id, "_t": now_ms()},
)
code, message, redirect_url = self.code_of(response.json())
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",
content=b"",
headers=self.api_headers(),
)
response.raise_for_status()
payload = response.json()
if not isinstance(payload, dict) or "cnName" not in payload:
raise RuntimeError("用户信息返回无法识别")
return payload
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.session_token(),
"User-Agent": USER_AGENT,
}
def study_snapshot(self) -> dict:
"""查询学时、学分和积分汇总,以及今日数据、我的班级数量。"""
headers = self.api_headers()
score_resp = self.client.post(
f"{YXT_API}/v1/customapiforweb/getscoreorpointorhour",
json={},
headers=headers,
)
score_resp.raise_for_status()
score_payload = score_resp.json()
data = 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.client.get(
f"{STUDY_API}/v1/studyapi/studyhour/todayscorehours",
headers=headers,
)
today_resp.raise_for_status()
today = today_resp.json()
class_count = None
class_resp = self.client.get(
f"{CLASS_API}/v1/zte/my/class",
params={"limit": 10, "offset": 0, "lang": 0},
headers=headers,
)
if class_resp.status_code == 200:
paging = ((class_resp.json().get("data") or {}).get("paging") or {})
class_count = paging.get("totalCount")
return {
"actual_study_hour": data.get("actualStudyHour"),
"actual_study_score": data.get("actualStudyScore"),
"points": data.get("totalUserPoint") or data.get("ablePoint"),
"today_hours": today.get("studyHours"),
"today_score": today.get("studyScore"),
"today": today.get("toDate"),
"class_count": class_count,
}
def home_summary(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()
periods = self._period_minutes()
if not periods["year"] and not periods["month"]:
raise RuntimeError("个人学习信息没有获取到。")
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_hours": periods["year"],
"month_hours": periods["month"],
"today_hours": today.get("studyHours"),
"total_hours": score.get("actualStudyHour") or "",
"total_score": score.get("actualStudyScore") or period.get("totalScores") or "",
"points": "" if score.get("ablePoint") is None else score.get("ablePoint"),
}
def home_exams(self) -> list[dict]:
return _by_closeness(self.my_exams(), "sort_at")
def home_trainings(self) -> list[dict]:
return _by_closeness(self.online_trainings(), "sort_days")
def home_snapshot(self) -> dict:
"""实时读取整页首页。调用方不得把结果写入数据库。"""
data = self.home_summary()
data["trainings"] = self.home_trainings()
data["exams"] = self.home_exams()
return data
def month_hours(self) -> str:
return self._period_minutes().get("month", "")
def _period_minutes(self) -> dict[str, str]:
text = self._study_period_page()
found = {}
for key, element in (("year", "spAnnualPeriod"), ("month", "spMonthlyPeriod")):
match = re.search(rf'id="{element}" title="(\d+)分钟"', text)
found[key] = match.group(1) if match else ""
return found
def _ensure_site(self) -> str:
"""确认网页会话可用。同一账号短时间内复用已打开的会话,避免并行请求各自重新登录。"""
account_id = str(self._profile.get("accountId") or "")
if self._profile.get("token") and not getattr(self, "_site_ready", False):
with _authorize_lock(account_id):
if getattr(self, "_site_ready", False):
return ""
shared = _site_sessions.get(account_id)
if shared and time.time() - shared[0] < _SITE_SHARE_SECONDS:
_load_cookies(self.client, shared[1])
self._site_ready = True
return ""
probe = self.client.get(
f"{EUNIV}/study/myperiod.htm",
headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"},
)
if "spMonthlyPeriod" not in probe.text:
self.authorize(self._profile)
self._site_ready = True
_remember_site(account_id, self.client)
return ""
self._site_ready = True
_remember_site(account_id, self.client)
return probe.text
return ""
def _study_period_page(self) -> str:
cached = self._ensure_site()
if "spMonthlyPeriod" in cached:
return cached
response = self.client.get(
f"{EUNIV}/study/myperiod.htm",
headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/sty/index.htm"},
)
return response.text
def online_trainings(self) -> list[dict]:
self._ensure_site()
url = f"{EUNIV}/sty/mystudytask.htm"
headers = {"User-Agent": USER_AGENT, "Referer": url, "Origin": EUNIV}
html = self.client.get(url, headers=headers).text
if "scType" not in html and "el-plan-li-3" not in html:
raise RuntimeError("培训列表没有获取到。")
items = parse_training_cards(html, "进行中")
form = training_form(html)
for event, status in (("2,已完成", "已完成"), ("1,已归档", "已归档")):
form["__EVENTTARGET"] = "scType"
form["__EVENTARGUMENT"] = event
html = self.client.post(url, data=form, headers=headers).text
if "scType" not in html and "el-plan-li-3" not in html:
raise RuntimeError("培训列表没有获取到。")
items.extend(parse_training_cards(html, status))
form = training_form(html)
return items
def my_exams(self) -> list[dict]:
self._ensure_site()
url = f"{EUNIV}/exam/userallexam.htm"
headers = {"User-Agent": USER_AGENT, "Referer": url, "Origin": EUNIV}
html = self.client.get(url, headers=headers).text
form = training_form(html)
form["__EVENTTARGET"] = "scExamState"
form["__EVENTARGUMENT"] = ""
html = self.client.post(url, data=form, headers=headers).text
if "scExamState" not in html and 'name="userExam"' not in html:
raise RuntimeError("考试列表没有获取到。")
return self._pages(url, headers, html, parse_exam_cards, "start")
def list_courses(self) -> list[dict]:
self._ensure_site()
found: dict[str, dict] = {}
total = None
page = 1
while page <= 120:
html = self._site_page(
"/kng/knowledgecatalogsearch.htm"
f"?sf=RecommendLevel&s=dc&st=1&mode=null&ps=50&pi={page}"
)
parsed = parse_course_page(html)
if total is None:
total = parsed["total"]
if not parsed["courses"]:
break
before = len(found)
for course in parsed["courses"]:
found[course["path"]] = course
if total is not None and len(found) >= total:
break
if len(found) == before:
break
page += 1
if total is not None and len(found) < total:
raise RuntimeError("课程清单没有取全")
return list(found.values())
def exam_detail(self, path: str) -> dict:
if not _exam_detail_path(path):
raise RuntimeError("考试明细无法打开")
return parse_exam_detail(self._site_page(path))
def training_detail(self, path: str) -> dict:
if not re.fullmatch(r"/plan/[0-9a-fA-F]{32}\.html", path):
raise RuntimeError("培训明细无法打开")
return parse_training_detail(self._site_page(path))
def _site_page(self, path: str) -> str:
self._ensure_site()
response = self.client.get(
f"{EUNIV}{path}",
headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"},
)
return response.text
def credential_alive(self) -> bool:
try:
response = self._request("POST", f"{YXT_API}/v1/customdiy/user/getuserinfobyid", content=b"")
except SessionExpired:
return False
payload = response.json()
return isinstance(payload, dict) and bool(payload.get("cnName"))
def _pages(self, url: str, headers: dict, html: str, parse, identity: str) -> list[dict]:
items = parse(html)
seen = {(item.get("name", ""), item.get(identity, "")) for item in items}
for _ in range(10):
count = re.search(r'id="hidDatasCoun"[^>]*value="(\d+)"', html)
if not count or count.group(1) != "20":
break
form = training_form(html)
form["btnLoadNext"] = "加载更多"
html = self.client.post(url, data=form, headers=headers).text
fresh = [item for item in parse(html) if (item.get("name", ""), item.get(identity, "")) not in seen]
if not fresh:
break
items.extend(fresh)
seen.update((item.get("name", ""), item.get(identity, "")) for item in fresh)
return items
def open_session(self) -> dict:
profile = self.login()
self.authorize(profile)
return {"profile": self.user_info(), "summary": self.study_snapshot()}