feat: TikTok 账号拉取头像昵称粉丝等资料并落库/S3展示

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-15 03:15:49 -05:00
parent 35728c405e
commit 60054cd188
7 changed files with 407 additions and 4 deletions

View File

@ -295,6 +295,19 @@ def init_db() -> None:
conn.execute(
"ALTER TABLE tiktok_channels ADD COLUMN platform_limit_probe_at REAL NOT NULL DEFAULT 0"
)
for col, decl in (
("tiktok_uid", "TEXT NOT NULL DEFAULT ''"),
("nickname", "TEXT NOT NULL DEFAULT ''"),
("avatar_url", "TEXT NOT NULL DEFAULT ''"),
("follower_count", "INTEGER NOT NULL DEFAULT 0"),
("following_count", "INTEGER NOT NULL DEFAULT 0"),
("video_count", "INTEGER NOT NULL DEFAULT 0"),
("heart_count", "INTEGER NOT NULL DEFAULT 0"),
("profile_fetched_at", "REAL NOT NULL DEFAULT 0"),
("profile_error", "TEXT NOT NULL DEFAULT ''"),
):
if col not in tt_cols:
conn.execute(f"ALTER TABLE tiktok_channels ADD COLUMN {col} {decl}")
from . import x2_db as _x2_db
_x2_db.ensure_x2_tables(conn)

View File

@ -1076,6 +1076,15 @@ def _public_tiktok_channel(ch: dict[str, Any] | None) -> dict[str, Any] | None:
out["platform_limit_probe_at"] = float(out.get("platform_limit_probe_at") or 0)
out["platform_limited"] = out["platform_limit_at"] > 0
out.update(tiktok_session.cookie_age_info(ch, persist_backfill=True))
out["tiktok_uid"] = str(out.get("tiktok_uid") or "")
out["nickname"] = str(out.get("nickname") or "")
out["avatar_url"] = str(out.get("avatar_url") or "")
out["follower_count"] = int(out.get("follower_count") or 0)
out["following_count"] = int(out.get("following_count") or 0)
out["video_count"] = int(out.get("video_count") or 0)
out["heart_count"] = int(out.get("heart_count") or 0)
out["profile_fetched_at"] = float(out.get("profile_fetched_at") or 0)
out["profile_error"] = str(out.get("profile_error") or "")
return out
@ -1138,6 +1147,24 @@ async def tiktok_channel_session(channel_pk: str, body: TikTokSessionBody) -> di
return {"ok": True, "channel": _public_tiktok_channel(updated)}
@app.post("/api/tiktok/channels/{channel_pk}/profile/refresh")
async def tiktok_channel_profile_refresh(channel_pk: str) -> dict[str, Any]:
from . import tiktok_db
from . import tiktok_profile
ch = tiktok_db.get_tiktok_channel(channel_pk)
if not ch:
raise HTTPException(404, "账号不存在")
try:
result = await asyncio.to_thread(tiktok_profile.fetch_profile_for_channel, channel_pk)
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
except Exception as exc:
raise HTTPException(400, str(exc) or "拉取资料失败") from exc
channel = (result or {}).get("channel") or tiktok_db.get_tiktok_channel(channel_pk)
return {"ok": True, "channel": _public_tiktok_channel(channel), "profile": (result or {}).get("profile")}
@app.delete("/api/tiktok/channels/{channel_pk}/session")
async def tiktok_channel_session_delete(channel_pk: str) -> dict[str, Any]:
from . import tiktok_db

View File

@ -110,6 +110,9 @@ def update_tiktok_channel(channel_pk: str, **fields: Any) -> dict[str, Any] | No
"oauth_ok", "oauth_checked_at", "oauth_error", "note", "cookie_saved_at",
"socks_enabled", "socks_profile_id",
"platform_limit_at", "platform_limit_msg", "platform_limit_probe_at",
"tiktok_uid", "nickname", "avatar_url",
"follower_count", "following_count", "video_count", "heart_count",
"profile_fetched_at", "profile_error",
}
with _lock:
conn = _connect()
@ -130,6 +133,10 @@ def update_tiktok_channel(channel_pk: str, **fields: Any) -> dict[str, Any] | No
v = int(v)
if k == "socks_profile_id":
v = str(v or "").strip()
if k in {"follower_count", "following_count", "video_count", "heart_count"}:
v = int(v or 0)
if k in {"tiktok_uid", "nickname", "avatar_url", "profile_error", "tiktok_username"}:
v = str(v or "").strip()
sets.append(f"{k} = ?")
params.append(v)
if not sets:

