fix: 注销后关掉学习连接,目标为零不再显示成零比零

This commit is contained in:
2026-11-16 15:57:23 +08:00
parent 1cd7c7f818
commit 58b3dedb2a
8 changed files with 97 additions and 16 deletions
+7 -1
View File
@@ -8,6 +8,7 @@ from __future__ import annotations
import hmac import hmac
import threading import threading
from contextlib import contextmanager
from admin.passwords import is_hashed, verify_password from admin.passwords import is_hashed, verify_password
from euniv.crypto import decrypt_secret from euniv.crypto import decrypt_secret
@@ -17,7 +18,12 @@ class AdminIdentity:
def __init__(self) -> None: def __init__(self) -> None:
self._username = "" self._username = ""
self._password_cipher = "" self._password_cipher = ""
self._lock = threading.Lock() self._lock = threading.RLock()
@contextmanager
def exclusive(self):
with self._lock:
yield
def replace(self, username: str, password_cipher: str) -> None: def replace(self, username: str, password_cipher: str) -> None:
with self._lock: with self._lock:
+3 -2
View File
@@ -260,8 +260,9 @@ def save_settings(db: Session, payload: dict) -> SystemConfig:
row.admin_password_cipher = hash_password(password_text) row.admin_password_cipher = hash_password(password_text)
if previous_username != username or password_text: if previous_username != username or password_text:
row.admin_sessions_valid_after = datetime.now(timezone.utc) row.admin_sessions_valid_after = datetime.now(timezone.utc)
db.commit() with identity.exclusive():
identity.replace(row.admin_username, row.admin_password_cipher) db.commit()
identity.replace(row.admin_username, row.admin_password_cipher)
if interval != previous_interval: if interval != previous_interval:
from euniv.service import notify_refresh_interval_changed from euniv.service import notify_refresh_interval_changed
+2
View File
@@ -316,8 +316,10 @@ def delete_user(db: Session, employee_id: str) -> dict:
db.delete(account) db.delete(account)
db.commit() db.commit()
from euniv.autostudy import stop_account from euniv.autostudy import stop_account
from euniv.study_push import close_account
stop_account(employee_id) stop_account(employee_id)
close_account(employee_id)
from euniv.service import release_credential_lock from euniv.service import release_credential_lock
release_credential_lock(employee_id) release_credential_lock(employee_id)
+33 -12
View File
@@ -16,6 +16,8 @@ logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("httpcore").setLevel(logging.WARNING) logging.getLogger("httpcore").setLevel(logging.WARNING)
from fastapi import Depends, FastAPI, HTTPException, Request, Response, WebSocket, WebSocketDisconnect from fastapi import Depends, FastAPI, HTTPException, Request, Response, WebSocket, WebSocketDisconnect
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
@@ -47,7 +49,7 @@ from euniv.session import clear_session, write_session
class MonthlyTargetBody(BaseModel): class MonthlyTargetBody(BaseModel):
monthly_target: int = Field(strict=True) monthly_target: int = Field(strict=True, ge=0, le=9999)
class ProxyBody(BaseModel): class ProxyBody(BaseModel):
@@ -59,25 +61,25 @@ class ProxyBody(BaseModel):
class StudyStartBody(BaseModel): class StudyStartBody(BaseModel):
day: int = Field(strict=True) day: int = Field(strict=True, ge=5, le=25)
hour: int = Field(strict=True) hour: int = Field(strict=True, ge=0, le=23)
minute: int = Field(strict=True) minute: int = Field(strict=True, ge=0, le=59)
second: int = Field(strict=True) second: int = Field(strict=True, ge=0, le=59)
enabled: bool | None = None enabled: bool | None = None
class CourseWorkersBody(BaseModel): class CourseWorkersBody(BaseModel):
workers: int = Field(strict=True) workers: int = Field(strict=True, ge=1, le=8)
class StudyBundleBody(BaseModel): class StudyBundleBody(BaseModel):
monthly_target: int = Field(strict=True) monthly_target: int = Field(strict=True, ge=0, le=9999)
day: int = Field(strict=True) day: int = Field(strict=True, ge=5, le=25)
hour: int = Field(strict=True) hour: int = Field(strict=True, ge=0, le=23)
minute: int = Field(strict=True) minute: int = Field(strict=True, ge=0, le=59)
second: int = Field(strict=True) second: int = Field(strict=True, ge=0, le=59)
enabled: bool = True enabled: bool = True
workers: int = Field(strict=True) workers: int = Field(strict=True, ge=1, le=8)
class StudyControlBody(BaseModel): class StudyControlBody(BaseModel):
@@ -131,6 +133,25 @@ app = FastAPI(
app.include_router(public_router) app.include_router(public_router)
app.include_router(admin_router) app.include_router(admin_router)
_FIELD_ERRORS = {
"monthly_target": "每月学时目标须为 0 到 9999 的整数",
"day": "每月开始日须为 5 到 25 的整数",
"hour": "每月开始时须为 0 到 23 的整数",
"minute": "每月开始分须为 0 到 59 的整数",
"second": "每月开始秒须为 0 到 59 的整数",
"workers": "同时学习课程数须为 1 到 8",
}
@app.exception_handler(RequestValidationError)
def reject_bad_body(_request: Request, exc: RequestValidationError) -> JSONResponse:
for item in exc.errors():
loc = item.get("loc") or ()
name = loc[-1] if loc else ""
if isinstance(name, str) and name in _FIELD_ERRORS:
return JSONResponse(status_code=400, content={"detail": _FIELD_ERRORS[name]})
return JSONResponse(status_code=422, 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)
+2
View File
@@ -519,8 +519,10 @@ def revoke_credential(db: Session, employee_id: str) -> None:
account.sessions_valid_after = datetime.now(timezone.utc) account.sessions_valid_after = datetime.now(timezone.utc)
db.commit() db.commit()
from euniv.autostudy import stop_account from euniv.autostudy import stop_account
from euniv.study_push import close_account
stop_account(employee_id) stop_account(employee_id)
close_account(employee_id)
release_credential_lock(employee_id) release_credential_lock(employee_id)
+28
View File
@@ -49,6 +49,34 @@ def unregister(employee_id: str, ws: WebSocket) -> None:
_last_flush.pop(key, None) _last_flush.pop(key, None)
def close_account(employee_id: str) -> None:
"""注销或删除后关掉这个账号已经打开的学习状态连接。"""
key = (employee_id or "").strip()
if not key:
return
loop = _loop
if loop is None or not loop.is_running():
_drop_account(key)
return
loop.call_soon_threadsafe(_drop_account, key)
def _drop_account(key: str) -> None:
handle = _pending.pop(key, None)
if handle is not None:
handle.cancel()
_dirty.discard(key)
_urgent.discard(key)
_inflight.discard(key)
_last_flush.pop(key, None)
sockets = list(_clients.pop(key, ()))
for ws in sockets:
try:
asyncio.get_running_loop().create_task(ws.close(code=4401))
except RuntimeError:
pass
def notify(employee_id: str | None = None, urgent: bool = False) -> None: def notify(employee_id: str | None = None, urgent: bool = False) -> None:
loop = _loop loop = _loop
if loop is None or not loop.is_running(): if loop is None or not loop.is_running():
+20
View File
@@ -53,3 +53,23 @@ def test_study_push_throttles_and_only_sends_latest(monkeypatch) -> None:
study_push.unregister("u1", socket) study_push.unregister("u1", socket)
asyncio.run(main()) asyncio.run(main())
def test_close_account_drops_open_socket() -> None:
closed: list[int] = []
class Socket(_Socket):
async def close(self, code: int = 1000) -> None:
closed.append(code)
socket = Socket()
async def main() -> None:
study_push._clients.clear()
study_push.attach_loop(asyncio.get_running_loop())
study_push.register("gone", socket)
study_push.close_account("gone")
await _until(lambda: closed == [4401])
assert "gone" not in study_push._clients
asyncio.run(main())
+2 -1
View File
@@ -887,7 +887,8 @@ onUnmounted(() => {
<div v-if="targetLoaded" class="study-progress"> <div v-if="targetLoaded" class="study-progress">
<div class="study-progress-meta"> <div class="study-progress-meta">
<span>本月进度</span> <span>本月进度</span>
<span>{{ monthProgress.current }} / {{ monthProgress.target }} 分钟</span> <span v-if="monthProgress.target > 0">{{ monthProgress.current }} / {{ monthProgress.target }} 分钟</span>
<span v-else>{{ monthProgress.current }} 分钟</span>
</div> </div>
<n-progress type="line" :percentage="monthProgress.pct" :show-indicator="false" :height="6" /> <n-progress type="line" :percentage="monthProgress.pct" :show-indicator="false" :height="6" />
</div> </div>