Files

1661 lines
62 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""登录中兴 e 学并查询学时、学分汇总。"""
from __future__ import annotations
import base64
import 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"<input\b[^>]*>", page, re.I):
tag = match.group(0)
if re.search(r"""type=['"]submit['"]""", tag, re.I):
continue
name = re.search(r"""name=['"]([^'"]+)['"]""", tag)
if not name:
continue
value = re.search(r"""value=['"]([^'"]*)['"]""", tag)
raw = value.group(1) if value else ""
found[name.group(1)] = 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 set_cookie(
cookies: httpx.Cookies,
name: str,
value: str,
domain: str = "",
path: str = "/",
secure: bool = False,
) -> None:
"""httpx 0.28 的 Cookies.set 不能传 secure,直接写入 jar。"""
from http.cookiejar import Cookie
path = path or "/"
domain = domain or ""
cookies.jar.set_cookie(
Cookie(
version=0,
name=name,
value=value,
port=None,
port_specified=False,
domain=domain,
domain_specified=bool(domain),
domain_initial_dot=domain.startswith("."),
path=path,
path_specified=bool(path),
secure=secure,
expires=None,
discard=True,
comment=None,
comment_url=None,
rest={"HttpOnly": None},
rfc2109=False,
)
)
def _load_cookies(client: httpx.Client | httpx.AsyncClient, dumped: list[tuple[str, str, str, str]]) -> None:
for name, value, domain, path in dumped:
set_cookie(client.cookies, name, value, domain=domain, path=path or "/")
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'<tr class="alter">\s*'
r'<td class="text-left" title="([^"]*)">([\s\S]*?)</td>\s*'
r'<td class="text-center">\s*(\d+)\s*</td>\s*'
r'<td class="text-center">\s*([^<]+?)\s*</td>',
re.I,
)
_PERIOD_CARDS = (
("year", "spAnnualPeriod"),
("month", "spMonthlyPeriod"),
("total", "spTotalPeriod"),
)
def history_rows_from_page(html: str) -> list[dict]:
"""我的学时页面表格:来源、获得学时(分钟)、日期。"""
items = []
for match in _HISTORY_ROW_RE.finditer(html or ""):
title = unescape(match.group(1) or "").strip()
cell = match.group(2) or ""
studied_at = unescape(match.group(4) or "").strip()
path_match = re.search(r"GoToSource\('([^']+)'", cell)
items.append(
{
"title": title,
"minutes": int(match.group(3)),
"studied_at": studied_at,
"path": path_match.group(1) if path_match else "",
}
)
return items
def period_cards(html: str) -> dict[str, str]:
"""我的学时页面顶部的总学时、本年学时、本月学时,单位是分钟。"""
found = {}
for key, element in _PERIOD_CARDS:
match = re.search(rf'id="{element}" title="(\d+)分钟"', html or "")
found[key] = match.group(1) if match else ""
return found
def month_span(year: int, month: int) -> tuple[str, str]:
from calendar import monthrange
last = monthrange(year, month)[1]
return f"{year:04d}-{month:02d}-01", f"{year:04d}-{month:02d}-{last:02d}"
def day_span(when: datetime) -> tuple[str, str]:
text = f"{when.year:04d}-{when.month:02d}-{when.day:02d}"
return text, text
def ajax_hidden_fields(payload: str) -> dict[str, str]:
"""读出我的学时翻页回包里的视图状态。回包不是整页,隐藏域在末尾的分段里。"""
fields: dict[str, str] = {}
text = payload or ""
index = 0
size = len(text)
while index < size:
bar = text.find("|", index)
if bar < 0:
break
length_text = text[index:bar]
if not length_text.isdigit():
index = bar + 1
continue
length = int(length_text)
index = bar + 1
bar = text.find("|", index)
if bar < 0:
break
kind = text[index:bar]
index = bar + 1
bar = text.find("|", index)
if bar < 0:
break
field_id = text[index:bar]
index = bar + 1
if index + length > size:
break
content = text[index:index + length]
index += length
if index < size and text[index] == "|":
index += 1
if kind == "hiddenField":
fields[field_id] = content
return fields
def _carry_state(form: dict[str, str], html: str) -> dict[str, str]:
for key, value in ajax_hidden_fields(html).items():
if key.startswith("__"):
form[key] = value
return form
def period_search_form(html: str, start: str, end: str) -> dict[str, str]:
form = training_form(html)
form["txtStartDate"] = start
form["txtEndDate"] = end
form["txtSearch"] = ""
form["ScriptManager1"] = "upList|btnSearch"
form["__EVENTTARGET"] = ""
form["__EVENTARGUMENT"] = ""
form["__ASYNCPOST"] = "true"
form["btnSearch"] = "搜索"
return _carry_state(form, html)
def period_form(html: str, argument: str, page_nav: str | None = None) -> dict[str, str]:
form = training_form(html)
form["__EVENTTARGET"] = "pageNav"
form["__EVENTARGUMENT"] = argument
form["ScriptManager1"] = "upList|pageNav"
form["__ASYNCPOST"] = "true"
if page_nav is not None:
form["pageNav"] = page_nav
return _carry_state(form, html)
def period_has_next(html: str, page: int) -> bool:
text = html or ""
return f"__doPostBack('pageNav','{page + 1}')" in text or "__doPostBack('pageNav','next')" in text
def _history_identity(item: dict) -> tuple:
return (item.get("title"), item.get("studied_at"), item.get("minutes"), item.get("path"))
def _minutes_of(items: list[dict], year: int, month: int, day: int | None = None) -> int:
total = 0
for item in items:
stamp = history_stamp(str(item.get("studied_at") or ""))
if stamp is None or stamp.year != year or stamp.month != month:
continue
if day is not None and stamp.day != day:
continue
minutes = item.get("minutes")
if isinstance(minutes, int) and not isinstance(minutes, bool):
total += minutes
return total
def _history_course_path(row: dict) -> str:
"""学时记录对应的课程页。已有地址直接用,否则按类型拼播放页。"""
explicit = str(row.get("url") or row.get("knowledgeUrl") or row.get("targetUrl") or "").strip()
if explicit:
return explicit
knowledge_id = str(row.get("knowledgeId") or row.get("kngId") or row.get("targetId") or "").replace("-", "").lower()
if len(knowledge_id) != 32 or any(char not in "0123456789abcdef" for char in knowledge_id):
return ""
kind = str(row.get("knowledgeType") or row.get("kngType") or row.get("fileType") or "").strip().lower()
folder = "document"
for needle, name in (
("package", "package"),
("scorm", "scorm"),
("courseknowledge", "scorm"),
("video", "video"),
("audio", "video"),
("xuanyes", "xuanyes"),
("xuan", "xuanyes"),
):
if needle in kind:
folder = name
break
return f"/kng/view/{folder}/{knowledge_id}.html"
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 = _history_course_path(row)
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 take_history_page(rows: list, seen: set[tuple], year: int, month: int, page_size: int) -> tuple[int, bool]:
"""先判断这一页是否重复。返回 (计入的分钟, 是否停止翻页)。"""
if not rows:
return 0, True
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 0, True
seen.add(mark)
add, done = fold_month_minutes(rows, year, month)
return add, bool(done or len(rows) != page_size)
def accumulate_month_minutes(fetch_page, year: int, month: int, page_size: int = HISTORY_PAGE_SIZE) -> tuple[int, bool]:
"""倒序分页累加本月分钟,遇到上个月即停。重复页直接返回,不再累加。"""
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, False
add, stop = take_history_page(rows, seen, year, month, page_size)
total += add
if stop:
return total, False
offset += page_size
return total, True
def parse_training_cards(page: str, status: str) -> list[dict]:
items = []
for block in re.findall(r"<li class='el-plan-li-3'[\s\S]*?</li>", page):
progress = re.search(r'progress="(\d+)"', block)
name = re.search(r'class="font-size-16 text-color6 ellipsis">\s*([^<]+)', block)
owner = re.search(r'<span class="mr10">\s*([^<]+)', block)
assigned = re.search(r"sty_lbl_assignedtime\"><span>([^<]+)", block)
credits = re.search(r"el-plan-time'><span>([^<]+)", block)
detail = re.search(r"""learningKnowledge\(['"](/plan/[0-9a-fA-F]{32}\.html)['"]\)""", block)
assigned_text = ""
if assigned:
assigned_text = assigned.group(1).replace("&nbsp;", " ").replace("\xa0", " ").strip()
items.append({
"name": 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'<li name="userExam">[\s\S]*?</li>', page):
name = re.search(r'class="my-exam-title ellipsis">([^<]+)', block)
status_match = re.search(r'my-exam-btn[^"]*"[^>]*value="([^"]+)"', block)
start = re.search(r'sty_lbl_teststarttime"></span>:([^<&]+)', block)
link = re.search(r'href="(/exam/exampreview\.htm\?[^"]+)"', block)
status = status_match.group(1).strip() if status_match else ""
start_text = start.group(1).replace("&nbsp;", " ").strip() if start else ""
detail = unescape(link.group(1)) if link else ""
if not _exam_detail_path(detail):
detail = ""
items.append({
"name": 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]*?</table>', page)
attempts = []
if table:
for row in re.findall(r"<tr>([\s\S]*?)</tr>", table.group(0))[1:]:
cells = [_plain(cell) for cell in re.findall(r"<td\b[^>]*>([\s\S]*?)</td>", row)]
if len(cells) >= 3 and cells[2] in {"通过", "未通过"}:
attempts.append({"submitted": cells[0], "score": cells[1], "result": cells[2]})
return {
"name": _field(page, "lblExamName"),
"total_score": _field(page, "lblMaxScore"),
"pass_score": _field(page, "lblPassScore"),
"questions": _field(page, "lblTotalQuestionQty"),
"window": _field(page, "lblControlDateTime"),
"times": _field(page, "lblExamTimes"),
"limit": _field(page, "lblExamLimit"),
"examinee": _field(page, "lblUserName"),
"view_policy": _field(page, "lblViewRestrict"),
"notice": _field(page, "lblMsg"),
"attempts": attempts,
}
def parse_training_detail(page: str) -> dict:
if "plandetailhead" not in page:
raise RuntimeError("培训明细没有获取到")
head = page.split('id="knowledgestudy"', 1)[0]
title = re.search(r'class="mb20 span-24 font-size-20">[\s\S]*?<span title="([^"]+)"', head)
rank = re.search(r'sty_lbl_ranknumber">([\s\S]*?)</label>\s*</label>\s*</label>', head)
progress = re.search(r'class="schedule1 floatleft">\s*([^<]+)', head)
deadline = re.search(r'mgt_lbl_requirecompletedate">\s*</label>\s*:\s*([^<\s]+)', head)
credits = re.findall(r">\s*([0-9]+(?:\.[0-9]+)?)\s*<span\s+data-localize=\"sty_lbl_point\"", head)
phases = []
for table in re.split(r'<th width="30"><span class="el-mixtrain-num">', page)[1:]:
phase_name = re.search(r'<th class="text-left">[\s\S]*?<span>([^<]+)</span>', table)
phase_hours = re.search(r":\s*([0-9]+(?:\.[0-9]+)?)\s*<span\s+data-localize=\"sty_lbl_minute\"", table)
phase_credits = re.search(r'common_lbl_totalscore"></span>[\s\S]*?:\s*([0-9]+(?:\.[0-9]+)?)', table)
tasks = []
for row in re.findall(r'<tr class="hand"[\s\S]*?</tr>', table):
task_name = re.search(r"""<span class="st" title=(['"])(.*?)\1""", row)
percents = re.findall(r">(\d+%)<", row)
score = re.search(
r'title="已获学分">\s*([^<]+?)\s*</span>\s*&nbsp;/\s*&nbsp;\s*<span class="fontnumber"\s+title="标准学分">\s*([^<]+)',
row,
)
hours = re.search(
r'core_lbl_knghours"></span>:\s*([^<&]+?)\s*&nbsp;/\s*&nbsp;\s*([^<&]+?)\s*<',
row,
)
tasks.append({
"name": 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]*?)</span>', 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"<tr>\s*<td>[\s\S]*?</tr>", page):
link = re.search(r'href="(/(?:kng/view|knowledge)/[^"]+)"[^>]*title=\'([^\']*)\'', row)
if not link:
continue
kind = re.search(r'class="(Knowledge_[A-Za-z]+)"', row)
contributor = re.search(r"title='([^']*)'[^>]*href=\"/myhome\.htm", row)
numbers = re.findall(r'<td class="textcenter"\s*>\s*<span class="color5">([^<]*)</span>', row)
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 LoginRejected(RuntimeError):
"""平台明确拒绝了账号或密码,不能再自动重试。"""
class ManualJigsaw(Exception):
"""自动拼图已用完,把新拼图交给人来拖。"""
def __init__(self, puzzle: dict) -> None:
self.puzzle = puzzle
class QrWaiting(Exception):
"""二维码尚未扫过或还在等待确认。"""
def guard_https(request: httpx.Request) -> None:
if request.url.scheme != "https":
raise RuntimeError("只允许 https 请求")
host = (request.url.host or "").rstrip(".").lower()
if host in {"zte.com.cn", "yunxuetang.cn"} or host.endswith((".zte.com.cn", ".yunxuetang.cn")):
return
request.headers.pop("token", None)
request.headers.pop("Token", None)
async def guard_https_async(request: httpx.Request) -> None:
"""httpx 异步客户端会 await 钩子的返回值,同步函数会得到 None。"""
guard_https(request)
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": [guard_https]},
)
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 "拼图未通过")
if any(word in message for word in ("密码", "账号", "用户名", "工号")):
raise LoginRejected("账号或密码错误")
raise RuntimeError("登录没有完成")
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():
set_cookie(self.client.cookies, name, value, domain=domain, path="/", secure=True)
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:
set_cookie(self.client.cookies, "ELEARNING_00024", token, domain="euniv.zte.com.cn", path="/", secure=True)
set_cookie(self.client.cookies, "ELEARNING_00024", token, domain=".yunxuetang.cn", path="/", secure=True)
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"):
set_cookie(self.client.cookies, "ELEARNING_00024", refreshed, domain=domain, path="/", secure=True)
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 "学时学分查询失败")
fields = self.hour_fields()
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": fields["year_hours"],
"month_hours": fields["month_hours"],
"today_hours": fields["today_hours"],
"total_hours": fields["total_hours"],
"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()
if not periods["year"] and not periods["month"] and not periods["total"]:
raise RuntimeError("个人学习信息没有获取到。")
return {
"year_hours": periods["year"],
"month_hours": periods["month"],
"today_hours": self.today_history_minutes(),
"total_hours": periods["total"],
}
def month_hours(self) -> str:
return self._period_minutes().get("month", "")
def study_history(self) -> list[dict]:
"""我的学时页面上的记录。获得学时和页面表格一致。"""
return self._rows_for_range()
def month_history_minutes(self, now: datetime | None = None) -> int:
"""按当月 1 日到月底搜索我的学时,每页 100 条,加总全部页。"""
current = self._cn_now(now)
start, end = month_span(current.year, current.month)
return _minutes_of(self._rows_for_range(start, end), current.year, current.month)
def today_history_minutes(self, now: datetime | None = None) -> int:
"""页面没有单独的当日学时,按当天日期搜索后把获得学时相加。"""
current = self._cn_now(now)
start, end = day_span(current)
return _minutes_of(self._rows_for_range(start, end), current.year, current.month, current.day)
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]:
return history_rows_from_page(self._study_period_page())
def _post_period(self, form: dict[str, str]) -> str:
response = self.client.post(
f"{EUNIV}/study/myperiod.htm",
data=form,
headers=self._period_headers(),
)
return response.text
def _cn_now(self, now: datetime | None) -> datetime:
from euniv.study_window import CN_TZ
current = now or datetime.now(CN_TZ)
if current.tzinfo is None:
return current.replace(tzinfo=CN_TZ)
return current.astimezone(CN_TZ)
def _open_period(self) -> str:
self._ensure_site()
response = self.client.get(f"{EUNIV}/study/myperiod.htm", headers=self._period_headers())
text = response.text
if "spMonthlyPeriod" not in text and 'class="alter"' not in text:
raise RuntimeError("学时历史没有获取到")
return text
def _rows_for_range(self, start: str | None = None, end: str | None = None) -> list[dict]:
"""读取我的学时表格。给出日期时先按这个范围搜索,再按每页 100 条取完。"""
html = self._open_period()
items: list[dict] = []
seen: set[tuple] = set()
def take(page_html: str) -> int:
added = 0
for row in history_rows_from_page(page_html):
key = _history_identity(row)
if key in seen:
continue
seen.add(key)
items.append(row)
added += 1
return added
if start:
html = self._post_period(period_search_form(html, start, end or start))
take(html)
nav = training_form(html).get("pageNav", "")
if not nav.endswith("|100"):
form = period_form(html, "current", "1|0|100")
if start:
form["txtStartDate"] = start
form["txtEndDate"] = end or start
widened = self._post_period(form)
if history_rows_from_page(widened):
html = widened
take(html)
limited = False
for page in range(2, 51):
if not period_has_next(html, page - 1):
break
before = len(items)
form = period_form(html, str(page))
if start:
form["txtStartDate"] = start
form["txtEndDate"] = end or start
html = self._post_period(form)
take(html)
if len(items) == before:
break
if page == 50 and period_has_next(html, page):
limited = True
self.history_limited = limited
return items
def _period_headers(self) -> dict[str, str]:
return {
"User-Agent": USER_AGENT,
"Referer": EUNIV + "/sty/index.htm",
"Origin": EUNIV,
}
def _period_minutes(self) -> dict[str, str]:
return period_cards(self._study_period_page())
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:
self._checked_profile = None
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("学习平台暂时不可用")
self._checked_profile = payload
return bool(payload.get("cnName"))
def checked_profile(self) -> dict:
"""最近一次凭据检查里的姓名和部门。职级不取出。"""
payload = getattr(self, "_checked_profile", None)
if not isinstance(payload, dict):
return {}
name = payload.get("cnName")
company = payload.get("departmentName")
return {
"name": name if isinstance(name, str) else "",
"department": company if isinstance(company, str) else "",
}
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