"""登录中兴 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 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") 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 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() self.password = password 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() 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}") self._cipher = encrypt_password(public_key, self.password) for _ in range(3): big, small, top = self._load_jigsaw() try: return self.submit_jigsaw(jigsaw_offset(big, small, top)) except JigsawRejected: continue 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"]) 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}) self._profile = { "token": str(profile.get("token") or ""), "accountId": account_id, "userId": user_id, "ssoinfo": str(profile.get("ssoinfo") or ""), "unionId": str(profile.get("unionId") or ""), } self._yxt_token = "" self.session_token() def export_credential(self) -> dict: profile = self._profile return { "ucs_token": str(profile.get("token") or ""), "ucs_account_id": str(profile.get("accountId") or ""), "ucs_user_id": str(profile.get("userId") or ""), "ucs_ssoinfo": str(profile.get("ssoinfo") or ""), "ucs_union_id": str(profile.get("unionId") or ""), "yxt_token": self.session_token(), } def restore(self, credential: dict) -> None: self._profile = { "token": str(credential.get("ucs_token") or ""), "accountId": str(credential.get("ucs_account_id") or ""), "userId": str(credential.get("ucs_user_id") or ""), "ssoinfo": str(credential.get("ucs_ssoinfo") or ""), "unionId": str(credential.get("ucs_union_id") or ""), } token = str(credential.get("yxt_token") or "") self._yxt_token = token if token: self.client.cookies.set("ELEARNING_00024", token, domain="euniv.zte.com.cn", path="/") self.client.cookies.set("ELEARNING_00024", token, domain=".yunxuetang.cn", path="/") def session_token(self) -> str: for cookie in self.client.cookies.jar: if cookie.name == "ELEARNING_00024" and cookie.value: self._yxt_token = cookie.value return cookie.value if self._yxt_token: return self._yxt_token names = sorted({cookie.name for cookie in self.client.cookies.jar}) raise RuntimeError("学习平台没有返回登录会话,现有 Cookie 名称:" + ", ".join(names)) def _request(self, method: str, url: str, **kwargs) -> httpx.Response: headers = self.api_headers() extra = kwargs.pop("headers", None) if extra: headers.update(extra) response = self.client.request(method, url, headers=headers, **kwargs) refreshed = response.headers.get("token") or response.headers.get("Token") if refreshed: self._yxt_token = refreshed self.client.cookies.set("ELEARNING_00024", refreshed, domain="euniv.zte.com.cn", path="/") for cookie in self.client.cookies.jar: if cookie.name == "ELEARNING_00024" and cookie.value: self._yxt_token = cookie.value if response.status_code in (401, 403): raise SessionExpired("学习平台登录已失效") if response.headers.get("content-type", "").startswith("application/json"): payload = response.json() if isinstance(payload, dict) and str(payload.get("code")) in {"401", "403"}: raise SessionExpired("学习平台登录已失效") return response 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 home_snapshot(self) -> dict: """实时读取首页要展示的个人信息,调用方不得把结果写入数据库。""" info_resp = self._request("POST", f"{YXT_API}/v1/customdiy/user/getuserinfobyid", content=b"") info = info_resp.json() if not isinstance(info, dict) or "cnName" not in info: raise RuntimeError("用户信息返回无法识别") period_resp = self._request("GET", f"{STUDY_API}/v1/frw/user/info") period = period_resp.json() if not isinstance(period, dict) or "yearScores" not in period: raise RuntimeError("本年和本月学分返回无法识别") score_resp = self._request("POST", f"{YXT_API}/v1/customapiforweb/getscoreorpointorhour", json={}) score_payload = score_resp.json() score = 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._request("GET", f"{STUDY_API}/v1/studyapi/studyhour/todayscorehours") today = today_resp.json() exam_resp = self._request("POST", f"{YXT_API}/v1/user/getmyexamcountnew", content=b"") exam_payload = exam_resp.json() exam = exam_payload.get("data") or {} pending_count = int(exam.get("preExamCount") or 0) return { "name": info.get("cnName") or "", "avatar": info.get("headPictureUrl") or "", "department": info.get("departmentName") or "", "level": period.get("levelName") or info.get("userClassLevelName") or "", "year_score": period.get("yearScores") or "0.00", "month_score": period.get("monthScores") or "0.00", "total_hours": score.get("actualStudyHour") or "", "total_score": score.get("actualStudyScore") or period.get("totalScores") or "", "today_hours": today.get("studyHours"), "today_score": today.get("studyScore"), "pending_exam_count": pending_count, "pending_exams": self._pending_exams(pending_count), } def _pending_exams(self, count: int) -> list[dict]: if count <= 0: return [] response = self._request( "GET", f"{EUNIV}/exam/userallexam.htm", headers={"Accept": "text/html,application/xhtml+xml"}, ) names = [] for match in response.text.split("lblExamName"): if ">" not in match: continue text = match.split(">", 1)[1].split("<", 1)[0].strip() if text: names.append(text) return [{"name": name, "deadline": ""} for name in names] def open_session(self) -> dict: profile = self.login() self.authorize(profile) return {"profile": self.user_info(), "summary": self.study_snapshot()}