import React, { useState, useEffect, useRef } from 'react'; import { Api, TelegramClient } from 'telegram'; import { StringSession } from 'telegram/sessions'; import * as XLSX from 'xlsx'; import { Facebook, Twitter, Send, Instagram, Menu, X, Globe, Search, Database, FileText, Upload, Shield, Square, User, Users, Bell, ExternalLink } from 'lucide-react'; import InstagramSearch from './components/InstagramSearch'; import FacebookSearch from './components/FacebookSearch'; import XSearch from './components/XSearch'; import TikTokSearch from './components/TikTokSearch'; import { Music2 } from 'lucide-react'; import { getApiUrl } from './config'; // User must provide these in .env.local const apiId = Number(import.meta.env.VITE_TELEGRAM_API_ID) || 0; const apiHash = import.meta.env.VITE_TELEGRAM_API_HASH || ""; // Simple range expander in JS. Equivalent to Python's extend_search_patterns function expandRange(pattern) { const chars = []; const regex = /([a-z0-9])-([a-z0-9])/gi; let match; while ((match = regex.exec(pattern)) !== null) { const start = match[1].charCodeAt(0); const end = match[2].charCodeAt(0); for (let c = start; c <= end; c++) { chars.push(String.fromCharCode(c)); } } return chars; } function expandSearchPatterns(terms) { const expandedTerms = []; for (const term of terms) { const matches = [...term.matchAll(/\[([^\[\]]+)\]/g)]; if (matches.length === 0) { expandedTerms.push(term); continue; } const staticParts = []; const dynamicCharSets = []; let lastEnd = 0; for (const match of matches) { staticParts.push(term.slice(lastEnd, match.index)); const pattern = match[1]; const ranges = pattern.match(/[a-z0-9]-[a-z0-9]/gi); const singles = pattern.replace(/[a-z0-9]-[a-z0-9]/gi, ''); const charset = ranges ? expandRange(pattern) : []; charset.push(...singles.split('')); dynamicCharSets.push(charset); lastEnd = match.index + match[0].length; } staticParts.push(term.slice(lastEnd)); // Cartesian product const cartesianProduct = (arr) => arr.reduce((a, b) => a.flatMap(d => b.map(e => [d, e].flat())) ); // We handle the edge case where dynamicCharSets only has 1 array differently const combos = dynamicCharSets.length === 1 ? dynamicCharSets[0].map(x => [x]) : cartesianProduct(dynamicCharSets); for (const combo of combos) { let newTerm = ''; for (let i = 0; i < staticParts.length; i++) { newTerm += staticParts[i] + (combo[i] !== undefined ? combo[i] : ''); } expandedTerms.push(newTerm); } } return expandedTerms; } export default function App() { const [client, setClient] = useState(null); const [sessionString, setSessionString] = useState(''); const [step, setStep] = useState('phone'); // phone, code, dashboard const [activeTab, setActiveTab] = useState(() => localStorage.getItem('lastActiveTab') || 'telegram'); const isRemote = !!import.meta.env.VITE_API_URL; const [platformsAuth, setPlatformsAuth] = useState({ telegram: { status: false, detail: 'OFFLINE', updated: null }, facebook: { status: false, detail: 'MISSING', updated: null }, x: { status: false, detail: 'MISSING', updated: null }, instagram: { status: false, detail: 'MISSING', updated: null }, tiktok: { status: true, detail: 'PUBLIC_ACCESS', updated: 'LIVE' } }); const [expansion, setExpansion] = useState('none'); const [localSearchTerm, setLocalSearchTerm] = useState(''); // Auth state const [phone, setPhone] = useState(''); const [phoneCodeHash, setPhoneCodeHash] = useState(''); const [code, setCode] = useState(''); const [loading, setLoading] = useState(false); const [error, setError] = useState(''); // Search state - Telegram const [tgSearchTerm, setTgSearchTerm] = useState(''); const [tgResults, setTgResults] = useState([]); const [isTgSearching, setIsTgSearching] = useState(false); const [tgSearchMode, setTgSearchMode] = useState('none'); const [tgProgress, setTgProgress] = useState(null); const [tgError, setTgError] = useState(''); // Search state - Instagram const [igSearchTerm, setIgSearchTerm] = useState(''); const [igResults, setIgResults] = useState([]); const [isIgSearching, setIsIgSearching] = useState(false); const [igProgress, setIgProgress] = useState(null); const [igError, setIgError] = useState(''); const [igSearchMode, setIgSearchMode] = useState('none'); // Search state - Facebook const [fbSearchTerm, setFbSearchTerm] = useState(''); const [fbResults, setFbResults] = useState([]); const [isFbSearching, setIsFbSearching] = useState(false); const [fbError, setFbError] = useState(''); const [fbSearchTypes, setFbSearchTypes] = useState(['pages']); const [fbSearchMode, setFbSearchMode] = useState('none'); const [fbProgress, setFbProgress] = useState(null); const fbAbortControllerRef = useRef(null); const [xSearchTerm, setXSearchTerm] = useState(''); const [xResults, setXResults] = useState([]); const [isXSearching, setIsXSearching] = useState(false); const [xError, setXError] = useState(''); const xAbortControllerRef = useRef(null); const [xProgress, setXProgress] = useState(null); // Search state - TikTok const [ttSearchTerm, setTtSearchTerm] = useState(''); const [ttResults, setTtResults] = useState([]); const [isTtSearching, setIsTtSearching] = useState(false); const [ttError, setTtError] = useState(''); const [ttProgress, setTtProgress] = useState(null); const ttAbortControllerRef = useRef(null); const [isFirstAuthCheckDone, setIsFirstAuthCheckDone] = useState(false); const checkAllAuth = async () => { try { const resp = await fetch(getApiUrl('/api/auth/status')); if (resp.ok) { const data = await resp.json(); const hasTg = !!localStorage.getItem('telegramSession'); setPlatformsAuth(prev => ({ ...prev, ...data, telegram: { status: hasTg, detail: hasTg ? 'SESSION_ID_FOUND' : 'OFFLINE', updated: hasTg ? 'LIVE' : null } })); } } catch (e) { console.error('[AUTH] Status check failed:', e); } finally { setIsFirstAuthCheckDone(true); } }; useEffect(() => { localStorage.setItem('lastActiveTab', activeTab); }, [activeTab]); useEffect(() => { checkAllAuth(); const interval = setInterval(checkAllAuth, 10000); // Poll every 10s return () => clearInterval(interval); }, []); useEffect(() => { if (activeTab === 'telegram') setLocalSearchTerm(tgSearchTerm); else if (activeTab === 'instagram') setLocalSearchTerm(igSearchTerm); else if (activeTab === 'facebook') setLocalSearchTerm(fbSearchTerm); else if (activeTab === 'tiktok') setLocalSearchTerm(ttSearchTerm); else setLocalSearchTerm(xSearchTerm); }, [activeTab, tgSearchTerm, igSearchTerm, fbSearchTerm, ttSearchTerm, xSearchTerm]); const stopFacebookSearch = () => { if (fbAbortControllerRef.current) { fbAbortControllerRef.current.abort(); fbAbortControllerRef.current = null; } }; const stopXSearch = () => { if (xAbortControllerRef.current) { xAbortControllerRef.current.abort(); xAbortControllerRef.current = null; } }; const stopTikTokSearch = () => { if (ttAbortControllerRef.current) { ttAbortControllerRef.current.abort(); ttAbortControllerRef.current = null; } }; // Auth state - Facebook const [showFbAuth, setShowFbAuth] = useState(false); const [fbAuthInput, setFbAuthInput] = useState(localStorage.getItem('fb_auth_input') || ''); const [isFbAuthenticating, setIsFbAuthenticating] = useState(false); const [fbAuthError, setFbAuthError] = useState(''); const [fbAuthSuccess, setFbAuthSuccess] = useState(false); // Auth state - Instagram const [igAuthInput, setIgAuthInput] = useState(localStorage.getItem('ig_auth_input') || ''); useEffect(() => { localStorage.setItem('ig_auth_input', igAuthInput); }, [igAuthInput]); const [igUsername, setIgUsername] = useState(localStorage.getItem('ig_username') || 'adarshs1780'); const [igPassword, setIgPassword] = useState(localStorage.getItem('ig_password') || '@J6Ku8HFTM3y,Af'); const [isIgAuthenticating, setIsIgAuthenticating] = useState(false); const [igAuthError, setIgAuthError] = useState(''); const [showIgAuth, setShowIgAuth] = useState(false); const [igAuthSuccess, setIgAuthSuccess] = useState(false); // Auth state - X (Twitter) const [showXAuth, setShowXAuth] = useState(false); const [xAuthInput, setXAuthInput] = useState(localStorage.getItem('x_auth_input') || ''); const [isXAuthenticating, setIsXAuthenticating] = useState(false); const [xAuthError, setXAuthError] = useState(''); const [xAuthSuccess, setXAuthSuccess] = useState(false); // Sidebar state const [sidebarOpen, setSidebarOpen] = useState(false); useEffect(() => { // Auto load session from localStorage const savedSession = localStorage.getItem('telegramSession'); if (apiId && apiHash) { if (savedSession) { setSessionString(savedSession); initClient(savedSession); } else { const initialSession = new StringSession(""); const tc = new TelegramClient(initialSession, apiId, apiHash, { connectionRetries: 5 }); setClient(tc); } } else { console.warn("[TELEGRAM] Skipping initialization: API ID or Hash missing."); } }, []); useEffect(() => { localStorage.setItem('ig_username', igUsername); localStorage.setItem('ig_password', igPassword); localStorage.setItem('ig_auth_input', igAuthInput); localStorage.setItem('fb_auth_input', fbAuthInput); localStorage.setItem('x_auth_input', xAuthInput); }, [igUsername, igPassword, igAuthInput, fbAuthInput, xAuthInput]); const initClient = async (savedSession) => { try { setLoading(true); const stringSession = new StringSession(savedSession); const tc = new TelegramClient(stringSession, apiId, apiHash, { connectionRetries: 5, }); await tc.connect(); // Verify login is still valid const isAuth = await tc.checkAuthorization(); if (isAuth) { setClient(tc); setStep('dashboard'); } else { localStorage.removeItem('telegramSession'); if (apiId && apiHash) { setClient(new TelegramClient(new StringSession(""), apiId, apiHash, { connectionRetries: 5 })); } setStep('phone'); } } catch (err) { console.error(err); setError("Failed to init Telegram Client"); } finally { setLoading(false); } }; const sendCode = async () => { if (!client || !apiId || !apiHash) { setError('Telegram API credentials missing. Please set them in environment variables.'); return; } try { setError(''); setLoading(true); await client.connect(); const result = await client.sendCode( { apiId: apiId, apiHash: apiHash, }, phone ); setPhoneCodeHash(result.phoneCodeHash); setStep('code'); } catch (err) { console.error(err); setError(err.message || 'Failed to send code.'); } finally { setLoading(false); } }; const verifyCode = async () => { try { setError(''); setLoading(true); await client.invoke( new Api.auth.SignIn({ phoneNumber: phone, phoneCodeHash: phoneCodeHash, phoneCode: code, }) ); const newSessionString = client.session.save(); localStorage.setItem('telegramSession', newSessionString); setSessionString(newSessionString); setStep('dashboard'); } catch (err) { console.error(err); setError(err.message || 'Verification failed. Password might be needed.'); } finally { setLoading(false); } }; const clearAuthSessions = async () => { if (!window.confirm("Are you sure you want to clear ALL stored session cookies (Instagram, Facebook, X)? This will log you out of these platforms locally and on the server.")) { return; } setLoading(true); try { const resp = await fetch(getApiUrl('/api/auth/clear'), { method: 'POST' }); if (!resp.ok) throw new Error('Failed to clear sessions'); // Clear local inputs as well localStorage.removeItem('fb_auth_input'); localStorage.removeItem('ig_auth_input'); localStorage.removeItem('x_auth_input'); setFbAuthInput(''); setIgAuthInput(''); setXAuthInput(''); // Refresh all auth statuses await checkAllAuth(); } catch (err) { setError(`Failed to clear sessions: ${err.message}`); } finally { setLoading(false); } }; const logout = async () => { localStorage.removeItem('telegramSession'); setSessionString(''); setStep('phone'); if (client) await client.disconnect(); setTgResults([]); // Setup fresh client if (apiId && apiHash) { setClient(new TelegramClient(new StringSession(""), apiId, apiHash, { connectionRetries: 5 })); } else { setClient(null); } }; const performSearch = async (term) => { try { const result = await client.invoke( new Api.contacts.Search({ q: term, limit: 50, }) ); const bufferToBase64 = (buffer) => { if (!buffer || buffer.length === 0) return null; let binary = ''; const bytes = new Uint8Array(buffer); const len = bytes.byteLength; for (let i = 0; i < len; i++) { binary += String.fromCharCode(bytes[i]); } return `data:image/jpeg;base64,${window.btoa(binary)}`; }; const newResults = []; for (const user of result.users) { if (user.username) { let image = null; try { const photoBuffer = await client.downloadProfilePhoto(user); image = bufferToBase64(photoBuffer); } catch (e) { console.warn(`Failed to download photo for ${user.username}`, e); } newResults.push({ search_term: term, type: 'user', name: `${user.firstName || ''} ${user.lastName || ''}`.trim(), username: user.username, url: `https://t.me/${user.username}`, image: image }); } } for (const chat of result.chats) { if (chat.username) { let image = null; try { const photoBuffer = await client.downloadProfilePhoto(chat); image = bufferToBase64(photoBuffer); } catch (e) { console.warn(`Failed to download photo for ${chat.username}`, e); } newResults.push({ search_term: term, type: chat.broadcast ? 'channel' : 'group', name: chat.title, username: chat.username, url: `https://t.me/${chat.username}`, image: image }); } } return newResults; } catch (err) { console.error(`Search failed for ${term}`, err); return []; } }; const startSearch = async () => { if (!tgSearchTerm) return; let termsToProcess = [tgSearchTerm]; if (!tgSearchTerm.match(/\[.*?\]/)) { if (tgSearchMode !== 'none') { termsToProcess = [`${tgSearchTerm}[${tgSearchMode}]`]; } } const expandedTerms = expandSearchPatterns(termsToProcess); const finalTerms = [...new Set([tgSearchTerm.replace(/\[.*?\]/, ''), ...expandedTerms])].filter(Boolean); setIsTgSearching(true); setTgResults([]); setTgError(''); const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); const BATCH_SIZE = 3; for (let i = 0; i < finalTerms.length; i += BATCH_SIZE) { const chunk = finalTerms.slice(i, i + BATCH_SIZE); setTgProgress(`Searching batch: ${chunk.join(', ')} (${Math.min(i + BATCH_SIZE, finalTerms.length)}/${finalTerms.length})`); const results = await Promise.all(chunk.map(term => performSearch(term))); // Merge and deduplicate setTgResults(prev => { const flat = [...prev, ...results.flat()]; return Array.from(new Map(flat.map(item => [item.url, item])).values()); }); if (i + BATCH_SIZE < finalTerms.length) { await sleep(5000); } } setIsTgSearching(false); setTgProgress('Search Complete!'); }; const exportExcel = () => { let dataToExport = []; let fileName = ''; if (activeTab === 'telegram') { if (tgResults.length === 0) return; dataToExport = tgResults; const baseTerm = tgSearchTerm.replace(/\[/g, '').replace(/\]/g, '') || 'results'; fileName = `telegram_search_${baseTerm}`; } else if (activeTab === 'instagram') { if (igResults.length === 0) return; dataToExport = igResults.map(r => ({ 'Full Name': r.user.full_name, 'Username': r.user.username, 'Profile URL': `https://www.instagram.com/${r.user.username}/`, 'Is Private': r.user.is_private ? 'Yes' : 'No', 'Is Verified': r.user.is_verified ? 'Yes' : 'No' })); fileName = `instagram_${igSearchTerm}`; } else if (activeTab === 'facebook') { if (fbResults.length === 0) return; dataToExport = fbResults.map(r => { const cleanUrl = r.url.replace('https://www.facebook.com/', '').replace('http://www.facebook.com/', '').split('?')[0].replace(/\/$/, ''); const fallbackUsername = cleanUrl.split('/').pop() || 'Facebook User'; return { 'Type': r.type.charAt(0).toUpperCase() + r.type.slice(1), 'Name': r.name || fallbackUsername, 'Profile URL': r.url, 'Search Term': r.term }; }); fileName = `facebook_${fbSearchTerm}`; } else if (activeTab === 'x') { if (xResults.length === 0) return; dataToExport = xResults.map(r => ({ 'Name': r.name, 'Username': r.username, 'Profile URL': r.url, 'Bio': r.bio, 'Followers': r.followers, 'Following': r.following, 'Tweets': r.tweets, 'Verified': r.verified ? 'Yes' : 'No', 'Location': r.location, 'Website': r.website, })); fileName = `x_search_${xSearchTerm}`; } else if (activeTab === 'tiktok') { if (ttResults.length === 0) return; dataToExport = ttResults.map(r => ({ 'Username': r.username, 'Nickname': r.nickname, 'Profile URL': r.url, })); fileName = `tiktok_search_${ttSearchTerm}`; } else { return; } const ws = XLSX.utils.json_to_sheet(dataToExport); const wb = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(wb, ws, "Results"); const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); XLSX.writeFile(wb, `${fileName}_${timestamp}.xlsx`); }; const performInstagramSearch = async () => { if (!igSearchTerm) return; let patterns = [igSearchTerm]; if (!igSearchTerm.match(/\[.*?\]/)) { if (igSearchMode !== 'none') { patterns = [`${igSearchTerm}[${igSearchMode}]`]; } } const expanded = expandSearchPatterns(patterns); const finalQueries = [...new Set([igSearchTerm.replace(/\[.*?\]/, ''), ...expanded])].filter(Boolean); setIsIgSearching(true); setIgResults([]); setIgError(''); const sleep = (ms) => new Promise(r => setTimeout(r, ms)); const BATCH_SIZE = 2; // Strict limit for IG const seen = new Set(); let combinedResults = []; try { for (let i = 0; i < finalQueries.length; i += BATCH_SIZE) { const chunk = finalQueries.slice(i, i + BATCH_SIZE); setIgProgress(`Searching IG batch: ${chunk.join(', ')} (${Math.min(i + BATCH_SIZE, finalQueries.length)}/${finalQueries.length})`); const responses = await Promise.all(chunk.map(query => fetch(getApiUrl('/api/instagram/search'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query }) }) )); for (const resp of responses) { if (resp.status === 401) { throw new Error("Instagram authentication failed. Please update cookies in Dashboard."); } if (!resp.ok) continue; const data = await resp.json(); if (data.users) { data.users.forEach(u => { if (!seen.has(u.user.username)) { seen.add(u.user.username); combinedResults.push(u); } }); } } setIgResults([...combinedResults]); if (i + BATCH_SIZE < finalQueries.length) { await sleep(5000); // Respect IG rate limits } } setIgProgress(null); } catch (err) { if (err.message.includes('Instagram authentication failed')) { setIgError("Authentication failed or missing cookies. Launching Instagram Login auto-configurator..."); setShowIgAuth(true); } else { setIgError(err.message); } setIgProgress(null); } finally { setIsIgSearching(false); } }; const launchFacebookAutoAuth = async () => { if (isRemote) return; setIsFbAuthenticating(true); setFbAuthError(''); setFbAuthSuccess(false); try { const resp = await fetch(getApiUrl('/api/facebook/auth-launch'), { method: 'POST' }); const data = await resp.json(); if (!resp.ok || !data.success) throw new Error(data.error || 'Failed to authenticate'); setFbAuthSuccess(true); setFbError(''); setTimeout(() => { setShowFbAuth(false); setFbAuthSuccess(false); }, 2000); } catch (err) { setFbAuthError(err.message); } finally { setIsFbAuthenticating(false); } }; const performFacebookSearch = async () => { if (!fbSearchTerm) return; setIsFbSearching(true); setFbResults([]); setFbError(''); fbAbortControllerRef.current = new AbortController(); try { const resp = await fetch(getApiUrl('/api/facebook/search'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query: fbSearchTerm, types: fbSearchTypes }), signal: fbAbortControllerRef.current.signal }).catch(err => { if (err.name === 'AbortError') throw err; throw new Error("Failed to connect to the backend server. Ensure 'npm run dev:all' is running."); }); if (!resp.ok) { if (resp.status === 401 || resp.status === 403) { setFbError("Authentication failed. Please check your cookies in the configuration panel."); setShowFbAuth(true); return; } let msg = `Server error: ${resp.status}`; try { const d = await resp.json(); msg = d.error || msg; } catch (e) { } throw new Error(msg); } const reader = resp.body.getReader(); const decoder = new TextDecoder(); let buffer = ''; while (true) { const { value, done } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); const lines = buffer.split('\n'); buffer = lines.pop() || ''; for (const line of lines) { if (line.startsWith('data: ')) { try { const data = JSON.parse(line.slice(6)); if (data.type === 'partial') { setFbResults(prev => { const existingIdx = prev.findIndex(x => x.url === data.data.url); if (existingIdx !== -1) { const existing = prev[existingIdx]; const incoming = data.data; // Update if name is longer OR if incoming has an image and existing doesn't if ((incoming.name && incoming.name.length > (existing.name || '').length) || (incoming.image && !existing.image)) { const copy = [...prev]; copy[existingIdx] = { ...existing, ...incoming }; return copy; } return prev; } return [...prev, data.data]; }); } else if (data.type === 'error') { throw new Error(data.error); } } catch (e) { if (e.message !== "Unexpected end of JSON input" && !e.message.startsWith("Unexpected token")) { throw e; } } } } } } catch (err) { if (err.name === 'AbortError') { const errorMsg = 'Search stopped by user.'; setFbError(errorMsg); return; } if (err.message.includes('FACEBOOK_AUTH_EXPIRED') || err.message.includes('fb_cookies.json not found')) { setFbError("Authentication expired or missing cookies. Launching Facebook Login auto-configurator..."); setShowFbAuth(true); launchFacebookAutoAuth(); } else { setFbError(err.message); } } finally { setIsFbSearching(false); } }; const performFacebookDeepSearch = async () => { if (!fbSearchTerm) return; setIsFbSearching(true); setFbResults([]); setFbError(''); setFbProgress('Initializing Facebook deep search...'); fbAbortControllerRef.current = new AbortController(); try { let charSet = []; if (fbSearchMode === 'a-z') charSet = 'abcdefghijklmnopqrstuvwxyz'.split(''); else if (fbSearchMode === '0-9') charSet = '0123456789'.split(''); else if (fbSearchMode === 'a-z0-9') charSet = 'abcdefghijklmnopqrstuvwxyz0123456789'.split(''); const resultsMap = new Map(); const BATCH_SIZE = 2; // Keep low for browser sessions for (let i = 0; i < charSet.length; i += BATCH_SIZE) { if (fbAbortControllerRef.current.signal.aborted) break; const chunk = charSet.slice(i, i + BATCH_SIZE); setFbProgress(`Searching FB batch: ${chunk.join(', ')} (${Math.min(i + BATCH_SIZE, charSet.length)}/${charSet.length})`); await Promise.all(chunk.map(async (char) => { const currentQuery = `${fbSearchTerm} ${char}`; try { const resp = await fetch(getApiUrl('/api/facebook/search'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query: currentQuery, types: fbSearchTypes }), signal: fbAbortControllerRef.current.signal }); if (!resp.ok) return; const reader = resp.body.getReader(); const decoder = new TextDecoder(); let buffer = ''; while (true) { const { value, done } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); const lines = buffer.split('\n'); buffer = lines.pop() || ''; for (const line of lines) { if (line.startsWith('data: ')) { try { const data = JSON.parse(line.slice(6)); if (data.type === 'partial') { const item = data.data; if (!resultsMap.has(item.url)) { resultsMap.set(item.url, item); setFbResults(Array.from(resultsMap.values())); } } } catch (e) { } } } } } catch (e) { if (e.name !== 'AbortError') console.error(`FB Error for ${char}:`, e); } })); } setFbProgress(null); } catch (err) { if (err.name === 'AbortError') { setFbError('Search stopped by user.'); } else { setFbError(err.message); } setFbProgress(null); } finally { setIsFbSearching(false); } }; const launchXAutoAuth = async () => { setIsXAuthenticating(true); setXAuthError(''); setXAuthSuccess(false); try { const resp = await fetch(getApiUrl('/api/x/auth-launch'), { method: 'POST' }); const data = await resp.json(); if (!resp.ok || !data.success) throw new Error(data.error || 'Failed to authenticate'); setXAuthSuccess(true); setXError(''); setTimeout(() => { setShowXAuth(false); setXAuthSuccess(false); }, 2000); } catch (err) { setXAuthError(err.message); } finally { setIsXAuthenticating(false); } }; const performXSearch = async () => { if (!xSearchTerm) return; setIsXSearching(true); setXResults([]); setXError(''); setXProgress('Starting X (Twitter) search...'); xAbortControllerRef.current = new AbortController(); try { const resp = await fetch(getApiUrl('/api/x/search'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query: xSearchTerm }), signal: xAbortControllerRef.current.signal }); if (!resp.ok) { let msg = 'Failed to search X (Twitter)'; try { const d = await resp.json(); msg = d.error || msg; } catch (e) { } throw new Error(msg); } const reader = resp.body.getReader(); const decoder = new TextDecoder(); let buffer = ''; while (true) { const { value, done } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); const lines = buffer.split('\n'); buffer = lines.pop() || ''; for (const line of lines) { if (line.startsWith('data: ')) { try { const data = JSON.parse(line.slice(6)); if (data.type === 'partial') { setXResults(prev => { const existingIdx = prev.findIndex(x => x.url === data.data.url); if (existingIdx !== -1) { // Update existing entry if more complete data arrives const copy = [...prev]; copy[existingIdx] = { ...copy[existingIdx], ...data.data }; return copy; } return [...prev, data.data]; }); setXProgress(`Found ${xResults.length + 1} results for "${xSearchTerm}"...`); } else if (data.type === 'progress') { setXProgress(data.message); } else if (data.type === 'error') { throw new Error(data.error); } } catch (e) { if (e.message !== "Unexpected end of JSON input" && !e.message.startsWith("Unexpected token")) { throw e; } } } } } setXProgress(`Search complete! Found ${xResults.length} results.`); } catch (err) { if (err.name === 'AbortError') { setXError('Search stopped by user.'); setXProgress(null); return; } if (err.message.includes('X_AUTH_EXPIRED') || err.message.includes('x_cookies.json not found')) { setXError("Authentication required for X (Twitter)."); setShowXAuth(true); if (!isRemote) { launchXAutoAuth(); } } else { setXError(err.message); } setXProgress(null); } finally { setIsXSearching(false); } }; const performTikTokSearch = async () => { if (!ttSearchTerm) return; setIsTtSearching(true); setTtResults([]); setTtError(''); setTtProgress('Starting TikTok search...'); ttAbortControllerRef.current = new AbortController(); try { const resp = await fetch(getApiUrl('/api/tiktok/search'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query: ttSearchTerm }), signal: ttAbortControllerRef.current.signal }); if (!resp.ok) { let msg = 'Failed to search TikTok'; try { const d = await resp.json(); msg = d.error || msg; } catch (e) { } throw new Error(msg); } const reader = resp.body.getReader(); const decoder = new TextDecoder(); let buffer = ''; while (true) { const { value, done } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); const lines = buffer.split('\n'); buffer = lines.pop() || ''; for (const line of lines) { if (line.startsWith('data: ')) { try { const data = JSON.parse(line.slice(6)); if (data.type === 'partial') { setTtResults(prev => { if (prev.some(x => x.url === data.data.url)) return prev; return [...prev, data.data]; }); } else if (data.type === 'progress') { setTtProgress(data.data); } else if (data.type === 'error') { throw new Error(data.error); } } catch (e) { if (e.message.includes('API credentials') || e.message.includes('TikTok') || e.message.includes('Navigation')) { throw e; // Bubble up important errors } } } } } setTtProgress(null); } catch (err) { if (err.name === 'AbortError') { setTtError('Search stopped by user.'); } else { setTtError(err.message); } setTtProgress(null); } finally { setIsTtSearching(false); } }; const launchInstagramAutoAuth = async () => { setIsIgAuthenticating(true); setIgAuthError(''); setIgAuthSuccess(false); try { const resp = await fetch(getApiUrl('/api/instagram/auth-launch'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: igUsername, password: igPassword }) }); const data = await resp.json(); if (!resp.ok || !data.success) throw new Error(data.error || 'Failed to authenticate'); // The backend handles saving these; we just need to know it succeeded setIgAuthSuccess(true); setIgError(''); // Trigger instant status check setTimeout(checkAllAuth, 500); setTimeout(() => { setShowIgAuth(false); setIgAuthSuccess(false); }, 2000); } catch (err) { setIgAuthError(err.message); } finally { setIsIgAuthenticating(false); } }; const saveInstagramCookies = async () => { if (!igAuthInput) { setIgAuthError('Please paste the cookies JSON array.'); return; } setIsIgAuthenticating(true); setIgAuthError(''); setIgAuthSuccess(false); try { let rawInput = igAuthInput.trim(); let allCookies; try { // First pass: try standard parse allCookies = JSON.parse(rawInput); // Second pass: if user pasted a JSON string wrapped in quotes (stringified JSON) if (typeof allCookies === 'string') { allCookies = JSON.parse(allCookies); } if (!Array.isArray(allCookies)) { throw new Error('Input is valid JSON but not an array of cookies.'); } } catch (e) { if (e.message.includes('JSON but not an array')) throw e; throw new Error(`JSON Error: Please ensure you paste a valid [ { ... } ] array. (${e.message})`); } const response = await fetch(getApiUrl('/api/instagram/save-cookies'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ allCookies }) }); if (!response.ok) { let errorMsg = 'Failed to save cookies'; try { const errData = await response.json(); errorMsg = errData.error || errorMsg; } catch (e) { } throw new Error(errorMsg); } setIgAuthSuccess(true); setIgError(''); // Clear search errors if any // Trigger instant status check setTimeout(checkAllAuth, 100); setTimeout(() => { setShowIgAuth(false); setIgAuthSuccess(false); }, 2000); } catch (err) { setIgAuthError(err.message); } finally { setIsIgAuthenticating(false); } }; const saveFacebookCookies = async () => { if (!fbAuthInput) { setFbAuthError('Cookies data is required.'); return; } setIsFbAuthenticating(true); setFbAuthError(''); setFbAuthSuccess(false); try { // Clean input (handle standard JSON format) let cookies; try { cookies = JSON.parse(fbAuthInput); } catch (e) { throw new Error('Invalid JSON format for cookies.'); } const response = await fetch(getApiUrl('/api/facebook/save-cookies'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ cookies }) }); if (!response.ok) throw new Error('Failed to save Facebook cookies'); setFbAuthSuccess(true); setTimeout(checkAllAuth, 500); setTimeout(() => { setShowFbAuth(false); setFbAuthSuccess(false); }, 2000); } catch (err) { setFbAuthError(err.message); } finally { setIsFbAuthenticating(false); } }; const saveXCookies = async () => { if (!xAuthInput) { setXAuthError('Cookies data is required.'); return; } setIsXAuthenticating(true); setXAuthError(''); setXAuthSuccess(false); try { const response = await fetch(getApiUrl('/api/x/save-cookies'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ cookies: xAuthInput }) }); if (!response.ok) throw new Error('Failed to save X cookies'); setXAuthSuccess(true); setTimeout(checkAllAuth, 500); setTimeout(() => { setShowXAuth(false); setXAuthSuccess(false); }, 2000); } catch (err) { setXAuthError(err.message); } finally { setIsXAuthenticating(false); } }; const LoginRequired = ({ platform, onLogin }) => { const icons = { telegram: , facebook: , x: , instagram: }; const colors = { telegram: 'var(--p-telegram)', facebook: 'var(--p-facebook)', x: 'var(--text-bright)', instagram: 'var(--p-instagram)' }; return (
{icons[platform]}

