344 lines
11 KiB
Python
344 lines
11 KiB
Python
"""本地用户的列表、检查、暂停和删除。按请求读数据库,不缓存用户或凭证。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
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.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",
|
|
"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):
|
|
try:
|
|
return build_client(login_name, password, proxy)
|
|
except TypeError:
|
|
return build_client(login_name, password)
|
|
|
|
|
|
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]:
|
|
accounts = db.scalars(select(Account).order_by(Account.employee_id)).all()
|
|
rows = []
|
|
for account in accounts:
|
|
control = study_view(account)
|
|
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": int(account.monthly_target or 600),
|
|
"has_proxy": enabled(account),
|
|
"proxy": summary_of(account),
|
|
"study_start": start_label(account),
|
|
"study_start_day": int(account.study_start_day or 1),
|
|
"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),
|
|
"course_workers": workers_of(account),
|
|
"study_paused": control["paused"],
|
|
"study_ignore_window": control["ignore_window"],
|
|
"study_started": control["started"],
|
|
}
|
|
)
|
|
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:
|
|
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
|
|
client = None
|
|
result = "检查失败"
|
|
valid: bool | None = None
|
|
try:
|
|
client = _open_client(employee_id, decrypt_secret(account.password_cipher), url_of(account))
|
|
client.restore(json.loads(decrypt_secret(account.credential_cipher)))
|
|
alive = bool(client.credential_alive())
|
|
result = "有效" if alive else "已失效"
|
|
valid = alive
|
|
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="用户不存在")
|
|
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}
|
|
if result == "检查失败":
|
|
payload["detail"] = "检查失败"
|
|
return payload
|
|
|
|
|
|
def check_all(db: Session) -> list[dict]:
|
|
employee_ids = list(
|
|
db.scalars(
|
|
select(Account.employee_id)
|
|
.where(Account.credential_cipher != "")
|
|
.order_by(Account.employee_id)
|
|
)
|
|
)
|
|
results = []
|
|
for employee_id in employee_ids:
|
|
try:
|
|
results.append(check_employee(db, employee_id))
|
|
except HTTPException:
|
|
raise
|
|
except Exception:
|
|
results.append({"employee_id": employee_id, "result": "检查失败", "detail": "检查失败"})
|
|
return results
|
|
|
|
|
|
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 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()
|
|
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:
|
|
clear(account)
|
|
db.commit()
|
|
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"}:
|
|
raise HTTPException(status_code=400, detail="请选择开始或停止")
|
|
accounts = _accounts_by_ids(db, employee_ids)
|
|
from euniv.autostudy import request_stop, request_wake
|
|
|
|
for account in accounts:
|
|
if kind == "start":
|
|
start_now(account)
|
|
else:
|
|
stop_now(account)
|
|
db.commit()
|
|
if kind == "start":
|
|
request_wake()
|
|
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,
|
|
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 的整数")
|
|
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 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()
|
|
return {"ok": True, "count": len(accounts)}
|
|
|
|
|
|
def delete_user(db: Session, employee_id: str) -> dict:
|
|
account = _require(db, employee_id)
|
|
db.delete(account)
|
|
db.commit()
|
|
return {"ok": True}
|