# -*- 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: stream = room.get("stream_url") or {} flv_map = stream.get("flv_pull_url") or {} hls_map = stream.get("hls_pull_url_map") or {} for key in ("ORIGIN", "FULL_HD1", "HD1", "SD1", "SD2"): if key in flv_map and flv_map[key]: return str(flv_map[key]) for key in ("ORIGIN", "FULL_HD1", "HD1", "SD1", "SD2"): if key in hls_map and hls_map[key]: return str(hls_map[key]) if isinstance(flv_map, dict) and flv_map: return str(next(iter(flv_map.values()))) if isinstance(hls_map, dict) and hls_map: return str(next(iter(hls_map.values()))) return str(stream.get("flv_pull_url") or stream.get("hls_pull_url") or "") 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_cover_image(room: dict[str, Any]) -> str: """Prefer live room cover, 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 owner = room.get("owner") or {} if isinstance(owner, dict): for key in ("avatar_medium", "avatar_thumb", "avatar_large"): url = _pick_url_list(owner.get(key)) if url: return url return "" 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) cover_image = _pick_cover_image(room) 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": _pick_stream_url(room) if is_live else "", "cover_image": cover_image, "raw": { "status": status_code, "user_count": room.get("user_count") or room.get("user_count_str") or 0, "has_stream": bool(_pick_stream_url(room)) if is_live else False, "has_cover_image": bool(cover_image), }, } 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'', 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"]\)