Session Inactive

System requires an active {platform.toUpperCase()} session to authorize search requests.

); }; const StatusBadge = ({ platform }) => { const auth = platformsAuth[platform] || { status: false, detail: 'OFFLINE' }; if (platform === 'status') return null; return (
{auth.status ? 'CONNECTED' : 'SESSION_INACTIVE'} | {auth.detail}
); }; const StatusHub = () => { const activeSearches = Object.entries(searchStates).filter(([_, busy]) => busy); return (
{activeSearches.length > 0 && (

LIVE_ACTIVITY_MONITOR [{activeSearches.length}]

{activeSearches.map(([platform, _]) => { const progress = platform === 'telegram' ? tgProgress : platform === 'instagram' ? igProgress : platform === 'facebook' ? fbProgress : platform === 'tiktok' ? ttProgress : xProgress; const resultsCount = platform === 'telegram' ? tgResults.length : platform === 'instagram' ? igResults.length : platform === 'facebook' ? fbResults.length : platform === 'tiktok' ? ttResults.length : xResults.length; return (
{platform} {resultsCount} results found
{progress || 'Processing...'}
); })}
)}
{Object.entries(platforms).filter(([k]) => k !== 'status').map(([key, p]) => { const auth = platformsAuth[key] || { status: false, detail: 'UNKNOWN', updated: null }; const Icon = p.icon; return (
{p.label}
{auth.status ? 'ONLINE' : 'OFFLINE'}
Local Storage {auth.detail}
Sync Status {auth.updated || 'NEVER'}
); })}
{/* System Management */}

// security & maintenance

CAUTION: This will permanently delete Instagram, Facebook, and X session files from the server.

); }; // Platform config const platforms = { status: { icon: Database, label: 'STATUS', accent: 'var(--neon-cyan)' }, telegram: { icon: Send, label: 'Telegram', accent: 'var(--p-telegram)' }, facebook: { icon: Facebook, label: 'Facebook', accent: 'var(--p-facebook)' }, x: { icon: Twitter, label: 'X', accent: 'var(--p-x)' }, tiktok: { icon: Music2, label: 'TikTok', accent: 'var(--p-tiktok)' }, instagram: { icon: Instagram, label: 'Instagram', accent: 'var(--p-instagram)' }, }; const cur = platforms[activeTab] || platforms.telegram; const CurIcon = cur.icon; const searchStates = { telegram: isTgSearching, instagram: isIgSearching, facebook: isFbSearching, tiktok: isTtSearching, x: isXSearching }; const busy = activeTab === 'status' ? false : searchStates[activeTab] || false; const curTerm = activeTab === 'status' ? '' : activeTab === 'telegram' ? tgSearchTerm : activeTab === 'instagram' ? igSearchTerm : activeTab === 'facebook' ? fbSearchTerm : activeTab === 'tiktok' ? ttSearchTerm : xSearchTerm; return (
{/* Scanline overlay */}
{/* ═══ TOP NAV ═══ */} {/* ═══ MAIN ═══ */}
{/* Page header */}

