Files
EnuivTools/backend/euniv/courses.py
T

302 lines
9.7 KiB
Python

"""后台课程清单。一次只跑一个全量任务,完成后随机隔 8 到 16 小时。"""
from __future__ import annotations
import os
import random
import threading
from datetime import datetime, timedelta, timezone
from sqlalchemy import delete, func, or_, select
from sqlalchemy.orm import Session
from euniv.client import EUNIV
from euniv.models import Account, Course, CourseSync
UNCATEGORIZED = "__none__"
_lock = threading.Lock()
_running = False
_message = ""
def sync_decision(
running: bool,
next_allowed_at: datetime | None,
now: datetime,
force: bool = False,
) -> str:
if running:
return "busy"
if not force and next_allowed_at is not None and now < _as_utc(next_allowed_at):
return "wait"
return "start"
def next_gap(rng: random.Random | None = None) -> timedelta:
hours = (rng or random).uniform(8, 16)
return timedelta(hours=hours)
def choose_account(rows: list[tuple[str, bool | None]], trigger: str, last: str) -> str | None:
eligible = [employee_id for employee_id, valid in rows if employee_id == trigger or valid is not False]
if not eligible:
return None
if len(eligible) > 1 and last in eligible:
eligible = [employee_id for employee_id in eligible if employee_id != last]
eligible.sort()
later = [employee_id for employee_id in eligible if last and employee_id > last]
return later[0] if later else eligible[0]
def request_course_sync(employee_id: str) -> bool:
"""凭据刚被确认有效时尝试启动。已有任务或未到间隔则直接放弃。"""
return _begin(employee_id, force=False) == "start"
def request_course_sync_now() -> str:
"""手动加载。任务已在跑则放弃;否则立刻开始,成功后重新计算间隔。"""
return _begin("", force=True)
def course_running() -> bool:
return _running
def course_message() -> str:
return _message
def _like_pattern(value: str) -> str:
escaped = value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
return f"%{escaped}%"
def course_page(db: Session, query: str, offset: int, limit: int, kind: str = "") -> dict:
text = query.strip()
base = []
if text:
like = _like_pattern(text)
base.append(or_(Course.title.like(like, escape="\\"), Course.contributor.like(like, escape="\\")))
counts = db.execute(select(Course.kind, func.count()).where(*base).group_by(Course.kind)).all()
kinds = [
{"name": name or "未分类", "value": name if name else UNCATEGORIZED, "count": int(count)}
for name, count in sorted(counts, key=lambda row: (_kind_rank(row[0]), row[0]))
]
filters = list(base)
if kind == UNCATEGORIZED:
filters.append(Course.kind == "")
elif kind:
filters.append(Course.kind == kind)
total = db.scalar(select(func.count()).select_from(Course).where(*filters)) or 0
rows = db.scalars(
select(Course)
.where(*filters)
.order_by(Course.updated_on.desc(), Course.title)
.offset(offset)
.limit(limit)
).all()
sync = db.get(CourseSync, 1)
return {
"total": int(total),
"synced_at": _iso(sync.finished_at) if sync else None,
"running": course_running(),
"message": course_message(),
"kinds": kinds,
"items": [
{
"title": row.title,
"kind": row.kind,
"url": EUNIV + row.path,
"contributor": row.contributor,
"recommend": row.recommend,
"learners": row.learners,
"released_on": row.released_on,
"updated_on": row.updated_on,
}
for row in rows
],
}
_KIND_RANK = ("课程包", "课程", "视频", "音频", "文档", "微课", "压缩包")
def _kind_rank(name: str) -> tuple[int, str]:
try:
return (_KIND_RANK.index(name), name)
except ValueError:
return (len(_KIND_RANK), name)
def _begin(employee_id: str, force: bool) -> str:
if os.environ.get("EUNIV_DISABLE_REFRESH") == "1":
return "disabled"
global _running
with _lock:
decision = sync_decision(_running, _next_allowed(), datetime.now(timezone.utc), force=force)
if decision != "start":
return decision
if not _has_credential(employee_id):
return "empty"
_running = True
threading.Thread(target=_run, args=(employee_id,), name="euniv-course-sync", daemon=True).start()
return "start"
def _has_credential(trigger: str) -> bool:
from euniv.db import SessionLocal
with SessionLocal() as db:
return _pick_employee(db, trigger) is not None
def _run(trigger: str) -> None:
global _running, _message
try:
stored = _fetch_and_store(trigger)
with _lock:
_message = "" if stored else "课程清单没有获取到。"
except Exception:
with _lock:
_message = "课程清单没有获取到。"
finally:
with _lock:
_running = False
def _cool_failed_sync(employee_id: str, *, invalid: bool = False) -> None:
from euniv.db import SessionLocal
if not employee_id:
return
with SessionLocal() as db:
sync = db.get(CourseSync, 1)
if sync is None:
sync = CourseSync(id=1, last_employee_id=employee_id)
db.add(sync)
sync.last_employee_id = employee_id
sync.next_allowed_at = datetime.now(timezone.utc) + timedelta(minutes=30)
if invalid:
account = db.get(Account, employee_id)
if account is not None:
account.credential_valid = False
db.commit()
def _fetch_and_store(trigger: str) -> bool:
from euniv.client import EunivClient
from euniv.crypto import decrypt_secret
from euniv.db import SessionLocal
import json
with SessionLocal() as db:
employee_id = _pick_employee(db, trigger)
if not employee_id:
return False
account = db.get(Account, employee_id)
if account is None or not account.credential_cipher:
return False
password = decrypt_secret(account.password_cipher)
credential = json.loads(decrypt_secret(account.credential_cipher))
from euniv.client import is_qr_password
from euniv.proxy import bind_url, is_proxy_failure, uses_pool
from euniv.proxy_pool import MAX_SWITCHES, retire_if_dead
proxy = bind_url(account)
courses = None
last_exc: BaseException | None = None
for _ in range(MAX_SWITCHES + 1):
client = EunivClient(employee_id, password, proxy=proxy)
try:
client.restore(credential)
if not client.credential_alive():
if uses_pool(account) and proxy:
from euniv.proxy_pool import force_direct
force_direct(employee_id)
client.close()
client = EunivClient(employee_id, password, proxy=None)
proxy = None
client.restore(credential)
if client.credential_alive():
courses = client.list_courses()
last_exc = None
break
if password and not is_qr_password(password):
from euniv.service import _persist
profile = client.login(manual=False)
with SessionLocal() as saved:
_persist(saved, employee_id, password, client, profile)
courses = client.list_courses()
last_exc = None
break
_cool_failed_sync(employee_id, invalid=True)
return False
courses = client.list_courses()
last_exc = None
break
except Exception as exc:
last_exc = exc
if uses_pool(account) and proxy and is_proxy_failure(exc):
if retire_if_dead(employee_id, proxy, str(exc)[:200]):
proxy = bind_url(account)
continue
_cool_failed_sync(employee_id)
return False
finally:
client.close()
if last_exc is not None or not courses:
_cool_failed_sync(employee_id)
return False
with SessionLocal() as db:
db.execute(delete(Course))
db.add_all(Course(**course) for course in courses)
sync = db.get(CourseSync, 1)
if sync is None:
sync = CourseSync(id=1)
db.add(sync)
sync.last_employee_id = employee_id
sync.finished_at = datetime.now(timezone.utc)
sync.next_allowed_at = sync.finished_at + next_gap()
db.commit()
from euniv.autostudy import clear_study_hold, request_wake
clear_study_hold(employee_id)
request_wake()
return True
def _pick_employee(db: Session, trigger: str) -> str | None:
rows = db.execute(
select(Account.employee_id, Account.credential_valid)
.where(Account.credential_cipher != "")
.order_by(Account.employee_id)
).all()
sync = db.get(CourseSync, 1)
last = sync.last_employee_id if sync else ""
return choose_account([(row.employee_id, row.credential_valid) for row in rows], trigger, last)
def _next_allowed() -> datetime | None:
from euniv.db import SessionLocal
with SessionLocal() as db:
sync = db.get(CourseSync, 1)
return sync.next_allowed_at if sync else None
def _as_utc(value: datetime) -> datetime:
if value.tzinfo is None:
return value.replace(tzinfo=timezone.utc)
return value
def _iso(value: datetime | None) -> str | None:
if value is None:
return None
moment = _as_utc(value)
return moment.isoformat()