feat: 考试和培训可点开明细,考试列表显示是否通过

This commit is contained in:
2026-10-27 05:48:57 +08:00
parent 84772c9f7a
commit d42691aebb
6 changed files with 538 additions and 24 deletions
+32 -4
View File
@@ -12,7 +12,15 @@ from pydantic import BaseModel, Field
from sqlalchemy.orm import Session
from euniv.db import get_db, init_db
from euniv.service import fetch_home, login_and_store, revoke_credential, start_credential_refresh, submit_jigsaw
from euniv.service import (
fetch_exam_detail,
fetch_home,
fetch_training_detail,
login_and_store,
revoke_credential,
start_credential_refresh,
submit_jigsaw,
)
from euniv.session import clear_session, read_employee_id, write_session
@@ -95,13 +103,33 @@ def revoke(request: Request, response: Response, db: Session = Depends(get_db))
return {"ok": True}
@app.get("/api/home")
def home(request: Request, db: Session = Depends(get_db)) -> dict:
def _signed_in(request: Request) -> str:
employee_id = read_employee_id(request.cookies)
if not employee_id:
raise HTTPException(status_code=401, detail="未登录")
return employee_id
@app.get("/api/home")
def home(request: Request, db: Session = Depends(get_db)) -> dict:
try:
return fetch_home(db, employee_id)
return fetch_home(db, _signed_in(request))
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@app.get("/api/exam")
def exam_detail(path: str, request: Request, db: Session = Depends(get_db)) -> dict:
try:
return fetch_exam_detail(db, _signed_in(request), path)
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@app.get("/api/training")
def training_detail(path: str, request: Request, db: Session = Depends(get_db)) -> dict:
try:
return fetch_training_detail(db, _signed_in(request), path)
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
+134 -2
View File
@@ -9,6 +9,7 @@ import re
import time
import uuid
from datetime import datetime
from html import unescape
from urllib.parse import quote
import httpx
@@ -86,6 +87,7 @@ def parse_training_cards(page: str, status: str) -> list[dict]:
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()
@@ -96,6 +98,7 @@ def parse_training_cards(page: str, status: str) -> list[dict]:
"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
@@ -105,18 +108,129 @@ 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 = re.search(r'my-exam-btn[^"]*"[^>]*value="([^"]+)"', 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": (name.group(1).strip() if name else ""),
"status": (status.group(1).strip() if status 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": task_name.group(2).strip() if task_name else "",
"progress": percents[-1] if percents else "",
"score": f"{score.group(1).strip()}/{score.group(2).strip()}" if score else "",
"hours": f"{hours.group(1).strip()}/{hours.group(2).strip()}" if hours else "",
})
phases.append({
"name": phase_name.group(1).strip() if phase_name else "",
"hours": phase_hours.group(1) if phase_hours else "",
"credits": phase_credits.group(1) if phase_credits else "",
"tasks": tasks,
})
return {
"name": title.group(1).strip() if title else "",
"owner": _field(head, "lblCertificate"),
"earned_hours": _field(head, "Span1"),
"actual_hours": _field(head, "lblTotalScore"),
"reward_hours": _field(head, "lblPassScore"),
"earned_credits": credits[0] if len(credits) > 0 else "",
"actual_credits": credits[1] if len(credits) > 1 else "",
"reward_credits": credits[2] if len(credits) > 2 else "",
"rank": _plain(rank.group(1)) if rank else "",
"progress": progress.group(1).strip() if progress else "",
"deadline": deadline.group(1) if deadline else "",
"phases": phases,
}
def _exam_result(block: str, status: str) -> str:
state = re.search(r"my-exam-state\s+([A-Za-z]+)", block)
if state and state.group(1).lower() == "pass":
return "已通过"
if state and state.group(1).lower() in {"notpass", "nopass", "fail", "unpass"}:
return "未通过"
if status in {"已完成", "已过期", "未参考"}:
return "未通过"
return ""
def _exam_detail_path(value: str) -> bool:
return bool(re.fullmatch(r"/exam/exampreview\.htm\?[A-Za-z0-9_=&%.\-]+", value)) and "xamArrangeID=" in value
def _field(page: str, element_id: str) -> str:
match = re.search(rf'id="{re.escape(element_id)}"[^>]*>([\s\S]*?)</span>', page)
return _plain(match.group(1)) if match else ""
def _plain(value: str) -> str:
text = re.sub(r"<[^>]+>", " ", value)
return re.sub(r"\s+", " ", text).replace("\xa0", " ").replace("&nbsp;", " ").strip()
def _leading_number(value: str) -> float:
match = re.search(r"(\d+)", value)
return float(match.group(1)) if match else float("inf")
@@ -571,6 +685,24 @@ class EunivClient:
html = self.client.post(url, data=form, headers=headers).text
return self._pages(url, headers, html, parse_exam_cards, "start")
def exam_detail(self, path: str) -> dict:
if not _exam_detail_path(path):
raise RuntimeError("考试明细无法打开")
return parse_exam_detail(self._site_page(path))
def training_detail(self, path: str) -> dict:
if not re.fullmatch(r"/plan/[0-9a-fA-F]{32}\.html", path):
raise RuntimeError("培训明细无法打开")
return parse_training_detail(self._site_page(path))
def _site_page(self, path: str) -> str:
self._ensure_site()
response = self.client.get(
f"{EUNIV}{path}",
headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"},
)
return response.text
def credential_alive(self) -> bool:
try:
response = self._request("POST", f"{YXT_API}/v1/customdiy/user/getuserinfobyid", content=b"")
+14 -2
View File
@@ -122,6 +122,18 @@ def submit_jigsaw(db: Session, attempt_id: str, offset: int) -> dict:
def fetch_home(db: Session, employee_id: str, client_factory=EunivClient) -> dict:
"""向 e 学现查首页信息。个人信息只出现在返回值里,不写入数据库。凭证变化时更新密文。"""
return _live(db, employee_id, client_factory, lambda client: client.home_snapshot())
def fetch_exam_detail(db: Session, employee_id: str, path: str, client_factory=EunivClient) -> dict:
return _live(db, employee_id, client_factory, lambda client: client.exam_detail(path))
def fetch_training_detail(db: Session, employee_id: str, path: str, client_factory=EunivClient) -> dict:
return _live(db, employee_id, client_factory, lambda client: client.training_detail(path))
def _live(db: Session, employee_id: str, client_factory, read):
account = db.get(Account, employee_id)
if account is None:
raise RuntimeError("请先登录")
@@ -136,13 +148,13 @@ def fetch_home(db: Session, employee_id: str, client_factory=EunivClient) -> dic
except ManualJigsaw:
raise RuntimeError("登录需要重新验证,请重新登录") from None
try:
data = client.home_snapshot()
data = read(client)
except SessionExpired:
try:
client.authorize(client.login())
except ManualJigsaw:
raise RuntimeError("登录需要重新验证,请重新登录") from None
data = client.home_snapshot()
data = read(client)
updated = client.export_credential()
if _dump(updated) != _dump(credential):
account.credential_cipher = encrypt_secret(_dump(updated))