refactor: 本地只保存工号和加密密码,并整理后端目录
This commit is contained in:
+6
-9
@@ -7,15 +7,12 @@ RUN npm run build
|
|||||||
|
|
||||||
FROM python:3.13-slim
|
FROM python:3.13-slim
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY requirements.txt .
|
COPY backend/requirements.txt .
|
||||||
RUN pip install --no-cache-dir -r requirements.txt
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
COPY euniv_client euniv_client
|
COPY backend/euniv euniv
|
||||||
COPY app app
|
COPY backend/alembic alembic
|
||||||
COPY worker worker
|
COPY backend/alembic.ini .
|
||||||
COPY alembic alembic
|
COPY --from=web /src/web/dist /web/dist
|
||||||
COPY alembic.ini .
|
|
||||||
COPY scripts scripts
|
|
||||||
COPY --from=web /src/web/dist web/dist
|
|
||||||
ENV EUNIV_DB_PATH=/data/euniv.db
|
ENV EUNIV_DB_PATH=/data/euniv.db
|
||||||
EXPOSE 8000
|
EXPOSE 8000
|
||||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
CMD ["uvicorn", "euniv.api:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
"""EunivTools Web API。"""
|
|
||||||
-75
@@ -1,75 +0,0 @@
|
|||||||
"""登录、使用者记录和定时配置接口。"""
|
|
||||||
|
|
||||||
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")
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
"""账号、定时配置和调度状态。不保存每节课的实时记录。"""
|
|
||||||
|
|
||||||
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
@@ -1,100 +0,0 @@
|
|||||||
"""登录、保存使用者和读取调度配置。"""
|
|
||||||
|
|
||||||
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)))
|
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
from alembic import context
|
from alembic import context
|
||||||
from sqlalchemy import engine_from_config, pool
|
from sqlalchemy import engine_from_config, pool
|
||||||
|
|
||||||
from app.db import database_url
|
from euniv.db import database_url
|
||||||
from app.models import Base
|
from euniv.models import Base
|
||||||
|
|
||||||
config = context.config
|
config = context.config
|
||||||
config.set_main_option("sqlalchemy.url", database_url())
|
config.set_main_option("sqlalchemy.url", database_url())
|
||||||
@@ -10,7 +10,12 @@ target_metadata = Base.metadata
|
|||||||
|
|
||||||
|
|
||||||
def run_migrations_offline() -> None:
|
def run_migrations_offline() -> None:
|
||||||
context.configure(url=database_url(), target_metadata=target_metadata, literal_binds=True)
|
context.configure(
|
||||||
|
url=database_url(),
|
||||||
|
target_metadata=target_metadata,
|
||||||
|
literal_binds=True,
|
||||||
|
render_as_batch=True,
|
||||||
|
)
|
||||||
with context.begin_transaction():
|
with context.begin_transaction():
|
||||||
context.run_migrations()
|
context.run_migrations()
|
||||||
|
|
||||||
@@ -22,7 +27,7 @@ def run_migrations_online() -> None:
|
|||||||
poolclass=pool.NullPool,
|
poolclass=pool.NullPool,
|
||||||
)
|
)
|
||||||
with connectable.connect() as connection:
|
with connectable.connect() as connection:
|
||||||
context.configure(connection=connection, target_metadata=target_metadata)
|
context.configure(connection=connection, target_metadata=target_metadata, render_as_batch=True)
|
||||||
with context.begin_transaction():
|
with context.begin_transaction():
|
||||||
context.run_migrations()
|
context.run_migrations()
|
||||||
|
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
"""本地只保留工号和加密密码。"""
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
revision = "0002_accounts_only"
|
||||||
|
down_revision = "0001_init"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
with op.batch_alter_table("accounts") as batch:
|
||||||
|
batch.drop_column("cn_name")
|
||||||
|
batch.drop_column("department_name")
|
||||||
|
batch.drop_column("level_name")
|
||||||
|
batch.drop_column("email")
|
||||||
|
batch.drop_column("actual_study_hour")
|
||||||
|
batch.drop_column("actual_study_score")
|
||||||
|
batch.drop_column("points")
|
||||||
|
batch.drop_column("today_hours")
|
||||||
|
batch.drop_column("today_score")
|
||||||
|
batch.drop_column("today")
|
||||||
|
batch.drop_column("class_count")
|
||||||
|
batch.drop_column("last_login_at")
|
||||||
|
batch.drop_column("updated_at")
|
||||||
|
op.drop_table("schedules")
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
"schedules",
|
||||||
|
sa.Column("employee_id", sa.String(32), primary_key=True),
|
||||||
|
sa.Column("run_time", sa.String(5), nullable=False, server_default="08:00"),
|
||||||
|
sa.Column("enabled", sa.Boolean(), nullable=False, server_default=sa.true()),
|
||||||
|
sa.Column("status", sa.String(16), nullable=False, server_default="idle"),
|
||||||
|
sa.Column("last_run_at", sa.DateTime(), nullable=True),
|
||||||
|
sa.Column("last_message", sa.String(255), nullable=False, server_default=""),
|
||||||
|
)
|
||||||
|
with op.batch_alter_table("accounts") as batch:
|
||||||
|
batch.add_column(sa.Column("cn_name", sa.String(64), nullable=False, server_default=""))
|
||||||
|
batch.add_column(sa.Column("department_name", sa.String(128), nullable=False, server_default=""))
|
||||||
|
batch.add_column(sa.Column("level_name", sa.String(64), nullable=False, server_default=""))
|
||||||
|
batch.add_column(sa.Column("email", sa.String(128), nullable=False, server_default=""))
|
||||||
|
batch.add_column(sa.Column("actual_study_hour", sa.String(32), nullable=False, server_default=""))
|
||||||
|
batch.add_column(sa.Column("actual_study_score", sa.String(32), nullable=False, server_default=""))
|
||||||
|
batch.add_column(sa.Column("points", sa.String(32), nullable=False, server_default=""))
|
||||||
|
batch.add_column(sa.Column("today_hours", sa.String(32), nullable=False, server_default=""))
|
||||||
|
batch.add_column(sa.Column("today_score", sa.String(32), nullable=False, server_default=""))
|
||||||
|
batch.add_column(sa.Column("today", sa.String(16), nullable=False, server_default=""))
|
||||||
|
batch.add_column(sa.Column("class_count", sa.String(16), nullable=False, server_default=""))
|
||||||
|
batch.add_column(sa.Column("last_login_at", sa.DateTime(), nullable=True))
|
||||||
|
batch.add_column(sa.Column("updated_at", sa.DateTime(), nullable=True))
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
"""中兴 e 学客户端和本机账号库。"""
|
||||||
|
|
||||||
|
from euniv.client import EunivClient
|
||||||
|
|
||||||
|
__all__ = ["EunivClient"]
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
"""登录接口。本地只保存工号和加密密码。"""
|
||||||
|
|
||||||
|
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 euniv.db import get_db, init_db
|
||||||
|
from euniv.service import list_accounts, login_and_store
|
||||||
|
|
||||||
|
|
||||||
|
@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)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/health")
|
||||||
|
def health() -> dict:
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/login")
|
||||||
|
def login(body: LoginBody, db: Session = Depends(get_db)) -> dict:
|
||||||
|
employee_id = body.employee_id.strip()
|
||||||
|
try:
|
||||||
|
login_and_store(db, employee_id, body.password)
|
||||||
|
except RuntimeError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
return {"employee_id": employee_id}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/accounts")
|
||||||
|
def accounts(db: Session = Depends(get_db)) -> list[dict]:
|
||||||
|
return [{"employee_id": item.employee_id} for item in list_accounts(db)]
|
||||||
|
|
||||||
|
|
||||||
|
_dist = Path(__file__).resolve().parents[2] / "web" / "dist"
|
||||||
|
if _dist.is_dir():
|
||||||
|
app.mount("/", StaticFiles(directory=_dist, html=True), name="web")
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
"""SQLite 连接。开启 WAL,供 Web 和 Worker 同时读取。"""
|
"""SQLite 连接。"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -9,6 +9,7 @@ from pathlib import Path
|
|||||||
from sqlalchemy import create_engine, event
|
from sqlalchemy import create_engine, event
|
||||||
from sqlalchemy.orm import Session, sessionmaker
|
from sqlalchemy.orm import Session, sessionmaker
|
||||||
|
|
||||||
|
|
||||||
def database_url() -> str:
|
def database_url() -> str:
|
||||||
path = os.environ.get("EUNIV_DB_PATH", "data/euniv.db")
|
path = os.environ.get("EUNIV_DB_PATH", "data/euniv.db")
|
||||||
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
||||||
@@ -28,8 +29,6 @@ def _enable_wal(dbapi_connection, _connection_record) -> None:
|
|||||||
|
|
||||||
|
|
||||||
def init_db() -> None:
|
def init_db() -> None:
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
from alembic import command
|
from alembic import command
|
||||||
from alembic.config import Config
|
from alembic.config import Config
|
||||||
|
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
"""本地只保存工号和加密后的密码。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from sqlalchemy import 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)
|
||||||
|
password_cipher: Mapped[str] = mapped_column(Text)
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
"""校验 e 学登录,并只把工号和加密密码写入本地库。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from euniv.client import EunivClient
|
||||||
|
from euniv.crypto import decrypt_secret, encrypt_secret
|
||||||
|
from euniv.models import Account
|
||||||
|
|
||||||
|
|
||||||
|
def login_and_store(db: Session, employee_id: str, password: str, client_factory=EunivClient) -> Account:
|
||||||
|
client = client_factory(employee_id, password)
|
||||||
|
try:
|
||||||
|
client.login()
|
||||||
|
finally:
|
||||||
|
client.close()
|
||||||
|
account = db.get(Account, employee_id)
|
||||||
|
if account is None:
|
||||||
|
account = Account(employee_id=employee_id, password_cipher=encrypt_secret(password))
|
||||||
|
db.add(account)
|
||||||
|
else:
|
||||||
|
account.password_cipher = encrypt_secret(password)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(account)
|
||||||
|
return account
|
||||||
|
|
||||||
|
|
||||||
|
def list_accounts(db: Session) -> list[Account]:
|
||||||
|
return list(db.scalars(select(Account).order_by(Account.employee_id)))
|
||||||
|
|
||||||
|
|
||||||
|
def stored_password(account: Account) -> str:
|
||||||
|
return decrypt_secret(account.password_cipher)
|
||||||
@@ -1,7 +1,10 @@
|
|||||||
import os
|
import os
|
||||||
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
_root = Path(__file__).resolve().parents[1] / "Temp" / "pytest"
|
_backend = Path(__file__).resolve().parents[1]
|
||||||
|
sys.path.insert(0, str(_backend))
|
||||||
|
_root = _backend.parent / "Temp" / "pytest"
|
||||||
_root.mkdir(parents=True, exist_ok=True)
|
_root.mkdir(parents=True, exist_ok=True)
|
||||||
os.environ["EUNIV_SECRET_KEY"] = "test-secret-key"
|
os.environ["EUNIV_SECRET_KEY"] = "test-secret-key"
|
||||||
os.environ["EUNIV_DB_PATH"] = str(_root / "euniv.db")
|
os.environ["EUNIV_DB_PATH"] = str(_root / "euniv.db")
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
from fastapi.testclient import TestClient
|
||||||
|
from sqlalchemy import text
|
||||||
|
|
||||||
|
from euniv.crypto import decrypt_secret
|
||||||
|
from euniv.db import SessionLocal, engine, init_db
|
||||||
|
from euniv.models import Account
|
||||||
|
|
||||||
|
|
||||||
|
class FakeClient:
|
||||||
|
def __init__(self, login_name: str, password: str) -> None:
|
||||||
|
self.login_name = login_name
|
||||||
|
self.password = password
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def login(self) -> dict:
|
||||||
|
return {"accountId": self.login_name}
|
||||||
|
|
||||||
|
|
||||||
|
def setup_function() -> None:
|
||||||
|
with engine.begin() as connection:
|
||||||
|
connection.execute(text("DROP TABLE IF EXISTS accounts"))
|
||||||
|
connection.execute(text("DROP TABLE IF EXISTS schedules"))
|
||||||
|
connection.execute(text("DROP TABLE IF EXISTS alembic_version"))
|
||||||
|
init_db()
|
||||||
|
|
||||||
|
|
||||||
|
def test_login_stores_only_employee_id_and_password() -> None:
|
||||||
|
import euniv.api as api_module
|
||||||
|
import euniv.service as service_module
|
||||||
|
|
||||||
|
api_module.login_and_store = lambda db, employee_id, password: service_module.login_and_store(
|
||||||
|
db, employee_id, password, FakeClient
|
||||||
|
)
|
||||||
|
client = TestClient(api_module.app)
|
||||||
|
response = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"})
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json() == {"employee_id": "6650000146"}
|
||||||
|
listed = client.get("/api/accounts").json()
|
||||||
|
assert listed == [{"employee_id": "6650000146"}]
|
||||||
|
with SessionLocal() as db:
|
||||||
|
account = db.get(Account, "6650000146")
|
||||||
|
assert account is not None
|
||||||
|
assert decrypt_secret(account.password_cipher) == "secret-pass"
|
||||||
|
assert set(account.__table__.columns.keys()) == {"employee_id", "password_cipher"}
|
||||||
@@ -9,17 +9,6 @@ services:
|
|||||||
EUNIV_DB_PATH: /data/euniv.db
|
EUNIV_DB_PATH: /data/euniv.db
|
||||||
volumes:
|
volumes:
|
||||||
- euniv-data:/data
|
- euniv-data:/data
|
||||||
worker:
|
|
||||||
build: .
|
|
||||||
command: ["python", "-m", "worker"]
|
|
||||||
environment:
|
|
||||||
EUNIV_SECRET_KEY: ${EUNIV_SECRET_KEY:?请在环境变量或 .env 中设置 EUNIV_SECRET_KEY}
|
|
||||||
EUNIV_DB_PATH: /data/euniv.db
|
|
||||||
EUNIV_WORKER_INTERVAL: "20"
|
|
||||||
volumes:
|
|
||||||
- euniv-data:/data
|
|
||||||
depends_on:
|
|
||||||
- web
|
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
euniv-data:
|
euniv-data:
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
"""中兴 e 学登录与学习数据查询。"""
|
|
||||||
|
|
||||||
from euniv_client.client import EunivClient
|
|
||||||
|
|
||||||
__all__ = ["EunivClient"]
|
|
||||||
+7
-12
@@ -1,4 +1,4 @@
|
|||||||
"""命令行登录中兴 e 学并打印用户资料与学时汇总。"""
|
"""命令行登录中兴 e 学并打印用户资料。资料只打印,不写入本地库。"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -6,9 +6,9 @@ import os
|
|||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "backend"))
|
||||||
|
|
||||||
from euniv_client import EunivClient
|
from euniv import EunivClient
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
def main() -> int:
|
||||||
@@ -19,26 +19,21 @@ def main() -> int:
|
|||||||
return 2
|
return 2
|
||||||
client = EunivClient(login_name, password)
|
client = EunivClient(login_name, password)
|
||||||
try:
|
try:
|
||||||
session = client.open_session()
|
profile = client.login()
|
||||||
|
client.authorize(profile)
|
||||||
|
info = client.user_info()
|
||||||
finally:
|
finally:
|
||||||
client.close()
|
client.close()
|
||||||
info = session["profile"]
|
|
||||||
summary = session["summary"]
|
|
||||||
fields = [
|
fields = [
|
||||||
("工号", info.get("username")),
|
("工号", info.get("username")),
|
||||||
("姓名", info.get("cnName")),
|
("姓名", info.get("cnName")),
|
||||||
("部门", info.get("departmentName")),
|
("部门", info.get("departmentName")),
|
||||||
("岗位层级", info.get("userClassLevelName")),
|
("岗位层级", info.get("userClassLevelName")),
|
||||||
("邮箱", info.get("email")),
|
("邮箱", info.get("email")),
|
||||||
("累计学时", summary.get("actual_study_hour")),
|
|
||||||
("累计学分", summary.get("actual_study_score")),
|
|
||||||
("积分", summary.get("points")),
|
|
||||||
("今日学时", summary.get("today_hours")),
|
|
||||||
("今日学分", summary.get("today_score")),
|
|
||||||
]
|
]
|
||||||
print("登录成功")
|
print("登录成功")
|
||||||
for label, value in fields:
|
for label, value in fields:
|
||||||
if value is not None and value != "":
|
if value:
|
||||||
print(f"{label}:{value}")
|
print(f"{label}:{value}")
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|||||||
@@ -1,103 +0,0 @@
|
|||||||
from datetime import datetime
|
|
||||||
|
|
||||||
from fastapi.testclient import TestClient
|
|
||||||
|
|
||||||
from app.db import SessionLocal, init_db
|
|
||||||
from app.models import Account, Schedule
|
|
||||||
from worker.__main__ import due, run_once
|
|
||||||
|
|
||||||
|
|
||||||
class FakeClient:
|
|
||||||
def __init__(self, login_name: str, password: str) -> None:
|
|
||||||
self.login_name = login_name
|
|
||||||
self.password = password
|
|
||||||
|
|
||||||
def close(self) -> None:
|
|
||||||
return None
|
|
||||||
|
|
||||||
def open_session(self) -> dict:
|
|
||||||
return {
|
|
||||||
"profile": {
|
|
||||||
"username": self.login_name,
|
|
||||||
"cnName": "莫英达",
|
|
||||||
"departmentName": "广州处",
|
|
||||||
"userClassLevelName": "Scientist",
|
|
||||||
"email": "mo@example.com",
|
|
||||||
},
|
|
||||||
"summary": {
|
|
||||||
"actual_study_hour": "10",
|
|
||||||
"actual_study_score": "3.5",
|
|
||||||
"points": "20",
|
|
||||||
"today_hours": 1.5,
|
|
||||||
"today_score": 0,
|
|
||||||
"today": "2026-10-26",
|
|
||||||
"class_count": 0,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def setup_function() -> None:
|
|
||||||
from sqlalchemy import text
|
|
||||||
|
|
||||||
from app.db import engine
|
|
||||||
|
|
||||||
with engine.begin() as connection:
|
|
||||||
connection.execute(text("DROP TABLE IF EXISTS accounts"))
|
|
||||||
connection.execute(text("DROP TABLE IF EXISTS schedules"))
|
|
||||||
connection.execute(text("DROP TABLE IF EXISTS alembic_version"))
|
|
||||||
init_db()
|
|
||||||
|
|
||||||
|
|
||||||
def test_login_stores_account_without_returning_password() -> None:
|
|
||||||
from app.main import app
|
|
||||||
import app.main as main_module
|
|
||||||
import app.service as service_module
|
|
||||||
|
|
||||||
service_module.EunivClient = FakeClient
|
|
||||||
main_module.login_and_store = lambda db, employee_id, password: service_module.login_and_store(
|
|
||||||
db, employee_id, password, FakeClient
|
|
||||||
)
|
|
||||||
client = TestClient(app)
|
|
||||||
response = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"})
|
|
||||||
assert response.status_code == 200
|
|
||||||
body = response.json()
|
|
||||||
assert body["cn_name"] == "莫英达"
|
|
||||||
assert body["actual_study_hour"] == "10"
|
|
||||||
assert "password" not in body
|
|
||||||
listed = client.get("/api/accounts").json()
|
|
||||||
assert listed[0]["employee_id"] == "6650000146"
|
|
||||||
assert "password" not in listed[0]
|
|
||||||
|
|
||||||
|
|
||||||
def test_schedule_and_worker_sync() -> None:
|
|
||||||
from app.main import app
|
|
||||||
|
|
||||||
with SessionLocal() as db:
|
|
||||||
db.add(
|
|
||||||
Account(
|
|
||||||
employee_id="10001",
|
|
||||||
password_cipher="",
|
|
||||||
last_login_at=datetime.now(),
|
|
||||||
updated_at=datetime.now(),
|
|
||||||
)
|
|
||||||
)
|
|
||||||
db.commit()
|
|
||||||
from app.service import login_and_store
|
|
||||||
|
|
||||||
with SessionLocal() as db:
|
|
||||||
login_and_store(db, "10001", "secret-pass", FakeClient)
|
|
||||||
client = TestClient(app)
|
|
||||||
saved = client.post("/api/schedules", json={"employee_id": "10001", "run_time": "00:00", "enabled": True})
|
|
||||||
assert saved.status_code == 200
|
|
||||||
assert run_once(FakeClient) == 1
|
|
||||||
with SessionLocal() as db:
|
|
||||||
schedule = db.get(Schedule, "10001")
|
|
||||||
assert schedule is not None
|
|
||||||
assert schedule.status == "ok"
|
|
||||||
|
|
||||||
|
|
||||||
def test_due_skips_completed_today() -> None:
|
|
||||||
now = datetime(2026, 10, 26, 9, 0)
|
|
||||||
schedule = Schedule(employee_id="1", run_time="08:00", enabled=True, status="ok", last_run_at=now)
|
|
||||||
assert due(schedule, now) is False
|
|
||||||
assert due(schedule, datetime(2026, 10, 27, 8, 0)) is True
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
"""定时同步学习汇总。"""
|
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
"""轮询定时配置,到点登录并刷新学时学分汇总。"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import os
|
|
||||||
import time
|
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
from sqlalchemy import select
|
|
||||||
|
|
||||||
from app.db import SessionLocal, init_db
|
|
||||||
from app.models import Account, Schedule
|
|
||||||
from app.service import apply_session
|
|
||||||
from euniv_client import EunivClient
|
|
||||||
from euniv_client.crypto import decrypt_secret
|
|
||||||
|
|
||||||
|
|
||||||
def due(schedule: Schedule, now: datetime) -> bool:
|
|
||||||
if not schedule.enabled:
|
|
||||||
return False
|
|
||||||
hour, minute = schedule.run_time.split(":")
|
|
||||||
if (now.hour, now.minute) < (int(hour), int(minute)):
|
|
||||||
return False
|
|
||||||
if schedule.last_run_at and schedule.last_run_at.date() == now.date() and schedule.status == "ok":
|
|
||||||
return False
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
def run_once(client_factory=EunivClient) -> int:
|
|
||||||
init_db()
|
|
||||||
now = datetime.now()
|
|
||||||
ran = 0
|
|
||||||
with SessionLocal() as db:
|
|
||||||
schedules = list(db.scalars(select(Schedule)))
|
|
||||||
for schedule in schedules:
|
|
||||||
if not due(schedule, now):
|
|
||||||
continue
|
|
||||||
account = db.get(Account, schedule.employee_id)
|
|
||||||
if account is None:
|
|
||||||
schedule.status = "error"
|
|
||||||
schedule.last_message = "账号不存在"
|
|
||||||
db.commit()
|
|
||||||
continue
|
|
||||||
schedule.status = "running"
|
|
||||||
db.commit()
|
|
||||||
try:
|
|
||||||
password = decrypt_secret(account.password_cipher)
|
|
||||||
client = client_factory(account.employee_id, password)
|
|
||||||
try:
|
|
||||||
session = client.open_session()
|
|
||||||
finally:
|
|
||||||
client.close()
|
|
||||||
apply_session(account, account.employee_id, password, session, now)
|
|
||||||
schedule.status = "ok"
|
|
||||||
schedule.last_message = "已同步学时学分"
|
|
||||||
schedule.last_run_at = now
|
|
||||||
ran += 1
|
|
||||||
except Exception as exc:
|
|
||||||
schedule.status = "error"
|
|
||||||
schedule.last_message = str(exc)[:255]
|
|
||||||
schedule.last_run_at = now
|
|
||||||
db.commit()
|
|
||||||
return ran
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
|
||||||
interval = int(os.environ.get("EUNIV_WORKER_INTERVAL", "20"))
|
|
||||||
while True:
|
|
||||||
run_once()
|
|
||||||
time.sleep(interval)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
Reference in New Issue
Block a user