fix: TikTok 上传自动探测 tt-target-idc,避免 KeyError project

Cookie 有效但默认机房 useast2a 会导致 project/create 返回 status_code=8。上传前探测可用机房并写回 Cookie。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-14 11:22:56 -05:00
parent 78a043b0de
commit 0815e05094
7 changed files with 155 additions and 21 deletions

View File

@ -873,7 +873,7 @@ async def tiktok_channel_session(channel_pk: str, body: TikTokSessionBody) -> di
tiktok_session.save_session_from_values,
channel_pk,
sessionid=str(body.sessionid or "").strip(),
dc_id=str(body.dc_id or "useast2a").strip(),
dc_id=str(body.dc_id or "").strip(),
username=str(body.tiktok_username or "").strip(),
)
except ValueError as exc:

View File

@ -18,6 +18,11 @@ if str(_VENDOR_ROOT) not in sys.path:
DEFAULT_DC = "useast2a"
REQUIRED_COOKIES = ("sessionid", "tt-target-idc")
_DC_CANDIDATES = ("useast5a", "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:
@ -79,15 +84,18 @@ def save_session_from_values(
channel_pk: str,
*,
sessionid: str,
dc_id: str = DEFAULT_DC,
dc_id: str = "",
username: str = "",
) -> dict[str, Any]:
sid = str(sessionid or "").strip()
if not sid:
raise ValueError("sessionid 不能为空")
dc = str(dc_id or DEFAULT_DC).strip() or DEFAULT_DC
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)
@ -181,6 +189,79 @@ def _which(name: str) -> str | None:
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))

View File

