douyinWEB/backend/app/tiktok_session.py
hackrobot 1e8eb0130a Sync dylive production working tree to test3.
Include latest server fixes for yt-long/disk/ops and related frontend.
Exclude .bak scratch files.
2026-10-14 07:04:18 +00:00

338 lines
12 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 -*-
"""TikTok cookie session — TiktokAutoUploader style, no developer OAuth."""
from __future__ import annotations
import os
import pickle
import sys
import time
from pathlib import Path
from typing import Any
from . import db
from . import tiktok_db
_VENDOR_ROOT = Path(__file__).resolve().parent.parent / "third_party" / "TiktokAutoUploader"
if str(_VENDOR_ROOT) not in sys.path:
sys.path.insert(0, str(_VENDOR_ROOT))
DEFAULT_DC = "useast2a"
COOKIE_TTL_DAYS = 30.0
REQUIRED_COOKIES = ("sessionid", "tt-target-idc")
_DC_CANDIDATES = ("useast5a", "useast5", "useast1a", "useast2a", "euwest1a", "alisg", "no1a", "useast8")
_PROBE_UA = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
)
def cookies_dir() -> Path:
raw = str(db.get_settings_map().get("tiktok_cookies_dir") or "").strip()
if raw:
p = Path(raw)
else:
p = Path(__file__).resolve().parent.parent / "data" / "tiktok_cookies"
p.mkdir(parents=True, exist_ok=True)
return p
def session_filename(channel_pk: str) -> str:
return f"tiktok_session-{channel_pk}"
def session_cookie_path(channel_pk: str) -> Path:
return cookies_dir() / f"{session_filename(channel_pk)}.cookie"
def _normalize_cookie(raw: dict[str, Any]) -> dict[str, Any]:
c = dict(raw)
if c.get("sameSite") == "None":
c["sameSite"] = "Strict"
return c
def load_session_cookies(channel_pk: str) -> list[dict[str, Any]]:
path = session_cookie_path(channel_pk)
if not path.is_file():
return []
try:
data = pickle.load(path.open("rb"))
except Exception:
return []
if not isinstance(data, list):
return []
out: list[dict[str, Any]] = []
for item in data:
if isinstance(item, dict) and item.get("name"):
out.append(_normalize_cookie(item))
return out
def save_session_cookies(channel_pk: str, cookies: list[dict[str, Any]]) -> None:
path = session_cookie_path(channel_pk)
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("wb") as f:
pickle.dump([_normalize_cookie(c) for c in cookies if c.get("name")], f)
def delete_session_cookies(channel_pk: str) -> None:
path = session_cookie_path(channel_pk)
if path.is_file():
path.unlink()
def save_session_from_values(
channel_pk: str,
*,
sessionid: str,
dc_id: str = "",
username: str = "",
) -> dict[str, Any]:
sid = str(sessionid or "").strip()
if not sid:
raise ValueError("sessionid 不能为空")
dc = str(dc_id or "").strip()
if not dc:
dc = detect_working_datacenter(sid)
cookies = [
{"name": "sessionid", "value": sid, "domain": ".tiktok.com", "path": "/"},
{"name": "sessionid_ss", "value": sid, "domain": ".tiktok.com", "path": "/"},
{"name": "tt-target-idc", "value": dc, "domain": ".tiktok.com", "path": "/"},
]
save_session_cookies(channel_pk, cookies)
now = time.time()
patch: dict[str, Any] = {
"oauth_ok": 1,
"oauth_checked_at": now,
"oauth_error": "",
"refresh_token": "cookie",
"cookie_saved_at": now,
}
if username.strip():
patch["tiktok_username"] = username.strip()
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:
if not channel:
return False
pk = str(channel.get("id") or "")
if not pk:
return False
cookies = load_session_cookies(pk)
names = {str(c.get("name") or "") for c in cookies}
return "sessionid" in names and bool(next((c.get("value") for c in cookies if c.get("name") == "sessionid"), ""))
def cookie_age_info(channel: dict[str, Any] | None, *, persist_backfill: bool = False) -> dict[str, Any]:
"""Days since this account's Cookie was pasted. Probe/DC rewrite must not reset the clock."""
ch = channel or {}
pk = str(ch.get("id") or "")
has = channel_has_session(ch) if pk else False
saved = float(ch.get("cookie_saved_at") or 0)
if has and saved <= 0 and pk:
path = session_cookie_path(pk)
if path.is_file():
saved = float(path.stat().st_mtime)
if persist_backfill:
tiktok_db.update_tiktok_channel(pk, cookie_saved_at=saved)
if not has or saved <= 0:
return {
"cookie_saved_at": 0.0,
"cookie_age_days": None,
"cookie_ttl_days": COOKIE_TTL_DAYS,
"cookie_expires_in_days": None,
"cookie_status": "missing",
}
age_days = max(0.0, (time.time() - saved) / 86400.0)
left_days = COOKIE_TTL_DAYS - age_days
if left_days <= 0:
status = "expired"
elif left_days <= 5:
status = "warn"
else:
status = "ok"
return {
"cookie_saved_at": saved,
"cookie_age_days": round(age_days, 1),
"cookie_ttl_days": COOKIE_TTL_DAYS,
"cookie_expires_in_days": round(max(0.0, left_days), 1),
"cookie_status": status,
}
def probe_channel_session(channel: dict[str, Any] | None) -> dict[str, Any]:
ch = channel or {}
pk = str(ch.get("id") or "")
if not pk:
return {"ok": False, "error": "账号不存在"}
if channel_has_session(ch):
tiktok_db.update_tiktok_channel(
pk,
oauth_ok=1,
oauth_checked_at=time.time(),
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,
oauth_ok=0,
oauth_checked_at=time.time(),
oauth_error="未配置 Cookie 会话",
refresh_token="",
)
return {"ok": False, "channel_pk": pk, "error": "未配置 Cookie 会话"}
def setup_checklist(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
channels = tiktok_db.list_tiktok_channels()
ready = [c for c in channels if channel_has_session(c)]
vendor_ok = _VENDOR_ROOT.is_dir() and (_VENDOR_ROOT / "tiktok_uploader" / "tiktok.py").is_file()
sig_js = _VENDOR_ROOT / "tiktok_uploader" / "tiktok-signature" / "browser.js"
node_ok = bool(os.environ.get("NODE_PATH") or _which("node"))
return {
"mode": "cookie",
"vendor_ready": vendor_ok,
"signature_ready": sig_js.is_file(),
"node_available": node_ok,
"cookies_dir": str(cookies_dir()),
"steps": [
{
"id": "browser_login",
"title": "浏览器登录 tiktok.com,导出 sessionid(及 tt-target-idc)",
"url": "https://www.tiktok.com",
"done": len(ready) > 0,
},
{
"id": "paste_cookie",
"title": "在 TikTok 页为每个账号粘贴 Cookie / sessionid",
"done": len(ready) > 0,
},
{
"id": "account",
"title": "添加 TikTok 账号并完成 Cookie 授权",
"done": len(channels) > 0 and len(ready) == len(channels),
},
],
"note": (
"使用 TiktokAutoUploader Cookie 方案,无需 TikTok 开发者应用。"
" sessionid 等同账号密码,请勿泄露;约 30 天过期需重新粘贴。"
),
"note_unaudited": "",
}
def _which(name: str) -> str | None:
from shutil import which
return which(name)
def probe_project_create(sessionid: str, dc_id: str) -> dict[str, Any]:
"""Hit TikTok project/create to see if this sessionid + datacenter works."""
import secrets
import string
import requests
sid = str(sessionid or "").strip()
dc = str(dc_id or "").strip()
if not sid or not dc:
return {"ok": False, "dc_id": dc, "error": "缺少 sessionid 或机房"}
sess = requests.Session()
sess.cookies.set("sessionid", sid, domain=".tiktok.com")
sess.cookies.set("sessionid_ss", sid, domain=".tiktok.com")
sess.cookies.set("tt-target-idc", dc, domain=".tiktok.com")
sess.headers.update({"User-Agent": _PROBE_UA, "Accept": "application/json, text/plain, */*"})
cid = "".join(secrets.choice(string.ascii_letters + string.digits + "_") for _ in range(21))
url = f"https://www.tiktok.com/api/v1/web/project/create/?creation_id={cid}&type=1&aid=1988"
try:
r = sess.post(url, timeout=20)
payload = r.json()
except Exception as exc:
return {"ok": False, "dc_id": dc, "error": str(exc)[:160]}
project = payload.get("project") if isinstance(payload, dict) else None
ok = isinstance(project, dict) and bool(project.get("project_id"))
return {
"ok": ok,
"dc_id": dc,
"status_code": payload.get("status_code") if isinstance(payload, dict) else None,
"status_msg": str((payload or {}).get("status_msg") or "")[:160],
}
def detect_working_datacenter(sessionid: str, preferred: str = "") -> str:
order: list[str] = []
pref = str(preferred or "").strip()
if pref:
order.append(pref)
for item in _DC_CANDIDATES:
if item not in order:
order.append(item)
last: dict[str, Any] = {}
for dc in order:
last = probe_project_create(sessionid, dc)
if last.get("ok"):
return dc
msg = str(last.get("status_msg") or last.get("error") or "").strip()
code = last.get("status_code")
hint = f"(status_code={code} {msg})" if code is not None or msg else ""
raise ValueError(
f"TikTok Cookie 无效或机房不匹配{hint}。请重新从已登录的 tiktok.com 复制 sessionid 和 tt-target-idc"
)
def ensure_working_datacenter(channel_pk: str) -> str:
cookies = load_session_cookies(channel_pk)
sid = next((str(c.get("value") or "") for c in cookies if c.get("name") == "sessionid"), "")
dc = next((str(c.get("value") or "") for c in cookies if c.get("name") == "tt-target-idc"), "")
if not sid:
raise ValueError("Cookie 缺少 sessionid")
working = detect_working_datacenter(sid, dc)
if working != dc:
save_session_cookies(
channel_pk,
[
{"name": "sessionid", "value": sid, "domain": ".tiktok.com", "path": "/"},
{"name": "sessionid_ss", "value": sid, "domain": ".tiktok.com", "path": "/"},
{"name": "tt-target-idc", "value": working, "domain": ".tiktok.com", "path": "/"},
],
)
return working
def configure_vendor_paths() -> None:
"""Point vendored Config at our cookies directory."""
os.environ.setdefault("TIKTOK_VENDOR_ROOT", str(_VENDOR_ROOT))
try:
from tiktok_uploader.Config import Config
cfg = Config.get()
cfg._insert_option("COOKIES_DIR", str(cookies_dir()))
cfg._insert_option("VIDEOS_DIR", str(cookies_dir()))
except Exception:
pass