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:
2026-11-17 16:35:09 -03:00
co-authored by Claude Opus 5.5
commit 84f30bbc2d
484 changed files with 74826 additions and 0 deletions
+271
View File
@@ -0,0 +1,271 @@
"""Montagem das requisições de envio de cada API (rede simulada com httpx.MockTransport)."""
from __future__ import annotations
import json
import time
from urllib.parse import parse_qs
import httpx
import pytest
from app.platforms import tiktok_api, youtube_api
from app.platforms.base import PublishError
from app.platforms.instagram_api import InstagramApi
from app.platforms.tiktok_api import UNAUDITED, chunk_plan
YT, TT, IG = "canal--youtube", "canal--tiktok", "canal--instagram"
VALID = {"accessToken": "tok", "accessExpiresAt": time.time() + 3600, "refreshToken": "r",
"refreshExpiresAt": time.time() + 10_000_000}
def _run(env, pid, **extra):
video = env.video(size=1000)
response = env.client.post("/v1/jobs", json=env.job_body(pid, video, **extra))
assert response.status_code == 201, response.text
assert env.worker.run_once()
return env.client.get(f"/v1/jobs/{response.json()['jobId']}").json()
# ---------- YouTube
def _youtube(env):
env.client.put("/v1/apps/youtube", json={"clientId": "id", "clientSecret": "sec"})
env.connect_profile(YT, secret=dict(VALID))
def test_youtube_resumable_upload_in_chunks(env, monkeypatch):
_youtube(env)
monkeypatch.setattr(youtube_api, "CHUNK", 400)
env.router.add("POST", "https://www.googleapis.com/upload/youtube/v3/videos",
lambda r: httpx.Response(200, headers={"Location": "https://upload.example/session/1"}))
ranges = iter(["bytes=0-399", "bytes=0-799"])
def put(request):
if request.headers["content-range"].endswith("999/1000"):
return httpx.Response(201, json={"id": "VID123"})
return httpx.Response(308, headers={"Range": next(ranges)})
env.router.add("PUT", "https://upload.example/session/1", put)
job = _run(env, YT, aiGenerated=True, tags=["#cortes", "live, top"], title="Título <legal>")
assert job["status"] == "done", job
assert job["remoteId"] == "VID123" and job["url"] == "https://youtu.be/VID123" and job["progress"] == 1
start = env.router.find("POST", "https://www.googleapis.com/upload/youtube/v3/videos")[0]
assert parse_qs(start.url.query.decode()) == {"uploadType": ["resumable"], "part": ["snippet,status"]}
assert start.headers["authorization"] == "Bearer tok"
assert start.headers["x-upload-content-length"] == "1000"
body = json.loads(start.content)
assert body["status"] == {"privacyStatus": "public", "selfDeclaredMadeForKids": False, "containsSyntheticMedia": True}
assert body["snippet"]["title"] == "Título ‹legal›" and body["snippet"]["tags"] == ["cortes", "live top"]
puts = env.router.find("PUT", "https://upload.example/session/1")
assert [p.headers["content-range"] for p in puts] == ["bytes 0-399/1000", "bytes 400-799/1000", "bytes 800-999/1000"]
assert sum(len(p.content) for p in puts) == 1000
def test_youtube_schedule_forces_private(env):
spec_body = youtube_api.YouTubeApi(None, "i", "s", "r").video_body # type: ignore[arg-type]
from app.platforms.base import JobSpec
from pathlib import Path
spec = JobSpec("j", YT, "youtube", Path("x.mp4"), None, "t", "c", privacy="public",
publish_at="2026-12-01T15:00:00Z", made_for_kids=True)
status = spec_body(spec)["status"]
assert status["privacyStatus"] == "private" and status["publishAt"] == "2026-12-01T15:00:00Z"
assert status["selfDeclaredMadeForKids"] is True
def test_youtube_quota_error_is_human(env):
_youtube(env)
env.router.add("POST", "https://www.googleapis.com/upload/youtube/v3/videos", lambda r: httpx.Response(
403, json={"error": {"errors": [{"reason": "quotaExceeded"}], "message": "quota"}}))
job = _run(env, YT)
assert job["status"] == "failed" and "cota diária" in job["error"]
def test_youtube_cover_after_processing(env):
_youtube(env)
cover = env.root / "output" / "capa.jpg"
cover.parent.mkdir(parents=True, exist_ok=True)
cover.write_bytes(b"\xff\xd8jpg")
env.router.add("POST", "https://www.googleapis.com/upload/youtube/v3/videos",
lambda r: httpx.Response(200, headers={"Location": "https://upload.example/s"}))
env.router.add("PUT", "https://upload.example/s", lambda r: httpx.Response(200, json={"id": "V1"}))
states = iter(["processing", "succeeded"])
env.router.add("GET", "https://www.googleapis.com/youtube/v3/videos",
lambda r: httpx.Response(200, json={"items": [{"processingDetails": {"processingStatus": next(states)}}]}))
env.router.add("POST", "https://www.googleapis.com/upload/youtube/v3/thumbnails/set", {"items": []})
job = _run(env, YT, cover=str(cover))
assert job["status"] == "done" and "capa não foi aplicada" not in job["step"]
thumb = env.router.find("POST", "https://www.googleapis.com/upload/youtube/v3/thumbnails/set")[0]
assert thumb.headers["content-type"] == "image/jpeg" and thumb.content == b"\xff\xd8jpg"
assert env.sleeps == [15] # esperou o processamento uma vez
# ---------- TikTok
def _tiktok(env, options=("PUBLIC_TO_EVERYONE", "SELF_ONLY")):
env.client.put("/v1/apps/tiktok", json={"clientId": "ck", "clientSecret": "cs"})
env.connect_profile(TT, secret=dict(VALID))
env.router.add("POST", "https://open.tiktokapis.com/v2/post/publish/creator_info/query/", {
"data": {"creator_username": "litoral", "creator_nickname": "Litoral", "privacy_level_options": list(options),
"comment_disabled": False, "duet_disabled": False, "stitch_disabled": True,
"max_video_post_duration_sec": 600}, "error": {"code": "ok"}})
env.router.add("PUT", "https://upload.tiktok.example/", lambda r: httpx.Response(201))
def test_chunk_plan_rules():
mb = 1024 * 1024
assert chunk_plan(3 * mb) == (3 * mb, 1)
assert chunk_plan(64 * mb) == (64 * mb, 1)
size, count = chunk_plan(100 * mb)
assert (size, count) == (32 * mb, 3) and 100 * mb - size * (count - 1) <= 128 * mb
def test_tiktok_direct_post(env):
_tiktok(env)
env.router.add("POST", "https://open.tiktokapis.com/v2/post/publish/video/init/", {
"data": {"publish_id": "p1", "upload_url": "https://upload.tiktok.example/u"}, "error": {"code": "ok"}})
env.router.add("POST", "https://open.tiktokapis.com/v2/post/publish/status/fetch/", {
"data": {"status": "PUBLISH_COMPLETE", "publicaly_available_post_id": [7311]}, "error": {"code": "ok"}})
job = _run(env, TT, aiGenerated=True, caption="Olha isso #fy")
assert job["status"] == "done", job
assert job["url"] == "https://www.tiktok.com/@litoral/video/7311" and job["draft"] is False
init = json.loads(env.router.find("POST", "https://open.tiktokapis.com/v2/post/publish/video/init/")[0].content)
assert init["source_info"] == {"source": "FILE_UPLOAD", "video_size": 1000, "chunk_size": 1000, "total_chunk_count": 1}
assert init["post_info"]["privacy_level"] == "PUBLIC_TO_EVERYONE" and init["post_info"]["is_aigc"] is True
assert init["post_info"]["title"] == "Olha isso #fy"
put = env.router.find("PUT", "https://upload.tiktok.example/")[0]
assert put.headers["content-range"] == "bytes 0-999/1000" and put.headers["content-type"] == "video/mp4"
status = env.router.find("POST", "https://open.tiktokapis.com/v2/post/publish/status/fetch/")[0]
assert json.loads(status.content) == {"publish_id": "p1"} and status.headers["authorization"] == "Bearer tok"
def test_tiktok_multi_chunk_put(env, monkeypatch):
_tiktok(env)
monkeypatch.setattr(tiktok_api.TikTokApi, "single_max", 300)
monkeypatch.setattr(tiktok_api.TikTokApi, "chunk", 300)
env.router.add("POST", "https://open.tiktokapis.com/v2/post/publish/inbox/video/init/", {
"data": {"publish_id": "p2", "upload_url": "https://upload.tiktok.example/u2"}, "error": {"code": "ok"}})
env.router.add("POST", "https://open.tiktokapis.com/v2/post/publish/status/fetch/", {
"data": {"status": "SEND_TO_USER_INBOX"}, "error": {"code": "ok"}})
job = _run(env, TT, tiktokMode="draft")
assert job["status"] == "done" and job["draft"] is True and job["url"] is None
assert "caixa de entrada" in job["step"]
init = json.loads(env.router.find("POST", "https://open.tiktokapis.com/v2/post/publish/inbox/video/init/")[0].content)
assert init == {"source_info": {"source": "FILE_UPLOAD", "video_size": 1000, "chunk_size": 300, "total_chunk_count": 3}}
ranges = [p.headers["content-range"] for p in env.router.find("PUT", "https://upload.tiktok.example/")]
assert ranges == ["bytes 0-299/1000", "bytes 300-599/1000", "bytes 600-999/1000"] # último leva o resto
assert not env.router.find("POST", "https://open.tiktokapis.com/v2/post/publish/creator_info/query/")
def test_tiktok_unaudited_message(env):
_tiktok(env, options=["SELF_ONLY"])
job = _run(env, TT, privacy="public")
assert job["status"] == "failed" and job["error"] == UNAUDITED
assert "Somente eu" in UNAUDITED and "Rascunho" in UNAUDITED
env.router.add("POST", "https://open.tiktokapis.com/v2/post/publish/video/init/", lambda r: httpx.Response(
403, json={"error": {"code": "unaudited_client_can_only_post_to_private_accounts", "message": "x"}}))
_tiktok(env)
job = _run(env, TT, privacy="public")
assert job["status"] == "failed" and job["error"].startswith(UNAUDITED)
def test_tiktok_private_without_public_link(env):
_tiktok(env)
env.router.add("POST", "https://open.tiktokapis.com/v2/post/publish/video/init/", {
"data": {"publish_id": "p3", "upload_url": "https://upload.tiktok.example/u3"}, "error": {"code": "ok"}})
statuses = iter(["PROCESSING_UPLOAD", "PUBLISH_COMPLETE"])
env.router.add("POST", "https://open.tiktokapis.com/v2/post/publish/status/fetch/", lambda r: httpx.Response(
200, json={"data": {"status": next(statuses)}, "error": {"code": "ok"}}))
job = _run(env, TT, privacy="private")
assert job["status"] == "done" and "Somente eu" in job["step"] and job["url"] is None
init = json.loads(env.router.find("POST", "https://open.tiktokapis.com/v2/post/publish/video/init/")[0].content)
assert init["post_info"]["privacy_level"] == "SELF_ONLY"
def test_tiktok_creator_info_route(env):
_tiktok(env)
info = env.client.get(f"/v1/profiles/{TT}/tiktok/creator-info").json()
assert info == {"nickname": "Litoral", "privacyOptions": ["PUBLIC_TO_EVERYONE", "SELF_ONLY"], "maxDurationS": 600,
"commentDisabled": False, "duetDisabled": False, "stitchDisabled": True}
assert env.client.get(f"/v1/profiles/{YT}/tiktok/creator-info").status_code == 409
# ---------- Instagram
GRAPH = "https://graph.instagram.com/v24.0"
def test_instagram_paste_token(env):
env.router.add("GET", f"{GRAPH}/me", {"user_id": "1784", "username": "litoral", "name": "Litoral",
"account_type": "MEDIA_CREATOR"})
profile = env.client.post(f"/v1/profiles/{IG}/token", json={"accessToken": "IGAA" + "x" * 40}).json()
assert profile["status"] == "connected" and profile["handle"] == "@litoral" and profile["expiresAt"]
assert env.vault.get(f"token:{IG}")["igUserId"] == "1784"
env.router.add("GET", f"{GRAPH}/me", {"user_id": "1", "username": "pessoal", "account_type": "PERSONAL"})
refused = env.client.post(f"/v1/profiles/{IG}/token", json={"accessToken": "IGAA" + "y" * 40})
assert refused.status_code == 400 and "Profissional" in refused.json()["detail"]
def test_instagram_reel_upload(env):
env.connect_profile(IG, secret={"accessToken": "igtok", "accessExpiresAt": time.time() + 50 * 86400,
"igUserId": "1784", "obtainedAt": time.time()})
env.router.add("POST", f"{GRAPH}/1784/media", {"id": "C1", "uri": "https://rupload.facebook.com/ig-api-upload/v24.0/C1"})
env.router.add("POST", "https://rupload.facebook.com/ig-api-upload/v24.0/C1", {"success": True})
statuses = iter(["IN_PROGRESS", "FINISHED"])
env.router.add("GET", f"{GRAPH}/C1", lambda r: httpx.Response(200, json={"status_code": next(statuses)}))
env.router.add("POST", f"{GRAPH}/1784/media_publish", {"id": "M9"})
env.router.add("GET", f"{GRAPH}/M9", {"permalink": "https://www.instagram.com/reel/abc/"})
job = _run(env, IG, aiGenerated=True, caption="Legenda #reels")
assert job["status"] == "done", job
assert job["remoteId"] == "M9" and job["url"] == "https://www.instagram.com/reel/abc/"
form = parse_qs(env.router.find("POST", f"{GRAPH}/1784/media")[0].content.decode())
assert form["media_type"] == ["REELS"] and form["upload_type"] == ["resumable"]
assert form["caption"] == ["Legenda #reels"] and form["is_ai_generated"] == ["true"]
upload = env.router.find("POST", "https://rupload.facebook.com/")[0]
assert upload.headers["authorization"] == "OAuth igtok" and upload.headers["offset"] == "0"
assert upload.headers["file_size"] == "1000" and len(upload.content) == 1000
publish = parse_qs(env.router.find("POST", f"{GRAPH}/1784/media_publish")[0].content.decode())
assert publish["creation_id"] == ["C1"]
assert env.sleeps == [InstagramApi.poll_s]
def test_instagram_rupload_refused_explains_fb_login(env):
env.connect_profile(IG, secret={"accessToken": "igtok", "accessExpiresAt": time.time() + 50 * 86400,
"igUserId": "1784", "obtainedAt": time.time()})
env.router.add("POST", f"{GRAPH}/1784/media", {"id": "C1"})
env.router.add("POST", "https://rupload.facebook.com/", lambda r: httpx.Response(
400, json={"error": {"code": 1, "message": "unsupported"}}))
job = _run(env, IG)
assert job["status"] == "failed" and "Facebook Login for Business" in job["error"]
def test_instagram_refreshes_token_close_to_expiry(env):
env.connect_profile(IG, secret={"accessToken": "old", "accessExpiresAt": time.time() + 5 * 86400,
"igUserId": "1784", "obtainedAt": time.time() - 50 * 86400})
env.router.add("GET", "https://graph.instagram.com/refresh_access_token",
{"access_token": "new", "token_type": "bearer", "expires_in": 5184000})
env.publisher.maintenance()
assert env.vault.get(f"token:{IG}")["accessToken"] == "new"
sent = env.router.find("GET", "https://graph.instagram.com/refresh_access_token")[0]
assert sent.url.params["grant_type"] == "ig_refresh_token" and sent.url.params["access_token"] == "old"
def test_instagram_expired_token_code_190(env):
env.connect_profile(IG, secret={"accessToken": "igtok", "accessExpiresAt": time.time() + 50 * 86400,
"igUserId": "1784", "obtainedAt": time.time()})
env.router.add("POST", f"{GRAPH}/1784/media", lambda r: httpx.Response(
400, json={"error": {"code": 190, "message": "Error validating access token"}}))
job = _run(env, IG)
assert job["status"] == "needs_login"
assert env.client.get(f"/v1/profiles/{IG}").json()["status"] == "expired"
def test_publish_error_kinds():
assert PublishError("x").kind == "failed"
with pytest.raises(PublishError):
raise PublishError("y", "needs_login")