fix: 一次保存学习配置,改代理后重开任务
This commit is contained in:
+45
-1
@@ -72,6 +72,16 @@ class CourseWorkersBody(_BaseModel):
|
||||
workers: int
|
||||
|
||||
|
||||
class StudyBundleBody(_BaseModel):
|
||||
monthly_target: int
|
||||
day: int
|
||||
hour: int
|
||||
minute: int
|
||||
second: int
|
||||
enabled: bool = True
|
||||
workers: int
|
||||
|
||||
|
||||
class StudyControlBody(_BaseModel):
|
||||
action: str
|
||||
|
||||
@@ -371,6 +381,34 @@ def put_study_start(body: StudyStartBody, request: Request, db: Session = Depend
|
||||
return view_of(account)
|
||||
|
||||
|
||||
@app.put("/api/settings/study")
|
||||
def put_study_bundle(body: StudyBundleBody, request: Request, db: Session = Depends(get_db)) -> dict:
|
||||
from euniv.course_workers import CourseWorkersError, apply as apply_workers
|
||||
from euniv.study_window import StudyWindowError, apply as apply_start, view_of
|
||||
|
||||
if not 0 <= body.monthly_target <= 9999:
|
||||
raise HTTPException(status_code=400, detail="每月学时目标须为 0 到 9999 的整数")
|
||||
account = db.get(Account, _signed_in(request, db))
|
||||
if account is None:
|
||||
raise HTTPException(status_code=401, detail="未登录")
|
||||
try:
|
||||
account.monthly_target = body.monthly_target
|
||||
apply_start(account, body.day, body.hour, body.minute, body.second)
|
||||
account.study_schedule_enabled = bool(body.enabled)
|
||||
apply_workers(account, body.workers)
|
||||
except (StudyWindowError, CourseWorkersError) as exc:
|
||||
db.rollback()
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
db.commit()
|
||||
from euniv.autostudy import sync_work
|
||||
|
||||
sync_work(account.employee_id)
|
||||
payload = view_of(account)
|
||||
payload["monthly_target"] = account.monthly_target
|
||||
payload["workers"] = account.course_workers
|
||||
return payload
|
||||
|
||||
|
||||
@app.get("/api/settings/course-workers")
|
||||
def get_course_workers(request: Request, db: Session = Depends(get_db)) -> dict:
|
||||
from euniv.course_workers import view_of
|
||||
@@ -418,6 +456,9 @@ def put_proxy(body: ProxyBody, request: Request, db: Session = Depends(get_db))
|
||||
except ProxyError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
db.commit()
|
||||
from euniv.autostudy import restart_work
|
||||
|
||||
restart_work(account.employee_id)
|
||||
return view_of(account)
|
||||
|
||||
|
||||
@@ -430,13 +471,16 @@ def delete_proxy(request: Request, db: Session = Depends(get_db)) -> dict:
|
||||
raise HTTPException(status_code=401, detail="未登录")
|
||||
clear(account)
|
||||
db.commit()
|
||||
from euniv.autostudy import restart_work
|
||||
|
||||
restart_work(account.employee_id)
|
||||
return view_of(account)
|
||||
|
||||
|
||||
@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 assemble, settle
|
||||
from euniv.study_control import assemble, settle, stamp_frame
|
||||
|
||||
employee_id = _signed_in(request, db)
|
||||
account = db.get(Account, employee_id)
|
||||
|
||||
@@ -424,6 +424,14 @@ def sync_work(employee_id: str) -> None:
|
||||
halt_work(key)
|
||||
|
||||
|
||||
def restart_work(employee_id: str) -> None:
|
||||
"""代理或学习配置变了,正在跑的这一轮先停掉,再按新配置评估。"""
|
||||
key = (employee_id or "").strip()
|
||||
if key and work_running(key):
|
||||
halt_work(key)
|
||||
sync_work(key)
|
||||
|
||||
|
||||
_KIND_RANK = {"视频": 0, "文档": 1, "课程包": 2, "课程": 3}
|
||||
|
||||
|
||||
|
||||
@@ -157,6 +157,25 @@ def _run(trigger: str) -> None:
|
||||
_running = False
|
||||
|
||||
|
||||
def _cool_failed_sync(employee_id: str, *, invalid: bool = False) -> None:
|
||||
from euniv.db import SessionLocal
|
||||
|
||||
if not employee_id:
|
||||
return
|
||||
with SessionLocal() as db:
|
||||
sync = db.get(CourseSync, 1)
|
||||
if sync is None:
|
||||
sync = CourseSync(id=1, last_employee_id=employee_id, course_count=0)
|
||||
db.add(sync)
|
||||
sync.last_employee_id = employee_id
|
||||
sync.next_allowed_at = datetime.now(timezone.utc) + timedelta(minutes=30)
|
||||
if invalid:
|
||||
account = db.get(Account, employee_id)
|
||||
if account is not None:
|
||||
account.credential_valid = False
|
||||
db.commit()
|
||||
|
||||
|
||||
def _fetch_and_store(trigger: str) -> bool:
|
||||
from euniv.client import EunivClient
|
||||
from euniv.crypto import decrypt_secret
|
||||
@@ -184,6 +203,7 @@ def _fetch_and_store(trigger: str) -> bool:
|
||||
try:
|
||||
client.restore(credential)
|
||||
if not client.credential_alive():
|
||||
_cool_failed_sync(employee_id, invalid=True)
|
||||
return False
|
||||
courses = client.list_courses()
|
||||
last_exc = None
|
||||
@@ -194,10 +214,12 @@ def _fetch_and_store(trigger: str) -> bool:
|
||||
mark_failed(employee_id, proxy, str(exc)[:200])
|
||||
proxy = bind_url(account)
|
||||
continue
|
||||
_cool_failed_sync(employee_id)
|
||||
return False
|
||||
finally:
|
||||
client.close()
|
||||
if last_exc is not None or not courses:
|
||||
_cool_failed_sync(employee_id)
|
||||
return False
|
||||
with SessionLocal() as db:
|
||||
db.execute(delete(Course))
|
||||
|
||||
@@ -48,6 +48,8 @@ _assign_lock = threading.Lock()
|
||||
_holds: dict[str, int] = {}
|
||||
_refresh_lock = threading.Lock()
|
||||
_stop: threading.Event | None = None
|
||||
_probe_guard = threading.Lock()
|
||||
_probe_state = {"running": False, "count": 0, "error": ""}
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
@@ -507,7 +509,44 @@ def probe_one(node_id: int) -> dict:
|
||||
return view_item(node)
|
||||
|
||||
|
||||
def request_probe(ids: list[int] | None = None) -> dict:
|
||||
"""整表探测放到后台,避免一次请求卡住到超时。"""
|
||||
with _probe_guard:
|
||||
if _probe_state["running"]:
|
||||
return {"running": True, "count": _probe_state["count"], "items": []}
|
||||
_probe_state["running"] = True
|
||||
_probe_state["error"] = ""
|
||||
_probe_state["count"] = 0
|
||||
|
||||
def work() -> None:
|
||||
try:
|
||||
result = probe_ids(ids)
|
||||
with _probe_guard:
|
||||
_probe_state["count"] = int(result.get("count") or 0)
|
||||
_probe_state["error"] = ""
|
||||
except Exception as exc:
|
||||
with _probe_guard:
|
||||
_probe_state["error"] = str(exc)[:200]
|
||||
finally:
|
||||
with _probe_guard:
|
||||
_probe_state["running"] = False
|
||||
|
||||
threading.Thread(target=work, name="euniv-proxy-probe", daemon=True).start()
|
||||
return {"running": True, "count": 0, "items": []}
|
||||
|
||||
|
||||
def probe_state() -> dict:
|
||||
with _probe_guard:
|
||||
return {
|
||||
"running": _probe_state["running"],
|
||||
"count": _probe_state["count"],
|
||||
"error": _probe_state["error"],
|
||||
}
|
||||
|
||||
|
||||
def probe_ids(ids: list[int] | None = None) -> dict:
|
||||
if ids is not None and not ids:
|
||||
return {"ok": True, "count": 0, "items": []}
|
||||
with SessionLocal() as db:
|
||||
if ids:
|
||||
wanted = []
|
||||
|
||||
@@ -38,7 +38,7 @@ def _credential_lock(employee_id: str) -> threading.Lock:
|
||||
with _credential_guard:
|
||||
lock = _credential_locks.get(employee_id)
|
||||
if lock is None:
|
||||
lock = threading.Lock()
|
||||
lock = threading.RLock()
|
||||
_credential_locks[employee_id] = lock
|
||||
return lock
|
||||
|
||||
@@ -104,6 +104,11 @@ def _drop_employee(employee_id: str) -> None:
|
||||
|
||||
|
||||
def _persist(db: Session, employee_id: str, password: str | None, client: EunivClient, profile: dict) -> None:
|
||||
with _credential_lock(employee_id):
|
||||
_persist_locked(db, employee_id, password, client, profile)
|
||||
|
||||
|
||||
def _persist_locked(db: Session, employee_id: str, password: str | None, client: EunivClient, profile: dict) -> None:
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
client.authorize(profile)
|
||||
@@ -421,6 +426,7 @@ def _live(db: Session, employee_id: str, client_factory, read):
|
||||
credential = json.loads(decrypt_secret(account.credential_cipher))
|
||||
attempts = _auto_attempts(db)
|
||||
password = decrypt_secret(account.password_cipher) if account.password_cipher else ""
|
||||
db.commit()
|
||||
last_exc: BaseException | None = None
|
||||
for _ in range(MAX_SWITCHES + 1):
|
||||
client = _client(client_factory, employee_id, password, account)
|
||||
@@ -515,14 +521,19 @@ def _refresh_one(employee_id: str, attempts: int, client_factory) -> None:
|
||||
|
||||
password = decrypt_secret(account.password_cipher)
|
||||
previous = json.loads(decrypt_secret(account.credential_cipher))
|
||||
db.commit()
|
||||
for _ in range(MAX_SWITCHES + 1):
|
||||
client = _client(client_factory, employee_id, password, account)
|
||||
try:
|
||||
client.restore(previous)
|
||||
if client.credential_alive():
|
||||
updated = client.export_credential()
|
||||
if _dump(updated) != _dump(previous):
|
||||
account.credential_cipher = encrypt_secret(_dump(updated))
|
||||
with _credential_lock(employee_id):
|
||||
db.refresh(account)
|
||||
current_raw = account.credential_cipher
|
||||
current = json.loads(decrypt_secret(current_raw)) if current_raw else {}
|
||||
if current_raw and _dump(current) == _dump(previous) and _dump(updated) != _dump(previous):
|
||||
account.credential_cipher = encrypt_secret(_dump(updated))
|
||||
valid = True
|
||||
checked_alive = True
|
||||
elif is_qr_password(password):
|
||||
|
||||
Reference in New Issue
Block a user