From 60054cd1886314362a039e96e31e661c1519deb3 Mon Sep 17 00:00:00 2001 From: eric Date: Sat, 15 Aug 2026 03:15:49 -0500 Subject: [PATCH] =?UTF-8?q?feat:=20TikTok=20=E8=B4=A6=E5=8F=B7=E6=8B=89?= =?UTF-8?q?=E5=8F=96=E5=A4=B4=E5=83=8F=E6=98=B5=E7=A7=B0=E7=B2=89=E4=B8=9D?= =?UTF-8?q?=E7=AD=89=E8=B5=84=E6=96=99=E5=B9=B6=E8=90=BD=E5=BA=93/S3?= =?UTF-8?q?=E5=B1=95=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cursor --- backend/app/db.py | 13 ++ backend/app/main.py | 27 ++++ backend/app/tiktok_db.py | 7 + backend/app/tiktok_profile.py | 255 +++++++++++++++++++++++++++++++ backend/app/tiktok_schedule.py | 6 + backend/app/tiktok_session.py | 24 ++- frontend/src/app/tiktok/page.tsx | 79 +++++++++- 7 files changed, 407 insertions(+), 4 deletions(-) create mode 100644 backend/app/tiktok_profile.py diff --git a/backend/app/db.py b/backend/app/db.py index 41af945..4872af0 100644 --- a/backend/app/db.py +++ b/backend/app/db.py @@ -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) diff --git a/backend/app/main.py b/backend/app/main.py index fc27af4..1b79779 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -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 diff --git a/backend/app/tiktok_db.py b/backend/app/tiktok_db.py index 5c3314a..26f739b 100644 --- a/backend/app/tiktok_db.py +++ b/backend/app/tiktok_db.py @@ -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: diff --git a/backend/app/tiktok_profile.py b/backend/app/tiktok_profile.py new file mode 100644 index 0000000..1c8693b --- /dev/null +++ b/backend/app/tiktok_profile.py @@ -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']+id="__UNIVERSAL_DATA_FOR_REHYDRATION__"[^>]*>(\{.*?\})', + 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']+id="SIGI_STATE"[^>]*>(\{.*?\})', 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]} diff --git a/backend/app/tiktok_schedule.py b/backend/app/tiktok_schedule.py index 6ce266e..a6b7639 100644 --- a/backend/app/tiktok_schedule.py +++ b/backend/app/tiktok_schedule.py @@ -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, diff --git a/backend/app/tiktok_session.py b/backend/app/tiktok_session.py index a2f6cbc..a92c004 100644 --- a/backend/app/tiktok_session.py +++ b/backend/app/tiktok_session.py @@ -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, diff --git a/frontend/src/app/tiktok/page.tsx b/frontend/src/app/tiktok/page.tsx index a372a20..557908f 100644 --- a/frontend/src/app/tiktok/page.tsx +++ b/frontend/src/app/tiktok/page.tsx @@ -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() { }`} >
-
-
{ch.name || "未命名"}
-
{ch.tiktok_username || "—"}
+
+ {full?.avatar_url ? ( + // eslint-disable-next-line @next/next/no-img-element + + ) : ( +
+ TT +
+ )} +
+
+ {full?.nickname || ch.name || "未命名"} +
+
+ {full?.tiktok_username || ch.tiktok_username + ? `@${(full?.tiktok_username || ch.tiktok_username || "").replace(/^@/, "")}` + : ch.name || "—"} + {full?.tiktok_uid ? ` · id ${full.tiktok_uid}` : ""} +
+
{full?.authorized ? "Cookie 就绪" : "未配置"}
+ {(full?.follower_count || full?.video_count || full?.heart_count) ? ( +
+ 粉丝 {fmtCount(full?.follower_count)} + 视频 {fmtCount(full?.video_count)} + 赞 {fmtCount(full?.heart_count)} +
+ ) : full?.authorized ? ( +
+ {full.profile_error || "资料未拉取,可点「刷新资料」"} +
+ ) : null}
{cookieAgeLabel(full)}
{full?.authorized && full.cookie_saved_at ? (
保存于 {fmtTs(full.cookie_saved_at)}
@@ -1115,6 +1178,16 @@ export default function TikTokPage() { {full?.authorized ? "更新 Cookie" : "粘贴 Cookie"} + {full?.authorized ? ( + + ) : null} {full && (