From b9a332f791b2338a7e99efa5af5d38fa89242765 Mon Sep 17 00:00:00 2001 From: Nixevol Date: Thu, 19 Nov 2026 02:34:29 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E5=AD=A6=E6=97=B6=E5=8E=86=E5=8F=B2?= =?UTF-8?q?=E6=94=B9=E4=B8=BA=E8=AF=BB=E5=8F=96=E6=88=91=E7=9A=84=E5=AD=A6?= =?UTF-8?q?=E6=97=B6=E9=A1=B5=E9=9D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/euniv/autostudy.py | 60 ++++++++------ backend/euniv/client.py | 163 ++++++++++++++++++++++++++----------- backend/tests/test_api.py | 22 +++++ 3 files changed, 173 insertions(+), 72 deletions(-) diff --git a/backend/euniv/autostudy.py b/backend/euniv/autostudy.py index e0c24e4..a899fb4 100644 --- a/backend/euniv/autostudy.py +++ b/backend/euniv/autostudy.py @@ -1308,35 +1308,49 @@ class StudySession: return m.group(1) if m else "" async def month_history_minutes(self, now: datetime | None = None) -> int: - from euniv.client import ( - HISTORY_PAGE_SIZE, - history_items_from_payload, - history_search_body, - take_history_page, - ) + from euniv.client import history_month_side, history_rows_from_page, period_form, period_has_next, training_form from euniv.study_window import CN_TZ current = now or datetime.now(CN_TZ) year, month = current.year, current.month - offset = 0 + url = f"{EUNIV}/study/myperiod.htm" + headers = {"User-Agent": USER_AGENT, "Referer": EUNIV + "/sty/index.htm", "Origin": EUNIV} + resp = await self._http("GET", url, headers=headers) + html = resp.text + nav = training_form(html).get("pageNav", "") + if nav and not nav.endswith("|100"): + resp = await self._http("POST", url, data=period_form(html, "current", "1|0|100"), headers=headers) + html = resp.text total = 0 seen: set[tuple] = set() - for _ in range(50): - resp = await self._api( - "POST", - f"{STUDY_API}/v1/styhis/studyhistory/daily/search", - json=history_search_body(True, offset, HISTORY_PAGE_SIZE), - ) - rows = history_items_from_payload(resp.json()) - if rows is None: - if offset == 0: - raise RuntimeError("学时历史没有获取到") - return total - add, stop = take_history_page(rows, seen, year, month, HISTORY_PAGE_SIZE) - total += add - if stop: - return total - offset += HISTORY_PAGE_SIZE + + def absorb(page_html: str) -> bool: + nonlocal total + for row in history_rows_from_page(page_html): + key = (row.get("title"), row.get("studied_at"), row.get("minutes"), row.get("path")) + if key in seen: + continue + seen.add(key) + side = history_month_side(str(row.get("studied_at") or ""), year, month) + if side == "before": + return True + minutes = row.get("minutes") + if side == "in" and isinstance(minutes, int) and not isinstance(minutes, bool): + total += minutes + return False + + if "spMonthlyPeriod" not in html and 'class="alter"' not in html: + raise RuntimeError("学时历史没有获取到") + if absorb(html): + return total + for page in range(2, 51): + if not period_has_next(html, page - 1): + break + before = len(seen) + resp = await self._http("POST", url, data=period_form(html, str(page)), headers=headers) + html = resp.text + if absorb(html) or len(seen) == before: + break return total def for_course(self) -> "CourseSession": diff --git a/backend/euniv/client.py b/backend/euniv/client.py index 2398d2b..b1d1be9 100644 --- a/backend/euniv/client.py +++ b/backend/euniv/client.py @@ -328,6 +328,59 @@ _HISTORY_ROW_RE = re.compile( r'\s*([^<]+?)\s*', re.I, ) +_PERIOD_CARDS = ( + ("year", "spAnnualPeriod"), + ("month", "spMonthlyPeriod"), + ("total", "spTotalPeriod"), +) + + +def history_rows_from_page(html: str) -> list[dict]: + """我的学时页面表格:来源、获得学时(分钟)、日期。""" + items = [] + for match in _HISTORY_ROW_RE.finditer(html or ""): + title = unescape(match.group(1) or "").strip() + cell = match.group(2) or "" + studied_at = unescape(match.group(4) or "").strip() + path_match = re.search(r"GoToSource\('([^']+)'", cell) + items.append( + { + "title": title, + "minutes": int(match.group(3)), + "studied_at": studied_at, + "path": path_match.group(1) if path_match else "", + } + ) + return items + + +def period_cards(html: str) -> dict[str, str]: + """我的学时页面顶部的总学时、本年学时、本月学时,单位是分钟。""" + found = {} + for key, element in _PERIOD_CARDS: + match = re.search(rf'id="{element}" title="(\d+)分钟"', html or "") + found[key] = match.group(1) if match else "" + return found + + +def period_form(html: str, argument: str, page_nav: str | None = None) -> dict[str, str]: + form = training_form(html) + form["__EVENTTARGET"] = "pageNav" + form["__EVENTARGUMENT"] = argument + form["ScriptManager1"] = "upList|pageNav" + form["__ASYNCPOST"] = "true" + if page_nav is not None: + form["pageNav"] = page_nav + return form + + +def period_has_next(html: str, page: int) -> bool: + text = html or "" + return f"__doPostBack('pageNav','{page + 1}')" in text or "__doPostBack('pageNav','next')" in text + + +def _history_identity(item: dict) -> tuple: + return (item.get("title"), item.get("studied_at"), item.get("minutes"), item.get("path")) def _history_course_path(row: dict) -> str: @@ -1227,7 +1280,7 @@ class EunivClient: "year_hours": periods["year"], "month_hours": periods["month"], "today_hours": today.get("studyHours"), - "total_hours": score.get("actualStudyHour") or "", + "total_hours": periods.get("total") or 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"), } @@ -1252,42 +1305,29 @@ class EunivClient: "year_hours": periods["year"], "month_hours": periods["month"], "today_hours": today.get("studyHours"), - "total_hours": score.get("actualStudyHour") or "", + "total_hours": periods.get("total") or score.get("actualStudyHour") or "", } def month_hours(self) -> str: return self._period_minutes().get("month", "") def study_history(self) -> list[dict]: - """读取「我的学时」列表:来源、获得学时(分钟)、日期。""" - try: - items = self._study_history_search(pageable=False) - except SessionExpired: - raise - except Exception: - items = None - if items is not None: - return items - return self._study_history_page() + """我的学时页面上的记录。获得学时和页面表格一致。""" + return self._load_period_rows() def month_history_minutes(self, now: datetime | None = None) -> int: - """倒序分页统计本月学时分钟,遇到上个月即停。""" + """按我的学时页面倒序累加本月获得学时,遇到上个月即停。""" from euniv.study_window import CN_TZ current = now or datetime.now(CN_TZ) - year, month = current.year, current.month - - def fetch_page(offset: int, limit: int) -> list[dict] | None: - return self._study_history_search(pageable=True, offset=offset, limit=limit) - - try: - total, limited = accumulate_month_minutes(fetch_page, year, month) - self.history_limited = limited - return total - except SessionExpired: - raise - except Exception as exc: - raise RuntimeError("学时历史没有获取到") from exc + total = 0 + for item in self._load_period_rows(current.year, current.month): + if history_month_side(str(item.get("studied_at") or ""), current.year, current.month) != "in": + continue + minutes = item.get("minutes") + if isinstance(minutes, int) and not isinstance(minutes, bool): + total += minutes + return total def _study_history_search( self, *, pageable: bool, offset: int = 0, limit: int = HISTORY_PAGE_SIZE @@ -1300,32 +1340,57 @@ class EunivClient: return history_items_from_payload(response.json()) def _study_history_page(self) -> list[dict]: - text = self._study_period_page() - items = [] - for match in _HISTORY_ROW_RE.finditer(text): - title = unescape(match.group(1) or "").strip() - cell = match.group(2) or "" - minutes = int(match.group(3)) - studied_at = unescape(match.group(4) or "").strip() - path_match = re.search(r"GoToSource\('([^']+)'", cell) - path = path_match.group(1) if path_match else "" - items.append( - { - "title": title, - "minutes": minutes, - "studied_at": studied_at, - "path": path, - } - ) + return history_rows_from_page(self._study_period_page()) + + def _post_period(self, form: dict[str, str]) -> str: + response = self.client.post( + f"{EUNIV}/study/myperiod.htm", + data=form, + headers={ + "User-Agent": USER_AGENT, + "Referer": EUNIV + "/sty/index.htm", + "Origin": EUNIV, + }, + ) + return response.text + + def _load_period_rows(self, stop_year: int | None = None, stop_month: int | None = None) -> list[dict]: + """翻页读取我的学时。指定月份时,遇到更早的月份就停止。""" + html = self._study_period_page() + if "spMonthlyPeriod" not in html and 'class="alter"' not in html: + raise RuntimeError("学时历史没有获取到") + nav = training_form(html).get("pageNav", "") + if nav and not nav.endswith("|100"): + html = self._post_period(period_form(html, "current", "1|0|100")) + items: list[dict] = [] + seen: set[tuple] = set() + + def take(page_html: str) -> bool: + for row in history_rows_from_page(page_html): + key = _history_identity(row) + if key in seen: + continue + if stop_year is not None: + side = history_month_side(str(row.get("studied_at") or ""), stop_year, stop_month or 1) + if side == "before": + return True + seen.add(key) + items.append(row) + return False + + if take(html): + return items + for page in range(2, 51): + if not period_has_next(html, page - 1): + break + before = len(items) + html = self._post_period(period_form(html, str(page))) + if take(html) or len(items) == before: + break return items def _period_minutes(self) -> dict[str, str]: - text = self._study_period_page() - found = {} - for key, element in (("year", "spAnnualPeriod"), ("month", "spMonthlyPeriod")): - match = re.search(rf'id="{element}" title="(\d+)分钟"', text) - found[key] = match.group(1) if match else "" - return found + return period_cards(self._study_period_page()) def _ensure_site(self) -> str: """确认网页会话可用。同一账号短时间内复用已打开的会话,避免并行请求各自重新登录。""" diff --git a/backend/tests/test_api.py b/backend/tests/test_api.py index 868383d..0fa94f8 100644 --- a/backend/tests/test_api.py +++ b/backend/tests/test_api.py @@ -1212,6 +1212,28 @@ def test_history_course_path_follows_type_and_keeps_explicit_url() -> None: assert named["path"] == "/kng/view/package/abc.html" +def test_period_page_minutes_match_the_official_table() -> None: + from euniv.client import history_rows_from_page, period_cards + + html = """ + 2452... + 1020... + 126 + + + ACL协议及VRRP协议原理及配置.mp4 + + + 111 + 2026-11-19 01:51 + + """ + assert period_cards(html) == {"year": "10209", "month": "126", "total": "24522"} + rows = history_rows_from_page(html) + assert rows[0]["minutes"] == 111 + assert rows[0]["title"].startswith("ACL协议") + + def test_study_history_parses_period_table() -> None: from euniv.client import EunivClient