refactor: 本地只保存工号和加密密码,并整理后端目录
This commit is contained in:
@@ -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()}
|
||||
Reference in New Issue
Block a user