douyinWEB/backend/app/tiktok_upload.py
2026-08-14 22:00:33 -05:00

171 lines
5.7 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 upload via TiktokAutoUploader (cookie session + requests)."""
from __future__ import annotations
import asyncio
import sys
import uuid
from pathlib import Path
from typing import Any
from . import tiktok_session
_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))
def _privacy_to_visibility(privacy_level: str) -> int:
pl = str(privacy_level or "").strip().upper()
if pl in {"SELF_ONLY", "PRIVATE"}:
return 1
return 0
def _friendly_upload_error(log: str) -> str:
text = str(log or "")
low = text.lower()
if is_platform_rate_limit(text):
return "TikTok 官方限流:发得太快或达日上限(如 status 2158)。将每小时自动试传,成功后解除提示"
if "login expired" in low or '"status_code": 8' in text:
return "TikTok Cookie 已过期,请重新粘贴 sessionid"
if "invalid parameters" in low:
return "TikTok 拒绝发布参数,请稍后重试 1 次"
tail = " ".join(line.strip() for line in text.strip().splitlines()[-4:] if line.strip())[:240]
return tail or "TikTok 上传失败"
def is_platform_rate_limit(err: str) -> bool:
"""True when TikTok itself rejects for posting frequency / daily spam caps."""
text = str(err or "")
low = text.lower()
needles = (
"2158",
"posting videos too fast",
"take a rest",
"spam_risk",
"too_many_posts",
"spam_risk_too_many_posts",
"rate_limit",
"rate limit",
"daily upload",
"too many posts",
"官方限流",
)
return any(n in low or n in text for n in needles)
def _upload_sync(
*,
channel_pk: str,
file_path: str,
title: str,
privacy_level: str = "PUBLIC_TO_EVERYONE",
allow_comment: int = 1,
allow_duet: int = 0,
allow_stitch: int = 0,
proxy: str | None = None,
) -> dict[str, Any]:
path = Path(file_path)
if not path.is_file():
raise ValueError("成片文件不存在")
cookies = tiktok_session.load_session_cookies(channel_pk)
if not cookies:
raise ValueError("账号未配置 Cookie 会话,请先粘贴 sessionid")
sessionid = next((c.get("value") for c in cookies if c.get("name") == "sessionid"), "")
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
save_cookies_to_file(cookies, tiktok_session.session_filename(channel_pk), str(tiktok_session.cookies_dir()))
session_user = channel_pk
visibility = _privacy_to_visibility(privacy_level)
import contextlib
import io
buf = io.StringIO()
try:
with contextlib.redirect_stdout(buf), contextlib.redirect_stderr(buf):
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
log = buf.getvalue()
if log:
print(log, end="")
published = "Published successfully" in log
if published or ok is True:
return {
"ok": True,
"publish_id": f"cookie-{uuid.uuid4().hex[:12]}",
"video_id": "",
"mode": "cookie",
"privacy_level": privacy_level,
"dc_id": working_dc,
}
raise ValueError(_friendly_upload_error(log))
async def upload_tiktok_mp4(
*,
file_path: str,
title: str,
description: str = "",
privacy_level: str = "PUBLIC_TO_EVERYONE",
channel_pk: str = "",
client_key: str = "",
client_secret: str = "",
refresh_token: str = "",
access_token: str = "",
token_expires_at: float = 0,
disable_duet: bool = False,
disable_comment: bool = False,
disable_stitch: bool = False,
proxy: str | None = None,
) -> dict[str, Any]:
_ = (description, client_key, client_secret, refresh_token, access_token, token_expires_at)
if not channel_pk:
raise ValueError("缺少 channel_pk")
# 只用 title;不再把 description 拼进文案(避免带上直播间名)
caption = (title or "").strip()[:2200]
try:
return await asyncio.wait_for(
asyncio.to_thread(
_upload_sync,
channel_pk=channel_pk,
file_path=file_path,
title=caption,
privacy_level=privacy_level,
allow_comment=0 if disable_comment else 1,
allow_duet=0 if disable_duet else 1,
allow_stitch=0 if disable_stitch else 1,
proxy=proxy,
),
timeout=180,
)
except TimeoutError as exc:
raise ValueError("TikTok 上传超时(180s),Cookie 可能失效或签名服务卡住,请重试") from exc