From 7f0466b0f6b82f17d11127dbba8d5039a153143d Mon Sep 17 00:00:00 2001 From: Nixevol Date: Mon, 16 Nov 2026 01:14:36 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=8C=89=E8=B4=A6=E5=8F=B7=E8=B0=83?= =?UTF-8?q?=E5=BA=A6=E8=87=AA=E5=8A=A8=E5=AD=A6=E4=B9=A0=E5=B9=B6=E8=AE=A9?= =?UTF-8?q?=E9=A6=96=E9=A1=B5=E5=AE=9E=E6=97=B6=E8=B7=9F=E4=B8=8A=E7=8A=B6?= =?UTF-8?q?=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/admin/routes.py | 2 + backend/admin/settings.py | 12 +- backend/admin/users.py | 14 +- .../alembic/versions/0014_study_schedule.py | 49 ++ backend/euniv/api.py | 83 +- backend/euniv/autostudy.py | 738 +++++++++++++----- backend/euniv/client.py | 247 ++++-- backend/euniv/models.py | 5 +- backend/euniv/proxy.py | 30 +- backend/euniv/proxy_pool.py | 12 +- backend/euniv/service.py | 75 +- backend/euniv/study_control.py | 144 +++- backend/euniv/study_push.py | 127 +++ backend/euniv/study_window.py | 48 +- backend/requirements.txt | 4 + backend/tests/test_admin.py | 12 + backend/tests/test_api.py | 156 +++- backend/tests/test_autostudy.py | 517 +++++++++++- backend/tests/test_proxy_pool.py | 8 +- backend/tests/test_study_poll.py | 19 + backend/tests/test_study_push.py | 48 ++ web/src/features/admin/CoursesView.vue | 9 +- web/src/features/admin/ProxiesView.vue | 11 +- web/src/features/admin/SettingsView.vue | 23 +- web/src/features/admin/UsersView.vue | 18 +- web/src/features/history/HoursHistoryView.vue | 69 +- web/src/features/home/HomeView.vue | 541 +++++++++---- web/src/shared/studyFields.ts | 13 +- web/src/shared/theme.ts | 15 + web/src/styles.css | 276 ++++++- web/vite.config.ts | 5 +- 31 files changed, 2699 insertions(+), 631 deletions(-) create mode 100644 backend/alembic/versions/0014_study_schedule.py create mode 100644 backend/euniv/study_push.py create mode 100644 backend/tests/test_study_poll.py create mode 100644 backend/tests/test_study_push.py diff --git a/backend/admin/routes.py b/backend/admin/routes.py index f6b85a2..b6a9f8d 100644 --- a/backend/admin/routes.py +++ b/backend/admin/routes.py @@ -94,6 +94,7 @@ class AdminStudySettingsBody(BaseModel): hour: int | None = None minute: int | None = None second: int | None = None + schedule_enabled: bool | None = None workers: int | None = None scheme: str | None = None host: str = "" @@ -289,6 +290,7 @@ def put_users_study_settings( hour=body.hour, minute=body.minute, second=body.second, + schedule_enabled=body.schedule_enabled, workers=body.workers, scheme=body.scheme, host=body.host, diff --git a/backend/admin/settings.py b/backend/admin/settings.py index 60e7337..771423e 100644 --- a/backend/admin/settings.py +++ b/backend/admin/settings.py @@ -156,12 +156,12 @@ def save_settings(db: Session, payload: dict) -> SystemConfig: hb_video = _as_int(payload.get("heartbeat_video_seconds")) hb_doc = _as_int(payload.get("heartbeat_document_seconds")) hb_scorm = _as_int(payload.get("heartbeat_scorm_seconds")) - if hb_video is None or not 10 <= hb_video <= 300: - raise SettingsError("视频心跳间隔须为 10 到 300 的整数") - if hb_doc is None or not 30 <= hb_doc <= 600: - raise SettingsError("文档心跳间隔须为 30 到 600 的整数") - if hb_scorm is None or not 30 <= hb_scorm <= 600: - raise SettingsError("Scorm 心跳间隔须为 30 到 600 的整数") + if hb_video is None or not 0 <= hb_video <= 300: + raise SettingsError("视频心跳间隔须为 0 到 300 的整数") + if hb_doc is None or not 0 <= hb_doc <= 600: + raise SettingsError("文档心跳间隔须为 0 到 600 的整数") + if hb_scorm is None or not 0 <= hb_scorm <= 600: + raise SettingsError("Scorm 心跳间隔须为 0 到 600 的整数") source = str(payload.get("hours_source") or "api").strip().lower() if source not in ("api", "history"): raise SettingsError("学时达标依据须为 api 或 history") diff --git a/backend/admin/users.py b/backend/admin/users.py index cd2a4e2..b35e821 100644 --- a/backend/admin/users.py +++ b/backend/admin/users.py @@ -86,6 +86,7 @@ def list_users(db: Session) -> list[dict]: "study_start_hour": int(account.study_start_hour or 0), "study_start_minute": int(account.study_start_minute or 0), "study_start_second": int(account.study_start_second or 0), + "study_schedule_enabled": control["schedule_enabled"], "course_workers": workers_of(account), "study_paused": control["paused"], "study_ignore_window": control["ignore_window"], @@ -284,7 +285,7 @@ def set_study_action(db: Session, employee_ids: list[str], action: str) -> dict: if kind not in {"start", "stop"}: raise HTTPException(status_code=400, detail="请选择开始或停止") accounts = _accounts_by_ids(db, employee_ids) - from euniv.autostudy import request_stop, request_wake + from euniv.autostudy import request_stop, sync_work for account in accounts: if kind == "start": @@ -292,8 +293,10 @@ def set_study_action(db: Session, employee_ids: list[str], action: str) -> dict: else: stop_now(account) db.commit() + if kind == "start": - request_wake() + for account in accounts: + sync_work(account.employee_id) else: for account in accounts: request_stop(account.employee_id) @@ -308,6 +311,7 @@ def set_study_settings( hour: int | None = None, minute: int | None = None, second: int | None = None, + schedule_enabled: bool | None = None, workers: int | None = None, scheme: str | None = None, host: str = "", @@ -325,6 +329,8 @@ def set_study_settings( account.monthly_target = monthly_target if day is not None: apply_start(account, day, hour, minute, second) + if schedule_enabled is not None: + account.study_schedule_enabled = bool(schedule_enabled) if workers is not None: apply_workers(account, workers) if scheme is not None: @@ -333,6 +339,10 @@ def set_study_settings( db.rollback() raise HTTPException(status_code=400, detail=str(exc)) from exc db.commit() + from euniv.autostudy import sync_work + + for account in accounts: + sync_work(account.employee_id) return {"ok": True, "count": len(accounts)} diff --git a/backend/alembic/versions/0014_study_schedule.py b/backend/alembic/versions/0014_study_schedule.py new file mode 100644 index 0000000..fc67ae2 --- /dev/null +++ b/backend/alembic/versions/0014_study_schedule.py @@ -0,0 +1,49 @@ +"""定时自动学习开关,以及本月停止/学时月份标记。""" + +from datetime import datetime, timedelta, timezone + +from alembic import op +import sqlalchemy as sa + +revision = "0014_study_schedule" +down_revision = "0013_hours_source" +branch_labels = None +depends_on = None + +_CN = timezone(timedelta(hours=8)) + + +def upgrade() -> None: + with op.batch_alter_table("accounts") as batch: + batch.add_column(sa.Column("hours_month", sa.String(length=7), nullable=False, server_default="")) + batch.add_column(sa.Column("study_stop_month", sa.String(length=7), nullable=False, server_default="")) + batch.add_column( + sa.Column("study_schedule_enabled", sa.Boolean(), nullable=False, server_default=sa.true()) + ) + key = datetime.now(_CN).strftime("%Y-%m") + accounts = sa.table( + "accounts", + sa.column("hours_month", sa.String), + sa.column("month_hours", sa.String), + sa.column("study_paused", sa.Boolean), + sa.column("study_stop_month", sa.String), + ) + op.execute( + accounts.update() + .where(accounts.c.month_hours != "") + .where(accounts.c.hours_month == "") + .values(hours_month=key) + ) + op.execute( + accounts.update() + .where(accounts.c.study_paused.is_(True)) + .where(accounts.c.study_stop_month == "") + .values(study_stop_month=key) + ) + + +def downgrade() -> None: + with op.batch_alter_table("accounts") as batch: + batch.drop_column("study_schedule_enabled") + batch.drop_column("study_stop_month") + batch.drop_column("hours_month") diff --git a/backend/euniv/api.py b/backend/euniv/api.py index 16d4dbe..53cd449 100644 --- a/backend/euniv/api.py +++ b/backend/euniv/api.py @@ -2,11 +2,12 @@ from __future__ import annotations +import asyncio import os from contextlib import asynccontextmanager from pathlib import Path -from fastapi import Depends, FastAPI, HTTPException, Request, Response +from fastapi import Depends, FastAPI, HTTPException, Request, Response, WebSocket, WebSocketDisconnect from fastapi.staticfiles import StaticFiles from pydantic import BaseModel, Field from sqlalchemy.orm import Session @@ -54,6 +55,7 @@ class StudyStartBody(_BaseModel): hour: int minute: int second: int + enabled: bool | None = None class CourseWorkersBody(_BaseModel): @@ -69,6 +71,9 @@ async def lifespan(_app: FastAPI): init_db() ensure_admin_seed() load_admin_identity() + from euniv.study_push import attach_loop + + attach_loop(asyncio.get_running_loop()) stop_refresh = None study_worker = None stop_pool = None @@ -269,6 +274,9 @@ def put_monthly_target(body: MonthlyTargetBody, request: Request, db: Session = raise HTTPException(status_code=401, detail="未登录") account.monthly_target = body.monthly_target db.commit() + from euniv.autostudy import sync_work + + sync_work(employee_id) return {"monthly_target": account.monthly_target} @@ -293,7 +301,12 @@ def put_study_start(body: StudyStartBody, request: Request, db: Session = Depend apply(account, body.day, body.hour, body.minute, body.second) except StudyWindowError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc + if body.enabled is not None: + account.study_schedule_enabled = bool(body.enabled) db.commit() + from euniv.autostudy import sync_work + + sync_work(account.employee_id) return view_of(account) @@ -369,29 +382,26 @@ def autostudy_state(request: Request, db: Session = Depends(get_db)) -> dict: @app.get("/api/settings/study-control") def get_study_control(request: Request, db: Session = Depends(get_db)) -> dict: from euniv.autostudy import autostudy_status - from euniv.study_control import view_of + from euniv.study_control import assemble, settle employee_id = _signed_in(request, db) account = db.get(Account, employee_id) if account is None: raise HTTPException(status_code=401, detail="未登录") - payload = view_of(account) - live = (autostudy_status().get("users") or {}).get(employee_id) or {} - payload["state"] = str(live.get("state") or "") - payload["course"] = str(live.get("course") or "") - payload["message"] = str(live.get("message") or "") - workers = live.get("workers") or [] - payload["workers"] = workers if isinstance(workers, list) else [] - payload["active"] = bool(live) and payload["state"] not in {"已达标", "已停止", "会话失效", "会话过期"} - if payload["active"]: - payload["started"] = True - return payload + status = autostudy_status() + live = dict((status.get("users") or {}).get(employee_id) or {}) + if not live.get("message"): + live["message"] = str(status.get("message") or "") + if settle(account, live): + db.commit() + return assemble(account, live) @app.post("/api/settings/study-control") def post_study_control(body: StudyControlBody, request: Request, db: Session = Depends(get_db)) -> dict: - from euniv.autostudy import request_stop, request_wake - from euniv.study_control import start_now, stop_now + from euniv.autostudy import request_stop, sync_work + from euniv.study_control import hours_met, start_now, stop_now + from euniv.study_push import notify employee_id = _signed_in(request, db) account = db.get(Account, employee_id) @@ -399,18 +409,55 @@ def post_study_control(body: StudyControlBody, request: Request, db: Session = D raise HTTPException(status_code=401, detail="未登录") action = (body.action or "").strip().lower() if action == "start": - start_now(account) - db.commit() - request_wake() + if hours_met(account): + from euniv.autostudy import halt_work + + halt_work(employee_id) + else: + start_now(account) + db.commit() + sync_work(employee_id) elif action == "stop": stop_now(account) db.commit() request_stop(employee_id) else: raise HTTPException(status_code=400, detail="请选择开始或停止") + notify(employee_id, urgent=True) return get_study_control(request, db) +@app.websocket("/api/settings/study-control/ws") +async def study_control_ws(websocket: WebSocket): + from euniv.study_control import payload_for + from euniv.study_push import register, unregister + + await websocket.accept() + if admin_session_active(websocket.cookies): + await websocket.close(code=4403) + return + employee_id = read_employee_id(websocket.cookies) + if not employee_id: + await websocket.close(code=4401) + return + from euniv.db import SessionLocal + + with SessionLocal() as db: + if db.get(Account, employee_id) is None: + await websocket.close(code=4403) + return + register(employee_id, websocket) + try: + await websocket.send_json(await asyncio.to_thread(payload_for, employee_id)) + while True: + await websocket.receive_text() + await websocket.send_json(await asyncio.to_thread(payload_for, employee_id)) + except WebSocketDisconnect: + pass + finally: + unregister(employee_id, websocket) + + @app.get("/api/home/history") def home_history(request: Request, db: Session = Depends(get_db)) -> dict: try: diff --git a/backend/euniv/autostudy.py b/backend/euniv/autostudy.py index 3ccd70d..d110f83 100644 --- a/backend/euniv/autostudy.py +++ b/backend/euniv/autostudy.py @@ -7,7 +7,7 @@ - 每个用户一个 StudySession(httpx.AsyncClient),代理仅 HTTP/HTTPS/SOCKS4/SOCKS5 - 每个用户可配置同时学几门课(当前默认 1,结构已预留) - 心跳间隔用 asyncio.sleep,不占线程 -- 本月学时:看完一门视频后刷新,学习过程中每 5 分钟刷新;达到阈值即停止该账号 +- 本月学时:看完一门课后刷新,学习过程中每 1 分钟刷新;达到阈值即停止该账号 """ from __future__ import annotations @@ -16,6 +16,7 @@ import asyncio import contextlib import json import logging +import math import random import re import threading @@ -25,21 +26,36 @@ from datetime import datetime, timezone import httpx from sqlalchemy import select -from euniv.client import EUNIV, STUDY_API, USER_AGENT, EunivClient, SessionExpired, _load_cookies +from euniv.client import ( + EUNIV, + STUDY_API, + USER_AGENT, + EunivClient, + SessionExpired, + _load_cookies, + as_uuid, + compact_id, + play_page_params, + study_progress_fields, +) 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_control import eligible as study_eligible +from euniv.study_control import expire_pause, hours_met, stamp_hours +from euniv.study_window import as_cn, next_fire_at, next_month_start log = logging.getLogger(__name__) _MAX_CONCURRENT_USERS = 8 -_HOURS_REFRESH_SECONDS = 300.0 +_HOURS_REFRESH_SECONDS = 60.0 +_KEEP_LIVE = frozenset({"已达标", "已停止", "会话失效", "学习失败", "已学完"}) _lock = threading.Lock() _status: dict = {"running": False, "users": {}, "message": "", "updated_at": ""} _halt_lock = threading.Lock() _user_halts: dict[str, asyncio.Event] = {} +_wanted: set[str] = set() _worker = None @@ -71,10 +87,20 @@ def autostudy_status() -> dict: return raw +def _notify(employee_id: str = "", urgent: bool = False) -> None: + try: + from euniv.study_push import notify + + notify(employee_id or None, urgent=urgent) + except Exception: + return + + def _set_status(**kw: object) -> None: with _lock: _status.update(kw) _status["updated_at"] = datetime.now(timezone.utc).isoformat() + _notify() def _set_user_status(employee_id: str, **kw: object) -> None: @@ -83,11 +109,27 @@ def _set_user_status(employee_id: str, **kw: object) -> None: info = users.setdefault(employee_id, {}) info.update(kw) _status["updated_at"] = datetime.now(timezone.utc).isoformat() + _notify(employee_id) def _clear_user_status(employee_id: str) -> None: with _lock: _status.get("users", {}).pop(employee_id, None) + _notify(employee_id) + + +def _finish_user(employee_id: str, error: BaseException | None = None) -> None: + """周期结束时保留失败/达标,避免首页只剩「等待执行」。""" + if error is not None: + _set_user_status(employee_id, state="学习失败", message=str(error)[:200], workers={}, course="") + return + with _lock: + info = (_status.get("users") or {}).get(employee_id) or {} + state = str(info.get("state") or "") + if state in _KEEP_LIVE: + _set_user_status(employee_id, workers={}, course="") + return + _clear_user_status(employee_id) def _set_worker_status(employee_id: str, worker_id: int, **kw: object) -> None: @@ -104,22 +146,58 @@ def _set_worker_status(employee_id: str, worker_id: int, **kw: object) -> None: if isinstance(course, str) and course: info["course"] = course _status["updated_at"] = datetime.now(timezone.utc).isoformat() + _notify(employee_id) class WorkerView: def __init__(self, employee_id: str, worker_id: int) -> None: self.employee_id = employee_id self.worker_id = worker_id + self.sent = 0 + self.total = 0 + self._course = "" + self._origin = 0.0 def update(self, **kw: object) -> None: + course = kw.get("course") + if isinstance(course, str) and course != self._course: + self._course = course + self.sent = 0 + self.total = 0 + try: + self._origin = float(kw.get("progress") or 0) + except (TypeError, ValueError): + self._origin = 0.0 + kw.setdefault("sent", 0) + kw.setdefault("total", 0) _set_worker_status(self.employee_id, self.worker_id, **kw) + def after_beat(self, progress: float, **kw: object) -> None: + self.sent += 1 + planned = _count_total(self.sent, progress, self._origin) + if self.total <= 0: + self.total = planned + elif progress >= 100: + self.total = self.sent + elif planned > self.total: + self.total = planned + if self.sent > self.total: + self.total = self.sent + self.update(progress=progress, sent=self.sent, total=self.total, **kw) + def _touch(worker: WorkerView | None, **kw: object) -> None: if worker is not None: worker.update(**kw) +def _beat(worker: WorkerView | None, progress: float, **kw: object) -> None: + if worker is not None: + worker.after_beat(progress, **kw) + return + _touch(worker, progress=progress, **kw) + + def _progress_of(payload: dict) -> float: raw = payload.get("studyschedule") if raw is None: @@ -130,14 +208,59 @@ def _progress_of(payload: dict) -> float: return 0.0 -def request_stop(employee_id: str) -> None: +def _completed(payload: dict) -> bool: + if not isinstance(payload, dict): + return False + if _progress_of(payload) >= 100: + return True + return str(payload.get("status") or "").strip().lower() == "completed" + + +def _payload_time(wait: int, fallback: int) -> int: + if wait > 0: + return int(wait) + return max(1, int(fallback or 1)) + + +def _interval_plan(ctype: str, intervals: dict, auto_mode: bool, params: dict) -> tuple[int, int, int]: + """返回 (等待秒, 心跳 studyTime, pageSize)。等待 0 表示连续发送,studyTime 仍用播放页间隔。""" + video = ctype == "video" + wait = int(intervals.get(ctype, 30 if video else 120) or 0) + fallback = int((params or {}).get("submitProTimes" if video else "validtimeSpan") or (30 if video else 120)) + if auto_mode: + wait = fallback + page_size = max(1, int((params or {}).get("pageSize") or 1)) + return wait, _payload_time(wait, fallback), page_size + + +def _current_intervals() -> tuple[dict, bool]: + from admin.settings import heartbeat_intervals + + cfg = heartbeat_intervals() + return { + "video": int(cfg["video"]), + "document": int(cfg["document"]), + "scorm": int(cfg["scorm"]), + }, cfg["mode"] == "auto" + + +def halt_work(employee_id: str) -> None: key = (employee_id or "").strip() if not key: return + drop_work(key) with _halt_lock: event = _user_halts.get(key) if event is not None: event.set() + _notify(key, urgent=True) + + +def request_stop(employee_id: str) -> None: + key = (employee_id or "").strip() + if not key: + return + halt_work(key) _set_user_status(key, state="已停止", course="") @@ -147,6 +270,121 @@ def request_wake() -> None: worker.wake() +def want_work(employee_id: str) -> None: + key = (employee_id or "").strip() + if not key: + return + with _halt_lock: + _wanted.add(key) + _notify(key, urgent=True) + + +def drop_work(employee_id: str) -> None: + key = (employee_id or "").strip() + if not key: + return + with _halt_lock: + _wanted.discard(key) + _notify(key, urgent=True) + + +def is_wanted(employee_id: str) -> bool: + key = (employee_id or "").strip() + with _halt_lock: + return key in _wanted + + +def work_running(employee_id: str) -> bool: + return is_studying(employee_id) or is_wanted(employee_id) + + +def sync_work(employee_id: str) -> None: + """保存配置或点开始后:达标则停,到期且未达标则拉起该账号的 work。""" + from euniv.db import SessionLocal + from euniv.models import Account + + key = (employee_id or "").strip() + if not key: + return + with SessionLocal() as db: + account = db.get(Account, key) + if account is None: + return + if expire_pause(account): + db.commit() + met = hours_met(account) + due = study_eligible(account) + if met: + halt_work(key) + return + if due: + want_work(key) + request_wake() + return + halt_work(key) + + +_KIND_RANK = {"视频": 0, "文档": 1, "课程包": 2, "课程": 3} + + +def snapshot_courses(rows) -> list[tuple[str, str, str]]: + """work 启动时的课程清单快照。排序固定为 视频-文档-课程包-课程。""" + items: list[tuple[str, str, str]] = [] + for row in rows: + if isinstance(row, (tuple, list)): + path = str(row[0] if len(row) > 0 else "") + title = str(row[1] if len(row) > 1 else "") + kind = str(row[2] if len(row) > 2 else "") + else: + path = str(getattr(row, "path", "") or "") + title = str(getattr(row, "title", "") or "") + kind = str(getattr(row, "kind", "") or "") + items.append((path, title, kind)) + items.sort(key=lambda item: (_KIND_RANK.get(item[2], 9), item[1], item[0])) + return items + + +def _job_from_account(row) -> tuple | None: + """从账号列表行提取一次凭据。之后 work 只用这份拷贝,不再读账号表。""" + from euniv.crypto import decrypt_secret + + employee_id = str(getattr(row, "employee_id", "") or "") + target_raw = getattr(row, "monthly_target", None) + password_cipher = str(getattr(row, "password_cipher", "") or "") + credential_cipher = str(getattr(row, "credential_cipher", "") or "") + workers = course_workers_of(row) + pool = uses_pool(row) + try: + proxy = bind_url(row) + except Exception as exc: + log.warning("用户 %s 凭据无法读取: %s", employee_id, exc) + if employee_id: + _set_user_status(employee_id, state="学习失败", message="凭据无法读取") + return None + target = int(target_raw) if target_raw is not None else 600 + if target <= 0: + return None + try: + password = decrypt_secret(password_cipher) + credential = json.loads(decrypt_secret(credential_cipher)) + except Exception as exc: + log.warning("用户 %s 凭据无法读取: %s", employee_id, exc) + if employee_id: + _set_user_status(employee_id, state="学习失败", message="凭据无法读取") + return None + if not isinstance(credential, dict): + return None + return ( + employee_id, + target, + password, + credential, + proxy, + workers, + pool, + ) + + def is_studying(employee_id: str) -> bool: key = (employee_id or "").strip() with _halt_lock: @@ -177,19 +415,53 @@ def _course_type(kind: str, path: str) -> str: def _play_path(kind: str, path: str, kid: str) -> str: + compact = compact_id(kid) ctype = _course_type(kind, path) if ctype == "video": - return f"/kng/view/video/{kid}.html" + return f"/kng/view/video/{compact}.html" if ctype == "document": - return f"/kng/view/document/{kid}.html" + return f"/kng/view/document/{compact}.html" if ctype == "scorm": - return f"/kng/view/scorm/{kid}.html" + return f"/kng/view/scorm/{compact}.html" + if ctype == "package": + return f"/kng/view/package/{compact}.html" return path +def _package_chapter_path(pkg_id: str, ch_kid: str, ch_type: str) -> str: + return f"/kng/course/package/{ch_type}/{compact_id(pkg_id)}_{compact_id(ch_kid)}.html" + + +async def _open_play(session: "StudySession", path: str) -> dict: + if not path: + return {} + try: + return await session.course_page_params(path) + except Exception: + log.debug("打开播放页失败 %s", path, exc_info=True) + return {} + + +def _count_total(sent: int, progress: float, origin: float = 0.0) -> int: + """按开课进度估算剩余心跳数。总数在 WorkerView 里冻结,避免每拍都变。""" + if sent <= 0: + return 0 + if progress >= 100: + return sent + gained = float(progress) - float(origin) + if gained <= 0: + return 0 + span = max(0.0, 100.0 - float(origin)) + if span <= 0: + return sent + return max(sent, int(math.ceil(sent * span / gained))) + + def _jitter(seconds: int) -> float: - delta = random.uniform(-3.0, 3.0) - return max(5.0, seconds + delta) + if seconds <= 0: + return 0.0 + spread = min(3.0, max(0.0, float(seconds) * 0.2)) + return max(0.0, float(seconds) + random.uniform(-spread, spread)) def _parse_minutes(value: str) -> int: @@ -215,7 +487,7 @@ async def wait_stop(timeout: float, *events: asyncio.Event) -> bool: class HoursWatcher: - """刷新本月学时。看完视频或每 5 分钟查一次,达标后停止该账号。""" + """刷新本月学时。看完一门课或每 1 分钟查一次,达标后停止该账号。""" def __init__( self, @@ -248,10 +520,11 @@ class HoursWatcher: current = _parse_minutes(text) if text: await asyncio.to_thread(_update_month_hours, self.employee_id, text) - if current >= self.target: + if self.target > 0 and current >= self.target: self.reached = True self.user_stop.set() _set_user_status(self.employee_id, state="已达标") + await asyncio.to_thread(_release_ignore_window, self.employee_id) return True except Exception: log.warning("用户 %s 刷新本月学时失败", self.employee_id, exc_info=True) @@ -285,10 +558,12 @@ class StudySession: self._client: httpx.AsyncClient | None = None async def __aenter__(self) -> "StudySession": - self._client = httpx.AsyncClient( + from euniv.proxy import async_httpx_client + + self._client = async_httpx_client( + self._proxy, timeout=30, follow_redirects=True, - proxy=self._proxy, headers={"User-Agent": USER_AGENT}, ) _load_cookies(self._client, self._initial_cookies) @@ -310,10 +585,12 @@ class StudySession: parsed = parse_proxy(nxt) if parsed == old: return False - client = httpx.AsyncClient( + from euniv.proxy import async_httpx_client + + client = async_httpx_client( + parsed, timeout=30, follow_redirects=True, - proxy=parsed, headers={"User-Agent": USER_AGENT}, ) _load_cookies(client, self._initial_cookies) @@ -369,13 +646,14 @@ class StudySession: async def update_progress(self, kid: str, pkg_id: str = "") -> dict: resp = await self._api("POST", f"{STUDY_API}/v1/study/updateprogress", - json={"knowledgeId": kid, "packageId": pkg_id, + json={"knowledgeId": as_uuid(kid), + "packageId": as_uuid(pkg_id) if pkg_id else "", "masterId": "", "masterType": ""}) return resp.json() async def sync_package(self, kid: str) -> dict: resp = await self._api("GET", f"{STUDY_API}/v1/uk/syncpackage", - params={"knowledgeId": kid, "sourceType": "SingleStudy", "masterId": ""}) + params={"knowledgeId": as_uuid(kid), "sourceType": "SingleStudy", "masterId": ""}) return resp.json() async def get_encrypt_request(self, body_json: str) -> str: @@ -396,15 +674,11 @@ class StudySession: async def submit_video_heartbeat(self, kid: str, pkg_id: str, study_time: int, view_schedule: int) -> dict: - param = { - "knowledgeId": kid, "masterId": "", "masterType": "", - "packageId": pkg_id, "pageSize": 1, "studySize": 1, - "studyTime": study_time, "type": 0, "offLine": False, - "end": False, "care": True, "deviceId": "", - "studyChapterIds": "", "viewSchedule": view_schedule, - } - encrypt_body = json.dumps(param, separators=(",", ":")) - encryption = await self.get_encrypt_request(encrypt_body) + param = study_progress_fields( + kid, pkg_id, page_size=1, study_time=study_time, + kind=0, view_schedule=view_schedule, + ) + encryption = await self.get_encrypt_request(json.dumps(param, separators=(",", ":"))) param["encryption"] = encryption param["multiple"] = 1 param["realHour"] = study_time @@ -416,15 +690,11 @@ class StudySession: async def submit_document_heartbeat(self, kid: str, pkg_id: str, page_size: int, study_time: int, view_schedule: int) -> None: - param = { - "knowledgeId": kid, "masterId": "", "masterType": "", - "packageId": pkg_id, "pageSize": page_size, "studySize": page_size, - "studyTime": study_time, "type": 1, "offLine": False, - "end": False, "care": True, "deviceId": "", - "studyChapterIds": "", "viewSchedule": view_schedule, - } - encrypt_body = json.dumps(param, separators=(",", ":")) - encryption = await self.get_encrypt_request(encrypt_body) + param = study_progress_fields( + kid, pkg_id, page_size=page_size, study_time=study_time, + kind=1, view_schedule=view_schedule, + ) + encryption = await self.get_encrypt_request(json.dumps(param, separators=(",", ":"))) param["multiple"] = 1 param["realHour"] = study_time await self._api("POST", f"{STUDY_API}/v1/study/submit?encryption={encryption}", @@ -433,28 +703,25 @@ class StudySession: async def submit_scorm_heartbeat(self, kid: str, pkg_id: str, study_time: int, sco_id: str = "", end: bool = False) -> None: - param = { - "knowledgeId": kid, "masterId": "", "masterType": "", - "packageId": pkg_id, - "pageSize": -1 if end else 1, "studySize": -1 if end else 1, - "studyTime": study_time, "type": 2, "offLine": False, - "end": end, "care": True, "deviceId": "", - "studyChapterIds": sco_id, "viewSchedule": 0, - } - encrypt_body = json.dumps(param, separators=(",", ":")) - encryption = await self.get_encrypt_request(encrypt_body) - param["multiple"] = 1 - param["realHour"] = study_time + encrypt_param = study_progress_fields( + kid, pkg_id, page_size=-1 if end else 1, study_time=study_time, + kind=2, view_schedule=0, end=end, chapter_id=sco_id, for_encrypt=True, + ) + encryption = await self.get_encrypt_request(json.dumps(encrypt_param, separators=(",", ":"))) + param = study_progress_fields( + kid, pkg_id, page_size=-1 if end else 1, study_time=study_time, + kind=2, view_schedule=0, end=end, chapter_id=sco_id, + ) await self._api("POST", f"{STUDY_API}/v1/study/submit?encryption={encryption}", content=json.dumps(param, separators=(",", ":"))) async def scorm_count(self, kid: str) -> int: resp = await self._api("GET", f"{STUDY_API}/v1/kng/scorm/count/", - params={"knowledgeId": kid}) + params={"knowledgeId": as_uuid(kid)}) return int(resp.json().get("scocnt") or 1) async def scorm_get(self, user_id: str, sco_id: str) -> dict: - resp = await self._api("GET", f"https://api-mall.yxt.com/v1/scormstudy/{user_id}/{sco_id}") + resp = await self._api("GET", f"https://api-mall.yxt.com/v1/scormstudy/{user_id}/{as_uuid(sco_id)}") text = resp.text.strip() return resp.json() if text else {} @@ -463,8 +730,9 @@ class StudySession: pkg_id: str, data: dict) -> None: await self._api("POST", "https://api-mall.yxt.com/v1/scormstudy", json={ "sessionId": session_id, "orgId": org_id, "userId": user_id, - "scormId": scorm_id, "scormIdOri": scorm_id_ori, - "masterId": "", "masterType": "", "packageId": pkg_id, + "scormId": as_uuid(scorm_id), "scormIdOri": as_uuid(scorm_id_ori), + "masterId": "", "masterType": "", + "packageId": as_uuid(pkg_id) if pkg_id else "", "scocnt": sco_cnt, "data": data, }) @@ -478,22 +746,12 @@ class StudySession: html = resp.text from euniv.encrypt import note_play_html note_play_html(html, EUNIV) - - def _var(name: str, default: str = "") -> str: - m = re.search(rf'(?:var\s+)?{name}\s*=\s*["\']?([^"\';\r\n]+)', html) - return m.group(1).strip() if m else default - - return { - "submitProTimes": int(_var("submitProTimes", "30") or 30), - "validtimeSpan": int(_var("validtimeSpan", "120") or 120), - "pageSize": int(_var("pageSize", "1") or 1), - "userID": _var("userID"), - "orgID": _var("orgID"), - } + return play_page_params(html) async def scorm_extract_answers(self, kid: str) -> list[dict]: assert self._client is not None - index_url = f"https://cdn-cos-file.yunxuetang.cn/zt/scorm/{kid}/h5/js/index-scorm.js" + compact = compact_id(kid) + index_url = f"https://cdn-cos-file.yunxuetang.cn/zt/scorm/{compact}/h5/js/index-scorm.js" resp = await self._http("GET", index_url, headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"}) urls: list[str] = [] for m in re.finditer(r'["\']([^"\']+\.oss\.js)["\']', resp.text): @@ -505,7 +763,7 @@ class StudySession: elif raw.startswith("/"): urls.append(f"https://cdn-cos-file.yunxuetang.cn{raw}") else: - urls.append(f"https://cdn-cos-file.yunxuetang.cn/zt/scorm/{kid}/h5/js/{raw}") + urls.append(f"https://cdn-cos-file.yunxuetang.cn/zt/scorm/{compact}/h5/js/{raw}") answers: list[dict] = [] for url in urls: try: @@ -609,7 +867,11 @@ async def _heartbeat_wait( async def _study_video(session: StudySession, kid: str, pkg_id: str, interval: int, stop: asyncio.Event, hours: HoursWatcher, - worker: WorkerView | None = None) -> None: + worker: WorkerView | None = None, + study_time: int | None = None) -> None: + step = int(study_time if study_time is not None else (interval if interval > 0 else 30)) + if step <= 0: + step = 30 view = 0 started = False while not _halted(stop, hours): @@ -620,33 +882,37 @@ async def _study_video(session: StudySession, kid: str, pkg_id: str, raise schedule = _progress_of(progress) _touch(worker, progress=schedule, ok=True) - if schedule >= 100: + if _completed(progress): if started: await hours.refresh() return started = True - view = int(progress.get("viewSchedule", view)) - view += interval + view = int(progress.get("viewSchedule") or view) + view += step try: - result = await session.submit_video_heartbeat(kid, pkg_id, interval, view) + result = await session.submit_video_heartbeat(kid, pkg_id, step, view) except Exception: _touch(worker, ok=False) raise new_schedule = result.get("studySchedule") if new_schedule is not None: schedule = _progress_of({"studySchedule": new_schedule}) - _touch(worker, progress=schedule, ok=True) - if schedule >= 100: - await hours.refresh() - return + _beat(worker, schedule, ok=True) + if schedule >= 100: + await hours.refresh() + return if await _heartbeat_wait(worker, interval, stop, hours, schedule): return async def _study_document(session: StudySession, kid: str, pkg_id: str, page_size: int, interval: int, stop: asyncio.Event, - hours: HoursWatcher, worker: WorkerView | None = None) -> None: - view = 1 + hours: HoursWatcher, worker: WorkerView | None = None, + study_time: int | None = None) -> None: + step = int(study_time if study_time is not None else (interval if interval > 0 else 120)) + if step <= 0: + step = 120 + started = False while not _halted(stop, hours): try: progress = await session.update_progress(kid, pkg_id) @@ -655,21 +921,45 @@ async def _study_document(session: StudySession, kid: str, pkg_id: str, raise schedule = _progress_of(progress) _touch(worker, progress=schedule, ok=True) - if schedule >= 100: + if _completed(progress): + if started: + await hours.refresh() return + started = True + view = int(progress.get("viewSchedule") or 1) try: - await session.submit_document_heartbeat(kid, pkg_id, page_size, interval, view) + await session.submit_document_heartbeat(kid, pkg_id, page_size, step, view) + progress = await session.update_progress(kid, pkg_id) except Exception: _touch(worker, ok=False) raise + schedule = _progress_of(progress) + _beat(worker, schedule, ok=True) + if _completed(progress): + await hours.refresh() + return if await _heartbeat_wait(worker, interval, stop, hours, schedule): return async def _study_scorm(session: StudySession, kid: str, pkg_id: str, interval: int, stop: asyncio.Event, hours: HoursWatcher, - user_id: str, org_id: str, worker: WorkerView | None = None) -> None: + user_id: str, org_id: str, worker: WorkerView | None = None, + study_time: int | None = None) -> None: import uuid as _uuid + step = int(study_time if study_time is not None else (interval if interval > 0 else 120)) + if step <= 0: + step = 120 + try: + progress = await session.update_progress(kid, pkg_id) + except Exception: + _touch(worker, ok=False) + raise + schedule = _progress_of(progress) + _touch(worker, progress=schedule, ok=True) + if _completed(progress): + return + sco_cnt = await session.scorm_count(kid) session_id = str(_uuid.uuid4()) sco_id = kid @@ -703,16 +993,18 @@ async def _study_scorm(session: StudySession, kid: str, pkg_id: str, scorm_id=sco_id, scorm_id_ori=kid, sco_cnt=sco_cnt, pkg_id=pkg_id, data=scorm_data, ) - await session.submit_scorm_heartbeat(kid, pkg_id, interval, sco_id=sco_id, end=True) + await session.submit_scorm_heartbeat(kid, pkg_id, step, sco_id=sco_id, end=True) progress = await session.update_progress(kid, pkg_id) except Exception: _touch(worker, ok=False) raise schedule = _progress_of(progress) - _touch(worker, progress=schedule, ok=True) - if schedule >= 100: + _beat(worker, schedule, ok=True) + if _completed(progress): + await hours.refresh() return - if await _heartbeat_wait(worker, min(interval, 5), stop, hours, schedule): + page_wait = interval if interval <= 0 else min(interval, 5) + if await _heartbeat_wait(worker, page_wait, stop, hours, schedule): return while not _halted(stop, hours): @@ -723,13 +1015,20 @@ async def _study_scorm(session: StudySession, kid: str, pkg_id: str, raise schedule = _progress_of(progress) _touch(worker, progress=schedule, ok=True) - if schedule >= 100: + if _completed(progress): + await hours.refresh() return try: - await session.submit_scorm_heartbeat(kid, pkg_id, interval, sco_id=sco_id, end=False) + await session.submit_scorm_heartbeat(kid, pkg_id, step, sco_id=sco_id, end=False) + progress = await session.update_progress(kid, pkg_id) except Exception: _touch(worker, ok=False) raise + schedule = _progress_of(progress) + _beat(worker, schedule, ok=True) + if _completed(progress): + await hours.refresh() + return if await _heartbeat_wait(worker, interval, stop, hours, schedule): return @@ -738,37 +1037,33 @@ async def _study_package(session: StudySession, kid: str, intervals: dict, auto_mode: bool, stop: asyncio.Event, hours: HoursWatcher, user_id: str, org_id: str, worker: WorkerView | None = None) -> None: pkg = await session.sync_package(kid) + if _completed(pkg): + _touch(worker, progress=_progress_of(pkg), ok=True) + return chapters = pkg.get("userKnowledgeList") or [] for ch in chapters: if _halted(stop, hours): return - if float(ch.get("studySchedule", 0)) >= 100: + if _completed(ch): continue - ch_kid = str(ch.get("knowledgeId") or "").replace("-", "") + ch_kid = str(ch.get("knowledgeId") or "").strip() ch_title = ch.get("title") or ch_kid - if not ch_kid: + if not compact_id(ch_kid): continue _set_user_status(session._employee_id, course=ch_title) _touch(worker, course=ch_title, progress=_progress_of(ch), ok=True) is_video = "Video" in str(ch.get("knowledgeType") or "") ch_type = "video" if is_video else "document" - ch_interval = intervals.get(ch_type, 30 if is_video else 120) - page_size = 1 - - if auto_mode: - try: - params = await session.course_page_params( - f"/kng/course/package/{ch_type}/{kid}_{ch_kid}.html") - ch_interval = params.get("submitProTimes" if is_video else "validtimeSpan", ch_interval) - page_size = params.get("pageSize", 1) - except Exception: - pass + params = await _open_play(session, _package_chapter_path(kid, ch_kid, ch_type)) + wait, study_time, page_size = _interval_plan(ch_type, intervals, auto_mode, params) if is_video: - await _study_video(session, ch_kid, kid, ch_interval, stop, hours, worker) + await _study_video(session, ch_kid, kid, wait, stop, hours, worker, study_time=study_time) else: - await _study_document(session, ch_kid, kid, page_size, ch_interval, stop, hours, worker) + await _study_document( + session, ch_kid, kid, page_size, wait, stop, hours, worker, study_time=study_time, + ) # ── 同步准备:用 EunivClient 建立会话,导出 cookies ── @@ -798,6 +1093,7 @@ def _prepare_session(employee_id: str, password: str, return token, user_id, org_id, cookies, current except Exception as exc: last_exc = exc + log.warning("用户 %s 准备会话失败: %s", employee_id, exc) if use_pool and current and is_proxy_failure(exc): mark_failed(employee_id, current, str(exc)[:200]) current = acquire(employee_id) @@ -810,10 +1106,10 @@ def _prepare_session(employee_id: str, password: str, return "", "", "", [], current -# ── Worker 主循环 ── +# ── 启动器 + 按账号 Work ── class AutoStudyWorker: - """后台 asyncio 事件循环,管理所有用户的自动学习。""" + """定时启动器:到点检查各账号,已有 work 则跳过,未达标才拉起。""" def __init__(self) -> None: self._stop_flag = threading.Event() @@ -821,6 +1117,8 @@ class AutoStudyWorker: self._loop: asyncio.AbstractEventLoop | None = None self._async_stop: asyncio.Event | None = None self._kick: asyncio.Event | None = None + self._tasks: dict[str, asyncio.Task] = {} + self._sem: asyncio.Semaphore | None = None def start(self) -> None: self._thread = threading.Thread(target=self._run_thread, name="euniv-autostudy", daemon=True) @@ -848,35 +1146,40 @@ class AutoStudyWorker: async def _main_loop(self) -> None: assert self._async_stop is not None assert self._kick is not None - await wait_stop(15, self._async_stop, self._kick) + self._sem = asyncio.Semaphore(_MAX_CONCURRENT_USERS) while not self._async_stop.is_set(): self._kick.clear() try: - await self._run_cycle() + delay = self._tick() except Exception as exc: - log.exception("自动学习周期异常: %s", exc) + log.exception("自动学习调度异常: %s", exc) _set_status(message=f"异常: {exc}") + delay = 30.0 if self._async_stop.is_set(): return if self._kick.is_set(): continue - await wait_stop(random.uniform(300, 600), self._async_stop, self._kick) + await wait_stop(delay, self._async_stop, self._kick) - async def _run_cycle(self) -> None: - assert self._async_stop is not None - from admin.settings import heartbeat_intervals, hours_source_of - from euniv.crypto import decrypt_secret + def _alive(self) -> int: + dead = [eid for eid, task in self._tasks.items() if task.done()] + for eid in dead: + self._tasks.pop(eid, None) + return len(self._tasks) + + def _busy(self, employee_id: str) -> bool: + task = self._tasks.get(employee_id) + if task is not None and not task.done(): + return True + return is_studying(employee_id) + + def _tick(self) -> float: from euniv.db import SessionLocal - intervals_cfg = heartbeat_intervals() - hours_source = hours_source_of() - auto_mode = intervals_cfg["mode"] == "auto" - intervals = { - "video": intervals_cfg["video"], - "document": intervals_cfg["document"], - "scorm": intervals_cfg["scorm"], - } - + now = as_cn() + soonest = next_month_start(now) + jobs: list[tuple] = [] + course_list: list[tuple[str, str, str]] = [] with SessionLocal() as db: users = db.scalars( select(Account) @@ -884,70 +1187,83 @@ class AutoStudyWorker: .where(Account.credential_valid == True) .order_by(Account.employee_id) ).all() - courses = db.scalars(select(Course).order_by(Course.title)).all() - course_list = [(c.path, c.title, c.kind) for c in courses] - eligible = [] - waiting = 0 - paused = 0 + expired = False for row in users: - if not study_eligible(row): - if getattr(row, "study_paused", False): - paused += 1 - else: - waiting += 1 + if expire_pause(row): + expired = True + eid = row.employee_id + fire = next_fire_at(row, now) + if fire is not None and fire < soonest: + soonest = fire + if hours_met(row): + if is_studying(eid) or is_wanted(eid): + halt_work(eid) continue - target = int(row.monthly_target) if row.monthly_target is not None else 600 - current = _parse_minutes(row.month_hours) - below = hours_source == "history" or (target > 0 and current < target) - if below: - try: - password = decrypt_secret(row.password_cipher) - credential = json.loads(decrypt_secret(row.credential_cipher)) - proxy = bind_url(row) - except Exception: - continue - eligible.append( - ( - row.employee_id, - target, - password, - credential, - proxy, - course_workers_of(row), - uses_pool(row), - ) - ) + if not (study_eligible(row) or is_wanted(eid)): + continue + if self._busy(eid): + continue + job = _job_from_account(row) + if job is None: + drop_work(eid) + continue + jobs.append(job) + if jobs: + course_list = snapshot_courses(db.scalars(select(Course)).all()) + if expired: + db.commit() + launched = 0 + for job in jobs: + if self._launch(job, course_list): + launched += 1 + alive = self._alive() + wait = max(1.0, (soonest - as_cn()).total_seconds()) + if alive: + _set_status(running=True, message=f"运行中 {alive} 个账号") + elif launched: + _set_status(running=True, message=f"正在启动 {launched} 个账号") + else: + label = soonest.strftime("%m-%d %H:%M:%S") + _set_status(running=False, message=f"下一次定时 {label}") + return wait + def _launch(self, job: tuple, course_list: list[tuple[str, str, str]]) -> bool: + eid = job[0] + if self._busy(eid): + return False if not course_list: - _set_status(running=False, message="没有可用的用户或课程") - return + _set_user_status(eid, state="学习失败", message="没有可用的课程") + drop_work(eid) + return False + want_work(eid) + assert self._loop is not None + self._tasks[eid] = self._loop.create_task(self._run_account(job, list(course_list))) + log.info("启动账号 %s 的学习任务", eid) + return True - if not eligible: - if waiting: - _set_status(running=False, message="未到开始时间或已达标") - elif paused: - _set_status(running=False, message="任务已停止") - else: - _set_status(running=False, message="所有用户已达标或无有效凭据") - return + async def _run_account(self, job: tuple, course_list: list[tuple[str, str, str]]) -> None: + emp_id, target, pw, cred, proxy, workers, use_pool = job + try: + from admin.settings import hours_source_of - _set_status(running=True, message=f"本轮 {len(eligible)} 个用户") - - sem = asyncio.Semaphore(_MAX_CONCURRENT_USERS) - tasks = [ - self._study_user( + hours_source = hours_source_of() + intervals, auto_mode = _current_intervals() + if not course_list: + _set_user_status(emp_id, state="学习失败", message="没有可用的课程") + return + assert self._sem is not None + await self._study_user( emp_id, target, pw, cred, proxy, workers, use_pool, - course_list, intervals, auto_mode, hours_source, sem, + course_list, intervals, auto_mode, hours_source, self._sem, ) - for emp_id, target, pw, cred, proxy, workers, use_pool in eligible - ] - results = await asyncio.gather(*tasks, return_exceptions=True) - for emp_id_tuple, result in zip(eligible, results): - if isinstance(result, Exception): - log.warning("用户 %s 自动学习失败: %s", emp_id_tuple[0], result) - _clear_user_status(emp_id_tuple[0]) - - _set_status(running=False, message="本轮完成") + except Exception as exc: + log.warning("用户 %s 自动学习失败: %s", emp_id, exc) + _finish_user(emp_id, exc) + else: + _finish_user(emp_id) + finally: + drop_work(emp_id) + self._tasks.pop(emp_id, None) async def _study_user(self, employee_id: str, target: int, password: str, credential: dict, proxy: str | None, @@ -970,7 +1286,7 @@ class AutoStudyWorker: token, user_id, org_id, cookies, proxy = await loop.run_in_executor( None, _prepare_session, employee_id, password, credential, proxy, use_pool) if not token: - _set_user_status(employee_id, state="会话失效") + _set_user_status(employee_id, state="会话失效", message="无法连接学习平台") return async with StudySession( @@ -986,6 +1302,11 @@ class AutoStudyWorker: await self._study_courses( session, employee_id, course_list, intervals, auto_mode, hours, user_id, org_id, workers) + if hours.reached: + return + if user_stop.is_set() or self._async_stop.is_set(): + return + _set_user_status(employee_id, state="已学完", course="", workers={}) finally: ticker.cancel() with contextlib.suppress(asyncio.CancelledError): @@ -1037,41 +1358,39 @@ class AutoStudyWorker: kid = _knowledge_id_from_path(path) if not kid: return + intervals, auto_mode = _current_intervals() _set_user_status(employee_id, course=title) - _touch(worker, course=title, progress=0, ok=True) try: + params = await _open_play(session, _play_path(kind, path, kid)) if ctype == "package": + _touch(worker, course=title, progress=0, ok=True) await _study_package(session, kid, intervals, auto_mode, self._async_stop, hours, user_id, org_id, worker) - else: - progress = await session.update_progress(kid, "") - schedule = _progress_of(progress) - _touch(worker, progress=schedule, ok=True) - if schedule >= 100: - return + return - interval = intervals.get(ctype, 120) - page_size = 1 - if auto_mode: - try: - params = await session.course_page_params(_play_path(kind, path, kid)) - if ctype == "video": - interval = params.get("submitProTimes", interval) - else: - interval = params.get("validtimeSpan", interval) - page_size = params.get("pageSize", 1) - except Exception: - pass + progress = await session.update_progress(kid, "") + schedule = _progress_of(progress) + _touch(worker, course=title, progress=schedule, ok=True) + if _completed(progress): + return - if ctype == "video": - await _study_video(session, kid, "", interval, self._async_stop, hours, worker) - elif ctype == "document": - await _study_document(session, kid, "", page_size, interval, self._async_stop, hours, worker) - elif ctype == "scorm": - await _study_scorm(session, kid, "", interval, self._async_stop, hours, - user_id, org_id, worker) + wait, study_time, page_size = _interval_plan(ctype, intervals, auto_mode, params) + if ctype == "video": + await _study_video( + session, kid, "", wait, self._async_stop, hours, worker, study_time=study_time, + ) + elif ctype == "document": + await _study_document( + session, kid, "", page_size, wait, self._async_stop, hours, worker, + study_time=study_time, + ) + elif ctype == "scorm": + await _study_scorm( + session, kid, "", wait, self._async_stop, hours, + user_id, org_id, worker, study_time=study_time, + ) except SessionExpired: hours.user_stop.set() _touch(worker, ok=False) @@ -1089,8 +1408,19 @@ def _update_month_hours(employee_id: str, hours: str) -> None: with SessionLocal() as db: account = db.get(Account, employee_id) if account: - account.month_hours = hours + stamp_hours(account, hours) db.commit() + _set_user_status(employee_id, month_hours=hours) + + +def _release_ignore_window(employee_id: str) -> None: + from euniv.db import SessionLocal + with SessionLocal() as db: + account = db.get(Account, employee_id) + if account is None or not account.study_ignore_window: + return + account.study_ignore_window = False + db.commit() # ── 启动入口 ── diff --git a/backend/euniv/client.py b/backend/euniv/client.py index 290b964..334a621 100644 --- a/backend/euniv/client.py +++ b/backend/euniv/client.py @@ -57,6 +57,96 @@ def make_kid(prefix: str = "t") -> str: return prefix + "".join(random.choice("1234567890") for _ in range(4)) +def compact_id(value: str) -> str: + return (value or "").replace("-", "").lower() + + +def as_uuid(value: str) -> str: + raw = compact_id(value) + if len(raw) != 32 or any(char not in "0123456789abcdef" for char in raw): + return (value or "").strip() + return f"{raw[0:8]}-{raw[8:12]}-{raw[12:16]}-{raw[16:20]}-{raw[20:32]}" + + +def play_page_vars(html: str) -> dict[str, str]: + text = html or "" + + def read(name: str, default: str = "") -> str: + quoted = re.search(rf'(?:var\s+)?{re.escape(name)}\s*=\s*["\']([^"\']*)["\']', text) + if quoted: + return quoted.group(1).strip() + numeric = re.search(rf'(?:var\s+)?{re.escape(name)}\s*=\s*(-?\d+)', text) + if numeric: + return numeric.group(1).strip() + return default + + return { + "knowledgeType": read("knowledgeType"), + "submitIsOpen": read("submitIsOpen", "0"), + "submitProTimes": read("submitProTimes", "30"), + "validtimeSpan": read("validtimeSpan", "120"), + "standardStudyHours": read("standardStudyHours", "0"), + "pageSize": read("pageSize", "1"), + "fileType": read("fileType"), + "kngId": read("kngId"), + "packageID": read("packageID"), + "orgID": read("orgID"), + "userID": read("userID"), + } + + +def play_page_params(html: str) -> dict: + raw = play_page_vars(html) + + def as_int(name: str, default: int) -> int: + try: + return int(raw.get(name) or default) + except (TypeError, ValueError): + return default + + return { + **raw, + "submitProTimes": as_int("submitProTimes", 30), + "validtimeSpan": as_int("validtimeSpan", 120), + "standardStudyHours": as_int("standardStudyHours", 0), + "pageSize": max(1, as_int("pageSize", 1)), + } + + +def study_progress_fields( + knowledge_id: str, + package_id: str = "", + *, + page_size: int = 1, + study_time: int = 30, + kind: int = 0, + view_schedule: int | float = 0, + end: bool = False, + chapter_id: str = "", + for_encrypt: bool = False, +) -> dict: + """抓包里 knowledgeId/packageId 带连字符;Scorm 加密体的 studyChapterIds 末尾有分号。""" + chapter = as_uuid(chapter_id) if chapter_id else "" + if for_encrypt and kind == 2 and chapter: + chapter = chapter + ";" + return { + "knowledgeId": as_uuid(knowledge_id), + "masterId": "", + "masterType": "", + "packageId": as_uuid(package_id) if package_id else "", + "pageSize": int(page_size), + "studySize": int(page_size), + "studyTime": int(study_time), + "type": int(kind), + "offLine": False, + "end": bool(end), + "care": True, + "deviceId": "", + "studyChapterIds": chapter, + "viewSchedule": int(view_schedule or 0), + } + + def encrypt_password(public_key_b64: str, password: str) -> str: key = serialization.load_der_public_key(base64.b64decode(public_key_b64)) cipher = key.encrypt(password.encode("utf-8"), padding.PKCS1v15()) @@ -292,7 +382,7 @@ def fold_month_minutes(items: list[dict], year: int, month: int) -> tuple[int, b side = history_month_side(str(item.get("studied_at") or ""), year, month) if side == "in": minutes = item.get("minutes") - if isinstance(minutes, int): + if isinstance(minutes, int) and not isinstance(minutes, bool): total += minutes elif side == "before": reached_before = True @@ -300,6 +390,41 @@ def fold_month_minutes(items: list[dict], year: int, month: int) -> tuple[int, b return total, reached_before +def history_hour_totals(items: list[dict], now: datetime | None = None) -> dict[str, int]: + """按北京时间把学时历史加成累计、本年、本月、本日分钟。""" + from euniv.study_window import CN_TZ + + current = now or datetime.now(CN_TZ) + if current.tzinfo is None: + current = current.replace(tzinfo=CN_TZ) + else: + current = current.astimezone(CN_TZ) + year, month, day = current.year, current.month, current.day + total = year_total = month_total = today_total = 0 + for item in items: + minutes = item.get("minutes") + if not isinstance(minutes, int) or isinstance(minutes, bool): + continue + stamp = history_stamp(str(item.get("studied_at") or "")) + if stamp is None: + continue + total += minutes + if stamp.year != year: + continue + year_total += minutes + if stamp.month != month: + continue + month_total += minutes + if stamp.day == day: + today_total += minutes + return { + "year": year_total, + "month": month_total, + "today": today_total, + "total": total, + } + + def accumulate_month_minutes(fetch_page, year: int, month: int, page_size: int = HISTORY_PAGE_SIZE) -> int: """倒序分页累加本月分钟,遇到上个月即停。""" offset = 0 @@ -606,15 +731,15 @@ class QrWaiting(Exception): class EunivClient: def __init__(self, login_name: str, password: str, proxy: str | None = None) -> None: - from euniv.proxy import parse_proxy + from euniv.proxy import parse_proxy, sync_httpx_client self.login_name = login_name.strip() self.password = password self.proxy = parse_proxy(proxy) - self.client = httpx.Client( + self.client = sync_httpx_client( + self.proxy, timeout=30, follow_redirects=True, - proxy=self.proxy, headers={"User-Agent": USER_AGENT}, ) self._profile: dict = {} @@ -1254,29 +1379,14 @@ class EunivClient: html = self._site_page(path) from euniv.encrypt import note_play_html note_play_html(html, EUNIV) - def _var(name: str, default: str = "") -> str: - m = re.search(rf'(?:var\s+)?{name}\s*=\s*["\']?([^"\';\r\n]+)', html) - return m.group(1).strip() if m else default - return { - "knowledgeType": _var("knowledgeType"), - "submitIsOpen": _var("submitIsOpen", "0"), - "submitProTimes": int(_var("submitProTimes", "30") or 30), - "validtimeSpan": int(_var("validtimeSpan", "120") or 120), - "standardStudyHours": int(_var("standardStudyHours", "0") or 0), - "pageSize": int(_var("pageSize", "1") or 1), - "fileType": _var("fileType"), - "kngId": _var("kngId"), - "packageID": _var("packageID"), - "orgID": _var("orgID"), - "userID": _var("userID"), - } + return play_page_params(html) def update_progress(self, knowledge_id: str, package_id: str = "", master_id: str = "", master_type: str = "") -> dict: """POST /v1/study/updateprogress。返回 studyschedule, actualstudyhours, standardstudyhours, viewSchedule, status。""" body = { - "knowledgeId": knowledge_id, - "packageId": package_id, + "knowledgeId": as_uuid(knowledge_id), + "packageId": as_uuid(package_id) if package_id else "", "masterId": master_id, "masterType": master_type, } @@ -1286,7 +1396,7 @@ class EunivClient: def sync_package(self, knowledge_id: str) -> dict: """GET /v1/uk/syncpackage。返回整包和各章信息。""" resp = self._request("GET", f"{STUDY_API}/v1/uk/syncpackage", - params={"knowledgeId": knowledge_id, "sourceType": "SingleStudy", "masterId": ""}) + params={"knowledgeId": as_uuid(knowledge_id), "sourceType": "SingleStudy", "masterId": ""}) return resp.json() def get_encrypt_request(self, body_json: str) -> str: @@ -1298,24 +1408,12 @@ class EunivClient: study_time: int, view_schedule: int, master_id: str = "", master_type: str = "") -> dict: """视频心跳 POST /v1/study/submitpro。""" - param = { - "knowledgeId": knowledge_id, - "masterId": master_id, - "masterType": master_type, - "packageId": package_id, - "pageSize": 1, - "studySize": 1, - "studyTime": study_time, - "type": 0, - "offLine": False, - "end": False, - "care": True, - "deviceId": "", - "studyChapterIds": "", - "viewSchedule": view_schedule, - } - encrypt_body = json.dumps(param, separators=(",", ":")) - encryption = self.get_encrypt_request(encrypt_body) + del master_id, master_type + param = study_progress_fields( + knowledge_id, package_id, page_size=1, study_time=study_time, + kind=0, view_schedule=view_schedule, + ) + encryption = self.get_encrypt_request(json.dumps(param, separators=(",", ":"))) param["encryption"] = encryption param["multiple"] = 1 param["realHour"] = study_time @@ -1331,24 +1429,12 @@ class EunivClient: view_schedule: int, master_id: str = "", master_type: str = "") -> dict: """文档心跳 POST /v1/study/submit。""" - param = { - "knowledgeId": knowledge_id, - "masterId": master_id, - "masterType": master_type, - "packageId": package_id, - "pageSize": page_size, - "studySize": page_size, - "studyTime": study_time, - "type": 1, - "offLine": False, - "end": False, - "care": True, - "deviceId": "", - "studyChapterIds": "", - "viewSchedule": view_schedule, - } - encrypt_body = json.dumps(param, separators=(",", ":")) - encryption = self.get_encrypt_request(encrypt_body) + del master_id, master_type + param = study_progress_fields( + knowledge_id, package_id, page_size=page_size, study_time=study_time, + kind=1, view_schedule=view_schedule, + ) + encryption = self.get_encrypt_request(json.dumps(param, separators=(",", ":"))) param["multiple"] = 1 param["realHour"] = study_time resp = self._request("POST", f"{STUDY_API}/v1/study/submit?encryption={encryption}", @@ -1360,26 +1446,16 @@ class EunivClient: end: bool = False, master_id: str = "", master_type: str = "") -> dict: """Scorm 心跳 POST /v1/study/submit,type=2。""" - param = { - "knowledgeId": knowledge_id, - "masterId": master_id, - "masterType": master_type, - "packageId": package_id, - "pageSize": -1 if end else 1, - "studySize": -1 if end else 1, - "studyTime": study_time, - "type": 2, - "offLine": False, - "end": end, - "care": True, - "deviceId": "", - "studyChapterIds": sco_id, - "viewSchedule": 0, - } - encrypt_body = json.dumps(param, separators=(",", ":")) - encryption = self.get_encrypt_request(encrypt_body) - param["multiple"] = 1 - param["realHour"] = study_time + del master_id, master_type + encrypt_param = study_progress_fields( + knowledge_id, package_id, page_size=-1 if end else 1, study_time=study_time, + kind=2, view_schedule=0, end=end, chapter_id=sco_id, for_encrypt=True, + ) + encryption = self.get_encrypt_request(json.dumps(encrypt_param, separators=(",", ":"))) + param = study_progress_fields( + knowledge_id, package_id, page_size=-1 if end else 1, study_time=study_time, + kind=2, view_schedule=0, end=end, chapter_id=sco_id, + ) resp = self._request("POST", f"{STUDY_API}/v1/study/submit?encryption={encryption}", content=json.dumps(param, separators=(",", ":"))) return {} @@ -1387,7 +1463,7 @@ class EunivClient: def scorm_count(self, knowledge_id: str) -> int: """GET /v1/kng/scorm/count/。""" resp = self._request("GET", f"{STUDY_API}/v1/kng/scorm/count/", - params={"knowledgeId": knowledge_id}) + params={"knowledgeId": as_uuid(knowledge_id)}) data = resp.json() return int(data.get("scocnt") or 1) @@ -1408,11 +1484,11 @@ class EunivClient: "sessionId": session_id, "orgId": org_id, "userId": user_id, - "scormId": scorm_id, - "scormIdOri": scorm_id_ori, + "scormId": as_uuid(scorm_id), + "scormIdOri": as_uuid(scorm_id_ori), "masterId": master_id, "masterType": master_type, - "packageId": package_id, + "packageId": as_uuid(package_id) if package_id else "", "scocnt": sco_cnt, "data": data, } @@ -1421,7 +1497,8 @@ class EunivClient: def scorm_page_files(self, knowledge_id: str) -> list[str]: """下载 Scorm 课件的页索引,返回各页 .oss.js 的 URL 列表。""" - index_url = f"https://cdn-cos-file.yunxuetang.cn/zt/scorm/{knowledge_id}/h5/js/index-scorm.js" + compact = compact_id(knowledge_id) + index_url = f"https://cdn-cos-file.yunxuetang.cn/zt/scorm/{compact}/h5/js/index-scorm.js" resp = self.client.get(index_url, headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"}) urls = [] for m in re.finditer(r'["\']([^"\']+\.oss\.js)["\']', resp.text): @@ -1433,7 +1510,7 @@ class EunivClient: elif raw.startswith("/"): urls.append(f"https://cdn-cos-file.yunxuetang.cn{raw}") else: - urls.append(f"https://cdn-cos-file.yunxuetang.cn/zt/scorm/{knowledge_id}/h5/js/{raw}") + urls.append(f"https://cdn-cos-file.yunxuetang.cn/zt/scorm/{compact}/h5/js/{raw}") return urls def scorm_extract_answers(self, knowledge_id: str) -> list[dict]: diff --git a/backend/euniv/models.py b/backend/euniv/models.py index fc5dc7a..4ff935d 100644 --- a/backend/euniv/models.py +++ b/backend/euniv/models.py @@ -4,7 +4,7 @@ from __future__ import annotations from datetime import datetime -from sqlalchemy import Boolean, DateTime, String, Text, UniqueConstraint, false as sql_false +from sqlalchemy import Boolean, DateTime, String, Text, UniqueConstraint, false as sql_false, true as sql_true from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column @@ -46,6 +46,7 @@ class Account(Base): last_refresh_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) credential_valid: Mapped[bool | None] = mapped_column(Boolean, nullable=True) month_hours: Mapped[str] = mapped_column(String(32), nullable=False, default="", server_default="") + hours_month: Mapped[str] = mapped_column(String(7), nullable=False, default="", server_default="") monthly_target: Mapped[int] = mapped_column(nullable=False, default=600, server_default="600") proxy_scheme: Mapped[str] = mapped_column(String(16), nullable=False, default="", server_default="") proxy_host: Mapped[str] = mapped_column(String(255), nullable=False, default="", server_default="") @@ -59,7 +60,9 @@ class Account(Base): course_workers: Mapped[int] = mapped_column(nullable=False, default=1, server_default="1") use_proxy_pool: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=sql_false()) study_paused: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=sql_false()) + study_stop_month: Mapped[str] = mapped_column(String(7), nullable=False, default="", server_default="") study_ignore_window: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=sql_false()) + study_schedule_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default=sql_true()) class ProxyNode(Base): diff --git a/backend/euniv/proxy.py b/backend/euniv/proxy.py index 3d5e5ab..32d4811 100644 --- a/backend/euniv/proxy.py +++ b/backend/euniv/proxy.py @@ -7,6 +7,7 @@ from urllib.parse import quote, urlparse import httpx SCHEMES = ("http", "https", "socks4", "socks5", "socks5h") +SOCKS_SCHEMES = ("socks4", "socks5", "socks5h") OFF_SCHEMES = ("", "off", "none", "direct", "close") POOL_SCHEMES = ("pool", "auto") @@ -16,7 +17,7 @@ class ProxyError(ValueError): def parse_proxy(value: str | None) -> str | None: - """把代理地址规范成 httpx 可用的 URL。空值表示直连。""" + """把代理地址规范成内部使用的 URL。空值表示直连。""" text = (value or "").strip() if not text: return None @@ -182,6 +183,33 @@ def bind_url(account) -> str | None: return url_of(account) +def client_proxy_args(proxy: str | None, *, asynchronous: bool = False) -> dict: + """httpx 不认 socks4;SOCKS 走 httpx-socks 传输,HTTP/HTTPS 仍用 proxy=。""" + url = parse_proxy(proxy) + if not url: + return {} + scheme = urlparse(url).scheme.lower() + if scheme in SOCKS_SCHEMES: + if asynchronous: + from httpx_socks import AsyncProxyTransport + + return {"transport": AsyncProxyTransport.from_url(url)} + from httpx_socks import SyncProxyTransport + + return {"transport": SyncProxyTransport.from_url(url)} + return {"proxy": url} + + +def sync_httpx_client(proxy: str | None = None, **kwargs) -> httpx.Client: + kwargs.update(client_proxy_args(proxy)) + return httpx.Client(**kwargs) + + +def async_httpx_client(proxy: str | None = None, **kwargs) -> httpx.AsyncClient: + kwargs.update(client_proxy_args(proxy, asynchronous=True)) + return httpx.AsyncClient(**kwargs) + + def is_proxy_failure(exc: BaseException) -> bool: if isinstance(exc, (httpx.ProxyError, httpx.ConnectError, httpx.ConnectTimeout)): return True diff --git a/backend/euniv/proxy_pool.py b/backend/euniv/proxy_pool.py index 164ec37..7ebf713 100644 --- a/backend/euniv/proxy_pool.py +++ b/backend/euniv/proxy_pool.py @@ -17,7 +17,7 @@ from euniv.client import EUNIV, STUDY_API, USER_AGENT, YXT_API from euniv.collectors import collect_all, is_china, source_title from euniv.db import SessionLocal from euniv.models import ProxyNode, ProxyPoolSync -from euniv.proxy import build_proxy_url +from euniv.proxy import build_proxy_url, sync_httpx_client log = logging.getLogger(__name__) @@ -170,8 +170,8 @@ def probe(scheme: str, host: str, port: int) -> tuple[bool, int, str]: samples: list[int] = [] reasons: list[str] = [] try: - with httpx.Client( - proxy=url, + with sync_httpx_client( + url, timeout=LATENCY_LIMIT, follow_redirects=True, headers={"User-Agent": USER_AGENT}, @@ -202,9 +202,11 @@ def probe(scheme: str, host: str, port: int) -> tuple[bool, int, str]: def _short_reason(exc: BaseException) -> str: - if isinstance(exc, (httpx.ConnectTimeout, httpx.TimeoutException)): + from python_socks import ProxyConnectionError, ProxyTimeoutError + + if isinstance(exc, (httpx.ConnectTimeout, httpx.TimeoutException, ProxyTimeoutError)): return "超时" - if isinstance(exc, (httpx.ProxyError, httpx.ConnectError)): + if isinstance(exc, (httpx.ProxyError, httpx.ConnectError, ProxyConnectionError)): return "无法连接" text = str(exc).strip() or type(exc).__name__ return text[:200] diff --git a/backend/euniv/service.py b/backend/euniv/service.py index aff295c..8b6b91b 100644 --- a/backend/euniv/service.py +++ b/backend/euniv/service.py @@ -18,6 +18,7 @@ from euniv.client import ( ManualJigsaw, QrWaiting, SessionExpired, + history_hour_totals, is_qr_password, ) from euniv.crypto import decrypt_secret, encrypt_secret @@ -248,11 +249,11 @@ def poll_qr_login(db: Session, attempt_id: str, client_factory=EunivClient) -> d def fetch_home(db: Session, employee_id: str, client_factory=EunivClient) -> dict: """向 e 学现查首页信息。个人信息只出现在返回值里,不写入数据库。凭证变化时更新密文。""" - return _live(db, employee_id, client_factory, lambda client: client.home_snapshot()) + return _live(db, employee_id, client_factory, lambda client: _apply_hours_source(client, client.home_snapshot())) def fetch_home_summary(db: Session, employee_id: str, client_factory=EunivClient) -> dict: - return _live(db, employee_id, client_factory, lambda client: client.home_summary()) + return _live(db, employee_id, client_factory, lambda client: _apply_hours_source(client, client.home_summary())) def fetch_home_exams(db: Session, employee_id: str, client_factory=EunivClient) -> dict: @@ -272,10 +273,57 @@ def fetch_training_detail(db: Session, employee_id: str, path: str, client_facto def fetch_study_history(db: Session, employee_id: str, client_factory=EunivClient) -> dict: - items = _live(db, employee_id, client_factory, lambda client: client.study_history()) - if not isinstance(items, list): - items = [] - return {"items": items, "total": len(items)} + def read(client): + items = client.study_history() + if not isinstance(items, list): + items = [] + hours = _hour_fields(_apply_hours_source(client, _api_hour_fields(client), items)) + return {"items": items, "total": len(items), **hours} + + return _live(db, employee_id, client_factory, read) + + +def _apply_hours_source(client, summary: dict, items: list | None = None) -> dict: + from admin.settings import hours_source_of + + data = dict(summary) + source = hours_source_of() + data["hours_source"] = source + if source != "history": + 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"] + return data + + +def _api_hour_fields(client) -> dict: + from admin.settings import hours_source_of + + if hours_source_of() == "history": + return {} + summary = client.home_summary() + return { + "year_hours": summary.get("year_hours"), + "month_hours": summary.get("month_hours"), + "today_hours": summary.get("today_hours"), + "total_hours": summary.get("total_hours"), + } + + +def _hour_fields(data: dict) -> dict: + return { + "hours_source": data.get("hours_source") or "api", + "year_hours": data.get("year_hours"), + "month_hours": data.get("month_hours"), + "today_hours": data.get("today_hours"), + "total_hours": data.get("total_hours"), + } def _auto_attempts(db: Session) -> int: @@ -415,7 +463,9 @@ def _refresh_one(employee_id: str, attempts: int, client_factory) -> None: pass record_outcome(account, valid) if hours: - account.month_hours = hours + from euniv.study_control import stamp_hours + + stamp_hours(account, hours) db.commit() if checked_alive: _request_course_sync(employee_id) @@ -491,6 +541,17 @@ def start_credential_refresh() -> _RefreshGate: def _month_hours(client) -> str: + from admin.settings import hours_source_of + + if hours_source_of() == "history": + reader = getattr(client, "month_history_minutes", None) + if reader is None: + return "" + try: + value = reader() + except Exception: + return "" + return str(value) if isinstance(value, int) and not isinstance(value, bool) else "" reader = getattr(client, "month_hours", None) if reader is None: return "" diff --git a/backend/euniv/study_control.py b/backend/euniv/study_control.py index 997d124..d1937b1 100644 --- a/backend/euniv/study_control.py +++ b/backend/euniv/study_control.py @@ -2,7 +2,10 @@ from __future__ import annotations -from euniv.study_window import window_open +import re +from datetime import datetime + +from euniv.study_window import month_key, window_open class StudyControlError(ValueError): @@ -11,38 +14,157 @@ class StudyControlError(ValueError): def start_now(account) -> None: account.study_paused = False + account.study_stop_month = "" account.study_ignore_window = True -def stop_now(account) -> None: +def stop_now(account, now: datetime | None = None) -> None: account.study_paused = True account.study_ignore_window = False + account.study_stop_month = month_key(now) -def is_paused(account) -> bool: - return bool(getattr(account, "study_paused", False)) +def schedule_enabled(account) -> bool: + if not hasattr(account, "study_schedule_enabled"): + return True + value = getattr(account, "study_schedule_enabled", True) + return False if value is False else True + + +def is_paused(account, now: datetime | None = None) -> bool: + if not bool(getattr(account, "study_paused", False)): + return False + recorded = str(getattr(account, "study_stop_month", "") or "") + return (not recorded) or recorded == month_key(now) def ignores_window(account) -> bool: return bool(getattr(account, "study_ignore_window", False)) -def eligible(account) -> bool: - if is_paused(account): +def month_minutes(value: object) -> int: + match = re.search(r"(\d+)", str(value or "")) + return int(match.group(1)) if match else 0 + + +def stamp_hours(account, hours: str, now: datetime | None = None) -> None: + account.month_hours = hours + account.hours_month = month_key(now) + + +def hours_met(account, now: datetime | None = None) -> bool: + target = int(getattr(account, "monthly_target", 0) or 0) + if target <= 0: + return False + recorded = str(getattr(account, "hours_month", "") or "") + if recorded and recorded != month_key(now): + return False + return month_minutes(getattr(account, "month_hours", "")) >= target + + +def expire_pause(account, now: datetime | None = None) -> bool: + """本月停止不影响下月定时。遗留的无月份暂停记到当月。""" + if not bool(getattr(account, "study_paused", False)): + return False + key = month_key(now) + recorded = str(getattr(account, "study_stop_month", "") or "") + if not recorded: + account.study_stop_month = key + return True + if recorded != key: + account.study_paused = False + account.study_stop_month = "" + return True + return False + + +def eligible(account, now: datetime | None = None) -> bool: + if is_paused(account, now): + return False + if hours_met(account, now): return False if ignores_window(account): return True - return window_open(account) + if not schedule_enabled(account): + return False + return window_open(account, now) -def view_of(account) -> dict: - paused = is_paused(account) +def view_of(account, now: datetime | None = None) -> dict: + paused = is_paused(account, now) ignore = ignores_window(account) - opened = window_open(account) - started = (not paused) and (ignore or opened) + opened = window_open(account, now) + met = hours_met(account, now) + scheduled = schedule_enabled(account) + started = (not paused) and (not met) and (ignore or (scheduled and opened)) return { "paused": paused, "ignore_window": ignore, "window_open": opened, + "hours_met": met, + "schedule_enabled": scheduled, "started": started, } + + +def assemble(account, live: dict | None = None, now: datetime | None = None) -> dict: + payload = view_of(account, now) + info = live if isinstance(live, dict) else {} + payload["state"] = str(info.get("state") or "") + payload["course"] = str(info.get("course") or "") + payload["message"] = str(info.get("message") or "") + workers = info.get("workers") or [] + payload["workers"] = workers if isinstance(workers, list) else [] + from euniv.autostudy import work_running + + eid = str(getattr(account, "employee_id", "") or "") + running = bool(eid) and work_running(eid) + payload["active"] = running + payload["started"] = running + cached_hours = str(info.get("month_hours") or "") + payload["month_hours"] = cached_hours or str(getattr(account, "month_hours", "") or "") + try: + payload["monthly_target"] = int(getattr(account, "monthly_target", 0) or 0) + except (TypeError, ValueError): + payload["monthly_target"] = 0 + return payload + + +def settle(account, live: dict | None = None, now: datetime | None = None) -> bool: + """跨月恢复定时;达标且当前没在学时,收回立即开始标记。""" + changed = expire_pause(account, now) + payload = assemble(account, live, now) + if payload["hours_met"] and ignores_window(account) and not payload["active"]: + account.study_ignore_window = False + changed = True + return changed + + +def payload_for(employee_id: str) -> dict: + from euniv.autostudy import autostudy_status + from euniv.db import SessionLocal + from euniv.models import Account + + key = (employee_id or "").strip() + empty = { + "started": False, + "paused": True, + "hours_met": False, + "schedule_enabled": True, + "workers": [], + "active": False, + "message": "", + } + if not key: + return empty + with SessionLocal() as db: + account = db.get(Account, key) + if account is None: + return empty + status = autostudy_status() + live = dict((status.get("users") or {}).get(key) or {}) + if not live.get("message"): + live["message"] = str(status.get("message") or "") + if settle(account, live): + db.commit() + return assemble(account, live) diff --git a/backend/euniv/study_push.py b/backend/euniv/study_push.py new file mode 100644 index 0000000..1f7f8f9 --- /dev/null +++ b/backend/euniv/study_push.py @@ -0,0 +1,127 @@ +"""把自动学习状态推到首页 WebSocket。https 页面自动走 wss。 + +心跳等高频更新最多每 3 秒发一帧,只发当前最新快照。 +开始/停止等控制变化立刻推。 +""" + +from __future__ import annotations + +import asyncio +import logging +from collections import defaultdict + +from fastapi import WebSocket +from starlette.websockets import WebSocketState + +log = logging.getLogger(__name__) + +_PUSH_SECONDS = 3.0 + +_loop: asyncio.AbstractEventLoop | None = None +_clients: dict[str, set[WebSocket]] = defaultdict(set) +_pending: dict[str, asyncio.TimerHandle] = {} +_inflight: set[str] = set() +_dirty: set[str] = set() +_urgent: set[str] = set() +_last_flush: dict[str, float] = {} +_latest: dict[str, dict] = {} + + +def attach_loop(loop: asyncio.AbstractEventLoop) -> None: + global _loop + _loop = loop + + +def register(employee_id: str, ws: WebSocket) -> None: + key = (employee_id or "").strip() + if not key: + return + _clients[key].add(ws) + + +def unregister(employee_id: str, ws: WebSocket) -> None: + key = (employee_id or "").strip() + group = _clients.get(key) + if not group: + return + group.discard(ws) + if not group: + _clients.pop(key, None) + + +def notify(employee_id: str | None = None, urgent: bool = False) -> None: + loop = _loop + if loop is None or not loop.is_running(): + return + keys = [(employee_id or "").strip()] if employee_id else list(_clients) + for key in keys: + if key: + loop.call_soon_threadsafe(_mark, key, urgent) + + +def latest_of(employee_id: str) -> dict | None: + key = (employee_id or "").strip() + payload = _latest.get(key) + return dict(payload) if payload else None + + +def _mark(employee_id: str, urgent: bool) -> None: + _dirty.add(employee_id) + if urgent: + _urgent.add(employee_id) + _arm(employee_id, 0.0) + return + if employee_id in _pending or employee_id in _inflight: + return + loop = asyncio.get_running_loop() + wait = max(0.0, _PUSH_SECONDS - (loop.time() - _last_flush.get(employee_id, 0.0))) + _arm(employee_id, wait) + + +def _arm(employee_id: str, delay: float) -> None: + old = _pending.pop(employee_id, None) + if old is not None: + old.cancel() + loop = asyncio.get_running_loop() + if delay <= 0: + if employee_id in _inflight: + return + loop.create_task(_flush(employee_id)) + return + _pending[employee_id] = loop.call_later(delay, lambda: asyncio.create_task(_flush(employee_id))) + + +async def _flush(employee_id: str) -> None: + _pending.pop(employee_id, None) + sockets = list(_clients.get(employee_id) or ()) + if not sockets: + _dirty.discard(employee_id) + _urgent.discard(employee_id) + return + _inflight.add(employee_id) + try: + _dirty.discard(employee_id) + _urgent.discard(employee_id) + from euniv.study_control import payload_for + + payload = await asyncio.to_thread(payload_for, employee_id) + _latest[employee_id] = payload + _last_flush[employee_id] = asyncio.get_running_loop().time() + dead: list[WebSocket] = [] + for ws in sockets: + try: + if ws.client_state != WebSocketState.CONNECTED: + dead.append(ws) + continue + await ws.send_json(payload) + except Exception: + dead.append(ws) + for ws in dead: + unregister(employee_id, ws) + except Exception: + log.debug("学习状态快照失败", exc_info=True) + finally: + _inflight.discard(employee_id) + if employee_id in _dirty: + delay = 0.0 if employee_id in _urgent else _PUSH_SECONDS + _arm(employee_id, delay) diff --git a/backend/euniv/study_window.py b/backend/euniv/study_window.py index de751eb..0ad57ee 100644 --- a/backend/euniv/study_window.py +++ b/backend/euniv/study_window.py @@ -45,22 +45,32 @@ def view_of(account) -> dict: hour = int(getattr(account, "study_start_hour", 0) or 0) minute = int(getattr(account, "study_start_minute", 0) or 0) second = int(getattr(account, "study_start_second", 0) or 0) + enabled = getattr(account, "study_schedule_enabled", True) return { "day": day, "hour": hour, "minute": minute, "second": second, + "enabled": False if enabled is False else True, "label": label_of(account), } -def window_open(account, now: datetime | None = None) -> bool: - """当前是否已过该账号本月开始时刻。2 月 31 日等按当月最后一天。""" +def as_cn(now: datetime | None = None) -> datetime: current = now or datetime.now(CN_TZ) if current.tzinfo is None: - current = current.replace(tzinfo=CN_TZ) - else: - current = current.astimezone(CN_TZ) + return current.replace(tzinfo=CN_TZ) + return current.astimezone(CN_TZ) + + +def month_key(now: datetime | None = None) -> str: + current = as_cn(now) + return f"{current.year:04d}-{current.month:02d}" + + +def start_at(account, now: datetime | None = None) -> datetime: + """该账号在 now 所在月的开始时刻。2 月 31 日等按当月最后一天。""" + current = as_cn(now) day, hour, minute, second = validate_start( int(getattr(account, "study_start_day", 1) or 1), int(getattr(account, "study_start_hour", 0) or 0), @@ -68,7 +78,7 @@ def window_open(account, now: datetime | None = None) -> bool: int(getattr(account, "study_start_second", 0) or 0), ) last = calendar.monthrange(current.year, current.month)[1] - start = datetime( + return datetime( current.year, current.month, min(day, last), @@ -77,4 +87,28 @@ def window_open(account, now: datetime | None = None) -> bool: second, tzinfo=CN_TZ, ) - return current >= start + + +def window_open(account, now: datetime | None = None) -> bool: + """当前是否已过该账号本月开始时刻。""" + current = as_cn(now) + return current >= start_at(account, current) + + +def next_month_start(now: datetime | None = None) -> datetime: + current = as_cn(now) + if current.month == 12: + return datetime(current.year + 1, 1, 1, tzinfo=CN_TZ) + return datetime(current.year, current.month + 1, 1, tzinfo=CN_TZ) + + +def next_fire_at(account, now: datetime | None = None) -> datetime | None: + """下次定时触发。本月已到点则等到下月;关闭定时则没有下一次。""" + enabled = getattr(account, "study_schedule_enabled", True) + if enabled is False: + return None + current = as_cn(now) + this = start_at(account, current) + if current < this: + return this + return start_at(account, next_month_start(current)) diff --git a/backend/requirements.txt b/backend/requirements.txt index 73af6f9..2d89732 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -1,10 +1,14 @@ httpx==0.28.1 socksio==1.0.0 +httpx-socks==0.10.1 +python-socks==3.2.1 +sniffio==1.3.1 cryptography==50.0.2 pillow==13.0.0 qrcode==8.2 fastapi==0.162.0 uvicorn==0.54.0 +wsproto==1.2.0 sqlalchemy==2.1.6 alembic==1.20.1 pydantic==2.14.1 diff --git a/backend/tests/test_admin.py b/backend/tests/test_admin.py index 3cf78cb..a9350b9 100644 --- a/backend/tests/test_admin.py +++ b/backend/tests/test_admin.py @@ -226,6 +226,17 @@ def test_settings_reject_interval_and_attempts_outside_range() -> None: assert edges.status_code == 200 assert edges.json()["refresh_interval_minutes"] == 1 assert edges.json()["auto_jigsaw_attempts"] == 10 + zero = client.put( + "/api/admin/settings", + json=_settings_body(heartbeat_video_seconds=0, heartbeat_document_seconds=0, heartbeat_scorm_seconds=0), + ) + assert zero.status_code == 200 + assert zero.json()["heartbeat_video_seconds"] == 0 + assert zero.json()["heartbeat_document_seconds"] == 0 + assert zero.json()["heartbeat_scorm_seconds"] == 0 + negative = client.put("/api/admin/settings", json=_settings_body(heartbeat_video_seconds=-1)) + assert negative.status_code == 400 + assert negative.json()["detail"] == "视频心跳间隔须为 0 到 300 的整数" def test_refresh_interval_comes_only_from_database(monkeypatch) -> None: @@ -453,6 +464,7 @@ def test_check_skips_empty_credential_and_updates_saved_one() -> None: "study_start_hour", "study_start_minute", "study_start_second", + "study_schedule_enabled", "course_workers", "study_paused", "study_ignore_window", diff --git a/backend/tests/test_api.py b/backend/tests/test_api.py index ae5b038..fd1260c 100644 --- a/backend/tests/test_api.py +++ b/backend/tests/test_api.py @@ -75,6 +75,20 @@ class FakeClient: } ] + def home_summary(self) -> dict: + return { + "name": "测试用户", + "avatar": "https://example.test/a.jpg", + "department": "测试部门", + "level": "Scientist", + "year_hours": "100", + "month_hours": "60", + "today_hours": 1, + "total_hours": "10", + "total_score": "3.00", + "points": 20, + } + def home_snapshot(self) -> dict: if self._token == "yxt-1": self._token = "yxt-2" @@ -121,6 +135,7 @@ def test_login_stores_password_and_credential_only() -> None: "last_refresh_at", "credential_valid", "month_hours", + "hours_month", "monthly_target", "proxy_scheme", "proxy_host", @@ -134,7 +149,9 @@ def test_login_stores_password_and_credential_only() -> None: "course_workers", "use_proxy_pool", "study_paused", + "study_stop_month", "study_ignore_window", + "study_schedule_enabled", } home = client.get("/api/home") @@ -542,10 +559,20 @@ def test_user_can_set_monthly_study_start() -> None: assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200 empty = client.get("/api/settings/study-start") assert empty.status_code == 200 - assert empty.json() == {"day": 1, "hour": 0, "minute": 0, "second": 0, "label": "每月1日 00:00:00"} - saved = client.put("/api/settings/study-start", json={"day": 5, "hour": 16, "minute": 0, "second": 7}) + assert empty.json() == { + "day": 1, + "hour": 0, + "minute": 0, + "second": 0, + "enabled": True, + "label": "每月1日 00:00:00", + } + saved = client.put("/api/settings/study-start", json={"day": 5, "hour": 16, "minute": 0, "second": 7, "enabled": False}) assert saved.status_code == 200 assert saved.json()["label"] == "每月5日 16:00:07" + assert saved.json()["enabled"] is False + again = client.put("/api/settings/study-start", json={"day": 5, "hour": 16, "minute": 0, "second": 7, "enabled": True}) + assert again.json()["enabled"] is True bad = client.put("/api/settings/study-start", json={"day": 32, "hour": 16, "minute": 0, "second": 0}) assert bad.status_code == 400 @@ -563,11 +590,13 @@ def test_user_can_start_and_stop_study_immediately() -> None: idle = client.get("/api/settings/study-control") assert idle.status_code == 200 assert idle.json()["workers"] == [] + assert idle.json()["hours_met"] is False started = client.post("/api/settings/study-control", json={"action": "start"}) assert started.status_code == 200 assert started.json()["started"] is True assert started.json()["ignore_window"] is True assert started.json()["paused"] is False + assert started.json()["hours_met"] is False assert started.json()["workers"] == [] stopped = client.post("/api/settings/study-control", json={"action": "stop"}) assert stopped.status_code == 200 @@ -578,6 +607,56 @@ def test_user_can_start_and_stop_study_immediately() -> None: assert bad.status_code == 400 +def test_study_control_stays_stopped_when_month_hours_met() -> None: + import euniv.api as api_module + import euniv.service as service_module + + api_module.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store( + db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts + ) + client = TestClient(api_module.app) + assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200 + with SessionLocal() as db: + account = db.get(Account, "6650000146") + assert account is not None + account.monthly_target = 70 + account.month_hours = "78" + db.commit() + started = client.post("/api/settings/study-control", json={"action": "start"}) + assert started.status_code == 200 + assert started.json()["hours_met"] is True + assert started.json()["started"] is False + assert started.json()["paused"] is False + + +def test_study_control_websocket_sends_snapshot() -> None: + import euniv.api as api_module + import euniv.service as service_module + from starlette.websockets import WebSocketDisconnect + + api_module.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store( + db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts + ) + client = TestClient(api_module.app) + with pytest.raises(WebSocketDisconnect) as closed: + with client.websocket_connect("/api/settings/study-control/ws") as ws: + ws.receive_json() + assert closed.value.code == 4401 + assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200 + client.put("/api/settings/study-start", json={"day": 31, "hour": 23, "minute": 59, "second": 59}) + with client.websocket_connect("/api/settings/study-control/ws") as ws: + data = ws.receive_json() + assert data["started"] is False + assert data["hours_met"] is False + assert data["window_open"] is False + assert data["workers"] == [] + assert "month_hours" in data + ws.send_text("ping") + pong = ws.receive_json() + assert pong["paused"] is False + assert pong["started"] is False + + def test_user_can_read_study_history() -> None: import euniv.api as api_module import euniv.service as service_module @@ -596,6 +675,79 @@ def test_user_can_read_study_history() -> None: assert body["total"] == 1 assert body["items"][0]["title"].startswith("ZXCTN") assert body["items"][0]["minutes"] == 2 + assert body["hours_source"] == "api" + assert body["month_hours"] == "60" + assert body["year_hours"] == "100" + assert body["today_hours"] == 1 + assert body["total_hours"] == "10" + + +def _set_hours_source(value: str) -> None: + from admin.settings import load_config + + with SessionLocal() as db: + row = load_config(db) + row.hours_source = value + db.commit() + + +def test_home_and_history_hours_follow_source() -> None: + import euniv.api as api_module + import euniv.service as service_module + + api_module.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store( + db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts + ) + api_module.fetch_home_summary = lambda db, employee_id: service_module.fetch_home_summary( + db, employee_id, FakeClient + ) + api_module.fetch_study_history = lambda db, employee_id: service_module.fetch_study_history( + db, employee_id, FakeClient + ) + client = TestClient(api_module.app) + assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200 + + home = client.get("/api/home/summary") + history = client.get("/api/home/history") + assert home.status_code == 200 + assert history.status_code == 200 + assert home.json()["month_hours"] == history.json()["month_hours"] == "60" + assert home.json()["year_hours"] == history.json()["year_hours"] == "100" + assert home.json()["hours_source"] == history.json()["hours_source"] == "api" + + _set_hours_source("history") + home = client.get("/api/home/summary") + history = client.get("/api/home/history") + assert home.json()["hours_source"] == history.json()["hours_source"] == "history" + assert home.json()["month_hours"] == history.json()["month_hours"] == 2 + assert home.json()["year_hours"] == history.json()["year_hours"] == 2 + assert home.json()["total_hours"] == history.json()["total_hours"] == 2 + assert home.json()["today_hours"] == history.json()["today_hours"] == 0 + assert home.json()["total_score"] == "3.00" + + +def test_month_hours_refresh_follows_source() -> None: + from euniv.service import _month_hours + + class ApiClient: + def month_hours(self) -> str: + return "58" + + def month_history_minutes(self) -> int: + raise AssertionError("api 模式不应读历史") + + assert _month_hours(ApiClient()) == "58" + + _set_hours_source("history") + + class HistoryClient: + def month_hours(self) -> str: + raise AssertionError("history 模式不应读接口") + + def month_history_minutes(self) -> int: + return 80 + + assert _month_hours(HistoryClient()) == "80" def test_study_history_parses_period_table() -> None: diff --git a/backend/tests/test_autostudy.py b/backend/tests/test_autostudy.py index 06c39bb..462b942 100644 --- a/backend/tests/test_autostudy.py +++ b/backend/tests/test_autostudy.py @@ -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()) diff --git a/backend/tests/test_proxy_pool.py b/backend/tests/test_proxy_pool.py index 35eab72..4a5bf09 100644 --- a/backend/tests/test_proxy_pool.py +++ b/backend/tests/test_proxy_pool.py @@ -196,7 +196,7 @@ def test_probe_averages_euniv_related_sites(monkeypatch) -> None: status_code = 200 class FakeClient: - def __init__(self, **_kwargs) -> None: + def __init__(self, *_args, **_kwargs) -> None: return None def __enter__(self): @@ -210,7 +210,7 @@ def test_probe_averages_euniv_related_sites(monkeypatch) -> None: return FakeResponse() ticks = iter([0.0, 0.12, 0.12, 0.34, 0.34, 0.64]) - monkeypatch.setattr("euniv.proxy_pool.httpx.Client", FakeClient) + monkeypatch.setattr("euniv.proxy_pool.sync_httpx_client", FakeClient) monkeypatch.setattr("euniv.proxy_pool.time.perf_counter", lambda: next(ticks)) ok, latency, reason = probe("http", "10.0.0.9", 8080) assert seen == list(PROBE_URLS) @@ -221,7 +221,7 @@ def test_probe_averages_euniv_related_sites(monkeypatch) -> None: def test_probe_instant_connect_error_keeps_elapsed_latency(monkeypatch) -> None: class FakeClient: - def __init__(self, **_kwargs) -> None: + def __init__(self, *_args, **_kwargs) -> None: return None def __enter__(self): @@ -234,7 +234,7 @@ def test_probe_instant_connect_error_keeps_elapsed_latency(monkeypatch) -> None: raise httpx.ConnectError("boom") ticks = iter([0.0, 0.012, 0.012, 0.018, 0.018, 0.025]) - monkeypatch.setattr("euniv.proxy_pool.httpx.Client", FakeClient) + monkeypatch.setattr("euniv.proxy_pool.sync_httpx_client", FakeClient) monkeypatch.setattr("euniv.proxy_pool.time.perf_counter", lambda: next(ticks)) ok, latency, reason = probe("socks4", "10.0.0.9", 1080) assert ok is False diff --git a/backend/tests/test_study_poll.py b/backend/tests/test_study_poll.py new file mode 100644 index 0000000..bafd6ef --- /dev/null +++ b/backend/tests/test_study_poll.py @@ -0,0 +1,19 @@ +"""与 web/src/shared/studyFields.ts 的 studyPollSeconds 保持一致。""" + + +def study_poll_seconds(intervals: list[int]) -> int: + if any(value <= 0 for value in intervals): + return 10 + positive = [value for value in intervals if value > 0] + if not positive: + return 10 + return max(10, min(positive)) + + +def test_study_poll_seconds_floor_and_zero() -> None: + assert study_poll_seconds([]) == 10 + assert study_poll_seconds([0]) == 10 + assert study_poll_seconds([0, 30]) == 10 + assert study_poll_seconds([5]) == 10 + assert study_poll_seconds([30]) == 30 + assert study_poll_seconds([30, 120]) == 30 diff --git a/backend/tests/test_study_push.py b/backend/tests/test_study_push.py new file mode 100644 index 0000000..00f66a2 --- /dev/null +++ b/backend/tests/test_study_push.py @@ -0,0 +1,48 @@ +import asyncio + +from starlette.websockets import WebSocketState + +import euniv.study_push as study_push + + +class _Socket: + client_state = WebSocketState.CONNECTED + + def __init__(self) -> None: + self.payloads: list[dict] = [] + + async def send_json(self, payload: dict) -> None: + self.payloads.append(payload) + + +def test_study_push_throttles_and_only_sends_latest(monkeypatch) -> None: + socket = _Socket() + monkeypatch.setattr("euniv.study_control.payload_for", lambda eid: {"eid": eid, "n": len(socket.payloads)}) + + async def main() -> None: + study_push._pending.clear() + study_push._inflight.clear() + study_push._dirty.clear() + study_push._urgent.clear() + study_push._last_flush.clear() + study_push._latest.clear() + study_push._clients.clear() + study_push.attach_loop(asyncio.get_running_loop()) + study_push.register("u1", socket) + try: + study_push.notify("u1") + await asyncio.sleep(0.05) + assert len(socket.payloads) == 1 + study_push.notify("u1") + await asyncio.sleep(0.05) + assert len(socket.payloads) == 1 + study_push.notify("u1", urgent=True) + await asyncio.sleep(0.05) + assert len(socket.payloads) == 2 + assert study_push.latest_of("u1") == socket.payloads[-1] + finally: + for handle in list(study_push._pending.values()): + handle.cancel() + study_push.unregister("u1", socket) + + asyncio.run(main()) diff --git a/web/src/features/admin/CoursesView.vue b/web/src/features/admin/CoursesView.vue index e359574..554e651 100644 --- a/web/src/features/admin/CoursesView.vue +++ b/web/src/features/admin/CoursesView.vue @@ -167,12 +167,9 @@ onUnmounted(() => stopPoll());