- Created dedicated nodejs-redirector/ folder for Node.js application - Moved all Node.js files to nodejs-redirector/ directory - Kept CRM PHP code in crm/ folder for clear separation - Updated README_MONEYFLIX.md with new organized structure - Updated sync-from-crm.sh script to work with new structure - Improved project organization for better maintainability This provides clear separation between: - Node.js redirector application (nodejs-redirector/) - CRM PHP code reference (crm/) - Project documentation and scripts (root level)
345 lines
11 KiB
JavaScript
345 lines
11 KiB
JavaScript
import express from 'express';
|
|
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;
|
|
|
|
// ============================================================================
|
|
// CONFIGURAÇÃO E MIDDLEWARE
|
|
// ============================================================================
|
|
|
|
app.use(express.json());
|
|
app.use(express.urlencoded({ extended: 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 lastCacheUpdate = 0;
|
|
const CACHE_TTL = 30000; // 30 segundos
|
|
|
|
async function getRedirects() {
|
|
const now = Date.now();
|
|
|
|
if (now - lastCacheUpdate > CACHE_TTL || Object.keys(redirectsCache).length === 0) {
|
|
try {
|
|
redirectsCache = await fetchRedirects();
|
|
lastCacheUpdate = now;
|
|
console.log(`🔄 Redirects cache updated: ${Object.keys(redirectsCache).length} redirects`);
|
|
} catch (error) {
|
|
console.error('❌ Error fetching redirects:', error.message);
|
|
}
|
|
}
|
|
|
|
return redirectsCache;
|
|
}
|
|
|
|
// ============================================================================
|
|
// FUNÇÃO DE REDIRECIONAMENTO
|
|
// ============================================================================
|
|
|
|
async function processRedirect(req, res) {
|
|
const startTime = Date.now();
|
|
const { slug } = req.params;
|
|
|
|
try {
|
|
// Buscar redirects atualizados
|
|
const redirects = await 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)
|
|
logHit({
|
|
campaign_id: redirect.id,
|
|
ip_address: req.ip || req.connection.remoteAddress || '0.0.0.0',
|
|
user_agent: req.get('User-Agent') || null,
|
|
referer: req.get('Referer') || null,
|
|
destination_url: redirect.url,
|
|
response_time: Date.now() - startTime,
|
|
redirect_type: redirect.type,
|
|
country_code: req.get('CF-IPCountry') || null,
|
|
country_name: null, // Será preenchido pelo processor
|
|
city: req.get('CF-IPCITY') || null,
|
|
region_code: req.get('CF-IPREGION') || null,
|
|
region_name: null, // Será preenchido pelo processor
|
|
timezone: req.get('CF-IPTIMEZONE') || null,
|
|
asn: req.get('CF-IPASN') || null,
|
|
isp: req.get('CF-IPISP') || null,
|
|
language: req.get('Accept-Language') || 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, () => {
|
|
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'}`);
|
|
|
|
// Initial redirects fetch
|
|
getRedirects().then(() => {
|
|
console.log('✅ Initial redirects loaded');
|
|
}).catch(error => {
|
|
console.error('❌ Failed to load initial redirects:', error.message);
|
|
});
|
|
});
|
|
|
|
// 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);
|
|
}); |