require('dotenv').config(); const express = require('express'); const morgan = require('morgan'); const { chromium, devices } = require('playwright'); const path = require('path'); const os = require('os'); const fs = require('fs'); const crypto = require('crypto'); const { execSync } = require('child_process'); const { pathToFileURL } = require('url'); const app = express(); const PORT = process.env.PORT || 7860; app.use(morgan('common')); // ====== Config ====== const CONFIG = { viewport: { width: 1536, height: 695 }, maxTextLength: 100, }; // ====== Browser lifecycle ====== let browserPromise; const launchBrowser = () => { browserPromise ??= chromium.launch({ headless: true }) .then(browser => { browser.once('disconnected', () => { browserPromise = undefined; }); return browser; }) .catch(error => { browserPromise = undefined; throw error; }); return browserPromise; }; const closeBrowser = async () => { try { await (await browserPromise)?.close(); } catch {} }; // ====== Helpers ====== const siteFileUrl = pathToFileURL(path.join(__dirname, 'site', 'www.bratgenerator.com', 'index.html')).href; async function openBratRenderer(background, color) { const browser = await launchBrowser(); const context = await browser.newContext({ viewport: CONFIG.viewport }); try { await context.route(/^https?:\/\//, route => route.abort()); const page = await context.newPage(); await page.goto(siteFileUrl, { waitUntil: 'domcontentloaded', timeout: 20000 }); await page.evaluate(async ({ background, color }) => { window.setupTheme('white'); document.getElementById('memeImage').style.display = 'none'; const overlay = document.getElementById('textOverlay'); const fitted = overlay.querySelector('.textFitted'); overlay.style.backgroundColor = '#fff'; overlay.style.fontFamily = 'arial_narrowregular, "Arial Narrow", Arial, "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", sans-serif'; fitted.style.fontFamily = 'inherit'; if (typeof background === 'string' && background) overlay.style.backgroundColor = background; if (typeof color === 'string' && color) fitted.style.color = color; const fonts = await document.fonts.load('500 16px arial_narrowregular'); if (!fonts.length) throw new Error('Font Arial Narrow lokal tidak ditemukan'); }, { background, color }); return { context, overlay: page.locator('#textOverlay') }; } catch (error) { await context.close(); throw error; } } async function renderBrat(overlay, text) { await overlay.evaluate((element, text) => { const input = document.getElementById('textInput'); input.value = text; element.querySelector('.textFitted').textContent = input.value; window.textFit(element, { maxFontSize: 75 }); }, text); return overlay.screenshot(); } function isSafeUrl(u) { try { const url = new URL(u); if (!['http:', 'https:'].includes(url.protocol)) return false; const host = url.hostname.toLowerCase(); if ( host === 'localhost' || host === '127.0.0.1' || host === '0.0.0.0' || host.endsWith('.local') ) return false; return true; } catch { return false; } } // ====== Routes ====== app.get('/', async (req, res) => { res.json({ author: 'Kavion', message: "Gunakan /brat?q=teks, /bratvid?q=teks[&letter=true], /ssweb?url=https://...", runtime: { os: os.type(), platform: os.platform(), architecture: os.arch(), cpuCount: os.cpus().length, uptime: `${os.uptime()} seconds`, memoryUsage: `${Math.round((os.totalmem() - os.freemem()) / 1024 / 1024)} MB used of ${Math.round(os.totalmem() / 1024 / 1024)} MB` } }); }); /** * /brat — render gambar via .site lokal * q: teks (wajib), background: hex/rgb optional, color: hex/rgb optional */ app.get('/brat', async (req, res) => { const { q, background, color } = req.query; if (!q) { return res.status(400).json({ message: "Parameter `q` diperlukan" }); } const text = String(q).slice(0, CONFIG.maxTextLength); let context; try { const opened = await openBratRenderer(background, color); context = opened.context; const png = await renderBrat(opened.overlay, text); res.set('Content-Type', 'image/png'); res.send(png); } catch (e) { console.error('Error /brat:', e); res.status(500).json({ status: false, message: 'Gagal membuat gambar', error: process.env.NODE_ENV === 'development' ? e.message : undefined }); } finally { if (context) await context.close(); } }); /** * /bratvid — render video (per-kata default, per-huruf jika letter=true) * q: teks (wajib), background/color optional, letter=true|false * butuh ffmpeg terpasang */ app.get('/bratvid', async (req, res) => { const { q, background, color, letter } = req.query; if (!q) return res.status(400).json({ message: "Parameter `q` diperlukan" }); const text = String(q).slice(0, CONFIG.maxTextLength); const perLetter = String(letter).toLowerCase() === 'true'; let context; const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'brat-')); const id = crypto.randomUUID(); const frames = []; const fileList = path.join(tmpDir, `${id}.txt`); const outVideo = path.join(tmpDir, `${id}.mp4`); try { const opened = await openBratRenderer(background, color); context = opened.context; // tentukan segmen const segments = perLetter ? [...text] : text.split(' ').filter(Boolean); if (segments.length === 0) throw new Error('Teks kosong setelah diproses.'); let curr = ''; for (let i = 0; i < segments.length; i++) { curr += (i > 0 ? ' ' : '') + segments[i]; const buf = await renderBrat(opened.overlay, curr); const framePath = path.join(tmpDir, `${id}-${i}.png`); fs.writeFileSync(framePath, buf); frames.push(framePath); } // buat concat list const duration = perLetter ? 0.4 : 0.6; let fileListContent = frames.map(p => `file '${p.replace(/'/g, "'\\''")}'\nduration ${duration}`).join('\n'); fileListContent += `\nfile '${frames[frames.length - 1].replace(/'/g, "'\\''")}'\nduration 2\n`; fs.writeFileSync(fileList, fileListContent); // render video execSync( `ffmpeg -y -f concat -safe 0 -i "${fileList}" -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2,fps=30" -c:v libx264 -preset ultrafast -pix_fmt yuv420p "${outVideo}"`, { stdio: 'ignore', timeout: 120000 } ); const videoBuffer = fs.readFileSync(outVideo); res.set('Content-Type', 'video/mp4'); res.send(videoBuffer); } catch (e) { console.error('Error /bratvid:', e); res.status(500).json({ status: false, message: 'Gagal membuat video', error: process.env.NODE_ENV === 'development' ? e.message : undefined }); } finally { // cleanup try { for (const f of frames) fs.existsSync(f) && fs.unlinkSync(f); fs.existsSync(fileList) && fs.unlinkSync(fileList); fs.existsSync(outVideo) && fs.unlinkSync(outVideo); fs.existsSync(tmpDir) && fs.rmSync(tmpDir, { recursive: true, force: true }); } catch {} if (context) await context.close(); } }); /** * /ssweb — screenshot halaman web penuh * url (wajib), type=desktop|mobile|tablet, mode=light|dark */ app.get('/ssweb', async (req, res) => { const { url, type = 'desktop', mode = 'light' } = req.query; if (!url) return res.status(400).json({ message: 'Parameter `url` diperlukan' }); if (String(url).length > 2048 || !isSafeUrl(url)) { return res.status(400).json({ status: false, message: 'URL tidak valid atau tidak diizinkan' }); } let context; try { const browser = await launchBrowser(); const deviceOptions = { mobile: devices['Galaxy S5'], tablet: devices['Galaxy Tab S4'], desktop: devices['Desktop Chrome'], }; const device = deviceOptions[type] || deviceOptions.desktop; context = await browser.newContext({ ...device, colorScheme: mode }); const page = await context.newPage(); await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 20000 }); await page.waitForTimeout(1000); const buffer = await page.screenshot({ fullPage: true }); res.set('Content-Type', 'image/png'); res.send(buffer); } catch (e) { console.error('Error /ssweb:', e); res.status(500).json({ status: false, message: 'Gagal membuat screenshot', error: process.env.NODE_ENV === 'development' ? e.message : undefined }); } finally { if (context) await context.close(); } }); // ====== Start & shutdown ====== app.listen(PORT, async () => { console.log(`Server is running on port ${PORT}`); try { await launchBrowser(); } catch (e) { console.warn('Launch browser deferred:', e.message); } }); process.on('SIGINT', async () => { await closeBrowser(); process.exit(0); }); process.on('SIGTERM', async () => { await closeBrowser(); process.exit(0); }); process.on('exit', async () => { await closeBrowser(); });