fix: 学时统一从我的学时页面按日期统计
This commit is contained in:
+28
-30
@@ -1308,50 +1308,48 @@ 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 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
|
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
|
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"
|
url = f"{EUNIV}/study/myperiod.htm"
|
||||||
headers = {"User-Agent": USER_AGENT, "Referer": EUNIV + "/sty/index.htm", "Origin": EUNIV}
|
headers = {"User-Agent": USER_AGENT, "Referer": EUNIV + "/sty/index.htm", "Origin": EUNIV}
|
||||||
resp = await self._http("GET", url, headers=headers)
|
resp = await self._http("GET", url, headers=headers)
|
||||||
html = resp.text
|
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:
|
if "spMonthlyPeriod" not in html and 'class="alter"' not in html:
|
||||||
raise RuntimeError("学时历史没有获取到")
|
raise RuntimeError("学时历史没有获取到")
|
||||||
if absorb(html):
|
resp = await self._http("POST", url, data=period_search_form(html, start, end), headers=headers)
|
||||||
return total
|
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):
|
for page in range(2, 51):
|
||||||
if not period_has_next(html, page - 1):
|
if not period_has_next(html, page - 1):
|
||||||
break
|
break
|
||||||
before = len(seen)
|
form = period_form(html, str(page))
|
||||||
resp = await self._http("POST", url, data=period_form(html, str(page)), headers=headers)
|
form["txtStartDate"] = start
|
||||||
|
form["txtEndDate"] = end
|
||||||
|
resp = await self._http("POST", url, data=form, headers=headers)
|
||||||
html = resp.text
|
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
|
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":
|
def for_course(self) -> "CourseSession":
|
||||||
return CourseSession(self)
|
return CourseSession(self)
|
||||||
|
|||||||
+109
-53
@@ -363,6 +363,31 @@ def period_cards(html: str) -> dict[str, str]:
|
|||||||
return found
|
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]:
|
def period_form(html: str, argument: str, page_nav: str | None = None) -> dict[str, str]:
|
||||||
form = training_form(html)
|
form = training_form(html)
|
||||||
form["__EVENTTARGET"] = "pageNav"
|
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"))
|
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:
|
def _history_course_path(row: dict) -> str:
|
||||||
"""学时记录对应的课程页。已有地址直接用,否则按类型拼播放页。"""
|
"""学时记录对应的课程页。已有地址直接用,否则按类型拼播放页。"""
|
||||||
explicit = str(row.get("url") or row.get("knowledgeUrl") or row.get("targetUrl") or "").strip()
|
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):
|
if score_payload.get("code") not in (None, "0", 0):
|
||||||
raise RuntimeError(score_payload.get("message") or "学时学分查询失败")
|
raise RuntimeError(score_payload.get("message") or "学时学分查询失败")
|
||||||
|
|
||||||
today_resp = self._request("GET", f"{STUDY_API}/v1/studyapi/studyhour/todayscorehours")
|
fields = self.hour_fields()
|
||||||
today = today_resp.json()
|
|
||||||
|
|
||||||
periods = self._period_minutes()
|
|
||||||
if not periods["year"] and not periods["month"]:
|
|
||||||
raise RuntimeError("个人学习信息没有获取到。")
|
|
||||||
return {
|
return {
|
||||||
"name": info.get("cnName") or "",
|
"name": info.get("cnName") or "",
|
||||||
"avatar": info.get("headPictureUrl") or "",
|
"avatar": info.get("headPictureUrl") or "",
|
||||||
"department": info.get("departmentName") or "",
|
"department": info.get("departmentName") or "",
|
||||||
"level": period.get("levelName") or info.get("userClassLevelName") or "",
|
"level": period.get("levelName") or info.get("userClassLevelName") or "",
|
||||||
"year_hours": periods["year"],
|
"year_hours": fields["year_hours"],
|
||||||
"month_hours": periods["month"],
|
"month_hours": fields["month_hours"],
|
||||||
"today_hours": today.get("studyHours"),
|
"today_hours": fields["today_hours"],
|
||||||
"total_hours": periods.get("total") or score.get("actualStudyHour") or "",
|
"total_hours": fields["total_hours"],
|
||||||
"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"),
|
||||||
}
|
}
|
||||||
@@ -1292,20 +1326,15 @@ class EunivClient:
|
|||||||
return _by_closeness(self.online_trainings(), "sort_days")
|
return _by_closeness(self.online_trainings(), "sort_days")
|
||||||
|
|
||||||
def hour_fields(self) -> dict:
|
def hour_fields(self) -> dict:
|
||||||
"""只取四个学时数字,不读个人资料。"""
|
"""总学时、本年、本月来自我的学时页面顶部。当日学时由当天记录相加。"""
|
||||||
periods = self._period_minutes()
|
periods = self._period_minutes()
|
||||||
score_resp = self._request("POST", f"{YXT_API}/v1/customapiforweb/getscoreorpointorhour", json={})
|
if not periods["year"] and not periods["month"] and not periods["total"]:
|
||||||
score_payload = score_resp.json()
|
raise RuntimeError("个人学习信息没有获取到。")
|
||||||
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()
|
|
||||||
return {
|
return {
|
||||||
"year_hours": periods["year"],
|
"year_hours": periods["year"],
|
||||||
"month_hours": periods["month"],
|
"month_hours": periods["month"],
|
||||||
"today_hours": today.get("studyHours"),
|
"today_hours": self.today_history_minutes(),
|
||||||
"total_hours": periods.get("total") or score.get("actualStudyHour") or "",
|
"total_hours": periods["total"],
|
||||||
}
|
}
|
||||||
|
|
||||||
def month_hours(self) -> str:
|
def month_hours(self) -> str:
|
||||||
@@ -1313,21 +1342,19 @@ class EunivClient:
|
|||||||
|
|
||||||
def study_history(self) -> list[dict]:
|
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:
|
def month_history_minutes(self, now: datetime | None = None) -> int:
|
||||||
"""按我的学时页面倒序累加本月获得学时,遇到上个月即停。"""
|
"""按当月 1 日到月底搜索我的学时,每页 100 条,加总全部页。"""
|
||||||
from euniv.study_window import CN_TZ
|
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)
|
def today_history_minutes(self, now: datetime | None = None) -> int:
|
||||||
total = 0
|
"""页面没有单独的当日学时,按当天日期搜索后把获得学时相加。"""
|
||||||
for item in self._load_period_rows(current.year, current.month):
|
current = self._cn_now(now)
|
||||||
if history_month_side(str(item.get("studied_at") or ""), current.year, current.month) != "in":
|
start, end = day_span(current)
|
||||||
continue
|
return _minutes_of(self._rows_for_range(start, end), current.year, current.month, current.day)
|
||||||
minutes = item.get("minutes")
|
|
||||||
if isinstance(minutes, int) and not isinstance(minutes, bool):
|
|
||||||
total += minutes
|
|
||||||
return total
|
|
||||||
|
|
||||||
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
|
||||||
@@ -1346,49 +1373,78 @@ class EunivClient:
|
|||||||
response = self.client.post(
|
response = self.client.post(
|
||||||
f"{EUNIV}/study/myperiod.htm",
|
f"{EUNIV}/study/myperiod.htm",
|
||||||
data=form,
|
data=form,
|
||||||
headers={
|
headers=self._period_headers(),
|
||||||
"User-Agent": USER_AGENT,
|
|
||||||
"Referer": EUNIV + "/sty/index.htm",
|
|
||||||
"Origin": EUNIV,
|
|
||||||
},
|
|
||||||
)
|
)
|
||||||
return response.text
|
return response.text
|
||||||
|
|
||||||
def _load_period_rows(self, stop_year: int | None = None, stop_month: int | None = None) -> list[dict]:
|
def _cn_now(self, now: datetime | None) -> datetime:
|
||||||
"""翻页读取我的学时。指定月份时,遇到更早的月份就停止。"""
|
from euniv.study_window import CN_TZ
|
||||||
html = self._study_period_page()
|
|
||||||
if "spMonthlyPeriod" not in html and 'class="alter"' not in html:
|
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("学时历史没有获取到")
|
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", "")
|
nav = training_form(html).get("pageNav", "")
|
||||||
if nav and not nav.endswith("|100"):
|
if not nav.endswith("|100"):
|
||||||
html = self._post_period(period_form(html, "current", "1|0|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] = []
|
items: list[dict] = []
|
||||||
seen: set[tuple] = set()
|
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):
|
for row in history_rows_from_page(page_html):
|
||||||
key = _history_identity(row)
|
key = _history_identity(row)
|
||||||
if key in seen:
|
if key in seen:
|
||||||
continue
|
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)
|
seen.add(key)
|
||||||
items.append(row)
|
items.append(row)
|
||||||
return False
|
added += 1
|
||||||
|
return added
|
||||||
|
|
||||||
if take(html):
|
take(html)
|
||||||
return items
|
limited = False
|
||||||
for page in range(2, 51):
|
for page in range(2, 51):
|
||||||
if not period_has_next(html, page - 1):
|
if not period_has_next(html, page - 1):
|
||||||
break
|
break
|
||||||
before = len(items)
|
before = len(items)
|
||||||
html = self._post_period(period_form(html, str(page)))
|
form = period_form(html, str(page))
|
||||||
if take(html) or len(items) == before:
|
if start:
|
||||||
|
form["txtStartDate"] = start
|
||||||
|
form["txtEndDate"] = end or start
|
||||||
|
html = self._post_period(form)
|
||||||
|
take(html)
|
||||||
|
if len(items) == before:
|
||||||
break
|
break
|
||||||
|
if page == 50 and period_has_next(html, page):
|
||||||
|
limited = True
|
||||||
|
self.history_limited = limited
|
||||||
return items
|
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]:
|
def _period_minutes(self) -> dict[str, str]:
|
||||||
return period_cards(self._study_period_page())
|
return period_cards(self._study_period_page())
|
||||||
|
|
||||||
|
|||||||
@@ -418,15 +418,6 @@ def _apply_hours_source(client, summary: dict, items: list | None = None) -> dic
|
|||||||
data["hours_source"] = source
|
data["hours_source"] = source
|
||||||
if source != "history":
|
if source != "history":
|
||||||
return data
|
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)
|
walker = getattr(client, "month_history_minutes", None)
|
||||||
if callable(walker):
|
if callable(walker):
|
||||||
try:
|
try:
|
||||||
@@ -435,13 +426,15 @@ def _apply_hours_source(client, summary: dict, items: list | None = None) -> dic
|
|||||||
except Exception:
|
except Exception:
|
||||||
data["limited"] = False
|
data["limited"] = False
|
||||||
return data
|
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:
|
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)
|
reader = getattr(client, "hour_fields", None)
|
||||||
summary = reader() if reader is not None else client.home_summary()
|
summary = reader() if reader is not None else client.home_summary()
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -1155,9 +1155,9 @@ def test_home_and_history_hours_follow_source(monkeypatch) -> None:
|
|||||||
history = client.get("/api/home/history")
|
history = client.get("/api/home/history")
|
||||||
assert home.json()["hours_source"] == history.json()["hours_source"] == "history"
|
assert home.json()["hours_source"] == history.json()["hours_source"] == "history"
|
||||||
assert home.json()["month_hours"] == history.json()["month_hours"] == 2
|
assert home.json()["month_hours"] == history.json()["month_hours"] == 2
|
||||||
assert home.json()["year_hours"] == history.json()["year_hours"] == 2
|
assert home.json()["year_hours"] == history.json()["year_hours"] == "100"
|
||||||
assert home.json()["total_hours"] == history.json()["total_hours"] == 2
|
assert home.json()["total_hours"] == history.json()["total_hours"] == "10"
|
||||||
assert home.json()["today_hours"] == history.json()["today_hours"] == 0
|
assert home.json()["today_hours"] == history.json()["today_hours"] == 1
|
||||||
assert home.json()["total_score"] == "3.00"
|
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"
|
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("<input name='txtStartDate' value=''><input name='txtEndDate' value=''>", "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:
|
def test_period_page_minutes_match_the_official_table() -> None:
|
||||||
from euniv.client import history_rows_from_page, period_cards
|
from euniv.client import history_rows_from_page, period_cards
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user