feat: 首页显示全部线上培训和我的考试,并按离现在更近的时间排序
This commit is contained in:
+130
-30
@@ -8,6 +8,7 @@ import random
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from urllib.parse import quote
|
||||
|
||||
import httpx
|
||||
@@ -55,6 +56,80 @@ def data_uri(value: str) -> str:
|
||||
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)] = raw.replace("&", "&").replace("<", "<").replace(">", ">").replace(""", '"')
|
||||
return found
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
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)
|
||||
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 ""),
|
||||
"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 = re.search(r'my-exam-btn[^"]*"[^>]*value="([^"]+)"', block)
|
||||
start = re.search(r'sty_lbl_teststarttime"></span>:([^<&]+)', block)
|
||||
start_text = start.group(1).replace(" ", " ").strip() if start else ""
|
||||
items.append({
|
||||
"name": (name.group(1).strip() if name else ""),
|
||||
"status": (status.group(1).strip() if status else ""),
|
||||
"start": start_text,
|
||||
"sort_at": _clock_distance(start_text),
|
||||
})
|
||||
return items
|
||||
|
||||
|
||||
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")
|
||||
moment = datetime.strptime(match.group(1), "%Y-%m-%d %H:%M:%S")
|
||||
return abs((moment - datetime.now()).total_seconds())
|
||||
|
||||
|
||||
def jigsaw_offset(big_png: bytes, small_png: bytes, top: int) -> int:
|
||||
"""返回滑块左边缘在底图上的横坐标。"""
|
||||
big = Image.open(io.BytesIO(big_png)).convert("RGBA")
|
||||
@@ -428,10 +503,6 @@ class EunivClient:
|
||||
today_resp = self._request("GET", f"{STUDY_API}/v1/studyapi/studyhour/todayscorehours")
|
||||
today = today_resp.json()
|
||||
|
||||
exam_resp = self._request("POST", f"{YXT_API}/v1/user/getmyexamcountnew", content=b"")
|
||||
exam_payload = exam_resp.json()
|
||||
exam = exam_payload.get("data") or {}
|
||||
pending_count = int(exam.get("preExamCount") or 0)
|
||||
return {
|
||||
"name": info.get("cnName") or "",
|
||||
"avatar": info.get("headPictureUrl") or "",
|
||||
@@ -443,9 +514,9 @@ class EunivClient:
|
||||
"total_score": score.get("actualStudyScore") or period.get("totalScores") or "",
|
||||
"today_hours": today.get("studyHours"),
|
||||
"today_score": today.get("studyScore"),
|
||||
"pending_exam_count": pending_count,
|
||||
"pending_exams": self._pending_exams(pending_count),
|
||||
"month_hours": self._month_study_hours(),
|
||||
"trainings": _by_closeness(self.online_trainings(), "sort_days"),
|
||||
"exams": _by_closeness(self.my_exams(), "sort_at"),
|
||||
}
|
||||
|
||||
def _month_study_hours(self) -> str:
|
||||
@@ -453,21 +524,50 @@ class EunivClient:
|
||||
match = re.search(r'id="spMonthlyPeriod" title="(\d+)分钟"', text)
|
||||
return match.group(1) if match else ""
|
||||
|
||||
def _ensure_site(self) -> None:
|
||||
if self._profile.get("token") and not getattr(self, "_site_ready", False):
|
||||
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
|
||||
|
||||
def _study_period_page(self) -> str:
|
||||
self._ensure_site()
|
||||
response = self.client.get(
|
||||
f"{EUNIV}/study/myperiod.htm",
|
||||
headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/sty/index.htm"},
|
||||
)
|
||||
if "spMonthlyPeriod" in response.text:
|
||||
return response.text
|
||||
if self._profile.get("token"):
|
||||
self.authorize(self._profile)
|
||||
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
|
||||
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
|
||||
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
|
||||
return self._pages(url, headers, html, parse_exam_cards, "start")
|
||||
|
||||
def credential_alive(self) -> bool:
|
||||
try:
|
||||
response = self._request("POST", f"{YXT_API}/v1/customdiy/user/getuserinfobyid", content=b"")
|
||||
@@ -476,22 +576,22 @@ class EunivClient:
|
||||
payload = response.json()
|
||||
return isinstance(payload, dict) and bool(payload.get("cnName"))
|
||||
|
||||
def _pending_exams(self, count: int) -> list[dict]:
|
||||
if count <= 0:
|
||||
return []
|
||||
response = self._request(
|
||||
"GET",
|
||||
f"{EUNIV}/exam/userallexam.htm",
|
||||
headers={"Accept": "text/html,application/xhtml+xml"},
|
||||
)
|
||||
names = []
|
||||
for match in response.text.split("lblExamName"):
|
||||
if ">" not in match:
|
||||
continue
|
||||
text = match.split(">", 1)[1].split("<", 1)[0].strip()
|
||||
if text:
|
||||
names.append(text)
|
||||
return [{"name": name, "deadline": ""} for name in names]
|
||||
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
|
||||
|
||||
def open_session(self) -> dict:
|
||||
profile = self.login()
|
||||
|
||||
@@ -78,8 +78,9 @@ class FakeClient:
|
||||
"total_score": "3.00",
|
||||
"today_hours": "1",
|
||||
"today_score": "0.10",
|
||||
"pending_exam_count": 1,
|
||||
"pending_exams": [{"name": "安全考试", "deadline": ""}],
|
||||
"month_hours": "60",
|
||||
"exams": [{"name": "安全考试", "status": "已完成", "start": "2026-05-20 00:01:00"}],
|
||||
"trainings": [],
|
||||
}
|
||||
|
||||
|
||||
@@ -116,7 +117,7 @@ def test_login_stores_password_and_credential_only() -> None:
|
||||
assert home.status_code == 200
|
||||
body = home.json()
|
||||
assert body["name"] == "测试用户"
|
||||
assert body["pending_exams"] == [{"name": "安全考试", "deadline": ""}]
|
||||
assert body["exams"] == [{"name": "安全考试", "status": "已完成", "start": "2026-05-20 00:01:00"}]
|
||||
with SessionLocal() as db:
|
||||
account = db.get(Account, "6650000146")
|
||||
assert account is not None
|
||||
@@ -260,3 +261,57 @@ def test_browser_session_logout_and_revoke() -> None:
|
||||
assert account is not None
|
||||
assert account.credential_cipher == ""
|
||||
assert decrypt_secret(account.password_cipher) == "secret-pass"
|
||||
|
||||
|
||||
def test_parse_training_cards_keeps_status() -> None:
|
||||
from euniv.client import parse_training_cards
|
||||
|
||||
html = """
|
||||
<li class='el-plan-li-3' id="contentitem1" onclick='learningKnowledge("/plan/a.html")'>
|
||||
<div class="el-plan-circle-progress p5" progress="100" id="demo1"></div>
|
||||
<div class="font-size-16 text-color6 ellipsis">
|
||||
租赁人员数据保护合规培训-2026</div>
|
||||
<span class="mr10">
|
||||
Jiang Mingjun</span><span data-localizeph="sty_lbl_assignedtime"><span> 194 天</span></span>
|
||||
<span data-localizeph='sty_lbl_getcredits' class='el-plan-time'><span>1</span></span>
|
||||
</li>
|
||||
"""
|
||||
rows = parse_training_cards(html, "已完成")
|
||||
assert rows == [{
|
||||
"name": "租赁人员数据保护合规培训-2026",
|
||||
"status": "已完成",
|
||||
"progress": 100,
|
||||
"owner": "Jiang Mingjun",
|
||||
"assigned": "194 天",
|
||||
"credits": "1",
|
||||
"sort_days": 194.0,
|
||||
}]
|
||||
|
||||
|
||||
def test_lists_put_the_nearest_time_first() -> None:
|
||||
from euniv.client import _by_closeness, parse_exam_cards
|
||||
|
||||
html = """
|
||||
<li name="userExam">
|
||||
<a class="my-exam-title ellipsis">较远的考试</a>
|
||||
<input type="button" class="btn btn-smd btn-primary my-exam-btn btn-primary" onclick="" value="已完成" />
|
||||
<span data-localize="sty_lbl_teststarttime"></span>:2020-01-01 00:00:00
|
||||
</li>
|
||||
<li name="userExam">
|
||||
<a class="my-exam-title ellipsis">较近的考试</a>
|
||||
<input type="button" class="btn btn-smd btn-primary my-exam-btn btn-primary" onclick="" value="已过期" />
|
||||
<span data-localize="sty_lbl_teststarttime"></span>:2026-10-20 00:01:00
|
||||
</li>
|
||||
"""
|
||||
rows = _by_closeness(parse_exam_cards(html), "sort_at")
|
||||
assert [item["name"] for item in rows] == ["较近的考试", "较远的考试"]
|
||||
assert rows[0]["status"] == "已过期"
|
||||
assert "sort_at" not in rows[0]
|
||||
trainings = _by_closeness(
|
||||
[
|
||||
{"name": "很久以前", "sort_days": 741.0},
|
||||
{"name": "刚指派", "sort_days": 5.0},
|
||||
],
|
||||
"sort_days",
|
||||
)
|
||||
assert [item["name"] for item in trainings] == ["刚指派", "很久以前"]
|
||||
|
||||
Reference in New Issue
Block a user