"""登录中兴 e 学并查询学时、学分汇总。"""
from __future__ import annotations
import base64
import hashlib
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://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"
CLASS_API = "https://sdcs-api-ztec1.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"),
}
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(random.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)] = 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) 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
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"