Files
EnuivTools/backend/euniv/autostudy.py
T

2186 lines
82 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,
set_cookie,
as_uuid,
compact_id,
guard_https_async,
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 account_status(employee_id: str) -> dict:
"""只复制一个账号的状态,推送时不必复制全部账号。"""
key = (employee_id or "").strip()
with _lock:
raw = (_status.get("users") or {}).get(key)
if not isinstance(raw, dict):
return {}
info = dict(raw)
info["workers"] = _workers_list(info)
return info
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)
if kw.get("state") in ("已停止", "已学完", "学习失败", "会话失效", "已达标"):
info.pop("hours_refresh_at", None)
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:
marker = kw.get("knowledge_id")
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
if progress >= 100:
self.total = self.sent
elif self.total <= 0:
self.total = _count_total(self.sent, progress, self._origin)
if self.total > 0 and self.sent > self.total:
self.total = self.sent
self.update(progress=progress, sent=self.sent, total=self.total, **kw)
def adopt(self, payload: dict, **kw: object) -> None:
"""按官方百分比和已获得分钟刷新,不把本地发送次数当成进度。"""
data = payload if isinstance(payload, dict) else {}
progress = _progress_of(data)
actual, standard = _official_minutes(data)
extra = dict(kw)
extra["progress"] = progress
if standard is not None and standard > 0:
total = max(1, int(round(standard)))
sent = 0 if actual is None else max(0, int(round(actual)))
extra["sent"] = min(sent, total)
extra["total"] = total
self.update(**extra)
if "sent" in extra:
self.sent = int(extra["sent"])
self.total = int(extra["total"])
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 _show_progress(worker: WorkerView | None, payload: dict, **kw: object) -> None:
if worker is not None:
worker.adopt(payload, **kw)
return
_touch(worker, progress=_progress_of(payload), **kw)
def _earned_minutes(payload: dict) -> float | None:
if not isinstance(payload, dict):
return None
raw = payload.get("actualstudyhours")
if raw is None:
raw = payload.get("actualStudyHours")
try:
if raw is None or raw == "":
return None
return float(raw)
except (TypeError, ValueError):
return None
def _official_minutes(payload: dict) -> tuple[float | None, float | None]:
"""updateprogress 的已获得学时和标准学时,单位都是分钟。"""
if not isinstance(payload, dict):
return None, None
actual = _earned_minutes(payload)
raw = payload.get("standardstudyhours")
if raw is None:
raw = payload.get("standardStudyHours")
try:
if raw is None or raw == "":
standard = None
else:
standard = float(raw)
except (TypeError, ValueError):
standard = None
return actual, standard
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 分钟仍无进度才放弃。没入账的心跳按真实时间等满 5 分钟才放弃。"""
def __init__(self) -> None:
self.declared = 0
self.baseline: float | None = None
self.earned: float | None = None
self.quiet_since: float | None = None
self.paced = False
def note_landed(self) -> None:
self.quiet_since = None
self.paced = False
def quiet(self, now: float | None = None) -> bool:
current = time.time() if now is None else now
if self.quiet_since is None:
self.quiet_since = current
return current - self.quiet_since >= 300
def stuck(self, progress: float, sent: int, earned: float | None = None) -> bool:
if self.baseline is None:
self.baseline = progress
self.earned = earned
moved = progress > self.baseline + 0.01
if earned is not None and self.earned is not None and earned > self.earned + 0.01:
moved = True
if moved:
self.baseline = progress
self.earned = earned
self.declared = 0
elif earned is not None:
self.earned = earned
self.declared += max(0, sent)
return self.declared >= 300 and not moved
def _beat_landed(
before: float,
after: float,
before_earned: float | None,
after_earned: float | None,
result: object,
*,
video: bool,
) -> bool:
"""百分比或已获得学时增加才算入账。只把同一个百分比原样返回,不算进度往前走。"""
if after > before + 0.01:
return True
if after_earned is not None and (before_earned is None or after_earned > before_earned + 0.01):
return True
if not video or not isinstance(result, dict):
return False
try:
echoed = float(result.get("studySchedule"))
except (TypeError, ValueError):
return False
return echoed > before + 0.01
def _pace_wait(interval: int, step: int, landed: bool) -> int:
"""没入账时至少等到平台的一段时长,下一次心跳才有机会被记上。"""
chosen = 1 if interval <= 0 else int(interval)
if landed or step <= 0:
return chosen
return max(chosen, int(step))
def _pace_after(
stall: _Stall,
before: float,
after: float,
before_earned: float | None,
after_earned: float | None,
result: object,
*,
video: bool,
step: int,
interval: int,
now: float | None = None,
) -> tuple[bool, bool, int]:
"""返回 (是否入账, 是否放弃, 下一次等待秒)。"""
landed = _beat_landed(before, after, before_earned, after_earned, result, video=video)
if landed:
stall.note_landed()
return True, stall.stuck(after, step, after_earned), _pace_wait(interval, step, True)
return False, stall.quiet(now), _pace_wait(interval, step, False)
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 _declared_study_time(ctype: str, params: dict | None) -> int:
"""平台入账只认播放页上的一段时长。手动间隔只决定隔多久发一次,不改这一段报多少秒。"""
video = ctype == "video"
raw = (params or {}).get("submitProTimes" if video else "validtimeSpan")
try:
value = int(raw or 0)
except (TypeError, ValueError):
value = 0
if value <= 0:
value = 30 if video else 120
return value
def _interval_plan(ctype: str, intervals: dict, auto_mode: bool, params: dict) -> tuple[int, int, int]:
"""返回 (等待秒, 心跳 studyTime, pageSize)。studyTime 始终是播放页的 30 或 120。"""
video = ctype == "video"
wait = int(intervals.get(ctype, 30 if video else 120) or 0)
declared = _declared_study_time(ctype, params)
if auto_mode:
wait = max(1, declared)
page_size = max(1, int((params or {}).get("pageSize") or 1))
return wait, declared, page_size
def _current_intervals(employee_id: str) -> tuple[dict, bool]:
from euniv.db import SessionLocal
from euniv.heartbeat import intervals_of
from euniv.models import Account
with SessionLocal() as db:
account = db.get(Account, (employee_id or "").strip())
if account is None:
return {"video": 30, "document": 120, "scorm": 120}, True
return intervals_of(account)
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 _release_pool_later(employee_id: str, pool: bool) -> None:
"""在事件循环里把释放交给线程,避免堵住会写库的代理锁。"""
if not pool or not employee_id:
return
try:
loop = asyncio.get_running_loop()
except RuntimeError:
_release_pool(employee_id, True)
return
loop.create_task(asyncio.to_thread(_release_pool, employee_id, True))
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:
_release_pool(employee_id, pool)
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
proxy = None
if not pool:
try:
proxy = bind_url(row)
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 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 _chapter_type(raw: object) -> str:
"""空串和无法识别的章节类型都不当成文档。"""
text = str(raw or "").strip().lower()
if "video" in text:
return "video"
if "document" in text:
return "document"
return "unknown"
def _note_unknown(skipped: dict | None, label: str) -> None:
count = 1
if isinstance(skipped, dict):
count = int(skipped.get("n") or 0) + 1
skipped["n"] = count
log.info("跳过未知类型课程 %s,累计 %s 门", label, count)
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 _planned_beats(cap: int, position: int, step: int) -> int:
"""用课件时长和每拍申报的秒数算出固定总次数,不随进度回写变大。"""
if cap <= 0 or step <= 0:
return 0
remaining = max(0, int(cap) - max(0, int(position)))
if remaining <= 0:
return 1
return max(1, math.ceil(remaining / int(step)))
def _count_total(sent: int, progress: float, origin: float = 0.0) -> int:
"""没有课件时长时,用第一次看得到的进度估算总次数,之后不再上调。"""
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]
try:
done, _pending = await asyncio.wait(
tasks, timeout=timeout, return_when=asyncio.FIRST_COMPLETED,
)
return bool(done)
finally:
for task in tasks:
if not task.done():
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
class HoursWatcher:
"""刷新本月学时。看完一门课或每 1 分钟查一次,达标后停止该账号。"""
def __init__(
self,
session: "StudySession",
employee_id: str,
target: int,
user_stop: asyncio.Event,
interval: float = _HOURS_REFRESH_SECONDS,
) -> None:
self.session = session
self.employee_id = employee_id
self.target = target
self.user_stop = user_stop
self.interval = interval
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:
from admin.settings import hours_source_of
source = hours_source_of()
if 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():
_set_user_status(self.employee_id, hours_refresh_at=time.time() + self.interval)
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},
event_hooks={"request": [guard_https_async]},
)
_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, retire_if_dead
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
dead = await asyncio.to_thread(retire_if_dead, self._employee_id, failed)
if not dead:
return True
self._switches += 1
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},
event_hooks={"request": [guard_https_async]},
)
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"):
set_cookie(self._client.cookies, "ELEARNING_00024", refreshed, domain=domain, path="/", secure=True)
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) -> int:
"""只取页文件列表长度,不下载课件。索引失败返回 0,不让整门课失败。"""
return await self.scorm_page_count(kid)
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,
history_items_from_payload,
history_search_body,
take_history_page,
)
from euniv.study_window import CN_TZ
current = now or datetime.now(CN_TZ)
year, month = current.year, current.month
offset = 0
total = 0
seen: set[tuple] = set()
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
add, stop = take_history_page(rows, seen, year, month, HISTORY_PAGE_SIZE)
total += add
if stop:
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,
snapshot: dict | None = None,
video_cap: 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
if video_cap is None:
cap = int(getattr(session, "_video_cap", 0) or 0)
else:
cap = max(0, int(video_cap))
if worker is not None and worker.total <= 0 and cap > 0:
start_at = _whole((snapshot or {}).get("viewSchedule"), 0)
worker.total = _planned_beats(cap, start_at, step)
worker.update(total=worker.total, sent=worker.sent)
started = False
stall = _Stall()
pending = snapshot
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:
if pending is not None:
progress = pending
pending = None
else:
progress = await session.update_progress(kid, pkg_id)
except Exception:
_touch(worker, ok=False)
raise
schedule = _progress_of(progress)
_show_progress(worker, progress, ok=True)
if _completed(progress):
if started:
await hours.refresh()
return
started = True
before = schedule
before_earned = _earned_minutes(progress)
view = _whole(progress.get("viewSchedule"), view)
view = max(0, view + step + random.randint(-1, 1))
if cap > 0:
view = min(view, cap)
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
fresh = await session.update_progress(kid, pkg_id)
schedule = _progress_of(fresh)
landed, give_up, pause = _pace_after(
stall, before, schedule, before_earned, _earned_minutes(fresh), result,
video=True, step=step, interval=interval,
)
_show_progress(worker, fresh, ok=True)
if not landed and not stall.paced:
stall.paced = True
log.info("平台没有记下这次视频心跳,改为隔 %s 秒再发", pause)
if _completed(fresh):
await hours.refresh()
return
if give_up:
raise RuntimeError("进度长时间没有变化")
if not page_rhythm:
if await _heartbeat_wait(worker, pause, 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,
snapshot: dict | 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()
pending = snapshot
while not _halted(stop, hours):
try:
if pending is not None:
progress = pending
pending = None
else:
progress = await session.update_progress(kid, pkg_id)
except Exception:
_touch(worker, ok=False)
raise
schedule = _progress_of(progress)
_show_progress(worker, progress, ok=True)
if _completed(progress):
if started:
await hours.refresh()
return
started = True
before = schedule
before_earned = _earned_minutes(progress)
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)
except Exception:
_touch(worker, ok=False)
raise
fresh = await session.update_progress(kid, pkg_id)
schedule = _progress_of(fresh)
landed, give_up, pause = _pace_after(
stall, before, schedule, before_earned, _earned_minutes(fresh), None,
video=False, step=step, interval=interval,
)
_show_progress(worker, fresh, ok=True)
if not landed and not stall.paced:
stall.paced = True
log.info("平台没有记下这次文档心跳,改为隔 %s 秒再发", pause)
if _completed(fresh):
await hours.refresh()
return
if give_up:
raise RuntimeError("进度长时间没有变化")
if not page_rhythm:
if await _heartbeat_wait(worker, pause, 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 = "",
snapshot: dict | None = None) -> 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
if snapshot is not None:
progress = snapshot
else:
try:
progress = await session.update_progress(kid, pkg_id)
except Exception:
_touch(worker, ok=False)
raise
schedule = _progress_of(progress)
_show_progress(worker, progress, 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)
_show_progress(worker, latest, 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,
)
if _halted(stop, hours):
return
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)
_show_progress(worker, progress, 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)
_show_progress(worker, progress, 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,
skipped: dict | 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
ch_type = _chapter_type(ch.get("knowledgeType"))
if ch_type == "unknown":
_note_unknown(skipped, str(ch_title))
continue
_set_user_status(session._employee_id, course=ch_title)
_show_progress(worker, ch, course=ch_title, knowledge_id=ch_kid, ok=True)
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 ch_type == "video":
cap = _whole(params.get("standardStudyHours"), 0)
session._video_cap = cap
await _study_video(
session, ch_kid, kid, wait, stop, hours, worker,
study_time=study_time, video_cap=cap,
)
else:
session._video_cap = 0
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, retire_if_dead
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):
if retire_if_dead(employee_id, current, str(exc)[:200]):
current = acquire(employee_id)
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()
queried = {row.employee_id for row in users}
with _halt_lock:
stranded = [eid for eid in list(_wanted) if eid not in queried and eid not in _running]
for eid in stranded:
_set_user_status(eid, state="学习失败", message="登录凭证待校验")
drop_work(eid)
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)
_release_pool_later(eid, bool(job[6]))
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
if int(target or 0) <= 0:
if use_pool:
await asyncio.to_thread(_release_pool, emp_id, True)
return
if not course_list:
_set_user_status(emp_id, state="学习失败", message="没有可用的课程")
if use_pool:
await asyncio.to_thread(_release_pool, emp_id, True)
return
hours_source = await asyncio.to_thread(hours_source_of)
assert self._sem is not None
await self._study_user(
emp_id, target, pw, cred, proxy, workers, use_pool,
course_list, 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,
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
if use_pool:
from euniv.proxy_pool import acquire
proxy = await asyncio.to_thread(acquire, employee_id)
if user_stop.is_set():
_set_user_status(employee_id, state="已停止")
return
if not proxy:
_set_user_status(employee_id, message="正在直连")
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:
if reason == "expired":
_set_user_status(employee_id, state="会话失效", message="请重新登录")
log.info("用户 %s 需要重新登录", employee_id)
else:
_set_user_status(employee_id, state="学习失败", message="无法连接学习平台")
log.info("用户 %s 无法连接学习平台", employee_id)
return
async with StudySession(
token, cookies, proxy=proxy, employee_id=employee_id, use_pool=use_pool
) as session:
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)
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, 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, 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}
skipped = {"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,
hours, user_id, org_id, view, finished, skipped,
)
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
async with asyncio.TaskGroup() as group:
for index in range(1, count + 1):
group.create_task(worker_loop(index))
return failed["n"]
async def _study_one_course(self, session: StudySession, employee_id: str,
path: str, title: str, kind: str,
hours: HoursWatcher, user_id: str, org_id: str,
worker: WorkerView | None = None,
finished: set[str] | None = None,
skipped: dict | 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":
_note_unknown(skipped, 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"
_set_user_status(employee_id, course=title)
try:
progress = await session.update_progress(kid, "")
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"
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"
_show_progress(worker, progress, course=title, knowledge_id=kid, ok=True)
if await wait_stop(random.uniform(2.0, 5.0), self._async_stop, hours.user_stop):
return "stop"
intervals, auto_mode = await asyncio.to_thread(_current_intervals, employee_id)
try:
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, ok=True)
ok = await _study_package(
session, kid, intervals, auto_mode,
self._async_stop, hours, user_id, org_id, worker, skipped,
)
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":
video_cap = _whole(params.get("standardStudyHours"), 0)
session._video_cap = video_cap
else:
video_cap = 0
session._video_cap = 0
if ctype == "document" and _uses_new_timer(params) and auto_mode:
page_gap = _whole(params.get("submitProTimes"), 30)
wait = max(1, page_gap)
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, snapshot=progress, video_cap=video_cap,
)
elif ctype == "document":
await _study_document(
session, kid, "", page_size, wait, self._async_stop, hours, worker,
study_time=study_time, snapshot=progress,
)
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 ""),
snapshot=progress,
)
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"
# ── 数据库更新 ──
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