View File

@ -0,0 +1,255 @@
# -*- 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()
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 m:
try:
data = json.loads(m.group(1))
except Exception:
data = None
if isinstance(data, dict):
scope = data.get("__DEFAULT_SCOPE__") if isinstance(data.get("__DEFAULT_SCOPE__"), dict) else data
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 {}
return _parse_user_blob(user_info["user"], stats)
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:
return _parse_user_blob(u, {})
m2 = re.search(r'<script[^>]+id="SIGI_STATE"[^>]*>(\{.*?\})</script>', html, re.DOTALL)
if m2:
try:
data = json.loads(m2.group(1))
except Exception:
data = None
if isinstance(data, dict):
user_mod = data.get("UserModule") if isinstance(data.get("UserModule"), dict) else {}
users = user_mod.get("users") if isinstance(user_mod.get("users"), dict) else {}
stats_mod = user_mod.get("stats") if isinstance(user_mod.get("stats"), dict) else {}
for uid, user in users.items():
if isinstance(user, dict):
st = stats_mod.get(uid) if isinstance(stats_mod.get(uid), dict) else {}
return _parse_user_blob(user, st)
return None
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
if not profile:
try:
html = sess.get("https://www.tiktok.com/", timeout=25).text or ""
profile = _extract_from_rehydration(html)
except Exception:
profile = None
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]}

View File

@ -135,6 +135,12 @@ def schedule_board(limit: int = 24) -> dict[str, Any]:
"id": cid,
"name": c.get("name"),
"tiktok_username": c.get("tiktok_username"),
"nickname": c.get("nickname") or "",
"avatar_url": c.get("avatar_url") or "",
"tiktok_uid": c.get("tiktok_uid") or "",
"follower_count": int(c.get("follower_count") or 0),
"video_count": int(c.get("video_count") or 0),
"heart_count": int(c.get("heart_count") or 0),
"enabled": bool(c.get("enabled")),
"authorized": tiktok_session.channel_has_session(c),
"daily_min": TIKTOK_DAILY_FORCE,

View File

