feat: 自动学习按视频完成和五分钟刷新学时,代理仅 HTTP/SOCKS

This commit is contained in:
2026-11-15 01:10:39 +08:00
parent 9e85a4184c
commit 1141df17f7
6 changed files with 349 additions and 82 deletions
+142 -76
View File
@@ -4,21 +4,22 @@
- 一个后台线程运行独立的 asyncio 事件循环
- 每个用户一个协程,asyncio.gather 并行
- 全局 Semaphore 控制总并发,避免压爆上游
- 每个用户一个 StudySession(httpx.AsyncClient),支持独立 proxy
- 每个用户一个 StudySession(httpx.AsyncClient),代理仅 HTTP/HTTPS/SOCKS4/SOCKS5
- 每个用户可配置同时学几门课(当前默认 1,结构已预留)
- 心跳间隔用 asyncio.sleep,不占线程
- 本月学时:看完一门视频后刷新,学习过程中每 5 分钟刷新;达到阈值即停止该账号
"""
from __future__ import annotations
import asyncio
import contextlib
import hashlib
import json
import logging
import random
import re
import threading
import time
from datetime import datetime, timezone
import httpx
@@ -32,6 +33,7 @@ log = logging.getLogger(__name__)
_SCORM_MD5_KEY = "60db8c0a-72d8-4b8f-bb45-c4c3f29a2696"
_MAX_CONCURRENT_USERS = 8
_MAX_COURSE_PER_USER = 1
_HOURS_REFRESH_SECONDS = 300.0
_lock = threading.Lock()
_status: dict = {"running": False, "users": {}, "message": "", "updated_at": ""}
@@ -110,19 +112,80 @@ def _parse_minutes(value: str) -> int:
return int(m.group(1)) if m else 0
async def wait_stop(timeout: float, *events: asyncio.Event) -> bool:
"""等到任一事件触发或超时。触发返回 True,超时返回 False。"""
if any(event.is_set() for event in events):
return True
if timeout <= 0:
return False
tasks = [asyncio.create_task(event.wait()) for event in events]
done, pending = await asyncio.wait(tasks, timeout=timeout, return_when=asyncio.FIRST_COMPLETED)
for task in pending:
task.cancel()
if pending:
await asyncio.gather(*pending, return_exceptions=True)
return bool(done)
class HoursWatcher:
"""刷新本月学时。看完视频或每 5 分钟查一次,达标后停止该账号。"""
def __init__(
self,
session: "StudySession",
employee_id: str,
target: int,
user_stop: asyncio.Event,
interval: float = _HOURS_REFRESH_SECONDS,
) -> None:
self.session = session
self.employee_id = employee_id
self.target = target
self.user_stop = user_stop
self.interval = interval
self._lock = asyncio.Lock()
self.reached = False
async def refresh(self) -> bool:
async with self._lock:
if self.reached or self.user_stop.is_set():
return True
try:
text = await self.session.month_hours_text()
current = _parse_minutes(text)
if text:
await asyncio.to_thread(_update_month_hours, self.employee_id, text)
if current >= self.target:
self.reached = True
self.user_stop.set()
_set_user_status(self.employee_id, state="已达标")
return True
except Exception:
log.warning("用户 %s 刷新本月学时失败", self.employee_id, exc_info=True)
return False
async def ticker(self, global_stop: asyncio.Event) -> None:
while not global_stop.is_set() and not self.user_stop.is_set():
if await wait_stop(self.interval, global_stop, self.user_stop):
return
await self.refresh()
# ── Async 学习会话 ──
class StudySession:
"""一个用户的异步学习会话。包装 httpx.AsyncClient,提供心跳提交方法。
支持 proxy 参数(当前未启用,架构预留)。
proxy 为 httpx URL,仅 HTTP/HTTPS/SOCKS4/SOCKS5。空值直连。
"""
def __init__(self, token: str, cookies: list[tuple[str, str, str, str]],
proxy: str | None = None) -> None:
from euniv.proxy import parse_proxy
self._token = token
self._initial_cookies = cookies
self._proxy = proxy
self._proxy = parse_proxy(proxy)
self._client: httpx.AsyncClient | None = None
async def __aenter__(self) -> "StudySession":
@@ -331,43 +394,47 @@ class StudySession:
# ── 单门课程的学习协程 ──
def _halted(global_stop: asyncio.Event, hours: HoursWatcher) -> bool:
return global_stop.is_set() or hours.user_stop.is_set()
async def _study_video(session: StudySession, kid: str, pkg_id: str,
interval: int, stop: asyncio.Event,
check_target) -> None:
interval: int, stop: asyncio.Event, hours: HoursWatcher) -> None:
view = 0
while not stop.is_set():
started = False
while not _halted(stop, hours):
progress = await session.update_progress(kid, pkg_id)
schedule = float(progress.get("studyschedule", 0))
if schedule >= 100:
if started:
await hours.refresh()
return
started = True
view = int(progress.get("viewSchedule", view))
view += interval
result = await session.submit_video_heartbeat(kid, pkg_id, interval, view)
new_schedule = result.get("studySchedule")
if new_schedule is not None and float(new_schedule) >= 100:
await hours.refresh()
return
if await check_target():
return
await asyncio.sleep(_jitter(interval))
await wait_stop(_jitter(interval), stop, hours.user_stop)
async def _study_document(session: StudySession, kid: str, pkg_id: str,
page_size: int, interval: int, stop: asyncio.Event,
check_target) -> None:
hours: HoursWatcher) -> None:
view = 1
while not stop.is_set():
while not _halted(stop, hours):
progress = await session.update_progress(kid, pkg_id)
if float(progress.get("studyschedule", 0)) >= 100:
return
await session.submit_document_heartbeat(kid, pkg_id, page_size, interval, view)
if await check_target():
return
await asyncio.sleep(_jitter(interval))
await wait_stop(_jitter(interval), stop, hours.user_stop)
async def _study_scorm(session: StudySession, kid: str, pkg_id: str,
interval: int, stop: asyncio.Event,
check_target, user_id: str, org_id: str) -> None:
interval: int, stop: asyncio.Event, hours: HoursWatcher,
user_id: str, org_id: str) -> None:
import uuid as _uuid
sco_cnt = await session.scorm_count(kid)
session_id = str(_uuid.uuid4())
@@ -392,7 +459,7 @@ async def _study_scorm(session: StudySession, kid: str, pkg_id: str,
total_pages = max(len(answers), 10)
for page_idx in range(total_pages):
if stop.is_set():
if _halted(stop, hours):
return
scorm_data["cmi__core__lesson_location"] = str(page_idx + 1)
scorm_data["cmi__core__session_time"] = "00:00:01"
@@ -402,30 +469,26 @@ async def _study_scorm(session: StudySession, kid: str, pkg_id: str,
pkg_id=pkg_id, data=scorm_data,
)
await session.submit_scorm_heartbeat(kid, pkg_id, interval, sco_id=sco_id, end=True)
if await check_target():
return
progress = await session.update_progress(kid, pkg_id)
if float(progress.get("studyschedule", 0)) >= 100:
return
await asyncio.sleep(_jitter(min(interval, 5)))
await wait_stop(_jitter(min(interval, 5)), stop, hours.user_stop)
while not stop.is_set():
while not _halted(stop, hours):
progress = await session.update_progress(kid, pkg_id)
if float(progress.get("studyschedule", 0)) >= 100:
return
await session.submit_scorm_heartbeat(kid, pkg_id, interval, sco_id=sco_id, end=False)
if await check_target():
return
await asyncio.sleep(_jitter(interval))
await wait_stop(_jitter(interval), stop, hours.user_stop)
async def _study_package(session: StudySession, kid: str, intervals: dict,
auto_mode: bool, stop: asyncio.Event,
check_target, user_id: str, org_id: str) -> None:
auto_mode: bool, stop: asyncio.Event, hours: HoursWatcher,
user_id: str, org_id: str) -> None:
pkg = await session.sync_package(kid)
chapters = pkg.get("userKnowledgeList") or []
for ch in chapters:
if stop.is_set():
if _halted(stop, hours):
return
if float(ch.get("studySchedule", 0)) >= 100:
continue
@@ -450,19 +513,18 @@ async def _study_package(session: StudySession, kid: str, intervals: dict,
pass
if is_video:
await _study_video(session, ch_kid, kid, ch_interval, stop, check_target)
await _study_video(session, ch_kid, kid, ch_interval, stop, hours)
else:
await _study_document(session, ch_kid, kid, page_size, ch_interval, stop, check_target)
if await check_target():
return
await _study_document(session, ch_kid, kid, page_size, ch_interval, stop, hours)
# ── 同步准备:用 EunivClient 建立会话,导出 cookies ──
def _prepare_session(employee_id: str, password: str,
credential: dict) -> tuple[str, str, str, list[tuple[str, str, str, str]]]:
credential: dict, proxy: str | None = None
) -> tuple[str, str, str, list[tuple[str, str, str, str]]]:
"""同步:恢复会话并导出 token + cookies。返回 (token, user_id, org_id, cookies)。"""
client = EunivClient(employee_id, password)
client = EunivClient(employee_id, password, proxy=proxy)
try:
client.restore(credential)
if not client.credential_alive():
@@ -591,69 +653,74 @@ class AutoStudyWorker:
async with sem:
_set_user_status(employee_id, state="准备", course="")
# 后续从账号读取 HTTP/SOCKS 代理 URL 和同时学习门数
from euniv.proxy import parse_proxy
proxy = None
max_courses = _MAX_COURSE_PER_USER
try:
proxy = parse_proxy(proxy)
except ValueError:
_set_user_status(employee_id, state="代理无效")
return
loop = asyncio.get_event_loop()
token, user_id, org_id, cookies = await loop.run_in_executor(
None, _prepare_session, employee_id, password, credential)
None, _prepare_session, employee_id, password, credential, proxy)
if not token:
_set_user_status(employee_id, state="会话失效")
return
# 未来扩展:从数据库读取该用户的 proxy 和 max_concurrent_courses
proxy = None
max_courses = _MAX_COURSE_PER_USER
async with StudySession(token, cookies, proxy=proxy) as session:
session._employee_id = employee_id # type: ignore[attr-defined]
_set_user_status(employee_id, state="学习中")
async def check_target() -> bool:
try:
minutes_text = await session.month_hours_text()
current = _parse_minutes(minutes_text)
if minutes_text:
_update_month_hours(employee_id, minutes_text)
if current >= target:
_set_user_status(employee_id, state="已达标")
return True
except Exception:
pass
return False
if max_courses <= 1:
await self._study_courses_serial(
session, employee_id, course_list, intervals,
auto_mode, check_target, user_id, org_id)
else:
await self._study_courses_parallel(
session, employee_id, course_list, intervals,
auto_mode, check_target, user_id, org_id, max_courses)
user_stop = asyncio.Event()
hours = HoursWatcher(session, employee_id, target, user_stop)
if await hours.refresh():
return
ticker = asyncio.create_task(hours.ticker(self._async_stop))
try:
if max_courses <= 1:
await self._study_courses_serial(
session, employee_id, course_list, intervals,
auto_mode, hours, user_id, org_id)
else:
await self._study_courses_parallel(
session, employee_id, course_list, intervals,
auto_mode, hours, user_id, org_id, max_courses)
finally:
ticker.cancel()
with contextlib.suppress(asyncio.CancelledError):
await ticker
async def _study_courses_serial(self, session: StudySession, employee_id: str,
course_list: list, intervals: dict,
auto_mode: bool, check_target,
auto_mode: bool, hours: HoursWatcher,
user_id: str, org_id: str) -> None:
assert self._async_stop is not None
for path, title, kind in course_list:
if self._async_stop.is_set():
if _halted(self._async_stop, hours):
return
await self._study_one_course(
session, employee_id, path, title, kind,
intervals, auto_mode, check_target, user_id, org_id)
intervals, auto_mode, hours, user_id, org_id)
async def _study_courses_parallel(self, session: StudySession, employee_id: str,
course_list: list, intervals: dict,
auto_mode: bool, check_target,
auto_mode: bool, hours: HoursWatcher,
user_id: str, org_id: str,
max_courses: int) -> None:
"""同一用户同时学多门课。共享 session 和 check_target。"""
"""同一用户同时学多门课。共享会话和学时监视。"""
assert self._async_stop is not None
course_sem = asyncio.Semaphore(max_courses)
async def guarded(path: str, title: str, kind: str) -> None:
if _halted(self._async_stop, hours):
return
async with course_sem:
await self._study_one_course(
session, employee_id, path, title, kind,
intervals, auto_mode, check_target, user_id, org_id)
intervals, auto_mode, hours, user_id, org_id)
tasks = [guarded(p, t, k) for p, t, k in course_list]
await asyncio.gather(*tasks, return_exceptions=True)
@@ -661,8 +728,10 @@ class AutoStudyWorker:
async def _study_one_course(self, session: StudySession, employee_id: str,
path: str, title: str, kind: str,
intervals: dict, auto_mode: bool,
check_target, user_id: str, org_id: str) -> None:
hours: HoursWatcher, user_id: str, org_id: str) -> None:
assert self._async_stop is not None
if _halted(self._async_stop, hours):
return
ctype = _course_type(kind, path)
if ctype == "unknown":
return
@@ -675,7 +744,7 @@ class AutoStudyWorker:
try:
if ctype == "package":
await _study_package(session, kid, intervals, auto_mode,
self._async_stop, check_target, user_id, org_id)
self._async_stop, hours, user_id, org_id)
else:
progress = await session.update_progress(kid, "")
if float(progress.get("studyschedule", 0)) >= 100:
@@ -695,21 +764,18 @@ class AutoStudyWorker:
pass
if ctype == "video":
await _study_video(session, kid, "", interval, self._async_stop, check_target)
await _study_video(session, kid, "", interval, self._async_stop, hours)
elif ctype == "document":
await _study_document(session, kid, "", page_size, interval, self._async_stop, check_target)
await _study_document(session, kid, "", page_size, interval, self._async_stop, hours)
elif ctype == "scorm":
await _study_scorm(session, kid, "", interval, self._async_stop,
check_target, user_id, org_id)
await _study_scorm(session, kid, "", interval, self._async_stop, hours,
user_id, org_id)
except SessionExpired:
_set_user_status(employee_id, state="会话过期")
log.info("用户 %s 会话过期", employee_id)
except Exception as exc:
log.warning("用户 %s 课程 %s 异常: %s", employee_id, title, exc)
if await check_target():
return
# ── 数据库更新 ──
+10 -2
View File
@@ -389,10 +389,18 @@ class ManualJigsaw(Exception):
class EunivClient:
def __init__(self, login_name: str, password: str) -> None:
def __init__(self, login_name: str, password: str, proxy: str | None = None) -> None:
from euniv.proxy import parse_proxy
self.login_name = login_name.strip()
self.password = password
self.client = httpx.Client(timeout=30, follow_redirects=True, headers={"User-Agent": USER_AGENT})
self.proxy = parse_proxy(proxy)
self.client = httpx.Client(
timeout=30,
follow_redirects=True,
proxy=self.proxy,
headers={"User-Agent": USER_AGENT},
)
self._profile: dict = {}
self._yxt_token = ""
self._cipher = ""
+23
View File
@@ -0,0 +1,23 @@
"""账号级 HTTP/HTTPS/SOCKS4/SOCKS5 代理。不处理 VPN 或隧道。"""
from __future__ import annotations
from urllib.parse import urlparse
_SCHEMES = {"http", "https", "socks4", "socks5", "socks5h"}
def parse_proxy(value: str | None) -> str | None:
"""把代理地址规范成 httpx 可用的 URL。空值表示直连。"""
text = (value or "").strip()
if not text:
return None
if "://" not in text:
text = "http://" + text
parsed = urlparse(text)
scheme = (parsed.scheme or "").lower()
if scheme not in _SCHEMES:
raise ValueError("代理只支持 HTTP、HTTPS、SOCKS4、SOCKS5")
if not parsed.hostname:
raise ValueError("代理地址不完整")
return text
+1
View File
@@ -1,4 +1,5 @@
httpx==0.28.1
socksio==1.0.0
cryptography==50.0.2
pillow==13.0.0
fastapi==0.162.0
+153
View File
@@ -0,0 +1,153 @@
import asyncio
import pytest
from euniv.autostudy import HoursWatcher, _parse_minutes, _study_video, wait_stop
from euniv.proxy import parse_proxy
def test_parse_proxy_accepts_http_and_socks() -> None:
assert parse_proxy(None) is None
assert parse_proxy("") is None
assert parse_proxy("127.0.0.1:7890") == "http://127.0.0.1:7890"
assert parse_proxy("http://user:pass@10.0.0.1:8080") == "http://user:pass@10.0.0.1:8080"
assert parse_proxy("https://10.0.0.1:8443") == "https://10.0.0.1:8443"
assert parse_proxy("socks4://127.0.0.1:1080") == "socks4://127.0.0.1:1080"
assert parse_proxy("socks5://user:pass@127.0.0.1:1080") == "socks5://user:pass@127.0.0.1:1080"
def test_parse_proxy_rejects_other_schemes() -> None:
with pytest.raises(ValueError):
parse_proxy("ss://secret")
with pytest.raises(ValueError):
parse_proxy("openvpn://gateway")
with pytest.raises(ValueError):
parse_proxy("http://")
def test_parse_minutes() -> None:
assert _parse_minutes("") == 0
assert _parse_minutes("600") == 600
assert _parse_minutes("600分钟") == 600
def test_wait_stop_timeout_and_event() -> None:
async def main() -> None:
event = asyncio.Event()
assert await wait_stop(0.05, event) is False
event.set()
assert await wait_stop(1, event) is True
asyncio.run(main())
class _HourSession:
def __init__(self, hours: str) -> None:
self.hours = hours
self.calls = 0
async def month_hours_text(self) -> str:
self.calls += 1
return self.hours
def test_hours_watcher_stops_when_target_reached(monkeypatch) -> None:
saved: list[tuple[str, str]] = []
monkeypatch.setattr("euniv.autostudy._update_month_hours", lambda eid, hours: saved.append((eid, hours)))
async def main() -> None:
session = _HourSession("600")
user_stop = asyncio.Event()
watcher = HoursWatcher(session, "u1", 600, user_stop)
assert await watcher.refresh() is True
assert watcher.reached
assert user_stop.is_set()
assert saved == [("u1", "600")]
asyncio.run(main())
def test_hours_watcher_continues_below_target(monkeypatch) -> None:
monkeypatch.setattr("euniv.autostudy._update_month_hours", lambda *_args: None)
async def main() -> None:
session = _HourSession("100")
user_stop = asyncio.Event()
watcher = HoursWatcher(session, "u1", 600, user_stop)
assert await watcher.refresh() is False
assert not user_stop.is_set()
asyncio.run(main())
def test_hours_ticker_refreshes_while_running(monkeypatch) -> None:
monkeypatch.setattr("euniv.autostudy._update_month_hours", lambda *_args: None)
async def main() -> None:
session = _HourSession("10")
user_stop = asyncio.Event()
global_stop = asyncio.Event()
watcher = HoursWatcher(session, "u1", 600, user_stop, interval=0.05)
task = asyncio.create_task(watcher.ticker(global_stop))
await asyncio.sleep(0.14)
global_stop.set()
await task
assert session.calls >= 1
asyncio.run(main())
class _VideoSession:
def __init__(self, hours: str) -> None:
self.hours = hours
self.progress_calls = 0
self.hour_calls = 0
async def update_progress(self, _kid: str, _pkg: str) -> dict:
self.progress_calls += 1
if self.progress_calls == 1:
return {"studyschedule": 90, "viewSchedule": 30}
return {"studyschedule": 100, "viewSchedule": 60}
async def submit_video_heartbeat(self, *_args, **_kwargs) -> dict:
return {"studySchedule": 100}
async def month_hours_text(self) -> str:
self.hour_calls += 1
return self.hours
def test_video_refresh_hours_when_finished(monkeypatch) -> None:
monkeypatch.setattr("euniv.autostudy._update_month_hours", lambda *_args: None)
async def main() -> None:
session = _VideoSession("700")
global_stop = asyncio.Event()
user_stop = asyncio.Event()
watcher = HoursWatcher(session, "u1", 600, user_stop)
await _study_video(session, "kid", "", 30, global_stop, watcher)
assert session.hour_calls == 1
assert watcher.reached
assert user_stop.is_set()
asyncio.run(main())
class _AlreadyDoneSession:
async def update_progress(self, _kid: str, _pkg: str) -> dict:
return {"studyschedule": 100, "viewSchedule": 0}
async def month_hours_text(self) -> str:
raise AssertionError("跳过已完成视频时不应刷新学时")
def test_video_skip_already_complete_does_not_refresh() -> None:
async def main() -> None:
session = _AlreadyDoneSession()
global_stop = asyncio.Event()
user_stop = asyncio.Event()
watcher = HoursWatcher(session, "u1", 600, user_stop)
await _study_video(session, "kid", "", 30, global_stop, watcher)
assert not watcher.reached
asyncio.run(main())
+20 -4
View File
@@ -30,7 +30,22 @@ const monthlyTarget = ref<number | null>(null);
const targetLoaded = ref(false);
let targetSaveTimer: ReturnType<typeof setTimeout> | undefined;
const studyStatus = ref<{ running: boolean; user: string; course: string; message: string } | null>(null);
interface StudyUserState {
state?: string;
course?: string;
}
const studyStatus = ref<{
running: boolean;
users?: Record<string, StudyUserState>;
message: string;
} | null>(null);
const myStudy = computed(() => {
const users = studyStatus.value?.users;
if (!users) return null;
return users[props.employeeId] ?? null;
});
function amount(value: string | number | null | undefined) {
if (value === null || value === undefined || value === "") return "—";
@@ -200,10 +215,11 @@ onMounted(() => { refresh(); loadTarget(); loadStudyStatus(); });
</div>
</div>
<div v-if="studyStatus" class="home-study-status">
<span class="study-indicator" :class="{ active: studyStatus.running }"></span>
<span v-if="studyStatus.running" class="study-text">
正在学习:{{ studyStatus.course || "准备中" }}
<span class="study-indicator" :class="{ active: Boolean(myStudy) || studyStatus.running }"></span>
<span v-if="myStudy" class="study-text">
{{ myStudy.state === "已达标" ? "本月目标已达到" : `正在学习:${myStudy.course || myStudy.state || "准备中"}` }}
</span>
<span v-else-if="studyStatus.running" class="study-text muted">自动学习进行中</span>
<span v-else-if="studyStatus.message" class="study-text muted">{{ studyStatus.message }}</span>
<span v-else class="study-text muted">自动学习未运行</span>
</div>