fix: 清掉无用接口和样式,并收紧登录与工号边界
This commit is contained in:
@@ -2,7 +2,7 @@
|
||||
|
||||
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 sqlalchemy.orm import Session
|
||||
|
||||
@@ -130,8 +130,8 @@ def post_courses_load(_: str = Depends(require_admin)) -> dict:
|
||||
def get_courses(
|
||||
q: str = "",
|
||||
kind: str = "",
|
||||
offset: int = 0,
|
||||
limit: int = 50,
|
||||
offset: int = Query(default=0, ge=0, le=10**9),
|
||||
limit: int = Query(default=50, ge=1, le=10**9),
|
||||
db: Session = Depends(get_db),
|
||||
_: str = Depends(require_admin),
|
||||
) -> dict:
|
||||
@@ -144,8 +144,8 @@ def get_courses(
|
||||
def get_proxies(
|
||||
q: str = "",
|
||||
status: str = "",
|
||||
offset: int = 0,
|
||||
limit: int = 50,
|
||||
offset: int = Query(default=0, ge=0, le=10**9),
|
||||
limit: int = Query(default=50, ge=1, le=10**9),
|
||||
db: Session = Depends(get_db),
|
||||
_: str = Depends(require_admin),
|
||||
) -> dict:
|
||||
@@ -168,7 +168,7 @@ def get_proxies_probe(_: str = Depends(require_admin)) -> dict:
|
||||
|
||||
|
||||
@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:
|
||||
return probe_proxy_one(proxy_id)
|
||||
except ProxyProbeError as exc:
|
||||
|
||||
+3
-70
@@ -14,14 +14,12 @@ from euniv.models import Account
|
||||
from euniv.course_workers import CourseWorkersError
|
||||
from euniv.course_workers import apply as apply_workers
|
||||
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.study_control import start_now, stop_now
|
||||
from euniv.study_control import view_of as study_view
|
||||
from euniv.study_window import StudyWindowError
|
||||
from euniv.study_window import apply as apply_start
|
||||
from euniv.study_window import label_of as start_label
|
||||
from euniv.study_window import view_of as start_view
|
||||
|
||||
_TOKEN_KEYS = (
|
||||
"ucs_token",
|
||||
@@ -119,8 +117,6 @@ def check_employee(db: Session, employee_id: str) -> dict:
|
||||
account = _require(db, employee_id)
|
||||
if not account.credential_cipher:
|
||||
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 ""
|
||||
credential = json.loads(decrypt_secret(account.credential_cipher))
|
||||
pooled = uses_pool(account)
|
||||
@@ -158,9 +154,6 @@ def check_employee(db: Session, employee_id: str) -> dict:
|
||||
pass
|
||||
if account is None:
|
||||
raise HTTPException(status_code=404, detail="用户不存在")
|
||||
if result != "检查失败":
|
||||
account.password_cipher = before_password
|
||||
account.credential_cipher = before_credential
|
||||
record_outcome(account, valid)
|
||||
db.commit()
|
||||
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))
|
||||
|
||||
|
||||
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:
|
||||
accounts = _accounts_by_ids(db, employee_ids)
|
||||
for account in accounts:
|
||||
@@ -276,45 +245,6 @@ def clear_proxy(db: Session, employee_ids: list[str]) -> dict:
|
||||
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:
|
||||
kind = (action or "").strip().lower()
|
||||
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
|
||||
|
||||
stop_account(employee_id)
|
||||
from euniv.service import release_credential_lock
|
||||
|
||||
release_credential_lock(employee_id)
|
||||
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
@@ -45,45 +45,43 @@ from euniv.service import (
|
||||
)
|
||||
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):
|
||||
monthly_target: int
|
||||
class ProxyBody(BaseModel):
|
||||
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):
|
||||
scheme: str
|
||||
host: str = ""
|
||||
port: int | None = None
|
||||
username: str = ""
|
||||
password: str | None = None
|
||||
|
||||
|
||||
class StudyStartBody(_BaseModel):
|
||||
day: int
|
||||
hour: int
|
||||
minute: int
|
||||
second: int
|
||||
class StudyStartBody(BaseModel):
|
||||
day: int = Field(strict=True)
|
||||
hour: int = Field(strict=True)
|
||||
minute: int = Field(strict=True)
|
||||
second: int = Field(strict=True)
|
||||
enabled: bool | None = None
|
||||
|
||||
|
||||
class CourseWorkersBody(_BaseModel):
|
||||
workers: int
|
||||
class CourseWorkersBody(BaseModel):
|
||||
workers: int = Field(strict=True)
|
||||
|
||||
|
||||
class StudyBundleBody(_BaseModel):
|
||||
monthly_target: int
|
||||
day: int
|
||||
hour: int
|
||||
minute: int
|
||||
second: int
|
||||
class StudyBundleBody(BaseModel):
|
||||
monthly_target: int = Field(strict=True)
|
||||
day: int = Field(strict=True)
|
||||
hour: int = Field(strict=True)
|
||||
minute: int = Field(strict=True)
|
||||
second: int = Field(strict=True)
|
||||
enabled: bool = True
|
||||
workers: int
|
||||
workers: int = Field(strict=True)
|
||||
|
||||
|
||||
class StudyControlBody(_BaseModel):
|
||||
action: str
|
||||
class StudyControlBody(BaseModel):
|
||||
action: str = Field(min_length=1, max_length=16)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
@@ -462,21 +460,6 @@ def put_proxy(body: ProxyBody, request: Request, db: Session = Depends(get_db))
|
||||
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")
|
||||
def get_study_control(request: Request, db: Session = Depends(get_db)) -> dict:
|
||||
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)
|
||||
|
||||
|
||||
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")
|
||||
async def study_control_ws(websocket: WebSocket):
|
||||
from euniv.study_control import payload_for
|
||||
from euniv.study_push import register, unregister
|
||||
|
||||
if not _same_origin(websocket):
|
||||
await websocket.close(code=4403)
|
||||
return
|
||||
await websocket.accept()
|
||||
from euniv.db import SessionLocal
|
||||
from euniv.session import COOKIE_NAME, open_seal, still_valid
|
||||
|
||||
with SessionLocal() as db:
|
||||
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
|
||||
code, employee_id = await asyncio.to_thread(_ws_gate, dict(websocket.cookies))
|
||||
if code:
|
||||
await websocket.close(code=code)
|
||||
return
|
||||
register(employee_id, websocket)
|
||||
last_message = 0.0
|
||||
try:
|
||||
await websocket.send_json(await asyncio.to_thread(payload_for, employee_id))
|
||||
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))
|
||||
except WebSocketDisconnect:
|
||||
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
|
||||
|
||||
|
||||
@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"
|
||||
if _dist.is_dir():
|
||||
app.mount("/", StaticFiles(directory=_dist, html=True), name="web")
|
||||
app.mount("/", _WebFiles(directory=_dist, html=True), name="web")
|
||||
|
||||
@@ -165,7 +165,7 @@ def _cool_failed_sync(employee_id: str, *, invalid: bool = False) -> None:
|
||||
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)
|
||||
sync = CourseSync(id=1, last_employee_id=employee_id)
|
||||
db.add(sync)
|
||||
sync.last_employee_id = employee_id
|
||||
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.finished_at = datetime.now(timezone.utc)
|
||||
sync.next_allowed_at = sync.finished_at + next_gap()
|
||||
sync.course_count = len(courses)
|
||||
db.commit()
|
||||
from euniv.autostudy import clear_study_hold, request_wake
|
||||
|
||||
|
||||
@@ -30,10 +30,9 @@ class CourseSync(Base):
|
||||
__tablename__ = "course_sync"
|
||||
|
||||
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)
|
||||
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):
|
||||
@@ -50,7 +49,7 @@ class FinishedCourse(Base):
|
||||
class Account(Base):
|
||||
__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)
|
||||
credential_cipher: Mapped[str] = mapped_column(Text, default="")
|
||||
refresh_paused: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=sql_false())
|
||||
|
||||
+55
-27
@@ -32,6 +32,8 @@ _pending: dict[str, "PendingLogin"] = {}
|
||||
_pending_qr: dict[str, "PendingQr"] = {}
|
||||
_credential_guard = 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:
|
||||
@@ -43,6 +45,11 @@ def _credential_lock(employee_id: str) -> threading.Lock:
|
||||
return lock
|
||||
|
||||
|
||||
def release_credential_lock(employee_id: str) -> None:
|
||||
with _credential_guard:
|
||||
_credential_locks.pop((employee_id or "").strip(), None)
|
||||
|
||||
|
||||
@dataclass
|
||||
class PendingLogin:
|
||||
client: EunivClient
|
||||
@@ -80,27 +87,40 @@ def start_pending_cleaner() -> None:
|
||||
|
||||
def _purge_pending() -> None:
|
||||
now = time.time()
|
||||
for attempt_id, pending in list(_pending.items()):
|
||||
if now - pending.created > _PENDING_SECONDS:
|
||||
with _pending_guard:
|
||||
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.pop(attempt_id, None)
|
||||
for attempt_id, pending in list(_pending_qr.items()):
|
||||
if now - pending.created > _QR_SECONDS:
|
||||
for attempt_id, pending in list(_pending_qr.items()):
|
||||
if attempt_id in _pending_busy or now - pending.created <= _QR_SECONDS:
|
||||
continue
|
||||
pending.client.close()
|
||||
_pending_qr.pop(attempt_id, 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:
|
||||
pending.client.close()
|
||||
|
||||
|
||||
def _drop_employee(employee_id: str) -> None:
|
||||
for attempt_id, pending in list(_pending.items()):
|
||||
if pending.employee_id == employee_id:
|
||||
pending.client.close()
|
||||
_pending.pop(attempt_id, None)
|
||||
closing = []
|
||||
with _pending_guard:
|
||||
for attempt_id, pending in list(_pending.items()):
|
||||
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:
|
||||
@@ -221,7 +241,8 @@ def login_and_store(
|
||||
profile = client.login(manual=manual, auto_attempts=auto_attempts)
|
||||
except ManualJigsaw as exc:
|
||||
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
|
||||
return {"attempt_id": attempt_id, "jigsaw": exc.puzzle}
|
||||
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:
|
||||
_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:
|
||||
raise RuntimeError("请重新登录")
|
||||
try:
|
||||
@@ -273,16 +297,21 @@ def submit_jigsaw(db: Session, attempt_id: str, offset: int) -> dict:
|
||||
except JigsawRejected:
|
||||
pending.tries += 1
|
||||
if pending.tries >= 5:
|
||||
_pending.pop(attempt_id, None)
|
||||
with _pending_guard:
|
||||
_pending.pop(attempt_id, None)
|
||||
pending.client.close()
|
||||
raise RuntimeError("请重新登录")
|
||||
pending.created = time.time()
|
||||
return {"attempt_id": attempt_id, "jigsaw": pending.client.next_jigsaw()}
|
||||
except Exception:
|
||||
_pending.pop(attempt_id, None)
|
||||
with _pending_guard:
|
||||
_pending.pop(attempt_id, None)
|
||||
pending.client.close()
|
||||
raise
|
||||
_pending.pop(attempt_id, None)
|
||||
finally:
|
||||
_release_pending(attempt_id)
|
||||
with _pending_guard:
|
||||
_pending.pop(attempt_id, None)
|
||||
try:
|
||||
resolved = _resolved_id(profile, pending.employee_id)
|
||||
_persist(db, resolved, pending.password, pending.client, profile)
|
||||
@@ -303,13 +332,17 @@ def start_qr_login(client_factory=EunivClient) -> dict:
|
||||
client.close()
|
||||
raise
|
||||
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}
|
||||
|
||||
|
||||
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()
|
||||
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:
|
||||
raise RuntimeError("请重新扫码")
|
||||
try:
|
||||
@@ -319,7 +352,10 @@ def poll_qr_login(db: Session, attempt_id: str, client_factory=EunivClient) -> d
|
||||
except Exception:
|
||||
_drop_qr(attempt_id)
|
||||
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()
|
||||
if not employee_id:
|
||||
pending.client.close()
|
||||
@@ -332,11 +368,6 @@ def poll_qr_login(db: Session, attempt_id: str, client_factory=EunivClient) -> d
|
||||
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:
|
||||
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
|
||||
|
||||
stop_account(employee_id)
|
||||
release_credential_lock(employee_id)
|
||||
|
||||
|
||||
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
|
||||
|
||||
request_course_sync(employee_id)
|
||||
|
||||
|
||||
def stored_password(account: Account) -> str:
|
||||
return decrypt_secret(account.password_cipher)
|
||||
|
||||
@@ -24,7 +24,6 @@ _inflight: set[str] = set()
|
||||
_dirty: set[str] = set()
|
||||
_urgent: set[str] = set()
|
||||
_last_flush: dict[str, float] = {}
|
||||
_latest: dict[str, dict] = {}
|
||||
|
||||
|
||||
def attach_loop(loop: asyncio.AbstractEventLoop) -> None:
|
||||
@@ -47,6 +46,7 @@ def unregister(employee_id: str, ws: WebSocket) -> None:
|
||||
group.discard(ws)
|
||||
if not group:
|
||||
_clients.pop(key, None)
|
||||
_last_flush.pop(key, 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)
|
||||
|
||||
|
||||
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:
|
||||
_dirty.add(employee_id)
|
||||
if urgent:
|
||||
@@ -109,7 +103,6 @@ async def _flush(employee_id: str, armed: bool = False) -> None:
|
||||
from euniv.study_control import payload_for
|
||||
|
||||
payload = await asyncio.to_thread(payload_for, employee_id)
|
||||
_latest[employee_id] = payload
|
||||
_last_flush[employee_id] = asyncio.get_running_loop().time()
|
||||
dead: list[WebSocket] = []
|
||||
for ws in sockets:
|
||||
|
||||
@@ -24,6 +24,26 @@ def validate_start(day: object, hour: object, minute: object, second: object) ->
|
||||
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:
|
||||
d, h, m, s = validate_start(day, hour, minute, second)
|
||||
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:
|
||||
day = int(getattr(account, "study_start_day", 1) or 1)
|
||||
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)
|
||||
day, hour, minute, second = stored_start(account)
|
||||
return f"每月{day}日 {hour:02d}:{minute:02d}:{second:02d}"
|
||||
|
||||
|
||||
def view_of(account) -> dict:
|
||||
day = int(getattr(account, "study_start_day", 1) or 1)
|
||||
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)
|
||||
day, hour, minute, second = stored_start(account)
|
||||
enabled = getattr(account, "study_schedule_enabled", True)
|
||||
return {
|
||||
"day": day,
|
||||
@@ -71,12 +85,7 @@ def month_key(now: datetime | None = None) -> str:
|
||||
def start_at(account, now: datetime | None = None) -> datetime:
|
||||
"""该账号在 now 所在月的开始时刻。2 月 31 日等按当月最后一天。"""
|
||||
current = as_cn(now)
|
||||
day, hour, minute, second = validate_start(
|
||||
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),
|
||||
)
|
||||
day, hour, minute, second = stored_start(account)
|
||||
last = calendar.monthrange(current.year, current.month)[1]
|
||||
return datetime(
|
||||
current.year,
|
||||
|
||||
@@ -25,7 +25,6 @@ def fresh_database():
|
||||
|
||||
with engine.begin() as connection:
|
||||
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 courses"))
|
||||
connection.execute(text("DROP TABLE IF EXISTS course_sync"))
|
||||
|
||||
@@ -430,7 +430,7 @@ def test_paused_account_still_updates_when_opening_home() -> None:
|
||||
super().__init__(login_name, password)
|
||||
self._token = "yxt-1"
|
||||
|
||||
def home_snapshot(self) -> dict:
|
||||
def home_summary(self) -> dict:
|
||||
self._token = "yxt-2"
|
||||
return {"name": "测试用户"}
|
||||
|
||||
@@ -440,7 +440,7 @@ def test_paused_account_still_updates_when_opening_home() -> None:
|
||||
return exported
|
||||
|
||||
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")
|
||||
assert account is not None
|
||||
assert account.refresh_paused is True
|
||||
|
||||
@@ -579,14 +579,10 @@ def test_user_can_set_proxy_with_or_without_password() -> None:
|
||||
account = db.get(Account, "6650000146")
|
||||
assert account is not None
|
||||
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.json()["enabled"] is False
|
||||
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:
|
||||
|
||||
@@ -25,7 +25,6 @@ def test_study_push_throttles_and_only_sends_latest(monkeypatch) -> None:
|
||||
study_push._dirty.clear()
|
||||
study_push._urgent.clear()
|
||||
study_push._last_flush.clear()
|
||||
study_push._latest.clear()
|
||||
study_push._clients.clear()
|
||||
study_push.attach_loop(asyncio.get_running_loop())
|
||||
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)
|
||||
await asyncio.sleep(0.05)
|
||||
assert len(socket.payloads) == 2
|
||||
assert study_push.latest_of("u1") == socket.payloads[-1]
|
||||
assert socket.payloads[-1]["eid"] == "u1"
|
||||
finally:
|
||||
for handle in list(study_push._pending.values()):
|
||||
handle.cancel()
|
||||
|
||||
Reference in New Issue
Block a user