# -*- 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 _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) 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 "", "raw": { "status": status_code, "user_count": room.get("user_count") or room.get("user_count_str") or 0, }, } 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"]\)
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": "", }