feat: 账号可配置 HTTP/HTTPS/SOCKS 代理

This commit is contained in:
2026-11-15 01:21:17 +08:00
parent 1141df17f7
commit e9a1e9b315
15 changed files with 848 additions and 55 deletions
+45
View File
@@ -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
View File
@@ -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)
+4 -1
View File
@@ -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():
+5
View File
@@ -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
View File
@@ -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 = ""
+14 -4
View File
@@ -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()