@ -110,7 +110,23 @@ def save_session_from_values(
}
if username.strip():
patch["tiktok_username"] = username.strip()
return tiktok_db.update_tiktok_channel(channel_pk, **patch) or {}
updated = tiktok_db.update_tiktok_channel(channel_pk, **patch) or {}
try:
from . import tiktok_profile
refreshed = tiktok_profile.fetch_profile_for_channel(
channel_pk,
username_hint=str(username or patch.get("tiktok_username") or ""),
)
if isinstance(refreshed, dict) and refreshed.get("channel"):
updated = refreshed["channel"]
except Exception as exc:
try:
tiktok_db.update_tiktok_channel(channel_pk, profile_error=str(exc)[:240])
updated = tiktok_db.get_tiktok_channel(channel_pk) or updated
except Exception:
pass
return updated
def channel_has_session(channel: dict[str, Any] | None) -> bool:
@ -174,6 +190,12 @@ def probe_channel_session(channel: dict[str, Any] | None) -> dict[str, Any]:
oauth_error="",
refresh_token="cookie",
)
try:
from . import tiktok_profile
tiktok_profile.refresh_profile_if_stale(pk, force=False)
except Exception:
pass
return {"ok": True, "channel_pk": pk, "mode": "cookie"}
tiktok_db.update_tiktok_channel(
pk,

View File

@ -29,6 +29,15 @@ type Channel = {
id: string;
name: string;
tiktok_username?: string;
tiktok_uid?: string;
nickname?: string;
avatar_url?: string;
follower_count?: number;
following_count?: number;
video_count?: number;
heart_count?: number;
profile_fetched_at?: number;
profile_error?: string;
enabled?: boolean;
authorized?: boolean;
oauth_ok?: number;
@ -66,6 +75,12 @@ type BoardChannel = {
id: string;
name?: string;
tiktok_username?: string;
nickname?: string;
avatar_url?: string;
tiktok_uid?: string;
follower_count?: number;
video_count?: number;
heart_count?: number;
enabled?: boolean;
authorized?: boolean;
used: number;
@ -387,6 +402,22 @@ export default function TikTokPage() {
setShowSessionForm(true);
};
const refreshProfile = async (ch: Channel) => {
try {
await fetchJson(`/api/tiktok/channels/${ch.id}/profile/refresh`, { method: "POST" });
toast.push(`已刷新「${ch.name}」资料`, "ok");
void load();
} catch (e: any) {
toast.push(e?.message || "刷新资料失败", "err");
}
};
const fmtCount = (n?: number) => {
const v = Number(n || 0);
if (v >= 10000) return `${(v / 10000).toFixed(v >= 100000 ? 0 : 1)}万`;
return String(v);
};
const toggleChannelEnabled = async (ch: Channel) => {
await fetchJson(`/api/tiktok/channels/${ch.id}`, {
method: "PATCH",
@ -1068,14 +1099,46 @@ export default function TikTokPage() {
}`}
>
<div className="flex items-start justify-between gap-2">
<div className="min-w-0">
<div className="truncate font-medium text-slate-100">{ch.name || "未命名"}</div>
<div className="truncate text-[10px] text-slate-500">{ch.tiktok_username || "—"}</div>
<div className="flex min-w-0 items-center gap-2.5">
{full?.avatar_url ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={full.avatar_url}
alt=""
className="h-10 w-10 shrink-0 rounded-full object-cover ring-1 ring-white/10"
/>
) : (
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-pink-500/15 text-xs text-pink-200">
TT
</div>
)}
<div className="min-w-0">
<div className="truncate font-medium text-slate-100">
{full?.nickname || ch.name || "未命名"}
</div>
<div className="truncate text-[10px] text-slate-500">
{full?.tiktok_username || ch.tiktok_username
? `@${(full?.tiktok_username || ch.tiktok_username || "").replace(/^@/, "")}`
: ch.name || "—"}
{full?.tiktok_uid ? ` · id ${full.tiktok_uid}` : ""}
</div>
</div>
</div>
<span className={`shrink-0 text-[10px] ${cookieAgeClass(full)}`}>
{full?.authorized ? "Cookie 就绪" : "未配置"}
</span>
</div>
{(full?.follower_count || full?.video_count || full?.heart_count) ? (
<div className="mt-2 flex flex-wrap gap-2 text-[10px] text-slate-400">
<span>粉丝 {fmtCount(full?.follower_count)}</span>
<span>视频 {fmtCount(full?.video_count)}</span>
<span>赞 {fmtCount(full?.heart_count)}</span>
</div>
) : full?.authorized ? (
<div className="mt-1 text-[10px] text-slate-500">
{full.profile_error || "资料未拉取,可点「刷新资料」"}
</div>
) : null}
<div className={`mt-1 text-[10px] ${cookieAgeClass(full)}`}>{cookieAgeLabel(full)}</div>
{full?.authorized && full.cookie_saved_at ? (
<div className="text-[10px] text-slate-500">保存于 {fmtTs(full.cookie_saved_at)}</div>
@ -1115,6 +1178,16 @@ export default function TikTokPage() {
<KeyRound className="h-3 w-3" />
{full?.authorized ? "更新 Cookie" : "粘贴 Cookie"}
</button>
{full?.authorized ? (
<button
type="button"
onClick={() => void refreshProfile(full)}
className="inline-flex items-center gap-1 rounded-lg bg-white/5 px-2 py-1 text-[11px] text-slate-300"
>
<RefreshCw className="h-3 w-3" />
刷新资料
</button>
) : null}
{full && (
<button
type="button"