"""登录中兴 e 学并查询学时、学分汇总。""" from __future__ import annotations import base64 import io import json 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"]*>", 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("&", "&").replace("<", "<").replace(">", ">").replace(""", '"') 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 | httpx.AsyncClient, dumped: list[tuple[str, str, str, str]]) -> None: for name, value, domain, path in dumped: kwargs: dict[str, str] = {"path": path or "/"} if domain: kwargs["domain"] = domain client.cookies.set(name, value, **kwargs) 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 _HISTORY_ROW_RE = re.compile( r'\s*' r'([\s\S]*?)\s*' r'\s*(\d+)\s*\s*' r'\s*([^<]+?)\s*', re.I, ) def _history_api_item(row: object) -> dict | None: if not isinstance(row, dict): return None title = str(row.get("targetName") or row.get("title") or row.get("kngName") or "").strip() studied_at = str(row.get("studyDate") or row.get("studiedAt") or row.get("createTime") or "").strip() raw_minutes = row.get("duration") if raw_minutes is None: raw_minutes = row.get("studyHour") minutes: int | None = None if isinstance(raw_minutes, bool): minutes = None elif isinstance(raw_minutes, (int, float)): minutes = int(raw_minutes) elif isinstance(raw_minutes, str) and raw_minutes.strip(): match = re.search(r"(\d+)", raw_minutes) minutes = int(match.group(1)) if match else None path = str(row.get("url") or row.get("knowledgeUrl") or row.get("targetUrl") or "").strip() knowledge_id = str(row.get("knowledgeId") or row.get("kngId") or "").replace("-", "") if not path and len(knowledge_id) == 32: path = f"/kng/view/document/{knowledge_id}.html" if not title and not studied_at: return None return { "title": title, "minutes": minutes, "studied_at": studied_at, "path": path, } HISTORY_PAGE_SIZE = 100 def history_search_body(pageable: bool, offset: int = 0, limit: int = HISTORY_PAGE_SIZE) -> dict: body: dict = {"pageable": pageable} if pageable: page = offset // limit + 1 if limit else 1 body.update( { "offset": offset, "limit": limit, "page": page, "pageSize": limit, "start": offset, "length": limit, } ) return body def history_items_from_payload(payload: object) -> list[dict] | None: if not isinstance(payload, dict): return None rows = payload.get("datas") if rows is None: rows = payload.get("data") if isinstance(rows, dict): rows = rows.get("datas") or rows.get("list") or rows.get("records") or rows.get("items") if not isinstance(rows, list): return None items = [] for row in rows: item = _history_api_item(row) if item is not None: items.append(item) return items def history_stamp(studied_at: str) -> datetime | None: text = (studied_at or "").strip().replace("T", " ") if not text: return None text = text[:19] for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d"): try: return datetime.strptime(text, fmt) except ValueError: continue return None def history_month_side(studied_at: str, year: int, month: int) -> str: stamp = history_stamp(studied_at) if stamp is None: return "unknown" if (stamp.year, stamp.month) == (year, month): return "in" if (stamp.year, stamp.month) < (year, month): return "before" return "after" def fold_month_minutes(items: list[dict], year: int, month: int) -> tuple[int, bool]: total = 0 reached_before = False for item in items: side = history_month_side(str(item.get("studied_at") or ""), year, month) if side == "in": minutes = item.get("minutes") if isinstance(minutes, int): total += minutes elif side == "before": reached_before = True break return total, reached_before def accumulate_month_minutes(fetch_page, year: int, month: int, page_size: int = HISTORY_PAGE_SIZE) -> int: """倒序分页累加本月分钟,遇到上个月即停。""" offset = 0 total = 0 first_mark: tuple | None = None for _ in range(50): rows = fetch_page(offset, page_size) if rows is None: if offset == 0: raise RuntimeError("学时历史没有获取到") return total if not rows: return total add, done = fold_month_minutes(rows, year, month) total += add if done: return total if len(rows) != page_size: return total mark = ( len(rows), rows[0].get("studied_at"), rows[0].get("title"), rows[-1].get("studied_at"), rows[-1].get("title"), ) if offset == 0: first_mark = mark elif mark == first_mark: return total offset += page_size return total def parse_training_cards(page: str, status: str) -> list[dict]: items = [] for block in re.findall(r"
  • ", 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'\s*([^<]+)', block) assigned = re.search(r"sty_lbl_assignedtime\">([^<]+)", block) credits = re.search(r"el-plan-time'>([^<]+)", block) detail = re.search(r"""learningKnowledge\(['"](/plan/[0-9a-fA-F]{32}\.html)['"]\)""", block) assigned_text = "" if assigned: assigned_text = assigned.group(1).replace(" ", " ").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'
  • [\s\S]*?
  • ', 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">:([^<&]+)', 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(" ", " ").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]*?', page) attempts = [] if table: for row in re.findall(r"([\s\S]*?)", table.group(0))[1:]: cells = [_plain(cell) for cell in re.findall(r"]*>([\s\S]*?)", 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]*?([\s\S]*?)\s*\s*', head) progress = re.search(r'class="schedule1 floatleft">\s*([^<]+)', head) deadline = re.search(r'mgt_lbl_requirecompletedate">\s*\s*:\s*([^<\s]+)', head) credits = re.findall(r">\s*([0-9]+(?:\.[0-9]+)?)\s*', page)[1:]: phase_name = re.search(r'[\s\S]*?([^<]+)', table) phase_hours = re.search(r":\s*([0-9]+(?:\.[0-9]+)?)\s*[\s\S]*?:\s*([0-9]+(?:\.[0-9]+)?)', table) tasks = [] for row in re.findall(r'', table): task_name = re.search(r"""(\d+%)<", row) score = re.search( r'title="已获学分">\s*([^<]+?)\s*\s* /\s* \s*\s*([^<]+)', row, ) hours = re.search( r'core_lbl_knghours">:\s*([^<&]+?)\s* /\s* \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]*?)', 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(" ", " ").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"\s*[\s\S]*?", 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'\s*([^<]*)', row) comments = re.search(r"", 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, proxy: str | None = None) -> None: from euniv.proxy import parse_proxy self.login_name = login_name.strip() self.password = password self.proxy = parse_proxy(proxy) self.client = httpx.Client( timeout=30, follow_redirects=True, proxy=self.proxy, 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 study_history(self) -> list[dict]: """读取「我的学时」列表:来源、获得学时(分钟)、日期。""" try: items = self._study_history_search(pageable=False) except Exception: items = None if items is not None: return items return self._study_history_page() def month_history_minutes(self, now: datetime | None = None) -> int: """倒序分页统计本月学时分钟,遇到上个月即停。""" from euniv.study_window import CN_TZ current = now or datetime.now(CN_TZ) year, month = current.year, current.month def fetch_page(offset: int, limit: int) -> list[dict] | None: return self._study_history_search(pageable=True, offset=offset, limit=limit) try: return accumulate_month_minutes(fetch_page, year, month) except Exception: items = self.study_history() total, _ = fold_month_minutes(items, year, month) return total def _study_history_search( self, *, pageable: bool, offset: int = 0, limit: int = HISTORY_PAGE_SIZE ) -> list[dict] | None: response = self._request( "POST", f"{STUDY_API}/v1/styhis/studyhistory/daily/search", json=history_search_body(pageable, offset, limit), ) return history_items_from_payload(response.json()) def _study_history_page(self) -> list[dict]: text = self._study_period_page() items = [] for match in _HISTORY_ROW_RE.finditer(text): title = unescape(match.group(1) or "").strip() cell = match.group(2) or "" minutes = int(match.group(3)) studied_at = unescape(match.group(4) or "").strip() path_match = re.search(r"GoToSource\('([^']+)'", cell) path = path_match.group(1) if path_match else "" items.append( { "title": title, "minutes": minutes, "studied_at": studied_at, "path": path, } ) return items 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()} # ── 自动学习所需方法 ── def course_page_params(self, path: str) -> dict: """打开播放页,解析 JS 变量。返回 knowledgeType, submitProTimes, validtimeSpan, standardStudyHours, pageSize 等。""" html = self._site_page(path) from euniv.encrypt import note_play_html note_play_html(html, EUNIV) 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 { "knowledgeType": _var("knowledgeType"), "submitIsOpen": _var("submitIsOpen", "0"), "submitProTimes": int(_var("submitProTimes", "30") or 30), "validtimeSpan": int(_var("validtimeSpan", "120") or 120), "standardStudyHours": int(_var("standardStudyHours", "0") or 0), "pageSize": int(_var("pageSize", "1") or 1), "fileType": _var("fileType"), "kngId": _var("kngId"), "packageID": _var("packageID"), "orgID": _var("orgID"), "userID": _var("userID"), } def update_progress(self, knowledge_id: str, package_id: str = "", master_id: str = "", master_type: str = "") -> dict: """POST /v1/study/updateprogress。返回 studyschedule, actualstudyhours, standardstudyhours, viewSchedule, status。""" body = { "knowledgeId": knowledge_id, "packageId": package_id, "masterId": master_id, "masterType": master_type, } resp = self._request("POST", f"{STUDY_API}/v1/study/updateprogress", json=body) return resp.json() def sync_package(self, knowledge_id: str) -> dict: """GET /v1/uk/syncpackage。返回整包和各章信息。""" resp = self._request("GET", f"{STUDY_API}/v1/uk/syncpackage", params={"knowledgeId": knowledge_id, "sourceType": "SingleStudy", "masterId": ""}) return resp.json() def get_encrypt_request(self, body_json: str) -> str: from euniv.encrypt import fetch_encryption self._ensure_site() return fetch_encryption(self.client, body_json, origin=EUNIV, user_agent=USER_AGENT) def submit_video_heartbeat(self, knowledge_id: str, package_id: str, study_time: int, view_schedule: int, master_id: str = "", master_type: str = "") -> dict: """视频心跳 POST /v1/study/submitpro。""" param = { "knowledgeId": knowledge_id, "masterId": master_id, "masterType": master_type, "packageId": package_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 = self.get_encrypt_request(encrypt_body) param["encryption"] = encryption param["multiple"] = 1 param["realHour"] = study_time resp = self._request("POST", f"{STUDY_API}/v1/study/submitpro", content=json.dumps(param, separators=(",", ":"))) text = resp.text.strip() if not text: return {} return resp.json() def submit_document_heartbeat(self, knowledge_id: str, package_id: str, page_size: int, study_time: int, view_schedule: int, master_id: str = "", master_type: str = "") -> dict: """文档心跳 POST /v1/study/submit。""" param = { "knowledgeId": knowledge_id, "masterId": master_id, "masterType": master_type, "packageId": package_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 = self.get_encrypt_request(encrypt_body) param["multiple"] = 1 param["realHour"] = study_time resp = self._request("POST", f"{STUDY_API}/v1/study/submit?encryption={encryption}", content=json.dumps(param, separators=(",", ":"))) return {} def submit_scorm_heartbeat(self, knowledge_id: str, package_id: str, study_time: int, sco_id: str = "", end: bool = False, master_id: str = "", master_type: str = "") -> dict: """Scorm 心跳 POST /v1/study/submit,type=2。""" param = { "knowledgeId": knowledge_id, "masterId": master_id, "masterType": master_type, "packageId": package_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, } encrypt_body = json.dumps(param, separators=(",", ":")) encryption = self.get_encrypt_request(encrypt_body) param["multiple"] = 1 param["realHour"] = study_time resp = self._request("POST", f"{STUDY_API}/v1/study/submit?encryption={encryption}", content=json.dumps(param, separators=(",", ":"))) return {} def scorm_count(self, knowledge_id: str) -> int: """GET /v1/kng/scorm/count/。""" resp = self._request("GET", f"{STUDY_API}/v1/kng/scorm/count/", params={"knowledgeId": knowledge_id}) data = resp.json() return int(data.get("scocnt") or 1) def scorm_get(self, user_id: str, sco_id: str) -> dict: """GET /v1/scormstudy/{userId}/{scoId}。""" resp = self._request("GET", f"https://api-mall.yxt.com/v1/scormstudy/{user_id}/{sco_id}") text = resp.text.strip() if not text: return {} return resp.json() def scorm_save(self, session_id: str, org_id: str, user_id: str, scorm_id: str, scorm_id_ori: str, sco_cnt: int, package_id: str, master_id: str, master_type: str, data: dict) -> None: """POST /v1/scormstudy。""" body = { "sessionId": session_id, "orgId": org_id, "userId": user_id, "scormId": scorm_id, "scormIdOri": scorm_id_ori, "masterId": master_id, "masterType": master_type, "packageId": package_id, "scocnt": sco_cnt, "data": data, } self._request("POST", "https://api-mall.yxt.com/v1/scormstudy", json=body) def scorm_page_files(self, knowledge_id: str) -> list[str]: """下载 Scorm 课件的页索引,返回各页 .oss.js 的 URL 列表。""" index_url = f"https://cdn-cos-file.yunxuetang.cn/zt/scorm/{knowledge_id}/h5/js/index-scorm.js" resp = self.client.get(index_url, headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"}) urls = [] 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/{knowledge_id}/h5/js/{raw}") return urls def scorm_extract_answers(self, knowledge_id: str) -> list[dict]: """下载 .oss.js 页,提取题目和正确答案。""" urls = self.scorm_page_files(knowledge_id) answers = [] for url in urls: try: resp = self.client.get(url, headers={"User-Agent": USER_AGENT}) text = resp.text for block in re.finditer(r'单选题([\s\S]*?)正确答案[::]\s*([A-D])', text): answers.append({"page_url": url, "answer": block.group(2)}) except Exception: continue return answers def user_id(self) -> str: return str(self._profile.get("userId") or "")