Files
EnuivTools/backend/euniv/service.py
T

372 lines
12 KiB
Python

"""校验 e 学登录。本地只保存工号、加密密码和加密后的登录凭证。"""
from __future__ import annotations
import json
import secrets
import threading
import time
from dataclasses import dataclass
from sqlalchemy import select
from sqlalchemy.orm import Session
from euniv.client import EunivClient, JigsawRejected, ManualJigsaw, SessionExpired
from euniv.crypto import decrypt_secret, encrypt_secret
from euniv.models import Account
_PENDING_SECONDS = 180
_pending: dict[str, "PendingLogin"] = {}
_credential_guard = threading.Lock()
_credential_locks: dict[str, threading.Lock] = {}
def _credential_lock(employee_id: str) -> threading.Lock:
with _credential_guard:
lock = _credential_locks.get(employee_id)
if lock is None:
lock = threading.Lock()
_credential_locks[employee_id] = lock
return lock
@dataclass
class PendingLogin:
client: EunivClient
employee_id: str
password: str
created: float
def _dump(credential: dict) -> str:
return json.dumps(credential, ensure_ascii=False, sort_keys=True)
def _purge_pending() -> None:
now = time.time()
for attempt_id, pending in list(_pending.items()):
if now - pending.created > _PENDING_SECONDS:
pending.client.close()
_pending.pop(attempt_id, None)
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)
def _persist(db: Session, employee_id: str, password: str, client: EunivClient, profile: dict) -> None:
client.authorize(profile)
account = db.get(Account, employee_id)
if account is None:
account = Account(employee_id=employee_id, password_cipher="", credential_cipher="")
db.add(account)
account.password_cipher = encrypt_secret(password)
account.credential_cipher = encrypt_secret(_dump(client.export_credential()))
db.commit()
def _client(factory, employee_id: str, password: str, account: Account | None = None):
from euniv.proxy import url_of
proxy = url_of(account) if account is not None else None
try:
return factory(employee_id, password, proxy)
except TypeError:
return factory(employee_id, password)
def login_and_store(
db: Session,
employee_id: str,
password: str,
client_factory=EunivClient,
manual: bool = False,
auto_attempts: int = 3,
) -> dict:
_purge_pending()
account = db.get(Account, employee_id)
if account and account.password_cipher and account.credential_cipher:
if decrypt_secret(account.password_cipher) == password and _credential_still_valid(account, client_factory):
_request_course_sync(employee_id)
return {"employee_id": employee_id}
_drop_employee(employee_id)
client = _client(client_factory, employee_id, password, account)
held = False
try:
try:
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())
held = True
return {"attempt_id": attempt_id, "jigsaw": exc.puzzle}
_persist(db, employee_id, password, client, profile)
_request_course_sync(employee_id)
return {"employee_id": employee_id}
finally:
if not held:
client.close()
def _credential_still_valid(account: Account, client_factory) -> bool:
client = _client(client_factory, account.employee_id, decrypt_secret(account.password_cipher), account)
try:
client.restore(json.loads(decrypt_secret(account.credential_cipher)))
return bool(client.credential_alive())
except Exception:
return False
finally:
client.close()
def submit_jigsaw(db: Session, attempt_id: str, offset: int) -> dict:
_purge_pending()
pending = _pending.get(attempt_id)
if pending is None:
raise RuntimeError("请重新登录")
try:
profile = pending.client.submit_jigsaw(offset)
except JigsawRejected:
pending.created = time.time()
return {"attempt_id": attempt_id, "jigsaw": pending.client.next_jigsaw()}
except Exception:
_pending.pop(attempt_id, None)
pending.client.close()
raise
_pending.pop(attempt_id, None)
try:
_persist(db, pending.employee_id, pending.password, pending.client, profile)
_request_course_sync(pending.employee_id)
return {"employee_id": pending.employee_id}
finally:
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: 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: client.home_summary())
def fetch_home_exams(db: Session, employee_id: str, client_factory=EunivClient) -> dict:
return {"exams": _live(db, employee_id, client_factory, lambda client: client.home_exams())}
def fetch_home_trainings(db: Session, employee_id: str, client_factory=EunivClient) -> dict:
return {"trainings": _live(db, employee_id, client_factory, lambda client: client.home_trainings())}
def fetch_exam_detail(db: Session, employee_id: str, path: str, client_factory=EunivClient) -> dict:
return _live(db, employee_id, client_factory, lambda client: client.exam_detail(path))
def fetch_training_detail(db: Session, employee_id: str, path: str, client_factory=EunivClient) -> dict:
return _live(db, employee_id, client_factory, lambda client: client.training_detail(path))
def _auto_attempts(db: Session) -> int:
from admin.settings import auto_attempt_count
return auto_attempt_count(db)
def _live(db: Session, employee_id: str, client_factory, read):
account = db.get(Account, employee_id)
if account is None:
raise RuntimeError("请先登录")
credential = json.loads(decrypt_secret(account.credential_cipher)) if account.credential_cipher else {}
attempts = _auto_attempts(db)
client = _client(client_factory, employee_id, decrypt_secret(account.password_cipher), account)
try:
if credential.get("yxt_token"):
client.restore(credential)
else:
try:
client.authorize(client.login(manual=False, auto_attempts=attempts))
except ManualJigsaw:
raise RuntimeError("登录需要重新验证,请重新登录") from None
try:
data = read(client)
except SessionExpired:
try:
client.authorize(client.login(manual=False, auto_attempts=attempts))
except ManualJigsaw:
raise RuntimeError("登录需要重新验证,请重新登录") from None
data = read(client)
updated = client.export_credential()
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 _dump(updated) != _dump(current) and _dump(current) == _dump(credential):
account.credential_cipher = encrypt_secret(_dump(updated))
db.commit()
return data
finally:
client.close()
def revoke_credential(db: Session, employee_id: str) -> None:
account = db.get(Account, employee_id)
if account is None:
return
account.credential_cipher = ""
db.commit()
def refresh_stored_credentials(client_factory=EunivClient) -> None:
"""逐个刷新。先只取出工号,再每人单独打开会话,避免把全部凭证同时放进内存。"""
from admin.settings import auto_attempt_count
from euniv.db import SessionLocal
with SessionLocal() as db:
attempts = auto_attempt_count(db)
employee_ids = list(db.scalars(select(Account.employee_id).order_by(Account.employee_id)))
for employee_id in employee_ids:
_refresh_one(employee_id, attempts, client_factory)
def _refresh_one(employee_id: str, attempts: int, client_factory) -> None:
from admin.users import record_outcome
from euniv.db import SessionLocal
with SessionLocal() as db:
account = db.get(Account, employee_id)
if account is None or account.refresh_paused or not account.credential_cipher:
return
client = None
valid = False
checked_alive = False
hours = ""
try:
password = decrypt_secret(account.password_cipher)
previous = json.loads(decrypt_secret(account.credential_cipher))
client = _client(client_factory, employee_id, password, account)
client.restore(previous)
if client.credential_alive():
updated = client.export_credential()
if _dump(updated) != _dump(previous):
account.credential_cipher = encrypt_secret(_dump(updated))
valid = True
checked_alive = True
else:
profile = client.login(manual=False, auto_attempts=attempts)
_persist(db, employee_id, password, client, profile)
valid = True
if valid:
hours = _month_hours(client)
except Exception:
db.rollback()
valid = False
account = db.get(Account, employee_id)
if account is None:
return
finally:
if client is not None:
try:
client.close()
except Exception:
pass
record_outcome(account, valid)
if hours:
account.month_hours = hours
db.commit()
if checked_alive:
_request_course_sync(employee_id)
class _RefreshGate:
"""停止或变更间隔时立刻结束当前等待。"""
def __init__(self) -> None:
self._event = threading.Event()
self._lock = threading.Lock()
self._reason = ""
def set(self) -> None:
with self._lock:
self._reason = "stop"
self._event.set()
def wake(self) -> None:
with self._lock:
if self._reason != "stop":
self._reason = "wake"
self._event.set()
def wait(self, seconds: float) -> str:
self._event.wait(timeout=max(0.0, seconds))
with self._lock:
reason = self._reason
if reason == "stop":
return "stop"
if reason == "wake":
self._reason = ""
self._event.clear()
return "wake"
return "timeout"
_gate: _RefreshGate | None = None
def _refresh_interval_seconds() -> int:
from admin.settings import refresh_interval_seconds
return refresh_interval_seconds()
def notify_refresh_interval_changed() -> None:
"""保存新间隔后打断等待。这次唤醒只重新计时,不立刻刷新。"""
if _gate is not None:
_gate.wake()
def start_credential_refresh() -> _RefreshGate:
global _gate
gate = _RefreshGate()
_gate = gate
def loop() -> None:
while True:
seconds = _refresh_interval_seconds()
reason = gate.wait(seconds)
if reason == "stop":
return
if reason == "wake":
continue
try:
refresh_stored_credentials()
except Exception:
continue
threading.Thread(target=loop, name="euniv-credential-refresh", daemon=True).start()
return gate
def _month_hours(client) -> str:
reader = getattr(client, "month_hours", None)
if reader is None:
return ""
try:
value = reader()
except Exception:
return ""
return value if isinstance(value, str) else ""
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)