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,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
|
||||
Reference in New Issue
Block a user