douyinWEB/backend/app/tiktok_profile.py
eric 9fbf5ec04a fix: 从 TikTok @主页抓取完整头像与粉丝/视频数
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-15 03:19:18 -05:00

296 lines
11 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
"""Fetch TikTok account profile via cookie session; persist stats + S3 avatar."""
from __future__ import annotations
import json
import logging
import re
import tempfile
import time
from pathlib import Path
from typing import Any
import requests
from . import s3_storage
from . import tiktok_db
from . import tiktok_session
log = logging.getLogger("tiktok_profile")
_UA = tiktok_session._PROBE_UA
_PROFILE_STALE_SEC = 6 * 3600
def _cookie_jar(channel_pk: str) -> requests.Session:
sess = requests.Session()
sess.headers.update(
{
"User-Agent": _UA,
"Accept": "application/json, text/html, */*",
"Accept-Language": "en-US,en;q=0.9",
"Referer": "https://www.tiktok.com/",
}
)
for c in tiktok_session.load_session_cookies(channel_pk):
name = str(c.get("name") or "")
value = str(c.get("value") or "")
if not name or not value:
continue
domain = str(c.get("domain") or ".tiktok.com")
sess.cookies.set(name, value, domain=domain)
return sess
def _parse_user_blob(user: dict[str, Any], stats: dict[str, Any] | None = None) -> dict[str, Any]:
st = stats if isinstance(stats, dict) else {}
avatar = str(
user.get("avatarLarger") or user.get("avatarMedium") or user.get("avatarThumb") or ""
).strip()
if not avatar:
uris = user.get("avatarUri")
if isinstance(uris, list) and uris:
avatar = str(uris[0] or "").strip()
elif isinstance(uris, str):
avatar = uris.strip()
return {
"tiktok_uid": str(user.get("id") or user.get("uid") or "").strip(),
"tiktok_username": str(user.get("uniqueId") or user.get("unique_id") or "").strip().lstrip("@"),
"nickname": str(user.get("nickname") or user.get("nickName") or "").strip(),
"avatar_cdn": avatar,
"follower_count": int(
st.get("followerCount") or st.get("follower_count") or user.get("followerCount") or 0
),
"following_count": int(st.get("followingCount") or st.get("following_count") or 0),
"video_count": int(st.get("videoCount") or st.get("video_count") or 0),
"heart_count": int(st.get("heartCount") or st.get("heart") or st.get("diggCount") or 0),
"sec_uid": str(user.get("secUid") or user.get("sec_uid") or "").strip(),
}
def _extract_from_rehydration(html: str) -> dict[str, Any] | None:
m = re.search(
r'<script[^>]+id="__UNIVERSAL_DATA_FOR_REHYDRATION__"[^>]*>(\{.*?\})</script>',
html,
re.DOTALL,
)
if not m:
return None
try:
data = json.loads(m.group(1))
except Exception:
return None
if not isinstance(data, dict):
return None
scope = data.get("__DEFAULT_SCOPE__") if isinstance(data.get("__DEFAULT_SCOPE__"), dict) else data
# Prefer full profile module (has avatar + stats)
detail = scope.get("webapp.user-detail") if isinstance(scope, dict) else None
if isinstance(detail, dict):
user_info = detail.get("userInfo") if isinstance(detail.get("userInfo"), dict) else None
if user_info and isinstance(user_info.get("user"), dict):
stats = user_info.get("stats") if isinstance(user_info.get("stats"), dict) else {}
return _parse_user_blob(user_info["user"], stats)
best: dict[str, Any] | None = None
for _key, val in (scope or {}).items():
if not isinstance(val, dict):
continue
user_info = val.get("userInfo") if isinstance(val.get("userInfo"), dict) else None
if user_info and isinstance(user_info.get("user"), dict):
stats = user_info.get("stats") if isinstance(user_info.get("stats"), dict) else {}
parsed = _parse_user_blob(user_info["user"], stats)
if parsed.get("avatar_cdn") or parsed.get("follower_count") or parsed.get("video_count"):
return parsed
best = best or parsed
webapp = scope.get("webapp.app-context") if isinstance(scope, dict) else None
if isinstance(webapp, dict):
u = webapp.get("user") if isinstance(webapp.get("user"), dict) else None
if u:
parsed = _parse_user_blob(u, {})
# merge onto best if we only have thin context user
if best:
for k, v in parsed.items():
if v and not best.get(k):
best[k] = v
return best
return parsed
return best
def _fetch_user_detail(sess: requests.Session, unique_id: str) -> dict[str, Any] | None:
uid = str(unique_id or "").strip().lstrip("@")
if not uid:
return None
url = "https://www.tiktok.com/api/user/detail/"
params = {
"aid": "1988",
"app_name": "tiktok_web",
"device_platform": "web_pc",
"uniqueId": uid,
}
try:
r = sess.get(url, params=params, timeout=25)
payload = r.json()
except Exception as exc:
log.info("user/detail fail uniqueId=%s: %s", uid, exc)
return None
user_info = payload.get("userInfo") if isinstance(payload, dict) else None
if not isinstance(user_info, dict):
return None
user = user_info.get("user")
if not isinstance(user, dict):
return None
stats = user_info.get("stats") if isinstance(user_info.get("stats"), dict) else {}
return _parse_user_blob(user, stats)
def _resolve_unique_id(sess: requests.Session, hint: str = "") -> str:
hint = str(hint or "").strip().lstrip("@")
if hint:
return hint
for name in ("uniqueid", "uniqueId"):
val = sess.cookies.get(name)
if val:
return str(val).strip().lstrip("@")
try:
r = sess.get("https://www.tiktok.com/", timeout=25)
html = r.text or ""
except Exception:
return ""
parsed = _extract_from_rehydration(html)
if parsed and parsed.get("tiktok_username"):
return str(parsed["tiktok_username"])
m = re.search(r'"uniqueId"\s*:\s*"([^"]+)"', html)
return str(m.group(1)).strip() if m else ""
def _mirror_avatar_to_s3(channel_pk: str, cdn_url: str) -> str:
url = str(cdn_url or "").strip()
if not url or not s3_storage.s3_enabled():
return url
try:
r = requests.get(url, headers={"User-Agent": _UA}, timeout=30)
r.raise_for_status()
data = r.content
if len(data) < 64:
return url
ctype = (r.headers.get("Content-Type") or "image/jpeg").split(";")[0].strip() or "image/jpeg"
suffix = ".jpg"
if "png" in ctype:
suffix = ".png"
elif "webp" in ctype:
suffix = ".webp"
with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
tmp.write(data)
tmp_path = Path(tmp.name)
try:
key = f"tiktok/avatars/{channel_pk}{suffix}"
public = s3_storage.upload_file(tmp_path, key, content_type=ctype)
return public or url
finally:
try:
tmp_path.unlink(missing_ok=True)
except Exception:
pass
except Exception as exc:
log.info("avatar s3 mirror fail channel=%s: %s", channel_pk, exc)
return url
def fetch_profile_for_channel(channel_pk: str, *, username_hint: str = "") -> dict[str, Any]:
"""Pull profile for a channel that already has cookie session. Raises ValueError on hard fail."""
pk = str(channel_pk or "").strip()
if not pk:
raise ValueError("缺少 channel_pk")
ch = tiktok_db.get_tiktok_channel(pk)
if not ch:
raise ValueError("账号不存在")
if not tiktok_session.channel_has_session(ch):
raise ValueError("账号未配置 Cookie")
sess = _cookie_jar(pk)
hint = username_hint or str(ch.get("tiktok_username") or "")
unique = _resolve_unique_id(sess, hint)
profile = _fetch_user_detail(sess, unique) if unique else None
# Official web JSON often empty from datacenter IPs; scrape @page / home rehydration instead.
if not profile or not profile.get("avatar_cdn") or not (
profile.get("follower_count") or profile.get("video_count")
):
pages = []
if unique:
pages.append(f"https://www.tiktok.com/@{unique}")
pages.append("https://www.tiktok.com/")
for page in pages:
try:
html = sess.get(page, timeout=30).text or ""
except Exception:
continue
scraped = _extract_from_rehydration(html)
if not scraped:
continue
if not profile:
profile = scraped
else:
for k, v in scraped.items():
if v and not profile.get(k):
profile[k] = v
elif k in {"follower_count", "following_count", "video_count", "heart_count"} and int(
v or 0
) > int(profile.get(k) or 0):
profile[k] = v
elif k == "avatar_cdn" and v and not profile.get("avatar_cdn"):
profile[k] = v
if profile.get("avatar_cdn") and (
profile.get("follower_count") or profile.get("video_count") or profile.get("nickname")
):
break
if not profile or not (profile.get("tiktok_uid") or profile.get("tiktok_username") or profile.get("nickname")):
raise ValueError("未能从 TikTok 拉取账号资料(Cookie 可能失效或机房不匹配)")
avatar_cdn = str(profile.get("avatar_cdn") or "")
avatar_url = _mirror_avatar_to_s3(pk, avatar_cdn) if avatar_cdn else ""
patch = {
"tiktok_uid": str(profile.get("tiktok_uid") or ""),
"tiktok_username": str(profile.get("tiktok_username") or hint or "").lstrip("@"),
"nickname": str(profile.get("nickname") or ""),
"avatar_url": avatar_url or avatar_cdn,
"follower_count": int(profile.get("follower_count") or 0),
"following_count": int(profile.get("following_count") or 0),
"video_count": int(profile.get("video_count") or 0),
"heart_count": int(profile.get("heart_count") or 0),
"profile_fetched_at": time.time(),
"profile_error": "",
}
updated = tiktok_db.update_tiktok_channel(pk, **patch) or {}
return {"ok": True, "channel": updated, "profile": patch}
def refresh_profile_if_stale(
channel_pk: str,
*,
force: bool = False,
max_age_sec: float = _PROFILE_STALE_SEC,
) -> dict[str, Any] | None:
ch = tiktok_db.get_tiktok_channel(channel_pk)
if not ch or not tiktok_session.channel_has_session(ch):
return None
fetched = float(ch.get("profile_fetched_at") or 0)
if (
not force
and fetched > 0
and (time.time() - fetched) < max_age_sec
and str(ch.get("avatar_url") or "").strip()
):
return {"ok": True, "skipped": True, "channel": ch}
try:
return fetch_profile_for_channel(channel_pk)
except Exception as exc:
tiktok_db.update_tiktok_channel(channel_pk, profile_error=str(exc)[:240])
log.info("profile refresh fail %s: %s", channel_pk, exc)
return {"ok": False, "error": str(exc)[:240]}