- Add source maps and license files for compiled assets - Add debug and test files for development - Complete Git repository with all necessary files for MoneyFlix project
473 lines
16 KiB
JavaScript
473 lines
16 KiB
JavaScript
import express from 'express';
|
|
import crypto from 'crypto';
|
|
import dotenv from 'dotenv';
|
|
import { fetchRedirects } from './helpers/helpers.mjs';
|
|
import { logHit } from './db/logUser.mjs';
|
|
|
|
// Load environment variables
|
|
dotenv.config();
|
|
|
|
const app = express();
|
|
const PORT = process.env.PORT || 3000;
|
|
|
|
// ============================================================================
|
|
// FUNÇÕES AUXILIARES
|
|
// ============================================================================
|
|
|
|
/**
|
|
* Grava exatamente o que o CloudFlare envia - sem traduções
|
|
* As traduções podem ser feitas posteriormente na base de dados se necessário
|
|
*/
|
|
|
|
// ============================================================================
|
|
// CONFIGURAÇÃO E MIDDLEWARE
|
|
// ============================================================================
|
|
|
|
app.use(express.json());
|
|
app.use(express.urlencoded({ extended: true }));
|
|
|
|
// Configurar para confiar em proxies (CloudFlare + Nginx)
|
|
app.set('trust proxy', true);
|
|
|
|
// CORS headers
|
|
app.use((req, res, next) => {
|
|
res.header('Access-Control-Allow-Origin', '*');
|
|
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
|
|
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
|
|
|
|
if (req.method === 'OPTIONS') {
|
|
res.sendStatus(200);
|
|
} else {
|
|
next();
|
|
}
|
|
});
|
|
|
|
// ============================================================================
|
|
// CACHE DE REDIRECTS
|
|
// ============================================================================
|
|
|
|
let redirectsCache = {};
|
|
let lastCacheHash = '';
|
|
const CACHE_REFRESH_INTERVAL = 60000; // 60 segundos (1 minuto)
|
|
const INITIAL_RETRY_ATTEMPTS = 3;
|
|
const INITIAL_RETRY_DELAY = 5000; // 5 segundos
|
|
|
|
/**
|
|
* Gera hash MD5 do conteúdo completo dos redirects
|
|
* Qualquer mudança em qualquer redirect é detectada
|
|
*/
|
|
function generateCacheHash(redirects) {
|
|
const content = JSON.stringify(redirects, Object.keys(redirects).sort());
|
|
return crypto.createHash('md5').update(content).digest('hex');
|
|
}
|
|
|
|
/**
|
|
* Atualiza o cache de redirects em background
|
|
* Não bloqueia pedidos - sempre retorna o cache atual
|
|
* Só atualiza se houver mudanças reais
|
|
*/
|
|
async function refreshRedirectsCache(isInitial = false) {
|
|
try {
|
|
if (isInitial) {
|
|
console.log('🔄 Initial: Loading redirects...');
|
|
} else {
|
|
console.log('🔄 Background: Checking for updates...');
|
|
}
|
|
|
|
const newRedirects = await fetchRedirects();
|
|
|
|
// Proteção: Nunca aceitar cache vazio (exceto no primeiro load)
|
|
if (Object.keys(newRedirects).length === 0) {
|
|
if (isInitial) {
|
|
throw new Error('Initial load returned empty redirects');
|
|
}
|
|
console.warn('⚠️ Background: No redirects received, keeping old cache');
|
|
return false;
|
|
}
|
|
|
|
// Verificar se houve mudanças reais
|
|
const newHash = generateCacheHash(newRedirects);
|
|
if (newHash === lastCacheHash) {
|
|
console.log('✅ Background: No changes detected, cache unchanged');
|
|
return false;
|
|
}
|
|
|
|
// Atualizar cache e hash
|
|
const oldCount = Object.keys(redirectsCache).length;
|
|
redirectsCache = newRedirects;
|
|
lastCacheHash = newHash;
|
|
const newCount = Object.keys(redirectsCache).length;
|
|
|
|
if (isInitial) {
|
|
console.log(`✅ Initial: Loaded ${newCount} redirects`);
|
|
} else {
|
|
console.log(`✅ Background: Cache updated (${oldCount} → ${newCount} redirects)`);
|
|
}
|
|
|
|
return true;
|
|
} catch (error) {
|
|
console.error(`❌ ${isInitial ? 'Initial' : 'Background'}: Error refreshing cache:`, error.message);
|
|
|
|
// Se for o load inicial, isso é crítico
|
|
if (isInitial) {
|
|
throw error;
|
|
}
|
|
|
|
// Mantém o cache antigo em caso de erro no background
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Retorna os redirects do cache (sempre instantâneo)
|
|
*/
|
|
function getRedirects() {
|
|
return redirectsCache;
|
|
}
|
|
|
|
// ============================================================================
|
|
// FUNÇÃO DE REDIRECIONAMENTO
|
|
// ============================================================================
|
|
|
|
async function processRedirect(req, res) {
|
|
const startTime = Date.now();
|
|
const { slug } = req.params;
|
|
|
|
try {
|
|
// Buscar redirect do cache (instantâneo)
|
|
const redirects = getRedirects();
|
|
const redirect = redirects[slug];
|
|
|
|
if (!redirect) {
|
|
console.log(`❌ Redirect not found: ${slug}`);
|
|
return res.status(404).json({
|
|
error: 'Redirect not found',
|
|
slug: slug
|
|
});
|
|
}
|
|
|
|
if (!redirect.active) {
|
|
console.log(`❌ Redirect inactive: ${slug}`);
|
|
return res.status(410).json({
|
|
error: 'Redirect inactive',
|
|
slug: slug
|
|
});
|
|
}
|
|
|
|
// Log hit para analytics (não bloqueia o redirect)
|
|
// Capturar IP real do cliente (CloudFlare -> Nginx -> Node.js)
|
|
const clientIP = req.get('CF-Connecting-IP') ||
|
|
req.get('X-Forwarded-For')?.split(',')[0]?.trim() ||
|
|
req.get('X-Real-IP') ||
|
|
req.connection.remoteAddress ||
|
|
'0.0.0.0';
|
|
|
|
// Capturar todos os dados do CloudFlare
|
|
const cloudflareData = {
|
|
// IP e localização
|
|
ip_address: clientIP,
|
|
country_code: req.get('CF-IPCountry') || null,
|
|
country_name: req.get('CF-IPCountry') || null, // Gravar código do país como está
|
|
city: req.get('CF-IPCITY') || null,
|
|
region_code: req.get('CF-IPREGION') || null,
|
|
region_name: req.get('CF-IPREGION') || null, // Gravar código da região como está
|
|
timezone: req.get('CF-IPTIMEZONE') || null,
|
|
|
|
// Dados de rede
|
|
asn: req.get('CF-IPASN') || null,
|
|
isp: req.get('CF-IPISP') || null,
|
|
|
|
// Headers de segurança CloudFlare
|
|
cf_ray: req.get('CF-Ray') || null,
|
|
cf_visitor: req.get('CF-Visitor') || null,
|
|
cf_cache_status: req.get('CF-Cache-Status') || null,
|
|
|
|
// Dados do cliente
|
|
user_agent: req.get('User-Agent') || null,
|
|
referer: req.get('Referer') || null,
|
|
language: req.get('Accept-Language') || null,
|
|
|
|
// Dados do redirect
|
|
destination_url: redirect.url,
|
|
response_time: Date.now() - startTime,
|
|
redirect_type: redirect.type
|
|
};
|
|
|
|
logHit({
|
|
campaign_id: redirect.id,
|
|
timestamp: new Date(), // Adicionar timestamp original do hit
|
|
...cloudflareData,
|
|
raw_request: {
|
|
headers: req.headers,
|
|
query: req.query,
|
|
url: req.originalUrl,
|
|
method: req.method,
|
|
protocol: req.protocol,
|
|
httpVersion: req.httpVersion,
|
|
cookies: req.headers?.cookie || null
|
|
}
|
|
}).catch(error => {
|
|
console.error('❌ Error logging hit:', error.message);
|
|
});
|
|
|
|
// Redirecionar baseado no tipo
|
|
console.log(`✅ Redirecting ${slug} to ${redirect.url} (type: ${redirect.type})`);
|
|
|
|
switch (redirect.type) {
|
|
case '301':
|
|
res.redirect(301, redirect.url);
|
|
break;
|
|
|
|
case '302':
|
|
res.redirect(302, redirect.url);
|
|
break;
|
|
|
|
case 'meta':
|
|
// Meta Refresh redirect
|
|
res.set('Content-Type', 'text/html');
|
|
res.send(`
|
|
<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<meta http-equiv="refresh" content="0;url=${redirect.url}">
|
|
<title>Redirecting...</title>
|
|
</head>
|
|
<body>
|
|
<p>Redirecting to <a href="${redirect.url}">${redirect.url}</a>...</p>
|
|
<script>window.location.href = "${redirect.url}";</script>
|
|
</body>
|
|
</html>
|
|
`);
|
|
break;
|
|
|
|
case 'javascript':
|
|
// JavaScript redirect
|
|
res.set('Content-Type', 'text/html');
|
|
res.send(`
|
|
<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<title>Redirecting...</title>
|
|
</head>
|
|
<body>
|
|
<p>Redirecting...</p>
|
|
<script>
|
|
window.location.href = "${redirect.url}";
|
|
</script>
|
|
</body>
|
|
</html>
|
|
`);
|
|
break;
|
|
|
|
default:
|
|
// Default to 302
|
|
res.redirect(302, redirect.url);
|
|
}
|
|
|
|
} catch (error) {
|
|
console.error('❌ Error processing redirect:', error.message);
|
|
res.status(500).json({
|
|
error: 'Internal server error',
|
|
message: 'Failed to process redirect'
|
|
});
|
|
}
|
|
}
|
|
|
|
// ============================================================================
|
|
// ROTAS
|
|
// ============================================================================
|
|
|
|
// Root endpoint - 404
|
|
app.get('/', (req, res) => {
|
|
res.status(404).json({
|
|
error: 'Not found',
|
|
message: 'Use /r/{slug} for redirects'
|
|
});
|
|
});
|
|
|
|
// Health check endpoint
|
|
app.get('/health', (req, res) => {
|
|
res.json({
|
|
status: 'healthy',
|
|
timestamp: new Date().toISOString(),
|
|
uptime: process.uptime(),
|
|
memory: process.memoryUsage(),
|
|
redirects: Object.keys(redirectsCache).length
|
|
});
|
|
});
|
|
|
|
// Status endpoint with queue info
|
|
app.get('/status', async (req, res) => {
|
|
try {
|
|
const { getQueueStats, getDatabaseStats } = await import('./db/logUser.mjs');
|
|
|
|
const queueStats = getQueueStats();
|
|
const dbStats = await getDatabaseStats();
|
|
|
|
res.json({
|
|
status: 'running',
|
|
timestamp: new Date().toISOString(),
|
|
uptime: process.uptime(),
|
|
memory: process.memoryUsage(),
|
|
redirects: {
|
|
cached: Object.keys(redirectsCache).length,
|
|
lastUpdate: new Date(lastCacheUpdate).toISOString()
|
|
},
|
|
queue: queueStats,
|
|
database: dbStats
|
|
});
|
|
} catch (error) {
|
|
res.status(500).json({
|
|
error: 'Failed to get status',
|
|
message: error.message
|
|
});
|
|
}
|
|
});
|
|
|
|
// Stats endpoint for debugging
|
|
app.get('/stats', async (req, res) => {
|
|
try {
|
|
const { getDatabaseStats, getQueueStats } = await import('./db/logUser.mjs');
|
|
const dbStats = await getDatabaseStats();
|
|
const queueStats = getQueueStats();
|
|
|
|
res.json({
|
|
status: 'ok',
|
|
timestamp: new Date().toISOString(),
|
|
redirects_loaded: Object.keys(redirectsCache).length,
|
|
redirects_list: Object.keys(redirectsCache).slice(0, 10), // First 10 redirects
|
|
queue: queueStats,
|
|
database_stats: dbStats,
|
|
environment: {
|
|
node_env: process.env.NODE_ENV,
|
|
db_host: process.env.DB_HOST,
|
|
db_database: process.env.DB_DATABASE,
|
|
crm_api_url: process.env.CRM_API_URL
|
|
}
|
|
});
|
|
} catch (error) {
|
|
res.status(500).json({
|
|
status: 'error',
|
|
error: error.message,
|
|
timestamp: new Date().toISOString()
|
|
});
|
|
}
|
|
});
|
|
|
|
// Test database connection
|
|
app.get('/test-db', async (req, res) => {
|
|
try {
|
|
const { getPool } = await import('./db/logUser.mjs');
|
|
const pool = await getPool();
|
|
const connection = await pool.getConnection();
|
|
|
|
const [rows] = await connection.execute('SELECT 1 as test');
|
|
connection.release();
|
|
|
|
res.json({
|
|
status: 'ok',
|
|
message: 'Database connection successful',
|
|
test_result: rows[0]
|
|
});
|
|
} catch (error) {
|
|
res.status(500).json({
|
|
status: 'error',
|
|
error: error.message,
|
|
stack: error.stack
|
|
});
|
|
}
|
|
});
|
|
|
|
// Force queue processing
|
|
app.get('/process-queue', async (req, res) => {
|
|
try {
|
|
const { processQueue } = await import('./db/logUser.mjs');
|
|
await processQueue();
|
|
|
|
res.json({
|
|
status: 'ok',
|
|
message: 'Queue processed successfully'
|
|
});
|
|
} catch (error) {
|
|
res.status(500).json({
|
|
status: 'error',
|
|
error: error.message,
|
|
stack: error.stack
|
|
});
|
|
}
|
|
});
|
|
|
|
// Main redirect endpoint (MUST be last)
|
|
app.get('/:slug', processRedirect);
|
|
|
|
// ============================================================================
|
|
// ERROR HANDLING
|
|
// ============================================================================
|
|
|
|
app.use((err, req, res, next) => {
|
|
console.error('❌ Unhandled error:', err);
|
|
res.status(500).json({
|
|
error: 'Internal server error',
|
|
message: 'Something went wrong'
|
|
});
|
|
});
|
|
|
|
// 404 handler
|
|
app.use((req, res) => {
|
|
res.status(404).json({
|
|
error: 'Not found',
|
|
message: 'Endpoint not found'
|
|
});
|
|
});
|
|
|
|
// ============================================================================
|
|
// SERVER STARTUP
|
|
// ============================================================================
|
|
|
|
app.listen(PORT, async () => {
|
|
console.log('🚀 MoneyFlix Redirector started');
|
|
console.log(`📡 Server running on port ${PORT}`);
|
|
console.log(`🌐 Environment: ${process.env.NODE_ENV || 'development'}`);
|
|
console.log(`📊 Redirects API: ${process.env.CRM_API_URL || 'https://redirect.moneyflix.com/api/redirects'}`);
|
|
console.log(`🗄️ Database: ${process.env.DB_DATABASE || 'bitreport_redirects'}`);
|
|
console.log(`⏰ Cache refresh interval: ${CACHE_REFRESH_INTERVAL / 1000}s`);
|
|
|
|
// Load initial redirects with retry logic
|
|
let loaded = false;
|
|
for (let attempt = 1; attempt <= INITIAL_RETRY_ATTEMPTS; attempt++) {
|
|
try {
|
|
loaded = await refreshRedirectsCache(true);
|
|
if (loaded) break;
|
|
} catch (error) {
|
|
if (attempt < INITIAL_RETRY_ATTEMPTS) {
|
|
console.log(`⚠️ Retry ${attempt}/${INITIAL_RETRY_ATTEMPTS} in ${INITIAL_RETRY_DELAY/1000}s...`);
|
|
await new Promise(resolve => setTimeout(resolve, INITIAL_RETRY_DELAY));
|
|
} else {
|
|
console.error('❌ Failed to load initial redirects after all retries');
|
|
console.error('⚠️ Starting with empty cache - redirects will not work until first successful refresh');
|
|
}
|
|
}
|
|
}
|
|
|
|
// Setup background refresh interval
|
|
setInterval(async () => {
|
|
await refreshRedirectsCache(false);
|
|
}, CACHE_REFRESH_INTERVAL);
|
|
|
|
if (loaded) {
|
|
console.log('✅ Redirector ready to handle requests');
|
|
} else {
|
|
console.log('⚠️ Redirector started but waiting for first successful cache load');
|
|
}
|
|
});
|
|
|
|
// Graceful shutdown
|
|
process.on('SIGTERM', () => {
|
|
console.log('🔄 SIGTERM received, shutting down gracefully...');
|
|
process.exit(0);
|
|
});
|
|
|
|
process.on('SIGINT', () => {
|
|
console.log('🔄 SIGINT received, shutting down gracefully...');
|
|
process.exit(0);
|
|
}); |