douyinWEB/backend/app/tiktok_upload.py
eric 1515783760 fix: TikTok Cookie 上传不再依赖 undetected_chromedriver
Cookie 路径直接 import tiktok.upload_video,vendor 补丁将 Browser 改为 login 内 lazy import,避免服务器缺 Chrome 驱动导致上传失败。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-14 10:56:19 -05:00

116 lines
3.7 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")
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)
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,
)
if not ok:
raise ValueError("TikTok 上传失败,请检查 Cookie 是否过期或 Node.js 是否可用")
return {
"ok": True,
"publish_id": f"cookie-{uuid.uuid4().hex[:12]}",
"video_id": "",
"mode": "cookie",
"privacy_level": privacy_level,
}
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