# -*- coding: utf-8 -*- """TikTok OAuth — click-to-authorize, stores tokens on channel.""" from __future__ import annotations import secrets import time from typing import Any from urllib.parse import urlencode import httpx from . import db from . import tiktok_db TIKTOK_SCOPES = "user.info.basic,video.publish" _oauth_states: dict[str, tuple[str, float, str, str]] = {} def _cfg() -> dict[str, Any]: return db.get_settings_map() def _overseas_kwargs(*, timeout: float = 30.0) -> dict[str, Any]: try: from . import egress_hub return egress_hub.overseas_httpx_kwargs(timeout=timeout) except Exception: return {"timeout": timeout, "trust_env": False} def resolve_client_key_secret(cfg: dict[str, Any] | None = None) -> tuple[str, str]: settings = cfg or _cfg() key = str(settings.get("tiktok_oauth_client_key") or "").strip() secret = str(settings.get("tiktok_oauth_client_secret") or "").strip() return key, secret def oauth_configured(cfg: dict[str, Any] | None = None) -> bool: key, secret = resolve_client_key_secret(cfg) return bool(key and secret) def resolve_redirect_uri(request_base: str = "") -> str: """Callback follows the origin that started OAuth (request host first).""" from .config import settings as app_settings req = str(request_base or "").strip().rstrip("/") pub = str(getattr(app_settings, "public_base_url", "") or "").strip().rstrip("/") base = req or pub if base: return f"{base}/api/tiktok/oauth/callback/" custom = str(_cfg().get("tiktok_oauth_redirect_uri") or "").strip().rstrip("/") if custom: return custom.rstrip("/") + "/" raise ValueError("无法推导 TikTok OAuth 回调地址:请用站点域名打开,或设置 DY_PUBLIC_BASE_URL") def setup_checklist(cfg: dict[str, Any] | None = None) -> dict[str, Any]: settings = cfg or _cfg() key, secret = resolve_client_key_secret(settings) redirect = resolve_redirect_uri() return { "oauth_configured": bool(key and secret), "redirect_uri": redirect, "scopes": TIKTOK_SCOPES.split(","), "steps": [ { "id": "register", "title": "注册 TikTok 开发者应用", "url": "https://developers.tiktok.com/apps", "done": bool(key), }, { "id": "scopes", "title": "申请 video.publish 权限(Direct Post)", "url": "https://developers.tiktok.com/doc/content-posting-api-get-started", "done": bool(key), }, { "id": "redirect", "title": f"配置 Redirect URI:{redirect}", "url": "https://developers.tiktok.com/apps", "done": bool(key), }, { "id": "credentials", "title": "填写 Client Key / Client Secret", "done": bool(key and secret), }, { "id": "account", "title": "添加 TikTok 账号并点击授权", "done": len(tiktok_db.list_tiktok_channels()) > 0 and any(str(c.get("refresh_token") or "").strip() for c in tiktok_db.list_tiktok_channels()), }, ], "note_unaudited": "未审核应用只能发布 SELF_ONLY(仅自己可见),审核通过后可改为 PUBLIC_TO_EVERYONE。", } def build_authorize_url(*, channel_pk: str, request_base: str = "") -> str: cfg = _cfg() client_key, client_secret = resolve_client_key_secret(cfg) if not client_key or not client_secret: raise ValueError("请先在 TikTok 页面填写 Client Key / Client Secret") channel = tiktok_db.get_tiktok_channel(channel_pk) if not channel: raise ValueError("账号不存在") now = time.time() for k, packed in list(_oauth_states.items()): if packed[1] < now: _oauth_states.pop(k, None) state = secrets.token_urlsafe(24) _oauth_states[state] = (channel_pk, now + 600, client_key, client_secret) params = { "client_key": client_key, "redirect_uri": resolve_redirect_uri(request_base), "response_type": "code", "scope": TIKTOK_SCOPES, "state": state, } return "https://www.tiktok.com/v2/auth/authorize/?" + urlencode(params) async def exchange_code(*, code: str, state: str, request_base: str = "") -> dict[str, Any]: packed = _oauth_states.pop(state, None) if not packed: raise ValueError("授权 state 无效或已过期,请重新点击授权") channel_pk, exp, client_key, client_secret = packed if exp < time.time(): raise ValueError("授权已过期,请重新点击授权") redirect_uri = resolve_redirect_uri(request_base) async with httpx.AsyncClient(**_overseas_kwargs(timeout=45.0)) as client: resp = await client.post( "https://open.tiktokapis.com/v2/oauth/token/", headers={"Content-Type": "application/x-www-form-urlencoded"}, data={ "client_key": client_key, "client_secret": client_secret, "code": code, "grant_type": "authorization_code", "redirect_uri": redirect_uri, }, ) data = resp.json() if resp.content else {} if resp.status_code >= 400 or not data.get("access_token"): err = data.get("error_description") or data.get("message") or data or resp.text raise ValueError(f"换取 token 失败: {err}") access = str(data.get("access_token") or "") refresh = str(data.get("refresh_token") or "").strip() open_id = str(data.get("open_id") or "") expires_in = int(data.get("expires_in") or 86400) if not refresh: channel = tiktok_db.get_tiktok_channel(channel_pk) or {} refresh = str(channel.get("refresh_token") or "").strip() if not refresh: raise ValueError("未拿到 refresh_token,请撤销授权后重试") username = "" try: info = await client.get( "https://open.tiktokapis.com/v2/user/info/", params={"fields": "open_id,display_name,username"}, headers={"Authorization": f"Bearer {access}"}, ) info_data = info.json() if info.content else {} user = (info_data.get("data") or {}).get("user") or {} username = str(user.get("display_name") or user.get("username") or "") except Exception: pass patch: dict[str, Any] = { "client_key": client_key, "client_secret": client_secret, "refresh_token": refresh, "access_token": access, "token_expires_at": time.time() + max(300, expires_in - 60), "tiktok_open_id": open_id, "oauth_ok": 1, "oauth_checked_at": time.time(), "oauth_error": "", } if open_id: patch["tiktok_open_id"] = open_id if username: ch = tiktok_db.get_tiktok_channel(channel_pk) or {} if not str(ch.get("name") or "").strip() or ch.get("name") == "TikTok 账号": patch["name"] = username patch["tiktok_username"] = username updated = tiktok_db.update_tiktok_channel(channel_pk, **patch) return {"ok": True, "channel": updated, "username": username, "open_id": open_id} def channel_oauth_creds(channel: dict[str, Any], cfg: dict[str, Any] | None = None) -> dict[str, str]: settings = cfg or _cfg() g_key, g_secret = resolve_client_key_secret(settings) return { "client_key": str(channel.get("client_key") or g_key).strip(), "client_secret": str(channel.get("client_secret") or g_secret).strip(), "refresh_token": str(channel.get("refresh_token") or "").strip(), "access_token": str(channel.get("access_token") or "").strip(), "token_expires_at": str(channel.get("token_expires_at") or 0), } async def refresh_access_token( *, client_key: str, client_secret: str, refresh_token: str, ) -> dict[str, str]: if not (client_key and client_secret and refresh_token): raise ValueError("缺少 TikTok OAuth 凭证") async with httpx.AsyncClient(**_overseas_kwargs(timeout=45.0)) as client: resp = await client.post( "https://open.tiktokapis.com/v2/oauth/token/", headers={"Content-Type": "application/x-www-form-urlencoded"}, data={ "client_key": client_key, "client_secret": client_secret, "grant_type": "refresh_token", "refresh_token": refresh_token, }, ) data = resp.json() if resp.content else {} if resp.status_code >= 400 or not data.get("access_token"): raise ValueError(f"OAuth 刷新失败: {data.get('error_description') or data or resp.text}") return { "access_token": str(data["access_token"]), "refresh_token": str(data.get("refresh_token") or refresh_token), "expires_in": str(data.get("expires_in") or 86400), "open_id": str(data.get("open_id") or ""), } async def probe_channel_oauth(channel: dict[str, Any], cfg: dict[str, Any] | None = None) -> dict[str, Any]: creds = channel_oauth_creds(channel, cfg) cid = str(channel.get("id") or "") now = time.time() if not cid: return {"ok": False, "error": "账号 ID 缺失"} if not creds["refresh_token"]: tiktok_db.update_tiktok_channel(cid, oauth_ok=0, oauth_checked_at=now, oauth_error="未授权") return {"ok": False, "error": "未授权", "channel_id": cid} try: tok = await refresh_access_token( client_key=creds["client_key"], client_secret=creds["client_secret"], refresh_token=creds["refresh_token"], ) tiktok_db.update_tiktok_channel( cid, access_token=tok["access_token"], refresh_token=tok["refresh_token"], token_expires_at=now + max(300, int(tok.get("expires_in") or 86400) - 60), oauth_ok=1, oauth_checked_at=now, oauth_error="", ) return {"ok": True, "channel_id": cid} except Exception as exc: err = str(exc)[:240] tiktok_db.update_tiktok_channel(cid, oauth_ok=0, oauth_checked_at=now, oauth_error=err) return {"ok": False, "error": err, "channel_id": cid}