387 lines
15 KiB
JavaScript
387 lines
15 KiB
JavaScript
const express = require('express');
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const crypto = require('crypto');
|
|
const { initPool, renderHtml, POOL_SIZE } = require('./browserPool');
|
|
const v2Routes = require('./v2Routes');
|
|
const { cleanupExpiredSessions } = require('./db');
|
|
|
|
const app = express();
|
|
const PORT = 3000;
|
|
const CACHE_DIR = path.join(__dirname, 'cache');
|
|
|
|
// Create cache directory if it doesn't exist
|
|
if (!fs.existsSync(CACHE_DIR)) {
|
|
fs.mkdirSync(CACHE_DIR);
|
|
}
|
|
|
|
app.use(express.json({ limit: '1gb' }));
|
|
app.use(express.urlencoded({ limit: '1gb', extended: true }));
|
|
|
|
// Request logging middleware
|
|
app.use((req, res, next) => {
|
|
// skip logging health checks
|
|
if (req.url === '/health') {
|
|
return next();
|
|
}
|
|
|
|
const timestamp = new Date().toISOString();
|
|
console.log(`\n[${timestamp}] ${req.method} ${req.url}`);
|
|
|
|
if ((req.method === 'POST' || req.method === 'PATCH') && req.body) {
|
|
const logBody = { ...req.body };
|
|
|
|
// Truncate long base64 strings for readability
|
|
if (logBody.avatarUrl && logBody.avatarUrl.startsWith('data:')) {
|
|
logBody.avatarUrl = logBody.avatarUrl.substring(0, 50) + '... (base64 truncated)';
|
|
}
|
|
if (logBody.imageUrl && logBody.imageUrl.startsWith('data:')) {
|
|
logBody.imageUrl = logBody.imageUrl.substring(0, 50) + '... (base64 truncated)';
|
|
}
|
|
|
|
console.log('Body:', JSON.stringify(logBody, null, 2));
|
|
}
|
|
|
|
if (req.method === 'GET' && Object.keys(req.query).length > 0) {
|
|
const logQuery = { ...req.query };
|
|
|
|
// Truncate long base64 strings for readability
|
|
if (logQuery.avatarUrl && logQuery.avatarUrl.startsWith('data:')) {
|
|
logQuery.avatarUrl = logQuery.avatarUrl.substring(0, 50) + '... (base64 truncated)';
|
|
}
|
|
if (logQuery.imageUrl && logQuery.imageUrl.startsWith('data:')) {
|
|
logQuery.imageUrl = logQuery.imageUrl.substring(0, 50) + '... (base64 truncated)';
|
|
}
|
|
|
|
console.log('Query:', JSON.stringify(logQuery, null, 2));
|
|
}
|
|
|
|
next();
|
|
});
|
|
|
|
// mount v2 api
|
|
app.use('/v2', v2Routes);
|
|
|
|
function normalizeConfig(config) {
|
|
// Remove null, undefined, and empty string values
|
|
const normalized = {};
|
|
for (const [key, value] of Object.entries(config)) {
|
|
if (value !== null && value !== undefined && value !== '') {
|
|
normalized[key] = value;
|
|
}
|
|
}
|
|
return normalized;
|
|
}
|
|
|
|
function hashConfig(config) {
|
|
const normalized = normalizeConfig(config);
|
|
const configString = JSON.stringify(normalized);
|
|
return crypto.createHash('sha256').update(configString).digest('hex');
|
|
}
|
|
|
|
function getCachePath(hash) {
|
|
return path.join(CACHE_DIR, `${hash}.png`);
|
|
}
|
|
|
|
function getCachedImage(config) {
|
|
const hash = hashConfig(config);
|
|
const cachePath = getCachePath(hash);
|
|
|
|
if (fs.existsSync(cachePath)) {
|
|
// Update file modification time to mark as recently accessed
|
|
const now = new Date();
|
|
fs.utimesSync(cachePath, now, now);
|
|
return fs.readFileSync(cachePath);
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
function cacheImage(config, imageBuffer) {
|
|
const hash = hashConfig(config);
|
|
const cachePath = getCachePath(hash);
|
|
fs.writeFileSync(cachePath, imageBuffer);
|
|
}
|
|
|
|
function clearCache() {
|
|
if (!fs.existsSync(CACHE_DIR)) {
|
|
return;
|
|
}
|
|
|
|
const files = fs.readdirSync(CACHE_DIR);
|
|
files.forEach(file => {
|
|
const filePath = path.join(CACHE_DIR, file);
|
|
fs.unlinkSync(filePath);
|
|
});
|
|
|
|
console.log(`Cleared ${files.length} cached image(s)`);
|
|
}
|
|
|
|
function cleanupOldCache() {
|
|
const ONE_DAY = 24 * 60 * 60 * 1000; // 24 hours in milliseconds
|
|
const now = Date.now();
|
|
|
|
if (!fs.existsSync(CACHE_DIR)) {
|
|
return;
|
|
}
|
|
|
|
const files = fs.readdirSync(CACHE_DIR);
|
|
|
|
let deletedCount = 0;
|
|
files.forEach(file => {
|
|
const filePath = path.join(CACHE_DIR, file);
|
|
const stats = fs.statSync(filePath);
|
|
|
|
// Check if file was last modified more than 24 hours ago
|
|
if (now - stats.mtime.getTime() > ONE_DAY) {
|
|
fs.unlinkSync(filePath);
|
|
deletedCount++;
|
|
}
|
|
});
|
|
|
|
if (deletedCount > 0) {
|
|
console.log(`Cleaned up ${deletedCount} cached image(s)`);
|
|
}
|
|
}
|
|
|
|
function formatCount(num) {
|
|
if (num === null || num === undefined) return '0';
|
|
|
|
num = parseInt(num);
|
|
|
|
if (num >= 1000000000) {
|
|
return (num / 1000000000).toFixed(1).replace(/\.0$/, '') + 'B';
|
|
}
|
|
if (num >= 1000000) {
|
|
return (num / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';
|
|
}
|
|
if (num >= 1000) {
|
|
return (num / 1000).toFixed(1).replace(/\.0$/, '') + 'K';
|
|
}
|
|
return num.toString();
|
|
}
|
|
|
|
function formatTimestamp(epoch) {
|
|
const date = new Date(epoch * 1000);
|
|
|
|
const hours = date.getHours();
|
|
const minutes = date.getMinutes().toString().padStart(2, '0');
|
|
const ampm = hours >= 12 ? 'PM' : 'AM';
|
|
const hour12 = hours % 12 || 12;
|
|
|
|
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
|
const month = months[date.getMonth()];
|
|
const day = date.getDate();
|
|
const year = date.getFullYear();
|
|
|
|
return `${hour12}:${minutes} ${ampm} · ${month} ${day}, ${year}`;
|
|
}
|
|
|
|
const TEMPLATE_PATH = path.join(__dirname, 'template.html');
|
|
const templateHtml = fs.readFileSync(TEMPLATE_PATH, 'utf8');
|
|
|
|
function buildEngagementHtml(engagement) {
|
|
if (!engagement) return '';
|
|
return `
|
|
<div class="engagement-bar" role="group">
|
|
<div class="engagement-item">
|
|
<svg viewBox="0 0 24 24" class="engagement-icon"><g><path d="M1.751 10c0-4.42 3.584-8 8.005-8h4.366c4.49 0 8.129 3.64 8.129 8.13 0 2.96-1.607 5.68-4.196 7.11l-8.054 4.46v-3.69h-.067c-4.49.1-8.183-3.51-8.183-8.01zm8.005-6c-3.317 0-6.005 2.69-6.005 6 0 3.37 2.77 6.08 6.138 6.01l.351-.01h1.761v2.3l5.087-2.81c1.951-1.08 3.163-3.13 3.163-5.36 0-3.39-2.744-6.13-6.129-6.13H9.756z"></path></g></svg>
|
|
<span class="engagement-count">${engagement.replies}</span>
|
|
</div>
|
|
<div class="engagement-item">
|
|
<svg viewBox="0 0 24 24" class="engagement-icon"><g><path d="M4.5 3.88l4.432 4.14-1.364 1.46L5.5 7.55V16c0 1.1.896 2 2 2H13v2H7.5c-2.209 0-4-1.79-4-4V7.55L1.432 9.48.068 8.02 4.5 3.88zM16.5 6H11V4h5.5c2.209 0 4 1.79 4 4v8.45l2.068-1.93 1.364 1.46-4.432 4.14-4.432-4.14 1.364-1.46 2.068 1.93V8c0-1.1-.896-2-2-2z"></path></g></svg>
|
|
<span class="engagement-count">${engagement.retweets}</span>
|
|
</div>
|
|
<div class="engagement-item">
|
|
<svg viewBox="0 0 24 24" class="engagement-icon"><g><path d="M16.697 5.5c-1.222-.06-2.679.51-3.89 2.16l-.805 1.09-.806-1.09C9.984 6.01 8.526 5.44 7.304 5.5c-1.243.07-2.349.78-2.91 1.91-.552 1.12-.633 2.78.479 4.82 1.074 1.97 3.257 4.27 7.129 6.61 3.87-2.34 6.052-4.64 7.126-6.61 1.111-2.04 1.03-3.7.477-4.82-.561-1.13-1.666-1.84-2.908-1.91zm4.187 7.69c-1.351 2.48-4.001 5.12-8.379 7.67l-.503.3-.504-.3c-4.379-2.55-7.029-5.19-8.382-7.67-1.36-2.5-1.41-4.86-.514-6.67.887-1.79 2.647-2.91 4.601-3.01 1.651-.09 3.368.56 4.798 2.01 1.429-1.45 3.146-2.1 4.796-2.01 1.954.1 3.714 1.22 4.601 3.01.896 1.81.846 4.17-.514 6.67z"></path></g></svg>
|
|
<span class="engagement-count">${engagement.likes}</span>
|
|
</div>
|
|
<div class="engagement-item">
|
|
<svg viewBox="0 0 24 24" class="engagement-icon"><g><path d="M8.75 21V3h2v18h-2zM18 21V8.5h2V21h-2zM4 21l.004-10h2L6 21H4zm9.248 0v-7h2v7h-2z"></path></g></svg>
|
|
<span class="engagement-count">${engagement.views}</span>
|
|
</div>
|
|
</div>
|
|
`;
|
|
}
|
|
|
|
async function generateQuoteBuffer(config) {
|
|
const avatarHtml = config.avatarUrl
|
|
? `<img src="${config.avatarUrl}" style="width:100%;height:100%;object-fit:cover;" />`
|
|
: `<div style="width:100%;height:100%;background:rgb(51,54,57);"></div>`;
|
|
|
|
const imageHtml = config.imageUrl
|
|
? `<div class="tweet-image-container" style="margin-bottom:12px;border-radius:16px;overflow:hidden;border:1px solid rgb(47,51,54);"><img src="${config.imageUrl}" style="width:100%;display:block;" /></div>`
|
|
: '';
|
|
|
|
const engagementHtml = buildEngagementHtml(config.engagement);
|
|
|
|
const verifiedBadge = config.verified ? '<svg viewBox="0 0 22 22" class="verified-badge"><g><path d="M20.396 11c-.018-.646-.215-1.275-.57-1.816-.354-.54-.852-.972-1.438-1.246.223-.607.27-1.264.14-1.897-.131-.634-.437-1.218-.882-1.687-.47-.445-1.053-.75-1.687-.882-.633-.13-1.29-.083-1.897.14-.273-.587-.704-1.086-1.245-1.44S11.647 1.62 11 1.604c-.646.017-1.273.213-1.813.568s-.969.854-1.24 1.44c-.608-.223-1.267-.272-1.902-.14-.635.13-1.22.436-1.69.882-.445.47-.749 1.055-.878 1.688-.13.633-.08 1.29.144 1.896-.587.274-1.087.705-1.443 1.245-.356.54-.555 1.17-.574 1.817.02.647.218 1.276.574 1.817.356.54.856.972 1.443 1.245-.224.606-.274 1.263-.144 1.896.13.634.433 1.218.877 1.688.47.443 1.054.747 1.687.878.633.132 1.29.084 1.897-.136.274.586.705 1.084 1.246 1.439.54.354 1.17.551 1.816.569.647-.016 1.276-.213 1.817-.567s.972-.854 1.245-1.44c.604.239 1.266.296 1.903.164.636-.132 1.22-.447 1.68-.907.46-.46.776-1.044.908-1.681s.075-1.299-.165-1.903c.586-.274 1.084-.705 1.439-1.246.354-.54.551-1.17.569-1.816zM9.662 14.85l-3.429-3.428 1.293-1.302 2.072 2.072 4.4-4.794 1.347 1.246z"></path></g></svg>' : '';
|
|
|
|
const html = templateHtml
|
|
.replace('{{avatarHtml}}', avatarHtml)
|
|
.replace('{{displayName}}', config.displayName)
|
|
.replace('{{verifiedBadge}}', verifiedBadge)
|
|
.replace('{{username}}', config.username)
|
|
.replace('{{text}}', config.text)
|
|
.replace('{{imageHtml}}', imageHtml)
|
|
.replace('{{timestamp}}', config.timestamp)
|
|
.replace('{{engagementHtml}}', engagementHtml);
|
|
|
|
return await renderHtml(html, 1000);
|
|
}
|
|
|
|
// GET endpoint - use query parameters
|
|
app.get('/generate', async (req, res) => {
|
|
try {
|
|
const timestamp = req.query.timestamp ? formatTimestamp(parseInt(req.query.timestamp)) : formatTimestamp(Date.now() / 1000);
|
|
|
|
const config = {
|
|
displayName: req.query.displayName || "Anonymous",
|
|
username: req.query.username || "@anonymous",
|
|
avatarUrl: fixDataUri(req.query.avatarUrl) || null,
|
|
text: req.query.text || "No text provided",
|
|
imageUrl: fixDataUri(req.query.imageUrl) || null,
|
|
timestamp: timestamp,
|
|
engagement: null,
|
|
verified: req.query.verified === 'true' || req.query.verified === '1'
|
|
};
|
|
|
|
// Check cache first
|
|
let image = getCachedImage(config);
|
|
let fromCache = true;
|
|
|
|
if (!image) {
|
|
// Generate new image
|
|
image = await generateQuoteBuffer(config);
|
|
cacheImage(config, image);
|
|
fromCache = false;
|
|
}
|
|
|
|
res.setHeader('Content-Type', 'image/png');
|
|
res.setHeader('X-Cache', fromCache ? 'HIT' : 'MISS');
|
|
res.send(image);
|
|
} catch (error) {
|
|
console.error(error);
|
|
res.status(500).json({ error: 'Failed to generate image' });
|
|
}
|
|
});
|
|
|
|
// POST endpoint - use request body
|
|
function detectImageType(base64String) {
|
|
// Extract base64 data
|
|
const base64Data = base64String.includes(',') ? base64String.split(',')[1] : base64String;
|
|
const buffer = Buffer.from(base64Data, 'base64');
|
|
|
|
// Check magic numbers
|
|
if (buffer[0] === 0xFF && buffer[1] === 0xD8 && buffer[2] === 0xFF) {
|
|
return 'image/jpeg';
|
|
} else if (buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4E && buffer[3] === 0x47) {
|
|
return 'image/png';
|
|
} else if (buffer[0] === 0x47 && buffer[1] === 0x49 && buffer[2] === 0x46) {
|
|
return 'image/gif';
|
|
} else if (buffer[0] === 0x52 && buffer[1] === 0x49 && buffer[2] === 0x46 && buffer[3] === 0x46) {
|
|
return 'image/webp';
|
|
}
|
|
return 'image/png'; // default fallback
|
|
}
|
|
|
|
function fixDataUri(dataUri) {
|
|
if (!dataUri || !dataUri.startsWith('data:')) return dataUri;
|
|
|
|
// Extract the base64 part
|
|
const parts = dataUri.split(',');
|
|
if (parts.length !== 2) return dataUri;
|
|
|
|
const base64Data = parts[1];
|
|
|
|
try {
|
|
const correctType = detectImageType(base64Data);
|
|
return `data:${correctType};base64,${base64Data}`;
|
|
} catch (error) {
|
|
console.error('Invalid base64 data:', error.message);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
app.post('/generate', async (req, res) => {
|
|
try {
|
|
const timestamp = req.body.timestamp ? formatTimestamp(parseInt(req.body.timestamp)) : formatTimestamp(Date.now() / 1000);
|
|
|
|
const username = req.body.username?.trim();
|
|
|
|
// Only include engagement if all fields are provded
|
|
let engagement = null;
|
|
if (req.body.engagement &&
|
|
req.body.engagement.likes !== undefined &&
|
|
req.body.engagement.retweets !== undefined &&
|
|
req.body.engagement.replies !== undefined &&
|
|
req.body.engagement.views !== undefined) {
|
|
engagement = {
|
|
likes: formatCount(req.body.engagement.likes),
|
|
retweets: formatCount(req.body.engagement.retweets),
|
|
replies: formatCount(req.body.engagement.replies),
|
|
views: formatCount(req.body.engagement.views)
|
|
};
|
|
}
|
|
|
|
const config = {
|
|
displayName: req.body.displayName || "Anonymous",
|
|
username: (username && username !== "@") ? username : "@anonymous",
|
|
avatarUrl: fixDataUri(req.body.avatarUrl) || null,
|
|
text: req.body.text || "No text provided",
|
|
imageUrl: fixDataUri(req.body.imageUrl) || null,
|
|
timestamp: timestamp,
|
|
engagement: engagement,
|
|
verified: req.body.verified === true || req.body.verified === 'true' || req.body.verified === '1'
|
|
};
|
|
|
|
// Check cache first
|
|
let image = getCachedImage(config);
|
|
let fromCache = true;
|
|
|
|
if (!image) {
|
|
// Generate new image
|
|
image = await generateQuoteBuffer(config);
|
|
cacheImage(config, image);
|
|
fromCache = false;
|
|
}
|
|
|
|
res.setHeader('Content-Type', 'image/png');
|
|
res.setHeader('X-Cache', fromCache ? 'HIT' : 'MISS');
|
|
res.send(image);
|
|
} catch (error) {
|
|
console.error(error);
|
|
res.status(500).json({ error: 'Failed to generate image' });
|
|
}
|
|
});
|
|
|
|
// Health check endpoint
|
|
app.get('/health', (req, res) => {
|
|
res.status(200).json({ status: 'ok' });
|
|
});
|
|
|
|
// Clear all cache on startup
|
|
clearCache();
|
|
cleanupExpiredSessions();
|
|
|
|
// Run cleanup every hour
|
|
setInterval(() => {
|
|
cleanupOldCache();
|
|
cleanupExpiredSessions();
|
|
}, 60 * 60 * 1000);
|
|
|
|
// Initialize browser pool then start server
|
|
initPool().then(() => {
|
|
app.listen(PORT, () => {
|
|
console.log(`Quote generator API running on http://localhost:${PORT}`);
|
|
console.log(`Browser pool size: ${POOL_SIZE} (set BROWSER_POOL_SIZE env var to change)`);
|
|
console.log(`GET: http://localhost:${PORT}/generate?text=Hello&displayName=Test&username=@test×tamp=1735574400`);
|
|
console.log(`POST: http://localhost:${PORT}/generate`);
|
|
console.log(`v2 API: POST/GET/PATCH/DELETE http://localhost:${PORT}/v2/quote`);
|
|
console.log(`Cache cleared on startup, cleanup runs every hour`);
|
|
});
|
|
}).catch(err => {
|
|
console.error('Failed to initialize browser pool:', err);
|
|
process.exit(1);
|
|
});
|