File size: 5,639 Bytes
36d488d
 
 
 
 
 
 
 
 
 
 
 
 
 
3672121
 
 
 
 
 
 
 
 
36d488d
 
3672121
 
 
36d488d
 
 
 
 
 
 
 
 
 
ede1a98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36d488d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91ff24f
36d488d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ede1a98
 
36d488d
 
 
 
2cb7484
36d488d
 
 
2cb7484
 
 
 
 
 
36d488d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
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 };