# -*- coding: utf-8 -*- """TikTok video upload via Content Posting API (Direct Post).""" from __future__ import annotations import asyncio from pathlib import Path from typing import Any import httpx from . import tiktok_oauth async def _ensure_access_token( *, client_key: str, client_secret: str, refresh_token: str, access_token: str = "", token_expires_at: float = 0, ) -> tuple[str, str]: import time if access_token and token_expires_at > time.time() + 120: return access_token, refresh_token tok = await tiktok_oauth.refresh_access_token( client_key=client_key, client_secret=client_secret, refresh_token=refresh_token, ) return tok["access_token"], tok.get("refresh_token") or refresh_token async def query_creator_info(access_token: str) -> dict[str, Any]: async with httpx.AsyncClient(timeout=30.0, trust_env=False) as client: resp = await client.post( "https://open.tiktokapis.com/v2/post/publish/creator_info/query/", headers={ "Authorization": f"Bearer {access_token}", "Content-Type": "application/json; charset=UTF-8", }, json={}, ) data = resp.json() if resp.content else {} if resp.status_code >= 400: err = (data.get("error") or {}).get("message") or data or resp.text raise ValueError(f"查询创作者信息失败: {err}") return (data.get("data") or {}) async def upload_tiktok_mp4( *, file_path: str, title: str, description: str = "", privacy_level: str = "SELF_ONLY", 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, ) -> dict[str, Any]: path = Path(file_path) if not path.is_file(): raise ValueError("成片文件不存在") access, new_refresh = await _ensure_access_token( client_key=client_key, client_secret=client_secret, refresh_token=refresh_token, access_token=access_token, token_expires_at=token_expires_at, ) creator = await query_creator_info(access) allowed = creator.get("privacy_level_options") or ["SELF_ONLY"] pl = privacy_level if privacy_level in allowed else (allowed[0] if allowed else "SELF_ONLY") try: size = path.stat().st_size raw = path.read_bytes() except FileNotFoundError as exc: raise ValueError("成片文件不存在") from exc chunk_size = min(size, 10 * 1024 * 1024) or size chunk_count = max(1, (size + chunk_size - 1) // chunk_size) init_body = { "post_info": { "title": (title or "video")[:150], "description": (description or "")[:2200], "privacy_level": pl, "disable_duet": disable_duet, "disable_comment": disable_comment, "disable_stitch": disable_stitch, "video_cover_timestamp_ms": 1000, }, "source_info": { "source": "FILE_UPLOAD", "video_size": size, "chunk_size": chunk_size, "total_chunk_count": chunk_count, }, } async with httpx.AsyncClient(timeout=300.0, trust_env=False) as client: init = await client.post( "https://open.tiktokapis.com/v2/post/publish/video/init/", headers={ "Authorization": f"Bearer {access}", "Content-Type": "application/json; charset=UTF-8", }, json=init_body, ) init_data = init.json() if init.content else {} if init.status_code >= 400: err = (init_data.get("error") or {}).get("message") or init_data or init.text raise ValueError(f"初始化上传失败: {str(err)[:400]}") upload_url = (init_data.get("data") or {}).get("upload_url") or "" publish_id = (init_data.get("data") or {}).get("publish_id") or "" if not upload_url or not publish_id: raise ValueError(f"初始化上传失败: 缺少 upload_url/publish_id") headers = { "Content-Type": "video/mp4", "Content-Length": str(size), "Content-Range": f"bytes 0-{size - 1}/{size}", } put = await client.put(upload_url, headers=headers, content=raw) if put.status_code >= 400: raise ValueError(f"上传视频失败: {put.text[:400]}") # Poll publish status for _ in range(60): st_resp = await client.post( "https://open.tiktokapis.com/v2/post/publish/status/fetch/", headers={ "Authorization": f"Bearer {access}", "Content-Type": "application/json; charset=UTF-8", }, json={"publish_id": publish_id}, ) st_data = st_resp.json() if st_resp.content else {} status = str((st_data.get("data") or {}).get("status") or "") if status in {"PUBLISH_COMPLETE", "SEND_TO_USER_INBOX"}: break if status in {"FAILED"}: fail = (st_data.get("data") or {}).get("fail_reason") or status raise ValueError(f"TikTok 发布失败: {fail}") await asyncio.sleep(3) else: raise ValueError("TikTok 发布超时,请稍后在 TikTok 查看") return { "ok": True, "publish_id": publish_id, "video_id": publish_id, "access_token": access, "refresh_token": new_refresh, "privacy_level": pl, }