fix: 学时统一从我的学时页面按日期统计

This commit is contained in:
Nixevol
2026-11-19 02:44:04 +08:00
parent b9a332f791
commit a717ac714d
4 changed files with 159 additions and 99 deletions
+109 -53
View File
@@ -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())