douyinWEB/backend/app/tiktok_upload.py
eric d8fdeaa71c TikTok: Cookie 上传(TiktokAutoUploader),替代开发者 OAuth
账号粘贴 sessionid 即可上传;TikTok 模块独立,默认关闭不影响监控/Shorts。

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

112 lines
3.4 KiB
Python

# -*- 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 import tiktok as ttuploader
# Ensure cookie file exists where upstream loader expects it.
from tiktok_uploader.cookies import save_cookies_to_file
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 = ttuploader.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]
return await 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,
)