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())
|
||||
Reference in New Issue
Block a user