// Ponte do painel com o Publicador (publisher/, 127.0.0.1:4530): o executor que guarda os tokens (cofre DPAPI), // os perfis de navegador do modo "sessão logada" e envia os vídeos às redes. O painel decide o quê e quando // (lib/publishing.ts); o Publicador só executa. Contrato: doc/publicacao/PLANO.md, seção 3. // // A chave e a porta vêm de publisher/.env, como o Clipador (lib/clipper.ts). Segredos (client secret, tokens) // passam por aqui só na ida — nada que o Publicador devolva contém segredo, e as rotas do painel filtram os campos. import fs from "node:fs"; import path from "node:path"; import { ServiceError } from "./http"; import { REPO_ROOT } from "./paths"; import type { ConnectNext, ConnectionMode, NetworkStatus, Platform, Privacy, TiktokMode } from "./types"; const ENV_FILE = path.join(REPO_ROOT, "publisher", ".env"); export const PUBLISHER_OFFLINE = "O Publicador não está rodando — inicie com pnpm dev."; // ---------- formas do contrato (seção 3 do plano) ---------- export type PublisherProfile = { profileId: string; platform: Platform; mode: ConnectionMode | null; status: NetworkStatus; displayName: string | null; handle: string | null; connectedAt: string | null; expiresAt: string | null; lastCheckAt: string | null; lastError: string | null; }; export type PublisherAppState = { configured: boolean; clientId: string | null; redirectUri: string; notes: string }; export type PublisherStatus = { browser: { found: boolean; kind: "chrome" | "msedge" | null; path: string | null }; worker: "idle" | "busy"; queue: number; }; export type PublisherJobInput = { profileId: string; platform: Platform; file: string; cover: string | null; title: string; caption: string; tags: string[]; privacy: Privacy; publishAt: string | null; aiGenerated: boolean; madeForKids: boolean; tiktokMode: TiktokMode; /** * Referência idempotente (≤ 80): o Publicador guarda com UNIQUE e, se ela se repetir, devolve o job existente * em vez de criar outro. O painel manda ":". */ clientRef: string; }; export type PublisherJobStatus = "queued" | "running" | "done" | "failed" | "needs_login" | "canceled"; export type PublisherJob = { jobId: string; profileId: string; platform: string; status: PublisherJobStatus; step: string; progress: number; remoteId: string | null; url: string | null; draft: boolean; error: string | null; createdAt: string; updatedAt: string; }; export type TiktokCreatorInfo = { nickname: string; privacyOptions: string[]; maxDurationS: number; commentDisabled: boolean; duetDisabled: boolean; stitchDisabled: boolean; }; /** profileId do contrato: um perfil por (canal, rede). */ export const profileIdFor = (accountId: string, platform: Platform) => `${accountId}--${platform}`; // ---------- transporte ---------- function readPublisherEnv(): Record { if (!fs.existsSync(ENV_FILE)) return {}; const env: Record = {}; for (const line of fs.readFileSync(ENV_FILE, "utf8").split(/\r?\n/)) { const at = line.indexOf("="); if (at <= 0 || line.trimStart().startsWith("#")) continue; env[line.slice(0, at).trim()] = line.slice(at + 1).trim(); } return env; } function serviceUrl(pathname: string): { url: string; key: string } { const env = readPublisherEnv(); if (!env.PUBLISHER_SERVICE_KEY) { throw new ServiceError("O Publicador não está instalado: rode o setup.bat (ele cria publisher/.env com a chave).", 503); } return { url: `http://127.0.0.1:${env.PUBLISHER_PORT || "4530"}${pathname}`, key: env.PUBLISHER_SERVICE_KEY }; } /** Mensagem de erro do Publicador: `{detail}` em pt-BR (ou a lista de validação do FastAPI). */ async function serviceError(response: Response): Promise { let message = `O Publicador respondeu ${response.status}.`; try { const body = (await response.json()) as { detail?: unknown; error?: unknown }; const detail = body.detail ?? body.error; if (typeof detail === "string" && detail) message = detail; else if (Array.isArray(detail) && detail.length > 0) { message = detail.map((d) => (d && typeof d === "object" && "msg" in d ? String((d as { msg: unknown }).msg) : String(d))).join("; "); } } catch { /* corpo sem JSON: fica a mensagem com o código */ } // 4xx do Publicador = pedido recusado (mensagem dele); 5xx = falha do serviço (502 para o navegador). return new ServiceError(message, response.status >= 500 ? 502 : response.status); } async function publisherFetch(pathname: string, init: RequestInit = {}, timeoutMs = 30_000): Promise { const { url, key } = serviceUrl(pathname); const headers = new Headers(init.headers); headers.set("X-Service-Key", key); if (init.body) headers.set("Content-Type", "application/json"); try { return await fetch(url, { ...init, headers, signal: AbortSignal.timeout(timeoutMs), cache: "no-store" }); } catch (error) { if (error instanceof Error && error.name === "TimeoutError") { throw new ServiceError("O Publicador demorou demais para responder. Veja o terminal do pnpm dev.", 504); } throw new ServiceError(PUBLISHER_OFFLINE, 503); } } async function call(method: string, pathname: string, body?: unknown, timeoutMs?: number): Promise { const response = await publisherFetch(pathname, { method, body: body === undefined ? undefined : JSON.stringify(body) }, timeoutMs); if (!response.ok) throw await serviceError(response); return (await response.json()) as T; } const enc = encodeURIComponent; // ---------- chamadas ---------- export type PublisherOnline = ({ online: true } & PublisherStatus) | { online: false; reason: string }; /** Saúde sem falhar: fora do ar (ou sem chave) vira `online: false` com o motivo em pt-BR. */ export async function publisherStatus(): Promise { try { const status = await call("GET", "/v1/status", undefined, 5_000); return { online: true, browser: status.browser, worker: status.worker, queue: status.queue }; } catch (error) { return { online: false, reason: error instanceof ServiceError ? error.message : PUBLISHER_OFFLINE }; } } /** Só os campos públicos do AppState (o Publicador já não manda segredo; aqui garantimos). */ function cleanApp(app: PublisherAppState): PublisherAppState { return { configured: !!app.configured, clientId: app.clientId ?? null, redirectUri: String(app.redirectUri ?? ""), notes: String(app.notes ?? "") }; } export async function getApps(): Promise> { const apps = await call>("GET", "/v1/apps"); return { youtube: cleanApp(apps.youtube), tiktok: cleanApp(apps.tiktok), instagram: cleanApp(apps.instagram) }; } /** YouTube/TikTok exigem clientId + clientSecret; no Instagram o secret é opcional (redirectUri vem vazio: a Meta não aceita localhost). */ export async function putApp(platform: Platform, input: { clientId: string; clientSecret?: string }): Promise { const body = input.clientSecret ? input : { clientId: input.clientId }; return cleanApp(await call("PUT", `/v1/apps/${platform}`, body)); } export async function deleteApp(platform: Platform): Promise { return cleanApp(await call("DELETE", `/v1/apps/${platform}`)); } export const getProfile = (profileId: string) => call("GET", `/v1/profiles/${enc(profileId)}`, undefined, 15_000); export const connectProfile = (profileId: string, platform: Platform, mode: ConnectionMode) => // Modo sessão abre o navegador: pode demorar um pouco mais. call<{ profile: PublisherProfile; next: ConnectNext }>("POST", `/v1/profiles/${enc(profileId)}/connect`, { platform, mode }, 60_000); export const pasteToken = (profileId: string, accessToken: string) => call("POST", `/v1/profiles/${enc(profileId)}/token`, { accessToken }, 60_000); /** Confere a sessão logada (abre a página de envio e vê se está logado): pode levar até ~2 min. */ export const checkSession = (profileId: string) => call("POST", `/v1/profiles/${enc(profileId)}/session/check`, {}, 150_000); export const openSession = (profileId: string) => call<{ profile: PublisherProfile; next: ConnectNext }>("POST", `/v1/profiles/${enc(profileId)}/session/open`, {}, 60_000); export const deleteProfile = (profileId: string) => call("DELETE", `/v1/profiles/${enc(profileId)}`, undefined, 60_000); export const tiktokCreatorInfo = (profileId: string) => call("GET", `/v1/profiles/${enc(profileId)}/tiktok/creator-info`, undefined, 30_000); /** Números dos posts (dashboard). ids = id do vídeo (YouTube, TikTok) ou código do reel (Instagram). * TikTok e Instagram abrem a janela logada e esperam um envio em andamento: pode levar alguns minutos. */ export type PublisherPostStats = { remoteId: string; views: number | null; likes: number | null; comments: number | null; shares: number | null; saves: number | null }; export const postStats = (profileId: string, ids: string[]) => call<{ capturedAt: string; items: PublisherPostStats[]; missing: string[] }>("POST", `/v1/profiles/${enc(profileId)}/stats`, { ids }, 300_000); export const createJob = (input: PublisherJobInput) => call("POST", "/v1/jobs", input, 30_000); export const getJob = (jobId: string) => call("GET", `/v1/jobs/${enc(jobId)}`, undefined, 15_000); export const cancelJob = (jobId: string) => call("POST", `/v1/jobs/${enc(jobId)}/cancel`, {}, 15_000);