"""登录中兴 e 学并查询学时、学分汇总。""" from __future__ import annotations import base64 import hashlib import io import logging import random import re import secrets 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 log = logging.getLogger(__name__) PORTAL = "https://uac.zte.com.cn" PORTAL_BFF = f"{PORTAL}/zte-sec-uac-iportalbff" PORTAL_PAGE = f"{PORTAL}/zte-sec-uac-iportal/iportal/" EUNIV = "https://euniv.zte.com.cn" YXT_API = "https://api-qidacustomc1.yunxuetang.cn" STUDY_API = "https://api-qidac1.yunxuetang.cn" REDIRECT_URI = f"{YXT_API}/v1/ztctech/sso" CLIENT_ID = "183681933766" TENANT_ID = "10001" APP_ID = CLIENT_ID INNER_APP_ID = "10001" USER_AGENT = ( "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:158.0) " "Gecko/20100101 Firefox/158.0" ) PUBLIC_KEY_B64 = ( "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApeLemQaHD72LD0L6Jyc8OiDZhGla2SeHkpQWHfUR" "MGxV6zHCc0M8dvYZ5RTDWO53CVAEPCNFPG5oUIay+XH/UwxmOuO1aYxyNISSwyrovP341Qsy2uvZAnHo4cyY" "5xTAYqCP5Yv/e2pkUeQRu+KQ+Y4JiQzEGia+ASmI5tF4tYqArllaWFlDBR7rtAV4/O/9zn5WA2kISRwgjW1i" "rrQDG7OKe8AMjZx1RPw6gLRA18AE4Jf66U6GWi2nuI0mmeQ1kudBkH/ucVQ6wbReXcRJHpyxQGCQX871acHq" "ZTGGHv4l6SM0U5jegvmJqHRNsTgWN0WQVAmTFXUGoGornnf+6wIDAQAB" ) QR_PASSWORD_MARK = "扫码登陆" QR_PREFIX = "TwoDIMAuth" UAC_OK = "0000" UAC_QR_WAIT = "4002" 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 compact_id(value: str) -> str: return (value or "").replace("-", "").lower() def as_uuid(value: str) -> str: raw = compact_id(value) if len(raw) != 32 or any(char not in "0123456789abcdef" for char in raw): return (value or "").strip() return f"{raw[0:8]}-{raw[8:12]}-{raw[12:16]}-{raw[16:20]}-{raw[20:32]}" def play_page_vars(html: str) -> dict[str, str]: text = html or "" def read(name: str, default: str = "") -> str: quoted = re.search(rf'(?:var\s+)?{re.escape(name)}\s*=\s*["\']([^"\']*)["\']', text) if quoted: return quoted.group(1).strip() numeric = re.search(rf'(?:var\s+)?{re.escape(name)}\s*=\s*(-?\d+)', text) if numeric: return numeric.group(1).strip() return default return { "knowledgeType": read("knowledgeType"), "submitIsOpen": read("submitIsOpen", "0"), "submitProTimes": read("submitProTimes", "30"), "validtimeSpan": read("validtimeSpan", "120"), "standardStudyHours": read("standardStudyHours", "0"), "pageSize": read("pageSize", "1"), "fileType": read("fileType"), "kngId": read("kngId"), "packageID": read("packageID"), "orgID": read("orgID"), "userID": read("userID"), "scormId": read("scormId") or read("scoId"), } def play_page_params(html: str) -> dict: raw = play_page_vars(html) def as_int(name: str, default: int) -> int: try: return int(raw.get(name) or default) except (TypeError, ValueError): return default return { **raw, "submitProTimes": as_int("submitProTimes", 30), "validtimeSpan": as_int("validtimeSpan", 120), "standardStudyHours": as_int("standardStudyHours", 0), "pageSize": max(1, as_int("pageSize", 1)), } def study_progress_fields( knowledge_id: str, package_id: str = "", *, page_size: int = 1, study_time: int = 30, kind: int = 0, view_schedule: int | float = 0, end: bool = False, chapter_id: str = "", for_encrypt: bool = False, ) -> dict: """抓包里 knowledgeId/packageId 带连字符;Scorm 加密体的 studyChapterIds 末尾有分号。""" chapter = as_uuid(chapter_id) if chapter_id else "" if for_encrypt and kind == 2 and chapter: chapter = chapter + ";" return { "knowledgeId": as_uuid(knowledge_id), "masterId": "", "masterType": "", "packageId": as_uuid(package_id) if package_id else "", "pageSize": int(page_size), "studySize": int(page_size), "studyTime": int(study_time), "type": int(kind), "offLine": False, "end": bool(end), "care": True, "deviceId": "", "studyChapterIds": chapter, "viewSchedule": int(view_schedule or 0), } 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 encrypt_field(value: str) -> str: return encrypt_password(PUBLIC_KEY_B64, value) def is_qr_password(password: str) -> bool: return password == QR_PASSWORD_MARK def parse_uac(payload: object) -> tuple[str, str, object, str]: """解析 UAC 两种响应:code 为对象(嵌套 bo/other.data)或顶层字符串(data)。""" if not isinstance(payload, dict): return "", "", None, "" code = payload.get("code") reason = payload.get("reason") if isinstance(payload.get("reason"), dict) else {} if isinstance(code, dict): top = str(code.get("code") or "") bo = payload.get("bo") if isinstance(payload.get("bo"), dict) else {} inner = str(bo.get("code") or top) other = payload.get("other") if isinstance(payload.get("other"), dict) else {} data = other.get("data") if data is None: data = payload.get("data") message = str(bo.get("msg") or code.get("msg") or reason.get("zh_CN") or "") return top, inner, data, message top = str(code or "") message = str(payload.get("message") or reason.get("zh_CN") or "") return top, top, payload.get("data"), message def make_qr_payload(prefix: str = QR_PREFIX) -> str: def digest(text: str) -> str: return hashlib.md5(text.encode("utf-8")).hexdigest() def digits(count: int) -> str: return "".join(secrets.choice("0123456789") for _ in range(count)) key = digest(prefix + str(now_ms()) + digits(10)) value = digest(key + digits(10)) return f"{prefix}:{key}:{value}" def qr_data_uri(text: str) -> str: import qrcode qr = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_M, box_size=6, border=2) qr.add_data(text) qr.make(fit=True) image = qr.make_image(fill_color="black", back_color="white") buf = io.BytesIO() image.save(buf, format="PNG") return "data:image/png;base64," + base64.b64encode(buf.getvalue()).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)] = unescape(raw) 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[tuple[str, str], tuple[float, list[tuple[str, str, str, str]]]] = {} def forget_site(account_id: str) -> None: key = (account_id or "").strip() for item in list(_site_sessions): if item[0] == key: _site_sessions.pop(item, None) def _remember_site(account_id: str, client: httpx.Client, token: str = "") -> None: jar = getattr(getattr(client, "cookies", None), "jar", None) if not account_id or jar is None: return now = time.time() for item, (saved, _rows) in list(_site_sessions.items()): if now - saved > _SITE_SHARE_SECONDS: _site_sessions.pop(item, None) dumped = [] for cookie in jar: dumped.append((cookie.name, cookie.value or "", cookie.domain or "", cookie.path or "/")) _site_sessions[(account_id, token)] = (now, 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) and not isinstance(minutes, bool): total += minutes elif side == "before": reached_before = True break return total, reached_before def history_hour_totals(items: list[dict], now: datetime | None = None) -> dict[str, int]: """按北京时间把学时历史加成累计、本年、本月、本日分钟。""" from euniv.study_window import CN_TZ current = now or datetime.now(CN_TZ) if current.tzinfo is None: current = current.replace(tzinfo=CN_TZ) else: current = current.astimezone(CN_TZ) year, month, day = current.year, current.month, current.day total = year_total = month_total = today_total = 0 for item in items: minutes = item.get("minutes") if not isinstance(minutes, int) or isinstance(minutes, bool): continue stamp = history_stamp(str(item.get("studied_at") or "")) if stamp is None: continue total += minutes if stamp.year != year: continue year_total += minutes if stamp.month != month: continue month_total += minutes if stamp.day == day: today_total += minutes return { "year": year_total, "month": month_total, "today": today_total, "total": total, } def accumulate_month_minutes(fetch_page, year: int, month: int, page_size: int = HISTORY_PAGE_SIZE) -> int: """倒序分页累加本月分钟,遇到上个月即停。重复页直接返回,不再累加。""" offset = 0 total = 0 seen: set[tuple] = set() 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 mark = ( len(rows), rows[0].get("studied_at"), rows[0].get("title"), rows[-1].get("studied_at"), rows[-1].get("title"), ) if mark in seen: return total seen.add(mark) add, done = fold_month_minutes(rows, year, month) total += add if done or len(rows) != page_size: 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": unescape(name.group(1)).strip() if name else "", "status": status, "progress": int(progress.group(1)) if progress else 0, "owner": unescape(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": unescape(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": unescape(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": unescape(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": unescape(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_path_ok(value: str) -> bool: return bool(re.fullmatch(r"/exam/exampreview\.htm\?[A-Za-z0-9_=&%.\-]+", value)) and "xamArrangeID=" in value def training_path_ok(value: str) -> bool: return bool(re.fullmatch(r"/plan/[0-9a-fA-F]{32}\.html", value)) def _exam_detail_path(value: str) -> bool: return exam_path_ok(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 = unescape(re.sub(r"<[^>]+>", " ", value)) return re.sub(r"\s+", " ", text.replace("\xa0", " ")).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) courses.append({ "path": link.group(1), "title": unescape(link.group(2)).strip(), "kind": _course_kind(kind.group(1) if kind else "", link.group(1)), "contributor": unescape(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 "", }) 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") from euniv.study_window import CN_TZ moment = datetime.strptime(match.group(1), "%Y-%m-%d %H:%M:%S").replace(tzinfo=CN_TZ) return abs((moment - datetime.now(CN_TZ)).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 limit = width - piece_w if top < 0 or piece_w < 1 or piece_h < 1 or limit < 0 or top + piece_h > height: raise JigsawRejected("拼图纵坐标超出底图高度") big_px = big.load() small_px = small.load() mask: list[tuple[int, int, tuple[int, int, int]]] = [] for y in range(piece_h): row = top + y for x in range(piece_w): red, green, blue, alpha = small_px[x, y] if alpha > 128: mask.append((x, row, (red, green, blue))) best_x = 0 best_score: int | None = None for origin in range(limit + 1): score = 0 worse = False for x, row, color in mask: pixel = big_px[origin + x, row] score += abs(pixel[0] - color[0]) + abs(pixel[1] - color[1]) + abs(pixel[2] - color[2]) if best_score is not None and score >= best_score: worse = True break if not worse and (best_score is None or score < best_score): best_score = score best_x = origin return best_x class SessionExpired(RuntimeError): """学习平台凭证失效,需要重新登录。""" class JigsawRejected(RuntimeError): """这次拼图位置不对,可以换一张再试。""" class ManualJigsaw(Exception): """自动拼图已用完,把新拼图交给人来拖。""" def __init__(self, puzzle: dict) -> None: self.puzzle = puzzle class QrWaiting(Exception): """二维码尚未扫过或还在等待确认。""" def _https_only(request: httpx.Request) -> None: if request.url.scheme != "https": raise RuntimeError("只允许 https 请求") def _login_secret_too_long(value: str) -> bool: return len(value.encode("utf-8")) > 245 class EunivClient: def __init__(self, login_name: str, password: str, proxy: str | None = None) -> None: from euniv.proxy import parse_proxy, sync_httpx_client self.login_name = login_name.strip() self.password = password self.proxy = parse_proxy(proxy) self.client = sync_httpx_client( self.proxy, timeout=30, follow_redirects=True, headers={"User-Agent": USER_AGENT}, event_hooks={"request": [_https_only]}, ) self._profile: dict = {} self._yxt_token = "" self._cipher = "" self._cipher_name = "" self._kid = "" self._puzzle: dict = {} self._qr_str = "" def close(self) -> None: self.client.close() def portal_headers(self, app_id: str | None = None, json_body: bool = True) -> dict[str, str]: request_id = str(uuid.uuid4()) headers = { "Accept": "application/json, text/plain, */*", "Origin": PORTAL, "Referer": PORTAL_PAGE, "X-App-Id": app_id or APP_ID, "X-Device-Type": "pc", "X-Itp-Value": "client=pc;platform=iportal;deviceType=web", "X-Lang-Id": "zh_CN", "X-Tenant-Id": TENANT_ID, "x_uuid": request_id, "x-uuid": request_id, } if json_body: headers["Content-Type"] = "application/json;charset=UTF-8" return headers def _uac_post(self, path: str, *, app_id: str | None = None, json_body: object = None, extra: dict | None = None) -> httpx.Response: headers = self.portal_headers(app_id) if extra: headers.update(extra) url = path if path.startswith("http") else PORTAL_BFF + path if json_body is None: return self.client.post(url, headers=headers, content=b"null") return self.client.post(url, headers=headers, json=json_body) def _begin_uac(self) -> None: self.client.get(EUNIV + "/") self.client.get( f"{PORTAL_BFF}/auth/external/login/oauth/authorize.serv", params={ "client_id": CLIENT_ID, "scope": "openid", "redirect_uri": REDIRECT_URI, "response_type": "code", }, headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"}, ) self._uac_post(f"/auth/external/oauth/source/{CLIENT_ID}", app_id=INNER_APP_ID) top, _inner, _data, message = parse_uac( self._uac_post( "/auth/external/oauth/validate.serv", json_body={ "redirectUri": REDIRECT_URI, "clientId": CLIENT_ID, "responseType": "code", "state": "null", "scope": "openid", }, ).json() ) if top != UAC_OK: raise RuntimeError(f"登录页校验失败:{message or top}") def login(self, manual: bool = False, auto_attempts: int = 3) -> dict: if _login_secret_too_long(self.login_name) or _login_secret_too_long(self.password): raise RuntimeError("账号或密码过长") if is_qr_password(self.password): raise RuntimeError("扫码登录已失效,请重新扫码登录") self._begin_uac() check_resp = self._uac_post( "/authentication/pas/securitycode/check.serv", json_body={"accountId": self.login_name, "callerId": CLIENT_ID}, ) top, _inner, needs_security_code, message = parse_uac(check_resp.json()) if top == UAC_OK and needs_security_code is True: raise RuntimeError("这个账号开启了动态安全码,当前登录流程还不能提交安全码") if top not in ("", UAC_OK): raise RuntimeError(f"安全码检查失败:{message}") self._cipher_name = encrypt_field(self.login_name) self._cipher = encrypt_field(self.password) return self._login_with_jigsaw(manual, auto_attempts) def start_qr(self) -> tuple[str, str]: self._begin_uac() self._qr_str = make_qr_payload() return self._qr_str, qr_data_uri(self._qr_str) def poll_qr(self) -> dict: if not self._qr_str or ":" not in self._qr_str: raise RuntimeError("请重新扫码") parts = self._qr_str.split(":") if len(parts) < 3: raise RuntimeError("请重新扫码") try: payload = self._uac_post( "/authentication/qrscan.serv", json_body={"qrCodeKey": parts[1], "qrCodeValue": parts[2]}, ).json() except (httpx.TransportError, TimeoutError, ValueError): self._qr_misses = getattr(self, "_qr_misses", 0) + 1 if self._qr_misses >= 5: raise RuntimeError("扫码状态没有获取到") from None raise QrWaiting() from None self._qr_misses = 0 top, inner, data, message = parse_uac(payload) if top == UAC_OK and inner == UAC_QR_WAIT: raise QrWaiting() if top == UAC_OK and inner == UAC_OK and isinstance(data, dict) and data.get("token"): self.login_name = str(data.get("accountId") or data.get("userName") or self.login_name) self._qr_misses = 0 return data if any(word in (message or "") for word in ("已扫码", "待确认", "确认中")): raise QrWaiting() raise RuntimeError(message or "扫码登录失败") 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_BFF}/common/captcha/create.serv", params={"kid": kid}, headers=self.portal_headers(json_body=False), ) top, _inner, image, message = parse_uac(image_resp.json()) if top != UAC_OK: raise RuntimeError(f"获取拼图失败:{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 offset_y = int(image["yHeight"]) self._kid = kid self._puzzle = { "big_img": data_uri(image["bigImg"]), "small_img": data_uri(image["smallImg"]), "y": offset_y, "width": big_size[0], "height": big_size[1], "piece_width": small_size[0], "piece_height": small_size[1], } return big, small, offset_y 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: login_resp = self._uac_post( "/authentication/login.serv", extra={"kskip": "true"}, json_body={ "loginName": self._cipher_name or encrypt_field(self.login_name), "password": self._cipher, "kid": self._kid, "jigsawCode": int(offset), }, ) top, _inner, profile, message = parse_uac(login_resp.json()) if top == UAC_OK and isinstance(profile, dict) and profile.get("token"): 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.get("accountId") or profile.get("userName") or "") user_id = str(profile.get("userId") or account_id) token = str(profile.get("token") or "") if not account_id or not token: raise SessionExpired("登录结果缺少账号或令牌") domain = "zte.com.cn" jar = { "PORTALSSOLanguage": "zh_CN", "PORTALSSOUser": account_id, "PORTALSSOCookie": token, "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", "iAuthLoginName_prod": account_id, } if profile.get("unionId"): jar["iuacUnionId"] = str(profile["unionId"]) for name, value in jar.items(): self.client.cookies.set(name, value, domain=domain, path="/") self._uac_post( "/authentication/token/verify.serv", app_id=INNER_APP_ID, json_body={"accountId": account_id, "token": token}, ) try: self._uac_post( "/external/account/lasttenant/query.serv", app_id=INNER_APP_ID, json_body={"accountId": account_id}, ) self._uac_post( "/external/account/lasttenant/update.serv", app_id=INNER_APP_ID, json_body={"tenantId": TENANT_ID}, ) except Exception: pass response = self._uac_post( "/auth/external/oauth/authorize.serv" f"?redirect_uri={quote(REDIRECT_URI, safe='')}" f"&response_type=code&client_id={CLIENT_ID}&state=null&scope=openid", app_id=INNER_APP_ID, json_body={"accountId": account_id, "token": token, "redirectUri": REDIRECT_URI}, ) top, _inner, data, message = parse_uac(response.json()) callback = data.get("callbackUrl") if isinstance(data, dict) else None if top != UAC_OK or not isinstance(callback, str) or not callback.startswith(REDIRECT_URI): raise SessionExpired(f"申请学习平台授权码失败:{message}") self.client.get(callback, headers={"Referer": PORTAL + "/", "User-Agent": USER_AGENT}) self._profile = { "token": token, "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}) log.warning("学习平台没有返回登录会话,现有 Cookie 名称:%s", ", ".join(names)) raise RuntimeError("学习平台没有返回登录会话") 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 for domain in ("euniv.zte.com.cn", ".yunxuetang.cn"): self.client.cookies.set("ELEARNING_00024", refreshed, domain=domain, path="/") if response.status_code == 401: raise SessionExpired("学习平台登录已失效") if response.status_code == 403: raise PermissionError("当前课程没有权限") if response.headers.get("content-type", "").startswith("application/json"): try: payload = response.json() except (ValueError, UnicodeDecodeError): payload = None 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 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 hour_fields(self) -> dict: """只取四个学时数字,不读个人资料。""" periods = self._period_minutes() 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() return { "year_hours": periods["year"], "month_hours": periods["month"], "today_hours": today.get("studyHours"), "total_hours": score.get("actualStudyHour") or "", } 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 SessionExpired: raise 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 SessionExpired: raise except Exception as exc: raise RuntimeError("学时历史没有获取到") from exc 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 "" token = str(self._profile.get("token") or "") shared = _site_sessions.get((account_id, token)) 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, token) return "" self._site_ready = True _remember_site(account_id, self.client, token) 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: gap = total - len(found) if total > 0 and gap * 100 <= total: log.warning("课程清单少了 %s 条,页面共 %s 条,差额不超过 1%%", gap, total) else: 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 training_path_ok(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 if response.status_code >= 500 or response.status_code == 429: raise RuntimeError("学习平台暂时不可用") try: payload = response.json() except ValueError as exc: raise RuntimeError("学习平台暂时不可用") from exc if not isinstance(payload, dict): raise RuntimeError("学习平台暂时不可用") return 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