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,333 @@
|
||||
"""Correções das revisões: idempotência por clientRef, pastas permitidas, janela/porta CDP do modo sessão,
|
||||
capturas de tela, permissões (icacls) e PKCE fora do disco."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from app import acl
|
||||
from app.db import Database
|
||||
from app.paths import IMAGE_EXT, VIDEO_EXT, PathRefused, inside_root
|
||||
from app.platforms.base import JobSpec, PublishError, PublishResult
|
||||
from app.platforms.session import common, runner as runner_mod
|
||||
from app.platforms.session.browser import BrowserInfo, BrowserManager, _Window, owns_port
|
||||
|
||||
PID = "canal--youtube"
|
||||
|
||||
|
||||
# ---------- 1. idempotência
|
||||
|
||||
def test_client_ref_returns_existing_job(env):
|
||||
env.connect_profile(PID, mode="session")
|
||||
video = env.video()
|
||||
first = env.client.post("/v1/jobs", json=env.job_body(PID, video, clientRef="painel-42"))
|
||||
assert first.status_code == 201
|
||||
# Mesmo clientRef: 200 com o MESMO job, sem revalidar (o arquivo pode até ter sumido e o perfil caído).
|
||||
video.unlink()
|
||||
env.publisher._update(PID, status="needs_login")
|
||||
again = env.client.post("/v1/jobs", json=env.job_body(PID, video, clientRef="painel-42", title="outro"))
|
||||
assert again.status_code == 200 and again.json()["jobId"] == first.json()["jobId"]
|
||||
assert env.db.get("SELECT COUNT(*) AS n FROM jobs")["n"] == 1
|
||||
# Sem clientRef: comportamento antigo (valida e cria)
|
||||
env.publisher._update(PID, status="connected")
|
||||
other = env.client.post("/v1/jobs", json=env.job_body(PID, env.video()))
|
||||
assert other.status_code == 201 and other.json()["jobId"] != first.json()["jobId"]
|
||||
assert env.client.post("/v1/jobs", json=env.job_body(PID, env.video(), clientRef="x" * 81)).status_code == 422
|
||||
|
||||
|
||||
def test_client_ref_column_is_unique(env):
|
||||
env.db.run("INSERT INTO jobs (job_id, profile_id, platform, input_json, status, created_at, updated_at, client_ref) "
|
||||
"VALUES ('a', 'p', 'youtube', '{}', 'queued', 'x', 'x', 'r1')")
|
||||
with pytest.raises(Exception):
|
||||
env.db.run("INSERT INTO jobs (job_id, profile_id, platform, input_json, status, created_at, updated_at, client_ref) "
|
||||
"VALUES ('b', 'p', 'youtube', '{}', 'queued', 'x', 'x', 'r1')")
|
||||
assert env.db.get("PRAGMA user_version")["user_version"] == 2
|
||||
|
||||
|
||||
def test_migration_from_v1_keeps_jobs(tmp_path):
|
||||
import sqlite3
|
||||
|
||||
from app.db import SCHEMA, _split
|
||||
|
||||
path = tmp_path / "old.db"
|
||||
conn = sqlite3.connect(path)
|
||||
for statement in _split(SCHEMA[0]):
|
||||
conn.execute(statement)
|
||||
conn.execute("PRAGMA user_version = 1")
|
||||
conn.execute("INSERT INTO jobs (job_id, profile_id, platform, input_json, status, created_at, updated_at) "
|
||||
"VALUES ('j', 'p', 'youtube', '{}', 'done', 'x', 'x')")
|
||||
conn.execute("INSERT INTO oauth_states VALUES ('s', 'youtube', 'p', 'verificador-em-claro', 0, 9e12, 0)")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
db = Database(path)
|
||||
try:
|
||||
assert db.get("SELECT client_ref FROM jobs WHERE job_id = 'j'") == {"client_ref": None}
|
||||
assert db.get("SELECT verifier FROM oauth_states")["verifier"] == ""
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
# ---------- 4. só pastas de saída
|
||||
|
||||
def _file(root: Path, *parts: str) -> Path:
|
||||
path = root.joinpath(*parts)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(b"x")
|
||||
return path
|
||||
|
||||
|
||||
def test_paths_only_output_folders(tmp_path):
|
||||
root = tmp_path / "repo"
|
||||
for folder in ("output/clipper", "output/documentary", "stories/minha", "assets/library"):
|
||||
assert inside_root(str(_file(root, folder, "v.mp4")), root, VIDEO_EXT, "vídeo").is_file()
|
||||
assert inside_root(str(_file(root, "assets", "capa.png")), root, IMAGE_EXT, "capa")
|
||||
for bad in (("data", "publisher", "v.mp4"), ("data", "clipper", "v.mp4"), ("panel", "v.mp4"), ("v.mp4",),
|
||||
("outputx", "v.mp4")):
|
||||
with pytest.raises(PathRefused):
|
||||
inside_root(str(_file(root, *bad)), root, VIDEO_EXT, "vídeo")
|
||||
with pytest.raises(PathRefused, match="data/"):
|
||||
inside_root(str(_file(root, "data", "publisher", "vault.png")), root, IMAGE_EXT, "capa")
|
||||
# ".." não escapa para data/
|
||||
sneaky = os.path.join(str(root), "output", "..", "data", "publisher", "v.mp4")
|
||||
with pytest.raises(PathRefused):
|
||||
inside_root(sneaky, root, VIDEO_EXT, "vídeo")
|
||||
|
||||
|
||||
def test_job_route_refuses_data_folder(env):
|
||||
env.connect_profile(PID, mode="session")
|
||||
inside_data = _file(env.root, "data", "publisher", "x.mp4")
|
||||
response = env.client.post("/v1/jobs", json=env.job_body(PID, inside_data))
|
||||
assert response.status_code == 400 and "data/" in response.json()["detail"]
|
||||
|
||||
|
||||
# ---------- 6. PKCE fora do disco
|
||||
|
||||
def test_restart_mid_oauth_asks_to_connect_again(env):
|
||||
env.client.put("/v1/apps/youtube", json={"clientId": "id", "clientSecret": "s"})
|
||||
body = env.client.post(f"/v1/profiles/{PID}/connect", json={"platform": "youtube", "mode": "official"}).json()
|
||||
state = body["next"]["url"].split("state=")[1].split("&")[0]
|
||||
env.publisher._verifiers.clear() # "reiniciou"
|
||||
from fastapi.testclient import TestClient
|
||||
page = TestClient(env.app).get(f"/oauth/callback/youtube?state={state}&code=c")
|
||||
assert page.status_code == 400 and "reiniciado" in page.text
|
||||
|
||||
|
||||
# ---------- 5. capturas de tela
|
||||
|
||||
class ShotPage:
|
||||
def __init__(self, url="https://studio.youtube.com/x"):
|
||||
self.url = url
|
||||
self.calls = []
|
||||
|
||||
def screenshot(self, **kwargs):
|
||||
self.calls.append(kwargs)
|
||||
Path(kwargs["path"]).write_bytes(b"png")
|
||||
|
||||
# o detect_block olha a página; aqui nada bloqueia
|
||||
def get_by_role(self, *a, **k):
|
||||
return _Absent()
|
||||
|
||||
get_by_text = get_by_label = get_by_placeholder = locator = get_by_role
|
||||
|
||||
|
||||
class _Absent:
|
||||
first = property(lambda self: self)
|
||||
|
||||
def count(self):
|
||||
return 0
|
||||
|
||||
|
||||
def test_screenshot_is_viewport_only_and_skips_login(tmp_path):
|
||||
page = ShotPage()
|
||||
shot = common.screenshot(page, tmp_path, "falha")
|
||||
assert shot and shot.is_file() and page.calls[0]["full_page"] is False
|
||||
login = ShotPage("https://accounts.google.com/v3/signin/identifier")
|
||||
assert common.screenshot(login, tmp_path, "login") is None and login.calls == []
|
||||
|
||||
|
||||
def test_prune_old_screenshots(tmp_path):
|
||||
old, new = tmp_path / "velha.png", tmp_path / "nova.png"
|
||||
old.write_bytes(b"x")
|
||||
new.write_bytes(b"x")
|
||||
eight_days = time.time() - 8 * 86400
|
||||
os.utime(old, (eight_days, eight_days))
|
||||
assert common.prune_screenshots(tmp_path) == 1
|
||||
assert not old.exists() and new.exists()
|
||||
assert common.prune_screenshots(tmp_path / "nao-existe") == 0
|
||||
|
||||
|
||||
# ---------- 2. janela/porta CDP
|
||||
|
||||
def _devtools(user_dir: Path, port: int, browser_id: str = "abc") -> None:
|
||||
user_dir.mkdir(parents=True, exist_ok=True)
|
||||
(user_dir / "DevToolsActivePort").write_text(f"{port}\n/devtools/browser/{browser_id}\n", encoding="utf-8")
|
||||
|
||||
|
||||
def test_owns_port_checks_profile_file_and_browser_id(tmp_path, monkeypatch):
|
||||
ours = {"Browser": "Chrome/150", "webSocketDebuggerUrl": "ws://127.0.0.1:4541/devtools/browser/abc"}
|
||||
_devtools(tmp_path, 4541)
|
||||
assert owns_port(tmp_path, 4541, ours)
|
||||
assert not owns_port(tmp_path, 4542, ours) # arquivo aponta para outra porta
|
||||
other = {"Browser": "Chrome/150", "webSocketDebuggerUrl": "ws://127.0.0.1:4541/devtools/browser/zzz"}
|
||||
assert not owns_port(tmp_path, 4541, other) # outro navegador na mesma porta
|
||||
assert not owns_port(tmp_path / "vazio", 4541, ours) # perfil sem DevToolsActivePort
|
||||
monkeypatch.setattr("app.platforms.session.browser.cdp_version", lambda port: None)
|
||||
assert not owns_port(tmp_path, 4541) # porta não responde
|
||||
|
||||
|
||||
def test_owns_port_without_devtools_file_uses_window_mark(tmp_path, monkeypatch):
|
||||
"""Chrome 157+ com porta fixa não grava DevToolsActivePort: vale a marca do Publicador + o PID que escuta."""
|
||||
from app.platforms.session import browser as browser_module
|
||||
|
||||
ours = {"Browser": "Chrome/157", "webSocketDebuggerUrl": "ws://127.0.0.1:4540/devtools/browser/abc"}
|
||||
browser_module.write_window_mark(tmp_path, 777, 4540)
|
||||
monkeypatch.setattr(browser_module, "listener_pid", lambda port: 777 if port == 4540 else None)
|
||||
monkeypatch.setattr(browser_module, "process_exe_name", lambda pid: "chrome.exe")
|
||||
assert owns_port(tmp_path, 4540, ours)
|
||||
assert browser_module.active_port(tmp_path) == 4540
|
||||
assert not owns_port(tmp_path, 4541, ours) # a marca aponta para outra porta
|
||||
monkeypatch.setattr(browser_module, "listener_pid", lambda port: 999)
|
||||
assert not owns_port(tmp_path, 4540, ours) # outro processo escutando na porta
|
||||
monkeypatch.setattr(browser_module, "listener_pid", lambda port: 777)
|
||||
monkeypatch.setattr(browser_module, "process_exe_name", lambda pid: "python.exe")
|
||||
assert not owns_port(tmp_path, 4540, ours) # PID reaproveitado por outro programa
|
||||
assert not owns_port(tmp_path / "vazio", 4540, ours) # perfil sem marca nem DevToolsActivePort
|
||||
|
||||
|
||||
def test_wait_cdp_explains_when_profile_window_is_already_open(tmp_path, monkeypatch):
|
||||
manager = BrowserManager(tmp_path, BrowserInfo("chrome", "chrome.exe"), start_reaper=False)
|
||||
monkeypatch.setattr("app.platforms.session.browser.owns_port", lambda user_dir, port, version=None: False)
|
||||
exited = AliveProcess()
|
||||
exited.exited = True # o Chrome entregou a URL para a janela que já estava aberta e saiu
|
||||
with pytest.raises(PublishError, match="Já existe uma janela"):
|
||||
manager._wait_cdp(4540, tmp_path, exited, timeout_s=2)
|
||||
|
||||
|
||||
class AliveProcess:
|
||||
pid = 1
|
||||
|
||||
def __init__(self):
|
||||
self.exited = False
|
||||
|
||||
def poll(self):
|
||||
return 0 if self.exited else None
|
||||
|
||||
def wait(self, timeout=None):
|
||||
self.exited = True
|
||||
return 0
|
||||
|
||||
|
||||
def test_open_refuses_port_that_is_not_ours(tmp_path, monkeypatch):
|
||||
manager = BrowserManager(tmp_path, BrowserInfo("chrome", "chrome.exe"), start_reaper=False)
|
||||
manager._windows["canal--youtube"] = _Window(AliveProcess(), 4541, tmp_path / "canal--youtube")
|
||||
monkeypatch.setattr("app.platforms.session.browser.owns_port", lambda user_dir, port, version=None: False)
|
||||
with pytest.raises(PublishError, match="não responde como o nosso navegador"):
|
||||
manager.open("canal--youtube", "https://x")
|
||||
|
||||
|
||||
def test_idle_windows_are_closed(tmp_path, monkeypatch):
|
||||
manager = BrowserManager(tmp_path, BrowserInfo("chrome", "chrome.exe"), start_reaper=False)
|
||||
closed = []
|
||||
monkeypatch.setattr(manager, "close", lambda pid, graceful=True: closed.append(pid) or manager._windows.pop(pid))
|
||||
now = time.time()
|
||||
manager._windows["a--youtube"] = _Window(AliveProcess(), 4540, tmp_path / "a", 300, now - 301)
|
||||
manager._windows["b--youtube"] = _Window(AliveProcess(), 4541, tmp_path / "b", 900, now - 301) # login: 15 min
|
||||
manager._windows["c--youtube"] = _Window(AliveProcess(), 4542, tmp_path / "c", 300, now - 999)
|
||||
with manager.in_use("c--youtube"):
|
||||
assert manager.close_idle(now) == ["a--youtube"] # c está ocupado; b ainda no prazo do login
|
||||
assert closed == ["a--youtube"]
|
||||
|
||||
|
||||
class FakeBrowsers:
|
||||
def __init__(self):
|
||||
self.closed, self.opened = [], []
|
||||
|
||||
def open(self, profile_id, url, for_login=False):
|
||||
self.opened.append((profile_id, for_login))
|
||||
return 4541
|
||||
|
||||
def is_open(self, profile_id):
|
||||
return False
|
||||
|
||||
def close(self, profile_id, graceful=True):
|
||||
self.closed.append(profile_id)
|
||||
|
||||
def in_use(self, profile_id):
|
||||
from contextlib import nullcontext
|
||||
return nullcontext()
|
||||
|
||||
|
||||
def _runner(tmp_path, monkeypatch, outcome):
|
||||
browsers = FakeBrowsers()
|
||||
runner = runner_mod.SessionRunner(browsers, tmp_path, sleep=lambda s: None) # type: ignore[arg-type]
|
||||
|
||||
def fake_with_page(port, fn, keep_page, label):
|
||||
fn(object())
|
||||
|
||||
monkeypatch.setattr(runner, "_with_page", fake_with_page)
|
||||
fake = runner_mod.Uploader(PID.split("--")[1], "https://x", lambda page, sleep: outcome.get("reason"),
|
||||
lambda page, spec, progress, sleep: outcome["upload"]())
|
||||
monkeypatch.setitem(runner_mod.UPLOADERS, "youtube", fake)
|
||||
return runner, browsers
|
||||
|
||||
|
||||
def test_window_closes_after_successful_check_but_not_when_login_missing(tmp_path, monkeypatch):
|
||||
runner, browsers = _runner(tmp_path, monkeypatch, {"reason": None})
|
||||
assert runner.check(PID, "youtube") is None and browsers.closed == [PID]
|
||||
assert browsers.opened == [(PID, True)]
|
||||
runner, browsers = _runner(tmp_path, monkeypatch, {"reason": "tela de login"})
|
||||
assert runner.check(PID, "youtube") == "tela de login" and browsers.closed == []
|
||||
|
||||
|
||||
def test_window_closes_after_each_publish(tmp_path, monkeypatch):
|
||||
spec = JobSpec("j", PID, "youtube", Path("v.mp4"), None, "t", "c")
|
||||
runner, browsers = _runner(tmp_path, monkeypatch, {"upload": lambda: PublishResult("1", None)})
|
||||
assert runner.publish(spec, lambda s, p: None).remote_id == "1" and browsers.closed == [PID]
|
||||
|
||||
def fail():
|
||||
raise PublishError("Não achei o botão.")
|
||||
|
||||
runner, browsers = _runner(tmp_path, monkeypatch, {"upload": fail})
|
||||
with pytest.raises(PublishError):
|
||||
runner.publish(spec, lambda s, p: None)
|
||||
assert browsers.closed == [PID]
|
||||
|
||||
def login():
|
||||
raise PublishError("entre de novo", "needs_login")
|
||||
|
||||
runner, browsers = _runner(tmp_path, monkeypatch, {"upload": login})
|
||||
with pytest.raises(PublishError):
|
||||
runner.publish(spec, lambda s, p: None)
|
||||
assert browsers.closed == [] # fica aberta para o usuário entrar (o fechamento por ociosidade cuida depois)
|
||||
|
||||
|
||||
# ---------- 3. permissões
|
||||
|
||||
def test_icacls_args():
|
||||
assert acl.icacls_args(Path("C:/x"), "S-1-5-21-1", True) == [
|
||||
"icacls", str(Path("C:/x")), "/inheritance:r", "/grant:r", "*S-1-5-21-1:(OI)(CI)F"]
|
||||
assert acl.icacls_args(Path("C:/x/.env"), "S-1-5-21-1", False)[-1] == "*S-1-5-21-1:F"
|
||||
|
||||
|
||||
def test_restrict_uses_current_user(tmp_path, monkeypatch):
|
||||
calls = []
|
||||
|
||||
class Done:
|
||||
returncode = 0
|
||||
stdout = stderr = ""
|
||||
|
||||
monkeypatch.setattr(acl, "current_user_sid", lambda: "S-1-5-21-9")
|
||||
assert acl.restrict_to_current_user(tmp_path, run=lambda args, **kw: calls.append(args) or Done())
|
||||
assert calls == [["icacls", str(tmp_path), "/inheritance:r", "/grant:r", "*S-1-5-21-9:(OI)(CI)F"]]
|
||||
monkeypatch.setattr(acl, "current_user_sid", lambda: None)
|
||||
assert acl.restrict_to_current_user(tmp_path) is False
|
||||
|
||||
|
||||
def test_text_has_no_human_mimicry_wording():
|
||||
root = Path(__file__).resolve().parent.parent
|
||||
for path in list((root / "app").rglob("*.py")) + [root / "README.md"]:
|
||||
assert "ritmo humano" not in path.read_text(encoding="utf-8"), path
|
||||
Reference in New Issue
Block a user