feat: 账号可配置 HTTP/HTTPS/SOCKS 代理
This commit is contained in:
+51
-1
@@ -9,7 +9,17 @@ from sqlalchemy.orm import Session
|
||||
from admin.identity import identity
|
||||
from admin.session import admin_session_active, clear_admin_session
|
||||
from admin.settings import SettingsError, load_config, login_config_view, save_settings, settings_view
|
||||
from admin.users import check_all, check_employee, delete_user, list_users, read_credentials, set_paused
|
||||
from admin.users import (
|
||||
check_all,
|
||||
check_employee,
|
||||
clear_proxy,
|
||||
delete_user,
|
||||
list_users,
|
||||
read_credentials,
|
||||
read_proxy,
|
||||
set_paused,
|
||||
set_proxy,
|
||||
)
|
||||
from euniv.courses import course_page, request_course_sync_now
|
||||
from euniv.db import get_db
|
||||
|
||||
@@ -34,6 +44,19 @@ class PauseBody(BaseModel):
|
||||
paused: bool
|
||||
|
||||
|
||||
class AdminProxyBody(BaseModel):
|
||||
employee_ids: list[str]
|
||||
scheme: str
|
||||
host: str
|
||||
port: int
|
||||
username: str = ""
|
||||
password: str | None = None
|
||||
|
||||
|
||||
class AdminProxyClearBody(BaseModel):
|
||||
employee_ids: list[str]
|
||||
|
||||
|
||||
def require_admin(request: Request) -> str:
|
||||
if not admin_session_active(request.cookies):
|
||||
raise HTTPException(status_code=401, detail="未登录")
|
||||
@@ -114,6 +137,33 @@ def post_refresh(
|
||||
return set_paused(db, employee_id, body.paused)
|
||||
|
||||
|
||||
@admin_router.put("/users/proxy")
|
||||
def put_users_proxy(body: AdminProxyBody, db: Session = Depends(get_db), _: str = Depends(require_admin)) -> dict:
|
||||
return set_proxy(
|
||||
db,
|
||||
body.employee_ids,
|
||||
body.scheme,
|
||||
body.host,
|
||||
body.port,
|
||||
body.username,
|
||||
body.password,
|
||||
)
|
||||
|
||||
|
||||
@admin_router.post("/users/proxy/clear")
|
||||
def post_users_proxy_clear(
|
||||
body: AdminProxyClearBody,
|
||||
db: Session = Depends(get_db),
|
||||
_: str = Depends(require_admin),
|
||||
) -> dict:
|
||||
return clear_proxy(db, body.employee_ids)
|
||||
|
||||
|
||||
@admin_router.get("/users/{employee_id}/proxy")
|
||||
def get_user_proxy(employee_id: str, db: Session = Depends(get_db), _: str = Depends(require_admin)) -> dict:
|
||||
return read_proxy(db, employee_id)
|
||||
|
||||
|
||||
@admin_router.get("/users/{employee_id}/credentials")
|
||||
def get_credentials(employee_id: str, db: Session = Depends(get_db), _: str = Depends(require_admin)) -> dict:
|
||||
return read_credentials(db, employee_id)
|
||||
|
||||
+66
-3
@@ -11,6 +11,7 @@ from sqlalchemy.orm import Session
|
||||
|
||||
from euniv.crypto import decrypt_secret
|
||||
from euniv.models import Account
|
||||
from euniv.proxy import ProxyError, apply, clear, summary_of, url_of, view_of
|
||||
|
||||
_TOKEN_KEYS = (
|
||||
"ucs_token",
|
||||
@@ -22,10 +23,17 @@ _TOKEN_KEYS = (
|
||||
)
|
||||
|
||||
|
||||
def build_client(login_name: str, password: str):
|
||||
def build_client(login_name: str, password: str, proxy: str | None = None):
|
||||
from euniv.client import EunivClient
|
||||
|
||||
return EunivClient(login_name, password)
|
||||
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:
|
||||
@@ -57,6 +65,8 @@ def list_users(db: Session) -> list[dict]:
|
||||
"last_refresh_at": _iso_time(account.last_refresh_at),
|
||||
"credential_valid": _optional_bool(account.credential_valid),
|
||||
"month_hours": account.month_hours or "",
|
||||
"has_proxy": bool(account.proxy_scheme and account.proxy_host and account.proxy_port),
|
||||
"proxy": summary_of(account),
|
||||
}
|
||||
for account in accounts
|
||||
]
|
||||
@@ -79,7 +89,7 @@ def check_employee(db: Session, employee_id: str) -> dict:
|
||||
result = "检查失败"
|
||||
valid: bool | None = None
|
||||
try:
|
||||
client = build_client(employee_id, decrypt_secret(account.password_cipher))
|
||||
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 "已失效"
|
||||
@@ -154,6 +164,59 @@ def read_credentials(db: Session, employee_id: str) -> dict:
|
||||
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: int,
|
||||
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 delete_user(db: Session, employee_id: str) -> dict:
|
||||
account = _require(db, employee_id)
|
||||
db.delete(account)
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
"""账号 HTTP/SOCKS 代理。"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = "0008_proxy"
|
||||
down_revision = "0007_autostudy"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table("accounts") as batch:
|
||||
batch.add_column(sa.Column("proxy_scheme", sa.String(length=16), nullable=False, server_default=""))
|
||||
batch.add_column(sa.Column("proxy_host", sa.String(length=255), nullable=False, server_default=""))
|
||||
batch.add_column(sa.Column("proxy_port", sa.Integer(), nullable=True))
|
||||
batch.add_column(sa.Column("proxy_username", sa.String(length=128), nullable=False, server_default=""))
|
||||
batch.add_column(sa.Column("proxy_password_cipher", sa.Text(), nullable=False, server_default=""))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table("accounts") as batch:
|
||||
batch.drop_column("proxy_password_cipher")
|
||||
batch.drop_column("proxy_username")
|
||||
batch.drop_column("proxy_port")
|
||||
batch.drop_column("proxy_host")
|
||||
batch.drop_column("proxy_scheme")
|
||||
@@ -38,6 +38,14 @@ class MonthlyTargetBody(_BaseModel):
|
||||
monthly_target: int
|
||||
|
||||
|
||||
class ProxyBody(_BaseModel):
|
||||
scheme: str
|
||||
host: str
|
||||
port: int
|
||||
username: str = ""
|
||||
password: str | None = None
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
init_db()
|
||||
@@ -217,6 +225,43 @@ def put_monthly_target(body: MonthlyTargetBody, request: Request, db: Session =
|
||||
return {"monthly_target": account.monthly_target}
|
||||
|
||||
|
||||
@app.get("/api/settings/proxy")
|
||||
def get_proxy(request: Request, db: Session = Depends(get_db)) -> dict:
|
||||
from euniv.proxy import view_of
|
||||
|
||||
account = db.get(Account, _signed_in(request, db))
|
||||
if account is None:
|
||||
raise HTTPException(status_code=401, detail="未登录")
|
||||
return view_of(account)
|
||||
|
||||
|
||||
@app.put("/api/settings/proxy")
|
||||
def put_proxy(body: ProxyBody, request: Request, db: Session = Depends(get_db)) -> dict:
|
||||
from euniv.proxy import ProxyError, apply, view_of
|
||||
|
||||
account = db.get(Account, _signed_in(request, db))
|
||||
if account is None:
|
||||
raise HTTPException(status_code=401, detail="未登录")
|
||||
try:
|
||||
apply(account, body.scheme, body.host, body.port, body.username, body.password)
|
||||
except ProxyError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
db.commit()
|
||||
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()
|
||||
return view_of(account)
|
||||
|
||||
|
||||
@app.get("/api/autostudy/status")
|
||||
def autostudy_state(request: Request, db: Session = Depends(get_db)) -> dict:
|
||||
_signed_in(request, db)
|
||||
|
||||
+20
-30
@@ -600,32 +600,33 @@ class AutoStudyWorker:
|
||||
}
|
||||
|
||||
with SessionLocal() as db:
|
||||
users = db.execute(
|
||||
select(Account.employee_id, Account.monthly_target, Account.month_hours,
|
||||
Account.credential_cipher, Account.password_cipher)
|
||||
from euniv.proxy import url_of
|
||||
|
||||
users = db.scalars(
|
||||
select(Account)
|
||||
.where(Account.credential_cipher != "")
|
||||
.where(Account.credential_valid == True)
|
||||
.order_by(Account.employee_id)
|
||||
).all()
|
||||
courses = db.scalars(select(Course).order_by(Course.title)).all()
|
||||
course_list = [(c.path, c.title, c.kind) for c in courses]
|
||||
eligible = []
|
||||
for row in users:
|
||||
target = row.monthly_target or 600
|
||||
current = _parse_minutes(row.month_hours)
|
||||
if target > 0 and current < target:
|
||||
try:
|
||||
password = decrypt_secret(row.password_cipher)
|
||||
credential = json.loads(decrypt_secret(row.credential_cipher))
|
||||
proxy = url_of(row)
|
||||
except Exception:
|
||||
continue
|
||||
eligible.append((row.employee_id, target, password, credential, proxy))
|
||||
|
||||
if not users or not course_list:
|
||||
if not course_list:
|
||||
_set_status(running=False, message="没有可用的用户或课程")
|
||||
return
|
||||
|
||||
eligible = []
|
||||
for row in users:
|
||||
target = row.monthly_target or 600
|
||||
current = _parse_minutes(row.month_hours)
|
||||
if target > 0 and current < target:
|
||||
try:
|
||||
password = decrypt_secret(row.password_cipher)
|
||||
credential = json.loads(decrypt_secret(row.credential_cipher))
|
||||
except Exception:
|
||||
continue
|
||||
eligible.append((row.employee_id, target, password, credential))
|
||||
|
||||
if not eligible:
|
||||
_set_status(running=False, message="所有用户已达标或无有效凭据")
|
||||
return
|
||||
@@ -634,8 +635,8 @@ class AutoStudyWorker:
|
||||
|
||||
sem = asyncio.Semaphore(_MAX_CONCURRENT_USERS)
|
||||
tasks = [
|
||||
self._study_user(emp_id, target, pw, cred, course_list, intervals, auto_mode, sem)
|
||||
for emp_id, target, pw, cred in eligible
|
||||
self._study_user(emp_id, target, pw, cred, proxy, course_list, intervals, auto_mode, sem)
|
||||
for emp_id, target, pw, cred, proxy in eligible
|
||||
]
|
||||
results = await asyncio.gather(*tasks, return_exceptions=True)
|
||||
for emp_id_tuple, result in zip(eligible, results):
|
||||
@@ -646,24 +647,13 @@ class AutoStudyWorker:
|
||||
_set_status(running=False, message="本轮完成")
|
||||
|
||||
async def _study_user(self, employee_id: str, target: int,
|
||||
password: str, credential: dict,
|
||||
password: str, credential: dict, proxy: str | None,
|
||||
course_list: list, intervals: dict,
|
||||
auto_mode: bool, sem: asyncio.Semaphore) -> None:
|
||||
assert self._async_stop is not None
|
||||
async with sem:
|
||||
_set_user_status(employee_id, state="准备", course="")
|
||||
|
||||
# 后续从账号读取 HTTP/SOCKS 代理 URL 和同时学习门数
|
||||
from euniv.proxy import parse_proxy
|
||||
|
||||
proxy = None
|
||||
max_courses = _MAX_COURSE_PER_USER
|
||||
try:
|
||||
proxy = parse_proxy(proxy)
|
||||
except ValueError:
|
||||
_set_user_status(employee_id, state="代理无效")
|
||||
return
|
||||
|
||||
loop = asyncio.get_event_loop()
|
||||
token, user_id, org_id, cookies = await loop.run_in_executor(
|
||||
None, _prepare_session, employee_id, password, credential, proxy)
|
||||
|
||||
@@ -173,7 +173,10 @@ def _fetch_and_store(trigger: str) -> bool:
|
||||
return False
|
||||
password = decrypt_secret(account.password_cipher)
|
||||
credential = json.loads(decrypt_secret(account.credential_cipher))
|
||||
client = EunivClient(employee_id, password)
|
||||
from euniv.proxy import url_of
|
||||
|
||||
proxy = url_of(account)
|
||||
client = EunivClient(employee_id, password, proxy=proxy)
|
||||
try:
|
||||
client.restore(credential)
|
||||
if not client.credential_alive():
|
||||
|
||||
@@ -47,3 +47,8 @@ class Account(Base):
|
||||
credential_valid: Mapped[bool | None] = mapped_column(Boolean, nullable=True)
|
||||
month_hours: Mapped[str] = mapped_column(String(32), nullable=False, default="", server_default="")
|
||||
monthly_target: Mapped[int] = mapped_column(nullable=False, default=600, server_default="600")
|
||||
proxy_scheme: Mapped[str] = mapped_column(String(16), nullable=False, default="", server_default="")
|
||||
proxy_host: Mapped[str] = mapped_column(String(255), nullable=False, default="", server_default="")
|
||||
proxy_port: Mapped[int | None] = mapped_column(nullable=True)
|
||||
proxy_username: Mapped[str] = mapped_column(String(128), nullable=False, default="", server_default="")
|
||||
proxy_password_cipher: Mapped[str] = mapped_column(Text, nullable=False, default="", server_default="")
|
||||
|
||||
+108
-6
@@ -1,10 +1,14 @@
|
||||
"""账号级 HTTP/HTTPS/SOCKS4/SOCKS5 代理。不处理 VPN 或隧道。"""
|
||||
"""账号级 HTTP/HTTPS/SOCKS4/SOCKS5 代理。账号密码可选。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from urllib.parse import urlparse
|
||||
from urllib.parse import quote, urlparse
|
||||
|
||||
_SCHEMES = {"http", "https", "socks4", "socks5", "socks5h"}
|
||||
SCHEMES = ("http", "https", "socks4", "socks5", "socks5h")
|
||||
|
||||
|
||||
class ProxyError(ValueError):
|
||||
"""代理配置不符合要求。"""
|
||||
|
||||
|
||||
def parse_proxy(value: str | None) -> str | None:
|
||||
@@ -16,8 +20,106 @@ def parse_proxy(value: str | None) -> str | None:
|
||||
text = "http://" + text
|
||||
parsed = urlparse(text)
|
||||
scheme = (parsed.scheme or "").lower()
|
||||
if scheme not in _SCHEMES:
|
||||
raise ValueError("代理只支持 HTTP、HTTPS、SOCKS4、SOCKS5")
|
||||
if scheme not in SCHEMES:
|
||||
raise ProxyError("代理只支持 HTTP、HTTPS、SOCKS4、SOCKS5")
|
||||
if not parsed.hostname:
|
||||
raise ValueError("代理地址不完整")
|
||||
raise ProxyError("代理地址不完整")
|
||||
return text
|
||||
|
||||
|
||||
def build_proxy_url(
|
||||
scheme: str,
|
||||
host: str,
|
||||
port: int,
|
||||
username: str = "",
|
||||
password: str = "",
|
||||
) -> str:
|
||||
scheme, host, port, username = validate_parts(scheme, host, port, username)
|
||||
if username or password:
|
||||
user = quote(username, safe="")
|
||||
secret = quote(password, safe="")
|
||||
auth = f"{user}:{secret}@"
|
||||
else:
|
||||
auth = ""
|
||||
return f"{scheme}://{auth}{host}:{port}"
|
||||
|
||||
|
||||
def validate_parts(scheme: str, host: str, port: object, username: str = "") -> tuple[str, str, int, str]:
|
||||
kind = (scheme or "").strip().lower()
|
||||
if kind not in SCHEMES:
|
||||
raise ProxyError("代理只支持 HTTP、HTTPS、SOCKS4、SOCKS5")
|
||||
address = (host or "").strip()
|
||||
if not address or "://" in address or any(ch.isspace() for ch in address):
|
||||
raise ProxyError("请填写代理地址")
|
||||
if len(address) > 255:
|
||||
raise ProxyError("代理地址过长")
|
||||
if not isinstance(port, int) or isinstance(port, bool) or not 1 <= port <= 65535:
|
||||
raise ProxyError("代理端口须为 1 到 65535 的整数")
|
||||
user = (username or "").strip()
|
||||
if len(user) > 128:
|
||||
raise ProxyError("代理账号过长")
|
||||
return kind, address, port, user
|
||||
|
||||
|
||||
def enabled(account) -> bool:
|
||||
return bool(account.proxy_scheme and account.proxy_host and account.proxy_port)
|
||||
|
||||
|
||||
def view_of(account) -> dict:
|
||||
return {
|
||||
"enabled": enabled(account),
|
||||
"scheme": account.proxy_scheme or "http",
|
||||
"host": account.proxy_host or "",
|
||||
"port": int(account.proxy_port) if account.proxy_port else None,
|
||||
"username": account.proxy_username or "",
|
||||
"has_password": bool(account.proxy_password_cipher),
|
||||
}
|
||||
|
||||
|
||||
def summary_of(account) -> str:
|
||||
if not enabled(account):
|
||||
return ""
|
||||
return f"{account.proxy_scheme.upper()} {account.proxy_host}:{account.proxy_port}"
|
||||
|
||||
|
||||
def url_of(account) -> str | None:
|
||||
if not enabled(account):
|
||||
return None
|
||||
password = ""
|
||||
if account.proxy_password_cipher:
|
||||
from euniv.crypto import decrypt_secret
|
||||
|
||||
password = decrypt_secret(account.proxy_password_cipher)
|
||||
return build_proxy_url(
|
||||
account.proxy_scheme,
|
||||
account.proxy_host,
|
||||
int(account.proxy_port),
|
||||
account.proxy_username or "",
|
||||
password,
|
||||
)
|
||||
|
||||
|
||||
def apply(account, scheme: str, host: str, port: object, username: str = "", password: str | None = None) -> None:
|
||||
kind, address, number, user = validate_parts(scheme, host, port, username)
|
||||
if password is not None and len(str(password)) > 256:
|
||||
raise ProxyError("代理密码过长")
|
||||
account.proxy_scheme = kind
|
||||
account.proxy_host = address
|
||||
account.proxy_port = number
|
||||
account.proxy_username = user
|
||||
if password is None:
|
||||
return
|
||||
if password == "":
|
||||
account.proxy_password_cipher = ""
|
||||
return
|
||||
from euniv.crypto import encrypt_secret
|
||||
|
||||
account.proxy_password_cipher = encrypt_secret(str(password))
|
||||
|
||||
|
||||
def clear(account) -> None:
|
||||
account.proxy_scheme = ""
|
||||
account.proxy_host = ""
|
||||
account.proxy_port = None
|
||||
account.proxy_username = ""
|
||||
account.proxy_password_cipher = ""
|
||||
|
||||
@@ -68,6 +68,16 @@ def _persist(db: Session, employee_id: str, password: str, client: EunivClient,
|
||||
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,
|
||||
@@ -83,7 +93,7 @@ def login_and_store(
|
||||
_request_course_sync(employee_id)
|
||||
return {"employee_id": employee_id}
|
||||
_drop_employee(employee_id)
|
||||
client = client_factory(employee_id, password)
|
||||
client = _client(client_factory, employee_id, password, account)
|
||||
held = False
|
||||
try:
|
||||
try:
|
||||
@@ -102,7 +112,7 @@ def login_and_store(
|
||||
|
||||
|
||||
def _credential_still_valid(account: Account, client_factory) -> bool:
|
||||
client = client_factory(account.employee_id, decrypt_secret(account.password_cipher))
|
||||
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())
|
||||
@@ -172,7 +182,7 @@ def _live(db: Session, employee_id: str, client_factory, read):
|
||||
raise RuntimeError("请先登录")
|
||||
credential = json.loads(decrypt_secret(account.credential_cipher)) if account.credential_cipher else {}
|
||||
attempts = _auto_attempts(db)
|
||||
client = client_factory(employee_id, decrypt_secret(account.password_cipher))
|
||||
client = _client(client_factory, employee_id, decrypt_secret(account.password_cipher), account)
|
||||
try:
|
||||
if credential.get("yxt_token"):
|
||||
client.restore(credential)
|
||||
@@ -237,7 +247,7 @@ def _refresh_one(employee_id: str, attempts: int, client_factory) -> None:
|
||||
try:
|
||||
password = decrypt_secret(account.password_cipher)
|
||||
previous = json.loads(decrypt_secret(account.credential_cipher))
|
||||
client = client_factory(employee_id, password)
|
||||
client = _client(client_factory, employee_id, password, account)
|
||||
client.restore(previous)
|
||||
if client.credential_alive():
|
||||
updated = client.export_credential()
|
||||
|
||||
@@ -291,9 +291,10 @@ def test_saving_new_interval_restarts_wait_without_refresh(monkeypatch) -> None:
|
||||
|
||||
|
||||
class _Alive:
|
||||
def __init__(self, login_name: str, password: str) -> None:
|
||||
def __init__(self, login_name: str, password: str, proxy: str | None = None) -> None:
|
||||
self.login_name = login_name
|
||||
self.password = password
|
||||
self.proxy = proxy
|
||||
self.login_called = False
|
||||
|
||||
def close(self) -> None:
|
||||
@@ -444,6 +445,8 @@ def test_check_skips_empty_credential_and_updates_saved_one() -> None:
|
||||
"last_refresh_at",
|
||||
"credential_valid",
|
||||
"month_hours",
|
||||
"has_proxy",
|
||||
"proxy",
|
||||
}
|
||||
assert saved["has_credential"] is True
|
||||
assert saved["refresh_paused"] is False
|
||||
@@ -632,3 +635,58 @@ def test_settings_do_not_expose_process_switches() -> None:
|
||||
}
|
||||
assert identity.password_cipher()
|
||||
assert decrypt_secret(identity.password_cipher()) == INITIAL_PASSWORD
|
||||
|
||||
|
||||
def test_admin_can_set_and_clear_proxy_for_selected_users() -> None:
|
||||
_add_account("p1-user")
|
||||
_add_account("p2-user")
|
||||
api = _app()
|
||||
client = TestClient(api.app)
|
||||
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
|
||||
saved = client.put(
|
||||
"/api/admin/users/proxy",
|
||||
json={
|
||||
"employee_ids": ["p1-user", "p2-user"],
|
||||
"scheme": "socks5",
|
||||
"host": "127.0.0.1",
|
||||
"port": 1080,
|
||||
"username": "u",
|
||||
"password": "secret",
|
||||
},
|
||||
)
|
||||
assert saved.status_code == 200
|
||||
assert saved.json()["count"] == 2
|
||||
listed = client.get("/api/admin/users").json()
|
||||
one = next(item for item in listed if item["employee_id"] == "p1-user")
|
||||
assert one["has_proxy"] is True
|
||||
assert one["proxy"] == "SOCKS5 127.0.0.1:1080"
|
||||
detail = client.get("/api/admin/users/p1-user/proxy")
|
||||
assert detail.status_code == 200
|
||||
assert detail.json()["username"] == "u"
|
||||
assert detail.json()["has_password"] is True
|
||||
assert "password" not in detail.json()
|
||||
cleared = client.post("/api/admin/users/proxy/clear", json={"employee_ids": ["p1-user"]})
|
||||
assert cleared.status_code == 200
|
||||
listed = client.get("/api/admin/users").json()
|
||||
one = next(item for item in listed if item["employee_id"] == "p1-user")
|
||||
two = next(item for item in listed if item["employee_id"] == "p2-user")
|
||||
assert one["has_proxy"] is False
|
||||
assert two["has_proxy"] is True
|
||||
no_auth = client.put(
|
||||
"/api/admin/users/proxy",
|
||||
json={
|
||||
"employee_ids": ["p1-user"],
|
||||
"scheme": "http",
|
||||
"host": "10.0.0.1",
|
||||
"port": 8080,
|
||||
"username": "",
|
||||
"password": "",
|
||||
},
|
||||
)
|
||||
assert no_auth.status_code == 200
|
||||
listed = client.get("/api/admin/users").json()
|
||||
one = next(item for item in listed if item["employee_id"] == "p1-user")
|
||||
assert one["proxy"] == "HTTP 10.0.0.1:8080"
|
||||
detail = client.get("/api/admin/users/p1-user/proxy")
|
||||
assert detail.json()["has_password"] is False
|
||||
assert detail.json()["username"] == ""
|
||||
|
||||
@@ -10,9 +10,10 @@ from euniv.models import Account
|
||||
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self, login_name: str, password: str) -> None:
|
||||
def __init__(self, login_name: str, password: str, proxy: str | None = None) -> None:
|
||||
self.login_name = login_name
|
||||
self.password = password
|
||||
self.proxy = proxy
|
||||
self._token = "yxt-1"
|
||||
self._profile = {
|
||||
"token": "ucs-1",
|
||||
@@ -111,6 +112,11 @@ def test_login_stores_password_and_credential_only() -> None:
|
||||
"credential_valid",
|
||||
"month_hours",
|
||||
"monthly_target",
|
||||
"proxy_scheme",
|
||||
"proxy_host",
|
||||
"proxy_port",
|
||||
"proxy_username",
|
||||
"proxy_password_cipher",
|
||||
}
|
||||
|
||||
home = client.get("/api/home")
|
||||
@@ -434,6 +440,54 @@ def test_period_page_is_not_fetched_twice() -> None:
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
def test_user_can_set_proxy_with_or_without_password() -> None:
|
||||
import euniv.api as api_module
|
||||
import euniv.service as service_module
|
||||
|
||||
api_module.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store(
|
||||
db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts
|
||||
)
|
||||
client = TestClient(api_module.app)
|
||||
assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200
|
||||
empty = client.get("/api/settings/proxy")
|
||||
assert empty.status_code == 200
|
||||
assert empty.json()["enabled"] is False
|
||||
assert "password" not in empty.json()
|
||||
saved = client.put(
|
||||
"/api/settings/proxy",
|
||||
json={"scheme": "http", "host": "10.0.0.1", "port": 8080, "username": "", "password": ""},
|
||||
)
|
||||
assert saved.status_code == 200
|
||||
assert saved.json() == {
|
||||
"enabled": True,
|
||||
"scheme": "http",
|
||||
"host": "10.0.0.1",
|
||||
"port": 8080,
|
||||
"username": "",
|
||||
"has_password": False,
|
||||
}
|
||||
with_auth = client.put(
|
||||
"/api/settings/proxy",
|
||||
json={"scheme": "socks5", "host": "127.0.0.1", "port": 1080, "username": "u", "password": "p@ss"},
|
||||
)
|
||||
assert with_auth.status_code == 200
|
||||
assert with_auth.json()["has_password"] is True
|
||||
assert "password" not in with_auth.json()
|
||||
kept = client.put(
|
||||
"/api/settings/proxy",
|
||||
json={"scheme": "socks5", "host": "127.0.0.1", "port": 1080, "username": "u", "password": None},
|
||||
)
|
||||
assert kept.status_code == 200
|
||||
assert kept.json()["has_password"] is True
|
||||
with SessionLocal() as db:
|
||||
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")
|
||||
assert cleared.status_code == 200
|
||||
assert cleared.json()["enabled"] is False
|
||||
|
||||
|
||||
def test_exam_list_rejects_unrecognized_page() -> None:
|
||||
from euniv.client import EunivClient
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import asyncio
|
||||
import pytest
|
||||
|
||||
from euniv.autostudy import HoursWatcher, _parse_minutes, _study_video, wait_stop
|
||||
from euniv.proxy import parse_proxy
|
||||
from euniv.proxy import ProxyError, build_proxy_url, parse_proxy
|
||||
|
||||
|
||||
def test_parse_proxy_accepts_http_and_socks() -> None:
|
||||
@@ -16,6 +16,15 @@ def test_parse_proxy_accepts_http_and_socks() -> None:
|
||||
assert parse_proxy("socks5://user:pass@127.0.0.1:1080") == "socks5://user:pass@127.0.0.1:1080"
|
||||
|
||||
|
||||
def test_build_proxy_url_auth_is_optional_and_quoted() -> None:
|
||||
assert build_proxy_url("http", "10.0.0.1", 8080) == "http://10.0.0.1:8080"
|
||||
assert build_proxy_url("socks5", "127.0.0.1", 1080, "u", "p@ss") == "socks5://u:p%40ss@127.0.0.1:1080"
|
||||
assert build_proxy_url("http", "10.0.0.1", 8080, "u", "") == "http://u:@10.0.0.1:8080"
|
||||
assert build_proxy_url("socks4", "127.0.0.1", 1080, "", "s3cret") == "socks4://:s3cret@127.0.0.1:1080"
|
||||
with pytest.raises(ProxyError):
|
||||
build_proxy_url("ss", "127.0.0.1", 1080)
|
||||
|
||||
|
||||
def test_parse_proxy_rejects_other_schemes() -> None:
|
||||
with pytest.raises(ValueError):
|
||||
parse_proxy("ss://secret")
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from "vue";
|
||||
import { NAlert, NButton, NDropdown, NIcon, NModal, useDialog, type DropdownOption } from "naive-ui";
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { NAlert, NButton, NCheckbox, NDropdown, NIcon, NInput, NInputNumber, NModal, NSelect, useDialog, type DropdownOption } from "naive-ui";
|
||||
import { SettingsOutline } from "@vicons/ionicons5";
|
||||
|
||||
interface UserRow {
|
||||
@@ -10,6 +10,8 @@ interface UserRow {
|
||||
last_refresh_at: string | null;
|
||||
credential_valid: boolean | null;
|
||||
month_hours: string;
|
||||
has_proxy: boolean;
|
||||
proxy: string;
|
||||
}
|
||||
|
||||
interface SecretField {
|
||||
@@ -30,6 +32,27 @@ const credentialLoading = ref(false);
|
||||
const credentialError = ref("");
|
||||
const credentialNote = ref("");
|
||||
const credentialFields = ref<SecretField[]>([]);
|
||||
const picked = ref<Record<string, boolean>>({});
|
||||
const proxyOpen = ref(false);
|
||||
const proxySaving = ref(false);
|
||||
const proxyError = ref("");
|
||||
const proxyIds = ref<string[]>([]);
|
||||
const proxyScheme = ref("http");
|
||||
const proxyHost = ref("");
|
||||
const proxyPort = ref<number | null>(null);
|
||||
const proxyUser = ref("");
|
||||
const proxyPassword = ref("");
|
||||
const proxyHasPassword = ref(false);
|
||||
const proxyOptions = [
|
||||
{ label: "HTTP", value: "http" },
|
||||
{ label: "HTTPS", value: "https" },
|
||||
{ label: "SOCKS4", value: "socks4" },
|
||||
{ label: "SOCKS5", value: "socks5" },
|
||||
];
|
||||
|
||||
const pickedIds = computed(() => users.value.filter((row) => picked.value[row.employee_id]).map((row) => row.employee_id));
|
||||
const allPicked = computed(() => users.value.length > 0 && pickedIds.value.length === users.value.length);
|
||||
const somePicked = computed(() => pickedIds.value.length > 0 && !allPicked.value);
|
||||
|
||||
const tokenFields: { label: string; key: string }[] = [
|
||||
{ label: "统一认证 token", key: "ucs_token" },
|
||||
@@ -68,6 +91,8 @@ function asUser(value: unknown): UserRow | null {
|
||||
last_refresh_at: typeof value.last_refresh_at === "string" && value.last_refresh_at ? value.last_refresh_at : null,
|
||||
credential_valid: readValid(value.credential_valid),
|
||||
month_hours: textOf(value.month_hours),
|
||||
has_proxy: value.has_proxy === true,
|
||||
proxy: textOf(value.proxy),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -290,11 +315,126 @@ function confirmDelete(row: UserRow) {
|
||||
});
|
||||
}
|
||||
|
||||
function toggleAll(checked: boolean) {
|
||||
const next: Record<string, boolean> = {};
|
||||
if (checked) {
|
||||
for (const row of users.value) next[row.employee_id] = true;
|
||||
}
|
||||
picked.value = next;
|
||||
}
|
||||
|
||||
function resetProxyForm() {
|
||||
proxyScheme.value = "http";
|
||||
proxyHost.value = "";
|
||||
proxyPort.value = null;
|
||||
proxyUser.value = "";
|
||||
proxyPassword.value = "";
|
||||
proxyHasPassword.value = false;
|
||||
proxyError.value = "";
|
||||
}
|
||||
|
||||
async function openProxy(ids: string[]) {
|
||||
if (!ids.length) return;
|
||||
proxyIds.value = ids;
|
||||
resetProxyForm();
|
||||
proxyOpen.value = true;
|
||||
if (ids.length !== 1) return;
|
||||
try {
|
||||
const response = await fetch(`/api/admin/users/${encodeURIComponent(ids[0])}/proxy`);
|
||||
const payload: unknown = await response.json().catch(() => ({}));
|
||||
if (!response.ok || !isRecord(payload)) return;
|
||||
proxyScheme.value = textOf(payload.scheme) || "http";
|
||||
proxyHost.value = textOf(payload.host);
|
||||
proxyPort.value = typeof payload.port === "number" ? payload.port : null;
|
||||
proxyUser.value = textOf(payload.username);
|
||||
proxyHasPassword.value = payload.has_password === true;
|
||||
} catch { /* 静默 */ }
|
||||
}
|
||||
|
||||
function proxyPasswordPayload() {
|
||||
if (proxyPassword.value !== "") return proxyPassword.value;
|
||||
if (!proxyUser.value.trim()) return "";
|
||||
if (proxyIds.value.length === 1 && proxyHasPassword.value) return null;
|
||||
return "";
|
||||
}
|
||||
|
||||
async function saveProxy() {
|
||||
if (proxySaving.value || !proxyIds.value.length) return;
|
||||
proxyError.value = "";
|
||||
if (!proxyHost.value.trim()) {
|
||||
proxyError.value = "请填写代理地址";
|
||||
return;
|
||||
}
|
||||
if (proxyPort.value == null || !Number.isInteger(proxyPort.value)) {
|
||||
proxyError.value = "请填写代理端口";
|
||||
return;
|
||||
}
|
||||
proxySaving.value = true;
|
||||
try {
|
||||
const response = await fetch("/api/admin/users/proxy", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
employee_ids: proxyIds.value,
|
||||
scheme: proxyScheme.value,
|
||||
host: proxyHost.value.trim(),
|
||||
port: proxyPort.value,
|
||||
username: proxyUser.value.trim(),
|
||||
password: proxyPasswordPayload(),
|
||||
}),
|
||||
});
|
||||
const payload: unknown = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
proxyError.value = detailOf(payload, "没有保存。");
|
||||
return;
|
||||
}
|
||||
proxyOpen.value = false;
|
||||
await load();
|
||||
} catch {
|
||||
proxyError.value = "没有保存。";
|
||||
} finally {
|
||||
proxySaving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function clearProxy(ids: string[]) {
|
||||
if (!ids.length) return;
|
||||
errorText.value = "";
|
||||
try {
|
||||
const response = await fetch("/api/admin/users/proxy/clear", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ employee_ids: ids }),
|
||||
});
|
||||
const payload: unknown = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
errorText.value = detailOf(payload, "没有清除。");
|
||||
return;
|
||||
}
|
||||
await load();
|
||||
} catch {
|
||||
errorText.value = "没有清除。";
|
||||
}
|
||||
}
|
||||
|
||||
function confirmClearProxy(ids: string[]) {
|
||||
if (!ids.length) return;
|
||||
dialog.warning({
|
||||
title: "清除代理",
|
||||
content: ids.length === 1 ? `清除工号 ${ids[0]} 的代理?` : `清除已选 ${ids.length} 个账号的代理?`,
|
||||
positiveText: "清除",
|
||||
negativeText: "取消",
|
||||
onPositiveClick: () => clearProxy(ids),
|
||||
});
|
||||
}
|
||||
|
||||
function rowActions(row: UserRow): DropdownOption[] {
|
||||
const busy = checkingAll.value || checkingId.value !== "";
|
||||
return [
|
||||
{ label: "检查", key: "check", disabled: busy },
|
||||
{ label: "查看凭据", key: "credentials" },
|
||||
{ label: "设置代理", key: "proxy" },
|
||||
{ label: "清除代理", key: "proxy-clear" },
|
||||
{ label: row.refresh_paused ? "恢复自动刷新" : "停止自动刷新", key: "refresh" },
|
||||
{ label: "删除", key: "delete", props: { style: { color: "var(--danger)" } } },
|
||||
];
|
||||
@@ -303,6 +443,8 @@ function rowActions(row: UserRow): DropdownOption[] {
|
||||
function onRowAction(row: UserRow, key: string | number) {
|
||||
if (key === "check") void checkOne(row);
|
||||
else if (key === "credentials") void openCredentials(row);
|
||||
else if (key === "proxy") void openProxy([row.employee_id]);
|
||||
else if (key === "proxy-clear") confirmClearProxy([row.employee_id]);
|
||||
else if (key === "refresh") confirmRefresh(row);
|
||||
else if (key === "delete") confirmDelete(row);
|
||||
}
|
||||
@@ -316,7 +458,11 @@ onMounted(() => {
|
||||
<section class="page admin-page">
|
||||
<header class="page-head">
|
||||
<h2>用户管理</h2>
|
||||
<n-button :loading="checkingAll" :disabled="checkingAll || checkingId !== '' || !users.length" @click="checkAll">检查全部</n-button>
|
||||
<div class="page-head-actions">
|
||||
<n-button :disabled="!pickedIds.length" @click="openProxy(pickedIds)">设置代理</n-button>
|
||||
<n-button :disabled="!pickedIds.length" @click="confirmClearProxy(pickedIds)">清除代理</n-button>
|
||||
<n-button :loading="checkingAll" :disabled="checkingAll || checkingId !== '' || !users.length" @click="checkAll">检查全部</n-button>
|
||||
</div>
|
||||
</header>
|
||||
<n-alert v-if="errorText" class="admin-alert" type="error">{{ errorText }}</n-alert>
|
||||
<div class="admin-scroll">
|
||||
@@ -324,10 +470,14 @@ onMounted(() => {
|
||||
<table v-else-if="users.length" class="admin-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="pick">
|
||||
<n-checkbox :checked="allPicked" :indeterminate="somePicked" @update:checked="toggleAll" />
|
||||
</th>
|
||||
<th>工号</th>
|
||||
<th>凭证</th>
|
||||
<th>凭据是否有效</th>
|
||||
<th>本月学时</th>
|
||||
<th>代理</th>
|
||||
<th>上次刷新时间</th>
|
||||
<th>自动刷新</th>
|
||||
<th>操作</th>
|
||||
@@ -335,10 +485,14 @@ onMounted(() => {
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="row in users" :key="row.employee_id">
|
||||
<td class="pick">
|
||||
<n-checkbox :checked="Boolean(picked[row.employee_id])" @update:checked="(checked) => (picked = { ...picked, [row.employee_id]: checked })" />
|
||||
</td>
|
||||
<td class="employee">{{ row.employee_id }}</td>
|
||||
<td>{{ row.has_credential ? "已保存凭证" : "未保存凭证" }}</td>
|
||||
<td :class="validityClass(validityText(row))">{{ validityText(row) }}</td>
|
||||
<td class="when">{{ row.month_hours || "—" }}</td>
|
||||
<td class="when">{{ row.proxy || "—" }}</td>
|
||||
<td class="when">{{ formatRefreshTime(row.last_refresh_at) }}</td>
|
||||
<td>{{ row.refresh_paused ? "已停止" : "开启" }}</td>
|
||||
<td>
|
||||
@@ -376,5 +530,49 @@ onMounted(() => {
|
||||
</div>
|
||||
</template>
|
||||
</n-modal>
|
||||
<n-modal
|
||||
:show="proxyOpen"
|
||||
preset="card"
|
||||
:title="proxyIds.length === 1 ? `工号 ${proxyIds[0]} 的代理` : `已选 ${proxyIds.length} 个账号的代理`"
|
||||
:style="{ width: 'min(520px, calc(100vw - 32px))' }"
|
||||
@update:show="(show) => (proxyOpen = show)"
|
||||
>
|
||||
<n-alert v-if="proxyError" class="admin-alert" type="error">{{ proxyError }}</n-alert>
|
||||
<form class="settings-form" @submit.prevent="saveProxy">
|
||||
<div class="form-row">
|
||||
<label for="admin-proxy-scheme">类型</label>
|
||||
<n-select id="admin-proxy-scheme" v-model:value="proxyScheme" :options="proxyOptions" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="admin-proxy-host">地址</label>
|
||||
<n-input id="admin-proxy-host" v-model:value="proxyHost" placeholder="例如 127.0.0.1" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="admin-proxy-port">端口</label>
|
||||
<n-input-number id="admin-proxy-port" v-model:value="proxyPort" button-placement="both" :min="1" :max="65535" :precision="0" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="admin-proxy-user">账号</label>
|
||||
<n-input id="admin-proxy-user" v-model:value="proxyUser" placeholder="可不填" autocomplete="off" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="admin-proxy-password">密码</label>
|
||||
<n-input
|
||||
id="admin-proxy-password"
|
||||
v-model:value="proxyPassword"
|
||||
type="password"
|
||||
show-password-on="click"
|
||||
:placeholder="proxyIds.length === 1 && proxyHasPassword ? '已保存,留空则保持' : '可不填'"
|
||||
autocomplete="new-password"
|
||||
/>
|
||||
</div>
|
||||
</form>
|
||||
<template #footer>
|
||||
<div class="modal-actions">
|
||||
<n-button @click="proxyOpen = false">取消</n-button>
|
||||
<n-button type="primary" :loading="proxySaving" @click="saveProxy">保存</n-button>
|
||||
</div>
|
||||
</template>
|
||||
</n-modal>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from "vue";
|
||||
import { NAlert, NButton, NIcon, NInputNumber, NTooltip } from "naive-ui";
|
||||
import { NAlert, NButton, NIcon, NInput, NInputNumber, NSelect, NTooltip } from "naive-ui";
|
||||
import { RefreshOutline } from "@vicons/ionicons5";
|
||||
|
||||
interface HomeSummary {
|
||||
@@ -136,6 +136,105 @@ function saveTarget(value: number | null) {
|
||||
|
||||
watch(monthlyTarget, (v) => { if (targetLoaded.value) saveTarget(v); });
|
||||
|
||||
const proxyLoaded = ref(false);
|
||||
const proxySaving = ref(false);
|
||||
const proxyError = ref("");
|
||||
const proxyScheme = ref("http");
|
||||
const proxyHost = ref("");
|
||||
const proxyPort = ref<number | null>(null);
|
||||
const proxyUser = ref("");
|
||||
const proxyPassword = ref("");
|
||||
const proxyHasPassword = ref(false);
|
||||
const proxyOptions = [
|
||||
{ label: "HTTP", value: "http" },
|
||||
{ label: "HTTPS", value: "https" },
|
||||
{ label: "SOCKS4", value: "socks4" },
|
||||
{ label: "SOCKS5", value: "socks5" },
|
||||
];
|
||||
|
||||
async function loadProxy() {
|
||||
try {
|
||||
const res = await fetch("/api/settings/proxy");
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) return;
|
||||
proxyScheme.value = typeof data.scheme === "string" && data.scheme ? data.scheme : "http";
|
||||
proxyHost.value = typeof data.host === "string" ? data.host : "";
|
||||
proxyPort.value = typeof data.port === "number" ? data.port : null;
|
||||
proxyUser.value = typeof data.username === "string" ? data.username : "";
|
||||
proxyPassword.value = "";
|
||||
proxyHasPassword.value = data.has_password === true;
|
||||
proxyLoaded.value = true;
|
||||
} catch { /* 静默 */ }
|
||||
}
|
||||
|
||||
function proxyPasswordPayload() {
|
||||
if (proxyPassword.value !== "") return proxyPassword.value;
|
||||
if (!proxyUser.value.trim()) return "";
|
||||
return proxyHasPassword.value ? null : "";
|
||||
}
|
||||
|
||||
async function saveProxy() {
|
||||
if (proxySaving.value) return;
|
||||
proxyError.value = "";
|
||||
if (!proxyHost.value.trim()) {
|
||||
proxyError.value = "请填写代理地址";
|
||||
return;
|
||||
}
|
||||
if (proxyPort.value == null || !Number.isInteger(proxyPort.value)) {
|
||||
proxyError.value = "请填写代理端口";
|
||||
return;
|
||||
}
|
||||
proxySaving.value = true;
|
||||
try {
|
||||
const res = await fetch("/api/settings/proxy", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
scheme: proxyScheme.value,
|
||||
host: proxyHost.value.trim(),
|
||||
port: proxyPort.value,
|
||||
username: proxyUser.value.trim(),
|
||||
password: proxyPasswordPayload(),
|
||||
}),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
proxyError.value = failureText(data, "没有保存。");
|
||||
return;
|
||||
}
|
||||
proxyPassword.value = "";
|
||||
proxyHasPassword.value = data.has_password === true;
|
||||
} catch {
|
||||
proxyError.value = "没有保存。";
|
||||
} finally {
|
||||
proxySaving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function clearProxy() {
|
||||
if (proxySaving.value) return;
|
||||
proxySaving.value = true;
|
||||
proxyError.value = "";
|
||||
try {
|
||||
const res = await fetch("/api/settings/proxy", { method: "DELETE" });
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
proxyError.value = failureText(data, "没有清除。");
|
||||
return;
|
||||
}
|
||||
proxyScheme.value = "http";
|
||||
proxyHost.value = "";
|
||||
proxyPort.value = null;
|
||||
proxyUser.value = "";
|
||||
proxyPassword.value = "";
|
||||
proxyHasPassword.value = false;
|
||||
} catch {
|
||||
proxyError.value = "没有清除。";
|
||||
} finally {
|
||||
proxySaving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadStudyStatus() {
|
||||
try {
|
||||
const res = await fetch("/api/autostudy/status");
|
||||
@@ -143,7 +242,7 @@ async function loadStudyStatus() {
|
||||
} catch { /* 静默 */ }
|
||||
}
|
||||
|
||||
onMounted(() => { refresh(); loadTarget(); loadStudyStatus(); });
|
||||
onMounted(() => { refresh(); loadTarget(); loadProxy(); loadStudyStatus(); });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -214,6 +313,41 @@ onMounted(() => { refresh(); loadTarget(); loadStudyStatus(); });
|
||||
<span class="target-unit">分钟</span>
|
||||
</div>
|
||||
</div>
|
||||
<form v-if="proxyLoaded" class="home-proxy" @submit.prevent="saveProxy">
|
||||
<n-alert v-if="proxyError" class="summary-error" type="error">{{ proxyError }}</n-alert>
|
||||
<div class="form-row">
|
||||
<label for="proxy-scheme">代理类型</label>
|
||||
<n-select id="proxy-scheme" v-model:value="proxyScheme" size="small" :options="proxyOptions" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="proxy-host">代理地址</label>
|
||||
<n-input id="proxy-host" v-model:value="proxyHost" size="small" placeholder="例如 127.0.0.1" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="proxy-port">代理端口</label>
|
||||
<n-input-number id="proxy-port" v-model:value="proxyPort" size="small" button-placement="both" :min="1" :max="65535" :precision="0" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="proxy-user">代理账号</label>
|
||||
<n-input id="proxy-user" v-model:value="proxyUser" size="small" placeholder="可不填" autocomplete="off" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="proxy-password">代理密码</label>
|
||||
<n-input
|
||||
id="proxy-password"
|
||||
v-model:value="proxyPassword"
|
||||
size="small"
|
||||
type="password"
|
||||
show-password-on="click"
|
||||
:placeholder="proxyHasPassword ? '已保存,留空则保持' : '可不填'"
|
||||
autocomplete="new-password"
|
||||
/>
|
||||
</div>
|
||||
<div class="home-proxy-actions">
|
||||
<n-button type="primary" size="small" attr-type="submit" :loading="proxySaving">保存</n-button>
|
||||
<n-button size="small" attr-type="button" :disabled="proxySaving" @click="clearProxy">清除</n-button>
|
||||
</div>
|
||||
</form>
|
||||
<div v-if="studyStatus" class="home-study-status">
|
||||
<span class="study-indicator" :class="{ active: Boolean(myStudy) || studyStatus.running }"></span>
|
||||
<span v-if="myStudy" class="study-text">
|
||||
|
||||
+47
-2
@@ -434,6 +434,40 @@ select {
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.home-proxy {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
padding-top: 16px;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.home-proxy .form-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.home-proxy .form-row label {
|
||||
flex: none;
|
||||
width: 84px;
|
||||
font-size: 13px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.home-proxy .form-row .n-select,
|
||||
.home-proxy .form-row .n-input,
|
||||
.home-proxy .form-row .n-input-number {
|
||||
flex: 1;
|
||||
max-width: 320px;
|
||||
}
|
||||
|
||||
.home-proxy-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
padding-left: 96px;
|
||||
}
|
||||
|
||||
.home-study-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -1032,8 +1066,14 @@ select {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.admin-table {
|
||||
width: 100%;
|
||||
.page-head-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.admin-table { width: 100%;
|
||||
min-width: 820px;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
@@ -1056,6 +1096,11 @@ select {
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.admin-table .pick {
|
||||
width: 36px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.admin-table .employee,
|
||||
.admin-table .when {
|
||||
font-variant-numeric: tabular-nums;
|
||||
|
||||
Reference in New Issue
Block a user