douyinWEB/backend/app/tiktok_upload.py
eric c7a7275229 fix: TikTok 发布成功后正确记为已上传,并禁止并发重复上传
vendor 的 upload_video 成功后没有 return True,被误判失败;同时立即上传会抢正在上传的任务导致重复发布。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-14 11:31:31 -05:00

142 lines
4.8 KiB
Python
Raw 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 _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,
}
tail = " ".join(line.strip() for line in log.strip().splitlines()[-4:] if line.strip())[:240]
raise ValueError(
tail or "TikTok 上传失败,请检查 Cookie 是否过期或 Node.js 是否可用"
)
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")
caption = (title or "").strip()
if description.strip() and description.strip() not in caption:
caption = f"{caption}\n{description.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