From a717ac714d4c2d1fbcf29b7beb9877667f447b97 Mon Sep 17 00:00:00 2001 From: Nixevol Date: Thu, 19 Nov 2026 02:44:04 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E5=AD=A6=E6=97=B6=E7=BB=9F=E4=B8=80?= =?UTF-8?q?=E4=BB=8E=E6=88=91=E7=9A=84=E5=AD=A6=E6=97=B6=E9=A1=B5=E9=9D=A2?= =?UTF-8?q?=E6=8C=89=E6=97=A5=E6=9C=9F=E7=BB=9F=E8=AE=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/euniv/autostudy.py | 58 +++++++------ backend/euniv/client.py | 162 +++++++++++++++++++++++++------------ backend/euniv/service.py | 19 ++--- backend/tests/test_api.py | 19 ++++- 4 files changed, 159 insertions(+), 99 deletions(-) diff --git a/backend/euniv/autostudy.py b/backend/euniv/autostudy.py index a899fb4..f87734b 100644 --- a/backend/euniv/autostudy.py +++ b/backend/euniv/autostudy.py @@ -1308,50 +1308,48 @@ 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_month_side, history_rows_from_page, period_form, period_has_next, training_form + from euniv.client import _minutes_of, history_rows_from_page, month_span, period_form, period_has_next, period_search_form, training_form from euniv.study_window import CN_TZ current = now or datetime.now(CN_TZ) - year, month = current.year, current.month + if current.tzinfo is None: + current = current.replace(tzinfo=CN_TZ) + else: + current = current.astimezone(CN_TZ) + start, end = month_span(current.year, current.month) 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() - - 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 + resp = await self._http("POST", url, data=period_search_form(html, start, end), headers=headers) + html = resp.text + if not training_form(html).get("pageNav", "").endswith("|100"): + form = period_form(html, "current", "1|0|100") + form["txtStartDate"] = start + form["txtEndDate"] = end + resp = await self._http("POST", url, data=form, headers=headers) + html = resp.text + rows = history_rows_from_page(html) + seen = {(row.get("title"), row.get("studied_at"), row.get("minutes"), row.get("path")) for row in rows} 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) + form = period_form(html, str(page)) + form["txtStartDate"] = start + form["txtEndDate"] = end + resp = await self._http("POST", url, data=form, headers=headers) html = resp.text - if absorb(html) or len(seen) == before: + fresh = [ + row for row in history_rows_from_page(html) + if (row.get("title"), row.get("studied_at"), row.get("minutes"), row.get("path")) not in seen + ] + if not fresh: break - return total + rows.extend(fresh) + seen.update((row.get("title"), row.get("studied_at"), row.get("minutes"), row.get("path")) for row in fresh) + return _minutes_of(rows, current.year, current.month) def for_course(self) -> "CourseSession": return CourseSession(self) diff --git a/backend/euniv/client.py b/backend/euniv/client.py index b1d1be9..77ea723 100644 --- a/backend/euniv/client.py +++ b/backend/euniv/client.py @@ -363,6 +363,31 @@ def period_cards(html: str) -> dict[str, str]: return found +def month_span(year: int, month: int) -> tuple[str, str]: + from calendar import monthrange + + last = monthrange(year, month)[1] + return f"{year:04d}-{month:02d}-01", f"{year:04d}-{month:02d}-{last:02d}" + + +def day_span(when: datetime) -> tuple[str, str]: + text = f"{when.year:04d}-{when.month:02d}-{when.day:02d}" + return text, text + + +def period_search_form(html: str, start: str, end: str) -> dict[str, str]: + form = training_form(html) + form["txtStartDate"] = start + form["txtEndDate"] = end + form["txtSearch"] = "" + form["ScriptManager1"] = "upList|btnSearch" + form["__EVENTTARGET"] = "" + form["__EVENTARGUMENT"] = "" + form["__ASYNCPOST"] = "true" + form["btnSearch"] = "搜索" + return form + + def period_form(html: str, argument: str, page_nav: str | None = None) -> dict[str, str]: form = training_form(html) form["__EVENTTARGET"] = "pageNav" @@ -383,6 +408,20 @@ def _history_identity(item: dict) -> tuple: return (item.get("title"), item.get("studied_at"), item.get("minutes"), item.get("path")) +def _minutes_of(items: list[dict], year: int, month: int, day: int | None = None) -> int: + total = 0 + for item in items: + stamp = history_stamp(str(item.get("studied_at") or "")) + if stamp is None or stamp.year != year or stamp.month != month: + continue + if day is not None and stamp.day != day: + continue + minutes = item.get("minutes") + if isinstance(minutes, int) and not isinstance(minutes, bool): + total += minutes + return total + + def _history_course_path(row: dict) -> str: """学时记录对应的课程页。已有地址直接用,否则按类型拼播放页。""" explicit = str(row.get("url") or row.get("knowledgeUrl") or row.get("targetUrl") or "").strip() @@ -1266,21 +1305,16 @@ class EunivClient: if score_payload.get("code") not in (None, "0", 0): raise RuntimeError(score_payload.get("message") or "学时学分查询失败") - today_resp = self._request("GET", f"{STUDY_API}/v1/studyapi/studyhour/todayscorehours") - today = today_resp.json() - - periods = self._period_minutes() - if not periods["year"] and not periods["month"]: - raise RuntimeError("个人学习信息没有获取到。") + fields = self.hour_fields() return { "name": info.get("cnName") or "", "avatar": info.get("headPictureUrl") or "", "department": info.get("departmentName") or "", "level": period.get("levelName") or info.get("userClassLevelName") or "", - "year_hours": periods["year"], - "month_hours": periods["month"], - "today_hours": today.get("studyHours"), - "total_hours": periods.get("total") or score.get("actualStudyHour") or "", + "year_hours": fields["year_hours"], + "month_hours": fields["month_hours"], + "today_hours": fields["today_hours"], + "total_hours": fields["total_hours"], "total_score": score.get("actualStudyScore") or period.get("totalScores") or "", "points": "" if score.get("ablePoint") is None else score.get("ablePoint"), } @@ -1292,20 +1326,15 @@ class EunivClient: return _by_closeness(self.online_trainings(), "sort_days") def hour_fields(self) -> dict: - """只取四个学时数字,不读个人资料。""" + """总学时、本年、本月来自我的学时页面顶部。当日学时由当天记录相加。""" periods = self._period_minutes() - score_resp = self._request("POST", f"{YXT_API}/v1/customapiforweb/getscoreorpointorhour", json={}) - score_payload = score_resp.json() - score = score_payload.get("data") or {} - if score_payload.get("code") not in (None, "0", 0): - raise RuntimeError(score_payload.get("message") or "学时学分查询失败") - today_resp = self._request("GET", f"{STUDY_API}/v1/studyapi/studyhour/todayscorehours") - today = today_resp.json() + if not periods["year"] and not periods["month"] and not periods["total"]: + raise RuntimeError("个人学习信息没有获取到。") return { "year_hours": periods["year"], "month_hours": periods["month"], - "today_hours": today.get("studyHours"), - "total_hours": periods.get("total") or score.get("actualStudyHour") or "", + "today_hours": self.today_history_minutes(), + "total_hours": periods["total"], } def month_hours(self) -> str: @@ -1313,21 +1342,19 @@ class EunivClient: def study_history(self) -> list[dict]: """我的学时页面上的记录。获得学时和页面表格一致。""" - return self._load_period_rows() + return self._rows_for_range() def month_history_minutes(self, now: datetime | None = None) -> int: - """按我的学时页面倒序累加本月获得学时,遇到上个月即停。""" - from euniv.study_window import CN_TZ + """按当月 1 日到月底搜索我的学时,每页 100 条,加总全部页。""" + current = self._cn_now(now) + start, end = month_span(current.year, current.month) + return _minutes_of(self._rows_for_range(start, end), current.year, current.month) - current = now or datetime.now(CN_TZ) - 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 today_history_minutes(self, now: datetime | None = None) -> int: + """页面没有单独的当日学时,按当天日期搜索后把获得学时相加。""" + current = self._cn_now(now) + start, end = day_span(current) + return _minutes_of(self._rows_for_range(start, end), current.year, current.month, current.day) def _study_history_search( self, *, pageable: bool, offset: int = 0, limit: int = HISTORY_PAGE_SIZE @@ -1346,49 +1373,78 @@ class EunivClient: response = self.client.post( f"{EUNIV}/study/myperiod.htm", data=form, - headers={ - "User-Agent": USER_AGENT, - "Referer": EUNIV + "/sty/index.htm", - "Origin": EUNIV, - }, + headers=self._period_headers(), ) 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: + def _cn_now(self, now: datetime | None) -> datetime: + from euniv.study_window import CN_TZ + + current = now or datetime.now(CN_TZ) + if current.tzinfo is None: + return current.replace(tzinfo=CN_TZ) + return current.astimezone(CN_TZ) + + def _open_period(self) -> str: + self._ensure_site() + response = self.client.get(f"{EUNIV}/study/myperiod.htm", headers=self._period_headers()) + text = response.text + if "spMonthlyPeriod" not in text and 'class="alter"' not in text: raise RuntimeError("学时历史没有获取到") + return text + + def _rows_for_range(self, start: str | None = None, end: str | None = None) -> list[dict]: + """读取我的学时表格。给出日期时先按这个范围搜索,再按每页 100 条取完。""" + html = self._open_period() + if start: + html = self._post_period(period_search_form(html, start, end or start)) nav = training_form(html).get("pageNav", "") - if nav and not nav.endswith("|100"): - html = self._post_period(period_form(html, "current", "1|0|100")) + if not nav.endswith("|100"): + form = period_form(html, "current", "1|0|100") + if start: + form["txtStartDate"] = start + form["txtEndDate"] = end or start + html = self._post_period(form) items: list[dict] = [] seen: set[tuple] = set() - def take(page_html: str) -> bool: + def take(page_html: str) -> int: + added = 0 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 + added += 1 + return added - if take(html): - return items + take(html) + limited = False 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: + form = period_form(html, str(page)) + if start: + form["txtStartDate"] = start + form["txtEndDate"] = end or start + html = self._post_period(form) + take(html) + if len(items) == before: break + if page == 50 and period_has_next(html, page): + limited = True + self.history_limited = limited return items + def _period_headers(self) -> dict[str, str]: + return { + "User-Agent": USER_AGENT, + "Referer": EUNIV + "/sty/index.htm", + "Origin": EUNIV, + } + def _period_minutes(self) -> dict[str, str]: return period_cards(self._study_period_page()) diff --git a/backend/euniv/service.py b/backend/euniv/service.py index caed425..895959c 100644 --- a/backend/euniv/service.py +++ b/backend/euniv/service.py @@ -418,15 +418,6 @@ def _apply_hours_source(client, summary: dict, items: list | None = None) -> dic data["hours_source"] = source if source != "history": return data - if items is None: - raw = client.study_history() - items = raw if isinstance(raw, list) else [] - totals = history_hour_totals(items) - data["year_hours"] = totals["year"] - data["month_hours"] = totals["month"] - data["today_hours"] = totals["today"] - data["total_hours"] = totals["total"] - data["limited"] = False walker = getattr(client, "month_history_minutes", None) if callable(walker): try: @@ -434,14 +425,16 @@ def _apply_hours_source(client, summary: dict, items: list | None = None) -> dic data["limited"] = bool(getattr(client, "history_limited", False)) except Exception: data["limited"] = False + return data + if items is None: + raw = getattr(client, "study_history", None) + items = raw() if callable(raw) else [] + totals = history_hour_totals(items if isinstance(items, list) else []) + data["month_hours"] = totals["month"] return data def _api_hour_fields(client) -> dict: - from admin.settings import hours_source_of - - if hours_source_of() == "history": - return {} reader = getattr(client, "hour_fields", None) summary = reader() if reader is not None else client.home_summary() return { diff --git a/backend/tests/test_api.py b/backend/tests/test_api.py index 0fa94f8..da802e3 100644 --- a/backend/tests/test_api.py +++ b/backend/tests/test_api.py @@ -1155,9 +1155,9 @@ def test_home_and_history_hours_follow_source(monkeypatch) -> None: history = client.get("/api/home/history") assert home.json()["hours_source"] == history.json()["hours_source"] == "history" assert home.json()["month_hours"] == history.json()["month_hours"] == 2 - assert home.json()["year_hours"] == history.json()["year_hours"] == 2 - assert home.json()["total_hours"] == history.json()["total_hours"] == 2 - assert home.json()["today_hours"] == history.json()["today_hours"] == 0 + assert home.json()["year_hours"] == history.json()["year_hours"] == "100" + assert home.json()["total_hours"] == history.json()["total_hours"] == "10" + assert home.json()["today_hours"] == history.json()["today_hours"] == 1 assert home.json()["total_score"] == "3.00" @@ -1212,6 +1212,19 @@ def test_history_course_path_follows_type_and_keeps_explicit_url() -> None: assert named["path"] == "/kng/view/package/abc.html" +def test_month_span_covers_the_whole_month() -> None: + from euniv.client import day_span, month_span, period_search_form + + assert month_span(2026, 11) == ("2026-11-01", "2026-11-30") + assert month_span(2024, 2) == ("2024-02-01", "2024-02-29") + form = period_search_form("", "2026-11-01", "2026-11-30") + assert form["txtStartDate"] == "2026-11-01" + assert form["txtEndDate"] == "2026-11-30" + assert form["btnSearch"] == "搜索" + assert form["ScriptManager1"] == "upList|btnSearch" + assert day_span(datetime(2026, 11, 19, 2, 10)) == ("2026-11-19", "2026-11-19") + + def test_period_page_minutes_match_the_official_table() -> None: from euniv.client import history_rows_from_page, period_cards