feat: 账号可设置同时学习课程数并支持关闭代理
This commit is contained in:
+21
-2
@@ -17,7 +17,9 @@ from admin.users import (
|
||||
list_users,
|
||||
read_credentials,
|
||||
read_proxy,
|
||||
read_course_workers,
|
||||
read_study_start,
|
||||
set_course_workers,
|
||||
set_paused,
|
||||
set_proxy,
|
||||
set_study_start,
|
||||
@@ -49,8 +51,8 @@ class PauseBody(BaseModel):
|
||||
class AdminProxyBody(BaseModel):
|
||||
employee_ids: list[str]
|
||||
scheme: str
|
||||
host: str
|
||||
port: int
|
||||
host: str = ""
|
||||
port: int | None = None
|
||||
username: str = ""
|
||||
password: str | None = None
|
||||
|
||||
@@ -67,6 +69,11 @@ class AdminStudyStartBody(BaseModel):
|
||||
second: int
|
||||
|
||||
|
||||
class AdminCourseWorkersBody(BaseModel):
|
||||
employee_ids: list[str]
|
||||
workers: int
|
||||
|
||||
|
||||
def require_admin(request: Request) -> str:
|
||||
if not admin_session_active(request.cookies):
|
||||
raise HTTPException(status_code=401, detail="未登录")
|
||||
@@ -186,6 +193,18 @@ def get_user_study_start(employee_id: str, db: Session = Depends(get_db), _: str
|
||||
return read_study_start(db, employee_id)
|
||||
|
||||
|
||||
@admin_router.put("/users/course-workers")
|
||||
def put_users_course_workers(
|
||||
body: AdminCourseWorkersBody, db: Session = Depends(get_db), _: str = Depends(require_admin)
|
||||
) -> dict:
|
||||
return set_course_workers(db, body.employee_ids, body.workers)
|
||||
|
||||
|
||||
@admin_router.get("/users/{employee_id}/course-workers")
|
||||
def get_user_course_workers(employee_id: str, db: Session = Depends(get_db), _: str = Depends(require_admin)) -> dict:
|
||||
return read_course_workers(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)
|
||||
|
||||
+23
-2
@@ -11,6 +11,10 @@ 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, summary_of, url_of, view_of
|
||||
from euniv.study_window import StudyWindowError
|
||||
from euniv.study_window import apply as apply_start
|
||||
@@ -76,6 +80,7 @@ def list_users(db: Session) -> list[dict]:
|
||||
"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),
|
||||
}
|
||||
for account in accounts
|
||||
]
|
||||
@@ -202,8 +207,8 @@ def set_proxy(
|
||||
db: Session,
|
||||
employee_ids: list[str],
|
||||
scheme: str,
|
||||
host: str,
|
||||
port: int,
|
||||
host: str = "",
|
||||
port: object = None,
|
||||
username: str = "",
|
||||
password: str | None = None,
|
||||
) -> dict:
|
||||
@@ -249,6 +254,22 @@ def set_study_start(
|
||||
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 delete_user(db: Session, employee_id: str) -> dict:
|
||||
account = _require(db, employee_id)
|
||||
db.delete(account)
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
"""账号同时学习的课程数。"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = "0010_course_workers"
|
||||
down_revision = "0009_study_start"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table("accounts") as batch:
|
||||
batch.add_column(sa.Column("course_workers", sa.Integer(), nullable=False, server_default="1"))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table("accounts") as batch:
|
||||
batch.drop_column("course_workers")
|
||||
+31
-2
@@ -40,8 +40,8 @@ class MonthlyTargetBody(_BaseModel):
|
||||
|
||||
class ProxyBody(_BaseModel):
|
||||
scheme: str
|
||||
host: str
|
||||
port: int
|
||||
host: str = ""
|
||||
port: int | None = None
|
||||
username: str = ""
|
||||
password: str | None = None
|
||||
|
||||
@@ -53,6 +53,10 @@ class StudyStartBody(_BaseModel):
|
||||
second: int
|
||||
|
||||
|
||||
class CourseWorkersBody(_BaseModel):
|
||||
workers: int
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
init_db()
|
||||
@@ -257,6 +261,31 @@ def put_study_start(body: StudyStartBody, request: Request, db: Session = Depend
|
||||
return view_of(account)
|
||||
|
||||
|
||||
@app.get("/api/settings/course-workers")
|
||||
def get_course_workers(request: Request, db: Session = Depends(get_db)) -> dict:
|
||||
from euniv.course_workers 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/course-workers")
|
||||
def put_course_workers(body: CourseWorkersBody, request: Request, db: Session = Depends(get_db)) -> dict:
|
||||
from euniv.course_workers import CourseWorkersError, 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.workers)
|
||||
except CourseWorkersError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
db.commit()
|
||||
return view_of(account)
|
||||
|
||||
|
||||
@app.get("/api/settings/proxy")
|
||||
def get_proxy(request: Request, db: Session = Depends(get_db)) -> dict:
|
||||
from euniv.proxy import view_of
|
||||
|
||||
+42
-39
@@ -25,13 +25,13 @@ import httpx
|
||||
from sqlalchemy import select
|
||||
|
||||
from euniv.client import EUNIV, STUDY_API, USER_AGENT, EunivClient, SessionExpired, _load_cookies
|
||||
from euniv.course_workers import of as course_workers_of
|
||||
from euniv.models import Account, Course
|
||||
from euniv.study_window import window_open
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
_MAX_CONCURRENT_USERS = 8
|
||||
_MAX_COURSE_PER_USER = 1
|
||||
_HOURS_REFRESH_SECONDS = 300.0
|
||||
|
||||
_lock = threading.Lock()
|
||||
@@ -384,6 +384,23 @@ def _halted(global_stop: asyncio.Event, hours: HoursWatcher) -> bool:
|
||||
return global_stop.is_set() or hours.user_stop.is_set()
|
||||
|
||||
|
||||
class CourseCursor:
|
||||
"""多协程顺着同一份课程表往下领,每门课只被领取一次。"""
|
||||
|
||||
def __init__(self, courses: list) -> None:
|
||||
self._courses = list(courses)
|
||||
self._index = 0
|
||||
self._lock = asyncio.Lock()
|
||||
|
||||
async def take(self):
|
||||
async with self._lock:
|
||||
if self._index >= len(self._courses):
|
||||
return None
|
||||
item = self._courses[self._index]
|
||||
self._index += 1
|
||||
return item
|
||||
|
||||
|
||||
async def _study_video(session: StudySession, kid: str, pkg_id: str,
|
||||
interval: int, stop: asyncio.Event, hours: HoursWatcher) -> None:
|
||||
view = 0
|
||||
@@ -611,7 +628,9 @@ class AutoStudyWorker:
|
||||
proxy = url_of(row)
|
||||
except Exception:
|
||||
continue
|
||||
eligible.append((row.employee_id, target, password, credential, proxy))
|
||||
eligible.append(
|
||||
(row.employee_id, target, password, credential, proxy, course_workers_of(row))
|
||||
)
|
||||
|
||||
if not course_list:
|
||||
_set_status(running=False, message="没有可用的用户或课程")
|
||||
@@ -628,8 +647,8 @@ class AutoStudyWorker:
|
||||
|
||||
sem = asyncio.Semaphore(_MAX_CONCURRENT_USERS)
|
||||
tasks = [
|
||||
self._study_user(emp_id, target, pw, cred, proxy, course_list, intervals, auto_mode, sem)
|
||||
for emp_id, target, pw, cred, proxy in eligible
|
||||
self._study_user(emp_id, target, pw, cred, proxy, workers, course_list, intervals, auto_mode, sem)
|
||||
for emp_id, target, pw, cred, proxy, workers in eligible
|
||||
]
|
||||
results = await asyncio.gather(*tasks, return_exceptions=True)
|
||||
for emp_id_tuple, result in zip(eligible, results):
|
||||
@@ -641,12 +660,11 @@ class AutoStudyWorker:
|
||||
|
||||
async def _study_user(self, employee_id: str, target: int,
|
||||
password: str, credential: dict, proxy: str | None,
|
||||
course_list: list, intervals: dict,
|
||||
workers: int, 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="")
|
||||
max_courses = _MAX_COURSE_PER_USER
|
||||
loop = asyncio.get_event_loop()
|
||||
token, user_id, org_id, cookies = await loop.run_in_executor(
|
||||
None, _prepare_session, employee_id, password, credential, proxy)
|
||||
@@ -663,50 +681,34 @@ class AutoStudyWorker:
|
||||
return
|
||||
ticker = asyncio.create_task(hours.ticker(self._async_stop))
|
||||
try:
|
||||
if max_courses <= 1:
|
||||
await self._study_courses_serial(
|
||||
session, employee_id, course_list, intervals,
|
||||
auto_mode, hours, user_id, org_id)
|
||||
else:
|
||||
await self._study_courses_parallel(
|
||||
session, employee_id, course_list, intervals,
|
||||
auto_mode, hours, user_id, org_id, max_courses)
|
||||
await self._study_courses(
|
||||
session, employee_id, course_list, intervals,
|
||||
auto_mode, hours, user_id, org_id, workers)
|
||||
finally:
|
||||
ticker.cancel()
|
||||
with contextlib.suppress(asyncio.CancelledError):
|
||||
await ticker
|
||||
|
||||
async def _study_courses_serial(self, session: StudySession, employee_id: str,
|
||||
course_list: list, intervals: dict,
|
||||
auto_mode: bool, hours: HoursWatcher,
|
||||
user_id: str, org_id: str) -> None:
|
||||
async def _study_courses(self, session: StudySession, employee_id: str,
|
||||
course_list: list, intervals: dict,
|
||||
auto_mode: bool, hours: HoursWatcher,
|
||||
user_id: str, org_id: str, workers: int) -> None:
|
||||
"""N 个协程顺着课程表往下领,已完成的跳过,未完成的发心跳。"""
|
||||
assert self._async_stop is not None
|
||||
for path, title, kind in course_list:
|
||||
if _halted(self._async_stop, hours):
|
||||
return
|
||||
await self._study_one_course(
|
||||
session, employee_id, path, title, kind,
|
||||
intervals, auto_mode, hours, user_id, org_id)
|
||||
cursor = CourseCursor(course_list)
|
||||
count = max(1, min(8, int(workers or 1)))
|
||||
|
||||
async def _study_courses_parallel(self, session: StudySession, employee_id: str,
|
||||
course_list: list, intervals: dict,
|
||||
auto_mode: bool, hours: HoursWatcher,
|
||||
user_id: str, org_id: str,
|
||||
max_courses: int) -> None:
|
||||
"""同一用户同时学多门课。共享会话和学时监视。"""
|
||||
assert self._async_stop is not None
|
||||
course_sem = asyncio.Semaphore(max_courses)
|
||||
|
||||
async def guarded(path: str, title: str, kind: str) -> None:
|
||||
if _halted(self._async_stop, hours):
|
||||
return
|
||||
async with course_sem:
|
||||
async def worker() -> None:
|
||||
while not _halted(self._async_stop, hours):
|
||||
item = await cursor.take()
|
||||
if item is None:
|
||||
return
|
||||
path, title, kind = item
|
||||
await self._study_one_course(
|
||||
session, employee_id, path, title, kind,
|
||||
intervals, auto_mode, hours, user_id, org_id)
|
||||
|
||||
tasks = [guarded(p, t, k) for p, t, k in course_list]
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
await asyncio.gather(*(worker() for _ in range(count)))
|
||||
|
||||
async def _study_one_course(self, session: StudySession, employee_id: str,
|
||||
path: str, title: str, kind: str,
|
||||
@@ -754,6 +756,7 @@ class AutoStudyWorker:
|
||||
await _study_scorm(session, kid, "", interval, self._async_stop, hours,
|
||||
user_id, org_id)
|
||||
except SessionExpired:
|
||||
hours.user_stop.set()
|
||||
_set_user_status(employee_id, state="会话过期")
|
||||
log.info("用户 %s 会话过期", employee_id)
|
||||
except Exception as exc:
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
"""同一账号同时学习的课程数。默认 1,最多 8。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
DEFAULT = 1
|
||||
MAX = 8
|
||||
|
||||
|
||||
class CourseWorkersError(ValueError):
|
||||
"""同时学习课程数不符合要求。"""
|
||||
|
||||
|
||||
def validate(value: object) -> int:
|
||||
if not isinstance(value, int) or isinstance(value, bool) or not DEFAULT <= value <= MAX:
|
||||
raise CourseWorkersError(f"同时学习课程数须为 {DEFAULT} 到 {MAX} 的整数")
|
||||
return value
|
||||
|
||||
|
||||
def apply(account, value: object) -> None:
|
||||
account.course_workers = validate(value)
|
||||
|
||||
|
||||
def of(account) -> int:
|
||||
raw = int(getattr(account, "course_workers", DEFAULT) or DEFAULT)
|
||||
return max(DEFAULT, min(MAX, raw))
|
||||
|
||||
|
||||
def view_of(account) -> dict:
|
||||
workers = of(account)
|
||||
return {"workers": workers, "max": MAX, "recommended": workers == DEFAULT}
|
||||
@@ -56,3 +56,4 @@ class Account(Base):
|
||||
study_start_hour: Mapped[int] = mapped_column(nullable=False, default=0, server_default="0")
|
||||
study_start_minute: Mapped[int] = mapped_column(nullable=False, default=0, server_default="0")
|
||||
study_start_second: Mapped[int] = mapped_column(nullable=False, default=0, server_default="0")
|
||||
course_workers: Mapped[int] = mapped_column(nullable=False, default=1, server_default="1")
|
||||
|
||||
+12
-3
@@ -5,6 +5,7 @@ from __future__ import annotations
|
||||
from urllib.parse import quote, urlparse
|
||||
|
||||
SCHEMES = ("http", "https", "socks4", "socks5", "socks5h")
|
||||
OFF_SCHEMES = ("", "off", "none", "direct", "close")
|
||||
|
||||
|
||||
class ProxyError(ValueError):
|
||||
@@ -61,14 +62,19 @@ def validate_parts(scheme: str, host: str, port: object, username: str = "") ->
|
||||
return kind, address, port, user
|
||||
|
||||
|
||||
def is_off(scheme: str | None) -> bool:
|
||||
return (scheme or "").strip().lower() in OFF_SCHEMES
|
||||
|
||||
|
||||
def enabled(account) -> bool:
|
||||
return bool(account.proxy_scheme and account.proxy_host and account.proxy_port)
|
||||
|
||||
|
||||
def view_of(account) -> dict:
|
||||
on = enabled(account)
|
||||
return {
|
||||
"enabled": enabled(account),
|
||||
"scheme": account.proxy_scheme or "http",
|
||||
"enabled": on,
|
||||
"scheme": account.proxy_scheme if on else "off",
|
||||
"host": account.proxy_host or "",
|
||||
"port": int(account.proxy_port) if account.proxy_port else None,
|
||||
"username": account.proxy_username or "",
|
||||
@@ -99,7 +105,10 @@ def url_of(account) -> str | None:
|
||||
)
|
||||
|
||||
|
||||
def apply(account, scheme: str, host: str, port: object, username: str = "", password: str | None = None) -> None:
|
||||
def apply(account, scheme: str, host: str = "", port: object = None, username: str = "", password: str | None = None) -> None:
|
||||
if is_off(scheme):
|
||||
clear(account)
|
||||
return
|
||||
kind, address, number, user = validate_parts(scheme, host, port, username)
|
||||
if password is not None and len(str(password)) > 256:
|
||||
raise ProxyError("代理密码过长")
|
||||
|
||||
@@ -452,6 +452,7 @@ def test_check_skips_empty_credential_and_updates_saved_one() -> None:
|
||||
"study_start_hour",
|
||||
"study_start_minute",
|
||||
"study_start_second",
|
||||
"course_workers",
|
||||
}
|
||||
assert saved["has_credential"] is True
|
||||
assert saved["refresh_paused"] is False
|
||||
@@ -726,3 +727,67 @@ def test_admin_can_set_study_start_for_selected_users() -> None:
|
||||
assert two["study_start"] == "每月5日 16:08:09"
|
||||
detail = client.get("/api/admin/users/s1-user/study-start")
|
||||
assert detail.json()["day"] == 20
|
||||
|
||||
|
||||
def test_admin_can_set_course_workers_for_selected_users() -> None:
|
||||
_add_account("w1-user")
|
||||
_add_account("w2-user")
|
||||
api = _app()
|
||||
client = TestClient(api.app)
|
||||
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
|
||||
listed = client.get("/api/admin/users").json()
|
||||
one = next(item for item in listed if item["employee_id"] == "w1-user")
|
||||
assert one["course_workers"] == 1
|
||||
saved = client.put(
|
||||
"/api/admin/users/course-workers",
|
||||
json={"employee_ids": ["w1-user", "w2-user"], "workers": 4},
|
||||
)
|
||||
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"] == "w1-user")
|
||||
two = next(item for item in listed if item["employee_id"] == "w2-user")
|
||||
assert one["course_workers"] == 4
|
||||
assert two["course_workers"] == 4
|
||||
one_only = client.put(
|
||||
"/api/admin/users/course-workers",
|
||||
json={"employee_ids": ["w1-user"], "workers": 1},
|
||||
)
|
||||
assert one_only.status_code == 200
|
||||
listed = client.get("/api/admin/users").json()
|
||||
one = next(item for item in listed if item["employee_id"] == "w1-user")
|
||||
two = next(item for item in listed if item["employee_id"] == "w2-user")
|
||||
assert one["course_workers"] == 1
|
||||
assert two["course_workers"] == 4
|
||||
bad = client.put(
|
||||
"/api/admin/users/course-workers",
|
||||
json={"employee_ids": ["w1-user"], "workers": 9},
|
||||
)
|
||||
assert bad.status_code == 400
|
||||
detail = client.get("/api/admin/users/w1-user/course-workers")
|
||||
assert detail.json()["workers"] == 1
|
||||
|
||||
|
||||
def test_admin_can_turn_off_proxy_with_scheme() -> None:
|
||||
_add_account("off-user")
|
||||
api = _app()
|
||||
client = TestClient(api.app)
|
||||
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
|
||||
client.put(
|
||||
"/api/admin/users/proxy",
|
||||
json={"employee_ids": ["off-user"], "scheme": "http", "host": "10.0.0.1", "port": 8080},
|
||||
)
|
||||
listed = client.get("/api/admin/users").json()
|
||||
one = next(item for item in listed if item["employee_id"] == "off-user")
|
||||
assert one["has_proxy"] is True
|
||||
closed = client.put(
|
||||
"/api/admin/users/proxy",
|
||||
json={"employee_ids": ["off-user"], "scheme": "off"},
|
||||
)
|
||||
assert closed.status_code == 200
|
||||
listed = client.get("/api/admin/users").json()
|
||||
one = next(item for item in listed if item["employee_id"] == "off-user")
|
||||
assert one["has_proxy"] is False
|
||||
detail = client.get("/api/admin/users/off-user/proxy")
|
||||
assert detail.json()["enabled"] is False
|
||||
assert detail.json()["scheme"] == "off"
|
||||
|
||||
@@ -121,6 +121,7 @@ def test_login_stores_password_and_credential_only() -> None:
|
||||
"study_start_hour",
|
||||
"study_start_minute",
|
||||
"study_start_second",
|
||||
"course_workers",
|
||||
}
|
||||
|
||||
home = client.get("/api/home")
|
||||
@@ -456,6 +457,7 @@ def test_user_can_set_proxy_with_or_without_password() -> None:
|
||||
empty = client.get("/api/settings/proxy")
|
||||
assert empty.status_code == 200
|
||||
assert empty.json()["enabled"] is False
|
||||
assert empty.json()["scheme"] == "off"
|
||||
assert "password" not in empty.json()
|
||||
saved = client.put(
|
||||
"/api/settings/proxy",
|
||||
@@ -490,6 +492,30 @@ def test_user_can_set_proxy_with_or_without_password() -> None:
|
||||
cleared = client.delete("/api/settings/proxy")
|
||||
assert cleared.status_code == 200
|
||||
assert cleared.json()["enabled"] is False
|
||||
assert cleared.json()["scheme"] == "off"
|
||||
off = client.put("/api/settings/proxy", json={"scheme": "off"})
|
||||
assert off.status_code == 200
|
||||
assert off.json()["enabled"] is False
|
||||
assert off.json()["scheme"] == "off"
|
||||
|
||||
|
||||
def test_user_can_set_course_workers() -> 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/course-workers")
|
||||
assert empty.status_code == 200
|
||||
assert empty.json() == {"workers": 1, "max": 8, "recommended": True}
|
||||
saved = client.put("/api/settings/course-workers", json={"workers": 3})
|
||||
assert saved.status_code == 200
|
||||
assert saved.json() == {"workers": 3, "max": 8, "recommended": False}
|
||||
bad = client.put("/api/settings/course-workers", json={"workers": 9})
|
||||
assert bad.status_code == 400
|
||||
|
||||
|
||||
def test_user_can_set_monthly_study_start() -> None:
|
||||
|
||||
@@ -4,8 +4,9 @@ import pytest
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from euniv.autostudy import HoursWatcher, _parse_minutes, _study_video, wait_stop
|
||||
from euniv.proxy import ProxyError, build_proxy_url, parse_proxy
|
||||
from euniv.autostudy import CourseCursor, HoursWatcher, _parse_minutes, _study_video, wait_stop
|
||||
from euniv.course_workers import CourseWorkersError, of as workers_of, validate as validate_workers
|
||||
from euniv.proxy import ProxyError, apply as apply_proxy, build_proxy_url, parse_proxy, view_of as proxy_view
|
||||
from euniv.study_window import CN_TZ, StudyWindowError, validate_start, window_open
|
||||
|
||||
|
||||
@@ -192,3 +193,54 @@ def test_study_window_rejects_invalid_parts() -> None:
|
||||
validate_start(32, 0, 0, 0)
|
||||
with pytest.raises(StudyWindowError):
|
||||
validate_start(1, 24, 0, 0)
|
||||
|
||||
|
||||
def test_course_workers_default_and_range() -> None:
|
||||
class Account:
|
||||
course_workers = 1
|
||||
|
||||
assert workers_of(Account()) == 1
|
||||
assert validate_workers(8) == 8
|
||||
with pytest.raises(CourseWorkersError):
|
||||
validate_workers(0)
|
||||
with pytest.raises(CourseWorkersError):
|
||||
validate_workers(9)
|
||||
|
||||
|
||||
def test_course_cursor_hands_each_item_once() -> None:
|
||||
async def main() -> None:
|
||||
cursor = CourseCursor([("a", "A", "视频"), ("b", "B", "文档"), ("c", "C", "课程")])
|
||||
seen: list[str] = []
|
||||
|
||||
async def worker() -> None:
|
||||
while True:
|
||||
item = await cursor.take()
|
||||
if item is None:
|
||||
return
|
||||
seen.append(item[0])
|
||||
await asyncio.sleep(0)
|
||||
|
||||
await asyncio.gather(worker(), worker(), worker())
|
||||
assert sorted(seen) == ["a", "b", "c"]
|
||||
|
||||
asyncio.run(main())
|
||||
|
||||
|
||||
class _ProxyAccount:
|
||||
def __init__(self) -> None:
|
||||
self.proxy_scheme = "http"
|
||||
self.proxy_host = "10.0.0.1"
|
||||
self.proxy_port = 8080
|
||||
self.proxy_username = "u"
|
||||
self.proxy_password_cipher = "cipher"
|
||||
|
||||
|
||||
def test_proxy_off_scheme_clears_settings() -> None:
|
||||
account = _ProxyAccount()
|
||||
apply_proxy(account, "off")
|
||||
view = proxy_view(account)
|
||||
assert view["enabled"] is False
|
||||
assert view["scheme"] == "off"
|
||||
assert account.proxy_scheme == ""
|
||||
assert account.proxy_host == ""
|
||||
assert account.proxy_port is None
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
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";
|
||||
import { NAlert, NButton, NCheckbox, NDropdown, NIcon, NInput, NInputNumber, NModal, NSelect, NTooltip, useDialog, type DropdownOption } from "naive-ui";
|
||||
import { HelpCircleOutline, SettingsOutline } from "@vicons/ionicons5";
|
||||
|
||||
interface UserRow {
|
||||
employee_id: string;
|
||||
@@ -17,6 +17,7 @@ interface UserRow {
|
||||
study_start_hour: number;
|
||||
study_start_minute: number;
|
||||
study_start_second: number;
|
||||
course_workers: number;
|
||||
}
|
||||
|
||||
interface SecretField {
|
||||
@@ -42,13 +43,15 @@ const proxyOpen = ref(false);
|
||||
const proxySaving = ref(false);
|
||||
const proxyError = ref("");
|
||||
const proxyIds = ref<string[]>([]);
|
||||
const proxyScheme = ref("http");
|
||||
const proxyScheme = ref("off");
|
||||
const proxyHost = ref("");
|
||||
const proxyPort = ref<number | null>(null);
|
||||
const proxyUser = ref("");
|
||||
const proxyPassword = ref("");
|
||||
const proxyHasPassword = ref(false);
|
||||
const proxyOff = computed(() => proxyScheme.value === "off");
|
||||
const proxyOptions = [
|
||||
{ label: "关闭", value: "off" },
|
||||
{ label: "HTTP", value: "http" },
|
||||
{ label: "HTTPS", value: "https" },
|
||||
{ label: "SOCKS4", value: "socks4" },
|
||||
@@ -62,6 +65,11 @@ const startDay = ref<number | null>(1);
|
||||
const startHour = ref<number | null>(0);
|
||||
const startMinute = ref<number | null>(0);
|
||||
const startSecond = ref<number | null>(0);
|
||||
const workersOpen = ref(false);
|
||||
const workersSaving = ref(false);
|
||||
const workersError = ref("");
|
||||
const workersIds = ref<string[]>([]);
|
||||
const workersValue = ref<number | null>(1);
|
||||
|
||||
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);
|
||||
@@ -111,6 +119,7 @@ function asUser(value: unknown): UserRow | null {
|
||||
study_start_hour: typeof value.study_start_hour === "number" ? value.study_start_hour : 0,
|
||||
study_start_minute: typeof value.study_start_minute === "number" ? value.study_start_minute : 0,
|
||||
study_start_second: typeof value.study_start_second === "number" ? value.study_start_second : 0,
|
||||
course_workers: typeof value.course_workers === "number" ? value.course_workers : 1,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -342,7 +351,7 @@ function toggleAll(checked: boolean) {
|
||||
}
|
||||
|
||||
function resetProxyForm() {
|
||||
proxyScheme.value = "http";
|
||||
proxyScheme.value = "off";
|
||||
proxyHost.value = "";
|
||||
proxyPort.value = null;
|
||||
proxyUser.value = "";
|
||||
@@ -361,7 +370,7 @@ async function openProxy(ids: string[]) {
|
||||
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";
|
||||
proxyScheme.value = textOf(payload.scheme) || "off";
|
||||
proxyHost.value = textOf(payload.host);
|
||||
proxyPort.value = typeof payload.port === "number" ? payload.port : null;
|
||||
proxyUser.value = textOf(payload.username);
|
||||
@@ -379,27 +388,33 @@ function proxyPasswordPayload() {
|
||||
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;
|
||||
if (!proxyOff.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(),
|
||||
}),
|
||||
body: JSON.stringify(
|
||||
proxyOff.value
|
||||
? { employee_ids: proxyIds.value, scheme: "off" }
|
||||
: {
|
||||
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) {
|
||||
@@ -509,6 +524,49 @@ async function saveStart() {
|
||||
}
|
||||
}
|
||||
|
||||
function openWorkers(ids: string[]) {
|
||||
if (!ids.length) return;
|
||||
workersIds.value = ids;
|
||||
workersError.value = "";
|
||||
workersValue.value = 1;
|
||||
if (ids.length === 1) {
|
||||
const row = users.value.find((item) => item.employee_id === ids[0]);
|
||||
if (row) workersValue.value = row.course_workers;
|
||||
}
|
||||
workersOpen.value = true;
|
||||
}
|
||||
|
||||
async function saveWorkers() {
|
||||
if (workersSaving.value || !workersIds.value.length) return;
|
||||
workersError.value = "";
|
||||
if (workersValue.value == null || !Number.isInteger(workersValue.value) || workersValue.value < 1 || workersValue.value > 8) {
|
||||
workersError.value = "同时学习课程数须为 1 到 8";
|
||||
return;
|
||||
}
|
||||
workersSaving.value = true;
|
||||
try {
|
||||
const response = await fetch("/api/admin/users/course-workers", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
employee_ids: workersIds.value,
|
||||
workers: workersValue.value,
|
||||
}),
|
||||
});
|
||||
const payload: unknown = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
workersError.value = detailOf(payload, "没有保存。");
|
||||
return;
|
||||
}
|
||||
workersOpen.value = false;
|
||||
await load();
|
||||
} catch {
|
||||
workersError.value = "没有保存。";
|
||||
} finally {
|
||||
workersSaving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function rowActions(row: UserRow): DropdownOption[] {
|
||||
const busy = checkingAll.value || checkingId.value !== "";
|
||||
return [
|
||||
@@ -517,6 +575,7 @@ function rowActions(row: UserRow): DropdownOption[] {
|
||||
{ label: "设置代理", key: "proxy" },
|
||||
{ label: "清除代理", key: "proxy-clear" },
|
||||
{ label: "开始时刻", key: "start" },
|
||||
{ label: "同时课程", key: "workers" },
|
||||
{ label: row.refresh_paused ? "恢复自动刷新" : "停止自动刷新", key: "refresh" },
|
||||
{ label: "删除", key: "delete", props: { style: { color: "var(--danger)" } } },
|
||||
];
|
||||
@@ -528,6 +587,7 @@ function onRowAction(row: UserRow, key: string | number) {
|
||||
else if (key === "proxy") void openProxy([row.employee_id]);
|
||||
else if (key === "proxy-clear") confirmClearProxy([row.employee_id]);
|
||||
else if (key === "start") openStart([row.employee_id]);
|
||||
else if (key === "workers") openWorkers([row.employee_id]);
|
||||
else if (key === "refresh") confirmRefresh(row);
|
||||
else if (key === "delete") confirmDelete(row);
|
||||
}
|
||||
@@ -545,6 +605,7 @@ onMounted(() => {
|
||||
<n-button :disabled="!pickedIds.length" @click="openProxy(pickedIds)">设置代理</n-button>
|
||||
<n-button :disabled="!pickedIds.length" @click="confirmClearProxy(pickedIds)">清除代理</n-button>
|
||||
<n-button :disabled="!pickedIds.length" @click="openStart(pickedIds)">开始时刻</n-button>
|
||||
<n-button :disabled="!pickedIds.length" @click="openWorkers(pickedIds)">同时课程</n-button>
|
||||
<n-button :loading="checkingAll" :disabled="checkingAll || checkingId !== '' || !users.length" @click="checkAll">检查全部</n-button>
|
||||
</div>
|
||||
</header>
|
||||
@@ -562,6 +623,7 @@ onMounted(() => {
|
||||
<th>凭据是否有效</th>
|
||||
<th>本月学时</th>
|
||||
<th>开始时刻</th>
|
||||
<th>同时课程</th>
|
||||
<th>代理</th>
|
||||
<th>上次刷新时间</th>
|
||||
<th>自动刷新</th>
|
||||
@@ -578,6 +640,7 @@ onMounted(() => {
|
||||
<td :class="validityClass(validityText(row))">{{ validityText(row) }}</td>
|
||||
<td class="when">{{ row.month_hours || "—" }}</td>
|
||||
<td class="when">{{ row.study_start || "—" }}</td>
|
||||
<td class="when">{{ row.course_workers }}{{ row.course_workers === 1 ? "(推荐)" : "" }}</td>
|
||||
<td class="when">{{ row.proxy || "—" }}</td>
|
||||
<td class="when">{{ formatRefreshTime(row.last_refresh_at) }}</td>
|
||||
<td>{{ row.refresh_paused ? "已停止" : "开启" }}</td>
|
||||
@@ -631,15 +694,15 @@ onMounted(() => {
|
||||
</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" />
|
||||
<n-input id="admin-proxy-host" v-model:value="proxyHost" placeholder="例如 127.0.0.1" :disabled="proxyOff" />
|
||||
</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" />
|
||||
<n-input-number id="admin-proxy-port" v-model:value="proxyPort" button-placement="both" :min="1" :max="65535" :precision="0" :disabled="proxyOff" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="admin-proxy-user">账号</label>
|
||||
<n-input id="admin-proxy-user" v-model:value="proxyUser" placeholder="可不填" autocomplete="off" />
|
||||
<n-input id="admin-proxy-user" v-model:value="proxyUser" placeholder="可不填" autocomplete="off" :disabled="proxyOff" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="admin-proxy-password">密码</label>
|
||||
@@ -650,6 +713,7 @@ onMounted(() => {
|
||||
show-password-on="click"
|
||||
:placeholder="proxyIds.length === 1 && proxyHasPassword ? '已保存,留空则保持' : '可不填'"
|
||||
autocomplete="new-password"
|
||||
:disabled="proxyOff"
|
||||
/>
|
||||
</div>
|
||||
</form>
|
||||
@@ -693,5 +757,37 @@ onMounted(() => {
|
||||
</div>
|
||||
</template>
|
||||
</n-modal>
|
||||
<n-modal
|
||||
:show="workersOpen"
|
||||
preset="card"
|
||||
:title="workersIds.length === 1 ? `工号 ${workersIds[0]} 的同时课程` : `已选 ${workersIds.length} 个账号的同时课程`"
|
||||
:style="{ width: 'min(520px, calc(100vw - 32px))' }"
|
||||
@update:show="(show) => (workersOpen = show)"
|
||||
>
|
||||
<n-alert v-if="workersError" class="admin-alert" type="error">{{ workersError }}</n-alert>
|
||||
<form class="settings-form" @submit.prevent="saveWorkers">
|
||||
<div class="form-row">
|
||||
<label class="field-title" for="admin-course-workers">
|
||||
<span>同时学习</span>
|
||||
<n-tooltip placement="top">
|
||||
<template #trigger>
|
||||
<button type="button" class="hint-icon" aria-label="说明">
|
||||
<n-icon><HelpCircleOutline /></n-icon>
|
||||
</button>
|
||||
</template>
|
||||
速度较慢,但是稳定且不容易触发风控,最大可设置8
|
||||
</n-tooltip>
|
||||
</label>
|
||||
<n-input-number id="admin-course-workers" v-model:value="workersValue" button-placement="both" :min="1" :max="8" :precision="0" />
|
||||
</div>
|
||||
<p v-if="workersValue === 1" class="form-hint">1 门为推荐</p>
|
||||
</form>
|
||||
<template #footer>
|
||||
<div class="modal-actions">
|
||||
<n-button @click="workersOpen = false">取消</n-button>
|
||||
<n-button type="primary" :loading="workersSaving" @click="saveWorkers">保存</n-button>
|
||||
</div>
|
||||
</template>
|
||||
</n-modal>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from "vue";
|
||||
import { NAlert, NButton, NIcon, NInput, NInputNumber, NSelect, NTooltip } from "naive-ui";
|
||||
import { RefreshOutline } from "@vicons/ionicons5";
|
||||
import { HelpCircleOutline, RefreshOutline } from "@vicons/ionicons5";
|
||||
|
||||
interface HomeSummary {
|
||||
name: string;
|
||||
@@ -180,16 +180,49 @@ function saveStart() {
|
||||
|
||||
watch([startDay, startHour, startMinute, startSecond], () => { if (startLoaded.value) saveStart(); });
|
||||
|
||||
const workersLoaded = ref(false);
|
||||
const courseWorkers = ref<number | null>(1);
|
||||
let workersSaveTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
async function loadWorkers() {
|
||||
try {
|
||||
const res = await fetch("/api/settings/course-workers");
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
courseWorkers.value = typeof data.workers === "number" ? data.workers : 1;
|
||||
workersLoaded.value = true;
|
||||
}
|
||||
} catch { /* 静默 */ }
|
||||
}
|
||||
|
||||
function saveWorkers(value: number | null) {
|
||||
if (value == null || !Number.isInteger(value) || value < 1 || value > 8) return;
|
||||
clearTimeout(workersSaveTimer);
|
||||
workersSaveTimer = setTimeout(async () => {
|
||||
try {
|
||||
await fetch("/api/settings/course-workers", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ workers: value }),
|
||||
});
|
||||
} catch { /* 静默 */ }
|
||||
}, 600);
|
||||
}
|
||||
|
||||
watch(courseWorkers, (v) => { if (workersLoaded.value) saveWorkers(v); });
|
||||
|
||||
const proxyLoaded = ref(false);
|
||||
const proxySaving = ref(false);
|
||||
const proxyError = ref("");
|
||||
const proxyScheme = ref("http");
|
||||
const proxyScheme = ref("off");
|
||||
const proxyHost = ref("");
|
||||
const proxyPort = ref<number | null>(null);
|
||||
const proxyUser = ref("");
|
||||
const proxyPassword = ref("");
|
||||
const proxyHasPassword = ref(false);
|
||||
const proxyOff = computed(() => proxyScheme.value === "off");
|
||||
const proxyOptions = [
|
||||
{ label: "关闭", value: "off" },
|
||||
{ label: "HTTP", value: "http" },
|
||||
{ label: "HTTPS", value: "https" },
|
||||
{ label: "SOCKS4", value: "socks4" },
|
||||
@@ -201,7 +234,7 @@ async function loadProxy() {
|
||||
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";
|
||||
proxyScheme.value = typeof data.scheme === "string" && data.scheme ? data.scheme : "off";
|
||||
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 : "";
|
||||
@@ -220,26 +253,32 @@ function proxyPasswordPayload() {
|
||||
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;
|
||||
if (!proxyOff.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(),
|
||||
}),
|
||||
body: JSON.stringify(
|
||||
proxyOff.value
|
||||
? { scheme: "off" }
|
||||
: {
|
||||
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) {
|
||||
@@ -248,6 +287,12 @@ async function saveProxy() {
|
||||
}
|
||||
proxyPassword.value = "";
|
||||
proxyHasPassword.value = data.has_password === true;
|
||||
if (proxyOff.value) {
|
||||
proxyHost.value = "";
|
||||
proxyPort.value = null;
|
||||
proxyUser.value = "";
|
||||
proxyHasPassword.value = false;
|
||||
}
|
||||
} catch {
|
||||
proxyError.value = "没有保存。";
|
||||
} finally {
|
||||
@@ -255,30 +300,6 @@ async function saveProxy() {
|
||||
}
|
||||
}
|
||||
|
||||
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");
|
||||
@@ -286,7 +307,7 @@ async function loadStudyStatus() {
|
||||
} catch { /* 静默 */ }
|
||||
}
|
||||
|
||||
onMounted(() => { refresh(); loadTarget(); loadStart(); loadProxy(); loadStudyStatus(); });
|
||||
onMounted(() => { refresh(); loadTarget(); loadStart(); loadWorkers(); loadProxy(); loadStudyStatus(); });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -369,6 +390,32 @@ onMounted(() => { refresh(); loadTarget(); loadStart(); loadProxy(); loadStudySt
|
||||
<n-input-number v-model:value="startSecond" button-placement="both" :min="0" :max="59" :precision="0" size="small" />
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="workersLoaded" class="home-target">
|
||||
<label class="field-title" for="course-workers">
|
||||
<span>同时学习课程</span>
|
||||
<n-tooltip placement="top">
|
||||
<template #trigger>
|
||||
<button type="button" class="hint-icon" aria-label="说明">
|
||||
<n-icon><HelpCircleOutline /></n-icon>
|
||||
</button>
|
||||
</template>
|
||||
速度较慢,但是稳定且不容易触发风控,最大可设置8
|
||||
</n-tooltip>
|
||||
</label>
|
||||
<div class="target-control">
|
||||
<n-input-number
|
||||
id="course-workers"
|
||||
v-model:value="courseWorkers"
|
||||
button-placement="both"
|
||||
:min="1"
|
||||
:max="8"
|
||||
:precision="0"
|
||||
size="small"
|
||||
/>
|
||||
<span class="target-unit">门</span>
|
||||
<span v-if="courseWorkers === 1" class="recommend-mark">推荐</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">
|
||||
@@ -377,15 +424,15 @@ onMounted(() => { refresh(); loadTarget(); loadStart(); loadProxy(); loadStudySt
|
||||
</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" />
|
||||
<n-input id="proxy-host" v-model:value="proxyHost" size="small" placeholder="例如 127.0.0.1" :disabled="proxyOff" />
|
||||
</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" />
|
||||
<n-input-number id="proxy-port" v-model:value="proxyPort" size="small" button-placement="both" :min="1" :max="65535" :precision="0" :disabled="proxyOff" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="proxy-user">代理账号</label>
|
||||
<n-input id="proxy-user" v-model:value="proxyUser" size="small" placeholder="可不填" autocomplete="off" />
|
||||
<n-input id="proxy-user" v-model:value="proxyUser" size="small" placeholder="可不填" autocomplete="off" :disabled="proxyOff" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="proxy-password">代理密码</label>
|
||||
@@ -397,11 +444,11 @@ onMounted(() => { refresh(); loadTarget(); loadStart(); loadProxy(); loadStudySt
|
||||
show-password-on="click"
|
||||
:placeholder="proxyHasPassword ? '已保存,留空则保持' : '可不填'"
|
||||
autocomplete="new-password"
|
||||
:disabled="proxyOff"
|
||||
/>
|
||||
</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">
|
||||
|
||||
@@ -419,6 +419,34 @@ select {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.field-title {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.hint-icon {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.hint-icon .n-icon {
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.recommend-mark {
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.target-control {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
Reference in New Issue
Block a user