clipwright/clipwright/integrations/youtube_data.py

154 lines
5.7 KiB
Python

"""Minimal YouTube Data API v3 client -- first comment only (PLAN #6).
The Shorts "Related video" link and comment pinning are Studio-UI only and are
**not** exposed by any API, so this module deliberately does one thing: post a
top-level comment on a video via ``commentThreads.insert``. Pinning that comment
stays manual.
Auth is a real-channel OAuth refresh token (service accounts do not work for
this scope). Credentials come from the environment and the integration is
**opt-in**: with any of them missing, :func:`is_configured` is false and no
network call is ever made. Callers must check :func:`is_configured` (or handle
:class:`YoutubeDataError`) before asking for a comment.
Quota: ``commentThreads.insert`` costs 50 units of the default 10,000/day
project quota (~200 comments/day). That is the whole reason posting is a
deliberate, caller-triggered action and never automatic.
Blocking, like ``postiz.py``: call through ``asyncio.to_thread`` from async
handlers. Every function accepts an optional pre-built ``httpx.Client`` so tests
can inject a ``httpx.MockTransport`` and no live OAuth is ever needed.
"""
from __future__ import annotations
import os
from typing import Any, Dict, Optional
import httpx
TOKEN_URI = "https://oauth2.googleapis.com/token"
COMMENT_THREADS_URL = "https://www.googleapis.com/youtube/v3/commentThreads"
# Required by insert (the comment posting endpoint). Read-only analytics use a
# different scope; this module never reads.
SCOPE = "https://www.googleapis.com/auth/youtube.force-ssl"
# Environment variable names, kept as constants so the API layer can name them
# in its "not configured" message without duplicating strings.
CLIENT_ID_ENV = "YOUTUBE_OAUTH_CLIENT_ID"
CLIENT_SECRET_ENV = "YOUTUBE_OAUTH_CLIENT_SECRET"
REFRESH_TOKEN_ENV = "YOUTUBE_OAUTH_REFRESH_TOKEN"
TOKEN_URI_ENV = "YOUTUBE_OAUTH_TOKEN_URI"
class YoutubeDataError(Exception):
"""A missing config or non-2xx response from the YouTube Data API.
Carries the status and body so the FastAPI layer can translate it into the
same status/detail it would have surfaced otherwise.
"""
def __init__(self, status_code: int, detail: str):
super().__init__(detail)
self.status_code = status_code
self.detail = detail
def _env(name: str, default: Optional[str] = None) -> Optional[str]:
value = os.environ.get(name)
if value is None:
return default
value = value.strip()
return value or default
def credentials() -> Dict[str, Optional[str]]:
"""The OAuth credentials read from the environment (values may be None)."""
return {
"client_id": _env(CLIENT_ID_ENV),
"client_secret": _env(CLIENT_SECRET_ENV),
"refresh_token": _env(REFRESH_TOKEN_ENV),
"token_uri": _env(TOKEN_URI_ENV, TOKEN_URI),
}
def is_configured() -> bool:
"""True when a refresh-token flow can run. False = no-op, never called."""
creds = credentials()
return all(creds[key] for key in ("client_id", "client_secret", "refresh_token"))
def _access_token(client: httpx.Client, creds: Dict[str, Optional[str]]) -> str:
resp = client.post(str(creds["token_uri"]), data={
"client_id": creds["client_id"],
"client_secret": creds["client_secret"],
"refresh_token": creds["refresh_token"],
"grant_type": "refresh_token",
})
if resp.status_code != 200:
raise YoutubeDataError(
502,
f"YouTube OAuth token refresh failed: {(resp.text or '')[:300]}",
)
try:
token = (resp.json() or {}).get("access_token")
except ValueError:
token = None
if not token:
raise YoutubeDataError(502, "YouTube OAuth token refresh returned no access_token")
return token
def post_first_comment(video_id: str, text: str, timeout: float = 60.0,
client: Optional[httpx.Client] = None) -> Dict[str, Any]:
"""Post ``text`` as a top-level comment on ``video_id``.
Returns the API's ``commentThreads.insert`` response (id + snippet).
Raises :class:`YoutubeDataError` when unconfigured, given bad input, or when
YouTube rejects the insert. ``client`` is the test seam; pass an
``httpx.Client`` built with a ``MockTransport`` to exercise this offline.
"""
if not video_id or not str(video_id).strip():
raise YoutubeDataError(400, "video_id is required")
if not text or not str(text).strip():
raise YoutubeDataError(400, "comment text is required")
if not is_configured():
raise YoutubeDataError(
400,
"YouTube Data API is not configured; set "
f"{CLIENT_ID_ENV}, {CLIENT_SECRET_ENV} and {REFRESH_TOKEN_ENV}",
)
owns_client = client is None
client = client or httpx.Client(timeout=timeout)
try:
token = _access_token(client, credentials())
resp = client.post(
COMMENT_THREADS_URL,
params={"part": "snippet"},
headers={"Authorization": f"Bearer {token}"},
json={"snippet": {
"videoId": str(video_id).strip(),
"topLevelComment": {
"snippet": {"textOriginal": str(text)},
},
}},
)
finally:
if owns_client:
client.close()
if resp.status_code not in (200, 201):
# 4xx are the caller's (invalid video / scope); 5xx become 502 so the
# API layer does not claim the upstream is down with a gateway code
# that came from YouTube, not this server.
status = resp.status_code if resp.status_code < 500 else 502
raise YoutubeDataError(
status,
f"YouTube commentThreads.insert failed: {(resp.text or '')[:300]}",
)
try:
return resp.json() or {}
except ValueError:
return {}