Editor 100% funcional + dashboard + login Supabase + app desktop
Browse filesFUNCAO 1 (editor em massa) — correcoes:
- Render robusto nos 2 modos: molde COM furo transparente (arte por cima, video
pelo buraco) e molde OPACO (video colado por cima na area marcada). Verificado
por inspecao de pixel. Resolve o "so aparece o molde".
- Passo 3: area do video por presets (Centro/Inteiro/Topo/Base) e arrasto no
preview, salva no molde e usada no render. Aviso claro p/ molde sem transparencia.
- Upload nao trava mais: thumbnails viram poster JPG gerado sob demanda no servidor
(GET /thumb/:id), upload em lotes com progresso, <img loading=lazy>.
- Excluir um/todos: sources, biblioteca e moldes. Videos importados por referencia
(pasta do Mac) so saem da lista; o arquivo original NUNCA e apagado.
Dashboard (Inicio): visao geral com numeros, atalhos e proximos posts.
Login + seguranca (Supabase, opcional):
- src/auth.js valida o JWT do Supabase no servidor (HS256, sem deps).
- public/login.html + login.js (Google e e-mail+senha), auth-guard.js protege o app.
- Gate em server.js; /auth/config nao expoe o segredo. Servidor so em 127.0.0.1 +
cabecalhos de seguranca. Se o Supabase nao estiver no .env, roda em modo local.
- SETUP-LOGIN.md com o passo a passo (Supabase + Google).
App desktop (Electron): electron/main.cjs sobe o servidor e abre a janela.
npm run app roda; npm run dist gera o instalador. Continua editavel como um site.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- .env.example +14 -0
- CLAUDE.md +29 -4
- SETUP-LOGIN.md +81 -0
- electron/main.cjs +53 -0
- package-lock.json +0 -0
- package.json +24 -0
- public/app.js +225 -21
- public/auth-guard.js +44 -0
- public/index.html +76 -12
- public/login.html +59 -0
- public/login.js +50 -0
- public/style.css +17 -0
- src/auth.js +82 -0
- src/config.js +9 -0
- src/db.js +10 -0
- src/editor/mold.js +10 -3
- src/editor/render.js +22 -13
- src/ffmpeg.js +17 -0
- src/routes/editor.js +96 -6
- src/server.js +37 -5
|
@@ -16,6 +16,20 @@ ENCRYPTION_KEY=troque-isto-por-uma-chave-aleatoria-de-32-bytes
|
|
| 16 |
# Fuso horario usado nos agendamentos (horarios das campanhas)
|
| 17 |
TZ=America/Sao_Paulo
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
# ---------------------------------------------------------------------------
|
| 20 |
# YouTube (Google Cloud Console -> API "YouTube Data API v3" -> OAuth Client)
|
| 21 |
# Redirect URI: http://localhost:4310/oauth/youtube/callback
|
|
|
|
| 16 |
# Fuso horario usado nos agendamentos (horarios das campanhas)
|
| 17 |
TZ=America/Sao_Paulo
|
| 18 |
|
| 19 |
+
# ---------------------------------------------------------------------------
|
| 20 |
+
# LOGIN DOS USUARIOS (Supabase) — OPCIONAL.
|
| 21 |
+
# Se deixar VAZIO, o app roda em modo local (sem tela de login).
|
| 22 |
+
# Se preencher, o app passa a EXIGIR login (Google ou e-mail+senha).
|
| 23 |
+
# Onde achar: painel do Supabase -> Project Settings -> API.
|
| 24 |
+
# SUPABASE_URL = "Project URL"
|
| 25 |
+
# SUPABASE_ANON_KEY = "anon public" (pode ir pro cliente, e publica)
|
| 26 |
+
# SUPABASE_JWT_SECRET = Project Settings -> API -> "JWT Secret" (NUNCA exponha)
|
| 27 |
+
# Passo a passo completo em SETUP-LOGIN.md.
|
| 28 |
+
# ---------------------------------------------------------------------------
|
| 29 |
+
SUPABASE_URL=
|
| 30 |
+
SUPABASE_ANON_KEY=
|
| 31 |
+
SUPABASE_JWT_SECRET=
|
| 32 |
+
|
| 33 |
# ---------------------------------------------------------------------------
|
| 34 |
# YouTube (Google Cloud Console -> API "YouTube Data API v3" -> OAuth Client)
|
| 35 |
# Redirect URI: http://localhost:4310/oauth/youtube/callback
|
|
@@ -36,6 +36,7 @@ src/
|
|
| 36 |
db.js Banco SQLite (tabelas) + funções de acesso
|
| 37 |
ffmpeg.js Aponta o fluent-ffmpeg para os binários estáticos
|
| 38 |
crypto.js Cifra/decifra os tokens das contas
|
|
|
|
| 39 |
|
| 40 |
editor/ FUNÇÃO 1 — edição em massa
|
| 41 |
mold.js Detecta a área transparente do molde PNG (onde o vídeo entra)
|
|
@@ -70,11 +71,35 @@ data/ (não vai pro git) banco + vídeos + saídas + daemon.log
|
|
| 70 |
servidor + agendador sempre rodando e inicia ao logar — assim os posts disparam mesmo
|
| 71 |
com o navegador fechado. `npm run daemon:uninstall` remove. Logs em `data/daemon.log`.
|
| 72 |
|
| 73 |
-
## Editor: posicionamento (pan)
|
| 74 |
|
| 75 |
-
No passo 3 do Editor há um preview em canvas
|
| 76 |
-
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
## Banco de dados (tabelas)
|
| 80 |
|
|
|
|
| 36 |
db.js Banco SQLite (tabelas) + funções de acesso
|
| 37 |
ffmpeg.js Aponta o fluent-ffmpeg para os binários estáticos
|
| 38 |
crypto.js Cifra/decifra os tokens das contas
|
| 39 |
+
auth.js Login dos usuários (valida o JWT do Supabase) — opcional
|
| 40 |
|
| 41 |
editor/ FUNÇÃO 1 — edição em massa
|
| 42 |
mold.js Detecta a área transparente do molde PNG (onde o vídeo entra)
|
|
|
|
| 71 |
servidor + agendador sempre rodando e inicia ao logar — assim os posts disparam mesmo
|
| 72 |
com o navegador fechado. `npm run daemon:uninstall` remove. Logs em `data/daemon.log`.
|
| 73 |
|
| 74 |
+
## Editor: área do vídeo + posicionamento (pan)
|
| 75 |
|
| 76 |
+
No passo 3 do Editor há um preview em canvas. O usuário define a **área** onde o
|
| 77 |
+
vídeo entra de 3 formas: **presets** (Centro/Inteiro/Topo/Base), **arrastando** um
|
| 78 |
+
retângulo no preview, ou pela **detecção automática** do furo transparente do PNG.
|
| 79 |
+
A área é salva no molde (`area_x/y/w/h`, `POST /api/editor/molds/:id/area`).
|
| 80 |
+
O **render** decide a composição pelo `has_alpha` do molde: com furo transparente,
|
| 81 |
+
a arte vai por cima (vídeo aparece pelo buraco); molde opaco, o vídeo é colado por
|
| 82 |
+
cima da arte na área marcada. O **enquadramento** (`focusX`/`focusY`, 0–100) é o
|
| 83 |
+
`crop` do ffmpeg e vale para todo o lote.
|
| 84 |
+
|
| 85 |
+
Thumbnails são **posters JPG gerados sob demanda** (`GET /api/editor/thumb/:id`,
|
| 86 |
+
ffmpeg) — não usamos `<video>` na grade (travava o PC). Upload é feito em lotes.
|
| 87 |
+
Excluir: `DELETE /sources/:id|/sources|/library/:id|/library|/molds/:id`. Vídeos
|
| 88 |
+
importados por referência (pasta do Mac) só somem da lista — o original não é apagado.
|
| 89 |
+
|
| 90 |
+
## Login e segurança (opcional, Supabase)
|
| 91 |
+
|
| 92 |
+
`src/auth.js` valida o JWT do Supabase no servidor; `public/login.html` faz o login
|
| 93 |
+
(Google / e-mail+senha); `public/auth-guard.js` protege o app e mantém o cookie.
|
| 94 |
+
Só liga se `SUPABASE_URL/ANON_KEY/JWT_SECRET` estiverem no `.env` (senão, modo local).
|
| 95 |
+
Gate em `src/server.js`. Passo a passo: `SETUP-LOGIN.md`. O servidor escuta só em
|
| 96 |
+
`127.0.0.1` e manda cabeçalhos de segurança.
|
| 97 |
+
|
| 98 |
+
## Virar aplicativo (desktop, Electron)
|
| 99 |
+
|
| 100 |
+
`electron/main.cjs` sobe o `src/server.js` e abre uma janela. `npm run app` roda;
|
| 101 |
+
`npm run dist` (electron-builder) gera o instalador. É o **mesmo site por dentro** —
|
| 102 |
+
editar os arquivos e reabrir continua funcionando normalmente.
|
| 103 |
|
| 104 |
## Banco de dados (tabelas)
|
| 105 |
|
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🔐 Login dos usuários (Supabase + Google) — passo a passo
|
| 2 |
+
|
| 3 |
+
O PagsDark já vem com **tela de login pronta** (Google e e-mail+senha). Ela só
|
| 4 |
+
**liga** quando você preenche as 3 variáveis do Supabase no `.env`. Enquanto
|
| 5 |
+
estiverem vazias, o app roda em **modo local** (sem login), como antes.
|
| 6 |
+
|
| 7 |
+
> Por que Supabase? Ele já é o **banco de dados dos seus usuários** (guarda quem
|
| 8 |
+
> tem acesso, com senha/Google, de forma segura) e cuida do login com Google sem
|
| 9 |
+
> você precisar manter servidor de autenticação. É gratuito para começar.
|
| 10 |
+
|
| 11 |
+
---
|
| 12 |
+
|
| 13 |
+
## 1) Criar o projeto no Supabase
|
| 14 |
+
1. Acesse **https://supabase.com** e crie uma conta (pode entrar com o Google).
|
| 15 |
+
2. **New project** → dê um nome (ex.: `pagsdark`), defina uma senha de banco e crie.
|
| 16 |
+
3. Espere ~1 min até o projeto ficar pronto.
|
| 17 |
+
|
| 18 |
+
## 2) Pegar as 3 chaves
|
| 19 |
+
No projeto, vá em **Project Settings (engrenagem) → API** e copie:
|
| 20 |
+
|
| 21 |
+
| Variável no `.env` | Onde fica no Supabase | Pode ser pública? |
|
| 22 |
+
|------------------------|-----------------------------------------------|-------------------|
|
| 23 |
+
| `SUPABASE_URL` | **Project URL** | sim |
|
| 24 |
+
| `SUPABASE_ANON_KEY` | **Project API keys → `anon` `public`** | sim |
|
| 25 |
+
| `SUPABASE_JWT_SECRET` | **JWT Settings → JWT Secret** (botão *Reveal*) | **NÃO — segredo** |
|
| 26 |
+
|
| 27 |
+
Cole no seu arquivo `.env`:
|
| 28 |
+
```
|
| 29 |
+
SUPABASE_URL=https://xxxxxxxx.supabase.co
|
| 30 |
+
SUPABASE_ANON_KEY=eyJhbGciOi...
|
| 31 |
+
SUPABASE_JWT_SECRET=seu-jwt-secret-aqui
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
## 3) Liberar o endereço do app (Redirect URLs)
|
| 35 |
+
Em **Authentication → URL Configuration**:
|
| 36 |
+
- **Site URL**: `http://localhost:4310`
|
| 37 |
+
- **Redirect URLs** (Add URL): `http://localhost:4310/login`
|
| 38 |
+
|
| 39 |
+
> Quando você empacotar como app desktop, o endereço continua sendo
|
| 40 |
+
> `http://localhost:4310` — então não muda nada aqui.
|
| 41 |
+
|
| 42 |
+
## 4) Ativar o login com Google
|
| 43 |
+
1. Em **Authentication → Providers → Google**, ligue o provider.
|
| 44 |
+
2. O Supabase mostra um **Callback URL** (algo como
|
| 45 |
+
`https://xxxx.supabase.co/auth/v1/callback`). Copie.
|
| 46 |
+
3. No **Google Cloud Console** (https://console.cloud.google.com):
|
| 47 |
+
- **APIs & Services → Credentials → Create Credentials → OAuth client ID**.
|
| 48 |
+
- Tipo: **Web application**.
|
| 49 |
+
- **Authorized redirect URIs**: cole o *Callback URL* do Supabase.
|
| 50 |
+
- Crie e copie o **Client ID** e o **Client secret**.
|
| 51 |
+
4. De volta ao Supabase (provider Google), cole **Client ID** e **Client secret** e salve.
|
| 52 |
+
|
| 53 |
+
> Login por **e-mail+senha** já funciona sem o Google, assim que as 3 chaves do
|
| 54 |
+
> passo 2 estiverem no `.env`. O Google é opcional (mas recomendado).
|
| 55 |
+
|
| 56 |
+
## 5) Reiniciar o app
|
| 57 |
+
```
|
| 58 |
+
npm start # ou: npm run app (versão desktop)
|
| 59 |
+
```
|
| 60 |
+
Agora ao abrir `http://localhost:4310` você cai na **tela de login**. Entre com
|
| 61 |
+
Google ou crie uma conta por e-mail. Os usuários ficam salvos no Supabase.
|
| 62 |
+
|
| 63 |
+
---
|
| 64 |
+
|
| 65 |
+
## Como a segurança funciona aqui (resumo)
|
| 66 |
+
- O login acontece no Supabase; o app recebe um **token assinado (JWT)**.
|
| 67 |
+
- **O servidor valida a assinatura do token a cada requisição** (`src/auth.js`).
|
| 68 |
+
Não dá para burlar pelo navegador — rotas e mídias ficam protegidas.
|
| 69 |
+
- O **JWT Secret nunca vai para o navegador** (só `URL` e `anon key`, que são
|
| 70 |
+
públicas por design).
|
| 71 |
+
- Os **tokens das suas redes sociais** continuam cifrados no banco (AES-256-GCM).
|
| 72 |
+
- O servidor escuta **apenas em `127.0.0.1`** (não fica exposto na rede) e envia
|
| 73 |
+
cabeçalhos de segurança (`X-Content-Type-Options`, `X-Frame-Options`, etc.).
|
| 74 |
+
- `.env`, banco e mídias estão no `.gitignore` — **não vão para o GitHub**.
|
| 75 |
+
|
| 76 |
+
## Quero isolar os dados por usuário (multiusuário de verdade)
|
| 77 |
+
Hoje o banco local (SQLite) é **um por instalação** — perfeito para uso pessoal
|
| 78 |
+
no seu Mac, com login controlando o acesso. Se mais tarde você quiser que cada
|
| 79 |
+
usuário tenha seus próprios workspaces/campanhas separados na **nuvem** (acessível
|
| 80 |
+
de qualquer lugar, agendador rodando 24/7), isso é um passo maior: migrar os dados
|
| 81 |
+
para o Supabase e hospedar o servidor. Dá para fazer — é só pedir.
|
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Empacotamento como APLICATIVO DESKTOP (Electron).
|
| 2 |
+
// O Electron sobe o mesmo servidor local (src/server.js) num processo filho e
|
| 3 |
+
// abre uma janela apontando para ele. Ou seja: o app continua sendo o mesmo
|
| 4 |
+
// site — você edita os arquivos normalmente e as mudanças aparecem ao reabrir.
|
| 5 |
+
const { app, BrowserWindow } = require('electron');
|
| 6 |
+
const path = require('path');
|
| 7 |
+
const { spawn } = require('child_process');
|
| 8 |
+
const http = require('http');
|
| 9 |
+
|
| 10 |
+
const ROOT = path.join(__dirname, '..');
|
| 11 |
+
const PORT = process.env.PORT || 4310;
|
| 12 |
+
const URL = `http://localhost:${PORT}`;
|
| 13 |
+
let serverProc = null;
|
| 14 |
+
let win = null;
|
| 15 |
+
|
| 16 |
+
function startServer() {
|
| 17 |
+
// Usa o Node do sistema (a versão instalada no Mac tem o node:sqlite que o app usa).
|
| 18 |
+
serverProc = spawn('node', [path.join(ROOT, 'src', 'server.js')], {
|
| 19 |
+
cwd: ROOT,
|
| 20 |
+
env: { ...process.env, PORT: String(PORT) },
|
| 21 |
+
stdio: 'inherit',
|
| 22 |
+
shell: process.platform === 'win32',
|
| 23 |
+
});
|
| 24 |
+
serverProc.on('error', (e) => console.error('[electron] falha ao subir o servidor (Node instalado?):', e));
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
function waitForServer(cb, tries = 0) {
|
| 28 |
+
http.get(URL + '/auth/config', () => cb())
|
| 29 |
+
.on('error', () => {
|
| 30 |
+
if (tries > 80) return cb(); // ~40s; abre mesmo assim
|
| 31 |
+
setTimeout(() => waitForServer(cb, tries + 1), 500);
|
| 32 |
+
});
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
function createWindow() {
|
| 36 |
+
win = new BrowserWindow({
|
| 37 |
+
width: 1280, height: 860, minWidth: 980, minHeight: 640,
|
| 38 |
+
backgroundColor: '#0c0a09', title: 'PagsDark',
|
| 39 |
+
webPreferences: { contextIsolation: true, nodeIntegration: false },
|
| 40 |
+
});
|
| 41 |
+
win.loadURL(URL);
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
app.whenReady().then(() => {
|
| 45 |
+
startServer();
|
| 46 |
+
waitForServer(createWindow);
|
| 47 |
+
app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow(); });
|
| 48 |
+
});
|
| 49 |
+
|
| 50 |
+
function stopServer() { if (serverProc) { try { serverProc.kill(); } catch {} serverProc = null; } }
|
| 51 |
+
app.on('window-all-closed', () => { stopServer(); if (process.platform !== 'darwin') app.quit(); });
|
| 52 |
+
app.on('quit', stopServer);
|
| 53 |
+
app.on('before-quit', stopServer);
|
|
The diff for this file is too large to render.
See raw diff
|
|
|
|
@@ -3,6 +3,7 @@
|
|
| 3 |
"version": "0.1.0",
|
| 4 |
"private": true,
|
| 5 |
"type": "module",
|
|
|
|
| 6 |
"description": "PagsDark - plataforma local: edicao de video em massa + agendamento automatico de posts (Kwai, TikTok, Instagram, YouTube Shorts).",
|
| 7 |
"engines": {
|
| 8 |
"node": ">=22.5.0"
|
|
@@ -10,10 +11,29 @@
|
|
| 10 |
"scripts": {
|
| 11 |
"start": "node --no-warnings src/server.js",
|
| 12 |
"dev": "node --no-warnings --watch src/server.js",
|
|
|
|
|
|
|
| 13 |
"daemon:install": "bash scripts/install-daemon.sh",
|
| 14 |
"daemon:uninstall": "bash scripts/uninstall-daemon.sh",
|
| 15 |
"daemon:status": "launchctl list | grep com.pagsdark.server || echo 'daemon nao esta rodando'"
|
| 16 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
"dependencies": {
|
| 18 |
"archiver": "^7.0.1",
|
| 19 |
"axios": "^1.7.7",
|
|
@@ -27,5 +47,9 @@
|
|
| 27 |
"multer": "^1.4.5-lts.1",
|
| 28 |
"node-cron": "^3.0.3",
|
| 29 |
"sharp": "^0.33.5"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
}
|
| 31 |
}
|
|
|
|
| 3 |
"version": "0.1.0",
|
| 4 |
"private": true,
|
| 5 |
"type": "module",
|
| 6 |
+
"main": "electron/main.cjs",
|
| 7 |
"description": "PagsDark - plataforma local: edicao de video em massa + agendamento automatico de posts (Kwai, TikTok, Instagram, YouTube Shorts).",
|
| 8 |
"engines": {
|
| 9 |
"node": ">=22.5.0"
|
|
|
|
| 11 |
"scripts": {
|
| 12 |
"start": "node --no-warnings src/server.js",
|
| 13 |
"dev": "node --no-warnings --watch src/server.js",
|
| 14 |
+
"app": "electron electron/main.cjs",
|
| 15 |
+
"dist": "electron-builder",
|
| 16 |
"daemon:install": "bash scripts/install-daemon.sh",
|
| 17 |
"daemon:uninstall": "bash scripts/uninstall-daemon.sh",
|
| 18 |
"daemon:status": "launchctl list | grep com.pagsdark.server || echo 'daemon nao esta rodando'"
|
| 19 |
},
|
| 20 |
+
"build": {
|
| 21 |
+
"appId": "com.pagsdark.app",
|
| 22 |
+
"productName": "PagsDark",
|
| 23 |
+
"files": [
|
| 24 |
+
"src/**/*",
|
| 25 |
+
"public/**/*",
|
| 26 |
+
"electron/**/*",
|
| 27 |
+
"package.json"
|
| 28 |
+
],
|
| 29 |
+
"mac": {
|
| 30 |
+
"category": "public.app-category.video",
|
| 31 |
+
"target": "dmg"
|
| 32 |
+
},
|
| 33 |
+
"win": {
|
| 34 |
+
"target": "nsis"
|
| 35 |
+
}
|
| 36 |
+
},
|
| 37 |
"dependencies": {
|
| 38 |
"archiver": "^7.0.1",
|
| 39 |
"axios": "^1.7.7",
|
|
|
|
| 47 |
"multer": "^1.4.5-lts.1",
|
| 48 |
"node-cron": "^3.0.3",
|
| 49 |
"sharp": "^0.33.5"
|
| 50 |
+
},
|
| 51 |
+
"devDependencies": {
|
| 52 |
+
"electron": "^31.7.7",
|
| 53 |
+
"electron-builder": "^24.13.3"
|
| 54 |
}
|
| 55 |
}
|
|
@@ -30,20 +30,60 @@ const state = {
|
|
| 30 |
molds: [],
|
| 31 |
sourcesArr: [],
|
| 32 |
focusX: 50, focusY: 50, sampleIdx: 0,
|
|
|
|
|
|
|
| 33 |
activeWs: null,
|
| 34 |
settings: null,
|
| 35 |
};
|
| 36 |
let PLATFORMS = [];
|
| 37 |
|
| 38 |
// ===== Tabs =====
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
$$('nav button').forEach((b) => b.onclick = () => {
|
| 40 |
$$('nav button').forEach((x) => x.classList.toggle('active', x === b));
|
| 41 |
$$('.tab').forEach((t) => t.classList.toggle('active', t.id === `tab-${b.dataset.tab}`));
|
| 42 |
if (b.dataset.title) $('#pageTitle').textContent = b.dataset.title;
|
| 43 |
if (b.dataset.sub) $('#pageSub').textContent = b.dataset.sub;
|
|
|
|
| 44 |
if (b.dataset.tab === 'contas') loadContas();
|
| 45 |
if (b.dataset.tab === 'agendar') refreshScheduleTab();
|
| 46 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
// ===================== EDITOR =====================
|
| 49 |
async function loadMolds() {
|
|
@@ -54,18 +94,44 @@ async function loadMolds() {
|
|
| 54 |
const d = document.createElement('div');
|
| 55 |
d.className = 'thumb' + (state.selMold === m.id ? ' sel' : '');
|
| 56 |
d.innerHTML = `<img src="/mold-file/${m.id}" /><span class="tag">${m.canvas_w}×${m.canvas_h}</span>
|
| 57 |
-
<span class="pick">✓</span><span class="name">${m.name}</span>`;
|
| 58 |
-
d.onclick = () =>
|
|
|
|
| 59 |
box.appendChild(d);
|
| 60 |
});
|
| 61 |
refreshPreview();
|
| 62 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
$('#moldUpload').onclick = async () => {
|
| 64 |
const f = $('#moldFile').files[0];
|
| 65 |
if (!f) return toast('Escolha um PNG.', 'err');
|
| 66 |
const fd = new FormData(); fd.append('mold', f);
|
| 67 |
-
try {
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
};
|
| 70 |
|
| 71 |
async function loadSources() {
|
|
@@ -74,9 +140,10 @@ async function loadSources() {
|
|
| 74 |
$('#sourceCount').textContent = src.length
|
| 75 |
? `${src.length} vídeo(s) carregado(s). Selecione alguns ou deixe sem seleção para usar todos.`
|
| 76 |
: 'Nenhum vídeo carregado.';
|
|
|
|
| 77 |
const box = $('#sourceList');
|
| 78 |
box.innerHTML = '';
|
| 79 |
-
src.slice(0, MAX_THUMBS).forEach((m) => box.appendChild(mediaThumb(m, state.selSources, () => { loadSources(); })));
|
| 80 |
if (src.length > MAX_THUMBS) {
|
| 81 |
const more = document.createElement('p'); more.className = 'muted';
|
| 82 |
more.textContent = `+${src.length - MAX_THUMBS} vídeos não exibidos (incluídos se nada estiver selecionado).`;
|
|
@@ -84,20 +151,59 @@ async function loadSources() {
|
|
| 84 |
}
|
| 85 |
refreshPreview();
|
| 86 |
}
|
| 87 |
-
function
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
const d = document.createElement('div');
|
| 89 |
d.className = 'thumb' + (selSet.has(m.id) ? ' sel' : '');
|
| 90 |
-
d.innerHTML = `<
|
| 91 |
-
<span class="pick">✓</span>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
d.onclick = () => { selSet.has(m.id) ? selSet.delete(m.id) : selSet.add(m.id); reload(); };
|
|
|
|
| 93 |
return d;
|
| 94 |
}
|
|
|
|
|
|
|
| 95 |
$('#videoUpload').onclick = async () => {
|
| 96 |
-
const files = $('#videoFiles').files;
|
| 97 |
if (!files.length) return toast('Escolha vídeos.', 'err');
|
| 98 |
-
const
|
| 99 |
-
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
};
|
| 102 |
$('#folderImport').onclick = async () => {
|
| 103 |
const folder = $('#folderPath').value.trim();
|
|
@@ -117,35 +223,42 @@ function currentSample() {
|
|
| 117 |
function refreshPreview() {
|
| 118 |
const canvas = $('#previewCanvas'); if (!canvas) return;
|
| 119 |
const hint = $('#previewHint');
|
| 120 |
-
const mold = currentMold()
|
| 121 |
-
if (!mold
|
| 122 |
if (hint) hint.style.display = '';
|
|
|
|
| 123 |
canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
|
| 124 |
return;
|
| 125 |
}
|
| 126 |
if (hint) hint.style.display = 'none';
|
| 127 |
-
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
| 129 |
if (pv.moldId !== mold.id) {
|
| 130 |
pv.moldId = mold.id; pv.imgReady = false; pv.img = new Image();
|
| 131 |
pv.img.onload = () => { pv.imgReady = true; drawPreview(); };
|
| 132 |
pv.img.src = '/mold-file/' + mold.id;
|
| 133 |
}
|
| 134 |
-
|
|
|
|
| 135 |
pv.sampleId = sample.id; pv.vidReady = false;
|
| 136 |
if (!pv.video) { pv.video = document.createElement('video'); pv.video.muted = true; pv.video.playsInline = true; }
|
| 137 |
pv.video.onloadeddata = () => { try { pv.video.currentTime = Math.min(1, (pv.video.duration || 2) / 2); } catch (e) {} };
|
| 138 |
pv.video.onseeked = () => { pv.vidReady = true; drawPreview(); };
|
| 139 |
pv.video.src = '/preview/' + sample.id; pv.video.load();
|
|
|
|
|
|
|
| 140 |
}
|
| 141 |
drawPreview();
|
| 142 |
}
|
| 143 |
function drawPreview() {
|
| 144 |
const canvas = $('#previewCanvas'); if (!canvas) return;
|
| 145 |
-
const mold = currentMold(); if (!mold) return;
|
| 146 |
const ctx = canvas.getContext('2d');
|
| 147 |
const s = canvas.width / mold.canvas_w;
|
| 148 |
-
const ax =
|
| 149 |
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
| 150 |
ctx.fillStyle = '#000'; ctx.fillRect(ax, ay, aw, ah);
|
| 151 |
if (pv.vidReady && pv.video.videoWidth) {
|
|
@@ -157,7 +270,73 @@ function drawPreview() {
|
|
| 157 |
ctx.restore();
|
| 158 |
}
|
| 159 |
if (pv.imgReady) ctx.drawImage(pv.img, 0, 0, canvas.width, canvas.height);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
$('#focusX').oninput = (e) => { state.focusX = +e.target.value; drawPreview(); };
|
| 162 |
$('#focusY').oninput = (e) => { state.focusY = +e.target.value; drawPreview(); };
|
| 163 |
$('#sampleNext').onclick = () => { state.sampleIdx++; refreshPreview(); };
|
|
@@ -165,6 +344,15 @@ $('#centerFocus').onclick = () => { state.focusX = 50; state.focusY = 50; $('#fo
|
|
| 165 |
|
| 166 |
$('#renderBtn').onclick = async () => {
|
| 167 |
if (!state.selMold) return toast('Selecione um molde.', 'err');
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
try {
|
| 169 |
const { jobId } = await api('POST', '/api/editor/render', {
|
| 170 |
moldId: state.selMold, sourceIds: [...state.selSources],
|
|
@@ -375,9 +563,10 @@ $('#genSlots').onclick = () => {
|
|
| 375 |
};
|
| 376 |
async function loadLibrary() {
|
| 377 |
const lib = await api('GET', '/api/editor/library');
|
|
|
|
| 378 |
const box = $('#libList'); box.innerHTML = '';
|
| 379 |
if (!lib.length) { box.innerHTML = '<p class="muted">Nenhum vídeo renderizado ainda. Use o Editor primeiro.</p>'; updateSummary(); return; }
|
| 380 |
-
lib.slice(0, MAX_THUMBS).forEach((m) => box.appendChild(mediaThumb(m, state.selLib, () => { loadLibrary(); })));
|
| 381 |
if (lib.length > MAX_THUMBS) {
|
| 382 |
const p = document.createElement('p'); p.className = 'muted';
|
| 383 |
p.textContent = `+${lib.length - MAX_THUMBS} não exibidos (incluídos se nada for selecionado).`;
|
|
@@ -451,6 +640,21 @@ async function loadPosts() {
|
|
| 451 |
${posts.length > 100 ? `<p class="muted">+${posts.length - 100} posts…</p>` : ''}`;
|
| 452 |
}
|
| 453 |
window.cancelPost = async (id) => { await api('POST', `/api/schedule/posts/${id}/cancel`); loadPosts(); };
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 454 |
|
| 455 |
// ===== Init =====
|
| 456 |
-
|
|
|
|
|
|
|
|
|
| 30 |
molds: [],
|
| 31 |
sourcesArr: [],
|
| 32 |
focusX: 50, focusY: 50, sampleIdx: 0,
|
| 33 |
+
area: null, // { x, y, w, h } em pixels do molde (onde o video entra)
|
| 34 |
+
areaDirty: false, // true quando o usuario mexeu na area e ainda nao salvou
|
| 35 |
activeWs: null,
|
| 36 |
settings: null,
|
| 37 |
};
|
| 38 |
let PLATFORMS = [];
|
| 39 |
|
| 40 |
// ===== Tabs =====
|
| 41 |
+
function switchTab(name) {
|
| 42 |
+
const b = $$('nav button').find((x) => x.dataset.tab === name);
|
| 43 |
+
if (b) b.click();
|
| 44 |
+
}
|
| 45 |
$$('nav button').forEach((b) => b.onclick = () => {
|
| 46 |
$$('nav button').forEach((x) => x.classList.toggle('active', x === b));
|
| 47 |
$$('.tab').forEach((t) => t.classList.toggle('active', t.id === `tab-${b.dataset.tab}`));
|
| 48 |
if (b.dataset.title) $('#pageTitle').textContent = b.dataset.title;
|
| 49 |
if (b.dataset.sub) $('#pageSub').textContent = b.dataset.sub;
|
| 50 |
+
if (b.dataset.tab === 'inicio') loadInicio();
|
| 51 |
if (b.dataset.tab === 'contas') loadContas();
|
| 52 |
if (b.dataset.tab === 'agendar') refreshScheduleTab();
|
| 53 |
});
|
| 54 |
+
// Cartoes de atalho do dashboard
|
| 55 |
+
$$('.card.action').forEach((c) => c.onclick = () => switchTab(c.dataset.go));
|
| 56 |
+
|
| 57 |
+
// ===================== INÍCIO (DASHBOARD) =====================
|
| 58 |
+
async function loadInicio() {
|
| 59 |
+
const [molds, sources, lib, camps, posts] = await Promise.all([
|
| 60 |
+
api('GET', '/api/editor/molds').catch(() => []),
|
| 61 |
+
api('GET', '/api/editor/sources').catch(() => []),
|
| 62 |
+
api('GET', '/api/editor/library').catch(() => []),
|
| 63 |
+
api('GET', '/api/schedule/campaigns').catch(() => []),
|
| 64 |
+
api('GET', '/api/schedule/posts').catch(() => []),
|
| 65 |
+
]);
|
| 66 |
+
const scheduled = posts.filter((p) => p.status === 'scheduled').length;
|
| 67 |
+
const posted = posts.filter((p) => p.status === 'posted').length;
|
| 68 |
+
const stats = [
|
| 69 |
+
['🖼️', 'Moldes', molds.length],
|
| 70 |
+
['🎬', 'Vídeos carregados', sources.length],
|
| 71 |
+
['✨', 'Renderizados', lib.length],
|
| 72 |
+
['📅', 'Campanhas', camps.length],
|
| 73 |
+
['⏳', 'Posts agendados', scheduled],
|
| 74 |
+
['✅', 'Já postados', posted],
|
| 75 |
+
];
|
| 76 |
+
$('#dashStats').innerHTML = stats.map(([ic, lbl, v]) =>
|
| 77 |
+
`<div class="card stat"><span class="si">${ic}</span><div><div class="sv">${v}</div><div class="sl">${lbl}</div></div></div>`).join('');
|
| 78 |
+
const next = posts.filter((p) => p.status === 'scheduled')
|
| 79 |
+
.sort((a, b) => a.scheduled_at.localeCompare(b.scheduled_at)).slice(0, 6);
|
| 80 |
+
const box = $('#dashNext');
|
| 81 |
+
if (!next.length) { box.innerHTML = '<p class="muted">Nenhum post agendado ainda. Crie uma campanha na aba Agendar.</p>'; return; }
|
| 82 |
+
box.innerHTML = `<table><thead><tr><th>Quando</th><th>Conta</th><th>Status</th></tr></thead><tbody>${
|
| 83 |
+
next.map((p) => `<tr><td>${p.scheduled_at.replace('T', ' ').slice(0, 16)}</td>
|
| 84 |
+
<td>${platIcon(p.platform)} ${p.account_name || p.platform}</td>
|
| 85 |
+
<td class="status-${p.status}">${p.status}</td></tr>`).join('')}</tbody></table>`;
|
| 86 |
+
}
|
| 87 |
|
| 88 |
// ===================== EDITOR =====================
|
| 89 |
async function loadMolds() {
|
|
|
|
| 94 |
const d = document.createElement('div');
|
| 95 |
d.className = 'thumb' + (state.selMold === m.id ? ' sel' : '');
|
| 96 |
d.innerHTML = `<img src="/mold-file/${m.id}" /><span class="tag">${m.canvas_w}×${m.canvas_h}</span>
|
| 97 |
+
<span class="pick">✓</span><button class="del" title="Excluir molde">✕</button><span class="name">${m.name}</span>`;
|
| 98 |
+
d.onclick = () => selectMold(m.id);
|
| 99 |
+
d.querySelector('.del').onclick = (e) => { e.stopPropagation(); delMold(m.id); };
|
| 100 |
box.appendChild(d);
|
| 101 |
});
|
| 102 |
refreshPreview();
|
| 103 |
}
|
| 104 |
+
function selectMold(id) {
|
| 105 |
+
if (state.selMold === id) return; // ja selecionado: mantem (nao perde o preview nem a area em edicao)
|
| 106 |
+
if (state.areaDirty && !confirm('Você ajustou a área e não salvou. Trocar de molde vai descartar esse ajuste. Continuar?')) return;
|
| 107 |
+
state.selMold = id;
|
| 108 |
+
syncAreaFromMold();
|
| 109 |
+
loadMolds();
|
| 110 |
+
}
|
| 111 |
+
// Copia a area salva do molde selecionado para o estado local (ponto de partida da edicao).
|
| 112 |
+
function syncAreaFromMold() {
|
| 113 |
+
const m = currentMold();
|
| 114 |
+
state.area = m ? { x: m.area_x, y: m.area_y, w: m.area_w, h: m.area_h } : null;
|
| 115 |
+
state.areaDirty = false;
|
| 116 |
+
}
|
| 117 |
+
async function delMold(id) {
|
| 118 |
+
if (!confirm('Excluir este molde?')) return;
|
| 119 |
+
await api('DELETE', '/api/editor/molds/' + id);
|
| 120 |
+
if (state.selMold === id) { state.selMold = null; state.area = null; }
|
| 121 |
+
loadMolds();
|
| 122 |
+
}
|
| 123 |
$('#moldUpload').onclick = async () => {
|
| 124 |
const f = $('#moldFile').files[0];
|
| 125 |
if (!f) return toast('Escolha um PNG.', 'err');
|
| 126 |
const fd = new FormData(); fd.append('mold', f);
|
| 127 |
+
try {
|
| 128 |
+
const m = await api('POST', '/api/editor/molds', fd, true);
|
| 129 |
+
state.selMold = m.id;
|
| 130 |
+
await loadMolds();
|
| 131 |
+
syncAreaFromMold();
|
| 132 |
+
if (m.area_auto) toast(`Molde adicionado: área transparente detectada ${m.area_w}×${m.area_h}.`, 'ok');
|
| 133 |
+
else toast('Molde adicionado (PNG opaco). No passo 3, marque onde o vídeo entra — ele será colado nessa área.', 'ok');
|
| 134 |
+
} catch (e) { toast(e.message, 'err'); }
|
| 135 |
};
|
| 136 |
|
| 137 |
async function loadSources() {
|
|
|
|
| 140 |
$('#sourceCount').textContent = src.length
|
| 141 |
? `${src.length} vídeo(s) carregado(s). Selecione alguns ou deixe sem seleção para usar todos.`
|
| 142 |
: 'Nenhum vídeo carregado.';
|
| 143 |
+
$('#clearSources').style.display = src.length ? '' : 'none';
|
| 144 |
const box = $('#sourceList');
|
| 145 |
box.innerHTML = '';
|
| 146 |
+
src.slice(0, MAX_THUMBS).forEach((m) => box.appendChild(mediaThumb(m, state.selSources, () => { loadSources(); }, delSource)));
|
| 147 |
if (src.length > MAX_THUMBS) {
|
| 148 |
const more = document.createElement('p'); more.className = 'muted';
|
| 149 |
more.textContent = `+${src.length - MAX_THUMBS} vídeos não exibidos (incluídos se nada estiver selecionado).`;
|
|
|
|
| 151 |
}
|
| 152 |
refreshPreview();
|
| 153 |
}
|
| 154 |
+
async function delSource(m) {
|
| 155 |
+
await api('DELETE', '/api/editor/sources/' + m.id);
|
| 156 |
+
state.selSources.delete(m.id);
|
| 157 |
+
loadSources();
|
| 158 |
+
}
|
| 159 |
+
// Thumbnail leve: usa o poster JPG gerado no servidor (nada de dezenas de <video>).
|
| 160 |
+
function mediaThumb(m, selSet, reload, onDelete) {
|
| 161 |
const d = document.createElement('div');
|
| 162 |
d.className = 'thumb' + (selSet.has(m.id) ? ' sel' : '');
|
| 163 |
+
d.innerHTML = `<img loading="lazy" src="/api/editor/thumb/${m.id}" alt="" />
|
| 164 |
+
<span class="pick">✓</span>
|
| 165 |
+
${onDelete ? '<button class="del" title="Excluir">✕</button>' : ''}
|
| 166 |
+
<span class="name">${m.label || ('#' + m.id)}</span>`;
|
| 167 |
+
const img = d.querySelector('img');
|
| 168 |
+
if (img) img.onerror = () => { img.style.visibility = 'hidden'; };
|
| 169 |
d.onclick = () => { selSet.has(m.id) ? selSet.delete(m.id) : selSet.add(m.id); reload(); };
|
| 170 |
+
if (onDelete) d.querySelector('.del').onclick = (e) => { e.stopPropagation(); onDelete(m); };
|
| 171 |
return d;
|
| 172 |
}
|
| 173 |
+
// Upload em LOTES pequenos: evita segurar centenas de arquivos na memoria do
|
| 174 |
+
// navegador de uma vez (era o que travava o PC) e mostra progresso.
|
| 175 |
$('#videoUpload').onclick = async () => {
|
| 176 |
+
const files = [...$('#videoFiles').files];
|
| 177 |
if (!files.length) return toast('Escolha vídeos.', 'err');
|
| 178 |
+
const CHUNK = 4;
|
| 179 |
+
const prog = $('#uploadProgress');
|
| 180 |
+
prog.classList.remove('hide');
|
| 181 |
+
$('#videoUpload').disabled = true;
|
| 182 |
+
let done = 0, ok = 0;
|
| 183 |
+
for (let i = 0; i < files.length; i += CHUNK) {
|
| 184 |
+
const batch = files.slice(i, i + CHUNK);
|
| 185 |
+
const fd = new FormData(); batch.forEach((f) => fd.append('videos', f));
|
| 186 |
+
try { const r = await api('POST', '/api/editor/sources/upload', fd, true); ok += r.length; }
|
| 187 |
+
catch (e) { toast(e.message, 'err'); }
|
| 188 |
+
done += batch.length;
|
| 189 |
+
const pct = Math.round((done / files.length) * 100);
|
| 190 |
+
$('#uploadBar').style.width = pct + '%';
|
| 191 |
+
$('#uploadPct').textContent = pct + '%';
|
| 192 |
+
$('#uploadLabel').textContent = `Enviando… ${done}/${files.length}`;
|
| 193 |
+
await loadSources();
|
| 194 |
+
}
|
| 195 |
+
$('#uploadLabel').textContent = `Concluído: ${ok} vídeo(s).`;
|
| 196 |
+
$('#videoUpload').disabled = false;
|
| 197 |
+
$('#videoFiles').value = '';
|
| 198 |
+
toast(`${ok} vídeo(s) enviados`, 'ok');
|
| 199 |
+
setTimeout(() => prog.classList.add('hide'), 2500);
|
| 200 |
+
};
|
| 201 |
+
$('#clearSources').onclick = async () => {
|
| 202 |
+
if (!confirm('Excluir TODOS os vídeos carregados? Esta ação não pode ser desfeita.')) return;
|
| 203 |
+
await api('DELETE', '/api/editor/sources');
|
| 204 |
+
state.selSources.clear();
|
| 205 |
+
toast('Todos os vídeos foram removidos.', 'ok');
|
| 206 |
+
loadSources();
|
| 207 |
};
|
| 208 |
$('#folderImport').onclick = async () => {
|
| 209 |
const folder = $('#folderPath').value.trim();
|
|
|
|
| 223 |
function refreshPreview() {
|
| 224 |
const canvas = $('#previewCanvas'); if (!canvas) return;
|
| 225 |
const hint = $('#previewHint');
|
| 226 |
+
const mold = currentMold();
|
| 227 |
+
if (!mold) {
|
| 228 |
if (hint) hint.style.display = '';
|
| 229 |
+
$('#areaWarn').classList.add('hide');
|
| 230 |
canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
|
| 231 |
return;
|
| 232 |
}
|
| 233 |
if (hint) hint.style.display = 'none';
|
| 234 |
+
if (!state.area) syncAreaFromMold();
|
| 235 |
+
// avisa quando o molde nao tem area transparente confiavel (area_auto === 0)
|
| 236 |
+
$('#areaWarn').classList.toggle('hide', mold.area_auto !== 0);
|
| 237 |
+
const W = 240, s = W / mold.canvas_w, H = Math.round(mold.canvas_h * s);
|
| 238 |
+
if (canvas.width !== W || canvas.height !== H) { canvas.width = W; canvas.height = H; }
|
| 239 |
if (pv.moldId !== mold.id) {
|
| 240 |
pv.moldId = mold.id; pv.imgReady = false; pv.img = new Image();
|
| 241 |
pv.img.onload = () => { pv.imgReady = true; drawPreview(); };
|
| 242 |
pv.img.src = '/mold-file/' + mold.id;
|
| 243 |
}
|
| 244 |
+
const sample = currentSample();
|
| 245 |
+
if (sample && pv.sampleId !== sample.id) {
|
| 246 |
pv.sampleId = sample.id; pv.vidReady = false;
|
| 247 |
if (!pv.video) { pv.video = document.createElement('video'); pv.video.muted = true; pv.video.playsInline = true; }
|
| 248 |
pv.video.onloadeddata = () => { try { pv.video.currentTime = Math.min(1, (pv.video.duration || 2) / 2); } catch (e) {} };
|
| 249 |
pv.video.onseeked = () => { pv.vidReady = true; drawPreview(); };
|
| 250 |
pv.video.src = '/preview/' + sample.id; pv.video.load();
|
| 251 |
+
} else if (!sample) {
|
| 252 |
+
pv.sampleId = null; pv.vidReady = false;
|
| 253 |
}
|
| 254 |
drawPreview();
|
| 255 |
}
|
| 256 |
function drawPreview() {
|
| 257 |
const canvas = $('#previewCanvas'); if (!canvas) return;
|
| 258 |
+
const mold = currentMold(); if (!mold || !state.area) return;
|
| 259 |
const ctx = canvas.getContext('2d');
|
| 260 |
const s = canvas.width / mold.canvas_w;
|
| 261 |
+
const ax = state.area.x * s, ay = state.area.y * s, aw = state.area.w * s, ah = state.area.h * s;
|
| 262 |
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
| 263 |
ctx.fillStyle = '#000'; ctx.fillRect(ax, ay, aw, ah);
|
| 264 |
if (pv.vidReady && pv.video.videoWidth) {
|
|
|
|
| 270 |
ctx.restore();
|
| 271 |
}
|
| 272 |
if (pv.imgReady) ctx.drawImage(pv.img, 0, 0, canvas.width, canvas.height);
|
| 273 |
+
// contorno da area por cima de tudo, para o usuario ver onde o video entra
|
| 274 |
+
ctx.save();
|
| 275 |
+
ctx.strokeStyle = '#ff7a18'; ctx.lineWidth = 2; ctx.setLineDash([6, 4]);
|
| 276 |
+
ctx.strokeRect(ax + 1, ay + 1, Math.max(0, aw - 2), Math.max(0, ah - 2));
|
| 277 |
+
ctx.restore();
|
| 278 |
}
|
| 279 |
+
|
| 280 |
+
// ---- Definir a area arrastando no preview ----
|
| 281 |
+
(function setupAreaDrag() {
|
| 282 |
+
const canvas = $('#previewCanvas'); if (!canvas) return;
|
| 283 |
+
let dragging = false, sx = 0, sy = 0;
|
| 284 |
+
const toMold = (e) => {
|
| 285 |
+
const r = canvas.getBoundingClientRect();
|
| 286 |
+
const mold = currentMold();
|
| 287 |
+
const scale = mold ? mold.canvas_w / canvas.width : 1;
|
| 288 |
+
const cx = (e.clientX - r.left) * (canvas.width / r.width);
|
| 289 |
+
const cy = (e.clientY - r.top) * (canvas.height / r.height);
|
| 290 |
+
return { x: cx * scale, y: cy * scale };
|
| 291 |
+
};
|
| 292 |
+
canvas.addEventListener('mousedown', (e) => {
|
| 293 |
+
if (!currentMold()) return;
|
| 294 |
+
dragging = true; const p = toMold(e); sx = p.x; sy = p.y; e.preventDefault();
|
| 295 |
+
});
|
| 296 |
+
window.addEventListener('mousemove', (e) => {
|
| 297 |
+
if (!dragging) return;
|
| 298 |
+
const mold = currentMold(); if (!mold) return;
|
| 299 |
+
const p = toMold(e);
|
| 300 |
+
const x = Math.max(0, Math.min(sx, p.x)), y = Math.max(0, Math.min(sy, p.y));
|
| 301 |
+
const x2 = Math.min(mold.canvas_w, Math.max(sx, p.x)), y2 = Math.min(mold.canvas_h, Math.max(sy, p.y));
|
| 302 |
+
state.area = { x: Math.round(x), y: Math.round(y), w: Math.round(x2 - x), h: Math.round(y2 - y) };
|
| 303 |
+
state.areaDirty = true; drawPreview();
|
| 304 |
+
});
|
| 305 |
+
window.addEventListener('mouseup', () => {
|
| 306 |
+
if (!dragging) return; dragging = false;
|
| 307 |
+
if (state.area && (state.area.w < 8 || state.area.h < 8)) { syncAreaFromMold(); drawPreview(); } // ignora clique sem arrasto
|
| 308 |
+
});
|
| 309 |
+
})();
|
| 310 |
+
|
| 311 |
+
// ---- Locais predefinidos (presets) ----
|
| 312 |
+
$$('.presets [data-preset]').forEach((btn) => btn.onclick = () => {
|
| 313 |
+
const mold = currentMold(); if (!mold) return toast('Selecione um molde primeiro.', 'err');
|
| 314 |
+
const cw = mold.canvas_w, ch = mold.canvas_h;
|
| 315 |
+
const ev = (n) => Math.max(2, Math.round(n / 2) * 2);
|
| 316 |
+
const p = btn.dataset.preset; let a;
|
| 317 |
+
if (p === 'center') { const w = ev(cw * 0.8), h = ev(ch * 0.8); a = { x: ev((cw - w) / 2), y: ev((ch - h) / 2), w, h }; }
|
| 318 |
+
else if (p === 'full') a = { x: 0, y: 0, w: ev(cw), h: ev(ch) };
|
| 319 |
+
else if (p === 'top') { const w = ev(cw * 0.9), h = ev(ch * 0.45); a = { x: ev((cw - w) / 2), y: ev(ch * 0.05), w, h }; }
|
| 320 |
+
else { const w = ev(cw * 0.9), h = ev(ch * 0.45); a = { x: ev((cw - w) / 2), y: ev(ch * 0.5), w, h }; } // bottom
|
| 321 |
+
state.area = a; state.areaDirty = true; drawPreview();
|
| 322 |
+
});
|
| 323 |
+
|
| 324 |
+
// ---- Salvar a area no molde (persiste e passa a valer no render) ----
|
| 325 |
+
$('#saveArea').onclick = async () => {
|
| 326 |
+
const mold = currentMold(); if (!mold || !state.area) return toast('Selecione um molde e marque a área.', 'err');
|
| 327 |
+
try {
|
| 328 |
+
const updated = await api('POST', `/api/editor/molds/${mold.id}/area`, state.area);
|
| 329 |
+
const idx = state.molds.findIndex((m) => m.id === mold.id);
|
| 330 |
+
if (idx >= 0) state.molds[idx] = updated;
|
| 331 |
+
state.area = { x: updated.area_x, y: updated.area_y, w: updated.area_w, h: updated.area_h };
|
| 332 |
+
state.areaDirty = false;
|
| 333 |
+
$('#areaWarn').classList.add('hide');
|
| 334 |
+
const chip = $('#areaSaved'); chip.classList.remove('hide'); setTimeout(() => chip.classList.add('hide'), 2000);
|
| 335 |
+
toast('Área salva no molde. Já vale para a renderização.', 'ok');
|
| 336 |
+
drawPreview();
|
| 337 |
+
} catch (e) { toast(e.message, 'err'); }
|
| 338 |
+
};
|
| 339 |
+
|
| 340 |
$('#focusX').oninput = (e) => { state.focusX = +e.target.value; drawPreview(); };
|
| 341 |
$('#focusY').oninput = (e) => { state.focusY = +e.target.value; drawPreview(); };
|
| 342 |
$('#sampleNext').onclick = () => { state.sampleIdx++; refreshPreview(); };
|
|
|
|
| 344 |
|
| 345 |
$('#renderBtn').onclick = async () => {
|
| 346 |
if (!state.selMold) return toast('Selecione um molde.', 'err');
|
| 347 |
+
// se a area foi ajustada e nao salva, salva antes de renderizar
|
| 348 |
+
if (state.areaDirty && state.area) {
|
| 349 |
+
try {
|
| 350 |
+
const u = await api('POST', `/api/editor/molds/${state.selMold}/area`, state.area);
|
| 351 |
+
const idx = state.molds.findIndex((m) => m.id === state.selMold);
|
| 352 |
+
if (idx >= 0) state.molds[idx] = u;
|
| 353 |
+
state.areaDirty = false;
|
| 354 |
+
} catch (e) { return toast('Não consegui salvar a área: ' + e.message, 'err'); }
|
| 355 |
+
}
|
| 356 |
try {
|
| 357 |
const { jobId } = await api('POST', '/api/editor/render', {
|
| 358 |
moldId: state.selMold, sourceIds: [...state.selSources],
|
|
|
|
| 563 |
};
|
| 564 |
async function loadLibrary() {
|
| 565 |
const lib = await api('GET', '/api/editor/library');
|
| 566 |
+
$('#clearLibrary').style.display = lib.length ? '' : 'none';
|
| 567 |
const box = $('#libList'); box.innerHTML = '';
|
| 568 |
if (!lib.length) { box.innerHTML = '<p class="muted">Nenhum vídeo renderizado ainda. Use o Editor primeiro.</p>'; updateSummary(); return; }
|
| 569 |
+
lib.slice(0, MAX_THUMBS).forEach((m) => box.appendChild(mediaThumb(m, state.selLib, () => { loadLibrary(); }, delLibrary)));
|
| 570 |
if (lib.length > MAX_THUMBS) {
|
| 571 |
const p = document.createElement('p'); p.className = 'muted';
|
| 572 |
p.textContent = `+${lib.length - MAX_THUMBS} não exibidos (incluídos se nada for selecionado).`;
|
|
|
|
| 640 |
${posts.length > 100 ? `<p class="muted">+${posts.length - 100} posts…</p>` : ''}`;
|
| 641 |
}
|
| 642 |
window.cancelPost = async (id) => { await api('POST', `/api/schedule/posts/${id}/cancel`); loadPosts(); };
|
| 643 |
+
async function delLibrary(m) {
|
| 644 |
+
if (!confirm('Excluir este vídeo renderizado da biblioteca?')) return;
|
| 645 |
+
await api('DELETE', '/api/editor/library/' + m.id);
|
| 646 |
+
state.selLib.delete(m.id);
|
| 647 |
+
loadLibrary();
|
| 648 |
+
}
|
| 649 |
+
$('#clearLibrary').onclick = async () => {
|
| 650 |
+
if (!confirm('Excluir TODOS os vídeos renderizados da biblioteca?')) return;
|
| 651 |
+
await api('DELETE', '/api/editor/library');
|
| 652 |
+
state.selLib.clear();
|
| 653 |
+
toast('Biblioteca limpa.', 'ok');
|
| 654 |
+
loadLibrary();
|
| 655 |
+
};
|
| 656 |
|
| 657 |
// ===== Init =====
|
| 658 |
+
loadInicio();
|
| 659 |
+
loadMolds();
|
| 660 |
+
loadSources();
|
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Guarda de sessão do app. Roda ANTES do app.js (ambos são módulos, então o
|
| 2 |
+
// app.js só executa depois deste terminar — evita corrida com as chamadas à API).
|
| 3 |
+
// Em modo local (sem Supabase configurado) não faz nada.
|
| 4 |
+
const setCookie = (token, exp = 3600) => { document.cookie = `sb-access-token=${token}; path=/; max-age=${exp}; SameSite=Lax`; };
|
| 5 |
+
|
| 6 |
+
const cfg = await (await fetch('/auth/config')).json();
|
| 7 |
+
if (cfg.enabled) {
|
| 8 |
+
const { createClient } = await import('https://esm.sh/@supabase/supabase-js@2');
|
| 9 |
+
const sb = createClient(cfg.url, cfg.anonKey, {
|
| 10 |
+
auth: { persistSession: true, autoRefreshToken: true, detectSessionInUrl: false },
|
| 11 |
+
});
|
| 12 |
+
|
| 13 |
+
const { data } = await sb.auth.getSession();
|
| 14 |
+
if (!data.session) {
|
| 15 |
+
location.replace('/login');
|
| 16 |
+
// trava o resto do carregamento até a navegação acontecer
|
| 17 |
+
await new Promise(() => {});
|
| 18 |
+
}
|
| 19 |
+
setCookie(data.session.access_token, data.session.expires_in || 3600);
|
| 20 |
+
|
| 21 |
+
// Mantém o cookie atualizado quando o token é renovado.
|
| 22 |
+
sb.auth.onAuthStateChange((_e, session) => {
|
| 23 |
+
if (session) setCookie(session.access_token, session.expires_in || 3600);
|
| 24 |
+
else location.replace('/login');
|
| 25 |
+
});
|
| 26 |
+
|
| 27 |
+
// Mostra o usuário + botão Sair no rodapé da barra lateral.
|
| 28 |
+
const foot = document.querySelector('.sidebar .foot');
|
| 29 |
+
if (foot) {
|
| 30 |
+
const email = data.session.user?.email || 'conta';
|
| 31 |
+
const box = document.createElement('div');
|
| 32 |
+
box.style.cssText = 'margin-bottom:10px; padding-bottom:10px; border-bottom:1px solid var(--line)';
|
| 33 |
+
box.innerHTML = `<div style="font-size:12px; color:var(--txt); overflow:hidden; text-overflow:ellipsis; white-space:nowrap">👤 ${email}</div>`;
|
| 34 |
+
const out = document.createElement('button');
|
| 35 |
+
out.className = 'btn ghost sm';
|
| 36 |
+
out.textContent = 'Sair';
|
| 37 |
+
out.style.marginTop = '8px';
|
| 38 |
+
out.onclick = async () => { try { await sb.auth.signOut(); } catch {} location.href = '/logout'; };
|
| 39 |
+
box.appendChild(out);
|
| 40 |
+
foot.prepend(box);
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
window.__supabase = sb;
|
| 44 |
+
}
|
|
@@ -21,7 +21,9 @@
|
|
| 21 |
</div>
|
| 22 |
</div>
|
| 23 |
<nav>
|
| 24 |
-
<button data-tab="
|
|
|
|
|
|
|
| 25 |
<span class="ico">🎬</span> Editor em massa</button>
|
| 26 |
<button data-tab="contas" data-title="Contas & Workspaces" data-sub="Vincule suas redes e organize por workspace.">
|
| 27 |
<span class="ico">🔗</span> Contas</button>
|
|
@@ -34,13 +36,50 @@
|
|
| 34 |
<!-- ===== CONTEÚDO ===== -->
|
| 35 |
<section class="content">
|
| 36 |
<div class="topbar">
|
| 37 |
-
<h1 id="pageTitle">
|
| 38 |
-
<p id="pageSub">
|
| 39 |
</div>
|
| 40 |
<main>
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
<!-- ============ EDITOR ============ -->
|
| 43 |
-
<section id="tab-editor" class="tab
|
| 44 |
<div class="hero">
|
| 45 |
<h2>Transforme um lote inteiro em segundos 🎬</h2>
|
| 46 |
<p>Envie um molde (arte 9:16) e seus vídeos. Cada vídeo é recortado e encaixado no molde, em massa. Baixe tudo em ZIP ou mande direto para o agendador.</p>
|
|
@@ -68,6 +107,10 @@
|
|
| 68 |
</div>
|
| 69 |
<button class="btn" id="videoUpload">Enviar vídeos</button>
|
| 70 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
<div class="row" style="margin-top:12px">
|
| 72 |
<div style="flex:1; min-width:240px">
|
| 73 |
<label>…ou importar uma pasta inteira do Mac (ideal p/ centenas de vídeos)</label>
|
|
@@ -75,25 +118,42 @@
|
|
| 75 |
</div>
|
| 76 |
<button class="btn ghost" id="folderImport">Importar pasta</button>
|
| 77 |
</div>
|
| 78 |
-
<
|
|
|
|
|
|
|
|
|
|
| 79 |
<div class="grid cols" id="sourceList" style="margin-top:14px"></div>
|
| 80 |
</div>
|
| 81 |
|
| 82 |
<div class="card">
|
| 83 |
<h3><span class="step-n">3</span> Posicionar no molde</h3>
|
| 84 |
-
<p class="muted" id="previewHint" style="margin:0 0 16px">Selecione um molde
|
|
|
|
| 85 |
<div class="row" style="align-items:flex-start; gap:26px">
|
| 86 |
-
<
|
|
|
|
|
|
|
|
|
|
| 87 |
<div style="flex:1; min-width:240px">
|
| 88 |
-
<label>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
<input type="range" id="focusX" min="0" max="100" value="50" />
|
| 90 |
-
<label>↕
|
| 91 |
<input type="range" id="focusY" min="0" max="100" value="50" />
|
| 92 |
<div class="row" style="margin-top:8px">
|
| 93 |
<button class="btn ghost sm" id="sampleNext">🔀 Trocar amostra</button>
|
| 94 |
<button class="btn ghost sm" id="centerFocus">🎯 Centralizar</button>
|
| 95 |
</div>
|
| 96 |
-
<p class="note" style="margin-top:14px">
|
| 97 |
</div>
|
| 98 |
</div>
|
| 99 |
</div>
|
|
@@ -189,7 +249,10 @@
|
|
| 189 |
</div>
|
| 190 |
</div>
|
| 191 |
|
| 192 |
-
<
|
|
|
|
|
|
|
|
|
|
| 193 |
<div class="grid cols" id="libList"></div>
|
| 194 |
|
| 195 |
<div class="row between" style="margin-top:18px">
|
|
@@ -213,6 +276,7 @@
|
|
| 213 |
</section>
|
| 214 |
</div>
|
| 215 |
|
| 216 |
-
<script src="/
|
|
|
|
| 217 |
</body>
|
| 218 |
</html>
|
|
|
|
| 21 |
</div>
|
| 22 |
</div>
|
| 23 |
<nav>
|
| 24 |
+
<button data-tab="inicio" class="active" data-title="Início" data-sub="Visão geral da sua operação no PagsDark.">
|
| 25 |
+
<span class="ico">🏠</span> Início</button>
|
| 26 |
+
<button data-tab="editor" data-title="Editor em massa" data-sub="Aplique seu molde em centenas de vídeos de uma vez.">
|
| 27 |
<span class="ico">🎬</span> Editor em massa</button>
|
| 28 |
<button data-tab="contas" data-title="Contas & Workspaces" data-sub="Vincule suas redes e organize por workspace.">
|
| 29 |
<span class="ico">🔗</span> Contas</button>
|
|
|
|
| 36 |
<!-- ===== CONTEÚDO ===== -->
|
| 37 |
<section class="content">
|
| 38 |
<div class="topbar">
|
| 39 |
+
<h1 id="pageTitle">Início</h1>
|
| 40 |
+
<p id="pageSub">Visão geral da sua operação no PagsDark.</p>
|
| 41 |
</div>
|
| 42 |
<main>
|
| 43 |
|
| 44 |
+
<!-- ============ INÍCIO (DASHBOARD) ============ -->
|
| 45 |
+
<section id="tab-inicio" class="tab active">
|
| 46 |
+
<div class="hero">
|
| 47 |
+
<h2>Bem-vindo de volta 👋</h2>
|
| 48 |
+
<p>Edite vídeos em massa com seu molde e deixe o agendador postar sozinho em YouTube, Instagram, Facebook e TikTok. Comece por um atalho abaixo.</p>
|
| 49 |
+
<span class="big">💸</span>
|
| 50 |
+
</div>
|
| 51 |
+
|
| 52 |
+
<div class="grid stats" id="dashStats"></div>
|
| 53 |
+
|
| 54 |
+
<div class="grid" style="grid-template-columns:repeat(auto-fit,minmax(220px,1fr)); margin-top:4px">
|
| 55 |
+
<div class="card action" data-go="editor">
|
| 56 |
+
<span class="ai">🎬</span>
|
| 57 |
+
<h4>Editar em massa</h4>
|
| 58 |
+
<p class="muted">Aplique o molde em centenas de vídeos e baixe em ZIP ou mande pra biblioteca.</p>
|
| 59 |
+
<span class="cta">Abrir editor →</span>
|
| 60 |
+
</div>
|
| 61 |
+
<div class="card action" data-go="contas">
|
| 62 |
+
<span class="ai">🔗</span>
|
| 63 |
+
<h4>Conectar redes</h4>
|
| 64 |
+
<p class="muted">Vincule YouTube, Instagram, Facebook e TikTok por workspace.</p>
|
| 65 |
+
<span class="cta">Gerenciar contas →</span>
|
| 66 |
+
</div>
|
| 67 |
+
<div class="card action" data-go="agendar">
|
| 68 |
+
<span class="ai">📅</span>
|
| 69 |
+
<h4>Agendar o mês</h4>
|
| 70 |
+
<p class="muted">Escolha vídeos, contas e horários fixos. O PagsDark posta sozinho.</p>
|
| 71 |
+
<span class="cta">Criar campanha →</span>
|
| 72 |
+
</div>
|
| 73 |
+
</div>
|
| 74 |
+
|
| 75 |
+
<div class="card">
|
| 76 |
+
<h3>Próximos posts</h3>
|
| 77 |
+
<div id="dashNext"><p class="muted">Carregando…</p></div>
|
| 78 |
+
</div>
|
| 79 |
+
</section>
|
| 80 |
+
|
| 81 |
<!-- ============ EDITOR ============ -->
|
| 82 |
+
<section id="tab-editor" class="tab">
|
| 83 |
<div class="hero">
|
| 84 |
<h2>Transforme um lote inteiro em segundos 🎬</h2>
|
| 85 |
<p>Envie um molde (arte 9:16) e seus vídeos. Cada vídeo é recortado e encaixado no molde, em massa. Baixe tudo em ZIP ou mande direto para o agendador.</p>
|
|
|
|
| 107 |
</div>
|
| 108 |
<button class="btn" id="videoUpload">Enviar vídeos</button>
|
| 109 |
</div>
|
| 110 |
+
<div id="uploadProgress" class="hide" style="margin-top:14px">
|
| 111 |
+
<div class="row between"><span id="uploadLabel">Enviando…</span><span id="uploadPct">0%</span></div>
|
| 112 |
+
<div class="bar"><div id="uploadBar" style="width:0%"></div></div>
|
| 113 |
+
</div>
|
| 114 |
<div class="row" style="margin-top:12px">
|
| 115 |
<div style="flex:1; min-width:240px">
|
| 116 |
<label>…ou importar uma pasta inteira do Mac (ideal p/ centenas de vídeos)</label>
|
|
|
|
| 118 |
</div>
|
| 119 |
<button class="btn ghost" id="folderImport">Importar pasta</button>
|
| 120 |
</div>
|
| 121 |
+
<div class="row between" style="margin-top:14px">
|
| 122 |
+
<p class="note" id="sourceCount" style="margin:0; flex:1">Nenhum vídeo carregado.</p>
|
| 123 |
+
<button class="btn ghost sm" id="clearSources" style="display:none">🗑 Excluir todos</button>
|
| 124 |
+
</div>
|
| 125 |
<div class="grid cols" id="sourceList" style="margin-top:14px"></div>
|
| 126 |
</div>
|
| 127 |
|
| 128 |
<div class="card">
|
| 129 |
<h3><span class="step-n">3</span> Posicionar no molde</h3>
|
| 130 |
+
<p class="muted" id="previewHint" style="margin:0 0 16px">Selecione um molde acima para definir onde o vídeo entra. (Carregue um vídeo para ver a prévia com imagem.)</p>
|
| 131 |
+
<div id="areaWarn" class="note hide" style="margin-bottom:16px; border-color:#5c4a1f; color:var(--warn)">⚠️ Este molde <b>não tem furo transparente</b>. Sem problema: escolha um <b>local predefinido</b> abaixo ou <b>arraste no preview</b> para marcar a área, e o vídeo será <b>colado por cima da arte</b> exatamente nessa área. (Se preferir que o vídeo apareça <i>pelo buraco</i> da arte, exporte o PNG com uma área transparente.)</div>
|
| 132 |
<div class="row" style="align-items:flex-start; gap:26px">
|
| 133 |
+
<div>
|
| 134 |
+
<canvas id="previewCanvas" width="240" height="427" style="border-radius:12px; border:1px solid var(--line); background:#000; cursor:crosshair"></canvas>
|
| 135 |
+
<p class="muted" style="font-size:12px; margin:8px 0 0; max-width:240px; text-align:center">Arraste sobre o preview para marcar a área do vídeo.</p>
|
| 136 |
+
</div>
|
| 137 |
<div style="flex:1; min-width:240px">
|
| 138 |
+
<label>📍 Local predefinido do vídeo</label>
|
| 139 |
+
<div class="row presets" style="gap:8px">
|
| 140 |
+
<button class="btn ghost sm" data-preset="center">⬛ Centro</button>
|
| 141 |
+
<button class="btn ghost sm" data-preset="full">⬜ Inteiro</button>
|
| 142 |
+
<button class="btn ghost sm" data-preset="top">⬆ Topo</button>
|
| 143 |
+
<button class="btn ghost sm" data-preset="bottom">⬇ Base</button>
|
| 144 |
+
</div>
|
| 145 |
+
<button class="btn sm" id="saveArea" style="margin-top:10px">💾 Salvar área no molde</button>
|
| 146 |
+
<span class="chip ok hide" id="areaSaved" style="margin-left:8px">✓ área salva</span>
|
| 147 |
+
|
| 148 |
+
<label style="margin-top:20px">↔ Enquadramento horizontal (qual parte do vídeo aparece)</label>
|
| 149 |
<input type="range" id="focusX" min="0" max="100" value="50" />
|
| 150 |
+
<label>↕ Enquadramento vertical</label>
|
| 151 |
<input type="range" id="focusY" min="0" max="100" value="50" />
|
| 152 |
<div class="row" style="margin-top:8px">
|
| 153 |
<button class="btn ghost sm" id="sampleNext">🔀 Trocar amostra</button>
|
| 154 |
<button class="btn ghost sm" id="centerFocus">🎯 Centralizar</button>
|
| 155 |
</div>
|
| 156 |
+
<p class="note" style="margin-top:14px">A <b>área</b> define onde o vídeo aparece no molde; o <b>enquadramento</b> decide qual parte do vídeo fica visível. Ambos valem para <b>todos</b> os vídeos do lote.</p>
|
| 157 |
</div>
|
| 158 |
</div>
|
| 159 |
</div>
|
|
|
|
| 249 |
</div>
|
| 250 |
</div>
|
| 251 |
|
| 252 |
+
<div class="row between" style="margin-top:16px; align-items:flex-end">
|
| 253 |
+
<label style="margin:0">Vídeos da biblioteca (renderizados). Sem seleção = todos.</label>
|
| 254 |
+
<button class="btn ghost sm" id="clearLibrary" style="display:none">🗑 Excluir todos</button>
|
| 255 |
+
</div>
|
| 256 |
<div class="grid cols" id="libList"></div>
|
| 257 |
|
| 258 |
<div class="row between" style="margin-top:18px">
|
|
|
|
| 276 |
</section>
|
| 277 |
</div>
|
| 278 |
|
| 279 |
+
<script type="module" src="/auth-guard.js"></script>
|
| 280 |
+
<script type="module" src="/app.js"></script>
|
| 281 |
</body>
|
| 282 |
</html>
|
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!doctype html>
|
| 2 |
+
<html lang="pt-BR">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="utf-8" />
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
| 6 |
+
<title>💸 PagsDark — Entrar</title>
|
| 7 |
+
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>💸</text></svg>" />
|
| 8 |
+
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
| 9 |
+
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet" />
|
| 10 |
+
<link rel="stylesheet" href="/style.css" />
|
| 11 |
+
<style>
|
| 12 |
+
body { overflow: auto; }
|
| 13 |
+
.login-wrap { min-height: 100vh; display: grid; place-items: center; padding: 24px; }
|
| 14 |
+
.login-card { width: 100%; max-width: 400px; }
|
| 15 |
+
.login-card .brand { justify-content: center; padding-bottom: 8px; }
|
| 16 |
+
.login-card h2 { text-align: center; margin: 6px 0 2px; font-size: 22px; font-weight: 800; }
|
| 17 |
+
.login-card .sub { text-align: center; color: var(--muted); margin: 0 0 22px; font-size: 14px; }
|
| 18 |
+
.gbtn { width: 100%; display: flex; align-items: center; justify-content: center; gap: 10px; padding: 12px; border-radius: 11px; border: 1px solid var(--line); background: #fff; color: #222; font-weight: 700; cursor: pointer; font-size: 15px; }
|
| 19 |
+
.gbtn:hover { filter: brightness(.96); }
|
| 20 |
+
.sep { display: flex; align-items: center; gap: 12px; color: var(--muted); font-size: 12px; margin: 18px 0; }
|
| 21 |
+
.sep::before, .sep::after { content: ""; height: 1px; background: var(--line); flex: 1; }
|
| 22 |
+
.msg { font-size: 13px; margin-top: 12px; text-align: center; min-height: 18px; }
|
| 23 |
+
.msg.err { color: var(--err); } .msg.ok { color: var(--ok); }
|
| 24 |
+
.login-foot { text-align: center; color: var(--muted); font-size: 12px; margin-top: 18px; }
|
| 25 |
+
</style>
|
| 26 |
+
</head>
|
| 27 |
+
<body>
|
| 28 |
+
<div class="login-wrap">
|
| 29 |
+
<div class="card login-card">
|
| 30 |
+
<div class="brand"><span class="emoji" style="font-size:34px">💸</span>
|
| 31 |
+
<div><div class="name" style="font-size:24px">Pags<b>Dark</b></div></div></div>
|
| 32 |
+
<h2>Entrar</h2>
|
| 33 |
+
<p class="sub">Acesse sua conta para editar e agendar.</p>
|
| 34 |
+
|
| 35 |
+
<button class="gbtn" id="googleBtn">
|
| 36 |
+
<svg width="18" height="18" viewBox="0 0 48 48"><path fill="#EA4335" d="M24 9.5c3.5 0 6.6 1.2 9 3.6l6.7-6.7C35.6 2.6 30.2 0 24 0 14.6 0 6.5 5.4 2.6 13.2l7.8 6.1C12.3 13.2 17.6 9.5 24 9.5z"/><path fill="#4285F4" d="M46.1 24.6c0-1.6-.1-2.8-.4-4H24v7.6h12.7c-.3 2.1-1.6 5.2-4.7 7.3l7.2 5.6c4.3-4 6.9-9.9 6.9-16.5z"/><path fill="#FBBC05" d="M10.4 28.3c-.5-1.5-.8-3-.8-4.6s.3-3.1.8-4.6l-7.8-6.1C1 16.1 0 19.9 0 23.7s1 7.6 2.6 10.7l7.8-6.1z"/><path fill="#34A853" d="M24 47.4c6.2 0 11.4-2 15.2-5.5l-7.2-5.6c-2 1.4-4.6 2.3-8 2.3-6.4 0-11.7-3.7-13.6-8.9l-7.8 6.1C6.5 42 14.6 47.4 24 47.4z"/></svg>
|
| 37 |
+
Entrar com Google
|
| 38 |
+
</button>
|
| 39 |
+
|
| 40 |
+
<div class="sep">ou com e-mail</div>
|
| 41 |
+
|
| 42 |
+
<form id="emailForm">
|
| 43 |
+
<label>E-mail</label>
|
| 44 |
+
<input type="email" id="email" placeholder="voce@email.com" required />
|
| 45 |
+
<label>Senha</label>
|
| 46 |
+
<input type="password" id="password" placeholder="••••••••" required minlength="6" />
|
| 47 |
+
<div class="row" style="margin-top:14px; gap:10px">
|
| 48 |
+
<button class="btn" type="submit" style="flex:1">Entrar</button>
|
| 49 |
+
<button class="btn ghost" type="button" id="signupBtn" style="flex:1">Criar conta</button>
|
| 50 |
+
</div>
|
| 51 |
+
</form>
|
| 52 |
+
|
| 53 |
+
<div class="msg" id="msg"></div>
|
| 54 |
+
<div class="login-foot" id="foot"></div>
|
| 55 |
+
</div>
|
| 56 |
+
</div>
|
| 57 |
+
<script type="module" src="/login.js"></script>
|
| 58 |
+
</body>
|
| 59 |
+
</html>
|
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Tela de login: usa o Supabase no navegador (Google ou e-mail+senha).
|
| 2 |
+
// Em sucesso, guarda o token num cookie e volta para o app.
|
| 3 |
+
const msg = (t, cls = '') => { const m = document.getElementById('msg'); m.textContent = t; m.className = 'msg ' + cls; };
|
| 4 |
+
const setCookie = (token, exp = 3600) => { document.cookie = `sb-access-token=${token}; path=/; max-age=${exp}; SameSite=Lax`; };
|
| 5 |
+
|
| 6 |
+
const cfg = await (await fetch('/auth/config')).json();
|
| 7 |
+
if (!cfg.enabled) {
|
| 8 |
+
// Login não está configurado: o app roda em modo local, segue direto.
|
| 9 |
+
location.replace('/');
|
| 10 |
+
} else {
|
| 11 |
+
const { createClient } = await import('https://esm.sh/@supabase/supabase-js@2');
|
| 12 |
+
const sb = createClient(cfg.url, cfg.anonKey, {
|
| 13 |
+
auth: { detectSessionInUrl: true, persistSession: true, autoRefreshToken: true },
|
| 14 |
+
});
|
| 15 |
+
|
| 16 |
+
const enter = (session) => {
|
| 17 |
+
if (!session) return;
|
| 18 |
+
setCookie(session.access_token, session.expires_in || 3600);
|
| 19 |
+
location.replace('/');
|
| 20 |
+
};
|
| 21 |
+
|
| 22 |
+
// Já logado (ou voltou do Google com a sessão na URL)?
|
| 23 |
+
const { data } = await sb.auth.getSession();
|
| 24 |
+
if (data.session) enter(data.session);
|
| 25 |
+
sb.auth.onAuthStateChange((_e, session) => { if (session) enter(session); });
|
| 26 |
+
|
| 27 |
+
document.getElementById('googleBtn').onclick = () =>
|
| 28 |
+
sb.auth.signInWithOAuth({ provider: 'google', options: { redirectTo: location.origin + '/login' } });
|
| 29 |
+
|
| 30 |
+
document.getElementById('emailForm').onsubmit = async (e) => {
|
| 31 |
+
e.preventDefault();
|
| 32 |
+
msg('Entrando…');
|
| 33 |
+
const email = document.getElementById('email').value.trim();
|
| 34 |
+
const password = document.getElementById('password').value;
|
| 35 |
+
const { data, error } = await sb.auth.signInWithPassword({ email, password });
|
| 36 |
+
if (error) return msg(error.message, 'err');
|
| 37 |
+
enter(data.session);
|
| 38 |
+
};
|
| 39 |
+
|
| 40 |
+
document.getElementById('signupBtn').onclick = async () => {
|
| 41 |
+
msg('Criando conta…');
|
| 42 |
+
const email = document.getElementById('email').value.trim();
|
| 43 |
+
const password = document.getElementById('password').value;
|
| 44 |
+
if (!email || password.length < 6) return msg('Informe e-mail e senha (mín. 6 caracteres).', 'err');
|
| 45 |
+
const { data, error } = await sb.auth.signUp({ email, password });
|
| 46 |
+
if (error) return msg(error.message, 'err');
|
| 47 |
+
if (data.session) enter(data.session);
|
| 48 |
+
else msg('Conta criada! Confirme o e-mail (se exigido) e entre.', 'ok');
|
| 49 |
+
};
|
| 50 |
+
}
|
|
@@ -141,6 +141,23 @@ button.btn:disabled { opacity: .45; cursor: not-allowed; transform: none; box-sh
|
|
| 141 |
.thumb .pick { position: absolute; top: 7px; right: 7px; width: 22px; height: 22px; border-radius: 50%; background: #000a; display: grid; place-items: center; font-size: 12px; opacity: .5; transition: all .15s; }
|
| 142 |
.thumb.sel .pick { background: var(--orange); opacity: 1; }
|
| 143 |
.thumb .name { position: absolute; bottom: 0; left: 0; right: 0; font-size: 11px; padding: 14px 7px 5px; background: linear-gradient(0deg, #000d, transparent); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
|
| 145 |
.bar { height: 9px; background: #0d0a08; border-radius: 999px; overflow: hidden; margin: 10px 0; border: 1px solid var(--line); }
|
| 146 |
.bar > div { height: 100%; background: linear-gradient(90deg, var(--orange-deep), var(--orange2)); transition: width .4s ease; background-size: 200% 100%; animation: shimmer 2s linear infinite; }
|
|
|
|
| 141 |
.thumb .pick { position: absolute; top: 7px; right: 7px; width: 22px; height: 22px; border-radius: 50%; background: #000a; display: grid; place-items: center; font-size: 12px; opacity: .5; transition: all .15s; }
|
| 142 |
.thumb.sel .pick { background: var(--orange); opacity: 1; }
|
| 143 |
.thumb .name { position: absolute; bottom: 0; left: 0; right: 0; font-size: 11px; padding: 14px 7px 5px; background: linear-gradient(0deg, #000d, transparent); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
| 144 |
+
.thumb .del { position: absolute; top: 7px; left: 7px; width: 24px; height: 24px; border-radius: 50%; background: #000b; color: #fff; border: none; cursor: pointer; font-size: 13px; display: grid; place-items: center; opacity: 0; transition: opacity .15s, background .15s; z-index: 3; }
|
| 145 |
+
.thumb:hover .del { opacity: 1; }
|
| 146 |
+
.thumb .del:hover { background: var(--err); }
|
| 147 |
+
.thumb-ph { width: 100%; height: 100%; display: grid; place-items: center; font-size: 30px; background: #0d0a08; }
|
| 148 |
+
|
| 149 |
+
/* ===== Dashboard (Início) ===== */
|
| 150 |
+
.grid.stats { grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); margin-bottom: 20px; }
|
| 151 |
+
.card.stat { display: flex; align-items: center; gap: 14px; padding: 18px 20px; margin: 0; }
|
| 152 |
+
.card.stat .si { font-size: 26px; line-height: 1; }
|
| 153 |
+
.card.stat .sv { font-size: 24px; font-weight: 800; line-height: 1; }
|
| 154 |
+
.card.stat .sl { font-size: 12px; color: var(--muted); margin-top: 4px; }
|
| 155 |
+
.card.action { cursor: pointer; display: flex; flex-direction: column; gap: 4px; }
|
| 156 |
+
.card.action:hover { border-color: var(--orange); transform: translateY(-3px); }
|
| 157 |
+
.card.action .ai { font-size: 30px; }
|
| 158 |
+
.card.action h4 { margin: 6px 0 0; font-size: 16px; font-weight: 700; }
|
| 159 |
+
.card.action .cta { color: var(--orange2); font-weight: 700; font-size: 13px; margin-top: 8px; }
|
| 160 |
+
.presets { flex-wrap: wrap; }
|
| 161 |
|
| 162 |
.bar { height: 9px; background: #0d0a08; border-radius: 999px; overflow: hidden; margin: 10px 0; border: 1px solid var(--line); }
|
| 163 |
.bar > div { height: 100%; background: linear-gradient(90deg, var(--orange-deep), var(--orange2)); transition: width .4s ease; background-size: 200% 100%; animation: shimmer 2s linear infinite; }
|
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Autenticação via Supabase (login com Google / e-mail+senha).
|
| 2 |
+
//
|
| 3 |
+
// Como funciona, em resumo:
|
| 4 |
+
// - O LOGIN acontece no navegador (public/login.html) usando o Supabase.
|
| 5 |
+
// - O Supabase devolve um token de acesso (JWT) assinado com o "JWT secret"
|
| 6 |
+
// do seu projeto. O navegador guarda esse token num cookie (sb-access-token).
|
| 7 |
+
// - Aqui no servidor, a cada requisição protegida, verificamos a ASSINATURA do
|
| 8 |
+
// token com o mesmo segredo. Sem token válido, a resposta é 401 / redireciona
|
| 9 |
+
// para a tela de login.
|
| 10 |
+
//
|
| 11 |
+
// Segurança: a verificação é feita 100% no servidor (não dá para burlar pelo
|
| 12 |
+
// navegador). O segredo do JWT NUNCA vai para o cliente — só a URL e a anon key,
|
| 13 |
+
// que são públicas por design no Supabase.
|
| 14 |
+
import crypto from 'node:crypto';
|
| 15 |
+
import { config } from './config.js';
|
| 16 |
+
|
| 17 |
+
// Auth só é exigido quando o Supabase está configurado no .env.
|
| 18 |
+
export function authEnabled() {
|
| 19 |
+
const s = config.supabase;
|
| 20 |
+
return Boolean(s && s.url && s.anonKey && s.jwtSecret);
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
function b64urlToBuf(s) {
|
| 24 |
+
return Buffer.from(String(s).replace(/-/g, '+').replace(/_/g, '/'), 'base64');
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
// Verifica um JWT HS256 (formato dos tokens do Supabase) sem dependências externas.
|
| 28 |
+
export function verifyJWT(token, secret) {
|
| 29 |
+
if (!token || !secret) return null;
|
| 30 |
+
const parts = String(token).split('.');
|
| 31 |
+
if (parts.length !== 3) return null;
|
| 32 |
+
const [h, p, sig] = parts;
|
| 33 |
+
let header;
|
| 34 |
+
try { header = JSON.parse(b64urlToBuf(h).toString('utf8')); } catch { return null; }
|
| 35 |
+
if (header.alg !== 'HS256') return null; // só aceitamos HS256 (evita "alg=none")
|
| 36 |
+
const expected = crypto.createHmac('sha256', secret).update(`${h}.${p}`).digest();
|
| 37 |
+
const got = b64urlToBuf(sig);
|
| 38 |
+
if (expected.length !== got.length || !crypto.timingSafeEqual(expected, got)) return null;
|
| 39 |
+
let payload;
|
| 40 |
+
try { payload = JSON.parse(b64urlToBuf(p).toString('utf8')); } catch { return null; }
|
| 41 |
+
const now = Math.floor(Date.now() / 1000);
|
| 42 |
+
if (payload.exp && now > payload.exp) return null; // expirado
|
| 43 |
+
if (payload.nbf && now < payload.nbf) return null; // ainda não válido
|
| 44 |
+
return payload; // { sub, email, role, exp, ... }
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
function parseCookies(req) {
|
| 48 |
+
const out = {};
|
| 49 |
+
(req.headers.cookie || '').split(';').forEach((c) => {
|
| 50 |
+
const i = c.indexOf('=');
|
| 51 |
+
if (i > 0) { try { out[c.slice(0, i).trim()] = decodeURIComponent(c.slice(i + 1).trim()); } catch {} }
|
| 52 |
+
});
|
| 53 |
+
return out;
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
// Extrai o usuário autenticado de uma requisição (cookie ou Authorization: Bearer).
|
| 57 |
+
export function getUser(req) {
|
| 58 |
+
if (!authEnabled()) return { id: 'local', email: 'local', local: true };
|
| 59 |
+
const bearer = (req.headers.authorization || '').replace(/^Bearer\s+/i, '');
|
| 60 |
+
const token = parseCookies(req)['sb-access-token'] || bearer;
|
| 61 |
+
const payload = verifyJWT(token, config.supabase.jwtSecret);
|
| 62 |
+
if (!payload || !payload.sub) return null;
|
| 63 |
+
return { id: payload.sub, email: payload.email || '', role: payload.role || 'authenticated' };
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
// Middleware: bloqueia se não autenticado (quando o auth está ligado).
|
| 67 |
+
export function requireAuth(req, res, next) {
|
| 68 |
+
if (!authEnabled()) { req.user = { id: 'local', local: true }; return next(); }
|
| 69 |
+
const user = getUser(req);
|
| 70 |
+
if (!user) return res.status(401).json({ error: 'Não autenticado.' });
|
| 71 |
+
req.user = user;
|
| 72 |
+
next();
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
// Config pública para o cliente montar o Supabase (sem segredos).
|
| 76 |
+
export function publicAuthConfig() {
|
| 77 |
+
return {
|
| 78 |
+
enabled: authEnabled(),
|
| 79 |
+
url: config.supabase ? config.supabase.url : '',
|
| 80 |
+
anonKey: config.supabase ? config.supabase.anonKey : '',
|
| 81 |
+
};
|
| 82 |
+
}
|
|
@@ -14,6 +14,7 @@ export const DIRS = {
|
|
| 14 |
media: path.join(DATA_DIR, 'media'),
|
| 15 |
molds: path.join(DATA_DIR, 'molds'),
|
| 16 |
output: path.join(DATA_DIR, 'output'),
|
|
|
|
| 17 |
tmp: path.join(DATA_DIR, 'tmp'),
|
| 18 |
};
|
| 19 |
|
|
@@ -42,6 +43,14 @@ export const config = {
|
|
| 42 |
clientKey: pick('TIKTOK_CLIENT_KEY', 'tiktokClientKey'),
|
| 43 |
clientSecret: pick('TIKTOK_CLIENT_SECRET', 'tiktokClientSecret'),
|
| 44 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
};
|
| 46 |
|
| 47 |
// Salva credenciais vindas da interface e aplica em memoria na hora.
|
|
|
|
| 14 |
media: path.join(DATA_DIR, 'media'),
|
| 15 |
molds: path.join(DATA_DIR, 'molds'),
|
| 16 |
output: path.join(DATA_DIR, 'output'),
|
| 17 |
+
thumbs: path.join(DATA_DIR, 'thumbs'),
|
| 18 |
tmp: path.join(DATA_DIR, 'tmp'),
|
| 19 |
};
|
| 20 |
|
|
|
|
| 43 |
clientKey: pick('TIKTOK_CLIENT_KEY', 'tiktokClientKey'),
|
| 44 |
clientSecret: pick('TIKTOK_CLIENT_SECRET', 'tiktokClientSecret'),
|
| 45 |
},
|
| 46 |
+
|
| 47 |
+
// Login dos usuários (Supabase: Google / e-mail+senha). Opcional: se vazio, o
|
| 48 |
+
// app roda em modo local sem exigir login. Preenchido, o login passa a valer.
|
| 49 |
+
supabase: {
|
| 50 |
+
url: process.env.SUPABASE_URL || '',
|
| 51 |
+
anonKey: process.env.SUPABASE_ANON_KEY || '',
|
| 52 |
+
jwtSecret: process.env.SUPABASE_JWT_SECRET || '',
|
| 53 |
+
},
|
| 54 |
};
|
| 55 |
|
| 56 |
// Salva credenciais vindas da interface e aplica em memoria na hora.
|
|
@@ -109,6 +109,16 @@ CREATE TABLE IF NOT EXISTS posts (
|
|
| 109 |
CREATE INDEX IF NOT EXISTS idx_posts_due ON posts(status, scheduled_at);
|
| 110 |
`);
|
| 111 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
export default db;
|
| 113 |
|
| 114 |
// ----- Helpers genericos -----
|
|
|
|
| 109 |
CREATE INDEX IF NOT EXISTS idx_posts_due ON posts(status, scheduled_at);
|
| 110 |
`);
|
| 111 |
|
| 112 |
+
// ----- Migracoes leves (colunas adicionadas depois) -----
|
| 113 |
+
// SQLite nao tem "ADD COLUMN IF NOT EXISTS"; tentamos e ignoramos se ja existe.
|
| 114 |
+
function addColumn(table, colDef) {
|
| 115 |
+
try { db.exec(`ALTER TABLE ${table} ADD COLUMN ${colDef}`); }
|
| 116 |
+
catch (e) { if (!/duplicate column/i.test(String(e.message || e))) throw e; }
|
| 117 |
+
}
|
| 118 |
+
addColumn('media_assets', 'thumb_path TEXT'); // poster JPG leve (gerado sob demanda)
|
| 119 |
+
addColumn('molds', 'area_auto INTEGER DEFAULT 1'); // 1 = area confiavel (transparencia detectada OU definida na tela); 0 = placeholder, precisa atencao
|
| 120 |
+
addColumn('molds', 'has_alpha INTEGER DEFAULT 1'); // 1 = PNG tem furo transparente (video aparece por baixo da arte); 0 = PNG opaco (video e colado por cima, na area marcada)
|
| 121 |
+
|
| 122 |
export default db;
|
| 123 |
|
| 124 |
// ----- Helpers genericos -----
|
|
@@ -34,10 +34,17 @@ export async function analyzeMold(filePath) {
|
|
| 34 |
}
|
| 35 |
|
| 36 |
let area;
|
|
|
|
| 37 |
if (maxX < 0) {
|
| 38 |
-
// Sem transparencia:
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
} else {
|
|
|
|
| 41 |
area = {
|
| 42 |
x: even(minX),
|
| 43 |
y: even(minY),
|
|
@@ -46,5 +53,5 @@ export async function analyzeMold(filePath) {
|
|
| 46 |
};
|
| 47 |
}
|
| 48 |
|
| 49 |
-
return { canvasW: even(canvasW), canvasH: even(canvasH), area };
|
| 50 |
}
|
|
|
|
| 34 |
}
|
| 35 |
|
| 36 |
let area;
|
| 37 |
+
let detected;
|
| 38 |
if (maxX < 0) {
|
| 39 |
+
// Sem transparencia: assume um retangulo central 9:16 como ponto de partida
|
| 40 |
+
// (o usuario ajusta na tela). Antes usava o canvas inteiro, o que fazia a arte
|
| 41 |
+
// opaca cobrir o video por completo no resultado.
|
| 42 |
+
detected = false;
|
| 43 |
+
const w = even(Math.round(canvasW * 0.8));
|
| 44 |
+
const h = even(Math.round(canvasH * 0.8));
|
| 45 |
+
area = { x: even(Math.round((canvasW - w) / 2)), y: even(Math.round((canvasH - h) / 2)), w, h };
|
| 46 |
} else {
|
| 47 |
+
detected = true;
|
| 48 |
area = {
|
| 49 |
x: even(minX),
|
| 50 |
y: even(minY),
|
|
|
|
| 53 |
};
|
| 54 |
}
|
| 55 |
|
| 56 |
+
return { canvasW: even(canvasW), canvasH: even(canvasH), area, detected };
|
| 57 |
}
|
|
@@ -15,24 +15,33 @@ export async function renderOne(sourceVideo, mold, outputPath, focus = {}) {
|
|
| 15 |
const fx = Math.min(1, Math.max(0, fnum(focus.x) / 100));
|
| 16 |
const fy = Math.min(1, Math.max(0, fnum(focus.y) / 100));
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
return new Promise((resolve, reject) => {
|
| 19 |
ffmpeg()
|
| 20 |
.input(sourceVideo)
|
| 21 |
.input(mold.file_path)
|
| 22 |
.inputOptions(['-loop 1']) // aplica ao ultimo input (a imagem do molde)
|
| 23 |
-
.complexFilter(
|
| 24 |
-
[
|
| 25 |
-
// fundo preto do tamanho do canvas, com a duracao do video
|
| 26 |
-
`color=c=black:s=${cw}x${ch}:r=30:d=${dur}[bg]`,
|
| 27 |
-
// video: escala para COBRIR a area e recorta o excesso, com pan (foco)
|
| 28 |
-
`[0:v]scale=${aw}:${ah}:force_original_aspect_ratio=increase,crop=${aw}:${ah}:(iw-${aw})*${fx.toFixed(4)}:(ih-${ah})*${fy.toFixed(4)},setsar=1,fps=30[vid]`,
|
| 29 |
-
// coloca o video na posicao da area
|
| 30 |
-
`[bg][vid]overlay=${ax}:${ay}[tmp]`,
|
| 31 |
-
// arte do molde por cima (o buraco transparente revela o video)
|
| 32 |
-
`[tmp][1:v]overlay=0:0[out]`,
|
| 33 |
-
],
|
| 34 |
-
'out'
|
| 35 |
-
)
|
| 36 |
.outputOptions([
|
| 37 |
'-map 0:a?', // mantem o audio do video, se existir
|
| 38 |
'-t', String(dur), // limita a duracao do video original
|
|
|
|
| 15 |
const fx = Math.min(1, Math.max(0, fnum(focus.x) / 100));
|
| 16 |
const fy = Math.min(1, Math.max(0, fnum(focus.y) / 100));
|
| 17 |
|
| 18 |
+
// Dois modos de composicao:
|
| 19 |
+
// - has_alpha = 1: o molde TEM furo transparente -> a arte vai POR CIMA e o
|
| 20 |
+
// video aparece pelo buraco (comportamento classico de "moldura").
|
| 21 |
+
// - has_alpha = 0: o molde e opaco -> colamos o video POR CIMA da arte, dentro
|
| 22 |
+
// da area marcada. Assim a area que o usuario escolhe sempre tem efeito.
|
| 23 |
+
const hasAlpha = mold.has_alpha === undefined ? 1 : Number(mold.has_alpha);
|
| 24 |
+
const videoStage = `[0:v]scale=${aw}:${ah}:force_original_aspect_ratio=increase,crop=${aw}:${ah}:(iw-${aw})*${fx.toFixed(4)}:(ih-${ah})*${fy.toFixed(4)},setsar=1,fps=30[vid]`;
|
| 25 |
+
const filters = hasAlpha
|
| 26 |
+
? [
|
| 27 |
+
`color=c=black:s=${cw}x${ch}:r=30:d=${dur}[bg]`,
|
| 28 |
+
videoStage,
|
| 29 |
+
`[bg][vid]overlay=${ax}:${ay}[tmp]`, // video na area
|
| 30 |
+
`[tmp][1:v]overlay=0:0[out]`, // arte por cima (revela pelo furo)
|
| 31 |
+
]
|
| 32 |
+
: [
|
| 33 |
+
`color=c=black:s=${cw}x${ch}:r=30:d=${dur}[bg]`,
|
| 34 |
+
videoStage,
|
| 35 |
+
`[bg][1:v]overlay=0:0[tmp]`, // arte primeiro (preenche o fundo)
|
| 36 |
+
`[tmp][vid]overlay=${ax}:${ay}[out]`, // video colado por cima, na area marcada
|
| 37 |
+
];
|
| 38 |
+
|
| 39 |
return new Promise((resolve, reject) => {
|
| 40 |
ffmpeg()
|
| 41 |
.input(sourceVideo)
|
| 42 |
.input(mold.file_path)
|
| 43 |
.inputOptions(['-loop 1']) // aplica ao ultimo input (a imagem do molde)
|
| 44 |
+
.complexFilter(filters, 'out')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
.outputOptions([
|
| 46 |
'-map 0:a?', // mantem o audio do video, se existir
|
| 47 |
'-t', String(dur), // limita a duracao do video original
|
|
@@ -8,6 +8,23 @@ ffmpeg.setFfprobePath(ffprobeStatic.path);
|
|
| 8 |
|
| 9 |
export { ffmpeg };
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
// Le metadados (duracao, largura, altura) de um arquivo de video.
|
| 12 |
export function probe(file) {
|
| 13 |
return new Promise((resolve, reject) => {
|
|
|
|
| 8 |
|
| 9 |
export { ffmpeg };
|
| 10 |
|
| 11 |
+
// Gera um poster leve (1 frame, JPG ~320px de largura) para usar como thumbnail
|
| 12 |
+
// no navegador, em vez de carregar dezenas de <video> ao mesmo tempo (trava o PC).
|
| 13 |
+
export function makeThumbnail(videoFile, outPath, seconds = 0.5) {
|
| 14 |
+
return new Promise((resolve, reject) => {
|
| 15 |
+
ffmpeg(videoFile)
|
| 16 |
+
.inputOptions(['-ss', String(seconds)]) // seek rapido antes de decodificar
|
| 17 |
+
.outputOptions([
|
| 18 |
+
'-frames:v', '1',
|
| 19 |
+
'-vf', 'scale=320:-2:force_original_aspect_ratio=decrease',
|
| 20 |
+
'-q:v', '4',
|
| 21 |
+
])
|
| 22 |
+
.on('end', () => resolve(outPath))
|
| 23 |
+
.on('error', (err) => reject(err))
|
| 24 |
+
.save(outPath);
|
| 25 |
+
});
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
// Le metadados (duracao, largura, altura) de um arquivo de video.
|
| 29 |
export function probe(file) {
|
| 30 |
return new Promise((resolve, reject) => {
|
|
@@ -5,11 +5,14 @@ import fs from 'node:fs';
|
|
| 5 |
import path from 'node:path';
|
| 6 |
import archiver from 'archiver';
|
| 7 |
import { DIRS } from '../config.js';
|
| 8 |
-
import { all, get, insert } from '../db.js';
|
| 9 |
import { analyzeMold } from '../editor/mold.js';
|
| 10 |
-
import { probe } from '../ffmpeg.js';
|
| 11 |
import { startBatch, jobStatus } from '../editor/batch.js';
|
| 12 |
|
|
|
|
|
|
|
|
|
|
| 13 |
const router = express.Router();
|
| 14 |
|
| 15 |
const VIDEO_EXT = new Set(['.mp4', '.mov', '.m4v', '.webm', '.mkv', '.avi']);
|
|
@@ -28,12 +31,12 @@ router.post('/molds', uploadMold.single('mold'), async (req, res) => {
|
|
| 28 |
if (!req.file) return res.status(400).json({ error: 'Envie um arquivo PNG no campo "mold".' });
|
| 29 |
const finalPath = path.join(DIRS.molds, `mold-${Date.now()}.png`);
|
| 30 |
fs.renameSync(req.file.path, finalPath);
|
| 31 |
-
const { canvasW, canvasH, area } = await analyzeMold(finalPath);
|
| 32 |
const name = req.body.name || path.parse(req.file.originalname).name;
|
| 33 |
const id = insert(
|
| 34 |
-
`INSERT INTO molds (name, file_path, canvas_w, canvas_h, area_x, area_y, area_w, area_h)
|
| 35 |
-
VALUES (?,?,?,?,?,?,?,?)`,
|
| 36 |
-
[name, finalPath, canvasW, canvasH, area.x, area.y, area.w, area.h]
|
| 37 |
);
|
| 38 |
res.json(get('SELECT * FROM molds WHERE id = ?', [id]));
|
| 39 |
} catch (err) {
|
|
@@ -41,6 +44,32 @@ router.post('/molds', uploadMold.single('mold'), async (req, res) => {
|
|
| 41 |
}
|
| 42 |
});
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
// ---- Videos-fonte ----
|
| 45 |
router.get('/sources', (_req, res) => {
|
| 46 |
res.json(all("SELECT * FROM media_assets WHERE kind = 'source' ORDER BY id DESC"));
|
|
@@ -83,6 +112,54 @@ async function registerSource(filePath, label) {
|
|
| 83 |
return get('SELECT * FROM media_assets WHERE id = ?', [id]);
|
| 84 |
}
|
| 85 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
// ---- Renderizacao em lote ----
|
| 87 |
router.post('/render', express.json(), (req, res) => {
|
| 88 |
try {
|
|
@@ -126,4 +203,17 @@ router.get('/library', (_req, res) => {
|
|
| 126 |
res.json(all("SELECT * FROM media_assets WHERE kind = 'rendered' ORDER BY id DESC"));
|
| 127 |
});
|
| 128 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
export default router;
|
|
|
|
| 5 |
import path from 'node:path';
|
| 6 |
import archiver from 'archiver';
|
| 7 |
import { DIRS } from '../config.js';
|
| 8 |
+
import { all, get, run, insert } from '../db.js';
|
| 9 |
import { analyzeMold } from '../editor/mold.js';
|
| 10 |
+
import { probe, makeThumbnail } from '../ffmpeg.js';
|
| 11 |
import { startBatch, jobStatus } from '../editor/batch.js';
|
| 12 |
|
| 13 |
+
// Remove um arquivo do disco sem quebrar se ele nao existir.
|
| 14 |
+
function safeUnlink(p) { try { if (p && fs.existsSync(p)) fs.unlinkSync(p); } catch {} }
|
| 15 |
+
|
| 16 |
const router = express.Router();
|
| 17 |
|
| 18 |
const VIDEO_EXT = new Set(['.mp4', '.mov', '.m4v', '.webm', '.mkv', '.avi']);
|
|
|
|
| 31 |
if (!req.file) return res.status(400).json({ error: 'Envie um arquivo PNG no campo "mold".' });
|
| 32 |
const finalPath = path.join(DIRS.molds, `mold-${Date.now()}.png`);
|
| 33 |
fs.renameSync(req.file.path, finalPath);
|
| 34 |
+
const { canvasW, canvasH, area, detected } = await analyzeMold(finalPath);
|
| 35 |
const name = req.body.name || path.parse(req.file.originalname).name;
|
| 36 |
const id = insert(
|
| 37 |
+
`INSERT INTO molds (name, file_path, canvas_w, canvas_h, area_x, area_y, area_w, area_h, area_auto, has_alpha)
|
| 38 |
+
VALUES (?,?,?,?,?,?,?,?,?,?)`,
|
| 39 |
+
[name, finalPath, canvasW, canvasH, area.x, area.y, area.w, area.h, detected ? 1 : 0, detected ? 1 : 0]
|
| 40 |
);
|
| 41 |
res.json(get('SELECT * FROM molds WHERE id = ?', [id]));
|
| 42 |
} catch (err) {
|
|
|
|
| 44 |
}
|
| 45 |
});
|
| 46 |
|
| 47 |
+
// Atualiza a AREA do video no molde (seletor manual / presets na tela).
|
| 48 |
+
router.post('/molds/:id/area', express.json(), (req, res) => {
|
| 49 |
+
const mold = get('SELECT * FROM molds WHERE id = ?', [Number(req.params.id)]);
|
| 50 |
+
if (!mold) return res.status(404).json({ error: 'Molde nao encontrado.' });
|
| 51 |
+
const clampEven = (v, max) => {
|
| 52 |
+
let n = Math.round(Number(v) || 0);
|
| 53 |
+
n = Math.max(0, Math.min(n, max));
|
| 54 |
+
return Math.max(2, n - (n % 2)); // par (exigencia do H.264)
|
| 55 |
+
};
|
| 56 |
+
const x = Math.max(0, Math.min(Math.round(Number(req.body.x) || 0), mold.canvas_w - 2));
|
| 57 |
+
const y = Math.max(0, Math.min(Math.round(Number(req.body.y) || 0), mold.canvas_h - 2));
|
| 58 |
+
const w = clampEven(req.body.w, mold.canvas_w - x);
|
| 59 |
+
const h = clampEven(req.body.h, mold.canvas_h - y);
|
| 60 |
+
// area definida manualmente passa a ser "confiavel" (area_auto = 1): some o aviso.
|
| 61 |
+
run('UPDATE molds SET area_x=?, area_y=?, area_w=?, area_h=?, area_auto=1 WHERE id=?',
|
| 62 |
+
[x - (x % 2), y - (y % 2), w, h, mold.id]);
|
| 63 |
+
res.json(get('SELECT * FROM molds WHERE id = ?', [mold.id]));
|
| 64 |
+
});
|
| 65 |
+
|
| 66 |
+
// Exclui um molde (e o arquivo PNG).
|
| 67 |
+
router.delete('/molds/:id', (req, res) => {
|
| 68 |
+
const mold = get('SELECT * FROM molds WHERE id = ?', [Number(req.params.id)]);
|
| 69 |
+
if (mold) { safeUnlink(mold.file_path); run('DELETE FROM molds WHERE id = ?', [mold.id]); }
|
| 70 |
+
res.json({ ok: true });
|
| 71 |
+
});
|
| 72 |
+
|
| 73 |
// ---- Videos-fonte ----
|
| 74 |
router.get('/sources', (_req, res) => {
|
| 75 |
res.json(all("SELECT * FROM media_assets WHERE kind = 'source' ORDER BY id DESC"));
|
|
|
|
| 112 |
return get('SELECT * FROM media_assets WHERE id = ?', [id]);
|
| 113 |
}
|
| 114 |
|
| 115 |
+
// Poster leve (JPG) de qualquer asset — gerado sob demanda e cacheado em disco.
|
| 116 |
+
// Substitui dezenas de <video> no navegador (era o que travava o PC ao subir muitos videos).
|
| 117 |
+
router.get('/thumb/:id', async (req, res) => {
|
| 118 |
+
const m = get('SELECT * FROM media_assets WHERE id = ?', [Number(req.params.id)]);
|
| 119 |
+
if (!m || !fs.existsSync(m.file_path)) return res.status(404).end();
|
| 120 |
+
const cached = m.thumb_path && fs.existsSync(m.thumb_path) ? m.thumb_path : null;
|
| 121 |
+
if (cached) { res.type('jpg'); return res.sendFile(path.resolve(cached)); }
|
| 122 |
+
const out = path.join(DIRS.thumbs, `thumb-${m.id}.jpg`);
|
| 123 |
+
try {
|
| 124 |
+
await makeThumbnail(m.file_path, out);
|
| 125 |
+
run('UPDATE media_assets SET thumb_path = ? WHERE id = ?', [out, m.id]);
|
| 126 |
+
res.type('jpg');
|
| 127 |
+
res.sendFile(path.resolve(out));
|
| 128 |
+
} catch {
|
| 129 |
+
res.status(404).end();
|
| 130 |
+
}
|
| 131 |
+
});
|
| 132 |
+
|
| 133 |
+
// Um arquivo e "gerenciado" se vive dentro de data/ (foi copiado/gerado pelo app).
|
| 134 |
+
// Videos importados por REFERENCIA (via "Importar pasta") apontam para a pasta
|
| 135 |
+
// original do usuario e NUNCA devem ser apagados do disco ao excluir da lista.
|
| 136 |
+
function isManaged(p) {
|
| 137 |
+
if (!p) return false;
|
| 138 |
+
const rel = path.relative(DIRS.data, path.resolve(p));
|
| 139 |
+
return Boolean(rel) && !rel.startsWith('..') && !path.isAbsolute(rel);
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
// Remove um asset do banco; apaga do disco apenas arquivos gerenciados (data/).
|
| 143 |
+
function removeAsset(m) {
|
| 144 |
+
if (!m) return;
|
| 145 |
+
if (isManaged(m.file_path)) safeUnlink(m.file_path);
|
| 146 |
+
safeUnlink(m.thumb_path); // thumb fica sempre em data/thumbs -> seguro apagar
|
| 147 |
+
run('DELETE FROM media_assets WHERE id = ?', [m.id]);
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
// Excluir UM video-fonte.
|
| 151 |
+
router.delete('/sources/:id', (req, res) => {
|
| 152 |
+
removeAsset(get("SELECT * FROM media_assets WHERE id = ? AND kind = 'source'", [Number(req.params.id)]));
|
| 153 |
+
res.json({ ok: true });
|
| 154 |
+
});
|
| 155 |
+
|
| 156 |
+
// Excluir TODOS os videos-fonte de uma vez.
|
| 157 |
+
router.delete('/sources', (_req, res) => {
|
| 158 |
+
const list = all("SELECT * FROM media_assets WHERE kind = 'source'");
|
| 159 |
+
list.forEach(removeAsset);
|
| 160 |
+
res.json({ ok: true, removed: list.length });
|
| 161 |
+
});
|
| 162 |
+
|
| 163 |
// ---- Renderizacao em lote ----
|
| 164 |
router.post('/render', express.json(), (req, res) => {
|
| 165 |
try {
|
|
|
|
| 203 |
res.json(all("SELECT * FROM media_assets WHERE kind = 'rendered' ORDER BY id DESC"));
|
| 204 |
});
|
| 205 |
|
| 206 |
+
// Excluir UM video renderizado da biblioteca.
|
| 207 |
+
router.delete('/library/:id', (req, res) => {
|
| 208 |
+
removeAsset(get("SELECT * FROM media_assets WHERE id = ? AND kind = 'rendered'", [Number(req.params.id)]));
|
| 209 |
+
res.json({ ok: true });
|
| 210 |
+
});
|
| 211 |
+
|
| 212 |
+
// Excluir TODOS os videos renderizados.
|
| 213 |
+
router.delete('/library', (_req, res) => {
|
| 214 |
+
const list = all("SELECT * FROM media_assets WHERE kind = 'rendered'");
|
| 215 |
+
list.forEach(removeAsset);
|
| 216 |
+
res.json({ ok: true, removed: list.length });
|
| 217 |
+
});
|
| 218 |
+
|
| 219 |
export default router;
|
|
@@ -10,18 +10,49 @@ import editorRouter from './routes/editor.js';
|
|
| 10 |
import scheduleRouter from './routes/schedule.js';
|
| 11 |
import accountsRouter from './routes/accounts.js';
|
| 12 |
import { startWorker } from './scheduler/worker.js';
|
|
|
|
| 13 |
|
| 14 |
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
| 15 |
const app = express();
|
| 16 |
|
| 17 |
-
//
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
app.use('/api/editor', editorRouter);
|
| 19 |
app.use('/api/schedule', scheduleRouter);
|
| 20 |
app.use('/', accountsRouter); // /workspaces, /accounts, /platforms, /settings, /oauth/*
|
| 21 |
|
| 22 |
-
// Arquivos publicos (usado pelo tunel do Instagram e para previews)
|
| 23 |
-
app.use('/public-media', express.static(DIRS.output));
|
| 24 |
-
|
| 25 |
// Preview de qualquer asset/molde pelo id (no navegador)
|
| 26 |
app.get('/preview/:id', (req, res) => {
|
| 27 |
const m = get('SELECT file_path FROM media_assets WHERE id = ?', [Number(req.params.id)]);
|
|
@@ -38,7 +69,8 @@ app.get('/mold-file/:id', (req, res) => {
|
|
| 38 |
app.use(express.static(path.join(ROOT, 'public')));
|
| 39 |
app.get('*', (_req, res) => res.sendFile(path.join(ROOT, 'public', 'index.html')));
|
| 40 |
|
| 41 |
-
app
|
|
|
|
| 42 |
console.log(`\n 💸 PagsDark rodando em ${config.baseUrl}\n`);
|
| 43 |
startWorker();
|
| 44 |
});
|
|
|
|
| 10 |
import scheduleRouter from './routes/schedule.js';
|
| 11 |
import accountsRouter from './routes/accounts.js';
|
| 12 |
import { startWorker } from './scheduler/worker.js';
|
| 13 |
+
import { authEnabled, getUser, publicAuthConfig } from './auth.js';
|
| 14 |
|
| 15 |
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
| 16 |
const app = express();
|
| 17 |
|
| 18 |
+
// Cabecalhos basicos de seguranca (sem dependencia extra).
|
| 19 |
+
app.disable('x-powered-by');
|
| 20 |
+
app.use((_req, res, next) => {
|
| 21 |
+
res.setHeader('X-Content-Type-Options', 'nosniff');
|
| 22 |
+
res.setHeader('X-Frame-Options', 'SAMEORIGIN');
|
| 23 |
+
res.setHeader('Referrer-Policy', 'no-referrer');
|
| 24 |
+
next();
|
| 25 |
+
});
|
| 26 |
+
|
| 27 |
+
// Arquivos publicos para o tunel do Instagram (a Meta busca o video por fora):
|
| 28 |
+
// precisa ficar SEM login. Colocado antes do gate de autenticacao de proposito.
|
| 29 |
+
app.use('/public-media', express.static(DIRS.output));
|
| 30 |
+
|
| 31 |
+
// ---- Autenticacao (Supabase) ----
|
| 32 |
+
// Config publica para o cliente (sem segredos) e logout.
|
| 33 |
+
app.get('/auth/config', (_req, res) => res.json(publicAuthConfig()));
|
| 34 |
+
app.get('/login', (_req, res) => res.sendFile(path.join(ROOT, 'public', 'login.html')));
|
| 35 |
+
app.get('/logout', (_req, res) => {
|
| 36 |
+
res.setHeader('Set-Cookie', 'sb-access-token=; Path=/; Max-Age=0; SameSite=Lax');
|
| 37 |
+
res.redirect('/login');
|
| 38 |
+
});
|
| 39 |
+
|
| 40 |
+
// Gate: quando o login esta ligado, tudo (menos os itens publicos) exige sessao.
|
| 41 |
+
const OPEN_PATHS = ['/login', '/login.html', '/login.js', '/style.css', '/auth/config', '/logout', '/favicon.ico'];
|
| 42 |
+
app.use((req, res, next) => {
|
| 43 |
+
if (!authEnabled()) { req.user = { id: 'local', local: true }; return next(); }
|
| 44 |
+
if (OPEN_PATHS.includes(req.path) || req.path.startsWith('/public-media')) return next();
|
| 45 |
+
const user = getUser(req);
|
| 46 |
+
if (user) { req.user = user; return next(); }
|
| 47 |
+
if ((req.headers.accept || '').includes('text/html')) return res.redirect('/login');
|
| 48 |
+
return res.status(401).json({ error: 'Não autenticado.' });
|
| 49 |
+
});
|
| 50 |
+
|
| 51 |
+
// API (protegida pelo gate acima quando o login esta ligado)
|
| 52 |
app.use('/api/editor', editorRouter);
|
| 53 |
app.use('/api/schedule', scheduleRouter);
|
| 54 |
app.use('/', accountsRouter); // /workspaces, /accounts, /platforms, /settings, /oauth/*
|
| 55 |
|
|
|
|
|
|
|
|
|
|
| 56 |
// Preview de qualquer asset/molde pelo id (no navegador)
|
| 57 |
app.get('/preview/:id', (req, res) => {
|
| 58 |
const m = get('SELECT file_path FROM media_assets WHERE id = ?', [Number(req.params.id)]);
|
|
|
|
| 69 |
app.use(express.static(path.join(ROOT, 'public')));
|
| 70 |
app.get('*', (_req, res) => res.sendFile(path.join(ROOT, 'public', 'index.html')));
|
| 71 |
|
| 72 |
+
// Vincula apenas ao localhost: o app e local e nao deve ficar exposto na rede.
|
| 73 |
+
app.listen(config.port, '127.0.0.1', () => {
|
| 74 |
console.log(`\n 💸 PagsDark rodando em ${config.baseUrl}\n`);
|
| 75 |
startWorker();
|
| 76 |
});
|