From 86a7477fab56a6f8a41f18b138082f41bbd81cce Mon Sep 17 00:00:00 2001 From: Nixevol Date: Mon, 16 Nov 2026 11:48:24 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E6=94=B6=E7=B4=A7=E7=99=BB=E5=BD=95?= =?UTF-8?q?=E8=AF=B7=E6=B1=82=E5=92=8C=E6=92=AD=E6=94=BE=E8=84=9A=E6=9C=AC?= =?UTF-8?q?=E5=9C=B0=E5=9D=80=EF=BC=8C=E5=B9=B6=E5=88=A0=E6=8E=89=E5=90=8C?= =?UTF-8?q?=E6=AD=A5=E5=AD=A6=E4=B9=A0=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/euniv/client.py | 337 +++++++++------------------------------ backend/euniv/encrypt.py | 93 +++++++++-- 2 files changed, 153 insertions(+), 277 deletions(-) diff --git a/backend/euniv/client.py b/backend/euniv/client.py index 668767e..266f1f8 100644 --- a/backend/euniv/client.py +++ b/backend/euniv/client.py @@ -5,7 +5,7 @@ from __future__ import annotations import base64 import hashlib import io -import json +import logging import random import re import secrets @@ -21,13 +21,14 @@ from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import padding from PIL import Image +log = logging.getLogger(__name__) + PORTAL = "https://uac.zte.com.cn" PORTAL_BFF = f"{PORTAL}/zte-sec-uac-iportalbff" PORTAL_PAGE = f"{PORTAL}/zte-sec-uac-iportal/iportal/" 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 = "183681933766" TENANT_ID = "10001" @@ -230,7 +231,7 @@ def training_form(page: str) -> dict[str, str]: continue value = re.search(r"""value=['"]([^'"]*)['"]""", tag) raw = value.group(1) if value else "" - found[name.group(1)] = raw.replace("&", "&").replace("<", "<").replace(">", ">").replace(""", '"') + found[name.group(1)] = unescape(raw) return found @@ -439,10 +440,10 @@ def history_hour_totals(items: list[dict], now: datetime | None = None) -> dict[ def accumulate_month_minutes(fetch_page, year: int, month: int, page_size: int = HISTORY_PAGE_SIZE) -> int: - """倒序分页累加本月分钟,遇到上个月即停。""" + """倒序分页累加本月分钟,遇到上个月即停。重复页直接返回,不再累加。""" offset = 0 total = 0 - first_mark: tuple | None = None + seen: set[tuple] = set() for _ in range(50): rows = fetch_page(offset, page_size) if rows is None: @@ -451,12 +452,6 @@ def accumulate_month_minutes(fetch_page, year: int, month: int, page_size: int = return total if not rows: return total - add, done = fold_month_minutes(rows, year, month) - total += add - if done: - return total - if len(rows) != page_size: - return total mark = ( len(rows), rows[0].get("studied_at"), @@ -464,9 +459,12 @@ def accumulate_month_minutes(fetch_page, year: int, month: int, page_size: int = rows[-1].get("studied_at"), rows[-1].get("title"), ) - if offset == 0: - first_mark = mark - elif mark == first_mark: + if mark in seen: + return total + seen.add(mark) + add, done = fold_month_minutes(rows, year, month) + total += add + if done or len(rows) != page_size: return total offset += page_size return total @@ -485,10 +483,10 @@ def parse_training_cards(page: str, status: str) -> list[dict]: if assigned: assigned_text = assigned.group(1).replace(" ", " ").replace("\xa0", " ").strip() items.append({ - "name": (name.group(1).strip() if name else ""), + "name": unescape(name.group(1)).strip() if name else "", "status": status, "progress": int(progress.group(1)) if progress else 0, - "owner": (owner.group(1).strip() if owner else ""), + "owner": unescape(owner.group(1)).strip() if owner else "", "assigned": assigned_text, "credits": (credits.group(1).strip() if credits else ""), "detail": detail.group(1) if detail else "", @@ -510,7 +508,7 @@ def parse_exam_cards(page: str) -> list[dict]: if not _exam_detail_path(detail): detail = "" items.append({ - "name": (name.group(1).strip() if name else ""), + "name": unescape(name.group(1)).strip() if name else "", "status": status, "result": _exam_result(block, status), "start": start_text, @@ -572,19 +570,19 @@ def parse_training_detail(page: str) -> dict: row, ) tasks.append({ - "name": task_name.group(2).strip() if task_name else "", + "name": unescape(task_name.group(2)).strip() if task_name else "", "progress": percents[-1] if percents else "", "score": f"{score.group(1).strip()}/{score.group(2).strip()}" if score else "", "hours": f"{hours.group(1).strip()}/{hours.group(2).strip()}" if hours else "", }) phases.append({ - "name": phase_name.group(1).strip() if phase_name else "", + "name": unescape(phase_name.group(1)).strip() if phase_name else "", "hours": phase_hours.group(1) if phase_hours else "", "credits": phase_credits.group(1) if phase_credits else "", "tasks": tasks, }) return { - "name": title.group(1).strip() if title else "", + "name": unescape(title.group(1)).strip() if title else "", "owner": _field(head, "lblCertificate"), "earned_hours": _field(head, "Span1"), "actual_hours": _field(head, "lblTotalScore"), @@ -620,8 +618,8 @@ def _field(page: str, element_id: str) -> str: def _plain(value: str) -> str: - text = re.sub(r"<[^>]+>", " ", value) - return re.sub(r"\s+", " ", text).replace("\xa0", " ").replace(" ", " ").strip() + text = unescape(re.sub(r"<[^>]+>", " ", value)) + return re.sub(r"\s+", " ", text.replace("\xa0", " ")).strip() _COURSE_KIND = { @@ -652,9 +650,9 @@ def parse_course_page(page: str) -> dict: comments = re.search(r"", row) courses.append({ "path": link.group(1), - "title": link.group(2).strip(), + "title": unescape(link.group(2)).strip(), "kind": _course_kind(kind.group(1) if kind else "", link.group(1)), - "contributor": contributor.group(1).strip() if contributor else "", + "contributor": unescape(contributor.group(1)).strip() if contributor else "", "recommend": numbers[0].strip() if len(numbers) > 0 else "", "learners": numbers[1].strip() if len(numbers) > 1 else "", "released_on": numbers[2].strip() if len(numbers) > 2 else "", @@ -691,35 +689,44 @@ def _clock_distance(value: str) -> float: match = re.search(r"(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})", value) if not match: return float("inf") - moment = datetime.strptime(match.group(1), "%Y-%m-%d %H:%M:%S") - return abs((moment - datetime.now()).total_seconds()) + from euniv.study_window import CN_TZ + + moment = datetime.strptime(match.group(1), "%Y-%m-%d %H:%M:%S").replace(tzinfo=CN_TZ) + return abs((moment - datetime.now(CN_TZ)).total_seconds()) 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 + limit = width - piece_w + if top < 0 or piece_w < 1 or piece_h < 1 or limit < 0 or top + piece_h > height: + raise JigsawRejected("拼图纵坐标超出底图高度") + big_px = big.load() + small_px = small.load() mask: list[tuple[int, int, tuple[int, int, int]]] = [] for y in range(piece_h): + row = top + y for x in range(piece_w): - red, green, blue, alpha = small.getpixel((x, y)) + red, green, blue, alpha = small_px[x, y] if alpha > 128: - mask.append((x, y, (red, green, blue))) + mask.append((x, row, (red, green, blue))) best_x = 0 - best_score = None - limit = width - piece_w - for origin in range(max(limit, 0)): + best_score: int | None = None + for origin in range(limit + 1): score = 0 - for x, y, color in mask: - pixel = big.getpixel((origin + x, top + y)) + worse = False + for x, row, color in mask: + pixel = big_px[origin + x, row] 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: + if best_score is not None and score >= best_score: + worse = True + break + if not worse and (best_score is None or score < best_score): best_score = score best_x = origin - if top + piece_h > height: - raise RuntimeError("拼图纵坐标超出底图高度") return best_x @@ -742,6 +749,15 @@ class QrWaiting(Exception): """二维码尚未扫过或还在等待确认。""" +def _https_only(request: httpx.Request) -> None: + if request.url.scheme != "https": + raise RuntimeError("只允许 https 请求") + + +def _login_secret_too_long(value: str) -> bool: + return len(value.encode("utf-8")) > 245 + + class EunivClient: def __init__(self, login_name: str, password: str, proxy: str | None = None) -> None: from euniv.proxy import parse_proxy, sync_httpx_client @@ -754,6 +770,7 @@ class EunivClient: timeout=30, follow_redirects=True, headers={"User-Agent": USER_AGENT}, + event_hooks={"request": [_https_only]}, ) self._profile: dict = {} self._yxt_token = "" @@ -784,10 +801,6 @@ class EunivClient: headers["Content-Type"] = "application/json;charset=UTF-8" return headers - def code_of(self, payload: dict) -> tuple[str, str, object]: - top, _inner, data, message = parse_uac(payload) - return top, message, data - def _uac_post(self, path: str, *, app_id: str | None = None, json_body: object = None, extra: dict | None = None) -> httpx.Response: headers = self.portal_headers(app_id) if extra: @@ -826,6 +839,8 @@ class EunivClient: raise RuntimeError(f"登录页校验失败:{message or top}") def login(self, manual: bool = False, auto_attempts: int = 3) -> dict: + if _login_secret_too_long(self.login_name) or _login_secret_too_long(self.password): + raise RuntimeError("账号或密码过长") if is_qr_password(self.password): raise RuntimeError("扫码登录已失效,请重新扫码登录") self._begin_uac() @@ -858,11 +873,12 @@ class EunivClient: "/authentication/qrscan.serv", json_body={"qrCodeKey": parts[1], "qrCodeValue": parts[2]}, ).json() - except (httpx.TransportError, TimeoutError): + except (httpx.TransportError, TimeoutError, ValueError): self._qr_misses = getattr(self, "_qr_misses", 0) + 1 if self._qr_misses >= 5: raise RuntimeError("扫码状态没有获取到") from None raise QrWaiting() from None + self._qr_misses = 0 top, inner, data, message = parse_uac(payload) if top == UAC_OK and inner == UAC_QR_WAIT: raise QrWaiting() @@ -947,7 +963,7 @@ class EunivClient: user_id = str(profile.get("userId") or account_id) token = str(profile.get("token") or "") if not account_id or not token: - raise RuntimeError("登录结果缺少账号或令牌") + raise SessionExpired("登录结果缺少账号或令牌") domain = "zte.com.cn" jar = { "PORTALSSOLanguage": "zh_CN", @@ -1000,8 +1016,8 @@ class EunivClient: ) top, _inner, data, message = parse_uac(response.json()) callback = data.get("callbackUrl") if isinstance(data, dict) else None - if top != UAC_OK or not isinstance(callback, str) or not callback: - raise RuntimeError(f"申请学习平台授权码失败:{message}") + if top != UAC_OK or not isinstance(callback, str) or not callback.startswith(REDIRECT_URI): + raise SessionExpired(f"申请学习平台授权码失败:{message}") self.client.get(callback, headers={"Referer": PORTAL + "/", "User-Agent": USER_AGENT}) self._profile = { "token": token, @@ -1046,7 +1062,8 @@ class EunivClient: if self._yxt_token: return self._yxt_token names = sorted({cookie.name for cookie in self.client.cookies.jar}) - raise RuntimeError("学习平台没有返回登录会话,现有 Cookie 名称:" + ", ".join(names)) + log.warning("学习平台没有返回登录会话,现有 Cookie 名称:%s", ", ".join(names)) + raise RuntimeError("学习平台没有返回登录会话") def _request(self, method: str, url: str, **kwargs) -> httpx.Response: headers = self.api_headers() @@ -1057,16 +1074,17 @@ class EunivClient: 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 + for domain in ("euniv.zte.com.cn", ".yunxuetang.cn"): + self.client.cookies.set("ELEARNING_00024", refreshed, domain=domain, path="/") if response.status_code == 401: raise SessionExpired("学习平台登录已失效") if response.status_code == 403: raise PermissionError("当前课程没有权限") if response.headers.get("content-type", "").startswith("application/json"): - payload = response.json() + try: + payload = response.json() + except (ValueError, UnicodeDecodeError): + payload = None if isinstance(payload, dict) and str(payload.get("code")) in {"401", "403"}: raise SessionExpired("学习平台登录已失效") return response @@ -1094,47 +1112,6 @@ class EunivClient: "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_summary(self) -> dict: """实时读取首页上半部分。调用方不得把结果写入数据库。""" info_resp = self._request("POST", f"{YXT_API}/v1/customdiy/user/getuserinfobyid", content=b"") @@ -1178,13 +1155,6 @@ class EunivClient: def home_trainings(self) -> list[dict]: return _by_closeness(self.online_trainings(), "sort_days") - def home_snapshot(self) -> dict: - """实时读取整页首页。调用方不得把结果写入数据库。""" - data = self.home_summary() - data["trainings"] = self.home_trainings() - data["exams"] = self.home_exams() - return data - def month_hours(self) -> str: return self._period_minutes().get("month", "") @@ -1348,7 +1318,11 @@ class EunivClient: break page += 1 if total is not None and len(found) < total: - raise RuntimeError("课程清单没有取全") + gap = total - len(found) + if total > 0 and gap * 100 <= total: + log.warning("课程清单少了 %s 条,页面共 %s 条,差额不超过 1%%", gap, total) + else: + raise RuntimeError("课程清单没有取全") return list(found.values()) def exam_detail(self, path: str) -> dict: @@ -1400,166 +1374,3 @@ class EunivClient: items.extend(fresh) seen.update((item.get("name", ""), item.get(identity, "")) for item in fresh) return items - - def open_session(self) -> dict: - profile = self.login() - self.authorize(profile) - return {"profile": self.user_info(), "summary": self.study_snapshot()} - - # ── 自动学习所需方法 ── - - def course_page_params(self, path: str) -> dict: - """打开播放页,解析 JS 变量。返回 knowledgeType, submitProTimes, validtimeSpan, standardStudyHours, pageSize 等。""" - html = self._site_page(path) - from euniv.encrypt import note_play_html - note_play_html(html, EUNIV) - return play_page_params(html) - - def update_progress(self, knowledge_id: str, package_id: str = "", - master_id: str = "", master_type: str = "") -> dict: - """POST /v1/study/updateprogress。返回 studyschedule, actualstudyhours, standardstudyhours, viewSchedule, status。""" - body = { - "knowledgeId": as_uuid(knowledge_id), - "packageId": as_uuid(package_id) if package_id else "", - "masterId": master_id, - "masterType": master_type, - } - resp = self._request("POST", f"{STUDY_API}/v1/study/updateprogress", json=body) - return resp.json() - - def sync_package(self, knowledge_id: str) -> dict: - """GET /v1/uk/syncpackage。返回整包和各章信息。""" - resp = self._request("GET", f"{STUDY_API}/v1/uk/syncpackage", - params={"knowledgeId": as_uuid(knowledge_id), "sourceType": "SingleStudy", "masterId": ""}) - return resp.json() - - def get_encrypt_request(self, body_json: str) -> str: - from euniv.encrypt import fetch_encryption - self._ensure_site() - return fetch_encryption(self.client, body_json, origin=EUNIV, user_agent=USER_AGENT) - - def submit_video_heartbeat(self, knowledge_id: str, package_id: str, - study_time: int, view_schedule: int, - master_id: str = "", master_type: str = "") -> dict: - """视频心跳 POST /v1/study/submitpro。""" - del master_id, master_type - param = study_progress_fields( - knowledge_id, package_id, page_size=1, study_time=study_time, - kind=0, view_schedule=view_schedule, - ) - encryption = self.get_encrypt_request(json.dumps(param, separators=(",", ":"))) - param["encryption"] = encryption - param["multiple"] = 1 - param["realHour"] = study_time - resp = self._request("POST", f"{STUDY_API}/v1/study/submitpro", - content=json.dumps(param, separators=(",", ":"))) - text = resp.text.strip() - if not text: - return {} - return resp.json() - - def submit_document_heartbeat(self, knowledge_id: str, package_id: str, - page_size: int, study_time: int, - view_schedule: int, - master_id: str = "", master_type: str = "") -> dict: - """文档心跳 POST /v1/study/submit。""" - del master_id, master_type - param = study_progress_fields( - knowledge_id, package_id, page_size=page_size, study_time=study_time, - kind=1, view_schedule=view_schedule, - ) - encryption = self.get_encrypt_request(json.dumps(param, separators=(",", ":"))) - param["multiple"] = 1 - param["realHour"] = study_time - resp = self._request("POST", f"{STUDY_API}/v1/study/submit?encryption={encryption}", - content=json.dumps(param, separators=(",", ":"))) - return {} - - def submit_scorm_heartbeat(self, knowledge_id: str, package_id: str, - study_time: int, sco_id: str = "", - end: bool = False, - master_id: str = "", master_type: str = "") -> dict: - """Scorm 心跳 POST /v1/study/submit,type=2。""" - del master_id, master_type - encrypt_param = study_progress_fields( - knowledge_id, package_id, page_size=-1 if end else 1, study_time=study_time, - kind=2, view_schedule=0, end=end, chapter_id=sco_id, for_encrypt=True, - ) - encryption = self.get_encrypt_request(json.dumps(encrypt_param, separators=(",", ":"))) - param = study_progress_fields( - knowledge_id, package_id, page_size=-1 if end else 1, study_time=study_time, - kind=2, view_schedule=0, end=end, chapter_id=sco_id, - ) - resp = self._request("POST", f"{STUDY_API}/v1/study/submit?encryption={encryption}", - content=json.dumps(param, separators=(",", ":"))) - return {} - - def scorm_count(self, knowledge_id: str) -> int: - """GET /v1/kng/scorm/count/。""" - resp = self._request("GET", f"{STUDY_API}/v1/kng/scorm/count/", - params={"knowledgeId": as_uuid(knowledge_id)}) - data = resp.json() - return int(data.get("scocnt") or 1) - - def scorm_get(self, user_id: str, sco_id: str) -> dict: - """GET /v1/scormstudy/{userId}/{scoId}。""" - resp = self._request("GET", f"https://api-mall.yxt.com/v1/scormstudy/{user_id}/{sco_id}") - text = resp.text.strip() - if not text: - return {} - return resp.json() - - def scorm_save(self, session_id: str, org_id: str, user_id: str, - scorm_id: str, scorm_id_ori: str, sco_cnt: int, - package_id: str, master_id: str, master_type: str, - data: dict) -> None: - """POST /v1/scormstudy。""" - body = { - "sessionId": session_id, - "orgId": org_id, - "userId": user_id, - "scormId": as_uuid(scorm_id), - "scormIdOri": as_uuid(scorm_id_ori), - "masterId": master_id, - "masterType": master_type, - "packageId": as_uuid(package_id) if package_id else "", - "scocnt": sco_cnt, - "data": data, - } - self._request("POST", "https://api-mall.yxt.com/v1/scormstudy", - json=body) - - def scorm_page_files(self, knowledge_id: str) -> list[str]: - """下载 Scorm 课件的页索引,返回各页 .oss.js 的 URL 列表。""" - compact = compact_id(knowledge_id) - index_url = f"https://cdn-cos-file.yunxuetang.cn/zt/scorm/{compact}/h5/js/index-scorm.js" - resp = self.client.get(index_url, headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"}) - urls = [] - for m in re.finditer(r'["\']([^"\']+\.oss\.js)["\']', resp.text): - raw = m.group(1) - if raw.startswith("http"): - urls.append(raw) - elif raw.startswith("//"): - urls.append("https:" + raw) - elif raw.startswith("/"): - urls.append(f"https://cdn-cos-file.yunxuetang.cn{raw}") - else: - urls.append(f"https://cdn-cos-file.yunxuetang.cn/zt/scorm/{compact}/h5/js/{raw}") - return urls - - def scorm_extract_answers(self, knowledge_id: str) -> list[dict]: - """下载 .oss.js 页,提取题目和正确答案。""" - urls = self.scorm_page_files(knowledge_id) - answers = [] - for url in urls: - try: - resp = self.client.get(url, headers={"User-Agent": USER_AGENT}) - text = resp.text - for block in re.finditer(r'单选题([\s\S]*?)正确答案[::]\s*([A-D])', text): - answers.append({"page_url": url, "answer": block.group(2)}) - except Exception: - continue - return answers - - def user_id(self) -> str: - return str(self._profile.get("userId") or "") diff --git a/backend/euniv/encrypt.py b/backend/euniv/encrypt.py index 6744967..d51d6db 100644 --- a/backend/euniv/encrypt.py +++ b/backend/euniv/encrypt.py @@ -2,12 +2,14 @@ from __future__ import annotations +import asyncio import json import logging import re import threading import time from typing import Any +from urllib.parse import urlparse import httpx @@ -16,6 +18,11 @@ log = logging.getLogger(__name__) DEFAULT_ENCRYPT_PATH = "/kng/services/KngComService.svc/GetEncryptRequest" DEFAULT_JS_URL = "https://staticbdc1.yunxuetang.cn/SystemFiles/Js/kng_studytrack_rw.js" _TTL = 6 * 3600 +_FAIL_COOLDOWN = 5 * 60 +_SCRIPT_HOSTS = frozenset({ + "euniv.zte.com.cn", + "staticbdc1.yunxuetang.cn", +}) _SCRIPT_RE = re.compile( r"""(?:src|href)\s*=\s*["']([^"']*kng_studytrack_rw\.js[^"']*)["']""", @@ -24,10 +31,12 @@ _SCRIPT_RE = re.compile( _PATH_RE = re.compile(r"""url\s*:\s*["']([^"']*GetEncryptRequest)["']""") _lock = threading.Lock() +_fetch_guard = threading.Lock() _config: dict[str, Any] = { "path": DEFAULT_ENCRYPT_PATH, "js_url": DEFAULT_JS_URL, "loaded_at": 0.0, + "retry_at": 0.0, } @@ -36,6 +45,15 @@ def reset_encrypt_config() -> None: _config["path"] = DEFAULT_ENCRYPT_PATH _config["js_url"] = DEFAULT_JS_URL _config["loaded_at"] = 0.0 + _config["retry_at"] = 0.0 + + +def _script_host_allowed(url: str) -> bool: + parsed = urlparse(url) + if parsed.scheme != "https" or parsed.username or parsed.password: + return False + host = (parsed.hostname or "").rstrip(".").lower() + return host in _SCRIPT_HOSTS def encrypt_payload(body_json: str) -> bytes: @@ -76,17 +94,25 @@ def note_play_html(html: str, origin: str = "") -> None: url = origin.rstrip("/") + url if not url: return + if not _script_host_allowed(url): + log.warning("播放脚本地址不在允许的主机上") + return with _lock: if _config["js_url"] != url: _config["js_url"] = url _config["loaded_at"] = 0.0 + _config["retry_at"] = 0.0 def encrypt_url(origin: str) -> str: with _lock: path = str(_config["path"] or DEFAULT_ENCRYPT_PATH) + if path.startswith("//"): + path = "https:" + path if path.startswith("http://") or path.startswith("https://"): - return path + if _script_host_allowed(path): + return path + path = DEFAULT_ENCRYPT_PATH if not path.startswith("/"): path = "/" + path return origin.rstrip("/") + path @@ -94,31 +120,52 @@ def encrypt_url(origin: str) -> str: def _update_from_js(js: str) -> None: path = encrypt_path_from_js(js) + if path.startswith("//"): + path = "https:" + path + if path.startswith("http://") or path.startswith("https://"): + if not _script_host_allowed(path): + log.warning("播放脚本里的接口地址不在允许的主机上") + path = "" with _lock: if path: _config["path"] = path _config["loaded_at"] = time.time() + _config["retry_at"] = 0.0 def _js_url(origin: str) -> str: with _lock: url = str(_config["js_url"] or DEFAULT_JS_URL) if url.startswith("//"): - return "https:" + url - if url.startswith("/") and origin: - return origin.rstrip("/") + url - return url + url = "https:" + url + elif url.startswith("/") and origin: + url = origin.rstrip("/") + url + if _script_host_allowed(url): + return url + return DEFAULT_JS_URL def _stale() -> bool: + now = time.time() with _lock: - return time.time() - float(_config["loaded_at"] or 0) >= _TTL + retry_at = float(_config.get("retry_at") or 0) + if retry_at and now < retry_at: + return False + return now - float(_config["loaded_at"] or 0) >= _TTL + + +def _note_fetch_failure() -> None: + with _lock: + _config["retry_at"] = time.time() + _FAIL_COOLDOWN def refresh_encrypt_config(client: httpx.Client, origin: str, user_agent: str) -> None: if not _stale(): return - _fetch_js_config(client.get, origin, user_agent) + with _fetch_guard: + if not _stale(): + return + _fetch_js_config(client.get, origin, user_agent) async def refresh_encrypt_config_async( @@ -126,26 +173,44 @@ async def refresh_encrypt_config_async( ) -> None: if not _stale(): return - await _fetch_js_config_async(client, origin, user_agent) + while True: + if not _stale(): + return + if _fetch_guard.acquire(blocking=False): + break + await asyncio.sleep(0.02) + try: + if _stale(): + await _fetch_js_config_async(client, origin, user_agent) + finally: + _fetch_guard.release() def _fetch_js_config(get, origin: str, user_agent: str) -> None: url = _js_url(origin) + if not _script_host_allowed(url): + log.warning("播放脚本地址不在允许的主机上") + _note_fetch_failure() + return try: resp = get(url, headers={"User-Agent": user_agent, "Referer": origin.rstrip("/") + "/"}) if resp.status_code == 200 and resp.text: _update_from_js(resp.text) return + log.warning("读取播放脚本失败:HTTP %s", getattr(resp, "status_code", "")) except Exception: - log.debug("读取播放脚本失败", exc_info=True) - with _lock: - _config["loaded_at"] = time.time() + log.warning("读取播放脚本失败", exc_info=True) + _note_fetch_failure() async def _fetch_js_config_async( client: httpx.AsyncClient, origin: str, user_agent: str ) -> None: url = _js_url(origin) + if not _script_host_allowed(url): + log.warning("播放脚本地址不在允许的主机上") + _note_fetch_failure() + return try: resp = await client.get( url, headers={"User-Agent": user_agent, "Referer": origin.rstrip("/") + "/"} @@ -153,10 +218,10 @@ async def _fetch_js_config_async( if resp.status_code == 200 and resp.text: _update_from_js(resp.text) return + log.warning("读取播放脚本失败:HTTP %s", resp.status_code) except Exception: - log.debug("读取播放脚本失败", exc_info=True) - with _lock: - _config["loaded_at"] = time.time() + log.warning("读取播放脚本失败", exc_info=True) + _note_fetch_failure() def _as_encrypt_object(data: Any, depth: int = 0) -> Any: