feat: 首页拆分独立加载、骨架动画和手动刷新

This commit is contained in:
2026-11-15 00:48:26 +08:00
parent 9a6f134f56
commit fa6811dab7
9 changed files with 657 additions and 282 deletions
+171 -13
View File
@@ -6,6 +6,7 @@ import base64
import io
import random
import re
import threading
import time
import uuid
from datetime import datetime
@@ -72,6 +73,38 @@ def training_form(page: str) -> dict[str, str]:
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, dumped: list[tuple[str, str, str, str]]) -> None:
for name, value, domain, path in dumped:
client.cookies.set(name, value, domain=domain, path=path)
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:
@@ -231,6 +264,64 @@ def _plain(value: str) -> str:
return re.sub(r"\s+", " ", text).replace("\xa0", " ").replace(" ", " ").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)
comments = re.search(r"<label>\((\d+)\)</label>", row)
courses.append({
"path": link.group(1),
"title": link.group(2).strip(),
"kind": _course_kind(kind.group(1) if kind else "", link.group(1)),
"contributor": 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 "",
"comments": comments.group(1) if comments 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")
@@ -600,8 +691,8 @@ class EunivClient:
"class_count": class_count,
}
def home_snapshot(self) -> dict:
"""实时读取首页要展示的个人信息,调用方不得把结果写入数据库。"""
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:
@@ -622,6 +713,8 @@ class EunivClient:
today = today_resp.json()
periods = self._period_minutes()
if not periods["year"] and not periods["month"]:
raise RuntimeError("个人学习信息没有获取到。")
return {
"name": info.get("cnName") or "",
"avatar": info.get("headPictureUrl") or "",
@@ -633,10 +726,24 @@ class EunivClient:
"total_hours": score.get("actualStudyHour") or "",
"total_score": score.get("actualStudyScore") or period.get("totalScores") or "",
"points": "" if score.get("ablePoint") is None else score.get("ablePoint"),
"trainings": _by_closeness(self.online_trainings(), "sort_days"),
"exams": _by_closeness(self.my_exams(), "sort_at"),
}
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 home_snapshot(self) -> dict:
"""实时读取整页首页。调用方不得把结果写入数据库。"""
data = self.home_summary()
data["trainings"] = self.home_trainings()
data["exams"] = self.home_exams()
return data
def month_hours(self) -> str:
return self._period_minutes().get("month", "")
def _period_minutes(self) -> dict[str, str]:
text = self._study_period_page()
found = {}
@@ -645,18 +752,36 @@ class EunivClient:
found[key] = match.group(1) if match else ""
return found
def _ensure_site(self) -> None:
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):
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
with _authorize_lock(account_id):
if getattr(self, "_site_ready", False):
return ""
shared = _site_sessions.get(account_id)
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)
return ""
self._site_ready = True
_remember_site(account_id, self.client)
return probe.text
return ""
def _study_period_page(self) -> str:
self._ensure_site()
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"},
@@ -668,12 +793,16 @@ class EunivClient:
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
@@ -687,8 +816,37 @@ class EunivClient:
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:
raise RuntimeError("课程清单没有取全")
return list(found.values())
def exam_detail(self, path: str) -> dict:
if not _exam_detail_path(path):
raise RuntimeError("考试明细无法打开")