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()
|
||||
|
||||
Reference in New Issue
Block a user