@ -43,6 +43,9 @@ def _upload_sync(
if not sessionid:
raise ValueError("Cookie 缺少 sessionid")
working_dc = tiktok_session.ensure_working_datacenter(channel_pk)
cookies = tiktok_session.load_session_cookies(channel_pk)
tiktok_session.configure_vendor_paths()
from tiktok_uploader.cookies import save_cookies_to_file
from tiktok_uploader.tiktok import upload_video
@ -51,17 +54,27 @@ def _upload_sync(
session_user = channel_pk
visibility = _privacy_to_visibility(privacy_level)
ok = upload_video(
session_user,
str(path.resolve()),
(title or "video")[:2200],
schedule_time=0,
allow_comment=int(allow_comment),
allow_duet=int(allow_duet),
allow_stitch=int(allow_stitch),
visibility_type=visibility,
proxy=proxy or None,
)
try:
ok = upload_video(
session_user,
str(path.resolve()),
(title or "video")[:2200],
schedule_time=0,
allow_comment=int(allow_comment),
allow_duet=int(allow_duet),
allow_stitch=int(allow_stitch),
visibility_type=visibility,
proxy=proxy or None,
)
except KeyError as exc:
key = str(exc).strip("'\"")
if key == "project":
raise ValueError(
f"TikTok 会话机房不匹配(当前 {working_dc})。请重新粘贴 Cookie,并填写浏览器里的 tt-target-idc"
) from exc
raise ValueError(f"TikTok 上传失败:缺少字段 {key}") from exc
except SystemExit as exc:
raise ValueError("TikTok Cookie 缺少 sessionid,请重新粘贴") from exc
if not ok:
raise ValueError("TikTok 上传失败,请检查 Cookie 是否过期或 Node.js 是否可用")
return {

View File

@ -20,7 +20,7 @@ async function readTikTokCookies() {
Object.assign(byName, cookieMap(extra));
const sessionid = String(byName.sessionid || byName.sessionid_ss || "").trim();
const dc = String(byName["tt-target-idc"] || byName.tt_target_idc || "").trim() || "useast2a";
const dc = String(byName["tt-target-idc"] || byName.tt_target_idc || "").trim();
const username = String(byName["uniqueid"] || byName.uniqueId || "").trim();
return {
ok: Boolean(sessionid),

View File

@ -27,7 +27,7 @@
const list = await GM.cookie.list({ url: location.origin + "/" });
const map = Object.fromEntries((list || []).map((c) => [c.name, c.value]));
const sessionid = String(map.sessionid || map.sessionid_ss || "").trim();
const dc_id = String(map["tt-target-idc"] || "").trim() || "useast2a";
const dc_id = String(map["tt-target-idc"] || "").trim();
if (!sessionid) throw new Error("未找到 sessionid,请先登录 TikTok");
return { sessionid, dc_id, tiktok_username: "" };
}

View File

@ -93,7 +93,7 @@ export default function TikTokPage() {
const [sessionChannelId, setSessionChannelId] = useState("");
const [sessionId, setSessionId] = useState("");
const [sessionDcId, setSessionDcId] = useState("useast2a");
const [sessionDcId, setSessionDcId] = useState("");
const [sessionUsername, setSessionUsername] = useState("");
const [savingSession, setSavingSession] = useState(false);
const [showSessionForm, setShowSessionForm] = useState(false);
@ -166,7 +166,7 @@ export default function TikTokPage() {
const username = String((data as any)?.tiktok_username || "").trim();
if (!sessionid) throw new Error("剪贴板里没有 sessionid");
setSessionId(sessionid);
setSessionDcId(dc_id || "useast2a");
setSessionDcId(dc_id);
if (username) setSessionUsername(username);
};
@ -213,7 +213,7 @@ export default function TikTokPage() {
method: "POST",
body: JSON.stringify({
sessionid: sessionId.trim(),
dc_id: sessionDcId.trim() || "useast2a",
dc_id: sessionDcId.trim(),
tiktok_username: sessionUsername.trim(),
}),
});
@ -280,7 +280,7 @@ export default function TikTokPage() {
const openSessionForm = (id: string, ch?: Channel) => {
setSessionChannelId(id);
setSessionId("");
setSessionDcId("useast2a");
setSessionDcId("");
setSessionUsername(ch?.tiktok_username || "");
setShowForm(false);
setShowSessionForm(true);
@ -581,7 +581,7 @@ export default function TikTokPage() {
id="tiktok-dc-id"
value={sessionDcId}
onChange={(e) => setSessionDcId(e.target.value)}
placeholder="useast2a"
placeholder="留空则自动探测"
className="mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-3 py-2 text-sm"
/>
</label>

View File

@ -60,6 +60,46 @@ def _patch_vendor_upload() -> None:
text = text.replace(login_marker, login_patch)
changed = True
old_cookies = (
'\tsession.cookies.set("sessionid", session_id, domain=".tiktok.com")\n'
'\tsession.cookies.set("tt-target-idc", dc_id, domain=".tiktok.com")\n'
)
new_cookies = (
'\tsession.cookies.set("sessionid", session_id, domain=".tiktok.com")\n'
'\tsession.cookies.set("sessionid_ss", session_id, domain=".tiktok.com")\n'
'\tsession.cookies.set("tt-target-idc", dc_id, domain=".tiktok.com")\n'
)
if old_cookies in text:
text = text.replace(old_cookies, new_cookies)
changed = True
old_project = (
'\tif not assert_success(project_url, r):\n'
'\t\treturn False\n\n'
'\t# get project_id\n'
'\tproject_id = r.json()["project"]["project_id"]\n'
)
new_project = (
'\tif not assert_success(project_url, r):\n'
'\t\treturn False\n\n'
'\t# get project_id\n'
'\ttry:\n'
'\t\tpayload = r.json()\n'
'\texcept Exception:\n'
'\t\traise RuntimeError("TikTok 创建项目失败:返回不是 JSON")\n'
'\tproject = payload.get("project") if isinstance(payload, dict) else None\n'
'\tif not isinstance(project, dict) or not project.get("project_id"):\n'
'\t\tmsg = str((payload or {}).get("status_msg") or "").strip()\n'
'\t\tcode = (payload or {}).get("status_code")\n'
'\t\traise RuntimeError(\n'
'\t\t\tf"TikTok 会话无效或机房不匹配(status_code={code} {msg})。请重新粘贴 Cookie 并填写 tt-target-idc"\n'
'\t\t)\n'
'\tproject_id = project["project_id"]\n'
)
if old_project in text:
text = text.replace(old_project, new_project)
changed = True
old = (
'\t\t\t\t"privacy_setting_info": {\n'
'\t\t\t\t\t"visibility_type": 0,\n'