const path = require('path'); global.crypto = require('crypto'); require('dotenv').config({ path: path.join(__dirname, '..', '.env') }); const gemini = require('./gemini-service'); const shortsPipeline = require('./shorts-pipeline'); const fs = require('fs').promises; const db = require('./db'); /** * Multi-User Autonomous Agent (Supabase Edition) */ async function runDailyAutomation(userId = null) { const log = async (msg, uId) => { console.log(`[USER ${uId}] ${msg}`); try { await db.from('activity').insert([{ user_id: uId, type: 'LOG', message: msg }]); } catch (e) { console.error("Failed to save log to DB:", e.message); } }; // 1. Initial Heartbeat if (userId) await log("๐Ÿ“ก System Check: AI Production Engine Initialized. Looking for active channels...", userId); // Get channels from Supabase let query = db.from('channels').select('*').eq('is_active', true); if (userId) query = query.eq('user_id', userId); const { data: channels, error } = await query; if (error || !channels) return; for (const channel of channels) { const currentUserId = channel.user_id; // ๐Ÿ›ก๏ธ SECURITY: 1. Fetch User Data (Keys & Plan) const { data: userData } = await db.from('users') .select('custom_client_id, custom_client_secret, plan, role') .eq('id', currentUserId) .single(); if (!userData?.custom_client_id || !userData?.custom_client_secret) { await log(`โŒ Production Paused: Please provide your own Google API keys in Advanced Settings to continue.`, currentUserId); continue; } // ADMIN GOD-MODE & ULTRA: Define Limits const userPlan = (userData.role === 'admin' || userData.plan === 'ultra') ? 'ultra' : userData.plan; const limit = userPlan === 'ultra' ? 9999 : (userPlan === 'premium' ? 5 : 1); const { count: videosToday } = await db.from('activity') .select('*', { count: 'exact', head: true }) .eq('user_id', currentUserId) .eq('type', 'VIDEO_PUBLISHED') .gte('created_at', new Date().toISOString().split('T')[0]); if (videosToday >= limit) { console.log(`[Limit] User ${currentUserId} reached ${limit} videos. Skipping.`); await log(`Limit reached (${limit}/day). Come back tomorrow! ๐Ÿ›‘`, currentUserId); continue; } // ๐Ÿ›ก๏ธ SECURITY: 2. Production Lock (Prevent Simultaneous Cheat) if (channel.is_processing) { console.log(`[Busy] User ${currentUserId} already has a video in production. Skipping.`); continue; } // ACTIVATE LOCK await db.from('channels').update({ is_processing: true }).eq('id', channel.id); try { // Handle multiple niches (comma separated) const nicheList = (channel.niche || 'interesting facts').split(',').map(n => n.trim()); const selectedNiche = nicheList[Math.floor(Math.random() * nicheList.length)]; await log(`๐ŸŽฌ Starting production [Niche: ${selectedNiche}]: ${channel.channel_name}`, currentUserId); // 1. Viral Topic with Groq const groq = require('./groq-service'); const ideas = await groq.generateContentIdeas(selectedNiche, 1); const bestIdea = ideas[0]; // 2. Production Pipeline const result = await shortsPipeline.generateShort(bestIdea.topic, { niche: selectedNiche, durationSec: 45 }); // 3. Cloud Upload await log('โ˜๏ธ Uploading to YouTube...', currentUserId); const { uploadToYouTube } = require('./youtube-uploader'); const uploadResult = await uploadToYouTube(result.paths.video, { title: result.title, description: result.metadata.description, hashtags: result.metadata.hashtags, token: channel.token, custom_client_id: userData.custom_client_id, custom_client_secret: userData.custom_client_secret }); await log(`โœ… Success! Published to YouTube: ${uploadResult.id}`, currentUserId); // Record publication with metadata for the dashboard await db.from('activity').insert([{ user_id: currentUserId, type: 'VIDEO_PUBLISHED', message: result.title, metadata: { videoId: uploadResult.id, url: `https://youtube.com/shorts/${uploadResult.id}`, thumbnail: result.thumbnail || '' } }]); // 4. Cleanup to save storage (ONLY IF UPLOAD WAS SUCCESSFUL) if (uploadResult && uploadResult.id) { try { await log('๐Ÿงน Cleaning up temporary files...', currentUserId); const filesToClear = [ result.paths?.video, result.paths?.audio, result.paths?.captions, result.paths?.script, ...(result.paths?.clips || []) ].filter(Boolean); for (const f of filesToClear) { try { await fs.unlink(f); } catch (e) { // Ignore if file doesn't exist } } await log('โœจ Storage cleaned successfully.', currentUserId); } catch (cleanError) { console.error('Cleanup Error:', cleanError); } } // Update last run time in Cloud await db.from('channels').update({ last_run: new Date().toISOString() }).eq('id', channel.id); } catch (e) { await log(`โŒ Error: ${e.message}`, currentUserId); } finally { // ALWAYS UNLOCK await db.from('channels').update({ is_processing: false }).eq('user_id', currentUserId); } } } if (require.main === module) { runDailyAutomation(); } module.exports = { runDailyAutomation };