feat: 立即开始停止学习并整理学时历史与界面
This commit is contained in:
+61
-12
@@ -28,7 +28,7 @@ from euniv.client import EUNIV, STUDY_API, USER_AGENT, EunivClient, SessionExpir
|
||||
from euniv.course_workers import of as course_workers_of
|
||||
from euniv.models import Account, Course
|
||||
from euniv.proxy import bind_url, is_proxy_failure, uses_pool
|
||||
from euniv.study_window import window_open
|
||||
from euniv.study_control import eligible as study_eligible
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
@@ -37,6 +37,9 @@ _HOURS_REFRESH_SECONDS = 300.0
|
||||
|
||||
_lock = threading.Lock()
|
||||
_status: dict = {"running": False, "users": {}, "message": "", "updated_at": ""}
|
||||
_halt_lock = threading.Lock()
|
||||
_user_halts: dict[str, asyncio.Event] = {}
|
||||
_worker = None
|
||||
|
||||
|
||||
def autostudy_status() -> dict:
|
||||
@@ -63,6 +66,30 @@ def _clear_user_status(employee_id: str) -> None:
|
||||
_status.get("users", {}).pop(employee_id, None)
|
||||
|
||||
|
||||
def request_stop(employee_id: str) -> None:
|
||||
key = (employee_id or "").strip()
|
||||
if not key:
|
||||
return
|
||||
with _halt_lock:
|
||||
event = _user_halts.get(key)
|
||||
if event is not None:
|
||||
event.set()
|
||||
_set_user_status(key, state="已停止", course="")
|
||||
|
||||
|
||||
def request_wake() -> None:
|
||||
worker = _worker
|
||||
if worker is not None:
|
||||
worker.wake()
|
||||
|
||||
|
||||
def is_studying(employee_id: str) -> bool:
|
||||
key = (employee_id or "").strip()
|
||||
with _halt_lock:
|
||||
event = _user_halts.get(key)
|
||||
return event is not None and not event.is_set()
|
||||
|
||||
|
||||
# ── 课程路径解析 ──
|
||||
|
||||
_ID_RE = re.compile(r"([0-9a-fA-F]{32})")
|
||||
@@ -622,6 +649,7 @@ class AutoStudyWorker:
|
||||
self._thread: threading.Thread | None = None
|
||||
self._loop: asyncio.AbstractEventLoop | None = None
|
||||
self._async_stop: asyncio.Event | None = None
|
||||
self._kick: asyncio.Event | None = None
|
||||
|
||||
def start(self) -> None:
|
||||
self._thread = threading.Thread(target=self._run_thread, name="euniv-autostudy", daemon=True)
|
||||
@@ -632,10 +660,15 @@ class AutoStudyWorker:
|
||||
if self._loop and self._async_stop:
|
||||
self._loop.call_soon_threadsafe(self._async_stop.set)
|
||||
|
||||
def wake(self) -> None:
|
||||
if self._loop and self._kick is not None:
|
||||
self._loop.call_soon_threadsafe(self._kick.set)
|
||||
|
||||
def _run_thread(self) -> None:
|
||||
self._loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(self._loop)
|
||||
self._async_stop = asyncio.Event()
|
||||
self._kick = asyncio.Event()
|
||||
try:
|
||||
self._loop.run_until_complete(self._main_loop())
|
||||
finally:
|
||||
@@ -643,18 +676,20 @@ class AutoStudyWorker:
|
||||
|
||||
async def _main_loop(self) -> None:
|
||||
assert self._async_stop is not None
|
||||
await asyncio.sleep(15)
|
||||
assert self._kick is not None
|
||||
await wait_stop(15, self._async_stop, self._kick)
|
||||
while not self._async_stop.is_set():
|
||||
self._kick.clear()
|
||||
try:
|
||||
await self._run_cycle()
|
||||
except Exception as exc:
|
||||
log.exception("自动学习周期异常: %s", exc)
|
||||
_set_status(message=f"异常: {exc}")
|
||||
try:
|
||||
await asyncio.wait_for(self._async_stop.wait(), timeout=random.uniform(300, 600))
|
||||
if self._async_stop.is_set():
|
||||
return
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
if self._kick.is_set():
|
||||
continue
|
||||
await wait_stop(random.uniform(300, 600), self._async_stop, self._kick)
|
||||
|
||||
async def _run_cycle(self) -> None:
|
||||
assert self._async_stop is not None
|
||||
@@ -681,9 +716,13 @@ class AutoStudyWorker:
|
||||
course_list = [(c.path, c.title, c.kind) for c in courses]
|
||||
eligible = []
|
||||
waiting = 0
|
||||
paused = 0
|
||||
for row in users:
|
||||
if not window_open(row):
|
||||
waiting += 1
|
||||
if not study_eligible(row):
|
||||
if getattr(row, "study_paused", False):
|
||||
paused += 1
|
||||
else:
|
||||
waiting += 1
|
||||
continue
|
||||
target = row.monthly_target or 600
|
||||
current = _parse_minutes(row.month_hours)
|
||||
@@ -713,6 +752,8 @@ class AutoStudyWorker:
|
||||
if not eligible:
|
||||
if waiting:
|
||||
_set_status(running=False, message="未到开始时间或已达标")
|
||||
elif paused:
|
||||
_set_status(running=False, message="任务已停止")
|
||||
else:
|
||||
_set_status(running=False, message="所有用户已达标或无有效凭据")
|
||||
return
|
||||
@@ -740,8 +781,17 @@ class AutoStudyWorker:
|
||||
workers: int, use_pool: bool, course_list: list, intervals: dict,
|
||||
auto_mode: bool, sem: asyncio.Semaphore) -> None:
|
||||
assert self._async_stop is not None
|
||||
user_stop = asyncio.Event()
|
||||
with _halt_lock:
|
||||
current = _user_halts.get(employee_id)
|
||||
if current is not None and not current.is_set():
|
||||
return
|
||||
_user_halts[employee_id] = user_stop
|
||||
try:
|
||||
async with sem:
|
||||
if user_stop.is_set():
|
||||
_set_user_status(employee_id, state="已停止")
|
||||
return
|
||||
_set_user_status(employee_id, state="准备", course="")
|
||||
loop = asyncio.get_event_loop()
|
||||
token, user_id, org_id, cookies, proxy = await loop.run_in_executor(
|
||||
@@ -755,7 +805,6 @@ class AutoStudyWorker:
|
||||
) as session:
|
||||
session._employee_id = employee_id # type: ignore[attr-defined]
|
||||
_set_user_status(employee_id, state="学习中")
|
||||
user_stop = asyncio.Event()
|
||||
hours = HoursWatcher(session, employee_id, target, user_stop)
|
||||
if await hours.refresh():
|
||||
return
|
||||
@@ -769,6 +818,9 @@ class AutoStudyWorker:
|
||||
with contextlib.suppress(asyncio.CancelledError):
|
||||
await ticker
|
||||
finally:
|
||||
with _halt_lock:
|
||||
if _user_halts.get(employee_id) is user_stop:
|
||||
_user_halts.pop(employee_id, None)
|
||||
if use_pool:
|
||||
from euniv.proxy_pool import release
|
||||
|
||||
@@ -861,9 +913,6 @@ def _update_month_hours(employee_id: str, hours: str) -> None:
|
||||
|
||||
# ── 启动入口 ──
|
||||
|
||||
_worker: AutoStudyWorker | None = None
|
||||
|
||||
|
||||
def start_autostudy() -> AutoStudyWorker:
|
||||
global _worker
|
||||
w = AutoStudyWorker()
|
||||
|
||||
Reference in New Issue
Block a user