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):
+90
View File
@@ -3,6 +3,7 @@ import json
from fastapi.testclient import TestClient
from sqlalchemy import text
from euniv.client import JigsawRejected, ManualJigsaw
from euniv.crypto import decrypt_secret
from euniv.db import SessionLocal, engine, init_db
from euniv.models import Account
@@ -110,3 +111,92 @@ def test_login_stores_password_and_credential_only() -> None:
assert updated["yxt_token"] == "yxt-2"
assert "测试用户" not in decrypt_secret(account.credential_cipher)
assert "测试用户" not in decrypt_secret(account.password_cipher)
def test_manual_jigsaw_keeps_image_pixels_and_retries() -> None:
import euniv.api as api_module
import euniv.service as service_module
service_module._pending.clear()
class ManualClient:
def __init__(self, login_name: str, password: str) -> None:
self.login_name = login_name
self.password = password
self._profile = {
"token": "ucs-1",
"accountId": login_name,
"userId": "u1",
"ssoinfo": "sso",
"unionId": "",
}
def close(self) -> None:
return None
def login(self) -> dict:
raise ManualJigsaw({
"big_img": "data:image/png;base64,YQ==",
"small_img": "data:image/png;base64,Yg==",
"y": 56,
"width": 280,
"height": 172,
"piece_width": 48,
"piece_height": 48,
})
def next_jigsaw(self) -> dict:
return {
"big_img": "data:image/png;base64,Yw==",
"small_img": "data:image/png;base64,ZA==",
"y": 60,
"width": 280,
"height": 172,
"piece_width": 48,
"piece_height": 48,
}
def submit_jigsaw(self, offset: int) -> dict:
if offset != 157:
raise JigsawRejected("拼图未通过")
return dict(self._profile)
def authorize(self, profile: dict) -> None:
self._profile = dict(profile)
def export_credential(self) -> dict:
return {
"ucs_token": "ucs-1",
"ucs_account_id": self.login_name,
"ucs_user_id": "u1",
"ucs_ssoinfo": "sso",
"ucs_union_id": "",
"yxt_token": "yxt-manual",
}
api_module.login_and_store = lambda db, employee_id, password: service_module.login_and_store(
db, employee_id, password, ManualClient
)
api_module.submit_jigsaw = service_module.submit_jigsaw
client = TestClient(api_module.app)
started = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"})
assert started.status_code == 200
body = started.json()
assert body["jigsaw"]["width"] == 280
assert body["jigsaw"]["height"] == 172
assert body["jigsaw"]["y"] == 56
assert "password" not in body["jigsaw"]
with SessionLocal() as db:
assert db.get(Account, "6650000146") is None
missed = client.post("/api/login/jigsaw", json={"attempt_id": body["attempt_id"], "offset": 10})
assert missed.status_code == 200
assert missed.json()["jigsaw"]["y"] == 60
done = client.post("/api/login/jigsaw", json={"attempt_id": body["attempt_id"], "offset": 157})
assert done.status_code == 200
assert done.json() == {"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"