feat: 增加登录页面、学时查询和定时同步
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""EunivTools Web API。"""
|
||||
@@ -0,0 +1,48 @@
|
||||
"""SQLite 连接。开启 WAL,供 Web 和 Worker 同时读取。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from collections.abc import Generator
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import create_engine, event
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
def database_url() -> str:
|
||||
path = os.environ.get("EUNIV_DB_PATH", "data/euniv.db")
|
||||
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
||||
return "sqlite:///" + path.replace("\\", "/")
|
||||
|
||||
|
||||
engine = create_engine(database_url(), connect_args={"check_same_thread": False})
|
||||
SessionLocal = sessionmaker(bind=engine, autoflush=False, expire_on_commit=False)
|
||||
|
||||
|
||||
@event.listens_for(engine, "connect")
|
||||
def _enable_wal(dbapi_connection, _connection_record) -> None:
|
||||
cursor = dbapi_connection.cursor()
|
||||
cursor.execute("PRAGMA journal_mode=WAL")
|
||||
cursor.execute("PRAGMA busy_timeout=5000")
|
||||
cursor.close()
|
||||
|
||||
|
||||
def init_db() -> None:
|
||||
from pathlib import Path
|
||||
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
config = Config(str(root / "alembic.ini"))
|
||||
config.set_main_option("script_location", str(root / "alembic"))
|
||||
config.set_main_option("sqlalchemy.url", database_url())
|
||||
command.upgrade(config, "head")
|
||||
|
||||
|
||||
def get_db() -> Generator[Session, None, None]:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
"""登录、使用者记录和定时配置接口。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import Depends, FastAPI, HTTPException
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.db import get_db, init_db
|
||||
from app.service import list_accounts, list_schedules, login_and_store, public_account, public_schedule, save_schedule
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
init_db()
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(title="EunivTools", lifespan=lifespan)
|
||||
|
||||
|
||||
class LoginBody(BaseModel):
|
||||
employee_id: str = Field(min_length=1, max_length=32)
|
||||
password: str = Field(min_length=1, max_length=128)
|
||||
|
||||
|
||||
class ScheduleBody(BaseModel):
|
||||
employee_id: str = Field(min_length=1, max_length=32)
|
||||
run_time: str = Field(pattern=r"^\d{2}:\d{2}$")
|
||||
enabled: bool = True
|
||||
|
||||
|
||||
@app.get("/api/health")
|
||||
def health() -> dict:
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@app.post("/api/login")
|
||||
def login(body: LoginBody, db: Session = Depends(get_db)) -> dict:
|
||||
try:
|
||||
account = login_and_store(db, body.employee_id.strip(), body.password)
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
return public_account(account)
|
||||
|
||||
|
||||
@app.get("/api/accounts")
|
||||
def accounts(db: Session = Depends(get_db)) -> list[dict]:
|
||||
return [public_account(item) for item in list_accounts(db)]
|
||||
|
||||
|
||||
@app.get("/api/schedules")
|
||||
def schedules(db: Session = Depends(get_db)) -> list[dict]:
|
||||
return [public_schedule(item) for item in list_schedules(db)]
|
||||
|
||||
|
||||
@app.post("/api/schedules")
|
||||
def upsert_schedule(body: ScheduleBody, db: Session = Depends(get_db)) -> dict:
|
||||
hour, minute = body.run_time.split(":")
|
||||
if not (0 <= int(hour) <= 23 and 0 <= int(minute) <= 59):
|
||||
raise HTTPException(status_code=400, detail="时间格式应为 HH:MM")
|
||||
try:
|
||||
schedule = save_schedule(db, body.employee_id.strip(), body.run_time, body.enabled)
|
||||
except LookupError as exc:
|
||||
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||
return public_schedule(schedule)
|
||||
|
||||
|
||||
_dist = Path(__file__).resolve().parents[1] / "web" / "dist"
|
||||
if _dist.is_dir():
|
||||
app.mount("/", StaticFiles(directory=_dist, html=True), name="web")
|
||||
@@ -0,0 +1,43 @@
|
||||
"""账号、定时配置和调度状态。不保存每节课的实时记录。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, String, Text
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
class Account(Base):
|
||||
__tablename__ = "accounts"
|
||||
|
||||
employee_id: Mapped[str] = mapped_column(String(32), primary_key=True)
|
||||
cn_name: Mapped[str] = mapped_column(String(64), default="")
|
||||
department_name: Mapped[str] = mapped_column(String(128), default="")
|
||||
level_name: Mapped[str] = mapped_column(String(64), default="")
|
||||
email: Mapped[str] = mapped_column(String(128), default="")
|
||||
password_cipher: Mapped[str] = mapped_column(Text)
|
||||
actual_study_hour: Mapped[str] = mapped_column(String(32), default="")
|
||||
actual_study_score: Mapped[str] = mapped_column(String(32), default="")
|
||||
points: Mapped[str] = mapped_column(String(32), default="")
|
||||
today_hours: Mapped[str] = mapped_column(String(32), default="")
|
||||
today_score: Mapped[str] = mapped_column(String(32), default="")
|
||||
today: Mapped[str] = mapped_column(String(16), default="")
|
||||
class_count: Mapped[str] = mapped_column(String(16), default="")
|
||||
last_login_at: Mapped[datetime] = mapped_column(DateTime)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime)
|
||||
|
||||
|
||||
class Schedule(Base):
|
||||
__tablename__ = "schedules"
|
||||
|
||||
employee_id: Mapped[str] = mapped_column(String(32), primary_key=True)
|
||||
run_time: Mapped[str] = mapped_column(String(5), default="08:00")
|
||||
enabled: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
status: Mapped[str] = mapped_column(String(16), default="idle")
|
||||
last_run_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
|
||||
last_message: Mapped[str] = mapped_column(String(255), default="")
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
"""登录、保存使用者和读取调度配置。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.models import Account, Schedule
|
||||
from euniv_client import EunivClient
|
||||
from euniv_client.crypto import encrypt_secret
|
||||
|
||||
|
||||
def public_account(account: Account) -> dict:
|
||||
return {
|
||||
"employee_id": account.employee_id,
|
||||
"cn_name": account.cn_name,
|
||||
"department_name": account.department_name,
|
||||
"level_name": account.level_name,
|
||||
"email": account.email,
|
||||
"actual_study_hour": account.actual_study_hour,
|
||||
"actual_study_score": account.actual_study_score,
|
||||
"points": account.points,
|
||||
"today_hours": account.today_hours,
|
||||
"today_score": account.today_score,
|
||||
"today": account.today,
|
||||
"class_count": account.class_count,
|
||||
"last_login_at": account.last_login_at.isoformat(timespec="seconds"),
|
||||
}
|
||||
|
||||
|
||||
def public_schedule(schedule: Schedule) -> dict:
|
||||
return {
|
||||
"employee_id": schedule.employee_id,
|
||||
"run_time": schedule.run_time,
|
||||
"enabled": schedule.enabled,
|
||||
"status": schedule.status,
|
||||
"last_run_at": schedule.last_run_at.isoformat(timespec="seconds") if schedule.last_run_at else None,
|
||||
"last_message": schedule.last_message,
|
||||
}
|
||||
|
||||
|
||||
def apply_session(account: Account, employee_id: str, password: str, session: dict, now: datetime) -> None:
|
||||
profile = session["profile"]
|
||||
summary = session["summary"]
|
||||
account.employee_id = employee_id
|
||||
account.cn_name = str(profile.get("cnName") or "")
|
||||
account.department_name = str(profile.get("departmentName") or "")
|
||||
account.level_name = str(profile.get("userClassLevelName") or "")
|
||||
account.email = str(profile.get("email") or "")
|
||||
account.password_cipher = encrypt_secret(password)
|
||||
account.actual_study_hour = str(summary.get("actual_study_hour") or "")
|
||||
account.actual_study_score = str(summary.get("actual_study_score") or "")
|
||||
account.points = str(summary.get("points") or "")
|
||||
account.today_hours = "" if summary.get("today_hours") is None else str(summary.get("today_hours"))
|
||||
account.today_score = "" if summary.get("today_score") is None else str(summary.get("today_score"))
|
||||
account.today = str(summary.get("today") or "")
|
||||
account.class_count = "" if summary.get("class_count") is None else str(summary.get("class_count"))
|
||||
account.last_login_at = now
|
||||
account.updated_at = now
|
||||
|
||||
|
||||
def login_and_store(db: Session, employee_id: str, password: str, client_factory=EunivClient) -> Account:
|
||||
client = client_factory(employee_id, password)
|
||||
try:
|
||||
session = client.open_session()
|
||||
finally:
|
||||
client.close()
|
||||
now = datetime.now()
|
||||
account = db.get(Account, employee_id)
|
||||
if account is None:
|
||||
account = Account(employee_id=employee_id, password_cipher="", last_login_at=now, updated_at=now)
|
||||
db.add(account)
|
||||
apply_session(account, employee_id, password, session, now)
|
||||
db.commit()
|
||||
db.refresh(account)
|
||||
return account
|
||||
|
||||
|
||||
def list_accounts(db: Session) -> list[Account]:
|
||||
return list(db.scalars(select(Account).order_by(Account.last_login_at.desc())))
|
||||
|
||||
|
||||
def save_schedule(db: Session, employee_id: str, run_time: str, enabled: bool) -> Schedule:
|
||||
if db.get(Account, employee_id) is None:
|
||||
raise LookupError("请先登录该工号")
|
||||
schedule = db.get(Schedule, employee_id)
|
||||
if schedule is None:
|
||||
schedule = Schedule(employee_id=employee_id)
|
||||
db.add(schedule)
|
||||
schedule.run_time = run_time
|
||||
schedule.enabled = enabled
|
||||
db.commit()
|
||||
db.refresh(schedule)
|
||||
return schedule
|
||||
|
||||
|
||||
def list_schedules(db: Session) -> list[Schedule]:
|
||||
return list(db.scalars(select(Schedule).order_by(Schedule.employee_id)))
|
||||
Reference in New Issue
Block a user