feat: 账号可设置同时学习课程数并支持关闭代理

This commit is contained in:
2026-11-15 01:48:39 +08:00
parent ecd774507f
commit aa26d00c60
14 changed files with 564 additions and 119 deletions
+42 -39
View File
@@ -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: