feat: 按账号调度自动学习并让首页实时跟上状态

This commit is contained in:
2026-11-16 01:14:36 +08:00
parent 158578d17c
commit 7f0466b0f6
31 changed files with 2699 additions and 631 deletions
+509 -8
View File
@@ -1,25 +1,60 @@
import asyncio
import pytest
import json
from datetime import datetime
import httpx
import pytest
from euniv.autostudy import (
CourseCursor,
HoursWatcher,
StudySession,
_HOURS_REFRESH_SECONDS,
_clear_user_status,
_completed,
_count_total,
_finish_user,
_interval_plan,
_jitter,
_job_from_account,
snapshot_courses,
_package_chapter_path,
_parse_minutes,
_play_path,
_set_user_status,
_set_worker_status,
_study_document,
_study_video,
autostudy_status,
wait_stop,
)
from euniv.client import accumulate_month_minutes, fold_month_minutes
from euniv.client import (
accumulate_month_minutes,
as_uuid,
fold_month_minutes,
history_hour_totals,
play_page_params,
study_progress_fields,
)
from euniv.course_workers import CourseWorkersError, of as workers_of, validate as validate_workers
from euniv.proxy import ProxyError, apply as apply_proxy, build_proxy_url, parse_proxy, view_of as proxy_view
from euniv.study_control import eligible as study_eligible, start_now, stop_now
from euniv.study_window import CN_TZ, StudyWindowError, validate_start, window_open
from euniv.proxy import (
ProxyError,
apply as apply_proxy,
build_proxy_url,
client_proxy_args,
parse_proxy,
sync_httpx_client,
view_of as proxy_view,
)
from euniv.study_control import (
assemble,
eligible as study_eligible,
hours_met,
start_now,
stop_now,
view_of as study_view,
)
from euniv.study_window import CN_TZ, StudyWindowError, next_fire_at, validate_start, window_open
def test_parse_proxy_accepts_http_and_socks() -> None:
@@ -50,6 +85,23 @@ def test_parse_proxy_rejects_other_schemes() -> None:
parse_proxy("http://")
def test_socks4_uses_socks_transport_instead_of_httpx_proxy() -> None:
from httpx_socks import AsyncProxyTransport, SyncProxyTransport
http_args = client_proxy_args("http://10.0.0.1:8080")
assert http_args == {"proxy": "http://10.0.0.1:8080"}
socks_args = client_proxy_args("socks4://127.0.0.1:1080")
assert "proxy" not in socks_args
assert isinstance(socks_args["transport"], SyncProxyTransport)
with pytest.raises(ValueError, match="Unknown scheme"):
httpx.Client(proxy="socks4://127.0.0.1:1080", timeout=1)
client = sync_httpx_client("socks4://127.0.0.1:1080", timeout=1)
client.close()
async_args = client_proxy_args("socks5://127.0.0.1:1080", asynchronous=True)
assert isinstance(async_args["transport"], AsyncProxyTransport)
assert "proxy" not in async_args
def test_parse_minutes() -> None:
assert _parse_minutes("") == 0
assert _parse_minutes("600") == 600
@@ -62,10 +114,59 @@ def test_wait_stop_timeout_and_event() -> None:
assert await wait_stop(0.05, event) is False
event.set()
assert await wait_stop(1, event) is True
event.clear()
assert await wait_stop(0, event) is False
asyncio.run(main())
def test_jitter_zero_means_no_wait() -> None:
assert _jitter(0) == 0
assert _jitter(-1) == 0
for _ in range(30):
wait = _jitter(1)
assert 0 <= wait < 5
assert abs(wait - 1) <= 0.3
for _ in range(30):
wait = _jitter(10)
assert 7 <= wait <= 13
def test_count_total_estimates_from_progress() -> None:
assert _count_total(0, 10) == 0
assert _count_total(1, 0) == 0
assert _count_total(2, 100) == 2
assert _count_total(1, 10) == 10
assert _count_total(3, 40) == 8
assert _count_total(1, 39, origin=38) == 62
def test_worker_view_freezes_total_after_first_beat() -> None:
from euniv.autostudy import WorkerView, _clear_user_status
_clear_user_status("u-total")
view = WorkerView("u-total", 1)
view.update(course="甲", progress=38)
view.after_beat(39, ok=True)
first = autostudy_status()["users"]["u-total"]["workers"][0]["total"]
assert first == 62
view.after_beat(50, ok=True)
row = autostudy_status()["users"]["u-total"]["workers"][0]
assert row["sent"] == 2
assert row["total"] == 62
view.after_beat(100, ok=True)
row = autostudy_status()["users"]["u-total"]["workers"][0]
assert row["sent"] == 3
assert row["total"] == 3
_clear_user_status("u-total")
def test_hours_watcher_default_interval_is_one_minute() -> None:
watcher = HoursWatcher(_HourSession("0"), "u1", 600, asyncio.Event())
assert _HOURS_REFRESH_SECONDS == 60
assert watcher.interval == 60
class _HourSession:
def __init__(self, hours: str) -> None:
self.hours = hours
@@ -144,6 +245,18 @@ def test_accumulate_month_minutes_stops_at_previous_month() -> None:
assert accumulate_month_minutes(lambda _offset, _limit: dumped, 2026, 11, page_size=100) == 8
def test_history_hour_totals_splits_year_month_today() -> None:
now = datetime(2026, 11, 15, 12, 0, tzinfo=CN_TZ)
items = [
{"minutes": 10, "studied_at": "2026-11-15 09:00"},
{"minutes": 4, "studied_at": "2026-11-14 23:55"},
{"minutes": 8, "studied_at": "2025-12-01 00:00"},
{"minutes": None, "studied_at": "2026-11-15 10:00"},
{"minutes": 2, "studied_at": ""},
]
assert history_hour_totals(items, now) == {"year": 14, "month": 14, "today": 10, "total": 22}
def test_autostudy_status_lists_workers_in_id_order() -> None:
_clear_user_status("u1")
_set_user_status("u1", state="学习中")
@@ -249,7 +362,22 @@ class _Start:
self.study_start_minute = minute
self.study_start_second = second
self.study_paused = False
self.study_stop_month = ""
self.study_ignore_window = False
self.study_schedule_enabled = True
self.monthly_target = 600
self.month_hours = ""
self.hours_month = ""
def test_next_fire_at_this_month_then_next_month() -> None:
account = _Start(5, 16, 0, 0)
before = datetime(2026, 11, 5, 15, 59, 59, tzinfo=CN_TZ)
assert next_fire_at(account, before) == datetime(2026, 11, 5, 16, 0, 0, tzinfo=CN_TZ)
at = datetime(2026, 11, 5, 16, 0, 0, tzinfo=CN_TZ)
assert next_fire_at(account, at) == datetime(2026, 12, 5, 16, 0, 0, tzinfo=CN_TZ)
account.study_schedule_enabled = False
assert next_fire_at(account, before) is None
def test_study_window_opens_after_configured_time() -> None:
@@ -273,10 +401,182 @@ def test_immediate_start_skips_monthly_window() -> None:
assert account.study_paused is False
assert account.study_ignore_window is True
assert study_eligible(account) is True
stop_now(account)
stop_now(account, datetime(2026, 11, 15, 12, 0, tzinfo=CN_TZ))
assert account.study_paused is True
assert account.study_stop_month == "2026-11"
assert account.study_ignore_window is False
assert study_eligible(account, datetime(2026, 11, 15, 13, 0, tzinfo=CN_TZ)) is False
def test_hours_met_clears_started_without_pause() -> None:
account = _Start(1, 0, 0, 0)
start_now(account)
account.monthly_target = 70
account.month_hours = "78"
assert hours_met(account) is True
assert study_eligible(account) is False
view = study_view(account)
assert view["started"] is False
assert view["hours_met"] is True
assert account.study_paused is False
idle = assemble(account, {})
assert idle["started"] is False
assert idle["active"] is False
live = assemble(account, {"state": "学习中", "workers": [{"id": 1, "course": "A"}]})
assert live["started"] is False
assert live["active"] is False
from euniv.study_control import settle
assert settle(account, {}) is True
assert account.study_ignore_window is False
assert settle(account, {}) is False
def test_stop_this_month_does_not_block_next_month_schedule() -> None:
account = _Start(1, 0, 0, 0)
start_now(account)
stop_now(account, datetime(2026, 11, 15, 12, 0, tzinfo=CN_TZ))
assert study_eligible(account, datetime(2026, 11, 20, 8, 0, tzinfo=CN_TZ)) is False
assert study_view(account, datetime(2026, 12, 1, 0, 0, tzinfo=CN_TZ))["paused"] is False
assert study_eligible(account, datetime(2026, 12, 1, 0, 0, tzinfo=CN_TZ)) is True
def test_stale_month_hours_do_not_block_next_month() -> None:
account = _Start(1, 0, 0, 0)
account.monthly_target = 70
account.month_hours = "78"
account.hours_month = "2026-11"
assert hours_met(account, datetime(2026, 11, 20, tzinfo=CN_TZ)) is True
assert hours_met(account, datetime(2026, 12, 1, tzinfo=CN_TZ)) is False
assert study_eligible(account, datetime(2026, 12, 1, tzinfo=CN_TZ)) is True
def test_work_running_is_wanted_or_studying() -> None:
from euniv.autostudy import drop_work, want_work, work_running
drop_work("u-want")
assert work_running("u-want") is False
want_work("u-want")
assert work_running("u-want") is True
account = _Start(31, 23, 59, 59)
account.employee_id = "u-want"
payload = assemble(account, {})
assert payload["started"] is True
assert payload["month_hours"] == ""
assert payload["monthly_target"] == 600
drop_work("u-want")
assert assemble(account, {})["started"] is False
def test_want_and_drop_work_push_home(monkeypatch) -> None:
seen: list[str | None] = []
monkeypatch.setattr("euniv.study_push.notify", lambda eid=None, urgent=False: seen.append(eid))
from euniv.autostudy import drop_work, want_work
want_work("u-push")
drop_work("u-push")
assert seen == ["u-push", "u-push"]
def test_interval_plan_manual_one_second_uses_admin_wait() -> None:
wait, step, page = _interval_plan(
"video", {"video": 1, "document": 1, "scorm": 1}, False, {"submitProTimes": 30, "pageSize": 1},
)
assert wait == 1
assert step == 1
assert page == 1
def test_assemble_prefers_live_month_hours() -> None:
account = _Start(1, 0, 0, 0)
account.month_hours = "10"
assert assemble(account, {"month_hours": "68"})["month_hours"] == "68"
assert assemble(account, {})["month_hours"] == "10"
def test_schedule_disabled_skips_window_until_started() -> None:
account = _Start(1, 0, 0, 0)
account.study_schedule_enabled = False
assert study_eligible(account, datetime(2026, 11, 15, tzinfo=CN_TZ)) is False
start_now(account)
assert study_eligible(account, datetime(2026, 11, 15, tzinfo=CN_TZ)) is True
def test_job_from_account_is_collected_when_credentials_ok() -> None:
from types import SimpleNamespace
import euniv.crypto as crypto
row = SimpleNamespace(
employee_id="u1",
monthly_target=600,
password_cipher="pw",
credential_cipher='{"token":"x"}',
course_workers=2,
use_proxy_pool=False,
proxy_scheme="",
proxy_host="",
proxy_port=None,
proxy_username="",
proxy_password_cipher="",
)
original = crypto.decrypt_secret
crypto.decrypt_secret = lambda value: value
try:
job = _job_from_account(row)
finally:
crypto.decrypt_secret = original
assert job is not None
assert job[0] == "u1"
assert job[1] == 600
assert job[2] == "pw"
assert job[3] == {"token": "x"}
assert job[5] == 2
assert job[6] is False
def test_job_from_account_skips_when_decrypt_fails() -> None:
from types import SimpleNamespace
import euniv.crypto as crypto
row = SimpleNamespace(
employee_id="u-fail",
monthly_target=600,
password_cipher="pw",
credential_cipher="bad",
course_workers=1,
use_proxy_pool=False,
proxy_scheme="",
proxy_host="",
proxy_port=None,
proxy_username="",
proxy_password_cipher="",
)
original = crypto.decrypt_secret
def boom(_value: str) -> str:
raise ValueError("bad")
crypto.decrypt_secret = boom
try:
assert _job_from_account(row) is None
assert autostudy_status()["users"]["u-fail"]["state"] == "学习失败"
finally:
crypto.decrypt_secret = original
_clear_user_status("u-fail")
def test_finish_user_keeps_failure_and_clears_idle() -> None:
_clear_user_status("u1")
_set_user_status("u1", state="会话失效")
_finish_user("u1")
assert autostudy_status()["users"]["u1"]["state"] == "会话失效"
_set_user_status("u1", state="学习中")
_finish_user("u1")
assert "u1" not in autostudy_status()["users"]
_finish_user("u2", RuntimeError("boom"))
assert autostudy_status()["users"]["u2"]["state"] == "学习失败"
_clear_user_status("u2")
def test_study_window_rejects_invalid_parts() -> None:
@@ -298,6 +598,25 @@ def test_course_workers_default_and_range() -> None:
validate_workers(9)
def test_course_snapshot_orders_video_document_package_scorm() -> None:
from types import SimpleNamespace
rows = [
SimpleNamespace(path="/c", title="Z课", kind="课程"),
SimpleNamespace(path="/a2", title="乙视频", kind="视频"),
SimpleNamespace(path="/a1", title="甲视频", kind="视频"),
SimpleNamespace(path="/e", title="音频", kind="音频"),
SimpleNamespace(path="/d", title="包", kind="课程包"),
SimpleNamespace(path="/b", title="文档", kind="文档"),
]
snapshot = snapshot_courses(rows)
assert [item[2] for item in snapshot] == ["视频", "视频", "文档", "课程包", "课程", "音频"]
assert [item[1] for item in snapshot[:2]] == ["乙视频", "甲视频"]
copied = snapshot_courses([("p", "课", "课程"), ("v", "视", "视频")])
assert copied[0][2] == "视频"
assert copied[1][2] == "课程"
def test_course_cursor_hands_each_item_once() -> None:
async def main() -> None:
cursor = CourseCursor([("a", "A", "视频"), ("b", "B", "文档"), ("c", "C", "课程")])
@@ -347,3 +666,185 @@ def test_proxy_pool_scheme_enables_auto() -> None:
apply_proxy(account, "http", "10.0.0.1", 8080)
assert account.use_proxy_pool is False
assert proxy_view(account)["scheme"] == "http"
DASHED_KID = "6970e77d-08b3-4c2a-91e8-8471089f4e73"
COMPACT_KID = "6970e77d08b34c2a91e88471089f4e73"
DASHED_PKG = "00689cb9-1111-4c2a-91e8-8471089f4e73"
COMPACT_PKG = "00689cb911114c2a91e88471089f4e73"
def test_as_uuid_matches_capture_dashed_ids() -> None:
assert as_uuid(COMPACT_KID) == DASHED_KID
assert as_uuid(DASHED_KID) == DASHED_KID
assert as_uuid("") == ""
def test_study_progress_fields_match_capture_body() -> None:
video = study_progress_fields(COMPACT_KID, "", page_size=1, study_time=30, kind=0, view_schedule=30)
assert video["knowledgeId"] == DASHED_KID
assert video["packageId"] == ""
assert video["type"] == 0
assert video["studyTime"] == 30
assert video["end"] is False
packed = study_progress_fields(COMPACT_KID, COMPACT_PKG, page_size=69, study_time=120, kind=1, view_schedule=1)
assert packed["packageId"] == DASHED_PKG
assert packed["pageSize"] == packed["studySize"] == 69
encrypt = study_progress_fields(
COMPACT_KID, "", page_size=-1, study_time=120, kind=2, end=True,
chapter_id=COMPACT_KID, for_encrypt=True,
)
submit = study_progress_fields(
COMPACT_KID, "", page_size=-1, study_time=120, kind=2, end=True, chapter_id=COMPACT_KID,
)
assert encrypt["studyChapterIds"] == DASHED_KID + ";"
assert submit["studyChapterIds"] == DASHED_KID
def test_play_page_params_reads_document_page_count() -> None:
html = (
'var knowledgeType = "DocumentKnowledge";\n'
"var pageSize = 69;\n"
"var submitProTimes = 30;\n"
"var validtimeSpan = 120;\n"
f'var kngId = "{DASHED_KID}";\n'
)
params = play_page_params(html)
assert params["pageSize"] == 69
assert params["submitProTimes"] == 30
assert params["kngId"] == DASHED_KID
def test_play_path_uses_compact_html_id() -> None:
assert _play_path("视频", "/knowledge/video/x.html", DASHED_KID) == f"/kng/view/video/{COMPACT_KID}.html"
assert _play_path("课程包", "/kng/view/package/x.html", COMPACT_PKG) == f"/kng/view/package/{COMPACT_PKG}.html"
assert _package_chapter_path(DASHED_PKG, DASHED_KID, "document") == (
f"/kng/course/package/document/{COMPACT_PKG}_{COMPACT_KID}.html"
)
def test_completed_uses_progress_or_status() -> None:
assert _completed({"studyschedule": 100, "status": "NoStart"}) is True
assert _completed({"studyschedule": 0, "status": "Completed"}) is True
assert _completed({"studyschedule": 8, "status": "Studying"}) is False
assert _completed({"studySchedule": 100}) is True
def test_interval_zero_keeps_payload_time_from_play_page() -> None:
wait, step, page = _interval_plan("video", {"video": 0}, False, {"submitProTimes": 30, "pageSize": 1})
assert wait == 0
assert step == 30
wait, step, page = _interval_plan(
"document", {"document": 10}, True, {"validtimeSpan": 120, "pageSize": 79},
)
assert wait == 120
assert step == 120
assert page == 79
def test_study_session_sends_dashed_ids_to_progress_and_heartbeat() -> None:
async def main() -> None:
session = StudySession.__new__(StudySession)
seen: dict = {}
async def fake_api(_method: str, url: str, **kw: object):
seen["url"] = url
if "content" in kw:
seen["body"] = json.loads(str(kw["content"]))
else:
seen["json"] = kw.get("json")
class Resp:
text = '{"studySchedule":1.61}'
def json(self) -> dict:
return {"studySchedule": 1.61, "studyschedule": 0, "status": "NoStart"}
return Resp()
async def fake_encrypt(body_json: str) -> str:
seen["encrypt"] = json.loads(body_json)
return "deadbeef"
session._api = fake_api
session.get_encrypt_request = fake_encrypt
await session.update_progress(COMPACT_KID, "")
assert seen["json"]["knowledgeId"] == DASHED_KID
assert seen["json"]["packageId"] == ""
await session.submit_video_heartbeat(COMPACT_KID, COMPACT_PKG, 30, 30)
assert seen["encrypt"]["knowledgeId"] == DASHED_KID
assert seen["encrypt"]["packageId"] == DASHED_PKG
assert "encryption" not in seen["encrypt"]
assert seen["body"]["encryption"] == "deadbeef"
assert seen["body"]["realHour"] == 30
assert seen["url"].endswith("/v1/study/submitpro")
asyncio.run(main())
class _CaptureVideo:
def __init__(self) -> None:
self.heartbeats: list[tuple[int, int]] = []
self.progress_calls = 0
async def update_progress(self, _kid: str, _pkg: str) -> dict:
self.progress_calls += 1
if self.progress_calls == 1:
return {"studyschedule": 0, "viewSchedule": 0, "status": "NoStart"}
return {"studyschedule": 100, "viewSchedule": 30, "status": "Completed"}
async def submit_video_heartbeat(self, _kid: str, _pkg: str, study_time: int, view: int) -> dict:
self.heartbeats.append((study_time, view))
return {"studySchedule": 100}
async def month_hours_text(self) -> str:
return "10"
def test_video_interval_zero_still_sends_study_time(monkeypatch) -> None:
monkeypatch.setattr("euniv.autostudy._update_month_hours", lambda *_args: None)
async def main() -> None:
session = _CaptureVideo()
global_stop = asyncio.Event()
user_stop = asyncio.Event()
watcher = HoursWatcher(session, "u1", 600, user_stop)
await _study_video(session, "kid", "", 0, global_stop, watcher, study_time=30)
assert session.heartbeats == [(30, 30)]
asyncio.run(main())
class _CaptureDocument:
def __init__(self) -> None:
self.submits: list[tuple[int, int, int]] = []
self.progress_calls = 0
async def update_progress(self, _kid: str, _pkg: str) -> dict:
self.progress_calls += 1
if self.progress_calls == 1:
return {"studyschedule": 0, "status": "NoStart", "viewSchedule": 1}
return {"studyschedule": 100, "status": "Completed", "viewSchedule": 1}
async def submit_document_heartbeat(
self, _kid: str, _pkg: str, page_size: int, study_time: int, view: int
) -> None:
self.submits.append((page_size, study_time, view))
async def month_hours_text(self) -> str:
return "10"
def test_document_uses_page_size_and_requeries_after_submit(monkeypatch) -> None:
monkeypatch.setattr("euniv.autostudy._update_month_hours", lambda *_args: None)
async def main() -> None:
session = _CaptureDocument()
global_stop = asyncio.Event()
user_stop = asyncio.Event()
watcher = HoursWatcher(session, "u1", 600, user_stop)
await _study_document(session, "kid", "", 69, 0, global_stop, watcher, study_time=120)
assert session.submits == [(69, 120, 1)]
assert session.progress_calls == 2
asyncio.run(main())