Spaces:
Sleeping
Sleeping
Nathan commited on
Commit ·
e8f6f7b
1
Parent(s): aed3df4
Fix: YouTube Connection Sync & Duplicate Channel Prevention
Browse files290 unmodified lines29129229329429529629729827 unmodified lines32632732832933033133233333433533633733833934034114 unmodified lines35635735835936036136236336436536636736836937037137282 unmodified lines455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496290 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();// 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 linesapp.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);if (!channels || channels.length === 0) return res.json({ connected: false, channels: [] });// Fetch keys from Users tableconst { 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);for (const chan of channels) {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);}}res.json({connected: results.length > 0,channels: results,count: results.length});} catch (error) {res.json({ connected: false, channels: [] });}});82 unmodified linesreturn res.send('<h1>🚫 Channel Banned</h1><p>This YouTube channel has been permanently blacklisted from ViralFlow AI.</p>');}// 2. Multi-Channel Logicconst { 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 isPaid = user?.plan === 'premium' || user?.plan === 'ultra' || user?.role === 'admin';const limit = isPaid ? 2 : 1;// 3. Check if user already has this specific channelconst { data: hasThisChannel } = await db.from('channels').select('channel_id').eq('user_id', userId).eq('channel_id', channel.id).single();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>`);}// 4. Check if this channel is already connected to another userconst { data: existing } = await db.from('channels').select('user_id').eq('channel_id', channel.id).neq('user_id', userId).limit(1);if (existing && existing.length > 0) {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 neededconst { data: userData } = await db.from('users').select('custom_client_id, custom_client_secret').eq('id', userId).single();await db.from('channels').upsert({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' });}res.send('<h1>✅ YouTube Connected!</h1><p>Close this and refresh your dashboard.</p>');} catch (e) {290 unmodified lines29129229329429529629729829930030130227 unmodified lines33033133233333433533633733833934034134234334434534634734834935035135235335414 unmodified lines36937037137237337437537637737837938038138238338438538638738838939039139239382 unmodified lines476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528290 unmodified lines// --- Dashboard API ---app.get('/api/stats', authenticateToken, async (req, res) => {// 1. Fetch channel data (niche, stats) - Prioritize active channelsconst { 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 linesapp.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: [] });// Fetch keys from Users tableconst { 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(`❌ [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.some(r => r.connected),channels: results,count: results.length});} catch (error) {console.error("🔥 [API/YouTube] Critical Error:", error.message);res.json({ connected: false, channels: [], error: error.message });}});82 unmodified linesreturn res.send('<h1>🚫 Channel Banned</h1><p>This YouTube channel has been permanently blacklisted from ViralFlow AI.</p>');}// 4. Multi-Channel Logicconst { 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 isPaid = user?.plan === 'premium' || user?.plan === 'ultra' || user?.role === 'admin';const limit = isPaid ? 2 : 1;// 5. Check if this specific channel is already connected to this userconst 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(`<h1>❌ Limit Reached</h1><p>Your ${user?.plan} plan allows only ${limit} channel(s). Upgrade to add more.</p>`);}}// 6. Check if this channel is already connected to another userconst { data: otherUserChannel } = await db.from('channels').select('user_id').eq('channel_id', channel.id).neq('user_id', userId).maybeSingle();if (otherUserChannel) {return res.send('<h1>❌ Connection Denied</h1><p>This YouTube channel is already linked to another account.</p>');}// 7. UPSERT: Update placeholder or add new channel// If we found a placeholder, use its ID for the upsert to replace itconst 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};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