Files
MateuusandClaude Opus 5.5 84f30bbc2d CenaForge: primeira versão pública
Gerador de vídeos narrativos (Godot + FFmpeg), painel Next.js, serviço de voz,
Clipador de lives e Publicador para YouTube, TikTok e Instagram.

Inclui a leitura das visualizações dos posts para o Dashboard e o botão
"Publicar no <rede>" nos cartões das publicações.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:35:09 -03:00

272 lines
15 KiB
Python
Raw Permalink 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.
"""YouTube pela API oficial (Data API v3).
OAuth: cliente "Desktop app" do Google Cloud, PKCE (S256, base64url) e redirect loopback
http://127.0.0.1:4530/oauth/callback/youtube. Envio: `videos.insert` resumable em blocos; capa por
`thumbnails.set` depois do processamento (falha na capa não derruba o envio: o vídeo já está no ar).
"""
from __future__ import annotations
import time
from typing import Callable
from urllib.parse import urlencode
import httpx
from .base import (JobSpec, Progress, PublishError, PublishResult, Sleep, Tokens, challenge_s256_base64url,
expires_in, file_size, network_error, response_json)
AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth"
TOKEN_URL = "https://oauth2.googleapis.com/token"
API = "https://www.googleapis.com/youtube/v3"
UPLOAD_URL = "https://www.googleapis.com/upload/youtube/v3/videos"
THUMB_URL = "https://www.googleapis.com/upload/youtube/v3/thumbnails/set"
SCOPES = ["https://www.googleapis.com/auth/youtube.upload", "https://www.googleapis.com/auth/youtube.readonly"]
# Blocos do upload resumable: múltiplos de 256 KiB (exigência do Google). 8 MiB dá progresso sem muita requisição.
CHUNK = 8 * 1024 * 1024
PRIVACY = {"public": "public", "unlisted": "unlisted", "private": "private"}
TokenProvider = Callable[[bool], str] # (forçar refresh?) -> access token válido
def _google_error(response: httpx.Response) -> tuple[str, str]:
"""(motivo, mensagem) do erro do Google (`error.errors[0].reason`)."""
data = response_json(response)
error = data.get("error")
if isinstance(error, dict):
errors = error.get("errors") or [{}]
return str(errors[0].get("reason") or error.get("status") or ""), str(error.get("message") or "")
return str(error or ""), str(data.get("error_description") or response.text[:200])
def explain_upload_error(response: httpx.Response) -> PublishError:
reason, message = _google_error(response)
if response.status_code == 401:
return PublishError("A autorização do YouTube não vale mais. Conecte o YouTube de novo em Canais de publicação.",
"expired")
if reason in ("quotaExceeded", "uploadLimitExceeded", "rateLimitExceeded", "dailyLimitExceeded"):
return PublishError("O YouTube não aceita mais envios hoje por este app (a cota diária acabou). "
"Tente de novo amanhã — a cota zera à meia-noite do horário do Pacífico (5h de Brasília).")
if reason == "youtubeSignupRequired":
return PublishError("Esta conta Google ainda não tem um canal do YouTube. Crie o canal no YouTube e conecte de novo.")
if reason in ("forbidden", "insufficientPermissions"):
return PublishError("O YouTube recusou o envio por falta de permissão. Conecte de novo e marque a permissão "
"de enviar vídeos.", "expired")
if reason in ("invalidTitle", "invalidDescription", "invalidTags"):
return PublishError(f"O YouTube recusou o título, a descrição ou as tags do vídeo ({message}). Ajuste o texto e tente de novo.")
if reason == "invalidPublishAt":
return PublishError("O horário de agendamento foi recusado pelo YouTube (precisa ser no futuro). Escolha outro horário.")
return PublishError(f"O YouTube recusou o envio (código {response.status_code}{', ' + reason if reason else ''}). {message}".strip())
def clean_text(text: str, limit: int) -> str:
# O YouTube recusa "<" e ">" no título e na descrição.
return text.replace("<", "‹").replace(">", "›").strip()[:limit]
def clean_tags(tags: list[str]) -> list[str]:
"""Tags sem vírgula/aspas e com no máximo 500 caracteres somados (limite do YouTube)."""
out: list[str] = []
total = 0
for tag in tags:
tag = tag.replace(",", " ").replace('"', "").replace("<", "").replace(">", "").strip().lstrip("#")
if not tag:
continue
cost = len(tag) + (2 if " " in tag else 0) + (1 if out else 0)
if total + cost > 500:
break
out.append(tag)
total += cost
return out
class YouTubeApi:
def __init__(self, client: httpx.Client, client_id: str, client_secret: str, redirect_uri: str,
sleep: Sleep = time.sleep):
self.client, self.client_id, self.client_secret = client, client_id, client_secret
self.redirect_uri, self.sleep = redirect_uri, sleep
# ---------- OAuth
def authorize_url(self, state: str, verifier: str) -> str:
params = {
"client_id": self.client_id, "redirect_uri": self.redirect_uri, "response_type": "code",
"scope": " ".join(SCOPES), "state": state, "code_challenge": challenge_s256_base64url(verifier),
"code_challenge_method": "S256",
# offline + consent: garante o refresh token (sem ele seria preciso conectar de novo a cada hora).
"access_type": "offline", "prompt": "consent", "include_granted_scopes": "true",
}
return f"{AUTH_URL}?{urlencode(params)}"
def _token_request(self, data: dict) -> dict:
try:
response = self.client.post(TOKEN_URL, data={**data, "client_id": self.client_id,
"client_secret": self.client_secret})
except httpx.HTTPError as exc:
raise network_error("Google", exc) from exc
body = response_json(response)
if response.status_code >= 400:
error = str(body.get("error") or "")
if error == "invalid_grant":
raise PublishError("A autorização do YouTube expirou ou foi revogada. Conecte o YouTube de novo em "
"Canais de publicação. (Se acontece a cada 7 dias, o app do Google Cloud ainda está "
"em \"Testing\": coloque-o \"In production\".)", "expired")
if error in ("invalid_client", "unauthorized_client"):
raise PublishError("O Google recusou o Client ID/Secret do app. Confira em Configurações → Apps das redes "
"(o cliente precisa ser do tipo \"App para computador\" / Desktop app).")
raise PublishError(f"O Google recusou a autorização ({error or response.status_code}). Tente conectar de novo.")
return body
def exchange_code(self, code: str, verifier: str) -> Tokens:
body = self._token_request({"code": code, "code_verifier": verifier, "grant_type": "authorization_code",
"redirect_uri": self.redirect_uri})
if not body.get("refresh_token"):
raise PublishError("O Google não devolveu a autorização permanente (refresh token). Remova o acesso do app em "
"myaccount.google.com/permissions e conecte de novo.")
return Tokens(body["access_token"], expires_in(body.get("expires_in")), body["refresh_token"], None)
def refresh(self, refresh_token: str) -> Tokens:
body = self._token_request({"refresh_token": refresh_token, "grant_type": "refresh_token"})
# O Google mantém o mesmo refresh token (só devolve outro se rotacionar).
return Tokens(body["access_token"], expires_in(body.get("expires_in")), body.get("refresh_token") or refresh_token, None)
def channel(self, access_token: str) -> tuple[str | None, str | None, str | None]:
"""(nome do canal, @handle, id do canal) — None se não der para ler."""
try:
response = self.client.get(f"{API}/channels", params={"part": "snippet", "mine": "true"},
headers={"Authorization": f"Bearer {access_token}"})
except httpx.HTTPError:
return None, None, None
items = response_json(response).get("items") or []
if response.status_code != 200 or not items:
return None, None, None
snippet = items[0].get("snippet") or {}
return snippet.get("title"), snippet.get("customUrl"), items[0].get("id")
# ---------- envio
def video_body(self, spec: JobSpec) -> dict:
status: dict = {
"privacyStatus": PRIVACY.get(spec.privacy, "public"),
"selfDeclaredMadeForKids": bool(spec.made_for_kids),
"containsSyntheticMedia": bool(spec.ai_generated),
}
if spec.publish_at:
# Agendamento nativo: o YouTube exige `private` + `publishAt`; ele mesmo torna público na hora.
status["privacyStatus"] = "private"
status["publishAt"] = spec.publish_at
snippet = {"title": clean_text(spec.title, 100) or "Vídeo", "description": clean_text(spec.caption, 5000)}
tags = clean_tags(spec.tags)
if tags:
snippet["tags"] = tags
return {"snippet": snippet, "status": status}
def upload(self, spec: JobSpec, token: TokenProvider, progress: Progress) -> PublishResult:
total = file_size(spec.file)
progress("Abrindo o envio no YouTube…", 0.02)
session_url = self._start_session(spec, total, token)
video = self._send_chunks(spec, session_url, total, token, progress)
video_id = video.get("id")
if not video_id:
raise PublishError("O YouTube terminou o envio mas não devolveu o ID do vídeo. Confira no YouTube Studio antes "
"de tentar de novo (pode ter subido).")
url = f"https://youtu.be/{video_id}"
step = (f"Agendado no YouTube para {spec.publish_at}" if spec.publish_at else "Publicado no YouTube")
if spec.cover:
progress("Aplicando a capa (esperando o YouTube processar o vídeo)…", 0.95)
cover_problem = self._set_thumbnail(video_id, spec, token)
if cover_problem:
step += f"; a capa não foi aplicada ({cover_problem})"
return PublishResult(video_id, url, False, step)
def _start_session(self, spec: JobSpec, total: int, token: TokenProvider) -> str:
for attempt in (0, 1):
try:
response = self.client.post(
UPLOAD_URL, params={"uploadType": "resumable", "part": "snippet,status"},
json=self.video_body(spec),
headers={"Authorization": f"Bearer {token(attempt == 1)}", "X-Upload-Content-Type": "video/*",
"X-Upload-Content-Length": str(total)})
except httpx.HTTPError as exc:
raise network_error("YouTube", exc) from exc
if response.status_code == 401 and attempt == 0:
continue # access token venceu: renova e tenta uma vez
if response.status_code != 200 or not response.headers.get("location"):
raise explain_upload_error(response)
return response.headers["location"]
raise PublishError("A autorização do YouTube não vale mais. Conecte de novo.", "expired")
def _send_chunks(self, spec: JobSpec, session_url: str, total: int, token: TokenProvider,
progress: Progress) -> dict:
offset = 0
retries = 0
with spec.file.open("rb") as handle:
while True:
handle.seek(offset)
data = handle.read(CHUNK)
end = offset + len(data) - 1
headers = {"Authorization": f"Bearer {token(False)}", "Content-Type": "video/*",
"Content-Range": f"bytes {offset}-{end}/{total}" if data else f"bytes */{total}"}
try:
response = self.client.put(session_url, content=data, headers=headers)
except httpx.HTTPError as exc:
retries += 1
if retries > 3:
raise network_error("YouTube", exc) from exc
self.sleep(2 ** retries)
offset = self._resume_offset(session_url, total, token)
continue
if response.status_code in (200, 201):
progress("Vídeo enviado; o YouTube está processando…", 0.92)
return response_json(response)
if response.status_code == 308:
# "Resume Incomplete": o cabeçalho Range diz até onde o Google recebeu.
received = response.headers.get("range", "")
offset = int(received.rsplit("-", 1)[1]) + 1 if "-" in received else 0
retries = 0
progress(f"Enviando vídeo… {int(offset * 100 / total)}%", 0.05 + 0.85 * offset / total)
continue
if response.status_code in (500, 502, 503, 504) and retries < 3:
retries += 1
self.sleep(2 ** retries)
offset = self._resume_offset(session_url, total, token)
continue
raise explain_upload_error(response)
def _resume_offset(self, session_url: str, total: int, token: TokenProvider) -> int:
try:
response = self.client.put(session_url, content=b"", headers={
"Authorization": f"Bearer {token(False)}", "Content-Range": f"bytes */{total}"})
except httpx.HTTPError:
return 0
received = response.headers.get("range", "")
return int(received.rsplit("-", 1)[1]) + 1 if response.status_code == 308 and "-" in received else 0
def _set_thumbnail(self, video_id: str, spec: JobSpec, token: TokenProvider) -> str | None:
"""Devolve None se a capa entrou, ou o motivo (curto, pt-BR) se não entrou."""
assert spec.cover is not None
# Espera o processamento (até ~10 min); a capa personalizada só é aceita depois.
for _ in range(40):
try:
response = self.client.get(f"{API}/videos", params={"part": "processingDetails", "id": video_id},
headers={"Authorization": f"Bearer {token(False)}"})
items = response_json(response).get("items") or []
status = ((items[0].get("processingDetails") or {}).get("processingStatus")) if items else None
except httpx.HTTPError:
status = None
if status in ("succeeded", "terminated", "failed"):
break
self.sleep(15)
mime = "image/png" if spec.cover.suffix.lower() == ".png" else "image/jpeg"
try:
response = self.client.post(THUMB_URL, params={"videoId": video_id, "uploadType": "media"},
content=spec.cover.read_bytes(),
headers={"Authorization": f"Bearer {token(False)}", "Content-Type": mime})
except httpx.HTTPError:
return "sem conexão na hora de enviar a capa"
if response.status_code == 200:
return None
reason, _ = _google_error(response)
if reason == "forbidden" or response.status_code == 403:
return "o canal precisa estar verificado por telefone para usar capa personalizada"
return f"o YouTube recusou a imagem ({reason or response.status_code})"