feat: 账号可设置同时学习课程数并支持关闭代理
This commit is contained in:
+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("代理密码过长")
|
||||
|
||||
Reference in New Issue
Block a user