"""校验 e 学登录。本地只保存工号、加密密码和加密后的登录凭证。""" from __future__ import annotations import hmac import json import secrets import threading import time from datetime import datetime, timedelta, timezone from dataclasses import dataclass from sqlalchemy import delete, select from sqlalchemy.orm import Session from euniv.client import ( QR_PASSWORD_MARK, EunivClient, JigsawRejected, LoginRejected, ManualJigsaw, QrWaiting, SessionExpired, history_hour_totals, is_qr_password, ) from euniv.crypto import decrypt_secret, encrypt_secret from euniv.models import Account _PENDING_SECONDS = 180 _QR_SECONDS = 70 _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: with _credential_guard: lock = _credential_locks.get(employee_id) if lock is None: lock = threading.RLock() _credential_locks[employee_id] = 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 employee_id: str password: str created: float tries: int = 0 @dataclass class PendingQr: client: EunivClient created: float def _dump(credential: dict) -> str: return json.dumps(credential, ensure_ascii=False, sort_keys=True) def start_pending_cleaner() -> None: """定时丢掉过期的登录会话,不依赖下一次请求。""" def loop() -> None: while True: time.sleep(30) try: _purge_pending() except Exception: import logging logging.getLogger("euniv.service").exception("清理未完成的登录失败") threading.Thread(target=loop, name="euniv-pending", daemon=True).start() def _purge_pending() -> None: now = time.time() 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 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: 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: 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: with _credential_lock(employee_id): _persist_locked(db, employee_id, password, client, profile) def _persist_locked(db: Session, employee_id: str, password: str | None, client: EunivClient, profile: dict) -> None: from sqlalchemy.exc import IntegrityError client.authorize(profile) account = db.get(Account, employee_id) if account is None: from admin.settings import hours_source_of account = Account( employee_id=employee_id, password_cipher="", credential_cipher="", hours_source=hours_source_of(), ) db.add(account) if password is None: stored = "" if account.password_cipher: try: stored = decrypt_secret(account.password_cipher) except Exception: stored = "" if not stored or is_qr_password(stored): account.password_cipher = encrypt_secret(QR_PASSWORD_MARK) else: account.password_cipher = encrypt_secret(password) account.password_login_at = datetime.now(timezone.utc) account.credential_cipher = encrypt_secret(_dump(client.export_credential())) account.credential_valid = True try: db.commit() except IntegrityError: db.rollback() account = db.get(Account, employee_id) if account is None: raise if password is None: stored = decrypt_secret(account.password_cipher) if account.password_cipher else "" if not stored or is_qr_password(stored): account.password_cipher = encrypt_secret(QR_PASSWORD_MARK) else: account.password_cipher = encrypt_secret(password) account.password_login_at = datetime.now(timezone.utc) account.credential_cipher = encrypt_secret(_dump(client.export_credential())) account.credential_valid = True db.commit() from euniv.autostudy import sync_work sync_work(employee_id) def _client(factory, employee_id: str, password: str, account: Account | None = None): from euniv.proxy import bind_url proxy = bind_url(account) if account is not None else None return factory(employee_id, password, proxy) def _switch_proxy(account: Account | None, client, exc: BaseException) -> bool: from euniv.proxy import is_proxy_failure, uses_pool from euniv.proxy_pool import retire_if_dead if account is None or not uses_pool(account): return False proxy = getattr(client, "proxy", None) if not proxy or not is_proxy_failure(exc): return False retire_if_dead(account.employee_id, proxy, str(exc)[:200]) return True def fresh_password(account: Account) -> bool: confirmed = getattr(account, "password_login_at", None) if confirmed is None: return False if confirmed.tzinfo is None: confirmed = confirmed.replace(tzinfo=timezone.utc) return datetime.now(timezone.utc) - confirmed <= timedelta(days=7) def _resolved_id(profile: dict, fallback: str) -> str: return str(profile.get("accountId") or fallback or "").strip() or fallback def login_and_store( db: Session, employee_id: str, password: str, client_factory=EunivClient, manual: bool = False, auto_attempts: int = 3, ) -> dict: _purge_pending() if is_qr_password(password): raise RuntimeError("请使用扫码登录") account = db.get(Account, employee_id) if account and account.password_cipher and account.credential_cipher: stored = decrypt_secret(account.password_cipher) same_password = ( not is_qr_password(stored) and hmac.compare_digest(stored.encode("utf-8"), password.encode("utf-8")) ) if same_password and fresh_password(account) and _credential_still_valid(account, client_factory): _request_course_sync(employee_id) return {"employee_id": employee_id} from euniv.proxy_pool import MAX_SWITCHES held = False client = None last_exc: BaseException | None = None try: for _ in range(MAX_SWITCHES + 1): client = _client(client_factory, employee_id, password, account) try: profile = client.login(manual=manual, auto_attempts=auto_attempts) except ManualJigsaw as exc: attempt_id = secrets.token_urlsafe(18) 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: last_exc = exc if _switch_proxy(account, client, exc): client.close() client = None continue raise resolved = _resolved_id(profile, employee_id) _persist(db, resolved, password, client, profile) _drop_employee(employee_id) _drop_employee(resolved) _request_course_sync(resolved) return {"employee_id": resolved} if last_exc is not None: raise last_exc raise RuntimeError("登录失败") finally: if client is not None and not held: client.close() def _credential_still_valid(account: Account, client_factory) -> bool: from euniv.proxy_pool import MAX_SWITCHES password = decrypt_secret(account.password_cipher) for _ in range(MAX_SWITCHES + 1): client = _client(client_factory, account.employee_id, password, account) try: client.restore(json.loads(decrypt_secret(account.credential_cipher))) return bool(client.credential_alive()) except Exception as exc: if _switch_proxy(account, client, exc): continue return False finally: client.close() return False def submit_jigsaw(db: Session, attempt_id: str, offset: int) -> dict: _purge_pending() 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: profile = pending.client.submit_jigsaw(offset) except JigsawRejected: pending.tries += 1 if pending.tries >= 5: 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: with _pending_guard: _pending.pop(attempt_id, None) pending.client.close() raise 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) _request_course_sync(resolved) return {"employee_id": resolved} finally: pending.client.close() def start_qr_login(client_factory=EunivClient) -> dict: _purge_pending() client = None try: client = client_factory("", "") _unused_qr, image = client.start_qr() except Exception: if client is not None: client.close() raise attempt_id = secrets.token_urlsafe(18) 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) -> dict: _purge_pending() 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: profile = pending.client.poll_qr() except QrWaiting: return {"status": "waiting"} except Exception: _drop_qr(attempt_id) raise 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() raise RuntimeError("扫码登录没有返回工号") try: _persist(db, employee_id, None, pending.client, profile) _request_course_sync(employee_id) return {"employee_id": employee_id} finally: pending.client.close() def fetch_home_summary(db: Session, employee_id: str, client_factory=EunivClient) -> dict: data = _live(db, employee_id, client_factory, lambda client: _apply_hours_source(client, client.home_summary())) _remember_month_hours(db, employee_id, data) _remember_profile(db, employee_id, data) return data 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: from euniv.client import exam_path_ok if not exam_path_ok(path): raise RuntimeError("考试明细无法打开") 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: from euniv.client import training_path_ok if not training_path_ok(path): raise RuntimeError("培训明细无法打开") return _live(db, employee_id, client_factory, lambda client: client.training_detail(path)) def fetch_study_history(db: Session, employee_id: str, client_factory=EunivClient) -> dict: def read(client): items = client.study_history() if not isinstance(items, list): items = [] hours = _hour_fields(_apply_hours_source(client, _api_hour_fields(client), items)) return {"items": items, "total": len(items), **hours} data = _live(db, employee_id, client_factory, read) _remember_month_hours(db, employee_id, data) return data def _apply_hours_source(client, summary: dict, items: list | None = None) -> dict: from admin.settings import source_for_employee data = dict(summary) source = source_for_employee(str(getattr(client, "login_name", "") or "")) data["hours_source"] = source data["official_month_hours"] = data.get("month_hours") if source != "history": return data walker = getattr(client, "month_history_minutes", None) if callable(walker): try: data["month_hours"] = walker() data["limited"] = bool(getattr(client, "history_limited", False)) except Exception: data["limited"] = False return data if items is None: raw = getattr(client, "study_history", None) items = raw() if callable(raw) else [] totals = history_hour_totals(items if isinstance(items, list) else []) data["month_hours"] = totals["month"] return data def _api_hour_fields(client) -> dict: reader = getattr(client, "hour_fields", None) summary = reader() if reader is not None else client.home_summary() return { "year_hours": summary.get("year_hours"), "month_hours": summary.get("month_hours"), "official_month_hours": summary.get("official_month_hours") or summary.get("month_hours"), "today_hours": summary.get("today_hours"), "total_hours": summary.get("total_hours"), } def _remember_month_hours(db: Session, employee_id: str, payload: dict) -> None: """首页、学时历史这些已经取到本月学时的地方,顺手写回用户列表。""" if not isinstance(payload, dict): return raw = payload.get("month_hours") if raw is None or isinstance(raw, bool): return text = str(raw).strip() if not text: return account = db.get(Account, employee_id) if account is None: return from euniv.study_control import stamp_hours stamp_hours(account, text) official = payload.get("official_month_hours") if official is not None and not isinstance(official, bool): official_text = str(official).strip() if official_text: account.official_month_hours = official_text[:32] db.commit() def _profile_text(value: object, limit: int) -> str: if not isinstance(value, str): return "" return value.strip()[:limit] def _remember_profile(db: Session, employee_id: str, payload: dict) -> None: """首页或凭据检查已经取到姓名和部门时,顺手写回用户列表。不记录职级。""" if not isinstance(payload, dict): return name = _profile_text(payload.get("name"), 64) company = _profile_text(payload.get("department"), 300) if not name and not company: return account = db.get(Account, employee_id) if account is None: return changed = False if name and account.user_name != name: account.user_name = name changed = True if company and account.company != company: account.company = company changed = True if changed: db.commit() def _hour_fields(data: dict) -> dict: fields = { "hours_source": data.get("hours_source") or "api", "year_hours": data.get("year_hours"), "month_hours": data.get("month_hours"), "official_month_hours": data.get("official_month_hours"), "today_hours": data.get("today_hours"), "total_hours": data.get("total_hours"), } if data.get("limited") is True: fields["limited"] = True return fields def _drop_rejected_password(db: Session, employee_id: str) -> None: """密码被平台拒绝后清掉登录凭证,停止自动重试。""" with _credential_lock(employee_id): db.rollback() account = db.get(Account, employee_id) if account is None: return account.credential_cipher = "" account.credential_valid = False account.last_refresh_at = datetime.now(timezone.utc) db.commit() 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): from euniv.proxy_pool import MAX_SWITCHES account = db.get(Account, employee_id) if account is None or not account.credential_cipher: raise RuntimeError("请先登录") credential = json.loads(decrypt_secret(account.credential_cipher)) attempts = _auto_attempts(db) password = decrypt_secret(account.password_cipher) if account.password_cipher else "" db.commit() last_exc: BaseException | None = None for _ in range(MAX_SWITCHES + 1): client = _client(client_factory, employee_id, password, account) try: if credential.get("yxt_token"): client.restore(credential) elif is_qr_password(password): raise RuntimeError("扫码登录已失效,请重新扫码登录") else: try: client.authorize(client.login(manual=False, auto_attempts=attempts)) except ManualJigsaw: raise RuntimeError("登录需要重新验证,请重新登录") from None try: data = read(client) except SessionExpired: if is_qr_password(password): raise RuntimeError("扫码登录已失效,请重新扫码登录") from None from euniv.proxy import uses_pool if uses_pool(account) and getattr(client, "proxy", None): from euniv.proxy_pool import force_direct force_direct(employee_id) client.close() client = client_factory(employee_id, password, None) client.restore(credential) if client.credential_alive(): data = read(client) else: try: client.authorize(client.login(manual=False, auto_attempts=attempts)) except ManualJigsaw: raise RuntimeError("登录需要重新验证,请重新登录") from None data = read(client) else: 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 except LoginRejected: _drop_rejected_password(db, employee_id) raise RuntimeError("请先登录") from None except RuntimeError: raise except Exception as exc: last_exc = exc if _switch_proxy(account, client, exc): continue raise finally: client.close() if last_exc is not None: raise last_exc raise RuntimeError("请先登录") def revoke_credential(db: Session, employee_id: str) -> None: """从本平台删除账号,并停掉定时任务和已经开始的学习。""" from euniv.models import FinishedCourse with _credential_lock(employee_id): account = db.get(Account, employee_id) if account is not None: db.refresh(account) db.execute(delete(FinishedCourse).where(FinishedCourse.employee_id == employee_id)) db.delete(account) db.commit() from euniv.autostudy import stop_account from euniv.study_push import close_account stop_account(employee_id) close_account(employee_id) release_credential_lock(employee_id) 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 from euniv.autostudy import is_studying if is_studying(employee_id): return if account.credential_valid is False: return client = None valid = False checked_alive = False hours = "" official = "" profile: dict = {} try: from euniv.proxy_pool import MAX_SWITCHES password = decrypt_secret(account.password_cipher) previous = json.loads(decrypt_secret(account.credential_cipher)) db.commit() for _ in range(MAX_SWITCHES + 1): client = _client(client_factory, employee_id, password, account) try: client.restore(previous) if client.credential_alive(): 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 current_raw and _dump(current) == _dump(previous) and _dump(updated) != _dump(previous): account.credential_cipher = encrypt_secret(_dump(updated)) valid = True checked_alive = True elif is_qr_password(password): valid = False else: from euniv.proxy import uses_pool if uses_pool(account) and getattr(client, "proxy", None): from euniv.proxy_pool import force_direct force_direct(employee_id) client.close() client = client_factory(employee_id, password, None) client.restore(previous) if client.credential_alive(): valid = True checked_alive = True else: profile = client.login(manual=False, auto_attempts=attempts) _persist(db, employee_id, password, client, profile) valid = True else: profile = client.login(manual=False, auto_attempts=attempts) _persist(db, employee_id, password, client, profile) valid = True if valid: from admin.users import describe_credential found = describe_credential(client) hours = found["hours"] official = found["official"] profile = found["profile"] valid = bool(found["valid"]) checked_alive = valid break except Exception as exc: if _switch_proxy(account, client, exc): client.close() client = None continue raise except Exception as exc: import logging from cryptography.fernet import InvalidToken if isinstance(exc, InvalidToken): logging.getLogger("euniv.service").exception("账号 %s 的密文无法用当前密钥解开", employee_id) return if isinstance(exc, LoginRejected): logging.getLogger("euniv.service").warning("账号 %s 的密码已被拒绝,停止自动登录", employee_id) _drop_rejected_password(db, employee_id) return logging.getLogger("euniv.service").exception("刷新账号 %s 的登录状态失败", employee_id) db.rollback() account = db.get(Account, employee_id) if account is None: return valid = account.credential_valid finally: if client is not None: try: client.close() except Exception: pass record_outcome(account, valid) if profile: _remember_profile(db, employee_id, profile) if hours: from euniv.study_control import stamp_hours stamp_hours(account, hours) if official: account.official_month_hours = official[:32] db.commit() if valid is True: from euniv.autostudy import request_wake request_wake() 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 refresh_now(self) -> None: with self._lock: if self._reason != "stop": self._reason = "now" 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 in {"wake", "now"}: self._reason = "" self._event.clear() return reason 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 notify_hours_source_changed() -> None: """学时依据变了,立刻再刷新一轮已保存的学时。""" if _gate is not None: _gate.refresh_now() return threading.Thread(target=refresh_stored_credentials, name="euniv-hours-source", daemon=True).start() def start_credential_refresh() -> _RefreshGate: global _gate gate = _RefreshGate() _gate = gate def loop() -> None: import logging logger = logging.getLogger("euniv.service") while True: try: seconds = _refresh_interval_seconds() except Exception: logger.exception("读取凭据刷新间隔失败") seconds = 30 * 60 reason = gate.wait(seconds) if reason == "stop": return if reason == "wake": continue try: refresh_stored_credentials() except Exception: logger.exception("凭据刷新失败") threading.Thread(target=loop, name="euniv-credential-refresh", daemon=True).start() return gate def _month_hours(client) -> str: from admin.settings import source_for_employee if source_for_employee(str(getattr(client, "login_name", "") or "")) == "history": reader = getattr(client, "month_history_minutes", None) if reader is None: return "" try: value = reader() except Exception: return "" return str(value) if isinstance(value, int) and not isinstance(value, bool) else "" 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)