Spaces:
Sleeping
Sleeping
Nathan commited on
Commit ·
e8f6f7b
1
Parent(s): aed3df4
Fix: YouTube Connection Sync & Duplicate Channel Prevention
Browse files290 unmodified lines29129229329429529429529629729829930030130227 unmodified lines33033133232933333433533633733333833934034134234334434534634734834935035135235335414 unmodified lines36937037135937237337437537637737837938038138238336438438538638738838936939039139239382 unmodified lines476477478458479480460481482483484485465466486487488468469489490491492493494495496472473497498499500501477502503479504505506507483484485486508509510511512513514515516517492493518519520521522523524525526527528290 unmodified lines// --- Dashboard API ---
app.get('/api/stats', authenticateToken, async (req, res) => { // 1. Fetch channel data (niche, stats) const { data: channel } = await db.from('channels').select('niche, preferred_hours, total_views, subscribers').eq('user_id', req.userId).limit(1).maybeSingle(); // 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();27 unmodified lines
app.get('/api/youtube', authenticateToken, async (req, res) => { try { const { data: channels } = await db.from('channels').select('token, channel_id, channel_name, total_views, subscribers').eq('user_id', req.userId); 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: [] });
// 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 { data: user, error: userError } = await db.from('users').select('custom_client_id, custom_client_secret').eq('id', req.userId).single(); if (userError) throw userError;
const results = []; const oauth2Client = await getOAuth2Client(user?.custom_client_id, user?.custom_client_secret); if (!oauth2Client) { console.warn(`⚠️ [API/YouTube] No OAuth2 client for user ${req.userId} - check custom keys.`); return res.json({ connected: false, channels: [], error: 'API keys not configured' }); }
for (const chan of channels) { if (!chan.token || !chan.channel_id) continue;
try { oauth2Client.setCredentials(chan.token); const youtube = google.youtube({ version: 'v3', auth: oauth2Client });14 unmodified lines }); } } catch (e) { console.error(`Error fetching stats for ${chan.channel_id}:`, e.message); console.error(`❌ [API/YouTube] Stats fetch failed for channel ${chan.channel_id}:`, e.message); // If it's a token error, we might still want to show the channel as "connected but broken" results.push({ connected: false, channel_id: chan.channel_id, channel_name: chan.channel_name, error: 'Token expired or invalid' }); } }
res.json({ connected: results.length > 0, connected: results.some(r => r.connected), channels: results, count: results.length }); } catch (error) { console.error("🔥 [API/YouTube] Critical Error:", error.message); res.json({ connected: false, channels: [] }); res.json({ connected: false, channels: [], error: error.message }); }});
82 unmodified lines return res.send('<h1>🚫 Channel Banned</h1><p>This YouTube channel has been permanently blacklisted from ViralFlow AI.</p>'); }
// 2. Multi-Channel Logic // 4. Multi-Channel Logic const { data: user } = await db.from('users').select('plan, role').eq('id', userId).single(); const { count: currentChannels } = await db.from('channels').select('*', { count: 'exact', head: true }).eq('user_id', userId); const { data: existingChannels, count: currentChannels } = await db.from('channels').select('*', { count: 'exact' }).eq('user_id', userId); const isPaid = user?.plan === 'premium' || user?.plan === 'ultra' || user?.role === 'admin'; const limit = isPaid ? 2 : 1;
// 3. Check if user already has this specific channel const { data: hasThisChannel } = await db.from('channels').select('channel_id').eq('user_id', userId).eq('channel_id', channel.id).single(); // 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 >= limit) { return res.send(`<h1>❌ Limit Reached</h1><p>Your ${user?.plan} plan allows only ${limit} channel(s). Upgrade to add more.</p>`); 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(`<h1>❌ Limit Reached</h1><p>Your ${user?.plan} plan allows only ${limit} channel(s). Upgrade to add more.</p>`); } }
// 4. Check if this channel is already connected to another user const { data: existing } = await db.from('channels') // 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) .limit(1); .maybeSingle();
if (existing && existing.length > 0) { if (otherUserChannel) { return res.send('<h1>❌ Connection Denied</h1><p>This YouTube channel is already linked to another account.</p>'); }
// 5. Get existing keys from USERS table to preserve them in state-callback if needed const { data: userData } = await db.from('users').select('custom_client_id, custom_client_secret').eq('id', userId).single();
await db.from('channels').upsert({ // 7. UPSERT: Update placeholder or add new channel // If we found a placeholder, use its ID for the upsert to replace it const placeholder = existingChannels?.find(c => !c.channel_id); const upsertData = { user_id: userId, channel_id: channel.id, channel_name: channel.snippet.title, token: tokens, is_active: true, is_locked: true // Lock the connection once successful }, { onConflict: 'channel_id' }); is_locked: true };
if (placeholder) { upsertData.id = placeholder.id; // Use the internal Supabase UUID of the placeholder }
await db.from('channels').upsert(upsertData, { onConflict: 'channel_id' }); } res.send('<h1>✅ YouTube Connected!</h1><p>Close this and refresh your dashboard.</p>'); } catch (e) {server.js+55-23