douyinWEB/backend/app/douyin.py
eric 11394a2a80 Document Pro relay/time-slot ops and harden relay worker stability.
README covers YouTube RTMPS relay, time-slot mode, ops/Netdata, and global SOCKS plan. Relay pipeline keeps FFmpeg alive across probe flicker, stabilizes time-slot source selection, and fixes misleading start-button copy in the UI.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 10:53:29 -05:00

409 lines
14 KiB
Python

# -*- coding: utf-8 -*-
"""Douyin live status probe — aligned with sh2/d2ypp2 spider (web/enter + a_bogus).
Mass monitoring deliberately avoids HTML page scrape: visiting live.douyin.com/{id}
triggers captcha far more often than webcast/room/web/enter.
"""
from __future__ import annotations
import json
import re
from typing import Any, Optional
from urllib.parse import unquote, urlencode, urlparse
import httpx
from .ab_sign import ab_sign
from .models import extract_room_id, normalize_room_url
# Match sh2 spider UA (a_bogus is tied to this fingerprint)
SH2_UA = (
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/116.0.5845.97 Safari/537.36 Core/1.116.567.400 QQBrowser/19.7.6764.400"
)
BUILTIN_COOKIE = (
"ttwid=1%7C2iDIYVmjzMcpZ20fcaFde0VghXAA3NaNXE_SLR68IyE%7C1761045455"
"%7Cab35197d5cfb21df6cbb2fa7ef1c9262206b062c315b9d04da746d0b37dfbc7d"
)
class RiskControlError(Exception):
pass
def _cookie(cookie: str = "") -> str:
return (cookie or "").strip() or BUILTIN_COOKIE
def _web_headers(cookie: str = "") -> dict[str, str]:
return {
"cookie": _cookie(cookie),
"referer": "https://live.douyin.com/",
"user-agent": SH2_UA,
"accept": "application/json, text/plain, */*",
"accept-language": "zh-CN,zh;q=0.9,en;q=0.8",
}
def _html_headers(cookie: str = "") -> dict[str, str]:
return {
"Cookie": _cookie(cookie),
"Referer": "https://live.douyin.com/",
"User-Agent": SH2_UA,
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
}
def _pick_stream_url(room: dict[str, Any]) -> str:
cands = pick_stream_candidates(room)
return cands[0] if cands else ""
def pick_stream_candidates(room: dict[str, Any], *, prefer: str = "flv") -> list[str]:
"""Build ordered playable URLs — aligned with DouyinLiveRecorder stream.get_douyin_stream_url.
Prefer FLV for Douyin (DLR select_source_url), but keep HLS fallbacks because CDN FLV
lines often 404; quality ladder ORIGIN → FULL_HD1 → HD1 → SD1 → SD2.
"""
stream = room.get("stream_url") or {}
if not isinstance(stream, dict):
return []
flv_map = stream.get("flv_pull_url") or {}
hls_map = stream.get("hls_pull_url_map") or {}
if not isinstance(flv_map, dict):
flv_map = {}
if not isinstance(hls_map, dict):
hls_map = {}
order = ("ORIGIN", "FULL_HD1", "HD1", "SD1", "SD2")
flv_list: list[str] = []
hls_list: list[str] = []
for key in order:
u = str(flv_map.get(key) or "").strip()
if u.startswith("http") and u not in flv_list:
flv_list.append(u)
for key in order:
u = str(hls_map.get(key) or "").strip()
if u.startswith("http") and u not in hls_list:
hls_list.append(u)
for u in list(flv_map.values()) if isinstance(flv_map, dict) else []:
s = str(u or "").strip()
if s.startswith("http") and s not in flv_list:
flv_list.append(s)
for u in list(hls_map.values()) if isinstance(hls_map, dict) else []:
s = str(u or "").strip()
if s.startswith("http") and s not in hls_list:
hls_list.append(s)
single_flv = str(stream.get("flv_pull_url") or "").strip()
if single_flv.startswith("http") and single_flv not in flv_list:
flv_list.append(single_flv)
single_hls = str(stream.get("hls_pull_url") or "").strip()
if single_hls.startswith("http") and single_hls not in hls_list:
hls_list.append(single_hls)
if prefer == "hls":
return hls_list + flv_list
return flv_list + hls_list
def _pick_url_list(node: Any) -> str:
"""Pick first usable URL from Douyin url_list / cover structures."""
if not node:
return ""
if isinstance(node, str):
return node.strip()
if isinstance(node, dict):
urls = node.get("url_list") or node.get("urlList") or []
if isinstance(urls, list):
for u in urls:
s = str(u or "").strip()
if s.startswith("http"):
return s
for key in ("url", "uri", "download_url"):
s = str(node.get(key) or "").strip()
if s.startswith("http"):
return s
if isinstance(node, list):
for item in node:
s = _pick_url_list(item)
if s:
return s
return ""
def _pick_avatar_image(room: dict[str, Any]) -> str:
"""Owner profile avatar (频道/主播头像) — not the live room poster."""
owner = room.get("owner") or {}
if not isinstance(owner, dict):
return ""
for key in ("avatar_large", "avatar_medium", "avatar_thumb"):
url = _pick_url_list(owner.get(key))
if url:
return url
return ""
def _pick_cover_image(room: dict[str, Any]) -> str:
"""Prefer live room cover/poster, then owner avatar — usable even without stream."""
for key in ("cover", "origin_cover", "keyframe_image"):
url = _pick_url_list(room.get(key))
if url:
return url
return _pick_avatar_image(room)
def _normalize_result(room: dict[str, Any], source_url: str) -> dict[str, Any]:
status_code = room.get("status")
is_live = status_code == 2
anchor = (
room.get("anchor_name")
or (room.get("owner") or {}).get("nickname")
or ""
)
title = room.get("title") or ""
room_id = str(room.get("id") or room.get("id_str") or extract_room_id(source_url) or "")
web_rid = extract_room_id(source_url)
avatar_image = _pick_avatar_image(room)
cover_image = _pick_cover_image(room)
candidates = pick_stream_candidates(room) if is_live else []
stream_url = candidates[0] if candidates else ""
return {
"ok": True,
"is_live": bool(is_live),
"status_code": status_code,
"status": "live" if is_live else "offline",
"anchor_name": anchor,
"title": title,
"room_id": web_rid or room_id,
"source_url": normalize_room_url(source_url),
"stream_url": stream_url,
"stream_candidates": candidates,
"cover_image": cover_image,
"avatar_image": avatar_image,
"raw": {
"status": status_code,
"user_count": room.get("user_count") or room.get("user_count_str") or 0,
"has_stream": bool(stream_url),
"has_cover_image": bool(cover_image),
"has_avatar_image": bool(avatar_image),
"stream_candidate_count": len(candidates),
},
}
def _find_room_info(node: Any) -> Optional[dict[str, Any]]:
if isinstance(node, dict):
if "room" in node and isinstance(node["room"], dict) and "status" in node["room"]:
room = dict(node["room"])
owner = room.get("owner") or node.get("anchor") or {}
if isinstance(owner, dict):
room["anchor_name"] = owner.get("nickname") or room.get("anchor_name") or ""
return room
if "roomInfo" in node:
found = _find_room_info(node["roomInfo"])
if found:
return found
for value in node.values():
found = _find_room_info(value)
if found:
return found
elif isinstance(node, list):
for item in node:
found = _find_room_info(item)
if found:
return found
return None
def _parse_html_room(html: str) -> dict[str, Any]:
m = re.search(
r'<script id="RENDER_DATA" type="application/json">(.*?)</script>',
html,
re.DOTALL,
)
if m:
try:
data = json.loads(unquote(m.group(1)))
found = _find_room_info(data)
if found:
return found
except Exception:
pass
match_json_str = re.search(r'(\{\\"state\\":.*?)]\\n"]\)', html)
if not match_json_str:
match_json_str = re.search(r'(\{\\"common\\":.*?)]\\n"]\)</script><div hidden', html)
if not match_json_str:
if '"status":4' in html or '\\"status\\":4' in html:
return {"status": 4, "anchor_name": "", "title": ""}
raise ValueError("未能解析直播页状态")
json_str = match_json_str.group(1)
cleaned = json_str.replace("\\", "").replace(r"u0026", r"&")
room_store_match = re.search(r'"roomStore":(.*?),"linkmicStore"', cleaned, re.DOTALL)
if not room_store_match:
raise ValueError("roomStore 缺失")
room_store = room_store_match.group(1)
anchor_match = re.search(r'"nickname":"(.*?)","avatar_thumb', room_store, re.DOTALL)
anchor_name = anchor_match.group(1) if anchor_match else ""
room_store = room_store.split(',"has_commerce_goods"')[0] + "}}}"
room = json.loads(room_store)["roomInfo"]["room"]
room["anchor_name"] = anchor_name
return room
async def _fetch_web_enter(client: httpx.AsyncClient, web_rid: str, cookie: str = "") -> dict[str, Any]:
"""Primary path: webcast/room/web/enter + a_bogus (sh2 spider.get_douyin_web_stream_data)."""
params = {
"aid": "6383",
"app_name": "douyin_web",
"live_id": "1",
"device_platform": "web",
"language": "zh-CN",
"browser_language": "zh-CN",
"browser_platform": "Win32",
"browser_name": "Chrome",
"browser_version": "116.0.0.0",
"web_rid": web_rid,
"msToken": "",
}
api = f"https://live.douyin.com/webcast/room/web/enter/?{urlencode(params)}"
query = urlparse(api).query
headers = _web_headers(cookie)
api = f"{api}&a_bogus={ab_sign(query, headers['user-agent'])}"
resp = await client.get(api, headers=headers, follow_redirects=True)
text = (resp.text or "").strip()
if not text:
raise RiskControlError("web/enter 空响应(风控)")
if "验证码" in text or "captcha" in text.lower():
raise RiskControlError("web/enter 触发验证码/风控")
try:
payload = resp.json()
except Exception as exc:
raise RiskControlError("web/enter 非 JSON") from exc
# API-level risk / auth failures
status_code = (payload or {}).get("status_code")
if status_code not in (None, 0):
msg = str((payload or {}).get("data") or (payload or {}).get("message") or status_code)
if any(k in msg for k in ("验证", "登录", "forbid", "risk", "captcha")):
raise RiskControlError(f"web/enter status_code={status_code}")
data = (payload or {}).get("data") or {}
rooms = data.get("data") or []
user = data.get("user") or {}
if not rooms:
# sh2: empty data → not usable / treat as offline for status monitor
return {
"status": 4,
"anchor_name": user.get("nickname") or "",
"title": "",
"id_str": web_rid,
}
room = rooms[0]
room["anchor_name"] = user.get("nickname") or room.get("anchor_name") or ""
return room
async def _fetch_html(client: httpx.AsyncClient, url: str, cookie: str = "") -> dict[str, Any]:
resp = await client.get(url, headers=_html_headers(cookie), follow_redirects=True)
text = resp.text or ""
if resp.status_code in (302, 403) or "验证码" in text or "captcha" in text.lower():
raise RiskControlError("页面触发验证码/风控")
if len(text) < 200:
raise RiskControlError("响应过短,疑似风控")
return _parse_html_room(text)
async def check_room(
url_or_id: str,
*,
cookie: str = "",
proxy: Optional[str] = None,
allow_html_fallback: bool = False,
) -> dict[str, Any]:
"""Check live status.
Default = web/enter only (sh2 primary path). HTML fallback is opt-in because
scraping live.douyin.com pages is what usually trips captcha under mass polling.
"""
source_url = normalize_room_url(url_or_id)
web_rid = extract_room_id(source_url)
if not web_rid:
return {"ok": False, "is_live": False, "status": "error", "error": "无效直播间地址"}
timeout = httpx.Timeout(20.0, connect=10.0)
last_err = ""
async with httpx.AsyncClient(
timeout=timeout,
proxy=proxy,
http2=False,
verify=False,
trust_env=False,
) as client:
try:
room = await _fetch_web_enter(client, web_rid, cookie=cookie)
return _normalize_result(room, source_url)
except RiskControlError as exc:
last_err = str(exc)
if not allow_html_fallback:
return {
"ok": False,
"is_live": False,
"status": "error",
"error": last_err,
"risk": True,
"source_url": source_url,
"room_id": web_rid,
"anchor_name": "",
"title": "",
"stream_url": "",
}
except Exception as exc:
last_err = str(exc)
if not allow_html_fallback:
return {
"ok": False,
"is_live": False,
"status": "error",
"error": last_err,
"source_url": source_url,
"room_id": web_rid,
"anchor_name": "",
"title": "",
"stream_url": "",
}
try:
room = await _fetch_html(client, source_url, cookie=cookie)
return _normalize_result(room, source_url)
except RiskControlError as exc:
return {
"ok": False,
"is_live": False,
"status": "error",
"error": f"{last_err}; {exc}".strip("; "),
"risk": True,
"source_url": source_url,
"room_id": web_rid,
"anchor_name": "",
"title": "",
"stream_url": "",
}
except Exception as exc:
last_err = f"{last_err}; {exc}".strip("; ")
return {
"ok": False,
"is_live": False,
"status": "error",
"error": last_err or "检查失败",
"source_url": source_url,
"room_id": web_rid,
"anchor_name": "",
"title": "",
"stream_url": "",
}