This commit is contained in:
Your Name
2026-07-17 09:24:47 +08:00
commit 530e7f839d
4353 changed files with 731879 additions and 0 deletions
+959
View File
@@ -0,0 +1,959 @@
"""从 Cookie 抓取抖音账号资料(昵称 / 头像 / UID)及作品列表。"""
from __future__ import annotations
import asyncio
import json
import logging
from datetime import datetime
from typing import Any, Optional
import requests
from sqlalchemy import delete, select
from sqlalchemy.ext.asyncio import AsyncSession
from models.models import Account, AccountProfileDetail, AccountVideo
from rpa_engine.douyin_im.auth import DouyinAuth
from rpa_engine.douyin_im.dy_util import (
DEFAULT_USER_AGENT,
generate_a_bogus,
generate_msToken,
generate_webid,
splice_url,
)
from rpa_engine.douyin_im.protocol import _pick_avatar_url
from rpa_engine.douyin_im.session import DouyinImSession
from rpa_engine.device_profiles import resolve_user_agent
logger = logging.getLogger("account_profile")
def _pick_str(data: dict, *keys: str) -> str:
for key in keys:
value = data.get(key)
if value is not None and str(value).strip():
return str(value).strip()
return ""
def _pick_int(data: dict, *keys: str) -> Optional[int]:
for key in keys:
value = data.get(key)
if value is None or value == "":
continue
try:
return int(value)
except (TypeError, ValueError):
continue
return None
def _iter_profile_nodes(data: Any):
if not isinstance(data, dict):
return
yield data
for key in ("user", "user_info", "data", "creator"):
node = data.get(key)
if isinstance(node, dict):
yield node
def _extract_profile_from_payload(data: Any) -> dict[str, str]:
for node in _iter_profile_nodes(data):
uid = _pick_str(node, "uid", "user_uid", "user_id", "creator_user_id", "id")
nickname = _pick_str(
node,
"nickname",
"nick_name",
"unique_id",
"display_name",
"name",
)
avatar = _pick_avatar_url(node)
if uid or nickname or avatar:
return {
"uid": uid,
"nickname": nickname,
"avatar_url": avatar,
}
return {}
def _extract_detail_from_payload(data: Any) -> dict[str, Any]:
"""从抖音资料接口响应中提取详细统计。"""
detail: dict[str, Any] = {}
for node in _iter_profile_nodes(data):
if not detail.get("uid"):
uid = _pick_str(node, "uid", "user_uid", "user_id", "creator_user_id", "id")
if uid:
detail["uid"] = uid
if not detail.get("nickname"):
nickname = _pick_str(
node, "nickname", "nick_name", "display_name", "name"
)
if nickname:
detail["nickname"] = nickname
if not detail.get("avatar_url"):
avatar = _pick_avatar_url(node)
if avatar:
detail["avatar_url"] = avatar
if not detail.get("unique_id"):
unique_id = _pick_str(node, "unique_id", "short_id", "douyin_id")
if unique_id:
detail["unique_id"] = unique_id
if not detail.get("sec_user_id"):
sec_user_id = _pick_str(node, "sec_uid", "sec_user_id")
if sec_user_id:
detail["sec_user_id"] = sec_user_id
if not detail.get("signature"):
signature = _pick_str(node, "signature", "desc", "bio")
if signature:
detail["signature"] = signature
for field, keys in (
("video_count", ("aweme_count", "post_count", "video_count", "works_count")),
("follower_count", ("follower_count", "fans_count")),
("following_count", ("following_count", "follow_count")),
("total_favorited", ("total_favorited", "total_favorited_count", "like_count")),
("favoriting_count", ("favoriting_count", "favorite_count")),
):
if detail.get(field) is None:
val = _pick_int(node, *keys)
if val is not None:
detail[field] = val
return detail
def _pick_url_list(data: Any) -> str:
if isinstance(data, str) and data.startswith("http"):
return data
if isinstance(data, dict):
urls = data.get("url_list") or data.get("urlList") or []
if isinstance(urls, list):
for item in urls:
if isinstance(item, str) and item.startswith("http"):
return item
if isinstance(data, list):
for item in data:
if isinstance(item, str) and item.startswith("http"):
return item
return ""
def _pick_video_play_url(video: dict[str, Any]) -> str:
play_addr = video.get("play_addr") or video.get("download_addr") or {}
urls = play_addr.get("url_list") or []
if not isinstance(urls, list):
urls = []
for item in urls:
if not isinstance(item, str) or not item.startswith("http"):
continue
lower = item.lower()
if lower.endswith(".mp3") or "/ies-music/" in lower:
continue
if "douyinvod.com" in lower or "/video/" in lower or "mime_type=video" in lower:
return item.replace("playwm", "play")
for item in urls:
if isinstance(item, str) and item.startswith("http") and not item.lower().endswith(".mp3"):
return item.replace("playwm", "play")
bit_rate = video.get("bit_rate")
if isinstance(bit_rate, list):
for entry in bit_rate:
if not isinstance(entry, dict):
continue
play = entry.get("play_addr") or {}
url = _pick_url_list(play)
if url and not url.lower().endswith(".mp3"):
return url.replace("playwm", "play")
return ""
def _is_published_aweme(item: dict[str, Any]) -> bool:
"""仅保留已公开发布的作品(排除私密/审核中/已删除)。"""
if not isinstance(item, dict):
return False
if item.get("is_private"):
return False
status = item.get("status")
if isinstance(status, dict):
if status.get("is_delete"):
return False
if status.get("in_reviewing"):
return False
if status.get("is_prohibited"):
return False
private_status = status.get("private_status")
if private_status not in (None, 0, "0"):
return False
part_see = status.get("part_see")
if part_see not in (None, 0, "0", False):
return False
review = status.get("review_result")
if isinstance(review, dict):
review_status = review.get("review_status")
if review_status not in (None, 0, "0"):
return False
rate = item.get("rate")
if rate in (10, 11, 12):
return False
return True
def _parse_aweme_item(item: dict[str, Any]) -> dict[str, Any] | None:
if not isinstance(item, dict):
return None
aweme_id = _pick_str(item, "aweme_id", "awemeId", "item_id")
if not aweme_id:
return None
title = _pick_str(item, "desc", "title", "content")
video = item.get("video") if isinstance(item.get("video"), dict) else {}
cover_url = _pick_url_list(video.get("cover") or video.get("origin_cover") or item.get("cover"))
video_url = _pick_video_play_url(video)
if not cover_url and isinstance(item.get("images"), list) and item["images"]:
first_image = item["images"][0]
if isinstance(first_image, dict):
cover_url = _pick_url_list(first_image.get("url_list") or first_image)
share_url = _pick_str(item, "share_url", "share_link")
if not share_url:
share_url = f"https://www.douyin.com/video/{aweme_id}"
create_time = item.get("create_time") or item.get("createTime")
create_dt: datetime | None = None
if create_time:
try:
create_dt = datetime.utcfromtimestamp(int(create_time))
except (TypeError, ValueError):
create_dt = None
statistics = item.get("statistics") if isinstance(item.get("statistics"), dict) else {}
if not title:
title = f"作品 {aweme_id}"
aweme_type = item.get("aweme_type")
if video_url:
media_type = "video"
elif aweme_type == 68 or item.get("images"):
media_type = "image"
elif aweme_type in (0, 51, 55, 61):
media_type = "video"
else:
media_type = "other"
return {
"aweme_id": aweme_id,
"title": title,
"cover_url": cover_url,
"video_url": video_url,
"share_url": share_url,
"create_time": create_dt,
"media_type": media_type,
"digg_count": _pick_int(statistics, "digg_count", "like_count"),
"comment_count": _pick_int(statistics, "comment_count"),
"play_count": _pick_int(statistics, "play_count", "view_count"),
}
def _parse_creator_item(item: dict[str, Any]) -> dict[str, Any] | None:
if not isinstance(item, dict):
return None
aweme_id = _pick_str(item, "item_id", "item_id_plain", "aweme_id")
if not aweme_id:
return None
title = _pick_str(item, "title", "desc") or f"作品 {aweme_id}"
cover_url = _pick_str(item, "cover_image_url", "cover_url")
share_url = _pick_str(item, "item_link", "share_url") or f"https://www.douyin.com/video/{aweme_id}"
create_time = item.get("create_time")
create_dt: datetime | None = None
if create_time:
try:
create_dt = datetime.utcfromtimestamp(int(create_time))
except (TypeError, ValueError):
create_dt = None
return {
"aweme_id": aweme_id,
"title": title,
"cover_url": cover_url or None,
"video_url": None,
"share_url": share_url,
"create_time": create_dt,
"media_type": "image" if _pick_int(item, "media_type") == 2 else "other",
"digg_count": _pick_int(item, "digg_count", "like_count"),
"comment_count": _pick_int(item, "comment_count"),
"play_count": _pick_int(item, "play_count", "view_count"),
}
def _extract_creator_item_list(data: Any) -> list[dict[str, Any]]:
if not isinstance(data, dict):
return []
for key in ("item_info_list", "aweme_list", "item_list"):
node = data.get(key)
if isinstance(node, list) and node:
return [x for x in node if isinstance(x, dict)]
return []
def _extract_aweme_list(data: Any) -> list[dict[str, Any]]:
if not isinstance(data, dict):
return []
for key in ("aweme_list", "awemeList", "item_list", "items", "data"):
node = data.get(key)
if isinstance(node, list) and node:
return [x for x in node if isinstance(x, dict)]
if isinstance(node, dict):
nested = node.get("aweme_list") or node.get("item_list")
if isinstance(nested, list):
return [x for x in nested if isinstance(x, dict)]
return []
def _douyin_get_json(
auth: DouyinAuth,
ua: str,
url: str,
base_params: dict[str, str],
referer: str = "https://www.douyin.com/",
) -> dict[str, Any] | None:
headers = {
"User-Agent": ua,
"Referer": referer,
"Accept": "application/json, text/plain, */*",
}
proxies = _requests_proxies()
try:
params = dict(base_params)
query = splice_url(params)
params["a_bogus"] = generate_a_bogus(query, user_agent=ua)
resp = requests.get(
url,
params=params,
headers=headers,
cookies=auth.cookie,
verify=False,
timeout=15,
proxies=proxies,
)
data = resp.json()
return data if isinstance(data, dict) else None
except Exception as exc:
logger.debug(f"douyin get failed for {url}: {exc}")
return None
def _fetch_aweme_post_page(
auth: DouyinAuth,
ua: str,
sec_user_id: str,
max_count: int,
strategy_type: str,
) -> list[dict[str, Any]]:
base_params = {
"device_platform": "webapp",
"aid": "6383",
"channel": "channel_pc_web",
"sec_user_id": sec_user_id,
"max_cursor": "0",
"count": str(min(max_count, 35)),
"publish_video_strategy_type": strategy_type,
"verifyFp": auth.cookie.get("s_v_web_id", "") if auth.cookie else "",
"fp": auth.cookie.get("s_v_web_id", "") if auth.cookie else "",
"webid": generate_webid(auth, "https://www.douyin.com/"),
"msToken": auth.msToken or generate_msToken(),
"pc_client_type": "1",
}
videos: list[dict[str, Any]] = []
max_cursor = 0
while len(videos) < max_count:
params = dict(base_params)
params["max_cursor"] = str(max_cursor)
params["count"] = str(min(35, max_count - len(videos)))
data = _douyin_get_json(
auth,
ua,
"https://www.douyin.com/aweme/v1/web/aweme/post/",
params,
referer=f"https://www.douyin.com/user/{sec_user_id}",
)
if not data:
break
status_code = data.get("status_code")
if status_code not in (None, 0):
break
batch = _extract_aweme_list(data)
if not batch:
break
for item in batch:
if not _is_published_aweme(item):
continue
parsed = _parse_aweme_item(item)
if parsed and parsed["aweme_id"] not in {v["aweme_id"] for v in videos}:
videos.append(parsed)
if len(videos) >= max_count:
break
has_more = bool(data.get("has_more") or data.get("hasMore"))
next_cursor = data.get("max_cursor") or data.get("maxCursor")
try:
next_cursor = int(next_cursor or 0)
except (TypeError, ValueError):
next_cursor = 0
if not has_more or next_cursor == max_cursor:
break
max_cursor = next_cursor
return videos
def fetch_douyin_user_videos_sync(
cookie_data: str,
sec_user_id: str,
user_agent: Optional[str] = None,
max_count: int = 50,
) -> dict[str, Any]:
"""抓取用户已公开发布的作品列表(与抖音主页「作品」一致)。"""
result: dict[str, Any] = {"videos": [], "fetched": False, "message": ""}
sec_user_id = (sec_user_id or "").strip()
try:
auth, ua = _build_auth(cookie_data, user_agent)
except Exception as exc:
result["message"] = f"Cookie 无效: {exc}"
return result
if not sec_user_id:
result["message"] = "缺少 sec_user_id,无法拉取已发布作品"
return result
videos = _fetch_aweme_post_page(auth, ua, sec_user_id, max_count, "2")
result["videos"] = videos
result["fetched"] = bool(videos)
if not result["fetched"]:
result["message"] = "未获取到已发布作品,请确认 Cookie 有效且主页有公开作品"
return result
def _fetch_own_videos_sync(
auth: DouyinAuth,
ua: str,
max_count: int,
) -> dict[str, Any]:
"""创作者中心作品列表(适用于当前登录账号)。"""
result: dict[str, Any] = {"videos": [], "fetched": False}
endpoints = [
(
"https://creator.douyin.com/aweme/v1/creator/item/list/",
{
"status": "1",
"count": str(min(max_count, 35)),
"max_cursor": "0",
"aid": "6383",
"device_platform": "webapp",
},
"https://creator.douyin.com/creator-micro/content/manage",
"creator_item",
),
(
"https://creator.douyin.com/aweme/v1/creator/aweme/list/",
{
"status": "1",
"count": str(min(max_count, 35)),
"max_cursor": "0",
"aid": "6383",
"device_platform": "webapp",
},
"https://creator.douyin.com/creator-micro/content/manage",
"aweme",
),
(
"https://creator.douyin.com/web/api/media/aweme/post/",
{
"status": "1",
"count": str(min(max_count, 35)),
"max_cursor": "0",
},
"https://creator.douyin.com/creator-micro/content/manage",
"aweme",
),
]
videos: list[dict[str, Any]] = []
for url, base_params, referer, parser in endpoints:
data = _douyin_get_json(auth, ua, url, base_params, referer=referer)
if not data:
continue
if parser == "creator_item":
batch = _extract_creator_item_list(data)
parse_fn = _parse_creator_item
else:
batch = _extract_aweme_list(data)
parse_fn = _parse_aweme_item
for item in batch:
parsed = parse_fn(item)
if parsed and parsed["aweme_id"] not in {v["aweme_id"] for v in videos}:
videos.append(parsed)
if len(videos) >= max_count:
break
if videos:
break
result["videos"] = videos
result["fetched"] = bool(videos)
return result
def _requests_proxies() -> dict | None:
try:
from rpa_engine.runtime_config import requests_proxies
return requests_proxies()
except Exception:
return None
def _build_auth(cookie_data: str, user_agent: Optional[str] = None) -> tuple[DouyinAuth, str]:
storage = json.loads(cookie_data)
session = DouyinImSession.from_storage_state(storage or {})
ua = resolve_user_agent(user_agent or session.user_agent or DEFAULT_USER_AGENT)
auth = DouyinAuth()
auth.perepare_auth(session.cookie_header(), session.web_protect_str, session.keys_str)
auth.user_agent = ua
auth.web_id = session.web_id or session.device_id or None
return auth, ua
def fetch_douyin_profile_sync(
cookie_data: str,
user_agent: Optional[str] = None,
) -> dict[str, str]:
detail = fetch_douyin_profile_detail_sync(cookie_data, user_agent)
return {
"uid": detail.get("uid") or "",
"nickname": detail.get("nickname") or "",
"avatar_url": detail.get("avatar_url") or "",
}
def fetch_douyin_profile_detail_sync(
cookie_data: str,
user_agent: Optional[str] = None,
) -> dict[str, Any]:
"""抓取抖音账号详细资料(昵称/头像/UID/作品数/粉丝等)。"""
result: dict[str, Any] = {
"uid": "",
"nickname": "",
"avatar_url": "",
"unique_id": "",
"signature": "",
"sec_user_id": "",
"video_count": None,
"follower_count": None,
"following_count": None,
"total_favorited": None,
"favoriting_count": None,
"fetched": False,
"message": "",
}
try:
auth, ua = _build_auth(cookie_data, user_agent)
except Exception as exc:
logger.warning(f"build auth for profile failed: {exc}")
result["message"] = "Cookie 无效,无法解析登录凭证"
return result
uid = auth.get_uid()
if uid:
result["uid"] = str(uid)
headers = {
"User-Agent": ua,
"Referer": "https://www.douyin.com/",
"Accept": "application/json, text/plain, */*",
}
endpoints: list[tuple[str, dict[str, str]]] = [
(
"https://www.douyin.com/aweme/v1/web/query/user/",
{
"device_platform": "webapp",
"aid": "6383",
"channel": "channel_pc_web",
"publish_video_strategy_type": "2",
"verifyFp": auth.cookie.get("s_v_web_id", "") if auth.cookie else "",
"fp": auth.cookie.get("s_v_web_id", "") if auth.cookie else "",
"webid": generate_webid(auth, "https://www.douyin.com/"),
"msToken": auth.msToken or generate_msToken(),
},
),
(
"https://creator.douyin.com/aweme/v1/creator/user/info/",
{
"device_platform": "webapp",
"aid": "6383",
},
),
(
"https://www.douyin.com/aweme/v1/web/user/profile/self/",
{
"device_platform": "webapp",
"aid": "6383",
"channel": "channel_pc_web",
},
),
]
proxies = _requests_proxies()
for url, base_params in endpoints:
try:
params = dict(base_params)
query = splice_url(params)
params["a_bogus"] = generate_a_bogus(query, user_agent=ua)
resp = requests.get(
url,
params=params,
headers=headers,
cookies=auth.cookie,
verify=False,
timeout=12,
proxies=proxies,
)
data = resp.json()
if not isinstance(data, dict):
continue
if data.get("user_uid") and not result["uid"]:
result["uid"] = str(data["user_uid"])
basic = _extract_profile_from_payload(data)
if basic.get("uid") and not result["uid"]:
result["uid"] = basic["uid"]
if basic.get("nickname") and not result["nickname"]:
result["nickname"] = basic["nickname"]
if basic.get("avatar_url") and not result["avatar_url"]:
result["avatar_url"] = basic["avatar_url"]
stats = _extract_detail_from_payload(data)
for key, value in stats.items():
if value is not None and value != "" and result.get(key) in (None, "", 0):
result[key] = value
if result.get("video_count") is not None:
result["fetched"] = True
break
if result["uid"] and result["nickname"] and result["avatar_url"]:
result["fetched"] = True
except Exception as exc:
logger.debug(f"profile detail fetch failed for {url}: {exc}")
if not result["fetched"] and (result["uid"] or result["nickname"]):
result["fetched"] = True
if not result["fetched"]:
result["message"] = result["message"] or "未能从抖音获取账号资料,请确认 Cookie 有效"
return result
async def fetch_douyin_profile(
cookie_data: str,
user_agent: Optional[str] = None,
) -> dict[str, str]:
return await asyncio.to_thread(fetch_douyin_profile_sync, cookie_data, user_agent)
async def fetch_douyin_profile_detail(
cookie_data: str,
user_agent: Optional[str] = None,
) -> dict[str, Any]:
return await asyncio.to_thread(fetch_douyin_profile_detail_sync, cookie_data, user_agent)
async def fetch_douyin_user_videos(
cookie_data: str,
sec_user_id: str,
user_agent: Optional[str] = None,
max_count: int = 50,
) -> dict[str, Any]:
return await asyncio.to_thread(
fetch_douyin_user_videos_sync,
cookie_data,
sec_user_id,
user_agent,
max_count,
)
def _douyin_profile_url(sec_user_id: Optional[str]) -> Optional[str]:
sec = (sec_user_id or "").strip()
if not sec:
return None
return f"https://www.douyin.com/user/{sec}"
def _profile_detail_to_dict(
profile: AccountProfileDetail | None,
account: Account,
videos: list[AccountVideo] | None = None,
) -> dict[str, Any]:
video_rows = videos or []
cached_count = len(video_rows)
def _row_media_type(row: AccountVideo) -> str:
if row.media_type:
return row.media_type
return "video" if row.video_url else "image"
video_work_count = sum(1 for v in video_rows if _row_media_type(v) == "video")
image_work_count = sum(1 for v in video_rows if _row_media_type(v) == "image")
playable_count = video_work_count
if profile:
api_count = profile.video_count
if cached_count:
display_count = cached_count
else:
display_count = api_count
return {
"account_id": account.id,
"uid": profile.uid or account.douyin_uid,
"nickname": profile.nickname or account.username,
"avatar_url": profile.avatar_url or account.avatar_url,
"unique_id": profile.unique_id,
"signature": profile.signature,
"sec_user_id": profile.sec_user_id,
"profile_url": _douyin_profile_url(profile.sec_user_id),
"video_count": display_count,
"video_count_douyin": api_count,
"cached_work_count": cached_count,
"playable_video_count": playable_count,
"video_work_count": video_work_count,
"image_work_count": image_work_count,
"follower_count": profile.follower_count,
"following_count": profile.following_count,
"total_favorited": profile.total_favorited,
"favoriting_count": profile.favoriting_count,
"fetched": bool(profile.synced_at),
"message": profile.sync_message,
"synced_at": profile.synced_at.isoformat() if profile.synced_at else None,
"profile_aweme_count": api_count,
"videos": [
{
"id": v.id,
"aweme_id": v.aweme_id,
"title": v.title or "",
"cover_url": v.cover_url,
"video_url": v.video_url,
"share_url": v.share_url,
"create_time": v.create_time.isoformat() if v.create_time else None,
"digg_count": v.digg_count,
"comment_count": v.comment_count,
"play_count": v.play_count,
"media_type": v.media_type,
}
for v in video_rows
],
}
return {
"account_id": account.id,
"uid": account.douyin_uid,
"nickname": account.username,
"avatar_url": account.avatar_url,
"unique_id": None,
"signature": None,
"sec_user_id": None,
"profile_url": None,
"video_count": None,
"video_count_douyin": None,
"cached_work_count": 0,
"playable_video_count": 0,
"video_work_count": 0,
"image_work_count": 0,
"follower_count": None,
"following_count": None,
"total_favorited": None,
"favoriting_count": None,
"fetched": False,
"message": "暂无本地资料,请点击刷新从抖音同步",
"synced_at": None,
"videos": [],
}
async def load_account_profile_from_db(
db: AsyncSession,
account: Account,
) -> dict[str, Any]:
profile = (
await db.execute(
select(AccountProfileDetail).where(AccountProfileDetail.account_id == account.id)
)
).scalar_one_or_none()
videos: list[AccountVideo] = []
if profile:
videos = list(
(
await db.execute(
select(AccountVideo)
.where(AccountVideo.account_id == account.id)
.order_by(AccountVideo.sort_order.asc(), AccountVideo.id.asc())
)
).scalars().all()
)
return _profile_detail_to_dict(profile, account, videos)
async def sync_account_profile_to_db(
db: AsyncSession,
account: Account,
cookie_data: str,
max_videos: int = 50,
) -> dict[str, Any]:
"""从抖音拉取资料与作品并写入本地数据库。"""
detail = await fetch_douyin_profile_detail(cookie_data, account.user_agent)
sec_user_id = (detail.get("sec_user_id") or "").strip()
if detail.get("fetched"):
try:
await apply_douyin_profile(db, account, cookie_data)
except Exception as exc:
logger.warning(f"apply douyin profile failed: {exc}")
if not sec_user_id and detail.get("uid"):
try:
auth, ua = _build_auth(cookie_data, account.user_agent)
extra = _douyin_get_json(
auth,
ua,
"https://www.douyin.com/aweme/v1/web/user/profile/other/",
{
"device_platform": "webapp",
"aid": "6383",
"channel": "channel_pc_web",
"user_id": str(detail["uid"]),
"sec_user_id": "",
"publish_video_strategy_type": "2",
"verifyFp": auth.cookie.get("s_v_web_id", "") if auth.cookie else "",
"fp": auth.cookie.get("s_v_web_id", "") if auth.cookie else "",
"webid": generate_webid(auth, "https://www.douyin.com/"),
"msToken": auth.msToken or generate_msToken(),
},
)
if extra:
sec_user_id = (_extract_detail_from_payload(extra).get("sec_user_id") or "").strip()
except Exception as exc:
logger.debug(f"resolve sec_user_id failed: {exc}")
video_result = await fetch_douyin_user_videos(
cookie_data,
sec_user_id,
account.user_agent,
max_count=max_videos,
)
now = datetime.utcnow()
profile = (
await db.execute(
select(AccountProfileDetail).where(AccountProfileDetail.account_id == account.id)
)
).scalar_one_or_none()
if not profile:
profile = AccountProfileDetail(account_id=account.id)
db.add(profile)
profile.uid = detail.get("uid") or account.douyin_uid
profile.nickname = detail.get("nickname") or account.username
profile.avatar_url = detail.get("avatar_url") or account.avatar_url
profile.unique_id = detail.get("unique_id") or None
profile.signature = detail.get("signature") or None
profile.sec_user_id = sec_user_id or None
profile.follower_count = detail.get("follower_count")
profile.following_count = detail.get("following_count")
profile.total_favorited = detail.get("total_favorited")
profile.favoriting_count = detail.get("favoriting_count")
profile.synced_at = now
messages: list[str] = []
if detail.get("message"):
messages.append(str(detail["message"]))
fetched_videos = video_result.get("videos") or []
await db.execute(delete(AccountVideo).where(AccountVideo.account_id == account.id))
for idx, item in enumerate(fetched_videos):
db.add(
AccountVideo(
account_id=account.id,
aweme_id=item["aweme_id"],
title=item.get("title"),
cover_url=item.get("cover_url"),
video_url=item.get("video_url"),
share_url=item.get("share_url"),
create_time=item.get("create_time"),
digg_count=item.get("digg_count"),
comment_count=item.get("comment_count"),
play_count=item.get("play_count"),
media_type=item.get("media_type"),
sort_order=idx,
synced_at=now,
)
)
profile.video_count = len(fetched_videos)
if fetched_videos:
profile.sync_message = ";".join(messages) if messages else None
else:
empty_msg = str(video_result.get("message") or "主页暂无已公开发布作品")
if messages:
messages.append(empty_msg)
else:
messages = [empty_msg]
profile.sync_message = ";".join(messages)
await db.commit()
await db.refresh(account)
return await load_account_profile_from_db(db, account)
async def _pick_unique_username(
db: AsyncSession,
account: Account,
nickname: str,
uid: str,
) -> str:
candidates: list[str] = []
if nickname and uid:
candidates.extend([nickname, f"{nickname}_{uid}"])
elif nickname:
candidates.append(nickname)
elif uid:
candidates.append(f"用户{uid}")
candidates.append(f"{(nickname or '账号')}_{account.id}")
for candidate in candidates:
name = candidate[:100]
stmt = select(Account.id).where(Account.username == name, Account.id != account.id)
conflict = (await db.execute(stmt)).scalar_one_or_none()
if not conflict:
return name
return f"账号_{account.id}"
async def apply_douyin_profile(
db: AsyncSession,
account: Account,
cookie_data: str,
) -> dict[str, str]:
"""抓取并写入账号资料,返回抓取结果。"""
profile = await fetch_douyin_profile(cookie_data, account.user_agent)
uid = (profile.get("uid") or "").strip()
nickname = (profile.get("nickname") or "").strip()
avatar = (profile.get("avatar_url") or "").strip()
if uid:
account.douyin_uid = uid
if avatar:
account.avatar_url = avatar
if nickname or uid:
account.username = await _pick_unique_username(db, account, nickname, uid)
return profile
+211
View File
@@ -0,0 +1,211 @@
"""账号凭证检测:静态 Cookie 分析 + IM 运行时校验"""
import json
import logging
from typing import Optional
from rpa_engine.douyin_im.auth import DouyinAuth
from rpa_engine.douyin_im.frontier import ensure_frontier_ws
from rpa_engine.douyin_im.http_client import DouyinImHttpClient
from rpa_engine.douyin_im.session import DouyinImSession
from utils.cookie_store import analyze_cookie
logger = logging.getLogger("credential")
def _should_reset_credentials(assessment: dict) -> bool:
"""凭证全面失效时需清空 Cookie/IM 数据并重新登录。"""
if not assessment.get("has_cookie"):
return False
if not assessment.get("cookie_valid"):
return True
message = assessment.get("message") or ""
# 仅缺 ticket/签名/浏览器采集 — 保留 Cookie,走浏览器补全即可
if any(
token in message
for token in ("ticket", "签名密钥", "浏览器模式", "web_protect")
):
return False
if (
not assessment.get("im_ready")
and not assessment.get("can_skip_browser")
and assessment.get("has_sessionid")
):
return True
return False
def build_im_session_from_storage(
storage: dict,
saved_im_data: Optional[str] = None,
) -> DouyinImSession:
session = DouyinImSession.from_storage_state(storage or {})
if saved_im_data:
try:
saved = DouyinImSession.from_dict(json.loads(saved_im_data))
# 新粘贴的 storage_state(含真实 frontier_ws_url)优先;只有它没带时才用缓存的。
if saved.ws_urls and not session.ws_urls:
session.ws_urls = saved.ws_urls
if saved.sdk_cert and not session.sdk_cert:
session.sdk_cert = saved.sdk_cert
if saved.frontier_ts_sign and not session.frontier_ts_sign:
session.frontier_ts_sign = saved.frontier_ts_sign
if saved.keys_str and not session.keys_str:
session.keys_str = saved.keys_str
if saved.web_protect_str and not session.web_protect_str:
session.web_protect_str = saved.web_protect_str
if saved.my_uid and not session.my_uid:
session.my_uid = saved.my_uid
if saved.device_id and not session.device_id:
session.device_id = saved.device_id
if saved.web_id and not session.web_id:
session.web_id = saved.web_id
if saved.conv_meta:
session.conv_meta = {**saved.conv_meta, **session.conv_meta}
except Exception:
pass
session.sanitize_ws_urls()
ensure_frontier_ws(session)
return session
def has_im_session_token(session: DouyinImSession) -> bool:
return bool(session.cookies.get("sessionid") or session.cookies.get("sessionid_ss"))
def extract_sessionid_info(session: DouyinImSession) -> dict:
sessionid = session.cookies.get("sessionid") or ""
sessionid_ss = session.cookies.get("sessionid_ss") or ""
return {
"has_sessionid": bool(sessionid or sessionid_ss),
"sessionid": sessionid,
"sessionid_ss": sessionid_ss,
}
async def build_cookie_credential_detail(
cookie_data: Optional[str],
im_session_data: Optional[str] = None,
runtime_check: bool = True,
) -> dict:
"""供编辑账号页展示 IM 凭证与 sessionid 信息"""
sessionid_info = {
"has_sessionid": False,
"sessionid": "",
"sessionid_ss": "",
"im_ready": False,
"im_status": "未保存 Cookie",
"can_skip_browser": False,
"should_reset": False,
}
if not cookie_data:
return sessionid_info
try:
storage = json.loads(cookie_data)
session = build_im_session_from_storage(storage, im_session_data)
sessionid_info.update(extract_sessionid_info(session))
except Exception:
sessionid_info["im_status"] = "Cookie 格式错误"
return sessionid_info
if not runtime_check:
if sessionid_info["has_sessionid"]:
sessionid_info["im_status"] = "已检测到 sessionid(未做运行时验证)"
else:
sessionid_info["im_status"] = "缺少 sessionid,无法 IM 直连"
return sessionid_info
assessment = await assess_account_credential(cookie_data, im_session_data)
sessionid_info["im_ready"] = assessment["im_ready"]
sessionid_info["im_status"] = assessment["message"]
sessionid_info["can_skip_browser"] = assessment["can_skip_browser"]
sessionid_info["should_reset"] = assessment["should_reset"]
return sessionid_info
async def validate_im_session(session: DouyinImSession) -> tuple[bool, str]:
if not session.can_direct_im():
if not has_im_session_token(session):
return False, "缺少 sessionid,无法直连 IM"
return False, "Cookie 不满足 IM 直连条件"
ensure_frontier_ws(session)
try:
auth = DouyinAuth.from_im_session(session)
# 优先用已持久化的 my_uid,避免每次都发起网络 query_my_uid(uid_tt 是加密串,
# int() 解析必然失败而回退到网络请求;该请求偶发失败会误判为“未就绪”)。
uid = session.my_uid or auth.get_uid()
if not uid:
return False, "服务端未认可当前 Cookie(无法获取用户 UID)"
if not auth.is_sign_ready():
return False, "缺少 IM 签名密钥(web_protect/keys),请用浏览器登录补全"
session.my_uid = int(uid)
async with DouyinImHttpClient(session) as http:
await http.get_unread_count()
# 若已缓存到会话票据,优先校验其是否仍新鲜(最理想)。
if session.conv_meta:
ok, reason = await http.verify_messaging_capability(auth, session.my_uid)
if ok:
return True, reason
# 没有缓存会话票据是首次登录的正常情况:会话 ticket 会在发送时即时
# 创建/获取(resolve_conversation_meta),因此只要 Cookie + sessionid +
# 签名密钥(web_protect/keys) + UID 齐全,就视为可 IM 直连托管,不必再开浏览器。
return True, "IM 凭证就绪(Cookie 与签名密钥齐全,可直连托管)"
except Exception as e:
logger.warning(f"IM session validation failed: {e}")
return False, f"IM 运行时验证失败: {e}"
async def assess_account_credential(
cookie_data: Optional[str],
im_session_data: Optional[str] = None,
) -> dict:
cookie_info = analyze_cookie(cookie_data)
result = {
"has_cookie": cookie_info.get("has_cookie", False),
"cookie_valid": cookie_info.get("cookie_valid", False),
"cookie_status": cookie_info.get("reason", ""),
"has_sessionid": False,
"im_ready": False,
"can_skip_browser": False,
"login_mode": "browser",
"message": "未保存 Cookie,需浏览器扫码登录",
"should_reset": False,
}
if not cookie_data:
return result
try:
storage = json.loads(cookie_data)
except Exception:
result["message"] = "Cookie 格式错误"
result["should_reset"] = _should_reset_credentials(result)
return result
session = build_im_session_from_storage(storage, im_session_data)
result["has_sessionid"] = has_im_session_token(session)
if not cookie_info.get("cookie_valid"):
result["message"] = cookie_info.get("reason") or "Cookie 无效,需重新登录"
result["should_reset"] = _should_reset_credentials(result)
return result
if not result["has_sessionid"]:
result["login_mode"] = "browser"
result["message"] = "Cookie 已保存但缺少 sessionid,需浏览器刷新登录态"
result["should_reset"] = _should_reset_credentials(result)
return result
im_ok, im_reason = await validate_im_session(session)
result["im_ready"] = im_ok
if im_ok:
result["can_skip_browser"] = True
result["login_mode"] = "im_direct"
result["message"] = im_reason
else:
result["login_mode"] = "browser"
result["message"] = im_reason
result["should_reset"] = _should_reset_credentials(result)
return result
+89
View File
@@ -0,0 +1,89 @@
"""浏览器 / IM 伪装设备头(User-Agent)预设。
a_bogus 签名、Playwright 浏览器上下文、IM HTTP 请求头、Protobuf body 必须使用同一 UA,
否则抖音会返回 7911 安全校验失败。
"""
from rpa_engine.douyin_im.dy_util import DEFAULT_USER_AGENT
# id 用于前端下拉;user_agent 为完整字符串
DEVICE_PROFILES: list[dict[str, str]] = [
{
"id": "chrome_win120",
"label": "Chrome 120 · Windows(默认,推荐)",
"platform": "Windows",
"user_agent": DEFAULT_USER_AGENT,
},
{
"id": "chrome_win131",
"label": "Chrome 131 · Windows",
"platform": "Windows",
"user_agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
),
},
{
"id": "edge_win125",
"label": "Edge 125 · Windows",
"platform": "Windows",
"user_agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0"
),
},
{
"id": "firefox_win117",
"label": "Firefox 117 · Windows",
"platform": "Windows",
"user_agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) "
"Gecko/20100101 Firefox/117.0"
),
},
{
"id": "chrome_mac120",
"label": "Chrome 120 · macOS",
"platform": "macOS",
"user_agent": (
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
),
},
{
"id": "safari_mac17",
"label": "Safari 17 · macOS",
"platform": "macOS",
"user_agent": (
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 "
"(KHTML, like Gecko) Version/17.0 Safari/605.1.15"
),
},
]
_PROFILE_BY_UA = {p["user_agent"]: p for p in DEVICE_PROFILES}
def list_device_profiles() -> list[dict[str, str]]:
return [
{"id": p["id"], "label": p["label"], "platform": p["platform"], "user_agent": p["user_agent"]}
for p in DEVICE_PROFILES
]
def resolve_user_agent(stored: str | None) -> str:
"""账号保存的 UA;空则使用默认 Chrome 120。"""
text = (stored or "").strip()
return text or DEFAULT_USER_AGENT
def profile_label_for_ua(ua: str | None) -> str:
text = (ua or "").strip()
if not text:
return "Chrome 120 · Windows(默认)"
hit = _PROFILE_BY_UA.get(text)
if hit:
return hit["label"]
if len(text) > 48:
return text[:48] + "…"
return text
+3
View File
@@ -0,0 +1,3 @@
from .service import DouyinImService
__all__ = ["DouyinImService"]
+163
View File
@@ -0,0 +1,163 @@
import base64
import json
import logging
import requests
from .dy_util import (
trans_cookies,
generate_msToken,
generate_a_bogus,
splice_url,
generate_webid,
normalize_client_cert,
resolve_proto_device_id,
DEFAULT_USER_AGENT,
)
logger = logging.getLogger("douyin_im.auth")
def _parse_storage_json(raw) -> dict | None:
"""Parse localStorage JSON (supports nested data wrapper)."""
if not raw:
return None
if isinstance(raw, dict):
data = raw
else:
text = str(raw).strip()
data = None
for _ in range(4):
try:
parsed = json.loads(text)
except Exception:
break
if isinstance(parsed, str):
text = parsed
continue
if isinstance(parsed, dict):
data = parsed
break
break
if not data:
return None
inner = data.get("data")
if isinstance(inner, str):
try:
inner = json.loads(inner)
except Exception:
inner = None
if isinstance(inner, dict):
return inner
return data
class DouyinAuth:
def __init__(self):
self.cookie = None
self.cookie_str = None
self.private_key = None
self.ticket = None
self.ts_sign = None
self.client_cert = None
self.ree_public_key = None
self.uid = None
self.msToken = None
self.web_id = None
def perepare_auth(self, cookieStr: str, web_protect_: str = "", keys_: str = ""):
self.cookie = trans_cookies(cookieStr)
self.cookie_str = cookieStr
self.msToken = self.cookie["msToken"] if "msToken" in self.cookie else generate_msToken()
self.cookie["msToken"] = self.msToken
self.cookie_str = "; ".join([f"{k}={v}" for k, v in self.cookie.items()])
web_data = _parse_storage_json(web_protect_)
if web_data:
try:
self.ticket = web_data.get("ticket") or ""
self.ts_sign = web_data.get("ts_sign") or ""
self.client_cert = web_data.get("client_cert") or ""
except Exception as e:
logger.debug(f"web_protect parse failed: {e}")
keys_data = _parse_storage_json(keys_)
if keys_data:
try:
self.private_key = keys_data.get("ec_privateKey") or keys_data.get("privateKey") or ""
if self.private_key:
self.ree_public_key = base64.b64encode(self.private_key.encode()).decode()
except Exception as e:
logger.debug(f"keys parse failed: {e}")
def is_sign_ready(self) -> bool:
return bool(
self.private_key
and self.ticket
and self.ts_sign
and self.client_cert
)
@classmethod
def from_im_session(cls, session) -> "DouyinAuth":
"""从 DouyinImSession 构建 HTTP 发送/拉会话用的签名上下文。
注意:frontier WS 的 sdk_cert/ts_sign 只用于长连接,不能覆盖 web_protect,
否则 bd-ticket-guard 与 protobuf 签名会与 ticket 失配 -> 7911。
"""
auth = cls()
auth.perepare_auth(
session.cookie_header(),
session.web_protect_str,
session.keys_str,
)
auth.web_id = session.web_id or session.device_id or None
auth.user_agent = session.user_agent or DEFAULT_USER_AGENT
auth.device_id = resolve_proto_device_id(
session.device_id, session.web_id, session.my_uid
)
# web_protect 缺 client_cert 时,才用 frontier 抓包证书兜底(不覆盖 ts_sign)
if not auth.client_cert and getattr(session, "sdk_cert", ""):
auth.client_cert = normalize_client_cert(session.sdk_cert)
elif auth.client_cert:
auth.client_cert = normalize_client_cert(auth.client_cert)
return auth
def get_uid(self):
if self.uid is None:
# 优先从 cookie 尝试提取,否则请求接口
for k in ("uid_tt", "uid_tt_ss"):
if self.cookie and self.cookie.get(k):
try:
self.uid = int(self.cookie.get(k))
return self.uid
except ValueError:
pass
try:
self.uid = self.query_my_uid()
except Exception:
pass
return self.uid
def query_my_uid(self) -> int:
url = 'https://www.douyin.com/aweme/v1/web/query/user/'
headers = {
"User-Agent": DEFAULT_USER_AGENT,
"Referer": "https://www.douyin.com/",
"Accept": "application/json, text/plain, */*",
}
params = {
"device_platform": "webapp",
"aid": "6383",
"channel": "channel_pc_web",
"publish_video_strategy_type": "2",
"verifyFp": self.cookie.get('s_v_web_id', ''),
"fp": self.cookie.get('s_v_web_id', ''),
"webid": generate_webid(self, "https://www.douyin.com/"),
"msToken": self.msToken
}
query = splice_url(params)
abogus = generate_a_bogus(query, user_agent=DEFAULT_USER_AGENT)
params['a_bogus'] = abogus
resp = requests.get(url, params=params, headers=headers, cookies=self.cookie, verify=False, timeout=10)
resp_json = resp.json()
return int(resp_json['user_uid'])
+47
View File
@@ -0,0 +1,47 @@
"""Conversation id helpers for Douyin IM."""
def parse_conversation_parts(conversation_id: str) -> tuple[int, int] | None:
parts = (conversation_id or "").split(":")
if len(parts) >= 4 and parts[0] == "0" and parts[1] == "1":
try:
return int(parts[2]), int(parts[3])
except (TypeError, ValueError):
return None
return None
def resolve_peer_uid(conversation_id: str, my_uid: int) -> int | None:
"""Resolve peer user id from conversation id or bare numeric id."""
raw = (conversation_id or "").strip()
if not raw:
return None
parts = parse_conversation_parts(raw)
if parts:
uid1, uid2 = parts
if my_uid and uid1 == my_uid:
return uid2
if my_uid and uid2 == my_uid:
return uid1
# 0:1:{my}:{peer} — 若 my_uid 与首段不一致,仍取末段为对方
return uid2
if raw.isdigit():
peer = int(raw)
if my_uid and peer == my_uid:
return None
return peer
return None
def build_conversation_id(my_uid: int, peer_uid: int) -> str:
return f"0:1:{int(my_uid)}:{int(peer_uid)}"
def normalize_conversation_id(conversation_id: str, my_uid: int) -> str:
"""Ensure conversation id uses current account uid as first participant."""
peer_uid = resolve_peer_uid(conversation_id, my_uid)
if peer_uid and my_uid:
return build_conversation_id(my_uid, peer_uid)
return (conversation_id or "").strip()
+191
View File
@@ -0,0 +1,191 @@
import hashlib
import re
import time
import json
import random
import base64
import urllib.parse
from os import path
import subprocess
original_popen = subprocess.Popen
def patched_popen(*args, **kwargs):
if kwargs.get('universal_newlines') or kwargs.get('text'):
if 'encoding' not in kwargs:
kwargs['encoding'] = 'utf-8'
return original_popen(*args, **kwargs)
subprocess.Popen = patched_popen
import execjs
import requests
basedir = path.dirname(__file__)
static_dir = path.join(basedir, 'static')
node_modules = path.join(static_dir, 'node_modules')
# 全局唯一 User-Agent:a_bogus 签名、HTTP 请求头、protobuf body、webid 采集等
# 必须全部使用同一个 UA,否则抖音服务端重算 a_bogus 时与请求头 UA 不一致 -> 7911。
# 该值需与浏览器登录上下文(playwright new_context user_agent)保持一致。
DEFAULT_USER_AGENT = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
)
# 动态编译 JS
dy_path = path.join(static_dir, 'dy_ab.js')
dy_js = execjs.compile(open(dy_path, 'r', encoding='utf-8').read(), cwd=node_modules)
sign_path = path.join(static_dir, 'dy_live_sign.js')
sign_js = execjs.compile(open(sign_path, 'r', encoding='utf-8').read(), cwd=node_modules)
login_path = path.join(static_dir, 'login.js')
login_js = execjs.compile(open(login_path, 'r', encoding='utf-8').read(), cwd=node_modules)
def generateSecretPhoneNum(phone):
return login_js.call('generateSecretPhoneNum', phone)
def generateSecretCode(phone, code):
return login_js.call('generateSecretCode', phone, code)
def trans_cookies(cookies_str):
cookies = {}
for i in cookies_str.split("; "):
try:
parts = i.split('=')
key = parts[0].strip()
val = '='.join(parts[1:]).strip()
# 防御性清洗:过滤掉因为误粘贴 fetch 等包含非法字符或换行的 Cookie 键
if not key or any(c in key for c in "()[]{}'\"\n \t\\"):
continue
cookies[key] = val
except:
continue
return cookies
def generate_req_sign(e, priK):
"""私信传 obj,其他的拼接"""
return dy_js.call('get_req_sign', e, priK)
def generate_a_bogus(query, data="", user_agent=None):
"""query, data 都是拼接字符串。
user_agent 必须与实际发出请求所用的 User-Agent 完全一致(见 DEFAULT_USER_AGENT),
否则抖音服务端用请求头 UA 重算 a_bogus 会对不上,导致 7911 安全校验失败。
"""
return dy_js.call('get_ab', query, data, user_agent or DEFAULT_USER_AGENT)
def generate_signature(room_id, user_unique_id):
raw_string = f"live_id=1,aid=6383,version_code=180800,webcast_sdk_version=1.0.15,room_id={room_id},sub_room_id=,sub_channel_id=,did_rule=3,user_unique_id={user_unique_id},device_platform=web,device_type=,ac=,identity=audience"
x_ms_stub = hashlib.md5(raw_string.encode("utf-8")).hexdigest()
result = sign_js.call("get_signature", x_ms_stub)
return result.get("X-Bogus")
def generate_ree_key(prik):
"""传递私钥"""
return dy_js.call('get_ree_key', prik)
def generate_bd_ticket_client_data(api, ticket, ts_sign, priK):
"""传递 query, ticket, ts_sign, priK"""
timestamp = int(time.time())
res_sign = f"ticket={ticket}&path={api}&timestamp={timestamp}"
p = {
'ts_sign': ts_sign,
'req_content': 'ticket,path,timestamp',
'req_sign': generate_req_sign(res_sign, priK),
'timestamp': timestamp,
}
p = json.dumps(p, ensure_ascii=False, separators=(',', ':'))
return base64.urlsafe_b64encode(p.encode('utf-8')).decode('utf-8')
def generate_msToken(randomlength=107):
random_str = ''
base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789='
length = len(base_str) - 1
for _ in range(randomlength):
random_str += base_str[random.randint(0, length)]
return random_str
def generate_fake_webid(random_length=19):
random_str = ''
base_str = '0123456789'
length = len(base_str) - 1
for _ in range(random_length):
random_str += base_str[random.randint(0, length)]
return random_str
def generate_webid(auth=None, url=""):
# 优先用已采集到的 web_id(避免每次发送都发起一次阻塞的 HTTP 请求,导致事件循环卡顿)
cached = getattr(auth, "web_id", None) if auth is not None else None
if cached:
return str(cached)
if url == "":
url = "https://www.douyin.com/discover?modal_id=7376449060384935209"
try:
from .auth import DouyinAuth
headers = {
"User-Agent": DEFAULT_USER_AGENT,
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"upgrade-insecure-requests": "1"
}
if auth and auth.cookie_str:
headers['cookie'] = auth.cookie_str
try:
from rpa_engine.runtime_config import requests_proxies
proxies = requests_proxies()
except Exception:
proxies = None
response = requests.get(
url, headers=headers, verify=False, timeout=10, proxies=proxies
)
res_text = response.text
user_unique_id = re.findall(r'\\"user_unique_id\\":\\"(.*?)\\"', res_text)[0]
return user_unique_id
except Exception:
return generate_fake_webid()
def generate_millisecond():
return int(round(time.time() * 1000))
def normalize_client_cert(cert: str) -> str:
"""统一 client_cert / sdk_cert 格式为「base64 证书体」。
web_protect.client_cert 与 frontier WS 的 sdk_cert 通常已是 base64(PEM);
若误把 PEM 原文或 frontier 证书二次 base64,会导致 7911。
"""
cert = (cert or "").strip()
if not cert:
return ""
if cert.startswith("-----BEGIN"):
return base64.b64encode(cert.encode("utf-8")).decode("utf-8")
return cert
def resolve_proto_device_id(device_id: str = "", web_id: str = "", my_uid: int = 0) -> str:
"""protobuf / frontier 更倾向使用数字 device_id(通常等于 my_uid)。"""
for candidate in (device_id, web_id, str(my_uid or "")):
c = str(candidate or "").strip()
if c.isdigit():
return c
return str(device_id or web_id or "0")
def splice_url(params):
splice_url_str = ''
for key, value in params.items():
if value is None:
value = ''
splice_url_str += key + '=' + urllib.parse.quote(str(value)) + '&'
return splice_url_str[:-1]
+122
View File
@@ -0,0 +1,122 @@
"""抖音标准表情(评论区 emoji)名称 -> 图片 URL 映射。
抖音文字表情如 [酷拽]/[微笑] 通过 WS 以 message_type=7 的纯文本下发,
content 形如 {"text":"[酷拽]","aweType":700},不带图片地址;
浏览器端靠本地表情表把 [name] 渲染成小图。这里拉取官方表情列表接口,
建立 name->url 映射,收到文字表情时补成可显示的贴纸。
"""
from __future__ import annotations
import logging
import re
import threading
import time
from typing import Optional
logger = logging.getLogger("douyin_im.emoji")
_EMOJI_MAP: dict[str, str] = {}
_FETCHED_AT: float = 0.0
_TTL = 6 * 3600 # 6 小时刷新一次
_lock = threading.Lock()
_BRACKET_RE = re.compile(r"^\[[^\[\]]{1,24}\]$")
def has_emoji_map() -> bool:
return bool(_EMOJI_MAP)
def is_fresh() -> bool:
return bool(_EMOJI_MAP) and (time.time() - _FETCHED_AT) < _TTL
def set_emoji_map(mapping: dict[str, str]) -> None:
global _EMOJI_MAP, _FETCHED_AT
if mapping:
with _lock:
_EMOJI_MAP = dict(mapping)
_FETCHED_AT = time.time()
def lookup_emoji_url(name: str) -> str:
"""name 可带或不带中括号,返回标准表情图片 URL(无则空串)。"""
if not name:
return ""
key = name.strip()
if not key:
return ""
if not key.startswith("["):
key = f"[{key}]"
return _EMOJI_MAP.get(key, "")
def looks_like_emoji_token(text: str) -> bool:
return bool(_BRACKET_RE.match((text or "").strip()))
def fetch_emoji_map(session) -> dict[str, str]:
"""用账号会话拉取官方表情列表,返回 {display_name: url}。失败返回 {}。"""
try:
import requests
from .auth import DouyinAuth
from .dy_util import generate_a_bogus, generate_msToken, splice_url
auth = DouyinAuth.from_im_session(session)
ua = session.user_agent
s_v_web_id = session.cookies.get("s_v_web_id", "") if session.cookies else ""
params = {
"device_platform": "webapp",
"aid": "6383",
"channel": "channel_pc_web",
"pc_client_type": "1",
"version_code": "170400",
"version_name": "17.4.0",
"cookie_enabled": "true",
"browser_language": "zh-CN",
"browser_platform": "Win32",
"browser_name": "Mozilla",
"browser_online": "true",
"verifyFp": s_v_web_id,
"fp": s_v_web_id,
"webid": session.web_id or session.device_id or "",
"msToken": generate_msToken(),
}
params["a_bogus"] = generate_a_bogus(splice_url(params), user_agent=ua)
headers = {
"User-Agent": ua,
"Referer": "https://www.douyin.com/",
"Accept": "application/json, text/plain, */*",
"Cookie": session.cookie_header(),
}
resp = requests.get(
"https://www.douyin.com/aweme/v1/web/emoji/list",
params=params,
headers=headers,
cookies=auth.cookie if getattr(auth, "cookie", None) else None,
verify=False,
timeout=20,
)
data = resp.json()
mapping: dict[str, str] = {}
for item in data.get("emoji_list") or []:
name = item.get("display_name")
urls = (item.get("emoji_url") or {}).get("url_list") or []
if name and urls:
mapping[name] = urls[0]
logger.info("Fetched %d douyin emoji", len(mapping))
return mapping
except Exception as e:
logger.warning("fetch_emoji_map failed: %s", e)
return {}
def ensure_emoji_map(session) -> None:
"""若缓存为空/过期则拉取(同步阻塞,调用方建议放线程)。"""
if is_fresh():
return
mapping = fetch_emoji_map(session)
if mapping:
set_emoji_map(mapping)
@@ -0,0 +1,183 @@
"""抖音网页版「粉丝列表」拉取,用于检测新粉丝(关注欢迎语功能)。
复用与 peer_profile / account_profile 相同的 a_bogus + msToken + cookie 签名方式,
调用 https://www.douyin.com/aweme/v1/web/user/follower/list/ 拉取本账号最近的粉丝。
返回的每个粉丝含:uid / sec_uid / nickname / follow_status / follower_status。
其中 follow_status 表示「我」与对方的关系:0=未关注 1=我已关注 2=互相关注(互关)。
"""
from __future__ import annotations
import asyncio
import logging
from typing import Any
from .dy_util import (
DEFAULT_USER_AGENT,
generate_a_bogus,
generate_msToken,
generate_webid,
splice_url,
)
from .auth import DouyinAuth
logger = logging.getLogger("douyin_im.follower_poll")
FOLLOWER_LIST_URL = "https://www.douyin.com/aweme/v1/web/user/follower/list/"
def _requests_proxies() -> dict | None:
try:
from rpa_engine.runtime_config import requests_proxies
return requests_proxies()
except Exception:
return None
def _to_int(value: Any) -> int:
try:
return int(value)
except (TypeError, ValueError):
return 0
def _extract_followers(data: dict[str, Any]) -> list[dict[str, Any]]:
raw = data.get("followers")
if not isinstance(raw, list):
return []
out: list[dict[str, Any]] = []
for item in raw:
if not isinstance(item, dict):
continue
uid = str(item.get("uid") or item.get("user_id") or "").strip()
if not uid:
continue
out.append(
{
"uid": uid,
"sec_uid": str(item.get("sec_uid") or item.get("sec_user_id") or "").strip(),
"nickname": str(item.get("nickname") or item.get("nick_name") or "").strip(),
# follow_status:我对对方的关系(2=互关);follower_status:对方对我的关系
"follow_status": _to_int(item.get("follow_status")),
"follower_status": _to_int(item.get("follower_status")),
}
)
return out
def fetch_recent_followers_sync(
session,
sec_user_id: str,
count: int = 20,
max_time: int = 0,
) -> list[dict[str, Any]]:
"""同步拉取最近粉丝(第一页)。失败返回 [],并在日志里写明原因。"""
import requests
sec_user_id = (sec_user_id or "").strip()
if not sec_user_id:
logger.warning("fetch followers skipped: 缺少本账号 sec_user_id")
return []
try:
auth = DouyinAuth()
auth.perepare_auth(session.cookie_header(), session.web_protect_str, session.keys_str)
except Exception as exc:
logger.warning("fetch followers: build auth failed: %s", exc)
return []
ua = session.user_agent or DEFAULT_USER_AGENT
params = {
"device_platform": "webapp",
"aid": "6383",
"channel": "channel_pc_web",
"sec_user_id": sec_user_id,
"count": str(count),
"max_time": str(max_time),
"min_time": "0",
"offset": "0",
"source_type": "1",
"gps_access": "0",
"address_book_access": "0",
"is_top": "1",
"update_version_code": "170400",
"pc_client_type": "1",
"version_code": "170400",
"version_name": "17.4.0",
"cookie_enabled": "true",
"screen_width": "1536",
"screen_height": "960",
"browser_language": "zh-CN",
"browser_platform": "Win32",
"browser_name": "Chrome",
"browser_version": "120.0.0.0",
"browser_online": "true",
"os_name": "Windows",
"os_version": "10",
"platform": "PC",
"webid": generate_webid(auth, "https://www.douyin.com/"),
"verifyFp": auth.cookie.get("s_v_web_id", "") if auth.cookie else "",
"fp": auth.cookie.get("s_v_web_id", "") if auth.cookie else "",
"msToken": auth.msToken or generate_msToken(),
}
query = splice_url(params)
params["a_bogus"] = generate_a_bogus(query, user_agent=ua)
headers = {
"User-Agent": ua,
"Referer": "https://www.douyin.com/",
"Accept": "application/json, text/plain, */*",
}
try:
resp = requests.get(
FOLLOWER_LIST_URL,
params=params,
headers=headers,
cookies=auth.cookie,
timeout=15,
verify=False,
proxies=_requests_proxies(),
)
try:
data = resp.json()
except Exception:
snippet = (resp.text or "")[:200].replace("\n", " ")
logger.warning(
"fetch followers: 非 JSON 响应 (HTTP %s): %s", resp.status_code, snippet
)
return []
if not isinstance(data, dict):
logger.warning("fetch followers: 响应不是 JSON 对象")
return []
status_code = data.get("status_code")
if status_code not in (None, 0):
logger.warning(
"fetch followers: status_code=%s msg=%s",
status_code,
data.get("status_msg") or data.get("message") or "",
)
return []
followers = _extract_followers(data)
logger.info(
"fetch followers ok: 拿到 %s 个粉丝 (has_more=%s total=%s)",
len(followers),
data.get("has_more"),
data.get("total"),
)
return followers
except Exception as exc:
logger.warning("fetch followers failed: %s", exc)
return []
async def fetch_recent_followers(
session,
sec_user_id: str,
count: int = 20,
max_time: int = 0,
) -> list[dict[str, Any]]:
return await asyncio.to_thread(
fetch_recent_followers_sync, session, sec_user_id, count, max_time
)
+124
View File
@@ -0,0 +1,124 @@
"""Build frontier-im WebSocket URL (DouYin_Spider douyin_recv_msg logic)."""
import hashlib
import logging
from typing import Optional
import requests
from .auth import DouyinAuth
from .dy_util import generate_a_bogus, generate_msToken, generate_webid, splice_url
from .session import DouyinImSession, is_frontier_ws_url
logger = logging.getLogger("douyin_im.frontier")
APP_KEY = "e1bd35ec9db7b8d846de66ed140b1ad9"
FP_ID = "9"
def build_frontier_ws_url(session: DouyinImSession, device_id: str) -> Optional[str]:
token = session.cookies.get("sessionid") or session.cookies.get("sessionid_ss") or ""
if not token or not device_id:
return None
access_key_raw = f"{FP_ID}{APP_KEY}{device_id}f8a69f1719916z"
access_key = hashlib.md5(access_key_raw.encode("utf-8")).hexdigest()
params = {
"aid": "6383",
"device_platform": "douyin_pc",
"fpid": FP_ID,
"device_id": device_id,
"token": token,
"access_key": access_key,
}
query = "&".join(f"{k}={v}" for k, v in params.items())
return f"wss://frontier-im.douyin.com/ws/v2?{query}"
def fetch_device_id(session: DouyinImSession) -> str:
"""Call Douyin user query API to obtain device/web id."""
auth = DouyinAuth()
auth.perepare_auth(
session.cookie_header(),
session.web_protect_str,
session.keys_str,
)
url = "https://www.douyin.com/aweme/v1/web/query/user"
headers = {
"User-Agent": session.user_agent,
"Referer": "https://www.douyin.com/discover",
"Accept": "application/json, text/plain, */*",
"Cookie": session.cookie_header(),
}
params = {
"device_platform": "webapp",
"aid": "6383",
"channel": "channel_pc_web",
"publish_video_strategy_type": "2",
"verifyFp": auth.cookie.get("s_v_web_id", "") if auth.cookie else "",
"fp": auth.cookie.get("s_v_web_id", "") if auth.cookie else "",
"webid": generate_webid(auth, "https://www.douyin.com/discover"),
"msToken": generate_msToken(),
}
query = splice_url(params)
params["a_bogus"] = generate_a_bogus(query, user_agent=session.user_agent)
try:
resp = requests.get(
url,
params=params,
headers=headers,
cookies=auth.cookie,
verify=False,
timeout=15,
)
data = resp.json()
device_id = str(data.get("id") or data.get("device_id") or "")
if device_id.isdigit():
logger.info(f"Fetched device_id: {device_id[:20]}...")
return device_id
logger.warning(f"query/user returned non-numeric id: {device_id[:32]!r}")
except Exception as e:
logger.warning(f"fetch_device_id failed: {e}")
return ""
def resolve_frontier_device_id(session: DouyinImSession) -> str:
"""Frontier WS requires numeric device_id from Douyin query/user API."""
current = str(session.device_id or session.web_id or "")
if current.isdigit():
return current
fetched = fetch_device_id(session)
if fetched and str(fetched).isdigit():
session.device_id = str(fetched)
logger.info(f"Using numeric device_id for frontier WS: {fetched[:16]}...")
return str(fetched)
logger.warning(
f"Invalid frontier device_id={current[:24]!r}; "
"expected numeric id from query/user API"
)
return ""
def ensure_frontier_ws(session: DouyinImSession) -> Optional[str]:
"""Ensure session has a usable frontier WebSocket URL."""
session.sanitize_ws_urls()
# 方案 A:若已有浏览器抓到的“真实” frontier URL(带 sdk_cert/ts_sign),
# 直接沿用,不要用我们自己推导 token/access_key 的版本去覆盖它。
for url in session.ws_urls:
if is_frontier_ws_url(url) and "sdk_cert=" in url:
session.ws_urls = [url]
logger.info("Using captured real frontier WS URL (with sdk_cert)")
return url
device_id = resolve_frontier_device_id(session)
if not device_id:
session.ws_urls = []
return None
built = build_frontier_ws_url(session, device_id)
if built:
session.ws_urls = [built]
logger.info("Built frontier WS URL from cookie session")
return built
return None
@@ -0,0 +1,38 @@
"""本系统当前托管中的账号 UID 注册表。
用途:避免两个都在本系统托管的账号互相自动回复,形成无限回环——
这种高频来回发送是触发抖音风控(7911)/业务拒绝(8004)的常见根因。
"""
import logging
logger = logging.getLogger("douyin_im.hosted_registry")
_HOSTED_UIDS: set[int] = set()
def register(uid) -> None:
try:
u = int(uid)
except (TypeError, ValueError):
return
if u:
_HOSTED_UIDS.add(u)
logger.info(f"Registered hosted uid {u} (total={len(_HOSTED_UIDS)})")
def unregister(uid) -> None:
try:
u = int(uid)
except (TypeError, ValueError):
return
_HOSTED_UIDS.discard(u)
logger.info(f"Unregistered hosted uid {u} (total={len(_HOSTED_UIDS)})")
def is_hosted(uid) -> bool:
try:
u = int(uid)
except (TypeError, ValueError):
return False
return u in _HOSTED_UIDS
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,60 @@
"""KEFU_WS_DEBUG=1 时把 IM 收/发原始 content 写入 backend/ws_media_debug.log。"""
from __future__ import annotations
import json
import os
from datetime import datetime
from pathlib import Path
from typing import Any
_ENABLED: bool | None = None
_LOG_PATH: Path | None = None
def _is_enabled() -> bool:
global _ENABLED
if _ENABLED is None:
_ENABLED = os.getenv("KEFU_WS_DEBUG", "").strip().lower() in ("1", "true", "yes")
return _ENABLED
def _log_path() -> Path:
global _LOG_PATH
if _LOG_PATH is None:
backend_dir = Path(__file__).resolve().parents[2]
_LOG_PATH = backend_dir / "ws_media_debug.log"
return _LOG_PATH
def log_im_message(
*,
direction: str,
message_type: int | str,
conversation_id: str = "",
content: Any = None,
fields: dict[str, Any] | None = None,
) -> None:
if not _is_enabled():
return
try:
ts = datetime.now().isoformat()
if isinstance(content, (dict, list)):
content_s = json.dumps(content, ensure_ascii=False, separators=(",", ":"))
elif content is None:
content_s = ""
else:
content_s = str(content)
fields_s = ""
if fields:
fields_s = " | fields=" + json.dumps(fields, ensure_ascii=False, separators=(",", ":"))
line = (
f"{ts} {direction} type={message_type} conv={conversation_id} "
f"content={content_s}{fields_s}\n"
)
path = _log_path()
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "a", encoding="utf-8") as f:
f.write(line)
except Exception:
pass
+32
View File
@@ -0,0 +1,32 @@
"""Parse Douyin IM Response protobuf for conversation metadata."""
from __future__ import annotations
def extract_conv_meta_from_response_bytes(raw: bytes) -> dict[str, dict]:
"""Return {conversation_id: {conversation_short_id, ticket}} from IM API protobuf body."""
if not raw:
return {}
try:
from .static import Response_pb2 as ResponseProto
response_proto = ResponseProto.Response()
response_proto.ParseFromString(raw)
body = response_proto.body
out: dict[str, dict] = {}
for field in (
"create_conversation_v2_body",
"get_conversation_info_list_v2_response_body",
):
if not body.HasField(field):
continue
conv_body = getattr(body, field)
for conv in conv_body.conversation_info_list:
if not conv.conversation_id:
continue
out[conv.conversation_id] = {
"conversation_short_id": str(conv.conversation_short_id),
"ticket": conv.ticket,
}
return out
except Exception:
return {}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,110 @@
"""抖音 IM 社交互动类消息(如 aweType=11400 点赞比心)构造。
此类消息通常由客户端在作品互动链路上产生;Web IM 发送时 content JSON 结构与分享视频类似,
message_type 实测多为 8(与 aweType=800 视频分享同族)。若发送失败可尝试 im_message_type=114。
"""
from __future__ import annotations
import copy
import os
from typing import Any
# 与 aweType=800 视频分享消息同族的 protobuf message_type
MSG_TYPE_INTERACTION_DEFAULT = 8
# 用户抓包样本:「向对方的点赞比了个心」
LIKE_HEART_SAMPLE: dict[str, Any] = {
"aweType": 11400,
"comment": "",
"content_thumb": {
"uri": "100x100/aweme-avatar/tos-cn-i-0813c001_2e91b5a5a18345b196038a72330a917f",
"url_list": [
"https://p3.douyinpic.com/aweme/100x100/aweme-avatar/tos-cn-i-0813c001_2e91b5a5a18345b196038a72330a917f.jpeg?biz_tag=aweme_im&from=3782654143&s=im_102&sc=avatar",
],
},
"content_title": "",
"cover_height": 720.0,
"cover_url": {
"data_size": 0,
"height": 720,
"uri": "tos-cn-p-0015c000-ce/o8fy5FTAEBBiTUwv8VBonpIjfEFU0S9IKixAPC",
"url_list": [
"https://p3-sign.douyinpic.com/obj/tos-cn-p-0015c000-ce/o8fy5FTAEBBiTUwv8VBonpIjfEFU0S9IKixAPC?lk3s=9698d6d2&x-expires=1814252400&x-signature=oOR8Kz7HyoL1tcn%2B7xyD7ZEcnMU%3D&from=2526598866&s=im_102&se=false&sc=cover&biz_tag=aweme_im&l=021782716851230fdbddc0c0001054a000000000000005676aa83",
],
"width": 720,
},
"cover_width": 720.0,
"createdAt": 0,
"is_card": False,
"itemId": "7636216221181053883",
"msgHint": "",
"push_internal_object_title": "对你的点赞比了个心",
"push_internal_object_title_v2": "",
"ref_type": 2,
"scene_type": 0,
"subject_title": "向对方的点赞比了个心",
"subject_title_v2": "",
"uid": "101081217900",
"without_panel": 0,
}
def default_interaction_message_type() -> int:
raw = (os.getenv("KEFU_INTERACTION_MSG_TYPE") or "").strip()
if raw.isdigit():
return int(raw)
return MSG_TYPE_INTERACTION_DEFAULT
def _merge_media_object(base: dict[str, Any], override: Any) -> dict[str, Any]:
if isinstance(override, dict):
merged = copy.deepcopy(base)
merged.update(override)
return merged
return copy.deepcopy(base)
def build_like_heart_payload(spec: dict[str, Any], *, my_uid: str = "") -> dict[str, Any]:
"""构造「对点赞比了个心」互动消息体(aweType=11400)。"""
payload = copy.deepcopy(LIKE_HEART_SAMPLE)
if spec.get("payload") and isinstance(spec["payload"], dict):
payload.update(copy.deepcopy(spec["payload"]))
if spec.get("item_id") or spec.get("itemId"):
payload["itemId"] = str(spec.get("item_id") or spec.get("itemId"))
if spec.get("subject_title"):
payload["subject_title"] = str(spec["subject_title"])
if spec.get("push_internal_object_title"):
payload["push_internal_object_title"] = str(spec["push_internal_object_title"])
if spec.get("ref_type") is not None:
payload["ref_type"] = int(spec["ref_type"])
if spec.get("aweType") is not None:
payload["aweType"] = int(spec["aweType"])
uid = str(spec.get("uid") or my_uid or "").strip()
if uid:
payload["uid"] = uid
if spec.get("content_thumb") is not None:
payload["content_thumb"] = _merge_media_object(
payload.get("content_thumb") or {}, spec["content_thumb"]
)
if spec.get("cover_url") is not None:
payload["cover_url"] = _merge_media_object(
payload.get("cover_url") or {}, spec["cover_url"]
)
if spec.get("cover_width") is not None:
payload["cover_width"] = float(spec["cover_width"])
if spec.get("cover_height") is not None:
payload["cover_height"] = float(spec["cover_height"])
return payload
def resolve_interaction_message_type(spec: dict[str, Any]) -> int:
for key in ("message_type", "im_message_type"):
val = spec.get(key)
if val is not None and str(val).strip().isdigit():
return int(val)
return default_interaction_message_type()
@@ -0,0 +1,818 @@
"""私信消息内容解析、存储与展示(文本 / 图片 / 表情 / 语音 / 视频)。"""
from __future__ import annotations
import json
import re
from typing import Any
MSG_TYPE_TEXT = 7
MSG_TYPE_STICKER = 5
MSG_TYPE_VOICE = 17
MSG_TYPE_IMAGE = 27
MSG_TYPE_VIDEO = 8
MSG_TYPE_LINK_CARD = 70
MSG_TYPE_VIDEO_SHARE = 8 # 视频分享 / 部分社交互动(aweType 800、11400 等)
_TYPE_LABELS = {
"text": "文本",
"image": "图片",
"sticker": "表情",
"voice": "语音",
"video": "视频",
"link": "链接",
"hyperlink": "超链接",
"link_card": "超链接",
}
_PLACEHOLDER_MARKERS = {
"[表情包]",
"[语音]",
"[图片]",
"[视频]",
"[未读消息]",
}
_URI_HINT_RE = re.compile(
r"(tos-cn|aweme-|voice/|ies-music|\.mp3|\.m4a|\.aac|\.mpeg|\.webp|\.jpeg|\.jpg|\.png|\.gif)",
re.I,
)
_AUDIO_URL_RE = re.compile(
r"(douyin-user-audio|/audio/|sc=audio|voice/|ies-music|\.mp3|\.m4a|\.aac|\.mpeg|\.wav|\.ogg)",
re.I,
)
_VIDEO_URL_RE = re.compile(
r"(sc=video|/video/|\.mp4|\.mov|\.webm|\.m3u8)",
re.I,
)
_MEDIA_STRING_KEYS = (
"url",
"uri",
"main_url",
"download_url",
"remote_url",
"encrypt_url",
"play_url",
"secret_url",
"audio_url",
"video_url",
"cover_url",
"local_path",
)
_MEDIA_NESTED_KEYS = (
"resource_url",
"static_url",
"animate_url",
"cover_url",
"thumb_url",
"origin_url",
"image",
"picture",
"pic",
"sticker",
"emoji",
"audio",
"voice",
"video",
"media",
"large_url",
"medium_url",
"thumb",
"avatar_thumb",
"play_url",
)
def _normalize_uri_path(raw: str) -> str:
path = (raw or "").strip().lstrip("/")
if path.startswith("obj/"):
path = path[4:]
return path
def uri_to_cdn_urls(uri: str, *, prefer_voice: bool = False) -> list[str]:
"""将抖音 IM 中的 uri / tos 路径转为可访问的 CDN URL 候选列表。"""
raw = (uri or "").strip()
if not raw:
return []
if raw.startswith("//"):
return [f"https:{raw}"]
if raw.startswith("http://") or raw.startswith("https://"):
return [raw]
path = _normalize_uri_path(raw)
if not path:
return []
candidates: list[str] = []
seen: set[str] = set()
def add(url: str) -> None:
url = (url or "").strip()
if url and url not in seen:
seen.add(url)
candidates.append(url)
lower = path.lower()
is_voice = prefer_voice or lower.startswith("voice/") or lower.endswith((".mp3", ".m4a", ".aac"))
is_image = (
not is_voice
and (
"tos-cn-i" in lower
or "aweme-" in lower
or lower.endswith((".jpeg", ".jpg", ".png", ".webp", ".gif"))
)
)
if is_voice:
for host in (
"sf6-cdn-tos.douyinstatic.com",
"sf3-cdn-tos.douyinstatic.com",
"lf3-static.bytednsdoc.com",
):
add(f"https://{host}/obj/{path}")
add(f"https://p3.douyinpic.com/obj/{path}")
if is_image or "tos-cn" in lower or "aweme" in lower:
add(f"https://p3.douyinpic.com/obj/{path}")
for size in ("720x720", "480x480", "300x300", "200x200", "100x100"):
add(f"https://p3.douyinpic.com/aweme/{size}/{path}")
add(f"https://p9-dy.byteimg.com/img/{path}")
add(f"https://p6-dy.byteimg.com/img/{path}")
add(f"https://p3.douyinpic.com/obj/{path}")
add(f"https://p3-sign.douyinpic.com/obj/{path}".replace("-sign", ""))
return candidates
def resolve_media_uri(uri: str, *, prefer_voice: bool = False) -> str:
urls = uri_to_cdn_urls(uri, prefer_voice=prefer_voice)
return urls[0] if urls else ""
def _looks_like_audio_url(value: str) -> bool:
raw = (value or "").strip()
return bool(raw and _AUDIO_URL_RE.search(raw))
def _looks_like_video_url(value: str) -> bool:
raw = (value or "").strip()
return bool(raw and _VIDEO_URL_RE.search(raw))
def _infer_media_type_from_url(url: str) -> str:
"""根据 URL 特征推断媒体类型(语音/视频/图片)。"""
if _looks_like_audio_url(url):
return "voice"
if _looks_like_video_url(url):
return "video"
return "image"
def _looks_like_media_uri(value: str) -> bool:
raw = (value or "").strip()
if not raw or raw.startswith("{"):
return False
if raw.startswith("http://") or raw.startswith("https://") or raw.startswith("//"):
return True
return bool(_URI_HINT_RE.search(raw))
def _resolve_string_media(value: str, *, prefer_voice: bool = False) -> tuple[str, str]:
raw = (value or "").strip()
if not raw:
return "", ""
if raw.startswith("//"):
return f"https:{raw}", raw
if raw.startswith("http://") or raw.startswith("https://"):
return raw, ""
if _looks_like_media_uri(raw):
return resolve_media_uri(raw, prefer_voice=prefer_voice), raw
return "", ""
def _valid_sticker_id(value: Any) -> str:
if value is None or value == "":
return ""
try:
if int(value) == 0:
return ""
except (TypeError, ValueError):
pass
sticker_id = str(value).strip()
return "" if sticker_id in ("0", "null", "None") else sticker_id
def _collect_media_candidates(value: Any, out: list[str], *, prefer_voice: bool = False, depth: int = 0) -> None:
if depth > 12:
return
if isinstance(value, str):
raw = value.strip()
if raw.startswith("http://") or raw.startswith("https://") or raw.startswith("//"):
url, _ = _resolve_string_media(raw, prefer_voice=prefer_voice)
if url:
out.append(url)
return
if isinstance(value, dict):
for list_key in ("url_list", "urls", "urlList"):
urls = value.get(list_key)
if isinstance(urls, list):
for item in urls:
_collect_media_candidates(item, out, prefer_voice=prefer_voice, depth=depth + 1)
for key in _MEDIA_STRING_KEYS:
direct = value.get(key)
if isinstance(direct, str):
url, _ = _resolve_string_media(direct, prefer_voice=prefer_voice)
if url:
out.append(url)
for nested_key in _MEDIA_NESTED_KEYS:
_collect_media_candidates(value.get(nested_key), out, prefer_voice=prefer_voice, depth=depth + 1)
for nested in value.values():
if isinstance(nested, (dict, list)):
_collect_media_candidates(nested, out, prefer_voice=prefer_voice, depth=depth + 1)
return
if isinstance(value, list):
for item in value:
_collect_media_candidates(item, out, prefer_voice=prefer_voice, depth=depth + 1)
def _pick_http_url(value: Any, *, prefer_voice: bool = False) -> str:
candidates: list[str] = []
_collect_media_candidates(value, candidates, prefer_voice=prefer_voice)
return candidates[0] if candidates else ""
def _pick_media_uri(value: Any) -> str:
if isinstance(value, str) and _looks_like_media_uri(value) and not value.strip().startswith("http"):
return _normalize_uri_path(value)
if isinstance(value, dict):
for key in ("uri", "local_path", "remote_url"):
direct = value.get(key)
if isinstance(direct, str) and _looks_like_media_uri(direct) and not direct.strip().startswith("http"):
return _normalize_uri_path(direct)
for nested_key in _MEDIA_NESTED_KEYS:
uri = _pick_media_uri(value.get(nested_key))
if uri:
return uri
for nested in value.values():
if isinstance(nested, (dict, list)):
uri = _pick_media_uri(nested)
if uri:
return uri
if isinstance(value, list):
for item in value:
uri = _pick_media_uri(item)
if uri:
return uri
return ""
def _coerce_message_type(value: Any, default: int = MSG_TYPE_TEXT) -> int:
try:
if value is None or value == "":
return default
return int(value)
except (TypeError, ValueError):
return default
def _parse_content_json(content_raw: str | dict | None) -> dict[str, Any]:
if isinstance(content_raw, dict):
data = content_raw
else:
raw = str(content_raw or "").strip()
if raw.startswith("{"):
try:
parsed = json.loads(raw)
if isinstance(parsed, dict):
data = parsed
else:
return {}
except json.JSONDecodeError:
return {}
else:
return {}
for nested_key in ("ext", "ai_ext", "extra", "payload", "data"):
nested = data.get(nested_key)
if isinstance(nested, str) and nested.strip().startswith("{"):
try:
nested_data = json.loads(nested)
if isinstance(nested_data, dict):
merged = {**nested_data, **data}
data = merged
except json.JSONDecodeError:
pass
return data
def _safe_int(value: Any) -> int | None:
try:
if value is None or value == "":
return None
return int(value)
except (TypeError, ValueError):
return None
def format_im_message(content_raw: str | dict | None, message_type: int = MSG_TYPE_TEXT) -> dict[str, Any]:
"""将 IM 原始 content 解析为统一结构 {type, text, url, ...}。"""
content_json = _parse_content_json(content_raw)
embedded_type = _coerce_message_type(
content_json.get("message_type")
or content_json.get("messageType")
or content_json.get("msg_type"),
message_type,
)
if embedded_type != MSG_TYPE_TEXT:
message_type = embedded_type
_EMPTY_MEDIA_DEFAULTS = {
MSG_TYPE_IMAGE: ("image", "[图片]"),
MSG_TYPE_STICKER: ("sticker", "[表情包]"),
MSG_TYPE_VOICE: ("voice", "[语音]"),
MSG_TYPE_VIDEO: ("video", "[视频]"),
MSG_TYPE_LINK_CARD: ("hyperlink", "[超链接]"),
}
if not content_json:
raw = str(content_raw or "").strip()
if not raw:
# 抖音相册图片(type 27)/部分语音等会以「空 content」推送,URL 不随推送下发。
# 不能直接丢弃,否则消息「收不到」;这里按类型返回占位,URL 留空待后续补取。
if message_type in _EMPTY_MEDIA_DEFAULTS:
t, txt = _EMPTY_MEDIA_DEFAULTS[message_type]
return {"type": t, "text": txt}
return {"type": "text", "text": ""}
if raw in _PLACEHOLDER_MARKERS:
mapping = {
"[图片]": "image",
"[表情包]": "sticker",
"[语音]": "voice",
"[视频]": "video",
}
return {"type": mapping.get(raw, "text"), "text": raw}
if message_type == MSG_TYPE_TEXT:
return {"type": "text", "text": raw}
content_json = {"text": raw}
prefer_voice = message_type == MSG_TYPE_VOICE or bool(content_json.get("audio") or content_json.get("voice"))
url = _pick_http_url(content_json, prefer_voice=prefer_voice)
media_uri = _pick_media_uri(content_json)
if not url and media_uri:
url = resolve_media_uri(media_uri, prefer_voice=prefer_voice)
duration = _safe_int(
content_json.get("duration")
or content_json.get("audio_duration")
or content_json.get("video_duration")
)
width = _safe_int(content_json.get("width") or content_json.get("w"))
height = _safe_int(content_json.get("height") or content_json.get("h"))
def _media_payload(msg_type: str, text: str, **extra: Any) -> dict[str, Any]:
payload: dict[str, Any] = {"type": msg_type, "text": text}
if url:
payload["url"] = url
elif media_uri:
payload["uri"] = media_uri
payload.update({k: v for k, v in extra.items() if v not in (None, "", 0)})
return payload
# 语音/视频也会带 resource_url,不能仅凭该字段判为图片;优先按类型与 URL 特征识别。
is_voice = (
message_type == MSG_TYPE_VOICE
or bool(content_json.get("audio") or content_json.get("voice"))
or (url and _looks_like_audio_url(url))
)
is_video = (
message_type == MSG_TYPE_VIDEO
or bool(content_json.get("video"))
or (url and _looks_like_video_url(url))
)
if is_voice and not is_video:
return _media_payload("voice", "[语音]", duration=duration)
if is_video:
return _media_payload("video", "[视频]", duration=duration, width=width, height=height)
has_image_hint = (
message_type == MSG_TYPE_IMAGE
or content_json.get("image")
or content_json.get("inline_pic")
or (
content_json.get("resource_url")
and not (url and (_looks_like_audio_url(url) or _looks_like_video_url(url)))
)
)
if has_image_hint:
# 抖音相册私图(biz_tag=aweme_im)的大图 URL 是加密内容,浏览器无法直接渲染;
# 但 content 内嵌 inline_pic(base64 WEBP 缩略图),直接转 data URI 即可显示。
inline = content_json.get("inline_pic")
if isinstance(inline, str) and inline.strip():
b64 = re.sub(r"\s+", "", inline)
data_uri = f"data:image/webp;base64,{b64}"
payload = {"type": "image", "text": "[图片]", "url": data_uri}
if width:
payload["width"] = width
if height:
payload["height"] = height
return payload
return _media_payload("image", "[图片]", width=width, height=height)
if message_type == MSG_TYPE_STICKER or content_json.get("static_url") or content_json.get("animate_url") or _valid_sticker_id(
content_json.get("sticker_id") or content_json.get("id")
):
sticker_id = _valid_sticker_id(content_json.get("sticker_id") or content_json.get("id"))
return _media_payload(
"sticker",
"[表情包]",
sticker_id=sticker_id,
name=str(content_json.get("display_name") or content_json.get("name") or ""),
)
awe_type = content_json.get("aweType")
if awe_type == 11400 or (
content_json.get("subject_title") and content_json.get("ref_type") is not None
):
title = str(
content_json.get("subject_title")
or content_json.get("push_internal_object_title")
or content_json.get("content_title")
or ""
).strip()
item_id = str(content_json.get("itemId") or content_json.get("item_id") or "").strip()
payload: dict[str, Any] = {
"type": "interaction",
"text": title or "[互动消息]",
"title": title or "[互动消息]",
"awe_type": awe_type,
}
if item_id:
payload["item_id"] = item_id
payload["url"] = f"https://www.douyin.com/video/{item_id}"
cover = content_json.get("cover_url")
if isinstance(cover, dict):
urls = cover.get("url_list")
if isinstance(urls, list) and urls:
payload["cover_url"] = str(urls[0])
return payload
link_card = _parse_link_card_payload(content_json, message_type)
if link_card:
return link_card
rich_link = _parse_rich_text_link(content_json)
if rich_link:
return rich_link
text = (
str(content_json.get("text") or content_json.get("content") or content_json.get("message") or "")
).strip()
if not text and url:
inferred = _infer_media_type_from_url(url)
if inferred == "voice":
return {"type": "voice", "text": "[语音]", "url": url, "duration": duration}
if inferred == "video":
return {"type": "video", "text": "[视频]", "url": url, "duration": duration}
if message_type == MSG_TYPE_IMAGE:
return {"type": "image", "text": "[图片]", "url": url, "width": width, "height": height}
if message_type == MSG_TYPE_STICKER:
return {"type": "sticker", "text": "[表情包]", "url": url}
if message_type == MSG_TYPE_VOICE:
return {"type": "voice", "text": "[语音]", "url": url, "duration": duration}
if message_type == MSG_TYPE_VIDEO:
return {"type": "video", "text": "[视频]", "url": url, "duration": duration}
final_text = text or str(content_raw or "").strip()
multiline_link = _parse_multiline_hyperlink_text(final_text)
if multiline_link and message_type == MSG_TYPE_TEXT:
return multiline_link
emoji = _resolve_text_emoji(final_text)
if emoji:
return emoji
return {"type": "text", "text": final_text}
def _parse_link_card_payload(content_json: dict[str, Any], message_type: int) -> dict[str, Any] | None:
if content_json.get("aweType") == 11400:
return None
link_info = content_json.get("link_info")
if not isinstance(link_info, dict):
link_info = {}
has_link = (
message_type == MSG_TYPE_LINK_CARD
or link_info
or content_json.get("link_url")
or (isinstance(content_json.get("cover_url"), str) and content_json.get("cover_url"))
)
if not has_link:
return None
title = str(content_json.get("title") or link_info.get("title") or "").strip()
desc = str(
content_json.get("desc")
or content_json.get("description")
or link_info.get("desc")
or link_info.get("description")
or ""
).strip()
url = str(
content_json.get("link_url")
or content_json.get("url")
or link_info.get("url")
or link_info.get("link_url")
or ""
).strip()
cover = str(content_json.get("cover_url") or link_info.get("cover_url") or "").strip()
text = title or desc or url or "[链接卡片]"
payload: dict[str, Any] = {
"type": "hyperlink",
"text": text,
"title": title,
"desc": desc,
}
if url:
payload["url"] = url
if cover:
payload["cover_url"] = cover
return payload
def _parse_multiline_hyperlink_text(text: str) -> dict[str, Any] | None:
"""网页 IM 多行超链接:标题\\n描述\\nhttps://...(type=7 发出,客户端解析为网页链接卡)。"""
raw = (text or "").strip()
if not raw or "\n" not in raw:
return None
lines = [ln.strip() for ln in raw.split("\n") if ln.strip()]
if len(lines) < 2:
return None
url = lines[-1]
if not url.lower().startswith(("http://", "https://")):
return None
if len(lines) == 2:
return {
"type": "hyperlink",
"text": lines[0] or url,
"title": lines[0],
"desc": "",
"url": url,
}
return {
"type": "hyperlink",
"text": lines[0] or url,
"title": lines[0],
"desc": "\n".join(lines[1:-1]),
"url": url,
}
def _parse_rich_text_link(content_json: dict[str, Any]) -> dict[str, Any] | None:
rich = content_json.get("richTextInfos")
if not isinstance(rich, list):
return None
for item in rich:
if not isinstance(item, dict):
continue
link = str(item.get("link") or item.get("url") or "").strip()
if not link:
continue
text = str(item.get("text") or item.get("display_text") or link).strip()
return {"type": "link", "text": text or link, "url": link}
return None
def _resolve_text_emoji(text: str) -> dict[str, Any] | None:
"""文字表情 [酷拽] 等:查标准表情表,命中则转成可显示的贴纸。"""
stripped = (text or "").strip()
if not stripped or not (stripped.startswith("[") and stripped.endswith("]")):
return None
try:
from .emoji_pack import looks_like_emoji_token, lookup_emoji_url
if not looks_like_emoji_token(stripped):
return None
url = lookup_emoji_url(stripped)
if url:
return {
"type": "sticker",
"text": stripped,
"url": url,
"name": stripped.strip("[]"),
}
except Exception:
pass
return None
def parse_incoming_message(data: dict[str, Any]) -> str:
"""从 IM API / WebSocket 消息 dict 提取并序列化展示内容。"""
if not isinstance(data, dict):
return str(data or "").strip()
msg_type = _coerce_message_type(
data.get("message_type") or data.get("messageType") or data.get("msg_type"),
MSG_TYPE_TEXT,
)
content_raw = (
data.get("content")
or data.get("message")
or data.get("msg")
or data.get("lastMessage")
or data.get("last_msg")
or data.get("preview")
or data.get("brief")
or ""
)
if isinstance(content_raw, dict):
if not msg_type or msg_type == MSG_TYPE_TEXT:
msg_type = _coerce_message_type(
content_raw.get("message_type")
or content_raw.get("messageType")
or content_raw.get("msg_type"),
msg_type,
)
parsed = format_im_message(content_raw, msg_type)
return serialize_message_content(parsed)
if isinstance(content_raw, str):
raw = content_raw.strip()
if raw.startswith("{"):
parsed = format_im_message(raw, msg_type)
if parsed.get("type") != "text" or parsed.get("url") or msg_type != MSG_TYPE_TEXT:
return serialize_message_content(parsed)
if raw in _PLACEHOLDER_MARKERS and msg_type != MSG_TYPE_TEXT:
parsed = format_im_message(raw, msg_type)
return serialize_message_content(parsed)
if msg_type != MSG_TYPE_TEXT:
parsed = format_im_message(raw, msg_type)
return serialize_message_content(parsed)
return raw
return ""
def serialize_message_content(msg: dict[str, Any]) -> str:
"""序列化写入 message_logs / reply_content。"""
msg_type = (msg.get("type") or "text").strip()
if msg_type == "text":
text = str(msg.get("text") or "").strip()
return text
cleaned = {k: v for k, v in msg.items() if v not in (None, "", [], {})}
return json.dumps(cleaned, ensure_ascii=False, separators=(",", ":"))
def parse_stored_content(raw: str | None) -> dict[str, Any]:
"""解析数据库中的 message_content / reply_content。"""
text = (raw or "").strip()
if not text:
return {"type": "text", "text": ""}
if text.startswith("{"):
try:
data = json.loads(text)
if isinstance(data, dict) and data.get("type"):
if not data.get("url") and data.get("uri"):
prefer_voice = data.get("type") == "voice"
resolved = resolve_media_uri(str(data["uri"]), prefer_voice=prefer_voice)
if resolved:
data = {**data, "url": resolved}
url = str(data.get("url") or "").strip()
if url:
inferred = _infer_media_type_from_url(url)
current = data.get("type")
if current == "image" and inferred in ("voice", "video"):
data = {
**data,
"type": inferred,
"text": "[语音]" if inferred == "voice" else "[视频]",
}
elif current not in ("voice", "video", "image", "sticker") and inferred:
data = {**data, "type": inferred}
return data
except json.JSONDecodeError:
pass
if text in _PLACEHOLDER_MARKERS:
mapping = {
"[图片]": "image",
"[表情包]": "sticker",
"[语音]": "voice",
"[视频]": "video",
}
return {"type": mapping.get(text, "text"), "text": text}
return {"type": "text", "text": text}
def message_preview(raw: str | None) -> str:
"""会话列表/日志摘要。"""
msg = parse_stored_content(raw)
msg_type = msg.get("type") or "text"
if msg_type == "text":
return str(msg.get("text") or "")
label = _TYPE_LABELS.get(msg_type, msg.get("text") or "[消息]")
extra = str(msg.get("name") or "").strip()
if extra and msg_type == "sticker":
return f"[表情] {extra}"
return str(msg.get("text") or label)
def normalize_outgoing_content(
content: str = "",
message_type: str | None = None,
media_url: str | None = None,
sticker_url: str | None = None,
width: int | None = None,
height: int | None = None,
sticker_id: str | None = None,
) -> str:
"""构造可发送/可落库的 content 字符串。"""
raw = (content or "").strip()
parsed_json: dict[str, Any] | None = None
if raw.startswith("{"):
try:
data = json.loads(raw)
if isinstance(data, dict):
parsed_json = data
except json.JSONDecodeError:
pass
if parsed_json:
merged = dict(parsed_json)
if merged.get("type") in ("raw_im", "interaction"):
return serialize_message_content(merged)
if merged.get("aweType") == 11400 and not merged.get("type"):
wrapped = {
"type": "interaction",
"variant": "like_heart",
"payload": merged,
}
return serialize_message_content(wrapped)
if width and not merged.get("width"):
merged["width"] = width
if height and not merged.get("height"):
merged["height"] = height
if sticker_id and not merged.get("sticker_id"):
merged["sticker_id"] = sticker_id
url = (media_url or sticker_url or "").strip()
if url and not merged.get("url"):
merged["url"] = url
if merged.get("type"):
return serialize_message_content(merged)
explicit_type = (message_type or "").strip().lower()
if explicit_type in ("image", "sticker", "voice", "video", "text"):
if explicit_type == "text":
return (content or "").strip()
payload: dict[str, Any] = {"type": explicit_type}
url = (media_url or sticker_url or "").strip()
if url:
payload["url"] = url
if explicit_type == "sticker" and sticker_id:
payload["sticker_id"] = sticker_id
if width:
payload["width"] = width
if height:
payload["height"] = height
text = (content or "").strip()
if text:
payload["text"] = text
elif explicit_type == "image":
payload["text"] = "[图片]"
elif explicit_type == "sticker":
payload["text"] = "[表情包]"
return serialize_message_content(payload)
raw = (content or "").strip()
if raw.startswith("{"):
try:
data = json.loads(raw)
if isinstance(data, dict) and data.get("type"):
return serialize_message_content(data)
except json.JSONDecodeError:
pass
return raw
def is_media_message(raw: str | None) -> bool:
return parse_stored_content(raw).get("type") not in (None, "text")
def format_system_log_message(raw: str | None) -> str:
"""系统诊断日志中的消息摘要。"""
msg = parse_stored_content(raw)
msg_type = msg.get("type") or "text"
if msg_type == "text":
return str(msg.get("text") or "")
parts = [message_preview(raw)]
url = str(msg.get("url") or "").strip()
if url:
parts.append(f"URL: {url}")
duration = msg.get("duration")
if duration:
parts.append(f"时长: {duration}s")
return " | ".join(parts)
def extract_urls_from_detail(detail: str | None) -> list[str]:
if not detail:
return []
return re.findall(r"https?://[^\s\]|))\"']+", detail)
+258
View File
@@ -0,0 +1,258 @@
"""极简 protobuf wire 解码器(无第三方依赖)。
用于解析抖音 IM 发送私信的响应:官方 Response.proto 只建模了
create/get_info/new_message_notify 三种 body,没有“发送消息响应”,
导致仅凭 error_desc 为空就误判为发送成功。这里直接按 wire 格式解码,
读取真实的 status_code / server_message_id,判定是否真的投递成功。
"""
import json
from typing import Any, Optional
def _format_status_json(status_json: dict) -> str:
"""把内嵌 status JSON 格式化为更可读的失败原因。"""
code = status_json.get("status_code")
raw_check = status_json.get("raw_check_code")
decision = status_json.get("decision_type")
parts = [f"status_code={code}"]
if raw_check is not None:
parts.append(f"raw_check_code={raw_check}")
if decision:
parts.append(f"decision_type={decision}")
return ";".join(parts)
def _read_varint(buf: bytes, i: int) -> tuple[int, int]:
shift = 0
result = 0
n = len(buf)
while i < n:
b = buf[i]
i += 1
result |= (b & 0x7F) << shift
if not (b & 0x80):
return result, i
shift += 7
if shift > 70:
break
raise ValueError("truncated varint")
def decode_fields(buf: bytes) -> list[tuple[int, int, Any]]:
"""返回 [(field_num, wire_type, value), ...]。
wire_type: 0=varint(int), 1=64bit(int), 2=length-delimited(bytes), 5=32bit(int)
"""
out: list[tuple[int, int, Any]] = []
i = 0
n = len(buf)
while i < n:
key, i = _read_varint(buf, i)
field = key >> 3
wt = key & 7
if wt == 0:
val, i = _read_varint(buf, i)
out.append((field, wt, val))
elif wt == 2:
ln, i = _read_varint(buf, i)
val = buf[i:i + ln]
i += ln
out.append((field, wt, val))
elif wt == 5:
val = int.from_bytes(buf[i:i + 4], "little")
i += 4
out.append((field, wt, val))
elif wt == 1:
val = int.from_bytes(buf[i:i + 8], "little")
i += 8
out.append((field, wt, val))
else:
raise ValueError(f"unsupported wire type {wt}")
return out
def _collect_big_varints(buf: bytes, acc: list[int], depth: int = 0) -> None:
"""递归收集疑似 ID 的大整数(server_message_id / short_id 等都是大数)。"""
if depth > 6:
return
try:
fields = decode_fields(buf)
except Exception:
return
for _field, wt, val in fields:
if wt == 0 and isinstance(val, int) and val > 10 ** 12:
acc.append(val)
elif wt == 2 and isinstance(val, (bytes, bytearray)) and val:
_collect_big_varints(bytes(val), acc, depth + 1)
def _extract_status_json(raw: bytes) -> Optional[dict]:
"""抖音发送响应的 body 内嵌一段 JSON:{"status_code":x,"tips":"...","status_msg":{...}}。
这才是“消息是否真正投递”的权威结论(status_code=0 才是真成功)。
顶层 message=OK 只是接口层面的“已受理”,不代表已投递。
"""
marker = b'"status_code"'
idx = raw.find(marker)
if idx < 0:
return None
start = raw.rfind(b"{", 0, idx)
if start < 0:
return None
depth = 0
in_str = False
esc = False
end = -1
for i in range(start, len(raw)):
c = raw[i]
if in_str:
if esc:
esc = False
elif c == 0x5C: # backslash
esc = True
elif c == 0x22: # quote
in_str = False
continue
if c == 0x22:
in_str = True
elif c == 0x7B: # {
depth += 1
elif c == 0x7D: # }
depth -= 1
if depth == 0:
end = i + 1
break
if end < 0:
return None
try:
return json.loads(raw[start:end].decode("utf-8", "ignore"))
except Exception:
return None
def analyze_send_response(raw: bytes) -> dict:
"""分析“发送私信”的 protobuf 响应,判定是否真正投递成功。
顶层 Response 字段(见 Response.proto):
1=cmd, 2=sequence_id, 3=error_desc(string), 4=message(string),
5=inbox_type, 6=body(ResponseBody)。
注意:顶层没有 status_code 字段。真正“消息已写入服务端”的标志是
body(field 6) 里带有服务端分配的 server_message_id(大整数)。
sequence_id(field 2) 也是大整数,因此只在 body 内部查找 message_id,
避免把 sequence_id 误当成投递成功标志。
返回:
ok: 是否真正发送成功(body 内带服务端 message_id,或 message=OK 且有 body)
cmd: 顶层 cmd
message: 顶层 message 文本(field 4)
error_desc: 顶层 error_desc 文本(field 3)
server_message_id: body 内服务端消息 ID(投递成功的强信号)
has_body: 是否带 body
summary: 顶层字段概览 + hex 片段,便于排查
"""
info = {
"ok": False,
"cmd": None,
"status": None,
"status_code": None,
"raw_check_code": None,
"delivered_with_notice": False,
"status_reason": "",
"message": "",
"error_desc": "",
"server_message_id": None,
"has_body": False,
"summary": "",
}
if not raw:
info["summary"] = "空响应"
return info
try:
fields = decode_fields(raw)
except Exception as e:
info["summary"] = f"解码失败: {e}; hex={raw[:120].hex()}"
return info
body = None
parts = []
for field, wt, val in fields:
if field == 1 and wt == 0:
info["cmd"] = val
elif field == 3 and wt == 2:
try:
info["error_desc"] = bytes(val).decode("utf-8", "ignore")
except Exception:
pass
elif field == 4 and wt == 2:
try:
info["message"] = bytes(val).decode("utf-8", "ignore")
except Exception:
pass
elif field == 6 and wt == 2:
body = bytes(val)
info["has_body"] = len(body) > 0
if wt == 0:
parts.append(f"{field}=int:{val}")
elif wt == 2:
parts.append(f"{field}=bytes[{len(val)}]")
else:
parts.append(f"{field}={val}")
info["summary"] = " ".join(parts) + f" | hex={raw[:120].hex()}"
# 只在 body 内部查找服务端 message_id(避免误用顶层 sequence_id)
if body:
ids: list[int] = []
_collect_big_varints(body, ids)
if ids:
info["server_message_id"] = max(ids)
# 权威结论:body 内嵌 JSON 的 status_code(0 才是真成功)
status_json = _extract_status_json(raw)
if status_json is not None:
info["status_code"] = status_json.get("status_code")
info["raw_check_code"] = status_json.get("raw_check_code")
tips = (status_json.get("tips") or "").strip()
status_msg = status_json.get("status_msg")
msg_text = ""
if isinstance(status_msg, dict):
# 抖音把人类可读提示放在 status_msg.msg_content.tips
mc = status_msg.get("msg_content")
if isinstance(mc, dict):
msg_text = (mc.get("tips") or mc.get("content") or "").strip()
if not msg_text:
msg_text = (
status_msg.get("toast")
or status_msg.get("content")
or status_msg.get("msg")
or ""
)
elif isinstance(status_msg, str):
msg_text = status_msg
info["status_reason"] = tips or msg_text or _format_status_json(status_json)
msg_ok = info["message"].strip().upper() == "OK"
# 优先用 status_code 判定:明确给了 status_code 就以它为准(0=成功,非0=另判)
if info["status_code"] is not None:
if info["status_code"] == 0 and not info["error_desc"]:
info["ok"] = True
elif msg_ok and not info["error_desc"] and info["server_message_id"] is not None:
# message=OK + server_message_id:消息已写入服务端。
# type=70 网页链接卡常见 status_code=8004 + raw_check_code=1,仍正常投递,
# 与是否互关无关;勿仅凭 8004 判失败。
info["ok"] = True
if info["status_code"] != 0 or info["raw_check_code"] not in (None, 0):
info["delivered_with_notice"] = True
else:
info["ok"] = False
else:
# 没有内嵌 status_code 时,退回“message=OK 且 body 内有服务端 message_id”
info["ok"] = bool(
not info["error_desc"]
and msg_ok
and info["server_message_id"] is not None
)
return info
@@ -0,0 +1,192 @@
"""私信对方用户资料抓取(昵称 / 头像 / UID)。"""
from __future__ import annotations
import asyncio
import logging
from typing import Any, Optional
import requests
from rpa_engine.device_profiles import resolve_user_agent
from .auth import DouyinAuth
from .conv_util import resolve_peer_uid
from .dy_util import (
DEFAULT_USER_AGENT,
generate_a_bogus,
generate_msToken,
generate_webid,
splice_url,
)
from .protocol import _pick_avatar_url
from .session import DouyinImSession
logger = logging.getLogger("douyin_im.peer_profile")
_profile_cache: dict[str, dict[str, str]] = {}
def _cache_key(account_id: int, peer_uid: str) -> str:
return f"{account_id}:{peer_uid}"
def _pick_str(data: dict, *keys: str) -> str:
for key in keys:
value = data.get(key)
if value is not None and str(value).strip():
return str(value).strip()
return ""
def _extract_profile_from_payload(data: Any) -> dict[str, str]:
if not isinstance(data, dict):
return {}
nodes = [data, data.get("user"), data.get("user_info"), data.get("data")]
for node in nodes:
if not isinstance(node, dict):
continue
uid = _pick_str(node, "uid", "user_id", "user_uid", "id")
nickname = _pick_str(
node,
"nickname",
"nick_name",
"unique_id",
"display_name",
"name",
)
avatar = _pick_avatar_url(node)
if uid or nickname or avatar:
return {"uid": uid, "nickname": nickname, "avatar_url": avatar}
return {}
def _requests_proxies() -> dict | None:
try:
from rpa_engine.runtime_config import requests_proxies
return requests_proxies()
except Exception:
return None
def _build_auth(session: DouyinImSession) -> tuple[DouyinAuth, str]:
auth = DouyinAuth()
auth.perepare_auth(session.cookie_header(), session.web_protect_str, session.keys_str)
ua = resolve_user_agent(session.user_agent or DEFAULT_USER_AGENT)
return auth, ua
def is_generic_peer_name(name: str, peer_uid: str = "") -> bool:
value = (name or "").strip()
if not value:
return True
if peer_uid and value == peer_uid:
return True
if value.isdigit():
return True
if value.startswith("用户") and value[2:].isdigit():
return True
if value.startswith("会话") and len(value) <= 16:
return True
return False
def fetch_peer_profile_sync(
session: DouyinImSession,
peer_uid: int | str,
account_id: int = 0,
) -> dict[str, str]:
uid = str(peer_uid or "").strip()
if not uid.isdigit():
return {}
cache_key = _cache_key(account_id, uid)
cached = _profile_cache.get(cache_key)
if cached:
return dict(cached)
result = {"uid": uid, "nickname": "", "avatar_url": ""}
try:
auth, ua = _build_auth(session)
except Exception as exc:
logger.warning(f"build auth for peer profile failed: {exc}")
return result
headers = {
"User-Agent": ua,
"Referer": "https://www.douyin.com/",
"Accept": "application/json, text/plain, */*",
}
base_params = {
"device_platform": "webapp",
"aid": "6383",
"channel": "channel_pc_web",
"publish_video_strategy_type": "2",
"user_id": uid,
"sec_user_id": "",
"verifyFp": auth.cookie.get("s_v_web_id", "") if auth.cookie else "",
"fp": auth.cookie.get("s_v_web_id", "") if auth.cookie else "",
"webid": generate_webid(auth, "https://www.douyin.com/"),
"msToken": auth.msToken or generate_msToken(),
}
endpoints = [
"https://www.douyin.com/aweme/v1/web/user/profile/other/",
"https://www.douyin.com/aweme/v1/web/im/user/info/",
]
proxies = _requests_proxies()
for url in endpoints:
try:
params = dict(base_params)
query = splice_url(params)
params["a_bogus"] = generate_a_bogus(query, user_agent=ua)
resp = requests.get(
url,
params=params,
headers=headers,
cookies=auth.cookie,
verify=False,
timeout=12,
proxies=proxies,
)
data = resp.json()
extracted = _extract_profile_from_payload(data)
if extracted.get("uid") and not result["uid"]:
result["uid"] = extracted["uid"]
if extracted.get("nickname") and not result["nickname"]:
result["nickname"] = extracted["nickname"]
if extracted.get("avatar_url") and not result["avatar_url"]:
result["avatar_url"] = extracted["avatar_url"]
if result["nickname"] and result["avatar_url"]:
break
except Exception as exc:
logger.debug(f"peer profile fetch failed for {url}: {exc}")
if result["nickname"] or result["avatar_url"]:
_profile_cache[cache_key] = dict(result)
return result
async def fetch_peer_profile(
session: DouyinImSession,
peer_uid: int | str,
account_id: int = 0,
) -> dict[str, str]:
return await asyncio.to_thread(fetch_peer_profile_sync, session, peer_uid, account_id)
def enrich_conversation_item(conv: dict, my_uid: int = 0) -> dict:
"""补全会话项中的 peer_uid / sender_id。"""
item = dict(conv or {})
conv_id = str(item.get("conversation_id") or "").strip()
peer_uid = str(item.get("peer_uid") or item.get("sender_id") or "").strip()
if (not peer_uid or not peer_uid.isdigit()) and conv_id and my_uid:
resolved = resolve_peer_uid(conv_id, int(my_uid))
if resolved:
peer_uid = str(resolved)
if peer_uid:
item["peer_uid"] = peer_uid
item["sender_id"] = peer_uid
elif conv_id:
item["sender_id"] = conv_id
return item
@@ -0,0 +1,124 @@
import json
import random
import uuid
from .static import Request_pb2 as RequestProto
from .dy_util import (
generate_webid,
generate_req_sign,
generate_millisecond,
normalize_client_cert,
DEFAULT_USER_AGENT,
)
def _ua_headers(auth) -> tuple[str, str]:
ua = getattr(auth, "user_agent", None) or DEFAULT_USER_AGENT
browser_version = ua.split("Mozilla/", 1)[-1] if "Mozilla/" in ua else ua
return ua, browser_version
class ProtoBuilder:
@staticmethod
def build_normal_request(auth, cmd):
ua, browser_version = _ua_headers(auth)
request = RequestProto.Request()
request.cmd = cmd
request.sequence_id = random.randint(10000, 11000)
request.sdk_version = "1.1.3"
request.token = auth.ticket if auth.ticket else ""
request.refer = 3
request.inbox_type = 0
request.build_number = "5fa6ff1:Detached: 5fa6ff1111fd53aafc4c753505d3c93daad74d27"
did = str(getattr(auth, "device_id", "") or "0")
request.device_id = did
request.device_platform = 'douyin_pc'
request.headers['session_aid'] = '6383'
request.headers['session_did'] = did
request.headers['app_name'] = 'douyin_pc'
request.headers['priority_region'] = 'cn'
request.headers['user_agent'] = ua
request.headers['cookie_enabled'] = 'true'
request.headers['browser_language'] = 'zh-CN'
request.headers['browser_platform'] = 'Win32'
request.headers['browser_name'] = 'Mozilla'
request.headers['browser_version'] = browser_version
request.headers['browser_online'] = 'true'
request.headers['screen_width'] = '1707'
request.headers['screen_height'] = '960'
request.headers['referer'] = ''
request.headers['timezone_name'] = 'Etc/GMT-8'
request.headers['deviceId'] = did
request.headers['webid'] = generate_webid(auth)
request.headers['fp'] = auth.cookie.get('s_v_web_id', '') if auth.cookie else ''
request.headers['is-retry'] = '0'
request.auth_type = 4
request.biz = 'douyin_web'
request.access = 'web_sdk'
request.ts_sign = auth.ts_sign if auth.ts_sign else ""
request.sdk_cert = normalize_client_cert(auth.client_cert or "")
return request
@staticmethod
def build_create_conversation_request(auth, toId, myId):
request = ProtoBuilder.build_normal_request(auth, 609)
request.body.create_conversation_v2_body.conversation_type = 1
request.body.create_conversation_v2_body.participants.extend([int(toId), int(myId)])
reuqest_sign = generate_req_sign({
"sign_data": f"avatar_url=&idempotent_id=&name=&participants={toId},{myId}",
"certType": "cookie",
"scene": "web_protect"
}, auth.private_key)
request.reuqest_sign = reuqest_sign
return request
@staticmethod
def build_get_conversation_list_info_request(auth, toId, myId, conversation_short_id):
request = ProtoBuilder.build_normal_request(auth, 610)
request.body.get_conversation_info_list_v2_body.data.conversation_id = f"0:1:{myId}:{toId}"
request.body.get_conversation_info_list_v2_body.data.conversation_short_id = int(conversation_short_id)
request.body.get_conversation_info_list_v2_body.data.conversation_type = 1
return request
@staticmethod
def build_send_message_request(
auth,
conversation_id,
conversation_short_id,
ticket,
msg_content,
message_type: int = 7,
):
client_message_id = str(uuid.uuid4())
request = ProtoBuilder.build_normal_request(auth, 100)
request.body.send_message_body.conversation_id = conversation_id
request.body.send_message_body.conversation_type = 1
request.body.send_message_body.conversation_short_id = int(conversation_short_id)
from .reply_payload import _sanitize_im_content
clean_content = _sanitize_im_content(msg_content)
request.body.send_message_body.content = json.dumps(
clean_content, ensure_ascii=False, separators=(',', ':')
)
request.body.send_message_body.ext.append(
RequestProto.ExtValue(key='s:client_message_id', value=client_message_id)
)
request.body.send_message_body.ext.append(
RequestProto.ExtValue(key='s:stime', value=str(generate_millisecond()))
)
request.body.send_message_body.ext.append(
RequestProto.ExtValue(key='s:mentioned_users', value='')
)
request.body.send_message_body.message_type = int(message_type)
request.body.send_message_body.ticket = ticket
request.body.send_message_body.client_message_id = client_message_id
# 签名数据计算
sign_data_str = f'content={json.dumps(clean_content, separators=(",", ":"), ensure_ascii=False)}' + f'&conversation_id={conversation_id}&conversation_short_id={conversation_short_id}'
req_sign = generate_req_sign({
"sign_data": sign_data_str,
"certType": "cookie",
"scene": "web_protect"
}, auth.private_key)
request.reuqest_sign = req_sign
return request
+399
View File
@@ -0,0 +1,399 @@
import gzip
import json
import logging
import re
from typing import Any, Optional
logger = logging.getLogger("douyin_im.protocol")
def _walk_strings(data: Any, depth: int = 0, max_depth: int = 10):
if depth > max_depth:
return
if isinstance(data, dict):
for v in data.values():
yield from _walk_strings(v, depth + 1, max_depth)
elif isinstance(data, list):
for item in data:
yield from _walk_strings(item, depth + 1, max_depth)
elif isinstance(data, str) and data.strip():
yield data.strip()
def extract_json_objects(raw: bytes | str) -> list[dict]:
"""从二进制帧中尽量提取 JSON 对象"""
if isinstance(raw, bytes):
for codec in ("utf-8", "latin-1"):
try:
text = raw.decode(codec, errors="ignore")
break
except Exception:
text = ""
else:
text = ""
else:
text = raw
results = []
for match in re.finditer(r"\{[^{}]{0,2000}\}", text):
chunk = match.group(0)
try:
obj = json.loads(chunk)
if isinstance(obj, dict):
results.append(obj)
except Exception:
continue
return results
def parse_ws_payload(raw: bytes | str) -> list[dict]:
"""解析 WebSocket 二进制帧,返回标准化消息 dict 列表"""
messages = []
# 尝试 Protobuf 解包
if isinstance(raw, bytes):
try:
from .static import Live_pb2, Response_pb2
frame = Live_pb2.PushFrame()
frame.ParseFromString(raw)
if frame.payloadType == 'pb':
response = Response_pb2.Response()
response.ParseFromString(frame.payload)
body = response.body
if body.HasField("new_message_notify"):
notify = body.new_message_notify
if notify.HasField("message"):
msg = notify.message
sender = str(msg.sender)
msg_type = msg.message_type
conversation_id = msg.conversation_id
content_str = msg.content
server_message_id = str(getattr(msg, "server_message_id", "") or "")
conv_short_id = str(getattr(msg, "conversation_short_id", "") or "")
index_in_conv = str(getattr(msg, "index_in_conversation", "") or "")
content_json: dict | None = None
try:
parsed = json.loads(content_str)
if isinstance(parsed, dict):
content_json = parsed
except Exception:
content_json = None
from .im_debug_log import log_im_message
log_im_message(
direction="in",
message_type=msg_type,
conversation_id=conversation_id,
content=content_json if content_json is not None else content_str,
fields={
"conversation_id": conversation_id,
"conversation_type": getattr(msg, "conversation_type", 1),
"server_message_id": server_message_id,
"index_in_conversation": index_in_conv,
"conversation_short_id": conv_short_id,
"message_type": msg_type,
"sender": sender,
},
)
text_content = ""
try:
if content_json is not None:
if msg_type == 7:
text_content = content_json.get("text") or ""
elif msg_type == 70:
li = content_json.get("link_info") or {}
text_content = (
content_json.get("title")
or li.get("title")
or content_json.get("text")
or "[网页链接]"
)
elif msg_type == 5:
text_content = "[表情包]"
elif msg_type == 17:
text_content = "[语音]"
elif msg_type == 27:
text_content = "[图片]"
elif msg_type == 8:
text_content = "[视频]"
except Exception:
text_content = content_str or ""
if text_content and conversation_id:
sender_uid = str(msg.sender)
messages.append({
"sender_name": sender_uid,
"sender_uid": sender_uid,
"content": text_content,
"conversation_id": conversation_id,
"unread_count": 1,
"server_message_id": server_message_id,
"message_type": msg_type,
})
logger.info(
f"Protobuf WS message parsed: sender={sender}, "
f"type={msg_type}, content={text_content!r}, conv={conversation_id}"
)
return messages
except Exception as e:
logger.debug(f"Protobuf WS parse failed: {e}")
if isinstance(raw, str):
payloads = [raw.encode("utf-8", errors="ignore")]
else:
payloads = [raw]
# 尝试 gzip 解压(frontier 常见)
try:
payloads.append(gzip.decompress(raw))
except Exception:
pass
for payload in payloads:
# 1) 直接 JSON
if isinstance(payload, bytes):
text = payload.decode("utf-8", errors="ignore").strip()
else:
text = str(payload).strip()
if text.startswith("{") or text.startswith("["):
try:
data = json.loads(text)
messages.extend(normalize_im_payload(data))
continue
except Exception:
pass
# 2) 嵌入 JSON
for obj in extract_json_objects(payload):
messages.extend(normalize_im_payload(obj))
# 3) 纯文本兜底
if isinstance(payload, bytes):
text = payload.decode("utf-8", errors="ignore")
plain = _extract_plain_text(text)
if plain:
messages.append({"content": plain, "sender_name": "", "raw": True})
return messages
def normalize_im_payload_from_bytes(raw: bytes) -> list[dict]:
"""Try to extract conversation/message payloads from binary IM API responses."""
results: list[dict] = []
for obj in extract_json_objects(raw):
results.extend(normalize_im_payload(obj))
if results:
return results
try:
from .static import Response_pb2
response = Response_pb2.Response()
response.ParseFromString(raw)
body = response.body
for field in (
"get_conversation_info_list_v2_response_body",
"create_conversation_v2_body",
):
if body.HasField(field):
conv_body = getattr(body, field)
for conv in conv_body.conversation_info_list:
conv_id = conv.conversation_id
peer_uid = ""
parts = conv_id.split(":")
if len(parts) >= 4:
peer_uid = parts[-1]
label = f"用户{peer_uid[-6:]}" if peer_uid else conv_id
results.append({
"conversation_id": conv_id,
"sender_name": label,
"content": "",
"unread_count": 0,
"peer_uid": peer_uid,
"conversation_short_id": str(conv.conversation_short_id),
"ticket": conv.ticket,
})
except Exception:
pass
return results
def normalize_im_payload(data: Any, depth: int = 0) -> list[dict]:
"""递归标准化 IM JSON 为 {sender_name, content, conversation_id, unread_count}"""
if depth > 12:
return []
results = []
if isinstance(data, list):
for item in data:
results.extend(normalize_im_payload(item, depth + 1))
return results
if not isinstance(data, dict):
return results
sender = (
_pick_str(data, "sender_name", "senderName", "nickname", "nick_name", "userName", "peerName")
or _pick_nested(data, ("core_info", "user_info", "peer_info"), "nick_name", "nickname", "name")
)
sender_avatar = _pick_avatar_url(data)
content = _pick_message_text(data)
conv_id = _pick_str(
data,
"conversation_id",
"conversationId",
"conv_id",
"cid",
)
unread = data.get("unread_count") or data.get("unreadCount") or data.get("unread_cnt") or 0
try:
unread = int(unread or 0)
except (TypeError, ValueError):
unread = 0
if content and len(content) < 500:
from_self = data.get("is_self") or data.get("isSelf") or data.get("fromSelf") or data.get("self")
if not from_self:
results.append({
"sender_name": sender or "未知用户",
"sender_avatar": sender_avatar or None,
"content": content,
"conversation_id": conv_id or "",
"unread_count": unread,
})
if sender and unread > 0 and not content:
results.append({
"sender_name": sender,
"sender_avatar": sender_avatar or None,
"content": "[未读消息]",
"conversation_id": conv_id or "",
"unread_count": unread,
})
for key in ("conversations", "conversation_list", "data", "messages", "messagesList", "body"):
nested = data.get(key)
if nested is not None:
results.extend(normalize_im_payload(nested, depth + 1))
for value in data.values():
if isinstance(value, (dict, list)):
results.extend(normalize_im_payload(value, depth + 1))
return results
def _pick_str(data: dict, *keys: str) -> str:
for key in keys:
val = data.get(key)
if isinstance(val, str) and val.strip():
return val.strip()
return ""
def _pick_nested(data: dict, parent_keys: tuple, *child_keys: str) -> str:
for pk in parent_keys:
nested = data.get(pk)
if isinstance(nested, dict):
val = _pick_str(nested, *child_keys)
if val:
return val
return ""
def _avatar_from_value(val: Any) -> str:
if isinstance(val, str) and val.strip().startswith("http"):
return val.strip()
if isinstance(val, dict):
direct = val.get("url")
if isinstance(direct, str) and direct.startswith("http"):
return direct.strip()
for list_key in ("url_list", "urls"):
urls = val.get(list_key)
if isinstance(urls, list):
for item in urls:
if isinstance(item, str) and item.startswith("http"):
return item.strip()
return ""
def _pick_avatar_url(data: dict) -> str:
for key in ("avatar_url", "avatarUrl", "head_url", "headUrl", "avatar"):
url = _avatar_from_value(data.get(key))
if url:
return url
for thumb_key in ("avatar_thumb", "avatar_medium", "avatar_larger", "avatarThumb"):
url = _avatar_from_value(data.get(thumb_key))
if url:
return url
for parent_key in ("core_info", "user_info", "peer_info", "target_user", "conversation_core_info"):
nested = data.get(parent_key)
if isinstance(nested, dict):
url = _pick_avatar_url(nested)
if url:
return url
return ""
def _pick_message_text(data: dict) -> str:
for key in (
"text",
"content",
"message",
"msg",
"lastMessage",
"last_msg",
"preview",
"brief",
):
val = data.get(key)
if isinstance(val, str) and val.strip():
return val.strip()
if isinstance(val, dict):
inner = _pick_str(val, "text", "content", "message")
if inner:
return inner
return ""
def _extract_plain_text(text: str) -> Optional[str]:
text = (text or "").strip()
if not text or len(text) > 200:
return None
if text.startswith("{") or text.startswith("["):
return None
# 过滤明显二进制垃圾
printable = sum(1 for c in text if c.isprintable() or c in "\n\r\t")
if printable / max(len(text), 1) < 0.8:
return None
return text
_NON_TEXT_MESSAGE_MARKERS = {
"[表情包]",
"[语音]",
"[图片]",
"[视频]",
"[未读消息]",
}
def should_skip_auto_reply(content: str) -> tuple[bool, str]:
"""判断收到的内容是否不适合触发自动回复(如纯点赞/表情互动)。"""
text = (content or "").strip()
if not text:
return True, "空消息"
if text.startswith("{") and '"aweType":11400' in text.replace(" ", ""):
return True, "社交互动消息(点赞比心),不宜触发自动回复"
if "[互动]" in text or "比了个心" in text:
return True, "社交互动消息,不宜触发自动回复"
if text in _NON_TEXT_MESSAGE_MARKERS:
return True, f"非文本消息({text})"
if re.fullmatch(r"(\[赞\])+", text):
return True, "表情互动消息(点赞),抖音通常不允许对此类消息自动回复"
if re.fullmatch(r"\[[^\]]+\](\[[^\]]+\])*", text) and "http" not in text:
inner = re.sub(r"[\[\]]", "", text)
if len(inner) <= 20 and not any(ch.isalnum() for ch in inner):
return True, f"非文本互动消息({text})"
return False, ""
@@ -0,0 +1,670 @@
"""自动回复内容解析与 IM 消息体构造(文本 / 网址 / 卡片)。"""
from __future__ import annotations
import json
import logging
import os
import socket
import ssl
from typing import Any, Tuple
from urllib.parse import urlparse
logger = logging.getLogger("douyin_im.reply_payload")
_REPLY_SPEC_TYPES = ("text", "link", "hyperlink", "hyperlink_multiline", "card", "image", "raw_im", "interaction")
def _safe_int(value: Any, default: int = 0) -> int:
try:
if value is None or value == "":
return default
return int(value)
except (TypeError, ValueError):
return default
def _sanitize_im_content(value: Any) -> Any:
"""递归剔除 None,避免 JSON 出现 null 导致抖音客户端显示「null」。"""
if isinstance(value, dict):
return {k: _sanitize_im_content(v) for k, v in value.items() if v is not None}
if isinstance(value, list):
return [_sanitize_im_content(v) for v in value if v is not None]
return value
def _image_url_list(spec: dict[str, Any], uri: str) -> list[str]:
from .message_content import uri_to_cdn_urls
from .image_upload import is_douyin_cdn_url
raw_list = spec.get("url_list")
if isinstance(raw_list, list):
urls = [
str(u).strip()
for u in raw_list
if isinstance(u, str) and u.strip().startswith("http") and is_douyin_cdn_url(u)
]
if urls:
return urls
cover_url = str(spec.get("cover_url") or spec.get("douyin_url") or "").strip()
cdn_urls = uri_to_cdn_urls(uri)
if cdn_urls:
return cdn_urls
if cover_url.startswith("http") and is_douyin_cdn_url(cover_url):
return [cover_url]
return []
def _build_image_payload(spec: dict[str, Any]) -> tuple[dict[str, Any] | None, int | None]:
"""构造 IM 图片消息体(message_type=27),需已上传至抖音 CDN 的 uri。"""
from .message_content import MSG_TYPE_IMAGE
uri = str(spec.get("uri") or spec.get("cover_uri") or "").strip().lstrip("/")
if not uri:
return None, None
md5 = str(spec.get("md5") or spec.get("cover_md5") or "").strip()
url_list = _image_url_list(spec, uri)
resource_url: dict[str, Any] = {"uri": uri}
if url_list:
resource_url["url_list"] = url_list
if md5:
resource_url["md5"] = md5
msg_content: dict[str, Any] = {
"aweType": 2702,
"from_gallery": 1,
"create_type": 0,
"resource_url": resource_url,
"local_path": uri,
}
if md5:
msg_content["md5"] = md5
return msg_content, MSG_TYPE_IMAGE
def _build_card_cover_fields(spec: dict[str, Any]) -> dict[str, str | list[str]]:
"""链接卡片封面字段,对齐网页 IM 抓包(cover_url/image_url/image_list 等)。"""
from .image_upload import is_douyin_cdn_url
cover_uri = str(spec.get("cover_uri") or spec.get("uri") or "").strip().lstrip("/")
if not cover_uri:
return {}
image_list = _image_url_list(spec, cover_uri)
image_list = [u for u in image_list if is_douyin_cdn_url(u)]
if not image_list:
from .message_content import uri_to_cdn_urls
image_list = uri_to_cdn_urls(cover_uri)
if not image_list:
return {}
primary = image_list[0]
return {
"cover_url": primary,
"image_url": primary,
"image": primary,
"thumb_url": primary,
"image_list": image_list,
}
def _merge_link_card_cover_fields(
msg_content: dict[str, Any],
link_info: dict[str, Any],
cover_fields: dict[str, Any],
) -> None:
"""对齐成功抓包:封面详情在 link_info;顶层仅 cover_url + image_url。"""
if not cover_fields:
return
link_info.update(cover_fields)
msg_content["cover_url"] = cover_fields["cover_url"]
msg_content["image_url"] = cover_fields["image_url"]
def parse_reply_content(raw: str) -> dict[str, Any]:
"""解析规则中的 reply_content。纯字符串视为文本,JSON 为结构化回复。"""
raw = (raw or "").strip()
if not raw:
return {"type": "text", "text": ""}
if raw.startswith("{"):
try:
data = json.loads(raw)
if isinstance(data, dict) and data.get("type") in _REPLY_SPEC_TYPES:
return data
except json.JSONDecodeError:
pass
return {"type": "text", "text": raw}
def format_reply_display(raw: str) -> str:
"""将 reply_content 格式化为日志/列表中的可读摘要。"""
spec = parse_reply_content(raw)
reply_type = spec.get("type", "text")
if reply_type == "text":
return (spec.get("text") or "").strip()
if reply_type == "link":
text = (spec.get("text") or spec.get("title") or "").strip()
url = (spec.get("url") or "").strip()
if text and url:
return f"{text} → {url}"
return text or url
if reply_type == "hyperlink":
title = (spec.get("title") or "").strip()
url = (spec.get("url") or spec.get("target_url") or spec.get("link_url") or "").strip()
if title and url:
return f"[超链接] {title}"
return title or url or "[超链接]"
if reply_type == "card":
title = (spec.get("title") or "").strip()
url = (spec.get("url") or "").strip()
if title and url:
return f"[卡片] {title} → {url}"
return title or url or "[卡片]"
if reply_type == "interaction":
title = (
str(spec.get("subject_title") or spec.get("push_internal_object_title") or "").strip()
or "点赞比心互动"
)
return f"[互动] {title}"
if reply_type == "raw_im":
mt = spec.get("message_type") or spec.get("im_message_type") or "?"
return f"[原始IM] message_type={mt}"
if reply_type == "image":
return (spec.get("text") or "").strip() or "[图片]"
return raw
def serialize_reply_content(spec: dict[str, Any]) -> str:
return json.dumps(spec, ensure_ascii=False, separators=(",", ":"))
def build_msg_payload(spec: dict[str, Any]) -> Tuple[dict[str, Any], int]:
"""根据回复规格构造 IM msg_content 与 message_type。"""
reply_type = spec.get("type", "text")
if reply_type == "raw_im":
payload = spec.get("payload") if spec.get("payload") is not None else spec.get("content")
if isinstance(payload, str):
payload = json.loads(payload)
if not isinstance(payload, dict):
raise ValueError("raw_im 缺少 payload/content 对象")
mt = _safe_int(spec.get("message_type") or spec.get("im_message_type"), 7)
return payload, mt
if reply_type == "interaction":
from .interaction_messages import build_like_heart_payload, resolve_interaction_message_type
variant = str(spec.get("variant") or "like_heart").strip()
if variant != "like_heart":
raise ValueError(f"不支持的互动类型 variant={variant!r}")
my_uid = str(spec.get("my_uid") or spec.get("uid") or "").strip()
msg_content = build_like_heart_payload(spec, my_uid=my_uid)
return msg_content, resolve_interaction_message_type(spec)
if reply_type == "text":
text = (spec.get("text") or "").strip()
return (
{
"mention_users": [],
"aweType": 700,
"richTextInfos": [],
"text": text,
},
7,
)
if reply_type == "link":
display = (spec.get("text") or spec.get("title") or "").strip()
url = (spec.get("url") or "").strip()
if not display:
display = url
msg_content: dict[str, Any] = {
"mention_users": [],
"aweType": 700,
"richTextInfos": [],
"text": display,
}
if url and display:
msg_content["richTextInfos"] = [
{
"start": 0,
"end": len(display),
"type": 2,
"link": url,
"text": display,
}
]
return msg_content, 7
if reply_type == "hyperlink":
from .message_content import MSG_TYPE_LINK_CARD
link_url = str(
spec.get("url") or spec.get("target_url") or spec.get("link_url") or ""
).strip()
if is_internal_http_url(link_url):
raise ValueError("超链接 URL 无效")
cover_fields = _build_card_cover_fields(spec)
if not cover_fields:
raise ValueError("网页链接卡封面未上传到抖音 CDN")
title = (spec.get("title") or "").strip() or "网页链接"
desc = (spec.get("desc") or spec.get("description") or "").strip() or title
link_info: dict[str, Any] = {
"title": title,
"desc": desc,
"description": desc,
"url": link_url,
"link_url": link_url,
}
msg_content = {
"mention_users": [],
"aweType": 0,
"richTextInfos": [],
"text": link_url or title,
"link_info": link_info,
"link_url": link_url,
"title": title,
"desc": desc,
"description": desc,
}
_merge_link_card_cover_fields(msg_content, link_info, cover_fields)
return _sanitize_im_content(msg_content), MSG_TYPE_LINK_CARD
if reply_type == "hyperlink_multiline":
title = (spec.get("title") or "").strip()
desc = (spec.get("desc") or spec.get("description") or "").strip()
url = str(
spec.get("url") or spec.get("target_url") or spec.get("link_url") or ""
).strip()
lines = [x for x in (title, desc, url) if x]
text = "\n".join(lines) if lines else url
return (
{
"mention_users": [],
"aweType": 700,
"richTextInfos": [],
"text": text,
},
7,
)
if reply_type == "card":
from .message_content import MSG_TYPE_LINK_CARD
link_url = _resolve_card_link_url(spec)
cover_fields = _build_card_cover_fields(spec)
if not cover_fields:
raise ValueError("链接卡片封面未上传到抖音 CDN")
title = (spec.get("title") or "").strip() or "链接卡片"
desc = (spec.get("desc") or spec.get("description") or "").strip() or title
link_info: dict[str, Any] = {
"title": title,
"desc": desc,
"description": desc,
"url": link_url,
"link_url": link_url,
}
msg_content: dict[str, Any] = {
"mention_users": [],
"aweType": 0,
"richTextInfos": [],
"text": link_url or title,
"link_info": link_info,
"link_url": link_url,
"title": title,
"desc": desc,
"description": desc,
}
_merge_link_card_cover_fields(msg_content, link_info, cover_fields)
return _sanitize_im_content(msg_content), MSG_TYPE_LINK_CARD
if reply_type == "image":
msg_content, message_type = _build_image_payload(spec)
if msg_content is not None and message_type is not None:
return msg_content, message_type
text = (spec.get("text") or "").strip() or "[图片]"
return (
{
"mention_users": [],
"aweType": 700,
"richTextInfos": [],
"text": text,
},
7,
)
text = format_reply_display(serialize_reply_content(spec))
return (
{
"mention_users": [],
"aweType": 700,
"richTextInfos": [],
"text": text,
},
7,
)
def parse_reply_messages(raw: str) -> list:
"""解析多条回复(messages数组)或单条回复 spec。"""
raw = (raw or "").strip()
if not raw:
return [{"type": "text", "text": ""}]
if raw.startswith("{") or raw.startswith("["):
try:
data = json.loads(raw)
if isinstance(data, dict) and isinstance(data.get("messages"), list) and data["messages"]:
return [m for m in data["messages"] if isinstance(m, dict) and m.get("type") in _REPLY_SPEC_TYPES]
if isinstance(data, list):
return [m for m in data if isinstance(m, dict) and m.get("type") in _REPLY_SPEC_TYPES]
if isinstance(data, dict) and data.get("type") in _REPLY_SPEC_TYPES:
return [data]
except json.JSONDecodeError:
pass
return [{"type": "text", "text": raw}]
def _abs_public_url(path_or_url: str) -> str:
value = (path_or_url or "").strip()
if not value:
return ""
if value.startswith("/"):
try:
from .image_upload import _public_base_url
base = _public_base_url().rstrip("/")
if base:
return f"{base}{value}"
except Exception:
pass
if value and not value.startswith("http"):
return f"https://{value.lstrip('/')}"
return value
def is_internal_http_url(url: str) -> bool:
"""localhost / 127.0.0.1 / 非 http(s) 均视为不可用于抖音卡片外显。"""
raw = (url or "").strip()
if not raw:
return True
if raw.startswith("/"):
return True
lower = raw.lower()
if not lower.startswith("http://") and not lower.startswith("https://"):
return True
return "localhost" in lower or "127.0.0.1" in lower
_DISALLOWED_IM_LINK_HOSTS = (
"e.douyin.com",
"developer.open-douyin.com",
"partner.open-douyin.com",
"open.douyin.com",
"imapi.douyin.com",
)
_DISALLOWED_IM_LINK_PATH_PARTS = (
"im-manage/card",
"operation-center/im-manage",
"douyin-mp/operation-center",
)
def disallowed_im_link_reason(url: str) -> str:
"""抖音不允许把后台/开放平台地址当作私信网页链接跳转目标。"""
raw = (url or "").strip()
if not raw:
return ""
try:
parsed = urlparse(raw)
except Exception:
return ""
host = (parsed.hostname or "").lower()
path = (parsed.path or "").lower()
if host in _DISALLOWED_IM_LINK_HOSTS:
return (
f"链接指向抖音后台/开放平台({host}),不能作为私信超链接跳转地址。"
"请填写您自己的业务页,例如企微获客链接、官网、表单页等。"
)
if host.endswith(".douyin.com") and any(p in path for p in _DISALLOWED_IM_LINK_PATH_PARTS):
return (
"链接指向抖音运营后台「IM 卡片管理」页面,不是给用户点击的业务 URL。"
"请改为 https://work.weixin.qq.com/... 或您自己的 HTTPS 业务页。"
)
if "example.com" in host:
return "请填写真实可访问的业务 HTTPS 链接,不要使用 example.com 示例域名。"
return ""
def public_https_url_ok(url: str, *, timeout: float = 8.0) -> tuple[bool, str]:
"""检测 HTTPS 链接是否证书有效且可连接(抖音发卡前会校验域名)。"""
raw = (url or "").strip()
if not raw:
return False, "URL 为空"
parsed = urlparse(raw)
if parsed.scheme != "https":
return False, "非 HTTPS 链接"
host = parsed.hostname
if not host:
return False, "无效 URL"
try:
ctx = ssl.create_default_context()
with socket.create_connection((host, 443), timeout=timeout) as sock:
with ctx.wrap_socket(sock, server_hostname=host) as ssock:
ssock.getpeercert()
return True, ""
except ssl.SSLError as exc:
return False, f"SSL 证书与域名不匹配或未信任({exc})"
except OSError as exc:
return False, f"无法连接 {host}({exc})"
def _card_im_link_mode() -> str:
"""page=落地页;target=业务 URL;auto=落地页证书有效时用落地页,否则用 target。"""
return (os.getenv("KEFU_CARD_IM_LINK") or "auto").strip().lower()
def _resolve_card_target_url(spec: dict[str, Any]) -> str:
target_url = str(spec.get("target_url") or "").strip()
if is_internal_http_url(target_url):
return ""
resolved = _abs_public_url(target_url)
return "" if is_internal_http_url(resolved) else resolved
def _resolve_card_page_url(spec: dict[str, Any]) -> str:
"""SEO 落地页地址(/p/slug)。"""
page_url = str(spec.get("url") or spec.get("page_url") or "").strip()
if is_internal_http_url(page_url):
return ""
resolved = _abs_public_url(page_url)
return "" if is_internal_http_url(resolved) else resolved
def _resolve_card_link_url(spec: dict[str, Any]) -> str:
"""IM 卡片点击跳转 URL。发送重试可通过 _im_link_url 临时覆盖。"""
override = str(spec.get("_im_link_url") or "").strip()
if override and not is_internal_http_url(override):
return override
page_url = _resolve_card_page_url(spec)
target_url = _resolve_card_target_url(spec)
mode = _card_im_link_mode()
if mode == "target":
return target_url or page_url
if mode == "page":
return page_url or target_url
# auto:落地页 HTTPS 证书有效则优先落地页,否则回退业务 URL
if page_url:
ok, reason = public_https_url_ok(page_url)
if ok:
return page_url
if target_url:
logger.warning(
"Card landing page HTTPS check failed (%s), using target_url for IM link: %s",
reason,
target_url[:120],
)
return target_url
logger.warning("Card landing page HTTPS check failed: %s", reason)
return page_url
return target_url
def validate_hyperlink_send_spec(spec: dict[str, Any], *, require_cover_uri: bool = False) -> str:
"""超链接(网页链接卡):直连业务 URL,无需 SEO 落地页。"""
if spec.get("type") != "hyperlink":
return ""
if not (spec.get("title") or "").strip():
return "缺少超链接标题"
cover_ref = str(
spec.get("cover_url") or spec.get("cover") or spec.get("image_path") or ""
).strip()
if not cover_ref:
return "网页链接卡必须上传封面图,否则客户端只会显示为多行纯文字"
link_url = str(
spec.get("url") or spec.get("target_url") or spec.get("link_url") or ""
).strip()
if not link_url or is_internal_http_url(link_url):
return "超链接 URL 无效,请填写公网 HTTPS 地址"
if not link_url.lower().startswith("https://"):
return "超链接须为 HTTPS 地址"
blocked = disallowed_im_link_reason(link_url)
if blocked:
return blocked
ok, reason = public_https_url_ok(link_url)
if not ok:
return f"超链接 HTTPS 不可用({reason})"
if require_cover_uri:
uri = str(spec.get("cover_uri") or spec.get("uri") or "").strip().lstrip("/")
if not uri:
return "超链接封面尚未上传到抖音 CDN"
return ""
def validate_card_send_spec(spec: dict[str, Any], *, require_cover_uri: bool = False) -> str:
"""校验卡片回复是否满足发送条件,返回错误文案;空串表示通过。"""
if spec.get("type") != "card":
return ""
if not (spec.get("title") or "").strip():
return "缺少卡片标题"
cover_ref = str(
spec.get("cover_url") or spec.get("cover") or spec.get("image_path") or ""
).strip()
if not cover_ref:
return "缺少卡片封面图"
target = str(spec.get("target_url") or spec.get("link_url") or "").strip()
blocked = disallowed_im_link_reason(target)
if blocked:
return blocked
link_url = _resolve_card_link_url(spec)
if not link_url:
return (
"卡片跳转链接无效:落地页为 localhost 或未配置公网地址。"
"请设置环境变量 KEFU_PUBLIC_BASE_URL=https://你的公网域名 后重新保存规则"
)
page_url = _resolve_card_page_url(spec)
if page_url and _card_im_link_mode() != "target":
ok, reason = public_https_url_ok(page_url)
if not ok and not _resolve_card_target_url(spec):
return (
f"落地页 HTTPS 不可用({reason}),且无有效 target_url 可回退。"
"请为 KEFU_PUBLIC_BASE_URL 配置有效 SSL 证书,或设置 KEFU_CARD_IM_LINK=target"
)
if require_cover_uri:
uri = str(spec.get("cover_uri") or spec.get("uri") or "").strip().lstrip("/")
if not uri:
return "卡片封面尚未上传到抖音 CDN"
cover_fields = _build_card_cover_fields(spec)
if not cover_fields:
return "卡片封面 CDN 地址无效,请重新上传封面或检查 IM 凭证"
return ""
def _extract_link_card_media_path(url: str) -> str:
value = (url or "").strip()
if not value:
return ""
idx = value.find("/api/media/link-cards/")
if idx >= 0:
return value[idx:]
idx = value.find("/api/media/messages/")
if idx >= 0:
return value[idx:]
return ""
def expand_card_spec(spec: dict) -> list:
"""已废弃:勿将卡片拆成「图片 + 多行文字」,对方看不到网页链接卡。
保留函数仅供排查旧数据;发送链路不再调用。
"""
title = (spec.get("title") or "").strip()
desc = (spec.get("desc") or spec.get("description") or "").strip()
target = (spec.get("target_url") or spec.get("url") or spec.get("link_url") or "").strip()
if "localhost" in target or "127.0.0.1" in target:
target = (spec.get("target_url") or spec.get("link_url") or "").strip() or target
cover = (spec.get("image_path") or "").strip()
if not cover:
cover = _extract_link_card_media_path(spec.get("cover_url") or "")
out = []
if cover:
out.append({"type": "image", "url": cover, "text": "[图片]"})
lines = [x for x in (title, desc, target) if x]
text = "\n".join(lines) if lines else target
if text:
out.append({"type": "text", "text": text})
if not out:
out.append({"type": "text", "text": target})
return out
def split_reply_payloads(raw: str) -> list:
"""将规则 reply_content 拆成可逐条发送的 payload。卡片以原生链接卡(type 70)单条发送。
多条消息时先发文/图再发卡片,降低陌生人会话首条即结构化消息被拒(8004)的概率。
"""
specs = parse_reply_messages(raw)
non_cards = [s for s in specs if s.get("type") not in ("card", "hyperlink")]
cards = [s for s in specs if s.get("type") in ("card", "hyperlink")]
ordered = non_cards + cards
has_lead = bool(non_cards)
out: list[str] = []
for spec in ordered:
item = dict(spec)
if has_lead and item.get("type") in ("card", "hyperlink"):
item["_skip_preface"] = True
out.append(serialize_reply_content(item))
return out
def serialize_reply_log(payloads: list) -> str:
"""把实际逐条发送的 payload 合并为结构化日志内容。"""
specs = []
for payload in payloads:
raw_s = (payload or "").strip()
if not raw_s:
continue
spec = None
if raw_s.startswith("{"):
try:
data = json.loads(raw_s)
if isinstance(data, dict) and data.get("type") in _REPLY_SPEC_TYPES:
spec = data
except json.JSONDecodeError:
pass
if spec is None:
spec = {"type": "text", "text": raw_s}
specs.append(spec)
if len(specs) == 1:
return serialize_reply_content(specs[0])
return json.dumps({"messages": specs}, ensure_ascii=False, separators=(",", ":"))
+501
View File
@@ -0,0 +1,501 @@
import asyncio
import logging
import time
from typing import Awaitable, Callable, Optional
from utils import system_logger
from .frontier import ensure_frontier_ws
from .http_client import DouyinImHttpClient, format_session_credential_summary
from .session import DouyinImSession
from .ws_client import DouyinImWsClient
from .reply_payload import format_reply_display, serialize_reply_log
logger = logging.getLogger("douyin_im.service")
MatchReplyFn = Callable[[str], Awaitable[Optional[list[str]]]]
LogFn = Callable[..., Awaitable[None]]
ReceivedLogFn = Callable[..., Awaitable[None]]
class DouyinImService:
"""抖音 IM 直连服务:WebSocket 实时监听 + HTTP 轮询 + 自动回复"""
def __init__(
self,
session: DouyinImSession,
match_reply: MatchReplyFn,
log_fn: LogFn,
account_id: int,
received_log_fn: Optional[ReceivedLogFn] = None,
reply_delay_seconds: int = 0,
reply_cooldown_seconds: Optional[int] = None,
cooldown_resolver: Optional[Callable[[], Awaitable[int]]] = None,
refresh_credentials: Optional[Callable[[], Awaitable[bool]]] = None,
follow_tick: Optional[Callable[[], Awaitable[None]]] = None,
on_session_invalid: Optional[Callable[[str], Awaitable[None]]] = None,
):
self.session = session
self.match_reply = match_reply
self.log_fn = log_fn
self.received_log_fn = received_log_fn
self.account_id = account_id
self.follow_tick = follow_tick
self.on_session_invalid = on_session_invalid
self._session_invalid_strikes = 0
self._session_invalid_fired = False
self.reply_delay_seconds = max(0, int(reply_delay_seconds or 0))
self._cooldown_override = (
max(0, int(reply_cooldown_seconds)) if reply_cooldown_seconds is not None else None
)
self._cooldown_resolver = cooldown_resolver
self.refresh_credentials = refresh_credentials
self._running = False
self._replied_keys: set[str] = set()
self._logged_keys: set[str] = set()
self._received_logged_keys: set[str] = set()
self._last_reply_at: dict[str, float] = {}
self._conv_previews: dict[str, str] = {}
self._conv_names: dict[str, str] = {}
self._conv_meta: dict[str, dict] = {}
self._ws_client: Optional[DouyinImWsClient] = None
self.last_error: str = ""
self.last_send_risk_notice: str = ""
def _reply_key(self, sender: str, content: str) -> str:
return f"{sender}::{content}"
def _cooldown_seconds_sync(self) -> int:
if self._cooldown_override is not None:
return self._cooldown_override
try:
from auth.system_settings import get_cached_settings
return max(0, int(get_cached_settings().auto_reply_cooldown_seconds or 0))
except Exception:
return 0
async def _resolve_cooldown_seconds(self) -> int:
if self._cooldown_resolver is not None:
try:
return max(0, int(await self._cooldown_resolver() or 0))
except Exception as e:
logger.debug(f"cooldown resolver failed: {e}")
return self._cooldown_seconds_sync()
def _peer_in_cooldown(self, peer_key: str, cooldown: int) -> bool:
if cooldown <= 0 or not peer_key:
return False
last = self._last_reply_at.get(peer_key)
if last is None:
return False
return (time.monotonic() - last) < cooldown
def _resolve_sender_name(self, msg: dict) -> str:
sender_uid = str(msg.get("sender_uid") or msg.get("sender_name") or "").strip()
conv_id = str(msg.get("conversation_id") or "")
name = (msg.get("sender_name") or "").strip()
if name and not name.isdigit():
return name
if sender_uid and self._conv_names.get(sender_uid):
return self._conv_names[sender_uid]
if conv_id and self._conv_names.get(conv_id):
return self._conv_names[conv_id]
if sender_uid:
return f"用户{sender_uid[-6:]}" if len(sender_uid) > 6 else f"用户{sender_uid}"
return "未知用户"
def _is_self_message(self, msg: dict) -> bool:
sender_uid = str(msg.get("sender_uid") or "").strip()
if not sender_uid or not self.session.my_uid:
return False
try:
return int(sender_uid) == int(self.session.my_uid)
except (TypeError, ValueError):
return False
async def _handle_incoming(self, msg: dict):
if self._is_self_message(msg):
return
sender = self._resolve_sender_name(msg)
content = (msg.get("content") or "").strip()
unread = int(msg.get("unread_count") or 0)
conv_id = msg.get("conversation_id") or ""
sender_uid = str(msg.get("sender_uid") or "")
sender_avatar = str(msg.get("sender_avatar") or "").strip()
# 每条 WS 消息带唯一 server_message_id:用它去重,避免“同一用户重复发送
# 相同文字(如多次‘你好’)被按内容去重而整条丢弃”,这是“有时收不到”的根因。
# HTTP 轮询的会话预览没有该 ID,则退回按 内容 去重(避免对同一未读重复回复)。
server_message_id = str(msg.get("server_message_id") or "")
if conv_id:
self._conv_meta[conv_id] = {
**self._conv_meta.get(conv_id, {}),
"conversation_id": conv_id,
"sender_name": sender,
"sender_avatar": sender_avatar or self._conv_meta.get(conv_id, {}).get("sender_avatar"),
"content": content or self._conv_meta.get(conv_id, {}).get("content", ""),
"unread_count": unread,
"peer_uid": sender_uid,
}
if sender and sender_uid:
self._conv_names[sender_uid] = sender
if not content and unread <= 0:
return
if content == "[未读消息]" and sender in self._conv_previews:
content = self._conv_previews.get(sender, content)
if server_message_id:
log_key = f"mid:{server_message_id}"
key = f"mid:{server_message_id}"
else:
log_key = self._reply_key(sender, content or "[未读]")
key = self._reply_key(sender, content)
log_kwargs = {
"sender_name": sender,
"sender_id": conv_id or sender_uid or None,
"sender_avatar": sender_avatar or self._conv_meta.get(conv_id, {}).get("sender_avatar"),
"message": content,
}
if log_key not in self._logged_keys and content:
self._logged_keys.add(log_key)
await self.log_fn(
**log_kwargs,
reply=None,
status="received",
)
if key in self._replied_keys:
return
prev = self._conv_previews.get(sender)
should_reply = unread > 0 or (prev and content != prev) or (content and content != "[未读消息]")
if not should_reply:
if content:
self._conv_previews[sender] = content
return
from .hosted_registry import is_hosted
if sender_uid and is_hosted(sender_uid):
# 对方也是本系统托管的账号:若双方都自动回复会形成无限回环,
# 高频来回发送极易触发抖音风控(7911)/业务拒绝(8004),故直接跳过。
await self.log_fn(
**log_kwargs,
reply=None,
status="ignored",
error="对方是本系统托管的另一账号,已跳过自动回复以避免互相回复触发风控",
)
self._replied_keys.add(key)
if content:
self._conv_previews[sender] = content
logger.info(
f"Skip auto-reply to hosted account {sender_uid} (avoid reply loop)"
)
return
from .protocol import should_skip_auto_reply
skip, skip_reason = should_skip_auto_reply(content)
if skip:
await self.log_fn(
**log_kwargs,
reply=None,
status="ignored",
error=skip_reason,
)
self._replied_keys.add(key)
if content:
self._conv_previews[sender] = content
logger.info(f"Skip auto-reply to {sender}: {content!r} ({skip_reason})")
return
replies = await self.match_reply(content if content != "[未读消息]" else "")
if not replies:
await self.log_fn(
**log_kwargs,
reply=None,
status="ignored",
error="未配置任何自动回复规则",
)
self._replied_keys.add(key)
if content:
self._conv_previews[sender] = content
return
peer_key = (sender_uid or conv_id or sender or "").strip()
cooldown = await self._resolve_cooldown_seconds()
if self._peer_in_cooldown(peer_key, cooldown):
logger.info(f"Auto-reply to {sender} skipped: within {cooldown}s cooldown")
self._replied_keys.add(key)
if content:
self._conv_previews[sender] = content
return
if peer_key and cooldown > 0:
self._last_reply_at[peer_key] = time.monotonic()
if self.reply_delay_seconds > 0:
logger.info(f"Delaying reply to {sender} for {self.reply_delay_seconds}s")
await asyncio.sleep(self.reply_delay_seconds)
if not self._running:
return
reply_displays = []
sent_any = False
send_error = ""
failed_parts: list[str] = []
meta = self._conv_meta.get(conv_id, {})
for index, reply in enumerate(replies):
if index > 0:
await asyncio.sleep(0.6)
reply_display = format_reply_display(reply)
reply_displays.append(reply_display)
sent = False
if conv_id:
sent, resolved = await self._send_text(
conv_id,
reply,
conversation_short_id=str(meta.get("conversation_short_id") or ""),
)
if sent:
if resolved:
meta = {**meta, **resolved, "conversation_id": conv_id}
self._conv_meta[conv_id] = meta
else:
part_err = self.last_error or "IM API 发送失败"
send_error = part_err
failed_parts.append(f"{reply_display}: {part_err}")
else:
send_error = "缺少会话 ID,无法发送自动回复"
failed_parts.append(f"{reply_display}: {send_error}")
if sent:
sent_any = True
combined_display = " | ".join(reply_displays)
reply_log_content = serialize_reply_log(replies)
partial = sent_any and bool(failed_parts)
if partial:
send_error = ";".join(failed_parts)
if not sent_any:
logger.warning(
f"IM API send failed for [{sender}]: {send_error}"
)
if peer_key and cooldown > 0:
self._last_reply_at.pop(peer_key, None)
self._replied_keys.add(key)
if content:
self._conv_previews[sender] = content
await self.log_fn(
**log_kwargs,
reply=reply_log_content,
status="replied" if sent_any and not partial else ("partial" if partial else "failed"),
error=None if sent_any and not partial else (send_error or "IM API 发送失败"),
)
if sent_any and not partial:
system_logger.record(
"自动回复成功",
detail=f"已回复 {sender}:{combined_display}",
level="success",
category="send",
account_id=self.account_id,
)
elif partial:
system_logger.record(
"自动回复部分失败",
detail=f"回复 {sender} 部分成功:{combined_display};失败:{send_error}",
level="warning",
category="send",
account_id=self.account_id,
)
else:
system_logger.record(
"自动回复失败",
detail=f"回复 {sender} 失败:{send_error}(收到:{content})",
level="error",
category="send",
account_id=self.account_id,
)
logger.info(
f"Auto-reply to {sender}: {content!r} -> {combined_display!r} "
f"(sent={sent_any}, partial={partial}, msgs={len(replies)})"
)
def _index_conversations(self, conversations: list[dict]):
for conv in conversations:
conv_id = str(conv.get("conversation_id") or "")
name = (conv.get("sender_name") or "").strip()
if conv_id:
self._conv_meta[conv_id] = conv
if name:
self._conv_names[conv_id] = name
peer_uid = str(conv.get("peer_uid") or "")
if peer_uid and name:
self._conv_names[peer_uid] = name
async def _poll_conversations(self):
async with DouyinImHttpClient(self.session, account_id=self.account_id) as http:
unread_total = await http.get_unread_count()
if unread_total:
logger.info(f"IM unread total: {unread_total}")
conversations = await http.get_conversations()
self._index_conversations(conversations)
for conv in conversations:
unread = int(conv.get("unread_count") or 0)
if unread > 0 or conv.get("content"):
await self._handle_incoming(conv)
async def run(self):
"""主循环:WebSocket + HTTP 轮询"""
self._running = True
ensure_frontier_ws(self.session)
has_ws = bool(self.session.frontier_ws_url())
cred_summary = format_session_credential_summary(self.session)
logger.info(cred_summary)
logger.info(
f"Starting IM direct service for account {self.account_id} "
f"(ws={'yes' if has_ws else 'no'})"
)
system_logger.record(
"私信托管已启动",
detail=f"实时接收通道:{'已就绪' if has_ws else '不可用(仅 HTTP 轮询)'}\n{cred_summary}",
level="success" if has_ws else "warning",
category="system",
account_id=self.account_id,
)
self._ws_client = DouyinImWsClient(
self.session, self._handle_incoming, account_id=self.account_id
)
await self._ws_client.start()
try:
await self._poll_conversations()
except Exception as e:
logger.warning(f"Initial conversation poll failed: {e}")
system_logger.record(
"首次会话轮询失败",
detail=f"{e}",
level="warning",
category="poll",
account_id=self.account_id,
)
loop_count = 0
while self._running:
loop_count += 1
try:
if loop_count % 3 == 1:
await self._poll_conversations()
if loop_count % 6 == 1:
logger.info(f"IM direct tick #{loop_count} account={self.account_id}")
except Exception as e:
logger.error(f"IM poll error: {e}")
system_logger.record(
"会话轮询出错",
detail=f"拉取会话/未读时出错:{e}",
level="error",
category="poll",
account_id=self.account_id,
)
await asyncio.sleep(5)
async def stop(self):
self._running = False
if self._ws_client:
await self._ws_client.stop()
def get_cached_conversations(self) -> list[dict]:
"""返回运行中缓存的会话(来自 WS / 轮询)。"""
results = []
seen = set()
for conv_id, meta in self._conv_meta.items():
name = (meta.get("sender_name") or "").strip()
key = conv_id or name
if not key or key in seen:
continue
seen.add(key)
results.append({
"conversation_id": conv_id,
"sender_name": name or f"会话{conv_id[-8:]}" if conv_id else "未知用户",
"sender_avatar": meta.get("sender_avatar") or None,
"content": str(meta.get("content") or ""),
"unread_count": int(meta.get("unread_count") or 0),
})
return results
async def _send_text(
self,
conversation_id: str,
content: str,
conversation_short_id: str = "",
) -> tuple[bool, Optional[dict]]:
"""发送一条私信;若因签名凭证失效(7911)失败,刷新 web_protect 后自动重试一次。
返回 (是否成功, 解析到的会话 meta)。失败原因写入 self.last_error。
"""
self.last_send_risk_notice = ""
for attempt in range(2):
async with DouyinImHttpClient(self.session, account_id=self.account_id) as http:
sent = await http.send_text_message(
conversation_id,
content,
conversation_short_id=conversation_short_id,
)
self.last_error = http.last_error
self.last_send_risk_notice = http.last_send_risk_notice
needs_refresh = http.last_send_needs_refresh
if sent:
resolved = http.last_send_meta.get(conversation_id)
self.session.conv_meta.update(http.session.conv_meta)
return True, resolved
# 仅在“签名凭证失效”时刷新并重试一次
if attempt == 0 and needs_refresh and self.refresh_credentials:
logger.warning(
f"Send hit credential-expiry(7911) for {conversation_id}; "
"refreshing web_protect and retrying once..."
)
try:
refreshed = await self.refresh_credentials()
except Exception as e:
logger.warning(f"refresh_credentials raised: {e}")
refreshed = False
if refreshed:
continue
break
return False, None
async def send_message(self, conversation_id: str, content: str) -> bool:
"""手动发送私信"""
from .conv_util import normalize_conversation_id
from .auth import DouyinAuth
auth = DouyinAuth()
auth.perepare_auth(
self.session.cookie_header(),
self.session.web_protect_str,
self.session.keys_str,
)
my_uid = auth.get_uid() or self.session.my_uid
if my_uid:
conversation_id = normalize_conversation_id(conversation_id, my_uid)
meta = self._conv_meta.get(conversation_id, {})
sent, resolved = await self._send_text(
conversation_id,
content,
conversation_short_id=str(meta.get("conversation_short_id") or ""),
)
if sent and resolved:
self._conv_meta[conversation_id] = {
**meta,
**resolved,
"conversation_id": conversation_id,
}
return sent
+247
View File
@@ -0,0 +1,247 @@
import json
import re
import time
from dataclasses import dataclass, field
from typing import Any, Optional
from urllib.parse import parse_qs, unquote, urlparse
IM_TOKEN_COOKIES = ("sessionid", "sessionid_ss")
def is_frontier_ws_url(url: str) -> bool:
"""判断是否为抖音 IM frontier 长连接地址。
真实抓包里 host 可能是 frontier-im.douyin.com,也可能是
frontierNN-normal.zijieapi.com 这类内部别名,二者都要认。
"""
if not url or "token=" not in url:
return False
return "frontier-im.douyin.com" in url or ("frontier" in url and "zijieapi.com" in url)
@dataclass
class DouyinImSession:
"""抖音 IM 直连所需会话信息(从 Cookie + 浏览器抓包获得)"""
cookies: dict = field(default_factory=dict)
ws_urls: list = field(default_factory=list)
device_id: str = ""
web_id: str = ""
user_agent: str = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
)
keys_str: str = ""
web_protect_str: str = ""
my_uid: int = 0
conv_meta: dict = field(default_factory=dict)
# 方案 A:直接复用浏览器抓到的真实 frontier 连接凭证(绕开我们自己推导 token/access_key 不准的问题)
sdk_cert: str = "" # bd-ticket-guard 客户端证书(frontier sdk_cert / HTTP client-cert)
frontier_ts_sign: str = "" # 抓包得到的新鲜 ts_sign(覆盖 web_protect 里可能已过期的)
@classmethod
def from_storage_state(cls, data: dict, extra: Optional[dict] = None) -> "DouyinImSession":
extra = extra or {}
cookies = {}
cookie_items = data.get("cookies", [])
priority_names = set(IM_TOKEN_COOKIES)
def pick_best_cookie(name: str) -> str:
matches = [
c for c in cookie_items
if c.get("name") == name and c.get("value")
]
if not matches:
return ""
matches.sort(
key=lambda c: (
0 if ".douyin.com" in (c.get("domain") or "") else 1,
-len(c.get("value") or ""),
)
)
return matches[0].get("value") or ""
for item in cookie_items:
name = item.get("name")
if not name or any(c in name for c in "()[]{}'\"\n \t\\"):
continue
val = item.get("value") or ""
if name in priority_names:
best = pick_best_cookie(name)
if best:
cookies[name] = best
elif name not in cookies or len(val) > len(cookies.get(name, "")):
cookies[name] = val
device_id = extra.get("device_id") or cookies.get("device_id") or ""
web_id = extra.get("web_id") or ""
keys_str = extra.get("keys_str") or ""
web_protect_str = extra.get("web_protect_str") or ""
# my_uid 优先级:浏览器实时采集(extra) > storage_state 顶层(凭证采集工具手填/抓取)。
# 顶层 my_uid 让导入的明文数字 UID 直接生效,避免后端用加密 uid_tt 解析失败而回退联网查询。
def _as_uid(v) -> int:
try:
return int(str(v).strip())
except (TypeError, ValueError):
return 0
my_uid = _as_uid(extra.get("my_uid")) or _as_uid(data.get("my_uid"))
user_agent = str(extra.get("user_agent") or data.get("user_agent") or "").strip()
if not device_id or not web_id or not keys_str or not web_protect_str or not my_uid:
for origin in data.get("origins", []):
for entry in origin.get("localStorage", []):
name = entry.get("name", "")
value = entry.get("value", "")
if not value:
continue
if name == "security-sdk/s_sdk_crypt_sdk" and not keys_str:
keys_str = value
if name == "security-sdk/s_sdk_sign_data_key/web_protect" and not web_protect_str:
web_protect_str = value
if "tea_cache_tokens" in name and not web_id:
try:
parsed = json.loads(value)
web_id = str(
parsed.get("user_unique_id")
or parsed.get("web_id")
or ""
)
except Exception:
pass
if name == "web_runtime_security_uid" and not device_id:
device_id = value
if not my_uid:
for item in data.get("cookies", []):
cname = item.get("name") or ""
if cname in ("uid_tt", "uid_tt_ss") and item.get("value"):
try:
my_uid = int(item.get("value"))
break
except (TypeError, ValueError):
pass
if not device_id and web_id:
device_id = web_id
ws_urls = list(extra.get("ws_urls") or [])
# 方案 A:凭证采集工具可携带浏览器抓到的真实 frontier 连接(含 token/sdk_cert/ts_sign)。
frontier_ws_url = str(
extra.get("frontier_ws_url") or data.get("frontier_ws_url") or ""
).strip()
sdk_cert = str(extra.get("sdk_cert") or data.get("sdk_cert") or "").strip()
frontier_ts_sign = str(
extra.get("frontier_ts_sign")
or data.get("frontier_ts_sign")
or data.get("ts_sign")
or ""
).strip()
if is_frontier_ws_url(frontier_ws_url):
# 真实抓包 URL 优先,放在最前面
ws_urls = [frontier_ws_url] + [u for u in ws_urls if u != frontier_ws_url]
# 从真实 URL 里补抽 sdk_cert / ts_sign(用户只贴了 URL 时)。
# 注意:不能用 parse_qs(它会把 + 解成空格,毁掉 base64 证书),用 unquote。
def _q(url: str, key: str) -> str:
m = re.search(rf"[?&]{re.escape(key)}=([^&\s]+)", url)
return unquote(m.group(1)) if m else ""
if not sdk_cert:
sdk_cert = _q(frontier_ws_url, "sdk_cert")
if not frontier_ts_sign:
frontier_ts_sign = _q(frontier_ws_url, "ts_sign")
return cls(
cookies=cookies,
ws_urls=ws_urls,
device_id=str(device_id or ""),
web_id=str(web_id or ""),
keys_str=keys_str,
web_protect_str=web_protect_str,
my_uid=my_uid,
user_agent=user_agent if user_agent else cls.user_agent,
sdk_cert=sdk_cert,
frontier_ts_sign=frontier_ts_sign,
)
def to_dict(self) -> dict:
return {
"cookies": self.cookies,
"ws_urls": self.ws_urls,
"device_id": self.device_id,
"web_id": self.web_id,
"user_agent": self.user_agent,
"keys_str": self.keys_str,
"web_protect_str": self.web_protect_str,
"my_uid": self.my_uid,
"conv_meta": self.conv_meta,
"sdk_cert": self.sdk_cert,
"frontier_ts_sign": self.frontier_ts_sign,
"saved_at": time.time(),
}
@classmethod
def from_dict(cls, data: dict) -> "DouyinImSession":
if not data:
return cls()
return cls(
cookies=data.get("cookies") or {},
ws_urls=data.get("ws_urls") or [],
device_id=str(data.get("device_id") or ""),
web_id=str(data.get("web_id") or ""),
user_agent=data.get("user_agent") or cls.user_agent,
keys_str=str(data.get("keys_str") or ""),
web_protect_str=str(data.get("web_protect_str") or ""),
my_uid=int(data.get("my_uid") or 0),
conv_meta=dict(data.get("conv_meta") or {}),
sdk_cert=str(data.get("sdk_cert") or ""),
frontier_ts_sign=str(data.get("frontier_ts_sign") or ""),
)
def cookie_header(self) -> str:
parts = []
for name, value in self.cookies.items():
if name and value is not None:
parts.append(f"{name}={value}")
return "; ".join(parts)
def has_login(self) -> bool:
login_keys = {
"sessionid",
"sessionid_ss",
"sid_tt",
"sid_guard",
"passport_auth_status",
"odin_tt",
}
return any(self.cookies.get(k) for k in login_keys)
def can_direct_im(self) -> bool:
"""是否具备 Cookie 直连 IM 的最低条件(无需浏览器)"""
return self.has_login() and bool(
self.cookies.get("sessionid") or self.cookies.get("sessionid_ss")
)
def frontier_ws_url(self) -> Optional[str]:
"""仅返回 IM frontier 地址,忽略浏览器抓到的 bytelink 等无关 WS。"""
for url in self.ws_urls:
if is_frontier_ws_url(url):
return url
return None
def sanitize_ws_urls(self) -> None:
self.ws_urls = [url for url in self.ws_urls if is_frontier_ws_url(url)]
def common_params(self) -> dict[str, str]:
return {
"aid": "6383",
"app_name": "douyin_web",
"device_platform": "webapp",
"channel": "channel_pc_web",
"pc_client_type": "1",
"version_code": "170400",
"version_name": "17.4.0",
"device_id": self.device_id or self.web_id or "",
"webid": self.web_id or self.device_id or "",
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,60 @@
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# NO CHECKED-IN PROTOBUF GENCODE
# source: Request.proto
# Protobuf Python Version: 5.27.1
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import runtime_version as _runtime_version
from google.protobuf import symbol_database as _symbol_database
from google.protobuf.internal import builder as _builder
_runtime_version.ValidateProtobufRuntimeVersion(
_runtime_version.Domain.PUBLIC,
5,
27,
1,
'',
'Request.proto'
)
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\rRequest.proto\"&\n\x08\x45xtValue\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t\"\x94\x04\n\x07Request\x12\x0b\n\x03\x63md\x18\x01 \x01(\x05\x12\x13\n\x0bsequence_id\x18\x02 \x01(\x03\x12\x13\n\x0bsdk_version\x18\x03 \x01(\t\x12\r\n\x05token\x18\x04 \x01(\t\x12\r\n\x05refer\x18\x05 \x01(\x05\x12\x12\n\ninbox_type\x18\x06 \x01(\x03\x12\x14\n\x0c\x62uild_number\x18\x07 \x01(\t\x12\x1a\n\x04\x62ody\x18\x08 \x01(\x0b\x32\x0c.RequestBody\x12\x11\n\tdevice_id\x18\t \x01(\t\x12\x0f\n\x07\x63hannel\x18\n \x01(\t\x12\x17\n\x0f\x64\x65vice_platform\x18\x0b \x01(\t\x12\x13\n\x0b\x64\x65vice_type\x18\x0c \x01(\t\x12\x12\n\nos_version\x18\r \x01(\t\x12\x14\n\x0cversion_code\x18\x0e \x01(\t\x12&\n\x07headers\x18\x0f \x03(\x0b\x32\x15.Request.HeadersEntry\x12\x11\n\tconfig_id\x18\x10 \x01(\x05\x12\x1e\n\ntoken_info\x18\x11 \x01(\x0b\x32\n.TokenInfo\x12\x11\n\tauth_type\x18\x12 \x01(\x05\x12\x0b\n\x03\x62iz\x18\x15 \x01(\t\x12\x0e\n\x06\x61\x63\x63\x65ss\x18\x16 \x01(\t\x12\x0f\n\x07ts_sign\x18\x17 \x01(\t\x12\x10\n\x08sdk_cert\x18\x18 \x01(\t\x12\x14\n\x0creuqest_sign\x18\x19 \x01(\t\x1a.\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\xeb\x01\n\x0bRequestBody\x12\x34\n\x11send_message_body\x18\x64 \x01(\x0b\x32\x17.SendMessageRequestBodyH\x00\x12H\n\x1b\x63reate_conversation_v2_body\x18\xe1\x04 \x01(\x0b\x32 .CreateConversationV2RequestBodyH\x00\x12T\n\"get_conversation_info_list_v2_body\x18\xe2\x04 \x01(\x0b\x32%.GetConversationInfoListV2RequestBodyH\x00\x42\x06\n\x04\x62ody\"\xb8\x02\n\x16SendMessageRequestBody\x12\x17\n\x0f\x63onversation_id\x18\x01 \x01(\t\x12\x19\n\x11\x63onversation_type\x18\x02 \x01(\x05\x12\x1d\n\x15\x63onversation_short_id\x18\x03 \x01(\x03\x12\x0f\n\x07\x63ontent\x18\x04 \x01(\t\x12\x16\n\x03\x65xt\x18\x05 \x03(\x0b\x32\t.ExtValue\x12\x14\n\x0cmessage_type\x18\x06 \x01(\x05\x12\x0e\n\x06ticket\x18\x07 \x01(\t\x12\x19\n\x11\x63lient_message_id\x18\x08 \x01(\t\x12\x17\n\x0fmentioned_users\x18\t \x03(\x03\x12\x1a\n\x12ignore_badge_count\x18\n \x01(\x08\x12,\n\x0cref_msg_info\x18\x0b \x01(\x0b\x32\x16.ReferencedMessageInfo\"y\n\x15ReferencedMessageInfo\x12\x1b\n\x13original_message_id\x18\x01 \x01(\x03\x12\x1f\n\x17original_message_sender\x18\x02 \x01(\t\x12\"\n\x1aoriginal_message_timestamp\x18\x03 \x01(\x03\"^\n\tTokenInfo\x12\x0f\n\x07mark_id\x18\x01 \x01(\x05\x12\x0c\n\x04type\x18\x02 \x01(\x05\x12\x0e\n\x06\x61pp_id\x18\x03 \x01(\x05\x12\x0f\n\x07user_id\x18\x04 \x01(\x03\x12\x11\n\ttimestamp\x18\x05 \x01(\x03\"\xa2\x02\n\x1f\x43reateConversationV2RequestBody\x12\x19\n\x11\x63onversation_type\x18\x01 \x01(\x05\x12\x14\n\x0cparticipants\x18\x02 \x03(\x03\x12\x12\n\npersistent\x18\x03 \x01(\x08\x12\x15\n\ridempotent_id\x18\x04 \x01(\t\x12\x0c\n\x04name\x18\x05 \x01(\t\x12\x12\n\navatar_url\x18\x06 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x07 \x01(\t\x12=\n\x07\x62iz_ext\x18\x08 \x03(\x0b\x32,.CreateConversationV2RequestBody.BizExtEntry\x1a-\n\x0b\x42izExtEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"`\n$GetConversationInfoListV2RequestBody\x12\x38\n\x04\x64\x61ta\x18\x01 \x01(\x0b\x32*.GetConversationInfoListV2ResponseBodyData\"~\n)GetConversationInfoListV2ResponseBodyData\x12\x17\n\x0f\x63onversation_id\x18\x01 \x01(\t\x12\x1d\n\x15\x63onversation_short_id\x18\x02 \x01(\x03\x12\x19\n\x11\x63onversation_type\x18\x03 \x01(\x05\x62\x06proto3')
_globals = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'Request_pb2', _globals)
if not _descriptor._USE_C_DESCRIPTORS:
DESCRIPTOR._loaded_options = None
_globals['_REQUEST_HEADERSENTRY']._loaded_options = None
_globals['_REQUEST_HEADERSENTRY']._serialized_options = b'8\001'
_globals['_CREATECONVERSATIONV2REQUESTBODY_BIZEXTENTRY']._loaded_options = None
_globals['_CREATECONVERSATIONV2REQUESTBODY_BIZEXTENTRY']._serialized_options = b'8\001'
_globals['_EXTVALUE']._serialized_start=17
_globals['_EXTVALUE']._serialized_end=55
_globals['_REQUEST']._serialized_start=58
_globals['_REQUEST']._serialized_end=590
_globals['_REQUEST_HEADERSENTRY']._serialized_start=544
_globals['_REQUEST_HEADERSENTRY']._serialized_end=590
_globals['_REQUESTBODY']._serialized_start=593
_globals['_REQUESTBODY']._serialized_end=828
_globals['_SENDMESSAGEREQUESTBODY']._serialized_start=831
_globals['_SENDMESSAGEREQUESTBODY']._serialized_end=1143
_globals['_REFERENCEDMESSAGEINFO']._serialized_start=1145
_globals['_REFERENCEDMESSAGEINFO']._serialized_end=1266
_globals['_TOKENINFO']._serialized_start=1268
_globals['_TOKENINFO']._serialized_end=1362
_globals['_CREATECONVERSATIONV2REQUESTBODY']._serialized_start=1365
_globals['_CREATECONVERSATIONV2REQUESTBODY']._serialized_end=1655
_globals['_CREATECONVERSATIONV2REQUESTBODY_BIZEXTENTRY']._serialized_start=1610
_globals['_CREATECONVERSATIONV2REQUESTBODY_BIZEXTENTRY']._serialized_end=1655
_globals['_GETCONVERSATIONINFOLISTV2REQUESTBODY']._serialized_start=1657
_globals['_GETCONVERSATIONINFOLISTV2REQUESTBODY']._serialized_end=1753
_globals['_GETCONVERSATIONINFOLISTV2RESPONSEBODYDATA']._serialized_start=1755
_globals['_GETCONVERSATIONINFOLISTV2RESPONSEBODYDATA']._serialized_end=1881
# @@protoc_insertion_point(module_scope)
@@ -0,0 +1,46 @@
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# NO CHECKED-IN PROTOBUF GENCODE
# source: Response.proto
# Protobuf Python Version: 5.27.1
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import runtime_version as _runtime_version
from google.protobuf import symbol_database as _symbol_database
from google.protobuf.internal import builder as _builder
_runtime_version.ValidateProtobufRuntimeVersion(
_runtime_version.Domain.PUBLIC,
5,
27,
1,
'',
'Response.proto'
)
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x0eResponse.proto\"\x82\x01\n\x08Response\x12\x0b\n\x03\x63md\x18\x01 \x01(\x05\x12\x13\n\x0bsequence_id\x18\x02 \x01(\x03\x12\x12\n\nerror_desc\x18\x03 \x01(\t\x12\x0f\n\x07message\x18\x04 \x01(\t\x12\x12\n\ninbox_type\x18\x05 \x01(\x03\x12\x1b\n\x04\x62ody\x18\x06 \x01(\x0b\x32\r.ResponseBody\"\xf8\x01\n\x0cResponseBody\x12\x30\n\x12new_message_notify\x18\xf4\x03 \x01(\x0b\x32\x11.NewMessageNotifyH\x00\x12N\n\x1b\x63reate_conversation_v2_body\x18\xe1\x04 \x01(\x0b\x32&.GetConversationInfoListV2ResponseBodyH\x00\x12^\n+get_conversation_info_list_v2_response_body\x18\xe2\x04 \x01(\x0b\x32&.GetConversationInfoListV2ResponseBodyH\x00\x42\x06\n\x04\x62ody\"z\n\x10NewMessageNotify\x12\x17\n\x0f\x63onversation_id\x18\x02 \x01(\t\x12\x19\n\x11\x63onversation_type\x18\x03 \x01(\x05\x12\x13\n\x0bnotify_type\x18\x04 \x01(\x05\x12\x1d\n\x07message\x18\x05 \x01(\x0b\x32\x0c.MessageBody\"\xd1\x01\n\x0bMessageBody\x12\x17\n\x0f\x63onversation_id\x18\x01 \x01(\t\x12\x19\n\x11\x63onversation_type\x18\x02 \x01(\x05\x12\x19\n\x11server_message_id\x18\x03 \x01(\x03\x12\x1d\n\x15index_in_conversation\x18\x04 \x01(\x03\x12\x1d\n\x15\x63onversation_short_id\x18\x05 \x01(\x03\x12\x14\n\x0cmessage_type\x18\x06 \x01(\x05\x12\x0e\n\x06sender\x18\x07 \x01(\x03\x12\x0f\n\x07\x63ontent\x18\x08 \x01(\t\"g\n%GetConversationInfoListV2ResponseBody\x12>\n\x16\x63onversation_info_list\x18\x01 \x03(\x0b\x32\x1e.GetConversationInfoV2Response\"\x82\x01\n\x1dGetConversationInfoV2Response\x12\x17\n\x0f\x63onversation_id\x18\x01 \x01(\t\x12\x1d\n\x15\x63onversation_short_id\x18\x02 \x01(\x03\x12\x19\n\x11\x63onversation_type\x18\x03 \x01(\x05\x12\x0e\n\x06ticket\x18\x04 \x01(\tb\x06proto3')
_globals = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'Response_pb2', _globals)
if not _descriptor._USE_C_DESCRIPTORS:
DESCRIPTOR._loaded_options = None
_globals['_RESPONSE']._serialized_start=19
_globals['_RESPONSE']._serialized_end=149
_globals['_RESPONSEBODY']._serialized_start=152
_globals['_RESPONSEBODY']._serialized_end=400
_globals['_NEWMESSAGENOTIFY']._serialized_start=402
_globals['_NEWMESSAGENOTIFY']._serialized_end=524
_globals['_MESSAGEBODY']._serialized_start=527
_globals['_MESSAGEBODY']._serialized_end=736
_globals['_GETCONVERSATIONINFOLISTV2RESPONSEBODY']._serialized_start=738
_globals['_GETCONVERSATIONINFOLISTV2RESPONSEBODY']._serialized_end=841
_globals['_GETCONVERSATIONINFOV2RESPONSE']._serialized_start=844
_globals['_GETCONVERSATIONINFOV2RESPONSE']._serialized_end=974
# @@protoc_insertion_point(module_scope)
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,167 @@
ea = function() {
return (ea = Object.assign || function(e) {
for (var t, n = 1, r = arguments.length; n < r; n++)
for (var o in t = arguments[n])
Object.prototype.hasOwnProperty.call(t, o) && (e[o] = t[o]);
return e
}
).apply(this, arguments)
}
var H = function(e) {
for (var t, n = e.toString(), r = [], o = 0; o < n.length; o++)
0 <= (t = n.charCodeAt(o)) && t <= 127 ? r.push(t) : 128 <= t && t <= 2047 ? (r.push(192 | 31 & t >> 6),
r.push(128 | 63 & t)) : (2048 <= t && t <= 55295 || 57344 <= t && t <= 65535) && (r.push(224 | 15 & t >> 12),
r.push(128 | 63 & t >> 6),
r.push(128 | 63 & t));
for (var i = 0; i < r.length; i++)
r[i] &= 255;
return r
}
V = function(e) {
var t = []
, n = [];
if (void 0 === e)
return "";
n = H(e);
for (var r = 0, o = n.length; r < o; ++r)
t.push((5 ^ n[r]).toString(16));
return t.join("")
}
function generate_account_sdk_source_info(){
let browserInfo = {
"hardwareConcurrency": 20,
"webdriver": false,
"chromedriver": false,
"shelldriver": false,
"plugins": 5,
"permissions": [
{
"name": "notifications",
"state": "prompt"
}
],
"innerHeight": 1442,
"innerWidth": 1166,
"outerHeight": 1552,
"outerWidth": 2560,
"stoargeStatus": {
"indexedDB": {
"idb": "object",
"open": "function",
"indexedDB": "object",
"IDBKeyRange": "function",
"openDatabase": "undefined",
"isSafari": false,
"hasFetch": false
},
"localStorage": {
"isSupportLStorage": true,
"size": 46382,
"write": true
},
"storageQuotaStatus": {
"usage": 149822,
"quota": 128849645568,
"isPrivate": false
}
},
"notificationPermission": "default",
"performance": {
// "timeOrigin": 1723036093298,
"timeOrigin": new Date().getTime(),
"usedJSHeapSize": 137509473,
"navigationTiming": {
"decodedBodySize": 633258,
"entryType": "navigation",
"initiatorType": "navigation",
"name": "https://www.douyin.com/?recommend=1",
"renderBlockingStatus": "non-blocking",
"serverTiming": "inner,tt_agw,cdn-cache,edge,origin",
"guleStart": 1496.2999999523163,
"guleDuration": 14.799999952316284
}
}
}
let data = {
request_host: "www.douyin.com",
request_pathname: '/'
}
return V(JSON.stringify(ea(ea({}, browserInfo || {}), data)))
}
// console.log(generate_account_sdk_source_info())
eD = function(e, t) {
var n, r = 0, o = 0;
if ("object" != typeof e || !t || t.length <= 0)
return e;
for (var i = ej({
mix_mode: r
}, e), a = 0, c = t.length; a < c; ++a)
void 0 !== (n = i[t[a]]) && (r |= 1,
o |= 1,
i[t[a]] = eN(n));
return i.mix_mode = r,
i.fixed_mix_mode = o,
i
}
var ek = function(e) {
for (var t, n = e.toString(), r = [], o = 0; o < n.length; o++)
0 <= (t = n.charCodeAt(o)) && t <= 127 ? r.push(t) : 128 <= t && t <= 2047 ? (r.push(192 | 31 & t >> 6),
r.push(128 | 63 & t)) : (2048 <= t && t <= 55295 || 57344 <= t && t <= 65535) && (r.push(224 | 15 & t >> 12),
r.push(128 | 63 & t >> 6),
r.push(128 | 63 & t));
for (var i = 0; i < r.length; i++)
r[i] &= 255;
return r
}
eN = function(e) {
var t = []
, n = [];
if (void 0 === e)
return "";
n = ek(e);
for (var r = 0, o = n.length; r < o; ++r)
t.push((5 ^ n[r]).toString(16));
return t.join("")
}
ej = function() {
return (ej = Object.assign || function(e) {
for (var t, n = 1, r = arguments.length; n < r; n++)
for (var o in t = arguments[n])
Object.prototype.hasOwnProperty.call(t, o) && (e[o] = t[o]);
return e
}
).apply(this, arguments)
};
function generateSecretPhoneNum(phoneNum) {
return eD({
"mobile": "+86 " + phoneNum,
"type": 24,
"is6Digits": 1
}, ["mobile", "type"])
}
// let res = eD({
// "mobile": "+86 15751076989",
// "type": 24,
// "is6Digits": 1
// }, ["mobile", "type"])
//
// console.log(res)
nx = function() {
return (nx = Object.assign || function(e) {
for (var t, n = 1, r = arguments.length; n < r; n++)
for (var o in t = arguments[n])
Object.prototype.hasOwnProperty.call(t, o) && (e[o] = t[o]);
return e
}
).apply(this, arguments)
}
function generateSecretCode(phoneNum, code) {
return eD({
"mobile": "+86 " + phoneNum,
"code": code,
"service": "https://www.douyin.com"
}, ["mobile", "code", "password"])
}
// console.log(generateSecretCode("15751076989", "090625"))
+18
View File
@@ -0,0 +1,18 @@
{
"name": "static",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"dependencies": {
"jsrsasign": "^11.1.0"
}
},
"node_modules/jsrsasign": {
"version": "11.1.3",
"resolved": "https://registry.npmjs.org/jsrsasign/-/jsrsasign-11.1.3.tgz",
"integrity": "sha512-nPnK5D/4lv0Dwr7TlzrKtAd8JlLZwFTqTUUB3NQCbtdobcRcohGFxjbPySDVh74iWUudcCsapYT6OxoyhJLhhA==",
"license": "MIT"
}
}
}
@@ -0,0 +1,5 @@
{
"dependencies": {
"jsrsasign": "^11.1.0"
}
}
+187
View File
@@ -0,0 +1,187 @@
import asyncio
import logging
import threading
from typing import Awaitable, Callable, Optional
from websocket import WebSocketApp
from utils import system_logger
from .protocol import parse_ws_payload
from .session import DouyinImSession
logger = logging.getLogger("douyin_im.ws")
MessageHandler = Callable[[dict], Awaitable[None]]
class DouyinImWsClient:
"""直连 frontier-im WebSocket(websocket-client,与 DouYin_Spider 一致)"""
def __init__(
self,
session: DouyinImSession,
on_message: MessageHandler,
account_id: int | None = None,
):
self.session = session
self.on_message = on_message
self.account_id = account_id
self._running = False
self._task: Optional[asyncio.Task] = None
self._loop: Optional[asyncio.AbstractEventLoop] = None
self._ws_app: Optional[WebSocketApp] = None
self._ws_lock = threading.Lock()
async def start(self):
url = self.session.frontier_ws_url()
if not url:
logger.warning("No frontier WebSocket URL captured; WS listener disabled")
system_logger.record(
"实时接收未启用:未获取到 frontier WebSocket 地址",
detail="缺少有效的 device_id 或 sessionid,无法建立实时私信通道,将仅依赖 HTTP 轮询。",
level="warning",
category="ws",
account_id=self.account_id,
)
return
self._running = True
self._loop = asyncio.get_running_loop()
self._task = asyncio.create_task(self._run_loop(url))
async def stop(self):
self._running = False
with self._ws_lock:
if self._ws_app:
try:
self._ws_app.close()
except Exception:
pass
self._ws_app = None
if self._task:
self._task.cancel()
try:
await self._task
except asyncio.CancelledError:
pass
self._task = None
async def _run_loop(self, url: str):
retry = 0
while self._running:
from .frontier import ensure_frontier_ws
ensure_frontier_ws(self.session)
connect_url = self.session.frontier_ws_url() or url
try:
logger.info(f"Connecting IM WebSocket: {connect_url[:100]}...")
await self._loop.run_in_executor(None, self._connect_sync, connect_url)
retry = 0
except asyncio.CancelledError:
break
except Exception as e:
logger.warning(f"IM WebSocket error: {e}")
system_logger.record(
"实时接收连接异常",
detail=f"建立 frontier WebSocket 失败:{e}",
level="error",
category="ws",
account_id=self.account_id,
)
if not self._running:
break
retry += 1
wait = min(30, 2 * retry)
logger.info(f"IM WebSocket reconnect in {wait}s...")
system_logger.record(
f"实时接收断开,{wait}s 后重连",
detail="frontier WebSocket 连接已断开,正在自动重连。",
level="warning",
category="ws",
account_id=self.account_id,
)
await asyncio.sleep(wait)
def _connect_sync(self, url: str):
if not self._loop:
return
def on_open(_ws):
logger.info("IM WebSocket connected")
system_logger.record(
"实时接收通道已连接",
detail="frontier WebSocket 已建立,可实时接收私信。",
level="success",
category="ws",
account_id=self.account_id,
)
def on_message(_ws, message):
asyncio.run_coroutine_threadsafe(self._dispatch(message), self._loop)
def on_error(_ws, error):
if self._running:
logger.warning(f"IM WebSocket error: {error}")
system_logger.record(
"实时接收通道报错",
detail=f"{error}",
level="error",
category="ws",
account_id=self.account_id,
)
def on_close(_ws, code, msg):
logger.info(f"IM WebSocket closed: code={code}, msg={msg}")
if self._running:
system_logger.record(
"实时接收通道关闭",
detail=f"code={code}, msg={msg}",
level="warning",
category="ws",
account_id=self.account_id,
)
headers = {
"User-Agent": self.session.user_agent,
"Pragma": "no-cache",
"Cache-Control": "no-cache",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Sec-WebSocket-Protocol": "binary, base64, pbbp2",
"Sec-WebSocket-Extensions": "permessage-deflate; client_max_window_bits",
}
ws_app = WebSocketApp(
url,
header=headers,
cookie=self.session.cookie_header(),
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close,
)
with self._ws_lock:
self._ws_app = ws_app
try:
ws_app.run_forever(origin="https://www.douyin.com", ping_interval=20, ping_timeout=10)
finally:
with self._ws_lock:
if self._ws_app is ws_app:
self._ws_app = None
async def _dispatch(self, raw):
if isinstance(raw, str):
payload = raw.encode("utf-8", errors="ignore")
else:
payload = raw
items = parse_ws_payload(payload)
for item in items:
try:
await self.on_message(item)
except Exception as e:
logger.debug(f"WS message handler error: {e}")
system_logger.record(
"实时消息处理失败",
detail=f"处理收到的私信时出错:{e}",
level="error",
category="recv",
account_id=self.account_id,
)
File diff suppressed because it is too large Load Diff
+129
View File
@@ -0,0 +1,129 @@
"""运行时环境配置:住宅代理 + 浏览器显示。
用于解决「部署到云服务器后」两类常见问题:
1. 机房 IP 触发抖音风控(7911)—— 通过 KEFU_DOUYIN_PROXY 让抖音请求走住宅代理。
2. 无图形界面的 Linux 起不来有头浏览器 —— 自动拉起 Xvfb 虚拟显示。
全部通过环境变量控制,无需改代码:
KEFU_DOUYIN_PROXY 抖音 IM HTTP 请求与浏览器登录走的代理,绕开机房 IP 风控。
形如 http://user:pass@host:port 或 socks5://host:port
KEFU_BROWSER_HEADLESS 是否使用无头浏览器(1/true 开启)。默认 false:抖音安全 SDK
对 headless 判定严格,无头易生成无效 ts_sign,反而刷新无效。
"""
import asyncio
import logging
import os
from typing import Optional
from urllib.parse import urlparse
logger = logging.getLogger("rpa_engine.runtime")
_TRUE = {"1", "true", "yes", "on"}
_FALSE = {"0", "false", "no", "off"}
_NO_DISPLAY_HINT = (
"当前是无图形界面的 Linux 服务器,且无法启动虚拟显示来运行有头浏览器。"
"抖音安全 SDK 对 headless 判定严格,扫码登录 / 刷新凭证需要有头 Chromium。请任选其一:\n"
" 1) 安装 Xvfb + pyvirtualdisplay,让程序自动拉起虚拟显示:\n"
" Debian/Ubuntu: apt install -y xvfb && pip install pyvirtualdisplay\n"
" CentOS/Rocky : yum install -y xorg-x11-server-Xvfb && pip install pyvirtualdisplay\n"
" 2) 或用 xvfb-run 启动后端:xvfb-run -a ./start_web.sh\n"
" 3) 或设置 KEFU_BROWSER_HEADLESS=1 强制无头(更易触发抖音风控,不推荐)。"
)
def get_douyin_proxy() -> Optional[str]:
"""读取抖音请求代理 URL(未配置返回 None)。"""
val = (os.getenv("KEFU_DOUYIN_PROXY") or "").strip()
return val or None
def httpx_proxy() -> Optional[str]:
"""供 httpx.AsyncClient(proxy=...) 使用的代理 URL。"""
return get_douyin_proxy()
def requests_proxies() -> Optional[dict]:
"""供 requests.get(proxies=...) 使用的代理字典。"""
url = get_douyin_proxy()
if not url:
return None
return {"http": url, "https": url}
def playwright_proxy() -> Optional[dict]:
"""转成 Playwright launch(proxy=...) 所需结构(未配置或无法解析返回 None)。"""
url = get_douyin_proxy()
if not url:
return None
parsed = urlparse(url)
if not parsed.hostname:
logger.warning("KEFU_DOUYIN_PROXY 格式无法解析,已忽略:%s", url)
return None
server = f"{parsed.scheme or 'http'}://{parsed.hostname}"
if parsed.port:
server += f":{parsed.port}"
proxy: dict[str, str] = {"server": server}
if parsed.username:
proxy["username"] = parsed.username
if parsed.password:
proxy["password"] = parsed.password
return proxy
def resolve_headless(default: bool = False) -> bool:
"""根据 KEFU_BROWSER_HEADLESS 决定是否无头;未设置时用 default。"""
val = (os.getenv("KEFU_BROWSER_HEADLESS") or "").strip().lower()
if val in _TRUE:
return True
if val in _FALSE:
return False
return default
# 进程内仅启动一次的虚拟显示(Xvfb)句柄
_virtual_display = None
_virtual_display_failed = False
def _start_virtual_display_sync() -> Optional[str]:
"""在无 DISPLAY 的 Linux 上启动一次 Xvfb 虚拟显示(阻塞,需放线程执行)。"""
global _virtual_display, _virtual_display_failed
# 仅 Linux 且无 DISPLAY 时才需要虚拟显示;Windows/macOS 有桌面,直接返回。
if os.name != "posix":
return os.environ.get("DISPLAY")
if os.environ.get("DISPLAY"):
return os.environ["DISPLAY"]
if _virtual_display is not None:
return os.environ.get("DISPLAY")
if _virtual_display_failed:
raise RuntimeError(_NO_DISPLAY_HINT)
try:
from pyvirtualdisplay import Display
except ImportError as e:
_virtual_display_failed = True
raise RuntimeError(_NO_DISPLAY_HINT) from e
try:
disp = Display(visible=False, size=(1280, 800))
disp.start() # 设置 os.environ['DISPLAY']
except Exception as e:
_virtual_display_failed = True
raise RuntimeError(_NO_DISPLAY_HINT) from e
_virtual_display = disp
logger.info("已启动 Xvfb 虚拟显示 DISPLAY=%s 供有头浏览器使用", os.environ.get("DISPLAY"))
return os.environ.get("DISPLAY")
async def ensure_browser_display(headless: bool) -> None:
"""有头模式在无 DISPLAY 的 Linux 上自动拉起 Xvfb 虚拟显示。
headless=True 时无需显示,直接返回;启动失败抛出带操作指引的 RuntimeError。
"""
if headless:
return
await asyncio.to_thread(_start_virtual_display_sync)