feat: 后台课程清单管理和自动同步
This commit is contained in:
@@ -0,0 +1,230 @@
|
||||
"""后台课程清单。一次只跑一个全量任务,完成后随机隔 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
|
||||
|
||||
_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 course_page(db: Session, query: str, offset: int, limit: int, kind: str = "") -> dict:
|
||||
text = query.strip()
|
||||
base = []
|
||||
if text:
|
||||
like = f"%{text}%"
|
||||
base.append(or_(Course.title.like(like), Course.contributor.like(like)))
|
||||
counts = db.execute(select(Course.kind, func.count()).where(*base).group_by(Course.kind)).all()
|
||||
kinds = [
|
||||
{"name": name or "未分类", "value": name, "count": int(count)}
|
||||
for name, count in sorted(counts, key=lambda row: (_kind_rank(row[0]), row[0]))
|
||||
]
|
||||
filters = list(base)
|
||||
if 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,
|
||||
"comments": row.comments,
|
||||
}
|
||||
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 _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))
|
||||
client = EunivClient(employee_id, password)
|
||||
try:
|
||||
client.restore(credential)
|
||||
if not client.credential_alive():
|
||||
return False
|
||||
courses = client.list_courses()
|
||||
finally:
|
||||
client.close()
|
||||
if not courses:
|
||||
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()
|
||||
sync.course_count = len(courses)
|
||||
db.commit()
|
||||
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()
|
||||
Reference in New Issue
Block a user