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,13 @@
|
||||
# Publicador do CenaForge. O setup.bat copia este arquivo para publisher/.env e preenche a chave.
|
||||
# Gere uma chave à mão com: python -c "import secrets; print(secrets.token_urlsafe(48))"
|
||||
# O painel lê esta mesma chave para conversar com o Publicador (cabeçalho X-Service-Key).
|
||||
PUBLISHER_SERVICE_KEY=
|
||||
# Porta (faixa 4500–4599 do CenaForge). Escuta só em 127.0.0.1. Os redirects do OAuth usam esta porta:
|
||||
# se mudar, troque também o redirect cadastrado no app do Google e do TikTok.
|
||||
PUBLISHER_PORT=4530
|
||||
# Navegador do modo "sessão logada". Vazio = procura Chrome (preferido) e depois Edge nos lugares de sempre.
|
||||
# PUBLISHER_BROWSER_PATH=C:\Program Files\Google\Chrome\Application\chrome.exe
|
||||
# Versão da Graph API do Instagram (graph.instagram.com).
|
||||
PUBLISHER_IG_API_VERSION=v24.0
|
||||
# Pasta de dados opcional para isolar uma instância de teste (vazio = data/publisher). Precisa ficar no repositório.
|
||||
# PUBLISHER_DATA_DIR=data/publisher
|
||||
@@ -0,0 +1,3 @@
|
||||
.venv/
|
||||
.env
|
||||
__pycache__/
|
||||
@@ -0,0 +1,115 @@
|
||||
# Publicador do CenaForge
|
||||
|
||||
Serviço local (`127.0.0.1:4530`) que **envia os vídeos para YouTube, TikTok e Instagram**. Ele é só o *executor*:
|
||||
recebe do painel um pedido de envio (arquivo + título/legenda + perfil), manda para a rede e devolve o progresso e o
|
||||
link. Quem decide **o quê** e **quando** publicar é o painel (Canais de publicação, aprovação, horários bons).
|
||||
|
||||
Contrato HTTP e regras: [doc/publicacao/PLANO.md](../doc/publicacao/PLANO.md) (§3). Fatos das APIs:
|
||||
[doc/publicacao/PESQUISA.md](../doc/publicacao/PESQUISA.md).
|
||||
|
||||
## Como rodar
|
||||
|
||||
- Instalação: `setup.bat` na raiz (cria `publisher/.venv` com Python 3.12 e `publisher/.env` com a chave).
|
||||
- Subir: `start.bat` ou `pnpm dev` (sobe junto com o painel). Sem `.venv`/chave, o `pnpm dev` pula o Publicador com
|
||||
um aviso.
|
||||
- Testes: `pnpm test:publisher` (pytest, sem internet e sem abrir navegador).
|
||||
- Só o serviço, à mão: `cd publisher && .venv\Scripts\python -m uvicorn app.main:build --factory --port 4530`.
|
||||
|
||||
O painel conversa com ele usando o cabeçalho `X-Service-Key` = `PUBLISHER_SERVICE_KEY` de `publisher/.env`.
|
||||
|
||||
## Envio sem duplicar
|
||||
|
||||
`POST /v1/jobs` aceita `clientRef` (até 80 caracteres, ex.: o id do job no painel). Se chegar de novo com o mesmo
|
||||
`clientRef`, o Publicador devolve o job que já existe (HTTP 200, sem criar outro nem revalidar); um job novo volta
|
||||
com 201. Vídeo e capa só são aceitos das pastas de saída (`output/`, `stories/`, `assets/`).
|
||||
|
||||
## Dois modos por rede (você escolhe perfil a perfil)
|
||||
|
||||
| | Conta oficial (API) | Sessão logada |
|
||||
|---|---|---|
|
||||
| Como conecta | autoriza na página da rede (YouTube, TikTok) ou cola um token (Instagram) | você entra na conta numa janela do Chrome/Edge aberta pelo CenaForge |
|
||||
| Precisa criar app | sim (passo a passo abaixo) | não |
|
||||
| Risco para a conta | baixo (caminho oficial) | **alto: viola os termos das três redes** (pode bloquear a conta) |
|
||||
| Limites | YouTube 100 envios/dia; TikTok sem auditoria só privado ou rascunho | captcha/verificações; a tela das redes muda |
|
||||
|
||||
### Regras do modo sessão (não negociáveis)
|
||||
|
||||
- A janela do navegador é **visível** e **você faz o login à mão** (com 2FA normal). O CenaForge nunca vê, guarda ou
|
||||
digita sua senha e **nunca** resolve captcha.
|
||||
- Nada de "stealth", patchright, stealth.js ou qualquer burla de detecção de automação. Se a rede pedir login,
|
||||
captcha ou "confirme que é você", o envio **para** em `needs_login` e o painel avisa — você resolve na janela e
|
||||
clica em "Já entrei".
|
||||
- Um envio por vez, com **intervalo mínimo entre envios** (30 s) e pausas curtas entre os passos. É só ritmo para
|
||||
não sobrecarregar a conta — não é tentativa de imitar uma pessoa.
|
||||
- A porta de depuração do navegador (4540–4549) dá controle total dele, então fica aberta o mínimo: a janela fecha
|
||||
depois de cada envio, depois do "Já entrei" bem-sucedido e quando fica parada (5 min; 15 min se foi aberta para o
|
||||
login). Antes de usar uma porta, o serviço confere que é o navegador DESTE perfil (`DevToolsActivePort` quando existe; no Chrome 157+ com porta
|
||||
fixa ele não é gravado, então vale a marca `CenaForgeWindow.json` + o PID que escuta na porta).
|
||||
- O navegador é o **seu Chrome** (ou Edge) instalado, aberto como programa normal com um perfil separado. O pacote
|
||||
`playwright` entra só como "controle remoto" (`connect_over_cdp`); **não rode `playwright install`** — nada é baixado.
|
||||
- Os seletores das telas (YouTube Studio, TikTok Studio, Instagram) ficam num dicionário `SELECTORS` no topo de cada
|
||||
arquivo em `app/platforms/session/` e **ainda precisam ser validados com uma conta real**. Quando algo falha, há uma
|
||||
captura só da área visível em `data/publisher/logs/` — nunca de tela de login, captcha ou verificação. Capturas com
|
||||
mais de 7 dias são apagadas na subida do serviço.
|
||||
|
||||
## Criar o app de cada rede (modo oficial)
|
||||
|
||||
Os dados do app vão em **Configurações → Apps das redes** no painel (ou `PUT /v1/apps/{rede}`).
|
||||
|
||||
### YouTube (Google Cloud)
|
||||
|
||||
1. Em <https://console.cloud.google.com/> crie um projeto e ative a **YouTube Data API v3**.
|
||||
2. Em "Tela de permissão OAuth" (Google Auth Platform), tipo **Externo**; adicione seu e-mail.
|
||||
3. Em "Clientes", crie um cliente OAuth do tipo **App para computador (Desktop app)**. Copie o Client ID e o Client
|
||||
Secret para o painel. O redirect usado é `http://127.0.0.1:4530/oauth/callback/youtube` (cliente Desktop aceita
|
||||
loopback em qualquer porta, não precisa cadastrar).
|
||||
4. Em "Público", clique em **Publicar app / In production**. Em "Testing" a autorização vence a cada 7 dias. Vai
|
||||
aparecer a tela "o Google não verificou este app" — é o seu próprio app: "Avançado → continuar".
|
||||
|
||||
### TikTok (TikTok for Developers)
|
||||
|
||||
1. Em <https://developers.tiktok.com/> crie um app e adicione **Login Kit** (plataforma **Desktop**) e **Content
|
||||
Posting API** (ative "Direct Post" se quiser publicar direto).
|
||||
2. Cadastre o redirect `http://127.0.0.1:4530/oauth/callback/tiktok` e os escopos `user.info.basic`,
|
||||
`video.upload`, `video.publish`.
|
||||
3. Copie o **Client Key** (vai no campo Client ID) e o **Client Secret** para o painel.
|
||||
4. **Sem auditoria do TikTok**, o Direct Post só sai como **privado (Somente eu)** e a conta precisa estar privada; o
|
||||
serviço avisa: "O TikTok só permite publicar como privado (Somente eu) até o app ser auditado. Use o modo Rascunho
|
||||
ou a Sessão logada." O modo **Rascunho** manda o vídeo para a caixa de entrada do app (até 5 pendentes por dia) e
|
||||
você publica pelo celular. A auditoria provavelmente é negada para uso próprio.
|
||||
|
||||
### Instagram (Meta for Developers)
|
||||
|
||||
1. A conta do Instagram precisa ser **Profissional** (Criador de conteúdo ou Empresa).
|
||||
2. Em <https://developers.facebook.com/> crie um app e adicione o produto **Instagram → "API setup with Instagram
|
||||
login"** (Instagram API with Instagram Login). Permissões: `instagram_business_basic`,
|
||||
`instagram_business_content_publish`.
|
||||
3. Em "Generate access tokens", adicione sua conta e clique em **Generate token**. Copie o token e cole em Canais de
|
||||
publicação → Instagram → Conta oficial. (A Meta não aceita redirect para `localhost`, por isso o token é colado.)
|
||||
4. O token vale 60 dias; o Publicador renova sozinho quando faltam menos de 10 dias (se estiver ligado).
|
||||
5. O envio usa o upload do arquivo local (`rupload`). A Meta documenta isso só para "Facebook Login for Business";
|
||||
se a rede recusar, o erro diz isso com clareza e a saída é usar a Sessão logada (ou o Facebook Login).
|
||||
|
||||
## Onde ficam os dados
|
||||
|
||||
Tudo em `data/publisher/` (fora do controle de versão):
|
||||
|
||||
| Caminho | O quê |
|
||||
|---|---|
|
||||
| `publisher.db` | perfis, jobs de envio e os `state` do OAuth (SQLite) |
|
||||
| `vault.bin` | **segredos** (tokens, client secret) cifrados com a DPAPI do Windows — só o seu usuário, nesta máquina, abre |
|
||||
| `browser/<perfil>/` | perfil do Chrome/Edge do modo sessão (cookies = sua sessão logada). "Desconectar" apaga a pasta |
|
||||
| `logs/` | capturas de tela das falhas do modo sessão (apagadas após 7 dias) |
|
||||
|
||||
Permissões: o `setup.bat` deixa `publisher/.env` e `data/publisher/` acessíveis só ao seu usuário do Windows
|
||||
(`icacls /inheritance:r`); se a pasta não existir, o próprio serviço a cria assim na primeira subida.
|
||||
|
||||
Os segredos nunca voltam pela API (só `configured: true/false`). Se o Publicador for fechado no meio de um envio, o
|
||||
job vira `failed` com "interrompido — tente de novo" (não dá para saber se chegou à rede: confira antes).
|
||||
|
||||
## Arquivos
|
||||
|
||||
- `app/main.py` rotas · `app/service.py` regras · `app/worker.py` fila (uma thread, um job por vez)
|
||||
- `app/db.py` SQLite · `app/vault.py` cofre DPAPI · `app/paths.py` só aceita vídeo/capa de `output/`, `stories/` e `assets/` (recusa `data/`)
|
||||
- `app/platforms/{youtube,tiktok,instagram}_api.py` APIs oficiais
|
||||
- `app/platforms/session/` navegador (`browser.py`), execução (`runner.py`) e um uploader por rede
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Permissões NTFS: deixa a pasta de dados do Publicador (cofre, banco, perfis de navegador, capturas) acessível só
|
||||
ao usuário atual do Windows. O setup.ps1 faz o mesmo (e também no publisher/.env); aqui cobre a pasta criada pelo
|
||||
próprio serviço na primeira subida."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
log = logging.getLogger("publisher.acl")
|
||||
|
||||
|
||||
def current_user_sid() -> str | None:
|
||||
if sys.platform != "win32":
|
||||
return None
|
||||
try:
|
||||
out = subprocess.run(["whoami", "/user", "/fo", "csv", "/nh"], capture_output=True, text=True, timeout=10)
|
||||
# "dominio\\usuario","S-1-5-21-..."
|
||||
return out.stdout.strip().split(",")[-1].strip().strip('"') or None
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return None
|
||||
|
||||
|
||||
def icacls_args(target: Path, sid: str, directory: bool) -> list[str]:
|
||||
grant = f"*{sid}:(OI)(CI)F" if directory else f"*{sid}:F"
|
||||
return ["icacls", str(target), "/inheritance:r", "/grant:r", grant]
|
||||
|
||||
|
||||
def restrict_to_current_user(target: Path, run=subprocess.run) -> bool:
|
||||
"""Tira a herança e dá controle total só ao usuário atual. Falha vira aviso no log (não derruba o serviço)."""
|
||||
sid = current_user_sid()
|
||||
if not sid:
|
||||
return False
|
||||
try:
|
||||
result = run(icacls_args(target, sid, target.is_dir()), capture_output=True, text=True, timeout=30)
|
||||
except (OSError, subprocess.SubprocessError) as exc:
|
||||
log.warning("não consegui restringir as permissões de %s: %s", target, exc)
|
||||
return False
|
||||
if result.returncode != 0:
|
||||
log.warning("icacls falhou em %s: %s", target, (result.stdout or result.stderr).strip()[:200])
|
||||
return False
|
||||
return True
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Configuração do Publicador, lida de publisher/.env (e do ambiente, que tem prioridade)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass, replace
|
||||
from pathlib import Path
|
||||
|
||||
PUBLISHER_DIR = Path(__file__).resolve().parent.parent
|
||||
REPO_ROOT = PUBLISHER_DIR.parent
|
||||
PORT_RANGE = (4500, 4599)
|
||||
# Portas de depuração (CDP) dos navegadores do modo sessão: uma por janela aberta.
|
||||
BROWSER_PORT_RANGE = (4540, 4549)
|
||||
|
||||
|
||||
class ConfigError(RuntimeError):
|
||||
"""Configuração inválida: o serviço não sobe."""
|
||||
|
||||
|
||||
def read_env_file(path: Path) -> dict[str, str]:
|
||||
if not path.is_file():
|
||||
return {}
|
||||
values: dict[str, str] = {}
|
||||
for line in path.read_text(encoding="utf-8").splitlines():
|
||||
if "=" not in line or line.lstrip().startswith("#"):
|
||||
continue
|
||||
name, value = line.split("=", 1)
|
||||
values[name.strip()] = value.strip()
|
||||
return values
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
service_key: str
|
||||
port: int
|
||||
data_dir: Path
|
||||
# Raiz do projeto: `file`/`cover` dos jobs precisam estar dentro dela.
|
||||
repo_root: Path
|
||||
browser_path: str | None
|
||||
ig_api_version: str
|
||||
|
||||
@property
|
||||
def base_url(self) -> str:
|
||||
return f"http://127.0.0.1:{self.port}"
|
||||
|
||||
def redirect_uri(self, platform: str) -> str:
|
||||
return f"{self.base_url}/oauth/callback/{platform}"
|
||||
|
||||
@property
|
||||
def db_path(self) -> Path:
|
||||
return self.data_dir / "publisher.db"
|
||||
|
||||
@property
|
||||
def vault_path(self) -> Path:
|
||||
return self.data_dir / "vault.bin"
|
||||
|
||||
@property
|
||||
def browser_dir(self) -> Path:
|
||||
return self.data_dir / "browser"
|
||||
|
||||
@property
|
||||
def logs_dir(self) -> Path:
|
||||
return self.data_dir / "logs"
|
||||
|
||||
@staticmethod
|
||||
def load(env_file: Path | None = None, **overrides: object) -> "Settings":
|
||||
env = {**read_env_file(env_file or PUBLISHER_DIR / ".env"), **os.environ}
|
||||
raw_port = env.get("PUBLISHER_PORT", "") or "4530"
|
||||
try:
|
||||
port = int(raw_port)
|
||||
except ValueError as exc:
|
||||
raise ConfigError("PUBLISHER_PORT precisa ser número") from exc
|
||||
if not PORT_RANGE[0] <= port <= PORT_RANGE[1]:
|
||||
raise ConfigError(f"PUBLISHER_PORT={port} fora da faixa {PORT_RANGE[0]}–{PORT_RANGE[1]} do CenaForge")
|
||||
|
||||
data_dir = REPO_ROOT / "data" / "publisher"
|
||||
raw_data = env.get("PUBLISHER_DATA_DIR", "").strip()
|
||||
if raw_data:
|
||||
path = Path(raw_data)
|
||||
path = (path if path.is_absolute() else REPO_ROOT / path).resolve()
|
||||
if not path.is_relative_to(REPO_ROOT.resolve()):
|
||||
raise ConfigError(f"PUBLISHER_DATA_DIR precisa ficar dentro do repositório ({REPO_ROOT})")
|
||||
data_dir = path
|
||||
|
||||
settings = Settings(
|
||||
service_key=env.get("PUBLISHER_SERVICE_KEY", ""),
|
||||
port=port,
|
||||
data_dir=data_dir,
|
||||
repo_root=REPO_ROOT,
|
||||
browser_path=env.get("PUBLISHER_BROWSER_PATH", "").strip() or None,
|
||||
ig_api_version=env.get("PUBLISHER_IG_API_VERSION", "").strip() or "v24.0",
|
||||
)
|
||||
if overrides:
|
||||
settings = replace(settings, **overrides) # type: ignore[arg-type]
|
||||
return settings
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Estado do Publicador em data/publisher/publisher.db (SQLite): perfis conectados, jobs de envio e os `state`
|
||||
pendentes do OAuth. Segredos (tokens, client secret) NÃO ficam aqui: vão para o cofre (vault.py)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sqlite3
|
||||
import threading
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
# Cada item é uma migração; `PRAGMA user_version` guarda quantas já rodaram.
|
||||
SCHEMA = [
|
||||
"""
|
||||
CREATE TABLE profiles (
|
||||
profile_id TEXT PRIMARY KEY,
|
||||
platform TEXT NOT NULL CHECK (platform IN ('youtube', 'tiktok', 'instagram')),
|
||||
mode TEXT CHECK (mode IN ('official', 'session')),
|
||||
status TEXT NOT NULL DEFAULT 'disconnected'
|
||||
CHECK (status IN ('disconnected', 'connecting', 'connected', 'needs_login', 'expired', 'error')),
|
||||
display_name TEXT,
|
||||
handle TEXT,
|
||||
connected_at TEXT,
|
||||
expires_at TEXT,
|
||||
last_check_at TEXT,
|
||||
last_error TEXT,
|
||||
meta_json TEXT NOT NULL DEFAULT '{}',
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE jobs (
|
||||
job_id TEXT PRIMARY KEY,
|
||||
profile_id TEXT NOT NULL,
|
||||
platform TEXT NOT NULL,
|
||||
input_json TEXT NOT NULL,
|
||||
status TEXT NOT NULL CHECK (status IN ('queued', 'running', 'done', 'failed', 'needs_login', 'canceled')),
|
||||
step TEXT NOT NULL DEFAULT '',
|
||||
progress REAL NOT NULL DEFAULT 0,
|
||||
remote_id TEXT,
|
||||
url TEXT,
|
||||
draft INTEGER NOT NULL DEFAULT 0,
|
||||
error TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX jobs_status_created ON jobs (status, created_at);
|
||||
CREATE TABLE oauth_states (
|
||||
state TEXT PRIMARY KEY,
|
||||
platform TEXT NOT NULL,
|
||||
profile_id TEXT NOT NULL,
|
||||
verifier TEXT NOT NULL,
|
||||
created_at REAL NOT NULL,
|
||||
expires_at REAL NOT NULL,
|
||||
used INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
""",
|
||||
# v2: idempotência do POST /v1/jobs (clientRef do painel) e o code_verifier do PKCE sai do disco (fica só em
|
||||
# memória; o state vale 10 min).
|
||||
"""
|
||||
ALTER TABLE jobs ADD COLUMN client_ref TEXT;
|
||||
CREATE UNIQUE INDEX jobs_client_ref ON jobs (client_ref);
|
||||
UPDATE oauth_states SET verifier = '';
|
||||
""",
|
||||
]
|
||||
|
||||
INTERRUPTED = "Envio interrompido (o Publicador foi fechado no meio) — tente de novo."
|
||||
|
||||
|
||||
def now() -> str:
|
||||
return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
|
||||
|
||||
|
||||
class Database:
|
||||
def __init__(self, path: Path):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self.lock = threading.RLock()
|
||||
self.conn = sqlite3.connect(path, check_same_thread=False, isolation_level=None)
|
||||
self.conn.row_factory = sqlite3.Row
|
||||
self.conn.executescript("PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 3000;")
|
||||
self._migrate()
|
||||
# Job que estava rodando quando o serviço caiu: o envio morreu junto. Não dá para saber se chegou à rede,
|
||||
# então vira 'failed' e o usuário decide se tenta de novo (o painel mostra o botão).
|
||||
self.interrupted_on_start = [r["job_id"] for r in self.all("SELECT job_id FROM jobs WHERE status = 'running'")]
|
||||
self.run("UPDATE jobs SET status = 'failed', error = ?, step = 'Interrompido', updated_at = ? WHERE status = 'running'",
|
||||
INTERRUPTED, now())
|
||||
|
||||
def _migrate(self) -> None:
|
||||
version = self.conn.execute("PRAGMA user_version").fetchone()[0]
|
||||
for v in range(version, len(SCHEMA)):
|
||||
with self.lock:
|
||||
self.conn.execute("BEGIN")
|
||||
try:
|
||||
for statement in _split(SCHEMA[v]):
|
||||
self.conn.execute(statement)
|
||||
self.conn.execute(f"PRAGMA user_version = {v + 1}")
|
||||
self.conn.execute("COMMIT")
|
||||
except Exception:
|
||||
self.conn.execute("ROLLBACK")
|
||||
raise
|
||||
|
||||
def run(self, sql: str, *params: Any) -> sqlite3.Cursor:
|
||||
with self.lock:
|
||||
return self.conn.execute(sql, params)
|
||||
|
||||
def all(self, sql: str, *params: Any) -> list[dict]:
|
||||
with self.lock:
|
||||
return [dict(r) for r in self.conn.execute(sql, params).fetchall()]
|
||||
|
||||
def get(self, sql: str, *params: Any) -> dict | None:
|
||||
with self.lock:
|
||||
row = self.conn.execute(sql, params).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
def close(self) -> None:
|
||||
with self.lock:
|
||||
self.conn.close()
|
||||
|
||||
|
||||
def _split(script: str) -> list[str]:
|
||||
# executescript faria COMMIT implícito no meio da transação; executamos comando por comando.
|
||||
return [s.strip() for s in script.split(";") if s.strip()]
|
||||
|
||||
|
||||
def loads(raw: str | None, default: Any) -> Any:
|
||||
try:
|
||||
return json.loads(raw) if raw else default
|
||||
except json.JSONDecodeError:
|
||||
return default
|
||||
@@ -0,0 +1,249 @@
|
||||
"""API do Publicador (127.0.0.1:4530, faixa 4500–4599 do CenaForge). Contrato: doc/publicacao/PLANO.md §3.
|
||||
|
||||
Toda rota exige `X-Service-Key` = PUBLISHER_SERVICE_KEY (publisher/.env), exceto `GET /health` e
|
||||
`GET /oauth/callback/{platform}` (essa é aberta pelo navegador do usuário e é validada pelo `state`).
|
||||
Erros: `{"detail": "<mensagem em pt-BR>"}`. Campos JSON em camelCase. Quem chama é o painel.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hmac
|
||||
import html
|
||||
import logging
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import FastAPI, Request, Response
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import HTMLResponse, JSONResponse
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from .acl import restrict_to_current_user
|
||||
from .config import ConfigError, Settings
|
||||
from .db import Database
|
||||
from .service import Publisher, UserError
|
||||
from .vault import Vault, VaultError
|
||||
from .worker import Worker
|
||||
|
||||
VERSION = "1.0.0"
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
|
||||
# httpx/httpcore logam a URL inteira em INFO — e a Graph API do Instagram leva o token na query. Silenciar.
|
||||
for _noisy in ("httpx", "httpcore"):
|
||||
logging.getLogger(_noisy).setLevel(logging.WARNING)
|
||||
|
||||
Platform = Literal["youtube", "tiktok", "instagram"]
|
||||
OPEN_PATHS = ("/health", "/oauth/callback/")
|
||||
|
||||
|
||||
class AppIn(BaseModel):
|
||||
clientId: str = Field(min_length=1, max_length=300)
|
||||
clientSecret: str = Field(default="", max_length=500)
|
||||
|
||||
|
||||
class ConnectIn(BaseModel):
|
||||
platform: Platform
|
||||
mode: Literal["official", "session"]
|
||||
|
||||
|
||||
class TokenIn(BaseModel):
|
||||
accessToken: str = Field(min_length=20, max_length=4000)
|
||||
|
||||
|
||||
class StatsIn(BaseModel):
|
||||
ids: list[str] = Field(min_length=1, max_length=200)
|
||||
|
||||
|
||||
class JobIn(BaseModel):
|
||||
profileId: str = Field(min_length=3, max_length=100)
|
||||
platform: Platform
|
||||
file: str = Field(min_length=3, max_length=1000)
|
||||
cover: str | None = Field(default=None, max_length=1000)
|
||||
title: str = Field(default="", max_length=500)
|
||||
caption: str = Field(default="", max_length=2200)
|
||||
tags: list[str] = Field(default_factory=list, max_length=60)
|
||||
privacy: Literal["public", "unlisted", "private"] = "public"
|
||||
publishAt: str | None = Field(default=None, max_length=40)
|
||||
aiGenerated: bool = False
|
||||
madeForKids: bool = False
|
||||
tiktokMode: Literal["direct", "draft"] = "direct"
|
||||
# Idempotência: o mesmo clientRef devolve o job já criado (200) em vez de criar outro.
|
||||
clientRef: str | None = Field(default=None, min_length=1, max_length=80)
|
||||
|
||||
|
||||
FIELD_NAMES = {"clientId": "Client ID", "clientSecret": "Client Secret", "accessToken": "token", "file": "arquivo",
|
||||
"cover": "capa", "title": "título", "caption": "legenda", "tags": "tags", "privacy": "privacidade",
|
||||
"platform": "rede", "mode": "modo", "profileId": "perfil", "tiktokMode": "modo do TikTok"}
|
||||
|
||||
|
||||
def validation_message(exc: RequestValidationError) -> str:
|
||||
parts = []
|
||||
for error in exc.errors()[:3]:
|
||||
loc = [str(p) for p in error.get("loc", []) if p not in ("body", "query", "path")]
|
||||
field = FIELD_NAMES.get(loc[0], loc[0]) if loc else "corpo"
|
||||
kind = error.get("type", "")
|
||||
if kind == "missing":
|
||||
parts.append(f"falta o campo {field}")
|
||||
elif kind in ("string_too_long", "too_long"):
|
||||
parts.append(f"{field} é longo demais (máx. {error.get('ctx', {}).get('max_length', '?')})")
|
||||
elif kind in ("string_too_short", "too_short"):
|
||||
parts.append(f"{field} é curto demais")
|
||||
elif kind in ("literal_error", "enum"):
|
||||
parts.append(f"{field} com valor inválido (aceitos: {error.get('ctx', {}).get('expected', '?')})")
|
||||
elif kind == "json_invalid":
|
||||
parts.append("o corpo não é um JSON válido")
|
||||
else:
|
||||
parts.append(f"{field} inválido")
|
||||
return "Pedido inválido: " + "; ".join(parts or ["formato inesperado"]) + "."
|
||||
|
||||
|
||||
def callback_page(title: str, message: str, ok: bool) -> str:
|
||||
# Página simples e acessível: lang pt-BR, contraste alto (texto #111 em #fff = 18:1), texto grande, sem script.
|
||||
color = "#0a6b2d" if ok else "#a4161a"
|
||||
return f"""<!doctype html>
|
||||
<html lang="pt-BR"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>{html.escape(title)} — CenaForge</title>
|
||||
<style>
|
||||
body{{margin:0;background:#fff;color:#111;font:18px/1.5 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}}
|
||||
main{{max-width:36rem;margin:12vh auto;padding:0 16px}}
|
||||
h1{{font-size:1.6rem;color:{color};margin:0 0 .5rem}}
|
||||
p{{margin:.5rem 0}}
|
||||
@media (prefers-color-scheme: dark){{body{{background:#111;color:#f2f2f2}}h1{{color:{'#6fdc8c' if ok else '#ff8a8a'}}}}}
|
||||
</style></head>
|
||||
<body><main role="main"><h1>{"✔" if ok else "✖"} {html.escape(title)}</h1>
|
||||
<p role="status">{html.escape(message)}</p></main></body></html>"""
|
||||
|
||||
|
||||
def create_app(settings: Settings | None = None, publisher: Publisher | None = None, start_worker: bool = True,
|
||||
worker: Worker | None = None) -> FastAPI:
|
||||
settings = settings or Settings.load()
|
||||
if not settings.service_key:
|
||||
raise ConfigError("PUBLISHER_SERVICE_KEY vazio: rode o setup.bat (ou preencha publisher/.env).")
|
||||
if publisher is None:
|
||||
if not settings.data_dir.exists():
|
||||
# Primeira subida: a pasta nasce acessível só ao usuário atual (cofre, banco, sessões, capturas).
|
||||
settings.data_dir.mkdir(parents=True)
|
||||
restrict_to_current_user(settings.data_dir)
|
||||
db = Database(settings.db_path)
|
||||
publisher = Publisher(settings, db, Vault(settings.vault_path))
|
||||
worker = worker or Worker(publisher.db, publisher.execute, publisher.maintenance)
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
if start_worker:
|
||||
worker.start()
|
||||
yield
|
||||
worker.stop()
|
||||
publisher.close()
|
||||
|
||||
app = FastAPI(title="CenaForge Publicador", version=VERSION, docs_url=None, redoc_url=None, openapi_url=None,
|
||||
lifespan=lifespan)
|
||||
app.state.publisher, app.state.worker = publisher, worker
|
||||
|
||||
@app.middleware("http")
|
||||
async def auth(request: Request, call_next):
|
||||
path = request.url.path
|
||||
if not (path == "/health" or (request.method == "GET" and path.startswith("/oauth/callback/"))):
|
||||
given = request.headers.get("X-Service-Key", "")
|
||||
if not hmac.compare_digest(given.encode(), settings.service_key.encode()):
|
||||
return JSONResponse({"detail": "Chave do serviço ausente ou inválida."}, status_code=401)
|
||||
return await call_next(request)
|
||||
|
||||
@app.exception_handler(UserError)
|
||||
async def user_error(_request: Request, exc: UserError):
|
||||
return JSONResponse({"detail": exc.message}, status_code=exc.status)
|
||||
|
||||
@app.exception_handler(VaultError)
|
||||
async def vault_error(_request: Request, exc: VaultError):
|
||||
return JSONResponse({"detail": str(exc)}, status_code=500)
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def invalid(_request: Request, exc: RequestValidationError):
|
||||
return JSONResponse({"detail": validation_message(exc)}, status_code=422)
|
||||
|
||||
@app.get("/health")
|
||||
async def health():
|
||||
return {"ok": True}
|
||||
|
||||
@app.get("/v1/status")
|
||||
def status():
|
||||
return {"browser": publisher.browser_status(), "worker": "busy" if worker.busy else "idle",
|
||||
"queue": publisher.queue_size()}
|
||||
|
||||
# ---------- apps das redes (Client ID/Secret; o segredo nunca volta)
|
||||
@app.get("/v1/apps")
|
||||
def apps():
|
||||
return {p: publisher.app_state(p) for p in ("youtube", "tiktok", "instagram")}
|
||||
|
||||
@app.put("/v1/apps/{platform}")
|
||||
def put_app(platform: str, body: AppIn):
|
||||
return publisher.set_app(platform, body.clientId, body.clientSecret)
|
||||
|
||||
@app.delete("/v1/apps/{platform}")
|
||||
def delete_app(platform: str):
|
||||
return publisher.delete_app(platform)
|
||||
|
||||
# ---------- perfis
|
||||
@app.get("/v1/profiles/{profile_id}")
|
||||
def get_profile(profile_id: str):
|
||||
return publisher.profile(profile_id)
|
||||
|
||||
@app.post("/v1/profiles/{profile_id}/connect")
|
||||
def connect(profile_id: str, body: ConnectIn):
|
||||
return publisher.connect(profile_id, body.platform, body.mode)
|
||||
|
||||
@app.post("/v1/profiles/{profile_id}/token")
|
||||
def token(profile_id: str, body: TokenIn):
|
||||
return publisher.paste_token(profile_id, body.accessToken)
|
||||
|
||||
@app.post("/v1/profiles/{profile_id}/session/check")
|
||||
def session_check(profile_id: str):
|
||||
return publisher.session_check(profile_id)
|
||||
|
||||
@app.post("/v1/profiles/{profile_id}/session/open")
|
||||
def session_open(profile_id: str):
|
||||
return publisher.session_open(profile_id)
|
||||
|
||||
@app.delete("/v1/profiles/{profile_id}")
|
||||
def disconnect(profile_id: str):
|
||||
return publisher.disconnect(profile_id)
|
||||
|
||||
@app.post("/v1/profiles/{profile_id}/stats")
|
||||
def post_stats(profile_id: str, body: StatsIn):
|
||||
return publisher.post_stats(profile_id, body.ids)
|
||||
|
||||
@app.get("/v1/profiles/{profile_id}/tiktok/creator-info")
|
||||
def creator_info(profile_id: str):
|
||||
return publisher.tiktok_creator_info(profile_id)
|
||||
|
||||
# ---------- jobs
|
||||
@app.post("/v1/jobs", status_code=201)
|
||||
def create_job(body: JobIn, response: Response):
|
||||
job, created = publisher.create_job(body.model_dump())
|
||||
if created:
|
||||
worker.wake()
|
||||
else:
|
||||
response.status_code = 200 # já existia com este clientRef: nada novo foi criado
|
||||
return job
|
||||
|
||||
@app.get("/v1/jobs/{job_id}")
|
||||
def get_job(job_id: str):
|
||||
return publisher.job(job_id)
|
||||
|
||||
@app.post("/v1/jobs/{job_id}/cancel")
|
||||
def cancel_job(job_id: str):
|
||||
return publisher.cancel_job(job_id)
|
||||
|
||||
# ---------- OAuth (aberta: validada pelo state de uso único)
|
||||
@app.get("/oauth/callback/{platform}", response_class=HTMLResponse)
|
||||
def oauth_callback(platform: str, request: Request):
|
||||
try:
|
||||
message = publisher.oauth_callback(platform, dict(request.query_params))
|
||||
except UserError as exc:
|
||||
return HTMLResponse(callback_page("Não deu para conectar", exc.message, False), status_code=exc.status)
|
||||
return HTMLResponse(callback_page("Conta conectada", message, True))
|
||||
|
||||
return app
|
||||
|
||||
|
||||
def build() -> FastAPI: # pragma: no cover - ponto de entrada do uvicorn (--factory)
|
||||
return create_app()
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Conferência dos caminhos `file`/`cover` dos jobs: só arquivos das pastas de SAÍDA do projeto.
|
||||
|
||||
Aceitas: `output/` (renders, Clipador, documentário), `stories/` e `assets/`. Todo o resto é recusado — em especial
|
||||
`data/` (bancos, cofre de tokens, perfis de navegador do Publicador): nunca enviar isso para uma rede.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class PathRefused(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
VIDEO_EXT = {".mp4", ".mov"}
|
||||
IMAGE_EXT = {".jpg", ".jpeg", ".png"}
|
||||
ALLOWED_DIRS = ("output", "stories", "assets")
|
||||
FORBIDDEN_DIRS = ("data",)
|
||||
|
||||
|
||||
def _under(real: str, base: str) -> bool:
|
||||
try:
|
||||
return os.path.commonpath([real, base]) == base
|
||||
except ValueError: # outro disco no Windows
|
||||
return False
|
||||
|
||||
|
||||
def inside_root(raw: str, root: Path, allowed_ext: set[str], what: str) -> Path:
|
||||
"""Caminho real (symlinks e `..` resolvidos com os.path.realpath) se estiver numa pasta de saída do projeto;
|
||||
senão PathRefused."""
|
||||
if not raw or not os.path.isabs(raw):
|
||||
raise PathRefused(f"O caminho do {what} precisa ser absoluto (recebi \"{raw}\").")
|
||||
real = os.path.normcase(os.path.realpath(raw))
|
||||
base = os.path.normcase(os.path.realpath(root))
|
||||
for name in FORBIDDEN_DIRS:
|
||||
if _under(real, os.path.join(base, name)):
|
||||
raise PathRefused(f"O {what} não pode vir da pasta {name}/ do CenaForge (dados internos). Caminho recusado: {raw}")
|
||||
if not any(_under(real, os.path.join(base, name)) for name in ALLOWED_DIRS):
|
||||
raise PathRefused(f"O {what} precisa estar numa pasta de saída do CenaForge ({', '.join(d + '/' for d in ALLOWED_DIRS)} "
|
||||
f"em {root}). Caminho recusado: {raw}")
|
||||
path = Path(os.path.realpath(raw))
|
||||
if path.suffix.lower() not in allowed_ext:
|
||||
raise PathRefused(f"O {what} precisa ser {', '.join(sorted(allowed_ext))} (recebi \"{path.suffix or 'sem extensão'}\").")
|
||||
if not path.is_file():
|
||||
raise PathRefused(f"O {what} não existe mais: {raw}")
|
||||
return path
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Tipos comuns aos envios (API oficial e sessão logada)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import os
|
||||
import secrets
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Callable, Literal
|
||||
|
||||
import httpx
|
||||
|
||||
# Callback de progresso: (texto curto em pt-BR para a UI, fração 0..1).
|
||||
Progress = Callable[[str, float], None]
|
||||
Sleep = Callable[[float], None]
|
||||
|
||||
PLATFORMS = ("youtube", "tiktok", "instagram")
|
||||
|
||||
|
||||
class PublishError(Exception):
|
||||
"""Falha que o usuário precisa ler. `kind`: 'failed' (erro comum), 'needs_login' (entrar de novo) ou
|
||||
'expired' (a autorização da API venceu: conectar de novo). A mensagem já sai em pt-BR, sem jargão."""
|
||||
|
||||
def __init__(self, message: str, kind: Literal["failed", "needs_login", "expired"] = "failed"):
|
||||
super().__init__(message)
|
||||
self.message = message
|
||||
self.kind = kind
|
||||
|
||||
|
||||
@dataclass
|
||||
class JobSpec:
|
||||
"""O que o worker entrega ao uploader (vem do JobInput do contrato)."""
|
||||
job_id: str
|
||||
profile_id: str
|
||||
platform: str
|
||||
file: Path
|
||||
cover: Path | None
|
||||
title: str
|
||||
caption: str
|
||||
tags: list[str] = field(default_factory=list)
|
||||
privacy: str = "public"
|
||||
publish_at: str | None = None
|
||||
ai_generated: bool = False
|
||||
made_for_kids: bool = False
|
||||
tiktok_mode: str = "direct"
|
||||
|
||||
|
||||
@dataclass
|
||||
class PublishResult:
|
||||
remote_id: str | None
|
||||
url: str | None
|
||||
draft: bool = False
|
||||
# Texto final para a UI ("Publicado", "Enviado para a caixa de entrada do TikTok"…).
|
||||
step: str = "Publicado"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Tokens:
|
||||
access_token: str
|
||||
access_expires_at: float | None # epoch (s)
|
||||
refresh_token: str | None = None
|
||||
refresh_expires_at: float | None = None # epoch (s); None = sem prazo conhecido
|
||||
extra: dict = field(default_factory=dict)
|
||||
|
||||
def to_vault(self) -> dict:
|
||||
return {"accessToken": self.access_token, "accessExpiresAt": self.access_expires_at,
|
||||
"refreshToken": self.refresh_token, "refreshExpiresAt": self.refresh_expires_at, **self.extra}
|
||||
|
||||
|
||||
# ---------- PKCE (RFC 7636)
|
||||
|
||||
def make_verifier() -> str:
|
||||
# 64 caracteres do alfabeto "unreserved" (A-Z a-z 0-9 - _): dentro dos 43–128 exigidos.
|
||||
return secrets.token_urlsafe(48)[:64]
|
||||
|
||||
|
||||
def challenge_s256_base64url(verifier: str) -> str:
|
||||
"""Desafio padrão do RFC (Google): base64url sem `=` do SHA-256."""
|
||||
digest = hashlib.sha256(verifier.encode("ascii")).digest()
|
||||
return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
|
||||
|
||||
|
||||
def challenge_s256_hex(verifier: str) -> str:
|
||||
"""Desafio do TikTok (Login Kit desktop): o SHA-256 em HEXADECIMAL, não base64url. Diferente do RFC de propósito
|
||||
— é assim que a documentação do TikTok pede, e o desafio em base64url é recusado."""
|
||||
return hashlib.sha256(verifier.encode("ascii")).hexdigest()
|
||||
|
||||
|
||||
# ---------- utilidades
|
||||
|
||||
def iter_chunks(path: Path, sizes: list[int]):
|
||||
"""Lê o arquivo em blocos de tamanhos dados (o último pode ser maior)."""
|
||||
with path.open("rb") as handle:
|
||||
offset = 0
|
||||
for size in sizes:
|
||||
data = handle.read(size)
|
||||
yield offset, data
|
||||
offset += len(data)
|
||||
|
||||
|
||||
def file_size(path: Path) -> int:
|
||||
return os.path.getsize(path)
|
||||
|
||||
|
||||
def expires_in(seconds: object) -> float | None:
|
||||
try:
|
||||
return time.time() + float(seconds) # type: ignore[arg-type]
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def response_json(response: httpx.Response) -> dict:
|
||||
try:
|
||||
data = response.json()
|
||||
except ValueError:
|
||||
return {}
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def network_error(name: str, exc: Exception) -> PublishError:
|
||||
return PublishError(f"Não consegui falar com o {name} (internet caiu ou o site está fora do ar). "
|
||||
f"Tente de novo daqui a pouco. Detalhe: {type(exc).__name__}")
|
||||
@@ -0,0 +1,189 @@
|
||||
"""Instagram (Reels) pela API oficial — "Instagram API with Instagram Login" (graph.instagram.com).
|
||||
|
||||
Conexão por TOKEN COLADO: a Meta não aceita redirect para localhost, então o usuário gera o token no painel de
|
||||
desenvolvedor do app e cola no CenaForge. Token longo vale 60 dias e é renovado com `refresh_access_token` quando
|
||||
faltam menos de 10 dias (precisa ter mais de 24 h de vida).
|
||||
|
||||
Envio: container `media_type=REELS` + `upload_type=resumable` → upload do arquivo LOCAL pelo `rupload` → consulta
|
||||
`status_code` até FINISHED → `media_publish`. A documentação descreve o rupload só para "Facebook Login for
|
||||
Business"; relatos mostram funcionando com graph.instagram.com. Se a Meta recusar, o erro diz isso com clareza.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Iterator
|
||||
|
||||
import httpx
|
||||
|
||||
from .base import (JobSpec, Progress, PublishError, PublishResult, Sleep, Tokens, expires_in, file_size,
|
||||
network_error, response_json)
|
||||
|
||||
GRAPH = "https://graph.instagram.com"
|
||||
RUPLOAD = "https://rupload.facebook.com/ig-api-upload"
|
||||
LONG_TOKEN_S = 60 * 24 * 3600
|
||||
REFRESH_BEFORE_S = 10 * 24 * 3600 # renovar quando faltar menos de 10 dias
|
||||
MIN_AGE_TO_REFRESH_S = 24 * 3600
|
||||
|
||||
NEEDS_FB_LOGIN = ("O Instagram recusou o envio do arquivo direto do computador por este tipo de conexão. "
|
||||
"Para publicar pela API será preciso o \"Facebook Login for Business\" (conta ligada a uma Página do "
|
||||
"Facebook) — ou use o modo Sessão logada.")
|
||||
|
||||
|
||||
def explain(response: httpx.Response, context: str = "") -> PublishError:
|
||||
error = response_json(response).get("error") or {}
|
||||
code = error.get("code") if isinstance(error, dict) else None
|
||||
message = str(error.get("message") or "") if isinstance(error, dict) else str(error)
|
||||
user_msg = str(error.get("error_user_msg") or "") if isinstance(error, dict) else ""
|
||||
if code == 190 or response.status_code == 401:
|
||||
return PublishError("O token do Instagram venceu ou foi revogado. Gere um token novo no painel da Meta e cole "
|
||||
"em Canais de publicação.", "expired")
|
||||
if code in (4, 17, 32, 613) or "limit" in message.lower():
|
||||
return PublishError("O Instagram pediu para esperar (limite de publicações ou de chamadas atingido). "
|
||||
"Tente de novo mais tarde.")
|
||||
if code == 10 or code == 200:
|
||||
return PublishError("Falta permissão no token do Instagram. Gere o token marcando instagram_business_basic e "
|
||||
"instagram_business_content_publish, e confira se a conta é Profissional.", "expired")
|
||||
if context == "container" and ("upload_type" in message or "resumable" in message.lower()):
|
||||
return PublishError(NEEDS_FB_LOGIN)
|
||||
detail = user_msg or message or f"código {response.status_code}"
|
||||
return PublishError(f"O Instagram recusou{(' ' + context) if context else ''}: {detail}")
|
||||
|
||||
|
||||
class InstagramApi:
|
||||
poll_s = 20.0
|
||||
poll_max = 30 # ~10 min
|
||||
read_block = 4 * 1024 * 1024
|
||||
|
||||
def __init__(self, client: httpx.Client, version: str = "v24.0", sleep: Sleep = time.sleep):
|
||||
self.client, self.version, self.sleep = client, version, sleep
|
||||
|
||||
def _url(self, path: str) -> str:
|
||||
return f"{GRAPH}/{self.version}/{path.lstrip('/')}"
|
||||
|
||||
def _get(self, path: str, token: str, **params) -> dict:
|
||||
try:
|
||||
response = self.client.get(self._url(path), params={**params, "access_token": token})
|
||||
except httpx.HTTPError as exc:
|
||||
raise network_error("Instagram", exc) from exc
|
||||
if response.status_code >= 400:
|
||||
raise explain(response)
|
||||
return response_json(response)
|
||||
|
||||
# ---------- token colado
|
||||
def me(self, token: str) -> dict:
|
||||
"""{igUserId, username, name, accountType} da conta dona do token."""
|
||||
data = self._get("me", token, fields="user_id,username,name,account_type")
|
||||
user_id = data.get("user_id") or data.get("id")
|
||||
if not user_id:
|
||||
raise PublishError("O token colado não parece ser do Instagram (não consegui ler a conta). Gere o token em "
|
||||
"\"Instagram API with Instagram Login\" no painel da Meta.")
|
||||
account_type = str(data.get("account_type") or "")
|
||||
if account_type and account_type.upper() not in ("BUSINESS", "MEDIA_CREATOR", "CREATOR"):
|
||||
raise PublishError("Esta conta do Instagram é pessoal. Para publicar pela API ela precisa ser Profissional "
|
||||
"(Criador de conteúdo ou Empresa) — dá para mudar nas configurações do app do Instagram.")
|
||||
return {"igUserId": str(user_id), "username": data.get("username"), "name": data.get("name"),
|
||||
"accountType": account_type or None}
|
||||
|
||||
def pasted_tokens(self, token: str, info: dict) -> Tokens:
|
||||
# Não dá para saber a validade exata de um token colado; o token longo da Meta vale 60 dias.
|
||||
return Tokens(token, time.time() + LONG_TOKEN_S, None, None,
|
||||
{"igUserId": info["igUserId"], "obtainedAt": time.time()})
|
||||
|
||||
def refresh(self, token: str) -> Tokens:
|
||||
try:
|
||||
response = self.client.get(f"{GRAPH}/refresh_access_token",
|
||||
params={"grant_type": "ig_refresh_token", "access_token": token})
|
||||
except httpx.HTTPError as exc:
|
||||
raise network_error("Instagram", exc) from exc
|
||||
if response.status_code >= 400:
|
||||
raise explain(response, "ao renovar o token")
|
||||
body = response_json(response)
|
||||
return Tokens(body["access_token"], expires_in(body.get("expires_in")) or time.time() + LONG_TOKEN_S, None, None,
|
||||
{"obtainedAt": time.time()})
|
||||
|
||||
@staticmethod
|
||||
def needs_refresh(secret: dict, now: float | None = None) -> bool:
|
||||
now = now or time.time()
|
||||
expires = secret.get("accessExpiresAt") or 0
|
||||
obtained = secret.get("obtainedAt") or 0
|
||||
return expires - now < REFRESH_BEFORE_S and now - obtained > MIN_AGE_TO_REFRESH_S
|
||||
|
||||
# ---------- envio
|
||||
def upload(self, spec: JobSpec, token: str, ig_user_id: str, progress: Progress) -> PublishResult:
|
||||
total = file_size(spec.file)
|
||||
progress("Criando o Reel no Instagram…", 0.03)
|
||||
form = {"media_type": "REELS", "upload_type": "resumable", "caption": spec.caption[:2200],
|
||||
"share_to_feed": "true", "access_token": token}
|
||||
if spec.ai_generated:
|
||||
form["is_ai_generated"] = "true"
|
||||
try:
|
||||
response = self.client.post(self._url(f"{ig_user_id}/media"), data=form)
|
||||
except httpx.HTTPError as exc:
|
||||
raise network_error("Instagram", exc) from exc
|
||||
if response.status_code >= 400:
|
||||
raise explain(response, "container")
|
||||
body = response_json(response)
|
||||
container = body.get("id")
|
||||
if not container:
|
||||
raise PublishError("O Instagram não devolveu o ID do Reel em preparo. Tente de novo.")
|
||||
upload_uri = body.get("uri") or f"{RUPLOAD}/{self.version}/{container}"
|
||||
|
||||
sent = [0]
|
||||
|
||||
def stream() -> Iterator[bytes]:
|
||||
with spec.file.open("rb") as handle:
|
||||
while block := handle.read(self.read_block):
|
||||
sent[0] += len(block)
|
||||
progress(f"Enviando vídeo… {int(sent[0] * 100 / total)}%", 0.05 + 0.75 * sent[0] / total)
|
||||
yield block
|
||||
|
||||
try:
|
||||
response = self.client.post(upload_uri, content=stream(), headers={
|
||||
"Authorization": f"OAuth {token}", "offset": "0", "file_size": str(total),
|
||||
"Content-Length": str(total), "Content-Type": "application/octet-stream"})
|
||||
except httpx.HTTPError as exc:
|
||||
raise network_error("Instagram", exc) from exc
|
||||
if response.status_code >= 400:
|
||||
if response.status_code in (400, 403, 404):
|
||||
error = explain(response)
|
||||
if error.kind == "failed":
|
||||
raise PublishError(NEEDS_FB_LOGIN + f" (Detalhe: {error.message})")
|
||||
raise error
|
||||
raise explain(response, "o arquivo")
|
||||
|
||||
progress("Aguardando o Instagram processar…", 0.82)
|
||||
for _ in range(self.poll_max):
|
||||
data = self._get(container, token, fields="status_code,status")
|
||||
status = data.get("status_code")
|
||||
if status == "FINISHED":
|
||||
break
|
||||
if status in ("ERROR", "EXPIRED"):
|
||||
raise PublishError(f"O Instagram não conseguiu processar o vídeo ({data.get('status') or status}). "
|
||||
"Confira o formato: MP4 H.264, 3 s a 15 min, até 300 MB, 9:16.")
|
||||
self.sleep(self.poll_s)
|
||||
else:
|
||||
raise PublishError("O Instagram demorou demais para processar o vídeo. Tente de novo mais tarde.")
|
||||
|
||||
progress("Publicando o Reel…", 0.95)
|
||||
try:
|
||||
response = self.client.post(self._url(f"{ig_user_id}/media_publish"),
|
||||
data={"creation_id": container, "access_token": token})
|
||||
except httpx.HTTPError as exc:
|
||||
raise network_error("Instagram", exc) from exc
|
||||
if response.status_code >= 400:
|
||||
raise explain(response, "a publicação")
|
||||
media_id = response_json(response).get("id")
|
||||
if not media_id:
|
||||
raise PublishError("O Instagram não confirmou a publicação. Confira no app antes de tentar de novo.")
|
||||
url = None
|
||||
try:
|
||||
url = self._get(str(media_id), token, fields="permalink").get("permalink")
|
||||
except PublishError:
|
||||
pass
|
||||
step = "Publicado no Instagram"
|
||||
if spec.cover:
|
||||
step += " (a capa escolhida não vai pela API sem link público; o Instagram usou um quadro do vídeo)"
|
||||
if not url:
|
||||
step += "; link não encontrado"
|
||||
return PublishResult(str(media_id), url, False, step)
|
||||
@@ -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)
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Números dos posts publicados (visualizações, curtidas, comentários) para o dashboard do painel.
|
||||
|
||||
De onde vem cada rede (medido em 17/11/2026, conta real):
|
||||
- YouTube: página pública do vídeo (`watch?v=`), SEM navegador e em qualquer modo de conexão. `videoDetails.viewCount`
|
||||
e `likeCount` vêm exatos; comentários só arredondados ("5,2 mil").
|
||||
- TikTok: a página pública devolve só uma tela de verificação (1,4 KB) ⇒ precisa da janela logada: lista
|
||||
"Publicações" do TikTok Studio (session/stats.py).
|
||||
- Instagram: sem login a página do reel não traz número nenhum ⇒ janela logada: aba Reels do perfil
|
||||
(session/stats.py).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import asdict, dataclass
|
||||
|
||||
import httpx
|
||||
|
||||
# Navegador comum, sem identificar o usuário (só lê a página pública do vídeo).
|
||||
PUBLIC_HEADERS = {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
|
||||
"Chrome/131.0.0.0 Safari/537.36",
|
||||
"Accept-Language": "pt-BR,pt;q=0.9",
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class PostStats:
|
||||
remote_id: str
|
||||
views: int | None
|
||||
likes: int | None = None
|
||||
comments: int | None = None
|
||||
shares: int | None = None
|
||||
saves: int | None = None
|
||||
|
||||
def view(self) -> dict:
|
||||
data = asdict(self)
|
||||
return {"remoteId": data.pop("remote_id"), **data}
|
||||
|
||||
|
||||
_COUNT = re.compile(r"^([\d.,]+)\s*(mil|mi|bi|k|m|b)?\.?$", re.I)
|
||||
_MULTIPLIER = {"mil": 1_000, "k": 1_000, "mi": 1_000_000, "m": 1_000_000, "bi": 1_000_000_000, "b": 1_000_000_000}
|
||||
|
||||
|
||||
def parse_count(text: object) -> int | None:
|
||||
"""Número como a rede mostra: '1.499' / '1,499' → 1499; '1,2 mil' / '1.2K' → 1200; '3,4 mi' / '3.4M' → 3400000.
|
||||
Texto que não é número → None."""
|
||||
raw = str(text or "").replace("\xa0", " ").replace(" ", " ").strip()
|
||||
match = _COUNT.match(raw)
|
||||
if not match:
|
||||
return None
|
||||
digits, suffix = match.group(1), (match.group(2) or "").lower()
|
||||
if not any(ch.isdigit() for ch in digits):
|
||||
return None
|
||||
if suffix:
|
||||
value = float(digits.replace(".", "").replace(",", ".") if digits.count(",") == 1 and "." not in digits
|
||||
else digits.replace(",", ""))
|
||||
return round(value * _MULTIPLIER[suffix])
|
||||
return int(digits.replace(".", "").replace(",", ""))
|
||||
|
||||
|
||||
_YT_VIEWS = re.compile(r'"viewCount":"(\d+)"')
|
||||
_YT_LIKES = re.compile(r'"likeCount":"?(\d+)')
|
||||
_YT_COMMENTS = re.compile(r'"contextualInfo":\{"runs":\[\{"text":"([^"]+)"')
|
||||
|
||||
|
||||
def youtube_from_html(video_id: str, html: str) -> PostStats | None:
|
||||
views = _YT_VIEWS.search(html)
|
||||
if not views: # vídeo privado, removido ou página de consentimento
|
||||
return None
|
||||
likes = _YT_LIKES.search(html)
|
||||
comments = _YT_COMMENTS.search(html)
|
||||
return PostStats(video_id, int(views.group(1)), int(likes.group(1)) if likes else None,
|
||||
parse_count(comments.group(1)) if comments else None)
|
||||
|
||||
|
||||
def youtube_public(http: httpx.Client, video_id: str) -> PostStats | None:
|
||||
response = http.get(f"https://www.youtube.com/watch?v={video_id}", headers=PUBLIC_HEADERS,
|
||||
cookies={"SOCS": "CAI"}, follow_redirects=True, timeout=20)
|
||||
if response.status_code != 200:
|
||||
return None
|
||||
return youtube_from_html(video_id, response.text)
|
||||
@@ -0,0 +1,237 @@
|
||||
"""TikTok pela API oficial (Login Kit desktop + Content Posting API).
|
||||
|
||||
OAuth: PKCE S256 com o desafio em HEXADECIMAL (particularidade do TikTok), redirect
|
||||
http://127.0.0.1:4530/oauth/callback/tiktok. Access token vale 2 h; o refresh token vale 180 dias e é ROTATIVO:
|
||||
toda renovação devolve um novo e o antigo morre — por isso o serviço grava o novo sempre (ver service.py).
|
||||
|
||||
Envio por FILE_UPLOAD (PULL_FROM_URL exige domínio verificado). Dois modos:
|
||||
- `direct`: Direct Post (`video.publish`) — antes consulta `creator_info`. Sem auditoria do app só sai SELF_ONLY.
|
||||
- `draft`: vai para a caixa de entrada do app do TikTok (`video.upload`); o usuário termina de publicar no celular.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Callable
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import httpx
|
||||
|
||||
from .base import (JobSpec, Progress, PublishError, PublishResult, Sleep, Tokens, challenge_s256_hex, expires_in,
|
||||
file_size, network_error, response_json)
|
||||
|
||||
AUTH_URL = "https://www.tiktok.com/v2/auth/authorize/"
|
||||
API = "https://open.tiktokapis.com"
|
||||
TOKEN_URL = f"{API}/v2/oauth/token/"
|
||||
SCOPES = "user.info.basic,video.upload,video.publish"
|
||||
|
||||
MB = 1024 * 1024
|
||||
PRIVACY = {"public": "PUBLIC_TO_EVERYONE", "private": "SELF_ONLY",
|
||||
# "Não listado" não existe no TikTok: o mais próximo sem expor o vídeo é "Somente eu".
|
||||
"unlisted": "SELF_ONLY"}
|
||||
|
||||
UNAUDITED = ("O TikTok só permite publicar como privado (Somente eu) até o app ser auditado. "
|
||||
"Use o modo Rascunho ou a Sessão logada.")
|
||||
|
||||
TokenProvider = Callable[[bool], str]
|
||||
|
||||
|
||||
def chunk_plan(size: int, single_max: int = 64 * MB, chunk: int = 32 * MB) -> tuple[int, int]:
|
||||
"""(chunk_size, total_chunk_count) pelas regras do TikTok: até 64 MB vai inteiro; acima, blocos de 5–64 MB em
|
||||
que o último absorve o resto (pode passar do tamanho do bloco, até 128 MB)."""
|
||||
if size <= single_max:
|
||||
return size, 1
|
||||
return chunk, max(1, size // chunk)
|
||||
|
||||
|
||||
def explain(code: str, message: str = "") -> PublishError:
|
||||
if code == "unaudited_client_can_only_post_to_private_accounts":
|
||||
return PublishError(UNAUDITED + " (A conta do TikTok também precisa estar como privada.)")
|
||||
if code == "privacy_level_option_mismatch":
|
||||
return PublishError("A privacidade escolhida não está disponível para esta conta do TikTok. "
|
||||
"Escolha outra no canal de publicação.")
|
||||
if code in ("spam_risk_too_many_posts", "spam_risk_too_many_pending_share", "spam_risk_user_banned_from_posting"):
|
||||
return PublishError("O TikTok bloqueou novos envios por enquanto (limite diário atingido — no modo Rascunho são "
|
||||
"até 5 pendentes por dia). Publique os rascunhos no app ou tente de novo amanhã.")
|
||||
if code == "reached_active_user_cap":
|
||||
return PublishError("O app do TikTok ainda sem auditoria aceita só 5 contas por dia. Tente amanhã.")
|
||||
if code in ("access_token_invalid", "token_not_authorized_for_specified_url"):
|
||||
return PublishError("A autorização do TikTok venceu. Conecte o TikTok de novo em Canais de publicação.", "expired")
|
||||
if code == "scope_not_authorized":
|
||||
return PublishError("Falta permissão no TikTok. Conecte de novo e aceite todas as permissões pedidas.", "expired")
|
||||
if code == "rate_limit_exceeded":
|
||||
return PublishError("O TikTok pediu para ir mais devagar (muitas chamadas por minuto). Tente de novo daqui a pouco.")
|
||||
return PublishError(f"O TikTok recusou o envio ({code or 'erro desconhecido'}). {message}".strip())
|
||||
|
||||
|
||||
def _check(response: httpx.Response) -> dict:
|
||||
body = response_json(response)
|
||||
error = body.get("error") or {}
|
||||
code = str(error.get("code") or "") if isinstance(error, dict) else str(error)
|
||||
if response.status_code >= 400 or (code and code != "ok"):
|
||||
raise explain(code or str(response.status_code), str(error.get("message") or "") if isinstance(error, dict) else "")
|
||||
return body.get("data") or {}
|
||||
|
||||
|
||||
class TikTokApi:
|
||||
# Limites dos blocos (sobrescritos nos testes para não precisar de arquivo de 64 MB).
|
||||
single_max = 64 * MB
|
||||
chunk = 32 * MB
|
||||
poll_s = 5.0
|
||||
poll_max = 180 # ~15 min
|
||||
|
||||
def __init__(self, client: httpx.Client, client_key: str, client_secret: str, redirect_uri: str,
|
||||
sleep: Sleep = time.sleep):
|
||||
self.client, self.client_key, self.client_secret = client, client_key, client_secret
|
||||
self.redirect_uri, self.sleep = redirect_uri, sleep
|
||||
|
||||
# ---------- OAuth
|
||||
def authorize_url(self, state: str, verifier: str) -> str:
|
||||
params = {"client_key": self.client_key, "scope": SCOPES, "response_type": "code",
|
||||
"redirect_uri": self.redirect_uri, "state": state,
|
||||
"code_challenge": challenge_s256_hex(verifier), "code_challenge_method": "S256"}
|
||||
return f"{AUTH_URL}?{urlencode(params)}"
|
||||
|
||||
def _token_request(self, data: dict) -> Tokens:
|
||||
try:
|
||||
response = self.client.post(TOKEN_URL, data={**data, "client_key": self.client_key,
|
||||
"client_secret": self.client_secret},
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded"})
|
||||
except httpx.HTTPError as exc:
|
||||
raise network_error("TikTok", exc) from exc
|
||||
body = response_json(response)
|
||||
if response.status_code >= 400 or body.get("error") or not body.get("access_token"):
|
||||
error = str(body.get("error") or response.status_code)
|
||||
if error in ("invalid_grant", "invalid_request") and data.get("grant_type") == "refresh_token":
|
||||
raise PublishError("A autorização do TikTok expirou. Conecte o TikTok de novo em Canais de publicação.",
|
||||
"expired")
|
||||
if error in ("invalid_client", "unauthorized_client"):
|
||||
raise PublishError("O TikTok recusou o Client Key/Secret do app. Confira em Configurações → Apps das redes.")
|
||||
raise PublishError(f"O TikTok recusou a autorização ({error}). Tente conectar de novo.")
|
||||
return Tokens(body["access_token"], expires_in(body.get("expires_in")), body.get("refresh_token"),
|
||||
expires_in(body.get("refresh_expires_in")), {"openId": body.get("open_id")})
|
||||
|
||||
def exchange_code(self, code: str, verifier: str) -> Tokens:
|
||||
return self._token_request({"code": code, "grant_type": "authorization_code",
|
||||
"redirect_uri": self.redirect_uri, "code_verifier": verifier})
|
||||
|
||||
def refresh(self, refresh_token: str) -> Tokens:
|
||||
# Rotativo: o refresh devolvido substitui o antigo (quem chama grava o novo no cofre na hora).
|
||||
return self._token_request({"grant_type": "refresh_token", "refresh_token": refresh_token})
|
||||
|
||||
def _post(self, path: str, access_token: str, json: dict | None = None) -> dict:
|
||||
try:
|
||||
response = self.client.post(f"{API}{path}", json=json or {}, headers={
|
||||
"Authorization": f"Bearer {access_token}", "Content-Type": "application/json; charset=UTF-8"})
|
||||
except httpx.HTTPError as exc:
|
||||
raise network_error("TikTok", exc) from exc
|
||||
return _check(response)
|
||||
|
||||
def user_info(self, access_token: str) -> tuple[str | None, str | None]:
|
||||
"""(nome de exibição, @usuário). O usuário vem do creator_info (o user.info.basic não traz)."""
|
||||
name = handle = None
|
||||
try:
|
||||
response = self.client.get(f"{API}/v2/user/info/", params={"fields": "open_id,display_name"},
|
||||
headers={"Authorization": f"Bearer {access_token}"})
|
||||
name = ((response_json(response).get("data") or {}).get("user") or {}).get("display_name")
|
||||
except httpx.HTTPError:
|
||||
pass
|
||||
try:
|
||||
info = self.creator_info(access_token)
|
||||
name = name or info.get("creator_nickname")
|
||||
handle = info.get("creator_username")
|
||||
except PublishError:
|
||||
pass
|
||||
return name, (f"@{handle}" if handle and not str(handle).startswith("@") else handle)
|
||||
|
||||
def creator_info(self, access_token: str) -> dict:
|
||||
return self._post("/v2/post/publish/creator_info/query/", access_token)
|
||||
|
||||
# ---------- envio
|
||||
def post_info(self, spec: JobSpec, creator: dict) -> dict:
|
||||
privacy = PRIVACY.get(spec.privacy, "SELF_ONLY")
|
||||
options = list(creator.get("privacy_level_options") or [])
|
||||
if options and privacy not in options:
|
||||
if options == ["SELF_ONLY"]:
|
||||
raise PublishError(UNAUDITED)
|
||||
raise PublishError(f"A privacidade \"{spec.privacy}\" não está disponível nesta conta do TikTok "
|
||||
f"(a conta oferece: {', '.join(options)}). Mude a privacidade no canal de publicação.")
|
||||
return {
|
||||
"title": spec.caption[:2200], "privacy_level": privacy,
|
||||
# Diretriz do TikTok: interações começam DESMARCADAS (o criador escolhe permitir). Sem campo para isso no
|
||||
# contrato do job, ficam desligadas — e desligadas também se o criador já desligou na conta.
|
||||
"disable_comment": True, "disable_duet": True, "disable_stitch": True,
|
||||
"brand_content_toggle": False, "brand_organic_toggle": False,
|
||||
"is_aigc": bool(spec.ai_generated),
|
||||
}
|
||||
|
||||
def upload(self, spec: JobSpec, token: TokenProvider, progress: Progress) -> PublishResult:
|
||||
total = file_size(spec.file)
|
||||
chunk_size, count = chunk_plan(total, self.single_max, self.chunk)
|
||||
source = {"source": "FILE_UPLOAD", "video_size": total, "chunk_size": chunk_size, "total_chunk_count": count}
|
||||
access = token(False)
|
||||
draft = spec.tiktok_mode == "draft"
|
||||
username = None
|
||||
if draft:
|
||||
progress("Abrindo o envio para a caixa de entrada do TikTok…", 0.02)
|
||||
data = self._post("/v2/post/publish/inbox/video/init/", access, {"source_info": source})
|
||||
else:
|
||||
progress("Consultando a conta do TikTok…", 0.01)
|
||||
creator = self.creator_info(access)
|
||||
username = creator.get("creator_username")
|
||||
body = {"post_info": self.post_info(spec, creator), "source_info": source}
|
||||
progress("Abrindo a publicação no TikTok…", 0.03)
|
||||
data = self._post("/v2/post/publish/video/init/", access, body)
|
||||
publish_id, upload_url = data.get("publish_id"), data.get("upload_url")
|
||||
if not publish_id or not upload_url:
|
||||
raise PublishError("O TikTok não devolveu o endereço de envio. Tente de novo daqui a pouco.")
|
||||
|
||||
self._put_chunks(spec, upload_url, total, chunk_size, count, progress)
|
||||
return self._wait(publish_id, token, progress, draft, username, spec.privacy)
|
||||
|
||||
def _put_chunks(self, spec: JobSpec, upload_url: str, total: int, chunk_size: int, count: int,
|
||||
progress: Progress) -> None:
|
||||
with spec.file.open("rb") as handle:
|
||||
for index in range(count):
|
||||
start = index * chunk_size
|
||||
# O último bloco leva o resto do arquivo.
|
||||
length = total - start if index == count - 1 else chunk_size
|
||||
handle.seek(start)
|
||||
data = handle.read(length)
|
||||
end = start + len(data) - 1
|
||||
try:
|
||||
response = self.client.put(upload_url, content=data, headers={
|
||||
"Content-Type": "video/mp4", "Content-Length": str(len(data)),
|
||||
"Content-Range": f"bytes {start}-{end}/{total}"})
|
||||
except httpx.HTTPError as exc:
|
||||
raise network_error("TikTok", exc) from exc
|
||||
if response.status_code not in (200, 201, 206):
|
||||
raise PublishError(f"O TikTok recusou um pedaço do vídeo (código {response.status_code}). "
|
||||
"Tente de novo; se repetir, confira se o vídeo tem até 10 min e 4 GB.")
|
||||
progress(f"Enviando vídeo… {int((end + 1) * 100 / total)}%", 0.05 + 0.8 * (end + 1) / total)
|
||||
|
||||
def _wait(self, publish_id: str, token: TokenProvider, progress: Progress, draft: bool,
|
||||
username: str | None, privacy: str) -> PublishResult:
|
||||
progress("Aguardando o TikTok processar…", 0.88)
|
||||
for _ in range(self.poll_max):
|
||||
data = self._post("/v2/post/publish/status/fetch/", token(False), {"publish_id": publish_id})
|
||||
status = data.get("status")
|
||||
if status == "FAILED":
|
||||
reason = str(data.get("fail_reason") or "")
|
||||
raise explain(reason, "O TikTok não conseguiu processar o vídeo.")
|
||||
if draft and status == "SEND_TO_USER_INBOX":
|
||||
return PublishResult(publish_id, None, True,
|
||||
"Enviado para a caixa de entrada do TikTok: abra o app para revisar e publicar")
|
||||
if status == "PUBLISH_COMPLETE":
|
||||
# (sic) o campo da API é "publicaly_available_post_id".
|
||||
posts = data.get("publicaly_available_post_id") or []
|
||||
if posts and username:
|
||||
post = str(posts[0])
|
||||
return PublishResult(post, f"https://www.tiktok.com/@{username}/video/{post}", False, "Publicado no TikTok")
|
||||
if PRIVACY.get(privacy) == "SELF_ONLY":
|
||||
return PublishResult(publish_id, None, False, "Publicado no TikTok como privado (Somente eu)")
|
||||
return PublishResult(str(posts[0]) if posts else publish_id, None, False,
|
||||
"Publicado no TikTok; o link ainda não apareceu (confira no app)")
|
||||
self.sleep(self.poll_s)
|
||||
raise PublishError("O TikTok demorou demais para processar o vídeo. Confira no app antes de tentar de novo "
|
||||
"(pode ter publicado).")
|
||||
@@ -0,0 +1,271 @@
|
||||
"""YouTube pela API oficial (Data API v3).
|
||||
|
||||
OAuth: cliente "Desktop app" do Google Cloud, PKCE (S256, base64url) e redirect loopback
|
||||
http://127.0.0.1:4530/oauth/callback/youtube. Envio: `videos.insert` resumable em blocos; capa por
|
||||
`thumbnails.set` depois do processamento (falha na capa não derruba o envio: o vídeo já está no ar).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Callable
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import httpx
|
||||
|
||||
from .base import (JobSpec, Progress, PublishError, PublishResult, Sleep, Tokens, challenge_s256_base64url,
|
||||
expires_in, file_size, network_error, response_json)
|
||||
|
||||
AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth"
|
||||
TOKEN_URL = "https://oauth2.googleapis.com/token"
|
||||
API = "https://www.googleapis.com/youtube/v3"
|
||||
UPLOAD_URL = "https://www.googleapis.com/upload/youtube/v3/videos"
|
||||
THUMB_URL = "https://www.googleapis.com/upload/youtube/v3/thumbnails/set"
|
||||
SCOPES = ["https://www.googleapis.com/auth/youtube.upload", "https://www.googleapis.com/auth/youtube.readonly"]
|
||||
|
||||
# Blocos do upload resumable: múltiplos de 256 KiB (exigência do Google). 8 MiB dá progresso sem muita requisição.
|
||||
CHUNK = 8 * 1024 * 1024
|
||||
PRIVACY = {"public": "public", "unlisted": "unlisted", "private": "private"}
|
||||
|
||||
TokenProvider = Callable[[bool], str] # (forçar refresh?) -> access token válido
|
||||
|
||||
|
||||
def _google_error(response: httpx.Response) -> tuple[str, str]:
|
||||
"""(motivo, mensagem) do erro do Google (`error.errors[0].reason`)."""
|
||||
data = response_json(response)
|
||||
error = data.get("error")
|
||||
if isinstance(error, dict):
|
||||
errors = error.get("errors") or [{}]
|
||||
return str(errors[0].get("reason") or error.get("status") or ""), str(error.get("message") or "")
|
||||
return str(error or ""), str(data.get("error_description") or response.text[:200])
|
||||
|
||||
|
||||
def explain_upload_error(response: httpx.Response) -> PublishError:
|
||||
reason, message = _google_error(response)
|
||||
if response.status_code == 401:
|
||||
return PublishError("A autorização do YouTube não vale mais. Conecte o YouTube de novo em Canais de publicação.",
|
||||
"expired")
|
||||
if reason in ("quotaExceeded", "uploadLimitExceeded", "rateLimitExceeded", "dailyLimitExceeded"):
|
||||
return PublishError("O YouTube não aceita mais envios hoje por este app (a cota diária acabou). "
|
||||
"Tente de novo amanhã — a cota zera à meia-noite do horário do Pacífico (5h de Brasília).")
|
||||
if reason == "youtubeSignupRequired":
|
||||
return PublishError("Esta conta Google ainda não tem um canal do YouTube. Crie o canal no YouTube e conecte de novo.")
|
||||
if reason in ("forbidden", "insufficientPermissions"):
|
||||
return PublishError("O YouTube recusou o envio por falta de permissão. Conecte de novo e marque a permissão "
|
||||
"de enviar vídeos.", "expired")
|
||||
if reason in ("invalidTitle", "invalidDescription", "invalidTags"):
|
||||
return PublishError(f"O YouTube recusou o título, a descrição ou as tags do vídeo ({message}). Ajuste o texto e tente de novo.")
|
||||
if reason == "invalidPublishAt":
|
||||
return PublishError("O horário de agendamento foi recusado pelo YouTube (precisa ser no futuro). Escolha outro horário.")
|
||||
return PublishError(f"O YouTube recusou o envio (código {response.status_code}{', ' + reason if reason else ''}). {message}".strip())
|
||||
|
||||
|
||||
def clean_text(text: str, limit: int) -> str:
|
||||
# O YouTube recusa "<" e ">" no título e na descrição.
|
||||
return text.replace("<", "‹").replace(">", "›").strip()[:limit]
|
||||
|
||||
|
||||
def clean_tags(tags: list[str]) -> list[str]:
|
||||
"""Tags sem vírgula/aspas e com no máximo 500 caracteres somados (limite do YouTube)."""
|
||||
out: list[str] = []
|
||||
total = 0
|
||||
for tag in tags:
|
||||
tag = tag.replace(",", " ").replace('"', "").replace("<", "").replace(">", "").strip().lstrip("#")
|
||||
if not tag:
|
||||
continue
|
||||
cost = len(tag) + (2 if " " in tag else 0) + (1 if out else 0)
|
||||
if total + cost > 500:
|
||||
break
|
||||
out.append(tag)
|
||||
total += cost
|
||||
return out
|
||||
|
||||
|
||||
class YouTubeApi:
|
||||
def __init__(self, client: httpx.Client, client_id: str, client_secret: str, redirect_uri: str,
|
||||
sleep: Sleep = time.sleep):
|
||||
self.client, self.client_id, self.client_secret = client, client_id, client_secret
|
||||
self.redirect_uri, self.sleep = redirect_uri, sleep
|
||||
|
||||
# ---------- OAuth
|
||||
def authorize_url(self, state: str, verifier: str) -> str:
|
||||
params = {
|
||||
"client_id": self.client_id, "redirect_uri": self.redirect_uri, "response_type": "code",
|
||||
"scope": " ".join(SCOPES), "state": state, "code_challenge": challenge_s256_base64url(verifier),
|
||||
"code_challenge_method": "S256",
|
||||
# offline + consent: garante o refresh token (sem ele seria preciso conectar de novo a cada hora).
|
||||
"access_type": "offline", "prompt": "consent", "include_granted_scopes": "true",
|
||||
}
|
||||
return f"{AUTH_URL}?{urlencode(params)}"
|
||||
|
||||
def _token_request(self, data: dict) -> dict:
|
||||
try:
|
||||
response = self.client.post(TOKEN_URL, data={**data, "client_id": self.client_id,
|
||||
"client_secret": self.client_secret})
|
||||
except httpx.HTTPError as exc:
|
||||
raise network_error("Google", exc) from exc
|
||||
body = response_json(response)
|
||||
if response.status_code >= 400:
|
||||
error = str(body.get("error") or "")
|
||||
if error == "invalid_grant":
|
||||
raise PublishError("A autorização do YouTube expirou ou foi revogada. Conecte o YouTube de novo em "
|
||||
"Canais de publicação. (Se acontece a cada 7 dias, o app do Google Cloud ainda está "
|
||||
"em \"Testing\": coloque-o \"In production\".)", "expired")
|
||||
if error in ("invalid_client", "unauthorized_client"):
|
||||
raise PublishError("O Google recusou o Client ID/Secret do app. Confira em Configurações → Apps das redes "
|
||||
"(o cliente precisa ser do tipo \"App para computador\" / Desktop app).")
|
||||
raise PublishError(f"O Google recusou a autorização ({error or response.status_code}). Tente conectar de novo.")
|
||||
return body
|
||||
|
||||
def exchange_code(self, code: str, verifier: str) -> Tokens:
|
||||
body = self._token_request({"code": code, "code_verifier": verifier, "grant_type": "authorization_code",
|
||||
"redirect_uri": self.redirect_uri})
|
||||
if not body.get("refresh_token"):
|
||||
raise PublishError("O Google não devolveu a autorização permanente (refresh token). Remova o acesso do app em "
|
||||
"myaccount.google.com/permissions e conecte de novo.")
|
||||
return Tokens(body["access_token"], expires_in(body.get("expires_in")), body["refresh_token"], None)
|
||||
|
||||
def refresh(self, refresh_token: str) -> Tokens:
|
||||
body = self._token_request({"refresh_token": refresh_token, "grant_type": "refresh_token"})
|
||||
# O Google mantém o mesmo refresh token (só devolve outro se rotacionar).
|
||||
return Tokens(body["access_token"], expires_in(body.get("expires_in")), body.get("refresh_token") or refresh_token, None)
|
||||
|
||||
def channel(self, access_token: str) -> tuple[str | None, str | None, str | None]:
|
||||
"""(nome do canal, @handle, id do canal) — None se não der para ler."""
|
||||
try:
|
||||
response = self.client.get(f"{API}/channels", params={"part": "snippet", "mine": "true"},
|
||||
headers={"Authorization": f"Bearer {access_token}"})
|
||||
except httpx.HTTPError:
|
||||
return None, None, None
|
||||
items = response_json(response).get("items") or []
|
||||
if response.status_code != 200 or not items:
|
||||
return None, None, None
|
||||
snippet = items[0].get("snippet") or {}
|
||||
return snippet.get("title"), snippet.get("customUrl"), items[0].get("id")
|
||||
|
||||
# ---------- envio
|
||||
def video_body(self, spec: JobSpec) -> dict:
|
||||
status: dict = {
|
||||
"privacyStatus": PRIVACY.get(spec.privacy, "public"),
|
||||
"selfDeclaredMadeForKids": bool(spec.made_for_kids),
|
||||
"containsSyntheticMedia": bool(spec.ai_generated),
|
||||
}
|
||||
if spec.publish_at:
|
||||
# Agendamento nativo: o YouTube exige `private` + `publishAt`; ele mesmo torna público na hora.
|
||||
status["privacyStatus"] = "private"
|
||||
status["publishAt"] = spec.publish_at
|
||||
snippet = {"title": clean_text(spec.title, 100) or "Vídeo", "description": clean_text(spec.caption, 5000)}
|
||||
tags = clean_tags(spec.tags)
|
||||
if tags:
|
||||
snippet["tags"] = tags
|
||||
return {"snippet": snippet, "status": status}
|
||||
|
||||
def upload(self, spec: JobSpec, token: TokenProvider, progress: Progress) -> PublishResult:
|
||||
total = file_size(spec.file)
|
||||
progress("Abrindo o envio no YouTube…", 0.02)
|
||||
session_url = self._start_session(spec, total, token)
|
||||
video = self._send_chunks(spec, session_url, total, token, progress)
|
||||
video_id = video.get("id")
|
||||
if not video_id:
|
||||
raise PublishError("O YouTube terminou o envio mas não devolveu o ID do vídeo. Confira no YouTube Studio antes "
|
||||
"de tentar de novo (pode ter subido).")
|
||||
url = f"https://youtu.be/{video_id}"
|
||||
step = (f"Agendado no YouTube para {spec.publish_at}" if spec.publish_at else "Publicado no YouTube")
|
||||
if spec.cover:
|
||||
progress("Aplicando a capa (esperando o YouTube processar o vídeo)…", 0.95)
|
||||
cover_problem = self._set_thumbnail(video_id, spec, token)
|
||||
if cover_problem:
|
||||
step += f"; a capa não foi aplicada ({cover_problem})"
|
||||
return PublishResult(video_id, url, False, step)
|
||||
|
||||
def _start_session(self, spec: JobSpec, total: int, token: TokenProvider) -> str:
|
||||
for attempt in (0, 1):
|
||||
try:
|
||||
response = self.client.post(
|
||||
UPLOAD_URL, params={"uploadType": "resumable", "part": "snippet,status"},
|
||||
json=self.video_body(spec),
|
||||
headers={"Authorization": f"Bearer {token(attempt == 1)}", "X-Upload-Content-Type": "video/*",
|
||||
"X-Upload-Content-Length": str(total)})
|
||||
except httpx.HTTPError as exc:
|
||||
raise network_error("YouTube", exc) from exc
|
||||
if response.status_code == 401 and attempt == 0:
|
||||
continue # access token venceu: renova e tenta uma vez
|
||||
if response.status_code != 200 or not response.headers.get("location"):
|
||||
raise explain_upload_error(response)
|
||||
return response.headers["location"]
|
||||
raise PublishError("A autorização do YouTube não vale mais. Conecte de novo.", "expired")
|
||||
|
||||
def _send_chunks(self, spec: JobSpec, session_url: str, total: int, token: TokenProvider,
|
||||
progress: Progress) -> dict:
|
||||
offset = 0
|
||||
retries = 0
|
||||
with spec.file.open("rb") as handle:
|
||||
while True:
|
||||
handle.seek(offset)
|
||||
data = handle.read(CHUNK)
|
||||
end = offset + len(data) - 1
|
||||
headers = {"Authorization": f"Bearer {token(False)}", "Content-Type": "video/*",
|
||||
"Content-Range": f"bytes {offset}-{end}/{total}" if data else f"bytes */{total}"}
|
||||
try:
|
||||
response = self.client.put(session_url, content=data, headers=headers)
|
||||
except httpx.HTTPError as exc:
|
||||
retries += 1
|
||||
if retries > 3:
|
||||
raise network_error("YouTube", exc) from exc
|
||||
self.sleep(2 ** retries)
|
||||
offset = self._resume_offset(session_url, total, token)
|
||||
continue
|
||||
if response.status_code in (200, 201):
|
||||
progress("Vídeo enviado; o YouTube está processando…", 0.92)
|
||||
return response_json(response)
|
||||
if response.status_code == 308:
|
||||
# "Resume Incomplete": o cabeçalho Range diz até onde o Google recebeu.
|
||||
received = response.headers.get("range", "")
|
||||
offset = int(received.rsplit("-", 1)[1]) + 1 if "-" in received else 0
|
||||
retries = 0
|
||||
progress(f"Enviando vídeo… {int(offset * 100 / total)}%", 0.05 + 0.85 * offset / total)
|
||||
continue
|
||||
if response.status_code in (500, 502, 503, 504) and retries < 3:
|
||||
retries += 1
|
||||
self.sleep(2 ** retries)
|
||||
offset = self._resume_offset(session_url, total, token)
|
||||
continue
|
||||
raise explain_upload_error(response)
|
||||
|
||||
def _resume_offset(self, session_url: str, total: int, token: TokenProvider) -> int:
|
||||
try:
|
||||
response = self.client.put(session_url, content=b"", headers={
|
||||
"Authorization": f"Bearer {token(False)}", "Content-Range": f"bytes */{total}"})
|
||||
except httpx.HTTPError:
|
||||
return 0
|
||||
received = response.headers.get("range", "")
|
||||
return int(received.rsplit("-", 1)[1]) + 1 if response.status_code == 308 and "-" in received else 0
|
||||
|
||||
def _set_thumbnail(self, video_id: str, spec: JobSpec, token: TokenProvider) -> str | None:
|
||||
"""Devolve None se a capa entrou, ou o motivo (curto, pt-BR) se não entrou."""
|
||||
assert spec.cover is not None
|
||||
# Espera o processamento (até ~10 min); a capa personalizada só é aceita depois.
|
||||
for _ in range(40):
|
||||
try:
|
||||
response = self.client.get(f"{API}/videos", params={"part": "processingDetails", "id": video_id},
|
||||
headers={"Authorization": f"Bearer {token(False)}"})
|
||||
items = response_json(response).get("items") or []
|
||||
status = ((items[0].get("processingDetails") or {}).get("processingStatus")) if items else None
|
||||
except httpx.HTTPError:
|
||||
status = None
|
||||
if status in ("succeeded", "terminated", "failed"):
|
||||
break
|
||||
self.sleep(15)
|
||||
mime = "image/png" if spec.cover.suffix.lower() == ".png" else "image/jpeg"
|
||||
try:
|
||||
response = self.client.post(THUMB_URL, params={"videoId": video_id, "uploadType": "media"},
|
||||
content=spec.cover.read_bytes(),
|
||||
headers={"Authorization": f"Bearer {token(False)}", "Content-Type": mime})
|
||||
except httpx.HTTPError:
|
||||
return "sem conexão na hora de enviar a capa"
|
||||
if response.status_code == 200:
|
||||
return None
|
||||
reason, _ = _google_error(response)
|
||||
if reason == "forbidden" or response.status_code == 403:
|
||||
return "o canal precisa estar verificado por telefone para usar capa personalizada"
|
||||
return f"o YouTube recusou a imagem ({reason or response.status_code})"
|
||||
@@ -0,0 +1,584 @@
|
||||
"""Regras do Publicador: apps das redes, perfis (conexão oficial ou sessão), OAuth e execução dos jobs.
|
||||
|
||||
O Publicador é só EXECUTOR: não sabe o que é canal, história ou corte. Recebe um job (arquivo + metadados + perfil),
|
||||
envia e devolve progresso/resultado. Quem decide o quê e quando publicar é o painel.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import secrets
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
|
||||
import httpx
|
||||
|
||||
from .config import Settings
|
||||
from .db import Database, loads, now
|
||||
from .paths import IMAGE_EXT, VIDEO_EXT, PathRefused, inside_root
|
||||
from .platforms.base import PLATFORMS, JobSpec, Progress, PublishError, PublishResult, Sleep, Tokens, make_verifier
|
||||
from .platforms.instagram_api import InstagramApi
|
||||
from .platforms.session.browser import BrowserInfo, BrowserManager, detect_browser
|
||||
from .platforms.session.common import prune_screenshots
|
||||
from .platforms.session.runner import SessionRunner
|
||||
from .platforms.stats import PostStats, youtube_public
|
||||
from .platforms.tiktok_api import TikTokApi
|
||||
from .platforms.youtube_api import YouTubeApi
|
||||
from .vault import Vault
|
||||
|
||||
log = logging.getLogger("publisher")
|
||||
|
||||
PROFILE_ID = re.compile(r"^[a-z0-9][a-z0-9-]{0,63}--(youtube|tiktok|instagram)$")
|
||||
STATE_TTL_S = 10 * 60
|
||||
SESSION_GAP_S = 30 # intervalo mínimo entre dois envios pelo navegador
|
||||
|
||||
NAMES = {"youtube": "YouTube", "tiktok": "TikTok", "instagram": "Instagram"}
|
||||
APP_NOTES = {
|
||||
"youtube": ("Google Cloud: crie um cliente OAuth do tipo \"App para computador\" (Desktop app), ative a YouTube Data "
|
||||
"API v3 e coloque o app em \"In production\" (em \"Testing\" a autorização vence a cada 7 dias)."),
|
||||
"tiktok": ("TikTok for Developers: app com Login Kit (Desktop) e Content Posting API; cadastre o redirect acima. "
|
||||
"Sem auditoria do TikTok, o Direct Post só sai como privado (Somente eu); o modo Rascunho funciona."),
|
||||
"instagram": ("Meta for Developers: produto \"Instagram API with Instagram Login\". A Meta não aceita redirect para "
|
||||
"este computador, então não há redirect: gere o token no painel do app e cole em Canais de "
|
||||
"publicação. Client ID/Secret aqui são opcionais (só para referência)."),
|
||||
}
|
||||
|
||||
|
||||
class UserError(Exception):
|
||||
def __init__(self, message: str, status: int = 400):
|
||||
super().__init__(message)
|
||||
self.message, self.status = message, status
|
||||
|
||||
|
||||
def iso(epoch: float | None) -> str | None:
|
||||
if not epoch:
|
||||
return None
|
||||
return datetime.fromtimestamp(epoch, timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
|
||||
|
||||
|
||||
def parse_iso(text: str | None) -> float | None:
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
return datetime.fromisoformat(text.replace("Z", "+00:00")).timestamp()
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def profile_view(row: dict) -> dict:
|
||||
return {
|
||||
"profileId": row["profile_id"], "platform": row["platform"], "mode": row["mode"], "status": row["status"],
|
||||
"displayName": row["display_name"], "handle": row["handle"], "connectedAt": row["connected_at"],
|
||||
"expiresAt": row["expires_at"], "lastCheckAt": row["last_check_at"], "lastError": row["last_error"],
|
||||
}
|
||||
|
||||
|
||||
def job_view(row: dict) -> dict:
|
||||
return {
|
||||
"jobId": row["job_id"], "profileId": row["profile_id"], "platform": row["platform"], "status": row["status"],
|
||||
"step": row["step"], "progress": round(float(row["progress"] or 0), 4), "remoteId": row["remote_id"],
|
||||
"url": row["url"], "draft": bool(row["draft"]), "error": row["error"],
|
||||
"createdAt": row["created_at"], "updatedAt": row["updated_at"],
|
||||
}
|
||||
|
||||
|
||||
class Publisher:
|
||||
def __init__(self, settings: Settings, db: Database, vault: Vault, http: httpx.Client | None = None,
|
||||
browsers: BrowserManager | None = None, runner: SessionRunner | None = None,
|
||||
sleep: Sleep = time.sleep, detect: Callable[[], BrowserInfo | None] | None = None):
|
||||
self.settings, self.db, self.vault, self.sleep = settings, db, vault, sleep
|
||||
self.http = http or httpx.Client(timeout=httpx.Timeout(120, connect=15))
|
||||
self._detect = detect or (lambda: detect_browser(settings.browser_path))
|
||||
self.browsers = browsers or BrowserManager(settings.browser_dir, self._detect())
|
||||
self.runner = runner or SessionRunner(self.browsers, settings.logs_dir, sleep)
|
||||
self._refresh_lock = threading.Lock()
|
||||
self._last_session_end = 0.0
|
||||
self._verifiers: dict[str, str] = {} # state → code_verifier do PKCE (só em memória)
|
||||
prune_screenshots(settings.logs_dir)
|
||||
|
||||
# ---------- status
|
||||
def browser_status(self) -> dict:
|
||||
info = self._detect()
|
||||
if info and self.browsers.browser is None:
|
||||
self.browsers.browser = info # instalou o Chrome com o serviço ligado
|
||||
return {"found": bool(info), "kind": info.kind if info else None, "path": info.path if info else None}
|
||||
|
||||
# ---------- apps das redes
|
||||
def _check_platform(self, platform: str) -> None:
|
||||
if platform not in PLATFORMS:
|
||||
raise UserError("Rede desconhecida. Use youtube, tiktok ou instagram.", 404)
|
||||
|
||||
def app_state(self, platform: str) -> dict:
|
||||
self._check_platform(platform)
|
||||
app = self.vault.get(f"app:{platform}") or {}
|
||||
client_id = app.get("clientId") or None
|
||||
configured = bool(client_id and (app.get("clientSecret") or platform == "instagram"))
|
||||
return {"configured": configured, "clientId": client_id,
|
||||
"redirectUri": "" if platform == "instagram" else self.settings.redirect_uri(platform),
|
||||
"notes": APP_NOTES[platform]}
|
||||
|
||||
def set_app(self, platform: str, client_id: str, client_secret: str) -> dict:
|
||||
self._check_platform(platform)
|
||||
client_id, client_secret = client_id.strip(), client_secret.strip()
|
||||
if not client_id:
|
||||
raise UserError("Preencha o Client ID.")
|
||||
if platform != "instagram" and not client_secret:
|
||||
raise UserError("Preencha o Client Secret.")
|
||||
previous = self.vault.get(f"app:{platform}") or {}
|
||||
# Secret em branco no Instagram = manter o que já estava.
|
||||
self.vault.set(f"app:{platform}", {"clientId": client_id,
|
||||
"clientSecret": client_secret or previous.get("clientSecret", "")})
|
||||
return self.app_state(platform)
|
||||
|
||||
def delete_app(self, platform: str) -> dict:
|
||||
self._check_platform(platform)
|
||||
self.vault.delete(f"app:{platform}")
|
||||
return self.app_state(platform)
|
||||
|
||||
def _app(self, platform: str) -> dict:
|
||||
app = self.vault.get(f"app:{platform}") or {}
|
||||
if not app.get("clientId") or not app.get("clientSecret"):
|
||||
raise UserError(f"Antes de conectar pela conta oficial, cadastre o app do {NAMES[platform]} em "
|
||||
"Configurações → Apps das redes.")
|
||||
return app
|
||||
|
||||
def youtube(self) -> YouTubeApi:
|
||||
app = self._app("youtube")
|
||||
return YouTubeApi(self.http, app["clientId"], app["clientSecret"], self.settings.redirect_uri("youtube"), self.sleep)
|
||||
|
||||
def tiktok(self) -> TikTokApi:
|
||||
app = self._app("tiktok")
|
||||
return TikTokApi(self.http, app["clientId"], app["clientSecret"], self.settings.redirect_uri("tiktok"), self.sleep)
|
||||
|
||||
def instagram(self) -> InstagramApi:
|
||||
return InstagramApi(self.http, self.settings.ig_api_version, self.sleep)
|
||||
|
||||
# ---------- perfis
|
||||
def check_profile_id(self, profile_id: str) -> str:
|
||||
match = PROFILE_ID.fullmatch(profile_id or "")
|
||||
if not match:
|
||||
raise UserError("profileId inválido: use \"<canal>--<rede>\" (ex.: historias-do-litoral--youtube).")
|
||||
return match.group(1)
|
||||
|
||||
def _row(self, profile_id: str) -> dict | None:
|
||||
return self.db.get("SELECT * FROM profiles WHERE profile_id = ?", profile_id)
|
||||
|
||||
def _ensure_row(self, profile_id: str) -> dict:
|
||||
platform = self.check_profile_id(profile_id)
|
||||
row = self._row(profile_id)
|
||||
if row:
|
||||
return row
|
||||
self.db.run("INSERT OR IGNORE INTO profiles (profile_id, platform, status, updated_at) VALUES (?, ?, 'disconnected', ?)",
|
||||
profile_id, platform, now())
|
||||
return self._row(profile_id) # type: ignore[return-value]
|
||||
|
||||
def _update(self, profile_id: str, **fields: Any) -> dict:
|
||||
self._ensure_row(profile_id)
|
||||
if fields:
|
||||
columns = ", ".join(f"{name} = ?" for name in fields)
|
||||
self.db.run(f"UPDATE profiles SET {columns}, updated_at = ? WHERE profile_id = ?",
|
||||
*fields.values(), now(), profile_id)
|
||||
return self._row(profile_id) # type: ignore[return-value]
|
||||
|
||||
def profile(self, profile_id: str) -> dict:
|
||||
row = self._ensure_row(profile_id)
|
||||
# Autorização oficial vencida (refresh do TikTok, token do Instagram): marca na leitura.
|
||||
if row["status"] == "connected" and row["mode"] == "official":
|
||||
expires = parse_iso(row["expires_at"])
|
||||
if expires and expires < time.time():
|
||||
row = self._update(profile_id, status="expired",
|
||||
last_error=f"A autorização do {NAMES[row['platform']]} venceu. Conecte de novo.")
|
||||
return profile_view(row)
|
||||
|
||||
def connect(self, profile_id: str, platform: str, mode: str) -> dict:
|
||||
actual = self.check_profile_id(profile_id)
|
||||
if actual != platform:
|
||||
raise UserError(f"O profileId é do {NAMES[actual]}, mas o pedido diz {NAMES.get(platform, platform)}.")
|
||||
if mode == "session":
|
||||
self._update(profile_id, mode="session", status="connecting", last_error=None)
|
||||
try:
|
||||
self.runner.open_for_login(profile_id, platform)
|
||||
except PublishError as exc:
|
||||
self._update(profile_id, status="error", last_error=exc.message)
|
||||
raise UserError(exc.message, 409) from exc
|
||||
return {"profile": self.profile(profile_id), "next": self._browser_next(platform)}
|
||||
if platform == "instagram":
|
||||
self._update(profile_id, mode="official", status="connecting", last_error=None)
|
||||
return {"profile": self.profile(profile_id), "next": {"kind": "paste_token", "help": (
|
||||
"No painel da Meta (developers.facebook.com → seu app → Instagram → \"API setup with Instagram "
|
||||
"login\"), clique em \"Generate token\" ao lado da sua conta profissional, entre com o Instagram e "
|
||||
"copie o token. Cole aqui. Ele vale 60 dias e o CenaForge renova sozinho antes de vencer.")}}
|
||||
api = self.youtube() if platform == "youtube" else self.tiktok()
|
||||
state, verifier = secrets.token_urlsafe(32), make_verifier()
|
||||
self.db.run("DELETE FROM oauth_states WHERE expires_at < ? OR used = 1", time.time())
|
||||
# O code_verifier fica só na memória do processo (nunca no disco). Se o Publicador reiniciar no meio, é só
|
||||
# clicar em Conectar de novo.
|
||||
self._verifiers = {k: v for k, v in self._verifiers.items()
|
||||
if self.db.get("SELECT 1 FROM oauth_states WHERE state = ? AND used = 0", k)}
|
||||
self._verifiers[state] = verifier
|
||||
self.db.run("INSERT INTO oauth_states (state, platform, profile_id, verifier, created_at, expires_at) "
|
||||
"VALUES (?, ?, ?, '', ?, ?)", state, platform, profile_id, time.time(),
|
||||
time.time() + STATE_TTL_S)
|
||||
self._update(profile_id, mode="official", status="connecting", last_error=None)
|
||||
return {"profile": self.profile(profile_id), "next": {"kind": "open_url", "url": api.authorize_url(state, verifier)}}
|
||||
|
||||
@staticmethod
|
||||
def _browser_next(platform: str) -> dict:
|
||||
return {"kind": "browser_opened", "help": (
|
||||
f"Abrimos uma janela do navegador só para o {NAMES[platform]}. Entre na sua conta nela, do jeito normal "
|
||||
"(com a verificação em duas etapas, se tiver). O CenaForge nunca vê nem digita a sua senha. Quando "
|
||||
"terminar, volte aqui e clique em \"Já entrei\". Não feche a janela antes disso.")}
|
||||
|
||||
def paste_token(self, profile_id: str, access_token: str) -> dict:
|
||||
platform = self.check_profile_id(profile_id)
|
||||
if platform != "instagram":
|
||||
raise UserError("Colar token só vale para o Instagram. YouTube e TikTok conectam pela página de autorização.")
|
||||
token = access_token.strip()
|
||||
api = self.instagram()
|
||||
try:
|
||||
info = api.me(token)
|
||||
except PublishError as exc:
|
||||
self._update(profile_id, mode="official", status="error", last_error=exc.message)
|
||||
raise UserError(exc.message) from exc
|
||||
tokens = api.pasted_tokens(token, info)
|
||||
self.vault.set(f"token:{profile_id}", tokens.to_vault())
|
||||
self._update(profile_id, mode="official", status="connected", display_name=info.get("name") or info.get("username"),
|
||||
handle=f"@{info['username']}" if info.get("username") else None, connected_at=now(),
|
||||
expires_at=iso(tokens.access_expires_at), last_check_at=now(), last_error=None,
|
||||
meta_json=json.dumps({"igUserId": info["igUserId"], "accountType": info.get("accountType")}))
|
||||
return self.profile(profile_id)
|
||||
|
||||
def session_check(self, profile_id: str) -> dict:
|
||||
platform = self.check_profile_id(profile_id)
|
||||
row = self._ensure_row(profile_id)
|
||||
if row["mode"] != "session":
|
||||
raise UserError("Este perfil não está no modo Sessão logada. Conecte escolhendo \"Sessão logada\".")
|
||||
try:
|
||||
reason = self.runner.check(profile_id, platform)
|
||||
except PublishError as exc:
|
||||
self._update(profile_id, status="error", last_check_at=now(), last_error=exc.message)
|
||||
return self.profile(profile_id)
|
||||
if reason:
|
||||
self._update(profile_id, status="needs_login", last_check_at=now(),
|
||||
last_error=f"Ainda não está logado: {reason}. Entre na conta na janela aberta e clique em \"Já entrei\".")
|
||||
else:
|
||||
self._update(profile_id, status="connected", last_check_at=now(), last_error=None,
|
||||
connected_at=row["connected_at"] if row["status"] == "connected" else now())
|
||||
return self.profile(profile_id)
|
||||
|
||||
def session_open(self, profile_id: str) -> dict:
|
||||
platform = self.check_profile_id(profile_id)
|
||||
row = self._ensure_row(profile_id)
|
||||
if row["mode"] != "session":
|
||||
raise UserError("Este perfil não está no modo Sessão logada.")
|
||||
try:
|
||||
self.runner.open_for_login(profile_id, platform)
|
||||
except PublishError as exc:
|
||||
raise UserError(exc.message, 409) from exc
|
||||
if row["status"] != "connected":
|
||||
self._update(profile_id, status="connecting")
|
||||
return {"profile": self.profile(profile_id), "next": self._browser_next(platform)}
|
||||
|
||||
# ---------- números dos posts (dashboard)
|
||||
def post_stats(self, profile_id: str, ids: list[str]) -> dict:
|
||||
"""Visualizações/curtidas/comentários dos posts `ids` (id do vídeo no YouTube e TikTok, código do reel no
|
||||
Instagram). YouTube: página pública, em qualquer modo. TikTok e Instagram: janela logada (só modo sessão)."""
|
||||
platform = self.check_profile_id(profile_id)
|
||||
ids = list(dict.fromkeys(i.strip() for i in ids if i and i.strip()))[:200]
|
||||
if not ids:
|
||||
return {"capturedAt": iso(time.time()), "items": [], "missing": []}
|
||||
found: dict[str, PostStats] = {}
|
||||
if platform == "youtube":
|
||||
for video_id in ids:
|
||||
try:
|
||||
stats = youtube_public(self.http, video_id)
|
||||
except httpx.HTTPError:
|
||||
stats = None
|
||||
if stats:
|
||||
found[video_id] = stats
|
||||
else:
|
||||
row = self._ensure_row(profile_id)
|
||||
if row["mode"] != "session":
|
||||
raise UserError(f"Ler os números do {NAMES[platform]} por enquanto só funciona no modo Sessão logada.", 409)
|
||||
try:
|
||||
found = self.runner.read_stats(profile_id, platform, ids)
|
||||
except PublishError as exc:
|
||||
if exc.kind == "needs_login":
|
||||
self._update(profile_id, status="needs_login", last_check_at=now(),
|
||||
last_error=f"Ainda não está logado: {exc.message}")
|
||||
raise UserError(exc.message, 409) from exc
|
||||
return {"capturedAt": iso(time.time()), "items": [found[i].view() for i in ids if i in found],
|
||||
"missing": [i for i in ids if i not in found]}
|
||||
|
||||
def disconnect(self, profile_id: str) -> dict:
|
||||
self._ensure_row(profile_id)
|
||||
self.vault.delete(f"token:{profile_id}")
|
||||
try:
|
||||
self.browsers.remove_profile(profile_id)
|
||||
except PublishError as exc:
|
||||
log.warning("não consegui apagar o perfil de navegador %s: %s", profile_id, exc.message)
|
||||
self.db.run("UPDATE jobs SET status = 'canceled', error = ?, step = 'Cancelado', updated_at = ? "
|
||||
"WHERE profile_id = ? AND status = 'queued'", "O perfil foi desconectado.", now(), profile_id)
|
||||
self.db.run("DELETE FROM oauth_states WHERE profile_id = ?", profile_id)
|
||||
self._update(profile_id, mode=None, status="disconnected", display_name=None, handle=None, connected_at=None,
|
||||
expires_at=None, last_check_at=None, last_error=None, meta_json="{}")
|
||||
return self.profile(profile_id)
|
||||
|
||||
def tiktok_creator_info(self, profile_id: str) -> dict:
|
||||
platform = self.check_profile_id(profile_id)
|
||||
row = self._ensure_row(profile_id)
|
||||
if platform != "tiktok" or row["mode"] != "official" or row["status"] != "connected":
|
||||
raise UserError("Disponível só para um perfil do TikTok conectado pela conta oficial.", 409)
|
||||
try:
|
||||
info = self.tiktok().creator_info(self._token_provider(profile_id, "tiktok")(False))
|
||||
except PublishError as exc:
|
||||
self._apply_error(profile_id, exc)
|
||||
raise UserError(exc.message, 409 if exc.kind != "failed" else 502) from exc
|
||||
return {"nickname": info.get("creator_nickname"), "privacyOptions": list(info.get("privacy_level_options") or []),
|
||||
"maxDurationS": info.get("max_video_post_duration_sec"),
|
||||
"commentDisabled": bool(info.get("comment_disabled")), "duetDisabled": bool(info.get("duet_disabled")),
|
||||
"stitchDisabled": bool(info.get("stitch_disabled"))}
|
||||
|
||||
# ---------- OAuth (YouTube e TikTok)
|
||||
def consume_state(self, state: str, platform: str) -> dict:
|
||||
"""Uso único e validade de 10 min. Devolve a linha do state ou levanta UserError."""
|
||||
cursor = self.db.run("UPDATE oauth_states SET used = 1 WHERE state = ? AND platform = ? AND used = 0 AND expires_at > ?",
|
||||
state or "", platform, time.time())
|
||||
row = self.db.get("SELECT * FROM oauth_states WHERE state = ?", state or "")
|
||||
if cursor.rowcount == 1 and row:
|
||||
return row
|
||||
if not row or row["platform"] != platform:
|
||||
raise UserError("Este link de autorização não é válido. Volte ao painel e clique em Conectar de novo.")
|
||||
if row["used"]:
|
||||
raise UserError("Este link de autorização já foi usado. Volte ao painel e clique em Conectar de novo.")
|
||||
raise UserError("O link de autorização expirou (vale 10 minutos). Volte ao painel e clique em Conectar de novo.")
|
||||
|
||||
def oauth_callback(self, platform: str, params: dict[str, str]) -> str:
|
||||
"""Troca o code pelo token. Devolve a mensagem de sucesso ou levanta UserError."""
|
||||
self._check_platform(platform)
|
||||
if platform == "instagram":
|
||||
raise UserError("O Instagram conecta por token colado, não por este endereço.", 404)
|
||||
row = self.consume_state(params.get("state", ""), platform)
|
||||
profile_id = row["profile_id"]
|
||||
verifier = self._verifiers.pop(row["state"], None)
|
||||
if params.get("error"):
|
||||
message = (f"Você não autorizou o CenaForge no {NAMES[platform]} (ou cancelou). Nada foi conectado; "
|
||||
"pode tentar de novo pelo painel.")
|
||||
self._update(profile_id, status="error", last_error=message)
|
||||
raise UserError(message)
|
||||
code = params.get("code", "")
|
||||
if not code:
|
||||
raise UserError("A rede não devolveu o código de autorização. Tente conectar de novo.")
|
||||
if not verifier:
|
||||
message = "O Publicador foi reiniciado no meio da conexão. Volte ao painel e clique em Conectar de novo."
|
||||
self._update(profile_id, status="error", last_error=message)
|
||||
raise UserError(message)
|
||||
try:
|
||||
if platform == "youtube":
|
||||
api = self.youtube()
|
||||
tokens = api.exchange_code(code, verifier)
|
||||
name, handle, channel_id = api.channel(tokens.access_token)
|
||||
meta = {"channelId": channel_id}
|
||||
else:
|
||||
api = self.tiktok()
|
||||
tokens = api.exchange_code(code, verifier)
|
||||
name, handle = api.user_info(tokens.access_token)
|
||||
meta = {"openId": tokens.extra.get("openId")}
|
||||
except PublishError as exc:
|
||||
self._update(profile_id, status="error", last_error=exc.message)
|
||||
raise UserError(exc.message) from exc
|
||||
self.vault.set(f"token:{profile_id}", tokens.to_vault())
|
||||
self._update(profile_id, mode="official", status="connected", display_name=name, handle=handle,
|
||||
connected_at=now(), expires_at=iso(tokens.refresh_expires_at), last_check_at=now(),
|
||||
last_error=None, meta_json=json.dumps(meta))
|
||||
return f"Conectado{f' como {handle or name}' if (handle or name) else ''}! Pode fechar esta aba e voltar ao painel."
|
||||
|
||||
def _token_provider(self, profile_id: str, platform: str) -> Callable[[bool], str]:
|
||||
key = f"token:{profile_id}"
|
||||
|
||||
def provide(force: bool = False) -> str:
|
||||
with self._refresh_lock:
|
||||
secret = self.vault.get(key) or {}
|
||||
access, expires = secret.get("accessToken"), secret.get("accessExpiresAt") or 0
|
||||
if access and not force and expires - 120 > time.time():
|
||||
return access
|
||||
refresh = secret.get("refreshToken")
|
||||
refresh_expires = secret.get("refreshExpiresAt")
|
||||
if not refresh or (refresh_expires and refresh_expires < time.time()):
|
||||
raise PublishError(f"A autorização do {NAMES[platform]} venceu. Conecte de novo em Canais de publicação.",
|
||||
"expired")
|
||||
api = self.youtube() if platform == "youtube" else self.tiktok()
|
||||
tokens: Tokens = api.refresh(refresh)
|
||||
# TikTok: refresh ROTATIVO — o novo substitui o antigo agora, antes de qualquer outra chamada.
|
||||
fields = {k: v for k, v in tokens.to_vault().items() if v is not None}
|
||||
self.vault.update(key, **fields)
|
||||
if tokens.refresh_expires_at:
|
||||
self._update(profile_id, expires_at=iso(tokens.refresh_expires_at))
|
||||
return tokens.access_token
|
||||
|
||||
return provide
|
||||
|
||||
def maintenance(self) -> None:
|
||||
"""Renova os tokens do Instagram que vencem em menos de 10 dias (rodado pelo worker quando ocioso)."""
|
||||
for row in self.db.all("SELECT profile_id FROM profiles WHERE platform = 'instagram' AND mode = 'official' "
|
||||
"AND status = 'connected'"):
|
||||
try:
|
||||
self._instagram_token(row["profile_id"])
|
||||
except PublishError as exc:
|
||||
self._apply_error(row["profile_id"], exc)
|
||||
except Exception: # noqa: BLE001 - manutenção não pode derrubar o worker
|
||||
log.exception("falha renovando token do Instagram de %s", row["profile_id"])
|
||||
|
||||
def _instagram_token(self, profile_id: str) -> tuple[str, str]:
|
||||
key = f"token:{profile_id}"
|
||||
secret = self.vault.get(key) or {}
|
||||
token, ig_user_id = secret.get("accessToken"), secret.get("igUserId")
|
||||
if not token or not ig_user_id:
|
||||
raise PublishError("O Instagram não tem token salvo. Cole o token de novo em Canais de publicação.", "expired")
|
||||
if (secret.get("accessExpiresAt") or 0) < time.time():
|
||||
raise PublishError("O token do Instagram venceu (60 dias). Gere um novo no painel da Meta e cole de novo.",
|
||||
"expired")
|
||||
api = self.instagram()
|
||||
if api.needs_refresh(secret):
|
||||
tokens = api.refresh(token)
|
||||
self.vault.update(key, accessToken=tokens.access_token, accessExpiresAt=tokens.access_expires_at,
|
||||
obtainedAt=tokens.extra.get("obtainedAt"))
|
||||
self._update(profile_id, expires_at=iso(tokens.access_expires_at))
|
||||
token = tokens.access_token
|
||||
return token, ig_user_id
|
||||
|
||||
# ---------- jobs
|
||||
def validate_job(self, body: dict) -> dict:
|
||||
platform = self.check_profile_id(body["profileId"])
|
||||
if platform != body["platform"]:
|
||||
raise UserError(f"O profileId é do {NAMES[platform]}, mas o job diz {NAMES.get(body['platform'], body['platform'])}.")
|
||||
try:
|
||||
file = inside_root(body["file"], self.settings.repo_root, VIDEO_EXT, "vídeo")
|
||||
cover = inside_root(body["cover"], self.settings.repo_root, IMAGE_EXT, "capa") if body.get("cover") else None
|
||||
except PathRefused as exc:
|
||||
raise UserError(str(exc)) from exc
|
||||
if platform == "youtube" and len(body.get("title") or "") > 100:
|
||||
raise UserError("O título do YouTube pode ter no máximo 100 caracteres.")
|
||||
if platform == "youtube" and not (body.get("title") or "").strip():
|
||||
raise UserError("O vídeo do YouTube precisa de título.")
|
||||
row = self._row(body["profileId"])
|
||||
if not row or row["status"] != "connected":
|
||||
raise UserError(f"O perfil {body['profileId']} não está conectado"
|
||||
f"{' (' + row['status'] + ')' if row else ''}. Conecte a rede antes de publicar.", 409)
|
||||
if body.get("publishAt") and parse_iso(body["publishAt"]) is None:
|
||||
raise UserError("publishAt precisa ser uma data ISO (ex.: 2026-11-18T15:00:00Z).")
|
||||
return {**body, "file": str(file), "cover": str(cover) if cover else None}
|
||||
|
||||
def create_job(self, body: dict) -> tuple[dict, bool]:
|
||||
"""(job, criado?). Com `clientRef` já conhecido devolve o job existente sem revalidar nem criar outro."""
|
||||
ref = body.get("clientRef")
|
||||
if ref:
|
||||
existing = self.db.get("SELECT job_id FROM jobs WHERE client_ref = ?", ref)
|
||||
if existing:
|
||||
return self.job(existing["job_id"]), False
|
||||
clean = self.validate_job(body)
|
||||
job_id = uuid.uuid4().hex
|
||||
stamp = now()
|
||||
try:
|
||||
self.db.run("INSERT INTO jobs (job_id, profile_id, platform, input_json, status, step, progress, created_at, "
|
||||
"updated_at, client_ref) VALUES (?, ?, ?, ?, 'queued', 'Na fila', 0, ?, ?, ?)",
|
||||
job_id, clean["profileId"], clean["platform"], json.dumps(clean, ensure_ascii=False), stamp,
|
||||
stamp, ref)
|
||||
except sqlite3.IntegrityError:
|
||||
# Dois pedidos iguais ao mesmo tempo: o outro ganhou a corrida; devolve o dele.
|
||||
existing = self.db.get("SELECT job_id FROM jobs WHERE client_ref = ?", ref)
|
||||
if not existing:
|
||||
raise
|
||||
return self.job(existing["job_id"]), False
|
||||
return self.job(job_id), True
|
||||
|
||||
def job(self, job_id: str) -> dict:
|
||||
row = self.db.get("SELECT * FROM jobs WHERE job_id = ?", job_id)
|
||||
if not row:
|
||||
raise UserError("Job não encontrado.", 404)
|
||||
return job_view(row)
|
||||
|
||||
def cancel_job(self, job_id: str) -> dict:
|
||||
row = self.db.get("SELECT status FROM jobs WHERE job_id = ?", job_id)
|
||||
if not row:
|
||||
raise UserError("Job não encontrado.", 404)
|
||||
cursor = self.db.run("UPDATE jobs SET status = 'canceled', step = 'Cancelado', updated_at = ? "
|
||||
"WHERE job_id = ? AND status = 'queued'", now(), job_id)
|
||||
if cursor.rowcount != 1:
|
||||
raise UserError("Só dá para cancelar um envio que ainda está na fila (este já começou ou terminou).", 409)
|
||||
return self.job(job_id)
|
||||
|
||||
def queue_size(self) -> int:
|
||||
return int(self.db.get("SELECT COUNT(*) AS n FROM jobs WHERE status = 'queued'")["n"])
|
||||
|
||||
@staticmethod
|
||||
def spec(row: dict) -> JobSpec:
|
||||
data = loads(row["input_json"], {})
|
||||
return JobSpec(
|
||||
job_id=row["job_id"], profile_id=row["profile_id"], platform=row["platform"], file=Path(data["file"]),
|
||||
cover=Path(data["cover"]) if data.get("cover") else None, title=data.get("title") or "",
|
||||
caption=data.get("caption") or "", tags=list(data.get("tags") or []), privacy=data.get("privacy") or "public",
|
||||
publish_at=data.get("publishAt"), ai_generated=bool(data.get("aiGenerated")),
|
||||
made_for_kids=bool(data.get("madeForKids")), tiktok_mode=data.get("tiktokMode") or "direct")
|
||||
|
||||
def _apply_error(self, profile_id: str, exc: PublishError) -> None:
|
||||
if exc.kind == "expired":
|
||||
self._update(profile_id, status="expired", last_error=exc.message)
|
||||
elif exc.kind == "needs_login":
|
||||
self._update(profile_id, status="needs_login", last_error=exc.message, last_check_at=now())
|
||||
|
||||
def execute(self, row: dict, progress: Progress) -> PublishResult:
|
||||
"""Roda um job (chamado pelo worker, uma thread). PublishError sobe para o worker gravar o estado."""
|
||||
spec = self.spec(row)
|
||||
profile = self._row(spec.profile_id)
|
||||
if not profile or profile["mode"] is None or profile["status"] == "disconnected":
|
||||
raise PublishError("O perfil foi desconectado antes do envio. Conecte de novo e tente outra vez.")
|
||||
if profile["status"] in ("needs_login", "expired"):
|
||||
raise PublishError(profile["last_error"] or "É preciso entrar de novo nesta rede.", "needs_login")
|
||||
# O arquivo pode ter sumido entre a criação do job e a vez dele.
|
||||
try:
|
||||
inside_root(str(spec.file), self.settings.repo_root, VIDEO_EXT, "vídeo")
|
||||
if spec.cover:
|
||||
inside_root(str(spec.cover), self.settings.repo_root, IMAGE_EXT, "capa")
|
||||
except PathRefused as exc:
|
||||
raise PublishError(str(exc)) from exc
|
||||
try:
|
||||
if profile["mode"] == "session":
|
||||
result = self._execute_session(spec, progress)
|
||||
elif spec.platform == "youtube":
|
||||
if spec.publish_at and (parse_iso(spec.publish_at) or 0) < time.time() + 5 * 60:
|
||||
spec.publish_at = None # horário já passou (ou quase): publica agora em vez de recusar
|
||||
result = self.youtube().upload(spec, self._token_provider(spec.profile_id, "youtube"), progress)
|
||||
elif spec.platform == "tiktok":
|
||||
result = self.tiktok().upload(spec, self._token_provider(spec.profile_id, "tiktok"), progress)
|
||||
else:
|
||||
token, ig_user_id = self._instagram_token(spec.profile_id)
|
||||
result = self.instagram().upload(spec, token, ig_user_id, progress)
|
||||
except PublishError as exc:
|
||||
self._apply_error(spec.profile_id, exc)
|
||||
if exc.kind == "expired":
|
||||
raise PublishError(exc.message, "needs_login") from exc
|
||||
raise
|
||||
self._update(spec.profile_id, last_error=None)
|
||||
return result
|
||||
|
||||
def _execute_session(self, spec: JobSpec, progress: Progress) -> PublishResult:
|
||||
wait = self._last_session_end + SESSION_GAP_S - time.time()
|
||||
if wait > 0:
|
||||
progress("Aguardando o intervalo mínimo entre envios…", 0.0)
|
||||
self.sleep(wait)
|
||||
try:
|
||||
return self.runner.publish(spec, progress)
|
||||
finally:
|
||||
self._last_session_end = time.time()
|
||||
|
||||
def close(self) -> None:
|
||||
self.browsers.close_all()
|
||||
self.http.close()
|
||||
@@ -0,0 +1,150 @@
|
||||
"""Cofre de segredos do Publicador (tokens de acesso, refresh tokens, client secrets).
|
||||
|
||||
Tudo fica num arquivo só (data/publisher/vault.bin): um JSON cifrado com a DPAPI do Windows
|
||||
(`CryptProtectData`, escopo do USUÁRIO). Só a mesma conta do Windows, nesta máquina, consegue abrir. Copiar o
|
||||
arquivo para outro PC ou outro usuário não adianta: lá ele não decifra.
|
||||
|
||||
Nos testes, um cifrador falso é injetado (`Vault(path, cipher=...)`); a DPAPI real só existe no Windows.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import Any, Protocol
|
||||
|
||||
|
||||
class VaultError(RuntimeError):
|
||||
"""O cofre não abriu (arquivo de outro usuário/máquina, corrompido, ou DPAPI indisponível)."""
|
||||
|
||||
|
||||
class Cipher(Protocol):
|
||||
def protect(self, data: bytes) -> bytes: ...
|
||||
def unprotect(self, data: bytes) -> bytes: ...
|
||||
|
||||
|
||||
# Entropia extra: um segredo fixo do app que entra na cifra junto com a chave do usuário. Não é senha; só impede
|
||||
# que outro programa do mesmo usuário abra o arquivo chamando CryptUnprotectData "às cegas".
|
||||
_ENTROPY = b"CenaForge.Publisher.vault.v1"
|
||||
|
||||
|
||||
class DpapiCipher:
|
||||
"""DPAPI via ctypes (crypt32.dll). Sem dependência externa."""
|
||||
|
||||
CRYPTPROTECT_UI_FORBIDDEN = 0x01
|
||||
|
||||
def __init__(self) -> None:
|
||||
if sys.platform != "win32":
|
||||
raise VaultError("O cofre do Publicador usa a DPAPI do Windows; este sistema não tem.")
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
|
||||
class DataBlob(ctypes.Structure):
|
||||
_fields_ = [("cbData", wintypes.DWORD), ("pbData", ctypes.POINTER(ctypes.c_char))]
|
||||
|
||||
self._ctypes = ctypes
|
||||
self._blob = DataBlob
|
||||
self._crypt32 = ctypes.WinDLL("crypt32", use_last_error=True)
|
||||
self._kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
self._kernel32.LocalFree.argtypes = [ctypes.c_void_p]
|
||||
self._kernel32.LocalFree.restype = ctypes.c_void_p
|
||||
for fn in (self._crypt32.CryptProtectData, self._crypt32.CryptUnprotectData):
|
||||
fn.argtypes = [ctypes.POINTER(DataBlob), ctypes.c_void_p, ctypes.POINTER(DataBlob), ctypes.c_void_p,
|
||||
ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(DataBlob)]
|
||||
fn.restype = wintypes.BOOL
|
||||
|
||||
def _to_blob(self, data: bytes):
|
||||
buffer = self._ctypes.create_string_buffer(data, len(data))
|
||||
blob = self._blob(len(data), self._ctypes.cast(buffer, self._ctypes.POINTER(self._ctypes.c_char)))
|
||||
return blob, buffer # o buffer precisa continuar vivo enquanto o blob for usado
|
||||
|
||||
def _call(self, fn, data: bytes, what: str) -> bytes:
|
||||
ctypes = self._ctypes
|
||||
in_blob, _keep_in = self._to_blob(data)
|
||||
entropy, _keep_entropy = self._to_blob(_ENTROPY)
|
||||
out_blob = self._blob()
|
||||
ok = fn(ctypes.byref(in_blob), None, ctypes.byref(entropy), None, None, self.CRYPTPROTECT_UI_FORBIDDEN,
|
||||
ctypes.byref(out_blob))
|
||||
if not ok:
|
||||
code = ctypes.get_last_error()
|
||||
raise VaultError(f"A DPAPI do Windows não conseguiu {what} o cofre (erro {code}). O arquivo pode ser de "
|
||||
"outro usuário ou de outro computador.")
|
||||
try:
|
||||
return ctypes.string_at(out_blob.pbData, out_blob.cbData)
|
||||
finally:
|
||||
self._kernel32.LocalFree(out_blob.pbData)
|
||||
|
||||
def protect(self, data: bytes) -> bytes:
|
||||
return self._call(self._crypt32.CryptProtectData, data, "cifrar")
|
||||
|
||||
def unprotect(self, data: bytes) -> bytes:
|
||||
return self._call(self._crypt32.CryptUnprotectData, data, "abrir")
|
||||
|
||||
|
||||
class Vault:
|
||||
"""Dicionário de segredos persistido cifrado. Chaves usadas: `app:<platform>` e `token:<profileId>`."""
|
||||
|
||||
def __init__(self, path: Path, cipher: Cipher | None = None):
|
||||
self.path = path
|
||||
self._cipher = cipher
|
||||
self._lock = threading.RLock()
|
||||
|
||||
@property
|
||||
def cipher(self) -> Cipher:
|
||||
if self._cipher is None:
|
||||
self._cipher = DpapiCipher()
|
||||
return self._cipher
|
||||
|
||||
def _read(self) -> dict[str, Any]:
|
||||
if not self.path.is_file():
|
||||
return {}
|
||||
raw = self.path.read_bytes()
|
||||
if not raw:
|
||||
return {}
|
||||
try:
|
||||
return json.loads(self.cipher.unprotect(raw).decode("utf-8"))
|
||||
except VaultError:
|
||||
raise
|
||||
except Exception as exc: # JSON quebrado ou cifra inválida
|
||||
raise VaultError("O cofre do Publicador está corrompido ou não pertence a este usuário do Windows.") from exc
|
||||
|
||||
def _write(self, data: dict[str, Any]) -> None:
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
blob = self.cipher.protect(json.dumps(data, ensure_ascii=False).encode("utf-8"))
|
||||
tmp = self.path.with_suffix(".tmp")
|
||||
tmp.write_bytes(blob)
|
||||
os.replace(tmp, self.path) # troca atômica: nunca fica meio arquivo se o processo cair
|
||||
|
||||
def get(self, key: str) -> Any:
|
||||
with self._lock:
|
||||
return self._read().get(key)
|
||||
|
||||
def set(self, key: str, value: Any) -> None:
|
||||
with self._lock:
|
||||
data = self._read()
|
||||
data[key] = value
|
||||
self._write(data)
|
||||
|
||||
def update(self, key: str, **fields: Any) -> dict:
|
||||
"""Mescla campos no segredo `key` (ex.: gravar o refresh token novo do TikTok sem perder o resto)."""
|
||||
with self._lock:
|
||||
data = self._read()
|
||||
current = dict(data.get(key) or {})
|
||||
current.update(fields)
|
||||
data[key] = current
|
||||
self._write(data)
|
||||
return current
|
||||
|
||||
def delete(self, key: str) -> None:
|
||||
with self._lock:
|
||||
data = self._read()
|
||||
if key in data:
|
||||
del data[key]
|
||||
self._write(data)
|
||||
|
||||
def keys(self) -> list[str]:
|
||||
with self._lock:
|
||||
return list(self._read().keys())
|
||||
@@ -0,0 +1,113 @@
|
||||
"""Worker do Publicador: UMA thread, UM job por vez, na ordem de chegada.
|
||||
|
||||
Máquina de estados do job: queued → running → done | failed | needs_login
|
||||
queued → canceled (só pelo /cancel, antes de começar)
|
||||
Persistente: os jobs ficam no SQLite. Se o serviço cair com um job em `running`, na subida ele vira `failed`
|
||||
com "interrompido — tente de novo" (db.py) — não dá para saber se o vídeo chegou à rede.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from typing import Callable
|
||||
|
||||
from .db import Database, now
|
||||
from .platforms.base import Progress, PublishError, PublishResult
|
||||
|
||||
log = logging.getLogger("publisher.worker")
|
||||
|
||||
Execute = Callable[[dict, Progress], PublishResult]
|
||||
|
||||
|
||||
class Worker:
|
||||
def __init__(self, db: Database, execute: Execute, maintenance: Callable[[], None] | None = None,
|
||||
idle_wait_s: float = 2.0, maintenance_every_s: float = 3600.0):
|
||||
self.db = db
|
||||
self.execute = execute
|
||||
self.maintenance = maintenance
|
||||
self.idle_wait_s = idle_wait_s
|
||||
self.maintenance_every_s = maintenance_every_s
|
||||
self._wake = threading.Event()
|
||||
self._stop = threading.Event()
|
||||
self._thread: threading.Thread | None = None
|
||||
self._current: str | None = None
|
||||
self._last_maintenance = 0.0
|
||||
|
||||
@property
|
||||
def busy(self) -> bool:
|
||||
return self._current is not None
|
||||
|
||||
def start(self) -> None:
|
||||
if self._thread and self._thread.is_alive():
|
||||
return
|
||||
self._stop.clear()
|
||||
self._thread = threading.Thread(target=self._loop, name="publisher-worker", daemon=True)
|
||||
self._thread.start()
|
||||
|
||||
def stop(self, timeout: float = 5) -> None:
|
||||
self._stop.set()
|
||||
self._wake.set()
|
||||
if self._thread:
|
||||
self._thread.join(timeout)
|
||||
|
||||
def wake(self) -> None:
|
||||
self._wake.set()
|
||||
|
||||
def _loop(self) -> None:
|
||||
while not self._stop.is_set():
|
||||
try:
|
||||
if not self.run_once():
|
||||
if self.maintenance and time.time() - self._last_maintenance > self.maintenance_every_s:
|
||||
self._last_maintenance = time.time()
|
||||
self.maintenance()
|
||||
self._wake.wait(self.idle_wait_s)
|
||||
self._wake.clear()
|
||||
except Exception: # noqa: BLE001 - o laço não pode morrer
|
||||
log.exception("erro no laço do worker")
|
||||
time.sleep(self.idle_wait_s)
|
||||
|
||||
def _set(self, job_id: str, **fields) -> None:
|
||||
columns = ", ".join(f"{name} = ?" for name in fields)
|
||||
self.db.run(f"UPDATE jobs SET {columns}, updated_at = ? WHERE job_id = ?", *fields.values(), now(), job_id)
|
||||
|
||||
def run_once(self) -> bool:
|
||||
"""Pega o job mais antigo da fila e roda até o fim. False = fila vazia."""
|
||||
row = self.db.get("SELECT * FROM jobs WHERE status = 'queued' ORDER BY created_at, rowid LIMIT 1")
|
||||
if not row:
|
||||
return False
|
||||
job_id = row["job_id"]
|
||||
# Reserva atômica: se alguém cancelou entre o SELECT e aqui, não roda.
|
||||
claimed = self.db.run("UPDATE jobs SET status = 'running', step = 'Começando…', progress = 0, error = NULL, "
|
||||
"updated_at = ? WHERE job_id = ? AND status = 'queued'", now(), job_id)
|
||||
if claimed.rowcount != 1:
|
||||
return True
|
||||
self._current = job_id
|
||||
last = [0.0]
|
||||
|
||||
def progress(step: str, fraction: float) -> None:
|
||||
# Grava no máximo ~2x por segundo (o upload chama muito).
|
||||
if time.time() - last[0] < 0.5 and fraction < 1:
|
||||
return
|
||||
last[0] = time.time()
|
||||
self._set(job_id, step=step[:200], progress=max(0.0, min(1.0, float(fraction))))
|
||||
|
||||
try:
|
||||
result = self.execute(row, progress)
|
||||
except PublishError as exc:
|
||||
status = "needs_login" if exc.kind in ("needs_login", "expired") else "failed"
|
||||
self._set(job_id, status=status, error=exc.message,
|
||||
step="Precisa entrar de novo" if status == "needs_login" else "Falhou")
|
||||
log.info("job %s: %s (%s)", job_id, status, exc.message)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.exception("job %s falhou com erro inesperado", job_id)
|
||||
self._set(job_id, status="failed", step="Falhou",
|
||||
error=f"Erro inesperado no Publicador ({type(exc).__name__}: {str(exc)[:200]}). Tente de novo.")
|
||||
else:
|
||||
self._set(job_id, status="done", step=result.step[:200], progress=1.0, remote_id=result.remote_id,
|
||||
url=result.url, draft=1 if result.draft else 0, error=None)
|
||||
log.info("job %s: concluído (%s)", job_id, result.url or result.remote_id or "sem link")
|
||||
finally:
|
||||
self._current = None
|
||||
return True
|
||||
@@ -0,0 +1,3 @@
|
||||
[pytest]
|
||||
testpaths = tests
|
||||
addopts = -q -p no:cacheprovider
|
||||
@@ -0,0 +1,2 @@
|
||||
-r requirements.txt
|
||||
pytest==9.1.1
|
||||
@@ -0,0 +1,8 @@
|
||||
# Serviço Publicador do CenaForge (envio para YouTube, TikTok e Instagram). Versões fixas; suba com teste.
|
||||
fastapi==0.159.1
|
||||
uvicorn==0.54.0
|
||||
pydantic==2.14.1
|
||||
httpx==0.28.1
|
||||
# Modo "sessão logada": só o driver do Playwright, para conectar (connect_over_cdp) num Chrome/Edge que o próprio
|
||||
# serviço abre como processo normal. NÃO rode `playwright install`: nenhum navegador é baixado.
|
||||
playwright==1.65.2
|
||||
@@ -0,0 +1,134 @@
|
||||
"""Fixtures dos testes do Publicador: tudo em tmp_path, cofre com cifrador falso, rede simulada (httpx.MockTransport)
|
||||
e navegador falso. Nenhum teste abre navegador nem fala com a internet."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.config import Settings
|
||||
from app.db import Database
|
||||
from app.main import create_app
|
||||
from app.platforms.base import PublishResult
|
||||
from app.platforms.session.browser import BrowserInfo, BrowserManager
|
||||
from app.service import Publisher
|
||||
from app.vault import Vault
|
||||
from app.worker import Worker
|
||||
|
||||
KEY = "k" * 40
|
||||
|
||||
|
||||
class FakeCipher:
|
||||
"""Inverte e marca os bytes: suficiente para provar que o arquivo não fica em texto puro."""
|
||||
|
||||
def protect(self, data: bytes) -> bytes:
|
||||
return b"FAKE" + data[::-1]
|
||||
|
||||
def unprotect(self, data: bytes) -> bytes:
|
||||
assert data.startswith(b"FAKE")
|
||||
return data[4:][::-1]
|
||||
|
||||
|
||||
class Router:
|
||||
"""Rede simulada: registra handlers por (método, prefixo da URL) e guarda todas as requisições."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.routes: list[tuple[str, str, Callable[[httpx.Request], httpx.Response]]] = []
|
||||
self.requests: list[httpx.Request] = []
|
||||
|
||||
def add(self, method: str, prefix: str, handler: Callable[[httpx.Request], httpx.Response] | dict | list) -> None:
|
||||
if not callable(handler):
|
||||
payload = handler
|
||||
handler = lambda _req, payload=payload: httpx.Response(200, json=payload) # noqa: E731
|
||||
self.routes.insert(0, (method, prefix, handler))
|
||||
|
||||
def __call__(self, request: httpx.Request) -> httpx.Response:
|
||||
request.read()
|
||||
self.requests.append(request)
|
||||
url = str(request.url)
|
||||
for method, prefix, handler in self.routes:
|
||||
if request.method == method and url.startswith(prefix):
|
||||
return handler(request)
|
||||
return httpx.Response(599, json={"error": f"rota não simulada: {request.method} {url}"})
|
||||
|
||||
def find(self, method: str, prefix: str) -> list[httpx.Request]:
|
||||
return [r for r in self.requests if r.method == method and str(r.url).startswith(prefix)]
|
||||
|
||||
|
||||
class FakeRunner:
|
||||
"""Substitui o SessionRunner (Playwright) nos testes."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.opened: list[tuple[str, str]] = []
|
||||
self.check_reason: str | None = None
|
||||
self.result = PublishResult(None, None, False, "Publicado (sessão); link não encontrado na tela")
|
||||
self.error: Exception | None = None
|
||||
|
||||
def open_for_login(self, profile_id: str, platform: str) -> None:
|
||||
self.opened.append((profile_id, platform))
|
||||
|
||||
def check(self, profile_id: str, platform: str) -> str | None:
|
||||
return self.check_reason
|
||||
|
||||
def publish(self, spec, progress):
|
||||
progress("Enviando pelo navegador…", 0.5)
|
||||
if self.error:
|
||||
raise self.error
|
||||
return self.result
|
||||
|
||||
|
||||
class Env:
|
||||
def __init__(self, tmp_path: Path):
|
||||
self.root = tmp_path / "repo"
|
||||
self.root.mkdir()
|
||||
self.settings = Settings.load(env_file=tmp_path / "none.env", service_key=KEY,
|
||||
data_dir=self.root / "data" / "publisher", repo_root=self.root)
|
||||
self.router = Router()
|
||||
self.http = httpx.Client(transport=httpx.MockTransport(self.router))
|
||||
self.db = Database(self.settings.db_path)
|
||||
self.vault = Vault(self.settings.vault_path, cipher=FakeCipher())
|
||||
self.runner = FakeRunner()
|
||||
self.sleeps: list[float] = []
|
||||
browsers = BrowserManager(self.settings.browser_dir, BrowserInfo("chrome", "C:/fake/chrome.exe"))
|
||||
self.publisher = Publisher(self.settings, self.db, self.vault, http=self.http, browsers=browsers,
|
||||
runner=self.runner, sleep=self.sleeps.append, # type: ignore[arg-type]
|
||||
detect=lambda: BrowserInfo("chrome", "C:/fake/chrome.exe"))
|
||||
self.worker = Worker(self.db, self.publisher.execute)
|
||||
self.app = create_app(self.settings, self.publisher, start_worker=False, worker=self.worker)
|
||||
self.client = TestClient(self.app, headers={"X-Service-Key": KEY})
|
||||
|
||||
def video(self, name: str = "clip.mp4", size: int = 1000) -> Path:
|
||||
path = self.root / "output" / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(bytes(range(256)) * (size // 256) + b"x" * (size % 256))
|
||||
return path
|
||||
|
||||
def connect_profile(self, profile_id: str, mode: str = "official", secret: dict | None = None, **fields) -> None:
|
||||
platform = profile_id.rsplit("--", 1)[1]
|
||||
self.publisher._update(profile_id, mode=mode, status="connected", connected_at="2026-11-17T00:00:00Z", **fields)
|
||||
if secret is not None:
|
||||
self.vault.set(f"token:{profile_id}", secret)
|
||||
assert platform
|
||||
|
||||
def job_body(self, profile_id: str, file: Path, **extra) -> dict:
|
||||
body = {"profileId": profile_id, "platform": profile_id.rsplit("--", 1)[1], "file": str(file), "cover": None,
|
||||
"title": "Meu vídeo", "caption": "Legenda #cortes", "tags": ["cortes", "live"], "privacy": "public",
|
||||
"publishAt": None, "aiGenerated": False, "madeForKids": False, "tiktokMode": "direct"}
|
||||
body.update(extra)
|
||||
return body
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def env(tmp_path):
|
||||
e = Env(tmp_path)
|
||||
yield e
|
||||
e.db.close()
|
||||
|
||||
|
||||
def json_body(request: httpx.Request) -> dict:
|
||||
return json.loads(request.content or b"{}")
|
||||
@@ -0,0 +1,166 @@
|
||||
"""Rotas, chave do serviço e contrato JSON (doc/publicacao/PLANO.md §3)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from tests.conftest import KEY
|
||||
|
||||
PID = "historias-do-litoral--youtube"
|
||||
|
||||
|
||||
def test_health_is_open_and_everything_else_needs_key(env):
|
||||
anon = TestClient(env.app)
|
||||
assert anon.get("/health").json() == {"ok": True}
|
||||
for method, path in [("get", "/v1/status"), ("get", "/v1/apps"), ("get", f"/v1/profiles/{PID}"),
|
||||
("post", "/v1/jobs"), ("get", "/v1/jobs/x")]:
|
||||
response = getattr(anon, method)(path)
|
||||
assert response.status_code == 401
|
||||
assert response.json() == {"detail": "Chave do serviço ausente ou inválida."}
|
||||
wrong = TestClient(env.app, headers={"X-Service-Key": "errada"})
|
||||
assert wrong.get("/v1/status").status_code == 401
|
||||
assert KEY # a chave certa passa (fixture)
|
||||
assert env.client.get("/v1/status").status_code == 200
|
||||
|
||||
|
||||
def test_status_shape(env):
|
||||
body = env.client.get("/v1/status").json()
|
||||
assert body == {"browser": {"found": True, "kind": "chrome", "path": "C:/fake/chrome.exe"}, "worker": "idle", "queue": 0}
|
||||
|
||||
|
||||
def test_apps_never_return_secret(env):
|
||||
apps = env.client.get("/v1/apps").json()
|
||||
assert set(apps) == {"youtube", "tiktok", "instagram"}
|
||||
assert apps["youtube"] == {"configured": False, "clientId": None,
|
||||
"redirectUri": "http://127.0.0.1:4530/oauth/callback/youtube",
|
||||
"notes": apps["youtube"]["notes"]}
|
||||
assert apps["tiktok"]["redirectUri"] == "http://127.0.0.1:4530/oauth/callback/tiktok"
|
||||
assert apps["instagram"]["redirectUri"] == ""
|
||||
|
||||
state = env.client.put("/v1/apps/youtube", json={"clientId": "id.apps.googleusercontent.com", "clientSecret": "s3cr3t"}).json()
|
||||
assert state["configured"] is True and state["clientId"] == "id.apps.googleusercontent.com"
|
||||
assert "s3cr3t" not in env.client.get("/v1/apps").text
|
||||
assert b"s3cr3t" not in env.settings.vault_path.read_bytes() # cofre cifrado em disco
|
||||
|
||||
missing = env.client.put("/v1/apps/tiktok", json={"clientId": "abc", "clientSecret": ""})
|
||||
assert missing.status_code == 400 and "Client Secret" in missing.json()["detail"]
|
||||
assert env.client.put("/v1/apps/instagram", json={"clientId": "123"}).json()["configured"] is True
|
||||
assert env.client.delete("/v1/apps/youtube").json()["configured"] is False
|
||||
assert env.client.put("/v1/apps/vimeo", json={"clientId": "x", "clientSecret": "y"}).status_code == 404
|
||||
|
||||
|
||||
def test_profile_defaults_and_validation(env):
|
||||
profile = env.client.get(f"/v1/profiles/{PID}").json()
|
||||
assert profile == {"profileId": PID, "platform": "youtube", "mode": None, "status": "disconnected",
|
||||
"displayName": None, "handle": None, "connectedAt": None, "expiresAt": None,
|
||||
"lastCheckAt": None, "lastError": None}
|
||||
bad = env.client.get("/v1/profiles/..%2F..%2Fetc--youtube")
|
||||
assert bad.status_code in (400, 404)
|
||||
assert env.client.get("/v1/profiles/canal--vimeo").status_code == 400
|
||||
mismatch = env.client.post(f"/v1/profiles/{PID}/connect", json={"platform": "tiktok", "mode": "official"})
|
||||
assert mismatch.status_code == 400 and "YouTube" in mismatch.json()["detail"]
|
||||
|
||||
|
||||
def test_validation_errors_are_ptbr_strings(env):
|
||||
response = env.client.post(f"/v1/profiles/{PID}/connect", json={"platform": "youtube", "mode": "robô"})
|
||||
assert response.status_code == 422
|
||||
detail = response.json()["detail"]
|
||||
assert isinstance(detail, str) and detail.startswith("Pedido inválido") and "modo" in detail
|
||||
assert "falta o campo" in env.client.post("/v1/jobs", json={}).json()["detail"]
|
||||
|
||||
|
||||
def test_official_connect_requires_app(env):
|
||||
response = env.client.post(f"/v1/profiles/{PID}/connect", json={"platform": "youtube", "mode": "official"})
|
||||
assert response.status_code == 400
|
||||
assert "Apps das redes" in response.json()["detail"]
|
||||
|
||||
|
||||
def test_instagram_official_asks_for_token(env):
|
||||
pid = "canal--instagram"
|
||||
body = env.client.post(f"/v1/profiles/{pid}/connect", json={"platform": "instagram", "mode": "official"}).json()
|
||||
assert body["next"]["kind"] == "paste_token" and "token" in body["next"]["help"]
|
||||
assert body["profile"]["status"] == "connecting" and body["profile"]["mode"] == "official"
|
||||
assert env.client.post(f"/v1/profiles/{PID}/token", json={"accessToken": "x" * 30}).status_code == 400
|
||||
|
||||
|
||||
def test_session_connect_check_and_disconnect(env):
|
||||
pid = "canal--tiktok"
|
||||
body = env.client.post(f"/v1/profiles/{pid}/connect", json={"platform": "tiktok", "mode": "session"}).json()
|
||||
assert body["next"]["kind"] == "browser_opened" and "Já entrei" in body["next"]["help"]
|
||||
assert body["profile"]["status"] == "connecting" and env.runner.opened == [(pid, "tiktok")]
|
||||
|
||||
env.runner.check_reason = "a rede mostrou a tela de login"
|
||||
profile = env.client.post(f"/v1/profiles/{pid}/session/check").json()
|
||||
assert profile["status"] == "needs_login" and "tela de login" in profile["lastError"]
|
||||
assert profile["lastCheckAt"]
|
||||
|
||||
env.runner.check_reason = None
|
||||
profile = env.client.post(f"/v1/profiles/{pid}/session/check").json()
|
||||
assert profile["status"] == "connected" and profile["lastError"] is None and profile["connectedAt"]
|
||||
|
||||
reopened = env.client.post(f"/v1/profiles/{pid}/session/open").json()
|
||||
assert reopened["next"]["kind"] == "browser_opened" and reopened["profile"]["status"] == "connected"
|
||||
|
||||
browser_dir = env.settings.browser_dir / pid
|
||||
browser_dir.mkdir(parents=True)
|
||||
(browser_dir / "Cookies").write_text("x")
|
||||
env.vault.set(f"token:{pid}", {"accessToken": "a"})
|
||||
gone = env.client.delete(f"/v1/profiles/{pid}").json()
|
||||
assert gone["status"] == "disconnected" and gone["mode"] is None
|
||||
assert not browser_dir.exists() and env.vault.get(f"token:{pid}") is None
|
||||
|
||||
|
||||
def test_session_check_requires_session_mode(env):
|
||||
response = env.client.post(f"/v1/profiles/{PID}/session/check")
|
||||
assert response.status_code == 400 and "Sessão logada" in response.json()["detail"]
|
||||
|
||||
|
||||
def test_job_lifecycle_routes(env):
|
||||
env.connect_profile(PID, mode="session")
|
||||
video = env.video()
|
||||
created = env.client.post("/v1/jobs", json=env.job_body(PID, video))
|
||||
assert created.status_code == 201
|
||||
job = created.json()
|
||||
assert set(job) == {"jobId", "profileId", "platform", "status", "step", "progress", "remoteId", "url", "draft",
|
||||
"error", "createdAt", "updatedAt"}
|
||||
assert job["status"] == "queued" and job["progress"] == 0 and job["draft"] is False
|
||||
assert env.client.get(f"/v1/jobs/{job['jobId']}").json()["jobId"] == job["jobId"]
|
||||
assert env.client.get("/v1/status").json()["queue"] == 1
|
||||
canceled = env.client.post(f"/v1/jobs/{job['jobId']}/cancel").json()
|
||||
assert canceled["status"] == "canceled"
|
||||
again = env.client.post(f"/v1/jobs/{job['jobId']}/cancel")
|
||||
assert again.status_code == 409 and "na fila" in again.json()["detail"]
|
||||
assert env.client.get("/v1/jobs/nao-existe").status_code == 404
|
||||
|
||||
|
||||
def test_job_refuses_paths_outside_root(env, tmp_path):
|
||||
env.connect_profile(PID, mode="session")
|
||||
outside = tmp_path / "fora.mp4"
|
||||
outside.write_bytes(b"x" * 10)
|
||||
response = env.client.post("/v1/jobs", json=env.job_body(PID, outside))
|
||||
assert response.status_code == 400 and "pasta de saída do CenaForge" in response.json()["detail"]
|
||||
sneaky = str(env.root / "output" / ".." / ".." / "fora.mp4")
|
||||
assert env.client.post("/v1/jobs", json=env.job_body(PID, sneaky)).status_code == 400
|
||||
relative = env.client.post("/v1/jobs", json=env.job_body(PID, "output/clip.mp4"))
|
||||
assert relative.status_code == 400 and "absoluto" in relative.json()["detail"]
|
||||
video = env.video()
|
||||
bad_cover = env.client.post("/v1/jobs", json=env.job_body(PID, video, cover=str(outside)))
|
||||
assert bad_cover.status_code == 400
|
||||
missing = env.client.post("/v1/jobs", json=env.job_body(PID, str(env.root / "output" / "sumiu.mp4")))
|
||||
assert missing.status_code == 400 and "não existe" in missing.json()["detail"]
|
||||
wrong_ext = env.root / "output" / "a.exe"
|
||||
wrong_ext.write_bytes(b"MZ")
|
||||
assert env.client.post("/v1/jobs", json=env.job_body(PID, wrong_ext)).status_code == 400
|
||||
|
||||
|
||||
def test_job_requires_connected_profile_and_youtube_title(env):
|
||||
video = env.video()
|
||||
response = env.client.post("/v1/jobs", json=env.job_body(PID, video))
|
||||
assert response.status_code == 409 and "não está conectado" in response.json()["detail"]
|
||||
env.connect_profile(PID, mode="session")
|
||||
long_title = env.client.post("/v1/jobs", json=env.job_body(PID, video, title="x" * 101))
|
||||
assert long_title.status_code == 400 and "100" in long_title.json()["detail"]
|
||||
# TikTok/Instagram ignoram o título: não há limite de 100 para eles.
|
||||
env.connect_profile("canal--tiktok", mode="session")
|
||||
ok = env.client.post("/v1/jobs", json=env.job_body("canal--tiktok", video, title="x" * 300))
|
||||
assert ok.status_code == 201
|
||||
@@ -0,0 +1,323 @@
|
||||
"""Navegador do modo sessão: detecção, argumentos (sem burla de detecção), portas e apagar perfil.
|
||||
Nenhum navegador é aberto: o Popen é falso."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from app.config import BROWSER_PORT_RANGE
|
||||
from app.platforms.base import PublishError
|
||||
from app.platforms.session import common
|
||||
from app.platforms.session.browser import BrowserInfo, BrowserManager, detect_browser, launch_args
|
||||
|
||||
|
||||
def _exe(base: Path, *parts: str) -> Path:
|
||||
path = base.joinpath(*parts)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(b"")
|
||||
return path
|
||||
|
||||
|
||||
def test_detect_prefers_chrome_then_edge(tmp_path):
|
||||
env = {"PROGRAMFILES": str(tmp_path / "pf"), "PROGRAMFILES(X86)": str(tmp_path / "pf86"),
|
||||
"LOCALAPPDATA": str(tmp_path / "local")}
|
||||
no_registry = lambda exe: None # noqa: E731
|
||||
edge = _exe(tmp_path / "pf86", "Microsoft", "Edge", "Application", "msedge.exe")
|
||||
assert detect_browser(env=env, registry=no_registry) == BrowserInfo("msedge", str(edge))
|
||||
chrome = _exe(tmp_path / "local", "Google", "Chrome", "Application", "chrome.exe")
|
||||
assert detect_browser(env=env, registry=no_registry) == BrowserInfo("chrome", str(chrome))
|
||||
assert detect_browser(override=str(edge)) == BrowserInfo("msedge", str(edge))
|
||||
assert detect_browser(override=str(tmp_path / "nao-existe.exe")) is None
|
||||
|
||||
|
||||
def test_detect_uses_registry(tmp_path):
|
||||
chrome = _exe(tmp_path, "custom", "chrome.exe")
|
||||
found = detect_browser(env={}, registry=lambda exe: str(chrome) if exe == "chrome.exe" else None)
|
||||
assert found == BrowserInfo("chrome", str(chrome))
|
||||
|
||||
|
||||
def test_launch_args_are_plain_and_visible(tmp_path):
|
||||
args = launch_args(BrowserInfo("chrome", "chrome.exe"), tmp_path / "p", 4541, "https://studio.youtube.com/")
|
||||
assert args[0] == "chrome.exe" and f"--user-data-dir={tmp_path / 'p'}" in args
|
||||
assert "--remote-debugging-port=4541" in args and "--no-first-run" in args
|
||||
joined = " ".join(args).lower()
|
||||
for forbidden in ("headless", "automationcontrolled", "stealth", "enable-automation", "disable-blink-features"):
|
||||
assert forbidden not in joined
|
||||
|
||||
|
||||
class FakeProcess:
|
||||
pid = 1
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.args = args[0]
|
||||
|
||||
def poll(self):
|
||||
return None
|
||||
|
||||
|
||||
def test_open_picks_port_in_range_and_reuses_window(tmp_path, monkeypatch):
|
||||
launched = []
|
||||
manager = BrowserManager(tmp_path / "browser", BrowserInfo("chrome", "chrome.exe"), start_reaper=False,
|
||||
popen=lambda args, **kw: launched.append(args) or FakeProcess(args))
|
||||
monkeypatch.setattr(manager, "_wait_cdp", lambda port, user_dir, process=None: None)
|
||||
monkeypatch.setattr("app.platforms.session.browser.owns_port", lambda user_dir, port, version=None: True)
|
||||
port = manager.open("canal--youtube", "https://x")
|
||||
assert BROWSER_PORT_RANGE[0] <= port <= BROWSER_PORT_RANGE[1]
|
||||
assert manager.open("canal--youtube", "https://x") == port and len(launched) == 1
|
||||
other = manager.open("canal--tiktok", "https://y")
|
||||
assert other != port and (tmp_path / "browser" / "canal--tiktok").is_dir()
|
||||
|
||||
|
||||
def test_open_without_browser_explains(tmp_path):
|
||||
with pytest.raises(PublishError, match="Chrome"):
|
||||
BrowserManager(tmp_path, None).open("canal--youtube", "https://x")
|
||||
|
||||
|
||||
def test_remove_profile_only_inside_browser_dir(tmp_path):
|
||||
manager = BrowserManager(tmp_path / "browser", None)
|
||||
target = tmp_path / "browser" / "canal--youtube"
|
||||
target.mkdir(parents=True)
|
||||
(target / "Cookies").write_text("x")
|
||||
manager.remove_profile("canal--youtube")
|
||||
assert not target.exists()
|
||||
with pytest.raises(PublishError):
|
||||
manager.remove_profile("../fora")
|
||||
|
||||
|
||||
class FakeLocator:
|
||||
def __init__(self, present):
|
||||
self.present = present
|
||||
|
||||
@property
|
||||
def first(self):
|
||||
return self
|
||||
|
||||
def nth(self, i):
|
||||
return self
|
||||
|
||||
def count(self):
|
||||
return 1 if self.present else 0
|
||||
|
||||
def is_visible(self):
|
||||
return self.present
|
||||
|
||||
|
||||
class FakePage:
|
||||
def __init__(self, url, texts=()):
|
||||
self.url, self.texts = url, texts
|
||||
|
||||
def get_by_role(self, role, name):
|
||||
return FakeLocator(any(name.search(t) for t in self.texts))
|
||||
|
||||
def get_by_text(self, pattern):
|
||||
return FakeLocator(any(pattern.search(t) for t in self.texts))
|
||||
|
||||
def get_by_label(self, pattern):
|
||||
return FakeLocator(False)
|
||||
|
||||
def get_by_placeholder(self, pattern):
|
||||
return FakeLocator(False)
|
||||
|
||||
def locator(self, css):
|
||||
return FakeLocator(False)
|
||||
|
||||
|
||||
def test_detect_block_login_and_captcha():
|
||||
assert common.detect_block(FakePage("https://accounts.google.com/v3/signin/identifier")) is not None
|
||||
assert common.detect_block(FakePage("https://www.instagram.com/challenge/123/")) is not None
|
||||
assert "verificação" in common.detect_block(FakePage("https://www.tiktok.com/x", ["Verify it's you"]))
|
||||
login = [("role", "button", r"^(Entrar|Log in)$")]
|
||||
assert "login" in common.detect_block(FakePage("https://www.tiktok.com/tiktokstudio/upload", ["Entrar"]), login)
|
||||
assert common.detect_block(FakePage("https://www.tiktok.com/tiktokstudio/upload", ["Publicar"]), login) is None
|
||||
err = common.needs_login("a rede pediu login")
|
||||
assert err.kind == "needs_login" and "Já entrei" in err.message
|
||||
|
||||
|
||||
class FakeListPage:
|
||||
"""Lista "Publicações" do Studio: o link só aparece depois de algumas leituras (a lista demora a carregar)."""
|
||||
|
||||
def __init__(self, href, ready_after=2, url="https://www.tiktok.com/tiktokstudio/upload"):
|
||||
self.href, self.ready_after, self.url, self.reads, self.visited = href, ready_after, url, 0, []
|
||||
|
||||
def evaluate(self, script, key):
|
||||
self.reads += 1
|
||||
return self.href if self.reads > self.ready_after and key else None
|
||||
|
||||
def goto(self, url, wait_until=None):
|
||||
self.visited.append(url)
|
||||
self.url = url
|
||||
|
||||
|
||||
def test_tiktok_link_waits_for_the_list_and_matches_caption():
|
||||
from app.platforms.session import tiktok_studio
|
||||
|
||||
assert tiktok_studio.caption_key("#corte Ele pediu pra todo mundo só olhar o loot #x @y") == "Ele pediu pra todo mundo"
|
||||
# O vídeo só aparece depois de 7 leituras: a 1ª carga (5 leituras) não vê ⇒ recarrega a lista e acha na 2ª.
|
||||
page = FakeListPage("https://www.tiktok.com/@vortplay/video/7709179978520284437", ready_after=7)
|
||||
steps = []
|
||||
url = tiktok_studio.find_video_url(page, "Ele pediu pra todo mundo só olhar o loot", sleep=lambda s: None,
|
||||
progress=lambda text, p: steps.append(text))
|
||||
assert url.endswith("/video/7709179978520284437")
|
||||
assert page.visited == [tiktok_studio.CONTENT_URL, tiktok_studio.CONTENT_URL] # abriu a lista e recarregou
|
||||
assert "2 de 12" in steps[-1]
|
||||
never = FakeListPage(None, ready_after=0)
|
||||
assert tiktok_studio.find_video_url(never, "outro vídeo", sleep=lambda s: None, attempts=3) is None
|
||||
assert len(never.visited) == 3 # uma carga por tentativa
|
||||
|
||||
|
||||
class TipPage:
|
||||
"""Página com um aviso de novidade ("Entendi") por cima: cliques em outros elementos falham até fechar."""
|
||||
|
||||
def __init__(self):
|
||||
self.tip_open = True
|
||||
self.clicked = []
|
||||
|
||||
def get_by_role(self, role, name):
|
||||
page = self
|
||||
|
||||
class Tip:
|
||||
first = None
|
||||
|
||||
def count(self):
|
||||
return 1 if page.tip_open and name.search("Entendi") else 0
|
||||
|
||||
def is_visible(self):
|
||||
return self.count() > 0
|
||||
|
||||
def nth(self, i):
|
||||
return self
|
||||
|
||||
def click(self, timeout=None):
|
||||
page.tip_open = False
|
||||
page.clicked.append("Entendi")
|
||||
|
||||
tip = Tip()
|
||||
tip.first = tip
|
||||
return tip
|
||||
|
||||
|
||||
class CoveredField:
|
||||
def __init__(self, page):
|
||||
self.page = page
|
||||
|
||||
def click(self, timeout=None):
|
||||
if self.page.tip_open:
|
||||
raise TimeoutError("Locator.click: Timeout 8000ms exceeded")
|
||||
self.page.clicked.append("campo")
|
||||
|
||||
|
||||
def test_click_through_closes_tip_and_retries():
|
||||
page = TipPage()
|
||||
common.click_through(CoveredField(page), sleep=lambda s: None)
|
||||
assert page.clicked == ["Entendi", "campo"]
|
||||
assert common.dismiss_tips(page, sleep=lambda s: None) == 0 # nada mais aberto
|
||||
no_tip = TipPage()
|
||||
no_tip.tip_open = False
|
||||
|
||||
class Broken:
|
||||
page = no_tip
|
||||
|
||||
def click(self, timeout=None):
|
||||
raise TimeoutError("site mudou")
|
||||
|
||||
with pytest.raises(TimeoutError): # sem aviso para fechar: o erro original aparece
|
||||
common.click_through(Broken(), sleep=lambda s: None)
|
||||
|
||||
|
||||
def test_browser_error_text_explains_common_failures():
|
||||
from app.platforms.session.runner import browser_error_text
|
||||
|
||||
assert "aviso do site" in browser_error_text("Locator.click: Timeout 30000ms exceeded")
|
||||
assert "grande demais" in browser_error_text("Cannot transfer files larger than 50Mb to a browser")
|
||||
assert "fechada" in browser_error_text("Target page, context or browser has been closed")
|
||||
assert "travou" in browser_error_text("algo inesperado")
|
||||
|
||||
|
||||
def test_instagram_links_and_hashtag_suggestions():
|
||||
from app.platforms.session import instagram_web as ig
|
||||
|
||||
# A grade do perfil usa /<conta>/reel/<código>/; o link direto, /reel/<código>/.
|
||||
assert ig.MEDIA.search("https://www.instagram.com/vortplay27/reel/DAbC12_x/").group(1) == "DAbC12_x"
|
||||
assert ig.MEDIA.search("https://www.instagram.com/reel/DAbC12_x/").group(1) == "DAbC12_x"
|
||||
assert ig.MEDIA.search("https://www.instagram.com/vortplay27/") is None
|
||||
|
||||
class Keyboard:
|
||||
def __init__(self):
|
||||
self.typed = []
|
||||
|
||||
def insert_text(self, text):
|
||||
self.typed.append(text)
|
||||
|
||||
class Page:
|
||||
keyboard = Keyboard()
|
||||
|
||||
page = Page()
|
||||
# Legenda terminando em #tag: um espaço fecha a lista de sugestões (que trocou "#teste" por "#testemunho").
|
||||
assert ig.close_suggestions(page, "Ensaio #teste", sleep=lambda s: None) is True and page.keyboard.typed == [" "]
|
||||
assert ig.close_suggestions(page, "Ensaio\n\n🎥 Créditos: https://x", sleep=lambda s: None) is False
|
||||
assert ig.close_suggestions(page, "", sleep=lambda s: None) is False
|
||||
|
||||
|
||||
def test_buttons_of_the_flow_are_searched_inside_the_dialog():
|
||||
"""No feed cada post tem um botão "Compartilhar": o do fluxo precisa estar preso ao diálogo de criação."""
|
||||
from app.platforms.session import instagram_web as ig
|
||||
|
||||
for key in ("share", "next"):
|
||||
assert all(c[0] == "css" and "div[role='dialog']" in c[1] for c in ig.SELECTORS[key])
|
||||
|
||||
|
||||
def test_selectors_are_isolated_per_network():
|
||||
from app.platforms.session import instagram_web, tiktok_studio, youtube_studio
|
||||
|
||||
for module in (youtube_studio, tiktok_studio, instagram_web):
|
||||
assert module.SELECTORS["login"] and module.SELECTORS["file_input"]
|
||||
assert "VALIDADOS COM UMA CONTA REAL" in (module.__doc__ or "")
|
||||
|
||||
|
||||
class StudioDone:
|
||||
"""Botão Publicar do Studio: some (caixa fecha) depois de `closes_after` cliques; `enabled` controla o estado."""
|
||||
|
||||
def __init__(self, closes_after=1, enabled=True):
|
||||
self.clicks, self.closes_after, self.enabled = 0, closes_after, enabled
|
||||
self.page = TipPage()
|
||||
self.page.tip_open = False
|
||||
|
||||
def evaluate(self, script):
|
||||
return self.enabled
|
||||
|
||||
def is_visible(self):
|
||||
return self.clicks < self.closes_after
|
||||
|
||||
def click(self, timeout=None):
|
||||
self.clicks += 1
|
||||
|
||||
|
||||
def test_youtube_confirms_when_upload_box_closes_and_retries_once():
|
||||
from app.platforms.session import youtube_studio as yt
|
||||
|
||||
no_dialog = TipPage()
|
||||
no_dialog.tip_open = False
|
||||
no_dialog.get_by_text = lambda pattern: FakeLocator(False)
|
||||
# Caixa fechou depois do 1º clique: publicado, sem 2º clique.
|
||||
done = StudioDone(closes_after=1)
|
||||
done.click()
|
||||
assert yt.confirm_published(no_dialog, done, sleep=lambda s: None) is True and done.clicks == 1
|
||||
# O 1º clique sumiu (caixa continua com o botão liberado): clica de novo UMA vez e confirma.
|
||||
done = StudioDone(closes_after=2)
|
||||
done.click()
|
||||
assert yt.confirm_published(no_dialog, done, sleep=lambda s: None) is True and done.clicks == 2
|
||||
# Nunca fecha: no máximo um clique extra, e devolve False (o painel oferece "Já saiu: informar o link").
|
||||
done = StudioDone(closes_after=99)
|
||||
done.click()
|
||||
assert yt.confirm_published(no_dialog, done, sleep=lambda s: None, checks=20) is False and done.clicks == 2
|
||||
# Botão desativado (vídeo ainda subindo): não clica.
|
||||
done = StudioDone(closes_after=99, enabled=False)
|
||||
assert yt.wait_enabled(done, sleep=lambda s: None, checks=3) is False
|
||||
assert yt.confirm_published(no_dialog, done, sleep=lambda s: None, checks=20) is False and done.clicks == 0
|
||||
# A caixa "Short publicado" confirma mesmo com o botão ainda na tela.
|
||||
shown = TipPage()
|
||||
shown.tip_open = False
|
||||
shown.get_by_text = lambda pattern: FakeLocator(bool(pattern.search("Short publicado")))
|
||||
assert yt.confirm_published(shown, StudioDone(closes_after=99), sleep=lambda s: None) is True
|
||||
@@ -0,0 +1,333 @@
|
||||
"""Correções das revisões: idempotência por clientRef, pastas permitidas, janela/porta CDP do modo sessão,
|
||||
capturas de tela, permissões (icacls) e PKCE fora do disco."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from app import acl
|
||||
from app.db import Database
|
||||
from app.paths import IMAGE_EXT, VIDEO_EXT, PathRefused, inside_root
|
||||
from app.platforms.base import JobSpec, PublishError, PublishResult
|
||||
from app.platforms.session import common, runner as runner_mod
|
||||
from app.platforms.session.browser import BrowserInfo, BrowserManager, _Window, owns_port
|
||||
|
||||
PID = "canal--youtube"
|
||||
|
||||
|
||||
# ---------- 1. idempotência
|
||||
|
||||
def test_client_ref_returns_existing_job(env):
|
||||
env.connect_profile(PID, mode="session")
|
||||
video = env.video()
|
||||
first = env.client.post("/v1/jobs", json=env.job_body(PID, video, clientRef="painel-42"))
|
||||
assert first.status_code == 201
|
||||
# Mesmo clientRef: 200 com o MESMO job, sem revalidar (o arquivo pode até ter sumido e o perfil caído).
|
||||
video.unlink()
|
||||
env.publisher._update(PID, status="needs_login")
|
||||
again = env.client.post("/v1/jobs", json=env.job_body(PID, video, clientRef="painel-42", title="outro"))
|
||||
assert again.status_code == 200 and again.json()["jobId"] == first.json()["jobId"]
|
||||
assert env.db.get("SELECT COUNT(*) AS n FROM jobs")["n"] == 1
|
||||
# Sem clientRef: comportamento antigo (valida e cria)
|
||||
env.publisher._update(PID, status="connected")
|
||||
other = env.client.post("/v1/jobs", json=env.job_body(PID, env.video()))
|
||||
assert other.status_code == 201 and other.json()["jobId"] != first.json()["jobId"]
|
||||
assert env.client.post("/v1/jobs", json=env.job_body(PID, env.video(), clientRef="x" * 81)).status_code == 422
|
||||
|
||||
|
||||
def test_client_ref_column_is_unique(env):
|
||||
env.db.run("INSERT INTO jobs (job_id, profile_id, platform, input_json, status, created_at, updated_at, client_ref) "
|
||||
"VALUES ('a', 'p', 'youtube', '{}', 'queued', 'x', 'x', 'r1')")
|
||||
with pytest.raises(Exception):
|
||||
env.db.run("INSERT INTO jobs (job_id, profile_id, platform, input_json, status, created_at, updated_at, client_ref) "
|
||||
"VALUES ('b', 'p', 'youtube', '{}', 'queued', 'x', 'x', 'r1')")
|
||||
assert env.db.get("PRAGMA user_version")["user_version"] == 2
|
||||
|
||||
|
||||
def test_migration_from_v1_keeps_jobs(tmp_path):
|
||||
import sqlite3
|
||||
|
||||
from app.db import SCHEMA, _split
|
||||
|
||||
path = tmp_path / "old.db"
|
||||
conn = sqlite3.connect(path)
|
||||
for statement in _split(SCHEMA[0]):
|
||||
conn.execute(statement)
|
||||
conn.execute("PRAGMA user_version = 1")
|
||||
conn.execute("INSERT INTO jobs (job_id, profile_id, platform, input_json, status, created_at, updated_at) "
|
||||
"VALUES ('j', 'p', 'youtube', '{}', 'done', 'x', 'x')")
|
||||
conn.execute("INSERT INTO oauth_states VALUES ('s', 'youtube', 'p', 'verificador-em-claro', 0, 9e12, 0)")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
db = Database(path)
|
||||
try:
|
||||
assert db.get("SELECT client_ref FROM jobs WHERE job_id = 'j'") == {"client_ref": None}
|
||||
assert db.get("SELECT verifier FROM oauth_states")["verifier"] == ""
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
# ---------- 4. só pastas de saída
|
||||
|
||||
def _file(root: Path, *parts: str) -> Path:
|
||||
path = root.joinpath(*parts)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(b"x")
|
||||
return path
|
||||
|
||||
|
||||
def test_paths_only_output_folders(tmp_path):
|
||||
root = tmp_path / "repo"
|
||||
for folder in ("output/clipper", "output/documentary", "stories/minha", "assets/library"):
|
||||
assert inside_root(str(_file(root, folder, "v.mp4")), root, VIDEO_EXT, "vídeo").is_file()
|
||||
assert inside_root(str(_file(root, "assets", "capa.png")), root, IMAGE_EXT, "capa")
|
||||
for bad in (("data", "publisher", "v.mp4"), ("data", "clipper", "v.mp4"), ("panel", "v.mp4"), ("v.mp4",),
|
||||
("outputx", "v.mp4")):
|
||||
with pytest.raises(PathRefused):
|
||||
inside_root(str(_file(root, *bad)), root, VIDEO_EXT, "vídeo")
|
||||
with pytest.raises(PathRefused, match="data/"):
|
||||
inside_root(str(_file(root, "data", "publisher", "vault.png")), root, IMAGE_EXT, "capa")
|
||||
# ".." não escapa para data/
|
||||
sneaky = os.path.join(str(root), "output", "..", "data", "publisher", "v.mp4")
|
||||
with pytest.raises(PathRefused):
|
||||
inside_root(sneaky, root, VIDEO_EXT, "vídeo")
|
||||
|
||||
|
||||
def test_job_route_refuses_data_folder(env):
|
||||
env.connect_profile(PID, mode="session")
|
||||
inside_data = _file(env.root, "data", "publisher", "x.mp4")
|
||||
response = env.client.post("/v1/jobs", json=env.job_body(PID, inside_data))
|
||||
assert response.status_code == 400 and "data/" in response.json()["detail"]
|
||||
|
||||
|
||||
# ---------- 6. PKCE fora do disco
|
||||
|
||||
def test_restart_mid_oauth_asks_to_connect_again(env):
|
||||
env.client.put("/v1/apps/youtube", json={"clientId": "id", "clientSecret": "s"})
|
||||
body = env.client.post(f"/v1/profiles/{PID}/connect", json={"platform": "youtube", "mode": "official"}).json()
|
||||
state = body["next"]["url"].split("state=")[1].split("&")[0]
|
||||
env.publisher._verifiers.clear() # "reiniciou"
|
||||
from fastapi.testclient import TestClient
|
||||
page = TestClient(env.app).get(f"/oauth/callback/youtube?state={state}&code=c")
|
||||
assert page.status_code == 400 and "reiniciado" in page.text
|
||||
|
||||
|
||||
# ---------- 5. capturas de tela
|
||||
|
||||
class ShotPage:
|
||||
def __init__(self, url="https://studio.youtube.com/x"):
|
||||
self.url = url
|
||||
self.calls = []
|
||||
|
||||
def screenshot(self, **kwargs):
|
||||
self.calls.append(kwargs)
|
||||
Path(kwargs["path"]).write_bytes(b"png")
|
||||
|
||||
# o detect_block olha a página; aqui nada bloqueia
|
||||
def get_by_role(self, *a, **k):
|
||||
return _Absent()
|
||||
|
||||
get_by_text = get_by_label = get_by_placeholder = locator = get_by_role
|
||||
|
||||
|
||||
class _Absent:
|
||||
first = property(lambda self: self)
|
||||
|
||||
def count(self):
|
||||
return 0
|
||||
|
||||
|
||||
def test_screenshot_is_viewport_only_and_skips_login(tmp_path):
|
||||
page = ShotPage()
|
||||
shot = common.screenshot(page, tmp_path, "falha")
|
||||
assert shot and shot.is_file() and page.calls[0]["full_page"] is False
|
||||
login = ShotPage("https://accounts.google.com/v3/signin/identifier")
|
||||
assert common.screenshot(login, tmp_path, "login") is None and login.calls == []
|
||||
|
||||
|
||||
def test_prune_old_screenshots(tmp_path):
|
||||
old, new = tmp_path / "velha.png", tmp_path / "nova.png"
|
||||
old.write_bytes(b"x")
|
||||
new.write_bytes(b"x")
|
||||
eight_days = time.time() - 8 * 86400
|
||||
os.utime(old, (eight_days, eight_days))
|
||||
assert common.prune_screenshots(tmp_path) == 1
|
||||
assert not old.exists() and new.exists()
|
||||
assert common.prune_screenshots(tmp_path / "nao-existe") == 0
|
||||
|
||||
|
||||
# ---------- 2. janela/porta CDP
|
||||
|
||||
def _devtools(user_dir: Path, port: int, browser_id: str = "abc") -> None:
|
||||
user_dir.mkdir(parents=True, exist_ok=True)
|
||||
(user_dir / "DevToolsActivePort").write_text(f"{port}\n/devtools/browser/{browser_id}\n", encoding="utf-8")
|
||||
|
||||
|
||||
def test_owns_port_checks_profile_file_and_browser_id(tmp_path, monkeypatch):
|
||||
ours = {"Browser": "Chrome/150", "webSocketDebuggerUrl": "ws://127.0.0.1:4541/devtools/browser/abc"}
|
||||
_devtools(tmp_path, 4541)
|
||||
assert owns_port(tmp_path, 4541, ours)
|
||||
assert not owns_port(tmp_path, 4542, ours) # arquivo aponta para outra porta
|
||||
other = {"Browser": "Chrome/150", "webSocketDebuggerUrl": "ws://127.0.0.1:4541/devtools/browser/zzz"}
|
||||
assert not owns_port(tmp_path, 4541, other) # outro navegador na mesma porta
|
||||
assert not owns_port(tmp_path / "vazio", 4541, ours) # perfil sem DevToolsActivePort
|
||||
monkeypatch.setattr("app.platforms.session.browser.cdp_version", lambda port: None)
|
||||
assert not owns_port(tmp_path, 4541) # porta não responde
|
||||
|
||||
|
||||
def test_owns_port_without_devtools_file_uses_window_mark(tmp_path, monkeypatch):
|
||||
"""Chrome 157+ com porta fixa não grava DevToolsActivePort: vale a marca do Publicador + o PID que escuta."""
|
||||
from app.platforms.session import browser as browser_module
|
||||
|
||||
ours = {"Browser": "Chrome/157", "webSocketDebuggerUrl": "ws://127.0.0.1:4540/devtools/browser/abc"}
|
||||
browser_module.write_window_mark(tmp_path, 777, 4540)
|
||||
monkeypatch.setattr(browser_module, "listener_pid", lambda port: 777 if port == 4540 else None)
|
||||
monkeypatch.setattr(browser_module, "process_exe_name", lambda pid: "chrome.exe")
|
||||
assert owns_port(tmp_path, 4540, ours)
|
||||
assert browser_module.active_port(tmp_path) == 4540
|
||||
assert not owns_port(tmp_path, 4541, ours) # a marca aponta para outra porta
|
||||
monkeypatch.setattr(browser_module, "listener_pid", lambda port: 999)
|
||||
assert not owns_port(tmp_path, 4540, ours) # outro processo escutando na porta
|
||||
monkeypatch.setattr(browser_module, "listener_pid", lambda port: 777)
|
||||
monkeypatch.setattr(browser_module, "process_exe_name", lambda pid: "python.exe")
|
||||
assert not owns_port(tmp_path, 4540, ours) # PID reaproveitado por outro programa
|
||||
assert not owns_port(tmp_path / "vazio", 4540, ours) # perfil sem marca nem DevToolsActivePort
|
||||
|
||||
|
||||
def test_wait_cdp_explains_when_profile_window_is_already_open(tmp_path, monkeypatch):
|
||||
manager = BrowserManager(tmp_path, BrowserInfo("chrome", "chrome.exe"), start_reaper=False)
|
||||
monkeypatch.setattr("app.platforms.session.browser.owns_port", lambda user_dir, port, version=None: False)
|
||||
exited = AliveProcess()
|
||||
exited.exited = True # o Chrome entregou a URL para a janela que já estava aberta e saiu
|
||||
with pytest.raises(PublishError, match="Já existe uma janela"):
|
||||
manager._wait_cdp(4540, tmp_path, exited, timeout_s=2)
|
||||
|
||||
|
||||
class AliveProcess:
|
||||
pid = 1
|
||||
|
||||
def __init__(self):
|
||||
self.exited = False
|
||||
|
||||
def poll(self):
|
||||
return 0 if self.exited else None
|
||||
|
||||
def wait(self, timeout=None):
|
||||
self.exited = True
|
||||
return 0
|
||||
|
||||
|
||||
def test_open_refuses_port_that_is_not_ours(tmp_path, monkeypatch):
|
||||
manager = BrowserManager(tmp_path, BrowserInfo("chrome", "chrome.exe"), start_reaper=False)
|
||||
manager._windows["canal--youtube"] = _Window(AliveProcess(), 4541, tmp_path / "canal--youtube")
|
||||
monkeypatch.setattr("app.platforms.session.browser.owns_port", lambda user_dir, port, version=None: False)
|
||||
with pytest.raises(PublishError, match="não responde como o nosso navegador"):
|
||||
manager.open("canal--youtube", "https://x")
|
||||
|
||||
|
||||
def test_idle_windows_are_closed(tmp_path, monkeypatch):
|
||||
manager = BrowserManager(tmp_path, BrowserInfo("chrome", "chrome.exe"), start_reaper=False)
|
||||
closed = []
|
||||
monkeypatch.setattr(manager, "close", lambda pid, graceful=True: closed.append(pid) or manager._windows.pop(pid))
|
||||
now = time.time()
|
||||
manager._windows["a--youtube"] = _Window(AliveProcess(), 4540, tmp_path / "a", 300, now - 301)
|
||||
manager._windows["b--youtube"] = _Window(AliveProcess(), 4541, tmp_path / "b", 900, now - 301) # login: 15 min
|
||||
manager._windows["c--youtube"] = _Window(AliveProcess(), 4542, tmp_path / "c", 300, now - 999)
|
||||
with manager.in_use("c--youtube"):
|
||||
assert manager.close_idle(now) == ["a--youtube"] # c está ocupado; b ainda no prazo do login
|
||||
assert closed == ["a--youtube"]
|
||||
|
||||
|
||||
class FakeBrowsers:
|
||||
def __init__(self):
|
||||
self.closed, self.opened = [], []
|
||||
|
||||
def open(self, profile_id, url, for_login=False):
|
||||
self.opened.append((profile_id, for_login))
|
||||
return 4541
|
||||
|
||||
def is_open(self, profile_id):
|
||||
return False
|
||||
|
||||
def close(self, profile_id, graceful=True):
|
||||
self.closed.append(profile_id)
|
||||
|
||||
def in_use(self, profile_id):
|
||||
from contextlib import nullcontext
|
||||
return nullcontext()
|
||||
|
||||
|
||||
def _runner(tmp_path, monkeypatch, outcome):
|
||||
browsers = FakeBrowsers()
|
||||
runner = runner_mod.SessionRunner(browsers, tmp_path, sleep=lambda s: None) # type: ignore[arg-type]
|
||||
|
||||
def fake_with_page(port, fn, keep_page, label):
|
||||
fn(object())
|
||||
|
||||
monkeypatch.setattr(runner, "_with_page", fake_with_page)
|
||||
fake = runner_mod.Uploader(PID.split("--")[1], "https://x", lambda page, sleep: outcome.get("reason"),
|
||||
lambda page, spec, progress, sleep: outcome["upload"]())
|
||||
monkeypatch.setitem(runner_mod.UPLOADERS, "youtube", fake)
|
||||
return runner, browsers
|
||||
|
||||
|
||||
def test_window_closes_after_successful_check_but_not_when_login_missing(tmp_path, monkeypatch):
|
||||
runner, browsers = _runner(tmp_path, monkeypatch, {"reason": None})
|
||||
assert runner.check(PID, "youtube") is None and browsers.closed == [PID]
|
||||
assert browsers.opened == [(PID, True)]
|
||||
runner, browsers = _runner(tmp_path, monkeypatch, {"reason": "tela de login"})
|
||||
assert runner.check(PID, "youtube") == "tela de login" and browsers.closed == []
|
||||
|
||||
|
||||
def test_window_closes_after_each_publish(tmp_path, monkeypatch):
|
||||
spec = JobSpec("j", PID, "youtube", Path("v.mp4"), None, "t", "c")
|
||||
runner, browsers = _runner(tmp_path, monkeypatch, {"upload": lambda: PublishResult("1", None)})
|
||||
assert runner.publish(spec, lambda s, p: None).remote_id == "1" and browsers.closed == [PID]
|
||||
|
||||
def fail():
|
||||
raise PublishError("Não achei o botão.")
|
||||
|
||||
runner, browsers = _runner(tmp_path, monkeypatch, {"upload": fail})
|
||||
with pytest.raises(PublishError):
|
||||
runner.publish(spec, lambda s, p: None)
|
||||
assert browsers.closed == [PID]
|
||||
|
||||
def login():
|
||||
raise PublishError("entre de novo", "needs_login")
|
||||
|
||||
runner, browsers = _runner(tmp_path, monkeypatch, {"upload": login})
|
||||
with pytest.raises(PublishError):
|
||||
runner.publish(spec, lambda s, p: None)
|
||||
assert browsers.closed == [] # fica aberta para o usuário entrar (o fechamento por ociosidade cuida depois)
|
||||
|
||||
|
||||
# ---------- 3. permissões
|
||||
|
||||
def test_icacls_args():
|
||||
assert acl.icacls_args(Path("C:/x"), "S-1-5-21-1", True) == [
|
||||
"icacls", str(Path("C:/x")), "/inheritance:r", "/grant:r", "*S-1-5-21-1:(OI)(CI)F"]
|
||||
assert acl.icacls_args(Path("C:/x/.env"), "S-1-5-21-1", False)[-1] == "*S-1-5-21-1:F"
|
||||
|
||||
|
||||
def test_restrict_uses_current_user(tmp_path, monkeypatch):
|
||||
calls = []
|
||||
|
||||
class Done:
|
||||
returncode = 0
|
||||
stdout = stderr = ""
|
||||
|
||||
monkeypatch.setattr(acl, "current_user_sid", lambda: "S-1-5-21-9")
|
||||
assert acl.restrict_to_current_user(tmp_path, run=lambda args, **kw: calls.append(args) or Done())
|
||||
assert calls == [["icacls", str(tmp_path), "/inheritance:r", "/grant:r", "*S-1-5-21-9:(OI)(CI)F"]]
|
||||
monkeypatch.setattr(acl, "current_user_sid", lambda: None)
|
||||
assert acl.restrict_to_current_user(tmp_path) is False
|
||||
|
||||
|
||||
def test_text_has_no_human_mimicry_wording():
|
||||
root = Path(__file__).resolve().parent.parent
|
||||
for path in list((root / "app").rglob("*.py")) + [root / "README.md"]:
|
||||
assert "ritmo humano" not in path.read_text(encoding="utf-8"), path
|
||||
@@ -0,0 +1,157 @@
|
||||
"""OAuth: state de uso único com validade, PKCE (base64url no Google, HEX no TikTok), troca do code e refresh."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import time
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
import httpx
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.platforms.base import challenge_s256_base64url, challenge_s256_hex, make_verifier
|
||||
|
||||
YT = "canal--youtube"
|
||||
TT = "canal--tiktok"
|
||||
|
||||
|
||||
def _configure(env, platform):
|
||||
env.client.put(f"/v1/apps/{platform}", json={"clientId": f"{platform}-id", "clientSecret": f"{platform}-secret"})
|
||||
|
||||
|
||||
def _connect(env, pid, platform):
|
||||
body = env.client.post(f"/v1/profiles/{pid}/connect", json={"platform": platform, "mode": "official"}).json()
|
||||
assert body["next"]["kind"] == "open_url"
|
||||
return parse_qs(urlparse(body["next"]["url"]).query), body
|
||||
|
||||
|
||||
def test_pkce_helpers():
|
||||
verifier = make_verifier()
|
||||
assert 43 <= len(verifier) <= 128
|
||||
digest = hashlib.sha256(verifier.encode()).digest()
|
||||
assert challenge_s256_hex(verifier) == digest.hex()
|
||||
assert len(challenge_s256_hex(verifier)) == 64 and all(c in "0123456789abcdef" for c in challenge_s256_hex(verifier))
|
||||
assert challenge_s256_base64url(verifier) == base64.urlsafe_b64encode(digest).rstrip(b"=").decode()
|
||||
|
||||
|
||||
def test_youtube_full_flow(env):
|
||||
_configure(env, "youtube")
|
||||
query, body = _connect(env, YT, "youtube")
|
||||
assert body["profile"]["status"] == "connecting"
|
||||
assert query["redirect_uri"] == ["http://127.0.0.1:4530/oauth/callback/youtube"]
|
||||
assert query["code_challenge_method"] == ["S256"] and query["access_type"] == ["offline"]
|
||||
assert "youtube.upload" in query["scope"][0]
|
||||
state = query["state"][0]
|
||||
assert env.db.get("SELECT verifier FROM oauth_states WHERE state = ?", state)["verifier"] == "" # nunca no disco
|
||||
verifier = env.publisher._verifiers[state]
|
||||
assert query["code_challenge"] == [challenge_s256_base64url(verifier)]
|
||||
|
||||
env.router.add("POST", "https://oauth2.googleapis.com/token",
|
||||
{"access_token": "ya29.a", "expires_in": 3599, "refresh_token": "1//r"})
|
||||
env.router.add("GET", "https://www.googleapis.com/youtube/v3/channels",
|
||||
{"items": [{"id": "UC1", "snippet": {"title": "Histórias do Litoral", "customUrl": "@litoral"}}]})
|
||||
browser = TestClient(env.app) # o navegador do usuário não manda a chave do serviço
|
||||
page = browser.get(f"/oauth/callback/youtube?state={state}&code=4/abc")
|
||||
assert page.status_code == 200 and 'lang="pt-BR"' in page.text
|
||||
assert "Pode fechar esta aba e voltar ao painel." in page.text and "@litoral" in page.text
|
||||
|
||||
sent = parse_qs(env.router.find("POST", "https://oauth2.googleapis.com/token")[0].content.decode())
|
||||
assert sent["code_verifier"] == [verifier] and sent["grant_type"] == ["authorization_code"]
|
||||
assert sent["client_secret"] == ["youtube-secret"]
|
||||
profile = env.client.get(f"/v1/profiles/{YT}").json()
|
||||
assert profile["status"] == "connected" and profile["handle"] == "@litoral"
|
||||
assert profile["displayName"] == "Histórias do Litoral" and profile["expiresAt"] is None
|
||||
assert env.vault.get(f"token:{YT}")["refreshToken"] == "1//r"
|
||||
|
||||
# uso único
|
||||
again = browser.get(f"/oauth/callback/youtube?state={state}&code=4/abc")
|
||||
assert again.status_code == 400 and "já foi usado" in again.text
|
||||
|
||||
|
||||
def test_state_expired_wrong_platform_and_denied(env):
|
||||
_configure(env, "youtube")
|
||||
query, _ = _connect(env, YT, "youtube")
|
||||
state = query["state"][0]
|
||||
browser = TestClient(env.app)
|
||||
assert "não é válido" in browser.get(f"/oauth/callback/tiktok?state={state}&code=x").text
|
||||
assert "não é válido" in browser.get("/oauth/callback/youtube?state=inventado&code=x").text
|
||||
env.db.run("UPDATE oauth_states SET expires_at = ? WHERE state = ?", time.time() - 1, state)
|
||||
expired = browser.get(f"/oauth/callback/youtube?state={state}&code=x")
|
||||
assert expired.status_code == 400 and "expirou" in expired.text
|
||||
|
||||
query, _ = _connect(env, YT, "youtube")
|
||||
denied = browser.get(f"/oauth/callback/youtube?state={query['state'][0]}&error=access_denied")
|
||||
assert denied.status_code == 400 and "não autorizou" in denied.text
|
||||
assert env.client.get(f"/v1/profiles/{YT}").json()["status"] == "error"
|
||||
|
||||
|
||||
def test_google_invalid_grant_marks_error(env):
|
||||
_configure(env, "youtube")
|
||||
query, _ = _connect(env, YT, "youtube")
|
||||
env.router.add("POST", "https://oauth2.googleapis.com/token",
|
||||
lambda r: httpx.Response(400, json={"error": "invalid_grant"}))
|
||||
page = TestClient(env.app).get(f"/oauth/callback/youtube?state={query['state'][0]}&code=x")
|
||||
assert page.status_code == 400 and "In production" in page.text
|
||||
|
||||
|
||||
def test_tiktok_hex_challenge_and_callback(env):
|
||||
_configure(env, "tiktok")
|
||||
query, _ = _connect(env, TT, "tiktok")
|
||||
assert query["client_key"] == ["tiktok-id"]
|
||||
assert query["scope"] == ["user.info.basic,video.upload,video.publish"]
|
||||
assert query["redirect_uri"] == ["http://127.0.0.1:4530/oauth/callback/tiktok"]
|
||||
state = query["state"][0]
|
||||
assert env.db.get("SELECT verifier FROM oauth_states WHERE state = ?", state)["verifier"] == "" # nunca no disco
|
||||
verifier = env.publisher._verifiers[state]
|
||||
assert query["code_challenge"] == [hashlib.sha256(verifier.encode()).hexdigest()]
|
||||
|
||||
env.router.add("POST", "https://open.tiktokapis.com/v2/oauth/token/", {
|
||||
"access_token": "act.1", "expires_in": 7200, "open_id": "o1", "refresh_token": "rft.1",
|
||||
"refresh_expires_in": 15552000, "scope": "user.info.basic,video.upload,video.publish", "token_type": "Bearer"})
|
||||
env.router.add("GET", "https://open.tiktokapis.com/v2/user/info/", {"data": {"user": {"display_name": "Litoral"}}})
|
||||
env.router.add("POST", "https://open.tiktokapis.com/v2/post/publish/creator_info/query/",
|
||||
{"data": {"creator_username": "litoral", "creator_nickname": "Litoral"}, "error": {"code": "ok"}})
|
||||
page = TestClient(env.app).get(f"/oauth/callback/tiktok?state={state}&code=c*1!")
|
||||
assert page.status_code == 200, page.text
|
||||
sent = parse_qs(env.router.find("POST", "https://open.tiktokapis.com/v2/oauth/token/")[0].content.decode())
|
||||
assert sent["code_verifier"] == [verifier] and sent["client_key"] == ["tiktok-id"] and sent["code"] == ["c*1!"]
|
||||
profile = env.client.get(f"/v1/profiles/{TT}").json()
|
||||
assert profile["status"] == "connected" and profile["handle"] == "@litoral" and profile["expiresAt"]
|
||||
|
||||
|
||||
def test_tiktok_refresh_is_rotated_and_saved(env):
|
||||
_configure(env, "tiktok")
|
||||
env.connect_profile(TT, secret={"accessToken": "old", "accessExpiresAt": time.time() - 10,
|
||||
"refreshToken": "rft.old", "refreshExpiresAt": time.time() + 1000})
|
||||
env.router.add("POST", "https://open.tiktokapis.com/v2/oauth/token/", {
|
||||
"access_token": "act.new", "expires_in": 7200, "open_id": "o1", "refresh_token": "rft.new",
|
||||
"refresh_expires_in": 15552000})
|
||||
token = env.publisher._token_provider(TT, "tiktok")(False)
|
||||
assert token == "act.new"
|
||||
sent = parse_qs(env.router.requests[-1].content.decode())
|
||||
assert sent["grant_type"] == ["refresh_token"] and sent["refresh_token"] == ["rft.old"]
|
||||
saved = env.vault.get(f"token:{TT}")
|
||||
assert saved["refreshToken"] == "rft.new" and saved["accessToken"] == "act.new"
|
||||
# access ainda válido: não renova de novo
|
||||
assert env.publisher._token_provider(TT, "tiktok")(False) == "act.new"
|
||||
assert len(env.router.requests) == 1
|
||||
|
||||
|
||||
def test_expired_refresh_marks_profile_expired(env):
|
||||
_configure(env, "tiktok")
|
||||
env.connect_profile(TT, secret={"accessToken": "old", "accessExpiresAt": 0, "refreshToken": "r",
|
||||
"refreshExpiresAt": time.time() - 1}, expires_at="2020-01-01T00:00:00Z")
|
||||
assert env.client.get(f"/v1/profiles/{TT}").json()["status"] == "expired"
|
||||
|
||||
|
||||
def test_youtube_refresh_invalid_grant_is_expired(env):
|
||||
_configure(env, "youtube")
|
||||
env.connect_profile(YT, secret={"accessToken": "a", "accessExpiresAt": 0, "refreshToken": "r"})
|
||||
env.router.add("POST", "https://oauth2.googleapis.com/token", lambda r: httpx.Response(400, json={"error": "invalid_grant"}))
|
||||
video = env.video()
|
||||
env.client.post("/v1/jobs", json=env.job_body(YT, video))
|
||||
env.worker.run_once()
|
||||
job = env.db.get("SELECT * FROM jobs")
|
||||
assert job["status"] == "needs_login" and "Conecte o YouTube de novo" in job["error"]
|
||||
assert env.client.get(f"/v1/profiles/{YT}").json()["status"] == "expired"
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Números dos posts (dashboard): leitura de contagens, YouTube público, linha do TikTok Studio e API do Instagram."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.platforms.session import stats as session_stats
|
||||
from app.platforms.stats import parse_count, youtube_from_html
|
||||
|
||||
|
||||
def test_parse_count_reads_how_networks_show_numbers():
|
||||
assert parse_count("1.499") == 1499 and parse_count("1,499") == 1499 and parse_count("31") == 31
|
||||
assert parse_count("1,2 mil") == 1200 and parse_count("5,2\xa0mil") == 5200 and parse_count("1.2K") == 1200
|
||||
assert parse_count("3,4 mi") == 3_400_000 and parse_count("3.4M") == 3_400_000 and parse_count("0") == 0
|
||||
assert parse_count("Todos") is None and parse_count("") is None and parse_count("17 de nov, 15:50") is None
|
||||
|
||||
|
||||
def test_youtube_public_page():
|
||||
html = '..."videoDetails":{"viewCount":"1234"}..."likeCount":"56"..."contextualInfo":{"runs":[{"text":"7"}]}'
|
||||
stats = youtube_from_html("abc123", html)
|
||||
assert (stats.views, stats.likes, stats.comments) == (1234, 56, 7)
|
||||
assert youtube_from_html("abc123", "<html>consent</html>") is None
|
||||
|
||||
|
||||
def test_tiktok_studio_row():
|
||||
# Texto real de uma linha do Studio (17/11/2026).
|
||||
text = ("00:26\nA conversa sobre descanso vira... #skipnho 🎥 Créditos: https://twitch.tv/skipnho\n17 de nov, 15:50\n"
|
||||
"Todos\n2\n1\n0")
|
||||
stats = session_stats.tiktok_row_stats("https://www.tiktok.com/@vortplay/video/7709214727859146005", text)
|
||||
assert (stats.remote_id, stats.views, stats.likes, stats.comments) == ("7709214727859146005", 2, 1, 0)
|
||||
assert session_stats.tiktok_row_stats("https://www.tiktok.com/@vortplay/video/1", "Processando\nTodos") is None
|
||||
|
||||
|
||||
def test_instagram_graphql_media():
|
||||
payload = {"data": {"edges": [{"node": {"media": {"code": "Df2gT_ztuds", "play_count": 1499, "view_count": None,
|
||||
"like_count": 25, "comment_count": 1}}},
|
||||
{"node": {"media": {"code": "Df2m7MGNR0T", "play_count": 31, "like_count": 2,
|
||||
"comment_count": 0}}},
|
||||
{"node": {"code": "semNumero"}}]}}
|
||||
found = {}
|
||||
session_stats.instagram_media(payload, found)
|
||||
assert set(found) == {"Df2gT_ztuds", "Df2m7MGNR0T"}
|
||||
assert (found["Df2gT_ztuds"].views, found["Df2gT_ztuds"].likes, found["Df2gT_ztuds"].comments) == (1499, 25, 1)
|
||||
@@ -0,0 +1,271 @@
|
||||
"""Montagem das requisições de envio de cada API (rede simulada com httpx.MockTransport)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from urllib.parse import parse_qs
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from app.platforms import tiktok_api, youtube_api
|
||||
from app.platforms.base import PublishError
|
||||
from app.platforms.instagram_api import InstagramApi
|
||||
from app.platforms.tiktok_api import UNAUDITED, chunk_plan
|
||||
|
||||
YT, TT, IG = "canal--youtube", "canal--tiktok", "canal--instagram"
|
||||
VALID = {"accessToken": "tok", "accessExpiresAt": time.time() + 3600, "refreshToken": "r",
|
||||
"refreshExpiresAt": time.time() + 10_000_000}
|
||||
|
||||
|
||||
def _run(env, pid, **extra):
|
||||
video = env.video(size=1000)
|
||||
response = env.client.post("/v1/jobs", json=env.job_body(pid, video, **extra))
|
||||
assert response.status_code == 201, response.text
|
||||
assert env.worker.run_once()
|
||||
return env.client.get(f"/v1/jobs/{response.json()['jobId']}").json()
|
||||
|
||||
|
||||
# ---------- YouTube
|
||||
|
||||
def _youtube(env):
|
||||
env.client.put("/v1/apps/youtube", json={"clientId": "id", "clientSecret": "sec"})
|
||||
env.connect_profile(YT, secret=dict(VALID))
|
||||
|
||||
|
||||
def test_youtube_resumable_upload_in_chunks(env, monkeypatch):
|
||||
_youtube(env)
|
||||
monkeypatch.setattr(youtube_api, "CHUNK", 400)
|
||||
env.router.add("POST", "https://www.googleapis.com/upload/youtube/v3/videos",
|
||||
lambda r: httpx.Response(200, headers={"Location": "https://upload.example/session/1"}))
|
||||
ranges = iter(["bytes=0-399", "bytes=0-799"])
|
||||
|
||||
def put(request):
|
||||
if request.headers["content-range"].endswith("999/1000"):
|
||||
return httpx.Response(201, json={"id": "VID123"})
|
||||
return httpx.Response(308, headers={"Range": next(ranges)})
|
||||
|
||||
env.router.add("PUT", "https://upload.example/session/1", put)
|
||||
job = _run(env, YT, aiGenerated=True, tags=["#cortes", "live, top"], title="Título <legal>")
|
||||
assert job["status"] == "done", job
|
||||
assert job["remoteId"] == "VID123" and job["url"] == "https://youtu.be/VID123" and job["progress"] == 1
|
||||
|
||||
start = env.router.find("POST", "https://www.googleapis.com/upload/youtube/v3/videos")[0]
|
||||
assert parse_qs(start.url.query.decode()) == {"uploadType": ["resumable"], "part": ["snippet,status"]}
|
||||
assert start.headers["authorization"] == "Bearer tok"
|
||||
assert start.headers["x-upload-content-length"] == "1000"
|
||||
body = json.loads(start.content)
|
||||
assert body["status"] == {"privacyStatus": "public", "selfDeclaredMadeForKids": False, "containsSyntheticMedia": True}
|
||||
assert body["snippet"]["title"] == "Título ‹legal›" and body["snippet"]["tags"] == ["cortes", "live top"]
|
||||
puts = env.router.find("PUT", "https://upload.example/session/1")
|
||||
assert [p.headers["content-range"] for p in puts] == ["bytes 0-399/1000", "bytes 400-799/1000", "bytes 800-999/1000"]
|
||||
assert sum(len(p.content) for p in puts) == 1000
|
||||
|
||||
|
||||
def test_youtube_schedule_forces_private(env):
|
||||
spec_body = youtube_api.YouTubeApi(None, "i", "s", "r").video_body # type: ignore[arg-type]
|
||||
from app.platforms.base import JobSpec
|
||||
from pathlib import Path
|
||||
spec = JobSpec("j", YT, "youtube", Path("x.mp4"), None, "t", "c", privacy="public",
|
||||
publish_at="2026-12-01T15:00:00Z", made_for_kids=True)
|
||||
status = spec_body(spec)["status"]
|
||||
assert status["privacyStatus"] == "private" and status["publishAt"] == "2026-12-01T15:00:00Z"
|
||||
assert status["selfDeclaredMadeForKids"] is True
|
||||
|
||||
|
||||
def test_youtube_quota_error_is_human(env):
|
||||
_youtube(env)
|
||||
env.router.add("POST", "https://www.googleapis.com/upload/youtube/v3/videos", lambda r: httpx.Response(
|
||||
403, json={"error": {"errors": [{"reason": "quotaExceeded"}], "message": "quota"}}))
|
||||
job = _run(env, YT)
|
||||
assert job["status"] == "failed" and "cota diária" in job["error"]
|
||||
|
||||
|
||||
def test_youtube_cover_after_processing(env):
|
||||
_youtube(env)
|
||||
cover = env.root / "output" / "capa.jpg"
|
||||
cover.parent.mkdir(parents=True, exist_ok=True)
|
||||
cover.write_bytes(b"\xff\xd8jpg")
|
||||
env.router.add("POST", "https://www.googleapis.com/upload/youtube/v3/videos",
|
||||
lambda r: httpx.Response(200, headers={"Location": "https://upload.example/s"}))
|
||||
env.router.add("PUT", "https://upload.example/s", lambda r: httpx.Response(200, json={"id": "V1"}))
|
||||
states = iter(["processing", "succeeded"])
|
||||
env.router.add("GET", "https://www.googleapis.com/youtube/v3/videos",
|
||||
lambda r: httpx.Response(200, json={"items": [{"processingDetails": {"processingStatus": next(states)}}]}))
|
||||
env.router.add("POST", "https://www.googleapis.com/upload/youtube/v3/thumbnails/set", {"items": []})
|
||||
job = _run(env, YT, cover=str(cover))
|
||||
assert job["status"] == "done" and "capa não foi aplicada" not in job["step"]
|
||||
thumb = env.router.find("POST", "https://www.googleapis.com/upload/youtube/v3/thumbnails/set")[0]
|
||||
assert thumb.headers["content-type"] == "image/jpeg" and thumb.content == b"\xff\xd8jpg"
|
||||
assert env.sleeps == [15] # esperou o processamento uma vez
|
||||
|
||||
|
||||
# ---------- TikTok
|
||||
|
||||
def _tiktok(env, options=("PUBLIC_TO_EVERYONE", "SELF_ONLY")):
|
||||
env.client.put("/v1/apps/tiktok", json={"clientId": "ck", "clientSecret": "cs"})
|
||||
env.connect_profile(TT, secret=dict(VALID))
|
||||
env.router.add("POST", "https://open.tiktokapis.com/v2/post/publish/creator_info/query/", {
|
||||
"data": {"creator_username": "litoral", "creator_nickname": "Litoral", "privacy_level_options": list(options),
|
||||
"comment_disabled": False, "duet_disabled": False, "stitch_disabled": True,
|
||||
"max_video_post_duration_sec": 600}, "error": {"code": "ok"}})
|
||||
env.router.add("PUT", "https://upload.tiktok.example/", lambda r: httpx.Response(201))
|
||||
|
||||
|
||||
def test_chunk_plan_rules():
|
||||
mb = 1024 * 1024
|
||||
assert chunk_plan(3 * mb) == (3 * mb, 1)
|
||||
assert chunk_plan(64 * mb) == (64 * mb, 1)
|
||||
size, count = chunk_plan(100 * mb)
|
||||
assert (size, count) == (32 * mb, 3) and 100 * mb - size * (count - 1) <= 128 * mb
|
||||
|
||||
|
||||
def test_tiktok_direct_post(env):
|
||||
_tiktok(env)
|
||||
env.router.add("POST", "https://open.tiktokapis.com/v2/post/publish/video/init/", {
|
||||
"data": {"publish_id": "p1", "upload_url": "https://upload.tiktok.example/u"}, "error": {"code": "ok"}})
|
||||
env.router.add("POST", "https://open.tiktokapis.com/v2/post/publish/status/fetch/", {
|
||||
"data": {"status": "PUBLISH_COMPLETE", "publicaly_available_post_id": [7311]}, "error": {"code": "ok"}})
|
||||
job = _run(env, TT, aiGenerated=True, caption="Olha isso #fy")
|
||||
assert job["status"] == "done", job
|
||||
assert job["url"] == "https://www.tiktok.com/@litoral/video/7311" and job["draft"] is False
|
||||
|
||||
init = json.loads(env.router.find("POST", "https://open.tiktokapis.com/v2/post/publish/video/init/")[0].content)
|
||||
assert init["source_info"] == {"source": "FILE_UPLOAD", "video_size": 1000, "chunk_size": 1000, "total_chunk_count": 1}
|
||||
assert init["post_info"]["privacy_level"] == "PUBLIC_TO_EVERYONE" and init["post_info"]["is_aigc"] is True
|
||||
assert init["post_info"]["title"] == "Olha isso #fy"
|
||||
put = env.router.find("PUT", "https://upload.tiktok.example/")[0]
|
||||
assert put.headers["content-range"] == "bytes 0-999/1000" and put.headers["content-type"] == "video/mp4"
|
||||
status = env.router.find("POST", "https://open.tiktokapis.com/v2/post/publish/status/fetch/")[0]
|
||||
assert json.loads(status.content) == {"publish_id": "p1"} and status.headers["authorization"] == "Bearer tok"
|
||||
|
||||
|
||||
def test_tiktok_multi_chunk_put(env, monkeypatch):
|
||||
_tiktok(env)
|
||||
monkeypatch.setattr(tiktok_api.TikTokApi, "single_max", 300)
|
||||
monkeypatch.setattr(tiktok_api.TikTokApi, "chunk", 300)
|
||||
env.router.add("POST", "https://open.tiktokapis.com/v2/post/publish/inbox/video/init/", {
|
||||
"data": {"publish_id": "p2", "upload_url": "https://upload.tiktok.example/u2"}, "error": {"code": "ok"}})
|
||||
env.router.add("POST", "https://open.tiktokapis.com/v2/post/publish/status/fetch/", {
|
||||
"data": {"status": "SEND_TO_USER_INBOX"}, "error": {"code": "ok"}})
|
||||
job = _run(env, TT, tiktokMode="draft")
|
||||
assert job["status"] == "done" and job["draft"] is True and job["url"] is None
|
||||
assert "caixa de entrada" in job["step"]
|
||||
init = json.loads(env.router.find("POST", "https://open.tiktokapis.com/v2/post/publish/inbox/video/init/")[0].content)
|
||||
assert init == {"source_info": {"source": "FILE_UPLOAD", "video_size": 1000, "chunk_size": 300, "total_chunk_count": 3}}
|
||||
ranges = [p.headers["content-range"] for p in env.router.find("PUT", "https://upload.tiktok.example/")]
|
||||
assert ranges == ["bytes 0-299/1000", "bytes 300-599/1000", "bytes 600-999/1000"] # último leva o resto
|
||||
assert not env.router.find("POST", "https://open.tiktokapis.com/v2/post/publish/creator_info/query/")
|
||||
|
||||
|
||||
def test_tiktok_unaudited_message(env):
|
||||
_tiktok(env, options=["SELF_ONLY"])
|
||||
job = _run(env, TT, privacy="public")
|
||||
assert job["status"] == "failed" and job["error"] == UNAUDITED
|
||||
assert "Somente eu" in UNAUDITED and "Rascunho" in UNAUDITED
|
||||
|
||||
env.router.add("POST", "https://open.tiktokapis.com/v2/post/publish/video/init/", lambda r: httpx.Response(
|
||||
403, json={"error": {"code": "unaudited_client_can_only_post_to_private_accounts", "message": "x"}}))
|
||||
_tiktok(env)
|
||||
job = _run(env, TT, privacy="public")
|
||||
assert job["status"] == "failed" and job["error"].startswith(UNAUDITED)
|
||||
|
||||
|
||||
def test_tiktok_private_without_public_link(env):
|
||||
_tiktok(env)
|
||||
env.router.add("POST", "https://open.tiktokapis.com/v2/post/publish/video/init/", {
|
||||
"data": {"publish_id": "p3", "upload_url": "https://upload.tiktok.example/u3"}, "error": {"code": "ok"}})
|
||||
statuses = iter(["PROCESSING_UPLOAD", "PUBLISH_COMPLETE"])
|
||||
env.router.add("POST", "https://open.tiktokapis.com/v2/post/publish/status/fetch/", lambda r: httpx.Response(
|
||||
200, json={"data": {"status": next(statuses)}, "error": {"code": "ok"}}))
|
||||
job = _run(env, TT, privacy="private")
|
||||
assert job["status"] == "done" and "Somente eu" in job["step"] and job["url"] is None
|
||||
init = json.loads(env.router.find("POST", "https://open.tiktokapis.com/v2/post/publish/video/init/")[0].content)
|
||||
assert init["post_info"]["privacy_level"] == "SELF_ONLY"
|
||||
|
||||
|
||||
def test_tiktok_creator_info_route(env):
|
||||
_tiktok(env)
|
||||
info = env.client.get(f"/v1/profiles/{TT}/tiktok/creator-info").json()
|
||||
assert info == {"nickname": "Litoral", "privacyOptions": ["PUBLIC_TO_EVERYONE", "SELF_ONLY"], "maxDurationS": 600,
|
||||
"commentDisabled": False, "duetDisabled": False, "stitchDisabled": True}
|
||||
assert env.client.get(f"/v1/profiles/{YT}/tiktok/creator-info").status_code == 409
|
||||
|
||||
|
||||
# ---------- Instagram
|
||||
|
||||
GRAPH = "https://graph.instagram.com/v24.0"
|
||||
|
||||
|
||||
def test_instagram_paste_token(env):
|
||||
env.router.add("GET", f"{GRAPH}/me", {"user_id": "1784", "username": "litoral", "name": "Litoral",
|
||||
"account_type": "MEDIA_CREATOR"})
|
||||
profile = env.client.post(f"/v1/profiles/{IG}/token", json={"accessToken": "IGAA" + "x" * 40}).json()
|
||||
assert profile["status"] == "connected" and profile["handle"] == "@litoral" and profile["expiresAt"]
|
||||
assert env.vault.get(f"token:{IG}")["igUserId"] == "1784"
|
||||
|
||||
env.router.add("GET", f"{GRAPH}/me", {"user_id": "1", "username": "pessoal", "account_type": "PERSONAL"})
|
||||
refused = env.client.post(f"/v1/profiles/{IG}/token", json={"accessToken": "IGAA" + "y" * 40})
|
||||
assert refused.status_code == 400 and "Profissional" in refused.json()["detail"]
|
||||
|
||||
|
||||
def test_instagram_reel_upload(env):
|
||||
env.connect_profile(IG, secret={"accessToken": "igtok", "accessExpiresAt": time.time() + 50 * 86400,
|
||||
"igUserId": "1784", "obtainedAt": time.time()})
|
||||
env.router.add("POST", f"{GRAPH}/1784/media", {"id": "C1", "uri": "https://rupload.facebook.com/ig-api-upload/v24.0/C1"})
|
||||
env.router.add("POST", "https://rupload.facebook.com/ig-api-upload/v24.0/C1", {"success": True})
|
||||
statuses = iter(["IN_PROGRESS", "FINISHED"])
|
||||
env.router.add("GET", f"{GRAPH}/C1", lambda r: httpx.Response(200, json={"status_code": next(statuses)}))
|
||||
env.router.add("POST", f"{GRAPH}/1784/media_publish", {"id": "M9"})
|
||||
env.router.add("GET", f"{GRAPH}/M9", {"permalink": "https://www.instagram.com/reel/abc/"})
|
||||
job = _run(env, IG, aiGenerated=True, caption="Legenda #reels")
|
||||
assert job["status"] == "done", job
|
||||
assert job["remoteId"] == "M9" and job["url"] == "https://www.instagram.com/reel/abc/"
|
||||
|
||||
form = parse_qs(env.router.find("POST", f"{GRAPH}/1784/media")[0].content.decode())
|
||||
assert form["media_type"] == ["REELS"] and form["upload_type"] == ["resumable"]
|
||||
assert form["caption"] == ["Legenda #reels"] and form["is_ai_generated"] == ["true"]
|
||||
upload = env.router.find("POST", "https://rupload.facebook.com/")[0]
|
||||
assert upload.headers["authorization"] == "OAuth igtok" and upload.headers["offset"] == "0"
|
||||
assert upload.headers["file_size"] == "1000" and len(upload.content) == 1000
|
||||
publish = parse_qs(env.router.find("POST", f"{GRAPH}/1784/media_publish")[0].content.decode())
|
||||
assert publish["creation_id"] == ["C1"]
|
||||
assert env.sleeps == [InstagramApi.poll_s]
|
||||
|
||||
|
||||
def test_instagram_rupload_refused_explains_fb_login(env):
|
||||
env.connect_profile(IG, secret={"accessToken": "igtok", "accessExpiresAt": time.time() + 50 * 86400,
|
||||
"igUserId": "1784", "obtainedAt": time.time()})
|
||||
env.router.add("POST", f"{GRAPH}/1784/media", {"id": "C1"})
|
||||
env.router.add("POST", "https://rupload.facebook.com/", lambda r: httpx.Response(
|
||||
400, json={"error": {"code": 1, "message": "unsupported"}}))
|
||||
job = _run(env, IG)
|
||||
assert job["status"] == "failed" and "Facebook Login for Business" in job["error"]
|
||||
|
||||
|
||||
def test_instagram_refreshes_token_close_to_expiry(env):
|
||||
env.connect_profile(IG, secret={"accessToken": "old", "accessExpiresAt": time.time() + 5 * 86400,
|
||||
"igUserId": "1784", "obtainedAt": time.time() - 50 * 86400})
|
||||
env.router.add("GET", "https://graph.instagram.com/refresh_access_token",
|
||||
{"access_token": "new", "token_type": "bearer", "expires_in": 5184000})
|
||||
env.publisher.maintenance()
|
||||
assert env.vault.get(f"token:{IG}")["accessToken"] == "new"
|
||||
sent = env.router.find("GET", "https://graph.instagram.com/refresh_access_token")[0]
|
||||
assert sent.url.params["grant_type"] == "ig_refresh_token" and sent.url.params["access_token"] == "old"
|
||||
|
||||
|
||||
def test_instagram_expired_token_code_190(env):
|
||||
env.connect_profile(IG, secret={"accessToken": "igtok", "accessExpiresAt": time.time() + 50 * 86400,
|
||||
"igUserId": "1784", "obtainedAt": time.time()})
|
||||
env.router.add("POST", f"{GRAPH}/1784/media", lambda r: httpx.Response(
|
||||
400, json={"error": {"code": 190, "message": "Error validating access token"}}))
|
||||
job = _run(env, IG)
|
||||
assert job["status"] == "needs_login"
|
||||
assert env.client.get(f"/v1/profiles/{IG}").json()["status"] == "expired"
|
||||
|
||||
|
||||
def test_publish_error_kinds():
|
||||
assert PublishError("x").kind == "failed"
|
||||
with pytest.raises(PublishError):
|
||||
raise PublishError("y", "needs_login")
|
||||
@@ -0,0 +1,38 @@
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from app.vault import DpapiCipher, Vault, VaultError
|
||||
from tests.conftest import FakeCipher
|
||||
|
||||
|
||||
def test_vault_roundtrip_with_fake_cipher(tmp_path):
|
||||
vault = Vault(tmp_path / "vault.bin", cipher=FakeCipher())
|
||||
assert vault.get("token:x") is None
|
||||
vault.set("token:x", {"accessToken": "segredo-123", "refreshToken": "r1"})
|
||||
vault.update("token:x", refreshToken="r2")
|
||||
assert vault.get("token:x") == {"accessToken": "segredo-123", "refreshToken": "r2"}
|
||||
assert b"segredo-123" not in (tmp_path / "vault.bin").read_bytes()
|
||||
reopened = Vault(tmp_path / "vault.bin", cipher=FakeCipher())
|
||||
assert reopened.get("token:x")["refreshToken"] == "r2"
|
||||
reopened.delete("token:x")
|
||||
assert reopened.keys() == []
|
||||
|
||||
|
||||
def test_vault_refuses_garbage(tmp_path):
|
||||
(tmp_path / "vault.bin").write_bytes(b"FAKE{nao-e-json")
|
||||
with pytest.raises(VaultError):
|
||||
Vault(tmp_path / "vault.bin", cipher=FakeCipher()).get("x")
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform != "win32", reason="DPAPI só existe no Windows")
|
||||
def test_real_dpapi_roundtrip(tmp_path):
|
||||
cipher = DpapiCipher()
|
||||
blob = cipher.protect(b"token-de-verdade")
|
||||
assert b"token-de-verdade" not in blob
|
||||
assert cipher.unprotect(blob) == b"token-de-verdade"
|
||||
vault = Vault(tmp_path / "vault.bin") # cifrador real (padrão)
|
||||
vault.set("app:youtube", {"clientSecret": "abc"})
|
||||
assert Vault(tmp_path / "vault.bin").get("app:youtube") == {"clientSecret": "abc"}
|
||||
with pytest.raises(VaultError):
|
||||
cipher.unprotect(b"\x01\x02\x03 nao e dpapi")
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Máquina de estados do job e worker persistente."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.db import INTERRUPTED, Database
|
||||
from app.platforms.base import PublishError, PublishResult
|
||||
from app.worker import Worker
|
||||
|
||||
PID = "canal--instagram"
|
||||
|
||||
|
||||
def _queue(env, **extra):
|
||||
env.connect_profile(PID, mode="session")
|
||||
response = env.client.post("/v1/jobs", json=env.job_body(PID, env.video(), **extra))
|
||||
assert response.status_code == 201
|
||||
return response.json()["jobId"]
|
||||
|
||||
|
||||
def _job(env, job_id):
|
||||
return env.client.get(f"/v1/jobs/{job_id}").json()
|
||||
|
||||
|
||||
def test_queued_running_done(env):
|
||||
job_id = _queue(env)
|
||||
seen = []
|
||||
|
||||
def execute(row, progress):
|
||||
seen.append(_job(env, job_id)["status"])
|
||||
progress("Enviando…", 0.5)
|
||||
return PublishResult("R1", "https://exemplo/R1", False, "Publicado")
|
||||
|
||||
worker = Worker(env.db, execute)
|
||||
assert worker.run_once() is True
|
||||
assert seen == ["running"]
|
||||
job = _job(env, job_id)
|
||||
assert job["status"] == "done" and job["progress"] == 1 and job["remoteId"] == "R1" and job["step"] == "Publicado"
|
||||
assert worker.run_once() is False # fila vazia
|
||||
|
||||
|
||||
def test_failures_and_needs_login(env):
|
||||
env.runner.error = PublishError("É preciso entrar de novo: captcha.", "needs_login")
|
||||
job_id = _queue(env)
|
||||
env.worker.run_once()
|
||||
job = _job(env, job_id)
|
||||
assert job["status"] == "needs_login" and "captcha" in job["error"]
|
||||
profile = env.client.get(f"/v1/profiles/{PID}").json()
|
||||
assert profile["status"] == "needs_login"
|
||||
|
||||
# perfil precisando de login: o próximo job nem tenta o navegador
|
||||
env.publisher._update(PID, status="connected")
|
||||
env.runner.error = PublishError("Não achei o botão Publicar.")
|
||||
job_id = env.client.post("/v1/jobs", json=env.job_body(PID, env.video())).json()["jobId"]
|
||||
env.worker.run_once()
|
||||
assert _job(env, job_id)["status"] == "failed" and _job(env, job_id)["error"] == "Não achei o botão Publicar."
|
||||
|
||||
env.runner.error = RuntimeError("bug")
|
||||
job_id = env.client.post("/v1/jobs", json=env.job_body(PID, env.video())).json()["jobId"]
|
||||
env.worker.run_once()
|
||||
assert _job(env, job_id)["status"] == "failed" and "Erro inesperado" in _job(env, job_id)["error"]
|
||||
|
||||
|
||||
def test_session_job_uses_runner_without_link(env):
|
||||
job_id = _queue(env)
|
||||
env.worker.run_once()
|
||||
job = _job(env, job_id)
|
||||
assert job["status"] == "done" and job["remoteId"] is None and job["url"] is None
|
||||
assert "link não encontrado" in job["step"]
|
||||
|
||||
|
||||
def test_disconnected_profile_and_deleted_file(env):
|
||||
job_id = _queue(env)
|
||||
env.client.delete(f"/v1/profiles/{PID}")
|
||||
assert _job(env, job_id)["status"] == "canceled" # desconectar cancela o que estava na fila
|
||||
|
||||
job_id = _queue(env)
|
||||
video = env.root / "output" / "clip.mp4"
|
||||
video.unlink()
|
||||
env.worker.run_once()
|
||||
job = _job(env, job_id)
|
||||
assert job["status"] == "failed" and "não existe" in job["error"]
|
||||
|
||||
|
||||
def test_canceled_job_is_not_run(env):
|
||||
job_id = _queue(env)
|
||||
env.client.post(f"/v1/jobs/{job_id}/cancel")
|
||||
called = []
|
||||
Worker(env.db, lambda row, progress: called.append(row)).run_once()
|
||||
assert called == [] and _job(env, job_id)["status"] == "canceled"
|
||||
|
||||
|
||||
def test_running_job_becomes_failed_on_restart(env):
|
||||
job_id = _queue(env)
|
||||
env.db.run("UPDATE jobs SET status = 'running' WHERE job_id = ?", job_id)
|
||||
env.db.close()
|
||||
db = Database(env.settings.db_path) # "subida" do serviço
|
||||
try:
|
||||
assert db.interrupted_on_start == [job_id]
|
||||
row = db.get("SELECT * FROM jobs WHERE job_id = ?", job_id)
|
||||
assert row["status"] == "failed" and row["error"] == INTERRUPTED and "tente de novo" in INTERRUPTED
|
||||
finally:
|
||||
db.close()
|
||||
env.db = Database(env.settings.db_path) # a fixture fecha este
|
||||
|
||||
|
||||
def test_jobs_run_in_order_one_at_a_time(env):
|
||||
first = _queue(env)
|
||||
second = env.client.post("/v1/jobs", json=env.job_body(PID, env.video())).json()["jobId"]
|
||||
order = []
|
||||
worker = Worker(env.db, lambda row, progress: order.append(row["job_id"]) or PublishResult("x", None))
|
||||
worker.run_once()
|
||||
assert order == [first] and _job(env, second)["status"] == "queued"
|
||||
worker.run_once()
|
||||
assert order == [first, second]
|
||||
|
||||
|
||||
def test_worker_thread_starts_and_stops(env):
|
||||
job_id = _queue(env)
|
||||
done = []
|
||||
worker = Worker(env.db, lambda row, progress: done.append(1) or PublishResult("x", None), idle_wait_s=0.05)
|
||||
worker.start()
|
||||
worker.wake()
|
||||
import time
|
||||
deadline = time.time() + 5
|
||||
while not done and time.time() < deadline:
|
||||
time.sleep(0.05)
|
||||
worker.stop()
|
||||
assert done and _job(env, job_id)["status"] == "done"
|
||||
Reference in New Issue
Block a user