{cur.label} // search

{activeTab === 'status' ? '> system command center // global health' : activeTab === 'telegram' ? '> users, channels, groups' : activeTab === 'facebook' ? '> pages, people, groups' : activeTab === 'tiktok' ? '> profiles, creators' : activeTab === 'instagram' ? '> profiles, accounts' : '> users, profiles'}

{/* Errors */} {error &&
ERR{error}
} {activeTab === 'telegram' && tgError &&
ERR{tgError}
} {activeTab === 'x' && xError &&
ERR{xError}
} {loading && (
INITIALIZING_
)} {/* ═══ TELEGRAM AUTH ═══ */} {activeTab === 'telegram' && (step === 'phone' || step === 'code') && (

> Telegram.auth()

{step === 'phone' ? '// enter phone in intl format' : '// enter verification code'}

{step === 'phone' ? (
setPhone(e.target.value)} className="cyber-input" />
) : (
setCode(e.target.value)} className="cyber-input text-center tracking-[0.4em]" />
)}
)} {/* ═══ DASHBOARD ═══ */} {activeTab === 'status' ? ( ) : (activeTab !== 'telegram' || step === 'dashboard') && (
{!isFirstAuthCheckDone ? (

Verifying_Session_State...

) : ( <> {/* Config toggle */} {(activeTab === 'instagram' || activeTab === 'facebook' || activeTab === 'x') && (
)} {/* Facebook Auth */} {activeTab === 'facebook' && (showFbAuth || !platformsAuth['facebook']?.status) && (

> fb.authenticate()

// cookies required for search

{fbAuthError &&
ERR{fbAuthError}
} {isRemote && !fbAuthSuccess && (

REMOTE SERVER DETECTED

Browser login is disabled on Render to prevent crashes. Please perform login on your local machine and paste the cookies below.

)} {fbAuthSuccess ? (
✓cookies.saved()
) : (

paste cookies