fix: 全部检查跳过已删除账号,未捕获异常不再把内部错误返回给页面
This commit is contained in:
@@ -11,6 +11,7 @@ from admin.session import admin_session_active, clear_admin_session, write_admin
|
|||||||
from admin.settings import SettingsError, load_config, login_config_view, save_settings, settings_view
|
from admin.settings import SettingsError, load_config, login_config_view, save_settings, settings_view
|
||||||
from admin.users import (
|
from admin.users import (
|
||||||
check_all,
|
check_all,
|
||||||
|
check_state,
|
||||||
check_employee,
|
check_employee,
|
||||||
clear_proxy,
|
clear_proxy,
|
||||||
delete_user,
|
delete_user,
|
||||||
@@ -181,10 +182,15 @@ def get_users(db: Session = Depends(get_db), _: str = Depends(require_admin)) ->
|
|||||||
|
|
||||||
|
|
||||||
@admin_router.post("/users/check-all")
|
@admin_router.post("/users/check-all")
|
||||||
def post_check_all(db: Session = Depends(get_db), _: str = Depends(require_admin)) -> list[dict]:
|
def post_check_all(db: Session = Depends(get_db), _: str = Depends(require_admin)) -> list[dict] | dict:
|
||||||
return check_all(db)
|
return check_all(db)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_router.get("/users/check-all")
|
||||||
|
def get_check_all(_: str = Depends(require_admin)) -> dict:
|
||||||
|
return check_state()
|
||||||
|
|
||||||
|
|
||||||
@admin_router.post("/users/{employee_id}/check")
|
@admin_router.post("/users/{employee_id}/check")
|
||||||
def post_check(employee_id: str, db: Session = Depends(get_db), _: str = Depends(require_admin)) -> dict:
|
def post_check(employee_id: str, db: Session = Depends(get_db), _: str = Depends(require_admin)) -> dict:
|
||||||
return check_employee(db, employee_id)
|
return check_employee(db, employee_id)
|
||||||
|
|||||||
+63
-10
@@ -3,6 +3,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
import threading
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
from fastapi import HTTPException
|
from fastapi import HTTPException
|
||||||
@@ -159,7 +160,58 @@ def check_employee(db: Session, employee_id: str) -> dict:
|
|||||||
return payload
|
return payload
|
||||||
|
|
||||||
|
|
||||||
def check_all(db: Session) -> list[dict]:
|
def _check_saved(db: Session, employee_ids: list[str]) -> list[dict]:
|
||||||
|
results = []
|
||||||
|
for employee_id in employee_ids:
|
||||||
|
try:
|
||||||
|
results.append(check_employee(db, employee_id))
|
||||||
|
except HTTPException as exc:
|
||||||
|
if exc.status_code == 404:
|
||||||
|
continue
|
||||||
|
raise
|
||||||
|
except Exception:
|
||||||
|
results.append({"employee_id": employee_id, "result": "检查失败", "detail": "检查失败"})
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
_CHECK_INLINE = 8
|
||||||
|
_check_guard = threading.Lock()
|
||||||
|
_check_running = False
|
||||||
|
_check_results: list[dict] = []
|
||||||
|
_check_error = ""
|
||||||
|
|
||||||
|
|
||||||
|
def check_state() -> dict:
|
||||||
|
with _check_guard:
|
||||||
|
return {"running": _check_running, "results": list(_check_results), "error": _check_error}
|
||||||
|
|
||||||
|
|
||||||
|
def _run_check(employee_ids: list[str]) -> None:
|
||||||
|
global _check_running, _check_results, _check_error
|
||||||
|
from euniv.db import SessionLocal
|
||||||
|
|
||||||
|
results: list[dict] = []
|
||||||
|
error = ""
|
||||||
|
try:
|
||||||
|
for employee_id in employee_ids:
|
||||||
|
with SessionLocal() as db:
|
||||||
|
try:
|
||||||
|
results.append(check_employee(db, employee_id))
|
||||||
|
except HTTPException as exc:
|
||||||
|
if exc.status_code != 404:
|
||||||
|
raise
|
||||||
|
except Exception:
|
||||||
|
results.append({"employee_id": employee_id, "result": "检查失败", "detail": "检查失败"})
|
||||||
|
except Exception:
|
||||||
|
error = "检查失败"
|
||||||
|
with _check_guard:
|
||||||
|
_check_results = results
|
||||||
|
_check_error = error
|
||||||
|
_check_running = False
|
||||||
|
|
||||||
|
|
||||||
|
def check_all(db: Session) -> list[dict] | dict:
|
||||||
|
global _check_running
|
||||||
employee_ids = list(
|
employee_ids = list(
|
||||||
db.scalars(
|
db.scalars(
|
||||||
select(Account.employee_id)
|
select(Account.employee_id)
|
||||||
@@ -167,15 +219,16 @@ def check_all(db: Session) -> list[dict]:
|
|||||||
.order_by(Account.employee_id)
|
.order_by(Account.employee_id)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
results = []
|
if len(employee_ids) <= _CHECK_INLINE:
|
||||||
for employee_id in employee_ids:
|
return _check_saved(db, employee_ids)
|
||||||
try:
|
with _check_guard:
|
||||||
results.append(check_employee(db, employee_id))
|
if _check_running:
|
||||||
except HTTPException:
|
return check_state()
|
||||||
raise
|
_check_running = True
|
||||||
except Exception:
|
_check_results = []
|
||||||
results.append({"employee_id": employee_id, "result": "检查失败", "detail": "检查失败"})
|
_check_error = ""
|
||||||
return results
|
threading.Thread(target=_run_check, args=(employee_ids,), name="euniv-check-all", daemon=True).start()
|
||||||
|
return {"running": True, "results": [], "error": ""}
|
||||||
|
|
||||||
|
|
||||||
def set_paused(db: Session, employee_id: str, paused: bool) -> dict:
|
def set_paused(db: Session, employee_id: str, paused: bool) -> dict:
|
||||||
|
|||||||
@@ -153,6 +153,15 @@ def reject_bad_body(_request: Request, exc: RequestValidationError) -> JSONRespo
|
|||||||
return JSONResponse(status_code=422, content={"detail": "请求格式不正确"})
|
return JSONResponse(status_code=422, content={"detail": "请求格式不正确"})
|
||||||
|
|
||||||
|
|
||||||
|
@app.exception_handler(Exception)
|
||||||
|
def reject_unexpected(_request: Request, exc: Exception) -> JSONResponse:
|
||||||
|
if isinstance(exc, HTTPException):
|
||||||
|
detail = exc.detail if isinstance(exc.detail, str) else "请求没有完成"
|
||||||
|
return JSONResponse(status_code=exc.status_code, content={"detail": detail})
|
||||||
|
logging.getLogger("euniv.api").exception("请求没有完成")
|
||||||
|
return JSONResponse(status_code=500, content={"detail": "服务暂时不可用"})
|
||||||
|
|
||||||
|
|
||||||
class LoginBody(BaseModel):
|
class LoginBody(BaseModel):
|
||||||
employee_id: str = Field(min_length=1, max_length=64)
|
employee_id: str = Field(min_length=1, max_length=64)
|
||||||
password: str = Field(min_length=1, max_length=128)
|
password: str = Field(min_length=1, max_length=128)
|
||||||
|
|||||||
@@ -53,3 +53,36 @@ def fresh_database():
|
|||||||
users = autostudy_mod._status.get("users")
|
users = autostudy_mod._status.get("users")
|
||||||
if isinstance(users, dict):
|
if isinstance(users, dict):
|
||||||
users.clear()
|
users.clear()
|
||||||
|
from euniv import encrypt as encrypt_mod
|
||||||
|
from euniv import service as service_mod
|
||||||
|
from euniv import study_push
|
||||||
|
|
||||||
|
for pending in list(service_mod._pending.values()) + list(service_mod._pending_qr.values()):
|
||||||
|
client = getattr(pending, "client", None)
|
||||||
|
if client is not None:
|
||||||
|
try:
|
||||||
|
client.close()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
service_mod._pending.clear()
|
||||||
|
service_mod._pending_qr.clear()
|
||||||
|
service_mod._pending_busy.clear()
|
||||||
|
for handle in list(study_push._pending.values()):
|
||||||
|
handle.cancel()
|
||||||
|
study_push._pending.clear()
|
||||||
|
study_push._inflight.clear()
|
||||||
|
study_push._dirty.clear()
|
||||||
|
study_push._urgent.clear()
|
||||||
|
study_push._last_flush.clear()
|
||||||
|
study_push._clients.clear()
|
||||||
|
study_push._loop = None
|
||||||
|
with encrypt_mod._lock:
|
||||||
|
encrypt_mod._config.clear()
|
||||||
|
encrypt_mod._config.update(
|
||||||
|
{
|
||||||
|
"path": encrypt_mod.DEFAULT_ENCRYPT_PATH,
|
||||||
|
"js_url": encrypt_mod.DEFAULT_JS_URL,
|
||||||
|
"loaded_at": 0.0,
|
||||||
|
"retry_at": 0.0,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|||||||
@@ -297,6 +297,28 @@ async function checkOne(row: UserRow) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function applyCheckResults(payload: unknown) {
|
||||||
|
if (!Array.isArray(payload)) {
|
||||||
|
errorText.value = "检查失败";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const next = { ...liveResults.value };
|
||||||
|
const notes: string[] = [];
|
||||||
|
for (const item of payload) {
|
||||||
|
if (!isRecord(item) || item.employee_id == null) continue;
|
||||||
|
const employeeId = String(item.employee_id);
|
||||||
|
const label = checkLabel(item);
|
||||||
|
next[employeeId] = label;
|
||||||
|
if (label === "检查失败") {
|
||||||
|
const detail = typeof item.detail === "string" ? item.detail : "";
|
||||||
|
if (detail) notes.push(`${employeeId}:${detail}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
liveResults.value = next;
|
||||||
|
errorText.value = notes.join(";");
|
||||||
|
await load();
|
||||||
|
}
|
||||||
|
|
||||||
async function checkAll() {
|
async function checkAll() {
|
||||||
if (checkingId.value || checkingAll.value || !users.value.length) return;
|
if (checkingId.value || checkingAll.value || !users.value.length) return;
|
||||||
checkingAll.value = true;
|
checkingAll.value = true;
|
||||||
@@ -308,25 +330,27 @@ async function checkAll() {
|
|||||||
errorText.value = detailOf(payload, "检查失败");
|
errorText.value = detailOf(payload, "检查失败");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!Array.isArray(payload)) {
|
if (isRecord(payload) && payload.running === true) {
|
||||||
errorText.value = detailOf(payload, "检查失败");
|
for (let attempt = 0; attempt < 120; attempt += 1) {
|
||||||
|
await new Promise((resolve) => window.setTimeout(resolve, 1000));
|
||||||
|
const status = await apiFetch("/api/admin/users/check-all");
|
||||||
|
const body: unknown = await status.json().catch(() => ({}));
|
||||||
|
if (!status.ok || !isRecord(body)) {
|
||||||
|
errorText.value = "检查失败";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (body.running === true) continue;
|
||||||
|
if (typeof body.error === "string" && body.error) {
|
||||||
|
errorText.value = body.error;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await applyCheckResults(body.results);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
errorText.value = "检查失败";
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const next = { ...liveResults.value };
|
await applyCheckResults(payload);
|
||||||
const notes: string[] = [];
|
|
||||||
for (const item of payload) {
|
|
||||||
if (!isRecord(item) || item.employee_id == null) continue;
|
|
||||||
const employeeId = String(item.employee_id);
|
|
||||||
const label = checkLabel(item);
|
|
||||||
next[employeeId] = label;
|
|
||||||
if (label === "检查失败") {
|
|
||||||
const detail = typeof item.detail === "string" ? item.detail : "";
|
|
||||||
if (detail) notes.push(`${employeeId}:${detail}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
liveResults.value = next;
|
|
||||||
errorText.value = notes.join(";");
|
|
||||||
await load();
|
|
||||||
} catch {
|
} catch {
|
||||||
errorText.value = "检查失败";
|
errorText.value = "检查失败";
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
Reference in New Issue
Block a user