fix: 清掉无用接口和样式,并收紧登录与工号边界

This commit is contained in:
2026-11-16 11:30:59 +08:00
parent 7381b49e4c
commit 5b83b7e415
15 changed files with 232 additions and 329 deletions
+6 -6
View File
@@ -2,7 +2,7 @@
from __future__ import annotations from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException, Request, Response from fastapi import APIRouter, Depends, HTTPException, Path, Query, Request, Response
from pydantic import BaseModel from pydantic import BaseModel
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
@@ -130,8 +130,8 @@ def post_courses_load(_: str = Depends(require_admin)) -> dict:
def get_courses( def get_courses(
q: str = "", q: str = "",
kind: str = "", kind: str = "",
offset: int = 0, offset: int = Query(default=0, ge=0, le=10**9),
limit: int = 50, limit: int = Query(default=50, ge=1, le=10**9),
db: Session = Depends(get_db), db: Session = Depends(get_db),
_: str = Depends(require_admin), _: str = Depends(require_admin),
) -> dict: ) -> dict:
@@ -144,8 +144,8 @@ def get_courses(
def get_proxies( def get_proxies(
q: str = "", q: str = "",
status: str = "", status: str = "",
offset: int = 0, offset: int = Query(default=0, ge=0, le=10**9),
limit: int = 50, limit: int = Query(default=50, ge=1, le=10**9),
db: Session = Depends(get_db), db: Session = Depends(get_db),
_: str = Depends(require_admin), _: str = Depends(require_admin),
) -> dict: ) -> dict:
@@ -168,7 +168,7 @@ def get_proxies_probe(_: str = Depends(require_admin)) -> dict:
@admin_router.post("/proxies/{proxy_id}/probe") @admin_router.post("/proxies/{proxy_id}/probe")
def post_proxy_probe(proxy_id: int, _: str = Depends(require_admin)) -> dict: def post_proxy_probe(proxy_id: int = Path(ge=1, le=10**9), _: str = Depends(require_admin)) -> dict:
try: try:
return probe_proxy_one(proxy_id) return probe_proxy_one(proxy_id)
except ProxyProbeError as exc: except ProxyProbeError as exc:
+3 -70
View File
@@ -14,14 +14,12 @@ from euniv.models import Account
from euniv.course_workers import CourseWorkersError from euniv.course_workers import CourseWorkersError
from euniv.course_workers import apply as apply_workers from euniv.course_workers import apply as apply_workers
from euniv.course_workers import of as workers_of from euniv.course_workers import of as workers_of
from euniv.course_workers import view_of as workers_view
from euniv.proxy import ProxyError, apply, clear, enabled, summary_of, url_of, view_of from euniv.proxy import ProxyError, apply, clear, enabled, summary_of, url_of, view_of
from euniv.study_control import start_now, stop_now from euniv.study_control import start_now, stop_now
from euniv.study_control import view_of as study_view from euniv.study_control import view_of as study_view
from euniv.study_window import StudyWindowError from euniv.study_window import StudyWindowError
from euniv.study_window import apply as apply_start from euniv.study_window import apply as apply_start
from euniv.study_window import label_of as start_label from euniv.study_window import label_of as start_label
from euniv.study_window import view_of as start_view
_TOKEN_KEYS = ( _TOKEN_KEYS = (
"ucs_token", "ucs_token",
@@ -119,8 +117,6 @@ def check_employee(db: Session, employee_id: str) -> dict:
account = _require(db, employee_id) account = _require(db, employee_id)
if not account.credential_cipher: if not account.credential_cipher:
return {"employee_id": employee_id, "result": "未保存"} return {"employee_id": employee_id, "result": "未保存"}
before_password = account.password_cipher
before_credential = account.credential_cipher
password = decrypt_secret(account.password_cipher) if account.password_cipher else "" password = decrypt_secret(account.password_cipher) if account.password_cipher else ""
credential = json.loads(decrypt_secret(account.credential_cipher)) credential = json.loads(decrypt_secret(account.credential_cipher))
pooled = uses_pool(account) pooled = uses_pool(account)
@@ -158,9 +154,6 @@ def check_employee(db: Session, employee_id: str) -> dict:
pass pass
if account is None: if account is None:
raise HTTPException(status_code=404, detail="用户不存在") raise HTTPException(status_code=404, detail="用户不存在")
if result != "检查失败":
account.password_cipher = before_password
account.credential_cipher = before_credential
record_outcome(account, valid) record_outcome(account, valid)
db.commit() db.commit()
payload = {"employee_id": employee_id, "result": result} payload = {"employee_id": employee_id, "result": result}
@@ -240,30 +233,6 @@ def read_proxy(db: Session, employee_id: str) -> dict:
return view_of(_require(db, employee_id)) return view_of(_require(db, employee_id))
def set_proxy(
db: Session,
employee_ids: list[str],
scheme: str,
host: str = "",
port: object = None,
username: str = "",
password: str | None = None,
) -> dict:
accounts = _accounts_by_ids(db, employee_ids)
try:
for account in accounts:
apply(account, scheme, host, port, username, password)
except ProxyError as exc:
db.rollback()
raise HTTPException(status_code=400, detail=str(exc)) from exc
db.commit()
from euniv.autostudy import restart_work
for account in accounts:
restart_work(account.employee_id)
return {"ok": True, "count": len(accounts)}
def clear_proxy(db: Session, employee_ids: list[str]) -> dict: def clear_proxy(db: Session, employee_ids: list[str]) -> dict:
accounts = _accounts_by_ids(db, employee_ids) accounts = _accounts_by_ids(db, employee_ids)
for account in accounts: for account in accounts:
@@ -276,45 +245,6 @@ def clear_proxy(db: Session, employee_ids: list[str]) -> dict:
return {"ok": True, "count": len(accounts)} return {"ok": True, "count": len(accounts)}
def read_study_start(db: Session, employee_id: str) -> dict:
return start_view(_require(db, employee_id))
def set_study_start(
db: Session,
employee_ids: list[str],
day: int,
hour: int,
minute: int,
second: int,
) -> dict:
accounts = _accounts_by_ids(db, employee_ids)
try:
for account in accounts:
apply_start(account, day, hour, minute, second)
except StudyWindowError as exc:
db.rollback()
raise HTTPException(status_code=400, detail=str(exc)) from exc
db.commit()
return {"ok": True, "count": len(accounts)}
def read_course_workers(db: Session, employee_id: str) -> dict:
return workers_view(_require(db, employee_id))
def set_course_workers(db: Session, employee_ids: list[str], workers: int) -> dict:
accounts = _accounts_by_ids(db, employee_ids)
try:
for account in accounts:
apply_workers(account, workers)
except CourseWorkersError as exc:
db.rollback()
raise HTTPException(status_code=400, detail=str(exc)) from exc
db.commit()
return {"ok": True, "count": len(accounts)}
def set_study_action(db: Session, employee_ids: list[str], action: str) -> dict: def set_study_action(db: Session, employee_ids: list[str], action: str) -> dict:
kind = (action or "").strip().lower() kind = (action or "").strip().lower()
if kind not in {"start", "stop"}: if kind not in {"start", "stop"}:
@@ -391,4 +321,7 @@ def delete_user(db: Session, employee_id: str) -> dict:
from euniv.autostudy import stop_account from euniv.autostudy import stop_account
stop_account(employee_id) stop_account(employee_id)
from euniv.service import release_credential_lock
release_credential_lock(employee_id)
return {"ok": True} return {"ok": True}
@@ -0,0 +1,45 @@
"""工号列加长到 64,并去掉只写不读的课程数量。"""
from alembic import op
import sqlalchemy as sa
revision = "0006_employee_width"
down_revision = "0005_password_login_at"
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table("accounts") as batch:
batch.alter_column(
"employee_id",
existing_type=sa.String(length=32),
type_=sa.String(length=64),
existing_nullable=False,
)
with op.batch_alter_table("course_sync") as batch:
batch.alter_column(
"last_employee_id",
existing_type=sa.String(length=32),
type_=sa.String(length=64),
existing_nullable=False,
)
batch.drop_column("course_count")
def downgrade() -> None:
with op.batch_alter_table("course_sync") as batch:
batch.add_column(sa.Column("course_count", sa.Integer(), nullable=False, server_default="0"))
batch.alter_column(
"last_employee_id",
existing_type=sa.String(length=64),
type_=sa.String(length=32),
existing_nullable=False,
)
with op.batch_alter_table("accounts") as batch:
batch.alter_column(
"employee_id",
existing_type=sa.String(length=64),
type_=sa.String(length=32),
existing_nullable=False,
)
+85 -60
View File
@@ -45,45 +45,43 @@ from euniv.service import (
) )
from euniv.session import clear_session, write_session from euniv.session import clear_session, write_session
from pydantic import BaseModel as _BaseModel
class MonthlyTargetBody(BaseModel):
monthly_target: int = Field(strict=True)
class MonthlyTargetBody(_BaseModel): class ProxyBody(BaseModel):
monthly_target: int scheme: str = Field(min_length=1, max_length=16)
host: str = Field(default="", max_length=255)
port: int | None = Field(default=None, ge=1, le=65535)
username: str = Field(default="", max_length=128)
password: str | None = Field(default=None, max_length=128)
class ProxyBody(_BaseModel): class StudyStartBody(BaseModel):
scheme: str day: int = Field(strict=True)
host: str = "" hour: int = Field(strict=True)
port: int | None = None minute: int = Field(strict=True)
username: str = "" second: int = Field(strict=True)
password: str | None = None
class StudyStartBody(_BaseModel):
day: int
hour: int
minute: int
second: int
enabled: bool | None = None enabled: bool | None = None
class CourseWorkersBody(_BaseModel): class CourseWorkersBody(BaseModel):
workers: int workers: int = Field(strict=True)
class StudyBundleBody(_BaseModel): class StudyBundleBody(BaseModel):
monthly_target: int monthly_target: int = Field(strict=True)
day: int day: int = Field(strict=True)
hour: int hour: int = Field(strict=True)
minute: int minute: int = Field(strict=True)
second: int second: int = Field(strict=True)
enabled: bool = True enabled: bool = True
workers: int workers: int = Field(strict=True)
class StudyControlBody(_BaseModel): class StudyControlBody(BaseModel):
action: str action: str = Field(min_length=1, max_length=16)
@asynccontextmanager @asynccontextmanager
@@ -462,21 +460,6 @@ def put_proxy(body: ProxyBody, request: Request, db: Session = Depends(get_db))
return view_of(account) return view_of(account)
@app.delete("/api/settings/proxy")
def delete_proxy(request: Request, db: Session = Depends(get_db)) -> dict:
from euniv.proxy import clear, view_of
account = db.get(Account, _signed_in(request, db))
if account is None:
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") @app.get("/api/settings/study-control")
def get_study_control(request: Request, db: Session = Depends(get_db)) -> dict: def get_study_control(request: Request, db: Session = Depends(get_db)) -> dict:
from euniv.autostudy import autostudy_status from euniv.autostudy import autostudy_status
@@ -528,33 +511,61 @@ def post_study_control(body: StudyControlBody, request: Request, db: Session = D
return get_study_control(request, db) return get_study_control(request, db)
def _same_origin(websocket: WebSocket) -> bool:
origin = websocket.headers.get("origin", "")
if not origin:
return True
from urllib.parse import urlparse
origin_host = (urlparse(origin).hostname or "").lower()
request_host = websocket.headers.get("host", "").split(":")[0].strip("[]").lower()
return bool(origin_host) and origin_host == request_host
def _ws_gate(cookies: dict) -> tuple[int, str]:
from euniv.db import SessionLocal
from euniv.session import COOKIE_NAME, open_seal, still_valid
with SessionLocal() as db:
if admin_session_active(cookies, load_config(db).admin_sessions_valid_after):
return 4403, ""
opened = open_seal(cookies.get(COOKIE_NAME, ""), "user")
if opened is None:
return 4401, ""
employee_id, issued = opened
account = db.get(Account, employee_id)
if account is None or not still_valid(issued, account.sessions_valid_after):
return 4401, ""
return 0, employee_id
@app.websocket("/api/settings/study-control/ws") @app.websocket("/api/settings/study-control/ws")
async def study_control_ws(websocket: WebSocket): async def study_control_ws(websocket: WebSocket):
from euniv.study_control import payload_for from euniv.study_control import payload_for
from euniv.study_push import register, unregister from euniv.study_push import register, unregister
if not _same_origin(websocket):
await websocket.close(code=4403)
return
await websocket.accept() await websocket.accept()
from euniv.db import SessionLocal code, employee_id = await asyncio.to_thread(_ws_gate, dict(websocket.cookies))
from euniv.session import COOKIE_NAME, open_seal, still_valid if code:
await websocket.close(code=code)
with SessionLocal() as db: return
if admin_session_active(websocket.cookies, load_config(db).admin_sessions_valid_after):
await websocket.close(code=4403)
return
opened = open_seal(websocket.cookies.get(COOKIE_NAME, ""), "user")
if opened is None:
await websocket.close(code=4401)
return
employee_id, issued = opened
account = db.get(Account, employee_id)
if account is None or not still_valid(issued, account.sessions_valid_after):
await websocket.close(code=4401)
return
register(employee_id, websocket) register(employee_id, websocket)
last_message = 0.0
try: try:
await websocket.send_json(await asyncio.to_thread(payload_for, employee_id)) await websocket.send_json(await asyncio.to_thread(payload_for, employee_id))
while True: while True:
await websocket.receive_text() message = await websocket.receive()
if message.get("type") == "websocket.disconnect":
break
if "text" not in message:
continue
now = asyncio.get_running_loop().time()
if now - last_message < 1:
continue
last_message = now
await websocket.send_json(await asyncio.to_thread(payload_for, employee_id)) await websocket.send_json(await asyncio.to_thread(payload_for, employee_id))
except WebSocketDisconnect: except WebSocketDisconnect:
pass pass
@@ -578,6 +589,20 @@ def training_detail(path: str, request: Request, db: Session = Depends(get_db))
raise HTTPException(status_code=400, detail=str(exc)) from exc raise HTTPException(status_code=400, detail=str(exc)) from exc
@app.api_route("/api", methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"])
@app.api_route("/api/{rest:path}", methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"])
def api_fallback(rest: str = "") -> None:
raise HTTPException(status_code=405, detail="不支持该请求")
class _WebFiles(StaticFiles):
async def get_response(self, path: str, scope):
response = await super().get_response(path, scope)
if path in {"", "index.html"}:
response.headers["Cache-Control"] = "no-cache"
return response
_dist = Path(__file__).resolve().parents[2] / "web" / "dist" _dist = Path(__file__).resolve().parents[2] / "web" / "dist"
if _dist.is_dir(): if _dist.is_dir():
app.mount("/", StaticFiles(directory=_dist, html=True), name="web") app.mount("/", _WebFiles(directory=_dist, html=True), name="web")
+1 -2
View File
@@ -165,7 +165,7 @@ def _cool_failed_sync(employee_id: str, *, invalid: bool = False) -> None:
with SessionLocal() as db: with SessionLocal() as db:
sync = db.get(CourseSync, 1) sync = db.get(CourseSync, 1)
if sync is None: if sync is None:
sync = CourseSync(id=1, last_employee_id=employee_id, course_count=0) sync = CourseSync(id=1, last_employee_id=employee_id)
db.add(sync) db.add(sync)
sync.last_employee_id = employee_id sync.last_employee_id = employee_id
sync.next_allowed_at = datetime.now(timezone.utc) + timedelta(minutes=30) sync.next_allowed_at = datetime.now(timezone.utc) + timedelta(minutes=30)
@@ -231,7 +231,6 @@ def _fetch_and_store(trigger: str) -> bool:
sync.last_employee_id = employee_id sync.last_employee_id = employee_id
sync.finished_at = datetime.now(timezone.utc) sync.finished_at = datetime.now(timezone.utc)
sync.next_allowed_at = sync.finished_at + next_gap() sync.next_allowed_at = sync.finished_at + next_gap()
sync.course_count = len(courses)
db.commit() db.commit()
from euniv.autostudy import clear_study_hold, request_wake from euniv.autostudy import clear_study_hold, request_wake
+2 -3
View File
@@ -30,10 +30,9 @@ class CourseSync(Base):
__tablename__ = "course_sync" __tablename__ = "course_sync"
id: Mapped[int] = mapped_column(primary_key=True) id: Mapped[int] = mapped_column(primary_key=True)
last_employee_id: Mapped[str] = mapped_column(String(32), nullable=False, default="") last_employee_id: Mapped[str] = mapped_column(String(64), nullable=False, default="")
finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
next_allowed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) next_allowed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
course_count: Mapped[int] = mapped_column(nullable=False, default=0)
class FinishedCourse(Base): class FinishedCourse(Base):
@@ -50,7 +49,7 @@ class FinishedCourse(Base):
class Account(Base): class Account(Base):
__tablename__ = "accounts" __tablename__ = "accounts"
employee_id: Mapped[str] = mapped_column(String(32), primary_key=True) employee_id: Mapped[str] = mapped_column(String(64), primary_key=True)
password_cipher: Mapped[str] = mapped_column(Text) password_cipher: Mapped[str] = mapped_column(Text)
credential_cipher: Mapped[str] = mapped_column(Text, default="") credential_cipher: Mapped[str] = mapped_column(Text, default="")
refresh_paused: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=sql_false()) refresh_paused: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=sql_false())
+55 -27
View File
@@ -32,6 +32,8 @@ _pending: dict[str, "PendingLogin"] = {}
_pending_qr: dict[str, "PendingQr"] = {} _pending_qr: dict[str, "PendingQr"] = {}
_credential_guard = threading.Lock() _credential_guard = threading.Lock()
_credential_locks: dict[str, threading.Lock] = {} _credential_locks: dict[str, threading.Lock] = {}
_pending_guard = threading.RLock()
_pending_busy: set[str] = set()
def _credential_lock(employee_id: str) -> threading.Lock: def _credential_lock(employee_id: str) -> threading.Lock:
@@ -43,6 +45,11 @@ def _credential_lock(employee_id: str) -> threading.Lock:
return lock return lock
def release_credential_lock(employee_id: str) -> None:
with _credential_guard:
_credential_locks.pop((employee_id or "").strip(), None)
@dataclass @dataclass
class PendingLogin: class PendingLogin:
client: EunivClient client: EunivClient
@@ -80,27 +87,40 @@ def start_pending_cleaner() -> None:
def _purge_pending() -> None: def _purge_pending() -> None:
now = time.time() now = time.time()
for attempt_id, pending in list(_pending.items()): with _pending_guard:
if now - pending.created > _PENDING_SECONDS: for attempt_id, pending in list(_pending.items()):
if attempt_id in _pending_busy or now - pending.created <= _PENDING_SECONDS:
continue
pending.client.close() pending.client.close()
_pending.pop(attempt_id, None) _pending.pop(attempt_id, None)
for attempt_id, pending in list(_pending_qr.items()): for attempt_id, pending in list(_pending_qr.items()):
if now - pending.created > _QR_SECONDS: if attempt_id in _pending_busy or now - pending.created <= _QR_SECONDS:
continue
pending.client.close() pending.client.close()
_pending_qr.pop(attempt_id, None) _pending_qr.pop(attempt_id, None)
def _drop_qr(attempt_id: str) -> None: def _drop_qr(attempt_id: str) -> None:
pending = _pending_qr.pop(attempt_id, None) with _pending_guard:
pending = _pending_qr.pop(attempt_id, None)
if pending is not None: if pending is not None:
pending.client.close() pending.client.close()
def _drop_employee(employee_id: str) -> None: def _drop_employee(employee_id: str) -> None:
for attempt_id, pending in list(_pending.items()): closing = []
if pending.employee_id == employee_id: with _pending_guard:
pending.client.close() for attempt_id, pending in list(_pending.items()):
_pending.pop(attempt_id, None) if pending.employee_id == employee_id and attempt_id not in _pending_busy:
closing.append(pending)
_pending.pop(attempt_id, None)
for pending in closing:
pending.client.close()
def _release_pending(attempt_id: str) -> None:
with _pending_guard:
_pending_busy.discard(attempt_id)
def _persist(db: Session, employee_id: str, password: str | None, client: EunivClient, profile: dict) -> None: def _persist(db: Session, employee_id: str, password: str | None, client: EunivClient, profile: dict) -> None:
@@ -221,7 +241,8 @@ def login_and_store(
profile = client.login(manual=manual, auto_attempts=auto_attempts) profile = client.login(manual=manual, auto_attempts=auto_attempts)
except ManualJigsaw as exc: except ManualJigsaw as exc:
attempt_id = secrets.token_urlsafe(18) attempt_id = secrets.token_urlsafe(18)
_pending[attempt_id] = PendingLogin(client, employee_id, password, time.time()) with _pending_guard:
_pending[attempt_id] = PendingLogin(client, employee_id, password, time.time())
held = True held = True
return {"attempt_id": attempt_id, "jigsaw": exc.puzzle} return {"attempt_id": attempt_id, "jigsaw": exc.puzzle}
except Exception as exc: except Exception as exc:
@@ -265,7 +286,10 @@ def _credential_still_valid(account: Account, client_factory) -> bool:
def submit_jigsaw(db: Session, attempt_id: str, offset: int) -> dict: def submit_jigsaw(db: Session, attempt_id: str, offset: int) -> dict:
_purge_pending() _purge_pending()
pending = _pending.get(attempt_id) with _pending_guard:
pending = _pending.get(attempt_id)
if pending is not None:
_pending_busy.add(attempt_id)
if pending is None: if pending is None:
raise RuntimeError("请重新登录") raise RuntimeError("请重新登录")
try: try:
@@ -273,16 +297,21 @@ def submit_jigsaw(db: Session, attempt_id: str, offset: int) -> dict:
except JigsawRejected: except JigsawRejected:
pending.tries += 1 pending.tries += 1
if pending.tries >= 5: if pending.tries >= 5:
_pending.pop(attempt_id, None) with _pending_guard:
_pending.pop(attempt_id, None)
pending.client.close() pending.client.close()
raise RuntimeError("请重新登录") raise RuntimeError("请重新登录")
pending.created = time.time() pending.created = time.time()
return {"attempt_id": attempt_id, "jigsaw": pending.client.next_jigsaw()} return {"attempt_id": attempt_id, "jigsaw": pending.client.next_jigsaw()}
except Exception: except Exception:
_pending.pop(attempt_id, None) with _pending_guard:
_pending.pop(attempt_id, None)
pending.client.close() pending.client.close()
raise raise
_pending.pop(attempt_id, None) finally:
_release_pending(attempt_id)
with _pending_guard:
_pending.pop(attempt_id, None)
try: try:
resolved = _resolved_id(profile, pending.employee_id) resolved = _resolved_id(profile, pending.employee_id)
_persist(db, resolved, pending.password, pending.client, profile) _persist(db, resolved, pending.password, pending.client, profile)
@@ -303,13 +332,17 @@ def start_qr_login(client_factory=EunivClient) -> dict:
client.close() client.close()
raise raise
attempt_id = secrets.token_urlsafe(18) attempt_id = secrets.token_urlsafe(18)
_pending_qr[attempt_id] = PendingQr(client, time.time()) with _pending_guard:
_pending_qr[attempt_id] = PendingQr(client, time.time())
return {"attempt_id": attempt_id, "qr_image": image, "ttl": 60} return {"attempt_id": attempt_id, "qr_image": image, "ttl": 60}
def poll_qr_login(db: Session, attempt_id: str, client_factory=EunivClient) -> dict: def poll_qr_login(db: Session, attempt_id: str) -> dict:
_purge_pending() _purge_pending()
pending = _pending_qr.get(attempt_id) with _pending_guard:
pending = _pending_qr.get(attempt_id)
if pending is not None:
_pending_busy.add(attempt_id)
if pending is None: if pending is None:
raise RuntimeError("请重新扫码") raise RuntimeError("请重新扫码")
try: try:
@@ -319,7 +352,10 @@ def poll_qr_login(db: Session, attempt_id: str, client_factory=EunivClient) -> d
except Exception: except Exception:
_drop_qr(attempt_id) _drop_qr(attempt_id)
raise raise
_pending_qr.pop(attempt_id, None) finally:
_release_pending(attempt_id)
with _pending_guard:
_pending_qr.pop(attempt_id, None)
employee_id = str(profile.get("accountId") or profile.get("userName") or "").strip() employee_id = str(profile.get("accountId") or profile.get("userName") or "").strip()
if not employee_id: if not employee_id:
pending.client.close() pending.client.close()
@@ -332,11 +368,6 @@ def poll_qr_login(db: Session, attempt_id: str, client_factory=EunivClient) -> d
pending.client.close() pending.client.close()
def fetch_home(db: Session, employee_id: str, client_factory=EunivClient) -> dict:
"""向 e 学现查首页信息。个人信息只出现在返回值里,不写入数据库。凭证变化时更新密文。"""
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: def fetch_home_summary(db: Session, employee_id: str, client_factory=EunivClient) -> dict:
return _live(db, employee_id, client_factory, lambda client: _apply_hours_source(client, client.home_summary())) return _live(db, employee_id, client_factory, lambda client: _apply_hours_source(client, client.home_summary()))
@@ -484,6 +515,7 @@ def revoke_credential(db: Session, employee_id: str) -> None:
from euniv.autostudy import stop_account from euniv.autostudy import stop_account
stop_account(employee_id) stop_account(employee_id)
release_credential_lock(employee_id)
def refresh_stored_credentials(client_factory=EunivClient) -> None: def refresh_stored_credentials(client_factory=EunivClient) -> None:
@@ -690,7 +722,3 @@ def _request_course_sync(employee_id: str) -> None:
from euniv.courses import request_course_sync from euniv.courses import request_course_sync
request_course_sync(employee_id) request_course_sync(employee_id)
def stored_password(account: Account) -> str:
return decrypt_secret(account.password_cipher)
+1 -8
View File
@@ -24,7 +24,6 @@ _inflight: set[str] = set()
_dirty: set[str] = set() _dirty: set[str] = set()
_urgent: set[str] = set() _urgent: set[str] = set()
_last_flush: dict[str, float] = {} _last_flush: dict[str, float] = {}
_latest: dict[str, dict] = {}
def attach_loop(loop: asyncio.AbstractEventLoop) -> None: def attach_loop(loop: asyncio.AbstractEventLoop) -> None:
@@ -47,6 +46,7 @@ def unregister(employee_id: str, ws: WebSocket) -> None:
group.discard(ws) group.discard(ws)
if not group: if not group:
_clients.pop(key, None) _clients.pop(key, None)
_last_flush.pop(key, None)
def notify(employee_id: str | None = None, urgent: bool = False) -> None: def notify(employee_id: str | None = None, urgent: bool = False) -> None:
@@ -59,12 +59,6 @@ def notify(employee_id: str | None = None, urgent: bool = False) -> None:
loop.call_soon_threadsafe(_mark, key, urgent) 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: def _mark(employee_id: str, urgent: bool) -> None:
_dirty.add(employee_id) _dirty.add(employee_id)
if urgent: if urgent:
@@ -109,7 +103,6 @@ async def _flush(employee_id: str, armed: bool = False) -> None:
from euniv.study_control import payload_for from euniv.study_control import payload_for
payload = await asyncio.to_thread(payload_for, employee_id) payload = await asyncio.to_thread(payload_for, employee_id)
_latest[employee_id] = payload
_last_flush[employee_id] = asyncio.get_running_loop().time() _last_flush[employee_id] = asyncio.get_running_loop().time()
dead: list[WebSocket] = [] dead: list[WebSocket] = []
for ws in sockets: for ws in sockets:
+23 -14
View File
@@ -24,6 +24,26 @@ def validate_start(day: object, hour: object, minute: object, second: object) ->
return int(day), int(hour), int(minute), int(second) return int(day), int(hour), int(minute), int(second)
def _clamp_int(value: object, low: int, high: int, default: int) -> int:
if isinstance(value, bool):
return default
try:
number = int(value) # type: ignore[arg-type]
except (TypeError, ValueError):
return default
return min(high, max(low, number))
def stored_start(account) -> tuple[int, int, int, int]:
"""读取时把非法时刻收进合法范围,避免首页状态接口报错。"""
return (
_clamp_int(getattr(account, "study_start_day", 1), 1, 31, 1),
_clamp_int(getattr(account, "study_start_hour", 0), 0, 23, 0),
_clamp_int(getattr(account, "study_start_minute", 0), 0, 59, 0),
_clamp_int(getattr(account, "study_start_second", 0), 0, 59, 0),
)
def apply(account, day: object, hour: object, minute: object, second: object) -> None: def apply(account, day: object, hour: object, minute: object, second: object) -> None:
d, h, m, s = validate_start(day, hour, minute, second) d, h, m, s = validate_start(day, hour, minute, second)
account.study_start_day = d account.study_start_day = d
@@ -33,18 +53,12 @@ def apply(account, day: object, hour: object, minute: object, second: object) ->
def label_of(account) -> str: def label_of(account) -> str:
day = int(getattr(account, "study_start_day", 1) or 1) day, hour, minute, second = stored_start(account)
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)
return f"每月{day}日 {hour:02d}:{minute:02d}:{second:02d}" return f"每月{day}日 {hour:02d}:{minute:02d}:{second:02d}"
def view_of(account) -> dict: def view_of(account) -> dict:
day = int(getattr(account, "study_start_day", 1) or 1) day, hour, minute, second = stored_start(account)
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) enabled = getattr(account, "study_schedule_enabled", True)
return { return {
"day": day, "day": day,
@@ -71,12 +85,7 @@ def month_key(now: datetime | None = None) -> str:
def start_at(account, now: datetime | None = None) -> datetime: def start_at(account, now: datetime | None = None) -> datetime:
"""该账号在 now 所在月的开始时刻。2 月 31 日等按当月最后一天。""" """该账号在 now 所在月的开始时刻。2 月 31 日等按当月最后一天。"""
current = as_cn(now) current = as_cn(now)
day, hour, minute, second = validate_start( day, hour, minute, second = stored_start(account)
int(getattr(account, "study_start_day", 1) or 1),
int(getattr(account, "study_start_hour", 0) or 0),
int(getattr(account, "study_start_minute", 0) or 0),
int(getattr(account, "study_start_second", 0) or 0),
)
last = calendar.monthrange(current.year, current.month)[1] last = calendar.monthrange(current.year, current.month)[1]
return datetime( return datetime(
current.year, current.year,
-1
View File
@@ -25,7 +25,6 @@ def fresh_database():
with engine.begin() as connection: with engine.begin() as connection:
connection.execute(text("DROP TABLE IF EXISTS accounts")) connection.execute(text("DROP TABLE IF EXISTS accounts"))
connection.execute(text("DROP TABLE IF EXISTS schedules"))
connection.execute(text("DROP TABLE IF EXISTS system_config")) connection.execute(text("DROP TABLE IF EXISTS system_config"))
connection.execute(text("DROP TABLE IF EXISTS courses")) connection.execute(text("DROP TABLE IF EXISTS courses"))
connection.execute(text("DROP TABLE IF EXISTS course_sync")) connection.execute(text("DROP TABLE IF EXISTS course_sync"))
+2 -2
View File
@@ -430,7 +430,7 @@ def test_paused_account_still_updates_when_opening_home() -> None:
super().__init__(login_name, password) super().__init__(login_name, password)
self._token = "yxt-1" self._token = "yxt-1"
def home_snapshot(self) -> dict: def home_summary(self) -> dict:
self._token = "yxt-2" self._token = "yxt-2"
return {"name": "测试用户"} return {"name": "测试用户"}
@@ -440,7 +440,7 @@ def test_paused_account_still_updates_when_opening_home() -> None:
return exported return exported
with SessionLocal() as db: with SessionLocal() as db:
assert service.fetch_home(db, "paused-user", HomeClient)["name"] == "测试用户" assert service.fetch_home_summary(db, "paused-user", HomeClient)["name"] == "测试用户"
account = db.get(Account, "paused-user") account = db.get(Account, "paused-user")
assert account is not None assert account is not None
assert account.refresh_paused is True assert account.refresh_paused is True
+1 -5
View File
@@ -579,14 +579,10 @@ def test_user_can_set_proxy_with_or_without_password() -> None:
account = db.get(Account, "6650000146") account = db.get(Account, "6650000146")
assert account is not None assert account is not None
assert decrypt_secret(account.proxy_password_cipher) == "p@ss" assert decrypt_secret(account.proxy_password_cipher) == "p@ss"
cleared = client.delete("/api/settings/proxy") cleared = client.put("/api/settings/proxy", json={"scheme": "off"})
assert cleared.status_code == 200 assert cleared.status_code == 200
assert cleared.json()["enabled"] is False assert cleared.json()["enabled"] is False
assert cleared.json()["scheme"] == "off" assert cleared.json()["scheme"] == "off"
off = client.put("/api/settings/proxy", json={"scheme": "off"})
assert off.status_code == 200
assert off.json()["enabled"] is False
assert off.json()["scheme"] == "off"
def test_user_can_set_course_workers() -> None: def test_user_can_set_course_workers() -> None:
+1 -2
View File
@@ -25,7 +25,6 @@ def test_study_push_throttles_and_only_sends_latest(monkeypatch) -> None:
study_push._dirty.clear() study_push._dirty.clear()
study_push._urgent.clear() study_push._urgent.clear()
study_push._last_flush.clear() study_push._last_flush.clear()
study_push._latest.clear()
study_push._clients.clear() study_push._clients.clear()
study_push.attach_loop(asyncio.get_running_loop()) study_push.attach_loop(asyncio.get_running_loop())
study_push.register("u1", socket) study_push.register("u1", socket)
@@ -39,7 +38,7 @@ def test_study_push_throttles_and_only_sends_latest(monkeypatch) -> None:
study_push.notify("u1", urgent=True) study_push.notify("u1", urgent=True)
await asyncio.sleep(0.05) await asyncio.sleep(0.05)
assert len(socket.payloads) == 2 assert len(socket.payloads) == 2
assert study_push.latest_of("u1") == socket.payloads[-1] assert socket.payloads[-1]["eid"] == "u1"
finally: finally:
for handle in list(study_push._pending.values()): for handle in list(study_push._pending.values()):
handle.cancel() handle.cancel()
+3 -5
View File
@@ -1,6 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, ref } from "vue"; import { onMounted, ref } from "vue";
import { darkTheme, dateZhCN, NButton, NConfigProvider, NDialogProvider, NMessageProvider, zhCN } from "naive-ui"; import { darkTheme, dateZhCN, NButton, NConfigProvider, NDialogProvider, zhCN } from "naive-ui";
import LoginView from "./features/auth/LoginView.vue"; import LoginView from "./features/auth/LoginView.vue";
import Shell from "./shell/Shell.vue"; import Shell from "./shell/Shell.vue";
import AdminShell from "./shell/AdminShell.vue"; import AdminShell from "./shell/AdminShell.vue";
@@ -96,8 +96,7 @@ function onLogin(next: AppSession) {
<template> <template>
<n-config-provider class="app-root" :locale="zhCN" :date-locale="dateZhCN" :theme="isDark ? darkTheme : null" :theme-overrides="themeOverrides"> <n-config-provider class="app-root" :locale="zhCN" :date-locale="dateZhCN" :theme="isDark ? darkTheme : null" :theme-overrides="themeOverrides">
<n-message-provider class="app-root"> <n-dialog-provider>
<n-dialog-provider>
<div v-if="ready && sessionError && !session" class="gate"> <div v-if="ready && sessionError && !session" class="gate">
<section class="gate-card"> <section class="gate-card">
<p class="session-note">暂时无法确认登录状态</p> <p class="session-note">暂时无法确认登录状态</p>
@@ -115,7 +114,6 @@ function onLogin(next: AppSession) {
<Shell v-else-if="session.kind === 'user'" :employee-id="session.employeeId" @logout="exitSystem" @revoke="revokeAccount" /> <Shell v-else-if="session.kind === 'user'" :employee-id="session.employeeId" @logout="exitSystem" @revoke="revokeAccount" />
<AdminShell v-else-if="session.kind === 'admin'" :username="session.username" @logout="exitAdmin" @refresh="loadSession" /> <AdminShell v-else-if="session.kind === 'admin'" :username="session.username" @logout="exitAdmin" @refresh="loadSession" />
</div> </div>
</n-dialog-provider> </n-dialog-provider>
</n-message-provider>
</n-config-provider> </n-config-provider>
</template> </template>
+4 -124
View File
@@ -174,10 +174,6 @@ select {
opacity: 0.7; opacity: 0.7;
} }
.gate-card.with-qr {
width: min(440px, 100%);
}
.qr-block { .qr-block {
text-align: center; text-align: center;
} }
@@ -510,7 +506,6 @@ select {
margin-bottom: 4px; margin-bottom: 4px;
} }
.compact-form,
.compact-nform { .compact-nform {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -542,28 +537,6 @@ select {
display: none; display: none;
} }
.compact-row {
display: flex;
align-items: center;
gap: 12px;
}
.compact-row > label,
.compact-row > .field-title,
.field-title {
flex: none;
color: var(--muted);
font-size: 13px;
}
.compact-row > .n-select,
.compact-row > .n-input,
.compact-row > .n-input-number,
.compact-row > .n-time-picker {
flex: 1;
min-width: 0;
}
.settings-stack { .settings-stack {
flex: 1; flex: 1;
min-height: 0; min-height: 0;
@@ -632,24 +605,13 @@ select {
color: var(--muted); color: var(--muted);
} }
.home-target {
display: flex;
align-items: center;
gap: 12px;
padding-top: 16px;
border-top: 1px solid var(--line);
}
.home-target label {
flex: none;
font-size: 13px;
color: var(--muted);
}
.field-title { .field-title {
display: inline-flex; display: inline-flex;
flex: none;
align-items: center; align-items: center;
gap: 4px; gap: 4px;
color: var(--muted);
font-size: 13px;
} }
.hint-icon { .hint-icon {
@@ -669,11 +631,6 @@ select {
font-size: 15px; font-size: 15px;
} }
.recommend-mark {
color: var(--muted);
font-size: 12px;
}
.target-control { .target-control {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -736,7 +693,6 @@ select {
font-size: 13px; font-size: 13px;
} }
.home-study-status,
.study-live-status { .study-live-status {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -999,14 +955,6 @@ select {
font-variant-numeric: tabular-nums; font-variant-numeric: tabular-nums;
} }
.boards {
flex: 1;
min-height: 0;
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
gap: 16px;
}
.board { .board {
min-width: 0; min-width: 0;
min-height: 0; min-height: 0;
@@ -1017,19 +965,6 @@ select {
border-radius: 4px; border-radius: 4px;
} }
.board h3 {
flex: none;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin: 0;
padding: 8px 12px 8px 16px;
border-bottom: 1px solid var(--line);
font-size: 14px;
font-weight: 650;
}
.board-tools { .board-tools {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -1127,6 +1062,7 @@ select {
.event time { .event time {
display: block; display: block;
font-variant-numeric: tabular-nums;
} }
.event .meta { .event .meta {
@@ -1145,10 +1081,6 @@ select {
color: var(--danger); color: var(--danger);
} }
.event time {
font-variant-numeric: tabular-nums;
}
.event strong { .event strong {
display: block; display: block;
margin-top: 2px; margin-top: 2px;
@@ -1382,11 +1314,6 @@ select {
padding: 16px 12px; padding: 16px 12px;
} }
.boards {
grid-template-columns: minmax(0, 1fr);
grid-template-rows: minmax(0, 1fr) minmax(0, 1fr);
}
.facts { .facts {
grid-template-columns: repeat(3, minmax(0, 1fr)); grid-template-columns: repeat(3, minmax(0, 1fr));
} }
@@ -1497,42 +1424,6 @@ select {
color: var(--muted); color: var(--muted);
} }
.settings-form .form-row {
grid-template-columns: 7.5em minmax(160px, 280px);
justify-content: start;
}
.settings-form .form-row label {
min-width: 0;
white-space: normal;
}
.setting-control {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
}
.setting-control .n-input-number {
flex: 1;
width: 100%;
min-width: 0;
}
.setting-unit {
flex: none;
color: var(--muted);
}
.form-section {
margin: 20px 0 8px;
font-size: 13px;
font-weight: 600;
color: var(--muted);
letter-spacing: 0.04em;
}
.form-hint { .form-hint {
margin: 0; margin: 0;
padding: 2px 0 0 0; padding: 2px 0 0 0;
@@ -1720,17 +1611,6 @@ body .n-base-select-menu .n-base-select-option__content {
} }
} }
@media (max-width: 800px) {
.settings-form .form-row {
grid-template-columns: minmax(0, 1fr);
}
.settings-form .form-row label {
min-width: 0;
white-space: normal;
}
}
@media (max-width: 480px) { @media (max-width: 480px) {
.gate { .gate {
padding: 16px 12px; padding: 16px 12px;