fix: 心跳摘要改为在线 GetEncryptRequest 不再写死密钥
This commit is contained in:
@@ -0,0 +1,232 @@
|
||||
"""心跳摘要:按播放页 kng_studytrack_rw.js 向本站 GetEncryptRequest 换取。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
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
|
||||
|
||||
_SCRIPT_RE = re.compile(
|
||||
r"""(?:src|href)\s*=\s*["']([^"']*kng_studytrack_rw\.js[^"']*)["']""",
|
||||
re.I,
|
||||
)
|
||||
_PATH_RE = re.compile(r"""url\s*:\s*["']([^"']*GetEncryptRequest)["']""")
|
||||
|
||||
_lock = threading.Lock()
|
||||
_config: dict[str, Any] = {
|
||||
"path": DEFAULT_ENCRYPT_PATH,
|
||||
"js_url": DEFAULT_JS_URL,
|
||||
"loaded_at": 0.0,
|
||||
}
|
||||
|
||||
|
||||
def reset_encrypt_config() -> None:
|
||||
with _lock:
|
||||
_config["path"] = DEFAULT_ENCRYPT_PATH
|
||||
_config["js_url"] = DEFAULT_JS_URL
|
||||
_config["loaded_at"] = 0.0
|
||||
|
||||
|
||||
def encrypt_payload(body_json: str) -> bytes:
|
||||
"""WCF GetEncryptRequest 的 body 是进度 JSON 字符串,不是嵌套对象。
|
||||
|
||||
播放脚本先 JSON.stringify 再拼进 {"body":...};若入参已是字符串,线上实际发出
|
||||
{"body":"<进度 JSON>"}。直接发送嵌套对象会 HTTP 400。
|
||||
"""
|
||||
return json.dumps({"body": body_json}, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
||||
|
||||
|
||||
def encrypt_headers(origin: str, user_agent: str) -> dict[str, str]:
|
||||
return {
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"Content-Type": "text/json",
|
||||
"Origin": origin,
|
||||
"Referer": origin.rstrip("/") + "/",
|
||||
"User-Agent": user_agent,
|
||||
}
|
||||
|
||||
|
||||
def encrypt_path_from_js(js: str) -> str:
|
||||
match = _PATH_RE.search(js or "")
|
||||
return match.group(1) if match else ""
|
||||
|
||||
|
||||
def note_play_html(html: str, origin: str = "") -> None:
|
||||
"""从播放页记下当前 kng_studytrack_rw.js 地址,版本变化时重新读接口路径。"""
|
||||
if not html:
|
||||
return
|
||||
match = _SCRIPT_RE.search(html)
|
||||
if not match:
|
||||
return
|
||||
url = match.group(1).strip()
|
||||
if url.startswith("//"):
|
||||
url = "https:" + url
|
||||
elif url.startswith("/") and origin:
|
||||
url = origin.rstrip("/") + url
|
||||
if not url:
|
||||
return
|
||||
with _lock:
|
||||
if _config["js_url"] != url:
|
||||
_config["js_url"] = url
|
||||
_config["loaded_at"] = 0.0
|
||||
|
||||
|
||||
def encrypt_url(origin: str) -> str:
|
||||
with _lock:
|
||||
path = str(_config["path"] or DEFAULT_ENCRYPT_PATH)
|
||||
if path.startswith("http://") or path.startswith("https://"):
|
||||
return path
|
||||
if not path.startswith("/"):
|
||||
path = "/" + path
|
||||
return origin.rstrip("/") + path
|
||||
|
||||
|
||||
def _update_from_js(js: str) -> None:
|
||||
path = encrypt_path_from_js(js)
|
||||
with _lock:
|
||||
if path:
|
||||
_config["path"] = path
|
||||
_config["loaded_at"] = time.time()
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def _stale() -> bool:
|
||||
with _lock:
|
||||
return time.time() - float(_config["loaded_at"] or 0) >= _TTL
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
async def refresh_encrypt_config_async(
|
||||
client: httpx.AsyncClient, origin: str, user_agent: str
|
||||
) -> None:
|
||||
if not _stale():
|
||||
return
|
||||
await _fetch_js_config_async(client, origin, user_agent)
|
||||
|
||||
|
||||
def _fetch_js_config(get, origin: str, user_agent: str) -> None:
|
||||
url = _js_url(origin)
|
||||
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
|
||||
except Exception:
|
||||
log.debug("读取播放脚本失败", exc_info=True)
|
||||
with _lock:
|
||||
_config["loaded_at"] = time.time()
|
||||
|
||||
|
||||
async def _fetch_js_config_async(
|
||||
client: httpx.AsyncClient, origin: str, user_agent: str
|
||||
) -> None:
|
||||
url = _js_url(origin)
|
||||
try:
|
||||
resp = await client.get(
|
||||
url, headers={"User-Agent": user_agent, "Referer": origin.rstrip("/") + "/"}
|
||||
)
|
||||
if resp.status_code == 200 and resp.text:
|
||||
_update_from_js(resp.text)
|
||||
return
|
||||
except Exception:
|
||||
log.debug("读取播放脚本失败", exc_info=True)
|
||||
with _lock:
|
||||
_config["loaded_at"] = time.time()
|
||||
|
||||
|
||||
def _as_encrypt_object(data: Any, depth: int = 0) -> Any:
|
||||
if depth > 4:
|
||||
return data
|
||||
if isinstance(data, dict):
|
||||
if any(key in data for key in ("Status", "status", "Data", "data")):
|
||||
return data
|
||||
for key in ("d", "GetEncryptRequestResult", "body"):
|
||||
if key in data:
|
||||
return _as_encrypt_object(data[key], depth + 1)
|
||||
return data
|
||||
if isinstance(data, str):
|
||||
text = data.strip()
|
||||
if not text:
|
||||
return data
|
||||
try:
|
||||
return _as_encrypt_object(json.loads(text), depth + 1)
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
if "'" in text:
|
||||
try:
|
||||
return _as_encrypt_object(json.loads(text.replace("'", '"')), depth + 1)
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
return data
|
||||
|
||||
|
||||
def parse_encrypt_response(resp: httpx.Response) -> str:
|
||||
raw = (resp.text or "").strip()
|
||||
if resp.status_code >= 400:
|
||||
raise RuntimeError(f"GetEncryptRequest HTTP {resp.status_code}: {raw[:200]}")
|
||||
try:
|
||||
data: Any = resp.json()
|
||||
except Exception:
|
||||
data = raw
|
||||
obj = _as_encrypt_object(data)
|
||||
if isinstance(obj, dict):
|
||||
status = str(obj.get("Status") or obj.get("status") or "")
|
||||
digest = obj.get("Data") if obj.get("Data") not in (None, "") else obj.get("data")
|
||||
if status == "OK" and digest:
|
||||
return str(digest).strip()
|
||||
raise RuntimeError(f"GetEncryptRequest 失败: {raw[:200]}")
|
||||
|
||||
|
||||
def fetch_encryption(
|
||||
client: httpx.Client, body_json: str, *, origin: str, user_agent: str
|
||||
) -> str:
|
||||
refresh_encrypt_config(client, origin, user_agent)
|
||||
return _post_encryption(client.post, body_json, origin, user_agent)
|
||||
|
||||
|
||||
async def fetch_encryption_async(
|
||||
client: httpx.AsyncClient, body_json: str, *, origin: str, user_agent: str
|
||||
) -> str:
|
||||
await refresh_encrypt_config_async(client, origin, user_agent)
|
||||
return await _post_encryption_async(client, body_json, origin, user_agent)
|
||||
|
||||
|
||||
def _post_encryption(post, body_json: str, origin: str, user_agent: str) -> str:
|
||||
url = encrypt_url(origin)
|
||||
headers = encrypt_headers(origin, user_agent)
|
||||
resp = post(url, content=encrypt_payload(body_json), headers=headers)
|
||||
return parse_encrypt_response(resp)
|
||||
|
||||
|
||||
async def _post_encryption_async(
|
||||
client: httpx.AsyncClient, body_json: str, origin: str, user_agent: str
|
||||
) -> str:
|
||||
url = encrypt_url(origin)
|
||||
headers = encrypt_headers(origin, user_agent)
|
||||
resp = await client.post(url, content=encrypt_payload(body_json), headers=headers)
|
||||
return parse_encrypt_response(resp)
|
||||
Reference in New Issue
Block a user