Claude Opus 4.8
Deploy PagsDark — site 24/7 (sem túnel, perf otimizada, OAuth e login Google corrigidos)
e0454ce Download src/db.js from pagsdark/web: direct link, hf CLI and curl.
- Browser
- Download file 8.43 kB
-
https://huggingface.co/spaces/pagsdark/web/resolve/main/src/db.js
- Command line
-
hf download hf://spaces/pagsdark/web/src/db.js
-
curl -L -o db.js https://huggingface.co/spaces/pagsdark/web/resolve/main/src/db.js
8.43 kB
| // Banco de dados SQLite via cliente libsql (API SÍNCRONA, compatível). | |
| // | |
| // Dois modos: | |
| // - LOCAL (padrão): arquivo dark.db no disco. Simples, mas some se o disco reiniciar. | |
| // - TURSO (nuvem, grátis): se TURSO_DATABASE_URL + TURSO_AUTH_TOKEN estiverem no | |
| // ambiente, usa uma "réplica embutida" — as leituras são locais (rápidas) e as | |
| // gravações vão para o banco na NUVEM. Assim, contas, campanhas e logins | |
| // SOBREVIVEM a reinícios do servidor (na hospedagem grátis do Hugging Face). | |
| import Database from 'libsql'; | |
| import fs from 'node:fs'; | |
| import path from 'node:path'; | |
| import { DIRS } from './config.js'; | |
| // Garante que as pastas de dados existem. | |
| for (const dir of Object.values(DIRS)) fs.mkdirSync(dir, { recursive: true }); | |
| const localDbPath = path.join(DIRS.data, 'dark.db'); | |
| const TURSO_URL = process.env.TURSO_DATABASE_URL; | |
| const TURSO_TOKEN = process.env.TURSO_AUTH_TOKEN; | |
| export const usingTurso = Boolean(TURSO_URL && TURSO_TOKEN); | |
| let db; | |
| if (usingTurso) { | |
| // Réplica embutida: arquivo local sincronizado com o banco na nuvem (Turso). | |
| // Sem sync automático no construtor: cada db.sync() é SÍNCRONO e trava o event | |
| // loop. A replicação periódica fica só no setInterval abaixo (rede de segurança | |
| // de LEITURA — as GRAVAÇÕES já vão write-through para a nuvem na hora). | |
| db = new Database(localDbPath, { syncUrl: TURSO_URL, authToken: TURSO_TOKEN }); | |
| try { db.sync(); } catch (e) { console.warn('[db] sync inicial falhou (seguindo):', e.message || e); } | |
| db.exec('PRAGMA foreign_keys = ON;'); | |
| console.log('[db] usando Turso (nuvem) — dados persistem entre reinícios.'); | |
| } else { | |
| db = new Database(localDbPath); | |
| db.exec('PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;'); | |
| } | |
| // Replica pra nuvem periodicamente (rede de segurança, além do write-through). | |
| export function syncNow() { if (usingTurso) { try { db.sync(); } catch {} } } | |
| db.exec(` | |
| CREATE TABLE IF NOT EXISTS workspaces ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| name TEXT NOT NULL, | |
| created_at TEXT NOT NULL DEFAULT (datetime('now')) | |
| ); | |
| CREATE TABLE IF NOT EXISTS accounts ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| workspace_id INTEGER NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE, | |
| platform TEXT NOT NULL, -- youtube | instagram | tiktok | kwai | |
| display_name TEXT, | |
| external_id TEXT, -- id da conta na rede (canal, ig user, etc.) | |
| access_token_enc TEXT, | |
| refresh_token_enc TEXT, | |
| token_expires_at TEXT, | |
| scopes TEXT, | |
| meta TEXT, -- JSON extra por plataforma | |
| status TEXT NOT NULL DEFAULT 'connected', | |
| created_at TEXT NOT NULL DEFAULT (datetime('now')) | |
| ); | |
| CREATE TABLE IF NOT EXISTS molds ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| name TEXT NOT NULL, | |
| file_path TEXT NOT NULL, | |
| canvas_w INTEGER NOT NULL, | |
| canvas_h INTEGER NOT NULL, | |
| area_x INTEGER NOT NULL, | |
| area_y INTEGER NOT NULL, | |
| area_w INTEGER NOT NULL, | |
| area_h INTEGER NOT NULL, | |
| created_at TEXT NOT NULL DEFAULT (datetime('now')) | |
| ); | |
| CREATE TABLE IF NOT EXISTS media_assets ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| kind TEXT NOT NULL, -- source | rendered | |
| file_path TEXT NOT NULL, | |
| label TEXT, | |
| duration REAL, | |
| width INTEGER, | |
| height INTEGER, | |
| created_at TEXT NOT NULL DEFAULT (datetime('now')) | |
| ); | |
| CREATE TABLE IF NOT EXISTS render_jobs ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| mold_id INTEGER REFERENCES molds(id) ON DELETE SET NULL, | |
| status TEXT NOT NULL DEFAULT 'running', -- running | done | failed | |
| total INTEGER NOT NULL DEFAULT 0, | |
| done INTEGER NOT NULL DEFAULT 0, | |
| output_dir TEXT, | |
| created_at TEXT NOT NULL DEFAULT (datetime('now')) | |
| ); | |
| CREATE TABLE IF NOT EXISTS render_items ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| job_id INTEGER NOT NULL REFERENCES render_jobs(id) ON DELETE CASCADE, | |
| source_path TEXT NOT NULL, | |
| output_path TEXT, | |
| status TEXT NOT NULL DEFAULT 'pending', -- pending | done | failed | |
| error TEXT | |
| ); | |
| CREATE TABLE IF NOT EXISTS campaigns ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| workspace_id INTEGER NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE, | |
| name TEXT NOT NULL, | |
| start_date TEXT NOT NULL, -- YYYY-MM-DD | |
| posts_per_day INTEGER NOT NULL, | |
| time_slots TEXT NOT NULL, -- JSON: ["08:00","10:00",...] | |
| account_ids TEXT NOT NULL, -- JSON: [1,2,3] | |
| fanout TEXT NOT NULL DEFAULT 'cross', -- cross | roundrobin | |
| caption_template TEXT, | |
| status TEXT NOT NULL DEFAULT 'active', -- active | paused | done | |
| created_at TEXT NOT NULL DEFAULT (datetime('now')) | |
| ); | |
| CREATE TABLE IF NOT EXISTS posts ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| workspace_id INTEGER NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE, | |
| campaign_id INTEGER REFERENCES campaigns(id) ON DELETE CASCADE, | |
| account_id INTEGER NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, | |
| platform TEXT NOT NULL, | |
| media_path TEXT NOT NULL, | |
| caption TEXT, | |
| scheduled_at TEXT NOT NULL, -- ISO em hora local | |
| status TEXT NOT NULL DEFAULT 'scheduled', -- scheduled | posting | posted | failed | canceled | |
| external_post_id TEXT, | |
| error TEXT, | |
| posted_at TEXT, | |
| created_at TEXT NOT NULL DEFAULT (datetime('now')) | |
| ); | |
| CREATE TABLE IF NOT EXISTS users ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| email TEXT NOT NULL UNIQUE, | |
| pass_hash TEXT NOT NULL, -- scrypt: salt:hash (hex) | |
| name TEXT, | |
| created_at TEXT NOT NULL DEFAULT (datetime('now')) | |
| ); | |
| CREATE TABLE IF NOT EXISTS app_secrets ( | |
| key TEXT PRIMARY KEY, | |
| value TEXT NOT NULL | |
| ); | |
| CREATE INDEX IF NOT EXISTS idx_posts_due ON posts(status, scheduled_at); | |
| CREATE INDEX IF NOT EXISTS idx_render_items_job ON render_items(job_id); | |
| `); | |
| // ----- Migracoes leves (colunas adicionadas depois) ----- | |
| // SQLite nao tem "ADD COLUMN IF NOT EXISTS"; tentamos e ignoramos se ja existe. | |
| function addColumn(table, colDef) { | |
| try { db.exec(`ALTER TABLE ${table} ADD COLUMN ${colDef}`); } | |
| catch (e) { if (!/duplicate column/i.test(String(e.message || e))) throw e; } | |
| } | |
| addColumn('media_assets', 'thumb_path TEXT'); // poster JPG leve (gerado sob demanda) | |
| addColumn('molds', 'area_auto INTEGER DEFAULT 1'); // 1 = area confiavel (transparencia detectada OU definida na tela); 0 = placeholder, precisa atencao | |
| 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) | |
| // ----- Multiusuario: cada linha pertence a um DONO (owner_id) ----- | |
| // owner_id guarda o id do usuario logado (string: "local:<n>" ou "sb:<uuid>"). | |
| // Toda consulta filtra por owner_id, entao um usuario NUNCA ve/usa dados de outro. | |
| const OWNED_TABLES = ['workspaces', 'accounts', 'molds', 'media_assets', | |
| 'render_jobs', 'render_items', 'campaigns', 'posts']; | |
| for (const t of OWNED_TABLES) addColumn(t, 'owner_id TEXT'); | |
| for (const t of OWNED_TABLES) { | |
| db.exec(`CREATE INDEX IF NOT EXISTS idx_${t}_owner ON ${t}(owner_id)`); | |
| } | |
| // Indice composto para as listagens quentes que filtram por dono + tipo (source/rendered). | |
| db.exec('CREATE INDEX IF NOT EXISTS idx_media_assets_owner_kind ON media_assets(owner_id, kind)'); | |
| // Backfill: dados que ja existiam (antes do multiusuario) ficam com o PRIMEIRO | |
| // usuario local cadastrado. Roda so uma vez (linhas sem dono). Em banco novo | |
| // (producao) nao faz nada. | |
| (function backfillOwner() { | |
| const u = get('SELECT MIN(id) AS id FROM users'); | |
| if (!u || !u.id) return; // sem usuarios: nada a migrar | |
| const owner = 'local:' + u.id; | |
| for (const t of OWNED_TABLES) { | |
| run(`UPDATE ${t} SET owner_id = ? WHERE owner_id IS NULL`, [owner]); | |
| } | |
| })(); | |
| // Depois das migrações, empurra o schema pra nuvem e liga a replicação periódica. | |
| if (usingTurso) { | |
| syncNow(); | |
| const t = setInterval(syncNow, 60000); | |
| if (t.unref) t.unref(); | |
| } | |
| export default db; | |
| // ----- Helpers genericos ----- | |
| // O libsql adiciona um campo "_metadata" em cada linha; removemos pra não vazar | |
| // pra API/cliente. | |
| function clean(row) { if (row && row._metadata !== undefined) delete row._metadata; return row; } | |
| export function all(sql, params = []) { return db.prepare(sql).all(...params).map(clean); } | |
| export function get(sql, params = []) { return clean(db.prepare(sql).get(...params)); } | |
| export function run(sql, params = []) { return db.prepare(sql).run(...params); } | |
| export function insert(sql, params = []) { return Number(db.prepare(sql).run(...params).lastInsertRowid); } | |