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>
This commit is contained in:
@@ -0,0 +1,425 @@
|
||||
"""Navegador do modo "sessão logada".
|
||||
|
||||
Regra do projeto (inviolável): o Chrome/Edge é aberto como PROCESSO NORMAL e VISÍVEL, com um perfil próprio e
|
||||
vazio (`--user-data-dir=data/publisher/browser/<profileId>`). O usuário faz o login à mão, com 2FA se tiver.
|
||||
Só DEPOIS o serviço se conecta pela porta de depuração (CDP, faixa 4540–4549) com o Playwright
|
||||
(`connect_over_cdp`). Nada de navegador "de automação", stealth, patchright ou burla de detecção — o Google
|
||||
bloqueia login em navegador controlado e não vamos tentar contornar isso.
|
||||
|
||||
A porta de depuração dá controle total do navegador a quem falar com ela, então ela fica aberta o MENOS possível:
|
||||
a janela é fechada depois de cada envio, depois da conferência bem-sucedida ("Já entrei") e quando fica ociosa
|
||||
(5 min; 15 min se foi aberta para o login). Antes de usar uma porta, conferimos que ela é do NOSSO navegador
|
||||
(o `DevToolsActivePort` do perfil, quando existe; senão a marca `CenaForgeWindow.json` + o PID que escuta na porta —
|
||||
o Chrome 157+ com porta fixa não grava o `DevToolsActivePort`).
|
||||
|
||||
O pacote `playwright` entra só pelo driver: NUNCA rodar `playwright install` (não baixa navegador nenhum).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from ...config import BROWSER_PORT_RANGE
|
||||
from ..base import PublishError
|
||||
|
||||
# Janela ociosa é fechada sozinha (reduz o tempo com a porta CDP aberta).
|
||||
IDLE_CLOSE_S = 5 * 60
|
||||
# A janela aberta para o usuário entrar na conta ganha mais tempo (login com 2FA pode demorar).
|
||||
LOGIN_IDLE_CLOSE_S = 15 * 60
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BrowserInfo:
|
||||
kind: str # "chrome" | "msedge"
|
||||
path: str
|
||||
|
||||
|
||||
def _registry_app_path(exe: str) -> str | None:
|
||||
if sys.platform != "win32":
|
||||
return None
|
||||
import winreg
|
||||
|
||||
key_path = rf"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\{exe}"
|
||||
for hive in (winreg.HKEY_CURRENT_USER, winreg.HKEY_LOCAL_MACHINE):
|
||||
try:
|
||||
with winreg.OpenKey(hive, key_path) as key:
|
||||
value, _ = winreg.QueryValueEx(key, None)
|
||||
if value and Path(value).is_file():
|
||||
return str(value)
|
||||
except OSError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _candidates(kind: str, env: dict[str, str]) -> list[Path]:
|
||||
roots = [env.get("PROGRAMFILES"), env.get("PROGRAMFILES(X86)"), env.get("LOCALAPPDATA")]
|
||||
tail = (Path("Google") / "Chrome" / "Application" / "chrome.exe" if kind == "chrome"
|
||||
else Path("Microsoft") / "Edge" / "Application" / "msedge.exe")
|
||||
return [Path(root) / tail for root in roots if root]
|
||||
|
||||
|
||||
def detect_browser(override: str | None = None, env: dict[str, str] | None = None,
|
||||
registry=_registry_app_path) -> BrowserInfo | None:
|
||||
"""Chrome (preferido) ou Edge instalados. `override` = PUBLISHER_BROWSER_PATH."""
|
||||
env = dict(os.environ) if env is None else env
|
||||
if override:
|
||||
path = Path(override)
|
||||
if path.is_file():
|
||||
return BrowserInfo("msedge" if "edge" in path.name.lower() else "chrome", str(path))
|
||||
return None
|
||||
for kind, exe in (("chrome", "chrome.exe"), ("msedge", "msedge.exe")):
|
||||
for candidate in _candidates(kind, env):
|
||||
if candidate.is_file():
|
||||
return BrowserInfo(kind, str(candidate))
|
||||
found = registry(exe)
|
||||
if found:
|
||||
return BrowserInfo(kind, found)
|
||||
if sys.platform != "win32": # conveniência fora do Windows (desenvolvimento)
|
||||
for kind, names in (("chrome", ["google-chrome", "chromium"]), ("msedge", ["microsoft-edge"])):
|
||||
for name in names:
|
||||
if found := shutil.which(name):
|
||||
return BrowserInfo(kind, found)
|
||||
return None
|
||||
|
||||
|
||||
def port_is_free(port: int) -> bool:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
|
||||
try:
|
||||
probe.bind(("127.0.0.1", port))
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def launch_args(browser: BrowserInfo, user_data_dir: Path, port: int, url: str) -> list[str]:
|
||||
# Só o mínimo: perfil próprio, porta de depuração local e sem a tela de boas-vindas. Nenhuma flag que esconda
|
||||
# automação (nada de --disable-blink-features=AutomationControlled e afins).
|
||||
return [browser.path, f"--user-data-dir={user_data_dir}", f"--remote-debugging-port={port}",
|
||||
"--remote-debugging-address=127.0.0.1", "--no-first-run", "--no-default-browser-check", url]
|
||||
|
||||
|
||||
def cdp_version(port: int) -> dict | None:
|
||||
try:
|
||||
with urllib.request.urlopen(f"http://127.0.0.1:{port}/json/version", timeout=2) as response:
|
||||
data = json.loads(response.read())
|
||||
return data if isinstance(data, dict) and data.get("Browser") else None
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def cdp_alive(port: int) -> bool:
|
||||
return cdp_version(port) is not None
|
||||
|
||||
|
||||
def devtools_file(user_dir: Path) -> tuple[int, str] | None:
|
||||
"""(porta, "/devtools/browser/<id>") que o Chrome/Edge grava em `DevToolsActivePort` na pasta do perfil.
|
||||
Atenção: o Chrome recente (157+) NÃO grava esse arquivo quando a porta é fixa (`--remote-debugging-port=4540`);
|
||||
por isso existe também a marca própria (`WINDOW_MARK`)."""
|
||||
try:
|
||||
lines = (user_dir / "DevToolsActivePort").read_text(encoding="utf-8").splitlines()
|
||||
return int(lines[0].strip()), (lines[1].strip() if len(lines) > 1 else "")
|
||||
except (OSError, ValueError, IndexError):
|
||||
return None
|
||||
|
||||
|
||||
# Marca gravada pelo Publicador na pasta do perfil ao abrir a janela: {"pid": <processo do navegador>, "port": <CDP>}.
|
||||
WINDOW_MARK = "CenaForgeWindow.json"
|
||||
BROWSER_EXES = {"chrome.exe", "msedge.exe", "chrome", "chromium", "google-chrome", "microsoft-edge", "msedge"}
|
||||
|
||||
|
||||
def window_mark(user_dir: Path) -> tuple[int, int] | None:
|
||||
"""(pid, porta) da marca gravada ao abrir a janela."""
|
||||
try:
|
||||
data = json.loads((user_dir / WINDOW_MARK).read_text(encoding="utf-8"))
|
||||
return int(data["pid"]), int(data["port"])
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
def write_window_mark(user_dir: Path, pid: int, port: int) -> None:
|
||||
(user_dir / WINDOW_MARK).write_text(json.dumps({"pid": pid, "port": port}), encoding="utf-8")
|
||||
|
||||
|
||||
def listener_pid(port: int) -> int | None:
|
||||
"""PID do processo que ESCUTA na porta TCP (127.0.0.1/IPv4). Windows: GetExtendedTcpTable (sem dependência)."""
|
||||
if sys.platform != "win32":
|
||||
return None
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
|
||||
class TcpRowOwnerPid(ctypes.Structure):
|
||||
_fields_ = [("state", wintypes.DWORD), ("local_addr", wintypes.DWORD), ("local_port", wintypes.DWORD),
|
||||
("remote_addr", wintypes.DWORD), ("remote_port", wintypes.DWORD), ("owning_pid", wintypes.DWORD)]
|
||||
|
||||
af_inet, tcp_table_owner_pid_listener, error_insufficient_buffer = 2, 3, 122
|
||||
get_table = ctypes.windll.iphlpapi.GetExtendedTcpTable
|
||||
size = wintypes.DWORD(0)
|
||||
for _ in range(3): # a tabela pode crescer entre a consulta do tamanho e a leitura
|
||||
buffer = ctypes.create_string_buffer(max(size.value, 4))
|
||||
result = get_table(buffer, ctypes.byref(size), False, af_inet, tcp_table_owner_pid_listener, 0)
|
||||
if result == error_insufficient_buffer:
|
||||
continue
|
||||
if result != 0:
|
||||
return None
|
||||
count = ctypes.cast(buffer, ctypes.POINTER(wintypes.DWORD))[0]
|
||||
rows = (TcpRowOwnerPid * count).from_address(ctypes.addressof(buffer) + ctypes.sizeof(wintypes.DWORD))
|
||||
for row in rows:
|
||||
if socket.ntohs(row.local_port & 0xFFFF) == port:
|
||||
return int(row.owning_pid)
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def process_exe_name(pid: int) -> str | None:
|
||||
"""Nome do executável do processo (ex.: "chrome.exe"), ou None."""
|
||||
if sys.platform != "win32":
|
||||
return None
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
|
||||
kernel32 = ctypes.windll.kernel32
|
||||
handle = kernel32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION
|
||||
if not handle:
|
||||
return None
|
||||
try:
|
||||
buffer = ctypes.create_unicode_buffer(1024)
|
||||
length = wintypes.DWORD(len(buffer))
|
||||
if not kernel32.QueryFullProcessImageNameW(handle, 0, buffer, ctypes.byref(length)):
|
||||
return None
|
||||
return Path(buffer.value).name.lower()
|
||||
finally:
|
||||
kernel32.CloseHandle(handle)
|
||||
|
||||
|
||||
def active_port(user_dir: Path) -> int | None:
|
||||
info = devtools_file(user_dir)
|
||||
if info:
|
||||
return info[0]
|
||||
mark = window_mark(user_dir)
|
||||
return mark[1] if mark else None
|
||||
|
||||
|
||||
def owns_port(user_dir: Path, port: int, version: dict | None = None) -> bool:
|
||||
"""A porta é do NOSSO navegador deste perfil? Outro programa ouvindo na mesma porta não passa.
|
||||
|
||||
1. Se o Chrome/Edge gravou `DevToolsActivePort` no perfil: o arquivo precisa apontar para a porta e o id do
|
||||
navegador (`/devtools/browser/<id>`) precisa bater com o que a porta responde.
|
||||
2. Senão (Chrome 157+ com porta fixa não grava o arquivo): a marca que o Publicador gravou ao abrir a janela
|
||||
precisa apontar para a porta, e quem escuta nela precisa ser exatamente aquele processo — e um Chrome/Edge
|
||||
(protege contra PID reaproveitado depois de reiniciar o Windows)."""
|
||||
version = version if version is not None else cdp_version(port)
|
||||
if not version:
|
||||
return False
|
||||
info = devtools_file(user_dir)
|
||||
if info:
|
||||
ws = str(version.get("webSocketDebuggerUrl") or "")
|
||||
return info[0] == port and bool(info[1]) and ws.endswith(info[1])
|
||||
mark = window_mark(user_dir)
|
||||
if not mark or mark[1] != port:
|
||||
return False
|
||||
pid = listener_pid(port)
|
||||
return pid is not None and pid == mark[0] and process_exe_name(pid) in BROWSER_EXES
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Window:
|
||||
process: subprocess.Popen | None # None = janela que já estava aberta (achada pelo DevToolsActivePort/marca)
|
||||
port: int
|
||||
user_dir: Path
|
||||
idle_limit_s: float = IDLE_CLOSE_S
|
||||
last_used: float = 0.0
|
||||
|
||||
def alive(self) -> bool:
|
||||
if self.process is not None:
|
||||
return self.process.poll() is None
|
||||
return cdp_alive(self.port)
|
||||
|
||||
|
||||
class BrowserManager:
|
||||
"""Uma janela de navegador por perfil, aberta só enquanto precisa."""
|
||||
|
||||
def __init__(self, browser_dir: Path, browser: BrowserInfo | None, port_range: tuple[int, int] = BROWSER_PORT_RANGE,
|
||||
popen=subprocess.Popen, start_reaper: bool = True):
|
||||
self.browser_dir = browser_dir
|
||||
self.browser = browser
|
||||
self.port_range = port_range
|
||||
self._popen = popen
|
||||
self._windows: dict[str, _Window] = {}
|
||||
self._busy: set[str] = set()
|
||||
self._lock = threading.RLock()
|
||||
self._start_reaper = start_reaper
|
||||
self._reaper: threading.Thread | None = None
|
||||
|
||||
def profile_dir(self, profile_id: str) -> Path:
|
||||
return self.browser_dir / profile_id
|
||||
|
||||
def _free_port(self) -> int:
|
||||
used = {w.port for w in self._windows.values() if w.alive()}
|
||||
for port in range(self.port_range[0], self.port_range[1] + 1):
|
||||
if port not in used and port_is_free(port):
|
||||
return port
|
||||
raise PublishError("Todas as janelas de navegador do Publicador estão em uso (máximo 10). Feche alguma e "
|
||||
"tente de novo.")
|
||||
|
||||
def is_open(self, profile_id: str) -> bool:
|
||||
with self._lock:
|
||||
window = self._windows.get(profile_id)
|
||||
return bool(window and window.alive())
|
||||
|
||||
@contextmanager
|
||||
def in_use(self, profile_id: str):
|
||||
"""Marca a janela como ocupada: o fechamento por ociosidade não mexe nela enquanto isso."""
|
||||
with self._lock:
|
||||
self._busy.add(profile_id)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
with self._lock:
|
||||
self._busy.discard(profile_id)
|
||||
window = self._windows.get(profile_id)
|
||||
if window:
|
||||
window.last_used = time.time()
|
||||
|
||||
def open(self, profile_id: str, url: str, for_login: bool = False) -> int:
|
||||
"""Abre (ou reaproveita) a janela do perfil e devolve a porta CDP — sempre conferindo que a porta é nossa."""
|
||||
if not self.browser:
|
||||
raise PublishError("Não encontrei o Google Chrome nem o Microsoft Edge neste computador. Instale o Chrome "
|
||||
"(recomendado) para usar a Sessão logada.")
|
||||
limit = LOGIN_IDLE_CLOSE_S if for_login else IDLE_CLOSE_S
|
||||
user_dir = self.profile_dir(profile_id)
|
||||
with self._lock:
|
||||
window = self._windows.get(profile_id)
|
||||
if window and window.alive():
|
||||
if not owns_port(user_dir, window.port):
|
||||
self._windows.pop(profile_id, None)
|
||||
raise PublishError("A porta do navegador deste perfil não responde como o nosso navegador. Feche "
|
||||
"as janelas do navegador do CenaForge e tente de novo.")
|
||||
window.last_used, window.idle_limit_s = time.time(), max(window.idle_limit_s, limit)
|
||||
return window.port
|
||||
# Janela deste perfil que ficou aberta de uma execução anterior do Publicador: reaproveita, se for nossa.
|
||||
previous = active_port(user_dir)
|
||||
if previous and self.port_range[0] <= previous <= self.port_range[1] and owns_port(user_dir, previous):
|
||||
self._windows[profile_id] = _Window(None, previous, user_dir, limit, time.time())
|
||||
self._ensure_reaper()
|
||||
return previous
|
||||
port = self._free_port()
|
||||
user_dir.mkdir(parents=True, exist_ok=True)
|
||||
for stale in ("DevToolsActivePort", WINDOW_MARK): # resto de execução anterior não pode confundir o dono
|
||||
try:
|
||||
(user_dir / stale).unlink()
|
||||
except OSError:
|
||||
pass
|
||||
flags = subprocess.CREATE_NEW_PROCESS_GROUP if sys.platform == "win32" else 0
|
||||
process = self._popen(launch_args(self.browser, user_dir, port, url), stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL, creationflags=flags)
|
||||
write_window_mark(user_dir, process.pid, port)
|
||||
self._windows[profile_id] = _Window(process, port, user_dir, limit, time.time())
|
||||
self._wait_cdp(port, user_dir, process)
|
||||
self._ensure_reaper()
|
||||
return port
|
||||
|
||||
def _wait_cdp(self, port: int, user_dir: Path, process: subprocess.Popen | None = None,
|
||||
timeout_s: float = 20) -> None:
|
||||
deadline = time.time() + timeout_s
|
||||
while time.time() < deadline:
|
||||
if owns_port(user_dir, port):
|
||||
return
|
||||
if process is not None and process.poll() is not None:
|
||||
# O processo saiu logo: o Chrome entregou a URL para uma janela que já estava aberta com este perfil
|
||||
# (e essa janela não tem a nossa porta de depuração).
|
||||
raise PublishError("Já existe uma janela do navegador aberta com este perfil. Feche essa janela (a "
|
||||
"conta continua logada) e tente de novo.")
|
||||
time.sleep(0.5)
|
||||
raise PublishError("O navegador abriu mas não respondeu. Feche todas as janelas dele e tente de novo. (Se o "
|
||||
"Chrome já estava aberto com este mesmo perfil, ele precisa ser fechado antes.)")
|
||||
|
||||
# ---------- fechamento
|
||||
def _ensure_reaper(self) -> None:
|
||||
if not self._start_reaper or (self._reaper and self._reaper.is_alive()):
|
||||
return
|
||||
self._reaper = threading.Thread(target=self._reap_loop, name="publisher-browser-idle", daemon=True)
|
||||
self._reaper.start()
|
||||
|
||||
def _reap_loop(self) -> None:
|
||||
while True:
|
||||
time.sleep(30)
|
||||
try:
|
||||
self.close_idle()
|
||||
except Exception: # noqa: BLE001 - o vigia não pode morrer
|
||||
pass
|
||||
with self._lock:
|
||||
if not self._windows:
|
||||
self._reaper = None
|
||||
return
|
||||
|
||||
def close_idle(self, now: float | None = None) -> list[str]:
|
||||
"""Fecha as janelas paradas há mais que o limite (ou já fechadas pelo usuário). Devolve os perfis."""
|
||||
now = now or time.time()
|
||||
with self._lock:
|
||||
idle = [pid for pid, w in self._windows.items()
|
||||
if pid not in self._busy and (not w.alive() or now - w.last_used >= w.idle_limit_s)]
|
||||
for profile_id in idle:
|
||||
self.close(profile_id)
|
||||
return idle
|
||||
|
||||
def close(self, profile_id: str, graceful: bool = True) -> None:
|
||||
"""Fecha a janela. `graceful`: pede ao navegador para fechar (CDP Browser.close), que grava os cookies — a
|
||||
sessão logada não se perde. Só mata o processo se ele não fechar sozinho. NÃO chamar dentro de um bloco
|
||||
`sync_playwright()` aberto na mesma thread."""
|
||||
with self._lock:
|
||||
window = self._windows.pop(profile_id, None)
|
||||
if not window or not window.alive():
|
||||
return
|
||||
if graceful and owns_port(window.user_dir, window.port):
|
||||
try:
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
with sync_playwright() as pw:
|
||||
browser = pw.chromium.connect_over_cdp(f"http://127.0.0.1:{window.port}", timeout=5000, is_local=True)
|
||||
browser.new_browser_cdp_session().send("Browser.close")
|
||||
except Exception: # noqa: BLE001 - "melhor esforço"; abaixo o processo é encerrado à força
|
||||
pass
|
||||
if window.process is None:
|
||||
return
|
||||
try:
|
||||
window.process.wait(timeout=10 if graceful else 0.1)
|
||||
return
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
if sys.platform == "win32":
|
||||
subprocess.run(["taskkill", "/pid", str(window.process.pid), "/T", "/F"],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
else:
|
||||
window.process.terminate()
|
||||
try:
|
||||
window.process.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
|
||||
def remove_profile(self, profile_id: str) -> None:
|
||||
"""Fecha a janela e apaga o diretório do perfil (cookies = a sessão logada)."""
|
||||
target = self.profile_dir(profile_id).resolve()
|
||||
root = self.browser_dir.resolve()
|
||||
if target.parent != root: # só apaga pasta filha direta de data/publisher/browser
|
||||
raise PublishError("Caminho do perfil de navegador inválido.")
|
||||
self.close(profile_id, graceful=False)
|
||||
for _ in range(5): # o Chrome demora um instante para soltar os arquivos
|
||||
if not target.exists():
|
||||
return
|
||||
shutil.rmtree(target, ignore_errors=True)
|
||||
time.sleep(0.5)
|
||||
|
||||
def close_all(self) -> None:
|
||||
for profile_id in list(self._windows):
|
||||
self.close(profile_id)
|
||||
@@ -0,0 +1,203 @@
|
||||
"""Peças comuns aos uploaders do modo sessão (YouTube Studio, TikTok Studio, Instagram web).
|
||||
|
||||
Regras invioláveis (doc/publicacao/PLANO.md §2):
|
||||
- navegador VISÍVEL; o usuário faz login À MÃO; nunca digitar senha, nunca resolver captcha;
|
||||
- nada de stealth/patchright/stealth.js nem qualquer burla de detecção;
|
||||
- página de login, captcha, "confirme que é você"/checkpoint ⇒ PARAR com `needs_login` e avisar o usuário;
|
||||
- intervalo mínimo entre envios: pausas curtas entre passos e um envio por vez (o worker garante um job por vez).
|
||||
É só ritmo para não sobrecarregar a conta — não é tentativa de imitar uma pessoa nem de esconder a automação.
|
||||
|
||||
Seletores: cada rede tem um dicionário `SELECTORS` no próprio arquivo, com candidatos em PT e EN, do mais
|
||||
estável (role/label/atributo) ao menos estável (texto). Quando a rede mudar a tela, é só ali que se corrige.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
import re
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Iterable
|
||||
|
||||
from ..base import JobSpec, Progress, PublishError, PublishResult, Sleep
|
||||
|
||||
# Um candidato de seletor: (estratégia, valor[, nome]). Estratégias:
|
||||
# ("role", "button", r"regex do nome acessível") ("label", r"regex") ("placeholder", r"regex")
|
||||
# ("text", r"regex") ("css", "seletor CSS")
|
||||
Candidate = tuple
|
||||
|
||||
|
||||
def locate(page: Any, candidate: Candidate) -> Any:
|
||||
kind = candidate[0]
|
||||
if kind == "role":
|
||||
return page.get_by_role(candidate[1], name=re.compile(candidate[2], re.I))
|
||||
if kind == "label":
|
||||
return page.get_by_label(re.compile(candidate[1], re.I))
|
||||
if kind == "placeholder":
|
||||
return page.get_by_placeholder(re.compile(candidate[1], re.I))
|
||||
if kind == "text":
|
||||
return page.get_by_text(re.compile(candidate[1], re.I))
|
||||
if kind == "css":
|
||||
return page.locator(candidate[1])
|
||||
raise ValueError(f"estratégia de seletor desconhecida: {kind}")
|
||||
|
||||
|
||||
def find(page: Any, candidates: Iterable[Candidate], timeout_s: float = 10, visible: bool = True,
|
||||
sleep: Sleep = time.sleep) -> Any | None:
|
||||
"""Primeiro candidato que aparece na tela dentro do prazo (ou None). `visible=False` aceita elemento oculto
|
||||
(ex.: <input type=file>)."""
|
||||
candidates = list(candidates)
|
||||
deadline = time.time() + timeout_s
|
||||
while True:
|
||||
for candidate in candidates:
|
||||
try:
|
||||
matches = locate(page, candidate)
|
||||
total = matches.count()
|
||||
if total and not visible:
|
||||
return matches.first
|
||||
# A 1ª ocorrência pode ser uma cópia escondida (Instagram, 17/11/2026: botão "Original" do formato):
|
||||
# olha as primeiras até achar uma visível.
|
||||
for i in range(min(total, 6)):
|
||||
if matches.nth(i).is_visible():
|
||||
return matches.nth(i)
|
||||
except Exception: # noqa: BLE001 - página navegando no meio da busca: tenta de novo
|
||||
continue
|
||||
if time.time() >= deadline:
|
||||
return None
|
||||
sleep(0.5)
|
||||
|
||||
|
||||
def require(page: Any, candidates: Iterable[Candidate], what: str, timeout_s: float = 15, visible: bool = True,
|
||||
sleep: Sleep = time.sleep) -> Any:
|
||||
found = find(page, candidates, timeout_s, visible, sleep)
|
||||
if found is None:
|
||||
raise PublishError(f"Não achei {what} na página. O site pode ter mudado de layout; veja a captura de tela em "
|
||||
"data/publisher/logs/ e avise para ajustarmos os seletores.")
|
||||
return found
|
||||
|
||||
|
||||
def step_pause(sleep: Sleep = time.sleep, low: float = 0.8, high: float = 2.2) -> None:
|
||||
sleep(random.uniform(low, high))
|
||||
|
||||
|
||||
# Avisos de novidade/dica que as redes abrem por cima da página e que bloqueiam os cliques (ex.: TikTok Studio,
|
||||
# 17/11/2026: "Veja a prévia do seu vídeo no seu celular" → "Entendi"). SÓ botões de "entendi": fechar um aviso
|
||||
# desses não muda nada no post. Nunca aceitar/recusar opções (verificação de conteúdo, música, etc.) por aqui.
|
||||
TIP_BUTTONS: list[Candidate] = [("role", "button", r"^(Entendi|Entendido|Ok, entendi|Got it)$")]
|
||||
|
||||
|
||||
def dismiss_tips(page: Any, sleep: Sleep = time.sleep, rounds: int = 3) -> int:
|
||||
"""Fecha os avisos de novidade abertos (até `rounds`). Devolve quantos fechou."""
|
||||
closed = 0
|
||||
for _ in range(rounds):
|
||||
button = find(page, TIP_BUTTONS, timeout_s=0.5, sleep=sleep)
|
||||
if button is None:
|
||||
break
|
||||
try:
|
||||
button.click(timeout=3000)
|
||||
except Exception: # noqa: BLE001 - o aviso sumiu sozinho
|
||||
break
|
||||
closed += 1
|
||||
step_pause(sleep, 0.3, 0.8)
|
||||
return closed
|
||||
|
||||
|
||||
def click_through(locator: Any, sleep: Sleep = time.sleep, timeout_ms: float = 8000) -> None:
|
||||
"""Clica; se algo cobrir o elemento (aviso de novidade), fecha os avisos e tenta mais uma vez."""
|
||||
try:
|
||||
locator.click(timeout=timeout_ms)
|
||||
return
|
||||
except Exception: # noqa: BLE001 - quase sempre um aviso por cima; se não for, o segundo clique mostra o erro
|
||||
if not dismiss_tips(locator.page, sleep):
|
||||
raise
|
||||
locator.click(timeout=timeout_ms)
|
||||
|
||||
|
||||
def caption_key(caption: str, size: int = 24) -> str:
|
||||
"""Começo da legenda sem hashtags/menções: é o que aparece primeiro nas listas/páginas da rede. Serve para achar
|
||||
o vídeo recém-publicado sem nunca pegar o link de outro."""
|
||||
words = [w for w in (caption or "").split() if not w.startswith(("#", "@"))]
|
||||
return " ".join(words)[:size].strip()
|
||||
|
||||
|
||||
def fill_text(locator: Any, text: str, sleep: Sleep = time.sleep) -> None:
|
||||
"""Escreve num campo (inclusive contenteditable): foca, limpa e insere o texto como um colar."""
|
||||
click_through(locator, sleep)
|
||||
step_pause(sleep, 0.3, 0.8)
|
||||
page = locator.page
|
||||
page.keyboard.press("Control+A")
|
||||
page.keyboard.press("Delete")
|
||||
step_pause(sleep, 0.2, 0.5)
|
||||
page.keyboard.insert_text(text)
|
||||
step_pause(sleep, 0.4, 1.0)
|
||||
|
||||
|
||||
# Sinais universais de que é preciso a pessoa agir (login, captcha, verificação de identidade).
|
||||
BLOCK_URL = re.compile(r"(/login|/signin|/accounts/login|ServiceLogin|/challenge|checkpoint|captcha|/verify)", re.I)
|
||||
BLOCK_TEXT: list[Candidate] = [
|
||||
("css", "iframe[src*='captcha'], iframe[title*='captcha' i], #captcha-verify-container, .captcha_verify_container"),
|
||||
("text", r"^(Verifique|Verify|Confirme|Confirm)( que)? (é você|it's you|you're human|you are human)"),
|
||||
("text", r"(Arraste o controle|Drag the slider|Selecione todas as imagens|Select all images)"),
|
||||
("text", r"(Este navegador ou app pode não ser seguro|This browser or app may not be secure)"),
|
||||
]
|
||||
|
||||
|
||||
def detect_block(page: Any, login_candidates: Iterable[Candidate] = ()) -> str | None:
|
||||
"""Motivo (pt-BR) se a página pede login/captcha/verificação; None se está liberada."""
|
||||
url = str(getattr(page, "url", "") or "")
|
||||
if BLOCK_URL.search(url):
|
||||
return "a rede pediu para entrar na conta de novo"
|
||||
if find(page, BLOCK_TEXT, timeout_s=0, visible=True) is not None:
|
||||
return "a rede pediu uma verificação (captcha ou \"confirme que é você\")"
|
||||
if find(page, login_candidates, timeout_s=0, visible=True) is not None:
|
||||
return "a rede mostrou a tela de login"
|
||||
return None
|
||||
|
||||
|
||||
def needs_login(reason: str) -> PublishError:
|
||||
return PublishError(f"É preciso entrar de novo: {reason}. Clique em \"Entrar de novo\", faça o login (e a "
|
||||
"verificação, se aparecer) na janela que abrir e depois clique em \"Já entrei\".", "needs_login")
|
||||
|
||||
|
||||
SCREENSHOT_KEEP_DAYS = 7
|
||||
|
||||
|
||||
def screenshot(page: Any, logs_dir: Path, name: str) -> Path | None:
|
||||
"""Captura só a área VISÍVEL (nada de página inteira) para diagnosticar seletor quebrado. Quem chama não captura
|
||||
telas de login/captcha/verificação (podem mostrar dados pessoais)."""
|
||||
try:
|
||||
if detect_block(page) is not None:
|
||||
return None
|
||||
logs_dir.mkdir(parents=True, exist_ok=True)
|
||||
path = logs_dir / f"{datetime.now():%Y%m%d-%H%M%S}-{name}.png"
|
||||
page.screenshot(path=str(path), full_page=False)
|
||||
return path
|
||||
except Exception: # noqa: BLE001 - a captura é ajuda de diagnóstico; não pode mascarar o erro real
|
||||
return None
|
||||
|
||||
|
||||
def prune_screenshots(logs_dir: Path, keep_days: float = SCREENSHOT_KEEP_DAYS) -> int:
|
||||
"""Apaga capturas com mais de `keep_days` dias (roda na subida do serviço). Devolve quantas apagou."""
|
||||
if not logs_dir.is_dir():
|
||||
return 0
|
||||
limit = time.time() - keep_days * 86400
|
||||
removed = 0
|
||||
for path in logs_dir.glob("*.png"):
|
||||
try:
|
||||
if path.stat().st_mtime < limit:
|
||||
path.unlink()
|
||||
removed += 1
|
||||
except OSError:
|
||||
continue
|
||||
return removed
|
||||
|
||||
|
||||
@dataclass
|
||||
class Uploader:
|
||||
"""Contrato de cada rede no modo sessão."""
|
||||
platform: str
|
||||
upload_url: str
|
||||
check: Callable[[Any, Sleep], str | None] # página → motivo do bloqueio ou None (logado)
|
||||
upload: Callable[[Any, JobSpec, Progress, Sleep], PublishResult]
|
||||
@@ -0,0 +1,280 @@
|
||||
"""Instagram pelo site (modo sessão logada): instagram.com → Postar → "Criar novo post" → Reel.
|
||||
|
||||
Validado com conta real em 17/11/2026, num ensaio SEM publicar (`prepare`): Postar → caixa "Criar novo post" →
|
||||
arquivo → Avançar ×2 → legenda → rótulo de IA → botão Compartilhar achado (não clicado) → rascunho descartado.
|
||||
O clique em Compartilhar, a confirmação e o link do reel pelo perfil AINDA NÃO VALIDADOS COM UMA CONTA REAL (a conta
|
||||
não tinha reel). Corrigir só neste dicionário. O Instagram pede checkpoint ("confirme que é você") com frequência em
|
||||
navegador novo: o envio para em `needs_login` e o usuário resolve à mão na janela.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import time
|
||||
from typing import Any
|
||||
from urllib.parse import urljoin
|
||||
|
||||
from ..base import JobSpec, Progress, PublishError, PublishResult, Sleep
|
||||
from .common import (Uploader, caption_key, click_through, detect_block, dismiss_tips, fill_text, find, needs_login,
|
||||
require, step_pause)
|
||||
|
||||
HOME_URL = "https://www.instagram.com/"
|
||||
|
||||
# Validado com conta real em 17/11/2026 (layout novo, barra lateral só de ícones): o botão de postar é um <a> com
|
||||
# <svg aria-label="Postar"> e abre DIRETO o diálogo "Criar novo post" (sem submenu), com o input de arquivo dentro.
|
||||
# CUIDADO: no feed cada post tem um botão de ícone "Compartilhar" — os botões do fluxo (Avançar, Compartilhar) são
|
||||
# sempre procurados DENTRO do diálogo de criação, nunca na página.
|
||||
_DIALOG = "div[role='dialog']"
|
||||
|
||||
SELECTORS: dict[str, list[tuple]] = {
|
||||
"login": [("css", "input[name='username']"), ("role", "button", r"^(Entrar|Log in)$"),
|
||||
("role", "link", r"^(Entrar|Log in)$")],
|
||||
"create": [("css", "svg[aria-label='Postar'], svg[aria-label='Nova publicação'], svg[aria-label='New post'], "
|
||||
"svg[aria-label='Criar'], svg[aria-label='Create']"),
|
||||
("role", "link", r"^(Postar|Criar|Nova publicação|Create|New post)$"),
|
||||
("role", "button", r"^(Postar|Criar|Nova publicação|Create|New post)$")],
|
||||
# Layout antigo: depois de "Criar" podia abrir um submenu (Publicação / Live / Anúncio).
|
||||
"create_post": [("role", "link", r"^(Publicação|Post)$"), ("role", "menuitem", r"^(Publicação|Post)$"),
|
||||
("css", "svg[aria-label='Publicação'], svg[aria-label='Post']")],
|
||||
"dialog": [("role", "dialog", r"(Criar nov[oa]|Create new)")],
|
||||
"file_input": [("css", f"{_DIALOG} input[type='file']"), ("css", "form input[type='file']"),
|
||||
("css", "input[type='file'][accept*='video']")],
|
||||
# Etapa "Cortar" (validado 17/11/2026): o site vem em 1:1 e corta o vídeo 9:16 (sai o rosto da câmera de cima).
|
||||
# Ícone "Selecionar corte" → botões "Original", "1:1", "9:16", "16:9".
|
||||
"crop_toggle": [("css", f"{_DIALOG} svg[aria-label='Selecionar corte'], {_DIALOG} svg[aria-label='Select crop']")],
|
||||
# O botão tem o texto "Original" + o título do ícone ("Ícone de contorno de foto"): :text-is não casa.
|
||||
"crop_original": [("role", "button", r"^\s*Original\b"),
|
||||
("css", f"{_DIALOG} [role='button']:has-text('Original'), {_DIALOG} button:has-text('Original')")],
|
||||
"reels_notice_ok": [("css", f"{_DIALOG} button:text-is('OK'), {_DIALOG} [role='button']:text-is('OK')")],
|
||||
"next": [("css", f"{_DIALOG} [role='button']:text-is('Avançar'), {_DIALOG} button:text-is('Avançar'), "
|
||||
f"{_DIALOG} [role='button']:text-is('Next'), {_DIALOG} button:text-is('Next')")],
|
||||
"caption": [("css", f"{_DIALOG} div[contenteditable='true'][aria-label*='legenda' i], "
|
||||
f"{_DIALOG} div[contenteditable='true'][aria-label*='caption' i]"),
|
||||
("css", f"{_DIALOG} div[contenteditable='true']")],
|
||||
"advanced": [("css", f"{_DIALOG} [role='button']:has-text('Configurações avançadas'), "
|
||||
f"{_DIALOG} [role='button']:has-text('Advanced settings')"),
|
||||
("text", r"^(Configurações avançadas|Advanced settings)$")],
|
||||
"ai_label": [("role", "switch", r"(rótulo de IA|AI label|gerad[oa] por IA|AI info|IA)"),
|
||||
("css", "input[type='checkbox'][aria-label*='IA'], input[type='checkbox'][aria-label*='AI']")],
|
||||
"share": [("css", f"{_DIALOG} [role='button']:text-is('Compartilhar'), {_DIALOG} button:text-is('Compartilhar'), "
|
||||
f"{_DIALOG} [role='button']:text-is('Share'), {_DIALOG} button:text-is('Share')")],
|
||||
"shared": [("text", r"(Seu reel foi compartilhado|Seu post foi compartilhado|Your reel has been shared|"
|
||||
r"Your post has been shared|Reel compartilhado|Reel shared)")],
|
||||
"sharing": [("text", r"(Compartilhando|Sharing)")],
|
||||
}
|
||||
|
||||
# Aceita também o link com o @ na frente (a grade do perfil usa /<conta>/reel/<código>/).
|
||||
MEDIA = re.compile(r"instagram\.com/(?:[\w.]+/)?(?:reels?|p)/([\w-]+)")
|
||||
|
||||
|
||||
def check(page: Any, sleep: Sleep = time.sleep) -> str | None:
|
||||
page.goto(HOME_URL, wait_until="domcontentloaded")
|
||||
step_pause(sleep, 2.0, 3.5)
|
||||
reason = detect_block(page, SELECTORS["login"])
|
||||
if reason:
|
||||
return reason
|
||||
if find(page, SELECTORS["create"], timeout_s=15, sleep=sleep) is None:
|
||||
return "não achei o botão Postar do Instagram (a conta pode não estar logada)"
|
||||
return None
|
||||
|
||||
|
||||
def _guard(page: Any) -> None:
|
||||
reason = detect_block(page, SELECTORS["login"])
|
||||
if reason:
|
||||
raise needs_login(reason)
|
||||
|
||||
|
||||
def prepare(page: Any, spec: JobSpec, progress: Progress, sleep: Sleep = time.sleep) -> Any:
|
||||
"""Tudo até o botão Compartilhar (que é devolvido SEM clicar): abre a caixa, envia o arquivo, Avançar ×2,
|
||||
legenda e rótulo de IA. Separado do envio para dar para conferir o fluxo sem publicar."""
|
||||
progress("Abrindo o Instagram…", 0.02)
|
||||
reason = check(page, sleep)
|
||||
if reason:
|
||||
raise needs_login(reason)
|
||||
dismiss_tips(page, sleep)
|
||||
click_through(require(page, SELECTORS["create"], "o botão Postar", sleep=sleep), sleep)
|
||||
step_pause(sleep)
|
||||
submenu = find(page, SELECTORS["create_post"], timeout_s=3, sleep=sleep)
|
||||
if submenu is not None:
|
||||
click_through(submenu, sleep)
|
||||
step_pause(sleep)
|
||||
require(page, SELECTORS["file_input"], "o campo de arquivo", visible=False, sleep=sleep).set_input_files(str(spec.file))
|
||||
progress("Carregando o vídeo…", 0.15)
|
||||
step_pause(sleep, 2.0, 4.0)
|
||||
_guard(page)
|
||||
notice = find(page, SELECTORS["reels_notice_ok"], timeout_s=5, sleep=sleep)
|
||||
if notice is not None: # "Os posts de vídeo agora são compartilhados como reels"
|
||||
click_through(notice, sleep)
|
||||
step_pause(sleep)
|
||||
keep_original_shape(page, sleep)
|
||||
|
||||
for _ in range(2): # Cortar → Editar → Legenda
|
||||
click_through(require(page, SELECTORS["next"], "o botão Avançar", timeout_s=60, sleep=sleep), sleep)
|
||||
step_pause(sleep, 1.5, 3.0)
|
||||
caption = require(page, SELECTORS["caption"], "o campo de legenda", sleep=sleep)
|
||||
if spec.caption:
|
||||
text = spec.caption[:2199]
|
||||
fill_text(caption, text, sleep)
|
||||
close_suggestions(page, text, sleep)
|
||||
|
||||
if spec.ai_generated:
|
||||
toggle = find_ai_switch(page)
|
||||
if toggle is None: # layout antigo: ficava dentro de "Configurações avançadas"
|
||||
advanced = find(page, SELECTORS["advanced"], timeout_s=5, sleep=sleep)
|
||||
if advanced is not None:
|
||||
click_through(advanced, sleep)
|
||||
step_pause(sleep)
|
||||
toggle = find_ai_switch(page) or find(page, SELECTORS["ai_label"], timeout_s=5, visible=False, sleep=sleep)
|
||||
if toggle is None:
|
||||
raise PublishError("Não achei o \"rótulo de IA\" no Instagram; não publiquei sem ele.")
|
||||
if not _is_on(toggle):
|
||||
# Sem clique forçado: se algo cobrir o interruptor, o clique cairia nessa coisa (ensaio de 17/11/2026: caiu
|
||||
# na lista de sugestões de hashtag e trocou "#teste" por "#testemunho").
|
||||
click_through(toggle, sleep)
|
||||
step_pause(sleep)
|
||||
if not _is_on(toggle):
|
||||
raise PublishError("Não consegui ligar o \"rótulo de IA\" no Instagram; não publiquei sem ele.")
|
||||
|
||||
_guard(page)
|
||||
return require(page, SELECTORS["share"], "o botão Compartilhar", sleep=sleep)
|
||||
|
||||
|
||||
# O interruptor "Adicionar rótulo de IA" (validado em 17/11/2026) é um <input type=checkbox role=switch> SEM nome
|
||||
# acessível: o texto fica numa linha ao lado. Acha-se pelo texto da linha, entre os interruptores do diálogo.
|
||||
AI_ROW_TEXT = re.compile(r"(rótulo de IA|AI label|AI info|gerad[oa] por IA)", re.I)
|
||||
_ROW_TEXT_JS = """(e) => { let row = e; for (let i = 0; i < 6 && row; i++, row = row.parentElement) {
|
||||
const t = (row.innerText || '').trim(); if (t) return t.slice(0, 200); } return ''; }"""
|
||||
|
||||
|
||||
def keep_original_shape(page: Any, sleep: Sleep = time.sleep) -> None:
|
||||
"""Na etapa "Cortar", escolhe "Original": o Instagram vem em 1:1 e cortaria o vídeo vertical (o reel de 17/11/2026
|
||||
saiu quadrado, sem o topo do rosto do streamer). Sem achar o seletor, NÃO publica cortado."""
|
||||
toggle = find(page, SELECTORS["crop_toggle"], timeout_s=20, sleep=sleep)
|
||||
if toggle is None:
|
||||
raise PublishError("Não achei o botão de formato (\"Selecionar corte\") do Instagram; não publiquei para o vídeo "
|
||||
"não sair cortado em quadrado.")
|
||||
click_through(toggle, sleep)
|
||||
step_pause(sleep, 0.6, 1.2)
|
||||
original = require(page, SELECTORS["crop_original"], "a opção de formato \"Original\"", timeout_s=8, sleep=sleep)
|
||||
click_through(original, sleep)
|
||||
step_pause(sleep, 0.8, 1.5)
|
||||
# Fecha o menu de formatos (o mesmo ícone) para não ficar por cima do "Avançar".
|
||||
again = find(page, SELECTORS["crop_toggle"], timeout_s=2, sleep=sleep)
|
||||
if again is not None and find(page, SELECTORS["crop_original"], timeout_s=1, sleep=sleep) is not None:
|
||||
click_through(again, sleep)
|
||||
step_pause(sleep, 0.4, 0.8)
|
||||
|
||||
|
||||
def close_suggestions(page: Any, text: str, sleep: Sleep = time.sleep) -> bool:
|
||||
"""Legenda terminando em #tag/@menção deixa aberta a lista de sugestões, por cima dos interruptores — e um clique
|
||||
nela troca a tag (#teste → #testemunho). Um espaço no fim fecha a lista. (Esc aqui fecharia a caixa de criação.)"""
|
||||
words = text.split()
|
||||
if not words or not words[-1].startswith(("#", "@")) or text[-1:].isspace():
|
||||
return False
|
||||
page.keyboard.insert_text(" ")
|
||||
step_pause(sleep, 0.6, 1.2)
|
||||
return True
|
||||
|
||||
|
||||
def find_ai_switch(page: Any) -> Any | None:
|
||||
switches = page.locator(f"{_DIALOG} input[role='switch'], {_DIALOG} input[type='checkbox'], {_DIALOG} [role='switch']")
|
||||
try:
|
||||
total = switches.count()
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
for i in range(total):
|
||||
switch = switches.nth(i)
|
||||
try:
|
||||
if AI_ROW_TEXT.search(switch.evaluate(_ROW_TEXT_JS) or ""):
|
||||
return switch
|
||||
except Exception: # noqa: BLE001 - elemento sumiu durante a leitura
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _is_on(switch: Any) -> bool:
|
||||
try:
|
||||
if (switch.get_attribute("aria-checked") or "").lower() == "true":
|
||||
return True
|
||||
return bool(switch.is_checked())
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
|
||||
def upload(page: Any, spec: JobSpec, progress: Progress, sleep: Sleep = time.sleep) -> PublishResult:
|
||||
share = prepare(page, spec, progress, sleep)
|
||||
click_through(share, sleep)
|
||||
progress("Compartilhando o Reel…", 0.85)
|
||||
step_pause(sleep, 2.0, 4.0)
|
||||
if find(page, SELECTORS["shared"], timeout_s=15 * 60, sleep=sleep) is None:
|
||||
_guard(page)
|
||||
raise PublishError("Cliquei em Compartilhar mas o Instagram não confirmou em 15 minutos. Confira no app antes "
|
||||
"de tentar de novo.")
|
||||
match = MEDIA.search(page.url or "") or MEDIA.search(find_reel_url(page, spec.caption, sleep, progress=progress) or "")
|
||||
if match:
|
||||
return PublishResult(match.group(1), f"https://www.instagram.com/reel/{match.group(1)}/", False,
|
||||
"Publicado no Instagram (site)")
|
||||
return PublishResult(None, None, False, "Publicado no Instagram (site), mas o reel não apareceu no perfil em "
|
||||
"~3 min; link não encontrado")
|
||||
|
||||
|
||||
# Depois de compartilhar o site só diz "Seu reel foi compartilhado" (o endereço não muda): o link vem do perfil.
|
||||
# Barra lateral recolhida esconde o texto "Perfil" (innerText vazio): lê textContent ou a foto do perfil no link.
|
||||
_PROFILE_HREF_JS = """() => {
|
||||
const ok = (h) => /^\\/[\\w.]+\\/$/.test(h || '') && !/^\\/(explore|reels|direct|accounts|stories)\\//.test(h);
|
||||
for (const a of document.querySelectorAll('a[href]')) {
|
||||
const h = a.getAttribute('href');
|
||||
if (!ok(h)) continue;
|
||||
const text = (a.textContent || '').trim();
|
||||
const alt = [...a.querySelectorAll('img')].map((i) => i.getAttribute('alt') || '').join(' ');
|
||||
if (/^(Perfil|Profile)$/i.test(text) || /(foto do perfil|profile picture)/i.test(alt)) return h;
|
||||
}
|
||||
return null;
|
||||
}"""
|
||||
_MEDIA_LINKS_JS = """() => [...new Set([...document.querySelectorAll("a[href*='/reel/'], a[href*='/p/']")]
|
||||
.map(a => a.href))].slice(0, 6)"""
|
||||
_PAGE_HAS_JS = """(key) => { const norm = (s) => (s || '').replace(/\\s+/g, ' ').trim().toLowerCase();
|
||||
return norm(document.body.innerText).includes(norm(key)); }"""
|
||||
|
||||
|
||||
def find_reel_url(page: Any, caption: str, sleep: Sleep = time.sleep, attempts: int = 6, per_load: int = 3,
|
||||
progress: Progress | None = None) -> str | None:
|
||||
"""Link do reel recém-compartilhado: abre a aba Reels do perfil (o link "Perfil" da barra lateral), abre os mais
|
||||
novos e aceita o primeiro cuja página mostra o começo da legenda enviada (nunca o de outro vídeo). O reel novo
|
||||
pode demorar a entrar na grade: recarrega o perfil até `attempts` vezes (~3 min)."""
|
||||
key = caption_key(caption)
|
||||
if not key:
|
||||
return None
|
||||
try:
|
||||
page.goto(HOME_URL, wait_until="domcontentloaded")
|
||||
sleep(4)
|
||||
href = page.evaluate(_PROFILE_HREF_JS)
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
if not href:
|
||||
return None
|
||||
reels_url = urljoin(HOME_URL, href.rstrip("/") + "/reels/")
|
||||
checked: set[str] = set()
|
||||
for attempt in range(attempts):
|
||||
if progress:
|
||||
progress(f"Publicado. Procurando o reel no seu perfil para pegar o link ({attempt + 1} de {attempts})…", 0.95)
|
||||
try:
|
||||
page.goto(reels_url, wait_until="domcontentloaded")
|
||||
sleep(5)
|
||||
links = [link for link in page.evaluate(_MEDIA_LINKS_JS) if MEDIA.search(link)]
|
||||
except Exception: # noqa: BLE001 - rede oscilando: tenta na próxima volta
|
||||
links = []
|
||||
for link in [link for link in links if link not in checked][:per_load]:
|
||||
try:
|
||||
page.goto(link, wait_until="domcontentloaded")
|
||||
sleep(4)
|
||||
if page.evaluate(_PAGE_HAS_JS, key):
|
||||
return link
|
||||
checked.add(link)
|
||||
except Exception: # noqa: BLE001
|
||||
continue
|
||||
sleep(20)
|
||||
return None
|
||||
|
||||
|
||||
UPLOADER = Uploader("instagram", HOME_URL, check, upload)
|
||||
@@ -0,0 +1,177 @@
|
||||
"""Executa conferência de sessão e envios no navegador do perfil (Playwright conectado por CDP).
|
||||
|
||||
Ciclo da janela (para a porta de depuração ficar aberta o mínimo):
|
||||
- "Conectar"/"Entrar de novo": abre a janela na página de login e deixa o usuário entrar (fecha sozinha após 15 min
|
||||
ociosa);
|
||||
- "Já entrei" (check): conferiu que está logado ⇒ fecha a janela (os cookies ficam no perfil); não está ⇒ deixa
|
||||
aberta para o usuário terminar o login;
|
||||
- envio: abre, envia e fecha. Se a rede pedir login/captcha, deixa aberta para o usuário resolver.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
|
||||
from ..base import JobSpec, Progress, PublishError, PublishResult, Sleep
|
||||
from . import instagram_web, tiktok_studio, youtube_studio
|
||||
from .browser import BrowserManager
|
||||
from .common import Uploader, screenshot
|
||||
|
||||
UPLOADERS: dict[str, Uploader] = {
|
||||
"youtube": youtube_studio.UPLOADER,
|
||||
"tiktok": tiktok_studio.UPLOADER,
|
||||
"instagram": instagram_web.UPLOADER,
|
||||
}
|
||||
|
||||
# Onde o usuário faz o login à mão (a janela abre aqui).
|
||||
LOGIN_URLS = {
|
||||
"youtube": "https://studio.youtube.com/",
|
||||
"tiktok": "https://www.tiktok.com/login",
|
||||
"instagram": "https://www.instagram.com/accounts/login/",
|
||||
}
|
||||
|
||||
|
||||
def browser_error_text(detail: str) -> str:
|
||||
"""Frase em pt-BR para um erro do Playwright (o detalhe técnico vai junto, depois)."""
|
||||
if "larger than 50Mb" in detail:
|
||||
return "O navegador recusou o arquivo do vídeo por ser grande demais para a conexão atual. Reinicie o pnpm dev."
|
||||
if "Timeout" in detail and ".click" in detail:
|
||||
return ("Um botão ou campo da página não respondeu ao clique a tempo — em geral um aviso do site aberto por "
|
||||
"cima, ou o site mudou de layout. Veja a captura e tente de novo.")
|
||||
if "Timeout" in detail:
|
||||
return "A página demorou demais para responder. Confira a internet e a janela, e tente de novo."
|
||||
if "Target page, context or browser has been closed" in detail or "has been closed" in detail:
|
||||
return "A janela do navegador foi fechada no meio do envio. Deixe a janela aberta e tente de novo."
|
||||
return "O navegador travou ou mudou de página no meio do envio. Confira a janela e tente de novo."
|
||||
|
||||
|
||||
class SessionRunner:
|
||||
def __init__(self, browsers: BrowserManager, logs_dir: Path, sleep: Sleep = time.sleep):
|
||||
self.browsers = browsers
|
||||
self.logs_dir = logs_dir
|
||||
self.sleep = sleep
|
||||
# Uma ação de navegador por vez (conferência e envio não se atropelam).
|
||||
self.lock = threading.Lock()
|
||||
|
||||
@contextmanager
|
||||
def _busy_guard(self, wait_s: float):
|
||||
if not self.lock.acquire(timeout=wait_s):
|
||||
raise PublishError("O navegador do Publicador está ocupado com um envio agora. Espere terminar e tente de novo.")
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
self.lock.release()
|
||||
|
||||
def open_for_login(self, profile_id: str, platform: str) -> None:
|
||||
url = LOGIN_URLS[platform]
|
||||
was_open = self.browsers.is_open(profile_id)
|
||||
port = self.browsers.open(profile_id, url, for_login=True)
|
||||
if was_open: # janela já aberta: abre uma aba na página de login e traz para a frente
|
||||
with self._busy_guard(3), self.browsers.in_use(profile_id):
|
||||
self._with_page(port, lambda page: (page.goto(url), page.bring_to_front()), keep_page=True,
|
||||
label=f"{platform}-{profile_id}-abrir")
|
||||
|
||||
def check(self, profile_id: str, platform: str) -> str | None:
|
||||
"""None = sessão válida (e a janela é fechada); texto = motivo para entrar de novo (janela fica aberta)."""
|
||||
uploader = UPLOADERS[platform]
|
||||
holder: dict[str, Any] = {}
|
||||
with self._busy_guard(5):
|
||||
port = self.browsers.open(profile_id, uploader.upload_url, for_login=True)
|
||||
with self.browsers.in_use(profile_id):
|
||||
def run(page: Any) -> None:
|
||||
holder["reason"] = uploader.check(page, self.sleep)
|
||||
|
||||
self._with_page(port, run, keep_page=lambda: holder.get("reason") is not None,
|
||||
label=f"{platform}-{profile_id}-check")
|
||||
if holder.get("reason") is None:
|
||||
self.browsers.close(profile_id)
|
||||
return holder.get("reason")
|
||||
|
||||
def publish(self, spec: JobSpec, progress: Progress) -> PublishResult:
|
||||
uploader = UPLOADERS[spec.platform]
|
||||
holder: dict[str, Any] = {}
|
||||
with self.lock:
|
||||
port = self.browsers.open(spec.profile_id, uploader.upload_url)
|
||||
keep_window = False
|
||||
try:
|
||||
with self.browsers.in_use(spec.profile_id):
|
||||
def run(page: Any) -> None:
|
||||
holder["result"] = uploader.upload(page, spec, progress, self.sleep)
|
||||
|
||||
self._with_page(port, run, keep_page=lambda: "result" not in holder,
|
||||
label=f"{spec.platform}-{spec.job_id}")
|
||||
except PublishError as exc:
|
||||
# Login/captcha: a janela fica para o usuário resolver (fecha sozinha se ficar ociosa).
|
||||
keep_window = exc.kind == "needs_login"
|
||||
raise
|
||||
finally:
|
||||
if not keep_window:
|
||||
self.browsers.close(spec.profile_id)
|
||||
return holder["result"]
|
||||
|
||||
def read_stats(self, profile_id: str, platform: str, ids: list[str]) -> dict[str, Any]:
|
||||
"""Números dos posts pela janela logada (só lê). Espera até 2 min um envio em andamento terminar.
|
||||
Fecha a janela no fim, a não ser que ela já estivesse aberta antes (o usuário pode estar usando)."""
|
||||
from .stats import READERS
|
||||
|
||||
url, reader = READERS[platform]
|
||||
holder: dict[str, Any] = {}
|
||||
with self._busy_guard(120):
|
||||
was_open = self.browsers.is_open(profile_id)
|
||||
port = self.browsers.open(profile_id, url)
|
||||
try:
|
||||
with self.browsers.in_use(profile_id):
|
||||
def run(page: Any) -> None:
|
||||
holder["stats"] = reader(page, ids, self.sleep)
|
||||
|
||||
self._with_page(port, run, keep_page=False, label=f"{platform}-{profile_id}-numeros")
|
||||
finally:
|
||||
if not was_open:
|
||||
self.browsers.close(profile_id)
|
||||
return holder.get("stats", {})
|
||||
|
||||
def _with_page(self, port: int, fn: Callable[[Any], Any], keep_page: bool | Callable[[], bool], label: str) -> None:
|
||||
try:
|
||||
from playwright.sync_api import Error as PlaywrightError
|
||||
from playwright.sync_api import sync_playwright
|
||||
except ImportError as exc: # pragma: no cover - depende da venv
|
||||
raise PublishError("O Playwright não está instalado no Publicador. Rode o setup.bat de novo.") from exc
|
||||
with sync_playwright() as pw:
|
||||
try:
|
||||
# is_local: o Chrome roda NESTE computador (127.0.0.1, a porta é conferida como nossa). Sem isso o
|
||||
# Playwright trata o navegador como remoto e recusa enviar arquivo > 50 MB ("Cannot transfer files
|
||||
# larger than 50Mb to a browser not co-located with the server") — e os cortes passam de 100 MB.
|
||||
browser = pw.chromium.connect_over_cdp(f"http://127.0.0.1:{port}", timeout=15000, is_local=True)
|
||||
except PlaywrightError as exc:
|
||||
raise PublishError("Não consegui me conectar à janela do navegador. Feche a janela do perfil e tente "
|
||||
"de novo.") from exc
|
||||
context = browser.contexts[0] if browser.contexts else browser.new_context()
|
||||
page = context.new_page()
|
||||
page.set_default_timeout(30000)
|
||||
keep = True
|
||||
try:
|
||||
fn(page)
|
||||
keep = keep_page() if callable(keep_page) else keep_page
|
||||
except PublishError as exc:
|
||||
# Sem captura em login/captcha/verificação (a tela pode ter dados pessoais); só em falha comum.
|
||||
if exc.kind == "failed":
|
||||
shot = screenshot(page, self.logs_dir, label)
|
||||
if shot:
|
||||
exc.message += f" (Captura: {shot.name})"
|
||||
exc.args = (exc.message,)
|
||||
raise
|
||||
except PlaywrightError as exc:
|
||||
shot = screenshot(page, self.logs_dir, label)
|
||||
raise PublishError(f"{browser_error_text(str(exc))}{f' (Captura: {shot.name})' if shot else ''} "
|
||||
f"Detalhe: {str(exc)[:160]}") from exc
|
||||
finally:
|
||||
if not keep:
|
||||
try:
|
||||
page.close()
|
||||
except PlaywrightError:
|
||||
pass
|
||||
# Aqui só desconectamos; quem fecha a janela (quando deve) é o BrowserManager.close, fora deste bloco.
|
||||
@@ -0,0 +1,144 @@
|
||||
"""Números dos posts pela janela logada (TikTok e Instagram). Só LÊ: não clica em nada além de rolar a página.
|
||||
|
||||
Validado com a conta real em 17/11/2026:
|
||||
- TikTok Studio, /tiktokstudio/content: cada post é uma linha (`data-tt="components_RowLayout_FlexRow"`) com o link
|
||||
`/@conta/video/<id>` e o texto terminando em "Todos\\n<visualizações>\\n<curtidas>\\n<comentários>".
|
||||
- Instagram, aba Reels do perfil: a página busca os reels em /api/graphql com `code`, `play_count` (visualizações),
|
||||
`like_count` e `comment_count`; a grade mostra as visualizações no próprio quadradinho ("1.499").
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
from typing import Any, Iterable
|
||||
from urllib.parse import urljoin
|
||||
|
||||
from ..base import Sleep
|
||||
from ..stats import PostStats, parse_count
|
||||
from . import instagram_web
|
||||
from .common import detect_block, needs_login
|
||||
|
||||
# ---------- TikTok
|
||||
|
||||
TIKTOK_CONTENT_URL = "https://www.tiktok.com/tiktokstudio/content"
|
||||
_TIKTOK_VIDEO = re.compile(r"/video/(\d+)")
|
||||
|
||||
# Linha de cada link de vídeo: o ancestral mais próximo cujo texto tem várias linhas e a privacidade do post.
|
||||
_TIKTOK_ROWS_JS = r"""() => [...document.querySelectorAll('a[href*="/video/"]')].map(a => {
|
||||
let el = a;
|
||||
for (let i = 0; i < 14 && el; i++, el = el.parentElement) {
|
||||
if (el.getAttribute && el.getAttribute('data-tt') === 'components_RowLayout_FlexRow') break;
|
||||
}
|
||||
return {href: a.href, text: el ? el.innerText : ''};
|
||||
})"""
|
||||
|
||||
|
||||
def tiktok_row_stats(href: str, text: str) -> PostStats | None:
|
||||
"""As três últimas linhas da linha do Studio são visualizações, curtidas e comentários."""
|
||||
match = _TIKTOK_VIDEO.search(href or "")
|
||||
lines = [line.strip() for line in (text or "").split("\n") if line.strip()]
|
||||
if not match or len(lines) < 3:
|
||||
return None
|
||||
counts = [parse_count(line) for line in lines[-3:]]
|
||||
if any(c is None for c in counts):
|
||||
return None
|
||||
return PostStats(match.group(1), counts[0], counts[1], counts[2])
|
||||
|
||||
|
||||
def tiktok_stats(page: Any, ids: Iterable[str], sleep: Sleep = time.sleep, scrolls: int = 8) -> dict[str, PostStats]:
|
||||
wanted = set(ids)
|
||||
found: dict[str, PostStats] = {}
|
||||
page.goto(TIKTOK_CONTENT_URL, wait_until="domcontentloaded")
|
||||
_guard(page)
|
||||
for attempt in range(scrolls + 4):
|
||||
sleep(3)
|
||||
for row in page.evaluate(_TIKTOK_ROWS_JS) or []:
|
||||
stats = tiktok_row_stats(row.get("href", ""), row.get("text", ""))
|
||||
if stats and stats.remote_id in wanted:
|
||||
found[stats.remote_id] = stats
|
||||
if wanted <= set(found):
|
||||
break
|
||||
if attempt >= 3: # a lista carrega mais posts ao rolar até o fim
|
||||
page.mouse.wheel(0, 4000)
|
||||
return found
|
||||
|
||||
|
||||
# ---------- Instagram
|
||||
|
||||
INSTAGRAM_HOME = instagram_web.HOME_URL
|
||||
_TILES_JS = r"""() => [...document.querySelectorAll('a[href*="/reel/"]')].map(a => ({href: a.getAttribute('href'), text: a.innerText}))"""
|
||||
_REEL_CODE = re.compile(r"/reels?/([\w-]+)")
|
||||
|
||||
|
||||
def instagram_media(payload: Any, out: dict[str, PostStats]) -> None:
|
||||
"""Percorre a resposta do /api/graphql e guarda cada mídia com `code` e números."""
|
||||
if isinstance(payload, dict):
|
||||
code = payload.get("code")
|
||||
if isinstance(code, str) and any(k in payload for k in ("play_count", "like_count", "view_count")):
|
||||
views = next((payload[k] for k in ("play_count", "ig_play_count", "view_count", "video_view_count")
|
||||
if isinstance(payload.get(k), int)), None)
|
||||
likes = payload.get("like_count") if isinstance(payload.get("like_count"), int) else None
|
||||
comments = payload.get("comment_count") if isinstance(payload.get("comment_count"), int) else None
|
||||
if views is not None or likes is not None:
|
||||
out[code] = PostStats(code, views, likes, comments)
|
||||
for value in payload.values():
|
||||
instagram_media(value, out)
|
||||
elif isinstance(payload, list):
|
||||
for value in payload:
|
||||
instagram_media(value, out)
|
||||
|
||||
|
||||
def instagram_stats(page: Any, codes: Iterable[str], sleep: Sleep = time.sleep, scrolls: int = 6) -> dict[str, PostStats]:
|
||||
wanted = set(codes)
|
||||
bodies: list[str] = []
|
||||
|
||||
def on_response(response: Any) -> None:
|
||||
try:
|
||||
if "/api/graphql" in response.url or "/api/v1/" in response.url:
|
||||
bodies.append(response.text())
|
||||
except Exception: # noqa: BLE001 - resposta sem corpo (redirect, cancelada)
|
||||
pass
|
||||
|
||||
page.on("response", on_response)
|
||||
page.goto(INSTAGRAM_HOME, wait_until="domcontentloaded")
|
||||
_guard(page)
|
||||
sleep(4)
|
||||
href = page.evaluate(instagram_web._PROFILE_HREF_JS) # o mesmo do envio (barra lateral)
|
||||
if not href:
|
||||
raise needs_login("não achei o link do seu perfil no Instagram (a sessão pode ter saído)")
|
||||
page.goto(urljoin(INSTAGRAM_HOME, href.rstrip("/") + "/reels/"), wait_until="domcontentloaded")
|
||||
_guard(page)
|
||||
api: dict[str, PostStats] = {}
|
||||
tiles: dict[str, PostStats] = {}
|
||||
for attempt in range(scrolls + 2):
|
||||
sleep(4)
|
||||
while bodies:
|
||||
body = bodies.pop()
|
||||
try:
|
||||
instagram_media(json.loads(body), api)
|
||||
except ValueError:
|
||||
continue
|
||||
# Reserva, se a resposta da API mudar de formato: as visualizações do quadradinho da grade.
|
||||
for tile in page.evaluate(_TILES_JS) or []:
|
||||
match = _REEL_CODE.search(tile.get("href") or "")
|
||||
views = parse_count((tile.get("text") or "").split("\n")[0])
|
||||
if match and views is not None:
|
||||
tiles[match.group(1)] = PostStats(match.group(1), views)
|
||||
# A grade aparece antes da resposta da API: só para cedo com a API; com a grade, depois de umas voltas.
|
||||
if wanted <= set(api) or (attempt >= 2 and wanted <= set(api) | set(tiles)):
|
||||
break
|
||||
if attempt >= 1:
|
||||
page.mouse.wheel(0, 4000)
|
||||
found = {**tiles, **api}
|
||||
return {code: stats for code, stats in found.items() if code in wanted}
|
||||
|
||||
|
||||
def _guard(page: Any) -> None:
|
||||
reason = detect_block(page)
|
||||
if reason:
|
||||
raise needs_login(reason)
|
||||
|
||||
|
||||
READERS = {"tiktok": (TIKTOK_CONTENT_URL, tiktok_stats), "instagram": (INSTAGRAM_HOME, instagram_stats)}
|
||||
@@ -0,0 +1,189 @@
|
||||
"""TikTok pelo TikTok Studio (modo sessão logada): tiktok.com/tiktokstudio/upload.
|
||||
|
||||
ATENÇÃO: seletores escritos pela estrutura conhecida da página (nomes acessíveis em PT e EN, atributos
|
||||
`data-e2e`) e AINDA NÃO VALIDADOS COM UMA CONTA REAL. Corrigir só neste dicionário. O TikTok mostra captcha com
|
||||
frequência: quando aparecer, o envio para em `needs_login` — o usuário resolve na janela; nunca automatizamos isso.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from ..base import JobSpec, Progress, PublishError, PublishResult, Sleep
|
||||
from .common import (Uploader, caption_key, click_through, detect_block, dismiss_tips, fill_text, find, needs_login,
|
||||
require, step_pause)
|
||||
|
||||
UPLOAD_URL = "https://www.tiktok.com/tiktokstudio/upload?from=upload"
|
||||
|
||||
SELECTORS: dict[str, list[tuple]] = {
|
||||
"login": [("role", "button", r"^(Entrar|Log in)$"), ("css", "[data-e2e='top-login-button']"),
|
||||
("role", "link", r"^(Entrar|Log in)$")],
|
||||
"file_input": [("css", "input[type='file'][accept*='video']"), ("css", "input[type='file']")],
|
||||
"caption": [("css", "div[contenteditable='true'].public-DraftEditor-content"),
|
||||
("css", ".caption-editor div[contenteditable='true']"), ("css", "div[contenteditable='true']")],
|
||||
# Fim do envio do arquivo (a página mostra "Enviado"/"Uploaded" junto ao nome do arquivo).
|
||||
"uploaded": [("text", r"^(Enviado|Carregado|Uploaded)\b"), ("css", "[data-e2e='upload-success']")],
|
||||
"privacy_dropdown": [("role", "combobox", r"(Quem pode (ver|assistir)|Who can (watch|view))"),
|
||||
("css", "[data-e2e='video-setting-privacy'] [role='button'], .view-auth-container [role='button']")],
|
||||
"privacy_public": [("role", "option", r"^(Todos|Todo mundo|Everyone)$"), ("text", r"^(Todos|Everyone)$")],
|
||||
"privacy_private": [("role", "option", r"^(Somente você|Só você|Only you|Only me)$"),
|
||||
("text", r"^(Somente você|Só você|Only you|Only me)$")],
|
||||
"show_more": [("role", "button", r"^(Mostrar mais|Exibir mais|Show more)$"), ("text", r"^(Mostrar mais|Show more)$")],
|
||||
"ai_toggle": [("role", "switch", r"(gerado por IA|AI-generated)"),
|
||||
("css", "[data-e2e='aigc_container'] input[type='checkbox'], [data-e2e='aigc_container'] [role='switch']")],
|
||||
"post": [("css", "button[data-e2e='post_video_button']"), ("role", "button", r"^(Publicar|Postar|Post)$")],
|
||||
"post_now": [("role", "button", r"^(Publicar agora|Postar agora|Post now)$")],
|
||||
"posted": [("text", r"(Seu vídeo foi publicado|vídeo (está|foi) (sendo )?publicado|Your video (has been|is being) "
|
||||
r"(posted|published)|Gerenciar suas publicações|Manage your posts|Vídeo publicado|Video posted)")],
|
||||
}
|
||||
|
||||
VIDEO_ID = re.compile(r"tiktok\.com/@([\w.-]+)/video/(\d+)")
|
||||
|
||||
|
||||
def check(page: Any, sleep: Sleep = time.sleep) -> str | None:
|
||||
page.goto(UPLOAD_URL, wait_until="domcontentloaded")
|
||||
step_pause(sleep, 2.0, 3.5)
|
||||
reason = detect_block(page, SELECTORS["login"])
|
||||
if reason:
|
||||
return reason
|
||||
if find(page, SELECTORS["file_input"], timeout_s=15, visible=False, sleep=sleep) is None:
|
||||
return "não achei o campo de envio do TikTok Studio (a conta pode não estar logada)"
|
||||
return None
|
||||
|
||||
|
||||
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 TikTok Studio…", 0.02)
|
||||
reason = check(page, sleep)
|
||||
if reason:
|
||||
raise needs_login(reason)
|
||||
require(page, SELECTORS["file_input"], "o campo de arquivo", visible=False, sleep=sleep).set_input_files(str(spec.file))
|
||||
progress("Enviando vídeo pelo TikTok Studio…", 0.1)
|
||||
step_pause(sleep, 2.0, 4.0)
|
||||
_guard(page)
|
||||
|
||||
caption = require(page, SELECTORS["caption"], "o campo de legenda", timeout_s=60, sleep=sleep)
|
||||
# Com o vídeo carregado, o Studio às vezes abre um aviso de novidade por cima de tudo ("Veja a prévia…").
|
||||
step_pause(sleep, 1.0, 2.0)
|
||||
dismiss_tips(page, sleep)
|
||||
fill_text(caption, spec.caption[:2200], sleep)
|
||||
# Fecha a lista de sugestões de hashtag/menção que aparece ao digitar "#" ou "@".
|
||||
page.keyboard.press("Escape")
|
||||
step_pause(sleep)
|
||||
|
||||
want_private = spec.privacy in ("private", "unlisted")
|
||||
dropdown = find(page, SELECTORS["privacy_dropdown"], timeout_s=5, sleep=sleep)
|
||||
if dropdown is not None:
|
||||
click_through(dropdown, sleep)
|
||||
step_pause(sleep)
|
||||
click_through(require(page, SELECTORS["privacy_private" if want_private else "privacy_public"],
|
||||
"a opção de privacidade", sleep=sleep), sleep)
|
||||
step_pause(sleep)
|
||||
elif want_private:
|
||||
raise PublishError("Não achei onde escolher a privacidade no TikTok Studio; não publiquei para não expor um "
|
||||
"vídeo que era para ser privado.")
|
||||
|
||||
if spec.ai_generated:
|
||||
more = find(page, SELECTORS["show_more"], timeout_s=3, sleep=sleep)
|
||||
if more is not None:
|
||||
click_through(more, sleep)
|
||||
step_pause(sleep)
|
||||
toggle = find(page, SELECTORS["ai_toggle"], timeout_s=5, visible=False, sleep=sleep)
|
||||
if toggle is None:
|
||||
raise PublishError("Não achei o rótulo \"Conteúdo gerado por IA\" no TikTok Studio; não publiquei sem ele.")
|
||||
if (toggle.get_attribute("aria-checked") or "").lower() != "true" and not _is_checked(toggle):
|
||||
click_through(toggle, sleep)
|
||||
step_pause(sleep)
|
||||
|
||||
progress("Esperando o envio terminar…", 0.5)
|
||||
if find(page, SELECTORS["uploaded"], timeout_s=30 * 60, sleep=sleep) is None:
|
||||
raise PublishError("O envio pelo TikTok Studio não terminou em 30 minutos. Confira a internet e tente de novo.")
|
||||
_guard(page)
|
||||
|
||||
post = require(page, SELECTORS["post"], "o botão Publicar", timeout_s=60, sleep=sleep)
|
||||
for _ in range(60): # o botão fica desabilitado enquanto a verificação de conteúdo roda
|
||||
if post.is_enabled():
|
||||
break
|
||||
sleep(2)
|
||||
dismiss_tips(page, sleep)
|
||||
click_through(post, sleep)
|
||||
progress("Publicando…", 0.9)
|
||||
step_pause(sleep, 2.0, 4.0)
|
||||
now_button = find(page, SELECTORS["post_now"], timeout_s=5, sleep=sleep)
|
||||
if now_button is not None:
|
||||
click_through(now_button, sleep)
|
||||
step_pause(sleep)
|
||||
_guard(page)
|
||||
if find(page, SELECTORS["posted"], timeout_s=90, sleep=sleep) is None and "tiktokstudio/content" not in page.url:
|
||||
raise PublishError("Cliquei em Publicar mas o TikTok não confirmou. Confira no app antes de tentar de novo.")
|
||||
url = find_video_url(page, spec.caption, sleep, progress=progress)
|
||||
match = VIDEO_ID.search(url or "")
|
||||
if match:
|
||||
return PublishResult(match.group(2), f"https://www.tiktok.com/@{match.group(1)}/video/{match.group(2)}", False,
|
||||
"Publicado no TikTok (Studio)")
|
||||
return PublishResult(None, None, False, "Publicado no TikTok (Studio), mas o vídeo não apareceu na lista do Studio "
|
||||
"em ~3 min; link não encontrado")
|
||||
|
||||
|
||||
CONTENT_URL = "https://www.tiktok.com/tiktokstudio/content"
|
||||
|
||||
# Na lista "Publicações" do Studio (validado com conta real em 17/11/2026), cada linha tem um <a href="/@conta/video/<id>">
|
||||
# e a descrição do post. Só aceita o link cuja linha contém o começo da legenda enviada: nunca pegar o de outro vídeo.
|
||||
_LINK_FOR_CAPTION_JS = """(key) => {
|
||||
const norm = (s) => (s || "").replace(/\\s+/g, " ").trim().toLowerCase();
|
||||
const want = norm(key);
|
||||
for (const a of document.querySelectorAll("a[href*='/video/']")) {
|
||||
if (!want) return a.href;
|
||||
let el = a;
|
||||
for (let i = 0; i < 10 && el; i++, el = el.parentElement) {
|
||||
if (norm(el.innerText).includes(want)) return a.href;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}"""
|
||||
|
||||
|
||||
def find_video_url(page: Any, caption: str, sleep: Sleep = time.sleep, attempts: int = 12, reads: int = 5,
|
||||
progress: Progress | None = None) -> str | None:
|
||||
"""Link do vídeo recém-publicado (ideia do dono, 17/11/2026: "esperar um pouco e depois ir em /content ver se o
|
||||
vídeo já está lá"). A lista do Studio NÃO se atualiza sozinha e o vídeo novo só entra depois de processar: espera
|
||||
um pouco, abre (ou recarrega) a lista e procura por ~15 s; não achou ⇒ recarrega de novo. Até `attempts` cargas
|
||||
(~3 min). Na 1ª, se o Studio já levou para a lista sozinho, só lê."""
|
||||
key = caption_key(caption)
|
||||
sleep(5)
|
||||
for attempt in range(attempts):
|
||||
if progress:
|
||||
progress(f"Publicado. Esperando o vídeo aparecer na lista do Studio para pegar o link "
|
||||
f"({attempt + 1} de {attempts})…", 0.95)
|
||||
if attempt > 0 or "tiktokstudio/content" not in (page.url or ""):
|
||||
try:
|
||||
page.goto(CONTENT_URL, wait_until="domcontentloaded")
|
||||
except Exception: # noqa: BLE001 - rede oscilando: tenta de novo na próxima carga
|
||||
sleep(3)
|
||||
continue
|
||||
for _ in range(reads):
|
||||
try:
|
||||
href = page.evaluate(_LINK_FOR_CAPTION_JS, key)
|
||||
except Exception: # noqa: BLE001 - página trocando no meio da leitura: tenta de novo
|
||||
href = None
|
||||
if href and VIDEO_ID.search(href):
|
||||
return href
|
||||
sleep(3)
|
||||
return None
|
||||
|
||||
|
||||
def _is_checked(locator: Any) -> bool:
|
||||
try:
|
||||
return bool(locator.is_checked())
|
||||
except Exception: # noqa: BLE001 - nem todo switch é checkbox nativo
|
||||
return False
|
||||
|
||||
|
||||
UPLOADER = Uploader("tiktok", UPLOAD_URL, check, upload)
|
||||
@@ -0,0 +1,217 @@
|
||||
"""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)
|
||||
Reference in New Issue
Block a user