"""登录中兴 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"