feat: 自动拼图失败三次后改为手动拖动

This commit is contained in:
2026-10-27 04:28:25 +08:00
parent 858d777588
commit afda5a883f
6 changed files with 446 additions and 62 deletions
+15 -3
View File
@@ -11,7 +11,7 @@ from pydantic import BaseModel, Field
from sqlalchemy.orm import Session
from euniv.db import get_db, init_db
from euniv.service import fetch_home, login_and_store
from euniv.service import fetch_home, login_and_store, submit_jigsaw
@asynccontextmanager
@@ -28,6 +28,11 @@ class LoginBody(BaseModel):
password: str = Field(min_length=1, max_length=128)
class JigsawBody(BaseModel):
attempt_id: str = Field(min_length=8, max_length=64)
offset: int = Field(ge=0, le=2000)
@app.get("/api/health")
def health() -> dict:
return {"ok": True}
@@ -37,10 +42,17 @@ def health() -> dict:
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)
return login_and_store(db, employee_id, body.password)
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@app.post("/api/login/jigsaw")
def login_jigsaw(body: JigsawBody, db: Session = Depends(get_db)) -> dict:
try:
return submit_jigsaw(db, body.attempt_id, body.offset)
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
return {"employee_id": employee_id}
@app.get("/api/home")
+84 -37
View File
@@ -48,6 +48,12 @@ def decode_data_uri(value: str) -> bytes:
return base64.b64decode(payload)
def data_uri(value: str) -> str:
if value.startswith("data:"):
return value
return "data:image/png;base64," + value
def jigsaw_offset(big_png: bytes, small_png: bytes, top: int) -> int:
"""返回滑块左边缘在底图上的横坐标。"""
big = Image.open(io.BytesIO(big_png)).convert("RGBA")
@@ -80,6 +86,17 @@ class SessionExpired(RuntimeError):
"""学习平台凭证失效,需要重新登录。"""
class JigsawRejected(RuntimeError):
"""这次拼图位置不对,可以换一张再试。"""
class ManualJigsaw(Exception):
"""自动拼图已用完,把新拼图交给人来拖。"""
def __init__(self, puzzle: dict) -> None:
self.puzzle = puzzle
class EunivClient:
def __init__(self, login_name: str, password: str) -> None:
self.login_name = login_name.strip()
@@ -87,6 +104,9 @@ class EunivClient:
self.client = httpx.Client(timeout=30, follow_redirects=True, headers={"User-Agent": USER_AGENT})
self._profile: dict = {}
self._yxt_token = ""
self._cipher = ""
self._kid = ""
self._puzzle: dict = {}
def close(self) -> None:
self.client.close()
@@ -147,45 +167,72 @@ class EunivClient:
if check_code not in ("", "0000"):
raise RuntimeError(f"安全码检查失败:{check_message}")
cipher = encrypt_password(public_key, self.password)
last_message = "登录未完成"
self._cipher = encrypt_password(public_key, self.password)
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 ("验证码", "拼图", "滑块")):
big, small, top = self._load_jigsaw()
try:
return self.submit_jigsaw(jigsaw_offset(big, small, top))
except JigsawRejected:
continue
raise RuntimeError(f"登录失败:{last_message}")
raise RuntimeError(f"登录失败:{last_message}")
self._load_jigsaw()
raise ManualJigsaw(self.current_puzzle())
def _load_jigsaw(self) -> tuple[bytes, bytes, int]:
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("拼图返回无法识别")
big = decode_data_uri(image["bigImg"])
small = decode_data_uri(image["smallImg"])
big_size = Image.open(io.BytesIO(big)).size
small_size = Image.open(io.BytesIO(small)).size
top = int(image["yHeight"])
self._kid = kid
self._puzzle = {
"big_img": data_uri(image["bigImg"]),
"small_img": data_uri(image["smallImg"]),
"y": top,
"width": big_size[0],
"height": big_size[1],
"piece_width": small_size[0],
"piece_height": small_size[1],
}
return big, small, top
def next_jigsaw(self) -> dict:
self._load_jigsaw()
return self.current_puzzle()
def current_puzzle(self) -> dict:
return dict(self._puzzle)
def submit_jigsaw(self, offset: int) -> dict:
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": self._cipher,
"kid": self._kid,
"jigsawCode": int(offset),
"_t": now_ms(),
},
)
login_code, message, profile = self.code_of(login_resp.json())
if login_code == "0000" and isinstance(profile, dict):
return profile
if any(word in message for word in ("验证码", "拼图", "滑块")):
raise JigsawRejected(message or "拼图未通过")
raise RuntimeError(f"登录失败:{message}")
def authorize(self, profile: dict) -> None:
account_id = str(profile["accountId"])
+83 -14
View File
@@ -3,35 +3,98 @@
from __future__ import annotations
import json
import secrets
import time
from dataclasses import dataclass
from sqlalchemy.orm import Session
from euniv.client import EunivClient, SessionExpired
from euniv.client import EunivClient, JigsawRejected, ManualJigsaw, SessionExpired
from euniv.crypto import decrypt_secret, encrypt_secret
from euniv.models import Account
_PENDING_SECONDS = 180
_pending: dict[str, "PendingLogin"] = {}
@dataclass
class PendingLogin:
client: EunivClient
employee_id: str
password: str
created: float
def _dump(credential: dict) -> str:
return json.dumps(credential, ensure_ascii=False, sort_keys=True)
def login_and_store(db: Session, employee_id: str, password: str, client_factory=EunivClient) -> Account:
client = client_factory(employee_id, password)
try:
profile = client.login()
client.authorize(profile)
credential = client.export_credential()
finally:
client.close()
def _purge_pending() -> None:
now = time.time()
for attempt_id, pending in list(_pending.items()):
if now - pending.created > _PENDING_SECONDS:
pending.client.close()
_pending.pop(attempt_id, None)
def _drop_employee(employee_id: str) -> None:
for attempt_id, pending in list(_pending.items()):
if pending.employee_id == employee_id:
pending.client.close()
_pending.pop(attempt_id, None)
def _persist(db: Session, employee_id: str, password: str, client: EunivClient, profile: dict) -> None:
client.authorize(profile)
account = db.get(Account, employee_id)
if account is None:
account = Account(employee_id=employee_id, password_cipher="", credential_cipher="")
db.add(account)
account.password_cipher = encrypt_secret(password)
account.credential_cipher = encrypt_secret(_dump(credential))
account.credential_cipher = encrypt_secret(_dump(client.export_credential()))
db.commit()
db.refresh(account)
return account
def login_and_store(db: Session, employee_id: str, password: str, client_factory=EunivClient) -> dict:
_purge_pending()
_drop_employee(employee_id)
client = client_factory(employee_id, password)
held = False
try:
try:
profile = client.login()
except ManualJigsaw as exc:
attempt_id = secrets.token_urlsafe(18)
_pending[attempt_id] = PendingLogin(client, employee_id, password, time.time())
held = True
return {"attempt_id": attempt_id, "jigsaw": exc.puzzle}
_persist(db, employee_id, password, client, profile)
return {"employee_id": employee_id}
finally:
if not held:
client.close()
def submit_jigsaw(db: Session, attempt_id: str, offset: int) -> dict:
_purge_pending()
pending = _pending.get(attempt_id)
if pending is None:
raise RuntimeError("请重新登录")
try:
profile = pending.client.submit_jigsaw(offset)
except JigsawRejected:
pending.created = time.time()
return {"attempt_id": attempt_id, "jigsaw": pending.client.next_jigsaw()}
except Exception:
_pending.pop(attempt_id, None)
pending.client.close()
raise
_pending.pop(attempt_id, None)
try:
_persist(db, pending.employee_id, pending.password, pending.client, profile)
return {"employee_id": pending.employee_id}
finally:
pending.client.close()
def fetch_home(db: Session, employee_id: str, client_factory=EunivClient) -> dict:
@@ -45,11 +108,17 @@ def fetch_home(db: Session, employee_id: str, client_factory=EunivClient) -> dic
if credential.get("yxt_token"):
client.restore(credential)
else:
client.authorize(client.login())
try:
client.authorize(client.login())
except ManualJigsaw:
raise RuntimeError("登录需要重新验证,请重新登录") from None
try:
data = client.home_snapshot()
except SessionExpired:
client.authorize(client.login())
try:
client.authorize(client.login())
except ManualJigsaw:
raise RuntimeError("登录需要重新验证,请重新登录") from None
data = client.home_snapshot()
updated = client.export_credential()
if _dump(updated) != _dump(credential):