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>
218 lines
11 KiB
Python
218 lines
11 KiB
Python
"""YouTube pelo YouTube Studio (modo sessão logada).
|
||
|
||
ATENÇÃO: os seletores abaixo foram escritos pela estrutura conhecida do Studio (ids `ytcp-*`, nomes acessíveis em
|
||
PT e EN) mas AINDA NÃO FORAM VALIDADOS COM UMA CONTA REAL. Ao primeiro teste com conta, conferir cada um e corrigir
|
||
só neste dicionário. As capturas de tela das falhas ficam em data/publisher/logs/.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
import time
|
||
from typing import Any
|
||
|
||
from ..base import JobSpec, Progress, PublishError, PublishResult, Sleep
|
||
from .common import (Uploader, click_through, detect_block, dismiss_tips, fill_text, find, needs_login, require,
|
||
step_pause)
|
||
|
||
# /upload redireciona para o Studio com a caixa "Enviar vídeos" já aberta.
|
||
UPLOAD_URL = "https://www.youtube.com/upload"
|
||
|
||
SELECTORS: dict[str, list[tuple]] = {
|
||
"login": [("role", "link", r"^(Fazer login|Sign in)$"), ("css", "input[type='email'][name='identifier']")],
|
||
"file_input": [("css", "ytcp-uploads-file-picker input[type='file']"), ("css", "input[type='file'][name='Filedata']"),
|
||
("css", "input[type='file']")],
|
||
"create_button": [("role", "button", r"^(Criar|Create)$"), ("css", "#create-icon")],
|
||
"upload_menu": [("role", "menuitem", r"(Enviar vídeos|Upload videos)"), ("css", "#text-item-0")],
|
||
"title": [("css", "#title-textarea #textbox"), ("role", "textbox", r"(título|title)")],
|
||
"description": [("css", "#description-textarea #textbox"), ("role", "textbox", r"(descrição|Conte aos espectadores|description|Tell viewers)")],
|
||
"kids_yes": [("css", "tp-yt-paper-radio-button[name='VIDEO_MADE_FOR_KIDS_MFK']"),
|
||
("role", "radio", r"^(Sim, é conteúdo para crianças|Yes, it's made for kids)")],
|
||
"kids_no": [("css", "tp-yt-paper-radio-button[name='VIDEO_MADE_FOR_KIDS_NOT_MFK']"),
|
||
("role", "radio", r"^(Não é conteúdo para crianças|No, it's not made for kids)")],
|
||
"show_more": [("css", "#toggle-button"), ("role", "button", r"^(Mostrar mais|Show more)$")],
|
||
# "Conteúdo alterado ou sintético" (pergunta sobre IA realista).
|
||
# Só por atributo: um "Sim"/"Não" genérico poderia marcar a pergunta errada (a de crianças).
|
||
"altered_yes": [("css", "tp-yt-paper-radio-button[name='VIDEO_HAS_ALTERED_CONTENT_YES']")],
|
||
"altered_no": [("css", "tp-yt-paper-radio-button[name='VIDEO_HAS_ALTERED_CONTENT_NO']")],
|
||
"tags": [("css", "#tags-container input"), ("role", "textbox", r"^(Tags)$")],
|
||
"thumbnail_input": [("css", "ytcp-thumbnails-compact-editor-uploader input[type='file']"),
|
||
("css", "#file-loader")],
|
||
"next": [("css", "#next-button"), ("role", "button", r"^(Próxima|Próximo|Next)$")],
|
||
"public": [("css", "tp-yt-paper-radio-button[name='PUBLIC']"), ("role", "radio", r"^(Público|Public)$")],
|
||
"unlisted": [("css", "tp-yt-paper-radio-button[name='UNLISTED']"), ("role", "radio", r"^(Não listado|Unlisted)$")],
|
||
"private": [("css", "tp-yt-paper-radio-button[name='PRIVATE']"), ("role", "radio", r"^(Privado|Private)$")],
|
||
"done": [("css", "#done-button"), ("role", "button", r"^(Publicar|Salvar|Publish|Save)$")],
|
||
# Texto de progresso do envio na barra inferior da caixa.
|
||
"upload_done": [("text", r"(Upload concluído|Upload complete|Processamento|Processing|Verificações concluídas|"
|
||
r"Checks complete|Nenhum problema encontrado|No issues found|SD processado|SD processed)")],
|
||
"video_link": [("css", "a.ytcp-video-info, .video-url-fadeable a"), ("css", "a[href*='youtu.be/']"),
|
||
("css", "a[href*='youtube.com/shorts/']")],
|
||
"published_dialog": [("text", r"(Vídeo publicado|Video published|Vídeo salvo|Video saved|Short publicado|Short published|"
|
||
r"ainda está sendo processado|still processing)")],
|
||
"close_dialog": [("role", "button", r"^(Fechar|Close)$"), ("css", "#close-button")],
|
||
}
|
||
|
||
VIDEO_ID = re.compile(r"(?:youtu\.be/|youtube\.com/(?:shorts/|watch\?v=))([\w-]{6,})")
|
||
|
||
|
||
def check(page: Any, sleep: Sleep = time.sleep) -> str | None:
|
||
page.goto(UPLOAD_URL, wait_until="domcontentloaded")
|
||
step_pause(sleep, 1.5, 3.0)
|
||
reason = detect_block(page, SELECTORS["login"])
|
||
if reason:
|
||
return reason
|
||
if "accounts.google.com" in page.url:
|
||
return "o Google pediu para entrar na conta"
|
||
if find(page, SELECTORS["file_input"], timeout_s=12, visible=False, sleep=sleep) is None:
|
||
# Sem a caixa de envio: tenta pelo botão Criar → Enviar vídeos antes de desistir.
|
||
create = find(page, SELECTORS["create_button"], timeout_s=5, sleep=sleep)
|
||
if create is None:
|
||
return "não achei a área de envio do YouTube Studio (a conta pode não ter canal ou não estar logada)"
|
||
create.click()
|
||
step_pause(sleep)
|
||
menu = find(page, SELECTORS["upload_menu"], timeout_s=5, sleep=sleep)
|
||
if menu is not None:
|
||
menu.click()
|
||
if find(page, SELECTORS["file_input"], timeout_s=10, visible=False, sleep=sleep) is None:
|
||
return "não achei o campo de arquivo do YouTube Studio"
|
||
return None
|
||
|
||
|
||
_ENABLED_JS = """el => {
|
||
const inner = el.querySelector('button');
|
||
return !(el.hasAttribute('disabled') || el.getAttribute('aria-disabled') === 'true' || (inner && inner.disabled));
|
||
}"""
|
||
|
||
|
||
def is_enabled(locator: Any) -> bool:
|
||
"""O `#done-button` é um componente do Studio (não um <button> nativo): o Playwright clica nele mesmo
|
||
desativado e o clique some. Lê o `disabled`/`aria-disabled` dele e do botão de dentro."""
|
||
try:
|
||
return bool(locator.evaluate(_ENABLED_JS))
|
||
except Exception: # noqa: BLE001 - elemento sumiu no meio da leitura
|
||
return False
|
||
|
||
|
||
def wait_enabled(locator: Any, sleep: Sleep = time.sleep, checks: int = 300) -> bool:
|
||
"""Espera o botão liberar (até `checks` × 2 s = 10 min)."""
|
||
for _ in range(checks):
|
||
if is_enabled(locator):
|
||
return True
|
||
sleep(2.0)
|
||
return False
|
||
|
||
|
||
def confirm_published(page: Any, done: Any, sleep: Sleep = time.sleep, checks: int = 45, retry_at: int = 8) -> bool:
|
||
"""Depois de clicar em Publicar (~90 s). Conta como publicado: a caixa "Vídeo/Short publicado" (ou "ainda está
|
||
sendo processado") OU a caixa de envio ter fechado (o botão Publicar sumiu). 17/11/2026: o vídeo saiu, mas a
|
||
caixa de envio continuava na tela com o botão Publicar 60 s depois e o envio deu "não confirmou". Se o botão
|
||
continuar na tela e liberado, clica de novo UMA vez: o vídeo já existe no Studio, um 2º clique só salva o mesmo."""
|
||
retried = False
|
||
for i in range(checks):
|
||
if find(page, SELECTORS["published_dialog"], timeout_s=0, sleep=sleep) is not None:
|
||
return True
|
||
try:
|
||
still_open = done.is_visible()
|
||
except Exception: # noqa: BLE001 - a caixa foi desmontada
|
||
still_open = False
|
||
if not still_open:
|
||
return True
|
||
if i >= retry_at and not retried and is_enabled(done):
|
||
retried = True
|
||
dismiss_tips(page, sleep)
|
||
click_through(done, sleep)
|
||
sleep(2.0)
|
||
return False
|
||
|
||
|
||
def _guard(page: Any) -> None:
|
||
reason = detect_block(page, SELECTORS["login"])
|
||
if reason:
|
||
raise needs_login(reason)
|
||
|
||
|
||
def upload(page: Any, spec: JobSpec, progress: Progress, sleep: Sleep = time.sleep) -> PublishResult:
|
||
progress("Abrindo o YouTube Studio…", 0.02)
|
||
reason = check(page, sleep)
|
||
if reason:
|
||
raise needs_login(reason)
|
||
file_input = require(page, SELECTORS["file_input"], "o campo de arquivo", visible=False, sleep=sleep)
|
||
file_input.set_input_files(str(spec.file))
|
||
progress("Enviando vídeo pelo YouTube Studio…", 0.1)
|
||
step_pause(sleep, 2.0, 4.0)
|
||
_guard(page)
|
||
|
||
title = require(page, SELECTORS["title"], "o campo de título", timeout_s=60, sleep=sleep)
|
||
fill_text(title, spec.title[:100], sleep)
|
||
description = find(page, SELECTORS["description"], timeout_s=5, sleep=sleep)
|
||
if description is not None and spec.caption:
|
||
fill_text(description, spec.caption[:5000], sleep)
|
||
|
||
if spec.cover:
|
||
thumb = find(page, SELECTORS["thumbnail_input"], timeout_s=3, visible=False, sleep=sleep)
|
||
if thumb is not None:
|
||
thumb.set_input_files(str(spec.cover))
|
||
step_pause(sleep)
|
||
|
||
require(page, SELECTORS["kids_yes" if spec.made_for_kids else "kids_no"],
|
||
"a pergunta \"é conteúdo para crianças?\"", sleep=sleep).click()
|
||
step_pause(sleep)
|
||
|
||
more = find(page, SELECTORS["show_more"], timeout_s=3, sleep=sleep)
|
||
if more is not None:
|
||
more.click()
|
||
step_pause(sleep)
|
||
altered = find(page, SELECTORS["altered_yes" if spec.ai_generated else "altered_no"], timeout_s=3, sleep=sleep)
|
||
if altered is not None:
|
||
altered.click()
|
||
step_pause(sleep)
|
||
tags = find(page, SELECTORS["tags"], timeout_s=2, sleep=sleep)
|
||
if tags is not None and spec.tags:
|
||
fill_text(tags, ",".join(t.lstrip("#") for t in spec.tags) + ",", sleep)
|
||
|
||
progress("Preenchendo os detalhes…", 0.4)
|
||
for _ in range(3): # Detalhes → Elementos do vídeo → Verificações → Visibilidade
|
||
require(page, SELECTORS["next"], "o botão Próximo", sleep=sleep).click()
|
||
step_pause(sleep, 1.2, 2.5)
|
||
_guard(page)
|
||
|
||
require(page, SELECTORS[spec.privacy if spec.privacy in ("public", "unlisted", "private") else "public"],
|
||
"a opção de visibilidade", sleep=sleep).click()
|
||
step_pause(sleep)
|
||
|
||
# O vídeo precisa terminar de SUBIR antes de fechar a caixa (senão o envio é cancelado).
|
||
progress("Esperando o envio terminar…", 0.6)
|
||
if find(page, SELECTORS["upload_done"], timeout_s=30 * 60, sleep=sleep) is None:
|
||
raise PublishError("O envio pelo YouTube Studio não terminou em 30 minutos. Confira a internet e tente de novo.")
|
||
|
||
link = find(page, SELECTORS["video_link"], timeout_s=5, visible=False, sleep=sleep)
|
||
href = (link.get_attribute("href") or link.inner_text()) if link is not None else ""
|
||
|
||
done = require(page, SELECTORS["done"], "o botão Publicar", sleep=sleep)
|
||
if not wait_enabled(done, sleep):
|
||
raise PublishError("O botão Publicar do YouTube Studio não liberou em 10 minutos (o vídeo ainda pode estar "
|
||
"subindo). Confira no Studio e tente de novo.")
|
||
dismiss_tips(page, sleep)
|
||
click_through(done, sleep)
|
||
progress("Publicando…", 0.9)
|
||
step_pause(sleep, 2.0, 4.0)
|
||
_guard(page)
|
||
if not confirm_published(page, done, sleep):
|
||
seen = f" O link do vídeo é {href}: se ele já aparece no canal, use \"Já saiu: informar o link\"." if href else ""
|
||
raise PublishError("Cliquei em Publicar mas o YouTube Studio não confirmou. Confira no Studio antes de tentar "
|
||
f"de novo (o vídeo pode ter subido).{seen}")
|
||
if not href:
|
||
link = find(page, SELECTORS["video_link"], timeout_s=5, visible=False, sleep=sleep)
|
||
href = (link.get_attribute("href") or link.inner_text()) if link is not None else ""
|
||
close = find(page, SELECTORS["close_dialog"], timeout_s=3, sleep=sleep)
|
||
if close is not None:
|
||
close.click()
|
||
match = VIDEO_ID.search(href or "")
|
||
if match:
|
||
return PublishResult(match.group(1), f"https://youtu.be/{match.group(1)}", False, "Publicado no YouTube (Studio)")
|
||
return PublishResult(None, None, False, "Publicado no YouTube (Studio); link não encontrado na tela")
|
||
|
||
|
||
UPLOADER = Uploader("youtube", UPLOAD_URL, check, upload)
|