const express = require('express'); const path = require('path'); const fs = require('fs').promises; const { google } = require('googleapis'); const jwt = require('jsonwebtoken'); const bcrypt = require('bcryptjs'); const db = require('./utils/db'); require('dotenv').config(); global.crypto = require('crypto'); const rateLimit = require('express-rate-limit'); const app = express(); app.set('trust proxy', 1); // Fix for Hugging Face/Proxy Rate Limiting // Global Rate Limiter (DISABLED for troubleshooting) /* const limiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 100, message: { error: 'Too many requests, please try again later.' } }); app.use(limiter); */ const PORT = process.env.PORT || 7860; const JWT_SECRET = process.env.JWT_SECRET || 'youtube-automation-super-secret-2026'; app.use(express.json()); app.use(express.static(path.join(__dirname, 'dashboard'))); app.use('/video', express.static(path.join(__dirname, 'video'), { setHeaders: (res, path) => { if (path.endsWith('.mp4')) res.set('Content-Type', 'video/mp4'); } })); // JWT Middleware // Admin Authentication Middleware const authenticateAdmin = (req, res, next) => { authenticateToken(req, res, async () => { try { const { data: user, error } = await db.from('users').select('email, role').eq('id', req.userId).single(); console.log(`๐ Security Check: User ${user?.email} is [${user?.role || 'user'}]`); if (user && user.role === 'admin') { console.log("โ Admin Access Authorized"); next(); } else { console.warn(`โ Unauthorized Admin Attempt: ${user?.email}`); res.status(403).json({ error: 'Access Denied: Admin Role Required' }); } } catch (e) { console.error("๐ฅ Auth System Error:", e); res.status(500).json({ error: 'Security Engine Error' }); } }); }; const authenticateToken = (req, res, next) => { const authHeader = req.headers['authorization']; const token = authHeader && authHeader.split(' ')[1]; if (!token) return res.status(401).json({ error: 'Please login' }); jwt.verify(token, JWT_SECRET, (err, user) => { if (err) return res.status(403).json({ error: 'Session expired' }); req.userId = user.id; next(); }); }; // --- OAuth2 Configuration --- async function getOAuth2Client(customClientId = null, customClientSecret = null) { try { if (!customClientId || !customClientSecret) { return null; } const client_id = customClientId; const client_secret = customClientSecret; const redirectUri = (process.env.SPACE_ID || process.env.NODE_ENV === 'production') ? 'https://yogesh7705-youtube-auto-bot.hf.space/api/auth/callback' : 'http://localhost:7860/api/auth/callback'; return new google.auth.OAuth2(client_id, client_secret, redirectUri); } catch (e) { console.error('โ OAuth Client Error:', e.message); return null; } } // --- Auth API --- app.get('/api/config', (req, res) => { res.json({ supabaseUrl: process.env.SUPABASE_URL, supabaseKey: process.env.SUPABASE_ANON_KEY }); }); app.post('/api/auth/signup', async (req, res) => { const { email, password } = req.body; console.log(`๐ [Signup Start] Attempting for: ${email}`); try { // 1. Check Global Capacity const { count: totalUsers } = await db.from('users').select('*', { count: 'exact', head: true }); console.log(`๐ [Signup] Current users: ${totalUsers}/100`); if (totalUsers >= 100) return res.status(403).json({ error: 'Platform at 100-user capacity.' }); // 2. Hash Password const hashedPassword = await bcrypt.hash(password, 10); console.log(`๐ [Signup] Password hashed.`); // 3. Create User const { data: users, error: userError } = await db.from('users').insert([ { email, password: hashedPassword, role: 'user', plan: 'free' } ]).select(); if (userError) { console.error("โ [Signup] DB Error:", userError.message); return res.status(400).json({ error: userError.message }); } const newUser = users[0]; console.log(`โ [Signup] User created with ID: ${newUser.id}`); // 4. Initialize Channel (Non-blocking) try { await db.from('channels').insert([{ user_id: newUser.id, is_active: false, niche: 'Facts', preferred_hours: ['10:00'] }]); console.log(`๐บ [Signup] Channel row initialized.`); } catch (chanErr) { console.warn("โ ๏ธ [Signup] Channel init skipped:", chanErr.message); } const token = jwt.sign({ id: newUser.id }, JWT_SECRET, { expiresIn: '30d' }); res.json({ success: true, token }); } catch (e) { console.error("๐ฅ [Signup] Critical Crash:", e.message); res.status(500).json({ error: 'Internal Security Engine Error' }); } }); app.post('/api/auth/login', async (req, res) => { const emailInput = (req.body.email || "").trim(); const password = req.body.password; console.log(`๐ [Login Start] Attempting for: ${emailInput}`); try { const { data: user, error } = await db.from('users').select('*').ilike('email', emailInput).single(); if (error) { console.error(`โ [Login DB Error] ${error.message} for ${emailInput}`); return res.status(401).json({ error: `Database Error: ${error.message}` }); } if (!user) { console.warn(`โ [Login Failed] User not found: ${emailInput}`); return res.status(401).json({ error: 'User account not found' }); } const isMatch = await bcrypt.compare(password, user.password); console.log(`๐ [Login Debug] Password match for ${emailInput}: ${isMatch}`); if (isMatch) { console.log(`โ [Login Success] ${emailInput}`); const token = jwt.sign({ id: user.id }, JWT_SECRET, { expiresIn: '30d' }); res.json({ success: true, token }); } else { console.warn(`โ [Login Failed] Invalid credentials for: ${emailInput}`); res.status(401).json({ error: 'Invalid email or password' }); } } catch (e) { console.error("๐ฅ [Login Crash]:", e.message); res.status(500).json({ error: 'Authentication engine error' }); } }); app.post('/api/test-db', authenticateToken, async (req, res) => { try { const { error } = await db.from('activity').insert([{ user_id: req.userId, type: 'LOG', message: '๐งช Database Connection Test Successful!' }]); if (error) throw error; res.json({ success: true }); } catch (e) { res.status(500).json({ error: e.message }); } }); app.get('/api/auth/me', authenticateToken, async (req, res) => { try { let { data: user } = await db.from('users').select('email, role, plan, plan_expires_at').eq('id', req.userId).single(); // ๐ก๏ธ SUBSCRIPTION GUARD: Check for Expiry if (user?.plan === 'premium' && user.plan_expires_at) { if (new Date(user.plan_expires_at) < new Date()) { console.log(`๐ Plan Expired for ${user.email}. Reverting to free.`); await db.from('users').update({ plan: 'free' }).eq('id', req.userId); user.plan = 'free'; } } // MIRROR DB: Return plan exactly as stored in Database let finalPlan = user?.plan || 'free'; res.json({ loggedIn: true, email: user?.email, role: user?.role, plan: finalPlan, expires_at: user?.plan_expires_at }); } catch (e) { res.json({ loggedIn: false }); } }); // --- Platform Pricing --- app.get('/api/platform/pricing', async (req, res) => { const { data } = await db.from('platform_settings').select('value').eq('key', 'pricing').single(); res.json(data?.value || {}); }); app.post('/api/admin/pricing', authenticateAdmin, async (req, res) => { try { const { pricing } = req.body; if (!pricing) return res.status(400).json({ error: "Missing pricing data" }); console.log("๐พ [Admin] Attempting to Save Pricing:", JSON.stringify(pricing)); // Use upsert to update the 'pricing' row specifically const { error } = await db.from('platform_settings') .upsert({ key: 'pricing', value: pricing }, { onConflict: 'key' }); if (error) { console.error("๐ฅ [DB Error] Pricing Save Failed:", error.message, error.details); return res.status(500).json({ error: error.message }); } console.log("โ [Admin] Pricing Engine Synced Successfully."); res.json({ success: true }); } catch (e) { console.error("๐ฅ [API Crash] Pricing Save Engine:", e.message); res.status(500).json({ error: e.message }); } }); // --- Razorpay Payments --- const Razorpay = require('razorpay'); let rzp; if (process.env.RAZORPAY_KEY_ID) { rzp = new Razorpay({ key_id: process.env.RAZORPAY_KEY_ID, key_secret: process.env.RAZORPAY_KEY_SECRET }); console.log("๐ณ Razorpay Revenue Engine: ONLINE"); } else { console.warn("โ ๏ธ Razorpay Keys missing. Payments are currently disabled."); } app.post('/api/payments/create-order', authenticateToken, async (req, res) => { const { plan } = req.body; // 1. Fetch Dynamic Pricing from Settings const { data: settings } = await db.from('platform_settings').select('value').eq('key', 'pricing').single(); const p = settings?.value || { pro_monthly: 299, pro_yearly: 2999, discount_active: false }; // 2. Determine Base Price let amount = plan === 'pro_yearly' ? p.pro_yearly : p.pro_monthly; // 3. Apply Discount based on specific plan toggle const isMonthlySale = plan === 'pro_monthly' && p.m_discount_active; const isYearlySale = plan === 'pro_yearly' && p.y_discount_active; if ((isMonthlySale || isYearlySale) && p.discount_percent > 0) { amount = Math.round(amount * (1 - p.discount_percent / 100)); } const options = { amount: amount * 100, // Razorpay uses paise currency: "INR", receipt: `receipt_${Date.now()}` }; try { const order = await rzp.orders.create(options); res.json(order); } catch (e) { console.error("Razorpay Error:", e); res.status(500).send(e.message); } }); app.post('/api/payments/verify', authenticateToken, async (req, res) => { try { const { razorpay_order_id, razorpay_payment_id, plan_type } = req.body; // 1. Get current expiry const { data: user } = await db.from('users').select('plan_expires_at').eq('id', req.userId).single(); // 2. Calculate New Expiry (Stackable) const days = plan_type === 'pro_yearly' ? 365 : 30; let baseDate = new Date(); // If user already has an active plan, add to it! if (user?.plan_expires_at && new Date(user.plan_expires_at) > new Date()) { baseDate = new Date(user.plan_expires_at); } baseDate.setDate(baseDate.getDate() + days); await db.from('users').update({ plan: 'premium', plan_expires_at: baseDate.toISOString() }).eq('id', req.userId); res.json({ success: true }); } catch (e) { res.status(500).json({ error: 'Verification failed' }); } }); // --- Admin Control API --- app.get('/api/admin/users', authenticateAdmin, async (req, res) => { try { const { data: users, error } = await db.from('users').select('id, email, plan, role, created_at').order('created_at', { ascending: false }); if (error) throw error; res.json(users); } catch (e) { res.status(500).json({ error: e.message }); } }); app.post('/api/admin/update-plan', authenticateAdmin, async (req, res) => { const { userId, plan } = req.body; try { const { error } = await db.from('users').update({ plan }).eq('id', userId); if (error) throw error; res.json({ success: true, msg: `User updated to ${plan}` }); } catch (e) { res.status(500).json({ error: e.message }); } }); // --- Dashboard API --- app.get('/api/stats', authenticateToken, async (req, res) => { try { // 1. Fetch channel data (niche, stats) - Prioritize active channels const { data: channel } = await db.from('channels') .select('niche, preferred_hours, total_views, subscribers') .eq('user_id', req.userId) .order('is_active', { ascending: false }) .limit(1).maybeSingle(); // 2. Fetch user data (custom keys) const { data: user } = await db.from('users').select('custom_client_id, custom_client_secret').eq('id', req.userId).single(); const { count: videosProduced } = await db.from('activity').select('*', { count: 'exact', head: true }).eq('user_id', req.userId).eq('type', 'VIDEO_PUBLISHED'); res.json({ videosProduced: videosProduced || 0, totalViews: channel?.total_views || 0, subscribers: channel?.subscribers || 0, niche: channel ? channel.niche : 'Not set', preferred_hours: channel ? channel.preferred_hours : ['10:00'], custom_client_id: user?.custom_client_id || '', custom_client_secret: user?.custom_client_secret || '' }); } catch (e) { res.status(500).json({ error: e.message }); } }); app.get('/api/youtube/status', authenticateToken, async (req, res) => { const { data } = await db.from('channels').select('token').eq('user_id', req.userId).single(); res.json({ connected: !!data?.token }); }); app.get('/api/youtube', authenticateToken, async (req, res) => { try { const { data: channels, error: chanError } = await db.from('channels').select('token, channel_id, channel_name, total_views, subscribers').eq('user_id', req.userId); if (chanError) throw chanError; if (!channels || channels.length === 0) { return res.json({ connected: false, channels: [] }); } const { data: user } = await db.from('users').select('custom_client_id, custom_client_secret').eq('id', req.userId).single(); const results = []; const oauth2Client = await getOAuth2Client(user?.custom_client_id, user?.custom_client_secret); if (!oauth2Client) { return res.json({ connected: false, channels: channels.map(c => ({ ...c, connected: false })) }); } for (const chan of channels) { if (!chan.token || !chan.channel_id) { results.push({ ...chan, connected: false }); continue; } try { oauth2Client.setCredentials(chan.token); const youtube = google.youtube({ version: 'v3', auth: oauth2Client }); const response = await youtube.channels.list({ part: 'statistics', id: chan.channel_id }); if (response.data.items && response.data.items.length > 0) { const stats = response.data.items[0].statistics; results.push({ connected: true, channel_id: chan.channel_id, channel_name: chan.channel_name, subscribers: parseInt(stats.subscriberCount), totalViews: parseInt(stats.viewCount) }); } else { results.push({ ...chan, connected: false }); } } catch (e) { results.push({ ...chan, connected: false }); } } res.json({ connected: results.some(r => r.connected), channels: results }); } catch (error) { res.status(500).json({ error: error.message }); } }); app.post('/api/settings', authenticateToken, async (req, res) => { const { niche, preferred_hours, custom_client_id, custom_client_secret } = req.body; try { // 1. Update YouTube Credentials in USERS table const { error: userError } = await db.from('users').update({ custom_client_id, custom_client_secret }).eq('id', req.userId); if (userError) throw userError; // 2. Update Production Settings in ALL CHANNELS for this user const { error: chanError } = await db.from('channels').update({ niche, preferred_hours }).eq('user_id', req.userId); if (chanError) throw chanError; res.json({ success: true }); } catch (e) { console.error('โ Settings Save Error:', e); res.status(500).json({ error: 'Failed to save settings' }); } }); app.post('/api/youtube/disconnect', authenticateToken, async (req, res) => { try { await db.from('channels').update({ token: null, is_active: false, channel_id: null, channel_name: null }).eq('user_id', req.userId); res.json({ success: true }); } catch (e) { res.status(500).json({ error: 'Failed to disconnect' }); } }); app.get('/api/auth/url', authenticateToken, async (req, res) => { // Fetch keys from Users table const { data: user } = await db.from('users').select('custom_client_id, custom_client_secret').eq('id', req.userId).single(); const oauth2Client = await getOAuth2Client(user?.custom_client_id, user?.custom_client_secret); if (!oauth2Client) return res.status(500).json({ error: 'OAuth Client not configured' }); const state = Buffer.from(JSON.stringify({ userId: req.userId, custom_client_id: user?.custom_client_id, custom_client_secret: user?.custom_client_secret })).toString('base64'); const authUrl = oauth2Client.generateAuthUrl({ access_type: 'offline', scope: ['https://www.googleapis.com/auth/youtube.readonly', 'https://www.googleapis.com/auth/youtube.upload'], prompt: 'consent', state: state }); res.json({ url: authUrl }); }); app.get('/api/auth/callback', async (req, res) => { const { code, state } = req.query; const decoded = JSON.parse(Buffer.from(state, 'base64').toString()); const userId = decoded.userId; const oauth2Client = await getOAuth2Client(decoded.custom_client_id, decoded.custom_client_secret); if (!oauth2Client) return res.status(500).send('OAuth Client Configuration Error'); try { const { tokens } = await oauth2Client.getToken(code); oauth2Client.setCredentials(tokens); const youtube = google.youtube({ version: 'v3', auth: oauth2Client }); const chanRes = await youtube.channels.list({ part: 'snippet', mine: true }); if (chanRes.data.items && chanRes.data.items.length > 0) { const channel = chanRes.data.items[0]; // 1. Check if Channel is BLACKLISTED const { data: isBanned } = await db.from('blacklist').select('channel_id').eq('channel_id', channel.id).single(); if (isBanned) { return res.send('
This YouTube channel has been permanently blacklisted from ViralFlow AI.
'); } // 4. Multi-Channel Logic const { data: user } = await db.from('users').select('plan, role').eq('id', userId).single(); const { data: existingChannels, count: currentChannels } = await db.from('channels').select('*', { count: 'exact' }).eq('user_id', userId); const isAdmin = user?.role === 'admin' || user?.plan === 'ultra'; const isPremium = user?.plan === 'premium'; const limit = isAdmin ? 999 : (isPremium ? 2 : 1); // 5. Check if this specific channel is already connected to this user const hasThisChannel = existingChannels?.find(c => c.channel_id === channel.id); if (!hasThisChannel && (currentChannels || 0) >= limit) { // SPECIAL CASE: If they have a "placeholder" channel (no channel_id), we can replace it! const placeholder = existingChannels?.find(c => !c.channel_id); if (!placeholder) { return res.send(`Your ${user?.plan} plan allows only ${limit} channel(s). Upgrade to add more.
`); } } // 6. Check if this channel is already connected to another user const { data: otherUserChannel } = await db.from('channels') .select('user_id') .eq('channel_id', channel.id) .neq('user_id', userId) .maybeSingle(); if (otherUserChannel) { return res.send('This YouTube channel is already linked to another account.
'); } // 7. FINAL LINKING LOGIC (Universal) const existingChannel = existingChannels?.find(c => c.channel_id === channel.id); const placeholder = existingChannels?.find(c => !c.channel_id); const channelData = { user_id: userId, channel_id: channel.id, channel_name: channel.snippet.title, token: tokens, is_active: true, is_locked: true }; if (existingChannel) { // Case A: Update existing connection console.log(`โป๏ธ Updating existing channel: ${channel.id}`); const { error } = await db.from('channels').update(channelData).eq('id', existingChannel.id); if (error) throw error; } else if (placeholder) { // Case B: Fill the first empty slot console.log(`๐ฅ Filling placeholder slot: ${placeholder.id}`); const { error } = await db.from('channels').update(channelData).eq('id', placeholder.id); if (error) throw error; } else { // Case C: Create a brand new slot (for 2nd, 3rd channels etc) console.log(`โ Creating new channel slot for: ${channel.id}`); const { error } = await db.from('channels').insert([channelData]); if (error) throw error; } } res.send('Close this and refresh your dashboard.
'); } catch (e) { res.status(500).send('Auth Error: ' + e.message); } }); app.post('/api/generate', authenticateToken, async (req, res) => { try { const { data: channels } = await db.from('channels').select('*').eq('user_id', req.userId).eq('is_active', true); if (channels && channels.some(c => c.is_processing)) { return res.status(400).json({ error: 'Production already in progress. Please wait or Reset Lock.' }); } const { runDailyAutomation } = require('./utils/autonomous-agent'); runDailyAutomation(req.userId).catch(console.error); res.json({ message: 'Started!' }); } catch (e) { res.status(500).json({ error: 'Production Engine Error' }); } }); app.post('/api/generate/reset', authenticateToken, async (req, res) => { try { await db.from('channels').update({ is_processing: false }).eq('user_id', req.userId); await db.from('activity').insert([{ user_id: req.userId, type: 'LOG', message: 'โป๏ธ User manually reset production lock.' }]); res.json({ message: 'Lock Cleared! You can now start a new production.' }); } catch (e) { res.status(500).json({ error: 'Reset Failed' }); } }); app.get('/api/admin/global-stats', authenticateAdmin, async (req, res) => { try { const { count: totalUsers } = await db.from('users').select('*', { count: 'exact', head: true }); const { count: activeChannels } = await db.from('channels').select('*', { count: 'exact', head: true }).eq('is_active', true); const { count: totalVideos } = await db.from('activity').select('*', { count: 'exact', head: true }).eq('type', 'VIDEO_PUBLISHED'); res.json({ totalUsers, activeChannels, totalVideos }); } catch (e) { res.status(500).json({ error: 'Failed to fetch global stats' }); } }); app.post('/api/admin/remove-channel', authenticateAdmin, async (req, res) => { const { targetUserId, action } = req.body; // action: 'release' or 'ban' try { const { data: channel } = await db.from('channels').select('channel_id').eq('user_id', targetUserId).single(); if (action === 'ban' && channel?.channel_id) { await db.from('blacklist').insert([{ channel_id: channel.channel_id, reason: 'Admin Ban' }]); } await db.from('channels').delete().eq('user_id', targetUserId); res.json({ success: true }); } catch (e) { res.status(500).json({ error: 'Failed to execute admin action' }); } }); app.post('/api/admin/action', authenticateAdmin, async (req, res) => { try { const { userId, type } = req.body; console.log(`๐ก๏ธ [Admin] Attempting Action ${type} on User ${userId}`); let updateData = {}; if (type === 'ultra') { updateData = { plan: 'ultra', plan_expires_at: '2099-12-31T23:59:59Z' }; } else if (type === 'ban') { updateData = { role: 'banned' }; } else if (type === 'release') { updateData = { role: 'user' }; } const { error } = await db.from('users').update(updateData).eq('id', userId); if (error) { console.error(`๐ฅ [Admin Action Fail] ${type}:`, error.message, error.details); return res.status(500).json({ error: error.message }); } console.log(`โ [Admin Action Success] ${type} applied to ${userId}`); res.json({ success: true }); } catch (e) { console.error("๐ฅ [API Crash] Admin Action Engine:", e.message); res.status(500).json({ error: e.message }); } }); app.get('/api/admin/users', authenticateAdmin, async (req, res) => { const { data: users, error } = await db.from('users') .select(` id, email, plan, role, channels ( channel_name, channel_id, niche, is_active ) `); if (error) return res.status(500).json({ error: error.message }); res.json(users); }); app.get('/api/logs', authenticateToken, async (req, res) => { let { data: logs, error } = await db.from('activity') .select('created_at, message, type, metadata') .eq('user_id', req.userId) .order('created_at', { ascending: false }) .limit(20); // FALLBACK: If 'metadata' column is missing, try without it if (error && error.message.includes('metadata')) { console.warn("โ ๏ธ [API/Logs] Metadata column missing, falling back..."); const retry = await db.from('activity') .select('created_at, message, type') .eq('user_id', req.userId) .order('created_at', { ascending: false }) .limit(20); logs = retry.data; error = retry.error; } if (error) { return res.status(500).json({ error: error.message }); } res.json((logs || []).map(l => ({ time: l.created_at, msg: l.message, type: l.type, metadata: l.metadata || null }))); }); app.listen(PORT, '0.0.0.0', () => { console.log(`๐ Permanent Memory Server running on port ${PORT}`); }); // --- BACKGROUND SCHEDULER (Every 1 Minute) --- setInterval(async () => { try { const now = new Date(); // Get IST Time (matches dashboard clock) const istTime = now.toLocaleTimeString('en-GB', { timeZone: 'Asia/Kolkata', hour: '2-digit', minute: '2-digit' }); // 1. Fetch all active channels const { data: channels } = await db.from('channels').select('user_id, preferred_hours, last_run').eq('is_active', true); for (const channel of channels) { if (channel.preferred_hours && channel.preferred_hours.includes(istTime)) { // 2. Prevent double-triggering within the same minute/hour const lastRun = channel.last_run ? new Date(channel.last_run) : new Date(0); const diffMinutes = (now - lastRun) / (1000 * 60); if (diffMinutes > 10) { // Only run if it hasn't run in the last 10 mins console.log(`โฐ [Scheduler] Triggering Production for User ${channel.user_id} at ${istTime} IST`); const { runDailyAutomation } = require('./utils/autonomous-agent'); runDailyAutomation(channel.user_id).catch(err => console.error(`๐ฅ [Scheduler Error] User ${channel.user_id}:`, err)); } } } } catch (err) { console.error("๐ฅ [Scheduler Critical Failure]:", err.message); } }, 60000);