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
+27
View File
@@ -20,6 +20,9 @@ from euniv.models import Account
from euniv.service import (
fetch_exam_detail,
fetch_home,
fetch_home_exams,
fetch_home_summary,
fetch_home_trainings,
fetch_training_detail,
login_and_store,
revoke_credential,
@@ -151,6 +154,30 @@ def home(request: Request, db: Session = Depends(get_db)) -> dict:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@app.get("/api/home/summary")
def home_summary(request: Request, db: Session = Depends(get_db)) -> dict:
try:
return fetch_home_summary(db, _signed_in(request, db))
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@app.get("/api/home/exams")
def home_exams(request: Request, db: Session = Depends(get_db)) -> dict:
try:
return fetch_home_exams(db, _signed_in(request, db))
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@app.get("/api/home/trainings")
def home_trainings(request: Request, db: Session = Depends(get_db)) -> dict:
try:
return fetch_home_trainings(db, _signed_in(request, db))
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:
+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("考试明细无法打开")
+59 -3
View File
@@ -17,6 +17,17 @@ from euniv.models import Account
_PENDING_SECONDS = 180
_pending: dict[str, "PendingLogin"] = {}
_credential_guard = threading.Lock()
_credential_locks: dict[str, threading.Lock] = {}
def _credential_lock(employee_id: str) -> threading.Lock:
with _credential_guard:
lock = _credential_locks.get(employee_id)
if lock is None:
lock = threading.Lock()
_credential_locks[employee_id] = lock
return lock
@dataclass
@@ -69,6 +80,7 @@ def login_and_store(
account = db.get(Account, employee_id)
if account and account.password_cipher and account.credential_cipher:
if decrypt_secret(account.password_cipher) == password and _credential_still_valid(account, client_factory):
_request_course_sync(employee_id)
return {"employee_id": employee_id}
_drop_employee(employee_id)
client = client_factory(employee_id, password)
@@ -82,6 +94,7 @@ def login_and_store(
held = True
return {"attempt_id": attempt_id, "jigsaw": exc.puzzle}
_persist(db, employee_id, password, client, profile)
_request_course_sync(employee_id)
return {"employee_id": employee_id}
finally:
if not held:
@@ -116,6 +129,7 @@ def submit_jigsaw(db: Session, attempt_id: str, offset: int) -> dict:
_pending.pop(attempt_id, None)
try:
_persist(db, pending.employee_id, pending.password, pending.client, profile)
_request_course_sync(pending.employee_id)
return {"employee_id": pending.employee_id}
finally:
pending.client.close()
@@ -126,6 +140,18 @@ def fetch_home(db: Session, employee_id: str, client_factory=EunivClient) -> dic
return _live(db, employee_id, client_factory, lambda client: client.home_snapshot())
def fetch_home_summary(db: Session, employee_id: str, client_factory=EunivClient) -> dict:
return _live(db, employee_id, client_factory, lambda client: client.home_summary())
def fetch_home_exams(db: Session, employee_id: str, client_factory=EunivClient) -> dict:
return {"exams": _live(db, employee_id, client_factory, lambda client: client.home_exams())}
def fetch_home_trainings(db: Session, employee_id: str, client_factory=EunivClient) -> dict:
return {"trainings": _live(db, employee_id, client_factory, lambda client: client.home_trainings())}
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))
@@ -164,9 +190,13 @@ def _live(db: Session, employee_id: str, client_factory, read):
raise RuntimeError("登录需要重新验证,请重新登录") from None
data = read(client)
updated = client.export_credential()
if _dump(updated) != _dump(credential):
account.credential_cipher = encrypt_secret(_dump(updated))
db.commit()
with _credential_lock(employee_id):
db.refresh(account)
current_raw = account.credential_cipher
current = json.loads(decrypt_secret(current_raw)) if current_raw else {}
if _dump(updated) != _dump(current) and _dump(current) == _dump(credential):
account.credential_cipher = encrypt_secret(_dump(updated))
db.commit()
return data
finally:
client.close()
@@ -202,6 +232,8 @@ def _refresh_one(employee_id: str, attempts: int, client_factory) -> None:
return
client = None
valid = False
checked_alive = False
hours = ""
try:
password = decrypt_secret(account.password_cipher)
previous = json.loads(decrypt_secret(account.credential_cipher))
@@ -212,10 +244,13 @@ def _refresh_one(employee_id: str, attempts: int, client_factory) -> None:
if _dump(updated) != _dump(previous):
account.credential_cipher = encrypt_secret(_dump(updated))
valid = True
checked_alive = True
else:
profile = client.login(manual=False, auto_attempts=attempts)
_persist(db, employee_id, password, client, profile)
valid = True
if valid:
hours = _month_hours(client)
except Exception:
db.rollback()
valid = False
@@ -229,7 +264,11 @@ def _refresh_one(employee_id: str, attempts: int, client_factory) -> None:
except Exception:
pass
record_outcome(account, valid)
if hours:
account.month_hours = hours
db.commit()
if checked_alive:
_request_course_sync(employee_id)
class _RefreshGate:
@@ -301,5 +340,22 @@ def start_credential_refresh() -> _RefreshGate:
return gate
def _month_hours(client) -> str:
reader = getattr(client, "month_hours", None)
if reader is None:
return ""
try:
value = reader()
except Exception:
return ""
return value if isinstance(value, str) else ""
def _request_course_sync(employee_id: str) -> None:
from euniv.courses import request_course_sync
request_course_sync(employee_id)
def stored_password(account: Account) -> str:
return decrypt_secret(account.password_cipher)