feat: 按账号调度自动学习并让首页实时跟上状态
This commit is contained in:
@@ -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,
|
||||
|
||||
@@ -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")
|
||||
|
||||
+12
-2
@@ -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)}
|
||||
|
||||
|
||||
|
||||
@@ -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")
|
||||
+65
-18
@@ -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:
|
||||
|
||||
+534
-204
File diff suppressed because it is too large
Load Diff
+162
-85
@@ -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]:
|
||||
|
||||
@@ -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):
|
||||
|
||||
+29
-1
@@ -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
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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 ""
|
||||
|
||||
+133
-11
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
@@ -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))
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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",
|
||||
|
||||
+154
-2
@@ -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:
|
||||
|
||||
@@ -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())
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -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())
|
||||
@@ -167,12 +167,9 @@ onUnmounted(() => stopPoll());
|
||||
<template>
|
||||
<section class="page admin-page">
|
||||
<header class="page-head">
|
||||
<div>
|
||||
<h2>课程清单</h2>
|
||||
<p v-if="!loading && !errorText">
|
||||
{{ total }} 门<template v-if="syncedAt"> · 更新于 {{ formatTime(syncedAt) }}</template>
|
||||
</p>
|
||||
</div>
|
||||
<p v-if="!loading && !errorText">
|
||||
{{ total }} 门<template v-if="syncedAt"> · 更新于 {{ formatTime(syncedAt) }}</template>
|
||||
</p>
|
||||
<form class="course-search" @submit.prevent="search">
|
||||
<n-tooltip>
|
||||
<template #trigger>
|
||||
|
||||
@@ -251,13 +251,10 @@ onUnmounted(() => stopPoll());
|
||||
<template>
|
||||
<section class="page admin-page">
|
||||
<header class="page-head">
|
||||
<div>
|
||||
<h2>代理</h2>
|
||||
<p v-if="!loading">
|
||||
可用 {{ alive }} · 失效 {{ dead }}
|
||||
<template v-if="fetchedAt"> · 更新于 {{ formatTime(fetchedAt) }}</template>
|
||||
</p>
|
||||
</div>
|
||||
<p v-if="!loading">
|
||||
可用 {{ alive }} · 失效 {{ dead }}
|
||||
<template v-if="fetchedAt"> · 更新于 {{ formatTime(fetchedAt) }}</template>
|
||||
</p>
|
||||
<form class="course-search" @submit.prevent="search">
|
||||
<n-tooltip>
|
||||
<template #trigger>
|
||||
|
||||
@@ -93,16 +93,16 @@ async function save() {
|
||||
return;
|
||||
}
|
||||
if (hbMode.value === "manual") {
|
||||
if (invalidInteger(hbVideo.value, 10, 300)) {
|
||||
errorText.value = "视频心跳间隔须为 10 到 300 的整数";
|
||||
if (invalidInteger(hbVideo.value, 0, 300)) {
|
||||
errorText.value = "视频心跳间隔须为 0 到 300 的整数";
|
||||
return;
|
||||
}
|
||||
if (invalidInteger(hbDocument.value, 30, 600)) {
|
||||
errorText.value = "文档心跳间隔须为 30 到 600 的整数";
|
||||
if (invalidInteger(hbDocument.value, 0, 600)) {
|
||||
errorText.value = "文档心跳间隔须为 0 到 600 的整数";
|
||||
return;
|
||||
}
|
||||
if (invalidInteger(hbScorm.value, 30, 600)) {
|
||||
errorText.value = "Scorm 心跳间隔须为 30 到 600 的整数";
|
||||
if (invalidInteger(hbScorm.value, 0, 600)) {
|
||||
errorText.value = "Scorm 心跳间隔须为 0 到 600 的整数";
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -158,12 +158,11 @@ async function save() {
|
||||
<section class="page admin-page">
|
||||
<form class="settings-form" @submit.prevent="save">
|
||||
<header class="page-head">
|
||||
<h2>系统配置</h2>
|
||||
<n-button type="primary" attr-type="submit" :loading="saving" :disabled="!loaded">保存</n-button>
|
||||
</header>
|
||||
<n-alert v-if="errorText" class="admin-alert" type="error">{{ errorText }}</n-alert>
|
||||
<n-alert v-else-if="successText" class="admin-alert" type="success">{{ successText }}</n-alert>
|
||||
<div class="admin-scroll settings-stack">
|
||||
<div class="settings-stack">
|
||||
<p v-if="loading && !loaded" class="admin-status">正在获取</p>
|
||||
<template v-else-if="loaded">
|
||||
<section class="panel-card">
|
||||
@@ -202,19 +201,19 @@ async function save() {
|
||||
<template v-else>
|
||||
<n-form-item label="视频">
|
||||
<div class="target-control">
|
||||
<n-input-number id="hb-video" v-model:value="hbVideo" button-placement="both" :min="10" :max="300" :precision="0" />
|
||||
<n-input-number id="hb-video" v-model:value="hbVideo" button-placement="both" :min="0" :max="300" :precision="0" />
|
||||
<span class="target-unit">秒</span>
|
||||
</div>
|
||||
</n-form-item>
|
||||
<n-form-item label="文档">
|
||||
<div class="target-control">
|
||||
<n-input-number id="hb-document" v-model:value="hbDocument" button-placement="both" :min="30" :max="600" :precision="0" />
|
||||
<n-input-number id="hb-document" v-model:value="hbDocument" button-placement="both" :min="0" :max="600" :precision="0" />
|
||||
<span class="target-unit">秒</span>
|
||||
</div>
|
||||
</n-form-item>
|
||||
<n-form-item label="Scorm">
|
||||
<div class="target-control">
|
||||
<n-input-number id="hb-scorm" v-model:value="hbScorm" button-placement="both" :min="30" :max="600" :precision="0" />
|
||||
<n-input-number id="hb-scorm" v-model:value="hbScorm" button-placement="both" :min="0" :max="600" :precision="0" />
|
||||
<span class="target-unit">秒</span>
|
||||
</div>
|
||||
</n-form-item>
|
||||
@@ -231,7 +230,7 @@ async function save() {
|
||||
</n-radio-group>
|
||||
</n-form-item>
|
||||
</n-form>
|
||||
<p class="form-hint">学时历史按倒序分页统计到上个月为止</p>
|
||||
<p class="form-hint">首页、学时历史和达标判断使用同一来源</p>
|
||||
</section>
|
||||
<section class="panel-card">
|
||||
<h3>管理员</h3>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { NAlert, NButton, NCheckbox, NDropdown, NForm, NFormItem, NIcon, NInput, NInputNumber, NModal, NSelect, NTimePicker, NTooltip, useDialog, type DropdownOption } from "naive-ui";
|
||||
import { NAlert, NButton, NCheckbox, NDropdown, NForm, NFormItem, NIcon, NInput, NInputNumber, NModal, NSelect, NSwitch, NTimePicker, NTooltip, useDialog, type DropdownOption } from "naive-ui";
|
||||
import { EllipsisHorizontalOutline, EllipsisVerticalOutline, HelpCircleOutline, PauseOutline, PlayOutline, SettingsOutline, WarningOutline } from "@vicons/ionicons5";
|
||||
import { dayOptions, workerHint, workerOptions } from "../../shared/studyFields";
|
||||
|
||||
@@ -19,6 +19,7 @@ interface UserRow {
|
||||
study_start_hour: number;
|
||||
study_start_minute: number;
|
||||
study_start_second: number;
|
||||
study_schedule_enabled: boolean;
|
||||
course_workers: number;
|
||||
study_paused: boolean;
|
||||
study_ignore_window: boolean;
|
||||
@@ -54,6 +55,7 @@ const startDay = ref<number | null>(1);
|
||||
const startHour = ref<number | null>(0);
|
||||
const startMinute = ref<number | null>(0);
|
||||
const startSecond = ref<number | null>(0);
|
||||
const scheduleEnabled = ref(true);
|
||||
const workersValue = ref<number | null>(1);
|
||||
const proxyScheme = ref("off");
|
||||
const proxyHost = ref("");
|
||||
@@ -142,6 +144,7 @@ function asUser(value: unknown): UserRow | null {
|
||||
study_start_hour: typeof value.study_start_hour === "number" ? value.study_start_hour : 0,
|
||||
study_start_minute: typeof value.study_start_minute === "number" ? value.study_start_minute : 0,
|
||||
study_start_second: typeof value.study_start_second === "number" ? value.study_start_second : 0,
|
||||
study_schedule_enabled: value.study_schedule_enabled !== false,
|
||||
course_workers: typeof value.course_workers === "number" ? value.course_workers : 1,
|
||||
study_paused: value.study_paused === true,
|
||||
study_ignore_window: value.study_ignore_window === true,
|
||||
@@ -388,6 +391,7 @@ function resetSettingsForm() {
|
||||
startHour.value = 0;
|
||||
startMinute.value = 0;
|
||||
startSecond.value = 0;
|
||||
scheduleEnabled.value = true;
|
||||
workersValue.value = 1;
|
||||
proxyScheme.value = "off";
|
||||
proxyHost.value = "";
|
||||
@@ -404,6 +408,7 @@ function applyRowSettings(row: UserRow) {
|
||||
startHour.value = row.study_start_hour;
|
||||
startMinute.value = row.study_start_minute;
|
||||
startSecond.value = row.study_start_second;
|
||||
scheduleEnabled.value = row.study_schedule_enabled !== false;
|
||||
workersValue.value = row.course_workers;
|
||||
}
|
||||
|
||||
@@ -475,6 +480,7 @@ async function saveSettings() {
|
||||
hour: startHour.value,
|
||||
minute: startMinute.value,
|
||||
second: startSecond.value,
|
||||
schedule_enabled: scheduleEnabled.value,
|
||||
workers: workersValue.value,
|
||||
scheme: proxyScheme.value,
|
||||
host: proxyHost.value.trim(),
|
||||
@@ -585,7 +591,6 @@ onMounted(() => {
|
||||
<template>
|
||||
<section class="page admin-page">
|
||||
<header class="page-head">
|
||||
<h2>用户管理</h2>
|
||||
<div class="page-head-actions">
|
||||
<n-tooltip>
|
||||
<template #trigger>
|
||||
@@ -712,16 +717,19 @@ onMounted(() => {
|
||||
<span class="target-unit">分钟</span>
|
||||
</div>
|
||||
</n-form-item>
|
||||
<n-form-item label="定时开启">
|
||||
<n-switch v-model:value="scheduleEnabled" size="small" />
|
||||
</n-form-item>
|
||||
<n-form-item label="定时启动">
|
||||
<div class="target-control start-control">
|
||||
<n-select id="admin-start-day" v-model:value="startDay" :options="dayOptions" class="day-select" />
|
||||
<n-tooltip v-if="startDay === 1" placement="top">
|
||||
<n-select id="admin-start-day" v-model:value="startDay" :options="dayOptions" class="day-select" :disabled="!scheduleEnabled" />
|
||||
<n-tooltip v-if="scheduleEnabled && startDay === 1" placement="top">
|
||||
<template #trigger>
|
||||
<n-icon class="day-warn"><WarningOutline /></n-icon>
|
||||
</template>
|
||||
不推荐使用
|
||||
</n-tooltip>
|
||||
<n-time-picker v-model:formatted-value="startTime" value-format="HH:mm:ss" :actions="null" />
|
||||
<n-time-picker v-model:formatted-value="startTime" value-format="HH:mm:ss" :actions="null" :disabled="!scheduleEnabled" />
|
||||
</div>
|
||||
</n-form-item>
|
||||
<n-form-item>
|
||||
|
||||
@@ -10,9 +10,17 @@ interface HistoryItem {
|
||||
path: string;
|
||||
}
|
||||
|
||||
interface HistoryHours {
|
||||
year_hours: string | number | null;
|
||||
month_hours: string | number | null;
|
||||
today_hours: string | number | null;
|
||||
total_hours: string | number | null;
|
||||
}
|
||||
|
||||
type SectionState = "loading" | "ready" | "error";
|
||||
|
||||
const items = ref<HistoryItem[] | null>(null);
|
||||
const hours = ref<HistoryHours | null>(null);
|
||||
const state = ref<SectionState>("loading");
|
||||
const errorText = ref("");
|
||||
const refreshing = ref(false);
|
||||
@@ -40,6 +48,20 @@ function asItem(value: unknown): HistoryItem | null {
|
||||
};
|
||||
}
|
||||
|
||||
function asHour(value: unknown): string | number | null {
|
||||
if (typeof value === "number" && Number.isFinite(value)) return value;
|
||||
if (typeof value === "string") return value;
|
||||
return null;
|
||||
}
|
||||
|
||||
function amount(value: string | number | null | undefined) {
|
||||
if (value === null || value === undefined || value === "") return "—";
|
||||
const numeric = Number(value);
|
||||
if (!Number.isFinite(numeric)) return String(value);
|
||||
if (Number.isInteger(numeric)) return String(numeric);
|
||||
return String(value);
|
||||
}
|
||||
|
||||
async function load() {
|
||||
if (busy) return;
|
||||
busy = true;
|
||||
@@ -47,7 +69,7 @@ async function load() {
|
||||
if (!hadData) state.value = "loading";
|
||||
try {
|
||||
const response = await fetch("/api/home/history");
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
const payload = await response.json().catch(() => ({})) as Record<string, unknown>;
|
||||
if (!response.ok) {
|
||||
if (!hadData) {
|
||||
errorText.value = failureText(payload, "学时历史没有获取到。");
|
||||
@@ -62,6 +84,12 @@ async function load() {
|
||||
if (item) parsed.push(item);
|
||||
}
|
||||
items.value = parsed;
|
||||
hours.value = {
|
||||
year_hours: asHour(payload.year_hours),
|
||||
month_hours: asHour(payload.month_hours),
|
||||
today_hours: asHour(payload.today_hours),
|
||||
total_hours: asHour(payload.total_hours),
|
||||
};
|
||||
errorText.value = "";
|
||||
state.value = "ready";
|
||||
const maxPage = Math.max(1, Math.ceil(parsed.length / pageSize.value));
|
||||
@@ -86,42 +114,13 @@ function refresh() {
|
||||
});
|
||||
}
|
||||
|
||||
function beijingParts(now = new Date()) {
|
||||
const fmt = new Intl.DateTimeFormat("en-CA", {
|
||||
timeZone: "Asia/Shanghai",
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
});
|
||||
const mapped = Object.fromEntries(fmt.formatToParts(now).map((part) => [part.type, part.value]));
|
||||
return { y: Number(mapped.year), m: Number(mapped.month), d: Number(mapped.day) };
|
||||
}
|
||||
|
||||
function stampParts(text: string) {
|
||||
const match = /^(\d{4})-(\d{2})-(\d{2})/.exec(text.trim());
|
||||
if (!match) return null;
|
||||
return { y: Number(match[1]), m: Number(match[2]), d: Number(match[3]) };
|
||||
}
|
||||
|
||||
function sumMinutes(filter: (stamp: { y: number; m: number; d: number }) => boolean) {
|
||||
const rows = items.value ?? [];
|
||||
let total = 0;
|
||||
for (const item of rows) {
|
||||
if (typeof item.minutes !== "number") continue;
|
||||
const stamp = stampParts(item.studied_at);
|
||||
if (!stamp) continue;
|
||||
if (filter(stamp)) total += item.minutes;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
const historyFacts = computed(() => {
|
||||
const now = beijingParts();
|
||||
const current = hours.value;
|
||||
return [
|
||||
{ label: "总学时", value: sumMinutes(() => true) },
|
||||
{ label: "本年学时", value: sumMinutes((stamp) => stamp.y === now.y) },
|
||||
{ label: "本月学时", value: sumMinutes((stamp) => stamp.y === now.y && stamp.m === now.m) },
|
||||
{ label: "本日学时", value: sumMinutes((stamp) => stamp.y === now.y && stamp.m === now.m && stamp.d === now.d) },
|
||||
{ label: "总学时", value: current ? amount(current.total_hours) : "" },
|
||||
{ label: "本年学时", value: current ? amount(current.year_hours) : "" },
|
||||
{ label: "本月学时", value: current ? amount(current.month_hours) : "" },
|
||||
{ label: "本日学时", value: current ? amount(current.today_hours) : "" },
|
||||
];
|
||||
});
|
||||
|
||||
|
||||
+379
-162
@@ -1,6 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from "vue";
|
||||
import { NAlert, NButton, NForm, NFormItem, NIcon, NInput, NInputNumber, NModal, NProgress, NSelect, NTimePicker, NTooltip } from "naive-ui";
|
||||
import { NAlert, NButton, NForm, NFormItem, NIcon, NInput, NInputNumber, NModal, NProgress, NSelect, NSwitch, NTimePicker, NTooltip } from "naive-ui";
|
||||
import { GlobeOutline, HelpCircleOutline, PlayOutline, RefreshOutline, StopOutline, WarningOutline } from "@vicons/ionicons5";
|
||||
import { dayOptions, workerHint, workerOptions } from "../../shared/studyFields";
|
||||
|
||||
@@ -23,6 +23,8 @@ interface StudyWorker {
|
||||
progress: number;
|
||||
interval: number;
|
||||
heartbeat_at: number;
|
||||
sent: number;
|
||||
total: number;
|
||||
ok: boolean;
|
||||
}
|
||||
|
||||
@@ -35,18 +37,27 @@ const summaryError = ref("");
|
||||
const refreshing = ref(false);
|
||||
let refreshRunning = false;
|
||||
let busy = false;
|
||||
let studyPoll = 0;
|
||||
let studyTick = 0;
|
||||
let studySocket: WebSocket | null = null;
|
||||
let studyReconnect = 0;
|
||||
let studyPing = 0;
|
||||
let studyFallback = 0;
|
||||
let studyBackoff = 1000;
|
||||
let studyClosed = false;
|
||||
const nowTick = ref(Date.now());
|
||||
|
||||
const monthlyTarget = ref<number | null>(null);
|
||||
const targetLoaded = ref(false);
|
||||
let targetSaveTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
const scheduleSaving = ref(false);
|
||||
const scheduleError = ref("");
|
||||
|
||||
const studyControl = ref({
|
||||
started: false,
|
||||
paused: false,
|
||||
ignore_window: false,
|
||||
window_open: false,
|
||||
hours_met: false,
|
||||
schedule_enabled: true,
|
||||
active: false,
|
||||
state: "",
|
||||
course: "",
|
||||
@@ -56,19 +67,52 @@ const studyControl = ref({
|
||||
const studyBusy = ref(false);
|
||||
const studyError = ref("");
|
||||
|
||||
const studyingWorkers = computed(() => (
|
||||
studyControl.value.workers.filter((row) => row.course.trim() && workerPercent(row) < 100)
|
||||
));
|
||||
|
||||
const countdownOn = computed(() => (
|
||||
studyingWorkers.value.some((row) => row.interval > 0 && row.heartbeat_at > 0)
|
||||
));
|
||||
|
||||
const studyFailed = computed(() => {
|
||||
const state = studyControl.value.state;
|
||||
return state === "会话失效" || state === "学习失败";
|
||||
});
|
||||
|
||||
const monthProgress = computed(() => {
|
||||
const match = String(summary.value?.month_hours ?? "").match(/(\d+)/);
|
||||
const current = match ? Number(match[1]) : 0;
|
||||
const target = monthlyTarget.value ?? 0;
|
||||
const pct = target > 0 ? Math.min(100, Math.round((current * 100) / target)) : 0;
|
||||
return { current, target, pct };
|
||||
});
|
||||
|
||||
const studyLabel = computed(() => {
|
||||
const state = studyControl.value.state;
|
||||
const course = studyControl.value.course;
|
||||
if (state === "已达标") return "本月目标已达到";
|
||||
const message = studyControl.value.message.trim();
|
||||
if (studyControl.value.hours_met || state === "已达标") return "本月目标已达到";
|
||||
if (state === "已停止" || studyControl.value.paused) return "任务已停止";
|
||||
if (studyControl.value.active) {
|
||||
return `正在学习:${course || state || "准备中"}`;
|
||||
}
|
||||
if (studyControl.value.started) return "任务已开始,等待执行";
|
||||
if (studyControl.value.message) return studyControl.value.message;
|
||||
if (state === "已学完") return "课程已学完";
|
||||
if (studyFailed.value) return message || state;
|
||||
if (state === "准备") return "正在连接学习平台";
|
||||
if (studyingWorkers.value.length) return studyControl.value.course || "学习中";
|
||||
if (state === "学习中") return "正在领取课程";
|
||||
if (studyControl.value.active || studyControl.value.started) return "正在启动学习任务";
|
||||
if (!studyControl.value.schedule_enabled) return "未开启定时自动学习";
|
||||
if (message && !message.startsWith("下一次") && !message.startsWith("运行中")) return message;
|
||||
return "未到开始时间";
|
||||
});
|
||||
|
||||
const studyHint = computed(() => {
|
||||
if (studyingWorkers.value.length) return "";
|
||||
if (studyControl.value.hours_met) return "达到本月目标后不能再开始。改大目标并保存后才会再启动。";
|
||||
if (studyFailed.value) return "点立即开始或保存定时配置会再启动。";
|
||||
if (studyControl.value.started || studyControl.value.active) return "开始后会列出正在学的课。";
|
||||
if (!studyControl.value.schedule_enabled) return "关闭定时后,只能点立即开始。";
|
||||
return "到点后会自动开始。保存定时配置时,若已过点且未达标也会立刻启动。";
|
||||
});
|
||||
|
||||
function amount(value: string | number | null | undefined) {
|
||||
if (value === null || value === undefined || value === "") return "—";
|
||||
const numeric = Number(value);
|
||||
@@ -109,6 +153,8 @@ function asWorkers(value: unknown): StudyWorker[] {
|
||||
progress: typeof row.progress === "number" ? row.progress : 0,
|
||||
interval: typeof row.interval === "number" ? row.interval : 0,
|
||||
heartbeat_at: typeof row.heartbeat_at === "number" ? row.heartbeat_at : 0,
|
||||
sent: typeof row.sent === "number" ? row.sent : 0,
|
||||
total: typeof row.total === "number" ? row.total : 0,
|
||||
ok: row.ok !== false,
|
||||
});
|
||||
}
|
||||
@@ -125,11 +171,25 @@ function workerTitle(row: StudyWorker) {
|
||||
return "准备";
|
||||
}
|
||||
|
||||
function showHeartbeat(row: StudyWorker) {
|
||||
return row.interval > 0 && row.heartbeat_at > 0;
|
||||
}
|
||||
|
||||
function workerCount(row: StudyWorker) {
|
||||
if (row.total > 0) return `${row.sent}/${row.total}`;
|
||||
if (row.sent > 0) return `${row.sent}/—`;
|
||||
return "—";
|
||||
}
|
||||
|
||||
function heartbeatLeft(row: StudyWorker) {
|
||||
void nowTick.value;
|
||||
if (!row.heartbeat_at) return "—";
|
||||
const left = Math.max(0, Math.ceil(row.heartbeat_at - Date.now() / 1000));
|
||||
return `${left}s`;
|
||||
const now = Date.now() / 1000;
|
||||
const cycle = Math.max(0, row.interval);
|
||||
let left = row.heartbeat_at - now;
|
||||
if (left < 0 && cycle > 0) {
|
||||
left = cycle - ((now - row.heartbeat_at) % cycle);
|
||||
}
|
||||
return `${Math.max(0, Math.ceil(left))}s`;
|
||||
}
|
||||
|
||||
async function loadSummary() {
|
||||
@@ -181,28 +241,12 @@ async function loadTarget() {
|
||||
} catch { /* 静默 */ }
|
||||
}
|
||||
|
||||
function saveTarget(value: number | null) {
|
||||
if (value == null || !Number.isInteger(value) || value < 0 || value > 9999) return;
|
||||
clearTimeout(targetSaveTimer);
|
||||
targetSaveTimer = setTimeout(async () => {
|
||||
try {
|
||||
await fetch("/api/settings/monthly-target", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ monthly_target: value }),
|
||||
});
|
||||
} catch { /* 静默 */ }
|
||||
}, 600);
|
||||
}
|
||||
|
||||
watch(monthlyTarget, (v) => { if (targetLoaded.value) saveTarget(v); });
|
||||
|
||||
const startLoaded = ref(false);
|
||||
const scheduleEnabled = ref(true);
|
||||
const startDay = ref<number | null>(1);
|
||||
const startHour = ref<number | null>(0);
|
||||
const startMinute = ref<number | null>(0);
|
||||
const startSecond = ref<number | null>(0);
|
||||
let startSaveTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
const startTime = computed({
|
||||
get() {
|
||||
@@ -227,37 +271,15 @@ async function loadStart() {
|
||||
startHour.value = typeof data.hour === "number" ? data.hour : 0;
|
||||
startMinute.value = typeof data.minute === "number" ? data.minute : 0;
|
||||
startSecond.value = typeof data.second === "number" ? data.second : 0;
|
||||
scheduleEnabled.value = data.enabled !== false;
|
||||
startLoaded.value = true;
|
||||
}
|
||||
} catch { /* 静默 */ }
|
||||
}
|
||||
|
||||
function saveStart() {
|
||||
const day = startDay.value;
|
||||
const hour = startHour.value;
|
||||
const minute = startMinute.value;
|
||||
const second = startSecond.value;
|
||||
if (
|
||||
day == null || hour == null || minute == null || second == null
|
||||
|| !Number.isInteger(day) || !Number.isInteger(hour) || !Number.isInteger(minute) || !Number.isInteger(second)
|
||||
) return;
|
||||
clearTimeout(startSaveTimer);
|
||||
startSaveTimer = setTimeout(async () => {
|
||||
try {
|
||||
await fetch("/api/settings/study-start", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ day, hour, minute, second }),
|
||||
});
|
||||
} catch { /* 静默 */ }
|
||||
}, 600);
|
||||
}
|
||||
|
||||
watch([startDay, startHour, startMinute, startSecond], () => { if (startLoaded.value) saveStart(); });
|
||||
|
||||
const workersLoaded = ref(false);
|
||||
const courseWorkers = ref<number | null>(1);
|
||||
let workersSaveTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
const scheduleReady = computed(() => targetLoaded.value && startLoaded.value && workersLoaded.value);
|
||||
|
||||
async function loadWorkers() {
|
||||
try {
|
||||
@@ -270,21 +292,52 @@ async function loadWorkers() {
|
||||
} catch { /* 静默 */ }
|
||||
}
|
||||
|
||||
function saveWorkers(value: number | null) {
|
||||
if (value == null || !Number.isInteger(value) || value < 1 || value > 8) return;
|
||||
clearTimeout(workersSaveTimer);
|
||||
workersSaveTimer = setTimeout(async () => {
|
||||
try {
|
||||
await fetch("/api/settings/course-workers", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ workers: value }),
|
||||
});
|
||||
} catch { /* 静默 */ }
|
||||
}, 600);
|
||||
async function putJson(url: string, body: Record<string, unknown>, fallback: string) {
|
||||
const res = await fetch(url, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(failureText(data, fallback));
|
||||
}
|
||||
|
||||
watch(courseWorkers, (v) => { if (workersLoaded.value) saveWorkers(v); });
|
||||
async function saveSchedule() {
|
||||
if (scheduleSaving.value || !scheduleReady.value) return;
|
||||
const target = monthlyTarget.value;
|
||||
const day = startDay.value;
|
||||
const hour = startHour.value;
|
||||
const minute = startMinute.value;
|
||||
const second = startSecond.value;
|
||||
const workers = courseWorkers.value;
|
||||
if (target == null || !Number.isInteger(target) || target < 0 || target > 9999) {
|
||||
scheduleError.value = "每月学时目标须为 0 到 9999 的整数";
|
||||
return;
|
||||
}
|
||||
if (
|
||||
day == null || hour == null || minute == null || second == null
|
||||
|| !Number.isInteger(day) || !Number.isInteger(hour) || !Number.isInteger(minute) || !Number.isInteger(second)
|
||||
) {
|
||||
scheduleError.value = "请填写完整的定时启动时间";
|
||||
return;
|
||||
}
|
||||
if (workers == null || !Number.isInteger(workers) || workers < 1 || workers > 8) {
|
||||
scheduleError.value = "线程数量须为 1 到 8";
|
||||
return;
|
||||
}
|
||||
scheduleSaving.value = true;
|
||||
scheduleError.value = "";
|
||||
try {
|
||||
await putJson("/api/settings/monthly-target", { monthly_target: target }, "没有保存每月目标。");
|
||||
await putJson("/api/settings/study-start", { day, hour, minute, second, enabled: scheduleEnabled.value }, "没有保存定时启动。");
|
||||
await putJson("/api/settings/course-workers", { workers }, "没有保存线程数量。");
|
||||
await loadStudyControl();
|
||||
} catch (exc) {
|
||||
scheduleError.value = exc instanceof Error ? exc.message : "没有保存。";
|
||||
} finally {
|
||||
scheduleSaving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const proxyOpen = ref(false);
|
||||
const proxyLoaded = ref(false);
|
||||
@@ -411,12 +464,17 @@ function applyStudyControl(payload: Record<string, unknown>) {
|
||||
paused: payload.paused === true,
|
||||
ignore_window: payload.ignore_window === true,
|
||||
window_open: payload.window_open === true,
|
||||
hours_met: payload.hours_met === true,
|
||||
schedule_enabled: payload.schedule_enabled !== false,
|
||||
active: payload.active === true,
|
||||
state: typeof payload.state === "string" ? payload.state : "",
|
||||
course: typeof payload.course === "string" ? payload.course : "",
|
||||
message: typeof payload.message === "string" ? payload.message : "",
|
||||
workers: asWorkers(payload.workers),
|
||||
};
|
||||
if (typeof payload.month_hours === "string" && summary.value) {
|
||||
summary.value = { ...summary.value, month_hours: payload.month_hours };
|
||||
}
|
||||
}
|
||||
|
||||
async function loadStudyControl() {
|
||||
@@ -427,32 +485,148 @@ async function loadStudyControl() {
|
||||
} catch { /* 静默 */ }
|
||||
}
|
||||
|
||||
function startStudyPoll() {
|
||||
if (studyPoll) return;
|
||||
studyPoll = window.setInterval(() => {
|
||||
nowTick.value = Date.now();
|
||||
void loadStudyControl();
|
||||
}, 1000);
|
||||
function studySocketUrl() {
|
||||
const proto = window.location.protocol === "https:" ? "wss:" : "ws:";
|
||||
return `${proto}//${window.location.host}/api/settings/study-control/ws`;
|
||||
}
|
||||
|
||||
function stopStudyPoll() {
|
||||
if (studyPoll) {
|
||||
window.clearInterval(studyPoll);
|
||||
studyPoll = 0;
|
||||
function stopStudyFallback() {
|
||||
if (studyFallback) {
|
||||
window.clearTimeout(studyFallback);
|
||||
studyFallback = 0;
|
||||
}
|
||||
}
|
||||
|
||||
function startStudyFallback() {
|
||||
if (studyClosed) return;
|
||||
if (studyFallback) return;
|
||||
const tick = async () => {
|
||||
studyFallback = 0;
|
||||
await loadStudyControl();
|
||||
if (!studyClosed && (!studySocket || studySocket.readyState !== WebSocket.OPEN)) {
|
||||
studyFallback = window.setTimeout(tick, 3000);
|
||||
}
|
||||
};
|
||||
void tick();
|
||||
}
|
||||
|
||||
function stopStudySocket() {
|
||||
studyClosed = true;
|
||||
if (studyReconnect) {
|
||||
window.clearTimeout(studyReconnect);
|
||||
studyReconnect = 0;
|
||||
}
|
||||
if (studyPing) {
|
||||
window.clearInterval(studyPing);
|
||||
studyPing = 0;
|
||||
}
|
||||
stopStudyFallback();
|
||||
const ws = studySocket;
|
||||
studySocket = null;
|
||||
if (ws) {
|
||||
ws.onclose = null;
|
||||
ws.onerror = null;
|
||||
ws.onmessage = null;
|
||||
ws.close();
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleStudyReconnect() {
|
||||
if (studyClosed || studyReconnect) return;
|
||||
const delay = studyBackoff;
|
||||
studyBackoff = Math.min(10000, delay * 2);
|
||||
studyReconnect = window.setTimeout(() => {
|
||||
studyReconnect = 0;
|
||||
connectStudySocket();
|
||||
}, delay);
|
||||
}
|
||||
|
||||
function connectStudySocket() {
|
||||
if (studyClosed) return;
|
||||
if (studySocket && (studySocket.readyState === WebSocket.OPEN || studySocket.readyState === WebSocket.CONNECTING)) {
|
||||
return;
|
||||
}
|
||||
let ws: WebSocket;
|
||||
try {
|
||||
ws = new WebSocket(studySocketUrl());
|
||||
} catch {
|
||||
startStudyFallback();
|
||||
scheduleStudyReconnect();
|
||||
return;
|
||||
}
|
||||
studySocket = ws;
|
||||
ws.onmessage = (event) => {
|
||||
try {
|
||||
const data = JSON.parse(String(event.data));
|
||||
if (data && typeof data === "object") applyStudyControl(data as Record<string, unknown>);
|
||||
} catch { /* ignore */ }
|
||||
};
|
||||
ws.onopen = () => {
|
||||
studyBackoff = 1000;
|
||||
stopStudyFallback();
|
||||
void loadStudyControl();
|
||||
if (studyPing) window.clearInterval(studyPing);
|
||||
studyPing = window.setInterval(() => {
|
||||
if (ws.readyState === WebSocket.OPEN) ws.send("ping");
|
||||
}, 8000);
|
||||
};
|
||||
ws.onclose = () => {
|
||||
if (studyPing) {
|
||||
window.clearInterval(studyPing);
|
||||
studyPing = 0;
|
||||
}
|
||||
if (studySocket === ws) studySocket = null;
|
||||
if (!studyClosed) {
|
||||
startStudyFallback();
|
||||
scheduleStudyReconnect();
|
||||
}
|
||||
};
|
||||
ws.onerror = () => {
|
||||
ws.close();
|
||||
};
|
||||
}
|
||||
|
||||
function stopStudyTick() {
|
||||
if (studyTick) {
|
||||
window.clearInterval(studyTick);
|
||||
studyTick = 0;
|
||||
}
|
||||
}
|
||||
|
||||
function startStudyTick() {
|
||||
if (studyTick) return;
|
||||
nowTick.value = Date.now();
|
||||
studyTick = window.setInterval(() => {
|
||||
nowTick.value = Date.now();
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
watch(proxyOpen, (open, wasOpen) => {
|
||||
if (wasOpen && !open) restoreProxy();
|
||||
});
|
||||
|
||||
watch(
|
||||
() => studyControl.value.started,
|
||||
(started) => {
|
||||
if (started) startStudyPoll();
|
||||
else stopStudyPoll();
|
||||
},
|
||||
);
|
||||
function studyWake() {
|
||||
if (studyClosed) return;
|
||||
void loadStudyControl();
|
||||
if (!studySocket || studySocket.readyState === WebSocket.CLOSING || studySocket.readyState === WebSocket.CLOSED) {
|
||||
connectStudySocket();
|
||||
return;
|
||||
}
|
||||
if (studySocket.readyState === WebSocket.OPEN) {
|
||||
try {
|
||||
studySocket.send("ping");
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
function onStudyVisible() {
|
||||
if (document.visibilityState === "visible") studyWake();
|
||||
}
|
||||
|
||||
watch(countdownOn, (on) => {
|
||||
if (on) startStudyTick();
|
||||
else stopStudyTick();
|
||||
});
|
||||
|
||||
async function toggleStudy() {
|
||||
if (studyBusy.value) return;
|
||||
@@ -484,13 +658,20 @@ onMounted(() => {
|
||||
loadStart();
|
||||
loadWorkers();
|
||||
loadProxy();
|
||||
connectStudySocket();
|
||||
document.addEventListener("visibilitychange", onStudyVisible);
|
||||
window.addEventListener("focus", studyWake);
|
||||
window.addEventListener("online", studyWake);
|
||||
window.addEventListener("pageshow", studyWake);
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
stopStudyPoll();
|
||||
clearTimeout(targetSaveTimer);
|
||||
clearTimeout(startSaveTimer);
|
||||
clearTimeout(workersSaveTimer);
|
||||
document.removeEventListener("visibilitychange", onStudyVisible);
|
||||
window.removeEventListener("focus", studyWake);
|
||||
window.removeEventListener("online", studyWake);
|
||||
window.removeEventListener("pageshow", studyWake);
|
||||
stopStudySocket();
|
||||
stopStudyTick();
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -548,89 +729,125 @@ onUnmounted(() => {
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<section class="panel-card study-card">
|
||||
<section class="panel-card study-card" :class="{ 'is-busy': studyingWorkers.length > 0 }">
|
||||
<header class="panel-card-head">
|
||||
<h3>自动学习</h3>
|
||||
<div class="study-head-actions">
|
||||
<n-button v-if="proxyLoaded" size="small" quaternary @click="proxyOpen = true">
|
||||
<template #icon><n-icon><GlobeOutline /></n-icon></template>
|
||||
代理
|
||||
</n-button>
|
||||
<n-button
|
||||
:type="studyControl.started ? 'error' : 'primary'"
|
||||
size="small"
|
||||
:loading="studyBusy"
|
||||
@click="toggleStudy"
|
||||
>
|
||||
<template #icon>
|
||||
<n-icon><StopOutline v-if="studyControl.started" /><PlayOutline v-else /></n-icon>
|
||||
</template>
|
||||
{{ studyControl.started ? "停止" : "立即开始" }}
|
||||
</n-button>
|
||||
</div>
|
||||
</header>
|
||||
<n-alert v-if="studyError" class="summary-error" type="error">{{ studyError }}</n-alert>
|
||||
<n-form class="compact-nform" label-placement="left" label-align="left" :label-width="96" :show-feedback="false" size="small">
|
||||
<n-form-item v-if="targetLoaded" label="每月目标">
|
||||
<div class="target-control">
|
||||
<n-input-number
|
||||
id="monthly-target"
|
||||
v-model:value="monthlyTarget"
|
||||
button-placement="both"
|
||||
:min="0"
|
||||
:max="9999"
|
||||
:precision="0"
|
||||
size="small"
|
||||
/>
|
||||
<span class="target-unit">分钟</span>
|
||||
</div>
|
||||
</n-form-item>
|
||||
<n-form-item v-if="startLoaded" label="定时启动">
|
||||
<div class="target-control start-control">
|
||||
<n-select id="study-start-day" v-model:value="startDay" size="small" :options="dayOptions" class="day-select" />
|
||||
<n-tooltip v-if="startDay === 1" placement="top">
|
||||
<n-alert v-if="scheduleError" class="summary-error" type="error">{{ scheduleError }}</n-alert>
|
||||
<div class="study-card-body">
|
||||
<div class="study-config">
|
||||
<n-form class="compact-nform" label-placement="left" label-align="left" :label-width="96" :show-feedback="false" size="small">
|
||||
<n-form-item v-if="targetLoaded" label="每月目标">
|
||||
<div class="target-control">
|
||||
<n-input-number
|
||||
id="monthly-target"
|
||||
v-model:value="monthlyTarget"
|
||||
button-placement="both"
|
||||
:min="0"
|
||||
:max="9999"
|
||||
:precision="0"
|
||||
size="small"
|
||||
/>
|
||||
<span class="target-unit">分钟</span>
|
||||
</div>
|
||||
</n-form-item>
|
||||
<n-form-item v-if="startLoaded" label="定时开启">
|
||||
<n-switch v-model:value="scheduleEnabled" size="small" />
|
||||
</n-form-item>
|
||||
<n-form-item v-if="startLoaded" label="定时启动">
|
||||
<div class="start-control">
|
||||
<n-select id="study-start-day" v-model:value="startDay" size="small" :options="dayOptions" class="day-select" :disabled="!scheduleEnabled" />
|
||||
<n-tooltip v-if="scheduleEnabled && startDay === 1" placement="top">
|
||||
<template #trigger>
|
||||
<n-icon class="day-warn"><WarningOutline /></n-icon>
|
||||
</template>
|
||||
不推荐使用
|
||||
</n-tooltip>
|
||||
<n-time-picker
|
||||
class="start-time"
|
||||
v-model:formatted-value="startTime"
|
||||
value-format="HH:mm:ss"
|
||||
size="small"
|
||||
:actions="null"
|
||||
:disabled="!scheduleEnabled"
|
||||
/>
|
||||
</div>
|
||||
</n-form-item>
|
||||
<n-form-item v-if="workersLoaded" label="线程数量">
|
||||
<div class="target-control">
|
||||
<n-select id="course-workers" class="worker-select" v-model:value="courseWorkers" size="small" :options="workerOptions" />
|
||||
<n-tooltip v-if="courseWorkers === 1" placement="top">
|
||||
<template #trigger>
|
||||
<button type="button" class="hint-icon" aria-label="说明">
|
||||
<n-icon><HelpCircleOutline /></n-icon>
|
||||
</button>
|
||||
</template>
|
||||
{{ workerHint }}
|
||||
</n-tooltip>
|
||||
</div>
|
||||
</n-form-item>
|
||||
</n-form>
|
||||
<div class="study-actions">
|
||||
<n-button v-if="proxyLoaded" size="small" quaternary @click="proxyOpen = true">
|
||||
<template #icon><n-icon><GlobeOutline /></n-icon></template>
|
||||
代理
|
||||
</n-button>
|
||||
<n-button v-if="scheduleReady" type="primary" size="small" :loading="scheduleSaving" @click="saveSchedule">保存定时配置</n-button>
|
||||
<n-tooltip v-if="!studyControl.started" placement="top">
|
||||
<template #trigger>
|
||||
<n-icon class="day-warn"><WarningOutline /></n-icon>
|
||||
<span class="study-start-wrap">
|
||||
<n-button type="success" size="small" :disabled="studyControl.hours_met" :loading="studyBusy" @click="toggleStudy">
|
||||
<template #icon>
|
||||
<n-icon><PlayOutline /></n-icon>
|
||||
</template>
|
||||
立即开始
|
||||
</n-button>
|
||||
</span>
|
||||
</template>
|
||||
不推荐使用
|
||||
{{ studyControl.hours_met ? "本月目标已达到" : "会跳过设定的定时启动时间,立刻开始学习任务。" }}
|
||||
</n-tooltip>
|
||||
<n-time-picker v-model:formatted-value="startTime" value-format="HH:mm:ss" size="small" :actions="null" />
|
||||
<n-button v-else type="error" size="small" :loading="studyBusy" @click="toggleStudy">
|
||||
<template #icon>
|
||||
<n-icon><StopOutline /></n-icon>
|
||||
</template>
|
||||
停止
|
||||
</n-button>
|
||||
</div>
|
||||
</n-form-item>
|
||||
<n-form-item v-if="workersLoaded">
|
||||
<template #label>
|
||||
<span class="field-title">
|
||||
<span>线程数量</span>
|
||||
<n-tooltip placement="top">
|
||||
<template #trigger>
|
||||
<button type="button" class="hint-icon" aria-label="说明">
|
||||
<n-icon><HelpCircleOutline /></n-icon>
|
||||
</button>
|
||||
</template>
|
||||
{{ workerHint }}
|
||||
</n-tooltip>
|
||||
</span>
|
||||
</template>
|
||||
<n-select id="course-workers" class="worker-select" v-model:value="courseWorkers" size="small" :options="workerOptions" />
|
||||
</n-form-item>
|
||||
</n-form>
|
||||
<div class="home-study-status">
|
||||
<span class="study-indicator" :class="{ active: studyControl.started || studyControl.active }"></span>
|
||||
<span class="study-text" :class="{ muted: !studyControl.active }">{{ studyLabel }}</span>
|
||||
</div>
|
||||
<div class="study-live">
|
||||
<div class="study-live-status">
|
||||
<span
|
||||
class="study-indicator"
|
||||
:class="{
|
||||
active: !studyFailed && (studyControl.started || studyControl.active),
|
||||
down: studyFailed,
|
||||
}"
|
||||
></span>
|
||||
<span class="study-text" :class="{ muted: !studyControl.started && !studyControl.active }">{{ studyLabel }}</span>
|
||||
</div>
|
||||
<div v-if="targetLoaded" class="study-progress">
|
||||
<div class="study-progress-meta">
|
||||
<span>本月进度</span>
|
||||
<span>{{ monthProgress.current }} / {{ monthProgress.target }} 分钟</span>
|
||||
</div>
|
||||
<n-progress type="line" :percentage="monthProgress.pct" :show-indicator="false" :height="6" />
|
||||
</div>
|
||||
<ul v-if="studyingWorkers.length" class="study-workers" aria-label="当前课程">
|
||||
<li v-for="row in studyingWorkers" :key="row.id" class="study-worker">
|
||||
<span class="study-worker-title">{{ workerTitle(row) }}</span>
|
||||
<div class="study-worker-bar">
|
||||
<n-progress type="line" :percentage="workerPercent(row)" :show-indicator="false" :height="6" />
|
||||
</div>
|
||||
<span class="study-worker-pct">{{ workerPercent(row) }}%</span>
|
||||
<span class="study-worker-count">{{ workerCount(row) }}</span>
|
||||
<span v-if="showHeartbeat(row)" class="study-heartbeat">{{ heartbeatLeft(row) }}</span>
|
||||
<span class="study-dot" :class="row.ok ? 'up' : 'down'" :aria-label="row.ok ? '正常' : '异常'"></span>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else-if="studyHint" class="study-live-hint">{{ studyHint }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<ul v-if="studyControl.started && studyControl.workers.length" class="study-workers">
|
||||
<li v-for="row in studyControl.workers" :key="row.id" class="study-worker">
|
||||
<div class="study-worker-main">
|
||||
<span class="study-worker-title">{{ workerTitle(row) }}</span>
|
||||
<n-progress type="line" :percentage="workerPercent(row)" :show-indicator="false" :height="8" />
|
||||
</div>
|
||||
<div class="study-worker-meta">
|
||||
<span class="study-worker-pct">{{ workerPercent(row) }}%</span>
|
||||
<span class="study-heartbeat">{{ heartbeatLeft(row) }}</span>
|
||||
<span class="study-dot" :class="row.ok ? 'up' : 'down'"></span>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
</div>
|
||||
<n-modal
|
||||
|
||||
@@ -8,10 +8,19 @@ export const workerOptions = [
|
||||
{ label: "5", value: 5 },
|
||||
{ label: "6", value: 6 },
|
||||
{ label: "7", value: 7 },
|
||||
{ label: "8 · 最大", value: 8 },
|
||||
{ label: "8", value: 8 },
|
||||
];
|
||||
|
||||
export const dayOptions = Array.from({ length: 31 }, (_, index) => ({
|
||||
label: `${index + 1}日`,
|
||||
label: `每月 ${index + 1}号`,
|
||||
value: index + 1,
|
||||
}));
|
||||
|
||||
export const STUDY_POLL_FLOOR = 10;
|
||||
|
||||
export function studyPollSeconds(intervals: number[]): number {
|
||||
if (intervals.some((value) => value <= 0)) return STUDY_POLL_FLOOR;
|
||||
const positive = intervals.filter((value) => value > 0);
|
||||
if (!positive.length) return STUDY_POLL_FLOOR;
|
||||
return Math.max(STUDY_POLL_FLOOR, Math.min(...positive));
|
||||
}
|
||||
|
||||
@@ -60,12 +60,19 @@ export const scheme = computed(() => schemes.find((item) => item.id === schemeId
|
||||
export const isDark = computed(() => scheme.value.dark);
|
||||
export const themeOverrides = computed<GlobalThemeOverrides>(() => {
|
||||
const current = scheme.value;
|
||||
const success = current.dark ? "#238636" : "#1A7F37";
|
||||
const successHover = current.dark ? "#2EA043" : "#2DA44E";
|
||||
const successPressed = current.dark ? "#196C2E" : "#116329";
|
||||
return {
|
||||
common: {
|
||||
primaryColor: current.primary,
|
||||
primaryColorHover: current.primaryHover,
|
||||
primaryColorPressed: current.primaryPressed,
|
||||
primaryColorSuppl: current.primary,
|
||||
successColor: success,
|
||||
successColorHover: successHover,
|
||||
successColorPressed: successPressed,
|
||||
successColorSuppl: success,
|
||||
errorColor: current.danger,
|
||||
errorColorHover: current.danger,
|
||||
errorColorPressed: current.danger,
|
||||
@@ -92,6 +99,14 @@ export const themeOverrides = computed<GlobalThemeOverrides>(() => {
|
||||
textColorHoverPrimary: "#ffffff",
|
||||
textColorPressedPrimary: "#ffffff",
|
||||
textColorFocusPrimary: "#ffffff",
|
||||
textColorSuccess: "#ffffff",
|
||||
textColorHoverSuccess: "#ffffff",
|
||||
textColorPressedSuccess: "#ffffff",
|
||||
textColorFocusSuccess: "#ffffff",
|
||||
textColorError: "#ffffff",
|
||||
textColorHoverError: "#ffffff",
|
||||
textColorPressedError: "#ffffff",
|
||||
textColorFocusError: "#ffffff",
|
||||
},
|
||||
Menu: {
|
||||
itemTextColor: current.vars["--ink"],
|
||||
|
||||
+236
-40
@@ -432,7 +432,7 @@ select {
|
||||
.home {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
@@ -491,7 +491,9 @@ select {
|
||||
}
|
||||
|
||||
.compact-nform .n-form-item-blank {
|
||||
min-width: 0;
|
||||
min-height: 32px;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.compact-nform .n-form-item-feedback-wrapper {
|
||||
@@ -521,10 +523,27 @@ select {
|
||||
}
|
||||
|
||||
.settings-stack {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
grid-template-rows: minmax(0, 1fr) minmax(0, 1fr);
|
||||
gap: 16px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.settings-stack > .panel-card {
|
||||
box-sizing: border-box;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
max-width: 640px;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.settings-stack .compact-nform {
|
||||
max-width: none;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.settings-stack .form-hint {
|
||||
@@ -542,6 +561,7 @@ select {
|
||||
}
|
||||
|
||||
.home-summary {
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
@@ -616,18 +636,35 @@ select {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.target-control .n-input-number {
|
||||
width: 120px;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.start-control .n-input-number {
|
||||
width: 88px;
|
||||
.start-control {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.start-control .day-select {
|
||||
width: 108px;
|
||||
.start-control .day-select,
|
||||
.start-control .start-time {
|
||||
flex: 1 1 8.5rem;
|
||||
width: auto;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.start-control .start-time .n-input {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.worker-select {
|
||||
@@ -635,14 +672,17 @@ select {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.study-head-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
.study-start-wrap {
|
||||
display: inline-flex;
|
||||
}
|
||||
|
||||
.start-control .n-time-picker {
|
||||
width: 148px;
|
||||
.study-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding-left: 96px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.day-warn {
|
||||
@@ -656,13 +696,12 @@ select {
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.home-study-status {
|
||||
.home-study-status,
|
||||
.study-live-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding-top: 8px;
|
||||
margin-top: 4px;
|
||||
border-top: 1px solid var(--line);
|
||||
min-height: 32px;
|
||||
}
|
||||
|
||||
.study-indicator {
|
||||
@@ -678,6 +717,11 @@ select {
|
||||
box-shadow: 0 0 6px rgba(63, 185, 80, 0.5);
|
||||
}
|
||||
|
||||
.study-indicator.down {
|
||||
background: var(--danger);
|
||||
box-shadow: 0 0 6px rgba(248, 81, 73, 0.5);
|
||||
}
|
||||
|
||||
.study-text {
|
||||
font-size: 13px;
|
||||
}
|
||||
@@ -687,59 +731,143 @@ select {
|
||||
}
|
||||
|
||||
.study-card {
|
||||
flex: 0 1 auto;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.study-card.is-busy {
|
||||
flex: 1 1 auto;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.study-card-body {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 30rem) minmax(0, 1fr);
|
||||
gap: 16px 32px;
|
||||
align-items: start;
|
||||
padding-top: 12px;
|
||||
}
|
||||
|
||||
.study-card.is-busy .study-card-body {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
grid-template-columns: minmax(0, 30rem) minmax(0, 1fr);
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.study-config {
|
||||
min-width: 0;
|
||||
max-width: 30rem;
|
||||
}
|
||||
|
||||
.study-config .compact-nform {
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
.study-live {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
padding-left: 24px;
|
||||
border-left: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.study-card.is-busy .study-live {
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.study-progress {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
max-width: 28rem;
|
||||
}
|
||||
|
||||
.study-progress-meta {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
font-size: 13px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.study-progress-meta span:first-child {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.study-live-hint {
|
||||
margin: 0;
|
||||
max-width: 36rem;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.study-workers {
|
||||
list-style: none;
|
||||
margin: 12px 0 0;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.study-worker {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
gap: 12px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.study-worker-main {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.study-worker-title {
|
||||
flex: 1 1 9rem;
|
||||
min-width: 0;
|
||||
font-size: 13px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.study-worker-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
.study-worker-bar {
|
||||
flex: 1 1 10rem;
|
||||
min-width: 72px;
|
||||
}
|
||||
|
||||
.study-worker-bar .n-progress {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.study-worker-pct,
|
||||
.study-worker-count {
|
||||
flex: none;
|
||||
text-align: right;
|
||||
font-variant-numeric: tabular-nums;
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.study-worker-pct {
|
||||
width: 36px;
|
||||
text-align: right;
|
||||
color: var(--text);
|
||||
width: 3.25em;
|
||||
}
|
||||
|
||||
.study-worker-count {
|
||||
min-width: 3.75em;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.study-heartbeat {
|
||||
width: 36px;
|
||||
flex: none;
|
||||
width: 2.75em;
|
||||
text-align: right;
|
||||
font-variant-numeric: tabular-nums;
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.study-dot {
|
||||
@@ -1182,6 +1310,25 @@ select {
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 1099px) {
|
||||
.study-card-body,
|
||||
.study-card.is-busy .study-card-body {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.study-card.is-busy .study-card-body {
|
||||
grid-template-rows: auto minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.study-live {
|
||||
padding-left: 0;
|
||||
border-left: 0;
|
||||
padding-top: 12px;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 800px) {
|
||||
.page {
|
||||
padding: 16px 12px;
|
||||
@@ -1212,14 +1359,15 @@ select {
|
||||
.admin-page .page-head {
|
||||
flex: none;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.admin-page .page-head h2 {
|
||||
margin: 0;
|
||||
.admin-page .page-head:has(> :nth-child(2)) {
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.admin-page .page-head p {
|
||||
margin: 4px 0 0;
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
@@ -1441,6 +1589,54 @@ select {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
body .n-input .n-input__input-el,
|
||||
body .n-input .n-input__textarea-el,
|
||||
body .n-input-number .n-input__input-el {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
body .n-input .n-input__placeholder {
|
||||
justify-content: center;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
body .n-base-selection-input,
|
||||
body .n-base-selection-input__content,
|
||||
body .n-base-selection-overlay,
|
||||
body .n-base-selection-placeholder,
|
||||
body .n-base-selection-input-tag__input {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
body .n-base-selection-label,
|
||||
body .n-base-selection-placeholder,
|
||||
body .n-base-selection-overlay {
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
body .n-base-selection-input__content,
|
||||
body .n-base-selection-overlay {
|
||||
display: block;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
body .n-base-select-menu .n-base-select-option {
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
body .n-base-select-menu .n-base-select-option__content {
|
||||
flex: 1;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
@media (max-width: 1100px) {
|
||||
.settings-stack {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
grid-template-rows: none;
|
||||
grid-auto-rows: auto;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 800px) {
|
||||
.settings-form .form-row {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
|
||||
+4
-1
@@ -5,7 +5,10 @@ export default defineConfig({
|
||||
plugins: [vue()],
|
||||
server: {
|
||||
proxy: {
|
||||
"/api": "http://127.0.0.1:8000",
|
||||
"/api": {
|
||||
target: "http://127.0.0.1:8000",
|
||||
ws: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user