fix: 学时历史改为读取我的学时页面
This commit is contained in:
+35
-21
@@ -1308,35 +1308,49 @@ class StudySession:
|
|||||||
return m.group(1) if m else ""
|
return m.group(1) if m else ""
|
||||||
|
|
||||||
async def month_history_minutes(self, now: datetime | None = None) -> int:
|
async def month_history_minutes(self, now: datetime | None = None) -> int:
|
||||||
from euniv.client import (
|
from euniv.client import history_month_side, history_rows_from_page, period_form, period_has_next, training_form
|
||||||
HISTORY_PAGE_SIZE,
|
|
||||||
history_items_from_payload,
|
|
||||||
history_search_body,
|
|
||||||
take_history_page,
|
|
||||||
)
|
|
||||||
from euniv.study_window import CN_TZ
|
from euniv.study_window import CN_TZ
|
||||||
|
|
||||||
current = now or datetime.now(CN_TZ)
|
current = now or datetime.now(CN_TZ)
|
||||||
year, month = current.year, current.month
|
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
|
total = 0
|
||||||
seen: set[tuple] = set()
|
seen: set[tuple] = set()
|
||||||
for _ in range(50):
|
|
||||||
resp = await self._api(
|
def absorb(page_html: str) -> bool:
|
||||||
"POST",
|
nonlocal total
|
||||||
f"{STUDY_API}/v1/styhis/studyhistory/daily/search",
|
for row in history_rows_from_page(page_html):
|
||||||
json=history_search_body(True, offset, HISTORY_PAGE_SIZE),
|
key = (row.get("title"), row.get("studied_at"), row.get("minutes"), row.get("path"))
|
||||||
)
|
if key in seen:
|
||||||
rows = history_items_from_payload(resp.json())
|
continue
|
||||||
if rows is None:
|
seen.add(key)
|
||||||
if offset == 0:
|
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("学时历史没有获取到")
|
raise RuntimeError("学时历史没有获取到")
|
||||||
|
if absorb(html):
|
||||||
return total
|
return total
|
||||||
add, stop = take_history_page(rows, seen, year, month, HISTORY_PAGE_SIZE)
|
for page in range(2, 51):
|
||||||
total += add
|
if not period_has_next(html, page - 1):
|
||||||
if stop:
|
break
|
||||||
return total
|
before = len(seen)
|
||||||
offset += HISTORY_PAGE_SIZE
|
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
|
return total
|
||||||
|
|
||||||
def for_course(self) -> "CourseSession":
|
def for_course(self) -> "CourseSession":
|
||||||
|
|||||||
+112
-47
@@ -328,6 +328,59 @@ _HISTORY_ROW_RE = re.compile(
|
|||||||
r'<td class="text-center">\s*([^<]+?)\s*</td>',
|
r'<td class="text-center">\s*([^<]+?)\s*</td>',
|
||||||
re.I,
|
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:
|
def _history_course_path(row: dict) -> str:
|
||||||
@@ -1227,7 +1280,7 @@ class EunivClient:
|
|||||||
"year_hours": periods["year"],
|
"year_hours": periods["year"],
|
||||||
"month_hours": periods["month"],
|
"month_hours": periods["month"],
|
||||||
"today_hours": today.get("studyHours"),
|
"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 "",
|
"total_score": score.get("actualStudyScore") or period.get("totalScores") or "",
|
||||||
"points": "" if score.get("ablePoint") is None else score.get("ablePoint"),
|
"points": "" if score.get("ablePoint") is None else score.get("ablePoint"),
|
||||||
}
|
}
|
||||||
@@ -1252,42 +1305,29 @@ class EunivClient:
|
|||||||
"year_hours": periods["year"],
|
"year_hours": periods["year"],
|
||||||
"month_hours": periods["month"],
|
"month_hours": periods["month"],
|
||||||
"today_hours": today.get("studyHours"),
|
"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:
|
def month_hours(self) -> str:
|
||||||
return self._period_minutes().get("month", "")
|
return self._period_minutes().get("month", "")
|
||||||
|
|
||||||
def study_history(self) -> list[dict]:
|
def study_history(self) -> list[dict]:
|
||||||
"""读取「我的学时」列表:来源、获得学时(分钟)、日期。"""
|
"""我的学时页面上的记录。获得学时和页面表格一致。"""
|
||||||
try:
|
return self._load_period_rows()
|
||||||
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()
|
|
||||||
|
|
||||||
def month_history_minutes(self, now: datetime | None = None) -> int:
|
def month_history_minutes(self, now: datetime | None = None) -> int:
|
||||||
"""倒序分页统计本月学时分钟,遇到上个月即停。"""
|
"""按我的学时页面倒序累加本月获得学时,遇到上个月即停。"""
|
||||||
from euniv.study_window import CN_TZ
|
from euniv.study_window import CN_TZ
|
||||||
|
|
||||||
current = now or datetime.now(CN_TZ)
|
current = now or datetime.now(CN_TZ)
|
||||||
year, month = current.year, current.month
|
total = 0
|
||||||
|
for item in self._load_period_rows(current.year, current.month):
|
||||||
def fetch_page(offset: int, limit: int) -> list[dict] | None:
|
if history_month_side(str(item.get("studied_at") or ""), current.year, current.month) != "in":
|
||||||
return self._study_history_search(pageable=True, offset=offset, limit=limit)
|
continue
|
||||||
|
minutes = item.get("minutes")
|
||||||
try:
|
if isinstance(minutes, int) and not isinstance(minutes, bool):
|
||||||
total, limited = accumulate_month_minutes(fetch_page, year, month)
|
total += minutes
|
||||||
self.history_limited = limited
|
|
||||||
return total
|
return total
|
||||||
except SessionExpired:
|
|
||||||
raise
|
|
||||||
except Exception as exc:
|
|
||||||
raise RuntimeError("学时历史没有获取到") from exc
|
|
||||||
|
|
||||||
def _study_history_search(
|
def _study_history_search(
|
||||||
self, *, pageable: bool, offset: int = 0, limit: int = HISTORY_PAGE_SIZE
|
self, *, pageable: bool, offset: int = 0, limit: int = HISTORY_PAGE_SIZE
|
||||||
@@ -1300,32 +1340,57 @@ class EunivClient:
|
|||||||
return history_items_from_payload(response.json())
|
return history_items_from_payload(response.json())
|
||||||
|
|
||||||
def _study_history_page(self) -> list[dict]:
|
def _study_history_page(self) -> list[dict]:
|
||||||
text = self._study_period_page()
|
return history_rows_from_page(self._study_period_page())
|
||||||
items = []
|
|
||||||
for match in _HISTORY_ROW_RE.finditer(text):
|
def _post_period(self, form: dict[str, str]) -> str:
|
||||||
title = unescape(match.group(1) or "").strip()
|
response = self.client.post(
|
||||||
cell = match.group(2) or ""
|
f"{EUNIV}/study/myperiod.htm",
|
||||||
minutes = int(match.group(3))
|
data=form,
|
||||||
studied_at = unescape(match.group(4) or "").strip()
|
headers={
|
||||||
path_match = re.search(r"GoToSource\('([^']+)'", cell)
|
"User-Agent": USER_AGENT,
|
||||||
path = path_match.group(1) if path_match else ""
|
"Referer": EUNIV + "/sty/index.htm",
|
||||||
items.append(
|
"Origin": EUNIV,
|
||||||
{
|
},
|
||||||
"title": title,
|
|
||||||
"minutes": minutes,
|
|
||||||
"studied_at": studied_at,
|
|
||||||
"path": path,
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
|
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
|
return items
|
||||||
|
|
||||||
def _period_minutes(self) -> dict[str, str]:
|
def _period_minutes(self) -> dict[str, str]:
|
||||||
text = self._study_period_page()
|
return period_cards(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
|
|
||||||
|
|
||||||
def _ensure_site(self) -> str:
|
def _ensure_site(self) -> str:
|
||||||
"""确认网页会话可用。同一账号短时间内复用已打开的会话,避免并行请求各自重新登录。"""
|
"""确认网页会话可用。同一账号短时间内复用已打开的会话,避免并行请求各自重新登录。"""
|
||||||
|
|||||||
@@ -1212,6 +1212,28 @@ def test_history_course_path_follows_type_and_keeps_explicit_url() -> None:
|
|||||||
assert named["path"] == "/kng/view/package/abc.html"
|
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 = """
|
||||||
|
<span id="spTotalPeriod" title="24522分钟">2452...</span>
|
||||||
|
<span id="spAnnualPeriod" title="10209分钟">1020...</span>
|
||||||
|
<span id="spMonthlyPeriod" title="126分钟">126</span>
|
||||||
|
<tr class="alter">
|
||||||
|
<td class="text-left" title="ACL协议及VRRP协议原理及配置.mp4">
|
||||||
|
ACL协议及VRRP协议原理及配置.mp4
|
||||||
|
<span onclick="GoToSource('/knowledge/video/49f4d52d7011418492cd61e4615567d7.html','SingleStudy','49f4d52d-7011-4184-92cd-61e4615567d7')"></span>
|
||||||
|
</td>
|
||||||
|
<td class="text-center">111</td>
|
||||||
|
<td class="text-center">2026-11-19 01:51</td>
|
||||||
|
</tr>
|
||||||
|
"""
|
||||||
|
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:
|
def test_study_history_parses_period_table() -> None:
|
||||||
from euniv.client import EunivClient
|
from euniv.client import EunivClient
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user