"""本地用户的列表、检查、暂停和删除。按请求读数据库,不缓存用户或凭证。""" from __future__ import annotations import json import threading from datetime import datetime, timezone from fastapi import HTTPException from sqlalchemy import select from sqlalchemy.orm import Session from euniv.crypto import decrypt_secret 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.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 _TOKEN_KEYS = ( "ucs_token", "ucs_account_id", "ucs_user_id", "ucs_ssoinfo", "ucs_union_id", "yxt_token", ) def build_client(login_name: str, password: str, proxy: str | None = None): from euniv.client import EunivClient return EunivClient(login_name, password, proxy=proxy) def _open_client(login_name: str, password: str, proxy: str | None = None): return build_client(login_name, password, proxy) def record_outcome(account: Account, valid: bool | None) -> None: account.last_refresh_at = datetime.now(timezone.utc) account.credential_valid = valid def _optional_bool(value: object) -> bool | None: if value is None: return None return bool(value) def _iso_time(value: datetime | None) -> str | None: if value is None: return None if value.tzinfo is None: value = value.replace(tzinfo=timezone.utc) return value.isoformat() def list_users(db: Session) -> list[dict]: from euniv.autostudy import autostudy_status, work_running accounts = db.scalars(select(Account).order_by(Account.employee_id)).all() live_users = autostudy_status().get("users") or {} rows = [] for account in accounts: control = study_view(account) live = live_users.get(account.employee_id) if isinstance(live_users, dict) else {} if not isinstance(live, dict): live = {} rows.append( { "employee_id": account.employee_id, "has_credential": bool(account.credential_cipher), "refresh_paused": bool(account.refresh_paused), "last_refresh_at": _iso_time(account.last_refresh_at), "credential_valid": _optional_bool(account.credential_valid), "month_hours": account.month_hours or "", "monthly_target": account.monthly_target if account.monthly_target is not None else 600, "has_proxy": enabled(account), "proxy": summary_of(account), "study_start": start_label(account), "study_start_day": int(account.study_start_day or 8), "study_start_hour": int(account.study_start_hour or 0), "study_start_minute": int(account.study_start_minute or 0), "study_start_second": int(account.study_start_second or 0), "study_schedule_enabled": control["schedule_enabled"], "course_workers": workers_of(account), "study_paused": control["paused"], "study_ignore_window": control["ignore_window"], "study_started": control["started"], "hours_month": account.hours_month or "", "study_active": work_running(account.employee_id), "state": str(live.get("state") or ""), } ) return rows def _require(db: Session, employee_id: str) -> Account: account = db.get(Account, employee_id) if account is None: raise HTTPException(status_code=404, detail="用户不存在") return account def check_employee(db: Session, employee_id: str) -> dict: from euniv.proxy import bind_url, is_proxy_failure, url_of, uses_pool from euniv.proxy_pool import MAX_SWITCHES, retire_if_dead account = _require(db, employee_id) if not account.credential_cipher: return {"employee_id": employee_id, "result": "未保存"} password = decrypt_secret(account.password_cipher) if account.password_cipher else "" credential = json.loads(decrypt_secret(account.credential_cipher)) pooled = uses_pool(account) db.commit() client = None result = "检查失败" valid: bool | None = None try: for _ in range(MAX_SWITCHES + 1): proxy = bind_url(account) if pooled else url_of(account) client = _open_client(employee_id, password, proxy) try: client.restore(credential) alive = bool(client.credential_alive()) result = "有效" if alive else "已失效" valid = alive break except Exception as exc: if pooled and proxy and is_proxy_failure(exc): retire_if_dead(employee_id, proxy, str(exc)[:200]) client.close() client = None continue raise except Exception: db.rollback() account = db.get(Account, employee_id) result = "检查失败" valid = None finally: if client is not None: try: client.close() except Exception: pass if account is None: raise HTTPException(status_code=404, detail="用户不存在") record_outcome(account, valid) db.commit() payload = {"employee_id": employee_id, "result": result} if result == "检查失败": payload["detail"] = "检查失败" return payload def _check_saved(db: Session, employee_ids: list[str]) -> list[dict]: results = [] for employee_id in employee_ids: try: results.append(check_employee(db, employee_id)) except HTTPException as exc: if exc.status_code == 404: continue raise except Exception: results.append({"employee_id": employee_id, "result": "检查失败", "detail": "检查失败"}) return results _CHECK_INLINE = 8 _check_guard = threading.Lock() _check_running = False _check_results: list[dict] = [] _check_error = "" def check_state() -> dict: with _check_guard: return {"running": _check_running, "results": list(_check_results), "error": _check_error} def _run_check(employee_ids: list[str]) -> None: global _check_running, _check_results, _check_error from euniv.db import SessionLocal results: list[dict] = [] error = "" try: for employee_id in employee_ids: with SessionLocal() as db: try: results.append(check_employee(db, employee_id)) except HTTPException as exc: if exc.status_code != 404: raise except Exception: results.append({"employee_id": employee_id, "result": "检查失败", "detail": "检查失败"}) except Exception: error = "检查失败" with _check_guard: _check_results = results _check_error = error _check_running = False def check_all(db: Session) -> list[dict] | dict: global _check_running employee_ids = list( db.scalars( select(Account.employee_id) .where(Account.credential_cipher != "") .order_by(Account.employee_id) ) ) if len(employee_ids) <= _CHECK_INLINE: return _check_saved(db, employee_ids) with _check_guard: if _check_running: return check_state() _check_running = True _check_results = [] _check_error = "" threading.Thread(target=_run_check, args=(employee_ids,), name="euniv-check-all", daemon=True).start() return {"running": True, "results": [], "error": ""} def set_paused(db: Session, employee_id: str, paused: bool) -> dict: account = _require(db, employee_id) account.refresh_paused = paused db.commit() return {"ok": True} def read_credentials(db: Session, employee_id: str) -> dict: account = _require(db, employee_id) payload = { "password": decrypt_secret(account.password_cipher) if account.password_cipher else "", "ucs_token": "", "ucs_account_id": "", "ucs_user_id": "", "ucs_ssoinfo": "", "ucs_union_id": "", "yxt_token": "", } if not account.credential_cipher: payload["detail"] = "尚未完成登录或已注销" return payload stored = json.loads(decrypt_secret(account.credential_cipher)) for key in _TOKEN_KEYS: payload[key] = str(stored.get(key) or "") return payload def _accounts_by_ids(db: Session, employee_ids: list[str]) -> list[Account]: ids = [] seen: set[str] = set() for raw in employee_ids: employee_id = str(raw or "").strip() if not employee_id or employee_id in seen: continue seen.add(employee_id) ids.append(employee_id) if not ids: raise HTTPException(status_code=400, detail="请选择账号") if len(ids) > 200: raise HTTPException(status_code=400, detail="一次最多选择 200 个账号") accounts = db.scalars(select(Account).where(Account.employee_id.in_(ids))).all() found = {account.employee_id for account in accounts} missing = [employee_id for employee_id in ids if employee_id not in found] if missing: raise HTTPException(status_code=404, detail="用户不存在") return accounts def read_proxy(db: Session, employee_id: str) -> dict: return view_of(_require(db, employee_id)) def clear_proxy(db: Session, employee_ids: list[str]) -> dict: accounts = _accounts_by_ids(db, employee_ids) for account in accounts: clear(account) db.commit() from euniv.autostudy import restart_work for account in accounts: restart_work(account.employee_id) 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"}: raise HTTPException(status_code=400, detail="请选择开始或停止") accounts = _accounts_by_ids(db, employee_ids) from euniv.autostudy import request_stop, sync_work for account in accounts: if kind == "start": start_now(account) else: stop_now(account) db.commit() if kind == "start": for account in accounts: sync_work(account.employee_id) else: for account in accounts: request_stop(account.employee_id) return {"ok": True, "count": len(accounts), "action": kind} def set_study_settings( db: Session, employee_ids: list[str], monthly_target: int | None = None, day: int | None = None, hour: int | None = None, minute: int | None = None, second: int | None = None, schedule_enabled: bool | None = None, workers: int | None = None, scheme: str | None = None, host: str = "", port: object = None, username: str = "", password: str | None = None, ) -> dict: accounts = _accounts_by_ids(db, employee_ids) if monthly_target is not None: if not isinstance(monthly_target, int) or isinstance(monthly_target, bool) or not 0 <= monthly_target <= 9999: raise HTTPException(status_code=400, detail="每月学时目标须为 0 到 9999 的整数") workers_before = {account.employee_id: account.course_workers for account in accounts} try: for account in accounts: if monthly_target is not None: account.monthly_target = monthly_target if day is not None: apply_start(account, day, hour, minute, second) if schedule_enabled is not None: account.study_schedule_enabled = bool(schedule_enabled) if workers is not None: apply_workers(account, workers) if scheme is not None: apply(account, scheme, host, port, username, password) except (StudyWindowError, CourseWorkersError, ProxyError) as exc: db.rollback() raise HTTPException(status_code=400, detail=str(exc)) from exc db.commit() from euniv.autostudy import restart_work, sync_work for account in accounts: if scheme is not None or account.course_workers != workers_before[account.employee_id]: restart_work(account.employee_id) sync_work(account.employee_id) return {"ok": True, "count": len(accounts)} def delete_user(db: Session, employee_id: str) -> dict: from euniv.service import _credential_lock, release_credential_lock with _credential_lock(employee_id): account = _require(db, 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) return {"ok": True}