Files
EnuivTools/backend/euniv/autostudy.py
T

1929 lines
73 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""自动学习:asyncio 并发遍历用户和课程,发送心跳积累学时。
架构:
- 一个后台线程运行独立的 asyncio 事件循环
- 每个用户一个协程,asyncio.gather 并行
- 全局 Semaphore 控制总并发,避免压爆上游
- 每个用户一个 StudySession(httpx.AsyncClient),代理仅 HTTP/HTTPS/SOCKS4/SOCKS5
- 每个用户可配置同时学几门课(当前默认 1,结构已预留)
- 心跳间隔用 asyncio.sleep,不占线程
- 本月学时:看完一门课后刷新,学习过程中每 1 分钟刷新;达到阈值即停止该账号
"""
from __future__ import annotations
import asyncio
import json
import logging
import math
import random
import re
import threading
import time
from datetime import datetime, timezone
import httpx
from sqlalchemy import select
from euniv.client import (
EUNIV,
STUDY_API,
USER_AGENT,
EunivClient,
SessionExpired,
_load_cookies,
as_uuid,
compact_id,
play_page_params,
study_progress_fields,
)
from euniv.course_workers import of as course_workers_of
from euniv.models import Account, Course
from euniv.proxy import bind_url, is_proxy_failure, uses_pool
from euniv.study_control import eligible as study_eligible
from euniv.study_control import expire_pause, hours_met, stamp_hours
from euniv.study_window import as_cn, next_fire_at, next_month_start
log = logging.getLogger(__name__)
_MAX_CONCURRENT_USERS = 8
_HOURS_REFRESH_SECONDS = 60.0
_KEEP_LIVE = frozenset({"已达标", "已停止", "会话失效", "学习失败", "已学完"})
_lock = threading.Lock()
_status: dict = {"running": False, "users": {}, "message": "", "updated_at": ""}
_halt_lock = threading.Lock()
_user_halts: dict[str, asyncio.Event] = {}
_wanted: dict[str, int] = {}
_wanted_seq = 0
_running: set[str] = set()
_retry_at: dict[str, float] = {}
_retry_count: dict[str, int] = {}
_done_month: dict[str, str] = {}
_targets: dict[str, int] = {}
_RETRY_STEPS = (5 * 60, 15 * 60, 60 * 60)
_HOUR_FAIL_LIMIT = 5
_worker = None
def _workers_list(info: dict) -> list[dict]:
workers = info.get("workers") or {}
if isinstance(workers, list):
return [dict(item) for item in workers if isinstance(item, dict)]
if not isinstance(workers, dict):
return []
rows = []
for key in sorted(workers, key=lambda value: int(value) if str(value).isdigit() else 0):
item = workers[key]
if not isinstance(item, dict):
continue
row = dict(item)
row.setdefault("id", int(key) if str(key).isdigit() else key)
rows.append(row)
return rows
def autostudy_status() -> dict:
with _lock:
raw = {key: value for key, value in _status.items() if key != "users"}
users_in = dict(_status.get("users") or {})
copied = {eid: dict(info) for eid, info in users_in.items()}
for info in copied.values():
info["workers"] = _workers_list(info)
raw["users"] = copied
return raw
def _notify(employee_id: str = "", urgent: bool = False) -> None:
try:
from euniv.study_push import notify
notify(employee_id or None, urgent=urgent)
except Exception:
return
def _set_status(**kw: object) -> None:
with _lock:
_status.update(kw)
_status["updated_at"] = datetime.now(timezone.utc).isoformat()
_notify()
def _set_user_status(employee_id: str, **kw: object) -> None:
from euniv.study_window import month_key
with _lock:
users = _status.setdefault("users", {})
info = users.setdefault(employee_id, {})
info.update(kw)
info["month"] = str(kw["month"]) if "month" in kw else month_key()
_status["updated_at"] = datetime.now(timezone.utc).isoformat()
_notify(employee_id)
def _clear_user_status(employee_id: str) -> None:
with _lock:
_status.get("users", {}).pop(employee_id, None)
_notify(employee_id)
def _drop_live_hours(employee_id: str) -> None:
with _lock:
info = (_status.get("users") or {}).get(employee_id)
if isinstance(info, dict):
info.pop("month_hours", None)
def _finish_user(employee_id: str, error: BaseException | None = None) -> None:
"""周期结束时保留失败/达标,避免首页只剩「等待执行」。"""
if error is not None:
log.warning("用户 %s 学习没有完成: %s", employee_id, error)
_set_user_status(employee_id, state="学习失败", message="学习没有完成", workers={}, course="")
_drop_live_hours(employee_id)
return
with _lock:
info = (_status.get("users") or {}).get(employee_id) or {}
state = str(info.get("state") or "")
if state in _KEEP_LIVE:
_set_user_status(employee_id, workers={}, course="")
_drop_live_hours(employee_id)
return
_clear_user_status(employee_id)
def _set_worker_status(employee_id: str, worker_id: int, **kw: object) -> None:
with _lock:
users = _status.setdefault("users", {})
info = users.setdefault(employee_id, {})
workers = info.setdefault("workers", {})
if not isinstance(workers, dict):
workers = {}
info["workers"] = workers
row = workers.setdefault(str(worker_id), {"id": worker_id})
row.update(kw)
course = kw.get("course")
if isinstance(course, str) and course:
info["course"] = course
_status["updated_at"] = datetime.now(timezone.utc).isoformat()
_notify(employee_id)
class WorkerView:
def __init__(self, employee_id: str, worker_id: int) -> None:
self.employee_id = employee_id
self.worker_id = worker_id
self.sent = 0
self.total = 0
self._course = ""
self._origin = 0.0
def update(self, **kw: object) -> None:
course = kw.get("course")
marker = kw.get("knowledge_id")
if not isinstance(marker, str) or not marker:
marker = course if isinstance(course, str) else ""
if isinstance(marker, str) and marker and marker != self._course:
self._course = marker
self.sent = 0
self.total = 0
self._origin = 0.0
try:
self._origin = float(kw.get("progress") or 0)
except (TypeError, ValueError):
self._origin = 0.0
kw = dict(kw)
kw.setdefault("sent", 0)
kw.setdefault("total", 0)
kw["interval"] = 0
kw["heartbeat_at"] = 0
kw["heartbeat_in"] = 0
_set_worker_status(self.employee_id, self.worker_id, **kw)
def after_beat(self, progress: float, **kw: object) -> None:
self.sent += 1
planned = _count_total(self.sent, progress, self._origin)
if self.total <= 0:
self.total = planned
elif progress >= 100:
self.total = self.sent
elif planned > self.total:
self.total = planned
if self.sent > self.total:
self.total = self.sent
self.update(progress=progress, sent=self.sent, total=self.total, **kw)
def _touch(worker: WorkerView | None, **kw: object) -> None:
if worker is not None:
worker.update(**kw)
def _beat(worker: WorkerView | None, progress: float, **kw: object) -> None:
if worker is not None:
worker.after_beat(progress, **kw)
return
_touch(worker, progress=progress, **kw)
def _progress_of(payload: dict) -> float:
raw = payload.get("studyschedule")
if raw is None:
raw = payload.get("studySchedule")
try:
return max(0.0, min(100.0, float(raw or 0)))
except (TypeError, ValueError):
return 0.0
class _Stall:
"""累计申报满 5 分钟仍无进度时放弃,避免短间隔把一门课打成死循环。"""
def __init__(self) -> None:
self.declared = 0
self.baseline: float | None = None
def stuck(self, progress: float, sent: int) -> bool:
if self.baseline is None:
self.baseline = progress
elif progress > self.baseline + 0.01:
self.baseline = progress
self.declared = 0
self.declared += max(0, sent)
return self.declared >= 300 and progress <= self.baseline + 0.01
def _completed(payload: dict) -> bool:
if not isinstance(payload, dict):
return False
if _progress_of(payload) >= 100:
return True
return str(payload.get("status") or "").strip().lower() == "completed"
def _payload_time(wait: int, fallback: int) -> int:
if wait > 0:
return int(wait)
return max(1, int(fallback or 1))
def _interval_plan(ctype: str, intervals: dict, auto_mode: bool, params: dict) -> tuple[int, int, int]:
"""返回 (等待秒, 心跳 studyTime, pageSize)。等待 0 表示连续发送,studyTime 仍用播放页间隔。"""
video = ctype == "video"
wait = int(intervals.get(ctype, 30 if video else 120) or 0)
fallback = int((params or {}).get("submitProTimes" if video else "validtimeSpan") or (30 if video else 120))
if auto_mode:
wait = max(1, fallback)
page_size = max(1, int((params or {}).get("pageSize") or 1))
return wait, _payload_time(wait, fallback), page_size
def _current_intervals() -> tuple[dict, bool]:
from admin.settings import heartbeat_intervals
cfg = heartbeat_intervals()
return {
"video": int(cfg["video"]),
"document": int(cfg["document"]),
"scorm": int(cfg["scorm"]),
}, cfg["mode"] == "auto"
def _signal_stop(event: asyncio.Event | None) -> None:
if event is None:
return
worker = _worker
loop = getattr(worker, "_loop", None) if worker is not None else None
if loop is not None and loop.is_running():
loop.call_soon_threadsafe(event.set)
return
event.set()
def halt_work(employee_id: str) -> None:
key = (employee_id or "").strip()
if not key:
return
with _halt_lock:
_wanted.pop(key, None)
_running.discard(key)
event = _user_halts.get(key)
_signal_stop(event)
_notify(key, urgent=True)
def stop_account(employee_id: str) -> None:
"""停止学习、释放代理,并清掉内存里的状态和站点会话。"""
key = (employee_id or "").strip()
if not key:
return
request_stop(key)
from euniv.client import forget_site
from euniv.proxy_pool import release
release(key)
_clear_user_status(key)
forget_site(key)
def request_stop(employee_id: str) -> None:
key = (employee_id or "").strip()
if not key:
return
halt_work(key)
_set_user_status(key, state="已停止", course="")
def request_wake() -> None:
worker = _worker
if worker is not None:
worker.wake()
def clear_study_hold(employee_id: str) -> None:
key = (employee_id or "").strip()
_retry_at.pop(key, None)
_retry_count.pop(key, None)
_done_month.pop(key, None)
def note_attempt_end(employee_id: str) -> None:
with _lock:
info = (_status.get("users") or {}).get(employee_id) or {}
state = str(info.get("state") or "")
if state in ("学习失败", "会话失效"):
count = _retry_count.get(employee_id, 0)
delay = _RETRY_STEPS[min(count, len(_RETRY_STEPS) - 1)]
_retry_count[employee_id] = count + 1
_retry_at[employee_id] = time.time() + delay
return
if state == "已学完":
from euniv.study_window import month_key
_done_month[employee_id] = month_key()
_retry_at.pop(employee_id, None)
_retry_count.pop(employee_id, None)
def want_work(employee_id: str) -> None:
key = (employee_id or "").strip()
if not key:
return
global _wanted_seq
with _halt_lock:
if key not in _wanted:
_wanted_seq += 1
_wanted[key] = _wanted_seq
_notify(key, urgent=True)
def drop_work(employee_id: str) -> None:
key = (employee_id or "").strip()
if not key:
return
with _halt_lock:
_wanted.pop(key, None)
_notify(key, urgent=True)
def is_wanted(employee_id: str) -> bool:
key = (employee_id or "").strip()
with _halt_lock:
return key in _wanted
def work_running(employee_id: str) -> bool:
return is_studying(employee_id) or is_wanted(employee_id)
def sync_work(employee_id: str) -> None:
"""保存配置或点开始后:达标则停,到期且未达标则拉起该账号的 work。"""
from euniv.db import SessionLocal
from euniv.models import Account
key = (employee_id or "").strip()
if not key:
return
with SessionLocal() as db:
account = db.get(Account, key)
if account is None:
return
if expire_pause(account):
db.commit()
raw_target = getattr(account, "monthly_target", None)
_targets[key] = int(raw_target) if raw_target is not None else 600
met = hours_met(account)
due = study_eligible(account)
if met:
halt_work(key)
return
if due:
want_work(key)
request_wake()
return
halt_work(key)
def restart_work(employee_id: str) -> None:
"""代理或学习配置变了,正在跑的这一轮先停掉,再按新配置评估。"""
key = (employee_id or "").strip()
if key and work_running(key):
halt_work(key)
sync_work(key)
_KIND_RANK = {"视频": 0, "文档": 1, "课程包": 2, "课程": 3}
def snapshot_courses(rows) -> list[tuple[str, str, str]]:
"""work 启动时的课程清单快照。排序固定为 视频-文档-课程包-课程。"""
items: list[tuple[str, str, str]] = []
for row in rows:
if isinstance(row, (tuple, list)):
path = str(row[0] if len(row) > 0 else "")
title = str(row[1] if len(row) > 1 else "")
kind = str(row[2] if len(row) > 2 else "")
else:
path = str(getattr(row, "path", "") or "")
title = str(getattr(row, "title", "") or "")
kind = str(getattr(row, "kind", "") or "")
items.append((path, title, kind))
items.sort(key=lambda item: (_KIND_RANK.get(item[2], 9), item[1], item[0]))
return items
def _release_pool(employee_id: str, pool: bool) -> None:
if not pool or not employee_id:
return
from euniv.proxy_pool import release
release(employee_id)
def _job_from_account(row) -> tuple | None:
"""从账号列表行提取一次凭据。之后 work 只用这份拷贝,不再读账号表。"""
from euniv.crypto import decrypt_secret
employee_id = str(getattr(row, "employee_id", "") or "")
target_raw = getattr(row, "monthly_target", None)
password_cipher = str(getattr(row, "password_cipher", "") or "")
credential_cipher = str(getattr(row, "credential_cipher", "") or "")
workers = course_workers_of(row)
pool = uses_pool(row)
target = int(target_raw) if target_raw is not None else 600
if target <= 0:
return None
try:
proxy = bind_url(row)
if pool and not proxy and employee_id:
_set_user_status(employee_id, message="正在直连")
except Exception as exc:
log.warning("用户 %s 凭据无法读取: %s", employee_id, exc)
_release_pool(employee_id, pool)
if employee_id:
_set_user_status(employee_id, state="学习失败", message="凭据无法读取")
return None
try:
password = decrypt_secret(password_cipher)
credential = json.loads(decrypt_secret(credential_cipher))
except Exception as exc:
log.warning("用户 %s 凭据无法读取: %s", employee_id, exc)
_release_pool(employee_id, pool)
if employee_id:
_set_user_status(employee_id, state="学习失败", message="凭据无法读取")
return None
if not isinstance(credential, dict):
_release_pool(employee_id, pool)
return None
if employee_id:
_targets[employee_id] = target
return (
employee_id,
target,
password,
credential,
proxy,
workers,
pool,
)
def is_studying(employee_id: str) -> bool:
key = (employee_id or "").strip()
with _halt_lock:
return key in _running
# ── 课程路径解析 ──
_ID_RE = re.compile(r"([0-9a-fA-F]{32})")
def _knowledge_id_from_path(path: str) -> str:
m = _ID_RE.search(path.replace("-", "").split(".")[0].split("/")[-1])
return m.group(1) if m else ""
def _course_type(kind: str, path: str) -> str:
if kind == "课程包" or "/package/" in path:
return "package"
if kind == "课程" or "/scorm/" in path:
return "scorm"
if kind == "视频" or "/video/" in path:
return "video"
if kind == "文档" or "/document/" in path:
return "document"
return "unknown"
def _play_path(kind: str, path: str, kid: str) -> str:
compact = compact_id(kid)
ctype = _course_type(kind, path)
if ctype == "video":
return f"/kng/view/video/{compact}.html"
if ctype == "document":
return f"/kng/view/document/{compact}.html"
if ctype == "scorm":
return f"/kng/view/scorm/{compact}.html"
if ctype == "package":
return f"/kng/view/package/{compact}.html"
return path
def _package_chapter_path(pkg_id: str, ch_kid: str, ch_type: str) -> str:
return f"/kng/course/package/{ch_type}/{compact_id(pkg_id)}_{compact_id(ch_kid)}.html"
async def _open_play(session: "StudySession", path: str) -> dict:
if not path:
return {}
try:
return await session.course_page_params(path)
except SessionExpired:
raise
except Exception:
log.debug("打开播放页失败 %s", path, exc_info=True)
return {}
def _count_total(sent: int, progress: float, origin: float = 0.0) -> int:
"""按开课进度估算剩余心跳数。总数在 WorkerView 里冻结,避免每拍都变。"""
if sent <= 0:
return 0
if progress >= 100:
return sent
gained = float(progress) - float(origin)
if gained <= 0:
return 0
span = max(0.0, 100.0 - float(origin))
if span <= 0:
return sent
return max(sent, int(math.ceil(sent * span / gained)))
def _jitter(seconds: int) -> float:
"""只往晚了偏,避免心跳比页面节奏更早发出。间隔为 0 时至少等 1 秒。"""
if seconds <= 0:
return 1.0
spread = min(3.0, max(0.3, float(seconds) * 0.1))
return float(seconds) + random.uniform(0.3, spread)
def _parse_minutes(value: str) -> int:
if not value:
return 0
m = re.search(r"(\d+)", value)
return int(m.group(1)) if m else 0
async def wait_stop(timeout: float, *events: asyncio.Event) -> bool:
"""等到任一事件触发或超时。触发返回 True,超时返回 False。"""
if any(event.is_set() for event in events):
return True
if timeout <= 0:
return False
tasks = [asyncio.create_task(event.wait()) for event in events]
done, pending = await asyncio.wait(tasks, timeout=timeout, return_when=asyncio.FIRST_COMPLETED)
for task in pending:
task.cancel()
if pending:
await asyncio.gather(*pending, return_exceptions=True)
return bool(done)
class HoursWatcher:
"""刷新本月学时。看完一门课或每 1 分钟查一次,达标后停止该账号。"""
def __init__(
self,
session: "StudySession",
employee_id: str,
target: int,
user_stop: asyncio.Event,
interval: float = _HOURS_REFRESH_SECONDS,
source: str = "api",
) -> None:
self.session = session
self.employee_id = employee_id
self.target = target
self.user_stop = user_stop
self.interval = interval
self.source = source if source in ("api", "history") else "api"
self._lock = asyncio.Lock()
self.reached = False
from euniv.study_window import month_key
self.month = month_key()
self.month_rolled = False
self._misses = 0
def current_target(self) -> int:
return int(_targets.get(self.employee_id, self.target))
async def refresh(self) -> bool:
from euniv.study_window import month_key
async with self._lock:
if self.reached or self.user_stop.is_set():
return True
if month_key() != self.month:
self.month_rolled = True
self.user_stop.set()
return True
try:
if self.source == "history":
current = int(await self.session.month_history_minutes())
text = str(current)
else:
text = await self.session.month_hours_text()
current = _parse_minutes(text)
if not text:
raise RuntimeError("学时没有解析到")
self._misses = 0
await asyncio.to_thread(_update_month_hours, self.employee_id, text)
target = self.current_target()
if target > 0 and current >= target:
self.reached = True
self.user_stop.set()
_set_user_status(self.employee_id, state="已达标")
await asyncio.to_thread(_release_ignore_window, self.employee_id)
return True
except Exception:
self._misses += 1
log.warning("用户 %s 刷新本月学时失败", self.employee_id, exc_info=True)
if self._misses >= _HOUR_FAIL_LIMIT:
self.user_stop.set()
_set_user_status(self.employee_id, state="学习失败", message="学时没有获取到")
return True
return False
async def ticker(self, global_stop: asyncio.Event) -> None:
while not global_stop.is_set() and not self.user_stop.is_set():
if await wait_stop(self.interval, global_stop, self.user_stop):
return
await self.refresh()
# ── Async 学习会话 ──
class StudySession:
"""一个用户的异步学习会话。包装 httpx.AsyncClient,提供心跳提交方法。
proxy 为 httpx URL,仅 HTTP/HTTPS/SOCKS4/SOCKS5。空值直连。
"""
def __init__(self, token: str, cookies: list[tuple[str, str, str, str]],
proxy: str | None = None, employee_id: str = "",
use_pool: bool = False) -> None:
from euniv.proxy import parse_proxy
self._token = token
self._initial_cookies = cookies
self._proxy = parse_proxy(proxy)
self._employee_id = employee_id
self._use_pool = use_pool
self._referer = EUNIV + "/"
self._submit_logs = 0
self._proxy_lock: asyncio.Lock | None = None
self._closing: list[httpx.AsyncClient] = []
self._switches = 0
self._client: httpx.AsyncClient | None = None
async def __aenter__(self) -> "StudySession":
from euniv.proxy import async_httpx_client
self._client = async_httpx_client(
self._proxy,
timeout=30,
follow_redirects=True,
headers={"User-Agent": USER_AGENT},
)
_load_cookies(self._client, self._initial_cookies)
self._proxy_lock = asyncio.Lock()
return self
async def __aexit__(self, *args: object) -> None:
for client in self._closing:
await client.aclose()
self._closing.clear()
if self._client:
await self._client.aclose()
async def _rotate_proxy(self, used: str | None = None) -> bool:
if not self._use_pool:
return False
from euniv.proxy import async_httpx_client, parse_proxy
from euniv.proxy_pool import MAX_SWITCHES, acquire, mark_failed
if self._proxy_lock is None:
self._proxy_lock = asyncio.Lock()
failed = self._proxy if used is None else used
async with self._proxy_lock:
if failed != self._proxy:
return True
if self._switches >= MAX_SWITCHES:
return False
self._switches += 1
await asyncio.to_thread(mark_failed, self._employee_id, failed)
nxt = await asyncio.to_thread(acquire, self._employee_id)
parsed = parse_proxy(nxt)
if parsed == failed:
return False
client = async_httpx_client(
parsed,
timeout=30,
follow_redirects=True,
headers={"User-Agent": USER_AGENT},
)
cookies = self._initial_cookies
if self._client is not None:
cookies = [
(cookie.name, cookie.value or "", cookie.domain or "", cookie.path or "/")
for cookie in self._client.cookies.jar
] or self._initial_cookies
self._closing.append(self._client)
_load_cookies(client, cookies)
self._client = client
self._proxy = parsed
return True
async def _http(self, method: str, url: str, **kw: object) -> httpx.Response:
assert self._client is not None
limit = getattr(self, "_request_limit", None)
async def once() -> httpx.Response:
assert self._client is not None
if limit is None:
return await self._client.request(method, url, **kw)
async with limit:
return await self._client.request(method, url, **kw)
used = self._proxy
try:
return await once()
except Exception as exc:
if self._use_pool and used and is_proxy_failure(exc):
if await self._rotate_proxy(used):
return await once()
raise
def _api_headers(self) -> dict[str, str]:
return {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json",
"Origin": EUNIV,
"Referer": EUNIV + "/",
"source": "501",
"token": self._token,
"User-Agent": USER_AGENT,
}
async def _api(self, method: str, url: str, **kw: object) -> httpx.Response:
assert self._client is not None
headers = self._api_headers()
extra = kw.pop("headers", None)
if extra and isinstance(extra, dict):
headers.update(extra)
resp = await self._http(method, url, headers=headers, **kw)
refreshed = resp.headers.get("token") or resp.headers.get("Token")
if refreshed:
self._token = refreshed
for domain in ("euniv.zte.com.cn", "api-mall.yxt.com"):
self._client.cookies.set("ELEARNING_00024", refreshed, domain=domain, path="/")
if resp.status_code == 401:
raise SessionExpired("学习平台登录已失效")
if resp.status_code == 403:
raise PermissionError("当前课程没有权限")
if resp.headers.get("content-type", "").startswith("application/json"):
try:
payload = resp.json()
except (json.JSONDecodeError, ValueError):
payload = None
if isinstance(payload, dict) and str(payload.get("code")) == "401":
raise SessionExpired("学习平台登录已失效")
if isinstance(payload, dict) and str(payload.get("code")) == "403":
raise PermissionError("当前课程没有权限")
return resp
async def _guard_single(self, kid: str) -> None:
if not getattr(self, "_single_limit", False) or not kid:
return
try:
await self._api("POST", f"{EUNIV}/kng/knowledges/{as_uuid(kid)}/heart")
except (SessionExpired, PermissionError):
raise
except Exception:
log.info("多端检查没有发出")
async def update_progress(self, kid: str, pkg_id: str = "") -> dict:
resp = await self._api("POST", f"{STUDY_API}/v1/study/updateprogress",
json={"knowledgeId": as_uuid(kid),
"packageId": as_uuid(pkg_id) if pkg_id else "",
"masterId": "", "masterType": ""})
return resp.json()
async def sync_package(self, kid: str) -> dict:
resp = await self._api("GET", f"{STUDY_API}/v1/uk/syncpackage",
params={"knowledgeId": as_uuid(kid), "sourceType": "SingleStudy", "masterId": ""})
return resp.json()
async def get_encrypt_request(self, body_json: str) -> str:
from euniv.encrypt import fetch_encryption_async
assert self._client is not None
try:
return await fetch_encryption_async(
self._client, body_json, origin=EUNIV, user_agent=USER_AGENT
)
except Exception as exc:
if self._use_pool and self._proxy and is_proxy_failure(exc):
if await self._rotate_proxy():
assert self._client is not None
return await fetch_encryption_async(
self._client, body_json, origin=EUNIV, user_agent=USER_AGENT
)
raise
async def post_site_log(self, name: str, body: dict) -> None:
if getattr(self, "_client", None) is None:
return
try:
await self._http(
"POST",
f"{EUNIV}/kng/services/KngComService.svc/{name}",
headers={
"Content-Type": "text/json",
"Origin": EUNIV,
"Referer": self._referer or (EUNIV + "/"),
"Accept": "application/json, text/javascript, */*",
"User-Agent": USER_AGENT,
},
content=json.dumps(body, ensure_ascii=False).encode("utf-8"),
)
except Exception:
log.info("网站日志 %s 没有发出", name)
async def submit_video_heartbeat(self, kid: str, pkg_id: str,
study_time: int, view_schedule: int) -> dict:
await self._guard_single(kid)
param = study_progress_fields(
kid, pkg_id, page_size=1, study_time=study_time,
kind=0, view_schedule=view_schedule,
)
plain = json.dumps(param, ensure_ascii=False, separators=(",", ":"))
encryption = await self.get_encrypt_request(plain)
param["encryption"] = encryption
param["multiple"] = 1
param["realHour"] = study_time
resp = await self._api("POST", f"{STUDY_API}/v1/study/submitpro",
content=json.dumps(param, separators=(",", ":")))
self._submit_logs = getattr(self, "_submit_logs", 0) + 1
await self.post_site_log("CreateSubmitLog", {
"kngId": as_uuid(kid),
"apiUrl": f"视频心跳,知识 {as_uuid(kid)},第 {self._submit_logs} 次,实际 {study_time} 秒,位置 {view_schedule}",
"context": plain,
})
text = resp.text.strip()
return resp.json() if text else {}
async def submit_document_heartbeat(self, kid: str, pkg_id: str,
page_size: int, study_time: int,
view_schedule: int, end: bool = False) -> None:
await self._guard_single(kid)
param = study_progress_fields(
kid, pkg_id, page_size=page_size, study_time=study_time,
kind=1, view_schedule=view_schedule, end=end,
)
plain = json.dumps(param, ensure_ascii=False, separators=(",", ":"))
encryption = await self.get_encrypt_request(plain)
param["multiple"] = 1
param["realHour"] = study_time
await self._api("POST", f"{STUDY_API}/v1/study/submit?encryption={encryption}",
content=json.dumps(param, separators=(",", ":")))
self._submit_logs = getattr(self, "_submit_logs", 0) + 1
await self.post_site_log("CreateSubmitLog", {
"kngId": as_uuid(kid),
"apiUrl": f"文档心跳,知识 {as_uuid(kid)},第 {self._submit_logs} 次,实际 {study_time} 秒",
"context": plain,
})
async def submit_scorm_heartbeat(self, kid: str, pkg_id: str,
study_time: int, sco_id: str = "",
end: bool = False) -> None:
await self._guard_single(kid)
encrypt_param = study_progress_fields(
kid, pkg_id, page_size=-1 if end else 1, study_time=study_time,
kind=2, view_schedule=0, end=end, chapter_id=sco_id, for_encrypt=True,
)
plain = json.dumps(encrypt_param, ensure_ascii=False, separators=(",", ":"))
encryption = await self.get_encrypt_request(plain)
param = study_progress_fields(
kid, pkg_id, page_size=-1 if end else 1, study_time=study_time,
kind=2, view_schedule=0, end=end, chapter_id=sco_id,
)
param["multiple"] = 1
param["realHour"] = study_time
await self._api("POST", f"{STUDY_API}/v1/study/submit?encryption={encryption}",
content=json.dumps(param, separators=(",", ":")))
self._submit_logs = getattr(self, "_submit_logs", 0) + 1
await self.post_site_log("CreateSubmitLog", {
"kngId": as_uuid(kid),
"apiUrl": f"Scorm 心跳,知识 {as_uuid(kid)},第 {self._submit_logs} 次,实际 {study_time} 秒",
"context": plain,
})
async def scorm_count(self, kid: str) -> int:
resp = await self._api("GET", f"{STUDY_API}/v1/kng/scorm/count/",
params={"knowledgeId": as_uuid(kid)})
return int(resp.json().get("scocnt") or 1)
async def scorm_get(self, user_id: str, sco_id: str) -> dict:
resp = await self._api("GET", f"https://api-mall.yxt.com/v1/scormstudy/{user_id}/{as_uuid(sco_id)}")
text = resp.text.strip()
return resp.json() if text else {}
async def scorm_save(self, session_id: str, org_id: str, user_id: str,
scorm_id: str, scorm_id_ori: str, sco_cnt: int,
pkg_id: str, data: dict) -> None:
await self._api("POST", "https://api-mall.yxt.com/v1/scormstudy", json={
"sessionId": session_id, "orgId": org_id, "userId": user_id,
"scormId": as_uuid(scorm_id), "scormIdOri": as_uuid(scorm_id_ori),
"masterId": "", "masterType": "",
"packageId": as_uuid(pkg_id) if pkg_id else "",
"scocnt": sco_cnt, "data": data,
})
async def course_page_params(self, path: str) -> dict:
assert self._client is not None
resp = await self._http(
"GET",
f"{EUNIV}{path}",
headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"},
)
html = resp.text
if _page_is_login(html):
raise SessionExpired("学习平台登录已失效")
from euniv.encrypt import note_play_html
note_play_html(html, EUNIV)
return play_page_params(html)
async def scorm_page_count(self, kid: str) -> int:
"""只数课件页文件,不下载正文。失败时返回 0,调用方改为只发学时心跳。"""
assert self._client is not None
compact = compact_id(kid)
index_url = f"https://cdn-cos-file.yunxuetang.cn/zt/scorm/{compact}/h5/js/index-scorm.js"
try:
resp = await self._http("GET", index_url, headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"})
except Exception:
log.warning("课件页列表没有获取到")
return 0
return len(re.findall(r'["\']([^"\']+\.oss\.js)["\']', resp.text))
async def scorm_extract_answers(self, kid: str) -> list[dict]:
assert self._client is not None
compact = compact_id(kid)
index_url = f"https://cdn-cos-file.yunxuetang.cn/zt/scorm/{compact}/h5/js/index-scorm.js"
resp = await self._http("GET", index_url, headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"})
urls: list[str] = []
for m in re.finditer(r'["\']([^"\']+\.oss\.js)["\']', resp.text):
raw = m.group(1)
if raw.startswith("http"):
urls.append(raw)
elif raw.startswith("//"):
urls.append("https:" + raw)
elif raw.startswith("/"):
urls.append(f"https://cdn-cos-file.yunxuetang.cn{raw}")
else:
urls.append(f"https://cdn-cos-file.yunxuetang.cn/zt/scorm/{compact}/h5/js/{raw}")
answers: list[dict] = []
for url in urls:
try:
r = await self._http("GET", url, headers={"User-Agent": USER_AGENT})
for block in re.finditer(r'单选题([\s\S]*?)正确答案[::]\s*([A-D])', r.text):
answers.append({"page_url": url, "answer": block.group(2)})
except Exception:
continue
return answers
async def month_hours_text(self) -> str:
assert self._client is not None
resp = await self._http(
"GET",
f"{EUNIV}/study/myperiod.htm",
headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/sty/index.htm"},
)
m = re.search(r'id="spMonthlyPeriod" title="(\d+)分钟"', resp.text)
return m.group(1) if m else ""
async def month_history_minutes(self, now: datetime | None = None) -> int:
from euniv.client import (
HISTORY_PAGE_SIZE,
fold_month_minutes,
history_items_from_payload,
history_search_body,
)
from euniv.study_window import CN_TZ
current = now or datetime.now(CN_TZ)
year, month = current.year, current.month
offset = 0
total = 0
first_mark: tuple | None = None
for _ in range(50):
resp = await self._api(
"POST",
f"{STUDY_API}/v1/styhis/studyhistory/daily/search",
json=history_search_body(True, offset, HISTORY_PAGE_SIZE),
)
rows = history_items_from_payload(resp.json())
if rows is None:
if offset == 0:
raise RuntimeError("学时历史没有获取到")
return total
if not rows:
return total
add, done = fold_month_minutes(rows, year, month)
total += add
if done or len(rows) != HISTORY_PAGE_SIZE:
return total
mark = (
len(rows),
rows[0].get("studied_at"),
rows[0].get("title"),
rows[-1].get("studied_at"),
rows[-1].get("title"),
)
if offset == 0:
first_mark = mark
elif mark == first_mark:
return total
offset += HISTORY_PAGE_SIZE
return total
# ── 单门课程的学习协程 ──
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 _heartbeat_wait(
worker: WorkerView | None,
interval: int,
stop: asyncio.Event,
hours: HoursWatcher,
progress: float,
) -> bool:
delay = _jitter(interval)
cap = max(int(interval or 0), 1)
remaining = max(0, min(int(math.ceil(delay)), cap))
_touch(
worker,
interval=interval,
heartbeat_at=time.time() + delay,
heartbeat_in=remaining,
progress=progress,
ok=True,
)
return await wait_stop(delay, stop, hours.user_stop)
def _page_is_login(html: str) -> bool:
text = html or ""
if "submitProTimes" in text or "knowledgeType" in text or "spMonthlyPeriod" in text:
return False
lowered = text.lower()
return "password" in lowered and ("login" in lowered or "登录" in text)
def _whole(value: object, default: int = 0) -> int:
try:
return int(float(value))
except (TypeError, ValueError):
return default
def _uses_new_timer(params: dict | None) -> bool:
data = params or {}
def on(name: str) -> bool:
return str(data.get(name) or "").strip() == "1"
return on("submitIsOpen") or on("learningProgressSubmission")
async def _study_video(session: StudySession, kid: str, pkg_id: str,
interval: int, stop: asyncio.Event, hours: HoursWatcher,
worker: WorkerView | None = None,
study_time: int | None = None) -> None:
step = int(study_time if study_time is not None else (interval if interval > 0 else 30))
if step <= 0:
step = 30
view = 0
started = False
stall = _Stall()
if not getattr(session, "_play_logged", False):
session._play_logged = True
poster = getattr(session, "post_site_log", None)
if poster is not None:
await poster("CreateActionLog", {
"kngId": as_uuid(kid),
"backNo": f"{int(time.time() * 1000)}_1",
"type": "play",
"context": "开始播放",
})
while not _halted(stop, hours):
try:
progress = await session.update_progress(kid, pkg_id)
except Exception:
_touch(worker, ok=False)
raise
schedule = _progress_of(progress)
_touch(worker, progress=schedule, ok=True)
if _completed(progress):
if started:
await hours.refresh()
return
started = True
view = _whole(progress.get("viewSchedule"), view)
view = max(0, view + step + random.randint(-1, 1))
limit = int(getattr(session, "_video_cap", 0) or 0)
if limit > 0:
view = min(view, limit)
page_rhythm = interval > 0 and interval == step
if page_rhythm and await _heartbeat_wait(worker, interval, stop, hours, schedule):
return
if _halted(stop, hours):
return
try:
result = await session.submit_video_heartbeat(kid, pkg_id, step, view)
except Exception:
_touch(worker, ok=False)
raise
new_schedule = result.get("studySchedule")
if new_schedule is not None:
schedule = _progress_of({"studySchedule": new_schedule})
_beat(worker, schedule, ok=True)
if schedule >= 100:
await hours.refresh()
return
if stall.stuck(schedule, step):
raise RuntimeError("进度长时间没有变化")
if not page_rhythm:
if await _heartbeat_wait(worker, 1 if interval <= 0 else interval, stop, hours, schedule):
return
async def _study_document(session: StudySession, kid: str, pkg_id: str,
page_size: int, interval: int, stop: asyncio.Event,
hours: HoursWatcher, worker: WorkerView | None = None,
study_time: int | None = None) -> None:
step = int(study_time if study_time is not None else (interval if interval > 0 else 120))
if step <= 0:
step = 120
started = False
stall = _Stall()
while not _halted(stop, hours):
try:
progress = await session.update_progress(kid, pkg_id)
except Exception:
_touch(worker, ok=False)
raise
schedule = _progress_of(progress)
_touch(worker, progress=schedule, ok=True)
if _completed(progress):
if started:
await hours.refresh()
return
started = True
view = int(progress.get("viewSchedule") or 1)
page_rhythm = interval > 0 and interval == step
if page_rhythm and await _heartbeat_wait(worker, interval, stop, hours, schedule):
return
if _halted(stop, hours):
return
try:
await session.submit_document_heartbeat(kid, pkg_id, page_size, step, view)
progress = await session.update_progress(kid, pkg_id)
except Exception:
_touch(worker, ok=False)
raise
schedule = _progress_of(progress)
_beat(worker, schedule, ok=True)
if _completed(progress):
await hours.refresh()
return
if stall.stuck(schedule, step):
raise RuntimeError("进度长时间没有变化")
if not page_rhythm:
if await _heartbeat_wait(worker, 1 if interval <= 0 else interval, stop, hours, schedule):
return
async def _study_scorm(session: StudySession, kid: str, pkg_id: str,
interval: int, stop: asyncio.Event, hours: HoursWatcher,
user_id: str, org_id: str, worker: WorkerView | None = None,
study_time: int | None = None, scorm_id: str = "") -> None:
import uuid as _uuid
step = int(study_time if study_time is not None else (interval if interval > 0 else 120))
if step <= 0:
step = 120
try:
progress = await session.update_progress(kid, pkg_id)
except Exception:
_touch(worker, ok=False)
raise
schedule = _progress_of(progress)
_touch(worker, progress=schedule, ok=True)
if _completed(progress):
return
async def hours_only() -> None:
while not _halted(stop, hours):
if _halted(stop, hours):
return
try:
await session.submit_scorm_heartbeat(kid, pkg_id, step, sco_id="", end=False)
latest = await session.update_progress(kid, pkg_id)
except Exception:
_touch(worker, ok=False)
raise
current = _progress_of(latest)
_beat(worker, current, ok=True)
if _completed(latest):
await hours.refresh()
return
if await _heartbeat_wait(worker, interval, stop, hours, current):
return
page_count = 0
if user_id and org_id and scorm_id:
counter = getattr(session, "scorm_page_count", None)
if counter is not None:
page_count = int(await counter(kid) or 0)
if page_count <= 0 or not user_id or not org_id or not scorm_id:
await hours_only()
return
sco_cnt = await session.scorm_count(kid)
session_id = str(_uuid.uuid4())
sco_id = scorm_id
existing = await session.scorm_get(user_id, sco_id)
scorm_data = existing.get("data") if existing else None
if not scorm_data or not isinstance(scorm_data, dict):
scorm_data = {
"cmi__core__lesson_status": "incomplete",
"cmi__core__lesson_location": "1",
"cmi__core__lesson_progress": "0.00",
"cmi__core__session_time": "00:00:01",
"cmi__core__exit": "suspend",
"cmi__suspend_data": {},
}
total_pages = max(1, page_count)
prior_done = str(scorm_data.get("cmi__core__lesson_status") or "") == "completed"
for page_idx in range(total_pages):
if _halted(stop, hours):
return
scorm_data["cmi__core__lesson_location"] = str(page_idx + 1)
scorm_data["cmi__core__lesson_progress"] = f"{(page_idx + 1) / total_pages:.2f}"
scorm_data["cmi__core__lesson_status"] = "completed" if prior_done and page_idx + 1 == total_pages else "incomplete"
scorm_data["cmi__core__session_time"] = "00:00:01"
try:
await session.scorm_save(
session_id=session_id, org_id=org_id, user_id=user_id,
scorm_id=sco_id, scorm_id_ori=kid, sco_cnt=sco_cnt,
pkg_id=pkg_id, data=scorm_data,
)
await session.submit_scorm_heartbeat(kid, pkg_id, step, sco_id=sco_id, end=True)
progress = await session.update_progress(kid, pkg_id)
except Exception:
_touch(worker, ok=False)
raise
schedule = _progress_of(progress)
_beat(worker, schedule, ok=True)
if _completed(progress):
await hours.refresh()
return
page_wait = interval if interval <= 0 else min(interval, 5)
if await _heartbeat_wait(worker, page_wait, stop, hours, schedule):
return
while not _halted(stop, hours):
if _halted(stop, hours):
return
try:
await session.submit_scorm_heartbeat(kid, pkg_id, step, sco_id=sco_id, end=False)
progress = await session.update_progress(kid, pkg_id)
except Exception:
_touch(worker, ok=False)
raise
schedule = _progress_of(progress)
_beat(worker, schedule, ok=True)
if _completed(progress):
await hours.refresh()
return
if await _heartbeat_wait(worker, interval, stop, hours, schedule):
return
async def _study_package(session: StudySession, kid: str, intervals: dict,
auto_mode: bool, stop: asyncio.Event, hours: HoursWatcher,
user_id: str, org_id: str, worker: WorkerView | None = None) -> bool:
pkg = await session.sync_package(kid)
if _completed(pkg):
_touch(worker, progress=_progress_of(pkg), ok=True)
return True
chapters = pkg.get("userKnowledgeList") or []
failed = 0
for ch in chapters:
if _halted(stop, hours):
return failed == 0
if _completed(ch):
continue
ch_kid = str(ch.get("knowledgeId") or "").strip()
ch_title = ch.get("title") or ch_kid
if not compact_id(ch_kid):
log.info("跳过没有编号的章节 %s", ch_title)
continue
_set_user_status(session._employee_id, course=ch_title)
_touch(worker, course=ch_title, knowledge_id=ch_kid, progress=_progress_of(ch), ok=True)
is_video = "Video" in str(ch.get("knowledgeType") or "")
ch_type = "video" if is_video else "document"
try:
params = await _open_play(session, _package_chapter_path(kid, ch_kid, ch_type))
wait, study_time, page_size = _interval_plan(ch_type, intervals, auto_mode, params)
if is_video:
await _study_video(session, ch_kid, kid, wait, stop, hours, worker, study_time=study_time)
else:
await _study_document(
session, ch_kid, kid, page_size, wait, stop, hours, worker, study_time=study_time,
)
except SessionExpired:
raise
except Exception:
failed += 1
log.warning("章节 %s 没有学完", ch_title, exc_info=True)
continue
return failed == 0
# ── 同步准备:用 EunivClient 建立会话,导出 cookies ──
def _prepare_session(employee_id: str, password: str,
credential: dict, proxy: str | None = None,
use_pool: bool = False
) -> tuple[str, str, str, list[tuple[str, str, str, str]], str | None, str]:
"""同步:恢复会话并导出 cookies。最后一项是 expired 或 network。"""
from euniv.proxy_pool import MAX_SWITCHES, acquire, mark_failed
current = proxy
last_reason = "network"
for _ in range(MAX_SWITCHES + 1):
client = EunivClient(employee_id, password, proxy=current)
try:
client.restore(credential)
if not client.credential_alive():
return "", "", "", [], current, "expired"
client._ensure_site()
token = client.session_token()
user_id = str(client._profile.get("userId") or "")
org_id = str(client._profile.get("accountId") or "")
cookies: list[tuple[str, str, str, str]] = []
for cookie in client.client.cookies.jar:
cookies.append((cookie.name, cookie.value or "", cookie.domain or "", cookie.path or "/"))
return token, user_id, org_id, cookies, current, ""
except SessionExpired:
return "", "", "", [], current, "expired"
except Exception as exc:
log.warning("用户 %s 准备会话失败: %s", employee_id, exc)
if use_pool and current and is_proxy_failure(exc):
mark_failed(employee_id, current, str(exc)[:200])
current = acquire(employee_id)
last_reason = "network"
continue
last_reason = "expired" if isinstance(exc, SessionExpired) else "network"
return "", "", "", [], current, last_reason
finally:
client.close()
return "", "", "", [], current, last_reason
# ── 启动器 + 按账号 Work ──
class AutoStudyWorker:
"""定时启动器:到点检查各账号,已有 work 则跳过,未达标才拉起。"""
def __init__(self) -> None:
self._stop_flag = threading.Event()
self._thread: threading.Thread | None = None
self._loop: asyncio.AbstractEventLoop | None = None
self._async_stop: asyncio.Event | None = None
self._kick: asyncio.Event | None = None
self._tasks: dict[str, asyncio.Task] = {}
self._sem: asyncio.Semaphore | None = None
def start(self) -> None:
self._thread = threading.Thread(target=self._run_thread, name="euniv-autostudy", daemon=True)
self._thread.start()
def stop(self) -> None:
self._stop_flag.set()
if self._loop and self._async_stop:
self._loop.call_soon_threadsafe(self._async_stop.set)
thread = self._thread
if thread is not None and thread is not threading.current_thread():
thread.join(timeout=15)
def wake(self) -> None:
if self._loop and self._kick is not None:
self._loop.call_soon_threadsafe(self._kick.set)
def _run_thread(self) -> None:
self._loop = asyncio.new_event_loop()
asyncio.set_event_loop(self._loop)
self._async_stop = asyncio.Event()
self._kick = asyncio.Event()
try:
self._loop.run_until_complete(self._main_loop())
finally:
self._loop.close()
async def _main_loop(self) -> None:
assert self._async_stop is not None
assert self._kick is not None
self._sem = asyncio.Semaphore(_MAX_CONCURRENT_USERS)
while not self._async_stop.is_set():
self._kick.clear()
try:
jobs, course_list, delay, idle = await asyncio.to_thread(self._collect)
except Exception as exc:
log.exception("自动学习调度异常: %s", exc)
_set_status(message="调度出现异常")
jobs, course_list, delay, idle = [], [], 30.0, ""
if self._async_stop.is_set():
break
for job in jobs:
self._launch(job, course_list)
alive = self._alive()
if alive:
_set_status(running=True, message=f"运行中 {alive} 个账号")
elif idle:
_set_status(running=False, message=idle)
if self._kick.is_set():
continue
await wait_stop(delay, self._async_stop, self._kick)
pending = [task for task in self._tasks.values() if not task.done()]
if pending:
_done, leftover = await asyncio.wait(pending, timeout=10)
for task in leftover:
task.cancel()
if leftover:
await asyncio.gather(*leftover, return_exceptions=True)
def _alive(self) -> int:
dead = [eid for eid, task in self._tasks.items() if task.done()]
for eid in dead:
self._tasks.pop(eid, None)
return len(self._tasks)
def _busy(self, employee_id: str) -> bool:
task = self._tasks.get(employee_id)
if task is not None and not task.done():
return True
return is_studying(employee_id)
def _collect(self) -> tuple[list, list, float, str]:
from euniv.db import SessionLocal
from euniv.study_window import CN_TZ, month_key
now = as_cn()
soonest = next_month_start(now)
jobs: list[tuple] = []
course_list: list[tuple[str, str, str]] = []
with SessionLocal() as db:
users = db.scalars(
select(Account)
.where(Account.credential_cipher != "")
.where(Account.credential_valid == True)
.order_by(Account.employee_id)
).all()
expired = False
for row in users:
try:
if expire_pause(row):
expired = True
eid = row.employee_id
fire = next_fire_at(row, now)
if fire is not None and fire < soonest:
soonest = fire
if hours_met(row):
if is_studying(eid) or is_wanted(eid):
halt_work(eid)
continue
retry_hold = _retry_at.get(eid)
if retry_hold and time.time() < retry_hold and not is_wanted(eid):
retry_at = datetime.fromtimestamp(retry_hold, CN_TZ)
if retry_at < soonest:
soonest = retry_at
continue
if retry_hold and time.time() >= retry_hold:
want_work(eid)
_retry_at.pop(eid, None)
if _done_month.get(eid) == month_key(now) and not is_wanted(eid):
continue
if not (study_eligible(row) or is_wanted(eid)):
continue
if self._busy(eid):
continue
job = _job_from_account(row)
if job is None:
drop_work(eid)
continue
jobs.append(job)
except Exception:
log.exception("调度账号 %s 失败", getattr(row, "employee_id", ""))
if jobs:
course_list = snapshot_courses(db.scalars(select(Course)).all())
if expired:
db.commit()
wait = max(1.0, min(3600.0, (soonest - as_cn()).total_seconds()))
label = soonest.strftime("%m-%d %H:%M:%S")
return jobs, course_list, wait, f"下一次定时 {label}"
def _tick(self) -> float:
jobs, course_list, delay, idle = self._collect()
for job in jobs:
self._launch(job, course_list)
alive = self._alive()
if alive:
_set_status(running=True, message=f"运行中 {alive} 个账号")
else:
_set_status(running=False, message=idle)
return delay
def _launch(self, job: tuple, course_list: list[tuple[str, str, str]]) -> bool:
eid = job[0]
if self._busy(eid):
return False
if not course_list:
_set_user_status(eid, state="学习失败", message="没有可用的课程")
drop_work(eid)
return False
_set_user_status(eid, state="排队中", course="")
want_work(eid)
with _halt_lock:
generation = _wanted.get(eid, 0)
assert self._loop is not None
self._tasks[eid] = self._loop.create_task(self._run_account(job, list(course_list), generation))
log.info("启动账号 %s 的学习任务", eid)
return True
async def _run_account(self, job: tuple, course_list: list[tuple[str, str, str]], generation: int) -> None:
emp_id, target, pw, cred, proxy, workers, use_pool = job
try:
from admin.settings import hours_source_of
hours_source = await asyncio.to_thread(hours_source_of)
intervals, auto_mode = await asyncio.to_thread(_current_intervals)
if not course_list:
_set_user_status(emp_id, state="学习失败", message="没有可用的课程")
return
assert self._sem is not None
await self._study_user(
emp_id, target, pw, cred, proxy, workers, use_pool,
course_list, intervals, auto_mode, hours_source, self._sem,
)
except Exception as exc:
log.warning("用户 %s 自动学习失败: %s", emp_id, exc)
_finish_user(emp_id, exc)
else:
_finish_user(emp_id)
finally:
with _halt_lock:
current = _wanted.get(emp_id)
if current == generation:
drop_work(emp_id)
elif current is not None and self._kick is not None:
self._kick.set()
note_attempt_end(emp_id)
self._tasks.pop(emp_id, None)
if self._kick is not None:
self._kick.set()
async def _study_user(self, employee_id: str, target: int,
password: str, credential: dict, proxy: str | None,
workers: int, use_pool: bool, course_list: list, intervals: dict,
auto_mode: bool, hours_source: str, sem: asyncio.Semaphore) -> None:
assert self._async_stop is not None
user_stop = asyncio.Event()
with _halt_lock:
current = _user_halts.get(employee_id)
if current is not None and employee_id in _running:
return
_user_halts[employee_id] = user_stop
_running.add(employee_id)
try:
if user_stop.is_set():
_set_user_status(employee_id, state="已停止")
return
_set_user_status(employee_id, state="准备", course="", workers={})
loop = asyncio.get_running_loop()
token, user_id, org_id, cookies, proxy, reason = await loop.run_in_executor(
None, _prepare_session, employee_id, password, credential, proxy, use_pool)
if user_stop.is_set():
_set_user_status(employee_id, state="已停止")
return
if not token:
message = "请重新登录" if reason == "expired" else "无法连接学习平台"
_set_user_status(employee_id, state="会话失效", message=message)
return
async with StudySession(
token, cookies, proxy=proxy, employee_id=employee_id, use_pool=use_pool
) as session:
session._employee_id = employee_id # type: ignore[attr-defined]
session._request_limit = sem
if user_stop.is_set():
_set_user_status(employee_id, state="已停止")
return
_set_user_status(employee_id, state="学习中")
hours = HoursWatcher(session, employee_id, target, user_stop, source=hours_source)
if await hours.refresh():
return
ticker = asyncio.create_task(hours.ticker(self._async_stop))
try:
failed = await self._study_courses(
session, employee_id, course_list, intervals,
auto_mode, hours, user_id, org_id, workers)
if hours.reached or user_stop.is_set() or self._async_stop.is_set():
return
if failed:
_set_user_status(
employee_id,
state="学习失败",
message=f"{failed} 门课程没有学完",
course="",
workers={},
)
return
_set_user_status(employee_id, state="已学完", course="", workers={})
finally:
ticker.cancel()
await asyncio.gather(ticker, return_exceptions=True)
finally:
with _halt_lock:
if _user_halts.get(employee_id) is user_stop:
_user_halts.pop(employee_id, None)
_running.discard(employee_id)
if use_pool:
from euniv.proxy_pool import release
await asyncio.to_thread(release, employee_id)
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) -> int:
"""N 个协程顺着课程表往下领,已完成的跳过,未完成的发心跳。"""
assert self._async_stop is not None
cursor = CourseCursor(course_list)
count = max(1, min(8, int(workers or 1)))
finished = await asyncio.to_thread(_load_finished, employee_id)
streak = {"n": 0, "wait": 60}
failed = {"n": 0}
streak_lock = asyncio.Lock()
async def worker_loop(index: int) -> None:
view = WorkerView(employee_id, index)
view.update(course="", progress=0, interval=0, heartbeat_at=0, ok=True)
while not _halted(self._async_stop, hours):
item = await cursor.take()
if item is None:
view.update(course="", progress=100, interval=0, heartbeat_at=0, ok=True)
return
path, title, kind = item
result = await self._study_one_course(
session, employee_id, path, title, kind,
intervals, auto_mode, hours, user_id, org_id, view, finished,
)
pause = 0
async with streak_lock:
if result == "fail":
failed["n"] += 1
streak["n"] += 1
if streak["n"] % 3 == 0:
pause = streak["wait"]
streak["wait"] = min(streak["wait"] * 2, 30 * 60)
if streak["n"] >= 10:
hours.user_stop.set()
_set_user_status(employee_id, state="学习失败", message="连续多门课程没有学完")
return
elif result in ("done", "studied"):
streak["n"] = 0
streak["wait"] = 60
if pause and await wait_stop(pause, self._async_stop, hours.user_stop):
return
try:
async with asyncio.TaskGroup() as group:
for index in range(1, count + 1):
group.create_task(worker_loop(index))
except ExceptionGroup:
log.warning("用户 %s 有学习协程没有跑完", employee_id)
return failed["n"]
async def _study_one_course(self, session: StudySession, employee_id: str,
path: str, title: str, kind: str,
intervals: dict, auto_mode: bool,
hours: HoursWatcher, user_id: str, org_id: str,
worker: WorkerView | None = None, finished: set[str] | None = None) -> str:
assert self._async_stop is not None
if _halted(self._async_stop, hours):
return "stop"
ctype = _course_type(kind, path)
if ctype == "unknown":
log.info("跳过未知类型课程 %s", title or path)
return "skip"
kid = _knowledge_id_from_path(path)
if not kid:
return "skip"
known = finished if finished is not None else set()
if kid in known:
return "skip"
intervals, auto_mode = await asyncio.to_thread(_current_intervals)
_set_user_status(employee_id, course=title)
try:
progress = await session.update_progress(kid, "")
schedule = _progress_of(progress)
_touch(worker, course=title, knowledge_id=kid, progress=schedule, ok=True)
if _completed(progress):
known.add(kid)
await asyncio.to_thread(_remember_finished, employee_id, kid)
await wait_stop(random.uniform(0.5, 1.5), self._async_stop, hours.user_stop)
return "done"
if await wait_stop(random.uniform(2.0, 5.0), self._async_stop, hours.user_stop):
return "stop"
play_path = _play_path(kind, path, kid)
session._referer = f"{EUNIV}{play_path}"
session._play_logged = False
params = await _open_play(session, play_path)
if ctype == "package":
_touch(worker, course=title, knowledge_id=kid, progress=0, ok=True)
ok = await _study_package(session, kid, intervals, auto_mode,
self._async_stop, hours, user_id, org_id, worker)
if _halted(self._async_stop, hours):
return "stop"
if not ok:
return "fail"
known.add(kid)
await asyncio.to_thread(_remember_finished, employee_id, kid)
return "studied"
wait, study_time, page_size = _interval_plan(ctype, intervals, auto_mode, params)
session._single_limit = str(params.get("isSingle") or "") == "1"
if ctype == "video":
session._video_cap = _whole(params.get("standardStudyHours"), 0)
if ctype == "document" and _uses_new_timer(params) and auto_mode:
wait = max(1, _whole(params.get("submitProTimes"), 30))
study_time = wait
if ctype == "document" and not _uses_new_timer(params):
standard = _whole(params.get("standardStudyHours"), 0)
span = _whole(params.get("validtimeSpan"), 120)
if 0 < standard < span:
beat = study_time if study_time > 0 else max(1, span)
if _halted(self._async_stop, hours):
return "stop"
await session.submit_document_heartbeat(kid, "", page_size, beat, 1, end=True)
known.add(kid)
await asyncio.to_thread(_remember_finished, employee_id, kid)
return "studied"
if ctype == "video":
await _study_video(
session, kid, "", wait, self._async_stop, hours, worker, study_time=study_time,
)
elif ctype == "document":
await _study_document(
session, kid, "", page_size, wait, self._async_stop, hours, worker,
study_time=study_time,
)
elif ctype == "scorm":
await _study_scorm(
session, kid, "", wait, self._async_stop, hours,
str(params.get("userID") or ""), str(params.get("orgID") or ""),
worker, study_time=study_time, scorm_id=str(params.get("scormId") or ""),
)
if _halted(self._async_stop, hours):
return "stop"
known.add(kid)
await asyncio.to_thread(_remember_finished, employee_id, kid)
return "studied"
except SessionExpired:
hours.user_stop.set()
_touch(worker, ok=False)
_set_user_status(employee_id, state="会话失效", message="请重新登录")
log.info("用户 %s 会话失效", employee_id)
return "stop"
except Exception as exc:
_touch(worker, ok=False)
log.warning("用户 %s 课程 %s 异常: %s", employee_id, title, exc)
return "fail"
return "skip"
# ── 数据库更新 ──
def _update_month_hours(employee_id: str, hours: str) -> None:
from euniv.db import SessionLocal
with SessionLocal() as db:
account = db.get(Account, employee_id)
if account:
stamp_hours(account, hours)
db.commit()
_set_user_status(employee_id, month_hours=hours)
def _load_finished(employee_id: str) -> set[str]:
from euniv.db import SessionLocal
from euniv.models import FinishedCourse
with SessionLocal() as db:
rows = db.scalars(
select(FinishedCourse.knowledge_id).where(FinishedCourse.employee_id == employee_id)
).all()
return {str(item) for item in rows if item}
def _remember_finished(employee_id: str, knowledge_id: str) -> None:
from sqlalchemy.exc import IntegrityError
from euniv.db import SessionLocal
from euniv.models import FinishedCourse
if not employee_id or not knowledge_id:
return
with SessionLocal() as db:
db.add(FinishedCourse(employee_id=employee_id, knowledge_id=knowledge_id))
try:
db.commit()
except IntegrityError:
db.rollback()
def _release_ignore_window(employee_id: str) -> None:
from euniv.db import SessionLocal
with SessionLocal() as db:
account = db.get(Account, employee_id)
if account is None or not account.study_ignore_window:
return
account.study_ignore_window = False
db.commit()
# ── 启动入口 ──
def start_autostudy() -> AutoStudyWorker:
global _worker
w = AutoStudyWorker()
_worker = w
w.start()
return w