feat: 按账号调度自动学习并让首页实时跟上状态

This commit is contained in:
2026-11-16 01:14:36 +08:00
parent 158578d17c
commit 7f0466b0f6
31 changed files with 2699 additions and 631 deletions
+65 -18
View File
@@ -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: