InvertedShu commited on
Commit
8a1c8a3
·
0 Parent(s):

Initial Deployment Version: Parallel OSINT Dashboard

Browse files
.dockerignore ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ node_modules
2
+ dist
3
+ .env.local
4
+ .env
5
+ *.json.local
6
+ ig_session.json
7
+ fb_cookies.json
8
+ **/x_user_data/
9
+ **/ig_cookies.json
10
+ .git
11
+ .github
12
+ *.png
13
+ *.log
.gitignore ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Logs
2
+ logs
3
+ *.log
4
+ npm-debug.log*
5
+ yarn-debug.log*
6
+ yarn-error.log*
7
+ pnpm-debug.log*
8
+ lerna-debug.log*
9
+
10
+ # Build & Cache
11
+ node_modules
12
+ dist
13
+ dist-ssr
14
+ .vite
15
+ .vite_temp_*
16
+ .temp
17
+ .cache
18
+
19
+ # Screenshots & Debug Images
20
+ *.png
21
+ *.jpg
22
+ *.jpeg
23
+ *.webp
24
+ *.gif
25
+ fb_search_fail.png
26
+ debug_*.png
27
+ !public/*.png
28
+ !src/assets/*.png
29
+
30
+ # Local/Sensitive
31
+ .env
32
+ .env.local
33
+ .env.*.local
34
+ *.json.local
35
+ ig_session.json
36
+ **/ig_session.json
37
+ **/fb_cookies.json
38
+ **/x_user_data/
39
+ **/ig_cookies.json
40
+ scratch/
41
+ debug_*.js
42
+ test_*.js
43
+ tiktok_home.html
44
+
45
+ # Editor
46
+ .vscode/
47
+ .idea/
48
+ .DS_Store
49
+ *.suo
50
+ *.ntvs*
51
+ *.njsproj
52
+ *.sln
53
+ *.sw?
DEPLOYMENT.md ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚀 Deployment Guide: Split Backend & Frontend (Vercel + Render)
2
+
3
+ This application has been structured to separate the React User Interface (Frontend) and the Playwright/Express API (Backend). This enables hosting the Frontend on an edge network for maximum speed and the Backend on a container service capable of running full browsers.
4
+
5
+ ## Part 1: Deploying the Backend to Render.com
6
+
7
+ The backend powers the search logic via Playwright web scraping and needs to be hosted on a platform that supports Docker or heavy Node.js instances.
8
+
9
+ 1. **Create an Account**: Go to [Render.com](https://render.com) and create an account.
10
+ 2. **New Web Service**: Click "New" -> "Web Service".
11
+ 3. **Connect Repository**: Connect your GitHub account and select this repository.
12
+ 4. **Configuration Options**:
13
+ - **Environment**: Select **Node** or **Docker** (Docker is recommended for Playwright dependencies).
14
+ - **Build Command**: `npm install`
15
+ - **Start Command**: `npm start` (This will execute `node server.js`).
16
+ 5. **Environment Variables**: Head into the 'Environment' section and set up necessary secrets (derived from your `.env.local`):
17
+ - `VITE_INSTAGRAM_SESSION_ID`
18
+ - `VITE_INSTAGRAM_USER_ID`
19
+ - `VITE_INSTAGRAM_CSRF_TOKEN`
20
+ - `HEADLESS=true`
21
+ - `PORT=3001` (Or any port Render assigns).
22
+ 6. **Deploy**: Trigger the initial deployment.
23
+ 7. **Copy API URL**: Once the service is live, **copy the URL of your Render application** (e.g., `https://sm-hunting-backend.onrender.com`). You will need this for Vercel.
24
+
25
+ ---
26
+
27
+ ## Part 2: Deploying the Frontend to Vercel
28
+
29
+ Vercel will host the frontend UI, delivering it at lightning speed.
30
+
31
+ 1. **Create an Account**: Go to [Vercel.com](https://vercel.com) and sign in via GitHub.
32
+ 2. **Add New Project**: Select the exact same GitHub repository you deployed to Render.
33
+ 3. **Configure Project**:
34
+ - **Framework Preset**: Vite
35
+ - **Build Command**: `npm run build`
36
+ - **Output Directory**: `dist`
37
+ 4. **Set Environment Variables**:
38
+ - Expand the **Environment Variables** section.
39
+ - Add a new variable called `VITE_API_URL`.
40
+ - Set the value to the **Render URL** you copied in Part 1 (e.g. `https://sm-hunting-backend.onrender.com`).
41
+ - *Note: Leave off any trailing slashes.*
42
+ 5. **Deploy**: Click Deploy and wait for Vercel to build the user interface!
43
+
44
+ ---
45
+
46
+ ## 🛠️ Local Development
47
+
48
+ If you wish to spin up the local development environment, everything will continue to work seamlessly!
49
+
50
+ When `VITE_API_URL` is undefined locally, the frontend will automatically infer the local API path `/api/...` and the Vite config acts as a proxy forwarding these directly to `http://localhost:3001`.
51
+
52
+ ```bash
53
+ # 1. Install dependencies
54
+ npm install
55
+
56
+ # 2. Start the backend Server
57
+ npm start
58
+
59
+ # 3. Start the Frontend Vite builder (in a separate terminal)
60
+ npm run dev
61
+ ```
Dockerfile ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use Node.js 20 base image
2
+ FROM node:20-slim
3
+
4
+ # Install system dependencies for Playwright
5
+ RUN apt-get update && apt-get install -y \
6
+ libgbm-dev \
7
+ libnss3 \
8
+ libatk-bridge2.0-0 \
9
+ libgtk-3-0 \
10
+ libasound2 \
11
+ && rm -rf /var/lib/apt/lists/*
12
+
13
+ # Set working directory
14
+ WORKDIR /app
15
+
16
+ # Copy package files and install dependencies
17
+ COPY package*.json ./
18
+ RUN npm install
19
+
20
+ # Install Playwright browsers
21
+ RUN npx playwright install --with-deps chromium
22
+
23
+ # Copy the rest of the application code
24
+ COPY . .
25
+
26
+ # Build the Vite frontend
27
+ RUN npm run build
28
+
29
+ # Expose the default Hugging Face port
30
+ EXPOSE 7860
31
+
32
+ # Set environment variables for production
33
+ ENV NODE_ENV=production
34
+ ENV PORT=7860
35
+
36
+ # Start the server
37
+ CMD ["node", "server.js"]
README.md ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: SM Tools OSINT
3
+ emoji: 🕵️
4
+ colorFrom: blue
5
+ colorTo: indigo
6
+ sdk: docker
7
+ pinned: false
8
+ ---
9
+
10
+ # SM Tools OSINT
11
+
12
+ A powerful OSINT (Open Source Intelligence) and Threat Hunting dashboard built with React, Vite, Node.js, and Playwright. This tool streamlines the process of searching, aggregating, and analyzing profiles and deep search results across major social media platforms.
13
+
14
+ ## Features
15
+
16
+ - **Telegram Search**: Search global users and channels. Supports advanced permutation searches (e.g., TargetName[a-z0-9]) integrated natively via Telegram API (MTProto).
17
+ - **Instagram Search**: Deep search for Instagram accounts, complete with visual profile previews. Also supports automated authentication.
18
+ - **Facebook Search**: Search Facebook Pages, Groups, and People with dynamic live streaming of results using Playwright.
19
+ - **X (Twitter) Search**: Scrape and aggregate tweets and accounts based on keyword targeting.
20
+ - **Advanced Expansion Modes**: Toggle exact matching, alphabetical (a-z), or alphanumeric (a-z0-9) permutations for broader intelligence gathering.
21
+ - **Exporting**: Export parsed results easily to `.xlsx` format for external reporting and correlation.
22
+
23
+ ## Tech Stack
24
+
25
+ - **Frontend**: React, TailwindCSS, Lucide Icons, Vite.
26
+ - **Backend/Middlewares**: Node-based Proxy & SSE Servers running natively inside Vite's dev server (`vite.config.js`).
27
+ - **Scraping Engine**: Playwright for Chromium automation (used heavily in Facebook and X modules).
28
+ - **Libraries**: `node-telegram`, `xlsx`, `playwright`.
29
+
30
+ ## Installation & Setup
31
+
32
+ 1. **Clone the Repository:**
33
+ ```bash
34
+ git clone https://github.com/InvertedShu/sm-tools-osint.git
35
+ cd sm-tools-osint
36
+ ```
37
+
38
+ 2. **Install Dependencies:**
39
+ ```bash
40
+ npm install
41
+ ```
42
+
43
+ 3. **Install Playwright Browsers:**
44
+ Since Playwright is used for scraping DOM structures and handling cookie-based authentications naturally, you need to install its browser binaries:
45
+ ```bash
46
+ npx playwright install
47
+ ```
48
+
49
+ ## Configuration
50
+
51
+ You must set up your environment variables and cookies to ensure all scrapers authenticate properly to bypass rate limits and bot-detection.
52
+
53
+ 1. **Environment Variables (`.env.local`)**:
54
+ Create a `.env.local` file in the root directory:
55
+ ```env
56
+ VITE_TELEGRAM_API_ID=your_api_id_here
57
+ VITE_TELEGRAM_API_HASH=your_api_hash_here
58
+ ```
59
+ *(You can obtain Telegram API credentials from my.telegram.org).*
60
+
61
+ 2. **Cookie State Files**:
62
+ Some scrapers utilize continuous session states. Ensure you manage your cookies locally:
63
+ - `facebook-search-main/fb_cookies.json` (for Facebook authentication state)
64
+
65
+ ## Running the Application
66
+
67
+ To start the local development server (which handles both the React frontend and the Proxy/Scraping API middlewares):
68
+
69
+ ```bash
70
+ npm run dev
71
+ ```
72
+
73
+ The application will be available at [http://localhost:5173/](http://localhost:5173/).
74
+
75
+ ## Usage Notes
76
+
77
+ - Depending on region and rate-limits, you may occasionally need to refresh the authentication state files (e.g. updating `fb_cookies.json`).
78
+ - If you notice 0 results returning for queries with known data, verify your active login status the respective platforms.
79
+ - Search expansion queries can sometimes take several seconds to stream all results. Do not interrupt the stream if large permutation modes are active.
80
+
81
+ ## License
82
+ Proprietary / Internal Use Only.
eslint.config.js ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import js from '@eslint/js'
2
+ import globals from 'globals'
3
+ import reactHooks from 'eslint-plugin-react-hooks'
4
+ import reactRefresh from 'eslint-plugin-react-refresh'
5
+ import { defineConfig, globalIgnores } from 'eslint/config'
6
+
7
+ export default defineConfig([
8
+ globalIgnores(['dist']),
9
+ {
10
+ files: ['**/*.{js,jsx}'],
11
+ extends: [
12
+ js.configs.recommended,
13
+ reactHooks.configs.flat.recommended,
14
+ reactRefresh.configs.vite,
15
+ ],
16
+ languageOptions: {
17
+ ecmaVersion: 2020,
18
+ globals: globals.browser,
19
+ parserOptions: {
20
+ ecmaVersion: 'latest',
21
+ ecmaFeatures: { jsx: true },
22
+ sourceType: 'module',
23
+ },
24
+ },
25
+ rules: {
26
+ 'no-unused-vars': ['error', { varsIgnorePattern: '^[A-Z_]' }],
27
+ },
28
+ },
29
+ ])
facebook-search-main/.gitignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ fb_cookies.json
2
+ venv/
3
+ __pycache__/
4
+ *.xlsx
5
+ debug_screenshot_*.png
6
+ debug_page_*.html
7
+ .env
8
+ .DS_Store
9
+ Wealth.txt
facebook-search-main/Facebook_Search_Documentation.md ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Facebook Search Scraper - 1-Page Documentation
2
+
3
+ ## 📌 Overview
4
+ An automated Python script leveraging **Playwright** to search Facebook for specific keywords and continuously scrape the resulting **Pages** and **Groups** URLs. It handles lazy loading, processes multiple search terms (individually or from a file), and consolidates all findings into a clean Excel report.
5
+
6
+ ## 🛠️ Setup & Installation
7
+ 1. **Prerequisites:** Python 3.8+ installed on your system.
8
+ 2. **Initial Setup:** Run the setup script to automatically create a virtual environment, install required packages (`playwright`, `pandas`), and download the necessary browser binaries:
9
+ ```bash
10
+ python setup_environment.py
11
+ ```
12
+
13
+ ## 🍪 Authentication (One-Time)
14
+ Facebook requires authentication to search and scrape data effectively.
15
+ - Upon running `setup_environment.py` for the first time, if it doesn't find a `fb_cookies.json` file, it will launch the cookie generator.
16
+ - A browser will open. **Log in manually** to your Facebook account.
17
+ - Once completely logged in, return to the terminal and press **ENTER**.
18
+ - Your secure session is saved locally to `fb_cookies.json`, allowing the main scraper to run seamlessly in future executions without requiring another login.
19
+
20
+ ## 🚀 Usage Guide
21
+
22
+ ### Option 1: Interactive Runner (`setup_environment.py`)
23
+ Run the setup script again. It acts as an interactive runner that ensures your environment is healthy before starting:
24
+ ```bash
25
+ python setup_environment.py
26
+ ```
27
+ - It will verify dependencies and immediately launch the scraper.
28
+ - When prompted, enter a **single search term** (e.g., `Nike`) or the **path to a text file** containing multiple terms (one per line, e.g., `my_searches.txt`).
29
+ - **Loop:** After completing a search, it will prompt you if you want to run another search or exit.
30
+
31
+ ### Option 2: Direct Execution (`facebook_search.py`)
32
+ If you prefer running the main script directly via standard command line:
33
+ ```bash
34
+ # Search for a single term
35
+ python facebook_search.py "NYSE"
36
+
37
+ # Search using a text file of terms
38
+ python facebook_search.py my_searches.txt
39
+ ```
40
+
41
+ ## 📊 Output Data
42
+ All successfully scraped URLs are smartly filtered (removing system paths like `/events/`, `/messages/`) to ensure quality page/group links. The results are aggregated and exported into timestamped Excel files in the project directory:
43
+ - **Format:** `facebook_search_results_YYYYMMDD_HHMMSS.xlsx`
44
+ - **Columns:** `Search Term`, `Type` (Pages/Groups), `URL`
45
+
46
+ ## ⚠️ Troubleshooting
47
+ - **No Results Found or Login Loop:** Ensure `fb_cookies.json` is fresh. If the session expired, delete the file and run `python fb_cookies.py` to regenerate it.
48
+ - **Missing Dependencies Error:** Run `python setup_environment.py` to re-synchronize your environment cleanly.
49
+ - **"End of results" not found:** The script attempts to scroll 10 times if no new content loads. Try running on a faster connection or increasing `max_retries` in `facebook_search.py`.
facebook-search-main/README.md ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Facebook Search Automation
2
+
3
+ A Python script to automate searching for Facebook pages and extracting their URLs, even capturing results that require scrolling.
4
+
5
+ ## Features
6
+
7
+ - **Automated Searching:** Uses Playwright to navigate Facebook and perform searches.
8
+ - **Robust Scrolling:** Automatically scrolls to the bottom of the results, handling "End of results" indicators and lazy loading.
9
+ - **Continuous Scraping:** Captures URLs while scrolling to handle DOM virtualization (where items disappear from the top).
10
+ - **Excel Export:** Saves all unique results to a timestamped Excel file (e.g., `facebook_search_term_20231027_120000.xlsx`).
11
+ - **Smart Filtering:** Removes system links, duplicates, and irrelevant pages.
12
+
13
+ ## Prerequisites
14
+
15
+ - **Python 3.8+**
16
+ - **Git**
17
+
18
+ ## Installation
19
+
20
+ 1. **Clone the repository:**
21
+ ```bash
22
+ git clone https://github.com/InvertedShu/facebook-search.git
23
+ cd facebook-search
24
+ ```
25
+
26
+ 2. **Run the Setup Script:**
27
+ This script creates a virtual environment, installs dependencies (Playwright, Pandas, OpenPyXL), and installs the necessary browsers.
28
+ ```bash
29
+ python setup_environment.py
30
+ ```
31
+
32
+ ## Configuration (Important)
33
+
34
+ The script requires a `fb_cookies.json` file to log in to Facebook automatically. A helper script is provided to generate this.
35
+
36
+ 1. **Run the Cookie Generator:**
37
+ ```bash
38
+ python fb_cookies.py
39
+ ```
40
+ 2. **Log In:** A browser window will open. Log in to your Facebook account manually.
41
+ 3. **Save:** Once logged in, go back to your terminal and press **ENTER**. The script will save your cookies to `fb_cookies.json` and close the browser.
42
+
43
+ > **Note:** `fb_cookies.json` contains your session data. It is ignored by Git to protect your privacy. Do not share this file.
44
+
45
+ ## Usage
46
+
47
+ 1. **Run the script:**
48
+ ```bash
49
+ python facebook_search.py
50
+ ```
51
+ 2. **Enter a search term** when prompted.
52
+ 3. **Wait** while the browser opens, searches, and scrolls through the results.
53
+ 4. **View Results:** The console will show the number of results found, and an Excel file will be saved in the same directory.
54
+
55
+ ### Bulk Search from File
56
+
57
+ You can also provide a text file containing multiple search terms (one per line) to automate batch processing.
58
+
59
+ 1. **Create a file** (e.g., `search_terms.txt`):
60
+ ```text
61
+ Nike
62
+ Adidas
63
+ Puma
64
+ ```
65
+ 2. **Run with argument:**
66
+ ```bash
67
+ python facebook_search.py search_terms.txt
68
+ ```
69
+ Or run `python facebook_search.py` and enter the file path when prompted.
70
+
71
+ ## Troubleshooting
72
+
73
+ - **"End of results" not found:** The script attempts to scroll 10 times if no new content loads. Increase `max_retries` in `facebook_search.py` if your connection is slow.
74
+ - **Login issues:** Ensure your `fb_cookies.json` is fresh. If the script fails to navigate, try exporting cookies again.
75
+
76
+ ## Disclaimer
77
+
78
+ This tool is for educational purposes only. Automated scraping may violate Facebook's Terms of Service. Use responsibly.
facebook-search-main/fbCookies.js ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { chromium } from 'playwright';
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ import { fileURLToPath } from 'url';
5
+
6
+ const __filename = fileURLToPath(import.meta.url);
7
+ const __dirname = path.dirname(__filename);
8
+
9
+ const COOKIE_FILE = path.join(__dirname, 'fb_cookies.json');
10
+
11
+ async function launchFacebookAutoAuth() {
12
+ const isHeadless = process.env.HEADLESS !== 'false';
13
+ const browser = await chromium.launch({
14
+ headless: isHeadless,
15
+ args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu']
16
+ });
17
+ const context = await browser.newContext();
18
+ const page = await context.newPage();
19
+
20
+ try {
21
+ console.log('[*] Opening Facebook login page...');
22
+ await page.goto('https://www.facebook.com/', { timeout: 60000 });
23
+
24
+ console.log('[*] Waiting for user to log in manually...');
25
+ let loggedIn = false;
26
+
27
+ // Wait up to 5 minutes
28
+ for (let i = 0; i < 300; i++) {
29
+ await new Promise(r => setTimeout(r, 1000));
30
+ try {
31
+ if (page.isClosed()) break;
32
+ const cookies = await context.cookies();
33
+ if (cookies.some(c => c.name === 'c_user')) {
34
+ loggedIn = true;
35
+ break;
36
+ }
37
+ } catch (e) {
38
+ break;
39
+ }
40
+ }
41
+
42
+ if (loggedIn) {
43
+ console.log('[*] Login detected! Saving cookies...');
44
+ await new Promise(r => setTimeout(r, 3000));
45
+ await context.storageState({ path: COOKIE_FILE });
46
+ return { success: true, message: 'Cookies saved successfully!' };
47
+ } else {
48
+ return { success: false, error: 'Login timed out or browser was closed.' };
49
+ }
50
+ } catch (e) {
51
+ return { success: false, error: e.message };
52
+ } finally {
53
+ try { await browser.close(); } catch (e) {}
54
+ }
55
+ }
56
+
57
+ export { launchFacebookAutoAuth };
facebook-search-main/fbSearch.js ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import path from 'path';
2
+ import fs from 'fs';
3
+ import { chromium } from 'playwright-extra';
4
+
5
+ const COOKIE_FILE = path.resolve(process.cwd(), 'facebook-search-main', 'fb_cookies.json');
6
+
7
+ async function extractFacebookUrls(searchTerm, searchType = 'pages', onNewUrl = null, onProgress = null) {
8
+ const urls = new Map();
9
+ const encodedTerm = encodeURIComponent(searchTerm);
10
+
11
+ const isHeadless = process.env.HEADLESS !== 'false';
12
+ const browser = await chromium.launch({
13
+ headless: isHeadless,
14
+ args: [
15
+ '--no-sandbox',
16
+ '--disable-setuid-sandbox',
17
+ '--disable-dev-shm-usage',
18
+ '--disable-gpu'
19
+ ]
20
+ });
21
+
22
+ if (!fs.existsSync(COOKIE_FILE)) {
23
+ await browser.close();
24
+ throw new Error('FACEBOOK_AUTH_EXPIRED');
25
+ }
26
+
27
+ const context = await browser.newContext({
28
+ storageState: COOKIE_FILE,
29
+ locale: 'en-US',
30
+ userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
31
+ });
32
+ const page = await context.newPage();
33
+
34
+ try {
35
+ // 1. Open Facebook Home
36
+ if (onProgress) onProgress(`Navigating to Facebook Home...`);
37
+ await page.goto('https://www.facebook.com/', { timeout: 60000, waitUntil: 'domcontentloaded' });
38
+ await page.waitForTimeout(5000);
39
+
40
+ const url = page.url().toLowerCase();
41
+ const loginBtn = await page.locator('button[name="login"]').count();
42
+
43
+ // Check for "Welcome" or "Continue as" screen
44
+ try {
45
+ // Look for the primary blue button which often says "Continue" or "Continue as Sam"
46
+ const continueBtn = page.locator('div[role="button"][tabindex="0"], button').filter({ hasText: /Continue|Stay logged in|Sam S/i }).first();
47
+ const needsContinue = await continueBtn.count();
48
+ if (needsContinue > 0) {
49
+ if (onProgress) onProgress(`Dismissing interstitial (detected button)...`);
50
+ await continueBtn.click();
51
+ await page.waitForTimeout(5000);
52
+ }
53
+ } catch (e) {}
54
+
55
+ if (url.includes('login') || loginBtn > 0) {
56
+ throw new Error('FACEBOOK_AUTH_EXPIRED');
57
+ }
58
+
59
+ // 2. Clear and perform search via UI
60
+ if (onProgress) onProgress(`Searching for "${searchTerm}" via UI...`);
61
+
62
+ // Try multiple selectors for the search bar
63
+ const searchSelectors = [
64
+ 'input[placeholder*="Search Facebook"]',
65
+ 'input[aria-label*="Search Facebook"]',
66
+ 'input[type="search"]',
67
+ '[role="search"] input'
68
+ ];
69
+
70
+ let searchInput = null;
71
+ for (const sel of searchSelectors) {
72
+ const el = page.locator(sel).first();
73
+ if (await el.count() > 0) {
74
+ searchInput = el;
75
+ break;
76
+ }
77
+ }
78
+
79
+ if (!searchInput) {
80
+ await page.screenshot({ path: 'fb_search_fail.png' });
81
+ throw new Error('Could not find Facebook search bar. Diagnostic saved to fb_search_fail.png');
82
+ }
83
+
84
+ await searchInput.waitFor({ state: 'visible', timeout: 15000 });
85
+ await searchInput.click();
86
+ await page.keyboard.down('Control');
87
+ await page.keyboard.press('A');
88
+ await page.keyboard.up('Control');
89
+ await page.keyboard.press('Backspace');
90
+ await searchInput.type(searchTerm, { delay: 50 });
91
+ await page.keyboard.press('Enter');
92
+
93
+ // Wait for Search results to load
94
+ if (onProgress) onProgress(`Waiting for search results...`);
95
+ await page.waitForTimeout(5000);
96
+
97
+ // 3. Switch to category filter (Pages, Groups, People)
98
+ if (onProgress) onProgress(`Applying filter: ${searchType}...`);
99
+ try {
100
+ const filterText = (searchType === 'people') ? 'People' : (searchType === 'groups' ? 'Groups' : 'Pages');
101
+ const filterTab = page.locator(`a:has-text("${filterText}"), span:has-text("${filterText}")`).first();
102
+ await filterTab.waitFor({ state: 'visible', timeout: 5000 });
103
+ await filterTab.click();
104
+ await page.waitForTimeout(4000);
105
+ } catch (e) {
106
+ console.log(`Filter tab ${searchType} not found or already active.`);
107
+ }
108
+
109
+ try {
110
+ await page.waitForSelector('div[role="feed"], div[role="main"]', { timeout: 15000 });
111
+ } catch (e) {
112
+ await page.waitForTimeout(5000);
113
+ }
114
+
115
+ const extractVisibleUrls = async () => {
116
+ try {
117
+ // Use page.evaluate to extract all results in one shot
118
+ // Facebook uses SVG <image> elements for profile pics, NOT <img> tags
119
+ const extracted = await page.evaluate(() => {
120
+ const results = [];
121
+ const links = document.querySelectorAll('a[href]');
122
+
123
+ for (const link of links) {
124
+ const href = link.getAttribute('href');
125
+ if (!href) continue;
126
+
127
+ let name = link.getAttribute('aria-label') || link.innerText || '';
128
+ name = name.trim();
129
+
130
+ // Try to find a profile picture near this link
131
+ // Facebook renders images as SVG <image> elements with href/xlink:href
132
+ let image = '';
133
+ let container = link.closest('[role="article"]') || link.parentElement?.parentElement?.parentElement?.parentElement?.parentElement;
134
+ if (container) {
135
+ // Look for SVG image elements (Facebook's actual rendering method)
136
+ const svgImgs = container.querySelectorAll('image');
137
+ for (const svgImg of svgImgs) {
138
+ const imgHref = svgImg.getAttribute('href') || svgImg.getAttribute('xlink:href');
139
+ if (imgHref && (imgHref.includes('scontent') || imgHref.includes('fbcdn'))) {
140
+ image = imgHref;
141
+ break;
142
+ }
143
+ }
144
+ // Fallback: check background-image CSS
145
+ if (!image) {
146
+ const bgEls = container.querySelectorAll('*');
147
+ for (const bgEl of bgEls) {
148
+ const bg = getComputedStyle(bgEl).backgroundImage;
149
+ if (bg && bg !== 'none' && bg.includes('scontent')) {
150
+ const match = bg.match(/url\(["']?(.*?)["']?\)/);
151
+ if (match && match[1]) {
152
+ image = match[1];
153
+ break;
154
+ }
155
+ }
156
+ }
157
+ }
158
+ }
159
+
160
+ // Check for verification badge
161
+ const verified = !!link.closest('div')?.querySelector('svg[aria-label="Verified account"], i[aria-label="Verified account"], span[aria-label="Verified account"]');
162
+
163
+ results.push({ href, name, image, verified });
164
+ }
165
+ return results;
166
+ });
167
+
168
+ let countNew = 0;
169
+
170
+ for (const { href, name: rawName, image, verified } of extracted) {
171
+ let name = rawName;
172
+ const lowerName = name.toLowerCase();
173
+ if (lowerName.startsWith('profile photo of ')) name = name.slice(17);
174
+ else if (lowerName.startsWith('profile picture of ')) name = name.slice(19);
175
+ else if (lowerName.startsWith('cover photo of ')) name = name.slice(15);
176
+ name = name.trim();
177
+
178
+ let fullUrl = '';
179
+ if (href.startsWith('/')) fullUrl = `https://www.facebook.com${href}`;
180
+ else if (href.includes('facebook.com')) fullUrl = href;
181
+ else continue;
182
+
183
+ let cleanUrl = '';
184
+ if (fullUrl.includes('profile.php')) {
185
+ if (fullUrl.includes('id=')) {
186
+ try {
187
+ const urlObj = new URL(fullUrl);
188
+ const id = urlObj.searchParams.get('id');
189
+ cleanUrl = `${urlObj.origin}${urlObj.pathname}?id=${id}`;
190
+ } catch (e) {
191
+ cleanUrl = fullUrl;
192
+ }
193
+ } else {
194
+ cleanUrl = fullUrl;
195
+ }
196
+ } else {
197
+ cleanUrl = fullUrl.split('?')[0].replace(/\/$/, '');
198
+ }
199
+
200
+ if (!cleanUrl.includes('facebook.com')) continue;
201
+
202
+ const ignorePatterns = [
203
+ '/events/', '/posts/', '/photos/', '/messages/',
204
+ '/watch/', '/gaming/', '/marketplace/', '/friends/',
205
+ '/notifications/', '/settings/', '/help/', '/recover/',
206
+ '/login/', '/ad_center/', '/saved/', '/stories/',
207
+ 'l.facebook.com', 'php?', 'checkpoint', 'dialog', 'sharer',
208
+ '/search/', '/people/', '/reel/', '/groups/feed/'
209
+ ];
210
+
211
+ if (searchType === 'pages') ignorePatterns.push('/groups/');
212
+ else if (searchType === 'groups') ignorePatterns.push('/pages/');
213
+
214
+ if (searchType !== 'people') ignorePatterns.push('/people/');
215
+
216
+ if (!cleanUrl.includes('profile.php') && (
217
+ ignorePatterns.some(p => cleanUrl.includes(p)) ||
218
+ cleanUrl.endsWith('/reel') ||
219
+ cleanUrl.endsWith('/marketplace') ||
220
+ cleanUrl.endsWith('/groups')
221
+ )) {
222
+ continue;
223
+ }
224
+
225
+ if (!cleanUrl.includes('profile.php')) {
226
+ const pathPart = cleanUrl.replace(/https?:\/\/(www\.)?facebook\.com/, '');
227
+ if (pathPart.length < 2) continue;
228
+ }
229
+
230
+ if (!urls.has(cleanUrl)) {
231
+ urls.set(cleanUrl, { name, image: image || '', verified });
232
+ countNew++;
233
+ if (onNewUrl) {
234
+ onNewUrl({ url: cleanUrl, name, image: image || '' });
235
+ }
236
+ } else if (name && name.length > (urls.get(cleanUrl).name || '').length) {
237
+ const current = urls.get(cleanUrl);
238
+ const bestImage = current.image || image || '';
239
+ urls.set(cleanUrl, { name, image: bestImage, verified: current.verified || verified });
240
+ if (onNewUrl) {
241
+ onNewUrl({ url: cleanUrl, name, image: bestImage, verified: current.verified || verified });
242
+ }
243
+ }
244
+ }
245
+ return countNew;
246
+ } catch (e) {
247
+ return 0;
248
+ }
249
+ };
250
+
251
+ // 3. Scroll loop
252
+ let lastHeight = await page.evaluate('document.body.scrollHeight');
253
+ let retries = 0;
254
+ const maxRetries = 10;
255
+
256
+ while (urls.size < 500) {
257
+ await extractVisibleUrls();
258
+
259
+ const endOfResults = await page.locator('text=End of results').first();
260
+ if (await endOfResults.isVisible()) break;
261
+
262
+ await page.keyboard.press('End');
263
+ await page.waitForTimeout(3000);
264
+ await page.evaluate('window.scrollTo(0, document.body.scrollHeight)');
265
+ await page.waitForTimeout(2000);
266
+
267
+ const newHeight = await page.evaluate('document.body.scrollHeight');
268
+ if (newHeight === lastHeight) {
269
+ retries++;
270
+ if (retries >= maxRetries) break;
271
+ } else {
272
+ retries = 0;
273
+ }
274
+ lastHeight = newHeight;
275
+ }
276
+
277
+ await extractVisibleUrls();
278
+ } finally {
279
+ await browser.close();
280
+ }
281
+
282
+ const results = Array.from(urls.entries()).map(([url, data]) => ({ url, name: data.name, image: data.image, verified: data.verified }));
283
+ return results.sort((a, b) => a.url.localeCompare(b.url));
284
+ }
285
+
286
+ export { extractFacebookUrls };
index.html ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <link rel="icon" type="image/svg+xml" href="/vite.svg" />
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
+ <title>SM Tools</title>
8
+ </head>
9
+ <body>
10
+ <div id="root"></div>
11
+ <script type="module" src="/src/main.jsx"></script>
12
+ </body>
13
+ </html>
instagram-search-main/igCookies.js ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { chromium } from 'playwright';
2
+
3
+ /**
4
+ * Launches Instagram in a persistent window for manual authentication.
5
+ * The browser will stay open until the user manually closes it.
6
+ * Cookies are captured continuously in the background.
7
+ */
8
+ async function launchInstagramAutoAuth() {
9
+ const isHeadless = process.env.HEADLESS !== 'false';
10
+ const browser = await chromium.launch({
11
+ headless: isHeadless,
12
+ args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu'],
13
+ // Use a slowMo for better visibility of what's happening (only useful in headed)
14
+ slowMo: isHeadless ? 0 : 50
15
+ });
16
+ const context = await browser.newContext();
17
+ const page = await context.newPage();
18
+
19
+ try {
20
+ console.log('[*] Opening Instagram...');
21
+ // Setting a generous timeout for navigation
22
+ await page.goto('https://www.instagram.com/accounts/login/', { timeout: 60000 });
23
+
24
+ console.log('[*] PERSISTENT MODE ACTIVE');
25
+ console.log('[*] Please perform your login manually in the browser window.');
26
+ console.log('[!] DO NOT CLOSE this terminal. CLOSE THE BROWSER WINDOW when you are finished.');
27
+
28
+ let capturedResult = null;
29
+
30
+ // MONITORING LOOP: Captures cookies continuously until the window is closed
31
+ // This ensures that even if the user navigates around, we get the latest stable session.
32
+ while (true) {
33
+ try {
34
+ // Check if user closed the window
35
+ if (page.isClosed()) {
36
+ console.log('[*] Browser window closed by user.');
37
+ break;
38
+ }
39
+
40
+ const cookies = await context.cookies();
41
+ const sessionid = cookies.find(c => c.name === 'sessionid')?.value;
42
+ const ds_user_id = cookies.find(c => c.name === 'ds_user_id')?.value;
43
+ const csrftoken = cookies.find(c => c.name === 'csrftoken')?.value;
44
+
45
+ if (sessionid && ds_user_id && csrftoken) {
46
+ if (!capturedResult) {
47
+ console.log('---------------------------------------------------------');
48
+ console.log('[✓] LOGIN DETECTED! Session cookies captured.');
49
+ console.log('[*] You can close the browser now or stay logged in.');
50
+ console.log('---------------------------------------------------------');
51
+ }
52
+
53
+ // Keep updating the result so we have the absolute latest state when they close
54
+ capturedResult = {
55
+ success: true,
56
+ sessionId: sessionid,
57
+ userId: ds_user_id,
58
+ csrfToken: csrftoken,
59
+ allCookies: cookies
60
+ };
61
+ }
62
+
63
+ // Poll every 2 seconds
64
+ await new Promise(r => setTimeout(r, 2000));
65
+ } catch (e) {
66
+ // Catching errors like "Target closed" during the poll
67
+ break;
68
+ }
69
+ }
70
+
71
+ if (capturedResult) {
72
+ return capturedResult;
73
+ } else {
74
+ return {
75
+ success: false,
76
+ error: 'Browser was closed without a detectable login session.'
77
+ };
78
+ }
79
+ } catch (e) {
80
+ console.error(`[!] Instagram Auth Error: ${e.message}`);
81
+ return { success: false, error: e.message };
82
+ } finally {
83
+ // Cleanup - though usually the user closure triggers this
84
+ try {
85
+ if (!page.isClosed()) {
86
+ await browser.close();
87
+ }
88
+ } catch (e) {}
89
+ }
90
+ }
91
+
92
+ export { launchInstagramAutoAuth };
package-lock.json ADDED
The diff for this file is too large to render. See raw diff
 
package.json ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "threat-hunting",
3
+ "private": true,
4
+ "version": "0.0.0",
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "vite",
8
+ "dev:all": "concurrently \"npm run dev\" \"npm run backend\"",
9
+ "backend": "node server.js",
10
+ "start": "node server.js",
11
+ "build": "vite build",
12
+ "lint": "eslint .",
13
+ "preview": "vite preview"
14
+ },
15
+ "dependencies": {
16
+ "cheerio": "^1.2.0",
17
+ "cors": "^2.8.6",
18
+ "dotenv": "^17.4.1",
19
+ "express": "^5.2.1",
20
+ "lucide-react": "^0.577.0",
21
+ "playwright": "^1.58.2",
22
+ "playwright-extra": "^4.3.6",
23
+ "puppeteer-extra-plugin-stealth": "^2.11.2",
24
+ "react": "^19.2.0",
25
+ "react-dom": "^19.2.0",
26
+ "telegram": "^2.26.22",
27
+ "util": "^0.12.5",
28
+ "xlsx": "^0.18.5"
29
+ },
30
+ "devDependencies": {
31
+ "@eslint/js": "^9.39.1",
32
+ "@tailwindcss/vite": "^4.2.1",
33
+ "@types/react": "^19.2.7",
34
+ "@types/react-dom": "^19.2.3",
35
+ "@vitejs/plugin-react": "^5.1.1",
36
+ "autoprefixer": "^10.4.27",
37
+ "concurrently": "^9.2.1",
38
+ "eslint": "^9.39.1",
39
+ "eslint-plugin-react-hooks": "^7.0.1",
40
+ "eslint-plugin-react-refresh": "^0.4.24",
41
+ "globals": "^16.5.0",
42
+ "postcss": "^8.5.8",
43
+ "tailwindcss": "^4.2.1",
44
+ "vite": "^7.3.1",
45
+ "vite-plugin-node-polyfills": "^0.25.0"
46
+ }
47
+ }
public/vite.svg ADDED
server.js ADDED
@@ -0,0 +1,494 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import express from 'express';
2
+ import path from 'path';
3
+ import fs from 'fs';
4
+ import https from 'https';
5
+ import http from 'http';
6
+ import { fileURLToPath } from 'url';
7
+ import dotenv from 'dotenv';
8
+ import cors from 'cors';
9
+
10
+ // Load environment variables
11
+ dotenv.config({ path: '.env.local' });
12
+ dotenv.config();
13
+
14
+ const __filename = fileURLToPath(import.meta.url);
15
+ const __dirname = path.dirname(__filename);
16
+
17
+ const app = express();
18
+ const PORT = process.env.PORT || 7860; // Use 7860 for Hugging Face by default
19
+
20
+ app.use(cors());
21
+ app.use(express.json());
22
+ app.use(express.static(path.join(__dirname, 'dist')));
23
+
24
+ // Root health check for Render/Uptime monitoring
25
+ app.get('/', (req, res) => {
26
+ res.json({
27
+ status: 'online',
28
+ service: 'OSINT Dashboard Backend',
29
+ mode: process.env.NODE_ENV || 'development'
30
+ });
31
+ });
32
+
33
+ // Helper function to fetch arbitrary URL with redirects
34
+ const fetchUrl = (urlStr, maxRedirects = 5, extraHeaders = {}, method = 'GET', body = null) => {
35
+ return new Promise((resolve, reject) => {
36
+ try {
37
+ const url = new URL(urlStr);
38
+ const client = url.protocol === 'https:' ? https : http;
39
+
40
+ const options = {
41
+ method,
42
+ rejectUnauthorized: false,
43
+ headers: {
44
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
45
+ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
46
+ ...extraHeaders
47
+ }
48
+ };
49
+
50
+ const req = client.request(url, options, (res) => {
51
+ try {
52
+ if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
53
+ if (maxRedirects === 0) {
54
+ reject(new Error('Too many redirects'));
55
+ return;
56
+ }
57
+ const redirUrl = new URL(res.headers.location, urlStr).href;
58
+ return resolve(fetchUrl(redirUrl, maxRedirects - 1, extraHeaders, method, body));
59
+ }
60
+
61
+ const data = [];
62
+ res.on('data', chunk => data.push(chunk));
63
+ res.on('end', () => {
64
+ resolve({
65
+ statusCode: res.statusCode,
66
+ headers: res.headers,
67
+ body: Buffer.concat(data),
68
+ finalUrl: urlStr
69
+ });
70
+ });
71
+ } catch (e) {
72
+ reject(e);
73
+ }
74
+ });
75
+
76
+ req.on('error', reject);
77
+ req.setTimeout(15000, () => {
78
+ req.destroy();
79
+ reject(new Error('Request Timeout'));
80
+ });
81
+
82
+ if (body) {
83
+ req.write(body);
84
+ }
85
+ req.end();
86
+ } catch (err) {
87
+ reject(err);
88
+ }
89
+ });
90
+ };
91
+
92
+ // --- API ROUTES ---
93
+
94
+ // 1. Instagram Search
95
+ app.post('/api/instagram/search', async (req, res) => {
96
+ try {
97
+ const { query } = req.body;
98
+ if (!query) return res.status(400).json({ error: 'Query is required' });
99
+
100
+ // Try file first, then env
101
+ const igPath = path.join(__dirname, 'instagram-search-main', 'ig_session.json');
102
+ let session = {};
103
+ if (fs.existsSync(igPath)) {
104
+ try { session = JSON.parse(fs.readFileSync(igPath, 'utf8')); } catch (e) {}
105
+ }
106
+
107
+ const sessionid = session.sessionId || process.env.VITE_INSTAGRAM_SESSION_ID;
108
+ const ds_user_id = session.userId || process.env.VITE_INSTAGRAM_USER_ID;
109
+ const csrftoken = session.csrfToken || process.env.VITE_INSTAGRAM_CSRF_TOKEN;
110
+ const allCookies = session.allCookies || [];
111
+
112
+ if (!sessionid || !ds_user_id || !csrftoken) {
113
+ return res.status(401).json({ error: 'Missing Instagram session cookies' });
114
+ }
115
+
116
+ // Build Cookie string from allCookies array if available, otherwise fallback to 3 tokens
117
+ let cookieString = `sessionid=${sessionid}; ds_user_id=${ds_user_id}; csrftoken=${csrftoken}`;
118
+ if (allCookies && allCookies.length > 0) {
119
+ cookieString = allCookies.map(c => `${c.name}=${c.value}`).join('; ');
120
+ }
121
+
122
+ const encodedQuery = encodeURIComponent(query);
123
+ const url = `https://www.instagram.com/api/v1/web/search/topsearch/?context=blended&include_reel=true&query=${encodedQuery}&search_surface=web_top_search`;
124
+
125
+ const igRes = await fetchUrl(url, 5, {
126
+ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
127
+ "X-Requested-With": "XMLHttpRequest",
128
+ "Referer": "https://www.instagram.com/",
129
+ "X-CSRFToken": csrftoken,
130
+ "Cookie": cookieString
131
+ });
132
+
133
+ if (igRes.statusCode !== 200) {
134
+ return res.status(igRes.statusCode).json({ error: `Instagram returned status ${igRes.statusCode}` });
135
+ }
136
+
137
+ res.status(200).json(JSON.parse(igRes.body.toString('utf-8')));
138
+ } catch (error) {
139
+ res.status(500).json({ error: error.message });
140
+ }
141
+ });
142
+
143
+ // Internal helper to save Instagram credentials
144
+ const internalSaveInstagramCookies = async (sessionId, userId, csrfToken, allCookies = null) => {
145
+ console.log(`[*] SAVING INSTAGRAM SESSION: ${userId}`);
146
+
147
+ // 1. Save to Memory
148
+ process.env.VITE_INSTAGRAM_SESSION_ID = sessionId;
149
+ process.env.VITE_INSTAGRAM_USER_ID = userId;
150
+ process.env.VITE_INSTAGRAM_CSRF_TOKEN = csrfToken;
151
+
152
+ // 2. Save to Session File (New robust method)
153
+ const igPath = path.resolve(process.cwd(), 'instagram-search-main', 'ig_session.json');
154
+ console.log(`[*] Writing session file: ${igPath}`);
155
+ fs.writeFileSync(igPath, JSON.stringify({ sessionId, userId, csrfToken, allCookies }, null, 2), 'utf8');
156
+
157
+ // 3. Update .env.local (Backup)
158
+ const envPath = path.resolve(process.cwd(), '.env.local');
159
+ let envContent = fs.existsSync(envPath) ? fs.readFileSync(envPath, 'utf8') : '';
160
+ const updates = { VITE_INSTAGRAM_SESSION_ID: sessionId, VITE_INSTAGRAM_USER_ID: userId, VITE_INSTAGRAM_CSRF_TOKEN: csrfToken };
161
+ if (allCookies) {
162
+ updates.VITE_INSTAGRAM_ALL_COOKIES = JSON.stringify(allCookies);
163
+ }
164
+ for (const [key, value] of Object.entries(updates)) {
165
+ const regex = new RegExp(`^${key}=.*$`, 'm');
166
+ envContent = regex.test(envContent) ? envContent.replace(regex, `${key}=${value}`) : envContent + `\n${key}=${value}`;
167
+ }
168
+ fs.writeFileSync(envPath, envContent.trim() + '\n', 'utf8');
169
+ };
170
+
171
+ // Internal helper to save Facebook credentials
172
+ const internalSaveFacebookCookies = async (cookies) => {
173
+ console.log(`[*] SAVING FACEBOOK SESSION`);
174
+ const fbPath = path.resolve(process.cwd(), 'facebook-search-main', 'fb_cookies.json');
175
+ fs.writeFileSync(fbPath, JSON.stringify(cookies, null, 2), 'utf8');
176
+
177
+ // Update .env.local (Backup)
178
+ const envPath = path.resolve(process.cwd(), '.env.local');
179
+ let envContent = fs.existsSync(envPath) ? fs.readFileSync(envPath, 'utf8') : '';
180
+ const val = JSON.stringify(cookies);
181
+ const key = 'VITE_FACEBOOK_COOKIES';
182
+ const regex = new RegExp(`^${key}=.*$`, 'm');
183
+ envContent = regex.test(envContent) ? envContent.replace(regex, `${key}=${val}`) : envContent + `\n${key}=${val}`;
184
+ fs.writeFileSync(envPath, envContent.trim() + '\n', 'utf8');
185
+ };
186
+
187
+ // Internal helper to save X credentials
188
+ const internalSaveXCookies = async (cookies) => {
189
+ console.log(`[*] SAVING X SESSION`);
190
+ const xPath = path.resolve(process.cwd(), 'x-search-master', 'x_cookies.json');
191
+ fs.writeFileSync(xPath, JSON.stringify(cookies, null, 2), 'utf8');
192
+
193
+ // Update .env.local (Backup)
194
+ const envPath = path.resolve(process.cwd(), '.env.local');
195
+ let envContent = fs.existsSync(envPath) ? fs.readFileSync(envPath, 'utf8') : '';
196
+ const val = JSON.stringify(cookies);
197
+ const key = 'VITE_X_COOKIES';
198
+ const regex = new RegExp(`^${key}=.*$`, 'm');
199
+ envContent = regex.test(envContent) ? envContent.replace(regex, `${key}=${val}`) : envContent + `\n${key}=${val}`;
200
+ fs.writeFileSync(envPath, envContent.trim() + '\n', 'utf8');
201
+ };
202
+
203
+ // 2. Instagram Auth
204
+ app.post('/api/instagram/auth-launch', async (req, res) => {
205
+ try {
206
+ const { username, password } = req.body;
207
+ const { launchInstagramAutoAuth } = await import('./instagram-search-main/igCookies.js');
208
+ const result = await launchInstagramAutoAuth({ username, password });
209
+
210
+ if (result.success) {
211
+ await internalSaveInstagramCookies(result.sessionId, result.userId, result.csrfToken, result.allCookies);
212
+ }
213
+
214
+ res.json(result);
215
+ } catch (e) {
216
+ res.status(500).json({ success: false, error: e.message });
217
+ }
218
+ });
219
+
220
+ app.post('/api/instagram/save-cookies', async (req, res) => {
221
+ try {
222
+ const { sessionId, userId, csrfToken, allCookies } = req.body;
223
+ console.log(`[INSTAGRAM] Received save-cookies request. allCookies type: ${typeof allCookies}`);
224
+
225
+ // Support either full cookies or 3 tokens for backward compatibility
226
+ if (allCookies && Array.isArray(allCookies)) {
227
+ console.log(`[INSTAGRAM] Parsing allCookies array (length: ${allCookies.length})`);
228
+ const sid = allCookies.find(c => c.name.toLowerCase() === 'sessionid')?.value;
229
+ const uid = allCookies.find(c => c.name.toLowerCase() === 'ds_user_id')?.value;
230
+ const csrf = allCookies.find(c => c.name.toLowerCase() === 'csrftoken')?.value;
231
+
232
+ console.log(`[INSTAGRAM] Extracted: sid=${sid ? 'FOUND' : 'MISSING'}, uid=${uid ? 'FOUND' : 'MISSING'}, csrf=${csrf ? 'FOUND' : 'MISSING'}`);
233
+ await internalSaveInstagramCookies(sid, uid, csrf, allCookies);
234
+ } else {
235
+ if (!sessionId || !userId || !csrfToken) {
236
+ console.error('[INSTAGRAM] Missing tokens in request body');
237
+ return res.status(400).json({ error: 'Missing required credentials' });
238
+ }
239
+ await internalSaveInstagramCookies(sessionId, userId, csrfToken);
240
+ }
241
+ res.json({ success: true });
242
+ } catch (error) {
243
+ console.error(`[INSTAGRAM] Save error: ${error.message}`);
244
+ res.status(400).json({ error: error.message });
245
+ }
246
+ });
247
+
248
+ // 3. Facebook Search (SSE)
249
+ app.post('/api/facebook/search', async (req, res) => {
250
+ try {
251
+ const { query, types } = req.body;
252
+ const searchTypes = (types && types.length > 0) ? types : ["pages", "groups"];
253
+ const { extractFacebookUrls } = await import('./facebook-search-main/fbSearch.js');
254
+
255
+ res.writeHead(200, {
256
+ 'Content-Type': 'text/event-stream',
257
+ 'Cache-Control': 'no-cache',
258
+ 'Connection': 'keep-alive',
259
+ 'X-Accel-Buffering': 'no' // Prevent buffering in some proxies
260
+ });
261
+
262
+ const onNewUrl = (item) => {
263
+ res.write(`data: ${JSON.stringify({ type: 'partial', data: { term: query, type: 'result', ...item } })}\n\n`);
264
+ };
265
+
266
+ for (const type of searchTypes) {
267
+ res.write(`data: ${JSON.stringify({ type: 'progress', data: `Searching Facebook ${type}...` })}\n\n`);
268
+ try {
269
+ const onProgress = (msg) => {
270
+ res.write(`data: ${JSON.stringify({ type: 'progress', data: msg })}\n\n`);
271
+ };
272
+
273
+ await extractFacebookUrls(query, type, onNewUrl, onProgress);
274
+ } catch (err) {
275
+ res.write(`data: ${JSON.stringify({ type: 'error', error: `Failed searching ${type}: ${err.message}` })}\n\n`);
276
+ }
277
+ }
278
+ res.write(`data: ${JSON.stringify({ type: 'done', success: true })}\n\n`);
279
+ res.end();
280
+ } catch (e) {
281
+ res.status(400).json({ error: e.message });
282
+ }
283
+ });
284
+
285
+ // 4. Facebook Auth
286
+ app.post('/api/facebook/auth-launch', async (req, res) => {
287
+ try {
288
+ const { launchFacebookAutoAuth } = await import('./facebook-search-main/fbCookies.js');
289
+ const result = await launchFacebookAutoAuth();
290
+ res.json(result);
291
+ } catch (e) {
292
+ res.status(500).json({ success: false, error: e.message });
293
+ }
294
+ });
295
+
296
+ app.post('/api/facebook/save-cookies', async (req, res) => {
297
+ try {
298
+ const { cookies } = req.body;
299
+ if (!cookies) return res.status(400).json({ error: 'Missing cookies' });
300
+ await internalSaveFacebookCookies(cookies);
301
+ res.json({ success: true });
302
+ } catch (e) {
303
+ res.status(400).json({ error: e.message });
304
+ }
305
+ });
306
+
307
+ app.post('/api/x/save-cookies', async (req, res) => {
308
+ try {
309
+ const { cookies } = req.body;
310
+ if (!cookies) return res.status(400).json({ error: 'Missing cookies' });
311
+
312
+ // Accept string and parse if needed
313
+ const cookieData = typeof cookies === 'string' ? JSON.parse(cookies) : cookies;
314
+ await internalSaveXCookies(cookieData);
315
+ res.json({ success: true });
316
+ } catch (e) {
317
+ res.status(400).json({ error: e.message });
318
+ }
319
+ });
320
+
321
+ // 5. X Search (SSE)
322
+ app.post('/api/x/search', async (req, res) => {
323
+ try {
324
+ const { query } = req.body;
325
+ const { extractXUserUrls } = await import('./x-search-master/xSearch.js');
326
+
327
+ res.writeHead(200, {
328
+ 'Content-Type': 'text/event-stream',
329
+ 'Cache-Control': 'no-cache',
330
+ 'Connection': 'keep-alive'
331
+ });
332
+
333
+ const onNewUrl = (url, name, avatar, verified) => {
334
+ res.write(`data: ${JSON.stringify({ type: 'partial', data: { url, name, avatar, verified } })}\n\n`);
335
+ };
336
+
337
+ const onProgress = (msg) => {
338
+ res.write(`data: ${JSON.stringify({ type: 'progress', data: msg })}\n\n`);
339
+ };
340
+
341
+ await extractXUserUrls(query, onNewUrl, onProgress);
342
+ res.write(`data: ${JSON.stringify({ type: 'done', success: true })}\n\n`);
343
+ res.end();
344
+ } catch (e) {
345
+ res.status(400).json({ error: e.message });
346
+ }
347
+ });
348
+
349
+ // 6. X Auth
350
+ app.post('/api/x/auth-launch', async (req, res) => {
351
+ try {
352
+ const { launchXAutoAuth } = await import('./x-search-master/xCookies.js');
353
+ const result = await launchXAutoAuth();
354
+ res.json(result);
355
+ } catch (e) {
356
+ res.status(500).json({ success: false, error: e.message });
357
+ }
358
+ });
359
+
360
+ // 7. TikTok Search (SSE)
361
+ app.post('/api/tiktok/search', async (req, res) => {
362
+ try {
363
+ const { query } = req.body;
364
+ const { extractTikTokUrls } = await import('./tiktok-search-main/tiktokSearch.js');
365
+
366
+ res.writeHead(200, {
367
+ 'Content-Type': 'text/event-stream',
368
+ 'Cache-Control': 'no-cache',
369
+ 'Connection': 'keep-alive'
370
+ });
371
+
372
+ const onNewUrl = (item) => {
373
+ res.write(`data: ${JSON.stringify({ type: 'partial', data: { term: query, type: 'result', ...item } })}\n\n`);
374
+ };
375
+
376
+ const onProgress = (msg) => {
377
+ res.write(`data: ${JSON.stringify({ type: 'progress', data: msg })}\n\n`);
378
+ };
379
+
380
+ await extractTikTokUrls(query, onNewUrl, onProgress);
381
+ res.write(`data: ${JSON.stringify({ type: 'done', success: true })}\n\n`);
382
+ res.end();
383
+ } catch (e) {
384
+ console.error(`[TIKTOK] Search failed for "${req.body?.query}":`, e);
385
+ res.status(400).json({ error: e.message || 'Unknown TikTok search error' });
386
+ }
387
+ });
388
+
389
+ // 7.5 Auth Status Check
390
+ app.get('/api/auth/status', (req, res) => {
391
+ const getStat = (p, label = '') => {
392
+ try {
393
+ const exists = fs.existsSync(p);
394
+ if (label) console.log(`[STATUS] Checking ${label}: ${exists} at ${p}`);
395
+ if (exists) {
396
+ const s = fs.statSync(p);
397
+ return {
398
+ status: true,
399
+ detail: s.isDirectory() ? 'DIR_ACTIVE' : `${(s.size / 1024).toFixed(1)}KB`,
400
+ updated: s.mtime.toISOString().split('T')[0]
401
+ };
402
+ }
403
+ } catch (e) {
404
+ console.error(`[STATUS] Error checking ${label}:`, e.message);
405
+ }
406
+ return { status: false, detail: 'MISSING', updated: null };
407
+ };
408
+
409
+ const fbPath = path.resolve(process.cwd(), 'facebook-search-main', 'fb_cookies.json');
410
+ const xPath = path.resolve(process.cwd(), 'x-search-master', 'x_user_data');
411
+ const xCookiePath = path.resolve(process.cwd(), 'x-search-master', 'x_cookies.json');
412
+ const igPath = path.resolve(process.cwd(), 'instagram-search-main', 'ig_session.json');
413
+
414
+ res.json({
415
+ facebook: getStat(fbPath, 'Facebook'),
416
+ x: fs.existsSync(xCookiePath) ? getStat(xCookiePath, 'X (Cookies)') : getStat(xPath, 'X (Profile)'),
417
+ instagram: getStat(igPath, 'Instagram'),
418
+ tiktok: {
419
+ status: true,
420
+ detail: 'PUBLIC_ACCESS',
421
+ updated: 'LIVE'
422
+ }
423
+ });
424
+ });
425
+
426
+ // Debug endpoint for session verification
427
+ app.get('/api/debug/:platform-file', (req, res) => {
428
+ const { platform } = req.params;
429
+ let filePath = '';
430
+ if (platform === 'ig') filePath = path.resolve(process.cwd(), 'instagram-search-main', 'ig_session.json');
431
+ else if (platform === 'fb') filePath = path.resolve(process.cwd(), 'facebook-search-main', 'fb_cookies.json');
432
+ else if (platform === 'x') filePath = path.resolve(process.cwd(), 'x-search-master', 'x_cookies.json');
433
+
434
+ if (filePath && fs.existsSync(filePath)) {
435
+ res.json({ exists: true, content: JSON.parse(fs.readFileSync(filePath, 'utf8')) });
436
+ } else {
437
+ res.status(404).json({ exists: false, path: filePath });
438
+ }
439
+ });
440
+
441
+ // 8. Proxy Image
442
+ app.get('/api/proxy-image', async (req, res) => {
443
+ const targetUrl = req.query.url;
444
+ if (!targetUrl) return res.status(400).send('Missing url parameter');
445
+
446
+ try {
447
+ const url = new URL(targetUrl);
448
+ const extraHeaders = {
449
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
450
+ };
451
+
452
+ // Spoof Referer/Origin for common CDNs to bypass hotlink protection
453
+ if (url.hostname.includes('instagram.com')) {
454
+ extraHeaders['Referer'] = 'https://www.instagram.com/';
455
+ extraHeaders['Origin'] = 'https://www.instagram.com';
456
+ } else if (url.hostname.includes('fbcdn.net')) {
457
+ extraHeaders['Referer'] = 'https://www.facebook.com/';
458
+ extraHeaders['Origin'] = 'https://www.facebook.com';
459
+ } else if (url.hostname.includes('twimg.com')) {
460
+ extraHeaders['Referer'] = 'https://twitter.com/';
461
+ } else if (url.hostname.includes('tiktok.com') || url.hostname.includes('ttwstatic.com')) {
462
+ extraHeaders['Referer'] = 'https://www.tiktok.com/';
463
+ }
464
+
465
+ const proxyRes = await fetchUrl(targetUrl, 5, extraHeaders);
466
+
467
+ if (proxyRes.statusCode !== 200) {
468
+ console.error(`Proxy failed for ${targetUrl}: ${proxyRes.statusCode}`);
469
+ return res.status(proxyRes.statusCode).send('Failed to fetch image');
470
+ }
471
+
472
+ const contentType = proxyRes.headers['content-type'] || 'image/jpeg';
473
+ res.setHeader('Content-Type', contentType);
474
+ res.setHeader('Cache-Control', 'public, max-age=31536000');
475
+ res.send(proxyRes.body);
476
+ } catch (e) {
477
+ res.status(500).send('Internal Server Error: ' + e.message);
478
+ }
479
+ });
480
+
481
+ // 9. SPA Fallback (Serve index.html for all other routes)
482
+ app.get('*', (req, res) => {
483
+ const indexPath = path.join(__dirname, 'dist', 'index.html');
484
+ if (fs.existsSync(indexPath)) {
485
+ res.sendFile(indexPath);
486
+ } else {
487
+ res.status(404).send('Dashboard dist not found. Please run npm run build.');
488
+ }
489
+ });
490
+
491
+ // --- SERVER START ---
492
+ app.listen(PORT, () => {
493
+ console.log(`Server running on port ${PORT}`);
494
+ });
src/App.css ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ /* App-specific overrides – kept minimal since index.css owns the design system */
2
+ #root {
3
+ max-width: 100%;
4
+ margin: 0;
5
+ padding: 0;
6
+ text-align: left;
7
+ }
src/App.jsx ADDED
@@ -0,0 +1,1744 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState, useEffect, useRef } from 'react';
2
+ import { Api, TelegramClient } from 'telegram';
3
+ import { StringSession } from 'telegram/sessions';
4
+ import * as XLSX from 'xlsx';
5
+ import { Facebook, Twitter, Send, Instagram, Menu, X, Globe, Search, Database, FileText, Upload, Shield, Square, User, Users, Bell, ExternalLink } from 'lucide-react';
6
+ import InstagramSearch from './components/InstagramSearch';
7
+ import FacebookSearch from './components/FacebookSearch';
8
+ import XSearch from './components/XSearch';
9
+ import TikTokSearch from './components/TikTokSearch';
10
+ import { Music2 } from 'lucide-react';
11
+ import { getApiUrl } from './config';
12
+
13
+ // User must provide these in .env.local
14
+ const apiId = Number(import.meta.env.VITE_TELEGRAM_API_ID) || 0;
15
+ const apiHash = import.meta.env.VITE_TELEGRAM_API_HASH || "";
16
+
17
+ // Simple range expander in JS. Equivalent to Python's extend_search_patterns
18
+ function expandRange(pattern) {
19
+ const chars = [];
20
+ const regex = /([a-z0-9])-([a-z0-9])/gi;
21
+ let match;
22
+ while ((match = regex.exec(pattern)) !== null) {
23
+ const start = match[1].charCodeAt(0);
24
+ const end = match[2].charCodeAt(0);
25
+ for (let c = start; c <= end; c++) {
26
+ chars.push(String.fromCharCode(c));
27
+
28
+ }
29
+ }
30
+ return chars;
31
+ }
32
+
33
+ function expandSearchPatterns(terms) {
34
+ const expandedTerms = [];
35
+ for (const term of terms) {
36
+ const matches = [...term.matchAll(/\[([^\[\]]+)\]/g)];
37
+ if (matches.length === 0) {
38
+ expandedTerms.push(term);
39
+ continue;
40
+ }
41
+
42
+ const staticParts = [];
43
+ const dynamicCharSets = [];
44
+ let lastEnd = 0;
45
+
46
+ for (const match of matches) {
47
+ staticParts.push(term.slice(lastEnd, match.index));
48
+ const pattern = match[1];
49
+
50
+ const ranges = pattern.match(/[a-z0-9]-[a-z0-9]/gi);
51
+ const singles = pattern.replace(/[a-z0-9]-[a-z0-9]/gi, '');
52
+
53
+ const charset = ranges ? expandRange(pattern) : [];
54
+ charset.push(...singles.split(''));
55
+ dynamicCharSets.push(charset);
56
+ lastEnd = match.index + match[0].length;
57
+ }
58
+ staticParts.push(term.slice(lastEnd));
59
+
60
+ // Cartesian product
61
+ const cartesianProduct = (arr) => arr.reduce((a, b) =>
62
+ a.flatMap(d => b.map(e => [d, e].flat()))
63
+ );
64
+
65
+ // We handle the edge case where dynamicCharSets only has 1 array differently
66
+ const combos = dynamicCharSets.length === 1 ? dynamicCharSets[0].map(x => [x]) : cartesianProduct(dynamicCharSets);
67
+
68
+ for (const combo of combos) {
69
+ let newTerm = '';
70
+ for (let i = 0; i < staticParts.length; i++) {
71
+ newTerm += staticParts[i] + (combo[i] !== undefined ? combo[i] : '');
72
+ }
73
+ expandedTerms.push(newTerm);
74
+ }
75
+ }
76
+ return expandedTerms;
77
+ }
78
+
79
+ export default function App() {
80
+ const [client, setClient] = useState(null);
81
+ const [sessionString, setSessionString] = useState('');
82
+ const [step, setStep] = useState('phone'); // phone, code, dashboard
83
+ const [activeTab, setActiveTab] = useState(() => localStorage.getItem('lastActiveTab') || 'telegram');
84
+ const isRemote = !!import.meta.env.VITE_API_URL;
85
+ const [platformsAuth, setPlatformsAuth] = useState({
86
+ telegram: { status: false, detail: 'OFFLINE', updated: null },
87
+ facebook: { status: false, detail: 'MISSING', updated: null },
88
+ x: { status: false, detail: 'MISSING', updated: null },
89
+ instagram: { status: false, detail: 'MISSING', updated: null },
90
+ tiktok: { status: true, detail: 'PUBLIC_ACCESS', updated: 'LIVE' }
91
+ });
92
+ const [expansion, setExpansion] = useState('none');
93
+ const [localSearchTerm, setLocalSearchTerm] = useState('');
94
+
95
+ // Auth state
96
+ const [phone, setPhone] = useState('');
97
+ const [phoneCodeHash, setPhoneCodeHash] = useState('');
98
+ const [code, setCode] = useState('');
99
+ const [loading, setLoading] = useState(false);
100
+ const [error, setError] = useState('');
101
+
102
+ // Search state - Telegram
103
+ const [tgSearchTerm, setTgSearchTerm] = useState('');
104
+ const [tgResults, setTgResults] = useState([]);
105
+ const [isTgSearching, setIsTgSearching] = useState(false);
106
+ const [tgSearchMode, setTgSearchMode] = useState('none');
107
+ const [tgProgress, setTgProgress] = useState(null);
108
+ const [tgError, setTgError] = useState('');
109
+
110
+
111
+ // Search state - Instagram
112
+ const [igSearchTerm, setIgSearchTerm] = useState('');
113
+ const [igResults, setIgResults] = useState([]);
114
+ const [isIgSearching, setIsIgSearching] = useState(false);
115
+ const [igProgress, setIgProgress] = useState(null);
116
+ const [igError, setIgError] = useState('');
117
+ const [igSearchMode, setIgSearchMode] = useState('none');
118
+
119
+ // Search state - Facebook
120
+ const [fbSearchTerm, setFbSearchTerm] = useState('');
121
+ const [fbResults, setFbResults] = useState([]);
122
+ const [isFbSearching, setIsFbSearching] = useState(false);
123
+ const [fbError, setFbError] = useState('');
124
+ const [fbSearchTypes, setFbSearchTypes] = useState(['pages']);
125
+ const [fbSearchMode, setFbSearchMode] = useState('none');
126
+ const [fbProgress, setFbProgress] = useState(null);
127
+ const fbAbortControllerRef = useRef(null);
128
+
129
+ const [xSearchTerm, setXSearchTerm] = useState('');
130
+ const [xResults, setXResults] = useState([]);
131
+ const [isXSearching, setIsXSearching] = useState(false);
132
+ const [xError, setXError] = useState('');
133
+ const xAbortControllerRef = useRef(null);
134
+ const [xProgress, setXProgress] = useState(null);
135
+
136
+ // Search state - TikTok
137
+ const [ttSearchTerm, setTtSearchTerm] = useState('');
138
+ const [ttResults, setTtResults] = useState([]);
139
+ const [isTtSearching, setIsTtSearching] = useState(false);
140
+ const [ttError, setTtError] = useState('');
141
+ const [ttProgress, setTtProgress] = useState(null);
142
+ const ttAbortControllerRef = useRef(null);
143
+ const [isFirstAuthCheckDone, setIsFirstAuthCheckDone] = useState(false);
144
+ const checkAllAuth = async () => {
145
+ try {
146
+ const resp = await fetch(getApiUrl('/api/auth/status'));
147
+ if (resp.ok) {
148
+ const data = await resp.json();
149
+ const hasTg = !!localStorage.getItem('telegramSession');
150
+ setPlatformsAuth(prev => ({
151
+ ...prev,
152
+ ...data,
153
+ telegram: {
154
+ status: hasTg,
155
+ detail: hasTg ? 'SESSION_ID_FOUND' : 'OFFLINE',
156
+ updated: hasTg ? 'LIVE' : null
157
+ }
158
+ }));
159
+ }
160
+ } catch (e) {
161
+ console.error('[AUTH] Status check failed:', e);
162
+ } finally {
163
+ setIsFirstAuthCheckDone(true);
164
+ }
165
+ };
166
+
167
+ useEffect(() => {
168
+ localStorage.setItem('lastActiveTab', activeTab);
169
+ }, [activeTab]);
170
+
171
+ useEffect(() => {
172
+ checkAllAuth();
173
+ const interval = setInterval(checkAllAuth, 10000); // Poll every 10s
174
+ return () => clearInterval(interval);
175
+ }, []);
176
+
177
+ useEffect(() => {
178
+ if (activeTab === 'telegram') setLocalSearchTerm(tgSearchTerm);
179
+ else if (activeTab === 'instagram') setLocalSearchTerm(igSearchTerm);
180
+ else if (activeTab === 'facebook') setLocalSearchTerm(fbSearchTerm);
181
+ else if (activeTab === 'tiktok') setLocalSearchTerm(ttSearchTerm);
182
+ else setLocalSearchTerm(xSearchTerm);
183
+ }, [activeTab, tgSearchTerm, igSearchTerm, fbSearchTerm, ttSearchTerm, xSearchTerm]);
184
+
185
+ const stopFacebookSearch = () => {
186
+ if (fbAbortControllerRef.current) {
187
+ fbAbortControllerRef.current.abort();
188
+ fbAbortControllerRef.current = null;
189
+ }
190
+ };
191
+
192
+ const stopXSearch = () => {
193
+ if (xAbortControllerRef.current) {
194
+ xAbortControllerRef.current.abort();
195
+ xAbortControllerRef.current = null;
196
+ }
197
+ };
198
+
199
+ const stopTikTokSearch = () => {
200
+ if (ttAbortControllerRef.current) {
201
+ ttAbortControllerRef.current.abort();
202
+ ttAbortControllerRef.current = null;
203
+ }
204
+ };
205
+
206
+ // Auth state - Facebook
207
+ const [showFbAuth, setShowFbAuth] = useState(false);
208
+ const [fbAuthInput, setFbAuthInput] = useState(localStorage.getItem('fb_auth_input') || '');
209
+ const [isFbAuthenticating, setIsFbAuthenticating] = useState(false);
210
+ const [fbAuthError, setFbAuthError] = useState('');
211
+ const [fbAuthSuccess, setFbAuthSuccess] = useState(false);
212
+
213
+ // Auth state - Instagram
214
+ const [igAuthInput, setIgAuthInput] = useState(localStorage.getItem('ig_auth_input') || '');
215
+ useEffect(() => { localStorage.setItem('ig_auth_input', igAuthInput); }, [igAuthInput]);
216
+ const [igUsername, setIgUsername] = useState(localStorage.getItem('ig_username') || 'adarshs1780');
217
+ const [igPassword, setIgPassword] = useState(localStorage.getItem('ig_password') || '@J6Ku8HFTM3y,Af');
218
+ const [isIgAuthenticating, setIsIgAuthenticating] = useState(false);
219
+ const [igAuthError, setIgAuthError] = useState('');
220
+ const [showIgAuth, setShowIgAuth] = useState(false);
221
+ const [igAuthSuccess, setIgAuthSuccess] = useState(false);
222
+
223
+ // Auth state - X (Twitter)
224
+ const [showXAuth, setShowXAuth] = useState(false);
225
+ const [xAuthInput, setXAuthInput] = useState(localStorage.getItem('x_auth_input') || '');
226
+ const [isXAuthenticating, setIsXAuthenticating] = useState(false);
227
+ const [xAuthError, setXAuthError] = useState('');
228
+ const [xAuthSuccess, setXAuthSuccess] = useState(false);
229
+
230
+ // Sidebar state
231
+ const [sidebarOpen, setSidebarOpen] = useState(false);
232
+
233
+ useEffect(() => {
234
+ // Auto load session from localStorage
235
+ const savedSession = localStorage.getItem('telegramSession');
236
+ if (apiId && apiHash) {
237
+ if (savedSession) {
238
+ setSessionString(savedSession);
239
+ initClient(savedSession);
240
+ } else {
241
+ const initialSession = new StringSession("");
242
+ const tc = new TelegramClient(initialSession, apiId, apiHash, { connectionRetries: 5 });
243
+ setClient(tc);
244
+ }
245
+ } else {
246
+ console.warn("[TELEGRAM] Skipping initialization: API ID or Hash missing.");
247
+ }
248
+ }, []);
249
+
250
+ useEffect(() => {
251
+ localStorage.setItem('ig_username', igUsername);
252
+ localStorage.setItem('ig_password', igPassword);
253
+ localStorage.setItem('ig_auth_input', igAuthInput);
254
+ localStorage.setItem('fb_auth_input', fbAuthInput);
255
+ localStorage.setItem('x_auth_input', xAuthInput);
256
+ }, [igUsername, igPassword, igAuthInput, fbAuthInput, xAuthInput]);
257
+
258
+ const initClient = async (savedSession) => {
259
+ try {
260
+ setLoading(true);
261
+ const stringSession = new StringSession(savedSession);
262
+ const tc = new TelegramClient(stringSession, apiId, apiHash, {
263
+ connectionRetries: 5,
264
+ });
265
+ await tc.connect();
266
+
267
+ // Verify login is still valid
268
+ const isAuth = await tc.checkAuthorization();
269
+ if (isAuth) {
270
+ setClient(tc);
271
+ setStep('dashboard');
272
+ } else {
273
+ localStorage.removeItem('telegramSession');
274
+ if (apiId && apiHash) {
275
+ setClient(new TelegramClient(new StringSession(""), apiId, apiHash, { connectionRetries: 5 }));
276
+ }
277
+ setStep('phone');
278
+ }
279
+ } catch (err) {
280
+ console.error(err);
281
+ setError("Failed to init Telegram Client");
282
+ } finally {
283
+ setLoading(false);
284
+ }
285
+ };
286
+
287
+ const sendCode = async () => {
288
+ if (!client || !apiId || !apiHash) {
289
+ setError('Telegram API credentials missing. Please set them in environment variables.');
290
+ return;
291
+ }
292
+ try {
293
+ setError('');
294
+ setLoading(true);
295
+ await client.connect();
296
+ const result = await client.sendCode(
297
+ {
298
+ apiId: apiId,
299
+ apiHash: apiHash,
300
+ },
301
+ phone
302
+ );
303
+ setPhoneCodeHash(result.phoneCodeHash);
304
+ setStep('code');
305
+ } catch (err) {
306
+ console.error(err);
307
+ setError(err.message || 'Failed to send code.');
308
+ } finally {
309
+ setLoading(false);
310
+ }
311
+ };
312
+
313
+ const verifyCode = async () => {
314
+ try {
315
+ setError('');
316
+ setLoading(true);
317
+
318
+ await client.invoke(
319
+ new Api.auth.SignIn({
320
+ phoneNumber: phone,
321
+ phoneCodeHash: phoneCodeHash,
322
+ phoneCode: code,
323
+ })
324
+ );
325
+
326
+ const newSessionString = client.session.save();
327
+ localStorage.setItem('telegramSession', newSessionString);
328
+ setSessionString(newSessionString);
329
+ setStep('dashboard');
330
+ } catch (err) {
331
+ console.error(err);
332
+ setError(err.message || 'Verification failed. Password might be needed.');
333
+ } finally {
334
+ setLoading(false);
335
+ }
336
+ };
337
+
338
+ const logout = async () => {
339
+ localStorage.removeItem('telegramSession');
340
+ setSessionString('');
341
+ setStep('phone');
342
+ if (client) await client.disconnect();
343
+ setTgResults([]);
344
+ // Setup fresh client
345
+ if (apiId && apiHash) {
346
+ setClient(new TelegramClient(new StringSession(""), apiId, apiHash, { connectionRetries: 5 }));
347
+ } else {
348
+ setClient(null);
349
+ }
350
+ };
351
+
352
+ const performSearch = async (term) => {
353
+ try {
354
+ const result = await client.invoke(
355
+ new Api.contacts.Search({
356
+ q: term,
357
+ limit: 50,
358
+ })
359
+ );
360
+
361
+ const bufferToBase64 = (buffer) => {
362
+ if (!buffer || buffer.length === 0) return null;
363
+ let binary = '';
364
+ const bytes = new Uint8Array(buffer);
365
+ const len = bytes.byteLength;
366
+ for (let i = 0; i < len; i++) {
367
+ binary += String.fromCharCode(bytes[i]);
368
+ }
369
+ return `data:image/jpeg;base64,${window.btoa(binary)}`;
370
+ };
371
+
372
+ const newResults = [];
373
+ for (const user of result.users) {
374
+ if (user.username) {
375
+ let image = null;
376
+ try {
377
+ const photoBuffer = await client.downloadProfilePhoto(user);
378
+ image = bufferToBase64(photoBuffer);
379
+ } catch (e) {
380
+ console.warn(`Failed to download photo for ${user.username}`, e);
381
+ }
382
+
383
+ newResults.push({
384
+ search_term: term,
385
+ type: 'user',
386
+ name: `${user.firstName || ''} ${user.lastName || ''}`.trim(),
387
+ username: user.username,
388
+ url: `https://t.me/${user.username}`,
389
+ image: image
390
+ });
391
+ }
392
+ }
393
+
394
+ for (const chat of result.chats) {
395
+ if (chat.username) {
396
+ let image = null;
397
+ try {
398
+ const photoBuffer = await client.downloadProfilePhoto(chat);
399
+ image = bufferToBase64(photoBuffer);
400
+ } catch (e) {
401
+ console.warn(`Failed to download photo for ${chat.username}`, e);
402
+ }
403
+
404
+ newResults.push({
405
+ search_term: term,
406
+ type: chat.broadcast ? 'channel' : 'group',
407
+ name: chat.title,
408
+ username: chat.username,
409
+ url: `https://t.me/${chat.username}`,
410
+ image: image
411
+ });
412
+ }
413
+ }
414
+ return newResults;
415
+ } catch (err) {
416
+ console.error(`Search failed for ${term}`, err);
417
+ return [];
418
+ }
419
+ };
420
+
421
+ const startSearch = async () => {
422
+ if (!tgSearchTerm) return;
423
+
424
+ let termsToProcess = [tgSearchTerm];
425
+ if (!tgSearchTerm.match(/\[.*?\]/)) {
426
+ if (tgSearchMode !== 'none') {
427
+ termsToProcess = [`${tgSearchTerm}[${tgSearchMode}]`];
428
+ }
429
+ }
430
+
431
+ const expandedTerms = expandSearchPatterns(termsToProcess);
432
+ const finalTerms = [...new Set([tgSearchTerm.replace(/\[.*?\]/, ''), ...expandedTerms])].filter(Boolean);
433
+
434
+ setIsTgSearching(true);
435
+ setTgResults([]);
436
+ setTgError('');
437
+
438
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
439
+ const BATCH_SIZE = 3;
440
+
441
+ for (let i = 0; i < finalTerms.length; i += BATCH_SIZE) {
442
+ const chunk = finalTerms.slice(i, i + BATCH_SIZE);
443
+ setTgProgress(`Searching batch: ${chunk.join(', ')} (${Math.min(i + BATCH_SIZE, finalTerms.length)}/${finalTerms.length})`);
444
+
445
+ const results = await Promise.all(chunk.map(term => performSearch(term)));
446
+
447
+ // Merge and deduplicate
448
+ setTgResults(prev => {
449
+ const flat = [...prev, ...results.flat()];
450
+ return Array.from(new Map(flat.map(item => [item.url, item])).values());
451
+ });
452
+
453
+ if (i + BATCH_SIZE < finalTerms.length) {
454
+ await sleep(5000);
455
+ }
456
+ }
457
+
458
+ setIsTgSearching(false);
459
+ setTgProgress('Search Complete!');
460
+ };
461
+
462
+ const exportExcel = () => {
463
+ let dataToExport = [];
464
+ let fileName = '';
465
+
466
+ if (activeTab === 'telegram') {
467
+ if (tgResults.length === 0) return;
468
+ dataToExport = tgResults;
469
+ const baseTerm = tgSearchTerm.replace(/\[/g, '').replace(/\]/g, '') || 'results';
470
+ fileName = `telegram_search_${baseTerm}`;
471
+ } else if (activeTab === 'instagram') {
472
+ if (igResults.length === 0) return;
473
+ dataToExport = igResults.map(r => ({
474
+ 'Full Name': r.user.full_name,
475
+ 'Username': r.user.username,
476
+ 'Profile URL': `https://www.instagram.com/${r.user.username}/`,
477
+ 'Is Private': r.user.is_private ? 'Yes' : 'No',
478
+ 'Is Verified': r.user.is_verified ? 'Yes' : 'No'
479
+ }));
480
+ fileName = `instagram_${igSearchTerm}`;
481
+ } else if (activeTab === 'facebook') {
482
+ if (fbResults.length === 0) return;
483
+ dataToExport = fbResults.map(r => {
484
+ const cleanUrl = r.url.replace('https://www.facebook.com/', '').replace('http://www.facebook.com/', '').split('?')[0].replace(/\/$/, '');
485
+ const fallbackUsername = cleanUrl.split('/').pop() || 'Facebook User';
486
+ return {
487
+ 'Type': r.type.charAt(0).toUpperCase() + r.type.slice(1),
488
+ 'Name': r.name || fallbackUsername,
489
+ 'Profile URL': r.url,
490
+ 'Search Term': r.term
491
+ };
492
+ });
493
+ fileName = `facebook_${fbSearchTerm}`;
494
+ } else if (activeTab === 'x') {
495
+ if (xResults.length === 0) return;
496
+ dataToExport = xResults.map(r => ({
497
+ 'Name': r.name,
498
+ 'Username': r.username,
499
+ 'Profile URL': r.url,
500
+ 'Bio': r.bio,
501
+ 'Followers': r.followers,
502
+ 'Following': r.following,
503
+ 'Tweets': r.tweets,
504
+ 'Verified': r.verified ? 'Yes' : 'No',
505
+ 'Location': r.location,
506
+ 'Website': r.website,
507
+ }));
508
+ fileName = `x_search_${xSearchTerm}`;
509
+ } else if (activeTab === 'tiktok') {
510
+ if (ttResults.length === 0) return;
511
+ dataToExport = ttResults.map(r => ({
512
+ 'Username': r.username,
513
+ 'Nickname': r.nickname,
514
+ 'Profile URL': r.url,
515
+ }));
516
+ fileName = `tiktok_search_${ttSearchTerm}`;
517
+ } else {
518
+ return;
519
+ }
520
+
521
+ const ws = XLSX.utils.json_to_sheet(dataToExport);
522
+ const wb = XLSX.utils.book_new();
523
+ XLSX.utils.book_append_sheet(wb, ws, "Results");
524
+
525
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
526
+ XLSX.writeFile(wb, `${fileName}_${timestamp}.xlsx`);
527
+ };
528
+
529
+
530
+ const performInstagramSearch = async () => {
531
+ if (!igSearchTerm) return;
532
+
533
+ let patterns = [igSearchTerm];
534
+ if (!igSearchTerm.match(/\[.*?\]/)) {
535
+ if (igSearchMode !== 'none') {
536
+ patterns = [`${igSearchTerm}[${igSearchMode}]`];
537
+ }
538
+ }
539
+ const expanded = expandSearchPatterns(patterns);
540
+ const finalQueries = [...new Set([igSearchTerm.replace(/\[.*?\]/, ''), ...expanded])].filter(Boolean);
541
+
542
+ setIsIgSearching(true);
543
+ setIgResults([]);
544
+ setIgError('');
545
+
546
+ const sleep = (ms) => new Promise(r => setTimeout(r, ms));
547
+ const BATCH_SIZE = 2; // Strict limit for IG
548
+ const seen = new Set();
549
+ let combinedResults = [];
550
+
551
+ try {
552
+ for (let i = 0; i < finalQueries.length; i += BATCH_SIZE) {
553
+ const chunk = finalQueries.slice(i, i + BATCH_SIZE);
554
+ setIgProgress(`Searching IG batch: ${chunk.join(', ')} (${Math.min(i + BATCH_SIZE, finalQueries.length)}/${finalQueries.length})`);
555
+
556
+ const responses = await Promise.all(chunk.map(query =>
557
+ fetch(getApiUrl('/api/instagram/search'), {
558
+ method: 'POST',
559
+ headers: { 'Content-Type': 'application/json' },
560
+ body: JSON.stringify({ query })
561
+ })
562
+ ));
563
+
564
+ for (const resp of responses) {
565
+ if (resp.status === 401) {
566
+ throw new Error("Instagram authentication failed. Please update cookies in Dashboard.");
567
+ }
568
+ if (!resp.ok) continue;
569
+
570
+ const data = await resp.json();
571
+ if (data.users) {
572
+ data.users.forEach(u => {
573
+ if (!seen.has(u.user.username)) {
574
+ seen.add(u.user.username);
575
+ combinedResults.push(u);
576
+ }
577
+ });
578
+ }
579
+ }
580
+
581
+ setIgResults([...combinedResults]);
582
+
583
+ if (i + BATCH_SIZE < finalQueries.length) {
584
+ await sleep(5000); // Respect IG rate limits
585
+ }
586
+ }
587
+ setIgProgress(null);
588
+ } catch (err) {
589
+ if (err.message.includes('Instagram authentication failed')) {
590
+ setIgError("Authentication failed or missing cookies. Launching Instagram Login auto-configurator...");
591
+ setShowIgAuth(true);
592
+ } else {
593
+ setIgError(err.message);
594
+ }
595
+ setIgProgress(null);
596
+ } finally {
597
+ setIsIgSearching(false);
598
+ }
599
+ };
600
+
601
+ const launchFacebookAutoAuth = async () => {
602
+ if (isRemote) return;
603
+ setIsFbAuthenticating(true);
604
+ setFbAuthError('');
605
+ setFbAuthSuccess(false);
606
+ try {
607
+ const resp = await fetch(getApiUrl('/api/facebook/auth-launch'), { method: 'POST' });
608
+ const data = await resp.json();
609
+ if (!resp.ok || !data.success) throw new Error(data.error || 'Failed to authenticate');
610
+ setFbAuthSuccess(true);
611
+ setFbError('');
612
+ setTimeout(() => { setShowFbAuth(false); setFbAuthSuccess(false); }, 2000);
613
+ } catch (err) {
614
+ setFbAuthError(err.message);
615
+ } finally {
616
+ setIsFbAuthenticating(false);
617
+ }
618
+ };
619
+
620
+
621
+
622
+ const performFacebookSearch = async () => {
623
+ if (!fbSearchTerm) return;
624
+ setIsFbSearching(true);
625
+ setFbResults([]);
626
+ setFbError('');
627
+
628
+ fbAbortControllerRef.current = new AbortController();
629
+
630
+ try {
631
+ const resp = await fetch(getApiUrl('/api/facebook/search'), {
632
+ method: 'POST',
633
+ headers: { 'Content-Type': 'application/json' },
634
+ body: JSON.stringify({ query: fbSearchTerm, types: fbSearchTypes }),
635
+ signal: fbAbortControllerRef.current.signal
636
+ }).catch(err => {
637
+ if (err.name === 'AbortError') throw err;
638
+ throw new Error("Failed to connect to the backend server. Ensure 'npm run dev:all' is running.");
639
+ });
640
+
641
+ if (!resp.ok) {
642
+ if (resp.status === 401 || resp.status === 403) {
643
+ setFbError("Authentication failed. Please check your cookies in the configuration panel.");
644
+ setShowFbAuth(true);
645
+ return;
646
+ }
647
+ let msg = `Server error: ${resp.status}`;
648
+ try { const d = await resp.json(); msg = d.error || msg; } catch (e) { }
649
+ throw new Error(msg);
650
+ }
651
+
652
+ const reader = resp.body.getReader();
653
+ const decoder = new TextDecoder();
654
+ let buffer = '';
655
+
656
+ while (true) {
657
+ const { value, done } = await reader.read();
658
+ if (done) break;
659
+
660
+ buffer += decoder.decode(value, { stream: true });
661
+ const lines = buffer.split('\n');
662
+ buffer = lines.pop() || '';
663
+
664
+ for (const line of lines) {
665
+ if (line.startsWith('data: ')) {
666
+ try {
667
+ const data = JSON.parse(line.slice(6));
668
+ if (data.type === 'partial') {
669
+ setFbResults(prev => {
670
+ const existingIdx = prev.findIndex(x => x.url === data.data.url);
671
+ if (existingIdx !== -1) {
672
+ const existing = prev[existingIdx];
673
+ const incoming = data.data;
674
+ // Update if name is longer OR if incoming has an image and existing doesn't
675
+ if ((incoming.name && incoming.name.length > (existing.name || '').length) || (incoming.image && !existing.image)) {
676
+ const copy = [...prev];
677
+ copy[existingIdx] = { ...existing, ...incoming };
678
+ return copy;
679
+ }
680
+ return prev;
681
+ }
682
+ return [...prev, data.data];
683
+ });
684
+ } else if (data.type === 'error') {
685
+ throw new Error(data.error);
686
+ }
687
+ } catch (e) {
688
+ if (e.message !== "Unexpected end of JSON input" && !e.message.startsWith("Unexpected token")) {
689
+ throw e;
690
+ }
691
+ }
692
+ }
693
+ }
694
+ }
695
+
696
+ } catch (err) {
697
+ if (err.name === 'AbortError') {
698
+ const errorMsg = 'Search stopped by user.';
699
+ setFbError(errorMsg);
700
+ return;
701
+ }
702
+ if (err.message.includes('FACEBOOK_AUTH_EXPIRED') || err.message.includes('fb_cookies.json not found')) {
703
+ setFbError("Authentication expired or missing cookies. Launching Facebook Login auto-configurator...");
704
+ setShowFbAuth(true);
705
+ launchFacebookAutoAuth();
706
+ } else {
707
+ setFbError(err.message);
708
+ }
709
+ } finally {
710
+ setIsFbSearching(false);
711
+ }
712
+ };
713
+
714
+ const performFacebookDeepSearch = async () => {
715
+ if (!fbSearchTerm) return;
716
+ setIsFbSearching(true);
717
+ setFbResults([]);
718
+ setFbError('');
719
+ setFbProgress('Initializing Facebook deep search...');
720
+
721
+ fbAbortControllerRef.current = new AbortController();
722
+
723
+ try {
724
+ let charSet = [];
725
+ if (fbSearchMode === 'a-z') charSet = 'abcdefghijklmnopqrstuvwxyz'.split('');
726
+ else if (fbSearchMode === '0-9') charSet = '0123456789'.split('');
727
+ else if (fbSearchMode === 'a-z0-9') charSet = 'abcdefghijklmnopqrstuvwxyz0123456789'.split('');
728
+
729
+ const resultsMap = new Map();
730
+ const BATCH_SIZE = 2; // Keep low for browser sessions
731
+
732
+ for (let i = 0; i < charSet.length; i += BATCH_SIZE) {
733
+ if (fbAbortControllerRef.current.signal.aborted) break;
734
+
735
+ const chunk = charSet.slice(i, i + BATCH_SIZE);
736
+ setFbProgress(`Searching FB batch: ${chunk.join(', ')} (${Math.min(i + BATCH_SIZE, charSet.length)}/${charSet.length})`);
737
+
738
+ await Promise.all(chunk.map(async (char) => {
739
+ const currentQuery = `${fbSearchTerm} ${char}`;
740
+ try {
741
+ const resp = await fetch(getApiUrl('/api/facebook/search'), {
742
+ method: 'POST',
743
+ headers: { 'Content-Type': 'application/json' },
744
+ body: JSON.stringify({ query: currentQuery, types: fbSearchTypes }),
745
+ signal: fbAbortControllerRef.current.signal
746
+ });
747
+
748
+ if (!resp.ok) return;
749
+
750
+ const reader = resp.body.getReader();
751
+ const decoder = new TextDecoder();
752
+ let buffer = '';
753
+
754
+ while (true) {
755
+ const { value, done } = await reader.read();
756
+ if (done) break;
757
+
758
+ buffer += decoder.decode(value, { stream: true });
759
+ const lines = buffer.split('\n');
760
+ buffer = lines.pop() || '';
761
+
762
+ for (const line of lines) {
763
+ if (line.startsWith('data: ')) {
764
+ try {
765
+ const data = JSON.parse(line.slice(6));
766
+ if (data.type === 'partial') {
767
+ const item = data.data;
768
+ if (!resultsMap.has(item.url)) {
769
+ resultsMap.set(item.url, item);
770
+ setFbResults(Array.from(resultsMap.values()));
771
+ }
772
+ }
773
+ } catch (e) { }
774
+ }
775
+ }
776
+ }
777
+ } catch (e) {
778
+ if (e.name !== 'AbortError') console.error(`FB Error for ${char}:`, e);
779
+ }
780
+ }));
781
+ }
782
+
783
+ setFbProgress(null);
784
+ } catch (err) {
785
+ if (err.name === 'AbortError') {
786
+ setFbError('Search stopped by user.');
787
+ } else {
788
+ setFbError(err.message);
789
+ }
790
+ setFbProgress(null);
791
+ } finally {
792
+ setIsFbSearching(false);
793
+ }
794
+ };
795
+
796
+ const launchXAutoAuth = async () => {
797
+ setIsXAuthenticating(true);
798
+ setXAuthError('');
799
+ setXAuthSuccess(false);
800
+ try {
801
+ const resp = await fetch(getApiUrl('/api/x/auth-launch'), { method: 'POST' });
802
+ const data = await resp.json();
803
+ if (!resp.ok || !data.success) throw new Error(data.error || 'Failed to authenticate');
804
+ setXAuthSuccess(true);
805
+ setXError('');
806
+ setTimeout(() => { setShowXAuth(false); setXAuthSuccess(false); }, 2000);
807
+ } catch (err) {
808
+ setXAuthError(err.message);
809
+ } finally {
810
+ setIsXAuthenticating(false);
811
+ }
812
+ };
813
+
814
+
815
+
816
+ const performXSearch = async () => {
817
+ if (!xSearchTerm) return;
818
+ setIsXSearching(true);
819
+ setXResults([]);
820
+ setXError('');
821
+ setXProgress('Starting X (Twitter) search...');
822
+
823
+ xAbortControllerRef.current = new AbortController();
824
+
825
+ try {
826
+ const resp = await fetch(getApiUrl('/api/x/search'), {
827
+ method: 'POST',
828
+ headers: { 'Content-Type': 'application/json' },
829
+ body: JSON.stringify({ query: xSearchTerm }),
830
+ signal: xAbortControllerRef.current.signal
831
+ });
832
+
833
+ if (!resp.ok) {
834
+ let msg = 'Failed to search X (Twitter)';
835
+ try { const d = await resp.json(); msg = d.error || msg; } catch (e) { }
836
+ throw new Error(msg);
837
+ }
838
+
839
+ const reader = resp.body.getReader();
840
+ const decoder = new TextDecoder();
841
+ let buffer = '';
842
+
843
+ while (true) {
844
+ const { value, done } = await reader.read();
845
+ if (done) break;
846
+
847
+ buffer += decoder.decode(value, { stream: true });
848
+ const lines = buffer.split('\n');
849
+ buffer = lines.pop() || '';
850
+
851
+ for (const line of lines) {
852
+ if (line.startsWith('data: ')) {
853
+ try {
854
+ const data = JSON.parse(line.slice(6));
855
+ if (data.type === 'partial') {
856
+ setXResults(prev => {
857
+ const existingIdx = prev.findIndex(x => x.url === data.data.url);
858
+ if (existingIdx !== -1) {
859
+ // Update existing entry if more complete data arrives
860
+ const copy = [...prev];
861
+ copy[existingIdx] = { ...copy[existingIdx], ...data.data };
862
+ return copy;
863
+ }
864
+ return [...prev, data.data];
865
+ });
866
+ setXProgress(`Found ${xResults.length + 1} results for "${xSearchTerm}"...`);
867
+ } else if (data.type === 'progress') {
868
+ setXProgress(data.message);
869
+ } else if (data.type === 'error') {
870
+ throw new Error(data.error);
871
+ }
872
+ } catch (e) {
873
+ if (e.message !== "Unexpected end of JSON input" && !e.message.startsWith("Unexpected token")) {
874
+ throw e;
875
+ }
876
+ }
877
+ }
878
+ }
879
+ }
880
+ setXProgress(`Search complete! Found ${xResults.length} results.`);
881
+
882
+ } catch (err) {
883
+ if (err.name === 'AbortError') {
884
+ setXError('Search stopped by user.');
885
+ setXProgress(null);
886
+ return;
887
+ }
888
+ if (err.message.includes('X_AUTH_EXPIRED') || err.message.includes('x_cookies.json not found')) {
889
+ setXError("Authentication required for X (Twitter).");
890
+ setShowXAuth(true);
891
+ if (!isRemote) {
892
+ launchXAutoAuth();
893
+ }
894
+ } else {
895
+ setXError(err.message);
896
+ }
897
+ setXProgress(null);
898
+ } finally {
899
+ setIsXSearching(false);
900
+ }
901
+ };
902
+
903
+ const performTikTokSearch = async () => {
904
+ if (!ttSearchTerm) return;
905
+ setIsTtSearching(true);
906
+ setTtResults([]);
907
+ setTtError('');
908
+ setTtProgress('Starting TikTok search...');
909
+
910
+ ttAbortControllerRef.current = new AbortController();
911
+
912
+ try {
913
+ const resp = await fetch(getApiUrl('/api/tiktok/search'), {
914
+ method: 'POST',
915
+ headers: { 'Content-Type': 'application/json' },
916
+ body: JSON.stringify({ query: ttSearchTerm }),
917
+ signal: ttAbortControllerRef.current.signal
918
+ });
919
+
920
+ if (!resp.ok) {
921
+ let msg = 'Failed to search TikTok';
922
+ try { const d = await resp.json(); msg = d.error || msg; } catch (e) { }
923
+ throw new Error(msg);
924
+ }
925
+
926
+ const reader = resp.body.getReader();
927
+ const decoder = new TextDecoder();
928
+ let buffer = '';
929
+
930
+ while (true) {
931
+ const { value, done } = await reader.read();
932
+ if (done) break;
933
+
934
+ buffer += decoder.decode(value, { stream: true });
935
+ const lines = buffer.split('\n');
936
+ buffer = lines.pop() || '';
937
+
938
+ for (const line of lines) {
939
+ if (line.startsWith('data: ')) {
940
+ try {
941
+ const data = JSON.parse(line.slice(6));
942
+ if (data.type === 'partial') {
943
+ setTtResults(prev => {
944
+ if (prev.some(x => x.url === data.data.url)) return prev;
945
+ return [...prev, data.data];
946
+ });
947
+ } else if (data.type === 'progress') {
948
+ setTtProgress(data.data);
949
+ } else if (data.type === 'error') {
950
+ throw new Error(data.error);
951
+ }
952
+ } catch (e) {
953
+ if (e.message.includes('API credentials') || e.message.includes('TikTok') || e.message.includes('Navigation')) {
954
+ throw e; // Bubble up important errors
955
+ }
956
+ }
957
+ }
958
+ }
959
+ }
960
+ setTtProgress(null);
961
+
962
+ } catch (err) {
963
+ if (err.name === 'AbortError') {
964
+ setTtError('Search stopped by user.');
965
+ } else {
966
+ setTtError(err.message);
967
+ }
968
+ setTtProgress(null);
969
+ } finally {
970
+ setIsTtSearching(false);
971
+ }
972
+ };
973
+
974
+ const launchInstagramAutoAuth = async () => {
975
+ setIsIgAuthenticating(true);
976
+ setIgAuthError('');
977
+ setIgAuthSuccess(false);
978
+ try {
979
+ const resp = await fetch(getApiUrl('/api/instagram/auth-launch'), {
980
+ method: 'POST',
981
+ headers: { 'Content-Type': 'application/json' },
982
+ body: JSON.stringify({ username: igUsername, password: igPassword })
983
+ });
984
+ const data = await resp.json();
985
+ if (!resp.ok || !data.success) throw new Error(data.error || 'Failed to authenticate');
986
+
987
+ // The backend handles saving these; we just need to know it succeeded
988
+ setIgAuthSuccess(true);
989
+ setIgError('');
990
+
991
+ // Trigger instant status check
992
+ setTimeout(checkAllAuth, 500);
993
+
994
+ setTimeout(() => { setShowIgAuth(false); setIgAuthSuccess(false); }, 2000);
995
+ } catch (err) {
996
+ setIgAuthError(err.message);
997
+ } finally {
998
+ setIsIgAuthenticating(false);
999
+ }
1000
+ };
1001
+
1002
+ const saveInstagramCookies = async () => {
1003
+ if (!igAuthInput) {
1004
+ setIgAuthError('Please paste the cookies JSON array.');
1005
+ return;
1006
+ }
1007
+
1008
+ setIsIgAuthenticating(true);
1009
+ setIgAuthError('');
1010
+ setIgAuthSuccess(false);
1011
+
1012
+ try {
1013
+ let rawInput = igAuthInput.trim();
1014
+ let allCookies;
1015
+
1016
+ try {
1017
+ // First pass: try standard parse
1018
+ allCookies = JSON.parse(rawInput);
1019
+
1020
+ // Second pass: if user pasted a JSON string wrapped in quotes (stringified JSON)
1021
+ if (typeof allCookies === 'string') {
1022
+ allCookies = JSON.parse(allCookies);
1023
+ }
1024
+
1025
+ if (!Array.isArray(allCookies)) {
1026
+ throw new Error('Input is valid JSON but not an array of cookies.');
1027
+ }
1028
+ } catch (e) {
1029
+ if (e.message.includes('JSON but not an array')) throw e;
1030
+ throw new Error(`JSON Error: Please ensure you paste a valid [ { ... } ] array. (${e.message})`);
1031
+ }
1032
+
1033
+ const response = await fetch(getApiUrl('/api/instagram/save-cookies'), {
1034
+ method: 'POST',
1035
+ headers: {
1036
+ 'Content-Type': 'application/json'
1037
+ },
1038
+ body: JSON.stringify({ allCookies })
1039
+ });
1040
+
1041
+ if (!response.ok) {
1042
+ let errorMsg = 'Failed to save cookies';
1043
+ try {
1044
+ const errData = await response.json();
1045
+ errorMsg = errData.error || errorMsg;
1046
+ } catch (e) { }
1047
+ throw new Error(errorMsg);
1048
+ }
1049
+
1050
+ setIgAuthSuccess(true);
1051
+ setIgError(''); // Clear search errors if any
1052
+
1053
+ // Trigger instant status check
1054
+ setTimeout(checkAllAuth, 100);
1055
+
1056
+ setTimeout(() => {
1057
+ setShowIgAuth(false);
1058
+ setIgAuthSuccess(false);
1059
+ }, 2000);
1060
+ } catch (err) {
1061
+ setIgAuthError(err.message);
1062
+ } finally {
1063
+ setIsIgAuthenticating(false);
1064
+ }
1065
+ };
1066
+
1067
+ const saveFacebookCookies = async () => {
1068
+ if (!fbAuthInput) {
1069
+ setFbAuthError('Cookies data is required.');
1070
+ return;
1071
+ }
1072
+
1073
+ setIsFbAuthenticating(true);
1074
+ setFbAuthError('');
1075
+ setFbAuthSuccess(false);
1076
+
1077
+ try {
1078
+ // Clean input (handle standard JSON format)
1079
+ let cookies;
1080
+ try {
1081
+ cookies = JSON.parse(fbAuthInput);
1082
+ } catch (e) {
1083
+ throw new Error('Invalid JSON format for cookies.');
1084
+ }
1085
+
1086
+ const response = await fetch(getApiUrl('/api/facebook/save-cookies'), {
1087
+ method: 'POST',
1088
+ headers: { 'Content-Type': 'application/json' },
1089
+ body: JSON.stringify({ cookies })
1090
+ });
1091
+
1092
+ if (!response.ok) throw new Error('Failed to save Facebook cookies');
1093
+
1094
+ setFbAuthSuccess(true);
1095
+ setTimeout(checkAllAuth, 500);
1096
+ setTimeout(() => { setShowFbAuth(false); setFbAuthSuccess(false); }, 2000);
1097
+ } catch (err) {
1098
+ setFbAuthError(err.message);
1099
+ } finally {
1100
+ setIsFbAuthenticating(false);
1101
+ }
1102
+ };
1103
+
1104
+ const saveXCookies = async () => {
1105
+ if (!xAuthInput) {
1106
+ setXAuthError('Cookies data is required.');
1107
+ return;
1108
+ }
1109
+
1110
+ setIsXAuthenticating(true);
1111
+ setXAuthError('');
1112
+ setXAuthSuccess(false);
1113
+
1114
+ try {
1115
+ const response = await fetch(getApiUrl('/api/x/save-cookies'), {
1116
+ method: 'POST',
1117
+ headers: { 'Content-Type': 'application/json' },
1118
+ body: JSON.stringify({ cookies: xAuthInput })
1119
+ });
1120
+
1121
+ if (!response.ok) throw new Error('Failed to save X cookies');
1122
+
1123
+ setXAuthSuccess(true);
1124
+ setTimeout(checkAllAuth, 500);
1125
+ setTimeout(() => { setShowXAuth(false); setXAuthSuccess(false); }, 2000);
1126
+ } catch (err) {
1127
+ setXAuthError(err.message);
1128
+ } finally {
1129
+ setIsXAuthenticating(false);
1130
+ }
1131
+ };
1132
+
1133
+
1134
+ const LoginRequired = ({ platform, onLogin }) => {
1135
+ const icons = {
1136
+ telegram: <Send size={32} />,
1137
+ facebook: <Facebook size={32} />,
1138
+ x: <Twitter size={32} />,
1139
+ instagram: <Instagram size={32} />
1140
+ };
1141
+ const colors = {
1142
+ telegram: 'var(--p-telegram)',
1143
+ facebook: 'var(--p-facebook)',
1144
+ x: 'var(--text-bright)',
1145
+ instagram: 'var(--p-instagram)'
1146
+ };
1147
+
1148
+ return (
1149
+ <div className="flex flex-col items-center justify-center py-16 px-4 bg-black/40 rounded-lg border border-dashed anim-fade-in" style={{ borderColor: 'var(--line)' }}>
1150
+ <div className="mb-4 opacity-50" style={{ color: colors[platform] }}>
1151
+ {icons[platform]}
1152
+ </div>
1153
+ <h3 className="text-lg font-bold mb-1 uppercase tracking-widest" style={{ color: 'var(--text-bright)' }}>Session Inactive</h3>
1154
+ <p className="text-xs font-mono mb-6 text-center max-w-sm" style={{ color: 'var(--text-ghost)' }}>
1155
+ System requires an active <span style={{ color: colors[platform] }}>{platform.toUpperCase()}</span> session to authorize search requests.
1156
+ </p>
1157
+ <button onClick={onLogin} className="btn-primary flex items-center gap-2 group">
1158
+ <Shield size={14} className="group-hover:rotate-12 transition-transform" />
1159
+ AUTHORIZE SESSION
1160
+ </button>
1161
+ </div>
1162
+ );
1163
+ };
1164
+
1165
+ const StatusBadge = ({ platform }) => {
1166
+ const auth = platformsAuth[platform] || { status: false, detail: 'OFFLINE' };
1167
+ if (platform === 'status') return null;
1168
+ return (
1169
+ <div className="flex items-center gap-2 ml-auto">
1170
+ <div className={`flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[9px] font-mono border ${auth.status ? 'bg-green-500/5 border-green-500/20 text-green-500' : 'bg-red-500/5 border-red-500/20 text-red-400'}`}>
1171
+ <div className={`w-1 h-1 rounded-full ${auth.status ? 'bg-green-500 shadow-[0_0_4px_rgba(34,197,94,0.5)]' : 'bg-red-500'}`} />
1172
+ <span>{auth.status ? 'CONNECTED' : 'SESSION_INACTIVE'}</span>
1173
+ <span className="opacity-40 select-none">|</span>
1174
+ <span className="opacity-80">{auth.detail}</span>
1175
+ </div>
1176
+ </div>
1177
+ );
1178
+ };
1179
+
1180
+ const StatusHub = () => {
1181
+ const activeSearches = Object.entries(searchStates).filter(([_, busy]) => busy);
1182
+
1183
+ return (
1184
+ <div className="space-y-6 anim-fade-up">
1185
+ {activeSearches.length > 0 && (
1186
+ <div className="panel p-4 border-cyan-500/30 bg-cyan-500/5">
1187
+ <h3 className="text-xs font-bold font-mono mb-3 flex items-center gap-2" style={{ color: 'var(--neon-cyan)' }}>
1188
+ <div className="w-2 h-2 rounded-full bg-cyan-500 animate-pulse" />
1189
+ LIVE_ACTIVITY_MONITOR [{activeSearches.length}]
1190
+ </h3>
1191
+ <div className="space-y-3">
1192
+ {activeSearches.map(([platform, _]) => {
1193
+ const progress = platform === 'telegram' ? tgProgress :
1194
+ platform === 'instagram' ? igProgress :
1195
+ platform === 'facebook' ? fbProgress :
1196
+ platform === 'tiktok' ? ttProgress : xProgress;
1197
+ const resultsCount = platform === 'telegram' ? tgResults.length :
1198
+ platform === 'instagram' ? igResults.length :
1199
+ platform === 'facebook' ? fbResults.length :
1200
+ platform === 'tiktok' ? ttResults.length : xResults.length;
1201
+
1202
+ return (
1203
+ <div key={platform} className="flex flex-col gap-1 p-2 rounded bg-black/40 border border-white/5">
1204
+ <div className="flex justify-between items-center">
1205
+ <span className="text-[10px] font-bold uppercase" style={{ color: platforms[platform].accent }}>{platform}</span>
1206
+ <span className="text-[10px] font-mono opacity-60">{resultsCount} results found</span>
1207
+ </div>
1208
+ <div className="flex items-center gap-3">
1209
+ <div className="flex-grow bg-white/5 h-1 rounded-full overflow-hidden">
1210
+ <div className="h-full bg-cyan-500 animate-pulse" style={{ width: '100%' }} />
1211
+ </div>
1212
+ <span className="text-[9px] font-mono truncate max-w-[200px] opacity-80">{progress || 'Processing...'}</span>
1213
+ </div>
1214
+ </div>
1215
+ );
1216
+ })}
1217
+ </div>
1218
+ </div>
1219
+ )}
1220
+
1221
+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
1222
+ {Object.entries(platforms).filter(([k]) => k !== 'status').map(([key, p]) => {
1223
+ const auth = platformsAuth[key] || { status: false, detail: 'UNKNOWN', updated: null };
1224
+ const Icon = p.icon;
1225
+ return (
1226
+ <div key={key} className="status-card h-full flex flex-col">
1227
+ <div className="status-card-header">
1228
+ <div className="flex items-center gap-2">
1229
+ <Icon size={16} style={{ color: p.accent }} />
1230
+ <span className="font-bold text-xs tracking-wider uppercase">{p.label}</span>
1231
+ </div>
1232
+ <div className={`status-pill ${auth.status ? 'online' : 'offline'}`}>
1233
+ {auth.status ? 'ONLINE' : 'OFFLINE'}
1234
+ </div>
1235
+ </div>
1236
+ <div className="status-card-body flex-grow">
1237
+ <div className="space-y-2 mb-4">
1238
+ <div className="flex justify-between items-center bg-black/20 p-2 rounded border border-white/5">
1239
+ <span className="text-[10px] uppercase text-ghost">Local Storage</span>
1240
+ <span className="text-[10px] font-mono text-bright">{auth.detail}</span>
1241
+ </div>
1242
+ <div className="flex justify-between items-center bg-black/20 p-2 rounded border border-white/5">
1243
+ <span className="text-[10px] uppercase text-ghost">Sync Status</span>
1244
+ <span className="text-[10px] font-mono text-bright">{auth.updated || 'NEVER'}</span>
1245
+ </div>
1246
+ </div>
1247
+ <button onClick={() => setActiveTab(key)}
1248
+ className="btn-dim w-full text-[10px] font-mono py-2 flex items-center justify-center gap-2 group">
1249
+ <ExternalLink size={12} className="group-hover:translate-x-0.5 group-hover:-translate-y-0.5 transition-transform" />
1250
+ GOTO_{key.toUpperCase()}
1251
+ </button>
1252
+ </div>
1253
+ </div>
1254
+ );
1255
+ })}
1256
+ </div>
1257
+ </div>
1258
+ );
1259
+ };
1260
+
1261
+ // Platform config
1262
+ const platforms = {
1263
+ status: { icon: Database, label: 'STATUS', accent: 'var(--neon-cyan)' },
1264
+ telegram: { icon: Send, label: 'Telegram', accent: 'var(--p-telegram)' },
1265
+ facebook: { icon: Facebook, label: 'Facebook', accent: 'var(--p-facebook)' },
1266
+ x: { icon: Twitter, label: 'X', accent: 'var(--p-x)' },
1267
+ tiktok: { icon: Music2, label: 'TikTok', accent: 'var(--p-tiktok)' },
1268
+ instagram: { icon: Instagram, label: 'Instagram', accent: 'var(--p-instagram)' },
1269
+ };
1270
+ const cur = platforms[activeTab] || platforms.telegram;
1271
+ const CurIcon = cur.icon;
1272
+
1273
+ const searchStates = {
1274
+ telegram: isTgSearching,
1275
+ instagram: isIgSearching,
1276
+ facebook: isFbSearching,
1277
+ tiktok: isTtSearching,
1278
+ x: isXSearching
1279
+ };
1280
+
1281
+ const busy = activeTab === 'status' ? false : searchStates[activeTab] || false;
1282
+
1283
+ const curTerm = activeTab === 'status' ? '' :
1284
+ activeTab === 'telegram' ? tgSearchTerm :
1285
+ activeTab === 'instagram' ? igSearchTerm :
1286
+ activeTab === 'facebook' ? fbSearchTerm :
1287
+ activeTab === 'tiktok' ? ttSearchTerm : xSearchTerm;
1288
+
1289
+ return (
1290
+ <div className="min-h-screen flex flex-col" style={{ color: 'var(--text-normal)' }}>
1291
+ {/* Scanline overlay */}
1292
+ <div className="scanline-overlay" />
1293
+
1294
+ {/* ═══ TOP NAV ═══ */}
1295
+ <nav className="topnav">
1296
+ {/* Brand */}
1297
+ <div className="flex items-center gap-2 mr-6 select-none">
1298
+ <Shield size={18} style={{ color: 'var(--neon-cyan)' }} />
1299
+ <span className="text-sm font-bold tracking-tight text-neon font-mono">SM:TOOLS</span>
1300
+ <span className="hidden sm:inline text-[9px] font-mono py-0.5 px-1.5 rounded ml-1"
1301
+ style={{ background: 'var(--neon-cyan-glow)', color: 'var(--neon-cyan-dim)', border: '1px solid rgba(0,240,255,0.15)' }}>
1302
+ OSINT
1303
+ </span>
1304
+ </div>
1305
+
1306
+ {/* Tabs */}
1307
+ <div className="flex items-center gap-1">
1308
+ {Object.entries(platforms).map(([key, p]) => {
1309
+ const Icon = p.icon;
1310
+ const isActive = activeTab === key;
1311
+ const authInfo = platformsAuth[key] || { status: false };
1312
+ const isAuth = authInfo.status;
1313
+
1314
+ return (
1315
+ <button key={key} onClick={() => { setActiveTab(key); setSidebarOpen(false); }}
1316
+ className={`nav-tab ${isActive ? 'active' : ''} relative`}>
1317
+ <Icon size={15} style={isActive ? { color: 'var(--neon-cyan)' } : undefined} />
1318
+ <span className="hidden md:inline">{p.label}</span>
1319
+ {key !== 'status' && (
1320
+ <div className="absolute -top-1 -right-1 flex gap-0.5">
1321
+ {searchStates[key] && (
1322
+ <div className="w-2 h-2 rounded-full bg-cyan-400 animate-ping opacity-75" />
1323
+ )}
1324
+ <div className={`status-dot-mini ${isAuth ? 'bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.4)]' : 'bg-red-500 shadow-[0_0_8px_rgba(239,68,68,0.4)]'}`}
1325
+ title={isAuth ? 'Connected' : 'Login Required'} />
1326
+ </div>
1327
+ )}
1328
+ </button>
1329
+ );
1330
+ })}
1331
+ </div>
1332
+
1333
+ {/* Right side */}
1334
+ <div className="ml-auto flex items-center gap-3">
1335
+ {activeTab === 'telegram' && step === 'dashboard' && (
1336
+ <button onClick={logout} className="btn-dim text-[10px]">SIGN OUT</button>
1337
+ )}
1338
+ <a href="http://github.com/InvertedShu" target="_blank" rel="noopener noreferrer"
1339
+ className="flex items-center gap-1.5 px-2 py-1 rounded transition-all"
1340
+ style={{ color: 'var(--text-dim)', border: '1px solid var(--line)' }}
1341
+ onMouseEnter={e => { e.currentTarget.style.color = 'var(--neon-cyan)'; e.currentTarget.style.borderColor = 'rgba(0,240,255,0.25)'; e.currentTarget.style.boxShadow = '0 0 12px rgba(0,240,255,0.1)'; }}
1342
+ onMouseLeave={e => { e.currentTarget.style.color = 'var(--text-dim)'; e.currentTarget.style.borderColor = 'var(--line)'; e.currentTarget.style.boxShadow = 'none'; }}>
1343
+ <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z"/></svg>
1344
+ <span className="text-[10px] font-mono hidden sm:inline">by <span style={{ color: 'var(--neon-cyan-dim)' }}>InvertedShu</span></span>
1345
+ </a>
1346
+ <div className="status-dot" />
1347
+ </div>
1348
+ </nav>
1349
+
1350
+ {/* ═══ MAIN ═══ */}
1351
+ <main className="flex-1 px-4 md:px-8 py-6 max-w-6xl mx-auto w-full">
1352
+
1353
+ {/* Page header */}
1354
+ <div className="mb-6 anim-fade-up">
1355
+ <div className="flex items-center gap-3 mb-1">
1356
+ <CurIcon size={18} style={{ color: cur.accent }} />
1357
+ <h1 className="text-xl font-bold" style={{ color: 'var(--text-bright)' }}>{cur.label} <span className="font-mono text-sm" style={{ color: 'var(--text-dim)' }}>// search</span></h1>
1358
+ <StatusBadge platform={activeTab} />
1359
+ </div>
1360
+ <p className="text-xs font-mono" style={{ color: 'var(--text-ghost)' }}>
1361
+ {activeTab === 'status' ? '> system command center // global health' :
1362
+ activeTab === 'telegram' ? '> users, channels, groups' :
1363
+ activeTab === 'facebook' ? '> pages, people, groups' :
1364
+ activeTab === 'tiktok' ? '> profiles, creators' :
1365
+ activeTab === 'instagram' ? '> profiles, accounts' :
1366
+ '> users, profiles'}
1367
+ </p>
1368
+ </div>
1369
+
1370
+ {/* Errors */}
1371
+ {error && <div className="err-box mb-5 anim-fade-up"><span className="font-mono text-xs">ERR</span><span>{error}</span></div>}
1372
+ {activeTab === 'telegram' && tgError && <div className="err-box mb-5 anim-fade-up"><span className="font-mono text-xs">ERR</span><span>{tgError}</span></div>}
1373
+ {activeTab === 'x' && xError && <div className="err-box mb-5 anim-fade-up"><span className="font-mono text-xs">ERR</span><span>{xError}</span></div>}
1374
+
1375
+ {loading && (
1376
+ <div className="mb-5 text-center anim-fade-in">
1377
+ <div className="prog-bar w-40 mx-auto mb-2" />
1378
+ <span className="text-xs font-mono" style={{ color: 'var(--text-ghost)' }}>INITIALIZING<span className="anim-blink">_</span></span>
1379
+ </div>
1380
+ )}
1381
+
1382
+ {/* ═══ TELEGRAM AUTH ═══ */}
1383
+ {activeTab === 'telegram' && (step === 'phone' || step === 'code') && (
1384
+ <div className="mx-auto mt-8 md:mt-16 max-w-md w-full auth-panel anim-fade-up">
1385
+ <h2 className="text-lg font-bold mb-0.5 font-mono" style={{ color: 'var(--text-bright)' }}>
1386
+ <span style={{ color: 'var(--neon-cyan)' }}>&gt;</span> Telegram.auth()
1387
+ </h2>
1388
+ <p className="text-xs mb-5 font-mono" style={{ color: 'var(--text-ghost)' }}>
1389
+ {step === 'phone' ? '// enter phone in intl format' : '// enter verification code'}
1390
+ </p>
1391
+ {step === 'phone' ? (
1392
+ <div className="space-y-3">
1393
+ <input type="text" placeholder="+1234567890" value={phone} onChange={e => setPhone(e.target.value)} className="cyber-input" />
1394
+ <button onClick={sendCode} disabled={loading || !phone} className="btn-neon w-full">SEND_CODE</button>
1395
+ </div>
1396
+ ) : (
1397
+ <div className="space-y-3">
1398
+ <input type="text" placeholder="______" value={code} onChange={e => setCode(e.target.value)} className="cyber-input text-center tracking-[0.4em]" />
1399
+ <button onClick={verifyCode} disabled={loading || !code} className="btn-neon w-full">VERIFY</button>
1400
+ </div>
1401
+ )}
1402
+ </div>
1403
+ )}
1404
+
1405
+ {/* ═══ DASHBOARD ═══ */}
1406
+ {activeTab === 'status' ? (
1407
+ <StatusHub />
1408
+ ) : (activeTab !== 'telegram' || step === 'dashboard') && (
1409
+ <div className="space-y-5 anim-fade-up">
1410
+
1411
+ {!isFirstAuthCheckDone ? (
1412
+ <div className="flex flex-col items-center justify-center py-20 anim-fade-in opacity-50">
1413
+ <div className="prog-bar w-32 mb-4" />
1414
+ <p className="text-[10px] font-mono uppercase tracking-widest">Verifying_Session_State...</p>
1415
+ </div>
1416
+ ) : (!(platformsAuth[activeTab]?.status) && !showFbAuth && !showXAuth && !showIgAuth && activeTab !== 'tiktok') ? (
1417
+ <LoginRequired
1418
+ platform={activeTab}
1419
+ onLogin={() => {
1420
+ if (activeTab === 'instagram') setShowIgAuth(true);
1421
+ else if (activeTab === 'facebook') setShowFbAuth(true);
1422
+ else if (activeTab === 'x') setShowXAuth(true);
1423
+ }}
1424
+ />
1425
+ ) : (
1426
+ <>
1427
+ {/* Config toggle */}
1428
+ {(activeTab === 'instagram' || activeTab === 'facebook' || activeTab === 'x') && (
1429
+ <div className="flex justify-end">
1430
+ <button onClick={() => {
1431
+ if (activeTab === 'instagram') setShowIgAuth(!showIgAuth);
1432
+ else if (activeTab === 'facebook') setShowFbAuth(!showFbAuth);
1433
+ else if (activeTab === 'x') setShowXAuth(!showXAuth);
1434
+ }} className="btn-dim font-mono text-[10px]">
1435
+ <Upload size={12} />
1436
+ {(activeTab === 'instagram' ? showIgAuth : activeTab === 'facebook' ? showFbAuth : showXAuth) ? 'HIDE_CFG' : 'CONFIG'}
1437
+ </button>
1438
+ </div>
1439
+ )}
1440
+
1441
+ {/* Facebook Auth */}
1442
+ {activeTab === 'facebook' && showFbAuth && (
1443
+ <div className="auth-panel anim-slide-down">
1444
+ <h3 className="text-sm font-bold mb-0.5 font-mono" style={{ color: 'var(--text-bright)' }}><span style={{ color: 'var(--p-facebook)' }}>&gt;</span> fb.authenticate()</h3>
1445
+ <p className="text-xs mb-4 font-mono" style={{ color: 'var(--text-ghost)' }}>// cookies required for search</p>
1446
+ {fbAuthError && <div className="err-box mb-3 text-xs"><span>ERR</span><span>{fbAuthError}</span></div>}
1447
+
1448
+ {isRemote && !fbAuthSuccess && (
1449
+ <div className="mb-4 p-3 rounded text-[10px] font-mono leading-relaxed bg-yellow-500/5 border border-yellow-500/20 text-yellow-500/80">
1450
+ <p className="font-bold mb-1">REMOTE SERVER DETECTED</p>
1451
+ <p>Browser login is disabled on Render to prevent crashes. Please perform login on your local machine and paste the cookies below.</p>
1452
+ </div>
1453
+ )}
1454
+
1455
+ {fbAuthSuccess ? (
1456
+ <div className="ok-box"><span className="text-2xl">✓</span><span className="font-mono text-sm">cookies.saved()</span></div>
1457
+ ) : (
1458
+ <div className="space-y-3">
1459
+ {!isRemote && (
1460
+ <div className="p-3 rounded" style={{ background: 'rgba(24,119,242,0.04)', border: '1px solid rgba(24,119,242,0.12)' }}>
1461
+ <p className="sec-label mb-2">auto login</p>
1462
+ <button onClick={launchFacebookAutoAuth} disabled={isFbAuthenticating} className="btn-neon w-full text-xs">{isFbAuthenticating ? 'WAITING...' : 'LAUNCH_BROWSER'}</button>
1463
+ </div>
1464
+ )}
1465
+ {!isRemote && <div className="text-center text-[10px] font-mono" style={{ color: 'var(--text-ghost)' }}>— OR —</div>}
1466
+ <div>
1467
+ <p className="sec-label mb-1.5">paste cookies</p>
1468
+ <textarea placeholder='[{ "name": "c_user", ... }]' value={fbAuthInput} onChange={e => setFbAuthInput(e.target.value)}
1469
+ className="cyber-input text-xs" style={{ height: '5rem', resize: 'vertical' }} />
1470
+ </div>
1471
+ <button onClick={saveFacebookCookies} disabled={isFbAuthenticating || !fbAuthInput} className="btn-dim w-full font-mono text-[10px]">{isFbAuthenticating ? 'SAVING...' : 'SAVE_COOKIES'}</button>
1472
+ </div>
1473
+ )}
1474
+ </div>
1475
+ )}
1476
+
1477
+ {/* X Auth */}
1478
+ {activeTab === 'x' && showXAuth && (
1479
+ <div className="auth-panel anim-slide-down">
1480
+ <h3 className="text-sm font-bold mb-0.5 font-mono" style={{ color: 'var(--text-bright)' }}><span style={{ color: 'var(--p-x)' }}>&gt;</span> x.authenticate()</h3>
1481
+ <p className="text-xs mb-4 font-mono" style={{ color: 'var(--text-ghost)' }}>// cookies required for search</p>
1482
+ {xAuthError && <div className="err-box mb-3 text-xs"><span>ERR</span><span>{xAuthError}</span></div>}
1483
+
1484
+ {isRemote && !xAuthSuccess && (
1485
+ <div className="mb-4 p-3 rounded text-[10px] font-mono leading-relaxed bg-yellow-500/5 border border-yellow-500/20 text-yellow-500/80">
1486
+ <p className="font-bold mb-1">REMOTE SERVER DETECTED</p>
1487
+ <p>Browser login is disabled on Render to prevent crashes. Please perform login on your local machine and paste the cookies below.</p>
1488
+ </div>
1489
+ )}
1490
+
1491
+ {xAuthSuccess ? (
1492
+ <div className="ok-box"><span className="text-2xl">✓</span><span className="font-mono text-sm">cookies.saved()</span></div>
1493
+ ) : (
1494
+ <div className="space-y-3">
1495
+ {!isRemote && (
1496
+ <div className="p-3 rounded" style={{ background: 'rgba(231,233,234,0.03)', border: '1px solid rgba(231,233,234,0.08)' }}>
1497
+ <p className="sec-label mb-2">auto login</p>
1498
+ <button onClick={launchXAutoAuth} disabled={isXAuthenticating} className="btn-neon w-full text-xs">{isXAuthenticating ? 'WAITING...' : 'LAUNCH_BROWSER'}</button>
1499
+ </div>
1500
+ )}
1501
+ {!isRemote && <div className="text-center text-[10px] font-mono" style={{ color: 'var(--text-ghost)' }}>— OR —</div>}
1502
+ <div>
1503
+ <p className="sec-label mb-1.5">paste cookies</p>
1504
+ <textarea placeholder='[{ "name": "auth_token", ... }]' value={xAuthInput} onChange={e => setXAuthInput(e.target.value)}
1505
+ className="cyber-input text-xs" style={{ height: '5rem', resize: 'vertical' }} />
1506
+ </div>
1507
+ <button onClick={saveXCookies} disabled={isXAuthenticating || !xAuthInput} className="btn-dim w-full font-mono text-[10px]">{isXAuthenticating ? 'SAVING...' : 'SAVE_COOKIES'}</button>
1508
+ </div>
1509
+ )}
1510
+ </div>
1511
+ )}
1512
+
1513
+ {/* Instagram Auth */}
1514
+ {activeTab === 'instagram' && showIgAuth && (
1515
+ <div className="auth-panel anim-slide-down">
1516
+ <h3 className="text-sm font-bold mb-0.5 font-mono" style={{ color: 'var(--text-bright)' }}><span style={{ color: 'var(--p-instagram)' }}>&gt;</span> ig.authenticate()</h3>
1517
+ <p className="text-xs mb-4 font-mono" style={{ color: 'var(--text-ghost)' }}>// active session required</p>
1518
+ {igAuthError && <div className="err-box mb-3 text-xs"><span>ERR</span><span>{igAuthError}</span></div>}
1519
+ {igAuthSuccess ? (
1520
+ <div className="ok-box"><span className="text-2xl">✓</span><span className="font-mono text-sm">credentials.saved()</span></div>
1521
+ ) : (
1522
+ <div className="space-y-3">
1523
+ {isRemote && (
1524
+ <div className="mb-4 p-3 rounded text-[10px] font-mono leading-relaxed bg-yellow-500/5 border border-yellow-500/20 text-yellow-500/80">
1525
+ <p className="font-bold mb-1">REMOTE SERVER DETECTED</p>
1526
+ <p>Browser login is disabled on Render. Please perform login locally and provide tokens below.</p>
1527
+ </div>
1528
+ )}
1529
+ {!isRemote && (
1530
+ <div className="p-3 rounded" style={{ background: 'rgba(228,64,95,0.04)', border: '1px solid rgba(228,64,95,0.12)' }}>
1531
+ <p className="sec-label mb-2 uppercase text-[10px] tracking-widest opacity-50">Browser Login</p>
1532
+ <p className="text-[10px] opacity-60 italic leading-relaxed mb-3">
1533
+ Log in manually in the browser window.
1534
+ <b> Capture occurs automatically; close the window when finished.</b>
1535
+ </p>
1536
+ <button onClick={launchInstagramAutoAuth} disabled={isIgAuthenticating} className="btn-neon w-full text-xs py-2"
1537
+ style={{ borderColor: 'var(--p-instagram)', color: 'var(--p-instagram)', background: 'rgba(228,64,95,0.06)' }}>
1538
+ {isIgAuthenticating ? 'BROWSER_OPEN_AND_MONITORING...' : 'OPEN_AUTH_BROWSER'}
1539
+ </button>
1540
+ </div>
1541
+ )}
1542
+ {!isRemote && <div className="text-center text-[10px] font-mono" style={{ color: 'var(--text-ghost)' }}>— OR —</div>}
1543
+ <div className="space-y-2">
1544
+ <p className="sec-label uppercase text-[10px] tracking-widest opacity-50">Manual Capture</p>
1545
+ <div className="flex flex-col gap-1.5">
1546
+ <label className="text-[9px] font-mono uppercase opacity-40">Paste Cookies JSON Array</label>
1547
+ <textarea
1548
+ placeholder='[{"name":"sessionid", "value":"..."}, ...]'
1549
+ value={igAuthInput}
1550
+ onChange={e => setIgAuthInput(e.target.value)}
1551
+ className="cyber-input text-[10px] min-h-[100px] font-mono py-2"
1552
+ />
1553
+ </div>
1554
+ <button onClick={saveInstagramCookies} disabled={isIgAuthenticating} className="btn-dim w-full font-mono text-[10px] tracking-wider uppercase mt-1">
1555
+ {isIgAuthenticating ? 'SAVING...' : 'Save_Manual_Tokens'}
1556
+ </button>
1557
+ </div>
1558
+ </div>
1559
+ )}
1560
+ </div>
1561
+ )}
1562
+
1563
+ {/* Facebook filters */}
1564
+ {activeTab === 'facebook' && (
1565
+ <div>
1566
+ <p className="sec-label mb-2">target_type</p>
1567
+ <div className="flex flex-wrap gap-1.5">
1568
+ {['pages', 'people', 'groups'].map(t => (
1569
+ <button key={t} onClick={() => setFbSearchTypes(prev => prev.includes(t) ? prev.length > 1 ? prev.filter(x => x !== t) : prev : [...prev, t])}
1570
+ className={`sel-chip ${fbSearchTypes.includes(t) ? 'on' : ''}`}>{t}</button>
1571
+ ))}
1572
+ <button onClick={() => fbSearchTypes.length === 3 ? setFbSearchTypes(['pages']) : setFbSearchTypes(['pages','people','groups'])}
1573
+ className={`sel-chip ${fbSearchTypes.length === 3 ? 'on' : ''}`} style={{ flex: '0 0 auto' }}>{fbSearchTypes.length === 3 ? 'NONE' : 'ALL'}</button>
1574
+ </div>
1575
+ </div>
1576
+ )}
1577
+
1578
+ {/* Search expansion */}
1579
+ {(activeTab === 'telegram' || activeTab === 'instagram') && (
1580
+ <div>
1581
+ <p className="sec-label mb-2">expansion_mode</p>
1582
+ <div className="flex flex-wrap gap-1.5">
1583
+ {['none', 'a-z', '0-9', 'a-z0-9'].map(m => {
1584
+ const cur = activeTab === 'telegram' ? tgSearchMode : igSearchMode;
1585
+ const set = activeTab === 'telegram' ? setTgSearchMode : setIgSearchMode;
1586
+ return <button key={m} onClick={() => set(m)} className={`sel-chip ${cur === m ? 'on' : ''}`}>{m === 'none' ? 'EXACT' : m}</button>;
1587
+ })}
1588
+ </div>
1589
+ </div>
1590
+ )}
1591
+
1592
+ {/* ═══ Search Area (Blocked until Auth) ═══ */}
1593
+ {(activeTab === 'tiktok' || platformsAuth[activeTab]?.status) && (
1594
+ <>
1595
+ {/* Search Bar ═══ */}
1596
+ <div className="panel anim-fade-up">
1597
+ <div className="panel-header">
1598
+ <span style={{ color: 'var(--neon-cyan-dim)' }}>⟩ QUERY_INPUT</span>
1599
+ {busy && <div className="status-dot" />}
1600
+ </div>
1601
+ <div className="p-4 flex flex-col md:flex-row gap-3">
1602
+ <div className="flex-grow">
1603
+ <input type="text"
1604
+ placeholder={activeTab === 'telegram' ? "target[a-z0-9]" : activeTab === 'x' ? "@handle OR #tag" : "keyword..."}
1605
+ value={localSearchTerm}
1606
+ onChange={e => {
1607
+ const v = e.target.value;
1608
+ setLocalSearchTerm(v);
1609
+ if (activeTab === 'telegram') setTgSearchTerm(v);
1610
+ else if (activeTab === 'instagram') setIgSearchTerm(v);
1611
+ else if (activeTab === 'facebook') setFbSearchTerm(v);
1612
+ else if (activeTab === 'tiktok') setTtSearchTerm(v);
1613
+ else setXSearchTerm(v);
1614
+ }}
1615
+ disabled={busy}
1616
+ onKeyDown={e => {
1617
+ if (e.key === 'Enter' && !busy && localSearchTerm) {
1618
+ if (activeTab === 'telegram') startSearch();
1619
+ else if (activeTab === 'instagram') performInstagramSearch();
1620
+ else if (activeTab === 'facebook') performFacebookSearch();
1621
+ else if (activeTab === 'tiktok') performTikTokSearch();
1622
+ else performXSearch();
1623
+ }
1624
+ }}
1625
+ className="cyber-input"
1626
+ />
1627
+ </div>
1628
+ <div className="flex flex-col justify-end md:w-32">
1629
+ {(activeTab === 'facebook' && isFbSearching) || (activeTab === 'x' && isXSearching) || (activeTab === 'tiktok' && isTtSearching) ? (
1630
+ <button onClick={activeTab === 'facebook' ? stopFacebookSearch : activeTab === 'x' ? stopXSearch : stopTikTokSearch} className="btn-abort w-full">
1631
+ <Square size={14} fill="currentColor" /> ABORT
1632
+ </button>
1633
+ ) : (
1634
+ <button onClick={() => {
1635
+ if (activeTab === 'telegram') startSearch();
1636
+ else if (activeTab === 'instagram') performInstagramSearch();
1637
+ else if (activeTab === 'facebook') performFacebookSearch();
1638
+ else if (activeTab === 'tiktok') performTikTokSearch();
1639
+ else performXSearch();
1640
+ }}
1641
+ disabled={busy || !curTerm} className="btn-neon w-full">
1642
+ {busy ? <span className="inline-block w-4 h-4 border-2 border-current/30 border-t-current rounded-full" style={{ animation: 'spin 0.6s linear infinite' }} /> : <><Search size={14} /> EXEC</>}
1643
+ </button>
1644
+ )}
1645
+ </div>
1646
+ </div>
1647
+ </div>
1648
+
1649
+ {/* Progress */}
1650
+ {activeTab === 'telegram' && (isTgSearching || tgProgress) && (
1651
+ <div className="panel px-4 py-2.5 flex items-center justify-between anim-fade-in">
1652
+ <span className="text-xs font-mono" style={{ color: 'var(--neon-cyan)' }}>{tgProgress}</span>
1653
+ {isTgSearching && <div className="prog-bar" style={{ width: '50px' }} />}
1654
+ </div>
1655
+ )}
1656
+ {activeTab === 'instagram' && (isIgSearching || igProgress) && (
1657
+ <div className="panel px-4 py-2.5 flex items-center justify-between anim-fade-in">
1658
+ <span className="text-xs font-mono" style={{ color: 'var(--p-instagram)' }}>{igProgress}</span>
1659
+ {isIgSearching && <div className="prog-bar" style={{ width: '50px' }} />}
1660
+ </div>
1661
+ )}
1662
+
1663
+ {/* ═══ Telegram Results Grid ═══ */}
1664
+ {activeTab === 'telegram' ? (
1665
+ <div className="space-y-4 anim-fade-up">
1666
+ <div className="flex justify-between items-center">
1667
+ <span className="sec-label">results [{tgResults.length}]</span>
1668
+ <button onClick={exportExcel} disabled={tgResults.length === 0} className="btn-export"><FileText size={11} /> EXPORT</button>
1669
+ </div>
1670
+
1671
+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2">
1672
+ {tgResults.length === 0 ? (
1673
+ <div className="col-span-full empty-zone py-8">
1674
+ <Send className="w-8 h-8 mb-2" style={{ color: 'var(--text-ghost)' }} />
1675
+ <p className="text-xs font-mono" style={{ color: 'var(--text-ghost)' }}>
1676
+ {isTgSearching ? 'scanning...' : '// no data — execute a search'}
1677
+ </p>
1678
+ </div>
1679
+ ) : tgResults.map((r, i) => {
1680
+ const TypeIcon = r.type === 'user' ? User : r.type === 'channel' ? Bell : Users;
1681
+ const typeColor = r.type === 'user' ? 'var(--neon-cyan-dim)' : r.type === 'channel' ? '#a78bfa' : 'var(--neon-green-dim)';
1682
+ const typeBg = r.type === 'user' ? 'rgba(0,240,255,0.06)' : r.type === 'channel' ? 'rgba(139,92,246,0.08)' : 'rgba(0,255,136,0.06)';
1683
+
1684
+ return (
1685
+ <div key={i} className="r-card group">
1686
+ <div className="r-card-border-glow" />
1687
+ <div className="flex items-center gap-3 relative z-10">
1688
+ <div className="relative">
1689
+ {r.image ? (
1690
+ <img src={r.image} alt={r.username} className="w-10 h-10 rounded object-cover shadow-sm" style={{ border: '1px solid var(--line)' }} />
1691
+ ) : (
1692
+ <div className="w-10 h-10 rounded flex items-center justify-center"
1693
+ style={{ background: 'var(--bg-raised)', border: '1px solid var(--line)' }}>
1694
+ <TypeIcon size={18} style={{ color: typeColor }} />
1695
+ </div>
1696
+ )}
1697
+ <div className="absolute -bottom-1 -right-1 w-3.5 h-3.5 rounded flex items-center justify-center"
1698
+ style={{ background: typeBg, border: '1px solid var(--line)', backdropFilter: 'blur(4px)' }}>
1699
+ <TypeIcon size={8} style={{ color: typeColor }} />
1700
+ </div>
1701
+ </div>
1702
+ <div className="min-w-0 flex-1">
1703
+ <div className="text-sm font-medium truncate" style={{ color: 'var(--text-bright)' }}>{r.name}</div>
1704
+ <div className="text-[10px] font-mono truncate" style={{ color: 'var(--text-ghost)' }}>@{r.username}</div>
1705
+ </div>
1706
+ <a href={r.url} target="_blank" rel="noopener noreferrer"
1707
+ className="p-1.5 rounded transition-colors" style={{ color: 'var(--text-dim)' }}><ExternalLink size={12} /></a>
1708
+ </div>
1709
+ <div className="mt-2.5 relative z-10">
1710
+ <span className="tag" style={{ background: typeBg, color: typeColor, borderColor: 'rgba(255,255,255,0.05)' }}>
1711
+ {r.type.toUpperCase()}
1712
+ </span>
1713
+ </div>
1714
+ </div>
1715
+ );
1716
+ })}
1717
+ </div>
1718
+ </div>
1719
+ ) : null}
1720
+
1721
+ {activeTab === 'instagram' && <InstagramSearch results={igResults} loading={isIgSearching} error={igError} term={igSearchTerm} />}
1722
+ {activeTab === 'facebook' && <FacebookSearch results={fbResults} loading={isFbSearching} error={fbError} term={fbSearchTerm} onExport={exportExcel} />}
1723
+ {activeTab === 'x' && <XSearch results={xResults} loading={isXSearching} error={xError} term={xSearchTerm} onExport={exportExcel} />}
1724
+ {activeTab === 'tiktok' && (
1725
+ <>
1726
+ {(isTtSearching || ttProgress) && (
1727
+ <div className="panel px-4 py-2.5 flex items-center justify-between anim-fade-in mb-1">
1728
+ <span className="text-xs font-mono" style={{ color: 'var(--p-tiktok)' }}>{ttProgress}</span>
1729
+ {isTtSearching && <div className="prog-bar" style={{ width: '50px' }} />}
1730
+ </div>
1731
+ )}
1732
+ <TikTokSearch results={ttResults} loading={isTtSearching} error={ttError} term={ttSearchTerm} onExport={exportExcel} />
1733
+ </>
1734
+ )}
1735
+ </>
1736
+ )}
1737
+ </>
1738
+ )}
1739
+ </div>
1740
+ )}
1741
+ </main>
1742
+ </div>
1743
+ );
1744
+ }
src/assets/react.svg ADDED
src/components/FacebookSearch.tsx ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { getApiUrl } from '../config';
2
+ import React from 'react';
3
+ import { Facebook, ExternalLink, Info, Download } from 'lucide-react';
4
+
5
+ interface FacebookResult {
6
+ term: string;
7
+ type: string;
8
+ url: string;
9
+ name?: string;
10
+ image?: string;
11
+ verified?: boolean;
12
+ }
13
+
14
+ interface FacebookSearchProps {
15
+ results: FacebookResult[];
16
+ loading: boolean;
17
+ error: string | null;
18
+ term: string;
19
+ onExport?: () => void;
20
+ }
21
+
22
+ const FacebookSearch: React.FC<FacebookSearchProps> = ({ results, loading, error, term, onExport }) => {
23
+ if (loading && results.length === 0) {
24
+ return (
25
+ <div className="flex flex-col items-center justify-center py-16 anim-fade-in">
26
+ <Facebook className="w-10 h-10 mb-3 anim-pulse" style={{ color: 'var(--p-facebook)' }} />
27
+ <p className="text-xs font-mono" style={{ color: 'var(--text-ghost)' }}>scanning fb.search("<span style={{ color: 'var(--neon-cyan)' }}>{term}</span>")<span className="anim-blink">_</span></p>
28
+ <div className="prog-bar w-28 mt-3" />
29
+ </div>
30
+ );
31
+ }
32
+
33
+ return (
34
+ <div className="space-y-5 anim-fade-up">
35
+ {error && (
36
+ <div className="err-box">
37
+ <span className="font-mono text-xs">ERR</span>
38
+ <div>
39
+ <span className="font-bold text-sm" style={{ color: '#ff6b6b' }}>{error.includes('stopped by user') ? 'ABORTED' : 'FAILED'}</span>
40
+ <p className="text-xs mt-0.5 opacity-80">{error}</p>
41
+ </div>
42
+ </div>
43
+ )}
44
+ <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-3">
45
+ <div className="flex items-center gap-2">
46
+ <span className="sec-label">results [{results.length}]</span>
47
+ {loading && <span className="text-[10px] font-mono anim-pulse" style={{ color: 'var(--p-facebook)' }}>expanding...</span>}
48
+ </div>
49
+ {onExport && <button onClick={onExport} disabled={results.length === 0} className="btn-export"><Download size={11} /> EXPORT</button>}
50
+ </div>
51
+
52
+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2">
53
+ {results.length === 0 && !loading ? (
54
+ <div className="col-span-full empty-zone">
55
+ <Facebook className="w-8 h-8 mb-2" style={{ color: 'var(--text-ghost)' }} />
56
+ <p className="text-xs font-mono" style={{ color: 'var(--text-ghost)' }}>// no results for "{term}"</p>
57
+ </div>
58
+ ) : (
59
+ results.map((item, idx) => {
60
+ const cleanUrl = item.url.replace('https://www.facebook.com/', '').replace('http://www.facebook.com/', '').split('?')[0].replace(/\/$/, '');
61
+ const fallbackUsername = cleanUrl.split('/').pop() || 'User';
62
+ const username = item.name || fallbackUsername;
63
+ const isPage = item.type === 'pages';
64
+ const fbIdentifier = cleanUrl.includes('profile.php')
65
+ ? new URLSearchParams(item.url.split('?')[1] || '').get('id') || fallbackUsername : fallbackUsername;
66
+ const fbGraphPicUrl = `https://graph.facebook.com/${fbIdentifier}/picture?type=large`;
67
+ const profileImageUrl = item.image
68
+ ? getApiUrl(`/api/proxy-image?url=${encodeURIComponent(item.image)}`)
69
+ : getApiUrl(`/api/proxy-image?url=${encodeURIComponent(fbGraphPicUrl)}`);
70
+ const fallbackAvatarUrl = `https://ui-avatars.com/api/?name=${encodeURIComponent(username)}&background=0a0a0f&color=00f0ff`;
71
+
72
+ return (
73
+ <div key={idx} className="r-card group">
74
+ <div className="r-card-border-glow" />
75
+ <div className="flex items-center gap-3 relative z-10">
76
+ <div className="relative">
77
+ <img src={profileImageUrl} alt={username}
78
+ className="w-10 h-10 rounded object-cover" style={{ border: '1px solid var(--line)' }}
79
+ onError={(e) => { (e.target as HTMLImageElement).src = fallbackAvatarUrl; }} />
80
+ {isPage && <div className="absolute -bottom-1 -right-1 w-3.5 h-3.5 rounded flex items-center justify-center" style={{ background: 'var(--p-facebook)', border: '2px solid var(--bg-raised)' }}>
81
+ <svg viewBox="0 0 24 24" className="w-2 h-2 fill-white"><path d="M22.5 12.5c0-1.58-.8-3-2.1-3.88.2-1.6-.2-3.3-1.4-4.5s-2.9-1.6-4.5-1.4c-.88-1.3-2.3-2.1-3.88-2.1s-3 .8-3.88 2.1c-1.6-.2-3.3.2-4.5 1.4s-1.6 2.9-1.4 4.5c-1.3.88-2.1 2.3-2.1 3.88s.8 3 2.1 3.88c-.2 1.6.2 3.3 1.4 4.5s2.9 1.6 4.5 1.4c.88 1.3 2.3 2.1 3.88 2.1s3-.8 3.88-2.1c1.6.2 3.3-.2 4.5-1.4s1.6-2.9 1.4-4.5c1.3-.88 2.1-2.3 2.1-3.88zM10 17l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" /></svg>
82
+ </div>}
83
+ </div>
84
+ <div className="min-w-0 flex-1">
85
+ <div className="flex items-center gap-1 text-sm font-medium truncate" style={{ color: 'var(--text-bright)' }}>
86
+ {username}
87
+ {item.verified && <svg viewBox="0 0 24 24" className="v-badge"><path d="M22.5 12.5c0-1.58-.8-3-2.1-3.88.2-1.6-.2-3.3-1.4-4.5s-2.9-1.6-4.5-1.4c-.88-1.3-2.3-2.1-3.88-2.1s-3 .8-3.88 2.1c-1.6-.2-3.3.2-4.5 1.4s-1.6 2.9-1.4 4.5c-1.3.88-2.1 2.3-2.1 3.88s.8 3 2.1 3.88c-.2 1.6.2 3.3 1.4 4.5s2.9 1.6 4.5 1.4c.88 1.3 2.3 2.1 3.88 2.1s3-.8 3.88-2.1c1.6.2 3.3-.2 4.5-1.4s1.6-2.9 1.4-4.5c1.3-.88 2.1-2.3 2.1-3.88zM10 17l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" /></svg>}
88
+ </div>
89
+ <div className="text-[10px] font-mono truncate" style={{ color: 'var(--text-ghost)' }}>{cleanUrl}</div>
90
+ </div>
91
+ <a href={item.url} target="_blank" rel="noopener noreferrer"
92
+ className="p-1.5 rounded transition-colors" style={{ color: 'var(--text-dim)' }} title="Open"><ExternalLink size={12} /></a>
93
+ </div>
94
+ <div className="mt-2.5 relative z-10">
95
+ <span className="tag" style={{ background: 'rgba(0,240,255,0.04)', color: 'var(--neon-cyan-dim)', borderColor: 'rgba(0,240,255,0.12)' }}>{item.type}</span>
96
+ </div>
97
+ </div>
98
+ );
99
+ })
100
+ )}
101
+ </div>
102
+ </div>
103
+ );
104
+ };
105
+
106
+ export default FacebookSearch;
src/components/InstagramSearch.tsx ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { getApiUrl } from '../config';
2
+ import React, { useState } from 'react';
3
+ import { Instagram, User, ExternalLink, Info } from 'lucide-react';
4
+
5
+ interface InstagramUser {
6
+ user: {
7
+ username: string;
8
+ full_name: string;
9
+ profile_pic_url: string;
10
+ is_private: boolean;
11
+ is_verified: boolean;
12
+ };
13
+ }
14
+
15
+ interface InstagramSearchProps {
16
+ results: InstagramUser[];
17
+ loading: boolean;
18
+ error: string | null;
19
+ term: string;
20
+ }
21
+
22
+ const InstagramSearch: React.FC<InstagramSearchProps> = ({ results, loading, error, term }) => {
23
+ const [hideVerified, setHideVerified] = useState(false);
24
+
25
+ if (loading && results.length === 0) {
26
+ return (
27
+ <div className="flex flex-col items-center justify-center py-16 anim-fade-in">
28
+ <Instagram className="w-10 h-10 mb-3 anim-pulse" style={{ color: 'var(--p-instagram)' }} />
29
+ <p className="text-xs font-mono" style={{ color: 'var(--text-ghost)' }}>scanning ig.search("<span style={{ color: 'var(--p-instagram)' }}>{term}</span>")<span className="anim-blink">_</span></p>
30
+ <div className="prog-bar w-28 mt-3" />
31
+ </div>
32
+ );
33
+ }
34
+
35
+ if (error) {
36
+ return (
37
+ <div className="err-box">
38
+ <span className="font-mono text-xs">ERR</span>
39
+ <div><span className="font-bold text-sm" style={{ color: '#ff6b6b' }}>FAILED</span><p className="text-xs mt-0.5 opacity-80">{error}</p></div>
40
+ </div>
41
+ );
42
+ }
43
+
44
+ const displayed = hideVerified ? results.filter(r => !r.user.is_verified) : results;
45
+
46
+ return (
47
+ <div className="space-y-5 anim-fade-up">
48
+ <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-3">
49
+ <div className="flex items-center gap-2">
50
+ <span className="sec-label">results [{displayed.length}{hideVerified && results.length !== displayed.length ? `/${results.length}` : ''}]</span>
51
+ {loading && <span className="text-[10px] font-mono anim-pulse" style={{ color: 'var(--p-instagram)' }}>expanding...</span>}
52
+ </div>
53
+ {results.length > 0 && (
54
+ <label className="flex items-center gap-1.5 text-[10px] font-mono cursor-pointer" style={{ color: 'var(--text-dim)' }}>
55
+ <input type="checkbox" checked={hideVerified} onChange={e => setHideVerified(e.target.checked)} className="w-3 h-3 cursor-pointer accent-pink-500" />
56
+ hide_verified
57
+ </label>
58
+ )}
59
+ </div>
60
+
61
+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2">
62
+ {displayed.length === 0 && !loading ? (
63
+ <div className="col-span-full empty-zone">
64
+ <User className="w-8 h-8 mb-2" style={{ color: 'var(--text-ghost)' }} />
65
+ <p className="text-xs font-mono" style={{ color: 'var(--text-ghost)' }}>// no results for "{term}"</p>
66
+ </div>
67
+ ) : displayed.map((item, idx) => (
68
+ <div key={idx} className="r-card group">
69
+ <div className="r-card-border-glow" />
70
+ <div className="flex items-center gap-3 relative z-10">
71
+ <div className="relative">
72
+ <img src={getApiUrl(`/api/proxy-image?url=${encodeURIComponent(item.user.profile_pic_url)}`)}
73
+ alt={item.user.username} referrerPolicy="no-referrer"
74
+ className="w-10 h-10 rounded object-cover" style={{ border: '1px solid var(--line)' }}
75
+ onError={(e) => { (e.target as HTMLImageElement).src = `https://ui-avatars.com/api/?name=${item.user.username}&background=0a0a0f&color=00f0ff`; }} />
76
+ {item.user.is_verified && <div className="absolute -bottom-1 -right-1 w-3.5 h-3.5 rounded flex items-center justify-center bg-blue-500" style={{ border: '2px solid var(--bg-raised)' }}>
77
+ <svg viewBox="0 0 24 24" className="w-2 h-2 fill-white"><path d="M22.5 12.5c0-1.58-.8-3-2.1-3.88.2-1.6-.2-3.3-1.4-4.5s-2.9-1.6-4.5-1.4c-.88-1.3-2.3-2.1-3.88-2.1s-3 .8-3.88 2.1c-1.6-.2-3.3.2-4.5 1.4s-1.6 2.9-1.4 4.5c-1.3.88-2.1 2.3-2.1 3.88s.8 3 2.1 3.88c-.2 1.6.2 3.3 1.4 4.5s2.9 1.6 4.5 1.4c.88 1.3 2.3 2.1 3.88 2.1s3-.8 3.88-2.1c1.6.2 3.3-.2 4.5-1.4s1.6-2.9 1.4-4.5c1.3-.88 2.1-2.3 2.1-3.88zM10 17l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" /></svg>
78
+ </div>}
79
+ </div>
80
+ <div className="min-w-0 flex-1">
81
+ <div className="text-sm font-medium truncate" style={{ color: 'var(--text-bright)' }}>{item.user.full_name || item.user.username}</div>
82
+ <div className="text-[10px] font-mono truncate" style={{ color: 'var(--text-ghost)' }}>@{item.user.username}</div>
83
+ </div>
84
+ <a href={`https://www.instagram.com/${item.user.username}/`} target="_blank" rel="noopener noreferrer"
85
+ className="p-1.5 rounded transition-colors" style={{ color: 'var(--text-dim)' }}><ExternalLink size={12} /></a>
86
+ </div>
87
+ <div className="mt-2.5 relative z-10">
88
+ <span className="tag" style={{
89
+ background: item.user.is_private ? 'rgba(255,107,43,0.06)' : 'rgba(0,255,136,0.06)',
90
+ color: item.user.is_private ? 'var(--neon-orange)' : 'var(--neon-green-dim)',
91
+ borderColor: item.user.is_private ? 'rgba(255,107,43,0.15)' : 'rgba(0,255,136,0.15)',
92
+ }}>{item.user.is_private ? 'PRIVATE' : 'PUBLIC'}</span>
93
+ </div>
94
+ </div>
95
+ ))}
96
+ </div>
97
+ </div>
98
+ );
99
+ };
100
+
101
+ export default InstagramSearch;
src/components/TikTokSearch.tsx ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { getApiUrl } from '../config';
2
+ import React from 'react';
3
+ import { Music2, ExternalLink, Info, Download } from 'lucide-react';
4
+
5
+ interface TikTokResult {
6
+ term: string;
7
+ url: string;
8
+ username: string;
9
+ nickname?: string;
10
+ avatar?: string;
11
+ }
12
+
13
+ interface TikTokSearchProps {
14
+ results: TikTokResult[];
15
+ loading: boolean;
16
+ error: string | null;
17
+ term: string;
18
+ onExport?: () => void;
19
+ }
20
+
21
+ const TikTokSearch: React.FC<TikTokSearchProps> = ({ results, loading, error, term, onExport }) => {
22
+ if (loading && results.length === 0) {
23
+ return (
24
+ <div className="flex flex-col items-center justify-center py-16 anim-fade-in">
25
+ <Music2 className="w-10 h-10 mb-3 anim-pulse" style={{ color: 'var(--p-tiktok)' }} />
26
+ <p className="text-xs font-mono" style={{ color: 'var(--text-ghost)' }}>scanning tt.search("<span style={{ color: 'var(--p-tiktok)' }}>{term}</span>")<span className="anim-blink">_</span></p>
27
+ <div className="prog-bar w-28 mt-3" />
28
+ </div>
29
+ );
30
+ }
31
+
32
+ return (
33
+ <div className="space-y-5 anim-fade-up">
34
+ {error && (
35
+ <div className="err-box">
36
+ <span className="font-mono text-xs">ERR</span>
37
+ <div><span className="font-bold text-sm" style={{ color: '#ff6b6b' }}>FAILED</span><p className="text-xs mt-0.5 opacity-80">{error}</p></div>
38
+ </div>
39
+ )}
40
+ <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-3">
41
+ <div className="flex items-center gap-2">
42
+ <span className="sec-label">results [{results.length}]</span>
43
+ {loading && <span className="text-[10px] font-mono anim-pulse" style={{ color: 'var(--p-tiktok)' }}>expanding...</span>}
44
+ </div>
45
+ {onExport && <button onClick={onExport} disabled={results.length === 0} className="btn-export"><Download size={11} /> EXPORT</button>}
46
+ </div>
47
+
48
+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2">
49
+ {results.length === 0 && !loading ? (
50
+ <div className="col-span-full empty-zone">
51
+ <Music2 className="w-8 h-8 mb-2" style={{ color: 'var(--text-ghost)' }} />
52
+ <p className="text-xs font-mono" style={{ color: 'var(--text-ghost)' }}>// no results for "{term}"</p>
53
+ </div>
54
+ ) : results.map((item, idx) => (
55
+ <div key={idx} className="r-card group">
56
+ <div className="r-card-border-glow" />
57
+ <div className="flex items-center gap-3 relative z-10">
58
+ <div className="relative">
59
+ <img src={item.avatar ? getApiUrl(`/api/proxy-image?url=${encodeURIComponent(item.avatar)}`) : `https://ui-avatars.com/api/?name=${item.username}&background=0a0a0f&color=ff0050`}
60
+ alt={item.username} className="w-10 h-10 rounded object-cover" style={{ border: '1px solid var(--line)' }}
61
+ onError={(e) => { (e.target as HTMLImageElement).src = `https://ui-avatars.com/api/?name=${item.username}&background=0a0a0f&color=ff0050`; }} />
62
+ <div className="absolute -bottom-1 -right-1 w-3.5 h-3.5 rounded flex items-center justify-center" style={{ background: 'var(--bg-raised)', border: '1px solid var(--line)' }}>
63
+ <Music2 size={8} style={{ color: 'var(--p-tiktok)' }} />
64
+ </div>
65
+ </div>
66
+ <div className="min-w-0 flex-1">
67
+ <div className="text-sm font-medium truncate" style={{ color: 'var(--text-bright)' }}>{item.nickname || item.username}</div>
68
+ <div className="text-[10px] font-mono truncate" style={{ color: 'var(--text-ghost)' }}>@{item.username}</div>
69
+ </div>
70
+ <a href={item.url} target="_blank" rel="noopener noreferrer"
71
+ className="p-1.5 rounded transition-colors" style={{ color: 'var(--text-dim)' }} title="Open"><ExternalLink size={12} /></a>
72
+ </div>
73
+ </div>
74
+ ))}
75
+ </div>
76
+ </div>
77
+ );
78
+ };
79
+
80
+ export default TikTokSearch;
src/components/XSearch.tsx ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import { Twitter, ExternalLink, Info, Download } from 'lucide-react';
3
+
4
+ interface XResult {
5
+ url: string;
6
+ name?: string;
7
+ avatar?: string;
8
+ verified?: boolean;
9
+ }
10
+
11
+ interface XSearchProps {
12
+ results: XResult[];
13
+ loading: boolean;
14
+ error: string | null;
15
+ term: string;
16
+ onExport?: () => void;
17
+ }
18
+
19
+ const XSearch: React.FC<XSearchProps> = ({ results, loading, error, term, onExport }) => {
20
+ if (loading && results.length === 0) {
21
+ return (
22
+ <div className="flex flex-col items-center justify-center py-16 anim-fade-in">
23
+ <Twitter className="w-10 h-10 mb-3 anim-pulse" style={{ color: 'var(--text-bright)' }} />
24
+ <p className="text-xs font-mono" style={{ color: 'var(--text-ghost)' }}>scanning x.search("<span style={{ color: 'var(--neon-cyan)' }}>{term}</span>")<span className="anim-blink">_</span></p>
25
+ <div className="prog-bar w-28 mt-3" />
26
+ </div>
27
+ );
28
+ }
29
+
30
+ return (
31
+ <div className="space-y-5 anim-fade-up">
32
+ {error && (
33
+ <div className="err-box">
34
+ <span className="font-mono text-xs">ERR</span>
35
+ <div><span className="font-bold text-sm" style={{ color: '#ff6b6b' }}>{error.includes('stopped by user') ? 'ABORTED' : 'FAILED'}</span><p className="text-xs mt-0.5 opacity-80">{error}</p></div>
36
+ </div>
37
+ )}
38
+ <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-3">
39
+ <div className="flex items-center gap-2">
40
+ <span className="sec-label">results [{results.length}]</span>
41
+ {loading && <span className="text-[10px] font-mono anim-pulse" style={{ color: 'var(--neon-cyan)' }}>expanding...</span>}
42
+ </div>
43
+ {onExport && <button onClick={onExport} disabled={results.length === 0} className="btn-export"><Download size={11} /> EXPORT</button>}
44
+ </div>
45
+
46
+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2">
47
+ {results.length === 0 && !loading ? (
48
+ <div className="col-span-full empty-zone">
49
+ <Twitter className="w-8 h-8 mb-2" style={{ color: 'var(--text-ghost)' }} />
50
+ <p className="text-xs font-mono" style={{ color: 'var(--text-ghost)' }}>// no results for "{term}"</p>
51
+ </div>
52
+ ) : results.map((item, idx) => {
53
+ const handle = item.url.split('/').pop() || 'User';
54
+ const displayName = item.name || handle;
55
+ return (
56
+ <div key={idx} className="r-card group">
57
+ <div className="r-card-border-glow" />
58
+ <div className="flex items-center gap-3 relative z-10">
59
+ <div className="relative">
60
+ <img src={item.avatar ? `/api/proxy-image?url=${encodeURIComponent(item.avatar)}` : `https://ui-avatars.com/api/?name=${displayName}&background=0a0a0f&color=e7e9ea`}
61
+ alt={displayName} className="w-10 h-10 rounded object-cover" style={{ border: '1px solid var(--line)' }}
62
+ onError={(e) => { (e.target as HTMLImageElement).src = `https://ui-avatars.com/api/?name=${displayName}&background=0a0a0f&color=e7e9ea`; }} />
63
+ <div className="absolute -bottom-1 -right-1 w-3.5 h-3.5 rounded flex items-center justify-center" style={{ background: 'var(--bg-raised)', border: '1px solid var(--line)' }}>
64
+ <Twitter size={8} className="fill-current" style={{ color: 'var(--text-bright)' }} />
65
+ </div>
66
+ </div>
67
+ <div className="min-w-0 flex-1">
68
+ <div className="flex items-center gap-1 text-sm font-medium truncate" style={{ color: 'var(--text-bright)' }}>
69
+ {displayName}
70
+ {item.verified && <svg viewBox="0 0 24 24" className="v-badge"><path d="M22.5 12.5c0-1.58-.8-3-2.1-3.88.2-1.6-.2-3.3-1.4-4.5s-2.9-1.6-4.5-1.4c-.88-1.3-2.3-2.1-3.88-2.1s-3 .8-3.88 2.1c-1.6-.2-3.3.2-4.5 1.4s-1.6 2.9-1.4 4.5c-1.3.88-2.1 2.3-2.1 3.88s.8 3 2.1 3.88c-.2 1.6.2 3.3 1.4 4.5s2.9 1.6 4.5 1.4c.88 1.3 2.3 2.1 3.88 2.1s3-.8 3.88-2.1c1.6.2 3.3-.2 4.5-1.4s1.6-2.9 1.4-4.5c1.3-.88 2.1-2.3 2.1-3.88zM10 17l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" /></svg>}
71
+ </div>
72
+ <div className="text-[10px] font-mono truncate" style={{ color: 'var(--text-ghost)' }}>@{handle}</div>
73
+ </div>
74
+ <a href={item.url} target="_blank" rel="noopener noreferrer"
75
+ className="p-1.5 rounded transition-colors" style={{ color: 'var(--text-dim)' }} title="Open"><ExternalLink size={12} /></a>
76
+ </div>
77
+ </div>
78
+ );
79
+ })}
80
+ </div>
81
+ </div>
82
+ );
83
+ };
84
+
85
+ export default XSearch;
src/config.js ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ export const getApiUrl = (path) => {
2
+ const baseUrl = import.meta.env.VITE_API_URL || '';
3
+ return `${baseUrl}${path}`;
4
+ };
src/index.css ADDED
@@ -0,0 +1,664 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@300;400;500;600;700&family=Space+Grotesk:wght@300;400;500;600;700&display=swap');
2
+ @import "tailwindcss";
3
+
4
+ /* ── Design Tokens ── */
5
+ :root {
6
+ /* Background layers */
7
+ --bg-base: #0a0a0f;
8
+ --bg-raised: #12121a;
9
+ --bg-surface: #1a1a25;
10
+ --bg-overlay: rgba(18, 18, 26, 0.85);
11
+
12
+ /* Neon Accents */
13
+ --neon-cyan: #00f0ff;
14
+ --neon-cyan-dim: #00b8c5;
15
+ --neon-cyan-glow: rgba(0, 240, 255, 0.12);
16
+ --neon-cyan-glow-strong: rgba(0, 240, 255, 0.25);
17
+ --neon-green: #00ff88;
18
+ --neon-green-dim: #00c96a;
19
+ --neon-green-glow: rgba(0, 255, 136, 0.12);
20
+ --neon-magenta: #ff00aa;
21
+ --neon-magenta-glow: rgba(255, 0, 170, 0.12);
22
+ --neon-orange: #ff6b2b;
23
+ --neon-red: #ff3355;
24
+ --neon-red-glow: rgba(255, 51, 85, 0.1);
25
+
26
+ /* Platform specific */
27
+ --p-telegram: #2AABEE;
28
+ --p-facebook: #1877F2;
29
+ --p-x: #e7e9ea;
30
+ --p-instagram: #E4405F;
31
+ --p-tiktok: #ff0050;
32
+
33
+ /* Text */
34
+ --text-bright: #e8ecf1;
35
+ --text-normal: #a0aab8;
36
+ --text-dim: #5a6475;
37
+ --text-ghost: #3a4050;
38
+
39
+ /* Borders */
40
+ --line: rgba(0, 240, 255, 0.08);
41
+ --line-active: rgba(0, 240, 255, 0.2);
42
+ --line-glow: rgba(0, 240, 255, 0.35);
43
+
44
+ /* Misc */
45
+ --radius-sm: 4px;
46
+ --radius-md: 6px;
47
+ --radius-lg: 8px;
48
+
49
+ /* Type */
50
+ font-family: 'Space Grotesk', system-ui, -apple-system, sans-serif;
51
+ line-height: 1.5;
52
+ font-weight: 400;
53
+ color-scheme: dark;
54
+ color: var(--text-normal);
55
+ background-color: var(--bg-base);
56
+ font-synthesis: none;
57
+ text-rendering: optimizeLegibility;
58
+ -webkit-font-smoothing: antialiased;
59
+ -moz-osx-font-smoothing: grayscale;
60
+ }
61
+
62
+ /* ── Body ── */
63
+ body {
64
+ margin: 0;
65
+ min-width: 320px;
66
+ min-height: 100vh;
67
+ background-color: var(--bg-base);
68
+ /* Subtle grid pattern */
69
+ background-image:
70
+ linear-gradient(rgba(0, 240, 255, 0.03) 1px, transparent 1px),
71
+ linear-gradient(90deg, rgba(0, 240, 255, 0.03) 1px, transparent 1px);
72
+ background-size: 60px 60px;
73
+ background-attachment: fixed;
74
+ }
75
+
76
+ /* ── Scrollbar ── */
77
+ ::-webkit-scrollbar { width: 5px; height: 5px; }
78
+ ::-webkit-scrollbar-track { background: transparent; }
79
+ ::-webkit-scrollbar-thumb { background: rgba(0, 240, 255, 0.15); border-radius: 0; }
80
+ ::-webkit-scrollbar-thumb:hover { background: rgba(0, 240, 255, 0.3); }
81
+
82
+ /* ── Animations ── */
83
+ @keyframes fadeUp {
84
+ from { opacity: 0; transform: translateY(10px); }
85
+ to { opacity: 1; transform: translateY(0); }
86
+ }
87
+ @keyframes fadeIn {
88
+ from { opacity: 0; }
89
+ to { opacity: 1; }
90
+ }
91
+ @keyframes slideDown {
92
+ from { opacity: 0; transform: translateY(-8px); }
93
+ to { opacity: 1; transform: translateY(0); }
94
+ }
95
+ @keyframes scanline {
96
+ 0% { transform: translateY(-100%); }
97
+ 100% { transform: translateY(100vh); }
98
+ }
99
+ @keyframes pulseNeon {
100
+ 0%, 100% { opacity: 0.6; }
101
+ 50% { opacity: 1; }
102
+ }
103
+ @keyframes blink {
104
+ 0%, 100% { opacity: 1; }
105
+ 50% { opacity: 0; }
106
+ }
107
+ @keyframes dataStream {
108
+ 0% { background-position: 0% 0%; }
109
+ 100% { background-position: 200% 0%; }
110
+ }
111
+ @keyframes spin {
112
+ from { transform: rotate(0deg); }
113
+ to { transform: rotate(360deg); }
114
+ }
115
+ @keyframes glitch {
116
+ 0%, 100% { transform: translate(0); }
117
+ 20% { transform: translate(-1px, 1px); }
118
+ 40% { transform: translate(1px, -1px); }
119
+ 60% { transform: translate(-1px, -1px); }
120
+ 80% { transform: translate(1px, 1px); }
121
+ }
122
+
123
+ .anim-fade-up { animation: fadeUp 0.35s ease-out both; }
124
+ .anim-fade-in { animation: fadeIn 0.3s ease both; }
125
+ .anim-slide-down { animation: slideDown 0.3s ease-out both; }
126
+ .anim-pulse { animation: pulseNeon 2s ease-in-out infinite; }
127
+ .anim-blink { animation: blink 1s step-end infinite; }
128
+
129
+ /* Stagger */
130
+ .stagger > *:nth-child(1) { animation-delay: 0ms; }
131
+ .stagger > *:nth-child(2) { animation-delay: 50ms; }
132
+ .stagger > *:nth-child(3) { animation-delay: 100ms; }
133
+ .stagger > *:nth-child(4) { animation-delay: 150ms; }
134
+ .stagger > *:nth-child(5) { animation-delay: 200ms; }
135
+
136
+ /* ── Mono text ── */
137
+ .font-mono { font-family: 'JetBrains Mono', monospace !important; }
138
+
139
+ /* ── Neon glow text ── */
140
+ .text-neon {
141
+ color: var(--neon-cyan);
142
+ text-shadow: 0 0 8px var(--neon-cyan-glow-strong), 0 0 20px var(--neon-cyan-glow);
143
+ }
144
+ .text-neon-green {
145
+ color: var(--neon-green);
146
+ text-shadow: 0 0 8px var(--neon-green-glow), 0 0 20px rgba(0,255,136,0.08);
147
+ }
148
+
149
+ /* ── Top Nav ── */
150
+ .topnav {
151
+ position: sticky;
152
+ top: 0;
153
+ z-index: 50;
154
+ display: flex;
155
+ align-items: center;
156
+ gap: 1rem;
157
+ padding: 0 1.5rem;
158
+ height: 56px;
159
+ background: var(--bg-raised);
160
+ border-bottom: 1px solid var(--line);
161
+ }
162
+ .topnav::after {
163
+ content: '';
164
+ position: absolute;
165
+ bottom: -1px;
166
+ left: 0;
167
+ right: 0;
168
+ height: 1px;
169
+ background: linear-gradient(90deg, transparent, var(--neon-cyan-glow-strong), transparent);
170
+ }
171
+
172
+ /* ── Nav Tab ── */
173
+ .nav-tab {
174
+ display: flex;
175
+ align-items: center;
176
+ gap: 0.5rem;
177
+ padding: 0.5rem 0.875rem;
178
+ font-size: 0.8125rem;
179
+ font-weight: 500;
180
+ color: var(--text-dim);
181
+ cursor: pointer;
182
+ transition: all 0.15s ease;
183
+ border: none;
184
+ background: none;
185
+ position: relative;
186
+ font-family: inherit;
187
+ border-radius: var(--radius-sm);
188
+ }
189
+ .nav-tab:hover {
190
+ color: var(--text-normal);
191
+ background: rgba(0, 240, 255, 0.04);
192
+ }
193
+ .nav-tab.active {
194
+ color: var(--neon-cyan);
195
+ background: rgba(0, 240, 255, 0.06);
196
+ }
197
+ .nav-tab.active::after {
198
+ content: '';
199
+ position: absolute;
200
+ bottom: -12px;
201
+ left: 15%;
202
+ right: 15%;
203
+ height: 2px;
204
+ background: var(--neon-cyan);
205
+ box-shadow: 0 0 6px var(--neon-cyan-glow-strong);
206
+ border-radius: 2px;
207
+ }
208
+
209
+ /* ── Status dot ── */
210
+ .status-dot {
211
+ width: 6px;
212
+ height: 6px;
213
+ border-radius: 50%;
214
+ background: var(--neon-green);
215
+ box-shadow: 0 0 4px var(--neon-green-glow);
216
+ animation: pulseNeon 2.5s ease-in-out infinite;
217
+ }
218
+
219
+ /* ── Panel (card container) ── */
220
+ .panel {
221
+ background: var(--bg-raised);
222
+ background-image:
223
+ linear-gradient(rgba(0, 240, 255, 0.015) 1px, transparent 1px),
224
+ linear-gradient(90deg, rgba(0, 240, 255, 0.015) 1px, transparent 1px);
225
+ background-size: 30px 30px;
226
+ border: 1px solid var(--line);
227
+ border-radius: var(--radius-md);
228
+ position: relative;
229
+ }
230
+ .panel-header {
231
+ display: flex;
232
+ align-items: center;
233
+ justify-content: space-between;
234
+ padding: 0.875rem 1.25rem;
235
+ border-bottom: 1px solid var(--line);
236
+ font-size: 0.75rem;
237
+ font-weight: 600;
238
+ text-transform: uppercase;
239
+ letter-spacing: 0.08em;
240
+ color: var(--text-dim);
241
+ font-family: 'JetBrains Mono', monospace;
242
+ }
243
+
244
+ /* ── Result Card ── */
245
+ .r-card {
246
+ padding: 0.875rem 1rem;
247
+ background: var(--bg-raised);
248
+ border: 1px solid var(--line);
249
+ border-radius: var(--radius-md);
250
+ transition: all 0.2s ease;
251
+ position: relative;
252
+ }
253
+ .r-card:hover {
254
+ border-color: var(--line-active);
255
+ background: var(--bg-surface);
256
+ box-shadow: 0 0 20px var(--neon-cyan-glow), inset 0 0 20px rgba(0, 240, 255, 0.02);
257
+ }
258
+ .r-card:hover .r-card-border-glow {
259
+ opacity: 1;
260
+ }
261
+ .r-card-border-glow {
262
+ position: absolute;
263
+ top: -1px;
264
+ left: 10%;
265
+ right: 10%;
266
+ height: 1px;
267
+ background: linear-gradient(90deg, transparent, var(--neon-cyan), transparent);
268
+ opacity: 0;
269
+ transition: opacity 0.3s ease;
270
+ }
271
+
272
+ /* ── Input ── */
273
+ .cyber-input {
274
+ width: 100%;
275
+ padding: 0.75rem 1rem;
276
+ font-size: 0.9375rem;
277
+ font-family: 'JetBrains Mono', monospace;
278
+ background: var(--bg-base);
279
+ border: 1px solid var(--line);
280
+ border-radius: var(--radius-sm);
281
+ color: var(--text-bright);
282
+ outline: none;
283
+ transition: all 0.15s ease;
284
+ }
285
+ .cyber-input::placeholder {
286
+ color: var(--text-ghost);
287
+ font-family: 'Space Grotesk', sans-serif;
288
+ }
289
+ .cyber-input:focus {
290
+ border-color: var(--neon-cyan-dim);
291
+ box-shadow: 0 0 0 2px var(--neon-cyan-glow), 0 0 16px var(--neon-cyan-glow);
292
+ }
293
+ .cyber-input:disabled {
294
+ opacity: 0.4;
295
+ }
296
+
297
+ /* ── Button: Primary ── */
298
+ .btn-neon {
299
+ display: inline-flex;
300
+ align-items: center;
301
+ justify-content: center;
302
+ gap: 0.5rem;
303
+ padding: 0.688rem 1.25rem;
304
+ font-size: 0.8125rem;
305
+ font-weight: 600;
306
+ font-family: 'JetBrains Mono', monospace;
307
+ text-transform: uppercase;
308
+ letter-spacing: 0.05em;
309
+ border: 1px solid var(--neon-cyan-dim);
310
+ border-radius: var(--radius-sm);
311
+ cursor: pointer;
312
+ transition: all 0.15s ease;
313
+ background: rgba(0, 240, 255, 0.08);
314
+ color: var(--neon-cyan);
315
+ position: relative;
316
+ overflow: hidden;
317
+ }
318
+ .btn-neon::before {
319
+ content: '';
320
+ position: absolute;
321
+ inset: 0;
322
+ background: linear-gradient(90deg, transparent, rgba(0,240,255,0.06), transparent);
323
+ background-size: 200% 100%;
324
+ animation: dataStream 3s linear infinite;
325
+ }
326
+ .btn-neon:hover:not(:disabled) {
327
+ background: rgba(0, 240, 255, 0.14);
328
+ box-shadow: 0 0 20px var(--neon-cyan-glow), 0 0 40px rgba(0,240,255,0.06);
329
+ border-color: var(--neon-cyan);
330
+ text-shadow: 0 0 6px var(--neon-cyan-glow-strong);
331
+ }
332
+ .btn-neon:active:not(:disabled) { transform: scale(0.98); }
333
+ .btn-neon:disabled { opacity: 0.3; cursor: not-allowed; }
334
+
335
+ /* Button: Ghost */
336
+ .btn-dim {
337
+ display: inline-flex;
338
+ align-items: center;
339
+ justify-content: center;
340
+ gap: 0.4rem;
341
+ padding: 0.5rem 0.875rem;
342
+ font-size: 0.75rem;
343
+ font-weight: 500;
344
+ font-family: inherit;
345
+ border: 1px solid var(--line);
346
+ border-radius: var(--radius-sm);
347
+ cursor: pointer;
348
+ transition: all 0.15s ease;
349
+ background: transparent;
350
+ color: var(--text-dim);
351
+ }
352
+ .btn-dim:hover {
353
+ border-color: var(--line-active);
354
+ color: var(--text-normal);
355
+ background: rgba(0, 240, 255, 0.03);
356
+ }
357
+
358
+ /* Button: Stop/Danger */
359
+ .btn-abort {
360
+ display: inline-flex;
361
+ align-items: center;
362
+ justify-content: center;
363
+ gap: 0.5rem;
364
+ padding: 0.688rem 1.25rem;
365
+ font-size: 0.8125rem;
366
+ font-weight: 600;
367
+ font-family: 'JetBrains Mono', monospace;
368
+ text-transform: uppercase;
369
+ letter-spacing: 0.05em;
370
+ border: 1px solid var(--neon-red);
371
+ border-radius: var(--radius-sm);
372
+ cursor: pointer;
373
+ transition: all 0.15s ease;
374
+ background: var(--neon-red-glow);
375
+ color: var(--neon-red);
376
+ }
377
+ .btn-abort:hover {
378
+ background: rgba(255, 51, 85, 0.2);
379
+ box-shadow: 0 0 20px var(--neon-red-glow);
380
+ }
381
+
382
+ /* Button: Export */
383
+ .btn-export {
384
+ display: inline-flex;
385
+ align-items: center;
386
+ gap: 0.4rem;
387
+ padding: 0.4rem 0.75rem;
388
+ font-size: 0.6875rem;
389
+ font-weight: 600;
390
+ font-family: 'JetBrains Mono', monospace;
391
+ text-transform: uppercase;
392
+ letter-spacing: 0.06em;
393
+ border: 1px solid rgba(0, 255, 136, 0.2);
394
+ border-radius: var(--radius-sm);
395
+ cursor: pointer;
396
+ transition: all 0.15s ease;
397
+ background: rgba(0, 255, 136, 0.05);
398
+ color: var(--neon-green-dim);
399
+ }
400
+ .btn-export:hover:not(:disabled) {
401
+ background: rgba(0, 255, 136, 0.1);
402
+ border-color: rgba(0, 255, 136, 0.35);
403
+ box-shadow: 0 0 12px var(--neon-green-glow);
404
+ color: var(--neon-green);
405
+ }
406
+ .btn-export:disabled { opacity: 0.25; cursor: not-allowed; }
407
+
408
+ /* ── Tag / Badge ── */
409
+ .tag {
410
+ display: inline-flex;
411
+ align-items: center;
412
+ gap: 0.2rem;
413
+ padding: 0.15rem 0.5rem;
414
+ font-size: 0.625rem;
415
+ font-weight: 600;
416
+ font-family: 'JetBrains Mono', monospace;
417
+ text-transform: uppercase;
418
+ letter-spacing: 0.06em;
419
+ border-radius: var(--radius-sm);
420
+ border: 1px solid;
421
+ }
422
+
423
+ /* ── Selection Chip (filter) ── */
424
+ .sel-chip {
425
+ flex: 1;
426
+ padding: 0.5rem 0.625rem;
427
+ font-size: 0.75rem;
428
+ font-weight: 500;
429
+ text-align: center;
430
+ cursor: pointer;
431
+ transition: all 0.15s ease;
432
+ border: 1px solid var(--line);
433
+ background: transparent;
434
+ color: var(--text-dim);
435
+ font-family: 'JetBrains Mono', monospace;
436
+ border-radius: var(--radius-sm);
437
+ }
438
+ .sel-chip:hover {
439
+ color: var(--text-normal);
440
+ border-color: var(--line-active);
441
+ background: rgba(0, 240, 255, 0.03);
442
+ }
443
+ .sel-chip.on {
444
+ color: var(--neon-cyan);
445
+ background: rgba(0, 240, 255, 0.06);
446
+ border-color: rgba(0, 240, 255, 0.25);
447
+ box-shadow: inset 0 0 12px var(--neon-cyan-glow);
448
+ }
449
+
450
+ /* ── Error ── */
451
+ .err-box {
452
+ display: flex;
453
+ align-items: flex-start;
454
+ gap: 0.75rem;
455
+ padding: 0.875rem 1rem;
456
+ border-radius: var(--radius-sm);
457
+ background: var(--neon-red-glow);
458
+ border: 1px solid rgba(255, 51, 85, 0.2);
459
+ color: #fca5a5;
460
+ font-size: 0.8125rem;
461
+ }
462
+
463
+ /* ── Success ── */
464
+ .ok-box {
465
+ display: flex;
466
+ flex-direction: column;
467
+ align-items: center;
468
+ justify-content: center;
469
+ gap: 0.5rem;
470
+ padding: 2rem;
471
+ color: var(--neon-green);
472
+ text-align: center;
473
+ }
474
+
475
+ /* ── Auth panel ── */
476
+ .auth-panel {
477
+ position: relative;
478
+ padding: 1.75rem;
479
+ background: var(--bg-raised);
480
+ background-image:
481
+ linear-gradient(rgba(0, 240, 255, 0.02) 1px, transparent 1px),
482
+ linear-gradient(90deg, rgba(0, 240, 255, 0.02) 1px, transparent 1px);
483
+ background-size: 20px 20px;
484
+ border: 1px solid var(--line);
485
+ border-radius: var(--radius-md);
486
+ overflow: hidden;
487
+ }
488
+ .auth-panel::before {
489
+ content: '';
490
+ position: absolute;
491
+ top: 0;
492
+ left: 0;
493
+ right: 0;
494
+ height: 2px;
495
+ background: linear-gradient(90deg, transparent, var(--neon-cyan), transparent);
496
+ }
497
+ .auth-panel::after {
498
+ content: '';
499
+ position: absolute;
500
+ top: 0;
501
+ left: -100%;
502
+ width: 50%;
503
+ height: 2px;
504
+ background: linear-gradient(90deg, transparent, var(--neon-green), transparent);
505
+ animation: dataStream 4s linear infinite;
506
+ }
507
+
508
+ /* ── Empty state ── */
509
+ .empty-zone {
510
+ display: flex;
511
+ flex-direction: column;
512
+ align-items: center;
513
+ justify-content: center;
514
+ padding: 2.5rem 1rem;
515
+ text-align: center;
516
+ border: 1px dashed var(--line);
517
+ border-radius: var(--radius-md);
518
+ background: rgba(10, 10, 15, 0.5);
519
+ }
520
+
521
+ /* ── Progress bar ── */
522
+ .prog-bar {
523
+ position: relative;
524
+ height: 2px;
525
+ background: rgba(0, 240, 255, 0.06);
526
+ overflow: hidden;
527
+ }
528
+ .prog-bar::after {
529
+ content: '';
530
+ position: absolute;
531
+ inset: 0;
532
+ background: linear-gradient(90deg, var(--neon-cyan), var(--neon-green), var(--neon-cyan));
533
+ background-size: 200% 100%;
534
+ animation: dataStream 1.5s linear infinite;
535
+ }
536
+
537
+ /* ── Label / Section header ── */
538
+ .sec-label {
539
+ font-size: 0.625rem;
540
+ font-weight: 700;
541
+ font-family: 'JetBrains Mono', monospace;
542
+ text-transform: uppercase;
543
+ letter-spacing: 0.12em;
544
+ color: var(--text-ghost);
545
+ display: flex;
546
+ align-items: center;
547
+ gap: 0.4rem;
548
+ }
549
+ .sec-label::before {
550
+ content: '//';
551
+ color: var(--neon-cyan-dim);
552
+ opacity: 0.5;
553
+ }
554
+
555
+ /* ── Verified badge ── */
556
+ .v-badge {
557
+ width: 0.875rem;
558
+ height: 0.875rem;
559
+ flex-shrink: 0;
560
+ fill: var(--neon-cyan-dim);
561
+ }
562
+
563
+ /* ── Scanline overlay effect (optional subtle) ── */
564
+ .scanline-overlay {
565
+ pointer-events: none;
566
+ position: fixed;
567
+ inset: 0;
568
+ z-index: 9999;
569
+ background: repeating-linear-gradient(
570
+ 0deg,
571
+ transparent,
572
+ transparent 2px,
573
+ rgba(0, 0, 0, 0.03) 2px,
574
+ rgba(0, 0, 0, 0.03) 4px
575
+ );
576
+ opacity: 1;
577
+ }
578
+ /* ── Status Hub Dashboard ── */
579
+ .status-card {
580
+ background: var(--bg-raised);
581
+ border: 1px solid var(--line);
582
+ border-radius: var(--radius-md);
583
+ overflow: hidden;
584
+ transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
585
+ position: relative;
586
+ }
587
+
588
+ .status-card:hover {
589
+ transform: translateY(-2px);
590
+ border-color: var(--line-active);
591
+ box-shadow: 0 10px 30px -10px rgba(0, 0, 0, 0.5), 0 0 20px rgba(0, 240, 255, 0.05);
592
+ }
593
+
594
+ .status-card-header {
595
+ padding: 1rem 1.25rem;
596
+ border-bottom: 1px dotted var(--line);
597
+ display: flex;
598
+ align-items: center;
599
+ justify-content: space-between;
600
+ background: linear-gradient(to bottom, rgba(255,255,255,0.02), transparent);
601
+ }
602
+
603
+ .status-card-body {
604
+ padding: 1.25rem;
605
+ }
606
+
607
+ .status-pill {
608
+ padding: 0.2rem 0.6rem;
609
+ font-family: 'JetBrains Mono', monospace;
610
+ font-size: 0.65rem;
611
+ font-weight: 700;
612
+ border-radius: 4px;
613
+ letter-spacing: 0.05em;
614
+ position: relative;
615
+ }
616
+
617
+ .status-pill.online {
618
+ background: rgba(34, 197, 94, 0.1);
619
+ color: var(--neon-green);
620
+ border: 1px solid rgba(34, 197, 94, 0.3);
621
+ box-shadow: 0 0 10px rgba(34, 197, 94, 0.1);
622
+ }
623
+
624
+ .status-pill.online::before {
625
+ content: '';
626
+ position: absolute;
627
+ left: -4px;
628
+ top: 50%;
629
+ transform: translateY(-50%);
630
+ width: 2px;
631
+ height: 8px;
632
+ background: var(--neon-green);
633
+ box-shadow: 0 0 6px var(--neon-green-glow);
634
+ }
635
+
636
+ .status-pill.offline {
637
+ background: rgba(239, 68, 68, 0.1);
638
+ color: #ef4444;
639
+ border: 1px solid rgba(239, 68, 68, 0.3);
640
+ }
641
+
642
+ .status-pill.offline::before {
643
+ content: '';
644
+ position: absolute;
645
+ left: -4px;
646
+ top: 50%;
647
+ transform: translateY(-50%);
648
+ width: 2px;
649
+ height: 8px;
650
+ background: #ef4444;
651
+ }
652
+
653
+ .status-label {
654
+ color: var(--text-dim);
655
+ text-transform: uppercase;
656
+ font-size: 0.625rem;
657
+ letter-spacing: 0.1em;
658
+ }
659
+
660
+ .status-val {
661
+ color: var(--text-bright);
662
+ font-family: 'JetBrains Mono', monospace;
663
+ font-size: 0.75rem;
664
+ }
src/main.jsx ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import './polyfills'
2
+ import React, { Component, StrictMode } from 'react'
3
+ import { createRoot } from 'react-dom/client'
4
+ import './index.css'
5
+ import App from './App.jsx'
6
+
7
+ class ErrorBoundary extends Component {
8
+ constructor(props) {
9
+ super(props);
10
+ this.state = { hasError: false, error: null };
11
+ }
12
+ static getDerivedStateFromError(error) {
13
+ return { hasError: true, error };
14
+ }
15
+ componentDidCatch(error, errorInfo) {
16
+ console.error("ErrorBoundary caught an error", error, errorInfo);
17
+ }
18
+ render() {
19
+ if (this.state.hasError) {
20
+ return (
21
+ <div className="p-20 text-red-500 bg-slate-100 min-h-screen">
22
+ <h1 className="text-2xl font-bold mb-4 text-red-600">Something went wrong.</h1>
23
+ <pre className="whitespace-pre-wrap text-slate-900 bg-slate-200 p-4 rounded border border-red-300 overflow-auto">
24
+ {this.state.error.stack || this.state.error.message}
25
+ </pre>
26
+ </div>
27
+ );
28
+ }
29
+ return this.props.children;
30
+ }
31
+ }
32
+
33
+ createRoot(document.getElementById('root')).render(
34
+ <StrictMode>
35
+ <ErrorBoundary>
36
+ <App />
37
+ </ErrorBoundary>
38
+ </StrictMode>,
39
+ )
src/polyfills.js ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import util from 'util'
2
+ import { Buffer } from 'buffer'
3
+ import process from 'process'
4
+
5
+ window.util = util
6
+ window.Buffer = Buffer
7
+ window.process = process
8
+ window.global = window
tiktok-search-main/tiktokSearch.js ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { chromium } from 'playwright-extra';
2
+ import stealth from 'puppeteer-extra-plugin-stealth';
3
+ import path from 'path';
4
+ import fs from 'fs';
5
+
6
+ // Apply stealth plugin
7
+ chromium.use(stealth());
8
+
9
+ /**
10
+ * Extracts TikTok profile URLs using the Direct URL method with cache-busting 't' parameter.
11
+ * Also implements a Grid-targeted scroll to bypass height stalls on the new UI.
12
+ */
13
+ async function extractTikTokUrls(searchTerm, onNewUrl = null, onProgress = null) {
14
+ const urls = new Map();
15
+ const browser = await chromium.launch({
16
+ headless: process.env.HEADLESS !== 'false',
17
+ args: [
18
+ '--no-sandbox',
19
+ '--disable-setuid-sandbox',
20
+ '--disable-dev-shm-usage',
21
+ '--disable-gpu',
22
+ '--disable-blink-features=AutomationControlled'
23
+ ]
24
+ });
25
+ if (onProgress) onProgress("Browser launched.");
26
+
27
+ const context = await browser.newContext({
28
+ viewport: { width: 1440, height: 900 },
29
+ userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
30
+ });
31
+
32
+ const page = await context.newPage();
33
+ if (onProgress) onProgress("Page created.");
34
+
35
+ // Helper to dismiss common overlays
36
+ const closeLoginModal = async () => {
37
+ try {
38
+ const selectors = [
39
+ '[data-e2e="modal-close-inner-button"]',
40
+ '.tiktok-14yv632-ButtonClose',
41
+ 'div[class*="ButtonClose"]',
42
+ 'div[aria-label="Close"]',
43
+ '#login-modal + div button'
44
+ ];
45
+ for (const sel of selectors) {
46
+ const btn = page.locator(sel).first();
47
+ if (await btn.isVisible()) {
48
+ await btn.click();
49
+ await page.waitForTimeout(500);
50
+ }
51
+ }
52
+ } catch (e) {}
53
+ };
54
+
55
+ try {
56
+ // 1. Direct URL Navigation with 't' parameter for freshness
57
+ const timestamp = Date.now();
58
+ const searchUrl = `https://www.tiktok.com/search/user?q=${encodeURIComponent(searchTerm)}&t=${timestamp}`;
59
+
60
+ if (onProgress) onProgress(`Navigating directly to TikTok Search (with t=${timestamp})...`);
61
+ try {
62
+ await page.goto(searchUrl, { waitUntil: 'domcontentloaded', timeout: 60000 });
63
+ if (onProgress) onProgress("Navigation successful.");
64
+ } catch (gotoErr) {
65
+ if (onProgress) onProgress(`Navigation failed: ${gotoErr.message}`);
66
+ throw gotoErr;
67
+ }
68
+
69
+ // Wait for results grid to mount
70
+ if (onProgress) onProgress(`Waiting for results grid to stabilize...`);
71
+ try {
72
+ await page.waitForSelector('main#grid-main, [data-e2e="search-user-container"]', { timeout: 15000 });
73
+ } catch (e) {
74
+ if (onProgress) onProgress(`Grid taking time to load, continuing anyway...`);
75
+ }
76
+
77
+ await page.waitForTimeout(3000);
78
+ await closeLoginModal();
79
+
80
+ // 2. Extraction & Deep Scroll loop targeting the specific Grid Container
81
+ if (onProgress) onProgress(`Starting deep grid-scroll extraction (Profiles only)...`);
82
+
83
+ const extractVisible = async () => {
84
+ const results = await page.evaluate(() => {
85
+ const items = [];
86
+ const seen = new Set();
87
+ const selectors = [
88
+ '[class*="DivSearchUserItemContainer"]',
89
+ '[class*="UserItem"]',
90
+ 'main#grid-main a[href*="/@"]',
91
+ '[data-e2e="search-user-container"]'
92
+ ];
93
+
94
+ const containers = document.querySelectorAll(selectors.join(', '));
95
+
96
+ containers.forEach(container => {
97
+ // Try to find the link in container, parent, or sibling
98
+ let link = container.querySelector('a[href*="/@"]') ||
99
+ (container.tagName === 'A' ? container : null) ||
100
+ (container.parentElement && container.parentElement.querySelector('a[href*="/@"]'));
101
+
102
+ let href = link ? link.getAttribute('href').split('?')[0] : '';
103
+ let fullUrl = href ? (href.startsWith('http') ? href : 'https://www.tiktok.com' + href) : '';
104
+
105
+ // Exclude non-profiles
106
+ if (fullUrl && (fullUrl.includes('/video/') || fullUrl.includes('/photo/'))) return;
107
+
108
+ let username = '';
109
+ let nickname = '';
110
+ let avatar = '';
111
+
112
+ try {
113
+ // Priority 1: Modern TUX Text classes (Found in diagnostic)
114
+ const nicknameEl = container.querySelector('[class*="TUXText--weight-bold"], [data-e2e="search-user-user-title"], [class*="Nickname"], p.tux-typography--title-m-bold');
115
+ const usernameEl = container.querySelector('[class*="TUXText--weight-normal"], [data-e2e="search-user-unique-id"], [class*="UniqueId"], p.tux-typography--body-m-regular');
116
+ const imgEl = container.querySelector('img.user-avatar, img');
117
+
118
+ nickname = nicknameEl ? nicknameEl.innerText.trim() : '';
119
+ username = usernameEl ? usernameEl.innerText.trim().replace('@', '') : '';
120
+
121
+ // Fallback: If username still empty, try to get from href
122
+ if (!username && fullUrl) {
123
+ const parts = fullUrl.split('/@');
124
+ if (parts.length > 1) username = parts[1];
125
+ }
126
+
127
+ avatar = imgEl ? imgEl.src : '';
128
+ } catch (e) {}
129
+
130
+ if (username) {
131
+ if (!fullUrl) fullUrl = `https://www.tiktok.com/@${username}`;
132
+ if (seen.has(fullUrl)) return;
133
+ seen.add(fullUrl);
134
+ items.push({ url: fullUrl, username, nickname, avatar });
135
+ }
136
+ });
137
+ return items;
138
+ });
139
+
140
+ let newCount = 0;
141
+ for (const item of results) {
142
+ if (!urls.has(item.url)) {
143
+ urls.set(item.url, item);
144
+ newCount++;
145
+ if (onNewUrl) onNewUrl(item);
146
+ }
147
+ }
148
+ return newCount;
149
+ };
150
+
151
+ let lastHeight = 0;
152
+ let scrollRetries = 0;
153
+ const maxScrollRetries = 10;
154
+ let endReached = false;
155
+
156
+ const getGridHeight = async () => {
157
+ return await page.evaluate(() => {
158
+ const grid = document.querySelector('main#grid-main');
159
+ return grid ? grid.scrollHeight : document.body.scrollHeight;
160
+ });
161
+ };
162
+
163
+ while (!endReached) {
164
+ await extractVisible();
165
+ if (onProgress) onProgress(`Collected ${urls.size} profiles...`);
166
+
167
+ // Check for "End of results" message
168
+ endReached = await page.evaluate(() => {
169
+ const text = document.body.innerText.toLowerCase();
170
+ const markers = ["end of results", "no more results", "reached the end"];
171
+ return markers.some(m => text.includes(m)) || !!document.querySelector('[data-e2e="search-no-results"]');
172
+ });
173
+
174
+ if (endReached) {
175
+ if (onProgress) onProgress(`"End of results" detected.`);
176
+ break;
177
+ }
178
+
179
+ // Target the grid container specifically for scrolling to avoid stalling
180
+ await page.evaluate(() => {
181
+ const grid = document.querySelector('main#grid-main');
182
+ if (grid) {
183
+ grid.scrollBy(0, 5000);
184
+ } else {
185
+ window.scrollBy(0, 5000);
186
+ }
187
+ });
188
+
189
+ await page.waitForTimeout(3000); // Wait for lazy load
190
+
191
+ const currentHeight = await getGridHeight();
192
+ if (currentHeight === lastHeight) {
193
+ scrollRetries++;
194
+ if (onProgress && scrollRetries > 2) onProgress(`Grid height stalling (${scrollRetries}/${maxScrollRetries})...`);
195
+ if (scrollRetries >= maxScrollRetries) break;
196
+ } else {
197
+ scrollRetries = 0;
198
+ await closeLoginModal();
199
+ }
200
+ lastHeight = currentHeight;
201
+
202
+ if (urls.size >= 5000) break;
203
+ }
204
+
205
+ await extractVisible();
206
+ if (onProgress) onProgress(`Extraction finished. Total: ${urls.size} profiles.`);
207
+
208
+ } catch (err) {
209
+ if (onProgress) onProgress(`Error during TikTok scraping: ${err.message}`);
210
+ throw err;
211
+ } finally {
212
+ await browser.close();
213
+ }
214
+
215
+ return Array.from(urls.values());
216
+ }
217
+
218
+ export { extractTikTokUrls };
vercel.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "version": 2,
3
+ "rewrites": [
4
+ { "source": "/(.*)", "destination": "/index.html" }
5
+ ]
6
+ }
vite.config.js ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { defineConfig } from 'vite'
2
+ import react from '@vitejs/plugin-react'
3
+ import { nodePolyfills } from 'vite-plugin-node-polyfills'
4
+ import tailwindcss from '@tailwindcss/vite'
5
+
6
+ // https://vite.dev/config/
7
+ export default defineConfig({
8
+ define: {
9
+ global: 'globalThis',
10
+ 'process.env': {},
11
+ },
12
+ plugins: [
13
+ react(),
14
+ tailwindcss(),
15
+ nodePolyfills({
16
+ // To run GramJS in the browser, we need specific polyfills
17
+ include: ['crypto', 'path', 'os', 'stream', 'buffer', 'net', 'util', 'process'],
18
+ globals: {
19
+ Buffer: true,
20
+ global: true,
21
+ process: true,
22
+ },
23
+ protocolImports: true,
24
+ }),
25
+ ],
26
+ resolve: {
27
+ alias: {
28
+ util: 'util',
29
+ },
30
+ },
31
+ server: {
32
+ proxy: {
33
+ '/api': {
34
+ target: 'http://localhost:3001',
35
+ changeOrigin: true,
36
+ ws: true,
37
+ },
38
+ },
39
+ },
40
+ })
x-search-master/.gitignore ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ venv/
2
+ __pycache__/
3
+ *.pyc
4
+ *.pyo
5
+ *.pyd
6
+ .Python
7
+ env/
8
+ pip-log.txt
9
+ pip-delete-this-directory.txt
10
+ .tox/
11
+ .coverage
12
+ .coverage.*
13
+ .cache
14
+ nosetests.xml
15
+ coverage.xml
16
+ *.cover
17
+ *.log
18
+ .git
19
+ .mypy_cache
20
+ .pytest_cache
21
+ .hypothesis
22
+ debug_*.html
23
+ debug_*.png
24
+ *.xlsx
25
+ x_cookies.json
26
+ x_user_data/
x-search-master/README.md ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # X Search Automation
2
+
3
+ This project automates the process of searching for user profiles on X (formerly Twitter) and saving the results to an Excel file. It uses Playwright for browser automation to handle dynamic content and anti-scraping measures.
4
+
5
+ ## Features
6
+
7
+ - **Automated Login**: Uses a persistent browser context to maintain session state and bypass login checks.
8
+ - **Stealth Mode**: Implements anti-detection techniques to mimic real user behavior.
9
+ - **Smart Filtering**: Specifically targets user profile links (`UserCell`) and ignores irrelevant content (ads, internal routes, etc.).
10
+ - **Excel Export**: unique results are automatically saved to a timestamped Excel file.
11
+
12
+ ## Prerequisites
13
+
14
+ - Python 3.7+
15
+ - Google Chrome installed
16
+
17
+ ## Setup
18
+
19
+ 1. **Clone the repository**:
20
+ ```bash
21
+ git clone https://github.com/InvertedShu/x-search.git
22
+ cd x-search
23
+ ```
24
+
25
+ 2. **Run the setup script**:
26
+ This script creates a virtual environment, installs dependencies (`playwright`, `pandas`, `openpyxl`), and sets up the browser.
27
+ ```bash
28
+ python setup_environment.py
29
+ ```
30
+
31
+ ## Usage
32
+
33
+ 1. **Run the search script**:
34
+ Pass your search term as a command-line argument.
35
+ ```bash
36
+ .\venv\Scripts\python.exe X_search.py "your search term"
37
+ ```
38
+ *Example:*
39
+ ```bash
40
+ .\venv\Scripts\python.exe X_search.py "new york stock exchange"
41
+ ```
42
+
43
+ 2. **Output**:
44
+ Results will be saved to an Excel file named `x_search_<term>_<timestamp>.xlsx` in the project directory.
45
+
46
+ ## File Structure
47
+
48
+ - `X_search.py`: Main script for searching and extracting URLs.
49
+ - `x_cookies.py`: Handles initial login and cookie generation (if needed).
50
+ - `setup_environment.py`: Automates dependency installation and environment setup.
51
+ - `x_user_data/`: Directory storing persistent browser profile data (do not delete to maintain login).
52
+
53
+ ## Disclaimer
54
+
55
+ This tool is for educational purposes only. Please respect X's Terms of Service and robots.txt.
x-search-master/xCookies.js ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { chromium } from 'playwright';
2
+ import path from 'path';
3
+ import { fileURLToPath } from 'url';
4
+
5
+ const __filename = fileURLToPath(import.meta.url);
6
+ const __dirname = path.dirname(__filename);
7
+
8
+ async function launchXAutoAuth() {
9
+ const userDataDir = path.join(__dirname, 'x_user_data');
10
+ const isHeadless = process.env.HEADLESS !== 'false';
11
+ const browser = await chromium.launchPersistentContext(userDataDir, {
12
+ headless: isHeadless,
13
+ args: ['--disable-blink-features=AutomationControlled', '--no-sandbox', '--disable-dev-shm-usage', '--disable-gpu'],
14
+ userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
15
+ });
16
+
17
+ const page = browser.pages()[0] || await browser.newPage();
18
+
19
+ try {
20
+ console.log('[*] Opening X (Twitter)...');
21
+ await page.goto('https://x.com/', { timeout: 60000 });
22
+
23
+ console.log('[*] Waiting for user to log in manually...');
24
+ let loggedIn = false;
25
+
26
+ // Wait up to 5 minutes
27
+ for (let i = 0; i < 300; i++) {
28
+ await new Promise(r => setTimeout(r, 1000));
29
+ try {
30
+ if (page.isClosed()) break;
31
+ // Check for 'auth_token' or 'twid' cookie
32
+ const cookies = await browser.cookies();
33
+ if (cookies.some(c => c.name === 'auth_token' || c.name === 'twid')) {
34
+ loggedIn = true;
35
+ break;
36
+ }
37
+
38
+ // Or check for navigation to home / feed
39
+ if (page.url().includes('home') || page.url().includes('x.com/home')) {
40
+ loggedIn = true;
41
+ break;
42
+ }
43
+ } catch (e) {
44
+ break;
45
+ }
46
+ }
47
+
48
+ if (loggedIn) {
49
+ console.log('[*] Login detected!');
50
+ await new Promise(r => setTimeout(r, 3000));
51
+ return { success: true, message: 'Authentication successful and saved!' };
52
+ } else {
53
+ return { success: false, error: 'Login timed out or browser was closed.' };
54
+ }
55
+ } catch (e) {
56
+ return { success: false, error: e.message };
57
+ } finally {
58
+ try { await browser.close(); } catch (e) {}
59
+ }
60
+ }
61
+
62
+ export { launchXAutoAuth };
x-search-master/xSearch.js ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { chromium } from 'playwright-extra';
2
+ import stealth from 'puppeteer-extra-plugin-stealth';
3
+ import path from 'path';
4
+ import fs from 'fs';
5
+ import { fileURLToPath } from 'url';
6
+
7
+ const __filename = fileURLToPath(import.meta.url);
8
+ const __dirname = path.dirname(__filename);
9
+
10
+ // Apply stealth plugin
11
+ chromium.use(stealth());
12
+
13
+ /**
14
+ * Extracts X (Twitter) profile URLs using direct search navigation.
15
+ */
16
+ async function extractXUserUrls(searchTerm, onNewUrl = null, onProgress = null) {
17
+ const urls = new Map();
18
+ const encodedTerm = encodeURIComponent(searchTerm);
19
+ const searchUrl = `https://x.com/search?q=${encodedTerm}&src=typed_query&f=user`;
20
+
21
+ const userDataDir = path.resolve(__dirname, 'x_user_data');
22
+ const cookieFile = path.resolve(__dirname, 'x_cookies.json');
23
+
24
+ if (!fs.existsSync(userDataDir)) fs.mkdirSync(userDataDir, { recursive: true });
25
+
26
+ const isHeadless = process.env.HEADLESS !== 'false';
27
+
28
+ // Launch Options
29
+ const launchOptions = {
30
+ headless: isHeadless,
31
+ args: [
32
+ '--no-sandbox',
33
+ '--disable-setuid-sandbox',
34
+ '--disable-dev-shm-usage',
35
+ '--disable-gpu',
36
+ '--disable-blink-features=AutomationControlled'
37
+ ],
38
+ userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
39
+ viewport: { width: 1280, height: 720 }
40
+ };
41
+
42
+ let browserContext;
43
+ if (fs.existsSync(cookieFile)) {
44
+ if (onProgress) onProgress(`Using X cookie file for session...`);
45
+ const baseBrowser = await chromium.launch({ headless: isHeadless });
46
+ browserContext = await baseBrowser.newContext({ ...launchOptions, storageState: cookieFile });
47
+ } else {
48
+ if (onProgress) onProgress(`Using X persistent user data directory...`);
49
+ browserContext = await chromium.launchPersistentContext(userDataDir, launchOptions);
50
+ }
51
+
52
+ const page = browserContext.pages()[0] || await browserContext.newPage();
53
+
54
+ try {
55
+ // 1. Open X and wait for transition
56
+ if (onProgress) onProgress(`Navigating to X search results...`);
57
+ await page.goto(searchUrl, { timeout: 60000, waitUntil: 'domcontentloaded' });
58
+
59
+ try {
60
+ await page.waitForSelector('[data-testid="primaryColumn"]', { timeout: 30000 });
61
+ } catch (e) {
62
+ if (onProgress) onProgress('Search results taking long to load, continuing anyway...');
63
+ }
64
+
65
+ const extractVisibleUrls = async () => {
66
+ try {
67
+ const elements = await page.locator('[data-testid="UserCell"]').all();
68
+ let countNew = 0;
69
+
70
+ for (const cell of elements) {
71
+ try {
72
+ const linkEl = cell.locator('a[href^="/"]').first();
73
+ const href = await linkEl.getAttribute('href');
74
+ if (!href) continue;
75
+
76
+ const fullUrl = `https://x.com${href}`;
77
+ const cleanUrl = fullUrl.split('?')[0];
78
+
79
+ // Skip non-profile links
80
+ if (cleanUrl.includes('/status/') || cleanUrl.includes('/i/') || cleanUrl.includes('search')) {
81
+ continue;
82
+ }
83
+
84
+ if (!urls.has(cleanUrl)) {
85
+ const nameEl = cell.locator('[data-testid="User-Name"]');
86
+ let name = '';
87
+ if (await nameEl.count() > 0) {
88
+ const fullText = await nameEl.innerText();
89
+ name = fullText.split('\n')[0];
90
+ }
91
+
92
+ let avatar = '';
93
+ const imgEl = cell.locator('img[src*="profile_images"]').first();
94
+ if (await imgEl.count() > 0) {
95
+ avatar = await imgEl.getAttribute('src');
96
+ }
97
+
98
+ const verified = await cell.locator('[data-testid="icon-verified"]').count() > 0;
99
+
100
+ const profileData = { url: cleanUrl, name, avatar, verified };
101
+ urls.set(cleanUrl, profileData);
102
+ countNew++;
103
+
104
+ if (onNewUrl) onNewUrl(cleanUrl, name, avatar, verified);
105
+ }
106
+ } catch (err) {}
107
+ }
108
+ return countNew;
109
+ } catch (e) {
110
+ return 0;
111
+ }
112
+ };
113
+
114
+ // 2. Scroll loop
115
+ let lastHeight = await page.evaluate('document.body.scrollHeight');
116
+ let retries = 0;
117
+ const maxRetries = 5;
118
+
119
+ while (urls.size < 500) {
120
+ if (onProgress) onProgress(`Scanning X profiles... (Found ${urls.size})`);
121
+ await extractVisibleUrls();
122
+
123
+ if (urls.size >= 500) break;
124
+
125
+ await page.keyboard.press('End');
126
+ await page.waitForTimeout(2000);
127
+
128
+ const newHeight = await page.evaluate('document.body.scrollHeight');
129
+ if (newHeight === lastHeight) {
130
+ retries++;
131
+ if (retries >= maxRetries) break;
132
+ } else {
133
+ retries = 0;
134
+ }
135
+ lastHeight = newHeight;
136
+ }
137
+ } catch (err) {
138
+ if (onProgress) onProgress(`Error during X search: ${err.message}`);
139
+ throw err;
140
+ } finally {
141
+ await browserContext.close();
142
+ }
143
+
144
+ return Array.from(urls.values());
145
+ }
146
+
147
+ export { extractXUserUrls };