feat: 增加登录页面、学时查询和定时同步

This commit is contained in:
2026-10-26 12:10:02 +08:00
parent cb935f081e
commit 626f9eab5c
32 changed files with 2924 additions and 249 deletions
+8
View File
@@ -0,0 +1,8 @@
.venv
.git
Temp
data
web/node_modules
web/dist
**/__pycache__
.env
+3
View File
@@ -0,0 +1,3 @@
EUNIV_SECRET_KEY=请换成一串只放在服务器上的密钥
EUNIV_DB_PATH=data/euniv.db
EUNIV_WORKER_INTERVAL=20
+3
View File
@@ -3,3 +3,6 @@ Temp/
__pycache__/
*.py[cod]
.env
data/
web/node_modules/
web/dist/
+21
View File
@@ -0,0 +1,21 @@
FROM node:22-alpine AS web
WORKDIR /src/web
COPY web/package.json web/package-lock.json* ./
RUN npm install
COPY web/ ./
RUN npm run build
FROM python:3.13-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY euniv_client euniv_client
COPY app app
COPY worker worker
COPY alembic alembic
COPY alembic.ini .
COPY scripts scripts
COPY --from=web /src/web/dist web/dist
ENV EUNIV_DB_PATH=/data/euniv.db
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
+25
View File
@@ -0,0 +1,25 @@
[alembic]
script_location = alembic
sqlalchemy.url = sqlite:///data/euniv.db
[loggers]
keys = root
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
+33
View File
@@ -0,0 +1,33 @@
from alembic import context
from sqlalchemy import engine_from_config, pool
from app.db import database_url
from app.models import Base
config = context.config
config.set_main_option("sqlalchemy.url", database_url())
target_metadata = Base.metadata
def run_migrations_offline() -> None:
context.configure(url=database_url(), target_metadata=target_metadata, literal_binds=True)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
connectable = engine_from_config(
config.get_section(config.config_ini_section) or {},
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
+21
View File
@@ -0,0 +1,21 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}
+44
View File
@@ -0,0 +1,44 @@
"""账号与定时配置。"""
from alembic import op
import sqlalchemy as sa
revision = "0001_init"
down_revision = None
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"accounts",
sa.Column("employee_id", sa.String(32), primary_key=True),
sa.Column("cn_name", sa.String(64), nullable=False, server_default=""),
sa.Column("department_name", sa.String(128), nullable=False, server_default=""),
sa.Column("level_name", sa.String(64), nullable=False, server_default=""),
sa.Column("email", sa.String(128), nullable=False, server_default=""),
sa.Column("password_cipher", sa.Text(), nullable=False),
sa.Column("actual_study_hour", sa.String(32), nullable=False, server_default=""),
sa.Column("actual_study_score", sa.String(32), nullable=False, server_default=""),
sa.Column("points", sa.String(32), nullable=False, server_default=""),
sa.Column("today_hours", sa.String(32), nullable=False, server_default=""),
sa.Column("today_score", sa.String(32), nullable=False, server_default=""),
sa.Column("today", sa.String(16), nullable=False, server_default=""),
sa.Column("class_count", sa.String(16), nullable=False, server_default=""),
sa.Column("last_login_at", sa.DateTime(), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=False),
)
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=""),
)
def downgrade() -> None:
op.drop_table("schedules")
op.drop_table("accounts")
+1
View File
@@ -0,0 +1 @@
"""EunivTools Web API。"""
+48
View File
@@ -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
View File
@@ -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")
+43
View File
@@ -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
View File
@@ -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)))
+25
View File
@@ -0,0 +1,25 @@
# Web 监听 8000。用 1Panel 反代到该端口,对外提供页面和 /api。
services:
web:
build: .
ports:
- "8000:8000"
environment:
EUNIV_SECRET_KEY: ${EUNIV_SECRET_KEY:?请在环境变量或 .env 中设置 EUNIV_SECRET_KEY}
EUNIV_DB_PATH: /data/euniv.db
volumes:
- 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:
euniv-data:
+5
View File
@@ -0,0 +1,5 @@
"""中兴 e 学登录与学习数据查询。"""
from euniv_client.client import EunivClient
__all__ = ["EunivClient"]
+298
View File
@@ -0,0 +1,298 @@
"""登录中兴 e 学并查询学时、学分汇总。"""
from __future__ import annotations
import base64
import io
import random
import time
import uuid
from urllib.parse import quote
import httpx
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding
from PIL import Image
PORTAL = "https://bmtucportal.zte.com.cn"
EUNIV = "https://euniv.zte.com.cn"
YXT_API = "https://api-qidacustomc1.yunxuetang.cn"
STUDY_API = "https://api-qidac1.yunxuetang.cn"
CLASS_API = "https://sdcs-api-ztec1.yunxuetang.cn"
REDIRECT_URI = f"{YXT_API}/v1/ztctech/sso"
CLIENT_ID = "30051"
TENANT_ID = "10001"
APP_ID = "10051"
USER_AGENT = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:158.0) "
"Gecko/20100101 Firefox/158.0"
)
def now_ms() -> int:
return int(time.time() * 1000)
def make_kid(prefix: str = "t") -> str:
return prefix + "".join(random.choice("1234567890") for _ in range(4))
def encrypt_password(public_key_b64: str, password: str) -> str:
key = serialization.load_der_public_key(base64.b64decode(public_key_b64))
cipher = key.encrypt(password.encode("utf-8"), padding.PKCS1v15())
return base64.b64encode(cipher).decode("ascii")
def decode_data_uri(value: str) -> bytes:
payload = value.split(",", 1)[1] if "," in value else value
return base64.b64decode(payload)
def jigsaw_offset(big_png: bytes, small_png: bytes, top: int) -> int:
"""返回滑块左边缘在底图上的横坐标。"""
big = Image.open(io.BytesIO(big_png)).convert("RGBA")
small = Image.open(io.BytesIO(small_png)).convert("RGBA")
width, height = big.size
piece_w, piece_h = small.size
mask: list[tuple[int, int, tuple[int, int, int]]] = []
for y in range(piece_h):
for x in range(piece_w):
red, green, blue, alpha = small.getpixel((x, y))
if alpha > 128:
mask.append((x, y, (red, green, blue)))
best_x = 0
best_score = None
limit = width - piece_w
for origin in range(max(limit, 0)):
score = 0
for x, y, color in mask:
pixel = big.getpixel((origin + x, top + y))
score += abs(pixel[0] - color[0]) + abs(pixel[1] - color[1]) + abs(pixel[2] - color[2])
if best_score is None or score < best_score:
best_score = score
best_x = origin
if top + piece_h > height:
raise RuntimeError("拼图纵坐标超出底图高度")
return best_x
class EunivClient:
def __init__(self, login_name: str, password: str) -> None:
self.login_name = login_name.strip()
self.password = password
self.client = httpx.Client(timeout=30, follow_redirects=True, headers={"User-Agent": USER_AGENT})
def close(self) -> None:
self.client.close()
def portal_headers(self) -> dict[str, str]:
referer = (
f"{PORTAL}/uc/{TENANT_ID}/oauthLogin?client_id={CLIENT_ID}"
f"&scope=profile&redirect_uri={quote(REDIRECT_URI, safe='')}"
"&response_type=code"
)
return {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json;charset=UTF-8",
"Origin": PORTAL,
"Referer": referer,
"X-App-Id": APP_ID,
"X-Device-Type": "pc",
"X-Itp-Value": "from=ucs-portal;client=pc;platform=portal",
"X-Lang-Id": "zh_CN",
"X-Tenant-Id": TENANT_ID,
"x_uuid": str(uuid.uuid4()),
}
def code_of(self, payload: dict) -> tuple[str, str, object]:
block = payload.get("code") or {}
return block.get("code") or "", block.get("msg") or "", payload.get("bo")
def login(self) -> dict:
self.client.get(EUNIV + "/")
self.client.post(
f"{PORTAL}/zte-bmt-ucs-portalbff/oauth/validate",
headers=self.portal_headers(),
json={
"clientId": CLIENT_ID,
"redirectUri": REDIRECT_URI,
"responseType": "code",
"scope": "profile",
"_t": now_ms(),
},
)
key_resp = self.client.post(
f"{PORTAL}/zte-bmt-ucs-portalbff/srv/password/publicKey/{TENANT_ID}",
headers=self.portal_headers(),
json={"_t": now_ms()},
)
key_code, key_message, public_key = self.code_of(key_resp.json())
if key_code != "0000" or not isinstance(public_key, str):
raise RuntimeError(f"获取密码公钥失败:{key_message or key_resp.status_code}")
check_resp = self.client.post(
f"{PORTAL}/zte-bmt-ucs-portalbff/srv/pas/securitycode/check",
headers=self.portal_headers(),
json={"accountId": self.login_name, "callerId": APP_ID, "_t": now_ms()},
)
check_code, check_message, needs_security_code = self.code_of(check_resp.json())
if check_code == "0000" and needs_security_code is True:
raise RuntimeError("这个账号开启了动态安全码,当前登录流程还不能提交安全码")
if check_code not in ("", "0000"):
raise RuntimeError(f"安全码检查失败:{check_message}")
cipher = encrypt_password(public_key, self.password)
last_message = "登录未完成"
for _ in range(3):
kid = make_kid("t")
image_resp = self.client.get(
f"{PORTAL}/zte-bmt-ucs-portalbff/srv/kaptcha/jigsaw",
params={"kid": kid, "_t": now_ms()},
headers=self.portal_headers(),
)
image_code, image_message, image = self.code_of(image_resp.json())
if image_code != "0000":
raise RuntimeError(f"获取拼图失败:{image_message}")
if not isinstance(image, dict):
raise RuntimeError("拼图返回无法识别")
offset = jigsaw_offset(
decode_data_uri(image["bigImg"]),
decode_data_uri(image["smallImg"]),
int(image["yHeight"]),
)
headers = self.portal_headers()
headers.update({"kcode": "", "kid": make_kid(""), "kskip": "true", "source": APP_ID})
login_resp = self.client.post(
f"{PORTAL}/zte-bmt-ucs-portalbff/srv/login",
headers=headers,
json={
"loginName": self.login_name,
"password": cipher,
"kid": kid,
"jigsawCode": offset,
"_t": now_ms(),
},
)
login_code, last_message, profile = self.code_of(login_resp.json())
if login_code == "0000" and isinstance(profile, dict):
return profile
if any(word in last_message for word in ("验证码", "拼图", "滑块")):
continue
raise RuntimeError(f"登录失败:{last_message}")
raise RuntimeError(f"登录失败:{last_message}")
def authorize(self, profile: dict) -> None:
account_id = str(profile["accountId"])
user_id = str(profile["userId"])
token = str(profile["token"])
domain = "zte.com.cn"
jar = {
"UCSLoginName": account_id,
"UCSSSOAccount": account_id,
"UCSSSOUser": user_id,
"UCSSSOToken": token,
"UCSSSOInfo": str(profile.get("ssoinfo") or ""),
"UCSSSOLanguage": "zh_CN",
"UCSLoginTime": str(now_ms()),
"iAuthTenantId_prod": TENANT_ID,
"iAuthUserId_prod": user_id,
"iAuthUid_prod": account_id,
"iAuthTid_prod": token,
"iAuthLanguage_prod": "zh_CN",
}
if profile.get("unionId"):
jar["iuacUnionId"] = str(profile["unionId"])
for name, value in jar.items():
self.client.cookies.set(name, value, domain=domain, path="/")
response = self.client.post(
f"{PORTAL}/zte-bmt-ucs-portalbff/oauth/authorize",
params={
"redirect_uri": REDIRECT_URI,
"client_id": CLIENT_ID,
"response_type": "code",
"scope": "profile",
},
headers=self.portal_headers(),
json={"accountId": account_id, "token": token, "userId": user_id, "_t": now_ms()},
)
code, message, redirect_url = self.code_of(response.json())
if code != "0000" or not isinstance(redirect_url, str):
raise RuntimeError(f"申请学习平台授权码失败:{message}")
self.client.get(redirect_url, headers={"Referer": PORTAL + "/", "User-Agent": USER_AGENT})
def session_token(self) -> str:
for cookie in self.client.cookies.jar:
if cookie.name == "ELEARNING_00024" and cookie.value:
return cookie.value
names = sorted({cookie.name for cookie in self.client.cookies.jar})
raise RuntimeError("学习平台没有返回登录会话,现有 Cookie 名称:" + ", ".join(names))
def user_info(self) -> dict:
response = self.client.post(
f"{YXT_API}/v1/customdiy/user/getuserinfobyid",
content=b"",
headers=self.api_headers(),
)
response.raise_for_status()
payload = response.json()
if not isinstance(payload, dict) or "cnName" not in payload:
raise RuntimeError("用户信息返回无法识别")
return payload
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.session_token(),
"User-Agent": USER_AGENT,
}
def study_snapshot(self) -> dict:
"""查询学时、学分和积分汇总,以及今日数据、我的班级数量。"""
headers = self.api_headers()
score_resp = self.client.post(
f"{YXT_API}/v1/customapiforweb/getscoreorpointorhour",
json={},
headers=headers,
)
score_resp.raise_for_status()
score_payload = score_resp.json()
data = score_payload.get("data") or {}
if score_payload.get("code") not in (None, "0", 0):
raise RuntimeError(score_payload.get("message") or "学时学分查询失败")
today_resp = self.client.get(
f"{STUDY_API}/v1/studyapi/studyhour/todayscorehours",
headers=headers,
)
today_resp.raise_for_status()
today = today_resp.json()
class_count = None
class_resp = self.client.get(
f"{CLASS_API}/v1/zte/my/class",
params={"limit": 10, "offset": 0, "lang": 0},
headers=headers,
)
if class_resp.status_code == 200:
paging = ((class_resp.json().get("data") or {}).get("paging") or {})
class_count = paging.get("totalCount")
return {
"actual_study_hour": data.get("actualStudyHour"),
"actual_study_score": data.get("actualStudyScore"),
"points": data.get("totalUserPoint") or data.get("ablePoint"),
"today_hours": today.get("studyHours"),
"today_score": today.get("studyScore"),
"today": today.get("toDate"),
"class_count": class_count,
}
def open_session(self) -> dict:
profile = self.login()
self.authorize(profile)
return {"profile": self.user_info(), "summary": self.study_snapshot()}
+25
View File
@@ -0,0 +1,25 @@
"""用服务端密钥对 e 学密码做可逆加密。"""
from __future__ import annotations
import base64
import hashlib
import os
from cryptography.fernet import Fernet
def _fernet() -> Fernet:
secret = os.environ.get("EUNIV_SECRET_KEY", "")
if not secret:
raise RuntimeError("请设置环境变量 EUNIV_SECRET_KEY")
digest = hashlib.sha256(secret.encode("utf-8")).digest()
return Fernet(base64.urlsafe_b64encode(digest))
def encrypt_secret(value: str) -> str:
return _fernet().encrypt(value.encode("utf-8")).decode("ascii")
def decrypt_secret(value: str) -> str:
return _fernet().decrypt(value.encode("ascii")).decode("utf-8")
+5
View File
@@ -1,3 +1,8 @@
httpx==0.28.1
cryptography==50.0.2
pillow==13.0.0
fastapi==0.162.0
uvicorn==0.54.0
sqlalchemy==2.1.6
alembic==1.20.1
pydantic==2.14.1
+14 -249
View File
@@ -1,254 +1,14 @@
"""登录中兴 e 学并打印当前用户资料。
账号从环境变量 EUNIV_LOGIN、EUNIV_PASSWORD 读取,不写入文件。
"""
"""命令行登录中兴 e 学并打印用户资料与学时汇总。"""
from __future__ import annotations
import base64
import io
import os
import random
import sys
import time
import uuid
from urllib.parse import quote
from pathlib import Path
import httpx
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding
from PIL import Image
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
PORTAL = "https://bmtucportal.zte.com.cn"
EUNIV = "https://euniv.zte.com.cn"
YXT_API = "https://api-qidacustomc1.yunxuetang.cn"
REDIRECT_URI = f"{YXT_API}/v1/ztctech/sso"
CLIENT_ID = "30051"
TENANT_ID = "10001"
APP_ID = "10051"
USER_AGENT = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:158.0) "
"Gecko/20100101 Firefox/158.0"
)
def now_ms() -> int:
return int(time.time() * 1000)
def make_kid(prefix: str = "t") -> str:
return prefix + "".join(random.choice("1234567890") for _ in range(4))
def encrypt_password(public_key_b64: str, password: str) -> str:
key = serialization.load_der_public_key(base64.b64decode(public_key_b64))
cipher = key.encrypt(password.encode("utf-8"), padding.PKCS1v15())
return base64.b64encode(cipher).decode("ascii")
def decode_data_uri(value: str) -> bytes:
payload = value.split(",", 1)[1] if "," in value else value
return base64.b64decode(payload)
def jigsaw_offset(big_png: bytes, small_png: bytes, top: int) -> int:
"""返回滑块左边缘在底图上的横坐标。样本上与抓包提交值一致。"""
big = Image.open(io.BytesIO(big_png)).convert("RGBA")
small = Image.open(io.BytesIO(small_png)).convert("RGBA")
width, height = big.size
piece_w, piece_h = small.size
mask: list[tuple[int, int, tuple[int, int, int]]] = []
for y in range(piece_h):
for x in range(piece_w):
red, green, blue, alpha = small.getpixel((x, y))
if alpha > 128:
mask.append((x, y, (red, green, blue)))
best_x = 0
best_score = None
limit = width - piece_w
for origin in range(max(limit, 0)):
score = 0
for x, y, color in mask:
pixel = big.getpixel((origin + x, top + y))
score += abs(pixel[0] - color[0]) + abs(pixel[1] - color[1]) + abs(pixel[2] - color[2])
if best_score is None or score < best_score:
best_score = score
best_x = origin
if top + piece_h > height:
raise RuntimeError("拼图纵坐标超出底图高度")
return best_x
class EunivLogin:
def __init__(self, login_name: str, password: str) -> None:
self.login_name = login_name.strip()
self.password = password
self.client = httpx.Client(timeout=30, follow_redirects=True, headers={"User-Agent": USER_AGENT})
def close(self) -> None:
self.client.close()
def portal_headers(self) -> dict[str, str]:
referer = (
f"{PORTAL}/uc/{TENANT_ID}/oauthLogin?client_id={CLIENT_ID}"
f"&scope=profile&redirect_uri={quote(REDIRECT_URI, safe='')}"
"&response_type=code"
)
return {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json;charset=UTF-8",
"Origin": PORTAL,
"Referer": referer,
"X-App-Id": APP_ID,
"X-Device-Type": "pc",
"X-Itp-Value": "from=ucs-portal;client=pc;platform=portal",
"X-Lang-Id": "zh_CN",
"X-Tenant-Id": TENANT_ID,
"x_uuid": str(uuid.uuid4()),
}
def code_of(self, payload: dict) -> tuple[str, str, object]:
block = payload.get("code") or {}
return block.get("code") or "", block.get("msg") or "", payload.get("bo")
def login(self) -> dict:
self.client.get(EUNIV + "/")
self.client.post(
f"{PORTAL}/zte-bmt-ucs-portalbff/oauth/validate",
headers=self.portal_headers(),
json={
"clientId": CLIENT_ID,
"redirectUri": REDIRECT_URI,
"responseType": "code",
"scope": "profile",
"_t": now_ms(),
},
)
key_resp = self.client.post(
f"{PORTAL}/zte-bmt-ucs-portalbff/srv/password/publicKey/{TENANT_ID}",
headers=self.portal_headers(),
json={"_t": now_ms()},
)
key_code, key_message, public_key = self.code_of(key_resp.json())
if key_code != "0000" or not isinstance(public_key, str):
raise RuntimeError(f"获取密码公钥失败:{key_message or key_resp.status_code}")
check_resp = self.client.post(
f"{PORTAL}/zte-bmt-ucs-portalbff/srv/pas/securitycode/check",
headers=self.portal_headers(),
json={"accountId": self.login_name, "callerId": APP_ID, "_t": now_ms()},
)
check_code, check_message, needs_security_code = self.code_of(check_resp.json())
if check_code == "0000" and needs_security_code is True:
raise RuntimeError("这个账号开启了动态安全码,当前登录流程还不能提交安全码")
if check_code not in ("", "0000"):
raise RuntimeError(f"安全码检查失败:{check_message}")
cipher = encrypt_password(public_key, self.password)
last_message = "登录未完成"
for _ in range(3):
kid = make_kid("t")
image_resp = self.client.get(
f"{PORTAL}/zte-bmt-ucs-portalbff/srv/kaptcha/jigsaw",
params={"kid": kid, "_t": now_ms()},
headers=self.portal_headers(),
)
image_code, image_message, image = self.code_of(image_resp.json())
if image_code != "0000":
raise RuntimeError(f"获取拼图失败:{image_message}")
offset = jigsaw_offset(
decode_data_uri(image["bigImg"]),
decode_data_uri(image["smallImg"]),
int(image["yHeight"]),
)
headers = self.portal_headers()
headers.update({"kcode": "", "kid": make_kid(""), "kskip": "true", "source": APP_ID})
login_resp = self.client.post(
f"{PORTAL}/zte-bmt-ucs-portalbff/srv/login",
headers=headers,
json={
"loginName": self.login_name,
"password": cipher,
"kid": kid,
"jigsawCode": offset,
"_t": now_ms(),
},
)
login_code, last_message, profile = self.code_of(login_resp.json())
if login_code == "0000":
return profile
if any(word in last_message for word in ("验证码", "拼图", "滑块")):
continue
raise RuntimeError(f"登录失败:{last_message}")
raise RuntimeError(f"登录失败:{last_message}")
def authorize(self, profile: dict) -> None:
account_id = str(profile["accountId"])
user_id = str(profile["userId"])
token = str(profile["token"])
domain = "zte.com.cn"
jar = {
"UCSLoginName": account_id,
"UCSSSOAccount": account_id,
"UCSSSOUser": user_id,
"UCSSSOToken": token,
"UCSSSOInfo": str(profile.get("ssoinfo") or ""),
"UCSSSOLanguage": "zh_CN",
"UCSLoginTime": str(now_ms()),
"iAuthTenantId_prod": TENANT_ID,
"iAuthUserId_prod": user_id,
"iAuthUid_prod": account_id,
"iAuthTid_prod": token,
"iAuthLanguage_prod": "zh_CN",
}
if profile.get("unionId"):
jar["iuacUnionId"] = str(profile["unionId"])
for name, value in jar.items():
self.client.cookies.set(name, value, domain=domain, path="/")
response = self.client.post(
f"{PORTAL}/zte-bmt-ucs-portalbff/oauth/authorize",
params={
"redirect_uri": REDIRECT_URI,
"client_id": CLIENT_ID,
"response_type": "code",
"scope": "profile",
},
headers=self.portal_headers(),
json={"accountId": account_id, "token": token, "userId": user_id, "_t": now_ms()},
)
code, message, redirect_url = self.code_of(response.json())
if code != "0000" or not isinstance(redirect_url, str):
raise RuntimeError(f"申请学习平台授权码失败:{message}")
self.client.get(redirect_url, headers={"Referer": PORTAL + "/", "User-Agent": USER_AGENT})
def user_info(self) -> dict:
token = None
for cookie in self.client.cookies.jar:
if cookie.name == "ELEARNING_00024" and cookie.value:
token = cookie.value
break
if not token:
names = sorted({cookie.name for cookie in self.client.cookies.jar})
raise RuntimeError("学习平台没有返回登录会话,现有 Cookie 名称:" + ", ".join(names))
response = self.client.post(
f"{YXT_API}/v1/customdiy/user/getuserinfobyid",
content=b"",
headers={
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json",
"Origin": EUNIV,
"Referer": EUNIV + "/",
"source": "501",
"token": token,
"User-Agent": USER_AGENT,
},
)
response.raise_for_status()
payload = response.json()
if not isinstance(payload, dict) or "cnName" not in payload:
raise RuntimeError("用户信息返回无法识别")
return payload
from euniv_client import EunivClient
def main() -> int:
@@ -257,23 +17,28 @@ def main() -> int:
if not login_name or not password:
print("请设置环境变量 EUNIV_LOGIN 和 EUNIV_PASSWORD", file=sys.stderr)
return 2
client = EunivLogin(login_name, password)
client = EunivClient(login_name, password)
try:
profile = client.login()
client.authorize(profile)
info = client.user_info()
session = client.open_session()
finally:
client.close()
info = session["profile"]
summary = session["summary"]
fields = [
("工号", info.get("username")),
("姓名", info.get("cnName")),
("部门", info.get("departmentName")),
("岗位层级", info.get("userClassLevelName")),
("邮箱", 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("登录成功")
for label, value in fields:
if value:
if value is not None and value != "":
print(f"{label}:{value}")
return 0
+7
View File
@@ -0,0 +1,7 @@
import os
from pathlib import Path
_root = Path(__file__).resolve().parents[1] / "Temp" / "pytest"
_root.mkdir(parents=True, exist_ok=True)
os.environ["EUNIV_SECRET_KEY"] = "test-secret-key"
os.environ["EUNIV_DB_PATH"] = str(_root / "euniv.db")
+103
View File
@@ -0,0 +1,103 @@
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
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>EunivTools</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+1696
View File
File diff suppressed because it is too large Load Diff
+19
View File
@@ -0,0 +1,19 @@
{
"name": "euniv-web",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vue-tsc --noEmit && vite build"
},
"dependencies": {
"naive-ui": "^2.43.2",
"vue": "^3.5.22"
},
"devDependencies": {
"@vitejs/plugin-vue": "^6.0.1",
"typescript": "^5.9.3",
"vite": "^7.1.12",
"vue-tsc": "^3.1.2"
}
}
+10
View File
@@ -0,0 +1,10 @@
<script setup lang="ts">
import { NMessageProvider } from "naive-ui";
import LoginPage from "./LoginPage.vue";
</script>
<template>
<n-message-provider>
<login-page />
</n-message-provider>
</template>
+165
View File
@@ -0,0 +1,165 @@
<script setup lang="ts">
import { onMounted, ref } from "vue";
import {
NButton,
NCard,
NDataTable,
NForm,
NFormItem,
NInput,
NLayout,
NLayoutContent,
NLayoutHeader,
NSpace,
NSwitch,
NTooltip,
useMessage,
} from "naive-ui";
interface Account {
employee_id: string;
cn_name: string;
department_name: string;
level_name: string;
email: string;
actual_study_hour: string;
actual_study_score: string;
points: string;
today_hours: string;
today_score: string;
today: string;
class_count: string;
last_login_at: string;
}
const message = useMessage();
const loading = ref(false);
const employeeId = ref("");
const password = ref("");
const current = ref<Account | null>(null);
const accounts = ref<Account[]>([]);
const runTime = ref("08:00");
const enabled = ref(true);
const columns = [
{ title: "工号", key: "employee_id" },
{ title: "姓名", key: "cn_name" },
{ title: "部门", key: "department_name" },
{ title: "最近登录", key: "last_login_at" },
];
async function readError(response: Response): Promise<string> {
const payload = await response.json().catch(() => ({}));
return typeof payload.detail === "string" ? payload.detail : "请求失败";
}
async function loadAccounts(): Promise<void> {
const response = await fetch("/api/accounts");
if (response.ok) {
accounts.value = await response.json();
}
}
async function login(): Promise<void> {
loading.value = true;
try {
const response = await fetch("/api/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ employee_id: employeeId.value.trim(), password: password.value }),
});
if (!response.ok) {
message.error(await readError(response));
return;
}
current.value = await response.json();
password.value = "";
message.success("登录成功");
await loadAccounts();
} finally {
loading.value = false;
}
}
async function saveSchedule(): Promise<void> {
if (!current.value) {
return;
}
const response = await fetch("/api/schedules", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
employee_id: current.value.employee_id,
run_time: runTime.value,
enabled: enabled.value,
}),
});
if (!response.ok) {
message.error(await readError(response));
return;
}
message.success("已保存定时同步");
}
onMounted(loadAccounts);
</script>
<template>
<n-layout style="min-height: 100vh">
<n-layout-header bordered style="position: sticky; top: 0; z-index: 2; height: 56px; display: flex; align-items: center; padding: 0 20px; background: #fff">
<n-space align="center" :size="8">
<strong>EunivTools</strong>
<n-tooltip>
<template #trigger>
<span style="cursor: help; color: #6b7280">?</span>
</template>
使用 e 学工号登录。后台记录使用者和学时学分汇总。
</n-tooltip>
</n-space>
</n-layout-header>
<n-layout-content style="padding: 20px; max-width: 920px; margin: 0 auto">
<n-card title="登录">
<n-form label-placement="left" label-width="72">
<n-form-item label="工号">
<n-input v-model:value="employeeId" placeholder="e 学工号" />
</n-form-item>
<n-form-item label="密码">
<n-input v-model:value="password" type="password" show-password-on="click" placeholder="e 学密码" />
</n-form-item>
<n-form-item label=" ">
<n-button type="primary" :loading="loading" @click="login">登录</n-button>
</n-form-item>
</n-form>
</n-card>
<n-card v-if="current" title="用户信息" style="margin-top: 16px">
<p>工号:{{ current.employee_id }}</p>
<p>姓名:{{ current.cn_name }}</p>
<p>部门:{{ current.department_name }}</p>
<p>岗位层级:{{ current.level_name }}</p>
<p>邮箱:{{ current.email }}</p>
<p>累计学时:{{ current.actual_study_hour }}</p>
<p>累计学分:{{ current.actual_study_score }}</p>
<p>积分:{{ current.points }}</p>
<p>今日学时:{{ current.today_hours }}</p>
<p>今日学分:{{ current.today_score }}</p>
<p>我的班级:{{ current.class_count }}</p>
<n-form label-placement="left" label-width="72" style="margin-top: 12px">
<n-form-item label="时间">
<n-input v-model:value="runTime" placeholder="08:00" style="width: 120px" />
</n-form-item>
<n-form-item label="启用">
<n-switch v-model:value="enabled" />
</n-form-item>
<n-form-item label=" ">
<n-button @click="saveSchedule">保存定时同步</n-button>
</n-form-item>
</n-form>
</n-card>
<n-card title="使用者" style="margin-top: 16px">
<n-data-table :columns="columns" :data="accounts" :bordered="false" />
</n-card>
</n-layout-content>
</n-layout>
</template>
+6
View File
@@ -0,0 +1,6 @@
import { createApp } from "vue";
import naive from "naive-ui";
import App from "./App.vue";
import "./styles.css";
createApp(App).use(naive).mount("#app");
+10
View File
@@ -0,0 +1,10 @@
html,
body,
#app {
margin: 0;
height: 100%;
}
body {
background: #f5f7f6;
}
+13
View File
@@ -0,0 +1,13 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"jsx": "preserve",
"noEmit": true,
"skipLibCheck": true,
"lib": ["ES2022", "DOM"]
},
"include": ["src"]
}
+11
View File
@@ -0,0 +1,11 @@
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
export default defineConfig({
plugins: [vue()],
server: {
proxy: {
"/api": "http://127.0.0.1:8000",
},
},
});
+1
View File
@@ -0,0 +1 @@
"""定时同步学习汇总。"""
+74
View File
@@ -0,0 +1,74 @@
"""轮询定时配置,到点登录并刷新学时学分汇总。"""
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()