250 lines
7.5 KiB
Python
250 lines
7.5 KiB
Python
"""心跳摘要:按播放页 kng_studytrack_rw.js 向本站 GetEncryptRequest 换取。"""
|
|
|
|
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
|
|
|
|
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[^"']*)["']""",
|
|
re.I,
|
|
)
|
|
_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,
|
|
}
|
|
|
|
|
|
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:
|
|
"""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
|
|
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://"):
|
|
if _script_host_allowed(path):
|
|
return path
|
|
path = DEFAULT_ENCRYPT_PATH
|
|
if not path.startswith("/"):
|
|
path = "/" + path
|
|
return origin.rstrip("/") + path
|
|
|
|
|
|
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("//"):
|
|
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:
|
|
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
|
|
|
|
|
|
async def refresh_encrypt_config_async(
|
|
client: httpx.AsyncClient, origin: str, user_agent: str
|
|
) -> None:
|
|
if not _stale():
|
|
return
|
|
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()
|
|
|
|
|
|
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("/") + "/"}
|
|
)
|
|
if resp.status_code == 200 and resp.text:
|
|
_update_from_js(resp.text)
|
|
return
|
|
log.warning("读取播放脚本失败:HTTP %s", resp.status_code)
|
|
except Exception:
|
|
log.warning("读取播放脚本失败", exc_info=True)
|
|
_note_fetch_failure()
|
|
|
|
|
|
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]}")
|
|
|
|
|
|
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)
|
|
|
|
|
|
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)
|